diff --git a/apps/desktop/Sources/StimDesktop/TutorialModel.swift b/apps/desktop/Sources/StimDesktop/TutorialModel.swift index 0d94014611..970af50de2 100644 --- a/apps/desktop/Sources/StimDesktop/TutorialModel.swift +++ b/apps/desktop/Sources/StimDesktop/TutorialModel.swift @@ -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") { @@ -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 diff --git a/apps/desktop/Sources/StimDesktop/Views/RootView.swift b/apps/desktop/Sources/StimDesktop/Views/RootView.swift index 38c853189b..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.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 }, @@ -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 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/StimDesktop/Views/TutorialRestartDialogs.swift b/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift new file mode 100644 index 0000000000..69477a44db --- /dev/null +++ b/apps/desktop/Sources/StimDesktop/Views/TutorialRestartDialogs.swift @@ -0,0 +1,42 @@ +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, 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) } + } + } +} diff --git a/apps/desktop/Sources/StimKit/TutorialCleanup.swift b/apps/desktop/Sources/StimKit/TutorialCleanup.swift new file mode 100644 index 0000000000..6d341bb2ea --- /dev/null +++ b/apps/desktop/Sources/StimKit/TutorialCleanup.swift @@ -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 + } +} diff --git a/apps/desktop/Sources/StimKit/TutorialSteps.swift b/apps/desktop/Sources/StimKit/TutorialSteps.swift index 904f79be34..e74d2b1a3f 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/StimKitTests/TutorialCleanupTests.swift b/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift new file mode 100644 index 0000000000..769c98238e --- /dev/null +++ b/apps/desktop/Tests/StimKitTests/TutorialCleanupTests.swift @@ -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)) + } +} 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/__tests__/guide.test.ts b/packages/stim-cli/src/__tests__/guide.test.ts index 29363b4405..ec9fd73393 100644 --- a/packages/stim-cli/src/__tests__/guide.test.ts +++ b/packages/stim-cli/src/__tests__/guide.test.ts @@ -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); }); diff --git a/packages/stim-cli/src/guide/tutorial-data.ts b/packages/stim-cli/src/guide/tutorial-data.ts index 6cbdbac64d..ef9665f994 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/packages/stim-cli/src/guide/tutorial.ts b/packages/stim-cli/src/guide/tutorial.ts index 78d4ce61fa..f01888675a 100644 --- a/packages/stim-cli/src/guide/tutorial.ts +++ b/packages/stim-cli/src/guide/tutorial.ts @@ -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 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 d2a07c5b36..c2366defed 100644 --- a/website/docs/desktop.md +++ b/website/docs/desktop.md @@ -93,8 +93,8 @@ 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. -- **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. +- **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. - **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: