From 6f365b85f71cac175a19259549296167121d1f2b Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 10 Oct 2026 12:54:29 -0400 Subject: [PATCH 1/3] feat(desktop): Restart Tutorial deletes the previous clone and reuses a clean one in the guide --- .../Sources/StimDesktop/TutorialModel.swift | 32 +++++++++++ .../Sources/StimDesktop/Views/RootView.swift | 3 +- .../Views/TutorialRestartDialogs.swift | 40 +++++++++++++ .../Sources/StimKit/TutorialCleanup.swift | 57 +++++++++++++++++++ .../StimKitTests/TutorialCleanupTests.swift | 26 +++++++++ packages/stim-cli/src/__tests__/guide.test.ts | 4 +- packages/stim-cli/src/guide/tutorial.ts | 10 +++- website/docs/desktop.md | 2 +- 8 files changed, 169 insertions(+), 5 deletions(-) create mode 100644 apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift create mode 100644 apps/desktop/Sources/StimKit/TutorialCleanup.swift create mode 100644 apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift diff --git a/apps/desktop/Sources/StimDesktop/TutorialModel.swift b/apps/desktop/Sources/StimDesktop/TutorialModel.swift index 0d94014611..70d9c274dc 100644 --- a/apps/desktop/Sources/StimDesktop/TutorialModel.swift +++ b/apps/desktop/Sources/StimDesktop/TutorialModel.swift @@ -32,6 +32,12 @@ 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 let cloneBase: String init(defaults: UserDefaults = .standard, cloneBase: String = NSHomeDirectory() + "/stim-tutorial") { @@ -178,6 +184,32 @@ final class TutorialModel: ObservableObject { checkCLI() } + func restart() { + guard let cli else { return open(beginning: true) } + let base = records.record?.clonePath ?? cloneBase + Task { + 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 else { return } + restartDialog = nil + Task { + 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 diff --git a/apps/desktop/Sources/StimDesktop/Views/RootView.swift b/apps/desktop/Sources/StimDesktop/Views/RootView.swift index 38c853189b..856f6fa8cd 100644 --- a/apps/desktop/Sources/StimDesktop/Views/RootView.swift +++ b/apps/desktop/Sources/StimDesktop/Views/RootView.swift @@ -129,7 +129,7 @@ struct RootView: View { 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) }, + restart: tutorial.restart, runIOS: { if let workspace = tutorial.workspace { actions.run( @@ -290,6 +290,7 @@ struct RootView: View { NativeViewerPermissionsView( permissions: nativePermissions, relaunch: onboarding.canRelaunch ? { onboarding.relaunch() } : nil) } + .modifier(TutorialRestartDialogs(tutorial: tutorial)) .onAppear { navigation.resolves = resolves navigation.apply = show diff --git a/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift b/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift new file mode 100644 index 0000000000..c97be48fc2 --- /dev/null +++ b/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift @@ -0,0 +1,40 @@ +import SwiftUI + +struct TutorialRestartDialogs: ViewModifier { + @ObservedObject var tutorial: TutorialModel + + private var confirming: Binding { + 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 { + 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, _) = dialog { + Text( + "Restart deletes \((base as NSString).abbreviatingWithTildeInPath) and its tutorial worktrees. " + + "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) } + } + } +} diff --git a/apps/desktop/Sources/StimKit/TutorialCleanup.swift b/apps/desktop/Sources/StimKit/TutorialCleanup.swift new file mode 100644 index 0000000000..b5242ece33 --- /dev/null +++ b/apps/desktop/Sources/StimKit/TutorialCleanup.swift @@ -0,0 +1,57 @@ +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 = list.stdoutText.split(separator: "\n").compactMap { line -> String? in + line.hasPrefix("worktree ") ? String(line.dropFirst("worktree ".count)) : nil + } + return tutorialCleanupPlan(base: base, hasMarker: true, linkedWorktrees: Array(paths.dropFirst())) + } + + /// The tutorial worktrees, then the clone, through `stim worktree remove` without `--force`; then the folder to the Trash. + public func remove(base: String, worktrees: [String]) async throws { + for path in worktrees { + if 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 FileManager.default.trashItem(at: URL(fileURLWithPath: base), 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"] != nil + } +} diff --git a/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift b/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift new file mode 100644 index 0000000000..03b4095a1a --- /dev/null +++ b/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift @@ -0,0 +1,26 @@ +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":1}}}"#.utf8).write(to: dir.appendingPathComponent("app.json")) + XCTAssertTrue(TutorialCleanup.hasMarker(at: dir.path)) + } +} diff --git a/packages/stim-cli/src/__tests__/guide.test.ts b/packages/stim-cli/src/__tests__/guide.test.ts index 0c99e5f6d3..de3168c4e2 100644 --- a/packages/stim-cli/src/__tests__/guide.test.ts +++ b/packages/stim-cli/src/__tests__/guide.test.ts @@ -579,7 +579,9 @@ 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(/reuse it only when all of these hold/i); + expect(run).toMatch(/git status --porcelain prints nothing/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); }); diff --git a/packages/stim-cli/src/guide/tutorial.ts b/packages/stim-cli/src/guide/tutorial.ts index d8261f3f9c..d3ecd3a7f0 100644 --- a/packages/stim-cli/src/guide/tutorial.ts +++ b/packages/stim-cli/src/guide/tutorial.ts @@ -48,8 +48,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 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. diff --git a/website/docs/desktop.md b/website/docs/desktop.md index a2d1d24302..9bfc10bf38 100644 --- a/website/docs/desktop.md +++ b/website/docs/desktop.md @@ -93,7 +93,7 @@ clone with its own simulator and dev server, and each checks its own work on the device. The panel clones [appandflow/stim-tutorial](https://github.com/appandflow/stim-tutorial), a tiny Expo app, and shows: -- **Get the Test App:** the prompt above. It clones, installs and runs `stim doctor` so Stim registers the clone, and builds nothing; the clone is the base for your changes and is never run; only the optional last step removes it. While your agent works, the step ticks **Test app cloned**, **Dependencies installed** and **Registered with Stim**. The first two read `~/stim-tutorial` itself, so a clone in another folder ticks only the last. +- **Get the Test App:** the prompt above. It clones, installs and runs `stim doctor` so Stim registers the clone, and builds nothing; the clone is the base for your changes and is never run; only the optional last step removes it. An existing `~/stim-tutorial` that is a clean clone of the tutorial repository is reused; any other existing folder makes your agent ask for another one. **Restart Tutorial** asks before it deletes the folder and its tutorial worktrees through `stim worktree remove`, then moves the folder to the Trash; a folder without the tutorial marker is left alone. While your agent works, the step ticks **Test app cloned**, **Dependencies installed** and **Registered with Stim**. The first two read `~/stim-tutorial` itself, so a clone in another folder ticks only the last. - **Make a Change:** ask your agent for a visual change in your own words, for example "Make the title purple and check it on the simulator." Your agent works in the first linked worktree of the clone. Watch its first build, usually a cache miss on a fresh Mac, including the readiness phase, which proves the app came up before the agent checks the change. The first build takes a few minutes. - **Change It Again in Parallel:** while that runs, ask for another change, for example "Try a dark background and check it on the simulator." The next linked worktree of the clone, made after the first change step began, has its own simulator and Metro port, and its first iOS build is a cache hit. - **Live View and Control, Agent Actions and Replay, App Logs (optional):** open the live view, watch what your agent did on the device and replay it, and read the logs. From 38ff02a84ab100e0630af7c4eb1c48ad248f193c Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 10 Oct 2026 12:55:50 -0400 Subject: [PATCH 2/3] polish(desktop): shorter Make a Change step with a copyable prompt, no Run iOS button --- .../Sources/StimDesktop/Views/RootView.swift | 10 ---------- .../StimDesktop/Views/TutorialPanel.swift | 17 +---------------- .../desktop/Sources/StimKit/TutorialSteps.swift | 2 +- .../VisualFixtureTests/TutorialModelTests.swift | 1 - .../TutorialScreenshotTests.swift | 2 +- packages/stim-cli/src/guide/tutorial-data.ts | 3 ++- website/docs/desktop.md | 7 +++---- 7 files changed, 8 insertions(+), 34 deletions(-) diff --git a/apps/desktop/Sources/StimDesktop/Views/RootView.swift b/apps/desktop/Sources/StimDesktop/Views/RootView.swift index 856f6fa8cd..42a37942e7 100644 --- a/apps/desktop/Sources/StimDesktop/Views/RootView.swift +++ b/apps/desktop/Sources/StimDesktop/Views/RootView.swift @@ -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.restart, - 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) - } - }, close: tutorial.close, openArchived: openTutorialArchive, pairPhone: { openRequests.pairsPhone = true }, diff --git a/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift b/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift index 53e9026938..fd78c647bb 100644 --- a/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift +++ b/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift @@ -10,7 +10,6 @@ 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 @@ -18,7 +17,6 @@ struct TutorialPanel: View { var skip: () -> Void = {} var markDone: () -> Void = {} var restart: () -> Void = {} - var runIOS: () -> Void = {} var close: () -> Void = {} var openArchived: () -> Void = {} var pairPhone: () -> Void = {} @@ -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)) } @@ -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." diff --git a/apps/desktop/Sources/StimKit/TutorialSteps.swift b/apps/desktop/Sources/StimKit/TutorialSteps.swift index 9888abdc84..104ef89051 100644 --- a/apps/desktop/Sources/StimKit/TutorialSteps.swift +++ b/apps/desktop/Sources/StimKit/TutorialSteps.swift @@ -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: [ ]), diff --git a/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift b/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift index 55cc1ab20d..90dcc61517 100644 --- a/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift +++ b/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift @@ -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") diff --git a/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift b/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift index 9fb44b7398..7640f9c00d 100644 --- a/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift +++ b/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift @@ -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( diff --git a/packages/stim-cli/src/guide/tutorial-data.ts b/packages/stim-cli/src/guide/tutorial-data.ts index f30e4b99c6..457207c873 100644 --- a/packages/stim-cli/src/guide/tutorial-data.ts +++ b/packages/stim-cli/src/guide/tutorial-data.ts @@ -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.", @@ -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: [], }, diff --git a/website/docs/desktop.md b/website/docs/desktop.md index 9bfc10bf38..8da85ebef0 100644 --- a/website/docs/desktop.md +++ b/website/docs/desktop.md @@ -94,7 +94,7 @@ device. The panel clones [appandflow/stim-tutorial](https://github.com/appandflo a tiny Expo app, and shows: - **Get the Test App:** the prompt above. It clones, installs and runs `stim doctor` so Stim registers the clone, and builds nothing; the clone is the base for your changes and is never run; only the optional last step removes it. An existing `~/stim-tutorial` that is a clean clone of the tutorial repository is reused; any other existing folder makes your agent ask for another one. **Restart Tutorial** asks before it deletes the folder and its tutorial worktrees through `stim worktree remove`, then moves the folder to the Trash; a folder without the tutorial marker is left alone. While your agent works, the step ticks **Test app cloned**, **Dependencies installed** and **Registered with Stim**. The first two read `~/stim-tutorial` itself, so a clone in another folder ticks only the last. -- **Make a Change:** ask your agent for a visual change in your own words, for example "Make the title purple and check it on the simulator." Your agent works in the first linked worktree of the clone. Watch its first build, usually a cache miss on a fresh Mac, including the readiness phase, which proves the app came up before the agent checks the change. The first build takes a few minutes. +- **Make a Change:** ask your agent for a visual change, for example "Make the title purple in the Stim tutorial app and check it on the simulator." (the step has a prompt to copy). It builds in the first linked worktree of the clone with its own simulator, and checks the result on the device. The first build, usually a cache miss on a fresh Mac, takes a few minutes. - **Change It Again in Parallel:** while that runs, ask for another change, for example "Try a dark background and check it on the simulator." The next linked worktree of the clone, made after the first change step began, has its own simulator and Metro port, and its first iOS build is a cache hit. - **Live View and Control, Agent Actions and Replay, App Logs (optional):** open the live view, watch what your agent did on the device and replay it, and read the logs. - **Watch on Your Phone (optional):** **Pair a Phone** opens the Pair a Phone wizard, which turns on serving itself. An existing pairing shows **Done Already**, then "Open Stim on your phone: the tutorial workspaces are there". **Skip** stays available. @@ -130,9 +130,8 @@ yourself, with the agent-device state directory and simulator filled in when known. Create the Tutorial has only the prompt. Desktop remembers whether the section is open. Copying a command does not start the three-minute workspace warning. The default base is `~/stim-tutorial`. -**Run iOS** on Make a Change runs `stim ios --remote local --remote-build local` -for the tour workspace, so it builds and runs on this Mac whatever `ios.remote` or -`remote.build` say. The agent keeps the tutorial's own runs local the same way. To +The agent keeps the tutorial's own runs local, whatever `ios.remote` or +`remote.build` say. To read the complete manual: From 0f0e0bfcde80001780e6a11735ac66fb0023ef42 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 10 Oct 2026 13:10:44 -0400 Subject: [PATCH 3/3] fix(desktop): Restart checks the clone is its own repository root, names its worktrees and guards re-entry --- .../Sources/StimDesktop/TutorialModel.swift | 8 +++++- .../Views/TutorialRestartDialogs.swift | 8 +++--- .../Sources/StimKit/TutorialCleanup.swift | 26 +++++++++++++------ .../StimKitTests/TutorialCleanupTests.swift | 18 ++++++++++++- packages/stim-cli/src/__tests__/guide.test.ts | 2 -- website/docs/desktop.md | 2 +- 6 files changed, 48 insertions(+), 16 deletions(-) diff --git a/apps/desktop/Sources/StimDesktop/TutorialModel.swift b/apps/desktop/Sources/StimDesktop/TutorialModel.swift index 70d9c274dc..970af50de2 100644 --- a/apps/desktop/Sources/StimDesktop/TutorialModel.swift +++ b/apps/desktop/Sources/StimDesktop/TutorialModel.swift @@ -37,6 +37,7 @@ final class TutorialModel: ObservableObject { case blocked(String) } @Published var restartDialog: RestartDialog? + private var restarting = false private let cloneBase: String @@ -186,8 +187,11 @@ final class TutorialModel: ObservableObject { 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) } @@ -200,9 +204,11 @@ final class TutorialModel: ObservableObject { } func confirmRestart(base: String, worktrees: [String]) { - guard let cli else { return } + 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) diff --git a/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift b/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift index c97be48fc2..69477a44db 100644 --- a/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift +++ b/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift @@ -25,10 +25,12 @@ struct TutorialRestartDialogs: ViewModifier { } Button("Cancel", role: .cancel) {} } message: { dialog in - if case .confirm(let base, _) = dialog { + if case .confirm(let base, let worktrees) = dialog { + let names = worktrees.map { ($0 as NSString).abbreviatingWithTildeInPath } Text( - "Restart deletes \((base as NSString).abbreviatingWithTildeInPath) and its tutorial worktrees. " - + "The folder moves to the Trash.") + "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) { diff --git a/apps/desktop/Sources/StimKit/TutorialCleanup.swift b/apps/desktop/Sources/StimKit/TutorialCleanup.swift index b5242ece33..6d341bb2ea 100644 --- a/apps/desktop/Sources/StimKit/TutorialCleanup.swift +++ b/apps/desktop/Sources/StimKit/TutorialCleanup.swift @@ -30,21 +30,31 @@ public struct TutorialCleanup: Sendable { 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 = list.stdoutText.split(separator: "\n").compactMap { line -> String? in - line.hasPrefix("worktree ") ? String(line.dropFirst("worktree ".count)) : nil - } + 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())) } - /// The tutorial worktrees, then the clone, through `stim worktree remove` without `--force`; then the folder to the Trash. public func remove(base: String, worktrees: [String]) async throws { - for path in worktrees { - if FileManager.default.fileExists(atPath: path) { _ = try await cli.run(["stop"], cwd: path) } + 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 FileManager.default.trashItem(at: URL(fileURLWithPath: base), resultingItemURL: nil) + 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 { @@ -52,6 +62,6 @@ public struct TutorialCleanup: Sendable { 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"] != nil + return (extra["stimTutorial"] as? Int).map(TutorialSteps.supportedVersions.contains) ?? false } } diff --git a/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift b/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift index 03b4095a1a..769c98238e 100644 --- a/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift +++ b/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift @@ -20,7 +20,23 @@ final class TutorialCleanupTests: XCTestCase { 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":1}}}"#.utf8).write(to: dir.appendingPathComponent("app.json")) + 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)) + } } diff --git a/packages/stim-cli/src/__tests__/guide.test.ts b/packages/stim-cli/src/__tests__/guide.test.ts index de3168c4e2..7fae082802 100644 --- a/packages/stim-cli/src/__tests__/guide.test.ts +++ b/packages/stim-cli/src/__tests__/guide.test.ts @@ -579,8 +579,6 @@ 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(/reuse it only when all of these hold/i); - expect(run).toMatch(/git status --porcelain prints nothing/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); diff --git a/website/docs/desktop.md b/website/docs/desktop.md index 8da85ebef0..ee625082de 100644 --- a/website/docs/desktop.md +++ b/website/docs/desktop.md @@ -93,7 +93,7 @@ clone with its own simulator and dev server, and each checks its own work on the device. The panel clones [appandflow/stim-tutorial](https://github.com/appandflow/stim-tutorial), a tiny Expo app, and shows: -- **Get the Test App:** the prompt above. It clones, installs and runs `stim doctor` so Stim registers the clone, and builds nothing; the clone is the base for your changes and is never run; only the optional last step removes it. An existing `~/stim-tutorial` that is a clean clone of the tutorial repository is reused; any other existing folder makes your agent ask for another one. **Restart Tutorial** asks before it deletes the folder and its tutorial worktrees through `stim worktree remove`, then moves the folder to the Trash; a folder without the tutorial marker is left alone. While your agent works, the step ticks **Test app cloned**, **Dependencies installed** and **Registered with Stim**. The first two read `~/stim-tutorial` itself, so a clone in another folder ticks only the last. +- **Get the Test App:** the prompt above. It clones, installs and runs `stim doctor` so Stim registers the clone, and builds nothing; the clone is the base for your changes and is never run; only the optional last step and **Restart Tutorial** remove it. An existing `~/stim-tutorial` that is a clean clone of the tutorial repository is reused; any other existing folder makes your agent ask for another one. **Restart Tutorial** asks before it deletes the folder and its tutorial worktrees through `stim worktree remove`, then moves the folder to the Trash; a folder without the tutorial marker is left alone. While your agent works, the step ticks **Test app cloned**, **Dependencies installed** and **Registered with Stim**. The first two read `~/stim-tutorial` itself, so a clone in another folder ticks only the last. - **Make a Change:** ask your agent for a visual change, for example "Make the title purple in the Stim tutorial app and check it on the simulator." (the step has a prompt to copy). It builds in the first linked worktree of the clone with its own simulator, and checks the result on the device. The first build, usually a cache miss on a fresh Mac, takes a few minutes. - **Change It Again in Parallel:** while that runs, ask for another change, for example "Try a dark background and check it on the simulator." The next linked worktree of the clone, made after the first change step began, has its own simulator and Metro port, and its first iOS build is a cache hit. - **Live View and Control, Agent Actions and Replay, App Logs (optional):** open the live view, watch what your agent did on the device and replay it, and read the logs.