Open source CapCut alternative.
TypeScript
feat(app): rename Task to Conversation and surface tool setup as a system conversation
David Le04e00cb2b392
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex 176f5ece..8a4d96b0 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -32,13 +32,6 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {return}- // Kick off the first-run download of the bundled CLI tools (ffmpeg/yt-dlp/...) in the background,- // so a later media task runs them by bare name instead of hunting for Homebrew. Non-blocking and a- // no-op once the current version is installed or when nothing is published yet.- Task.detached(priority: .utility) {- await BundledToolsInstaller.shared.installIfNeeded()- }-let authCoordinator = DonkeyAuthCoordinator()self.authCoordinator = authCoordinator// Seed the process-wide session gate before any surface is built, so the warm cache, Live@@ -172,6 +165,13 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {overlayController = controllercontroller.show()+ // Now that the notch surface is live, kick off the first-run download of the bundled CLI tools+ // (ffmpeg/yt-dlp/...). It surfaces as a system-driven conversation the user can watch but not stop,+ // and no-ops once the current version is installed or when nothing is published — so this is cheap+ // to call on every launch and re-sign-in. Tools are only used by agent tasks (which need sign-in),+ // so downloading once the authenticated notch is up — rather than before login — is the right time.+ model.startSystemToolsSetupIfNeeded()+// Run as a regular app so Donkey keeps a Dock icon and its menu bar (including Sign Out)// while the overlay surfaces are live, instead of receding into an accessory agent.NSApp.setActivationPolicy(.regular)diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 01958c3c..21006ebb 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -84,7 +84,7 @@ struct UserQueryCommandHandlingResult: Equatable, Sendable {var threadStatus: UserQueryConversationStatusvar decision: AppHarnessDecisionvar summary: String- var taskLabel: String?+ var conversationLabel: String?var traceID: Stringvar metadata: [String: String]var agentVisualizationPlan: AgentVisualizationPlan?@@ -97,7 +97,7 @@ struct UserQueryCommandHandlingResult: Equatable, Sendable {summary: String,traceID: String,metadata: [String: String],- taskLabel: String? = nil,+ conversationLabel: String? = nil,agentVisualizationPlan: AgentVisualizationPlan? = nil,cursorOverlayRequest: PointerCoachCursorGuideRequest? = nil) {@@ -105,7 +105,7 @@ struct UserQueryCommandHandlingResult: Equatable, Sendable {self.threadStatus = threadStatusself.decision = decisionself.summary = summary- self.taskLabel = taskLabel+ self.conversationLabel = conversationLabelself.traceID = traceIDself.metadata = metadataself.agentVisualizationPlan = agentVisualizationPlan@@ -114,7 +114,7 @@ struct UserQueryCommandHandlingResult: Equatable, Sendable {}struct UserQueryCommandContext: Sendable {- var task: UserQueryConversation+ var conversation: UserQueryConversationvar recentEvents: [UserQueryConversationEvent]var assets: [UserQueryConversationAsset]var isFollowUp: Bool@@ -215,7 +215,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// warm caches start (and stay) warm around this turn instead of only firing while idle.DonkeyEngagement.shared.noteInteraction()let traceID = "user-query-\(UUID().uuidString)"- let conversationID = context?.task.id ?? traceID+ let conversationID = context?.conversation.id ?? traceIDlogSubmittedCommand(command, traceID: traceID, conversationID: conversationID, context: context)return await continueHandlingNonVisualizationCommand(command: command,@@ -238,7 +238,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {let harnessRequest = Self.harnessRequest(command: redactedCommand, context: context)let genericPreparedTurn = await genericHarnessLifecycle.prepareUserQueryTurn(request: harnessRequest,- pointerTask: context?.task,+ pointerTask: context?.conversation,traceID: traceID,availableToolNames: Self.genericHarnessToolNames(),grantedPermissions: Self.userQueryGrantedPermissions@@ -699,6 +699,12 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// request that lives in a window the user isn't looking at can be found and switched to. Donkey's// own windows are filtered out by bundle id so the agent never targets its own overlay.let ownBundleID = Bundle.main.bundleIdentifier+ // Recall durable operating lessons distilled from earlier runs with a related goal, so a trap the+ // agent already hit once (a broad search that timed out, a wrong tool) steers this run from its+ // first step. Computed once here against the restated goal; nil when nothing relevant was learned.+ let restatedGoal = understanding?.restatedGoal+ let lessonGoal = (restatedGoal?.isEmpty == false ? restatedGoal : nil) ?? command+ let recalledLessons = RunLessonMemory.recall(forGoal: lessonGoal, store: .shared)let planner = HostedHarnessStepPlanner(backend: backend,descriptors: plannerDescriptors,@@ -706,6 +712,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {appGuidance: appGuidance,understanding: understanding,skillCatalog: Self.installedSkillCatalog(),+ recalledLessons: recalledLessons,trace: trace,openWindows: {MacWindowResolver().enumerateCandidates().filter { candidate in@@ -909,6 +916,41 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {}}+ // Self-improving loop: distill this run into one durable, general operating lesson and store it,+ // so a future turn with a related goal recalls it (see the recall at planner construction above)+ // and avoids a trap this run already paid for. Reuses the agent-memory approval + persistence+ // path. Gated to runs that plausibly taught something — a non-clean outcome, or a run long enough+ // to have taken a wrong turn — so a short clean success doesn't spend a model call to learn+ // nothing. Detached so it never delays the user-facing result.+ let shouldDistillLesson = outcomeReason != "ok" || turns >= 4+ if shouldDistillLesson, !threadText.isEmpty {+ Task.detached {+ let prompt = DonkeyPrompts.runLessonDistillation(+ goal: lessonGoal, outcome: outcomeReason, thread: threadText+ )+ let lessonStartedAt = RunTraceTimestamp.now()+ let raw = await textGenerator.generate(prompt) ?? ""+ trace.recordModelCall(TraceModelCall(+ kind: .lessonDistillation,+ prompt: prompt,+ response: raw.isEmpty ? "<no output>" : raw,+ status: raw.isEmpty ? .empty : .ok,+ startedAt: lessonStartedAt,+ endedAt: .now()+ ))+ guard let distillation = RunLessonMemory.parse(raw),+ let proposal = RunLessonMemory.proposal(+ for: distillation,+ goal: lessonGoal,+ outcome: outcomeReason,+ traceID: traceID,+ now: .now()+ )+ else { return }+ _ = try? SQLiteAgentMemoryStore.shared?.appendApprovedProposal(proposal, decidedAt: .now())+ }+ }+let baseMetadata = preparedTurnMetadata.merging(["appHarness.router": "harness","harness.app": appName,@@ -989,9 +1031,25 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {let conversationMessage = finalTask?.toolHistory.last { $0.call.name == "conversation.respond" }.flatMap { $0.call.input["response"] ?? $0.call.input["message"] }.flatMap { $0.isEmpty ? nil : $0 }- var response = conversationMessage- ?? planner.lastNarration- ?? (completed ? "Done." : "I tried operating \(appName) but couldn't confirm the goal was finished.")+ var response: String+ if let conversationMessage {+ response = conversationMessage+ } else if completed {+ response = planner.lastNarration ?? "Done."+ } else {+ // The run did not complete. Echoing `planner.lastNarration` here surfaces the last+ // forward-looking "I will…" line, which reads as a silent stop — the exact "it didn't tell me+ // why" failure. Explain what actually went wrong, in plain language, from the real step errors.+ var explained: String?+ if let prompt = Self.failureExplanationPrompt(goal: command, steps: runSteps) {+ let generated = await textGenerator.generate(prompt)?+ .trimmingCharacters(in: .whitespacesAndNewlines)+ if let generated, !generated.isEmpty { explained = generated }+ }+ response = explained+ ?? planner.lastNarration+ ?? "I tried operating \(appName) but couldn't confirm the goal was finished."+ }// Stream the assistant's final reply token-by-token into the notch (the chin and the open task// row) whenever the turn produced a real text answer. It is re-composed from the harness's drafted@@ -1055,6 +1113,30 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {return result}+ /// Build the prompt that turns a not-completed run's real step errors — which for yt-dlp/ffmpeg are+ /// buried under page-long signed URLs — into a one-or-two-sentence plain-language "why" for the user.+ /// Pure and Sendable; the caller runs the model inline so the misleading forward-looking narration the+ /// notch showed before is replaced by an actual explanation. Returns nil when no step failed.+ static func failureExplanationPrompt(goal: String, steps: [HarnessStepExecutionResult]) -> String? {+ let failures = steps.compactMap { step -> String? in+ guard let result = step.toolResult,+ result.status == .failed || result.status == .invalidInput,+ !result.summary.isEmpty else { return nil }+ let oneLine = result.summary.replacingOccurrences(of: "\n", with: " ")+ return "- \(result.toolName): \(String(oneLine.prefix(300)))"+ }+ guard !failures.isEmpty else { return nil }+ return """+ A macOS task did not finish. In ONE or TWO plain sentences, tell the user what was attempted and \+ why it did not finish, then the single most likely next step. Be concrete but human: no URLs, no \+ file paths, no code, no stack traces, no apology filler.++ GOAL: \(goal)+ ERRORS (most recent last):+ \(failures.suffix(4).joined(separator: "\n"))+ """+ }+/// The conversational arm of the two-tier split: a turn typed `.converse` is answered here, with no/// action loop, no tools, no world model, and no permission gate. The reply streams into the notch/// chin token-by-token and the turn completes as a chat message. Because this path is reached only on@@ -1251,9 +1333,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {) {guard UserQueryLog.isEnabled else { return }- let taskLabel = result.taskLabel ?? ""+ let conversationLabel = result.conversationLabel ?? ""UserQueryLog.commands.notice(- "command finished traceID=\(result.traceID, privacy: .public) stage=\(stage, privacy: .public) status=\(result.status.rawValue, privacy: .public) threadStatus=\(result.threadStatus.rawValue, privacy: .public) summary=\(result.summary, privacy: .public) taskLabel=\(taskLabel, privacy: .public) hint=\(hint, privacy: .public)"+ "command finished traceID=\(result.traceID, privacy: .public) stage=\(stage, privacy: .public) status=\(result.status.rawValue, privacy: .public) threadStatus=\(result.threadStatus.rawValue, privacy: .public) summary=\(result.summary, privacy: .public) conversationLabel=\(conversationLabel, privacy: .public) hint=\(hint, privacy: .public)")}@@ -1472,7 +1554,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {turn: AppHarnessTurn(text: command,source: context?.isFollowUp == true ? .followUp : context?.turnSource ?? .typedPrompt,- conversationID: context?.task.id,+ conversationID: context?.conversation.id,isFollowUp: context?.isFollowUp ?? false),recentEvents: context?.recentEvents ?? [],diff --git a/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swift b/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swiftindex 3cc7e5bc..d338fc98 100644--- a/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swift@@ -4,10 +4,10 @@ import Foundation@MainActorprotocol UserQueryConversationStoring {- func loadRecentTasks(limit: Int) -> [UserQueryConversation]- func searchTasks(matching query: String, limit: Int) -> [UserQueryConversation]- func upsertTask(_ task: UserQueryConversation)- func deleteTask(id: String)+ func loadRecentConversations(limit: Int) -> [UserQueryConversation]+ func searchConversations(matching query: String, limit: Int) -> [UserQueryConversation]+ func upsertConversation(_ conversation: UserQueryConversation)+ func deleteConversation(id: String)func loadEvents(conversationID: String) -> [UserQueryConversationEvent]func appendEvent(_ event: UserQueryConversationEvent)func loadAssets(conversationID: String) -> [UserQueryConversationAsset]@@ -24,90 +24,91 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {context = Self.makeContext(storeURL: storeURL ?? Self.defaultStoreURL())}- func loadRecentTasks(limit: Int) -> [UserQueryConversation] {+ func loadRecentConversations(limit: Int) -> [UserQueryConversation] {guard let context else {return []}- let request = NSFetchRequest<NSManagedObject>(entityName: Self.taskEntityName)+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.conversationEntityName)request.fetchLimit = limitrequest.sortDescriptors = [NSSortDescriptor(key: Self.updatedAtKey, ascending: false)]- guard let managedTasks = try? context.fetch(request) else {+ guard let managedConversations = try? context.fetch(request) else {return []}- return managedTasks.compactMap(Self.task(from:))+ return managedConversations.compactMap(Self.conversation(from:))}- func searchTasks(matching query: String, limit: Int) -> [UserQueryConversation] {+ func searchConversations(matching query: String, limit: Int) -> [UserQueryConversation] {guard let context else {return []}let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)guard !trimmedQuery.isEmpty else {- return loadRecentTasks(limit: limit)+ return loadRecentConversations(limit: limit)}- let matchingEventTaskIDs = conversationIDsWithMatchingEvents(trimmedQuery)- let matchingAssetTaskIDs = conversationIDsWithMatchingAssets(trimmedQuery)- let request = NSFetchRequest<NSManagedObject>(entityName: Self.taskEntityName)+ let matchingEventConversationIDs = conversationIDsWithMatchingEvents(trimmedQuery)+ let matchingAssetConversationIDs = conversationIDsWithMatchingAssets(trimmedQuery)+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.conversationEntityName)request.fetchLimit = limitvar predicates = [NSPredicate(format: "%K CONTAINS[cd] %@", Self.titleKey, trimmedQuery),NSPredicate(format: "%K CONTAINS[cd] %@", Self.detailKey, trimmedQuery),NSPredicate(format: "%K CONTAINS[cd] %@", Self.commandTextKey, trimmedQuery)]- if !matchingEventTaskIDs.isEmpty {- predicates.append(NSPredicate(format: "%K IN %@", Self.idKey, matchingEventTaskIDs))+ if !matchingEventConversationIDs.isEmpty {+ predicates.append(NSPredicate(format: "%K IN %@", Self.idKey, matchingEventConversationIDs))}- if !matchingAssetTaskIDs.isEmpty {- predicates.append(NSPredicate(format: "%K IN %@", Self.idKey, matchingAssetTaskIDs))+ if !matchingAssetConversationIDs.isEmpty {+ predicates.append(NSPredicate(format: "%K IN %@", Self.idKey, matchingAssetConversationIDs))}request.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)request.sortDescriptors = [NSSortDescriptor(key: Self.updatedAtKey, ascending: false)]- guard let managedTasks = try? context.fetch(request) else {+ guard let managedConversations = try? context.fetch(request) else {return []}- return managedTasks.compactMap(Self.task(from:))+ return managedConversations.compactMap(Self.conversation(from:))}- func upsertTask(_ task: UserQueryConversation) {+ func upsertConversation(_ conversation: UserQueryConversation) {guard let context else { return }- let managedTask = Self.existingTask(id: task.id, in: context)+ let managedConversation = Self.existingConversation(id: conversation.id, in: context)?? NSManagedObject(entity: Self.entityDescription(in: context), insertInto: context)- managedTask.setValue(task.id, forKey: Self.idKey)- managedTask.setValue(task.title, forKey: Self.titleKey)- managedTask.setValue(task.detail, forKey: Self.detailKey)- managedTask.setValue(task.commandText, forKey: Self.commandTextKey)- managedTask.setValue(task.status.rawValue, forKey: Self.statusKey)- managedTask.setValue(Int64(task.accentIndex), forKey: Self.accentIndexKey)- managedTask.setValue(task.createdAt, forKey: Self.createdAtKey)- managedTask.setValue(task.updatedAt, forKey: Self.updatedAtKey)- managedTask.setValue(Self.metadataJSONString(task.metadata), forKey: Self.metadataJSONKey)+ managedConversation.setValue(conversation.id, forKey: Self.idKey)+ managedConversation.setValue(conversation.title, forKey: Self.titleKey)+ managedConversation.setValue(conversation.detail, forKey: Self.detailKey)+ managedConversation.setValue(conversation.commandText, forKey: Self.commandTextKey)+ managedConversation.setValue(conversation.status.rawValue, forKey: Self.statusKey)+ managedConversation.setValue(Int64(conversation.accentIndex), forKey: Self.accentIndexKey)+ managedConversation.setValue(conversation.origin.rawValue, forKey: Self.originKey)+ managedConversation.setValue(conversation.createdAt, forKey: Self.createdAtKey)+ managedConversation.setValue(conversation.updatedAt, forKey: Self.updatedAtKey)+ managedConversation.setValue(Self.metadataJSONString(conversation.metadata), forKey: Self.metadataJSONKey)try? context.save()}- /// Permanently removes a task and everything attached to it — its row plus all- /// stored events and assets — so a dismissed task does not reappear on relaunch.- func deleteTask(id: String) {+ /// Permanently removes a conversation and everything attached to it — its row plus all+ /// stored events and assets — so a dismissed conversation does not reappear on relaunch.+ func deleteConversation(id: String) {guard let context else { return }- if let managedTask = Self.existingTask(id: id, in: context) {- context.delete(managedTask)+ if let managedConversation = Self.existingConversation(id: id, in: context) {+ context.delete(managedConversation)}- Self.deleteRows(entityName: Self.eventEntityName, conversationIDKey: Self.eventTaskIDKey, conversationID: id, in: context)- Self.deleteRows(entityName: Self.assetEntityName, conversationIDKey: Self.assetTaskIDKey, conversationID: id, in: context)+ Self.deleteRows(entityName: Self.eventEntityName, conversationIDKey: Self.eventConversationIDKey, conversationID: id, in: context)+ Self.deleteRows(entityName: Self.assetEntityName, conversationIDKey: Self.assetConversationIDKey, conversationID: id, in: context)try? context.save()}@@ -116,7 +117,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {guard let context else { return [] }let request = NSFetchRequest<NSManagedObject>(entityName: Self.assetEntityName)- request.predicate = NSPredicate(format: "%K == %@", Self.assetTaskIDKey, conversationID)+ request.predicate = NSPredicate(format: "%K == %@", Self.assetConversationIDKey, conversationID)request.sortDescriptors = [NSSortDescriptor(key: Self.assetCreatedAtKey, ascending: true)]@@ -136,7 +137,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {insertInto: context)managedAsset.setValue(asset.id, forKey: Self.assetIDKey)- managedAsset.setValue(asset.conversationID, forKey: Self.assetTaskIDKey)+ managedAsset.setValue(asset.conversationID, forKey: Self.assetConversationIDKey)managedAsset.setValue(asset.eventID, forKey: Self.assetEventIDKey)managedAsset.setValue(asset.source.rawValue, forKey: Self.assetSourceKey)managedAsset.setValue(asset.displayName, forKey: Self.assetDisplayNameKey)@@ -152,7 +153,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {guard let context else { return [] }let request = NSFetchRequest<NSManagedObject>(entityName: Self.eventEntityName)- request.predicate = NSPredicate(format: "%K == %@", Self.eventTaskIDKey, conversationID)+ request.predicate = NSPredicate(format: "%K == %@", Self.eventConversationIDKey, conversationID)request.sortDescriptors = [NSSortDescriptor(key: Self.eventSequenceKey, ascending: true),NSSortDescriptor(key: Self.eventCreatedAtKey, ascending: true)@@ -173,7 +174,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {insertInto: context)managedEvent.setValue(event.id, forKey: Self.eventIDKey)- managedEvent.setValue(event.conversationID, forKey: Self.eventTaskIDKey)+ managedEvent.setValue(event.conversationID, forKey: Self.eventConversationIDKey)managedEvent.setValue(event.role.rawValue, forKey: Self.eventRoleKey)managedEvent.setValue(event.text, forKey: Self.eventTextKey)managedEvent.setValue(Int64(event.sequence), forKey: Self.eventSequenceKey)@@ -216,28 +217,31 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {private static func model() -> NSManagedObjectModel {let model = NSManagedObjectModel()- let taskEntity = NSEntityDescription()- taskEntity.name = taskEntityName- taskEntity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)- taskEntity.properties = [+ let conversationEntity = NSEntityDescription()+ conversationEntity.name = conversationEntityName+ conversationEntity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)+ conversationEntity.properties = [attribute(idKey, type: .stringAttributeType, isOptional: false),attribute(titleKey, type: .stringAttributeType, isOptional: false),attribute(detailKey, type: .stringAttributeType, isOptional: false),attribute(commandTextKey, type: .stringAttributeType, isOptional: true),attribute(statusKey, type: .stringAttributeType, isOptional: false),attribute(accentIndexKey, type: .integer64AttributeType, isOptional: false),+ // Optional so lightweight migration can add it to stores written before origin existed; a+ // null on an old row decodes to `.user` below.+ attribute(originKey, type: .stringAttributeType, isOptional: true),attribute(createdAtKey, type: .dateAttributeType, isOptional: false),attribute(updatedAtKey, type: .dateAttributeType, isOptional: false),attribute(metadataJSONKey, type: .stringAttributeType, isOptional: true)]- taskEntity.uniquenessConstraints = [[idKey]]+ conversationEntity.uniquenessConstraints = [[idKey]]let eventEntity = NSEntityDescription()eventEntity.name = eventEntityNameeventEntity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)eventEntity.properties = [attribute(eventIDKey, type: .stringAttributeType, isOptional: false),- attribute(eventTaskIDKey, type: .stringAttributeType, isOptional: false),+ attribute(eventConversationIDKey, type: .stringAttributeType, isOptional: false),attribute(eventRoleKey, type: .stringAttributeType, isOptional: false),attribute(eventTextKey, type: .stringAttributeType, isOptional: false),attribute(eventSequenceKey, type: .integer64AttributeType, isOptional: false),@@ -250,7 +254,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {assetEntity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)assetEntity.properties = [attribute(assetIDKey, type: .stringAttributeType, isOptional: false),- attribute(assetTaskIDKey, type: .stringAttributeType, isOptional: false),+ attribute(assetConversationIDKey, type: .stringAttributeType, isOptional: false),attribute(assetEventIDKey, type: .stringAttributeType, isOptional: true),attribute(assetSourceKey, type: .stringAttributeType, isOptional: false),attribute(assetDisplayNameKey, type: .stringAttributeType, isOptional: false),@@ -261,7 +265,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {]assetEntity.uniquenessConstraints = [[assetIDKey]]- model.entities = [taskEntity, eventEntity, assetEntity]+ model.entities = [conversationEntity, eventEntity, assetEntity]return model}@@ -278,7 +282,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {}private static func entityDescription(in context: NSManagedObjectContext) -> NSEntityDescription {- NSEntityDescription.entity(forEntityName: taskEntityName, in: context)!+ NSEntityDescription.entity(forEntityName: conversationEntityName, in: context)!}private static func eventEntityDescription(in context: NSManagedObjectContext) -> NSEntityDescription {@@ -303,8 +307,8 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {}}- private static func existingTask(id: String, in context: NSManagedObjectContext) -> NSManagedObject? {- let request = NSFetchRequest<NSManagedObject>(entityName: taskEntityName)+ private static func existingConversation(id: String, in context: NSManagedObjectContext) -> NSManagedObject? {+ let request = NSFetchRequest<NSManagedObject>(entityName: conversationEntityName)request.fetchLimit = 1request.predicate = NSPredicate(format: "%K == %@", idKey, id)return try? context.fetch(request).first@@ -320,7 +324,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {return []}- return Array(Set(managedEvents.compactMap { $0.value(forKey: Self.eventTaskIDKey) as? String }))+ return Array(Set(managedEvents.compactMap { $0.value(forKey: Self.eventConversationIDKey) as? String }))}private func conversationIDsWithMatchingAssets(_ query: String) -> [String] {@@ -337,31 +341,34 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {return []}- return Array(Set(managedAssets.compactMap { $0.value(forKey: Self.assetTaskIDKey) as? String }))+ return Array(Set(managedAssets.compactMap { $0.value(forKey: Self.assetConversationIDKey) as? String }))}- private static func task(from managedTask: NSManagedObject) -> UserQueryConversation? {- guard let id = managedTask.value(forKey: idKey) as? String,- let title = managedTask.value(forKey: titleKey) as? String,- let detail = managedTask.value(forKey: detailKey) as? String,- let rawStatus = managedTask.value(forKey: statusKey) as? String,+ private static func conversation(from managedConversation: NSManagedObject) -> UserQueryConversation? {+ guard let id = managedConversation.value(forKey: idKey) as? String,+ let title = managedConversation.value(forKey: titleKey) as? String,+ let detail = managedConversation.value(forKey: detailKey) as? String,+ let rawStatus = managedConversation.value(forKey: statusKey) as? String,let status = UserQueryConversationStatus(rawValue: rawStatus),- let createdAt = managedTask.value(forKey: createdAtKey) as? Date,- let updatedAt = managedTask.value(forKey: updatedAtKey) as? Date else {+ let createdAt = managedConversation.value(forKey: createdAtKey) as? Date,+ let updatedAt = managedConversation.value(forKey: updatedAtKey) as? Date else {return nil}- let accentIndex = (managedTask.value(forKey: accentIndexKey) as? NSNumber)?.intValue ?? 0+ let accentIndex = (managedConversation.value(forKey: accentIndexKey) as? NSNumber)?.intValue ?? 0+ let origin = (managedConversation.value(forKey: originKey) as? String)+ .flatMap(UserQueryConversationOrigin.init(rawValue:)) ?? .userreturn UserQueryConversation(id: id,title: title,detail: detail,- commandText: managedTask.value(forKey: commandTextKey) as? String ?? title,+ commandText: managedConversation.value(forKey: commandTextKey) as? String ?? title,status: status,accentIndex: accentIndex,+ origin: origin,createdAt: createdAt,updatedAt: updatedAt,- metadata: metadata(fromJSONString: managedTask.value(forKey: metadataJSONKey) as? String)+ metadata: metadata(fromJSONString: managedConversation.value(forKey: metadataJSONKey) as? String))}@@ -386,7 +393,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {private static func event(from managedEvent: NSManagedObject) -> UserQueryConversationEvent? {guard let id = managedEvent.value(forKey: eventIDKey) as? String,- let conversationID = managedEvent.value(forKey: eventTaskIDKey) as? String,+ let conversationID = managedEvent.value(forKey: eventConversationIDKey) as? String,let rawRole = managedEvent.value(forKey: eventRoleKey) as? String,let role = UserQueryConversationEventRole(rawValue: rawRole),let text = managedEvent.value(forKey: eventTextKey) as? String,@@ -407,7 +414,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {private static func asset(from managedAsset: NSManagedObject) -> UserQueryConversationAsset? {guard let id = managedAsset.value(forKey: assetIDKey) as? String,- let conversationID = managedAsset.value(forKey: assetTaskIDKey) as? String,+ let conversationID = managedAsset.value(forKey: assetConversationIDKey) as? String,let rawSource = managedAsset.value(forKey: assetSourceKey) as? String,let source = UserQueryConversationAssetSource(rawValue: rawSource),let displayName = managedAsset.value(forKey: assetDisplayNameKey) as? String,@@ -430,7 +437,7 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {)}- private static let taskEntityName = "UserQueryStoredConversation"+ private static let conversationEntityName = "UserQueryStoredConversation"private static let eventEntityName = "UserQueryStoredConversationEvent"private static let assetEntityName = "UserQueryStoredConversationAsset"private static let idKey = "id"@@ -439,17 +446,18 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {private static let commandTextKey = "commandText"private static let statusKey = "status"private static let accentIndexKey = "accentIndex"+ private static let originKey = "origin"private static let createdAtKey = "createdAt"private static let updatedAtKey = "updatedAt"private static let metadataJSONKey = "metadataJSON"private static let eventIDKey = "id"- private static let eventTaskIDKey = "conversationID"+ private static let eventConversationIDKey = "conversationID"private static let eventRoleKey = "role"private static let eventTextKey = "text"private static let eventSequenceKey = "sequence"private static let eventCreatedAtKey = "createdAt"private static let assetIDKey = "id"- private static let assetTaskIDKey = "conversationID"+ private static let assetConversationIDKey = "conversationID"private static let assetEventIDKey = "eventID"private static let assetSourceKey = "source"private static let assetDisplayNameKey = "displayName"diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swiftindex e846b484..705f2a1b 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift@@ -630,18 +630,18 @@ final class UserQueryOverlayController {surfaceSize: metrics.surfaceSize,isExpanded: isStatusExpanded,isHostExpanded: isStatusHostExpanded,- isCurrentTaskPaused: model.isCurrentTaskPaused,+ isCurrentConversationPaused: model.isCurrentConversationPaused,notchCommandText: model.notchCommandText,notchCommandInputTextHeight: model.notchCommandInputTextHeight,isNotchCommandInputExpanded: model.isNotchCommandInputExpanded,- notchTasks: model.notchTasks,- notchSurfacedTasks: model.notchSurfacedTasks,+ notchConversations: model.notchConversations,+ notchSurfacedConversations: model.notchSurfacedConversations,accentIndex: model.notchAccentIndex,spawnState: spawnCue,spawnStates: model.spawnStates,selectedSpawnID: model.selectedSpawnID,- replyTargetTaskID: model.replyTargetTaskID,- selectedTaskID: model.selectedTaskID,+ replyTargetConversationID: model.replyTargetConversationID,+ selectedConversationID: model.selectedConversationID,needsLogin: model.needsLogin)}@@ -656,7 +656,7 @@ final class UserQueryOverlayController {surfaceHeight: metrics.surfaceSize.height,isHostExpanded: isStatusHostExpanded,isExpanded: isStatusExpanded,- isCurrentConversationPaused: model.isCurrentTaskPaused,+ isCurrentConversationPaused: model.isCurrentConversationPaused,commandText: Binding(get: { [weak self] inself?.model.notchCommandText ?? ""@@ -667,10 +667,10 @@ final class UserQueryOverlayController {),commandInputTextHeight: model.notchCommandInputTextHeight,isCommandInputExpanded: model.isNotchCommandInputExpanded,- conversations: model.notchTasks,- surfacedConversations: model.notchSurfacedTasks,- replyTargetConversationID: model.replyTargetTaskID,- selectedConversationID: model.selectedTaskID,+ conversations: model.notchConversations,+ surfacedConversations: model.notchSurfacedConversations,+ replyTargetConversationID: model.replyTargetConversationID,+ selectedConversationID: model.selectedConversationID,accentIndex: model.notchAccentIndex,spawnState: spawnCue,commandSubmitted: { [weak self] text in@@ -692,10 +692,10 @@ final class UserQueryOverlayController {self?.model.resumeAgent(id: conversationID)},dismissRequested: { [weak self] conversationID in- self?.model.dismissTask(id: conversationID)+ self?.model.dismissConversation(id: conversationID)},conversationSelected: { [weak self] conversationID in- self?.restoreSpawnPointer(forTaskID: conversationID)+ self?.restoreSpawnPointer(forConversationID: conversationID)},replyRequested: { [weak self] conversationID inguard let self else { return }@@ -747,9 +747,9 @@ final class UserQueryOverlayController {model.showUpdateUI()}- /// Brings back a pointer the user dismissed when its task is clicked in+ /// Brings back a pointer the user dismissed when its conversation is clicked in/// the notch; the surface re-emerges and travels to its target again.- private func restoreSpawnPointer(forTaskID conversationID: String) {+ private func restoreSpawnPointer(forConversationID conversationID: String) {guard let spawnID = model.spawnStates.first(where: { $0.conversationID == conversationID })?.id else {return}@@ -867,9 +867,9 @@ final class UserQueryOverlayController {statusHoverPhase = .expandedisStatusHostExpanded = trueisStatusExpanded = true- // Opening the notch dismisses the surfaced terminal tasks (completed pointers and any held+ // Opening the notch dismisses the surfaced terminal conversations (completed pointers and any held// error chin) piled up in the collapsed surface.- model.acknowledgeSurfacedTasks()+ model.acknowledgeSurfacedConversations()updateStatusPanelView()focusStatusComposerTextInputIfAvailable()return@@ -1002,7 +1002,7 @@ final class UserQueryOverlayController {// The chin band has to know its height before the surface frame is built, but that height// depends on the collapsed width (how wide the chin text can wrap). Resolve the width from a- // zero-chin probe first, then size the band to the surfaced tasks' wrapped line count.+ // zero-chin probe first, then size the band to the surfaced conversations' wrapped line count.let widthProbe = NotchMetrics(voidWidth: voidWidth,voidHeight: voidHeight,@@ -1033,9 +1033,9 @@ final class UserQueryOverlayController {}/// On a no-notch display the collapsed line renders inline in the top row (a real notch routes it into- /// the chin band instead). It shows the same rotating surfaced-task line the chin does, so size the+ /// the chin band instead). It shows the same rotating surfaced-conversation line the chin does, so size the/// pill to the tallest line that can rotate through — the max wrapped-line count across the surfaced- /// tasks, or the headline fallback when nothing is surfaced — and grow by one line-height when that is+ /// conversations, or the headline fallback when nothing is surfaced — and grow by one line-height when that is/// two lines. The text width subtracts the pill's pointer lane and gutter, measured narrow so the/// prediction never under-counts and clips. A real notch returns 0 — its second line lives in/// `statusChinHeight`.@@ -1043,30 +1043,30 @@ final class UserQueryOverlayController {guard !hasNotch else { return 0 }let textWidth = collapsedWidth - Self.statusCollapsedTopRowHorizontalReservelet headline = UserQueryNotchStatusView.collapsedHeadline(- conversations: model.notchTasks,+ conversations: model.notchConversations,state: model.promptState)- let lines = model.notchSurfacedTasks.reduce(+ let lines = model.notchSurfacedConversations.reduce(Self.chinLineCount(for: headline, width: textWidth)- ) { partial, task in- max(partial, Self.chinLineCount(for: task.chinDisplayText, width: textWidth))+ ) { partial, conversation in+ max(partial, Self.chinLineCount(for: conversation.chinDisplayText, width: textWidth))}return lines >= 2 ? Self.statusChinLineHeight : 0}- /// The collapsed chin hangs below the notch whenever a task is surfaced — running, a completion, or+ /// The collapsed chin hangs below the notch whenever a conversation is surfaced — running, a completion, or/// a failure the user hasn't dismissed yet. The notch view rotates which one's line it shows. The/// band fits one line by default and grows by a line-height to seat a wrapped second line (capped/// there), keeping the bottom margin constant. Real notch only.private func statusChinHeight(textWidth: CGFloat) -> CGFloat {- let surfaced = model.notchSurfacedTasks+ let surfaced = model.notchSurfacedConversationsguard !surfaced.isEmpty else { return 0 }// Cache by the surfaced chin text + width: `notchMetrics()` runs every frame, but the wrapped-line// Core Text measurement only needs to rerun when the text or available width actually changes.let key = "\(Int(textWidth))|" + surfaced.map(\.chinDisplayText).joined(separator: "\u{1}")if let cache = chinHeightCache, cache.key == key { return cache.height }- let lines = surfaced.reduce(1) { partial, task in- return max(partial, Self.chinLineCount(for: task.chinDisplayText, width: textWidth))+ let lines = surfaced.reduce(1) { partial, conversation in+ return max(partial, Self.chinLineCount(for: conversation.chinDisplayText, width: textWidth))}let height = CGFloat(lines) * Self.statusChinLineHeight + Self.statusChinBottomMarginchinHeightCache = (key, height)@@ -1112,15 +1112,15 @@ final class UserQueryOverlayController {return NotchMetrics.loginExpandedContentHeight}- if hasStatusTaskDisplayText || !model.notchTasks.isEmpty || model.updateState.headerButtonTitle != nil {- return NotchMetrics.expandedTaskContentHeight+ if hasStatusConversationDisplayText || !model.notchConversations.isEmpty || model.updateState.headerButtonTitle != nil {+ return NotchMetrics.expandedConversationContentHeight}return model.notchCommandInputSurfaceHeight + NotchMetrics.compactCommandContentVerticalPadding}- private var hasStatusTaskDisplayText: Bool {- UserQueryCopy.isTaskDisplayText(model.promptState.promptText)+ private var hasStatusConversationDisplayText: Bool {+ UserQueryCopy.isConversationDisplayText(model.promptState.promptText)}private func inferredVoidWidth(for screen: NSScreen, safeTop: CGFloat) -> CGFloat {@@ -1565,18 +1565,18 @@ private struct StatusPanelViewSnapshot: Equatable {var surfaceSize: CGSizevar isExpanded: Boolvar isHostExpanded: Bool- var isCurrentTaskPaused: Bool+ var isCurrentConversationPaused: Boolvar notchCommandText: Stringvar notchCommandInputTextHeight: CGFloatvar isNotchCommandInputExpanded: Bool- var notchTasks: [UserQueryConversation]- var notchSurfacedTasks: [UserQueryConversation]+ var notchConversations: [UserQueryConversation]+ var notchSurfacedConversations: [UserQueryConversation]var accentIndex: Intvar spawnState: UserQuerySpawnState?var spawnStates: [UserQuerySpawnState]var selectedSpawnID: String?- var replyTargetTaskID: String?- var selectedTaskID: String?+ var replyTargetConversationID: String?+ var selectedConversationID: String?var needsLogin: Bool}diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex ff491488..63690a7c 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -22,18 +22,18 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {didSet {// Starting a draft hands the arrows back to the composer for text editing; the row// highlight re-engages when the user clicks or arrows onto a row (see `focusNotchRow`).- if !notchCommandText.isEmpty { selectedTaskID = nil }+ if !notchCommandText.isEmpty { selectedConversationID = nil }}}@Published private(set) var notchCommandInputTextHeight = UserQueryLayout.composerInputTextMinimumHeight@Published private(set) var isNotchCommandInputExpanded = true@Published private(set) var notchAccentIndex = 0- @Published private(set) var isCurrentTaskPaused = false+ @Published private(set) var isCurrentConversationPaused = false@Published private(set) var updateState: UserQueryUpdateState- @Published private(set) var notchTasks: [UserQueryConversation]+ @Published private(set) var notchConversations: [UserQueryConversation]@Published private(set) var spawnStates: [UserQuerySpawnState] = []@Published private(set) var selectedSpawnID: String?- /// Logged out: the notch renders a login call-to-action instead of the task surface. The app+ /// Logged out: the notch renders a login call-to-action instead of the conversation surface. The app/// delegate pushes this from the auth coordinator's session state (true while signed out after a/// prior sign-in, i.e. an expired session) and clears it once sign-in completes.@Published private(set) var needsLogin = false@@ -42,43 +42,43 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {/// (the Google browser flow). The model never opens browsers or windows itself.var loginActionRequested: (() -> Void)?/// Fired when a hosted request fails authentication mid-run (an expired session). The app delegate- /// wires this to sign out, which flips the notch into login mode while the running tasks stay put.+ /// wires this to sign out, which flips the notch into login mode while the running conversations stay put.var sessionExpired: (() -> Void)?/// Fired when the Live session's optional audio streaming should start/stop,/// so the mic owner can keep the engine running continuously.var onLiveAudioStreamingChanged: ((Bool) -> Void)?private var commandHandler: any UserQueryCommandHandling- private let taskStore: any UserQueryConversationStoring+ private let conversationStore: any UserQueryConversationStoringprivate let followUpResolver: any UserQueryFollowUpResolvingprivate let voiceTranscriber: LocalVoiceTranscriptionAdapterprivate let liveController: GeminiLiveVoiceControllerprivate var updateChecker: any DonkeyUpdateCheckingprivate let appCatalogRefreshLoop: LocalAppDynamicCatalogRefreshLoopprivate var activeAgentIDs: Set<String> = []- /// Resume requests made while a task's previous loop was still winding down (e.g. a quick Stop→Resume).+ /// Resume requests made while a conversation'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> = []- /// The task an explicit Reply tap pinned the next submission to (a task waiting on the user — a- /// clarification or review). It routes the answer straight to that task instead of leaving the+ /// never run on one conversation and the tap is never silently dropped.+ private var pendingResumeConversationIDs: Set<String> = []+ /// The conversation an explicit Reply tap pinned the next submission to (a conversation waiting on the user — a+ /// clarification or review). It routes the answer straight to that conversation instead of leaving the/// follow-up resolver to guess, and the expanded panel dims every other row while it is set so the/// user sees which thread their reply continues. Consumed by the next submission.- @Published private(set) var replyTargetTaskID: String?- /// The task row the keyboard arrows currently highlight in the expanded notch, or nil when the- /// composer holds the focus. Distinct from `replyTargetTaskID`: arrowing only moves this highlight;+ @Published private(set) var replyTargetConversationID: String?+ /// The conversation row the keyboard arrows currently highlight in the expanded notch, or nil when the+ /// composer holds the focus. Distinct from `replyTargetConversationID`: arrowing only moves this highlight;/// pressing Return on it begins a reply (like clicking the row). Typing into the composer clears it/// so the arrows return to editing the draft; clicking a row re-engages it.- @Published private(set) var selectedTaskID: String?- /// Metadata flag marking a terminal task (completed or failed) as seen — set when the user expands- /// the notch. It lives on the task (and so is persisted through the task store) rather than in memory,+ @Published private(set) var selectedConversationID: String?+ /// Metadata flag marking a terminal conversation (completed or failed) as seen — set when the user expands+ /// the notch. It lives on the conversation (and so is persisted through the conversation store) rather than in memory,/// so an acknowledged failure stays dismissed across relaunches instead of re-surfacing every launch.private static let seenMetadataKey = "notch.seen"- /// Clear the "seen" dismissal a task carries into a fresh running run, so its next terminal state+ /// Clear the "seen" dismissal a conversation carries into a fresh running run, so its next terminal state/// re-surfaces in the collapsed notch. Applied at every stopped→running transition — both the in-place- /// resume (`updateTask`) and the matched-resume seed (`taskForSubmittedCommand`), which bypasses- /// `updateTask`. The same transitions also reset `conversationsStreamingAnswer`.+ /// resume (`updateConversation`) and the matched-resume seed (`conversationForSubmittedCommand`), which bypasses+ /// `updateConversation`. The same transitions also reset `conversationsStreamingAnswer`.private static func clearRunMetadata(_ metadata: inout [String: String]) {metadata[seenMetadataKey] = nil}@@ -89,30 +89,33 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {/// `clearRunMetadata` at every stopped→running transition so a new run's reply replaces the old one.private var conversationsStreamingAnswer: Set<String> = []- private var lastActiveTaskID: String?- /// The task/spawn the in-flight Gemini Live turn reports into, so the user- /// sees the same cursor-and-task feedback as a local pipeline run.+ private var lastActiveConversationID: String?+ /// The conversation/spawn the in-flight Gemini Live turn reports into, so the user+ /// sees the same cursor-and-conversation feedback as a local pipeline run.private var liveTurn: (conversationID: String, spawnID: String?)?private var liveTurnWatchdog: Task<Void, Never>?- private static let notchTaskDisplayLimit = 12+ private static let notchConversationDisplayLimit = 12private static let followUpCandidateLimit = 8+ /// Stable id for the app-managed tool-setup conversation, so a relaunch (or re-download for a new+ /// version) reuses the one row instead of stacking a fresh one each time. See `startSystemToolsSetupIfNeeded`.+ private static let toolsSetupConversationID = "system.tools-setup"private static let followUpMatchConfidenceThreshold = 0.62- /// How long a Live turn may stay silent (no tool, no answer) before the task+ /// How long a Live turn may stay silent (no tool, no answer) before the conversation/// is failed instead of spinning forever.private static let liveTurnSilenceLimitSeconds: TimeInterval = 75init(aiProvider: any AIHarnessSnapshotProviding = AIHarnessBoundary(),commandHandler: any UserQueryCommandHandling = LocalAppUserQueryCommandHandler(),- taskStore: any UserQueryConversationStoring = CoreDataUserQueryConversationStore(),- followUpResolver: any UserQueryFollowUpResolving = HostedTaskFollowUpResolver(),+ conversationStore: any UserQueryConversationStoring = CoreDataUserQueryConversationStore(),+ followUpResolver: any UserQueryFollowUpResolving = HostedConversationFollowUpResolver(),voiceTranscriber: LocalVoiceTranscriptionAdapter = LocalVoiceTranscriptionAdapter(),updateChecker: any DonkeyUpdateChecking = SparkleUpdateController(),liveController: GeminiLiveVoiceController = GeminiLiveVoiceController(),theme: UserQueryTheme = UserQueryOverlayModel.bundledTheme()) {self.commandHandler = commandHandler- self.taskStore = taskStore+ self.conversationStore = conversationStoreself.followUpResolver = followUpResolverself.voiceTranscriber = voiceTranscriberself.liveController = liveController@@ -120,15 +123,15 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {self.appCatalogRefreshLoop = LocalAppDynamicCatalogRefreshLoop(profileGenerator: HostedLocalAppCatalogProfileGenerator())- let restoration = Self.restoredTasks(- from: taskStore.loadRecentTasks(limit: Self.notchTaskDisplayLimit),+ let restoration = Self.restoredConversations(+ from: conversationStore.loadRecentConversations(limit: Self.notchConversationDisplayLimit),now: Date())- let restoredTasks = restoration.tasks- notchTasks = restoredTasks- notchAccentIndex = restoredTasks.first.map { UserQueryAccentPalette.normalizedIndex($0.accentIndex) }+ let restoredConversations = restoration.conversations+ notchConversations = restoredConversations+ notchAccentIndex = restoredConversations.first.map { UserQueryAccentPalette.normalizedIndex($0.accentIndex) }?? UserQueryAccentPalette.firstIndex- isCurrentTaskPaused = restoredTasks.first?.status == .paused+ isCurrentConversationPaused = restoredConversations.first?.status == .pausedupdateState = UserQueryUpdateState(currentVersion: updateChecker.currentVersion)@@ -149,20 +152,20 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {checkForUpdates()startLiveSessionIfEnabled()// A mid-run 401 from the hosted backend means the session expired: surface login (the app- // delegate wires `sessionExpired` to the auth coordinator) while the running tasks stay put.+ // delegate wires `sessionExpired` to the auth coordinator) while the running conversations stay put.self.commandHandler.onAuthenticationRequired = { [weak self] inself?.handleSessionExpired()}- autoResumeInterruptedTasks(restoration.autoResumeIDs)+ autoResumeInterruptedConversations(restoration.autoResumeIDs)}- /// Resume tasks that were actively running when the app last quit (see `restoredTasks`). Each runs as+ /// Resume conversations that were actively running when the app last quit (see `restoredConversations`). 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(_ conversationIDs: [String]) {+ /// the cursor; progress narrates into the conversation's own row. Fires once, at launch.+ private func autoResumeInterruptedConversations(_ conversationIDs: [String]) {guard !conversationIDs.isEmpty else { return }// Don't drive the harness while signed out — every planner step would 401. The interrupted- // tasks stay retryable and resume on the next launch (or manual retry) once signed in.+ // conversations stay retryable and resume on the next launch (or manual retry) once signed in.guard BackendSessionGate.shared.isAuthenticated else { return }for conversationID in conversationIDs {guard let context = commandContext(conversationID: conversationID, isFollowUp: false, source: .followUp, spawnID: nil) else {@@ -174,11 +177,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {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+ // backend off): keep the conversation 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.activeAgentIDs.remove(conversationID)- self.updateTask(id: conversationID, detail: "Interrupted — resume", status: .timedOut)+ self.updateConversation(id: conversationID, detail: "Interrupted — resume", status: .timedOut)return}self.handleCommandRunResult(conversationID: conversationID, spawnID: nil, isFollowUp: false, result: result!)@@ -187,6 +190,127 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}+ // MARK: - System tool setup (first-run bundle download)++ /// Begin the app-managed download of the bundled CLI tools, surfaced as a normal-looking conversation+ /// the user can watch but never stop, resume, reply to, or dismiss (it is `origin == .system`; every+ /// control gates on `isUserControllable`). The app delegate calls this once the notch surfaces are up.+ /// The installer no-ops when the bundle is already current or nothing is published, so it is cheap to+ /// call on every launch and sign-in, and it handles its own retries — the row just narrates them.+ func startSystemToolsSetupIfNeeded() {+ reconcileInterruptedSystemSetup()+ Task { [weak self] in+ await BundledToolsInstaller.shared.installIfNeeded(onEvent: { event in+ Task { @MainActor in self?.applyToolsSetupEvent(event) }+ })+ }+ }++ /// A relaunch tears down the install loop, so a setup row persisted mid-run can't keep advancing on its+ /// own. Settle it before the fresh install run (which reconciles it for real): if the tools are present+ /// it reads as ready; otherwise drop the stale row so the run below re-creates it only if work remains.+ private func reconcileInterruptedSystemSetup() {+ let id = Self.toolsSetupConversationID+ guard let conversation = conversation(withID: id),+ conversation.origin == .system,+ conversation.status != .completed,+ conversation.status != .failed else {+ return+ }+ if BundledTools.installedVersion != nil {+ updateConversation(id: id, detail: "Tools ready", status: .completed)+ } else {+ notchConversations.removeAll { $0.id == id }+ conversationStore.deleteConversation(id: id)+ }+ }++ /// Map one installer event onto the setup conversation. Discrete transitions announce through the+ /// lifecycle path (event log + thread record); the download's percent stream is a detail-only update so+ /// it doesn't spam an event per percent. The conversation stays `.running` through retries — the user+ /// can't act on it, so a momentary "failed" would only alarm; only a final give-up reads as `.failed`.+ private func applyToolsSetupEvent(_ event: BundledToolsSetupEvent) {+ let id = Self.toolsSetupConversationID+ switch event {+ case .started:+ ensureSystemSetupConversation()+ announceLifecycle(+ conversationID: id,+ UserQueryActivity(kind: .working, summary: "Setting up Donkey’s tools"),+ status: .running+ )+ case .downloading(let fraction):+ ensureSystemSetupConversation()+ let line = fraction.map { "Downloading tools — \(Int(($0 * 100).rounded()))%" } ?? "Downloading tools…"+ if conversation(withID: id)?.detail != line {+ updateConversation(id: id, detail: line, status: .running)+ }+ case .verifying:+ updateConversation(id: id, detail: "Verifying tools…", status: .running)+ case .installing:+ updateConversation(id: id, detail: "Installing tools…", status: .running)+ case .retrying(let attempt, let maxAttempts):+ updateConversation(+ id: id,+ detail: "Download interrupted — retrying (\(attempt)/\(maxAttempts))…",+ status: .running+ )+ case .completed:+ announceLifecycle(+ conversationID: id,+ UserQueryActivity(kind: .completed, summary: "Tools ready"),+ status: .completed+ )+ scheduleSystemSetupAutoAcknowledge(id: id)+ case .failed:+ announceLifecycle(+ conversationID: id,+ UserQueryActivity(kind: .failed, summary: "Couldn’t finish setting up tools — Donkey will try again later"),+ status: .failed+ )+ scheduleSystemSetupAutoAcknowledge(id: id)+ }+ }++ /// Create the setup row on the first event of a fresh run, or re-open the persisted one to running for a+ /// new version's download (which clears its "seen" flag so it resurfaces). Reuses the stable id.+ private func ensureSystemSetupConversation() {+ let id = Self.toolsSetupConversationID+ if let existing = conversation(withID: id) {+ if existing.status != .running {+ updateConversation(id: id, status: .running)+ }+ return+ }+ let conversation = UserQueryConversation(+ id: id,+ title: "Setting up Donkey’s tools",+ detail: "Preparing…",+ commandText: "",+ status: .running,+ accentIndex: nextRoundRobinAccentIndex(),+ origin: .system+ )+ prependConversation(conversation)+ }++ /// The user can't dismiss a system row, so a finished one would otherwise pin the collapsed chin+ /// forever. Mark it seen after a short read so the chin settles on its own; the row stays in the list+ /// (and history) like any other completed conversation.+ private func scheduleSystemSetupAutoAcknowledge(id: String) {+ DispatchQueue.main.asyncAfter(deadline: .now() + 6) { [weak self] in+ guard let self,+ let index = self.notchConversations.firstIndex(where: { $0.id == id }),+ Self.isSurfacedTerminalStatus(self.notchConversations[index].status) else {+ return+ }+ var conversation = self.notchConversations[index]+ conversation.metadata[Self.seenMetadataKey] = "true"+ self.notchConversations[index] = conversation+ self.conversationStore.upsertConversation(conversation)+ }+ }+/// Bring up the always-on Gemini Live session. It self-gates on configuration/// and only becomes `isConnected` if it can authenticate, so when it is not/// configured the existing command pipeline is used unchanged.@@ -198,7 +322,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {liveController.onComplexRequest = { [weak self] goal in// The model explicitly delegated via agent_run: close out the Live// turn and run the goal through the full local pipeline (never back- // through Live — no loop). The pipeline has its own task/spawn UI.+ // through Live — no loop). The pipeline has its own conversation/spawn UI.guard let self else { return }self.finishLiveTurn(detail: "Handed off to the desktop agent", status: .completed)self.runLocalCommand(goal, source: .typedPrompt)@@ -209,7 +333,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {self.promptState.promptText = summaryguard let liveTurn = self.liveTurn else { return }self.updateSpawn(id: liveTurn.spawnID, label: Self.collapsedDisplayText(for: summary), phase: .holding)- self.updateTask(id: liveTurn.conversationID, detail: summary, status: .running)+ self.updateConversation(id: liveTurn.conversationID, detail: summary, status: .running)self.appendAgentEvent(conversationID: liveTurn.conversationID, role: .system, text: summary)self.restartLiveTurnWatchdog()}@@ -289,9 +413,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {loginActionRequested?()}- /// The notch "Reload credits" CTA was tapped on a credit-exhausted task. Open the billing page in+ /// The notch "Reload credits" CTA was tapped on a credit-exhausted conversation. Open the billing page in/// the browser (donkeyuse.com in prod, localhost in dev — the configured web base URL) so the user- /// can top up; the task stays on the row so it can be re-run once credits land.+ /// can top up; the conversation stays on the row so it can be re-run once credits land.func reloadCredits(id conversationID: String) {let billingURL = DonkeyAuthConfiguration.current().webBaseURL.appendingPathComponent("app/settings")@@ -390,41 +514,41 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}/// Send a turn to the Live session with the same visible lifecycle as a- /// local run: a task in the rail and a spawn cursor that narrates tool+ /// local run: a conversation in the rail and a spawn cursor that narrates tool/// activity, consent gates, and the final answer.private func routeToLiveSession(_ text: String) {if liveTurn != nil {finishLiveTurn(detail: "Changed course", status: .interrupted)}let spawnID = beginSpawn(for: text)- let task = taskForSubmittedCommand(+ let conversation = conversationForSubmittedCommand(text: text,- matchedTaskID: nil,+ matchedConversationID: nil,reservedAccentIndex: spawnID.flatMap { spawn(withID: $0)?.accentIndex })- updateSpawn(id: spawnID, conversationID: task.id, accentIndex: task.accentIndex)- activeAgentIDs.insert(task.id)- lastActiveTaskID = task.id- appendAgentEvent(conversationID: task.id, role: .user, text: text)+ updateSpawn(id: spawnID, conversationID: conversation.id, accentIndex: conversation.accentIndex)+ activeAgentIDs.insert(conversation.id)+ lastActiveConversationID = conversation.id+ appendAgentEvent(conversationID: conversation.id, role: .user, text: text)clearSubmissionInputs()promptState.isActive = falsepromptState.isVoiceInputActive = falsepromptState.leadingSignalLevel = .thinking- promptState.promptText = task.title- liveTurn = (task.id, spawnID)+ promptState.promptText = conversation.title+ liveTurn = (conversation.id, spawnID)restartLiveTurnWatchdog()Task { [liveController] in await liveController.sendText(text) }}- /// Close out the in-flight Live turn's task and spawn.+ /// Close out the in-flight Live turn's conversation and spawn.private func finishLiveTurn(detail: String?, status: UserQueryConversationStatus) {liveTurnWatchdog?.cancel()liveTurnWatchdog = nilguard let turn = liveTurn else { return }liveTurn = nil- updateTask(id: turn.conversationID, detail: detail, status: status)+ updateConversation(id: turn.conversationID, detail: detail, status: status)activeAgentIDs.remove(turn.conversationID)- syncPrimaryTaskPausedFlag()+ syncPrimaryConversationPausedFlag()guard let spawnID = turn.spawnID, let index = spawnIndex(id: spawnID) else { return }var spawnState = spawnStates[index]switch status {@@ -444,7 +568,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}/// Fail the Live turn if the session stays silent (no tool call, no answer)- /// past the limit, instead of leaving the task spinning.+ /// past the limit, instead of leaving the conversation spinning.private func restartLiveTurnWatchdog() {liveTurnWatchdog?.cancel()let limit = Self.liveTurnSilenceLimitSeconds@@ -459,14 +583,14 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- /// Surface a Live-path shell consent in the notch using the same task+ /// Surface a Live-path shell consent in the notch using the same conversation/// metadata the harness consent UI reads, marked so approval routes back to/// the Live controller instead of the harness lifecycle.private func presentLiveShellConsent(_ request: GeminiLiveShellConsentRequest) {guard let turn = liveTurn else { return }liveTurnWatchdog?.cancel()updateSpawn(id: turn.spawnID, label: "Waiting for approval", phase: .holding)- updateTask(+ updateConversation(id: turn.conversationID,detail: request.summary,status: .waitingForPermission,@@ -480,13 +604,13 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {appendAgentEvent(conversationID: turn.conversationID, role: .system, text: request.summary)promptState.leadingSignalLevel = .readypromptState.promptText = request.summary- syncPrimaryTaskPausedFlag()+ syncPrimaryConversationPausedFlag()}private func runLocalCommand(_ text: String, source: AppHarnessTurnSource = .typedPrompt) {let candidates = followUpCandidates()let promptFollowUpTarget = promptSubmissionFollowUpTarget()- let replyTargetTaskID = consumePendingReplyTarget()+ let replyTargetConversationID = consumePendingReplyTarget()let spawnID: String?if let promptFollowUpTarget {updateSpawn(@@ -508,14 +632,14 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {let sourceTraceID = "user-query-followup-\(UUID().uuidString)"let confidenceThreshold = Self.followUpMatchConfidenceThresholdTask { [weak self, followUpResolver] in- let matchedTaskID: String?- if let replyTargetTaskID {- // An explicit Reply pins the answer to that task — never re-routed by the resolver.- matchedTaskID = replyTargetTaskID+ let matchedConversationID: String?+ if let replyTargetConversationID {+ // An explicit Reply pins the answer to that conversation — never re-routed by the resolver.+ matchedConversationID = replyTargetConversationID} else if let conversationID = promptFollowUpTarget?.conversationID {- matchedTaskID = conversationID+ matchedConversationID = conversationID} else if candidates.isEmpty {- matchedTaskID = nil+ matchedConversationID = nil} else {let resolution = await followUpResolver.resolveFollowUp(UserQueryFollowUpResolverRequest(@@ -526,16 +650,16 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {)if let conversationID = resolution.conversationID,resolution.confidence >= confidenceThreshold {- matchedTaskID = conversationID+ matchedConversationID = conversationID} else {- matchedTaskID = nil+ matchedConversationID = nil}}await MainActor.run {self?.startCommandRun(text: text,- matchedTaskID: matchedTaskID,+ matchedConversationID: matchedConversationID,source: source,spawnID: spawnID)@@ -546,30 +670,30 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {func handleDroppedAssets(_ drafts: [UserQueryConversationAssetDraft]) {guard !drafts.isEmpty else { return }- let targetTask = taskForDroppedAssets()+ let targetConversation = conversationForDroppedAssets()let assetNames = drafts.map(\.displayName)let eventText = Self.assetUploadEventText(assetNames)- let eventID = appendAgentEvent(conversationID: targetTask.id, role: .user, text: eventText)+ let eventID = appendAgentEvent(conversationID: targetConversation.id, role: .user, text: eventText)for draft in drafts {let assetID = UUID().uuidString- taskStore.appendAsset(+ conversationStore.appendAsset(Self.persistedAsset(from: draft,assetID: assetID,- conversationID: targetTask.id,+ conversationID: targetConversation.id,eventID: eventID))}- var updatedTask = targetTask- updatedTask.detail = drafts.count == 1 ? "1 asset attached" : "\(drafts.count) assets attached"- updatedTask.updatedAt = Date()- prependTask(updatedTask)- lastActiveTaskID = updatedTask.id- promptState.promptText = updatedTask.title- promptState.leadingSignalLevel = updatedTask.status == .running ? .thinking : .ready- syncPrimaryTaskPausedFlag()+ var updatedConversation = targetConversation+ updatedConversation.detail = drafts.count == 1 ? "1 asset attached" : "\(drafts.count) assets attached"+ updatedConversation.updatedAt = Date()+ prependConversation(updatedConversation)+ lastActiveConversationID = updatedConversation.id+ promptState.promptText = updatedConversation.title+ promptState.leadingSignalLevel = updatedConversation.status == .running ? .thinking : .ready+ syncPrimaryConversationPausedFlag()}func markSpawnDesktopEmerged(id spawnID: String) {@@ -608,7 +732,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {)startCommandRun(text: trimmedText,- matchedTaskID: conversationID,+ matchedConversationID: conversationID,source: .followUp,spawnID: spawnID)@@ -616,26 +740,26 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {private func startCommandRun(text: String,- matchedTaskID: String?,+ matchedConversationID: 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+ // A follow-up to a conversation whose loop is still running — or one blocked at a permission gate — is+ // queued into that conversation: the running loop folds it in at its next step, and a gated conversation 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, conversationID: matchedTaskID, source: source, spawnID: spawnID)+ // or clear the gate. Everything else (a brand-new command, or a follow-up to a stopped conversation) takes+ // the fresh/resume path below, which runs concurrently with any other in-flight conversation.+ let matchedStatus = matchedConversationID.flatMap { conversation(withID: $0)?.status }+ if let matchedConversationID, matchedStatus == .running || matchedStatus == .waitingForPermission {+ queueFollowUpIntoRunningConversation(text: text, conversationID: matchedConversationID, source: source, spawnID: spawnID)return}- runFreshOrResumedCommand(text: text, matchedTaskID: matchedTaskID, source: source, spawnID: spawnID)+ runFreshOrResumedCommand(text: text, matchedConversationID: matchedConversationID, 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(+ /// Queue a follow-up onto a conversation 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 conversation with the instruction.+ private func queueFollowUpIntoRunningConversation(text: String,conversationID: String,source: AppHarnessTurnSource,@@ -644,21 +768,21 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {appendAgentEvent(conversationID: conversationID, role: .user, text: text)updateSpawn(id: spawnID, conversationID: conversationID)clearSubmissionInputs()- lastActiveTaskID = conversationID+ lastActiveConversationID = conversationIDpromptState.isActive = falsepromptState.isVoiceInputActive = falsepromptState.leadingSignalLevel = .thinking- promptState.promptText = task(withID: conversationID)?.title ?? Self.collapsedDisplayText(for: text)- syncPrimaryTaskPausedFlag()+ promptState.promptText = conversation(withID: conversationID)?.title ?? Self.collapsedDisplayText(for: text)+ syncPrimaryConversationPausedFlag()Task { [weak self, commandHandler] inlet injected = await commandHandler.injectFollowUp(conversationID: conversationID, text: text)guard !injected else { return }- // Race: the loop finished between the live check and the enqueue. Resume the task with the+ // Race: the loop finished between the live check and the enqueue. Resume the conversation with the// instruction instead. The user event is already recorded, so it is not appended again.await MainActor.run {self?.runFreshOrResumedCommand(text: text,- matchedTaskID: conversationID,+ matchedConversationID: conversationID,source: source,spawnID: spawnID,appendUserEvent: false@@ -669,35 +793,35 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {private func runFreshOrResumedCommand(text: String,- matchedTaskID: String?,+ matchedConversationID: String?,source: AppHarnessTurnSource = .typedPrompt,spawnID: String? = nil,appendUserEvent: Bool = true) {- let isFollowUp = matchedTaskID != nil+ let isFollowUp = matchedConversationID != nillet reservedAccentIndex = spawnID.flatMap { spawn(withID: $0)?.accentIndex }- let task = taskForSubmittedCommand(+ let conversation = conversationForSubmittedCommand(text: text,- matchedTaskID: matchedTaskID,+ matchedConversationID: matchedConversationID,reservedAccentIndex: reservedAccentIndex)updateSpawn(id: spawnID,- conversationID: task.id,- accentIndex: task.accentIndex+ conversationID: conversation.id,+ accentIndex: conversation.accentIndex)- activeAgentIDs.insert(task.id)- lastActiveTaskID = task.id+ activeAgentIDs.insert(conversation.id)+ lastActiveConversationID = conversation.idif appendUserEvent {- appendAgentEvent(conversationID: task.id, role: .user, text: text)+ appendAgentEvent(conversationID: conversation.id, role: .user, text: text)}clearSubmissionInputs()promptState.isActive = falsepromptState.leadingSignalLevel = .thinking- promptState.promptText = task.title- syncPrimaryTaskPausedFlag()+ promptState.promptText = conversation.title+ syncPrimaryConversationPausedFlag()let context = commandContext(- conversationID: task.id,+ conversationID: conversation.id,isFollowUp: isFollowUp,source: source,spawnID: spawnID@@ -706,7 +830,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {let result = await commandHandler.handleSubmittedCommand(text, context: context)await MainActor.run {self?.handleCommandRunResult(- conversationID: task.id,+ conversationID: conversation.id,spawnID: spawnID,isFollowUp: isFollowUp,result: result@@ -715,7 +839,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- /// Apply a finished pipeline run to the task rail, prompt pill, cursor+ /// Apply a finished pipeline run to the conversation rail, prompt pill, cursor/// replay, and spawn — shared by fresh submissions and post-approval resumes.private func handleCommandRunResult(conversationID: String,@@ -723,11 +847,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {isFollowUp: Bool,result: UserQueryCommandHandlingResult) {- updateTask(+ updateConversation(id: conversationID,- title: isFollowUp ? nil : result.taskLabel,+ title: isFollowUp ? nil : result.conversationLabel,detail: result.summary,- status: Self.taskStatus(for: result),+ status: Self.conversationStatus(for: result),metadata: result.metadata)appendAgentEvent(conversationID: conversationID, role: .assistant, text: result.summary)@@ -743,8 +867,8 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {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 activeAgentIDs, the resume can start without racing a live loop.- if pendingResumeTaskIDs.remove(conversationID) != nil {+ // loop has ended and the conversation left activeAgentIDs, the resume can start without racing a live loop.+ if pendingResumeConversationIDs.remove(conversationID) != nil {resumeAgent(id: conversationID)}}@@ -757,13 +881,13 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {/// consumed; at the composer with a draft already typed, the arrows fall through to edit the text.@discardableResultfunc moveNotchSelection(_ direction: NotchArrowDirection) -> Bool {- guard !notchTasks.isEmpty else { return false }- let lastIndex = notchTasks.count - 1- guard let current = selectedTaskID.flatMap({ id in notchTasks.firstIndex { $0.id == id } }) else {+ guard !notchConversations.isEmpty else { return false }+ let lastIndex = notchConversations.count - 1+ guard let current = selectedConversationID.flatMap({ id in notchConversations.firstIndex { $0.id == id } }) else {// No row focused yet: enter the list, but only when the composer isn't holding a draft.if !notchCommandText.isEmpty { return false }let entry = direction == .up ? lastIndex : 0- focusNotchRow(notchTasks[entry].id)+ focusNotchRow(notchConversations[entry].id)return true}let next: Int@@ -771,7 +895,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {case .up: next = max(0, current - 1)case .down: next = min(lastIndex, current + 1)}- focusNotchRow(notchTasks[next].id)+ focusNotchRow(notchConversations[next].id)return true}@@ -780,68 +904,77 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {/// accent, and the other rows dim). Passing nil (Escape, or leaving reply) clears both, the same as/// clicking bare chrome.func focusNotchRow(_ conversationID: String?) {- selectedTaskID = conversationID- guard let conversationID, task(withID: conversationID) != nil else {- replyTargetTaskID = nil+ selectedConversationID = conversationID+ guard let conversationID, let conversation = conversation(withID: conversationID) else {+ replyTargetConversationID = nil+ return+ }+ // A system-driven row (tool setup) can be highlighted, but the user can't reply to it, so it never+ // becomes the reply target — a Return on it is inert rather than pinning the composer to it.+ guard conversation.isUserControllable else {+ replyTargetConversationID = nilreturn}- replyTargetTaskID = conversationID- lastActiveTaskID = conversationID+ replyTargetConversationID = conversationID+ lastActiveConversationID = conversationID}func clearNotchSelection() {- selectedTaskID = nil+ selectedConversationID = nil}/// Take the pinned Reply target, if any, for the submission about to run. Cleared on read so it only- /// applies to the one answer (which also un-dims the rows), and dropped if the task is no longer+ /// applies to the one answer (which also un-dims the rows), and dropped if the conversation is no longer/// around (fall back to normal routing).private func consumePendingReplyTarget() -> String? {- guard let conversationID = replyTargetTaskID else { return nil }- replyTargetTaskID = nil- // Drop the pin only if the task vanished between the tap and the submit (e.g. it was closed);+ guard let conversationID = replyTargetConversationID else { return nil }+ replyTargetConversationID = nil+ // Drop the pin only if the conversation vanished between the tap and the submit (e.g. it was closed);// otherwise the message is pinned to it whatever its current state (`startCommandRun` routes a// running/permission-gated target into a queued follow-up, a stopped/terminal one resumes).- return task(withID: conversationID) != nil ? conversationID : nil+ return conversation(withID: conversationID) != nil ? conversationID : nil}func pauseAgent(id conversationID: String) {- guard task(withID: conversationID)?.status == .running else { return }+ guard let conversation = conversation(withID: conversationID),+ conversation.isUserControllable,+ conversation.status == .running else { return }activeAgentIDs.insert(conversationID)- lastActiveTaskID = conversationID+ lastActiveConversationID = conversationIDannounceLifecycle(conversationID: conversationID, UserQueryActivity(kind: .paused), status: .paused)- syncPrimaryTaskPausedFlag()+ syncPrimaryConversationPausedFlag()Task { [commandHandler] in_ = await commandHandler.pauseCommand(conversationID: conversationID)}}func resumeAgent(id conversationID: String) {- guard let task = task(withID: conversationID),- [.paused, .interrupted, .timedOut, .needsAttention].contains(task.status) else {+ guard let conversation = conversation(withID: conversationID),+ conversation.isUserControllable,+ [.paused, .interrupted, .timedOut, .needsAttention].contains(conversation.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+ // Only run a conversation 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 !conversation.commandText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }+ // If the conversation's previous loop is still winding down (e.g. just Stopped), defer the resume until it+ // ends so two loops never run on one conversation; handleCommandRunResult fires the deferred resume.guard !activeAgentIDs.contains(conversationID) else {- pendingResumeTaskIDs.insert(conversationID)+ pendingResumeConversationIDs.insert(conversationID)return}activeAgentIDs.insert(conversationID)- lastActiveTaskID = conversationID+ lastActiveConversationID = conversationID// The live line falls back to the running activity ("Thinking"); the record logs "Resuming".announceLifecycle(conversationID: conversationID, UserQueryActivity(kind: .resumed), status: .running, liveDetail: "")updateSpawn(id: spawnStates.first { $0.conversationID == conversationID }?.id, resumesWork: true)promptState.leadingSignalLevel = .thinking- promptState.promptText = task.title- syncPrimaryTaskPausedFlag()+ promptState.promptText = conversation.title+ syncPrimaryConversationPausedFlag()// 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+ // re-run the conversation'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(conversationID: conversationID, isFollowUp: false, source: .followUp, spawnID: nil)Task { [weak self, commandHandler] in@@ -850,7 +983,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {// than leaving it stuck on the optimistic "running" with no loop behind it.await MainActor.run {self?.activeAgentIDs.remove(conversationID)- self?.updateTask(id: conversationID, detail: "Couldn’t resume — tap to retry", status: .timedOut)+ self?.updateConversation(id: conversationID, detail: "Couldn’t resume — tap to retry", status: .timedOut)}return}@@ -860,17 +993,17 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- /// The tasks the collapsed notch keeps surfaced as floating pointers: anything running, anything- /// blocked on the user (a clarification, a review, or a permission), plus terminal tasks (a finished+ /// The conversations the collapsed notch keeps surfaced as floating pointers: anything running, anything+ /// blocked on the user (a clarification, a review, or a permission), plus terminal conversations (a finished/// action, a conversational reply, or a failure) the user hasn't dismissed yet by expanding the notch./// A failure — like an auth error —- /// holds the chin until acknowledged just as a completion does; a waiting task keeps its pointer lit+ /// holds the chin until acknowledged just as a completion does; a waiting conversation keeps its pointer lit/// and pulsing (and its question in the chin) until the user answers.- var notchSurfacedTasks: [UserQueryConversation] {- notchTasks.filter { task in- task.status == .running ||- Self.isWaitingOnUserStatus(task.status) ||- (Self.isSurfacedTerminalStatus(task.status) && !Self.isSeen(task))+ var notchSurfacedConversations: [UserQueryConversation] {+ notchConversations.filter { conversation in+ conversation.status == .running ||+ Self.isWaitingOnUserStatus(conversation.status) ||+ (Self.isSurfacedTerminalStatus(conversation.status) && !Self.isSeen(conversation))}}@@ -880,16 +1013,16 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {status.isAwaitingUserResponse || status == .waitingForPermission}- /// Marks every currently-terminal task (a finished action, a conversational reply, or a failure) as+ /// Marks every currently-terminal conversation (a finished action, a conversational reply, or a failure) as/// seen so it stops surfacing in the/// collapsed notch. Called when the notch expands — the user is now looking at the full list. The- /// flag is written to the task store, so the dismissal sticks across relaunches.- func acknowledgeSurfacedTasks() {- for index in notchTasks.indices where Self.isSurfacedTerminalStatus(notchTasks[index].status) && !Self.isSeen(notchTasks[index]) {- var task = notchTasks[index]- task.metadata[Self.seenMetadataKey] = "true"- notchTasks[index] = task- taskStore.upsertTask(task)+ /// flag is written to the conversation store, so the dismissal sticks across relaunches.+ func acknowledgeSurfacedConversations() {+ for index in notchConversations.indices where Self.isSurfacedTerminalStatus(notchConversations[index].status) && !Self.isSeen(notchConversations[index]) {+ var conversation = notchConversations[index]+ conversation.metadata[Self.seenMetadataKey] = "true"+ notchConversations[index] = conversation+ conversationStore.upsertConversation(conversation)}}@@ -899,47 +1032,72 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {status == .completed || status == .chatting || status == .failed}- private static func isSeen(_ task: UserQueryConversation) -> Bool {- task.metadata[seenMetadataKey] == "true"+ private static func isSeen(_ conversation: UserQueryConversation) -> Bool {+ conversation.metadata[seenMetadataKey] == "true"}- /// Closes a task: removes it from the notch list and tears down its pointer.- /// Offered only for stopped (paused/interrupted/failed) and completed tasks —+ /// Closes a conversation: removes it from the notch list and tears down its pointer.+ /// Offered only for stopped (paused/interrupted/failed) and completed conversations —/// the same affordance the prototype calls "close".- func dismissTask(id conversationID: String) {- guard let task = task(withID: conversationID) else { return }- guard task.status != .running else { return }-- notchTasks.removeAll { $0.id == conversationID }+ func dismissConversation(id conversationID: String) {+ guard let conversation = conversation(withID: conversationID) else { return }+ // A system-driven conversation (tool setup) is the app's to close, not the user's — it clears+ // itself once finished (see `scheduleSystemSetupAutoAcknowledge`).+ guard conversation.isUserControllable else { return }+ guard conversation.status != .running else { return }++ notchConversations.removeAll { $0.id == conversationID }activeAgentIDs.remove(conversationID)- // Closing the targeted task ends reply mode so the remaining rows don't stay dimmed.- if replyTargetTaskID == conversationID {- replyTargetTaskID = nil+ // Closing the targeted conversation ends reply mode so the remaining rows don't stay dimmed.+ if replyTargetConversationID == conversationID {+ replyTargetConversationID = nil}- if selectedTaskID == conversationID {- selectedTaskID = nil+ if selectedConversationID == conversationID {+ selectedConversationID = nil}- if lastActiveTaskID == conversationID {- lastActiveTaskID = notchTasks.first?.id+ if lastActiveConversationID == conversationID {+ lastActiveConversationID = notchConversations.first?.id}if let spawnID = spawnStates.first(where: { $0.conversationID == conversationID })?.id {removeSpawn(id: spawnID)}- // Drop the persisted row (and its events/assets) too, so the task does not- // reappear when the notch reloads recent tasks on the next launch.- taskStore.deleteTask(id: conversationID)- syncPrimaryTaskPausedFlag()+ // Drop the persisted row (and its events/assets) too, so the conversation does not+ // reappear when the notch reloads recent conversations on the next launch.+ conversationStore.deleteConversation(id: conversationID)+ syncPrimaryConversationPausedFlag()+ // Return the free-floating prompt line to rest once this was the last row. The collapsed notch+ // reads `promptState` only when no conversation row exists, so a dismissed conversation's summary+ // left stranded in `promptText` kept rendering — the row read as "still listed" (with a generic+ // "Needs attention") even though it was gone. Resetting once the list empties is what actually+ // makes the X clear the notch.+ resetPromptLineIfNotchEmptied()+ }++ /// The prompt line the collapsed notch falls back to after a dismissal. Empty list → the resting+ /// placeholder, never the dismissed conversation's stranded summary; with rows remaining the collapsed+ /// notch reads them directly, so the line is left as the live flows set it (nil = leave untouched).+ static func restingPromptText(forRemainingConversations conversations: [UserQueryConversation]) -> String? {+ conversations.isEmpty ? UserQueryCopy.defaultPromptPlaceholder : nil+ }++ /// Apply `restingPromptText` to the live prompt state after the notch list changes. Skipped while the+ /// composer is active so it never clobbers what the user is typing into.+ private func resetPromptLineIfNotchEmptied() {+ guard !promptState.isActive,+ let restingText = Self.restingPromptText(forRemainingConversations: notchConversations) else { return }+ promptState.promptText = restingText+ promptState.leadingSignalLevel = .ready}func approvePermissionGate(id conversationID: String, alwaysAllow: Bool = false) {- guard let task = task(withID: conversationID),- task.status == .waitingForPermission else {+ guard let conversation = conversation(withID: conversationID),+ conversation.status == .waitingForPermission else {return}// A Live-path shell consent resolves through the Live controller, which// re-executes the held command and reports back via onActed/onResponse.- if task.metadata["live.shellConsent"] == "true" {+ if conversation.metadata["live.shellConsent"] == "true" {announceLifecycle(conversationID: conversationID,UserQueryActivity(kind: .resumed),@@ -951,7 +1109,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {updateSpawn(id: turn.spawnID, label: UserQueryActivity.Kind.resumed.label, resumesWork: true)restartLiveTurnWatchdog()}- syncPrimaryTaskPausedFlag()+ syncPrimaryConversationPausedFlag()Task { [liveController] inawait liveController.resolvePendingConsent(approved: true, alwaysAllow: alwaysAllow)}@@ -959,13 +1117,13 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}activeAgentIDs.insert(conversationID)- lastActiveTaskID = conversationID- // After approval the task simply resumes; the live line falls back to the running activity+ lastActiveConversationID = conversationID+ // After approval the conversation simply resumes; the live line falls back to the running activity// ("Thinking") rather than narrating an internal "approving permission" step.announceLifecycle(conversationID: conversationID, UserQueryActivity(kind: .resumed), status: .running, liveDetail: "")promptState.leadingSignalLevel = .thinking- promptState.promptText = task.title- syncPrimaryTaskPausedFlag()+ promptState.promptText = conversation.title+ syncPrimaryConversationPausedFlag()let spawnID = spawnStates.first { $0.conversationID == conversationID }?.idupdateSpawn(id: spawnID, resumesWork: true)let context = commandContext(conversationID: conversationID, isFollowUp: true, spawnID: spawnID)@@ -974,9 +1132,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {guard approved else {await MainActor.run {guard let self else { return }- self.updateTask(id: conversationID, detail: "Approval unavailable", status: .needsAttention)+ self.updateConversation(id: conversationID, detail: "Approval unavailable", status: .needsAttention)self.activeAgentIDs.remove(conversationID)- self.syncPrimaryTaskPausedFlag()+ self.syncPrimaryConversationPausedFlag()}return}@@ -986,9 +1144,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {await MainActor.run {guard let self else { return }guard let result else {- self.updateTask(id: conversationID, detail: "Could not resume the task", status: .needsAttention)+ self.updateConversation(id: conversationID, detail: "Could not resume the task", status: .needsAttention)self.activeAgentIDs.remove(conversationID)- self.syncPrimaryTaskPausedFlag()+ self.syncPrimaryConversationPausedFlag()return}self.handleCommandRunResult(@@ -1002,15 +1160,15 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}/// User denied a pending permission. The harness loop already exited at the consent gate, so this- /// stops the task into a resumable (paused) state — resuming re-runs it and asks again. A Live-path+ /// stops the conversation into a resumable (paused) state — resuming re-runs it and asks again. A Live-path/// consent is also told "no" so it stops re-trying.func denyPermissionGate(id conversationID: String) {- guard let task = task(withID: conversationID),- task.status == .waitingForPermission else {+ guard let conversation = conversation(withID: conversationID),+ conversation.status == .waitingForPermission else {return}- if task.metadata["live.shellConsent"] == "true" {+ if conversation.metadata["live.shellConsent"] == "true" {Task { [liveController] inawait liveController.resolvePendingConsent(approved: false, alwaysAllow: false)}@@ -1026,7 +1184,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {status: .paused)activeAgentIDs.remove(conversationID)- syncPrimaryTaskPausedFlag()+ syncPrimaryConversationPausedFlag()}func updateNotchCommandInputTextHeight(_ height: CGFloat) {@@ -1048,7 +1206,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}/// Desktop pointer spawning is temporarily disabled. Submissions no longer launch a- /// traveling cursor; accent assignment and task tracking continue without one. Flip to re-enable.+ /// traveling cursor; accent assignment and conversation tracking continue without one. Flip to re-enable.private static let spawnPointersEnabled = falseprivate func beginSpawn(@@ -1060,7 +1218,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {guard Self.spawnPointersEnabled else { return nil }let spawnID = UUID().uuidString- let displayText = Self.taskLabel(for: text)+ let displayText = Self.conversationLabel(for: text)let labelText = label ?? Self.collapsedDisplayText(for: text)let spawnAccentIndex: Intif let accentIndex {@@ -1147,7 +1305,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {spawnState.finishedAt = Date()// Keep the cursor visible whenever there is a response to read — a clarification, a wait, a- // failure, OR a completed task that produced a summary (e.g. "Now playing …"). Only a+ // failure, OR a completed conversation that produced a summary (e.g. "Now playing …"). Only a// completed action with no summary fades out, so the user always gets to see the result on// the cursor and several recent results can stay on screen at once.let hasReadableResult = UserQuerySpawnLifecycle.keepsVisibleResult(for: result.threadStatus)@@ -1206,10 +1364,10 @@ 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.+ /// Only an EXPLICIT spawn selection force-targets an existing conversation. A bare new prompt is never+ /// auto-attached to the latest conversation just because it is the most recent — that route is what made a+ /// new command hijack a running conversation. Implicit follow-up matching is left entirely to the typed+ /// follow-up resolver, which decides against conversation content rather than recency.private func promptSubmissionFollowUpTarget() -> (spawnID: String, conversationID: String)? {guard let selectedSpawnID,let conversationID = conversationIDForInteractableSpawn(id: selectedSpawnID) else {@@ -1235,13 +1393,13 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- private func prependTask(_ task: UserQueryConversation) {- notchTasks.removeAll { $0.id == task.id }- notchTasks.insert(task, at: 0)- if notchTasks.count > Self.notchTaskDisplayLimit {- notchTasks = Array(notchTasks.prefix(Self.notchTaskDisplayLimit))+ private func prependConversation(_ conversation: UserQueryConversation) {+ notchConversations.removeAll { $0.id == conversation.id }+ notchConversations.insert(conversation, at: 0)+ if notchConversations.count > Self.notchConversationDisplayLimit {+ notchConversations = Array(notchConversations.prefix(Self.notchConversationDisplayLimit))}- taskStore.upsertTask(task)+ conversationStore.upsertConversation(conversation)}private func clearSubmissionInputs() {@@ -1254,76 +1412,79 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {promptState.isVoiceInputActive = false}- private func taskForSubmittedCommand(+ private func conversationForSubmittedCommand(text: String,- matchedTaskID: String?,+ matchedConversationID: String?,reservedAccentIndex: Int? = nil) -> UserQueryConversation {- if let matchedTaskID,- var task = task(withID: matchedTaskID) {+ if let matchedConversationID,+ var conversation = conversation(withID: matchedConversationID) {if let reservedAccentIndex {- task.accentIndex = UserQueryAccentPalette.normalizedIndex(reservedAccentIndex)+ conversation.accentIndex = UserQueryAccentPalette.normalizedIndex(reservedAccentIndex)}- // 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+ // A follow-up to a conversation whose loop is still running is queued into it upstream (it never+ // reaches here). A matched conversation 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.//// The chin shows the conversation's latest line (`detail`), so seed both the command and that// line with what the user just sent; the agent's narration and reply overwrite `detail` from// there. (`appendAgentEvent` also writes these for the resume path, but the inject path seeds// straight here, so set them at the source too.)- task.commandText = text- task.detail = text- task.status = .running- task.updatedAt = Date()+ conversation.commandText = text+ conversation.detail = text+ conversation.status = .running+ conversation.updatedAt = Date()// Restamp the run-start: a resumed run's elapsed time should measure this run, not the idle- // gap since the task was first created (e.g. a task that failed, sat for hours, then resumed).- task.createdAt = Date()- // This branch seeds the task straight to running without going through `updateTask`, so it+ // gap since the conversation was first created (e.g. a conversation that failed, sat for hours, then resumed).+ conversation.createdAt = Date()+ // This branch seeds the conversation straight to running without going through `updateConversation`, so it// must apply the same fresh-run metadata reset (see `clearRunMetadata`): otherwise a replied-to// thread keeps its stale "seen" (its next terminal state never re-surfaces) and "streaming// answer" flag (the new streamed reply appends onto the old answer).- Self.clearRunMetadata(&task.metadata)- conversationsStreamingAnswer.remove(task.id)- notchAccentIndex = UserQueryAccentPalette.normalizedIndex(task.accentIndex)- prependTask(task)- return task+ Self.clearRunMetadata(&conversation.metadata)+ conversationsStreamingAnswer.remove(conversation.id)+ notchAccentIndex = UserQueryAccentPalette.normalizedIndex(conversation.accentIndex)+ prependConversation(conversation)+ return conversation}- let taskLabel = Self.taskLabel(for: text)+ let conversationLabel = Self.conversationLabel(for: text)let nextAccentIndex = reservedAccentIndex.map(UserQueryAccentPalette.normalizedIndex)?? nextRoundRobinAccentIndex()notchAccentIndex = nextAccentIndex- let task = UserQueryConversation(+ let conversation = UserQueryConversation(id: UUID().uuidString,- title: taskLabel,+ title: conversationLabel,detail: text,commandText: text,status: .running,accentIndex: nextAccentIndex)- prependTask(task)- return task+ prependConversation(conversation)+ return conversation}- private func taskForDroppedAssets() -> UserQueryConversation {- if let lastActiveTaskID,- activeAgentIDs.contains(lastActiveTaskID),- let task = task(withID: lastActiveTaskID) {- return task+ private func conversationForDroppedAssets() -> UserQueryConversation {+ // A drop only ever attaches to one of the user's own conversations — never to a system-driven row+ // like tool setup, which has no goal to fold an asset into.+ if let lastActiveConversationID,+ activeAgentIDs.contains(lastActiveConversationID),+ let conversation = conversation(withID: lastActiveConversationID),+ conversation.isUserControllable {+ return conversation}- if let activeTask = notchTasks.first(where: { $0.status == .running || $0.status == .paused }) {- return activeTask+ if let activeConversation = notchConversations.first(where: { $0.isUserControllable && ($0.status == .running || $0.status == .paused) }) {+ return activeConversation}- if let recentTask = notchTasks.first {- return recentTask+ if let recentConversation = notchConversations.first(where: { $0.isUserControllable }) {+ return recentConversation}let nextAccentIndex = nextRoundRobinAccentIndex()notchAccentIndex = nextAccentIndex- let task = UserQueryConversation(+ let conversation = UserQueryConversation(id: UUID().uuidString,title: "Uploaded assets",detail: "Assets attached",@@ -1331,17 +1492,17 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {status: .needsAttention,accentIndex: nextAccentIndex)- prependTask(task)- return task+ prependConversation(conversation)+ return conversation}- private func task(withID conversationID: String) -> UserQueryConversation? {- if let task = notchTasks.first(where: { $0.id == conversationID }) {- return task+ private func conversation(withID conversationID: String) -> UserQueryConversation? {+ if let conversation = notchConversations.first(where: { $0.id == conversationID }) {+ return conversation}- return taskStore- .loadRecentTasks(limit: max(Self.notchTaskDisplayLimit, Self.followUpCandidateLimit) * 2)+ return conversationStore+ .loadRecentConversations(limit: max(Self.notchConversationDisplayLimit, Self.followUpCandidateLimit) * 2).first { $0.id == conversationID }}@@ -1351,12 +1512,12 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {source: AppHarnessTurnSource = .typedPrompt,spawnID: String? = nil) -> UserQueryCommandContext? {- guard let task = task(withID: conversationID) else { return nil }+ guard let conversation = conversation(withID: conversationID) else { return nil }return UserQueryCommandContext(- task: task,- recentEvents: Array(taskStore.loadEvents(conversationID: conversationID).suffix(10)),- assets: taskStore.loadAssets(conversationID: conversationID),+ conversation: conversation,+ recentEvents: Array(conversationStore.loadEvents(conversationID: conversationID).suffix(10)),+ assets: conversationStore.loadAssets(conversationID: conversationID),isFollowUp: isFollowUp,turnSource: source,spawnProgressChanged: runProgressHandler(conversationID: conversationID, spawnID: spawnID),@@ -1364,9 +1525,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {)}- /// Streams the agent's live narration into the running task's status line — the planner's per-step+ /// Streams the agent's live narration into the running conversation's status line — the planner's per-step/// reason as it works ("Working out what you need", the restated goal, each tool's one-line summary)- /// — so the notch shows what the model is doing now instead of a static seed. The task title keeps+ /// — so the notch shows what the model is doing now instead of a static seed. The conversation title keeps/// showing the user's prompt; only the status subtext advances. When a spawn pointer is present its/// cursor label follows the same narration. Returned unconditionally (even with pointers disabled)/// so the status line always advances past its "Thinking" seed.@@ -1377,7 +1538,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {return { [weak self] update inguard let self else { return }- // A streamed answer chunk accumulates onto the task's detail (the chin and the open row both+ // A streamed answer chunk accumulates onto the conversation's detail (the chin and the open row both// read it), so the reply types itself out. It bypasses the label path below, which replaces.if let answerDelta = update.answerDelta {self.appendStreamedAnswer(conversationID: conversationID, delta: answerDelta, spawnID: spawnID)@@ -1385,8 +1546,8 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}let label = update.label?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""- if !label.isEmpty, self.task(withID: conversationID)?.status == .running {- self.updateTask(id: conversationID, detail: label)+ if !label.isEmpty, self.conversation(withID: conversationID)?.status == .running {+ self.updateConversation(id: conversationID, detail: label)}if let spawnID {self.updateSpawn(@@ -1399,16 +1560,16 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- /// Append one streamed chunk of the assistant's final reply to the running task's detail. The first+ /// Append one streamed chunk of the assistant's final reply to the running conversation's detail. The first/// chunk clears the per-step "Thinking" status and flips the streaming flag so the chin shows the- /// growing answer instead of the prompt; later chunks accumulate onto it. No-op once the task has+ /// growing answer instead of the prompt; later chunks accumulate onto it. No-op once the conversation has/// left the running state (a late chunk after completion must not reopen the row's status line).private func appendStreamedAnswer(conversationID: String, delta: String, spawnID: String?) {- guard let task = task(withID: conversationID), task.status == .running else { return }+ guard let conversation = conversation(withID: conversationID), conversation.status == .running else { return }let isStreaming = conversationsStreamingAnswer.contains(conversationID)- let newDetail = isStreaming ? task.detail + delta : delta+ let newDetail = isStreaming ? conversation.detail + delta : deltaconversationsStreamingAnswer.insert(conversationID)- updateTask(id: conversationID, detail: newDetail)+ updateConversation(id: conversationID, detail: newDetail)if let spawnID {updateSpawn(id: spawnID, label: newDetail)}@@ -1424,26 +1585,29 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}private func followUpCandidates() -> [UserQueryFollowUpCandidate] {- let recent = taskStore.loadRecentTasks(limit: Self.followUpCandidateLimit)+ let recent = conversationStore.loadRecentConversations(limit: Self.followUpCandidateLimit)+ // The follow-up resolver only ever continues one of the user's own conversations: a system-driven+ // row (tool setup) is never a target for the user's next message.return Self.activeFollowUpCandidates(from: recent, now: Date())- .map { task in- let recentEvents = taskStore- .loadEvents(conversationID: task.id)+ .filter { $0.isUserControllable }+ .map { conversation in+ let recentEvents = conversationStore+ .loadEvents(conversationID: conversation.id).suffix(6).map { event inSelf.truncated("\(event.role.rawValue): \(event.text)", maxLength: 220)}- let assetNames = taskStore- .loadAssets(conversationID: task.id)+ let assetNames = conversationStore+ .loadAssets(conversationID: conversation.id).suffix(8).map(\.displayName)return UserQueryFollowUpCandidate(- conversationID: task.id,- title: task.title,- detail: task.detail,- commandText: task.commandText,- status: task.status,- updatedAt: task.updatedAt,+ conversationID: conversation.id,+ title: conversation.title,+ detail: conversation.detail,+ commandText: conversation.commandText,+ status: conversation.status,+ updatedAt: conversation.updatedAt,recentEvents: recentEvents,assetNames: assetNames)@@ -1455,9 +1619,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)guard !trimmedText.isEmpty else { return nil }- let sequence = taskStore.loadEvents(conversationID: conversationID).count+ let sequence = conversationStore.loadEvents(conversationID: conversationID).countlet eventID = UUID().uuidString- taskStore.appendEvent(+ conversationStore.appendEvent(UserQueryConversationEvent(id: eventID,conversationID: conversationID,@@ -1468,18 +1632,18 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {)// The chin shows the latest line of the conversation, and `detail` holds it. A user message is the// newest line the instant it is sent, so write it here — the one chokepoint every user turn crosses- // (fresh, follow-up, resumed, or folded into a still-running task via the inject path) — rather than+ // (fresh, follow-up, resumed, or folded into a still-running conversation via the inject path) — rather than// at each call site, where a path that forgets leaves the chin reading back an older line. Clear any// in-flight streamed answer so the agent's next reply replaces this message instead of appending to// it; keep `commandText` in sync for the other surfaces (prompt pill, follow-up matching).if role == .user {conversationsStreamingAnswer.remove(conversationID)- updateTask(id: conversationID, commandText: trimmedText, detail: trimmedText)+ updateConversation(id: conversationID, commandText: trimmedText, detail: trimmedText)}return eventID}- /// The single place a lifecycle transition announces itself. It sets the task's live status line+ /// The single place a lifecycle transition announces itself. It sets the conversation's live status line/// from the typed activity, records the event in the in-app conversation store, and appends the/// same line to `thread.md` — so the conversation record stays the complete history we can render/// back to the user. New transitions pass a different `UserQueryActivity` kind; nothing else moves.@@ -1490,14 +1654,14 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {liveDetail: String? = nil,metadata: [String: String]? = nil) {- updateTask(id: conversationID, detail: liveDetail ?? activity.displayText, status: status, metadata: metadata)+ updateConversation(id: conversationID, detail: liveDetail ?? activity.displayText, status: status, metadata: metadata)// In-app event store keeps plain text (structured data for the conversation view); thread.md// gets the icon-prefixed markdown line._ = appendAgentEvent(conversationID: conversationID, role: .system, text: activity.displayText)recordThreadActivity(conversationID: conversationID, activity)}- /// Appends a typed activity line to the task's `thread.md` conversation record. The thread file+ /// Appends a typed activity line to the conversation's `thread.md` conversation record. The thread file/// already exists from the run, so this only ever appends (off the main thread — small file IO).private func recordThreadActivity(conversationID: String, _ activity: UserQueryActivity) {let line = activity.transcriptLine@@ -1506,7 +1670,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- private func updateTask(+ private func updateConversation(id: String,title: String? = nil,commandText: String? = nil,@@ -1514,41 +1678,41 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {status: UserQueryConversationStatus? = nil,metadata: [String: String]? = nil) {- guard let index = notchTasks.firstIndex(where: { $0.id == id }) else { return }+ guard let index = notchConversations.firstIndex(where: { $0.id == id }) else { return }- var task = notchTasks[index]- let wasRunning = task.status == .running+ var conversation = notchConversations[index]+ let wasRunning = conversation.status == .runningif let title {- task.title = title+ conversation.title = title}if let commandText {- task.commandText = commandText+ conversation.commandText = commandText}if let detail {- task.detail = detail+ conversation.detail = detail}if let status {- task.status = status+ conversation.status = status}if let metadata {- task.metadata = metadata+ conversation.metadata = metadata}- // A stopped task re-entering running begins a fresh run: clear the per-run metadata flags and+ // A stopped conversation re-entering running begins a fresh run: clear the per-run metadata flags and// restamp the run-start so elapsed measures this run, not the idle gap before it. Gated on the// prior status so the planner's per-step "still running" updates (and streamed-answer deltas,// which re-pass the streaming flag) don't keep resetting it mid-run.if status == .running, !wasRunning {- Self.clearRunMetadata(&task.metadata)+ Self.clearRunMetadata(&conversation.metadata)conversationsStreamingAnswer.remove(id)- task.createdAt = Date()+ conversation.createdAt = Date()}- task.updatedAt = Date()- notchTasks[index] = task- taskStore.upsertTask(task)- syncPrimaryTaskPausedFlag()+ conversation.updatedAt = Date()+ notchConversations[index] = conversation+ conversationStore.upsertConversation(conversation)+ syncPrimaryConversationPausedFlag()}- /// How recently a running task must have last advanced to auto-resume itself on relaunch. Inside the+ /// How recently a running conversation 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@@ -1557,7 +1721,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {/// follow-up routing runs through the typed resolver, but only over conversations touched within this/// window: one left idle longer is treated as closed, so an unrelated later turn starts a fresh/// conversation instead of folding into stale work (observed live: "hi" folding into a day-old- /// video-clip task that had never reached a terminal state). This gates eligibility, not selection —+ /// video-clip conversation that had never reached a terminal state). This gates eligibility, not selection —/// among eligible candidates the resolver still decides by content, never by recency. An explicit/// Reply or spawn selection bypasses this entirely; the user can always continue an old thread on purpose.private static let followUpStalenessWindow: TimeInterval = 30 * 60@@ -1565,47 +1729,51 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {/// Conversations recent enough to continue with a new turn. Sorted-by-recency input is filtered to the/// staleness window; everything older is considered closed and dropped from the follow-up pool.static func activeFollowUpCandidates(- from tasks: [UserQueryConversation],+ from conversations: [UserQueryConversation],now: Date) -> [UserQueryConversation] {- tasks.filter { now.timeIntervalSince($0.updatedAt) <= followUpStalenessWindow }+ conversations.filter { now.timeIntervalSince($0.updatedAt) <= followUpStalenessWindow }}- /// 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+ /// Maps persisted conversations into their post-relaunch state and collects the IDs to auto-resume. A relaunch+ /// tears down every live loop, so an in-flight conversation 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: [UserQueryConversation],+ static func restoredConversations(+ from conversations: [UserQueryConversation],now: Date- ) -> (tasks: [UserQueryConversation], autoResumeIDs: [String]) {+ ) -> (conversations: [UserQueryConversation], autoResumeIDs: [String]) {var autoResumeIDs: [String] = []- let restored = tasks.map { task -> UserQueryConversation in- switch task.status {+ let restored = conversations.map { conversation -> UserQueryConversation in+ // A system-driven row (tool setup) has no harness loop behind it, so it is never auto-resumed+ // through the command handler. The install run reconciles it on launch (see+ // `reconcileInterruptedSystemSetup`); here it just carries through untouched.+ guard conversation.isUserControllable else { return conversation }+ switch conversation.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+ if now.timeIntervalSince(conversation.updatedAt) <= autoResumeStalenessWindow {+ autoResumeIDs.append(conversation.id)+ return conversation}- var timedOut = task+ var timedOut = conversationtimedOut.status = .timedOuttimedOut.detail = "Timed out — resume"return timedOutcase .waitingForClarification, .waitingForReview, .waitingForPermission:// The loop that was blocked on the user is gone, but the gate still stands — the question or- // the pending approval is persisted in the task's continuation (and shown in its `detail`).+ // the pending approval is persisted in the conversation's continuation (and shown in its `detail`).// Keep it in that same waiting state rather than collapsing it to paused: pausing is a- // deliberate user action (Stop on a running task), never something a relaunch does on the+ // deliberate user action (Stop on a running conversation), never something a relaunch does on the// user's behalf. A waiting-on-user row keeps its Reply button (and the attention glyph); a// permission row keeps its Approve / Deny banner, and approving re-runs the persisted call- // with consent granted. Answering or approving continues the task with the context intact.- return task+ // with consent granted. Answering or approving continues the conversation with the context intact.+ return conversationdefault:// paused, completed, failed, timedOut, interrupted, needsAttention, chatting: unchanged.- return task+ return conversation}}return (restored, autoResumeIDs)@@ -1615,38 +1783,38 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {conversationID: String,result: UserQueryCommandHandlingResult) {- syncPrimaryTaskPausedFlag()+ syncPrimaryConversationPausedFlag()if promptState.isActive {- if lastActiveTaskID == conversationID {- lastActiveTaskID = notchTasks.first?.id+ if lastActiveConversationID == conversationID {+ lastActiveConversationID = notchConversations.first?.id}return}- if let runningTask = notchTasks.first(where: { activeAgentIDs.contains($0.id) && $0.status == .running }) {+ if let runningConversation = notchConversations.first(where: { activeAgentIDs.contains($0.id) && $0.status == .running }) {promptState.leadingSignalLevel = .thinking- promptState.promptText = runningTask.title+ promptState.promptText = runningConversation.titlereturn}- if let pausedTask = notchTasks.first(where: { activeAgentIDs.contains($0.id) && $0.status == .paused }) {+ if let pausedConversation = notchConversations.first(where: { activeAgentIDs.contains($0.id) && $0.status == .paused }) {promptState.leadingSignalLevel = .idle- promptState.promptText = pausedTask.title+ promptState.promptText = pausedConversation.titlereturn}promptState.leadingSignalLevel = result.status == .completed ? .ready : .idle- promptState.promptText = result.taskLabel ?? result.summary- if lastActiveTaskID == conversationID {- lastActiveTaskID = notchTasks.first?.id+ promptState.promptText = result.conversationLabel ?? result.summary+ if lastActiveConversationID == conversationID {+ lastActiveConversationID = notchConversations.first?.id}}- private func syncPrimaryTaskPausedFlag() {- isCurrentTaskPaused = notchTasks.first?.status == .paused+ private func syncPrimaryConversationPausedFlag() {+ isCurrentConversationPaused = notchConversations.first?.status == .paused}- private static func taskStatus(for result: UserQueryCommandHandlingResult) -> UserQueryConversationStatus {+ private static func conversationStatus(for result: UserQueryCommandHandlingResult) -> UserQueryConversationStatus {result.threadStatus}@@ -1680,25 +1848,25 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}private func nextRoundRobinAccentIndex() -> Int {- guard let mostRecentAccentIndex = spawnStates.last?.accentIndex ?? notchTasks.first?.accentIndex else {+ guard let mostRecentAccentIndex = spawnStates.last?.accentIndex ?? notchConversations.first?.accentIndex else {return UserQueryAccentPalette.firstIndex}return UserQueryAccentPalette.index(after: mostRecentAccentIndex)}- /// The task's title is the user's prompt, whitespace-collapsed. It is NOT hard-truncated here: every+ /// The conversation's title is the user's prompt, whitespace-collapsed. It is NOT hard-truncated here: every/// place that shows it (the collapsed bar, the prompt pill, each expanded row) renders it on a single/// line and tail-truncates to its own available width, so the expanded row title spans the full row/// rather than being clipped to a fixed character budget. Capped only by `collapsedDisplayText` so a/// runaway prompt can't blob through the store.- private static func taskLabel(for text: String) -> String {+ private static func conversationLabel(for text: String) -> String {let collapsed = collapsedDisplayText(for: text)- return collapsed.isEmpty ? "New task" : collapsed+ return collapsed.isEmpty ? "New conversation" : collapsed}/// A cursor label stays a short status line; cap it so a long tool result never blobs over the- /// screen. The overlay wraps within this, and the full text is always in the notch task list.+ /// screen. The overlay wraps within this, and the full text is always in the notch conversation list.private static let maxSpawnLabelLength = 200private static func collapsedDisplayText(for text: String) -> String {@@ -1754,7 +1922,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {assetID: String,displayName: String) -> URL? {- guard let assetsDirectory = taskAssetDirectory(conversationID: conversationID) else { return nil }+ guard let assetsDirectory = conversationAssetDirectory(conversationID: conversationID) else { return nil }do {try FileManager.default.createDirectory(@@ -1776,7 +1944,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- private static func taskAssetDirectory(conversationID: String) -> URL? {+ private static func conversationAssetDirectory(conversationID: String) -> URL? {guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory,in: .userDomainMaskdiff --git a/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift b/apps/Donkey/Sources/DonkeyAI/LocalConversationFollowUpResolver.swiftsimilarity index 98%rename from apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swiftrename to apps/Donkey/Sources/DonkeyAI/LocalConversationFollowUpResolver.swiftindex 9b1041de..81bbc3f2 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalConversationFollowUpResolver.swift@@ -74,7 +74,7 @@ public protocol UserQueryFollowUpResolving: Sendable {func resolveFollowUp(_ request: UserQueryFollowUpResolverRequest) async -> UserQueryFollowUpResolverResult}-public struct HostedTaskFollowUpResolver: UserQueryFollowUpResolving {+public struct HostedConversationFollowUpResolver: UserQueryFollowUpResolving {public static let schemaID = "task_followup_resolution_v1"public var router: AIModelRouter@@ -153,7 +153,7 @@ public struct HostedTaskFollowUpResolver: UserQueryFollowUpResolving {return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)}- let decision = try JSONDecoder().decode(LocalLLMTaskFollowUpDecision.self, from: decisionData)+ let decision = try JSONDecoder().decode(LocalLLMConversationFollowUpDecision.self, from: decisionData)let validCandidateIDs = Set(request.candidates.map(\.conversationID))let conversationID = decision.isFollowUp && validCandidateIDs.contains(decision.conversationID) ? decision.conversationID : nilreturn UserQueryFollowUpResolverResult(@@ -357,7 +357,7 @@ public struct HostedTaskFollowUpResolver: UserQueryFollowUpResolving {}}-private struct LocalLLMTaskFollowUpDecision: Codable, Equatable, Sendable {+private struct LocalLLMConversationFollowUpDecision: Codable, Equatable, Sendable {var isFollowUp: Boolvar conversationID: Stringvar confidence: Doublediff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swiftindex 378a0f0b..5757c5aa 100644--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swift@@ -26,7 +26,7 @@ public enum UserQueryCopy {return normalizedText}- public static func isTaskDisplayText(_ text: String) -> Bool {+ public static func isConversationDisplayText(_ text: String) -> Bool {let normalizedText = normalizedDisplayText(text)return !normalizedText.isEmpty &&normalizedText != defaultPromptPlaceholderdiff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swiftindex 173cd841..2440670d 100644--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swift@@ -24,6 +24,17 @@ public extension UserQueryConversationStatus {}}+/// Who started a conversation. `user` is the default — anything the person typed, spoke, or resumed,+/// and which they own (stop, resume, reply, dismiss). `system` is started by the app itself (e.g. the+/// first-run download of the bundled CLI tools): the person watches its progress like any other+/// conversation, but it runs to completion under the app's control and is never user-stoppable or+/// -dismissable. The distinction is typed rather than inferred so the "can't touch it" rule holds by+/// construction everywhere — the row controls, the lifecycle methods, follow-up routing, and restore.+public enum UserQueryConversationOrigin: String, Codable, Equatable, Sendable {+ case user+ case system+}+public struct UserQueryConversation: Codable, Equatable, Identifiable, Sendable {public var id: Stringpublic var title: String@@ -31,6 +42,7 @@ public struct UserQueryConversation: Codable, Equatable, Identifiable, Sendablepublic var commandText: Stringpublic var status: UserQueryConversationStatuspublic var accentIndex: Int+ public var origin: UserQueryConversationOriginpublic var createdAt: Datepublic var updatedAt: Datepublic var metadata: [String: String]@@ -42,6 +54,7 @@ public struct UserQueryConversation: Codable, Equatable, Identifiable, SendablecommandText: String = "",status: UserQueryConversationStatus,accentIndex: Int,+ origin: UserQueryConversationOrigin = .user,createdAt: Date = Date(),updatedAt: Date = Date(),metadata: [String: String] = [:]@@ -52,12 +65,20 @@ public struct UserQueryConversation: Codable, Equatable, Identifiable, Sendableself.commandText = commandTextself.status = statusself.accentIndex = accentIndex+ self.origin = originself.createdAt = createdAtself.updatedAt = updatedAtself.metadata = metadata}}+public extension UserQueryConversation {+ /// Whether the person may control this conversation — stop it, resume it, reply to it, or dismiss it.+ /// Only conversations they started are theirs to control; a system-driven one (tool setup) is watched,+ /// not operated. Every control surface and lifecycle hook gates on this, so the rule can't be missed.+ var isUserControllable: Bool { origin == .user }+}+public extension UserQueryConversation {/// The single line the collapsed chin shows for this task — always the latest line of the/// conversation. `detail` is the one field that carries it: the user's message the instant they senddiff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swiftindex 7aab22b8..57804e7e 100644--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swift+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swift@@ -69,7 +69,7 @@ public struct UserQueryNotchMetrics: Equatable, Sendable {public static let maximumInferredVoidWidth: CGFloat = 220public static let defaultScreenWidth: CGFloat = 1512public static let minimumPhysicalVoidHeight: CGFloat = 30- public static let expandedTaskContentHeight: CGFloat = 280+ public static let expandedConversationContentHeight: CGFloat = 280public static let inputHorizontalMargin: CGFloat = 14public static let compactCommandContentVerticalPadding: CGFloat = 30/// How long the open host window lingers after the surface starts collapsing, before it snaps todiff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swiftindex d1a753b2..23f3e2b9 100644--- a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift@@ -815,6 +815,8 @@ public struct UserQueryNotchStatusView: View {/// Trailing room a row's text leaves for the pinned top-right controls, by control set: a lone Close/// (or Stop) button, or a Resume + Close pair. Permission rows carry their own banner controls.private func controlsReserve(for conversation: UserQueryConversation) -> CGFloat {+ // A system-driven row carries no controls (see `topRightControls`), so its text spans the full row.+ if !conversation.isUserControllable { return 0 }if conversation.status == .waitingForPermission { return 0 }return rowShowsControlPair(conversation) ? 74 : 44}@@ -822,6 +824,7 @@ public struct UserQueryNotchStatusView: View {/// Whether a row shows a two-button pair (Resume + Close, or Reply + Close) vs a single Close/Stop —/// mirrors `stateControls`, so the title/subtext reserve the right trailing room for the controls.private func rowShowsControlPair(_ conversation: UserQueryConversation) -> Bool {+ guard conversation.isUserControllable else { return false }switch conversation.status {case .paused, .interrupted, .timedOut, .waitingForClarification, .waitingForReview:return true@@ -934,7 +937,9 @@ public struct UserQueryNotchStatusView: View {// eased highlight would land ~0.12s later and read as "scroll first, then select."// Snapping lands the selection with the scroll, so the row reads as selected first..onTapGesture {- // Every row is repliable. Tapping the active thread again leaves reply mode; tapping any+ // A system-driven row (tool setup) isn't repliable — tapping it does nothing.+ guard conversation.isUserControllable else { return }+ // Every user row is repliable. Tapping the active thread again leaves reply mode; tapping any// other row pins it and focuses the composer, so the user can just start typing. (A running// or permission-gated thread takes the message as a queued follow-up; the rest resume.)if isReplyTarget {@@ -967,12 +972,18 @@ public struct UserQueryNotchStatusView: View {/// running → stop; paused → resume + close; everything else → close, so any conversation can be deleted.@ViewBuilderprivate func topRightControls(_ conversation: UserQueryConversation) -> some View {- switch conversation.status {- case .waitingForPermission:- // The permission banner carries its own Approve / Deny; the row needs no extra control.+ if !conversation.isUserControllable {+ // A system-driven row (tool setup) is the app's to run: the user watches it, but it carries no+ // Stop / Resume / Close — it can't be stopped or dismissed by hand.EmptyView()- default:- stateControls(for: conversation)+ } else {+ switch conversation.status {+ case .waitingForPermission:+ // The permission banner carries its own Approve / Deny; the row needs no extra control.+ EmptyView()+ default:+ stateControls(for: conversation)+ }}}@@ -1412,7 +1423,7 @@ public struct UserQueryNotchStatusView: View {static func conversationDisplayText(state: UserQueryState) -> String? {let text = UserQueryCopy.normalizedDisplayText(state.promptText)- guard UserQueryCopy.isTaskDisplayText(text) else {+ guard UserQueryCopy.isConversationDisplayText(text) else {return nil}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex cc4a77e3..45571635 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -218,7 +218,7 @@ struct AIHarnessAdapterTests {data: Data(#"{"output_text":"{\"isFollowUp\":true,\"agentID\":\"task-1\",\"confidence\":0.82,\"reason\":\"same task\"}"}"#.utf8),statusCode: 200)- let resolver = HostedTaskFollowUpResolver(+ let resolver = HostedConversationFollowUpResolver(configuration: DonkeyBackendInferenceConfiguration(baseURL: URL(string: "https://donkey.example")!,clientID: "client-1"diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/TaskFollowUpInjectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationFollowUpInjectionTests.swiftsimilarity index 97%rename from apps/Donkey/Tests/DonkeyRuntimeTests/TaskFollowUpInjectionTests.swiftrename to apps/Donkey/Tests/DonkeyRuntimeTests/ConversationFollowUpInjectionTests.swiftindex f42d79eb..5ff075e8 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/TaskFollowUpInjectionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationFollowUpInjectionTests.swift@@ -9,7 +9,7 @@ import Testing/// Covers the task-lifecycle changes: follow-up injection into a running loop (instead of restarting it),/// concurrent loops on one coordinator, the timed-out status, and the relaunch staleness mapping.@Suite-struct TaskFollowUpInjectionTests {+struct ConversationFollowUpInjectionTests {// A stateless planner for the injection test: complete once the injected instruction has been folded// into the world model, otherwise queue one follow-up and take a no-op step. Keying off the fact (not// a call counter) keeps it a value type.@@ -273,14 +273,14 @@ struct TaskFollowUpInjectionTests {let paused = task("paused", .paused, ageMinutes: 5)let completed = task("done", .completed, ageMinutes: 5)- let result = UserQueryOverlayModel.restoredTasks(+ let result = UserQueryOverlayModel.restoredConversations(from: [recentRunning, staleRunning, waiting, review, permission, paused, completed],now: now)// Only the recently-running task auto-resumes; it keeps running.#expect(result.autoResumeIDs == ["recent"])- func status(_ id: String) -> UserQueryConversationStatus? { result.tasks.first { $0.id == id }?.status }+ func status(_ id: String) -> UserQueryConversationStatus? { result.conversations.first { $0.id == id }?.status }#expect(status("recent") == .running)#expect(status("stale") == .timedOut) // too old to auto-run → retryable row#expect(status("waiting") == .waitingForClarification) // still asking the user → comes back as a Reply row@@ -289,9 +289,9 @@ struct TaskFollowUpInjectionTests {#expect(status("paused") == .paused) // user-paused (Stop) stays paused#expect(status("done") == .completed) // terminal states untouched// The waiting rows keep their persisted detail (the question) rather than a bare "Paused".- #expect(result.tasks.first { $0.id == "waiting" }?.detail == "d")+ #expect(result.conversations.first { $0.id == "waiting" }?.detail == "d")// The persisted updatedAt is preserved so elapsed-time stays the real run duration.- #expect(result.tasks.first { $0.id == "stale" }?.updatedAt == staleRunning.updatedAt)+ #expect(result.conversations.first { $0.id == "stale" }?.updatedAt == staleRunning.updatedAt)}@MainActordiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolsSetupConversationTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolsSetupConversationTests.swiftnew file mode 100644index 00000000..f255a4c8--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolsSetupConversationTests.swift@@ -0,0 +1,68 @@+import DonkeyContracts+import Foundation+import Testing++@testable import Donkey++/// The first-run tool-bundle download surfaces as a normal-looking conversation, but it is system-driven:+/// the app runs it to completion and the user can't stop, resume, reply to, or dismiss it. That rule is+/// carried by `origin == .system` (so `isUserControllable` is false), and the relaunch restore must never+/// hand a system row to the harness auto-resume — it has no loop behind it. These lock both.+@Suite+@MainActor+struct SystemToolsSetupConversationTests {+ private func conversation(+ id: String,+ status: UserQueryConversationStatus,+ origin: UserQueryConversationOrigin,+ ageMinutes: Double = 1,+ now: Date = Date()+ ) -> UserQueryConversation {+ UserQueryConversation(+ id: id,+ title: id,+ detail: "d",+ status: status,+ accentIndex: 0,+ origin: origin,+ updatedAt: now.addingTimeInterval(-ageMinutes * 60)+ )+ }++ @Test+ func userConversationsAreControllableAndSystemOnesAreNot() {+ // The default origin is `.user`, so every existing call site stays user-controllable.+ #expect(conversation(id: "u", status: .running, origin: .user).isUserControllable)+ #expect(!conversation(id: "s", status: .running, origin: .system).isUserControllable)+ }++ @Test+ func restoredSystemConversationIsNeverAutoResumed() {+ let now = Date()+ // A recently-running USER row auto-resumes; a recently-running SYSTEM row never does, even though+ // it is just as fresh — it has no harness loop to resume, so the install run reconciles it instead.+ let userRow = conversation(id: "user", status: .running, origin: .user, ageMinutes: 1, now: now)+ let systemRow = conversation(id: "system", status: .running, origin: .system, ageMinutes: 1, now: now)++ let result = UserQueryOverlayModel.restoredConversations(from: [userRow, systemRow], now: now)++ #expect(result.autoResumeIDs == ["user"])+ #expect(!result.autoResumeIDs.contains("system"))+ }++ @Test+ func staleRunningSystemConversationCarriesThroughUnchanged() {+ let now = Date()+ // A stale running USER row is downgraded to the retryable `.timedOut`. A system row bypasses that+ // mapping entirely and carries through as-is — the install run, not the restore, decides its fate.+ let staleUser = conversation(id: "user", status: .running, origin: .user, ageMinutes: 120, now: now)+ let staleSystem = conversation(id: "system", status: .running, origin: .system, ageMinutes: 120, now: now)++ let result = UserQueryOverlayModel.restoredConversations(from: [staleUser, staleSystem], now: now)++ func status(_ id: String) -> UserQueryConversationStatus? { result.conversations.first { $0.id == id }?.status }+ #expect(status("user") == .timedOut)+ #expect(status("system") == .running)+ #expect(result.autoResumeIDs.isEmpty)+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryCopyTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryCopyTests.swiftindex f5f1616f..bc65b51b 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryCopyTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryCopyTests.swift@@ -12,9 +12,9 @@ struct UserQueryCopyTests {@Testfunc placeholderCopyDoesNotBecomeTaskDisplayText() {- #expect(!UserQueryCopy.isTaskDisplayText(UserQueryCopy.defaultPromptPlaceholder))- #expect(!UserQueryCopy.isTaskDisplayText(" \(UserQueryCopy.defaultPromptPlaceholder) "))- #expect(UserQueryCopy.isTaskDisplayText("Open Safari"))+ #expect(!UserQueryCopy.isConversationDisplayText(UserQueryCopy.defaultPromptPlaceholder))+ #expect(!UserQueryCopy.isConversationDisplayText(" \(UserQueryCopy.defaultPromptPlaceholder) "))+ #expect(UserQueryCopy.isConversationDisplayText("Open Safari"))}@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryDismissPromptResetTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryDismissPromptResetTests.swiftnew file mode 100644index 00000000..0a58ee85--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryDismissPromptResetTests.swift@@ -0,0 +1,44 @@+import DonkeyContracts+import Foundation+import Testing++@testable import Donkey++/// Closing a conversation with the notch X must make it disappear. The list removal already worked; the+/// bug that kept the row looking "still listed" lived in the *prompt line*: the collapsed notch falls back+/// to `promptState` only when no conversation row exists, so a dismissed conversation's summary left+/// stranded in `promptText` kept rendering (with a generic "Needs attention") as though the row were still+/// there. `dismissTask` now returns the line to rest once the list empties; these lock that decision.+/// `@MainActor`: `restingPromptText` is a static helper on the main-actor-isolated model, so the suite+/// runs on the main actor to call it — matching the model's other static-helper tests.+@Suite+@MainActor+struct UserQueryDismissPromptResetTests {+ private func task(id: String, status: UserQueryConversationStatus) -> UserQueryConversation {+ UserQueryConversation(+ id: id,+ title: "prompt",+ detail: "I'll start by checking the current directory.",+ commandText: "prompt",+ status: status,+ accentIndex: 0+ )+ }++ @Test+ func dismissingTheLastConversationReturnsThePromptLineToRest() {+ // No rows left: the line must reset to the resting placeholder so the collapsed notch reads Idle,+ // never the dismissed conversation's stranded summary.+ #expect(+ UserQueryOverlayModel.restingPromptText(forRemainingConversations: []) == UserQueryCopy.defaultPromptPlaceholder+ )+ }++ @Test+ func dismissingWithConversationsRemainingLeavesThePromptLineToTheList() {+ // Rows remain: the collapsed notch reads them directly, so the prompt line is left untouched (nil)+ // rather than overwritten — the surviving conversation, not the placeholder, drives the display.+ let remaining = [task(id: "a", status: .running)]+ #expect(UserQueryOverlayModel.restingPromptText(forRemainingConversations: remaining) == nil)+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryNotchMetricsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryNotchMetricsTests.swiftindex 06cd277d..2c205822 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryNotchMetricsTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryNotchMetricsTests.swift@@ -9,7 +9,7 @@ struct UserQueryNotchMetricsTests {let metrics = UserQueryNotchMetrics(voidWidth: 0,voidHeight: 0,- expandedContentHeight: UserQueryNotchMetrics.expandedTaskContentHeight,+ expandedContentHeight: UserQueryNotchMetrics.expandedConversationContentHeight,isExpanded: true,isHostExpanded: true,screenWidth: UserQueryNotchMetrics.defaultScreenWidth@@ -23,10 +23,10 @@ struct UserQueryNotchMetricsTests {UserQueryNotchLayout.expandedCommandOnlyTopPaddingBelowPhysicalVoid)#expect(layout.expandedContentFrame.minY == UserQueryNotchMetrics.fallbackVoidHeight)- #expect(layout.expandedContentFrame.height == UserQueryNotchMetrics.expandedTaskContentHeight)+ #expect(layout.expandedContentFrame.height == UserQueryNotchMetrics.expandedConversationContentHeight)#expect(layout.expandedSurfaceFrame.height ==- UserQueryNotchMetrics.expandedTaskContentHeight ++ UserQueryNotchMetrics.expandedConversationContentHeight +UserQueryNotchMetrics.fallbackVoidHeight)}@@ -36,7 +36,7 @@ struct UserQueryNotchMetricsTests {let metrics = UserQueryNotchMetrics(voidWidth: UserQueryNotchMetrics.fallbackVoidWidth,voidHeight: UserQueryNotchMetrics.fallbackVoidHeight,- expandedContentHeight: UserQueryNotchMetrics.expandedTaskContentHeight,+ expandedContentHeight: UserQueryNotchMetrics.expandedConversationContentHeight,isExpanded: true,isHostExpanded: true,screenWidth: UserQueryNotchMetrics.defaultScreenWidth@@ -50,10 +50,10 @@ struct UserQueryNotchMetricsTests {UserQueryNotchLayout.expandedCommandOnlyTopPaddingBelowPhysicalVoid)#expect(layout.expandedContentFrame.minY == UserQueryNotchMetrics.fallbackVoidHeight)- #expect(layout.expandedContentFrame.height == UserQueryNotchMetrics.expandedTaskContentHeight)+ #expect(layout.expandedContentFrame.height == UserQueryNotchMetrics.expandedConversationContentHeight)#expect(layout.expandedSurfaceFrame.height ==- UserQueryNotchMetrics.expandedTaskContentHeight ++ UserQueryNotchMetrics.expandedConversationContentHeight +UserQueryNotchMetrics.fallbackVoidHeight)}@@ -64,7 +64,7 @@ struct UserQueryNotchMetricsTests {UserQueryNotchMetrics(voidWidth: 0,voidHeight: 0,- expandedContentHeight: UserQueryNotchMetrics.expandedTaskContentHeight,+ expandedContentHeight: UserQueryNotchMetrics.expandedConversationContentHeight,isExpanded: false,isHostExpanded: false,screenWidth: UserQueryNotchMetrics.defaultScreenWidth,@@ -84,7 +84,7 @@ struct UserQueryNotchMetricsTests {UserQueryNotchMetrics(voidWidth: UserQueryNotchMetrics.fallbackVoidWidth,voidHeight: UserQueryNotchMetrics.fallbackVoidHeight,- expandedContentHeight: UserQueryNotchMetrics.expandedTaskContentHeight,+ expandedContentHeight: UserQueryNotchMetrics.expandedConversationContentHeight,isExpanded: false,isHostExpanded: false,screenWidth: UserQueryNotchMetrics.defaultScreenWidth,diff --git a/docs/guides/releasing-donkey.md b/docs/guides/releasing-donkey.mdindex 49dd959f..70dddf3b 100644--- a/docs/guides/releasing-donkey.md+++ b/docs/guides/releasing-donkey.md@@ -52,8 +52,11 @@ it needs to keep automating other apps once hardened.## Bundled ToolsThe capability skills (media, pdf) run CLI tools — `ffmpeg`, `yt-dlp`, and a few-others — that the app downloads on first launch instead of baking into the app-download. The `Publish Bundled Tools` workflow builds them from source on an+others — that the app downloads once the user signs in (so the bundle stays out+of the app download, and isn't fetched for someone who never gets past sign-in).+The download surfaces in the notch as a progress conversation the user can watch+but not stop or dismiss; it retries on its own and no-ops once the published+version is already installed. The `Publish Bundled Tools` workflow builds them from source on anarm64 runner, signs and notarizes them, uploads the bundle as a GitHub releaseasset, and commits the refreshed `bundled-tools.json` (the manifest the app readsto know what to fetch). It runs on demand and whenever the tools recipe changes.