Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions apps/desktop/Sources/StimDesktop/TutorialModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ final class TutorialModel: ObservableObject {
private lazy var agentFollower = LogFollower { [weak self] in self?.receive($0) }
private static let seenKey = "tutorial.openedPaths"

enum RestartDialog: Equatable {
case confirm(base: String, worktrees: [String])
case blocked(String)
}
@Published var restartDialog: RestartDialog?
private var restarting = false

private let cloneBase: String

init(defaults: UserDefaults = .standard, cloneBase: String = NSHomeDirectory() + "/stim-tutorial") {
Expand Down Expand Up @@ -178,6 +185,37 @@ final class TutorialModel: ObservableObject {
checkCLI()
}

func restart() {
guard let cli else { return open(beginning: true) }
guard !restarting, restartDialog == nil else { return }
restarting = true
let base = records.record?.clonePath ?? cloneBase
Task {
defer { restarting = false }
let cleanup = TutorialCleanup(cli: await cli.value)
do {
guard let plan = try await cleanup.plan(base: base) else { return open(beginning: true) }
switch plan {
case .remove(let worktrees): restartDialog = .confirm(base: base, worktrees: worktrees)
case .refuse(let reason): restartDialog = .blocked(reason)
}
} catch { restartDialog = .blocked(error.localizedDescription) }
}
}

func confirmRestart(base: String, worktrees: [String]) {
guard let cli, !restarting else { return }
restartDialog = nil
restarting = true
Task {
defer { restarting = false }
do {
try await TutorialCleanup(cli: await cli.value).remove(base: base, worktrees: worktrees)
open(beginning: true)
} catch { restartDialog = .blocked(error.localizedDescription) }
}
}

func close() {
isOpen = false
openPending = false
Expand Down
13 changes: 2 additions & 11 deletions apps/desktop/Sources/StimDesktop/Views/RootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,20 +125,10 @@ struct RootView: View {
TutorialPanel(
snapshot: snapshot, message: tutorial.notice,
issues: tutorial.workspace?.issues ?? [], phoneState: tutorial.phoneState,
canRunIOS: tutorial.workspace.map { $0.build?.isRunning != true && actions.active(for: $0.path) == nil } ?? false,
agentDeviceMissing: tutorial.workspace?.agentDevice?.installed == false,
asks: tutorial.ask, commands: tutorial.commands,
copied: { tutorial.copiedPrompt() }, skip: tutorial.skip, markDone: tutorial.markDone,
restart: { tutorial.open(beginning: true) },
runIOS: {
if let workspace = tutorial.workspace {
actions.run(
"Run \(workspace.names.title) on iOS",
steps: [
StimCommand(["ios", "--remote", "local", "--remote-build", "local"], cwd: workspace.path)
], present: false)
}
},
restart: tutorial.restart,
close: tutorial.close,
openArchived: openTutorialArchive,
pairPhone: { openRequests.pairsPhone = true },
Expand Down Expand Up @@ -290,6 +280,7 @@ struct RootView: View {
NativeViewerPermissionsView(
permissions: nativePermissions, relaunch: onboarding.canRelaunch ? { onboarding.relaunch() } : nil)
}
.modifier(TutorialRestartDialogs(tutorial: tutorial))
.onAppear {
navigation.resolves = resolves
navigation.apply = show
Expand Down
17 changes: 1 addition & 16 deletions apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,13 @@ struct TutorialPanel: View {
var message: TutorialNotice? = nil
var issues: [StatusIssue] = []
var phoneState = TutorialPhoneState(pairedPhoneCount: nil)
var canRunIOS = false
var agentDeviceMissing = false
var asks: (TutorialStep) -> String? = { $0.ask }
var commands: (TutorialStep) -> String
var copied: () -> Void = {}
var skip: () -> Void = {}
var markDone: () -> Void = {}
var restart: () -> Void = {}
var runIOS: () -> Void = {}
var close: () -> Void = {}
var openArchived: () -> Void = {}
var pairPhone: () -> Void = {}
Expand Down Expand Up @@ -167,19 +165,6 @@ struct TutorialPanel: View {
Text("\(issue.code): \(issue.message) \(issue.remedy)").foregroundStyle(Palette.warning)
.textSelection(.enabled)
}
if step.id == "build" {
Button {
runIOS()
} label: {
Label("Run iOS", systemImage: "play.fill")
}
.buttonStyle(.stim(.primary)).disabled(!canRunIOS)
.help(
"stim ios --remote local --remote-build local: builds here if needed, installs and launches in this "
+ "workspace"
)
.accessibilityLabel("Run the tutorial app on iOS")
}
if step.id == "phone", phoneState != .paired {
Button(phoneState.buttonTitle, action: pairPhone).buttonStyle(.stim(.primary))
}
Expand Down Expand Up @@ -291,7 +276,7 @@ struct TutorialPanel: View {
"Watch two agents make two changes at once, each in its own worktree with its own simulator and dev server, checking its own work on the device. First, clone the test app."
case "build":
return
"Ask your agent for a visual change in your own words, for example: \"Make the title purple and check it on the simulator.\" It works in its own worktree with its own simulator and Metro, and checks the result on the device. Stim waited until the app said it was ready, not just launched, so the agent knows the app works before it checks the change: look for the readiness phase in the build details. On a fresh Mac this build is usually a cache miss and takes a few minutes. Watch it in Desktop."
"Ask your agent for a visual change. It builds in its own worktree and simulator, and checks the result on the device. The first build can take a few minutes."
case "parallel":
return
"While that runs, ask for another change, for example: \"Try a dark background and check it on the simulator.\" Two worktrees run side by side with no port or simulator clash, and the second build is a cache hit, so isolation is cheap and it finishes much faster. Look at the cache badge and both simulators."
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import SwiftUI

struct TutorialRestartDialogs: ViewModifier {
@ObservedObject var tutorial: TutorialModel

private var confirming: Binding<Bool> {
Binding(
get: { if case .confirm = tutorial.restartDialog { return true } else { return false } },
set: { if !$0, case .confirm = tutorial.restartDialog { tutorial.restartDialog = nil } })
}

private var blocked: Binding<Bool> {
Binding(
get: { if case .blocked = tutorial.restartDialog { return true } else { return false } },
set: { if !$0 { tutorial.restartDialog = nil } })
}

func body(content: Content) -> some View {
content
.confirmationDialog(
"Restart the Tutorial?", isPresented: confirming, titleVisibility: .visible, presenting: tutorial.restartDialog
) { dialog in
if case .confirm(let base, let worktrees) = dialog {
Button("Delete & Restart", role: .destructive) { tutorial.confirmRestart(base: base, worktrees: worktrees) }
}
Button("Cancel", role: .cancel) {}
} message: { dialog in
if case .confirm(let base, let worktrees) = dialog {
let names = worktrees.map { ($0 as NSString).abbreviatingWithTildeInPath }
Text(
"Restart deletes \((base as NSString).abbreviatingWithTildeInPath)"
+ (names.isEmpty ? "" : " and its worktrees \(names.joined(separator: ", "))")
+ ". The folder moves to the Trash.")
}
}
.alert("Tutorial Not Restarted", isPresented: blocked) {
Button("OK", role: .cancel) {}
} message: {
if case .blocked(let reason) = tutorial.restartDialog { Text(reason) }
}
}
}
67 changes: 67 additions & 0 deletions apps/desktop/Sources/StimKit/TutorialCleanup.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import Foundation

/// What Restart Tutorial deletes: the tutorial worktrees, then the clone.
public enum TutorialCleanupPlan: Equatable, Sendable {
case remove(worktrees: [String])
case refuse(String)
}

/// Removes only a folder that carries the tutorial marker.
public func tutorialCleanupPlan(base: String, hasMarker: Bool, linkedWorktrees: [String]) -> TutorialCleanupPlan {
hasMarker
? .remove(worktrees: linkedWorktrees)
: .refuse("\(base) is not the tutorial clone (no tutorial marker in app.json), so Restart leaves it alone.")
}

public struct TutorialCleanup: Sendable {
public struct Failure: LocalizedError {
public var message: String
public var errorDescription: String? { message }
}

let cli: StimCLI

public init(cli: StimCLI) { self.cli = cli }

/// The plan for `base`, or nil when there is no folder there.
public func plan(base: String) async throws -> TutorialCleanupPlan? {
guard FileManager.default.fileExists(atPath: base) else { return nil }
let marker = Self.hasMarker(at: base)
guard marker else { return tutorialCleanupPlan(base: base, hasMarker: false, linkedWorktrees: []) }
let list = try await ProcessRequest("/usr/bin/git", ["worktree", "list", "--porcelain"], cwd: base, timeout: 30).run()
guard list.succeeded else { throw Failure(message: "git worktree list failed in \(base).") }
let paths = Self.worktreePaths(list.stdoutText)
guard let first = paths.first,
URL(fileURLWithPath: first).resolvingSymlinksInPath() == URL(fileURLWithPath: base).resolvingSymlinksInPath()
else { return .refuse("\(base) is not the root of its own git repository, so Restart leaves it alone.") }
return tutorialCleanupPlan(base: base, hasMarker: true, linkedWorktrees: Array(paths.dropFirst()))
}

public func remove(base: String, worktrees: [String]) async throws {
for path in worktrees where FileManager.default.fileExists(atPath: path) {
_ = try await cli.run(["stop"], cwd: path)
_ = try await cli.run(["worktree", "remove", path], cwd: base)
}
_ = try await cli.run(["stop"], cwd: base)
_ = try await cli.run(["worktree", "remove", base], cwd: base)
try Self.moveToTrash(base)
}

static func worktreePaths(_ porcelain: String) -> [String] {
porcelain.split(separator: "\n").compactMap { line in
line.hasPrefix("worktree ") ? String(line.dropFirst("worktree ".count)) : nil
}
}

static func moveToTrash(_ path: String) throws {
try FileManager.default.trashItem(at: URL(fileURLWithPath: path), resultingItemURL: nil)
}

static func hasMarker(at base: String) -> Bool {
guard let data = FileManager.default.contents(atPath: base + "/app.json"),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let extra = (json["expo"] as? [String: Any])?["extra"] as? [String: Any]
else { return false }
return (extra["stimTutorial"] as? Int).map(TutorialSteps.supportedVersions.contains) ?? false
}
}
2 changes: 1 addition & 1 deletion apps/desktop/Sources/StimKit/TutorialSteps.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public enum TutorialSteps {
]),
TutorialStep(
id: "build", title: "Make a Change", who: "you", optional: false,
ask: nil, section: nil,
ask: "Make the title purple in the Stim tutorial app and check it on the simulator.", section: nil,
commands: [

]),
Expand Down
42 changes: 42 additions & 0 deletions apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import XCTest

@testable import StimKit

final class TutorialCleanupTests: XCTestCase {
func testMarkedFolderIsRemovedWithItsWorktrees() {
XCTAssertEqual(
tutorialCleanupPlan(base: "/b", hasMarker: true, linkedWorktrees: ["/t", "/s"]), .remove(worktrees: ["/t", "/s"]))
}

func testFolderWithoutMarkerIsRefused() {
guard case .refuse(let reason) = tutorialCleanupPlan(base: "/b", hasMarker: false, linkedWorktrees: ["/t"]) else {
return XCTFail("removed")
}
XCTAssertTrue(reason.contains("/b"))
}

func testMarkerComesFromAppJSON() throws {
let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: dir) }
XCTAssertFalse(TutorialCleanup.hasMarker(at: dir.path))
try Data(#"{"expo":{"extra":{"stimTutorial":2}}}"#.utf8).write(to: dir.appendingPathComponent("app.json"))
XCTAssertTrue(TutorialCleanup.hasMarker(at: dir.path))
}

func testWorktreePathsKeepsTheCloneFirstAndTheLinkedOnesAfter() {
let porcelain = "worktree /a/base\nHEAD 1\nbranch refs/heads/main\n\nworktree /a/tour\nHEAD 1\n\nworktree /a/second\nHEAD 1\n"
XCTAssertEqual(TutorialCleanup.worktreePaths(porcelain), ["/a/base", "/a/tour", "/a/second"])
}

func testFolderMovesToTheTrashAndStaysRecoverable() throws {
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("stim-tutorial-trash-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try Data("x".utf8).write(to: dir.appendingPathComponent("file"))
try TutorialCleanup.moveToTrash(dir.path)
let inTrash = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".Trash/" + dir.lastPathComponent)
defer { try? FileManager.default.removeItem(at: inTrash) }
XCTAssertFalse(FileManager.default.fileExists(atPath: dir.path))
XCTAssertTrue(FileManager.default.fileExists(atPath: inTrash.appendingPathComponent("file").path))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@
model.update(workspaces: [old], archived: [], sheetOpen: false, now: start)
XCTAssertEqual(model.notice?.action, .restart)
XCTAssertEqual(model.snapshot?.steps.first { $0.id == "build" }?.action, .restart)
XCTAssertNil(model.ask(for: try XCTUnwrap(TutorialSteps.all.first { $0.id == "build" })))
model.open(beginning: true, now: start.addingTimeInterval(30))
XCTAssertNil(model.snapshot?.record.tourPath)
XCTAssertEqual(model.snapshot?.currentStep, "begin")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
TutorialPanel(
snapshot: snapshot, fixtureRendering: true,
phoneState: TutorialPhoneState(pairedPhoneCount: phoneCount),
canRunIOS: true, agentDeviceMissing: name == "build-no-agent-device",
agentDeviceMissing: name == "build-no-agent-device",
asks: { step in
step.ask.map {
tutorialAsk(
Expand Down
2 changes: 1 addition & 1 deletion packages/stim-cli/src/__tests__/guide.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ test('the run section names the marker version the status payload reports and on

test('tutorial setup protects existing folders and the user repository', () => {
const run = flat('run');
expect(run).toMatch(/If \{base\} exists, stop and ask the user for another folder; never overwrite or delete it/i);
expect(run).toMatch(/stop and ask the user for another folder; never overwrite or delete it/i);
expect(run).toMatch(/inside another repository: stop and ask the user for another folder/i);
expect(run).toMatch(/Never git add in the user's repo/i);
});
Expand Down
3 changes: 2 additions & 1 deletion packages/stim-cli/src/guide/tutorial-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const TUTORIAL_RESTART_PROMPT = 'Restart the Stim tutorial.';
*/
export const TUTORIAL_ASKS = {
begin: `Clone ${TUTORIAL_REPO} into {base} and follow stim guide tutorial run.`,
build: 'Make the title purple in the Stim tutorial app and check it on the simulator.',
agent: 'Open the app on the iOS simulator, take a screenshot and confirm the title color.',
finish:
"I'm done with these experiments in {base} and don't need the changes. Stop the apps and remove the worktrees {worktrees}, and keep the clone. Follow stim guide tutorial finish.",
Expand Down Expand Up @@ -42,7 +43,7 @@ export const TUTORIAL_STEPS: {
title: 'Make a Change',
who: 'you',
optional: false,
ask: null,
ask: TUTORIAL_ASKS.build,
section: null,
commands: [],
},
Expand Down
10 changes: 8 additions & 2 deletions packages/stim-cli/src/guide/tutorial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,14 @@ For commands to type yourself, read stim guide tutorial manual.`,

${paths}

Folder safety: use a fresh folder. If {base} exists, stop and ask the user for
another folder; never overwrite or delete it. First check the parent folder:
Folder safety: if {base} does not exist, clone into it. If it exists, reuse it
only when all of these hold: app.json has expo.extra.stimTutorial equal to
${TUTORIAL_VERSION}, git remote get-url origin names ${TUTORIAL_REPO}, git
rev-parse --show-toplevel equals {base}, and git status --porcelain prints
nothing. Then skip the clone, install its dependencies (npm ci), run stim doctor
--platform ios there, and continue at PAUSE. For any other existing folder (another
repository, local changes, no tutorial marker), stop and ask the user for
another folder; never overwrite or delete it. Before cloning, check the parent folder:
create it if absent, then run git -C <parent> rev-parse --is-inside-work-tree.
If that succeeds, the folder is inside another repository: stop and ask the
user for another folder. Never git add in the user's repo.
Expand Down
Loading
Loading