diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 6da1e24039..abf35e3910 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -1834,12 +1834,12 @@ To check a bundle, point the DSN at a local listener, such as `http://@127. **Help > Stim Tutorial…** and the setup guide's **Take the Tutorial** button open an inspector-width trailing column. It replaces the inspector until closed; Cmd-Opt-I returns to the inspector. A new tutorial path opens it once, after open -sheets close. UserDefaults stores progress, skipped steps and whether the Commands section is open. +sheets close. UserDefaults stores progress and skipped steps. Unfinished tours resume at launch when status lists the tracked path; archived ones show Done. Closing preserves progress. Restart shows the agent prompt and resets progress at once; see below for which worktrees count afterwards. The three-minute workspace warning starts at the first Copy of the run prompt -and survives relaunch. Copying commands does not start it. Only archives +and survives relaunch. Only archives removed after this run started can complete the tutorial. The panel clones appandflow/stim-tutorial and follows: a tutorial workspace @@ -1854,28 +1854,24 @@ tutorial version is 2, from the repository's `expo.extra.stimTutorial`. A stored version 1 record is dropped and starts over on a version 2 workspace. Restart and "take the tutorial" start a fresh record at the current time that forgets the old tour paths even while the old worktrees are still registered; only linked worktrees whose creation time is after -that start count, and the oldest one becomes the tour. Both optional steps -keep Skip available. +that start count, and the oldest one becomes the tour. Every step has one Next +button: it records the step as done when its non-optional ticks are all done or +its checkpoint completed, and as skipped otherwise. Detected steps advance on +their own. Pair a Phone opens the Pair a Phone wizard, which turns on serving itself when the server is off. A pairing that exists when the step starts shows Done Already, followed by "Open Stim on your phone: the tutorial workspaces are there". Add Remote Machine opens the existing wizard using the tour workspace as its -checkout. With no machine configured, Skip is the primary action. Once a machine +checkout. Once a machine is approved, the step shows a prompt that names the approved machine, or asks you to -name it when none is recorded. The commands include that name. Approval completes the step and preserves its handoff across status polls; +name it when none is recorded. Approval completes the step and preserves its handoff across status polls; an iOS build offloaded after the step started ticks the optional "Build ran on another Mac" check. Completed optional steps stay expanded so their handoff remains -visible. The tutorial never starts the server or pairs or grants access. Mark done -appears after two minutes. - -Each step with a prompt shows it first, then a collapsed "Commands your agent will run" -section; whether it is open is a per-user `tutorial.commandsExpanded` preference. The prompts and the -short command lists come from `TUTORIAL_ASKS` and each step's `commands` in -`tutorial-data.ts`, with the tracked paths, the agent-device state directory and the -simulator UDID substituted; the guide's own `manual` lists are unchanged. Create the -Tutorial has no commands. Desktop never runs the commands. Make a Change has a Run iOS button that calls the same `ActionCenter.runApp` as the -Build section's Run, and is disabled while a build or action runs in the workspace. +visible. The tutorial never starts the server or pairs or grants access. + +A step with a prompt shows it with a Copy button. The prompts come from `TUTORIAL_ASKS` in +`tutorial-data.ts`, with the tracked paths substituted. The panel cannot see a removal refusal from an agent-run command: the finish step keeps showing the finish prompt. Check the agent's output and revert the tutorial edit before retrying. diff --git a/apps/desktop/Sources/StimDesktop/Design/TutorialAnchors.swift b/apps/desktop/Sources/StimDesktop/Design/TutorialAnchors.swift index e339096894..c75cad600f 100644 --- a/apps/desktop/Sources/StimDesktop/Design/TutorialAnchors.swift +++ b/apps/desktop/Sources/StimDesktop/Design/TutorialAnchors.swift @@ -2,7 +2,7 @@ import StimKit import SwiftUI enum TutorialAnchorID: Hashable { - case sidebarRow, buildSection, cacheBadge, deviceTile, viewerControl, logsTab, agentActions, replay, archivedFilter + case launchNoticeShow, deviceControl, viewerScreen, logsTab, agentActions, replay, archivedFilter } struct TutorialAnchorKey: Hashable { @@ -18,36 +18,39 @@ struct TutorialAnchorPreference: PreferenceKey { } struct TutorialHint { + static let glowSeconds = 4.0 + var step: String? + /// The first change's worktree. var path: String? + var secondPath: String? var selectedPath: String? + var ticks: [TutorialTick] = [] var showMe: () -> Void - var anchor: TutorialAnchorID? { + /// The controls this step points at, most specific first; the first one on screen glows. + var targets: [(anchor: TutorialAnchorID, callout: String)] { switch step { - case "sidebar": return .sidebarRow - case "build": return .buildSection - case "rebuild": return .cacheBadge - case "device": return .deviceTile - case "logs", "refresh": return .logsTab - case "agent": return .agentActions - case "finish", "delete", "done": return .archivedFilter - default: return nil + case "build": return [(.launchNoticeShow, "Click Show to watch the build")] + case "device": + return [(.viewerScreen, "Tap the Tap me button and watch the counter"), (.deviceControl, "Open the live view")] + case "agent": + return (tick("viewed") ? [(.replay, "Play the replay")] : [(.agentActions, "See what your agent did")]) + + [(.deviceControl, "Open the live view")] + case "logs": return [(.logsTab, "Open Logs")] + case "finish", "done": return [(.archivedFilter, "Find the run in Archived")] + default: return [] } } - var callout: String { - switch step { - case "sidebar": return "Select the tutorial workspace" - case "build": return "Follow the iOS build" - case "rebuild": return "See the cache outcome in build details" - case "device": return "Open the live view, then tap Log an error." - case "logs", "refresh": return "Open Logs" - case "agent": return "Watch Agent actions and Replay" - case "finish", "delete", "done": return "Find the run in Archived" - default: return "Follow the tutorial workspace" - } + /// The worktrees whose controls this step may point at. + var paths: [String] { (step == "device" ? [path, secondPath] : [path]).compactMap { $0 } } + + var offersShowMe: Bool { + ["device", "agent", "logs", "finish", "done"].contains(step ?? "") } + + func tick(_ id: String) -> Bool { ticks.contains { $0.id == id && $0.done } } } private struct TutorialHintKey: EnvironmentKey { @@ -80,38 +83,25 @@ private struct TutorialHighlights: ViewModifier { func body(content: Content) -> some View { content.overlayPreferenceValue(TutorialAnchorPreference.self) { anchors in GeometryReader { geometry in - if let hint, let id = hint.anchor { - let match = - anchors.first { - $0.key.id == id && ($0.key.workspace == nil || $0.key.workspace == hint.path) - } ?? anchors.first { - hint.step == "rebuild" && $0.key.id == .buildSection && $0.key.workspace == hint.path - } ?? anchors.first { - hint.step == "device" && $0.key.id == .viewerControl - } - ?? anchors.first { - hint.step == "agent" && $0.key.id == .replay - } - if let match, hint.path == hint.selectedPath || id == .sidebarRow || id == .archivedFilter, - geometry[match.value].intersects(CGRect(origin: .zero, size: geometry.size)) - { - let rect = geometry[match.value] - RoundedRectangle(cornerRadius: Radius.control) - .stroke(Palette.accent, lineWidth: 2) - .frame(width: rect.width + 6, height: rect.height + 6) - .position(x: rect.midX, y: rect.midY) - .allowsHitTesting(false) - Text(hint.callout).font(.stim(.footnote, weight: .semibold)) - .foregroundStyle(Palette.text) - .padding(.horizontal, Space.md).padding(.vertical, Space.sm) - .background(RoundedRectangle(cornerRadius: Radius.control).fill(Palette.surface)) - .fixedSize(horizontal: true, vertical: false) - .position( - x: max(140, min(geometry.size.width - 140, rect.midX)), - y: rect.maxY + 38 < geometry.size.height ? rect.maxY + 22 : max(20, rect.minY - 22) - ) - .allowsHitTesting(false) - } else if showFallback, hint.path != nil, hint.path != hint.selectedPath { + if let hint { + let bounds = CGRect(origin: .zero, size: geometry.size) + let onPage = hint.selectedPath.map(hint.paths.contains) == true + let found = hint.targets.lazy.compactMap { target -> (TutorialAnchorID, String, CGRect)? in + guard + let anchor = anchors.first(where: { + $0.key.id == target.anchor && ($0.key.workspace == nil || hint.paths.contains($0.key.workspace!)) + }) + else { return nil } + let rect = geometry[anchor.value] + let global = [.archivedFilter, .launchNoticeShow].contains(target.anchor) + guard global || onPage, rect.intersects(bounds) else { return nil } + return (target.anchor, target.callout, rect) + }.first + if let found { + TutorialGlow( + rect: found.2, bounds: geometry.size, callout: found.1, + restartKey: "\(hint.step ?? "")|\(hint.selectedPath ?? "")|\(found.0)") + } else if showFallback, hint.offersShowMe, hint.path != nil, !onPage { Button("Show Me", action: hint.showMe) .buttonStyle(.stim(.secondary)) .accessibilityLabel("Show the tutorial workspace") @@ -123,3 +113,68 @@ private struct TutorialHighlights: ViewModifier { } } } + +/// A pulsing glow with a capsule label that fades after a few seconds, and shows again when the target changes or +/// comes back after an absence. +private struct TutorialGlow: View { + static let fadeSeconds = 0.6 + static let pulsePeriod = 1.4 + + var rect: CGRect + var bounds: CGSize + var callout: String + var restartKey: String + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var faded = false + @State private var gone = false + + var body: some View { + Group { + if !gone { + TimelineView(reduceMotion ? .animation(minimumInterval: 3600) : .animation) { context in + let phase = + reduceMotion ? 0 : (sin(context.date.timeIntervalSinceReferenceDate * 2 * .pi / Self.pulsePeriod) + 1) / 2 + glow(phase: phase) + } + .opacity(faded ? 0 : 1) + .allowsHitTesting(false) + .accessibilityHidden(true) + } + } + .task(id: restartKey) { + gone = false + faded = false + try? await Task.sleep(for: .seconds(TutorialHint.glowSeconds)) + if Task.isCancelled { return } + withAnimation(.easeOut(duration: Self.fadeSeconds)) { faded = true } + try? await Task.sleep(for: .seconds(Self.fadeSeconds)) + if !Task.isCancelled { gone = true } + } + } + + private func glow(phase: Double) -> some View { + let size = CGSize(width: rect.width + 6, height: rect.height + 6) + let aboveY = rect.minY - 18 + return ZStack { + RoundedRectangle(cornerRadius: Radius.control + 3) + .stroke(Palette.accent.opacity(0.45 + 0.25 * phase), lineWidth: 4 + 2 * phase) + .blur(radius: 6 + 2 * phase) + .frame(width: size.width, height: size.height) + .position(x: rect.midX, y: rect.midY) + RoundedRectangle(cornerRadius: Radius.control + 3) + .strokeBorder(Palette.accent.opacity(0.4), lineWidth: 1) + .frame(width: size.width, height: size.height) + .position(x: rect.midX, y: rect.midY) + Text(callout).font(.stim(.footnote, weight: .semibold)) + .foregroundStyle(Palette.onPrimary) + .padding(.horizontal, Space.md).padding(.vertical, Space.xs) + .background(Capsule().fill(Palette.accent)) + .shadow(color: Palette.accent.opacity(0.4), radius: 6) + .fixedSize(horizontal: true, vertical: false) + .position( + x: max(140, min(bounds.width - 140, rect.midX)), + y: aboveY >= 14 ? aboveY : min(rect.maxY + 18, bounds.height - 14) + ) + } + } +} diff --git a/apps/desktop/Sources/StimDesktop/TutorialModel.swift b/apps/desktop/Sources/StimDesktop/TutorialModel.swift index 970af50de2..d80005db31 100644 --- a/apps/desktop/Sources/StimDesktop/TutorialModel.swift +++ b/apps/desktop/Sources/StimDesktop/TutorialModel.swift @@ -222,12 +222,8 @@ final class TutorialModel: ObservableObject { syncFollowers() } - func skip() { - progress.skip(now: Date()) - refresh() - } - func markDone() { - progress.markDone(now: Date()) + func next() { + progress.next(now: Date()) refresh() } func copiedPrompt(now: Date = Date()) { @@ -235,13 +231,6 @@ final class TutorialModel: ObservableObject { refresh(now: now) } - func commands(for step: TutorialStep) -> String { - tutorialCommands( - step.commands, tourPath: tourPath, repository: workspace?.worktree?.repository ?? snapshot?.record.clonePath, - stateDir: workspace?.agentDevice?.stateDir, - udid: workspace?.ios?.udid, second: snapshot?.record.secondPath) - } - private func refresh(now: Date = Date()) { guard statusLoaded else { return } update( diff --git a/apps/desktop/Sources/StimDesktop/Views/BuildSection.swift b/apps/desktop/Sources/StimDesktop/Views/BuildSection.swift index e8d31fa51d..4a653f9b96 100644 --- a/apps/desktop/Sources/StimDesktop/Views/BuildSection.swift +++ b/apps/desktop/Sources/StimDesktop/Views/BuildSection.swift @@ -452,7 +452,6 @@ struct BuildOutcomeBadge: View { var body: some View { if let label = build.outcomeLabel { Pill(label, tone: build.outcome == "hit" ? .success : .warning, size: .small) - .tutorialAnchor(.cacheBadge) } } } diff --git a/apps/desktop/Sources/StimDesktop/Views/BuildSheet.swift b/apps/desktop/Sources/StimDesktop/Views/BuildSheet.swift index ba0e10ee1c..e92997be79 100644 --- a/apps/desktop/Sources/StimDesktop/Views/BuildSheet.swift +++ b/apps/desktop/Sources/StimDesktop/Views/BuildSheet.swift @@ -87,7 +87,6 @@ struct BuildSheet: View { cli: cli, env: app, run: run, archive: archive, logsExpired: logsExpired, readsServer: readsServer, dismiss: { dismiss() } ) - .tutorialAnchor(.buildSection, workspace: app.path) .id(page == nil ? run.id : "\(app.path)|\(run.id)") .padding(Space.xxl) if archive == nil, run.running == nil, run.id == runs.first?.id { nextBuild } @@ -103,7 +102,6 @@ struct BuildSheet: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } } - .tutorialHighlights(showFallback: false) .font(.stim(.callout)) .background(Palette.background) .frame(minWidth: 980, idealWidth: 980, minHeight: 720, idealHeight: 720) @@ -342,7 +340,6 @@ private struct BuildRunDetail: View { tone: run.running?.cacheLookupOutcome == "hit" || run.last?.cacheHit == .local || run.last?.cacheHit == .remote ? .success : .warning ) - .tutorialAnchor(.cacheBadge, workspace: env.path) } if let reason = run.missReason { MissReasonView(reason: reason) } if let note = run.running?.recheckNote { Text(note).foregroundStyle(Palette.tertiary) } diff --git a/apps/desktop/Sources/StimDesktop/Views/DeviceTile.swift b/apps/desktop/Sources/StimDesktop/Views/DeviceTile.swift index f407232c4a..9f09055e6e 100644 --- a/apps/desktop/Sources/StimDesktop/Views/DeviceTile.swift +++ b/apps/desktop/Sources/StimDesktop/Views/DeviceTile.swift @@ -331,6 +331,7 @@ struct DeviceTile: View { .lineLimit(1) .fixedSize() .accessibilityHidden(true) + .tutorialAnchor(.deviceControl, workspace: workspace) } if case .remote = device { Pill(tone: .warning) { Text("billable") } diff --git a/apps/desktop/Sources/StimDesktop/Views/DeviceViewer.swift b/apps/desktop/Sources/StimDesktop/Views/DeviceViewer.swift index 89737c19ad..9c44f2fc89 100644 --- a/apps/desktop/Sources/StimDesktop/Views/DeviceViewer.swift +++ b/apps/desktop/Sources/StimDesktop/Views/DeviceViewer.swift @@ -49,7 +49,10 @@ struct DeviceViewer: View { AgentFeed(cli: cli, workspace: env.path, slot: device.slot, deviceID: device.activityKey) { agentActions in if let target = replayTarget(device) { ReplayHost(target: target) { replay in - ReplayingContent(replay: replay) { replaying in + ReplayingContent( + replay: replay, + onPlay: { if let udid = device.localSimulatorUDID { TutorialViewerEvents.shared.replayPlayed(udid) } } + ) { replaying in content(device, size: size, agentActions: agentActions, replay: replay, replaying: replaying) } } @@ -137,6 +140,7 @@ struct DeviceViewer: View { HStack(spacing: 0) { VStack(spacing: 0) { canvas(device, replay: replay, replaying: replaying) + .overlay(alignment: .topLeading) { TutorialViewerCard().padding(Space.lg) } if let replay, replaying || env.replayOff || replay.timeline != nil { Rectangle().fill(Palette.border).frame(height: 1) ReplayBar( @@ -170,6 +174,11 @@ struct DeviceViewer: View { } ) .tutorialAnchor(.agentActions, workspace: env.path) + .task(id: agentActions.isEmpty) { + guard !agentActions.isEmpty, let udid = device.localSimulatorUDID else { return } + try? await Task.sleep(for: .seconds(TutorialHint.glowSeconds)) + if !Task.isCancelled { TutorialViewerEvents.shared.actionsViewed(udid) } + } .frame(width: Self.actionsWidth) .background(Palette.sidebar) } @@ -205,6 +214,7 @@ struct DeviceViewer: View { }, windowChoice: windowChoice ) + .tutorialAnchor(.viewerScreen, workspace: env.path) .frame(minWidth: geo.size.width, minHeight: geo.size.height) } .onChange(of: replaying) { _, replaying in @@ -291,6 +301,31 @@ struct DeviceViewer: View { } } +private struct TutorialViewerCard: View { + @Environment(\.tutorialHint) private var hint + + var body: some View { + if let hint, hint.step == "device" { + Card(fill: Palette.raised, border: Palette.separator) { + VStack(alignment: .leading, spacing: Space.sm) { + Text("Live View and Control").font(.stim(.callout, weight: .semibold)) + Text("Tap the Tap me button and watch the counter.").foregroundStyle(Palette.secondary) + ForEach(hint.ticks, id: \.id) { tick in + Label(TutorialPanel.tickTitle(tick.id), systemImage: tick.done ? "checkmark.circle.fill" : "circle") + .font(.stim(.footnote)).foregroundStyle(tick.done ? Palette.success : Palette.secondary) + } + } + .padding(Space.lg) + } + .frame(width: 260, alignment: .leading) + .shadow(color: .black.opacity(0.15), radius: 8, y: 2) + .allowsHitTesting(false) + .accessibilityElement(children: .combine) + .accessibilityLabel("Stim tutorial: Live View and Control") + } + } +} + /// Re-renders its content as the replay starts or stops, or its footage appears or goes, and not as the replay /// moves, so playing and scrubbing redraw only the replay bar, the screen and the action highlighted. private struct ReplayingContent: View { @@ -301,6 +336,7 @@ private struct ReplayingContent: View { } var replay: ReplayController + var onPlay: () -> Void @ViewBuilder var content: (Bool) -> Content @State private var shown = Shown(replaying: false, hasFootage: false) @@ -311,6 +347,7 @@ private struct ReplayingContent: View { .map { Shown(replaying: $0 != nil, hasFootage: !($1?.spans.isEmpty ?? true), replayable: $2) } .removeDuplicates() ) { shown = $0 } + .onReceive(replay.$replay.map { ($0?.rate ?? 0) > 0 }.removeDuplicates()) { if $0 { onPlay() } } } } diff --git a/apps/desktop/Sources/StimDesktop/Views/DeviceViewerToolbar.swift b/apps/desktop/Sources/StimDesktop/Views/DeviceViewerToolbar.swift index 30530d758a..a47078577e 100644 --- a/apps/desktop/Sources/StimDesktop/Views/DeviceViewerToolbar.swift +++ b/apps/desktop/Sources/StimDesktop/Views/DeviceViewerToolbar.swift @@ -199,7 +199,6 @@ struct DeviceViewerToolbar: View { .accessibilityLabel("Release Control") } else { Button("Control", systemImage: "cursorarrow.rays") { takenOver = true } - .tutorialAnchor(.viewerControl, workspace: env.path) .accessibilityLabel("Control device") .nativeIconStyle() .fixedSize() diff --git a/apps/desktop/Sources/StimDesktop/Views/Notices.swift b/apps/desktop/Sources/StimDesktop/Views/Notices.swift index ed30b8f174..0dd3841fc1 100644 --- a/apps/desktop/Sources/StimDesktop/Views/Notices.swift +++ b/apps/desktop/Sources/StimDesktop/Views/Notices.swift @@ -18,6 +18,8 @@ struct Notice: Identifiable { var perform: @MainActor () -> Void } var secondaryAction: Action? + + var launchedWorkspace: String? { key?.hasPrefix("device-launch:") == true ? workspacePath : nil } } @MainActor @@ -151,13 +153,18 @@ private struct NoticeCard: View { .padding(.top, Space.xxs) } - private var primary: some View { - Button(notice.actionTitle) { + @ViewBuilder private var primary: some View { + let button = Button(notice.actionTitle) { center.remove(notice.id) notice.perform() } .buttonStyle(.stim(.primary)) .fixedSize() + if let path = notice.launchedWorkspace { + button.tutorialAnchor(.launchNoticeShow, workspace: path) + } else { + button + } } private func secondary(_ action: Notice.Action) -> some View { diff --git a/apps/desktop/Sources/StimDesktop/Views/RootView.swift b/apps/desktop/Sources/StimDesktop/Views/RootView.swift index c411ff4106..04243a8a6d 100644 --- a/apps/desktop/Sources/StimDesktop/Views/RootView.swift +++ b/apps/desktop/Sources/StimDesktop/Views/RootView.swift @@ -126,11 +126,17 @@ struct RootView: View { snapshot: snapshot, message: tutorial.notice, issues: tutorial.workspace?.issues ?? [], phoneState: tutorial.phoneState, agentDeviceMissing: tutorial.workspace?.agentDevice?.installed == false, - asks: tutorial.ask, commands: tutorial.commands, - copied: { tutorial.copiedPrompt() }, skip: tutorial.skip, markDone: tutorial.markDone, + asks: tutorial.ask, + copied: { tutorial.copiedPrompt() }, next: tutorial.next, restart: tutorial.restart, close: tutorial.close, openArchived: openTutorialArchive, + openBuild: tutorial.tourPath.map { path in + { + navigate(.environment(path), .click("tutorial Open the build")) + focusedDeviceID = tutorial.workspace?.orderedDevices.first { $0.platform == "ios" }?.id + } + }, pairPhone: { openRequests.pairsPhone = true }, updateCLI: { onboarding.openGuide() @@ -411,7 +417,9 @@ struct RootView: View { guard tutorial.isOpen else { return nil } let selected: String? = if case .environment(let path) = selection { path } else { nil } return TutorialHint( - step: tutorial.snapshot?.currentStep ?? "done", path: tutorial.tourPath, selectedPath: selected, + step: tutorial.snapshot?.currentStep ?? "done", path: tutorial.tourPath, + secondPath: tutorial.snapshot?.record.secondPath, selectedPath: selected, + ticks: tutorial.snapshot?.steps.first { $0.id == tutorial.snapshot?.currentStep }?.ticks ?? [], showMe: { if tutorial.snapshot?.isFinished == true { openTutorialArchive() diff --git a/apps/desktop/Sources/StimDesktop/Views/Sidebar.swift b/apps/desktop/Sources/StimDesktop/Views/Sidebar.swift index 0b457efe8f..ec771acaa9 100644 --- a/apps/desktop/Sources/StimDesktop/Views/Sidebar.swift +++ b/apps/desktop/Sources/StimDesktop/Views/Sidebar.swift @@ -352,7 +352,6 @@ struct WorkspaceRow: View { TimelineView(.everyMinute) { _ in WorkspaceRowContent(env: env, now: Date(), place: place, showsGit: showsGit, openLogs: openLogs, isHidden: isHidden) } - .tutorialAnchor(.sidebarRow, workspace: env.path) .sidebarTag(.environment(env.path), selection: selection) .contextMenu { WorkspaceActionsMenu( diff --git a/apps/desktop/Sources/StimDesktop/Views/SidebarWorktreeRow.swift b/apps/desktop/Sources/StimDesktop/Views/SidebarWorktreeRow.swift index a6c3673cbe..834e60589b 100644 --- a/apps/desktop/Sources/StimDesktop/Views/SidebarWorktreeRow.swift +++ b/apps/desktop/Sources/StimDesktop/Views/SidebarWorktreeRow.swift @@ -20,7 +20,6 @@ struct SidebarWorktreeRow: View { if archives.isEmpty { WorktreeActions(page: page, openLogs: showLogs) { menu in row - .tutorialAnchor(.sidebarRow, workspace: page.apps.first(where: { $0.tutorial != nil })?.path ?? page.id) .sidebarTag(.environment(page.id), selection: selection) .contextMenu { menu } } diff --git a/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift b/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift index fd78c647bb..25317f861a 100644 --- a/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift +++ b/apps/desktop/Sources/StimDesktop/Views/TutorialPanel.swift @@ -12,18 +12,16 @@ struct TutorialPanel: View { var phoneState = TutorialPhoneState(pairedPhoneCount: nil) var agentDeviceMissing = false var asks: (TutorialStep) -> String? = { $0.ask } - var commands: (TutorialStep) -> String var copied: () -> Void = {} - var skip: () -> Void = {} - var markDone: () -> Void = {} + var next: () -> Void = {} var restart: () -> Void = {} var close: () -> Void = {} var openArchived: () -> Void = {} + var openBuild: (() -> Void)? = nil var pairPhone: () -> Void = {} var updateCLI: () -> Void = {} @State private var expanded: String? @State private var collapsedOptional: Set = [] - @AppStorage("tutorial.commandsExpanded") private var commandsExpanded = false @ObservedObject private var updater = AppUpdater.shared @ObservedObject private var flags = FeatureFlagStore.shared private var steps: [TutorialStep] { TutorialSteps.steps(phoneApp: flags.phoneApp) } @@ -129,7 +127,14 @@ struct TutorialPanel: View { if open { VStack(alignment: .leading, spacing: Space.md) { Text(explanation(step.id)).foregroundStyle(Palette.secondary) - copyBlock(step) + if let ask = asks(step) { TutorialPromptBox(prompt: ask, onCopy: copied) } + if step.id == "build", current, let openBuild { + HStack(spacing: Space.sm) { + Text("Click Show to watch the build.") + Button("Open the build", action: openBuild).buttonStyle(.link).foregroundStyle(Palette.primary) + .accessibilityLabel("Open the tutorial build") + } + } if step.id == "build", agentDeviceMissing { AgentDeviceCard(copied: copied) } if step.id == "phone", snapshot.record.phonePairedAtStart == true { Text(phoneState.buttonTitle).font(.stim(.footnote)).foregroundStyle(Palette.success) @@ -154,11 +159,15 @@ struct TutorialPanel: View { } ForEach(state.ticks, id: \.id) { tick in Label( - tickTitle(tick.id) + (tick.optional ? " (optional)" : ""), + Self.tickTitle(tick.id) + (tick.optional ? " (optional)" : ""), systemImage: tick.done ? "checkmark.circle.fill" : "circle" ) .font(.stim(.footnote)).foregroundStyle(tick.done ? Palette.success : Palette.secondary) - .accessibilityLabel("\(tickTitle(tick.id)), \(tick.done ? "done" : "waiting")") + .accessibilityLabel("\(Self.tickTitle(tick.id)), \(tick.done ? "done" : "waiting")") + } + if let pull = state.link, let url = URL(string: pull.url) { + Link("PR #\(pull.number): \(pull.title)", destination: url).lineLimit(1) + .accessibilityLabel("Open pull request \(pull.number)") } if current { ForEach(issues, id: \.self) { issue in @@ -168,15 +177,8 @@ struct TutorialPanel: View { if step.id == "phone", phoneState != .paired { Button(phoneState.buttonTitle, action: pairPhone).buttonStyle(.stim(.primary)) } - if step.optional { - Button("Skip", action: skip) - .buttonStyle(.stim(.secondary)) - .accessibilityLabel("Skip \(step.title)") - } - if state.canMarkDone { - Button("Mark Done", action: markDone).buttonStyle(.stim()) - .accessibilityLabel("Mark \(step.title) done") - } + Button("Next", action: next).buttonStyle(.stim(.secondary)) + .accessibilityLabel("Next: leave \(step.title)") } } .padding(.leading, Space.xl) @@ -186,45 +188,8 @@ struct TutorialPanel: View { } } - @ViewBuilder private func copyBlock(_ step: TutorialStep) -> some View { - let ask = asks(step) - let hasCommands = !step.commands.isEmpty - let showsAsk = ask != nil - if let ask, showsAsk { - TutorialPromptBox(prompt: ask, onCopy: copied) - } - if hasCommands { - DisclosureGroup(isExpanded: $commandsExpanded) { - VStack(alignment: .leading, spacing: Space.sm) { - Text(showsAsk ? "Your agent runs these. You can also run them yourself." : "Run these yourself.") - .font(.stim(.footnote)).foregroundStyle(Palette.secondary) - commandBlock(step) - } - .padding(.top, Space.sm) - } label: { - Text(showsAsk ? "Commands your agent will run" : "Commands to run yourself") - .font(.stim(.footnote)).foregroundStyle(Palette.secondary) - } - .accessibilityLabel("Commands for \(step.title)") - } - } - - @ViewBuilder private func commandBlock(_ step: TutorialStep) -> some View { - if rendersStatic { - CommandBlock(commandText: commands(step)) - .fixedSize(horizontal: false, vertical: true) - .frame(height: 280, alignment: .top).clipped() - } else { - ScrollView { CommandBlock(commandText: commands(step)) } - .frame(maxHeight: 280) - } - } - private var footer: some View { HStack { - if !snapshot.isComplete { - Button("Skip Step", action: skip).buttonStyle(.stim(.plain)).accessibilityLabel("Skip current tutorial step") - } Spacer() if rendersStatic { Image(systemName: "ellipsis").accessibilityLabel("Tutorial options") @@ -279,33 +244,32 @@ struct TutorialPanel: View { "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." - case "device": return "Optional. Open the live view of either simulator and tap around while your agents work." - case "agent": - return - "Optional. Your agent verifies UI changes itself with screenshots, taps and logs. Desktop shows what it did and lets you replay it. Apps can declare readiness with two log lines (stim guide lifecycle readiness), so agents can check their own apps the same way. Try a prompt like this, then watch Agent actions." + "While that builds, ask for a second change in a new worktree. 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." + case "device": return "Open a tutorial simulator's live view and tap the app yourself." + case "agent": return "See what your agent did on the device, then replay it." case "logs": return "Optional. Agents read the logs too. Open Logs to see the app's output and any errors." case "phone": return "Optional. Pair a phone from Settings > Phones, then open Stim on it to see these workspaces. You can skip this step." case "share": return - "Optional and public, and do it before finishing so your change still exists. If you paste this, your agent forks appandflow/stim-tutorial and opens a pull request: your GitHub name and change appear on that repo. It needs GitHub access (gh) for your agent, and a bot will reply and close it. Nothing depends on this step." + "Your agent opens a public PR on appandflow/stim-tutorial with before/after screenshots. Needs gh access. Do it before Finish." case "finish": return "Your agent stops the apps and removes the two worktrees and drops their changes. Their builds, logs and agent actions stay under Archived." case "delete": return - "Optional. Your agent removes any tutorial worktrees left and then the clone, through Stim so their simulators and dev servers go too, and deletes the folder. Skip this step to keep the clone." + "Optional. Your agent removes any tutorial worktrees left and then the clone, through Stim so their simulators and dev servers go too, and deletes the folder. Press Next to keep the clone." default: return "" } } - private func tickTitle(_ id: String) -> String { + static func tickTitle(_ id: String) -> String { switch id { case "opened": return "Live view opened" case "input": return "Device controlled" - case "action": return "Agent action received" + case "viewed": return "Agent actions viewed" + case "replayed": return "Replay played" case "stopped": return "Workspace stopped" case "archived": return "Worktree removed and archived" case "cloned": return "Test app cloned" @@ -313,6 +277,7 @@ struct TutorialPanel: View { case "registered": return "Registered with Stim" case "worktrees": return "Tutorial worktrees removed" case "clone": return "Clone removed and deleted" + case "pr": return "Pull request opened" default: return PhaseStep.name(id) } } diff --git a/apps/desktop/Sources/StimDesktop/Views/WorkspaceDetail.swift b/apps/desktop/Sources/StimDesktop/Views/WorkspaceDetail.swift index f037d888a4..733aed9ad6 100644 --- a/apps/desktop/Sources/StimDesktop/Views/WorkspaceDetail.swift +++ b/apps/desktop/Sources/StimDesktop/Views/WorkspaceDetail.swift @@ -151,7 +151,6 @@ struct WorkspaceDetail: View { } .environmentObject(actions) .environmentObject(checks) - .environment(\.tutorialHint, tutorialHint) } .confirmationDialog( "Delete \(archive?.title ?? "archive") (\(archive?.removedLabel(now: fixtureDate ?? Date()) ?? ""))?", @@ -536,7 +535,6 @@ struct WorkspaceDetail: View { ) return tile - .tutorialAnchor(.deviceTile, workspace: workspace.path) .background { Button { focusedID = device.id diff --git a/apps/desktop/Sources/StimDesktop/Views/WorkspaceHeaderLine.swift b/apps/desktop/Sources/StimDesktop/Views/WorkspaceHeaderLine.swift index fdfc0a267e..41e608c381 100644 --- a/apps/desktop/Sources/StimDesktop/Views/WorkspaceHeaderLine.swift +++ b/apps/desktop/Sources/StimDesktop/Views/WorkspaceHeaderLine.swift @@ -37,7 +37,6 @@ struct WorkspaceHeaderLine: View { gitWorkspace: page?.apps[0].path, openBuild: openBuild) } - .tutorialAnchor(.buildSection, workspace: env.path) Spacer(minLength: Space.md) if apps.contains(where: \.replayOff) { Pill("Replay off") diff --git a/apps/desktop/Sources/StimDesktop/Views/WorkspaceInspector.swift b/apps/desktop/Sources/StimDesktop/Views/WorkspaceInspector.swift index e82bfbce08..3d1b8e349b 100644 --- a/apps/desktop/Sources/StimDesktop/Views/WorkspaceInspector.swift +++ b/apps/desktop/Sources/StimDesktop/Views/WorkspaceInspector.swift @@ -25,7 +25,6 @@ struct Inspector: View { cli: cli, env: env, openLogs: openLogs, openBuild: openBuild, readOnly: archive != nil, totals: archive?.buildTotalsLine ) - .tutorialAnchor(.buildSection, workspace: env.path) .id(env.path) } diff --git a/apps/desktop/Sources/StimKit/TutorialCommands.swift b/apps/desktop/Sources/StimKit/TutorialCommands.swift index de706efaa7..b02ee5d7e0 100644 --- a/apps/desktop/Sources/StimKit/TutorialCommands.swift +++ b/apps/desktop/Sources/StimKit/TutorialCommands.swift @@ -1,19 +1,5 @@ import Foundation -public func tutorialCommands( - _ lines: [String], tourPath: String?, repository: String?, stateDir: String?, udid: String? = nil, - second: String? = nil -) -> String { - let base = repository ?? "~/stim-tutorial" - return fillTutorial( - lines.joined(separator: "\n"), - [ - "base": base, "tour": tourPath ?? "", - "stateDir": stateDir ?? "", - "udid": udid ?? "", "second": second ?? "", - ], shellDoubleQuotedValue) -} - public func tutorialAsk( _ template: String, tourPath: String?, repository: String?, second: String? = nil, existing: Set? = nil @@ -21,30 +7,16 @@ public func tutorialAsk( let base = repository ?? "~/stim-tutorial" let worktrees = [tourPath, second].compactMap { $0 }.filter { existing?.contains($0) ?? true } .joined(separator: " and ") - return fillTutorial( - template, - [ - "base": base, "tour": tourPath ?? "the first worktree", - "worktrees": worktrees.isEmpty ? "(there are none, so there is nothing to remove)" : worktrees, - ], { $0 }) -} - -private func fillTutorial(_ source: String, _ values: [String: String], _ format: (String) -> String) -> String { - let pattern = try! NSRegularExpression(pattern: #"\{(base|tour|second|worktrees|stateDir|udid)\}"#) - var result = source - for match in pattern.matches(in: source, range: NSRange(source.startIndex..., in: source)).reversed() { - let key = String(source[Range(match.range(at: 1), in: source)!]) + let values = [ + "base": base, "tour": tourPath ?? "the first worktree", + "worktrees": worktrees.isEmpty ? "(there are none, so there is nothing to remove)" : worktrees, + ] + let pattern = try! NSRegularExpression(pattern: #"\{(base|tour|worktrees)\}"#) + var result = template + for match in pattern.matches(in: template, range: NSRange(template.startIndex..., in: template)).reversed() { + let key = String(template[Range(match.range(at: 1), in: template)!]) guard let value = values[key] else { continue } - result.replaceSubrange(Range(match.range, in: result)!, with: format(value)) + result.replaceSubrange(Range(match.range, in: result)!, with: value) } return result } - -private func shellDoubleQuotedValue(_ value: String) -> String { - let literal = value.hasPrefix("~/") ? String(value.dropFirst(2)) : value - let escaped = literal.replacingOccurrences(of: "\\", with: "\\\\") - .replacingOccurrences(of: "\"", with: "\\\"") - .replacingOccurrences(of: "$", with: "\\$") - .replacingOccurrences(of: "`", with: "\\`") - return value.hasPrefix("~/") ? "$HOME/" + escaped : escaped -} diff --git a/apps/desktop/Sources/StimKit/TutorialProgress.swift b/apps/desktop/Sources/StimKit/TutorialProgress.swift index 868438c461..e4af902665 100644 --- a/apps/desktop/Sources/StimKit/TutorialProgress.swift +++ b/apps/desktop/Sources/StimKit/TutorialProgress.swift @@ -13,6 +13,7 @@ public struct TutorialEnvironment: Sendable { public var repository: String? public var recording: Workspace.Recording? public var agentStateDir: String? + public var pullRequest: PullRequestFacts? public var iosDoctorRanAt: Date? public init?(_ workspace: Workspace) { @@ -29,6 +30,7 @@ public struct TutorialEnvironment: Sendable { repository = workspace.worktree?.repository ?? workspace.path recording = workspace.recording agentStateDir = workspace.agentDevice?.stateDir + pullRequest = workspace.worktree?.pullRequest iosDoctorRanAt = workspace.doctorRuns?.ios.flatMap { parseTimestamp($0.at) } } @@ -76,6 +78,8 @@ public struct TutorialEnvironment: Sendable { public enum TutorialViewerEvent: Equatable, Sendable { case opened(String) case input(String) + case actionsViewed(String) + case replayPlayed(String) } public struct TutorialRecord: Codable, Equatable, Sendable { @@ -223,7 +227,7 @@ public struct TutorialStepProgress: Equatable, Sendable { public var detail: String public var action: TutorialAction? public var ticks: [TutorialTick] - public var canMarkDone: Bool + public var link: PullRequestFacts? } public struct TutorialSnapshot: Sendable { @@ -239,25 +243,24 @@ public struct TutorialProgress: Sendable { public private(set) var record: TutorialRecord? private var viewerOpened = false private var viewerInput = false + private var actionsViewed = false + private var replayPlayed = false private var details: [String: TutorialNotice] = [:] private var phoneApp = true + private var finished: Set = [] public init() {} - public mutating func skip(now: Date) { + /// Leaves the current step: recorded as done when its ticks are all done or it was detected, else as skipped. + public mutating func next(now: Date) { guard var record, record.step != "done" else { return } - record.skipped.append(record.step) - self.record = record - advance(now) - } - - @discardableResult - public mutating func markDone(now: Date) -> Bool { - guard let record, record.step != "done", now.timeIntervalSince(record.stepSince ?? record.startedAt) >= 120 else { - return false + if finished.contains(record.step) { + complete(at: now) + } else { + record.skipped.append(record.step) + self.record = record + advance(now) } - complete(at: now) - return true } public mutating func copiedRunPrompt(now: Date) { @@ -313,10 +316,14 @@ public struct TutorialProgress: Sendable { if record?.stepTimes == nil { record?.stepTimes = [:] } record?.stepTimes?[currentID] = currentSince let logs = input.logRecords.filter { $0.date >= record!.startedAt }.sorted { $0.ts < $1.ts } - if let udid = tracked?.ios?.udid { - for event in input.viewerEvents { - if event == .opened(udid) { viewerOpened = true } - if event == .input(udid), viewerOpened { viewerInput = true } + let devices = [tracked?.ios?.udid, second?.ios?.udid].compactMap { $0 } + for event in input.viewerEvents { + switch event { + case .opened(let udid) where devices.contains(udid): viewerOpened = true + case .input(let udid) where devices.contains(udid) && viewerOpened: viewerInput = true + case .actionsViewed(let udid) where udid == tracked?.ios?.udid: actionsViewed = true + case .replayPlayed(let udid) where udid == tracked?.ios?.udid: replayPlayed = true + default: break } } var failure: TutorialNotice? @@ -339,6 +346,12 @@ public struct TutorialProgress: Sendable { failure = TutorialNotice(reason) break } + let ticks = checkpoint.ticks.filter { !$0.optional } + if checkpoint.completed != nil || (!ticks.isEmpty && ticks.allSatisfy(\.done)) { + finished.insert(id) + } else { + finished.remove(id) + } guard let completed = checkpoint.completed else { break } complete(at: completed) } @@ -359,8 +372,7 @@ public struct TutorialProgress: Sendable { let shown = notice ?? TutorialNotice(checkpoint.detail, action: checkpoint.action) return TutorialStepProgress( id: step.id, state: state, detail: shown.text, action: shown.action, - ticks: checkpoint.ticks, - canMarkDone: current == step.id && input.now.timeIntervalSince(record!.stepSince ?? record!.startedAt) >= 120) + ticks: checkpoint.ticks, link: checkpoint.link) } return TutorialSnapshot( steps: steps, currentStep: current, record: record!, @@ -426,6 +438,7 @@ public struct TutorialProgress: Sendable { var detail = "" var action: TutorialAction? var ticks: [TutorialTick] = [] + var link: PullRequestFacts? } private mutating func checkpoint( @@ -436,9 +449,6 @@ public struct TutorialProgress: Sendable { let last = environment?.lastBuild let history = environment?.builds ?? [] let udid = environment?.ios?.udid - let actions = logs.filter { - udid != nil && $0.src == "agent" && $0.event == "agent_action" && $0.deviceId == udid && $0.date >= since - } func signal(_ substring: String) -> LogRecord? { logs.first { $0.msg.contains(substring) } } func tick(_ id: String, _ done: Bool, optional: Bool = false) -> TutorialTick { TutorialTick(id: id, done: done, optional: optional) @@ -505,19 +515,23 @@ public struct TutorialProgress: Sendable { completed: last.cacheHit == .none ? nil : last.endedAt, detail: last.summary + (last.missReason.map { ": " + $0.summary } ?? "")) case "device": - guard environment?.ios?.app?.state == "running" else { + guard [environment, second].contains(where: { $0?.ios?.app?.state == "running" }) else { return Checkpoint(detail: "Run the app first, then open its live view") } return Checkpoint( - completed: viewerOpened && viewerInput ? now : nil, detail: "Open the live view and tap around.", + completed: viewerOpened && viewerInput ? now : nil, ticks: [tick("opened", viewerOpened), tick("input", viewerInput)]) case "logs": return Checkpoint(detail: "Find the app output in Logs") case "agent": - let first = actions.first + let recorded = logs.contains { + udid != nil && $0.src == "agent" && $0.event == "agent_action" && $0.deviceId == udid + } let off = input.replayOff || environment?.recording?.enabled == false return Checkpoint( - completed: first?.date, detail: off ? "Replay is off: Settings > Advanced" : "Watch the agent actions", - ticks: [tick("action", first != nil)]) + detail: !recorded + ? "No agent actions were recorded on the first change's simulator." + : off ? "Replay is off: Settings > Advanced" : "", + ticks: [tick("viewed", actionsViewed), tick("replayed", replayPlayed)]) case "phone": let paired = (input.pairedPhoneCount ?? 0) > 0 return Checkpoint( @@ -525,6 +539,10 @@ public struct TutorialProgress: Sendable { detail: paired ? "Open Stim on your phone: the tour workspace is there" : "Pair your phone") + case "share": + let pull = environment?.pullRequest + return Checkpoint( + completed: pull == nil ? nil : now, ticks: [tick("pr", pull != nil)], link: pull) case "finish": if record?.step == "finish", environment?.live == false { record?.stopped = true } let absent = environment == nil && second == nil && record?.tourPath != nil diff --git a/apps/desktop/Sources/StimKit/TutorialSteps.swift b/apps/desktop/Sources/StimKit/TutorialSteps.swift index e74d2b1a3f..9f1d49c532 100644 --- a/apps/desktop/Sources/StimKit/TutorialSteps.swift +++ b/apps/desktop/Sources/StimKit/TutorialSteps.swift @@ -8,7 +8,6 @@ public struct TutorialStep: Sendable { public let optional: Bool public let ask: String? public let section: String? - public let commands: [String] } public enum TutorialSteps { @@ -17,91 +16,33 @@ public enum TutorialSteps { public static let all: [TutorialStep] = [ TutorialStep( id: "begin", title: "Get the Test App", who: "agent", optional: false, - ask: "Clone appandflow/stim-tutorial into {base} and follow stim guide tutorial run.", section: "run", - commands: [ - - ]), + ask: "Clone appandflow/stim-tutorial into {base} and follow stim guide tutorial run.", section: "run"), TutorialStep( id: "build", title: "Make a Change", who: "you", optional: false, - ask: "Make the title purple in the Stim tutorial app and check it on the simulator.", section: nil, - commands: [ - - ]), + ask: "Make the title purple in the Stim tutorial app and check it on the simulator.", section: nil), TutorialStep( id: "parallel", title: "Change It Again in Parallel", who: "you", optional: false, - ask: nil, section: nil, - commands: [ - - ]), + ask: "While that builds, make the Tap me button green in a new worktree and check it on the simulator.", section: nil), TutorialStep( id: "device", title: "Live View and Control", who: "you", optional: true, - ask: nil, section: nil, - commands: [ - "stim status" - ]), + ask: nil, section: nil), TutorialStep( - id: "agent", title: "Agent Actions and Replay", who: "agent", optional: true, - ask: "Open the app on the iOS simulator, take a screenshot and confirm the title color.", section: nil, - commands: [ - "cd \"{tour}\"", - "export AGENT_DEVICE_STATE_DIR=\"{stateDir}\"", - "agent-device open dev.stim.tutorial --platform ios --udid {udid}", - "agent-device screenshot tutorial.png", - "agent-device close", - "stim logs --source agent --tail 10", - ]), + id: "agent", title: "Agent Actions and Replay", who: "you", optional: true, + ask: nil, section: nil), TutorialStep( id: "logs", title: "App Logs", who: "you", optional: true, - ask: nil, section: nil, - commands: [ - "stim logs --errors", - "stim logs --grep stim:tutorial", - ]), + ask: nil, section: nil), TutorialStep( id: "phone", title: "Watch on Your Phone", who: "you", optional: true, - ask: nil, section: nil, - commands: [ - - ]), + ask: nil, section: nil), TutorialStep( id: "share", title: "Share Your Finish", who: "you", optional: true, - ask: "Open a pull request to appandflow/stim-tutorial with my title color change, with before and after screenshots from the simulator. See stim guide tutorial share.", section: "share", - commands: [ - "cd \"{tour}\"", - "git commit -am \"\"", - "mkdir -p .expo/screenshots", - "git checkout origin/main -- theme.js", - "xcrun simctl io {udid} screenshot .expo/screenshots/before.png", - "git checkout HEAD -- theme.js", - "xcrun simctl io {udid} screenshot .expo/screenshots/after.png", - "cp .github/pull_request_template.md .expo/screenshots/body.md", - "gh repo fork appandflow/stim-tutorial --remote --remote-name fork", - "git push -u fork HEAD", - "gh pr create --repo appandflow/stim-tutorial --title \"\" --body-file .expo/screenshots/body.md --attach \".expo/screenshots/before.png#Before\" --attach \".expo/screenshots/after.png#After\"", - ]), + ask: "Open a pull request to appandflow/stim-tutorial with my title color change, with before and after screenshots from the simulator. See stim guide tutorial share.", section: "share"), TutorialStep( id: "finish", title: "Finish and Archive", who: "agent", optional: false, - ask: "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.", section: "finish", - commands: [ - "cd \"{tour}\"", - "stim stop", - "cd \"{second}\"", - "stim stop", - "cd \"{base}\"", - "stim worktree remove \"{tour}\"", - "stim worktree remove \"{second}\"", - ]), + ask: "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.", section: "finish"), TutorialStep( id: "delete", title: "Delete the Test App", who: "agent", optional: true, - ask: "Remove the Stim tutorial: remove its worktrees and the clone at {base} with stim worktree remove, then delete {base}. Follow stim guide tutorial delete.", section: "delete", - commands: [ - "cd \"{base}\"", - "grep stimTutorial app.json", - "git worktree list", - "stim stop", - "stim worktree remove \"{base}\"", - "cd ..", - "rm -rf \"{base}\"", - ]), + ask: "Remove the Stim tutorial: remove its worktrees and the clone at {base} with stim worktree remove, then delete {base}. Follow stim guide tutorial delete.", section: "delete"), ] } diff --git a/apps/desktop/Sources/StimKit/TutorialViewerEvents.swift b/apps/desktop/Sources/StimKit/TutorialViewerEvents.swift index 394c7cbd2a..24c2fbaedc 100644 --- a/apps/desktop/Sources/StimKit/TutorialViewerEvents.swift +++ b/apps/desktop/Sources/StimKit/TutorialViewerEvents.swift @@ -15,6 +15,8 @@ public final class TutorialViewerEvents: ObservableObject { public func opened(_ udid: String) { append(.opened(udid)) } public func input(_ udid: String) { append(.input(udid)) } + public func actionsViewed(_ udid: String) { append(.actionsViewed(udid)) } + public func replayPlayed(_ udid: String) { append(.replayPlayed(udid)) } private func append(_ event: TutorialViewerEvent) { sequence += 1 diff --git a/apps/desktop/Tests/StimKitTests/TutorialCommandsTests.swift b/apps/desktop/Tests/StimKitTests/TutorialCommandsTests.swift index f060cd8a10..b4a560d09a 100644 --- a/apps/desktop/Tests/StimKitTests/TutorialCommandsTests.swift +++ b/apps/desktop/Tests/StimKitTests/TutorialCommandsTests.swift @@ -2,30 +2,6 @@ import Testing @testable import StimKit -@Test func tutorialCommandsResolveWorkspaceAndShellQuotedPaths() { - let result = tutorialCommands( - [#"cd "{base}""#, #"cd "{tour}""#, #"export AGENT_DEVICE_STATE_DIR="{stateDir}""#], - tourPath: "/tmp/tour with spaces", repository: "/tmp/base", stateDir: "/tmp/state\"$`\\") - #expect( - result - == "cd \"/tmp/base\"\ncd \"/tmp/tour with spaces\"\nexport AGENT_DEVICE_STATE_DIR=\"/tmp/state\\\"\\$\\`\\\\\"" - ) -} - -@Test func tutorialCommandsExpandDefaultHomeAndPreserveHeredoc() { - let result = tutorialCommands( - [#"base="{base}""#, #"cd "{tour}""#, "cat > App.js <<'EOF'", "console.log(`${TAG} title color=${TITLE_COLOR}`);", "EOF"], - tourPath: nil, repository: nil, stateDir: nil) - #expect(result.hasPrefix("base=\"$HOME/stim-tutorial\"\ncd \"\"")) - #expect(result.hasSuffix("cat > App.js <<'EOF'\nconsole.log(`${TAG} title color=${TITLE_COLOR}`);\nEOF")) -} - -@Test func tutorialCommandsDoNotSubstituteInsideInsertedValues() { - let result = tutorialCommands( - [#"cd "{base}""#, #"cd "{tour}""#], tourPath: "/tmp/tour", repository: "/tmp/{tour}", stateDir: nil) - #expect(result == "cd \"/tmp/{tour}\"\ncd \"/tmp/tour\"") -} - @Test func tutorialAskUsesPlainPathsAndFillsEachPlaceholderOnce() { let result = tutorialAsk( "In {tour}, keep {base}.", tourPath: "/tmp/my tour $1", repository: "/tmp/{tour}") diff --git a/apps/desktop/Tests/StimKitTests/TutorialProgressTests.swift b/apps/desktop/Tests/StimKitTests/TutorialProgressTests.swift index cc636a75b5..3de588c52d 100644 --- a/apps/desktop/Tests/StimKitTests/TutorialProgressTests.swift +++ b/apps/desktop/Tests/StimKitTests/TutorialProgressTests.swift @@ -91,7 +91,6 @@ private func log( #expect(state("build", in: result).state == .done) #expect(state("build", in: result).detail.contains("no earlier build")) #expect(state("build", in: result).ticks.contains { $0.id == "pods" && $0.done }) - #expect(!state("parallel", in: result).canMarkDone) } @Test func tutorialFirstBuildMayBeACacheHit() throws { @@ -232,22 +231,58 @@ private func sibling(path: String = secondPath, repository: String? = "/Users/ex #expect(state("device", in: result).detail == "Run the app first, then open its live view") } -@Test func tutorialAgentRequiresFreshActionOnTourDevice() throws { +@Test func tutorialDeviceTicksTheSecondChangesLiveViewToo() throws { + let tour = try environment("04-live-clean") + var second = tour + second.path = "/Users/example/stim-tutorial-second" + second.ios?.udid = "second-simulator" + var record = saved(at: "device") + record.secondPath = second.path var progress = TutorialProgress() - let actionDate = afterRebuild.addingTimeInterval(1) - let early = try log("press", at: afterBuild, source: "agent", event: "agent_action", device: "tutorial-simulator") - let wrong = try log("press", at: actionDate, source: "agent", event: "agent_action", device: "other") - let failed = try log("replay", at: actionDate, source: "agent", event: "agent_failed", device: "tutorial-simulator") var input = TutorialInput( - environment: try environment(), logRecords: [early, wrong, failed], now: actionDate, + environment: tour, siblings: [tour, second], viewerEvents: [.opened("second-simulator")], now: afterRebuild, + record: record) + var result = progress.update(input) + #expect(result.currentStep == "device") + #expect(state("device", in: result).ticks.map(\.done) == [true, false]) + input.viewerEvents = [.input("second-simulator")] + result = progress.update(input) + #expect(result.currentStep == "agent") + #expect(state("device", in: result).state == .done) +} + +@Test func tutorialShareCompletesWithAPullRequestFromTheFirstChangesWorktree() throws { + var env = try environment() + var progress = TutorialProgress() + var result = progress.update(TutorialInput(environment: env, now: afterRebuild, record: saved(at: "share"))) + #expect(result.currentStep == "share") + env.pullRequest = try JSONDecoder().decode( + PullRequestFacts.self, + from: Data(#"{"number":7,"url":"https://github.com/appandflow/stim-tutorial/pull/7","title":"Green","state":"open"}"#.utf8)) + result = progress.update(TutorialInput(environment: env, now: afterRebuild)) + #expect(result.currentStep == "finish") + #expect(state("share", in: result).state == .done) + #expect(state("share", in: result).link?.number == 7) +} + +@Test func tutorialAgentTicksViewerEventsOnTheTourDeviceAndNextRecordsItDone() throws { + var progress = TutorialProgress() + let checked = try log("press", at: afterBuild, source: "agent", event: "agent_action", device: "tutorial-simulator") + var input = TutorialInput( + environment: try environment(), logRecords: [checked], + viewerEvents: [.actionsViewed("other"), .replayPlayed("other")], now: afterRebuild, record: saved(at: "agent", since: afterRebuild)) - #expect(progress.update(input).currentStep == "agent") - input.logRecords = [ - try log("open", at: actionDate, source: "agent", event: "agent_action", device: "tutorial-simulator", command: "open") - ] - let result = progress.update(input) + var result = progress.update(input) + #expect(state("agent", in: result).detail.isEmpty) + #expect(state("agent", in: result).ticks.allSatisfy { !$0.done }) + input.viewerEvents = [.actionsViewed("tutorial-simulator"), .replayPlayed("tutorial-simulator")] + result = progress.update(input) + #expect(result.currentStep == "agent") + #expect(state("agent", in: result).ticks.map(\.done) == [true, true]) + progress.next(now: afterRebuild.addingTimeInterval(1)) + result = progress.update(TutorialInput(environment: try environment(), now: afterRebuild.addingTimeInterval(1))) #expect(result.currentStep == "logs") - #expect(state("agent", in: result).ticks.first { $0.id == "action" }?.done == true) + #expect(state("agent", in: result).state == .done) } @Test func tutorialLogsStepWaitsForTheUserToMarkItDone() throws { @@ -349,22 +384,17 @@ private func sibling(path: String = secondPath, repository: String? = "/Users/ex #expect(result.isComplete) } -@Test func tutorialSkipAndTimedMarkDonePersistAndResumeAtFirstUnfinishedStep() throws { +@Test func tutorialNextOnAnUndetectedStepRecordsSkippedAndResumesAtTheFirstUnfinishedStep() throws { var progress = TutorialProgress() _ = progress.update( TutorialInput(environment: try environment(), now: afterRebuild, record: saved(at: "phone", since: afterRebuild))) - let tooEarly = progress.markDone(now: afterRebuild.addingTimeInterval(119)) - #expect(!tooEarly) - let waiting = progress.update(TutorialInput(environment: try environment(), now: afterRebuild.addingTimeInterval(120))) - #expect(state("phone", in: waiting).canMarkDone) - let marked = progress.markDone(now: afterRebuild.addingTimeInterval(120)) - #expect(marked) - progress.skip(now: afterRebuild.addingTimeInterval(121)) + progress.next(now: afterRebuild.addingTimeInterval(1)) + progress.next(now: afterRebuild.addingTimeInterval(2)) var relaunched = TutorialProgress() let result = relaunched.update( - TutorialInput(environment: try environment(), now: afterRebuild.addingTimeInterval(122), record: progress.record)) + TutorialInput(environment: try environment(), now: afterRebuild.addingTimeInterval(3), record: progress.record)) #expect(result.currentStep == "finish") - #expect(state("phone", in: result).state == .done) + #expect(state("phone", in: result).state == .skipped) #expect(state("share", in: result).state == .skipped) } @@ -414,14 +444,15 @@ private func sibling(path: String = secondPath, repository: String? = "/Users/ex #expect(paired.record.phonePairedAtStart == false) } -@Test func tutorialAgentWithoutAnIosDeviceDoesNotAcceptUntargetedActions() throws { +@Test func tutorialAgentSaysNoActionsWereRecordedForOtherDevicesOrFailures() throws { var progress = TutorialProgress() - let untargeted = try log("open", at: afterRebuild, source: "agent", event: "agent_action") + let wrong = try log("press", at: afterRebuild, source: "agent", event: "agent_action", device: "other") + let failed = try log("press", at: afterRebuild, source: "agent", event: "agent_failed", device: "tutorial-simulator") let result = progress.update( TutorialInput( - environment: try environment("01-started"), logRecords: [untargeted], - now: afterRebuild, record: saved(at: "agent"))) + environment: try environment(), logRecords: [wrong, failed], now: afterRebuild, record: saved(at: "agent"))) #expect(result.currentStep == "agent") + #expect(state("agent", in: result).detail.hasPrefix("No agent actions")) } @Test func tutorialArchiveDisabledRelaunchRecognizesAnAlreadyRemovedTour() { diff --git a/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift b/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift index 90dcc61517..d5bc582fcb 100644 --- a/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift +++ b/apps/desktop/Tests/VisualFixtureTests/TutorialModelTests.swift @@ -205,7 +205,7 @@ } let model = TutorialModel(defaults: isolatedDefaults(), cloneBase: "/nonexistent/stim-tutorial") model.update(workspaces: [env], archived: [], sheetOpen: false, viewerEvents: events.events) - for _ in 0..<2 { model.skip() } + for _ in 0..<2 { model.next() } XCTAssertEqual(model.snapshot?.currentStep, "device") events.opened("reused-simulator") model.update(workspaces: [env], archived: [], sheetOpen: false, viewerEvents: events.events) diff --git a/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift b/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift index 7640f9c00d..cb8ed3811a 100644 --- a/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift +++ b/apps/desktop/Tests/VisualFixtureTests/TutorialScreenshotTests.swift @@ -16,7 +16,7 @@ BrandAssets.registerFonts() try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true) let variants = [ - "done", "failure", "agent-commands", "finish-commands", "build-no-agent-device", "begin-timeout", "begin-installing", + "done", "failure", "build-no-agent-device", "begin-timeout", "begin-installing", "phone-not-paired", "phone-server-off", "phone-already-paired", "phone-paired-during-step", ] @@ -44,12 +44,6 @@ return ["phone-already-paired", "phone-paired-during-step"].contains(name) ? 1 : 0 } - private var storage: UserDefaults { - let defaults = UserDefaults(suiteName: "TutorialFixture")! - defaults.set(name.hasSuffix("-commands"), forKey: "tutorial.commandsExpanded") - return defaults - } - var body: some View { let snapshot = fixture() TutorialPanel( @@ -62,30 +56,17 @@ $0, tourPath: "/Users/example/stim-tutorial-tour", repository: "/Users/example/stim-tutorial", second: snapshot.record.secondPath) } - }, - commands: { step in - tutorialCommands( - step.commands, tourPath: "/Users/example/stim-tutorial-tour", repository: "/Users/example/stim-tutorial", - stateDir: "/Users/example/.stim/workspaces/tutorial/agent-device", - udid: "tutorial-simulator", second: "/Users/example/stim-tutorial-second") } ) - .defaultAppStorage(storage) - .frame( - width: 320, - height: name.hasSuffix("-commands") || name == "build-no-agent-device" ? 1500 : 960) + .frame(width: 320, height: name == "build-no-agent-device" ? 1500 : 960) } private func fixture() -> TutorialSnapshot { let id = name.hasPrefix("phone-") ? "phone" - : name == "failure" - ? "build" - : name == "agent-commands" - ? "agent" - : name == "finish-commands" - ? "finish" : name == "build-no-agent-device" ? "build" : name.hasPrefix("begin-") ? "begin" : name + : name == "failure" || name == "build-no-agent-device" + ? "build" : name.hasPrefix("begin-") ? "begin" : name let now = Date(timeIntervalSince1970: 1_791_374_400) var engine = TutorialProgress() let done = name == "done" ? TutorialSteps.all.map(\.id) : TutorialSteps.all.prefix { $0.id != id }.map(\.id) diff --git a/apps/desktop/scripts/generate-tokens.mjs b/apps/desktop/scripts/generate-tokens.mjs index 4c7acac013..85049a024c 100644 --- a/apps/desktop/scripts/generate-tokens.mjs +++ b/apps/desktop/scripts/generate-tokens.mjs @@ -139,7 +139,6 @@ public struct TutorialStep: Sendable { public let optional: Bool public let ask: String? public let section: String? - public let commands: [String] } public enum TutorialSteps { @@ -149,10 +148,7 @@ public enum TutorialSteps { ${TUTORIAL_STEPS.map( (step) => ` TutorialStep( id: ${swiftString(step.id)}, title: ${swiftString(step.title)}, who: ${swiftString(step.who)}, optional: ${step.optional}, - ask: ${step.ask === null ? 'nil' : swiftString(step.ask)}, section: ${step.section === null ? 'nil' : swiftString(step.section)}, - commands: [ -${step.commands.map((line) => ` ${swiftString(line)}${step.commands.length === 1 ? '' : ','}`).join('\n')} - ]),`, + ask: ${step.ask === null ? 'nil' : swiftString(step.ask)}, section: ${step.section === null ? 'nil' : swiftString(step.section)}),`, ).join('\n')} ] } diff --git a/packages/stim-cli/src/__tests__/guide.test.ts b/packages/stim-cli/src/__tests__/guide.test.ts index ec9fd73393..2deccc27e8 100644 --- a/packages/stim-cli/src/__tests__/guide.test.ts +++ b/packages/stim-cli/src/__tests__/guide.test.ts @@ -577,6 +577,13 @@ test('the run section names the marker version the status payload reports and on }); }); +test('the run section checks each change on the tutorial app with agent-device', () => { + const run = flat('run'); + for (const testID of ['tap-button', 'dark-accent-switch', 'name-input']) expect(run).toContain(testID); + expect(run).toContain('agent-device open dev.stim.tutorial --platform ios --udid '); + expect(run).toMatch(/snapshot -i before every action/); +}); + test('tutorial setup protects existing folders and the user repository', () => { const run = flat('run'); expect(run).toMatch(/stop and ask the user for another folder; never overwrite or delete it/i); @@ -618,16 +625,14 @@ test('tutorial restart removes nothing, so it cannot contradict the finish force expect(flat('restart')).toMatch(/remove nothing/i); }); -test("the share step comes before finish, pushes to a fork with the simulator udid, and attaches the body's screenshots", () => { +test("the share step comes before finish, pushes to a fork, and attaches the body's screenshots", () => { const ids = TUTORIAL_STEPS.map((step) => step.id); expect(ids.indexOf('share')).toBeLessThan(ids.indexOf('finish')); - const commands = TUTORIAL_STEPS.find((step) => step.id === 'share')!.commands.join('\n'); - expect(commands).toContain('{udid}'); - expect(commands).not.toContain('booted'); - expect(commands).toMatch(/gh repo fork[\s\S]*git push[\s\S]*gh pr create --repo/); - expect(flat('share')).toMatch(/never booted/); + const share = flat('share'); + expect(share).toMatch(/gh repo fork[\s\S]*git push[\s\S]*gh pr create --repo/); + expect(share).toMatch(/never booted/); for (const shot of ['before', 'after']) { - expect(commands).toContain(`--attach ".expo/screenshots/${shot}.png`); + expect(share).toContain(`--attach ".expo/screenshots/${shot}.png`); expect(flat('share')).toContain(`(./.expo/screenshots/${shot}.png)`); } }); diff --git a/packages/stim-cli/src/guide/agent.ts b/packages/stim-cli/src/guide/agent.ts index be97f8770e..9567aae054 100644 --- a/packages/stim-cli/src/guide/agent.ts +++ b/packages/stim-cli/src/guide/agent.ts @@ -397,7 +397,7 @@ FULL TOPIC LIST stim guide cleanup # what reclaims a device, and what deletes stim guide cleanup collector # an unproven collector pid; why the app on a phone closed stim guide cleanup memory # watchman and Gradle daemon memory; gc --cache watchman - stim guide tutorial # tutorial sections and manual commands + stim guide tutorial # tutorial sections stim guide tutorial run # create the app and build in a tour worktree stim guide settings # configuration files and supported keys`, }; diff --git a/packages/stim-cli/src/guide/tutorial-data.ts b/packages/stim-cli/src/guide/tutorial-data.ts index ef9665f994..6934b64423 100644 --- a/packages/stim-cli/src/guide/tutorial-data.ts +++ b/packages/stim-cli/src/guide/tutorial-data.ts @@ -11,7 +11,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.', + parallel: 'While that builds, make the Tap me button green in a new worktree and check it on the simulator.', 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.", delete: @@ -27,7 +27,6 @@ export const TUTORIAL_STEPS: { optional: boolean; ask: string | null; section: string | null; - commands: string[]; }[] = [ { id: 'begin', @@ -36,7 +35,6 @@ export const TUTORIAL_STEPS: { optional: false, ask: TUTORIAL_ASKS.begin, section: 'run', - commands: [], }, { id: 'build', @@ -45,16 +43,14 @@ export const TUTORIAL_STEPS: { optional: false, ask: TUTORIAL_ASKS.build, section: null, - commands: [], }, { id: 'parallel', title: 'Change It Again in Parallel', who: 'you', optional: false, - ask: null, + ask: TUTORIAL_ASKS.parallel, section: null, - commands: [], }, { id: 'device', @@ -63,23 +59,14 @@ export const TUTORIAL_STEPS: { optional: true, ask: null, section: null, - commands: ['stim status'], }, { id: 'agent', title: 'Agent Actions and Replay', - who: 'agent', + who: 'you', optional: true, - ask: TUTORIAL_ASKS.agent, + ask: null, section: null, - commands: [ - 'cd "{tour}"', - 'export AGENT_DEVICE_STATE_DIR="{stateDir}"', - `agent-device open ${TUTORIAL_BUNDLE_ID} --platform ios --udid {udid}`, - 'agent-device screenshot tutorial.png', - 'agent-device close', - 'stim logs --source agent --tail 10', - ], }, { id: 'logs', @@ -88,7 +75,6 @@ export const TUTORIAL_STEPS: { optional: true, ask: null, section: null, - commands: ['stim logs --errors', 'stim logs --grep stim:tutorial'], }, { id: 'phone', @@ -97,7 +83,6 @@ export const TUTORIAL_STEPS: { optional: true, ask: null, section: null, - commands: [], }, { id: 'share', @@ -106,19 +91,6 @@ export const TUTORIAL_STEPS: { optional: true, ask: TUTORIAL_ASKS.share, section: 'share', - commands: [ - 'cd "{tour}"', - 'git commit -am ""', - 'mkdir -p .expo/screenshots', - 'git checkout origin/main -- theme.js', - 'xcrun simctl io {udid} screenshot .expo/screenshots/before.png', - 'git checkout HEAD -- theme.js', - 'xcrun simctl io {udid} screenshot .expo/screenshots/after.png', - 'cp .github/pull_request_template.md .expo/screenshots/body.md', - `gh repo fork ${TUTORIAL_REPO} --remote --remote-name fork`, - 'git push -u fork HEAD', - `gh pr create --repo ${TUTORIAL_REPO} --title "" --body-file .expo/screenshots/body.md --attach ".expo/screenshots/before.png#Before" --attach ".expo/screenshots/after.png#After"`, - ], }, { id: 'finish', @@ -127,15 +99,6 @@ export const TUTORIAL_STEPS: { optional: false, ask: TUTORIAL_ASKS.finish, section: 'finish', - commands: [ - 'cd "{tour}"', - 'stim stop', - 'cd "{second}"', - 'stim stop', - 'cd "{base}"', - 'stim worktree remove "{tour}"', - 'stim worktree remove "{second}"', - ], }, { id: 'delete', @@ -144,14 +107,5 @@ export const TUTORIAL_STEPS: { optional: true, ask: TUTORIAL_ASKS.delete, section: 'delete', - commands: [ - 'cd "{base}"', - 'grep stimTutorial app.json', - 'git worktree list', - 'stim stop', - 'stim worktree remove "{base}"', - 'cd ..', - 'rm -rf "{base}"', - ], }, ]; diff --git a/packages/stim-cli/src/guide/tutorial.ts b/packages/stim-cli/src/guide/tutorial.ts index f01888675a..304cd82470 100644 --- a/packages/stim-cli/src/guide/tutorial.ts +++ b/packages/stim-cli/src/guide/tutorial.ts @@ -1,5 +1,5 @@ import { TUTORIAL_VERSION } from '@stim-cli/core/state'; -import { TUTORIAL_BUNDLE_ID, TUTORIAL_REPO, TUTORIAL_RESTART_PROMPT, TUTORIAL_STEPS } from './tutorial-data.ts'; +import { TUTORIAL_BUNDLE_ID, TUTORIAL_REPO, TUTORIAL_RESTART_PROMPT } from './tutorial-data.ts'; import type { GuideTopic } from './types.ts'; const paths = `Use {base} = ~/stim-tutorial unless the user named another folder. Expand ~ @@ -30,21 +30,15 @@ never booted. Take both with the same tool so they match in size. .expo/ is ignored and outside the native fingerprint, so the files are never committed, never change the build, and never block stim worktree remove. Keep each PNG under 1 MB.`; -function commands(id: string): string { - return TUTORIAL_STEPS.find((step) => step.id === id)!.commands.join('\n'); -} - const tutorial: GuideTopic = { summary: 'A cloned test app: a first build, a second change in parallel with a cache hit, and cleanup', sectionHint: 'run', preamble: () => `STIM TUTORIAL The tutorial clones ${TUTORIAL_REPO}, a tiny Expo app, into {base}; the clone is -never run, and only the optional delete step removes it. The user then asks for a visual change, and for another -change while the first builds. Each change runs in its own linked worktree of -{base}, so each has its own simulator and Metro port, and the second worktree's -first iOS build reuses the first one's native build. Only the clone, the -optional share and the cleanup need this guide: the changes are ordinary +never run, and only the optional delete step removes it. The user then asks for a visual change, which runs in a +linked worktree of {base} with its own simulator and Metro port. Only the clone, +the optional share and the cleanup need this guide: the changes are ordinary requests, so follow stim guide agent for them, and check each change on the device. @@ -57,8 +51,7 @@ ${local} ${paths} -Never pair phones, approve machines, or grant access on the user's behalf. -For commands to type yourself, read stim guide tutorial manual.`, +Never pair phones, approve machines, or grant access on the user's behalf.`, sections: { run: { summary: 'Clone the test app into a fresh folder and install its dependencies', @@ -97,10 +90,20 @@ ${local} ${screenshots} +Check each change on the device with agent-device in that same session, after +the after screenshot, so Stim Desktop records your actions and the user can +replay them: tap tap-button, toggle dark-accent-switch, type a name in +name-input, then take a screenshot (agent-device screenshot +.expo/screenshots/checked.png) and confirm the change. Refs expire after each +action: run agent-device snapshot -i before every action and use the ref it +reports for that testID. When agentDevice.installed is false in stim status +--json, do not install agent-device unasked: check the change with the build +result and stim logs --errors, and tell the user that agent-device would let +you tap through the app. + PAUSE: end the turn. Tell the user to ask for a visual change next, such as -making the title purple, in their own words. Each change runs in a new linked -worktree of {base} (stim guide agent), and its first iOS build takes a few -minutes.`, +making the title purple, in their own words. It runs in a new linked worktree +of {base} (stim guide agent), and its first iOS build takes a few minutes.`, }, finish: { summary: 'Stop and remove the two tutorial worktrees, keeping the clone', @@ -114,7 +117,13 @@ as {tour} and {second}. Never touch any other worktree, an earlier tutorial clone, or the clone itself. For each, stop from its path, then remove it from the clone: -${commands('finish')} + cd "{tour}" + stim stop + cd "{second}" + stim stop + cd "{base}" + stim worktree remove "{tour}" + stim worktree remove "{second}" Use a plain remove first. The user's finish request says they do not need the changes, which is the consent stim guide agent asks for before worktree remove @@ -228,25 +237,6 @@ stimTutorial marker equals ${TUTORIAL_VERSION}; otherwise follow stim guide tutorial run into a fresh folder. Pause as run instructs. Stim Desktop starts over: only worktrees and builds after the restart count.`, }, - manual: { - summary: 'The commands behind each step, for typing yourself', - body: () => `MANUAL TUTORIAL - -${paths} - -Replace {base}, {tour} and {second} with absolute paths: {base} is the clone, -{tour} the first worktree and {second} the second. For Agent Actions, replace -{stateDir} with agentDevice.stateDir from stim ios or stim status --json and -{udid} with the workspace's ios.udid. Clone with git -clone https://github.com/${TUTORIAL_REPO}.git into a fresh folder outside any -repository. Each change runs in its own worktree of that clone (stim guide -agent); the clone itself is never run. Run each worktree on iOS with -stim ios --remote local --remote-build local so it stays on this Mac. - -${TUTORIAL_STEPS.map((step) => `${step.title}${step.optional ? ' (optional)' : ''}\n\n${step.commands.length ? `\`\`\`sh\n${step.commands.join('\n')}\n\`\`\`` : 'Ask your agent in your own words, or observe this step in Stim Desktop.'}`).join('\n\n')} - -Finish removes only the two tutorial worktrees, never the clone; stim guide tutorial finish says when --force is allowed for them.`, - }, }, }; diff --git a/website/docs/desktop.md b/website/docs/desktop.md index 10116f770e..370e9469bb 100644 --- a/website/docs/desktop.md +++ b/website/docs/desktop.md @@ -95,46 +95,49 @@ 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 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. -- **Share Your Finish (optional):** a prompt you may paste before finishing, while your change still exists, to fork the tutorial repo and open a public pull request with before and after screenshots of your change, a short note on how Stim verified it, and a link to Stim. It is public, needs your agent to have GitHub access (`gh`), and a bot replies and closes it. Desktop never runs it and nothing depends on it. +- **Change It Again in Parallel:** while that builds, copy the step's prompt, "While that builds, make the Tap me button green in a new worktree 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 (optional):** open a tutorial simulator's live view and tap the app yourself. A glow points at the device's live view, then its screen: tap **Tap me** and watch the counter. While the live view is open, a small card in it shows the step and its ticks, **Live view opened** and **Device controlled**; the step moves on once both are ticked. +- **Agent Actions and Replay (optional):** see what your agent did on the first change's simulator, then replay it. A glow points at its live view, then its Agent Actions list, then the replay's Play button. The step ticks **Agent actions viewed** and **Replay played** and stays open so you can keep watching; **Next** then records it done. When no agent actions were recorded on that simulator, the step says so. +- **App Logs (optional):** read the app's output and any errors in 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". +- **Share Your Finish (optional):** a prompt you may paste before finishing, while your change still exists, to fork the tutorial repo and open a public pull request with before and after screenshots of your change, a short note on how Stim verified it, and a link to Stim. It is public, needs your agent to have GitHub access (`gh`), and a bot replies and closes it. Desktop never runs it and nothing depends on it. When Stim reports a pull request for the first change's worktree, including one from your fork, the step ticks **Pull request opened**, links it and completes; Stim checks GitHub every few minutes, so the tick can take up to five minutes. - **Finish and Archive:** the prompt names the two worktrees; your agent stops their apps and removes only those, dropping their changes (a forced removal is allowed for exactly those two, after a plain remove refuses). The clone stays. **Open Archived** opens the same workspace page as a read-only archive, with retained build history, logs and recordings. Archived sidebar rows keep the live repository/worktree grouping and app labels. -- **Delete the Test App (optional):** a prompt to remove the tutorial for good. Your agent removes any worktrees of the clone and then the clone itself with a plain `stim worktree remove`, stopping to ask if one holds changes, so their simulators, Metro ports and Stim records are torn down, and then deletes the clone's folder. The step completes when Stim no longer lists the clone and its folder is gone. Skip it to keep the clone. +- **Delete the Test App (optional):** a prompt to remove the tutorial for good. Your agent removes any worktrees of the clone and then the clone itself with a plain `stim worktree remove`, stopping to ask if one holds changes, so their simulators, Metro ports and Stim records are torn down, and then deletes the clone's folder. The step completes when Stim no longer lists the clone and its folder is gone. Press **Next** to keep the clone. + +Your agent checks each change on its simulator with agent-device, following +`stim guide tutorial run`: it taps **Tap me**, toggles **Dark accent**, types a +name and takes a screenshot, so Desktop records its actions for the Agent +Actions and Replay step. When agent-device is not installed, **Make a Change** shows a card with `npm i -g agent-device` and a prompt that installs it. The tutorial completes either way; without it your agent can only check the build and logs. Completed optional steps stay expanded so you can follow the phone handoff. The tutorial does not start the server, pair phones or -grant access. Its only build is the **Run iOS** button. +grant access, and it runs no builds itself. -Accent rings and short callouts point to existing controls without covering the -app with a dimming layer. **Show me** selects the tutorial workspace when its -control is not visible. Build details and the device viewer keep their own -highlights when opened. +A soft glow with a short label points at the control a step needs, without +covering the app with a dimming layer, and fades after a few seconds; it shows +again when the step or page changes. On **Make a Change**, it points at the +**Show** button of the "launched for" notice for your first change's worktree; +if that notice is gone, **Open the build** in the step does the same. **Show +me** selects the tutorial workspace when the control is not on the page. Progress stays in this app's preferences. Closing the panel preserves it; Help reopens it. At launch an unfinished tutorial resumes when Stim still lists -its path, and an archived tour opens at Delete the Test App. **Skip Step** advances without -waiting for a signal. **Mark Done** appears after two minutes. The **…** menu +its path, and an archived tour opens at Delete the Test App. Every step has +**Next**, which moves on without waiting for a signal. It records the step as +done when its checks are all ticked or Desktop detected it, and as skipped +otherwise. Steps Desktop detects move on by themselves. The **…** menu also offers **Restart Tutorial**, which starts over at Get the Test App as on a first start; worktrees from before the restart stay and no longer count. When the tutorial workspace comes from an older tutorial version, the panel says so and offers only **Restart Tutorial**. -Each step shows a plain request to copy for your coding agent, with the paths -filled in from the tour's repository. Below it, a collapsed **Commands your agent -will run** section lists the same work as a short set of commands you can type -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`. +A step that needs your agent shows a plain request to copy, with the paths +filled in from the tour's repository. The default base is `~/stim-tutorial`. The agent keeps the tutorial's own runs local, whatever `ios.remote` or -`remote.build` say. To -read the complete manual: - - +`remote.build` say. Desktop reads the archive setting through `stim settings --json`. If that setting cannot be read, finish waits ten seconds after a previously stopped diff --git a/website/docs/getting-started.md b/website/docs/getting-started.md index bbc361e0b8..d861d5756a 100644 --- a/website/docs/getting-started.md +++ b/website/docs/getting-started.md @@ -101,10 +101,6 @@ Next, ask for a change in your own words.`} {`Clone appandflow/stim-tutorial into ~/stim-tutorial and follow stim guide tutorial run.`} -To type the commands yourself: - - - Finishing stops the apps and removes only the two experiment worktrees, keeping the base repository; an optional last step deletes it. With archiving enabled, the tour appears under Archived. Phone viewing is optional.