Open source CapCut alternative.
TypeScript
feat(app): rework task lifecycle for auto-resume, concurrency, and follow-up injection
David Le006a509a115d
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 11ee1607..9b4718e9 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -28,6 +28,57 @@ private enum VisionGroundingLog {}}+/// Serializes FOREGROUND harness runs so only one holds window focus at a time. Background runs route+/// input by pid and never raise an app, so they parallelize freely and never touch this gate; two+/// foreground runs, by contrast, would fight over the frontmost app, so they queue here and run their+/// visible work one at a time (FIFO). A run still does all its planning/observation concurrently — it+/// only waits for the token around the loop that actually drives the GUI.+actor ForegroundFocusGate {+ private var locked = false+ private var waiters: [(id: Int, continuation: CheckedContinuation<Bool, Never>)] = []+ private var nextWaiterID = 0++ /// Returns true if the caller now holds the token (and must `release()`), false if it was cancelled+ /// while waiting (and must NOT release — it never held the token).+ func acquire() async -> Bool {+ if !locked {+ locked = true+ return true+ }+ let id = nextWaiterID+ nextWaiterID += 1+ // Cancellation removes and resumes the waiter rather than leaving it parked forever; a cancelled+ // waiter never held the token, so it returns false and `locked` (held by the active run) is+ // untouched. Without this, release() would hand the token to a dead continuation and deadlock+ // every later foreground run.+ return await withTaskCancellationHandler {+ await withCheckedContinuation { (continuation: CheckedContinuation<Bool, Never>) in+ if Task.isCancelled {+ continuation.resume(returning: false)+ } else {+ waiters.append((id, continuation))+ }+ }+ } onCancel: {+ Task { await self.cancelWaiter(id) }+ }+ }++ private func cancelWaiter(_ id: Int) {+ guard let index = waiters.firstIndex(where: { $0.id == id }) else { return }+ waiters.remove(at: index).continuation.resume(returning: false)+ }++ func release() {+ if waiters.isEmpty {+ locked = false+ } else {+ // Hand the token directly to the next waiter; ownership transfers, so `locked` stays true.+ waiters.removeFirst().continuation.resume(returning: true)+ }+ }+}+struct UserQueryCommandHandlingResult: Equatable, Sendable {var status: LocalAppTaskLiveRunStatusvar threadStatus: UserQueryTaskStatus@@ -78,7 +129,6 @@ protocol UserQueryCommandHandling: Sendable {context: UserQueryCommandContext?) async -> UserQueryCommandHandlingResultfunc pauseCommand(taskID: String) async -> Bool- func resumeCommand(taskID: String) async -> Boolfunc approvePermissionGate(taskID: String, alwaysAllow: Bool) async -> Bool/// Re-run the harness loop for a task whose permission gate was just/// approved, so the granted command actually executes. Returns nil when the@@ -87,6 +137,16 @@ protocol UserQueryCommandHandling: Sendable {taskID: String,context: UserQueryCommandContext?) async -> UserQueryCommandHandlingResult?+ /// Queue a follow-up instruction onto a task whose loop is still running so it folds it in at its+ /// next step. Returns true when the task is live (a loop will pick it up); false means the caller+ /// should fall back to resuming the task with the instruction as a fresh turn.+ func injectFollowUp(taskID: String, text: String) async -> Bool+ /// Re-run a previously-interrupted task in the BACKGROUND (no focus steal), for unattended+ /// auto-resume on relaunch. Returns nil when the task is unknown or has no goal to resume.+ func autoResumeCommand(+ taskID: String,+ context: UserQueryCommandContext?+ ) async -> UserQueryCommandHandlingResult?}extension UserQueryCommandHandling {@@ -100,12 +160,26 @@ extension UserQueryCommandHandling {) async -> UserQueryCommandHandlingResult? {nil}++ func injectFollowUp(taskID: String, text: String) async -> Bool {+ false+ }++ func autoResumeCommand(+ taskID: String,+ context: UserQueryCommandContext?+ ) async -> UserQueryCommandHandlingResult? {+ nil+ }}struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {var permissionPolicy: ToolCallPolicyvar coordinatorRegistry: UserQueryRunCoordinatorRegistryvar genericHarnessLifecycle: AppHarnessGenericLifecycle+ /// Shared across every run (the actor is a reference, so struct copies captured into run Tasks share+ /// one gate): only one foreground run drives the GUI at a time. See `ForegroundFocusGate`.+ let foregroundFocusGate = ForegroundFocusGate()init(permissionPolicy: ToolCallPolicy = ToolCallPolicy(@@ -198,22 +272,96 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {func continueApprovedCommand(taskID: String,context: UserQueryCommandContext?+ ) async -> UserQueryCommandHandlingResult? {+ // Interactive resume (gate approval, tap Resume): let the understanding boundary pick foreground+ // vs. background as it would for any turn.+ await resumeExistingTask(taskID: taskID, context: context, tracePrefix: "user-query-resume")+ }++ func injectFollowUp(taskID: String, text: String) async -> Bool {+ guard let task = await genericHarnessLifecycle.taskState(taskID: taskID) else { return false }+ switch task.status {+ case .running, .resuming:+ // A live loop drains the queue. The returned flag is authoritative — false means the loop+ // ended in the meantime, so the caller resumes the task instead (which drains it on start).+ return await genericHarnessLifecycle.coordinator.enqueueUserMessage(taskID: taskID, text: text)+ case .waitingForPermission:+ // Blocked on the user at a permission gate. Queue the follow-up WITHOUT resuming, so the gate+ // is preserved; it drains when the user approves and the loop resumes. Report accepted so the+ // caller does not start a competing run that would clear the pending gate.+ _ = await genericHarnessLifecycle.coordinator.enqueueUserMessage(taskID: taskID, text: text)+ return true+ default:+ // No live or gated loop (paused, timedOut, completed, failedSafe, interrupted, cancelled, or a+ // clarification awaiting an answer): the caller resumes/answers, and that run drains the queue.+ return false+ }+ }++ func autoResumeCommand(+ taskID: String,+ context: UserQueryCommandContext?+ ) async -> UserQueryCommandHandlingResult? {+ // Unattended relaunch resume: force background so it never raises an app or moves the cursor.+ await resumeExistingTask(+ taskID: taskID,+ context: context,+ tracePrefix: "user-query-autoresume",+ forcedExecutionPreference: .background+ )+ }++ /// Task metadata keys for the drive target resolved on the first run, so a resume drives the same app.+ static let driveTargetAppMetadataKey = "harness.driveTargetApp"+ static let driveTargetBundleMetadataKey = "harness.driveTargetBundleID"++ /// Shared resume path: re-run an existing task's persisted goal as a fresh loop (its stored world+ /// model and history carry the work forward), pinned to the target the task resolved on its first run.+ /// Returns nil when the task is unknown or has no goal.+ private func resumeExistingTask(+ taskID: String,+ context: UserQueryCommandContext?,+ tracePrefix: String,+ forcedExecutionPreference: ExecutionPreference? = nil) async -> UserQueryCommandHandlingResult? {guard let task = await genericHarnessLifecycle.taskState(taskID: taskID),!task.goal.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {return nil}- let traceID = "user-query-resume-\(UUID().uuidString)"+ var forcedDriveTarget: (appName: String, bundleIdentifier: String?)?+ if let app = task.metadata[Self.driveTargetAppMetadataKey], !app.isEmpty {+ let bundle = task.metadata[Self.driveTargetBundleMetadataKey]+ forcedDriveTarget = (app, (bundle?.isEmpty == false) ? bundle : nil)+ }return await runHarnessLoop(command: task.goal,- traceID: traceID,+ traceID: "\(tracePrefix)-\(UUID().uuidString)",taskID: taskID,preparedTurnMetadata: [:],+ forcedExecutionPreference: forcedExecutionPreference,+ forcedDriveTarget: forcedDriveTarget,visualize: context?.agentVisualizationChanged,progress: Self.progressLabeler(context?.spawnProgressChanged))}+ /// The single bridge from the harness's lifecycle status to the notch row's status. Exhaustive on+ /// `HarnessTaskStatus` so a new harness case is a compile error here rather than silently collapsing+ /// to `.failed`. `.running`/`.resuming` only appear if a run returned still-runnable (a bug); they map+ /// to the retryable `.timedOut` so the row never looks live with no loop behind it.+ static func userQueryStatus(forHarness status: HarnessTaskStatus?) -> UserQueryTaskStatus {+ switch status {+ case .completed: return .completed+ case .paused: return .paused+ case .timedOut: return .timedOut+ case .interrupted: return .interrupted+ case .waitingForUser: return .waitingForClarification+ case .waitingForPermission: return .waitingForPermission+ case .failedSafe, .cancelled: return .failed+ case .running, .resuming, .none: return .timedOut+ }+ }+/// Adapt the spawn-progress callback into a plain narration sink the run/// loop can feed with one-line status labels.private static func progressLabeler(@@ -232,13 +380,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {) != nil}- func resumeCommand(taskID: String) async -> Bool {- await genericHarnessLifecycle.resumeTask(- taskID: taskID,- reason: "User query resumed task"- ) != nil- }-func approvePermissionGate(taskID: String, alwaysAllow: Bool) async -> Bool {await genericHarnessLifecycle.approvePermissionGate(taskID: taskID,@@ -262,6 +403,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {traceID: String,taskID: String,preparedTurnMetadata: [String: String],+ forcedExecutionPreference: ExecutionPreference? = nil,+ forcedDriveTarget: (appName: String, bundleIdentifier: String?)? = nil,visualize: (@MainActor @Sendable (AgentVisualizationPlan) -> Void)? = nil,progress: (@MainActor @Sendable (String) -> Void)? = nil) async -> UserQueryCommandHandlingResult {@@ -276,7 +419,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {preparedTurnMetadata: preparedTurnMetadata)}- guard let target = MacWindowResolver().frontmostUserAppTarget() else {+ // A resume pins the task's original target, so it can drive that app even when it (or nothing) is+ // frontmost — which is the common case right after a relaunch. A fresh turn with no frontmost app+ // and no pinned target still has nothing to drive, so it fails cleanly.+ let frontmost = MacWindowResolver().frontmostUserAppTarget()+ guard forcedDriveTarget != nil || frontmost != nil else {return await failHarnessRun(command: command,response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",@@ -287,8 +434,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {preparedTurnMetadata: preparedTurnMetadata)}- let frontmostAppName = target.appName ?? "the frontmost app"- let frontmostBundleIdentifier = target.bundleIdentifier+ let frontmostAppName = frontmost?.appName ?? forcedDriveTarget?.appName ?? "the frontmost app"+ let frontmostBundleIdentifier = frontmost?.bundleIdentifier ?? forcedDriveTarget?.bundleIdentifierguard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {return await failHarnessRun(@@ -331,14 +478,25 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// Drive the understood target app whenever it names a running or installed app; else the// frontmost app. An installed-but-not-running target stays pinned by name — the see/act tools- // re-resolve its window each call, so it works as soon as the planner launches it.- let driveTarget = Self.resolveDriveTarget(- understanding: understanding,- frontmostAppName: frontmostAppName,- frontmostBundleIdentifier: frontmostBundleIdentifier- )+ // re-resolve its window each call, so it works as soon as the planner launches it. A resume pins+ // the task's original target so the work continues against the right app, not whatever is in front.+ let driveTarget: (appName: String, bundleIdentifier: String?)+ if let forcedDriveTarget {+ driveTarget = (forcedDriveTarget.appName, forcedDriveTarget.bundleIdentifier)+ } else {+ driveTarget = Self.resolveDriveTarget(+ understanding: understanding,+ frontmostAppName: frontmostAppName,+ frontmostBundleIdentifier: frontmostBundleIdentifier+ )+ }let appName = driveTarget.appNamelet bundleIdentifier = driveTarget.bundleIdentifier+ // Pin the resolved target on the task so a later resume drives the same app (see forcedDriveTarget).+ await genericHarnessLifecycle.coordinator.recordMetadata(taskID: taskID, [+ Self.driveTargetAppMetadataKey: appName,+ Self.driveTargetBundleMetadataKey: bundleIdentifier ?? ""+ ])let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(forApp: appName,@@ -393,7 +551,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// boundary flips this to foreground only when the turn's point is for the user to watch. When// understanding is unavailable we still default to background (each lane degrades to foreground on// its own when an action can't be delivered that way).- let executionPreference = understanding?.executionPreference ?? .background+ // An unattended auto-resume forces background so it never raises an app or moves the cursor while+ // the user is away; an interactive turn lets the understanding boundary decide.+ let executionPreference = forcedExecutionPreference ?? understanding?.executionPreference ?? .backgroundlet axProvider = AXComputerUseToolProvider(appName: appName,bundleIdentifier: bundleIdentifier,@@ -496,7 +656,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// background actions already report no screen point, so they produce no cursor plan; this also// covers background coordinate/scroll/drag posts, which move no real pointer.) The overlay never// drives real input either way — realPointerMoved stays false.- let suppressBackgroundCursorPlayback = (understanding?.executionPreference ?? .background) == .background+ let suppressBackgroundCursorPlayback = executionPreference == .background// Always set onStep so every turn is recorded; the overlay narration/cursor is layered on top// when a UI is attached.@@ -560,7 +720,15 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {}// Step budget is progress-based, not a fixed count: the runtime keeps going while the task// advances and stops fast when it stalls or loops, so a long legitimate task isn't cut off.+ // A foreground run waits its turn for window focus so concurrent foreground turns don't fight+ // over the frontmost app; background runs route by pid and never take the gate.+ let holdsForegroundFocus = executionPreference == .foreground+ ? await foregroundFocusGate.acquire()+ : falselet runSteps = await runtime.run(taskID: taskID, planner: planner, onStep: onStep)+ if holdsForegroundFocus {+ await foregroundFocusGate.release()+ }VisionWarmCacheActivity.shared.resume()let finalTask = await genericHarnessLifecycle.coordinator.task(id: taskID)@@ -571,7 +739,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {let outcomeReason = completed ? "ok": (awaitingUser ? "awaitingUser": (awaitingPermission ? "awaitingPermission"- : (finalStatus == .failedSafe ? "failedSafe" : "maxStepsReached")))+ : (finalStatus == .failedSafe ? "failedSafe"+ : (finalStatus == .timedOut ? "timedOut"+ : (finalStatus == .paused ? "paused" : "stopped")))))let turns = runSteps.countlet anyTurnUsedCache = runSteps.contains { $0.toolResult?.metadata["usedCache"] == "true" }let totalParseMS = runSteps.reduce(0.0) { $0 + ($1.toolResult?.metadata["parseMS"].flatMap(Double.init) ?? 0) }@@ -716,9 +886,18 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {traceID: traceID,metadata: ["structuredDecision": "true", "router": "harness", "harness.completed": String(completed)])+ // The runtime sets the task's terminal status authoritatively (run.complete, a stall fail-safe,+ // the step-ceiling timeout, a user pause, or a gate), so the row status maps straight from it.+ // Defensive only: if a run somehow returned still-runnable, mark it timed out (retryable) rather+ // than leaving a row that looks live with no loop behind it.+ await genericHarnessLifecycle.coordinator.timeOutIfRunnable(+ taskID: taskID,+ reason: "User query harness run returned without a terminal status"+ )+ let threadStatus = Self.userQueryStatus(forHarness: finalStatus)let result = UserQueryCommandHandlingResult(status: completed ? .completed : .failedSafe,- threadStatus: completed ? .completed : .failed,+ threadStatus: threadStatus,decision: decision,summary: response,traceID: traceID,@@ -726,19 +905,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {"appHarness.decision": AppHarnessDecisionKind.respond.rawValue]) { _, new in new })- // The planner ends the run via run.complete/run.failSafe, so the task status is usually already- // terminal; finalize defensively for the maxSteps-reached case.- if completed {- _ = await genericHarnessLifecycle.coordinator.complete(- taskID: taskID,- reason: "User query harness run completed"- )- } else {- _ = await genericHarnessLifecycle.coordinator.failSafe(- taskID: taskID,- reason: "User query harness run did not confirm completion"- )- }await coordinatorRegistry.finish(taskID: taskID)logHandlingResult(result,diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex 875bf67d..626835b7 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -33,6 +33,10 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {private var updateChecker: any DonkeyUpdateCheckingprivate let appCatalogRefreshLoop: LocalAppDynamicCatalogRefreshLoopprivate var activeTaskIDs: Set<String> = []+ /// Resume requests made while a task's previous loop was still winding down (e.g. a quick Stop→Resume).+ /// The resume is deferred here and fired by `handleCommandRunResult` once that loop ends, so two loops+ /// never run on one task and the tap is never silently dropped.+ private var pendingResumeTaskIDs: Set<String> = []/// Completed tasks the user has already seen surfaced in the collapsed notch. Expanding the notch/// acknowledges them so their colored pointers stop floating in the collapsed surface; the tasks/// themselves stay in the expanded list until closed.@@ -68,7 +72,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {self.appCatalogRefreshLoop = LocalAppDynamicCatalogRefreshLoop(profileGenerator: HostedLocalAppCatalogProfileGenerator())- let restoredTasks = Self.restoredTasks(from: taskStore.loadRecentTasks(limit: Self.notchTaskDisplayLimit))+ let restoration = Self.restoredTasks(+ from: taskStore.loadRecentTasks(limit: Self.notchTaskDisplayLimit),+ now: Date()+ )+ let restoredTasks = restoration.tasksnotchTasks = restoredTasksnotchAccentIndex = restoredTasks.first.map { UserQueryAccentPalette.normalizedIndex($0.accentIndex) }?? UserQueryAccentPalette.firstIndex@@ -92,6 +100,35 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {appCatalogRefreshLoop.start()checkForUpdates()startLiveSessionIfEnabled()+ autoResumeInterruptedTasks(restoration.autoResumeIDs)+ }++ /// Resume tasks that were actively running when the app last quit (see `restoredTasks`). Each runs as+ /// an unattended BACKGROUND turn — the user may not be present — so it never raises an app or moves+ /// the cursor; progress narrates into the task's own row. Fires once, at launch.+ private func autoResumeInterruptedTasks(_ taskIDs: [String]) {+ guard !taskIDs.isEmpty else { return }+ for taskID in taskIDs {+ guard let context = commandContext(taskID: taskID, isFollowUp: false, source: .followUp, spawnID: nil) else {+ continue+ }+ activeTaskIDs.insert(taskID)+ Task { [weak self, commandHandler] in+ let result = await commandHandler.autoResumeCommand(taskID: taskID, context: context)+ await MainActor.run {+ guard let self else { return }+ // No goal to resume, or the unattended run couldn't even start (no frontmost app,+ // backend off): keep the task retryable rather than failing it, so the user can resume+ // it later. Only a run that actually executed reports its real outcome.+ if result == nil || result?.metadata["harness.abortReason"] != nil {+ self.activeTaskIDs.remove(taskID)+ self.updateTask(id: taskID, detail: "Interrupted — resume", status: .timedOut)+ return+ }+ self.handleCommandRunResult(taskID: taskID, spawnID: nil, isFollowUp: false, result: result!)+ }+ }+ }}/// Bring up the always-on Gemini Live session. It self-gates on configuration@@ -478,6 +515,60 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {matchedTaskID: String?,source: AppHarnessTurnSource = .typedPrompt,spawnID: String? = nil+ ) {+ // A follow-up to a task whose loop is still running — or one blocked at a permission gate — is+ // queued into that task: the running loop folds it in at its next step, and a gated task keeps its+ // gate and drains the follow-up when the user approves. Either way it must NOT start a second run+ // or clear the gate. Everything else (a brand-new command, or a follow-up to a stopped task) takes+ // the fresh/resume path below, which runs concurrently with any other in-flight task.+ let matchedStatus = matchedTaskID.flatMap { task(withID: $0)?.status }+ if let matchedTaskID, matchedStatus == .running || matchedStatus == .waitingForPermission {+ queueFollowUpIntoRunningTask(text: text, taskID: matchedTaskID, source: source, spawnID: spawnID)+ return+ }+ runFreshOrResumedCommand(text: text, matchedTaskID: matchedTaskID, source: source, spawnID: spawnID)+ }++ /// Queue a follow-up onto a task whose loop is still running. The live loop picks it up at its next+ /// step; if the loop happens to finish first, fall back to resuming the task with the instruction.+ private func queueFollowUpIntoRunningTask(+ text: String,+ taskID: String,+ source: AppHarnessTurnSource,+ spawnID: String?+ ) {+ appendTaskEvent(taskID: taskID, role: .user, text: text)+ updateSpawn(id: spawnID, taskID: taskID)+ clearSubmissionInputs()+ lastActiveTaskID = taskID+ promptState.isActive = false+ promptState.isVoiceInputActive = false+ promptState.leadingSignalLevel = .thinking+ promptState.promptText = task(withID: taskID)?.title ?? Self.collapsedDisplayText(for: text)+ syncPrimaryTaskPausedFlag()+ Task { [weak self, commandHandler] in+ let injected = await commandHandler.injectFollowUp(taskID: taskID, text: text)+ guard !injected else { return }+ // Race: the loop finished between the live check and the enqueue. Resume the task with the+ // instruction instead. The user event is already recorded, so it is not appended again.+ await MainActor.run {+ self?.runFreshOrResumedCommand(+ text: text,+ matchedTaskID: taskID,+ source: source,+ spawnID: spawnID,+ appendUserEvent: false+ )+ }+ }+ }++ private func runFreshOrResumedCommand(+ text: String,+ matchedTaskID: String?,+ source: AppHarnessTurnSource = .typedPrompt,+ spawnID: String? = nil,+ appendUserEvent: Bool = true) {let isFollowUp = matchedTaskID != nillet reservedAccentIndex = spawnID.flatMap { spawn(withID: $0)?.accentIndex }@@ -493,15 +584,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {)activeTaskIDs.insert(task.id)lastActiveTaskID = task.id- appendTaskEvent(taskID: task.id, role: .user, text: text)- messageText = ""- inputTextHeight = UserQueryLayout.composerInputTextMinimumHeight- isInputExpanded = false- notchCommandText = ""- notchCommandInputTextHeight = UserQueryLayout.composerInputTextMinimumHeight- isNotchCommandInputExpanded = true+ if appendUserEvent {+ appendTaskEvent(taskID: task.id, role: .user, text: text)+ }+ clearSubmissionInputs()promptState.isActive = false- promptState.isVoiceInputActive = falsepromptState.leadingSignalLevel = .thinkingpromptState.promptText = task.titlesyncPrimaryTaskPausedFlag()@@ -551,6 +638,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {result: result,minimumFadeDelay: cursorOverlayRequest.map(Self.visualizationPlaybackDuration))+ // Honor a resume requested while this loop was still winding down (e.g. Stop→Resume): now that the+ // loop has ended and the task left activeTaskIDs, the resume can start without racing a live loop.+ if pendingResumeTaskIDs.remove(taskID) != nil {+ resumeTask(id: taskID)+ }}func pauseTask(id taskID: String) {@@ -567,7 +659,16 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {func resumeTask(id taskID: String) {guard let task = task(withID: taskID),- task.status == .paused || task.status == .interrupted else {+ [.paused, .interrupted, .timedOut, .needsAttention].contains(task.status) else {+ return+ }+ // Only run a task with real work behind it; an info-only row (e.g. an asset drop) has no goal, so+ // resuming would dead-end. Such rows shouldn't offer Resume, but guard here too.+ guard !task.commandText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }+ // If the task's previous loop is still winding down (e.g. just Stopped), defer the resume until it+ // ends so two loops never run on one task; handleCommandRunResult fires the deferred resume.+ guard !activeTaskIDs.contains(taskID) else {+ pendingResumeTaskIDs.insert(taskID)return}@@ -579,12 +680,22 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {promptState.leadingSignalLevel = .thinkingpromptState.promptText = task.titlesyncPrimaryTaskPausedFlag()+ // Pausing or a relaunch tears the loop down, so there is no suspended loop to continue in memory:+ // re-run the task's existing goal as a fresh loop. The persisted world model and history carry the+ // context forward, so it continues the work rather than starting over.+ let context = commandContext(taskID: taskID, isFollowUp: false, source: .followUp, spawnID: nil)Task { [weak self, commandHandler] in- let resumedInMemory = await commandHandler.resumeCommand(taskID: taskID)- guard !resumedInMemory else { return }-+ guard let result = await commandHandler.continueApprovedCommand(taskID: taskID, context: context) else {+ // Nothing to resume (e.g. the harness snapshot is gone): restore a retryable row rather+ // than leaving it stuck on the optimistic "running" with no loop behind it.+ await MainActor.run {+ self?.activeTaskIDs.remove(taskID)+ self?.updateTask(id: taskID, detail: "Couldn’t resume — tap to retry", status: .timedOut)+ }+ return+ }await MainActor.run {- self?.startCommandRun(text: "Continue", matchedTaskID: taskID)+ self?.handleCommandRunResult(taskID: taskID, spawnID: nil, isFollowUp: false, result: result)}}}@@ -902,18 +1013,16 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {.id}+ /// Only an EXPLICIT spawn selection force-targets an existing task. A bare new prompt is never+ /// auto-attached to the latest task just because it is the most recent — that route is what made a+ /// new command hijack a running task. Implicit follow-up matching is left entirely to the typed+ /// follow-up resolver, which decides against task content rather than recency.private func promptSubmissionFollowUpTarget() -> (spawnID: String, taskID: String)? {- if let selectedSpawnID,- let taskID = taskIDForInteractableSpawn(id: selectedSpawnID) {- return (selectedSpawnID, taskID)- }-- guard let spawnID = latestInteractableSpawnID(),- let taskID = taskIDForInteractableSpawn(id: spawnID) else {+ guard let selectedSpawnID,+ let taskID = taskIDForInteractableSpawn(id: selectedSpawnID) else {return nil}-- return (spawnID, taskID)+ return (selectedSpawnID, taskID)}private func taskIDForInteractableSpawn(id spawnID: String) -> String? {@@ -962,15 +1071,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {if let reservedAccentIndex {task.accentIndex = UserQueryAccentPalette.normalizedIndex(reservedAccentIndex)}- if Self.shouldShowChangedCourseState(for: task) {- task.detail = "Changed course: \(Self.collapsedDisplayText(for: text))"- task.status = .interrupted- task.metadata["genericHarness.taskStatus"] = "interrupted"- task.metadata["genericHarness.newGoal"] = text- } else {- task.detail = Self.runningSeedDetail- task.status = .running- }+ // A follow-up to a task whose loop is still running is queued into it upstream (it never+ // reaches here). A matched task that reaches this point has a stopped loop, so a new turn+ // resumes it: seed it back to running rather than restarting it under a replaced goal.+ task.detail = Self.runningSeedDetail+ task.status = .runningtask.updatedAt = Date()notchAccentIndex = UserQueryAccentPalette.normalizedIndex(task.accentIndex)prependTask(task)@@ -1189,30 +1294,49 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {syncPrimaryTaskPausedFlag()}- private static func restoredTasks(from tasks: [UserQueryNotchTask]) -> [UserQueryNotchTask] {- tasks.map { task in- guard Self.inFlightStatusesAtLaunch.contains(task.status) else { return task }-- var restoredTask = task- restoredTask.status = .needsAttention- restoredTask.detail = "Interrupted"- restoredTask.updatedAt = Date()- return restoredTask+ /// How recently a running task must have last advanced to auto-resume itself on relaunch. Inside the+ /// window the work was clearly in progress and should pick back up; outside it, resuming unattended+ /// work the user likely moved on from (and spending credits while they're away) is the wrong default.+ private static let autoResumeStalenessWindow: TimeInterval = 30 * 60++ /// Maps persisted tasks into their post-relaunch state and collects the IDs to auto-resume. A relaunch+ /// tears down every live loop, so an in-flight task can't simply keep running — but one that was+ /// actively working moments ago resumes on its own, while staler or user-blocked work comes back as a+ /// row the user can resume with a tap. The persisted `updatedAt` is preserved throughout so a row's+ /// elapsed time stays the real run duration rather than the gap until the app was reopened.+ static func restoredTasks(+ from tasks: [UserQueryNotchTask],+ now: Date+ ) -> (tasks: [UserQueryNotchTask], autoResumeIDs: [String]) {+ var autoResumeIDs: [String] = []+ let restored = tasks.map { task -> UserQueryNotchTask in+ switch task.status {+ case .running:+ // Actively running when the app quit. Resume on its own only if that was recent;+ // otherwise it becomes a retryable row instead of running stale work unattended.+ if now.timeIntervalSince(task.updatedAt) <= autoResumeStalenessWindow {+ autoResumeIDs.append(task.id)+ return task+ }+ var timedOut = task+ timedOut.status = .timedOut+ timedOut.detail = "Timed out — resume"+ return timedOut+ case .waitingForClarification, .waitingForReview, .waitingForPermission:+ // Was blocked on the user; the loop that asked is gone. Surface a benign, resumable row+ // (it needs the user to continue anyway) without raising the collapsed attention glyph.+ var restoredTask = task+ restoredTask.status = .needsAttention+ restoredTask.detail = "Interrupted"+ return restoredTask+ default:+ // paused, completed, failed, timedOut, interrupted, needsAttention, chatting: unchanged.+ return task+ }}+ return (restored, autoResumeIDs)}- /// Statuses that imply a live harness loop. A relaunch tears that loop down, so none of these- /// can survive: the run is no longer in flight, nor is it actually blocked on the user for a- /// reply, a review, or a permission. Each is collapsed to the benign `needsAttention`, which- /// surfaces the task in the list without falsely raising the collapsed attention glyph (a- /// waiting reply/review) or permission shield for a session that has already ended.- private static let inFlightStatusesAtLaunch: Set<UserQueryTaskStatus> = [- .running,- .waitingForClarification,- .waitingForReview,- .waitingForPermission- ]-private func refreshPromptStateAfterRunResult(taskID: String,result: UserQueryCommandHandlingResult@@ -1276,6 +1400,8 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {return result.summary.isEmpty ? "Done" : collapsedDisplayText(for: result.summary)case .failed:return result.summary.isEmpty ? "Stopped" : collapsedDisplayText(for: result.summary)+ case .timedOut:+ return "Timed out — resume"}}@@ -1324,22 +1450,6 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {return "Uploaded assets: \(displayNames)"}- private static func shouldShowChangedCourseState(for task: UserQueryNotchTask) -> Bool {- switch task.status {- case .running, .interrupted:- return true- case .chatting,- .paused,- .completed,- .waitingForClarification,- .waitingForPermission,- .waitingForReview,- .needsAttention,- .failed:- return false- }- }-private static func persistedAsset(from draft: UserQueryTaskAssetDraft,assetID: String,diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex cbe594ab..79e552c0 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -147,11 +147,23 @@ public enum DonkeyPrompts {let elementsBlock = harnessStepElementsBlock(task.worldModel.elements)let windowsBlock = harnessStepWindowsBlock(openWindows)- let factsBlock = task.worldModel.facts.isEmpty+ // Follow-up instructions the user added after the task started are surfaced in their own block+ // below (right under the goal), so they are excluded from the generic facts dump here.+ let displayFacts = task.worldModel.facts+ .filter { $0.key != HarnessTaskCoordinator.additionalInstructionsFactKey }+ let factsBlock = displayFacts.isEmpty? ""- : "\nKnown state:\n" + task.worldModel.facts.sorted { $0.key < $1.key }+ : "\nKnown state:\n" + displayFacts.sorted { $0.key < $1.key }.map { " \($0.key) = \($0.value)" }.joined(separator: "\n") + "\n"+ let followUpInstructions = task.worldModel.facts[HarnessTaskCoordinator.additionalInstructionsFactKey]?+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ let followUpBlock = followUpInstructions.isEmpty+ ? ""+ : "\nADDITIONAL INSTRUCTIONS FROM THE USER (sent after the task started — fold them into your "+ + "current work; do NOT restart from scratch or redo completed steps):\n"+ + String(followUpInstructions.prefix(800)) + "\n"+let environmentBlock = (environmentSummary?.isEmpty == false)? "\nENVIRONMENT (command-line tools on this Mac — only reach for what's installed):\n \(environmentSummary!)\n": ""@@ -199,7 +211,7 @@ public enum DonkeyPrompts {entirely with system tools and have no on-screen UI target; reach for the GUI only when the tasktruly needs it.GOAL: \(goalText)- \(understandingBlock)+ \(followUpBlock)\(understandingBlock)\(historyBlock)\(factsBlock)\(environmentBlock)\(guidanceBlock)\(skillCatalogBlock)\(windowsBlock)\(elementsBlock)diff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryActivity.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryActivity.swiftindex 89a10197..b40e0135 100644--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryActivity.swift+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryActivity.swift@@ -144,6 +144,9 @@ public extension UserQueryActivity {case .interrupted: return .interruptedcase .needsAttention: return .needsAttentioncase .failed: return .failed+ // A timed-out run is benign and retryable, so it surfaces the same non-nagging attention kind;+ // the row's own detail ("Timed out — resume") carries the specifics.+ case .timedOut: return .needsAttention}}diff --git a/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swiftindex 279eeef4..27830718 100644--- a/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swift@@ -101,7 +101,8 @@ public enum UserQuerySpawnLifecycle {.waitingForReview,.interrupted,.needsAttention,- .failed:+ .failed,+ .timedOut:truecase .completed:falsediff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swiftindex 60cddeff..005b66a5 100644--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swift@@ -11,6 +11,7 @@ public enum UserQueryTaskStatus: String, Codable, Equatable, Sendable {case interruptedcase needsAttentioncase failed+ case timedOut}public struct UserQueryNotchTask: Codable, Equatable, Identifiable, Sendable {diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swiftindex f6ada002..13d1ee2c 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift@@ -25,6 +25,9 @@ public enum HarnessTaskStatus: String, Codable, CaseIterable, Equatable, Sendablcase completedcase failedSafecase cancelled+ /// The run hit the runaway step ceiling (or a wall-clock limit) without completing. Terminal for+ /// the loop, but the goal still stands, so it surfaces as a retryable row rather than a failure.+ case timedOutpublic var canExecuteTools: Bool {self == .running || self == .resumingdiff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swiftindex a546d3b1..da22fb52 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift@@ -32,6 +32,26 @@ public struct HarnessPendingContinuation: Codable, Equatable, Sendable {}}+/// A user instruction that arrived while the task's loop was already running. It is queued on the task+/// and drained at the top of the next loop iteration, so a live run folds in the new instruction at its+/// next step instead of being torn down and restarted. This is the deliberate opposite of `interrupt`,+/// which clobbers the goal.+public struct HarnessPendingUserMessage: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var text: String+ public var createdAt: Date++ public init(+ id: String = UUID().uuidString,+ text: String,+ createdAt: Date = Date()+ ) {+ self.id = id+ self.text = text+ self.createdAt = createdAt+ }+}+public struct HarnessTaskState: Codable, Equatable, Sendable {public var id: Stringpublic var threadID: String@@ -107,8 +127,23 @@ public struct HarnessTaskEvent: Codable, Equatable, Sendable {}public actor HarnessTaskCoordinator {+ /// Fact key the planner reads for instructions the user added after the task started. Persistent and+ /// additive: each follow-up appends here so every later step keeps incorporating it, unlike a+ /// transient "new message" flag that would read as brand-new on every prompt.+ public static let additionalInstructionsFactKey = "additionalUserInstructions"+private var tasksByID: [String: HarnessTaskState] = [:]private var eventsByTaskID: [String: [HarnessTaskEvent]] = [:]+ /// Ephemeral, in-memory only: follow-up instructions queued against a running loop, drained at the+ /// top of the next loop iteration. Deliberately not part of the persisted `HarnessTaskState` — a+ /// queued message only matters to a live loop, and the drained text is folded into the persisted+ /// world model anyway.+ private var pendingUserMessagesByID: [String: [HarnessPendingUserMessage]] = [:]+ /// Task IDs with a live runtime loop right now. The authoritative answer to "will an enqueued+ /// follow-up actually be drained?" — set in `beginRun`, cleared in `endRunUnlessPending`/`markLoopEnded`.+ /// Sampling this is what lets `enqueueUserMessage` tell a caller whether to inject or fall back to a+ /// fresh resume, instead of guessing from a status that can already be stale.+ private var runningLoopTaskIDs: Set<String> = []private let threadStore: (any HarnessThreadStoring)?public init(threadStore: (any HarnessThreadStoring)? = nil) {@@ -138,6 +173,23 @@ public actor HarnessTaskCoordinator {return task}+ /// Merge metadata onto a task without recording a lifecycle event (used to pin the resolved drive+ /// target so a later resume drives the original app rather than whatever is frontmost). Persists the+ /// snapshot but stays quiet in the thread record, since it is bookkeeping, not a step.+ public func recordMetadata(taskID: String, _ values: [String: String]) async {+ let existing: HarnessTaskState?+ if let cached = tasksByID[taskID] {+ existing = cached+ } else {+ existing = await threadStore?.taskSnapshot(id: taskID)+ }+ guard var task = existing else { return }+ task.metadata.merge(values) { _, new in new }+ task.updatedAt = Date()+ tasksByID[taskID] = task+ await threadStore?.upsertTaskSnapshot(task)+ }+public func task(id: String) async -> HarnessTaskState? {if let task = tasksByID[id] {return task@@ -242,6 +294,9 @@ public actor HarnessTaskCoordinator {public func complete(taskID: String, reason: String = "Task completed") async -> HarnessTaskState? {await mutate(taskID: taskID, status: .completed, summary: reason) { task intask.pendingContinuation = nil+ // Follow-up instructions were run-scoped context for this completed run; drop them so a later+ // reuse of the task never re-presents an already-handled one-shot as a fresh demand.+ task.worldModel.facts[Self.additionalInstructionsFactKey] = nil}}@@ -251,6 +306,14 @@ public actor HarnessTaskCoordinator {}}+ /// The loop hit the runaway step ceiling without completing — distinct from a fail-safe stall. The+ /// goal still stands, so the task is left retryable: resuming it (`startRunning`) re-enters the loop.+ public func timeOut(taskID: String, reason: String = "Task hit the step ceiling") async -> HarnessTaskState? {+ await mutate(taskID: taskID, status: .timedOut, summary: reason) { task in+ task.pendingContinuation = nil+ }+ }+public func interrupt(taskID: String,newGoal: String,@@ -271,6 +334,93 @@ public actor HarnessTaskCoordinator {}}+ /// Mark that a runtime loop has started for this task. Paired with `endRunUnlessPending` /+ /// `markLoopEnded`. While a loop is marked running, an enqueued follow-up is guaranteed to be drained+ /// by it (the loop drains every iteration and, on exit, atomically checks for late arrivals).+ public func beginRun(taskID: String) {+ runningLoopTaskIDs.insert(taskID)+ }++ /// Unconditionally clear the running-loop mark (used when a run ends on a terminal that should not be+ /// reopened, e.g. a step-ceiling timeout).+ public func markLoopEnded(taskID: String) {+ runningLoopTaskIDs.remove(taskID)+ }++ /// Atomically decide, at the end of a loop, whether the run is truly finished. Returns true (caller+ /// stops) only when no follow-up is queued; if a follow-up slipped in after the last drain, the mark+ /// is kept and the caller loops once more to drain it. Because this is one actor call, it cannot race+ /// `enqueueUserMessage`: either the message lands first (queue non-empty → keep running) or this clears+ /// the mark first (so `enqueueUserMessage` then reports no live loop and the caller resumes instead).+ public func endRunUnlessPending(taskID: String) -> Bool {+ if pendingUserMessagesByID[taskID]?.isEmpty == false {+ return false+ }+ runningLoopTaskIDs.remove(taskID)+ return true+ }++ /// Queue a follow-up instruction onto a task. Returns whether a live loop is running that will drain+ /// it — false means the caller should resume the task instead (a fresh run drains it at its top). The+ /// deliberate opposite of `interrupt`, which clobbers the goal; this amends the work in place.+ @discardableResult+ public func enqueueUserMessage(taskID: String, text: String) async -> Bool {+ guard let task = await task(id: taskID) else { return false }+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else { return runningLoopTaskIDs.contains(taskID) }+ pendingUserMessagesByID[taskID, default: []].append(HarnessPendingUserMessage(text: trimmed))+ // Record the follow-up immediately so it survives in the thread even if the loop ends before drain.+ await appendEvent(taskID: taskID, status: task.status, summary: "Queued follow-up: \(trimmed)")+ return runningLoopTaskIDs.contains(taskID)+ }++ /// Pull and clear any queued follow-up instructions, appending them to the additive+ /// `additionalUserInstructions` fact the planner reads. Returns the drained messages (empty if none).+ @discardableResult+ public func drainUserMessages(taskID: String) async -> [HarnessPendingUserMessage] {+ guard let queued = pendingUserMessagesByID[taskID], !queued.isEmpty else { return [] }+ pendingUserMessagesByID[taskID] = nil+ let addition = queued.map(\.text).joined(separator: "\n")+ _ = await mutate(taskID: taskID, status: nil, summary: "Folded in queued follow-up") { task in+ let existing = task.worldModel.facts[Self.additionalInstructionsFactKey]+ let combined = [existing, addition]+ .compactMap { $0 }+ .filter { !$0.isEmpty }+ .joined(separator: "\n")+ task.worldModel.facts[Self.additionalInstructionsFactKey] = combined+ }+ return queued+ }++ /// Re-open a task whose loop reached a non-gate terminal (completed/failedSafe/timedOut/cancelled) so a+ /// freshly-drained follow-up gets acted on. Unlike `startRunning`, it preserves the world model facts+ /// (including the just-folded instruction). Gates and already-runnable tasks are left untouched.+ public func reopenForFollowUp(taskID: String) async {+ guard let task = await task(id: taskID) else { return }+ switch task.status {+ case .completed, .failedSafe, .timedOut, .cancelled:+ _ = await mutate(taskID: taskID, status: .running, summary: "Reopened for queued follow-up") { task in+ task.pendingContinuation = nil+ }+ default:+ break+ }+ }++ /// Mark a still-runnable task as timed out (used when the loop hits the step ceiling). No-op if the+ /// task already reached a terminal/gate state.+ public func timeOutIfRunnable(taskID: String, reason: String) async {+ guard let task = await task(id: taskID), task.status.canExecuteTools else { return }+ _ = await timeOut(taskID: taskID, reason: reason)+ }++ /// Mark a still-runnable task as failed-safe (used when the planner stops or a tool call can't run). No-op+ /// if the task already reached a terminal/gate state.+ public func failSafeIfRunnable(taskID: String, reason: String) async {+ guard let task = await task(id: taskID), task.status.canExecuteTools else { return }+ _ = await failSafe(taskID: taskID, reason: reason)+ }+public func waitForUser(taskID: String,question: String,@@ -412,6 +562,6 @@ public actor HarnessTaskCoordinator {}private static func isActiveTask(_ task: HarnessTaskState) -> Bool {- [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming].contains(task.status)+ [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming, .timedOut].contains(task.status)}}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftindex d662c965..78b1ed41 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -67,22 +67,51 @@ public struct GenericHarnessRuntime: Sendable {var noProgressStreak = 0var identicalNoProgressStreak = 0var lastCallSignature: String?- for _ in 0..<maxSteps {+ var iterations = 0++ // Mark this task as having a live loop. While marked, an enqueued follow-up is guaranteed delivery:+ // it is drained at the top of each iteration, and the only stop that actually ends the run is one+ // where `endRunUnlessPending` confirms the queue is empty in the same actor step. A follow-up that+ // slips in at any stop reopens the run for one more pass instead of being silently dropped.+ await coordinator.beginRun(taskID: taskID)++ loop: while true {+ // Fold any queued follow-up into the world model before planning. A fresh instruction resets+ // the no-progress streak (legitimately new work) but NOT the identical-repeat guard, so a+ // planner looping on one call is still caught; it also reopens a task whose previous step had+ // already finished the run, so the new instruction is acted on rather than dropped.+ if !(await coordinator.drainUserMessages(taskID: taskID)).isEmpty {+ noProgressStreak = 0+ await coordinator.reopenForFollowUp(taskID: taskID)+ }++ // Runaway backstop: a still-runnable task that exhausts the iteration budget timed out (the+ // goal stands, so it stays retryable) — distinct from a stall (failSafe) or a clean stop.+ if iterations >= maxSteps {+ await coordinator.timeOutIfRunnable(taskID: taskID, reason: "maxStepsReached")+ await coordinator.markLoopEnded(taskID: taskID)+ break loop+ }+ iterations += 1+guard let task = await coordinator.task(id: taskID), task.status.canExecuteTools else {- break+ if await coordinator.endRunUnlessPending(taskID: taskID) { break loop } else { continue loop }}guard let call = await planner.planNextStep(for: task) else {- break+ // The planner stopped without a lifecycle call: an abnormal stop, not a timeout.+ await coordinator.failSafeIfRunnable(taskID: taskID, reason: "plannerStopped")+ if await coordinator.endRunUnlessPending(taskID: taskID) { break loop } else { continue loop }}let signature = call.name + "\u{1}" + Self.canonicalInput(call.input)guard let step = await executeToolCall(taskID: taskID, call: call) else {- break+ await coordinator.failSafeIfRunnable(taskID: taskID, reason: "executeFailed")+ if await coordinator.endRunUnlessPending(taskID: taskID) { break loop } else { continue loop }}results.append(step)await onStep?(step)if step.stoppedForGate || !step.task.status.canExecuteTools {- break+ if await coordinator.endRunUnlessPending(taskID: taskID) { break loop } else { continue loop }}// Stall detection — a step that changes the world or records a succeeded action is@@ -121,15 +150,15 @@ public struct GenericHarnessRuntime: Sendable {}if noProgressStreak >= maxNoProgressSteps {await failSafeStall(taskID: taskID, reason: "noProgress")- break+ if await coordinator.endRunUnlessPending(taskID: taskID) { break loop } else { continue loop }}if identicalNoProgressStreak + 1 >= maxIdenticalRepeats {await failSafeStall(taskID: taskID, reason: "stuckRepeatingCall")- break+ if await coordinator.endRunUnlessPending(taskID: taskID) { break loop } else { continue loop }}if let reason = Self.repeatedFailureStallReason(after: step, threshold: maxRepeatedFailures) {await failSafeStall(taskID: taskID, reason: reason)- break+ if await coordinator.endRunUnlessPending(taskID: taskID) { break loop } else { continue loop }}}lastCallSignature = signature@@ -543,6 +572,6 @@ public struct GenericHarnessRuntime: Sendable {when status: HarnessTaskStatus) -> Bool {guard call.name == "run.resume" else { return false }- return [.paused, .interrupted].contains(status)+ return [.paused, .interrupted, .timedOut].contains(status)}}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessThreadStore.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessThreadStore.swiftindex 3f6ae4ab..a64f7ddb 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessThreadStore.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessThreadStore.swift@@ -276,7 +276,7 @@ public actor InMemoryHarnessThreadStore: HarnessThreadStoring {}private static func isActiveTask(_ task: HarnessTaskState) -> Bool {- [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming].contains(task.status)+ [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming, .timedOut].contains(task.status)}private func updateActiveTaskIDs(for task: HarnessTaskState) {@@ -451,7 +451,7 @@ public actor FileHarnessThreadStore: HarnessThreadStoring {}private static func isActiveTask(_ task: HarnessTaskState) -> Bool {- [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming].contains(task.status)+ [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming, .timedOut].contains(task.status)}private func updateActiveTaskIDs(for task: HarnessTaskState) {@@ -654,7 +654,7 @@ public struct HarnessThreadCompactor: Sendable {) -> [HarnessTaskState] {let selected = tasks.filter { task inguard policy.preserveWaitingState else { return true }- return [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming].contains(task.status)+ return [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming, .timedOut].contains(task.status)}records.append(AppHarnessContextCompactionRecord(diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swiftindex 92cfd170..8d622c51 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift@@ -234,12 +234,14 @@ public struct AppHarnessGenericLifecycle: Sendable {response: response)} else if context.turn?.isFollowUp == true {- _ = await coordinator.interrupt(- taskID: taskID,- newGoal: goal,- turn: context.turn,- reason: "User query follow-up changed course"- )+ // A follow-up to a task whose loop already stopped (a live loop picks the message up directly+ // and never reaches here): queue the instruction so the resumed loop folds it in, and resume.+ // The original goal is preserved — the follow-up amends the work rather than replacing it,+ // the deliberate opposite of the old interrupt-and-restart behavior.+ if let followUpText = context.turn?.text,+ !followUpText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ _ = await coordinator.enqueueUserMessage(taskID: taskID, text: followUpText)+ }_ = await coordinator.resume(taskID: taskID,reason: "User query follow-up resumed task"diff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swiftindex 6ad2213a..5f4cdadc 100644--- a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift@@ -309,7 +309,7 @@ public struct UserQueryNotchStatusView: View {if layout.chinHeight > 0, let speaker {Text(speaker.detail.isEmpty ? speaker.title : speaker.detail)- .font(.system(size: 9, weight: .regular))+ .font(.system(size: 13, weight: .regular)).foregroundStyle(Color.white.opacity(0.72)).lineLimit(1).truncationMode(.tail)@@ -685,24 +685,43 @@ public struct UserQueryNotchStatusView: View {NotchControlButton(systemName: "stop.fill", label: "Stop", isEnabled: true) {pauseRequested(task.id)}- case .paused, .interrupted:- HStack(spacing: 6) {- NotchControlButton(systemName: "play.fill", label: "Resume", isEnabled: true) {- resumeRequested(task.id)- }- NotchControlButton(systemName: "xmark", label: "Close", isEnabled: true) {- dismissRequested(task.id)- }+ case .paused, .interrupted, .timedOut:+ // Paused (user), interrupted (changed course), and timed out (hit the step ceiling) all carry a+ // goal and real progress, so they are retryable: offer Resume + Close.+ resumeAndCloseControls(for: task)+ case .needsAttention:+ // A run cut short by a relaunch is retryable; but an info-only needsAttention row (e.g. an+ // asset drop) has no goal to resume, so it only gets Close — Resume there would dead-end.+ if task.commandText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ closeControl(for: task)+ } else {+ resumeAndCloseControls(for: task)}default:// Completed, failed, chatting, and the waiting states (e.g. a clarifying question) are all// dismissable straight from the row instead of showing a non-actionable status glyph.+ closeControl(for: task)+ }+ }++ @ViewBuilder+ private func resumeAndCloseControls(for task: UserQueryNotchTask) -> some View {+ HStack(spacing: 6) {+ NotchControlButton(systemName: "play.fill", label: "Resume", isEnabled: true) {+ resumeRequested(task.id)+ }NotchControlButton(systemName: "xmark", label: "Close", isEnabled: true) {dismissRequested(task.id)}}}+ private func closeControl(for task: UserQueryNotchTask) -> some View {+ NotchControlButton(systemName: "xmark", label: "Close", isEnabled: true) {+ dismissRequested(task.id)+ }+ }+/// Live ticking time while running; a frozen total once the task has stopped or finished. Both use/// the prototype's row time style (10px, 55% white) so every row's time matches regardless of status.@ViewBuilder@@ -927,10 +946,11 @@ public struct UserQueryNotchStatusView: View {slotIcon("shield")case .running:compactLiveTime(since: task.createdAt)- case .completed, .paused, .interrupted, .failed, .chatting, .needsAttention:+ case .completed, .paused, .interrupted, .failed, .chatting, .needsAttention, .timedOut:// The gutter only ever carries the waiting-on-user icons or the live clock — a completed// task keeps surfacing as a colored pointer + chin line, and the rest (including a benign- // needsAttention) surface in the list without nagging the collapsed gutter.+ // needsAttention or a retryable timed-out run) surface in the list without nagging the+ // collapsed gutter.EmptyView()}} else if updateState.isActionable {