Skip to content

Open source CapCut alternative.

TypeScript

Support durable task threads and per-task pause resume

David Le40895e2e6768
diff --git a/AGENTS.md b/AGENTS.md
index e1b48996..0ff9b32a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,6 +21,7 @@ Before changing `site/` UI, routes, API handlers, or data access patterns:
## Working Rules
+- Do not touch `prototype/` unless the user explicitly asks for prototype work. By default, assume requested product changes are for the Mac app or the site/landing page.
- Ask before creating any new plan document.
- Manage plans deliberately: move a plan to `plans/done/` when its work is complete, and create or keep plans only for work that remains.
- Over time, prefer shrinking active `plans/` by completing work and moving finished plans to `plans/done/`.
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
index da7f12b5..23a2b756 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
@@ -18,10 +18,26 @@ struct DocumentFormFillReviewRequest: Equatable, Sendable {
var traceID: String
}
+struct PointerPromptCommandContext: Equatable, Sendable {
+ var task: PointerPromptNotchTask
+ var recentEvents: [PointerPromptTaskEvent]
+ var assets: [PointerPromptTaskAsset]
+ var isFollowUp: Bool
+}
+
protocol PointerPromptCommandHandling: Sendable {
- func handleSubmittedCommand(_ command: String) async -> PointerPromptCommandHandlingResult
- func pauseCurrentCommand() async
- func resumeCurrentCommand() async
+ func handleSubmittedCommand(
+ _ command: String,
+ context: PointerPromptCommandContext?
+ ) async -> PointerPromptCommandHandlingResult
+ func pauseCommand(taskID: String) async -> Bool
+ func resumeCommand(taskID: String) async -> Bool
+}
+
+extension PointerPromptCommandHandling {
+ func handleSubmittedCommand(_ command: String) async -> PointerPromptCommandHandlingResult {
+ await handleSubmittedCommand(command, context: nil)
+ }
}
struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
@@ -30,7 +46,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
var liveRunner: LocalAppTaskLiveRunner
var redactor: AIHarnessRedactor
var memoryRetriever: SemanticRunMemoryRetriever
- var coordinator: RunCoordinator
+ var coordinatorRegistry: PointerPromptRunCoordinatorRegistry
var targetMemoryStore: TargetMemoryJSONLStore?
init(
@@ -39,40 +55,48 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
liveRunner: LocalAppTaskLiveRunner? = nil,
redactor: AIHarnessRedactor = AIHarnessRedactor(),
memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),
- coordinator: RunCoordinator = RunCoordinator(),
+ coordinatorRegistry: PointerPromptRunCoordinatorRegistry = PointerPromptRunCoordinatorRegistry(),
targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()
) {
self.catalog = catalog
- self.coordinator = coordinator
+ self.coordinatorRegistry = coordinatorRegistry
self.localModelResolver = localModelResolver ?? LocalModelTaskIntentResolver(catalog: catalog)
- self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog, coordinator: coordinator)
+ self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog)
self.redactor = redactor
self.memoryRetriever = memoryRetriever
self.targetMemoryStore = targetMemoryStore
}
- func handleSubmittedCommand(_ command: String) async -> PointerPromptCommandHandlingResult {
+ func handleSubmittedCommand(
+ _ command: String,
+ context: PointerPromptCommandContext?
+ ) async -> PointerPromptCommandHandlingResult {
let traceID = "pointer-prompt-\(UUID().uuidString)"
- let redaction = redactor.redact(command, surface: .modelContext)
+ let taskID = context?.task.id ?? traceID
+ let coordinator = await coordinatorRegistry.coordinator(for: taskID)
+ var taskLiveRunner = liveRunner
+ taskLiveRunner.coordinator = coordinator
+ let modelCommand = Self.modelCommand(for: command, context: context)
+ let redaction = redactor.redact(modelCommand, surface: .modelContext)
let memoryProposalDecisions = (try? ProviderDecodedMemoryProposalHandler.decisions(
from: Data("[]".utf8),
decidedAt: Self.now()
)) ?? []
let parseStartedAt = Self.uptimeMilliseconds()
let localModelResult = await localModelResolver.resolve(
- command: command,
+ command: modelCommand,
sourceTraceID: traceID
)
let resolution = localModelResult.resolution
let parseLatencyMS = Self.uptimeMilliseconds() - parseStartedAt
let semanticMemoryResults = await retrieveSemanticMemory(
- command: command,
+ command: modelCommand,
resolution: resolution
)
let modelObservability = AIModelObservabilityReportBuilder.build(from: [localModelResult.trace])
- let result = await liveRunner.run(
- command: command,
+ let result = await taskLiveRunner.run(
+ command: modelCommand,
traceID: traceID,
resolution: resolution,
metadata: [
@@ -89,7 +113,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
"semanticMemory.recordIDs": semanticMemoryResults.map(\.record.id).joined(separator: ","),
"semanticMemory.targetID": semanticMemoryTargetID(for: resolution) ?? "",
"memoryProposal.decisionCount": String(memoryProposalDecisions.count)
- ]
+ ].merging(Self.contextMetadata(context)) { current, _ in current }
)
await coordinator.recordToolEvent(
capability: .model,
@@ -104,7 +128,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
]
)
- return PointerPromptCommandHandlingResult(
+ let handlingResult = PointerPromptCommandHandlingResult(
status: result.status,
summary: summary(for: result),
taskLabel: taskLabel(for: result),
@@ -115,14 +139,22 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
result: result
)
)
+ await coordinatorRegistry.finish(taskID: taskID)
+ return handlingResult
}
- func pauseCurrentCommand() async {
- await coordinator.pause(reason: "Pointer prompt paused current task")
+ func pauseCommand(taskID: String) async -> Bool {
+ await coordinatorRegistry.pause(
+ taskID: taskID,
+ reason: "Pointer prompt paused task"
+ )
}
- func resumeCurrentCommand() async {
- await coordinator.resume(reason: "Pointer prompt resumed current task")
+ func resumeCommand(taskID: String) async -> Bool {
+ await coordinatorRegistry.resume(
+ taskID: taskID,
+ reason: "Pointer prompt resumed task"
+ )
}
private func retrieveSemanticMemory(
@@ -245,4 +277,73 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
)
}
+
+ private static func modelCommand(
+ for command: String,
+ context: PointerPromptCommandContext?
+ ) -> String {
+ guard let context, context.isFollowUp else { return command }
+
+ let events = context.recentEvents
+ .suffix(8)
+ .map { "\($0.role.rawValue): \($0.text)" }
+ .joined(separator: "\n")
+ let assets = context.assets
+ .suffix(8)
+ .map { "\($0.displayName) (\($0.contentType))" }
+ .joined(separator: ", ")
+ return [
+ "Existing task title: \(context.task.title)",
+ "Existing task original request: \(context.task.commandText)",
+ "Existing task status: \(context.task.status.rawValue)",
+ events.isEmpty ? nil : "Recent task thread:\n\(events)",
+ assets.isEmpty ? nil : "Task assets: \(assets)",
+ "Latest user follow-up: \(command)"
+ ]
+ .compactMap(\.self)
+ .joined(separator: "\n\n")
+ }
+
+ private static func contextMetadata(_ context: PointerPromptCommandContext?) -> [String: String] {
+ guard let context else { return [:] }
+
+ return [
+ "taskContext.taskID": context.task.id,
+ "taskContext.isFollowUp": String(context.isFollowUp),
+ "taskContext.eventCount": String(context.recentEvents.count),
+ "taskContext.assetCount": String(context.assets.count)
+ ]
+ }
+}
+
+actor PointerPromptRunCoordinatorRegistry {
+ private var coordinators: [String: RunCoordinator] = [:]
+
+ func coordinator(for taskID: String) -> RunCoordinator {
+ if let coordinator = coordinators[taskID] {
+ return coordinator
+ }
+
+ let coordinator = RunCoordinator()
+ coordinators[taskID] = coordinator
+ return coordinator
+ }
+
+ func pause(taskID: String, reason: String) async -> Bool {
+ guard let coordinator = coordinators[taskID] else { return false }
+
+ await coordinator.pause(reason: reason)
+ return true
+ }
+
+ func resume(taskID: String, reason: String) async -> Bool {
+ guard let coordinator = coordinators[taskID] else { return false }
+
+ await coordinator.resume(reason: reason)
+ return true
+ }
+
+ func finish(taskID: String) {
+ coordinators[taskID] = nil
+ }
}
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift
index a14bea14..02c81791 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift
@@ -141,7 +141,7 @@ final class PointerPromptOverlayController {
panel.becomesKeyOnlyIfNeeded = true
panel.ignoresMouseEvents = false
panel.mouseDownHandler = { [weak self] in
- self?.focusStatusComposerTextInputIfEmpty()
+ self?.focusStatusComposerTextInputIfAvailable()
}
panel.level = .statusBar
panel.collectionBehavior = [
@@ -529,6 +529,7 @@ final class PointerPromptOverlayController {
notchCommandText: model.notchCommandText,
notchCommandInputTextHeight: model.notchCommandInputTextHeight,
isNotchCommandInputExpanded: model.isNotchCommandInputExpanded,
+ notchTasks: model.notchTasks,
accentIndex: model.notchAccentIndex
)
}
@@ -552,6 +553,7 @@ final class PointerPromptOverlayController {
),
commandInputTextHeight: model.notchCommandInputTextHeight,
isCommandInputExpanded: model.isNotchCommandInputExpanded,
+ tasks: model.notchTasks,
accentIndex: model.notchAccentIndex,
commandSubmitted: { [weak self] text in
self?.model.handle(.messageSubmitted(text: text))
@@ -562,11 +564,14 @@ final class PointerPromptOverlayController {
commandInputExpansionChanged: { [weak self] isExpanded in
self?.model.updateNotchCommandInputExpansion(isExpanded)
},
- pauseRequested: { [weak self] in
- self?.model.pauseCurrentTask()
+ assetsDropped: { [weak self] drafts in
+ self?.model.handleDroppedAssets(drafts)
},
- resumeRequested: { [weak self] in
- self?.model.resumeCurrentTask()
+ pauseRequested: { [weak self] taskID in
+ self?.model.pauseTask(id: taskID)
+ },
+ resumeRequested: { [weak self] taskID in
+ self?.model.resumeTask(id: taskID)
},
updateRequested: { [weak self] in
self?.openAvailableUpdate()
@@ -633,7 +638,7 @@ final class PointerPromptOverlayController {
self.statusHoverPhase = .expanded
self.statusExpansionWorkItem = nil
self.updateStatusPanelView()
- self.focusStatusComposerTextInputIfEmpty()
+ self.focusStatusComposerTextInputIfAvailable()
}
statusExpansionWorkItem = workItem
DispatchQueue.main.asyncAfter(
@@ -764,7 +769,7 @@ final class PointerPromptOverlayController {
} else {
measuredVoidWidth = 0
}
- let hasNotch = safeTop > 0 || measuredVoidWidth > 0
+ let hasNotch = measuredVoidWidth > 0 || safeTop >= NotchMetrics.minimumPhysicalVoidHeight
let voidHeight = hasNotch ? max(safeTop, NotchMetrics.fallbackVoidHeight) : 0
let voidWidth = hasNotch ? max(measuredVoidWidth, inferredVoidWidth(for: screen, safeTop: safeTop)) : 0
@@ -779,7 +784,7 @@ final class PointerPromptOverlayController {
}
private var statusExpandedContentHeight: CGFloat {
- if hasStatusTaskDisplayText || model.updateState.headerButtonTitle != nil {
+ if hasStatusTaskDisplayText || !model.notchTasks.isEmpty || model.updateState.headerButtonTitle != nil {
return NotchMetrics.expandedTaskContentHeight
}
@@ -1065,9 +1070,7 @@ final class PointerPromptOverlayController {
}
}
- private func focusStatusComposerTextInputIfEmpty() {
- guard !hasStatusTaskDisplayText else { return }
-
+ private func focusStatusComposerTextInputIfAvailable() {
focusStatusComposerTextInput()
}
}
@@ -1124,6 +1127,7 @@ private struct NotchMetrics {
static let fallbackVoidHeight: CGFloat = 32
static let maximumInferredVoidWidth: CGFloat = 220
static let defaultScreenWidth: CGFloat = 1512
+ static let minimumPhysicalVoidHeight: CGFloat = 30
var voidWidth: CGFloat
var voidHeight: CGFloat
@@ -1217,12 +1221,16 @@ private struct NotchMetrics {
private var collapsedSurfaceWidth: CGFloat {
min(
Self.expandedContentDesignFrame.width,
- max(Self.minimumCollapsedSurfaceFrame.width, voidWidth + Self.collapsedSideLaneWidth * 2)
+ max(
+ Self.minimumCollapsedSurfaceFrame.width,
+ Self.commonCollapsedSurfaceFrame.width,
+ voidWidth + Self.collapsedSideLaneWidth * 2
+ )
)
}
private var collapsedVisibleHeight: CGFloat {
- voidHeight > 0 ? voidHeight : Self.minimumCollapsedSurfaceFrame.height
+ max(Self.minimumCollapsedSurfaceFrame.height, Self.commonCollapsedSurfaceFrame.height, voidHeight)
}
private var expandedVisibleHeight: CGFloat {
@@ -1230,14 +1238,26 @@ private struct NotchMetrics {
}
private var expandedContentTopInset: CGFloat {
- min(max(0, voidHeight), Self.maximumExpandedContentTopInset)
+ guard hasPhysicalVoid else { return 0 }
+
+ return min(max(0, voidHeight), Self.maximumExpandedContentTopInset)
}
private var expandedSurfaceHeight: CGFloat {
expandedContentHeight + expandedContentTopInset
}
+ private var hasPhysicalVoid: Bool {
+ voidWidth > 0 || voidHeight > 0
+ }
+
private static let minimumCollapsedSurfaceFrame = CGRect(x: 0, y: 0, width: 110, height: 28)
+ private static let commonCollapsedSurfaceFrame = CGRect(
+ x: 0,
+ y: 0,
+ width: Self.fallbackVoidWidth + Self.collapsedSideLaneWidth * 2,
+ height: Self.fallbackVoidHeight
+ )
private static let expandedContentDesignFrame = CGRect(
x: 0,
y: 0,
@@ -1266,6 +1286,7 @@ private struct StatusPanelViewSnapshot: Equatable {
var notchCommandText: String
var notchCommandInputTextHeight: CGFloat
var isNotchCommandInputExpanded: Bool
+ var notchTasks: [PointerPromptNotchTask]
var accentIndex: Int
}
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
index 2935e001..b2d5601c 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
@@ -16,15 +16,25 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
@Published private(set) var notchAccentIndex = Int.random(in: 0..<8)
@Published private(set) var isCurrentTaskPaused = false
@Published private(set) var updateState: PointerPromptUpdateState
+ @Published private(set) var notchTasks: [PointerPromptNotchTask]
private let commandHandler: any PointerPromptCommandHandling
+ private let taskStore: any PointerPromptTaskStoring
+ private let followUpResolver: any PointerPromptFollowUpResolving
private let voiceTranscriber: LocalVoiceTranscriptionAdapter
private var updateChecker: any DonkeyUpdateChecking
private let documentReviewController: DocumentFormFillReviewWindowController
+ private var activeTaskIDs: Set<String> = []
+ private var lastActiveTaskID: String?
+ private static let notchTaskDisplayLimit = 12
+ private static let followUpCandidateLimit = 8
+ private static let followUpMatchConfidenceThreshold = 0.62
init(
aiProvider: any AIHarnessSnapshotProviding = AIHarnessBoundary(),
commandHandler: any PointerPromptCommandHandling = LocalAppPointerPromptCommandHandler(),
+ taskStore: any PointerPromptTaskStoring = CoreDataPointerPromptTaskStore(),
+ followUpResolver: any PointerPromptFollowUpResolving = ProcessBackedLocalLLMTaskFollowUpResolver(),
voiceTranscriber: LocalVoiceTranscriptionAdapter = LocalVoiceTranscriptionAdapter(
runtime: ProcessBackedParakeetTranscriptionRuntime()
),
@@ -33,9 +43,14 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
theme: PointerPromptTheme = PointerPromptOverlayModel.bundledTheme()
) {
self.commandHandler = commandHandler
+ self.taskStore = taskStore
+ self.followUpResolver = followUpResolver
self.voiceTranscriber = voiceTranscriber
self.updateChecker = updateChecker
self.documentReviewController = documentReviewController
+ let restoredTasks = Self.restoredTasks(from: taskStore.loadRecentTasks(limit: Self.notchTaskDisplayLimit))
+ notchTasks = restoredTasks
+ isCurrentTaskPaused = restoredTasks.first?.status == .paused
updateState = PointerPromptUpdateState(
currentVersion: updateChecker.currentVersion
)
@@ -82,9 +97,11 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
case .voiceInputRequested:
promptState.leadingSignalLevel = .ready
promptState.promptText = "Listening..."
- case .primaryActionRequested:
- isCurrentTaskPaused = false
- promptState.leadingSignalLevel = .thinking
+ case .primaryActionRequested(let promptText):
+ let trimmedText = promptText.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedText.isEmpty else { return }
+
+ submitCommand(trimmedText)
case .messageSubmitted(let text):
let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedText.isEmpty else { return }
@@ -137,25 +154,101 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
}
private func submitCommand(_ text: String) {
- let taskLabel = Self.taskLabel(for: text)
+ let candidates = followUpCandidates()
+ clearSubmissionInputs()
+ promptState.isActive = false
+ promptState.leadingSignalLevel = .thinking
+ promptState.promptText = "Routing task"
+ let sourceTraceID = "pointer-prompt-followup-\(UUID().uuidString)"
+ let confidenceThreshold = Self.followUpMatchConfidenceThreshold
+ Task { [weak self, followUpResolver] in
+ let matchedTaskID: String?
+ if candidates.isEmpty {
+ matchedTaskID = nil
+ } else {
+ let resolution = await followUpResolver.resolveFollowUp(
+ PointerPromptFollowUpResolverRequest(
+ text: text,
+ candidates: candidates,
+ sourceTraceID: sourceTraceID
+ )
+ )
+ if let taskID = resolution.taskID,
+ resolution.confidence >= confidenceThreshold {
+ matchedTaskID = taskID
+ } else {
+ matchedTaskID = nil
+ }
+ }
+
+ await MainActor.run {
+ self?.startCommandRun(text: text, matchedTaskID: matchedTaskID)
+ }
+ }
+ }
+
+ func handleDroppedAssets(_ drafts: [PointerPromptTaskAssetDraft]) {
+ guard !drafts.isEmpty else { return }
+
+ let targetTask = taskForDroppedAssets()
+ let assetNames = drafts.map(\.displayName)
+ let eventText = Self.assetUploadEventText(assetNames)
+ let eventID = appendTaskEvent(taskID: targetTask.id, role: .user, text: eventText)
+ for draft in drafts {
+ let assetID = UUID().uuidString
+ taskStore.appendAsset(
+ Self.persistedAsset(
+ from: draft,
+ assetID: assetID,
+ taskID: targetTask.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()
+ }
+
+ private func startCommandRun(text: String, matchedTaskID: String?) {
+ let isFollowUp = matchedTaskID != nil
+ let task = taskForSubmittedCommand(text: text, matchedTaskID: matchedTaskID)
+ activeTaskIDs.insert(task.id)
+ lastActiveTaskID = task.id
+ appendTaskEvent(taskID: task.id, role: .user, text: text)
messageText = ""
inputTextHeight = PointerPromptLayout.composerInputTextMinimumHeight
isInputExpanded = false
notchCommandText = ""
notchCommandInputTextHeight = PointerPromptLayout.composerInputTextMinimumHeight
isNotchCommandInputExpanded = true
- isCurrentTaskPaused = false
- notchAccentIndex = Self.nextAccentIndex(after: notchAccentIndex)
promptState.isActive = false
promptState.leadingSignalLevel = .thinking
- promptState.promptText = taskLabel
+ promptState.promptText = task.title
+ syncPrimaryTaskPausedFlag()
+ let context = commandContext(taskID: task.id, isFollowUp: isFollowUp)
Task { [weak self, commandHandler] in
- let result = await commandHandler.handleSubmittedCommand(text)
+ let result = await commandHandler.handleSubmittedCommand(text, context: context)
await MainActor.run {
guard let self else { return }
- self.isCurrentTaskPaused = false
- self.promptState.leadingSignalLevel = result.status == .completed ? .ready : .idle
- self.promptState.promptText = result.taskLabel ?? result.summary
+ self.updateTask(
+ id: task.id,
+ title: isFollowUp ? nil : result.taskLabel,
+ detail: result.summary,
+ status: Self.taskStatus(for: result)
+ )
+ self.appendTaskEvent(taskID: task.id, role: .assistant, text: result.summary)
+ self.activeTaskIDs.remove(task.id)
+ self.refreshPromptStateAfterRunResult(
+ taskID: task.id,
+ result: result
+ )
if let documentReviewRequest = result.documentReviewRequest {
self.documentReviewController.show(request: documentReviewRequest)
}
@@ -163,24 +256,36 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
}
}
- func pauseCurrentTask() {
- guard promptState.leadingSignalLevel == .thinking,
- !isCurrentTaskPaused else {
- return
- }
+ func pauseTask(id taskID: String) {
+ guard task(withID: taskID)?.status == .running else { return }
- isCurrentTaskPaused = true
+ activeTaskIDs.insert(taskID)
+ lastActiveTaskID = taskID
+ updateTask(id: taskID, detail: "Paused", status: .paused)
+ appendTaskEvent(taskID: taskID, role: .system, text: "Paused")
+ syncPrimaryTaskPausedFlag()
Task { [commandHandler] in
- await commandHandler.pauseCurrentCommand()
+ _ = await commandHandler.pauseCommand(taskID: taskID)
}
}
- func resumeCurrentTask() {
- guard isCurrentTaskPaused else { return }
+ func resumeTask(id taskID: String) {
+ guard task(withID: taskID)?.status == .paused else { return }
- isCurrentTaskPaused = false
- Task { [commandHandler] in
- await commandHandler.resumeCurrentCommand()
+ activeTaskIDs.insert(taskID)
+ lastActiveTaskID = taskID
+ updateTask(id: taskID, detail: "Running", status: .running)
+ appendTaskEvent(taskID: taskID, role: .system, text: "Resumed")
+ promptState.leadingSignalLevel = .thinking
+ promptState.promptText = task(withID: taskID)?.title ?? "Working"
+ syncPrimaryTaskPausedFlag()
+ Task { [weak self, commandHandler] in
+ let resumedInMemory = await commandHandler.resumeCommand(taskID: taskID)
+ guard !resumedInMemory else { return }
+
+ await MainActor.run {
+ self?.startCommandRun(text: "Continue", matchedTaskID: taskID)
+ }
}
}
@@ -202,6 +307,220 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
max(92, notchCommandInputTextHeight + 60)
}
+ private func prependTask(_ task: PointerPromptNotchTask) {
+ notchTasks.removeAll { $0.id == task.id }
+ notchTasks.insert(task, at: 0)
+ if notchTasks.count > Self.notchTaskDisplayLimit {
+ notchTasks = Array(notchTasks.prefix(Self.notchTaskDisplayLimit))
+ }
+ taskStore.upsertTask(task)
+ }
+
+ private func clearSubmissionInputs() {
+ messageText = ""
+ inputTextHeight = PointerPromptLayout.composerInputTextMinimumHeight
+ isInputExpanded = false
+ notchCommandText = ""
+ notchCommandInputTextHeight = PointerPromptLayout.composerInputTextMinimumHeight
+ isNotchCommandInputExpanded = true
+ }
+
+ private func taskForSubmittedCommand(text: String, matchedTaskID: String?) -> PointerPromptNotchTask {
+ if let matchedTaskID,
+ var task = task(withID: matchedTaskID) {
+ task.detail = "Running"
+ task.status = .running
+ task.updatedAt = Date()
+ prependTask(task)
+ return task
+ }
+
+ let taskLabel = Self.taskLabel(for: text)
+ let nextAccentIndex = Self.nextAccentIndex(after: notchAccentIndex)
+ notchAccentIndex = nextAccentIndex
+ let task = PointerPromptNotchTask(
+ id: UUID().uuidString,
+ title: taskLabel,
+ detail: "Running",
+ commandText: text,
+ status: .running,
+ accentIndex: nextAccentIndex
+ )
+ prependTask(task)
+ return task
+ }
+
+ private func taskForDroppedAssets() -> PointerPromptNotchTask {
+ if let lastActiveTaskID,
+ activeTaskIDs.contains(lastActiveTaskID),
+ let task = task(withID: lastActiveTaskID) {
+ return task
+ }
+
+ if let activeTask = notchTasks.first(where: { $0.status == .running || $0.status == .paused }) {
+ return activeTask
+ }
+
+ if let recentTask = notchTasks.first {
+ return recentTask
+ }
+
+ let nextAccentIndex = Self.nextAccentIndex(after: notchAccentIndex)
+ notchAccentIndex = nextAccentIndex
+ let task = PointerPromptNotchTask(
+ id: UUID().uuidString,
+ title: "Uploaded assets",
+ detail: "Assets attached",
+ commandText: "",
+ status: .needsAttention,
+ accentIndex: nextAccentIndex
+ )
+ prependTask(task)
+ return task
+ }
+
+ private func task(withID taskID: String) -> PointerPromptNotchTask? {
+ if let task = notchTasks.first(where: { $0.id == taskID }) {
+ return task
+ }
+
+ return taskStore
+ .loadRecentTasks(limit: max(Self.notchTaskDisplayLimit, Self.followUpCandidateLimit) * 2)
+ .first { $0.id == taskID }
+ }
+
+ private func commandContext(taskID: String, isFollowUp: Bool) -> PointerPromptCommandContext? {
+ guard let task = task(withID: taskID) else { return nil }
+
+ return PointerPromptCommandContext(
+ task: task,
+ recentEvents: Array(taskStore.loadEvents(taskID: taskID).suffix(10)),
+ assets: taskStore.loadAssets(taskID: taskID),
+ isFollowUp: isFollowUp
+ )
+ }
+
+ private func followUpCandidates() -> [PointerPromptFollowUpCandidate] {
+ taskStore
+ .loadRecentTasks(limit: Self.followUpCandidateLimit)
+ .map { task in
+ let recentEvents = taskStore
+ .loadEvents(taskID: task.id)
+ .suffix(6)
+ .map { event in
+ Self.truncated("\(event.role.rawValue): \(event.text)", maxLength: 220)
+ }
+ let assetNames = taskStore
+ .loadAssets(taskID: task.id)
+ .suffix(8)
+ .map(\.displayName)
+ return PointerPromptFollowUpCandidate(
+ taskID: task.id,
+ title: task.title,
+ detail: task.detail,
+ commandText: task.commandText,
+ status: task.status,
+ updatedAt: task.updatedAt,
+ recentEvents: recentEvents,
+ assetNames: assetNames
+ )
+ }
+ }
+
+ @discardableResult
+ private func appendTaskEvent(taskID: String, role: PointerPromptTaskEventRole, text: String) -> String? {
+ let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedText.isEmpty else { return nil }
+
+ let sequence = taskStore.loadEvents(taskID: taskID).count
+ let eventID = UUID().uuidString
+ taskStore.appendEvent(
+ PointerPromptTaskEvent(
+ id: eventID,
+ taskID: taskID,
+ role: role,
+ text: trimmedText,
+ sequence: sequence
+ )
+ )
+ return eventID
+ }
+
+ private func updateTask(
+ id: String,
+ title: String? = nil,
+ detail: String? = nil,
+ status: PointerPromptTaskStatus? = nil
+ ) {
+ guard let index = notchTasks.firstIndex(where: { $0.id == id }) else { return }
+
+ var task = notchTasks[index]
+ if let title {
+ task.title = title
+ }
+ if let detail {
+ task.detail = detail
+ }
+ if let status {
+ task.status = status
+ }
+ task.updatedAt = Date()
+ notchTasks[index] = task
+ taskStore.upsertTask(task)
+ syncPrimaryTaskPausedFlag()
+ }
+
+ private static func restoredTasks(from tasks: [PointerPromptNotchTask]) -> [PointerPromptNotchTask] {
+ tasks.map { task in
+ guard task.status == .running else { return task }
+
+ var restoredTask = task
+ restoredTask.status = .needsAttention
+ restoredTask.detail = "Interrupted"
+ restoredTask.updatedAt = Date()
+ return restoredTask
+ }
+ }
+
+ private func refreshPromptStateAfterRunResult(
+ taskID: String,
+ result: PointerPromptCommandHandlingResult
+ ) {
+ syncPrimaryTaskPausedFlag()
+ if let runningTask = notchTasks.first(where: { activeTaskIDs.contains($0.id) && $0.status == .running }) {
+ promptState.leadingSignalLevel = .thinking
+ promptState.promptText = runningTask.title
+ return
+ }
+
+ if let pausedTask = notchTasks.first(where: { activeTaskIDs.contains($0.id) && $0.status == .paused }) {
+ promptState.leadingSignalLevel = .idle
+ promptState.promptText = pausedTask.title
+ return
+ }
+
+ promptState.leadingSignalLevel = result.status == .completed ? .ready : .idle
+ promptState.promptText = result.taskLabel ?? result.summary
+ if lastActiveTaskID == taskID {
+ lastActiveTaskID = notchTasks.first?.id
+ }
+ }
+
+ private func syncPrimaryTaskPausedFlag() {
+ isCurrentTaskPaused = notchTasks.first?.status == .paused
+ }
+
+ private static func taskStatus(for result: PointerPromptCommandHandlingResult) -> PointerPromptTaskStatus {
+ switch result.status {
+ case .completed:
+ return .completed
+ case .needsUserReview, .needsConfirmation, .unsupportedCommand:
+ return .needsAttention
+ case .appUnavailable, .failedSafe:
+ return .failed
+ }
+ }
+
private static func nextAccentIndex(after currentIndex: Int) -> Int {
let accentCount = 8
var nextIndex = Int.random(in: 0..<accentCount)
@@ -225,6 +544,106 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
return String(collapsed[..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines) + "..."
}
+ private static func assetUploadEventText(_ assetNames: [String]) -> String {
+ let displayNames = assetNames
+ .map { truncated($0, maxLength: 80) }
+ .joined(separator: ", ")
+ guard !displayNames.isEmpty else { return "Uploaded assets" }
+
+ return "Uploaded assets: \(displayNames)"
+ }
+
+ private static func persistedAsset(
+ from draft: PointerPromptTaskAssetDraft,
+ assetID: String,
+ taskID: String,
+ eventID: String?
+ ) -> PointerPromptTaskAsset {
+ var storedURLString = draft.urlString
+ if let sourceURL = URL(string: draft.urlString),
+ sourceURL.isFileURL,
+ let destinationURL = copyAssetToApplicationSupport(
+ sourceURL: sourceURL,
+ taskID: taskID,
+ assetID: assetID,
+ displayName: draft.displayName
+ ) {
+ storedURLString = destinationURL.absoluteString
+ }
+
+ return PointerPromptTaskAsset(
+ id: assetID,
+ taskID: taskID,
+ eventID: eventID,
+ source: draft.source,
+ displayName: draft.displayName,
+ contentType: draft.contentType,
+ urlString: storedURLString,
+ byteCount: draft.byteCount
+ )
+ }
+
+ private static func copyAssetToApplicationSupport(
+ sourceURL: URL,
+ taskID: String,
+ assetID: String,
+ displayName: String
+ ) -> URL? {
+ guard let assetsDirectory = taskAssetDirectory(taskID: taskID) else { return nil }
+
+ do {
+ try FileManager.default.createDirectory(
+ at: assetsDirectory,
+ withIntermediateDirectories: true
+ )
+ let fileName = "\(assetID)-\(safeAssetFileName(displayName))"
+ let destinationURL = assetsDirectory.appendingPathComponent(fileName, isDirectory: false)
+ let didStartAccess = sourceURL.startAccessingSecurityScopedResource()
+ defer {
+ if didStartAccess {
+ sourceURL.stopAccessingSecurityScopedResource()
+ }
+ }
+ try FileManager.default.copyItem(at: sourceURL, to: destinationURL)
+ return destinationURL
+ } catch {
+ return nil
+ }
+ }
+
+ private static func taskAssetDirectory(taskID: String) -> URL? {
+ guard let applicationSupportURL = FileManager.default.urls(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask
+ ).first else {
+ return nil
+ }
+
+ return applicationSupportURL
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("PointerPromptAssets", isDirectory: true)
+ .appendingPathComponent(safeAssetFileName(taskID), isDirectory: true)
+ }
+
+ private static func safeAssetFileName(_ fileName: String) -> String {
+ let allowedCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-_"))
+ let scalars = fileName.unicodeScalars.map { scalar in
+ allowedCharacters.contains(scalar) ? Character(scalar) : "-"
+ }
+ let sanitized = String(scalars)
+ .split(separator: "-")
+ .joined(separator: "-")
+ .trimmingCharacters(in: CharacterSet(charactersIn: ".-"))
+ return sanitized.isEmpty ? "asset" : sanitized
+ }
+
+ private static func truncated(_ text: String, maxLength: Int) -> String {
+ guard text.count > maxLength else { return text }
+
+ let endIndex = text.index(text.startIndex, offsetBy: maxLength)
+ return String(text[..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines) + "..."
+ }
+
private static func bundledTheme() -> PointerPromptTheme {
guard let themeURL = Bundle.module.url(forResource: "theme", withExtension: "json"),
let themeData = try? Data(contentsOf: themeURL),
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptTaskStore.swift b/apps/Donkey/Sources/Donkey/PointerPromptTaskStore.swift
new file mode 100644
index 00000000..ac842cd9
--- /dev/null
+++ b/apps/Donkey/Sources/Donkey/PointerPromptTaskStore.swift
@@ -0,0 +1,408 @@
+import DonkeyContracts
+import CoreData
+import Foundation
+
+@MainActor
+protocol PointerPromptTaskStoring {
+ func loadRecentTasks(limit: Int) -> [PointerPromptNotchTask]
+ func searchTasks(matching query: String, limit: Int) -> [PointerPromptNotchTask]
+ func upsertTask(_ task: PointerPromptNotchTask)
+ func loadEvents(taskID: String) -> [PointerPromptTaskEvent]
+ func appendEvent(_ event: PointerPromptTaskEvent)
+ func loadAssets(taskID: String) -> [PointerPromptTaskAsset]
+ func appendAsset(_ asset: PointerPromptTaskAsset)
+}
+
+@MainActor
+final class CoreDataPointerPromptTaskStore: PointerPromptTaskStoring {
+ private let context: NSManagedObjectContext?
+
+ init(
+ storeURL: URL? = nil
+ ) {
+ context = Self.makeContext(storeURL: storeURL ?? Self.defaultStoreURL())
+ }
+
+ func loadRecentTasks(limit: Int) -> [PointerPromptNotchTask] {
+ guard let context else {
+ return []
+ }
+
+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.taskEntityName)
+ request.fetchLimit = limit
+ request.sortDescriptors = [
+ NSSortDescriptor(key: Self.updatedAtKey, ascending: false)
+ ]
+
+ guard let managedTasks = try? context.fetch(request) else {
+ return []
+ }
+
+ return managedTasks.compactMap(Self.task(from:))
+ }
+
+ func searchTasks(matching query: String, limit: Int) -> [PointerPromptNotchTask] {
+ guard let context else {
+ return []
+ }
+
+ let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedQuery.isEmpty else {
+ return loadRecentTasks(limit: limit)
+ }
+
+ let matchingEventTaskIDs = taskIDsWithMatchingEvents(trimmedQuery)
+ let matchingAssetTaskIDs = taskIDsWithMatchingAssets(trimmedQuery)
+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.taskEntityName)
+ request.fetchLimit = limit
+ var 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 !matchingAssetTaskIDs.isEmpty {
+ predicates.append(NSPredicate(format: "%K IN %@", Self.idKey, matchingAssetTaskIDs))
+ }
+ request.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
+ request.sortDescriptors = [
+ NSSortDescriptor(key: Self.updatedAtKey, ascending: false)
+ ]
+
+ guard let managedTasks = try? context.fetch(request) else {
+ return []
+ }
+
+ return managedTasks.compactMap(Self.task(from:))
+ }
+
+ func upsertTask(_ task: PointerPromptNotchTask) {
+ guard let context else { return }
+
+ let managedTask = Self.existingTask(id: task.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)
+
+ try? context.save()
+ }
+
+ func loadAssets(taskID: String) -> [PointerPromptTaskAsset] {
+ guard let context else { return [] }
+
+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.assetEntityName)
+ request.predicate = NSPredicate(format: "%K == %@", Self.assetTaskIDKey, taskID)
+ request.sortDescriptors = [
+ NSSortDescriptor(key: Self.assetCreatedAtKey, ascending: true)
+ ]
+
+ guard let managedAssets = try? context.fetch(request) else {
+ return []
+ }
+
+ return managedAssets.compactMap(Self.asset(from:))
+ }
+
+ func appendAsset(_ asset: PointerPromptTaskAsset) {
+ guard let context else { return }
+
+ let managedAsset = NSManagedObject(
+ entity: Self.assetEntityDescription(in: context),
+ insertInto: context
+ )
+ managedAsset.setValue(asset.id, forKey: Self.assetIDKey)
+ managedAsset.setValue(asset.taskID, forKey: Self.assetTaskIDKey)
+ managedAsset.setValue(asset.eventID, forKey: Self.assetEventIDKey)
+ managedAsset.setValue(asset.source.rawValue, forKey: Self.assetSourceKey)
+ managedAsset.setValue(asset.displayName, forKey: Self.assetDisplayNameKey)
+ managedAsset.setValue(asset.contentType, forKey: Self.assetContentTypeKey)
+ managedAsset.setValue(asset.urlString, forKey: Self.assetURLStringKey)
+ managedAsset.setValue(asset.byteCount.map(NSNumber.init(value:)), forKey: Self.assetByteCountKey)
+ managedAsset.setValue(asset.createdAt, forKey: Self.assetCreatedAtKey)
+
+ try? context.save()
+ }
+
+ func loadEvents(taskID: String) -> [PointerPromptTaskEvent] {
+ guard let context else { return [] }
+
+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.eventEntityName)
+ request.predicate = NSPredicate(format: "%K == %@", Self.eventTaskIDKey, taskID)
+ request.sortDescriptors = [
+ NSSortDescriptor(key: Self.eventSequenceKey, ascending: true),
+ NSSortDescriptor(key: Self.eventCreatedAtKey, ascending: true)
+ ]
+
+ guard let managedEvents = try? context.fetch(request) else {
+ return []
+ }
+
+ return managedEvents.compactMap(Self.event(from:))
+ }
+
+ func appendEvent(_ event: PointerPromptTaskEvent) {
+ guard let context else { return }
+
+ let managedEvent = NSManagedObject(
+ entity: Self.eventEntityDescription(in: context),
+ insertInto: context
+ )
+ managedEvent.setValue(event.id, forKey: Self.eventIDKey)
+ managedEvent.setValue(event.taskID, forKey: Self.eventTaskIDKey)
+ managedEvent.setValue(event.role.rawValue, forKey: Self.eventRoleKey)
+ managedEvent.setValue(event.text, forKey: Self.eventTextKey)
+ managedEvent.setValue(Int64(event.sequence), forKey: Self.eventSequenceKey)
+ managedEvent.setValue(event.createdAt, forKey: Self.eventCreatedAtKey)
+
+ try? context.save()
+ }
+
+ private static func makeContext(storeURL: URL) -> NSManagedObjectContext? {
+ let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model())
+ do {
+ try FileManager.default.createDirectory(
+ at: storeURL.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try coordinator.addPersistentStore(
+ ofType: NSSQLiteStoreType,
+ configurationName: nil,
+ at: storeURL,
+ options: [
+ NSMigratePersistentStoresAutomaticallyOption: true,
+ NSInferMappingModelAutomaticallyOption: true
+ ]
+ )
+ } catch {
+ return nil
+ }
+
+ let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
+ context.persistentStoreCoordinator = coordinator
+ context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType)
+ return context
+ }
+
+ private static func defaultStoreURL() -> URL {
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("PointerPromptTasks.sqlite")
+ }
+
+ private static func model() -> NSManagedObjectModel {
+ let model = NSManagedObjectModel()
+ let taskEntity = NSEntityDescription()
+ taskEntity.name = taskEntityName
+ taskEntity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
+ taskEntity.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),
+ attribute(createdAtKey, type: .dateAttributeType, isOptional: false),
+ attribute(updatedAtKey, type: .dateAttributeType, isOptional: false)
+ ]
+ taskEntity.uniquenessConstraints = [[idKey]]
+
+ let eventEntity = NSEntityDescription()
+ eventEntity.name = eventEntityName
+ eventEntity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
+ eventEntity.properties = [
+ attribute(eventIDKey, type: .stringAttributeType, isOptional: false),
+ attribute(eventTaskIDKey, type: .stringAttributeType, isOptional: false),
+ attribute(eventRoleKey, type: .stringAttributeType, isOptional: false),
+ attribute(eventTextKey, type: .stringAttributeType, isOptional: false),
+ attribute(eventSequenceKey, type: .integer64AttributeType, isOptional: false),
+ attribute(eventCreatedAtKey, type: .dateAttributeType, isOptional: false)
+ ]
+ eventEntity.uniquenessConstraints = [[eventIDKey]]
+
+ let assetEntity = NSEntityDescription()
+ assetEntity.name = assetEntityName
+ assetEntity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
+ assetEntity.properties = [
+ attribute(assetIDKey, type: .stringAttributeType, isOptional: false),
+ attribute(assetTaskIDKey, type: .stringAttributeType, isOptional: false),
+ attribute(assetEventIDKey, type: .stringAttributeType, isOptional: true),
+ attribute(assetSourceKey, type: .stringAttributeType, isOptional: false),
+ attribute(assetDisplayNameKey, type: .stringAttributeType, isOptional: false),
+ attribute(assetContentTypeKey, type: .stringAttributeType, isOptional: false),
+ attribute(assetURLStringKey, type: .stringAttributeType, isOptional: false),
+ attribute(assetByteCountKey, type: .integer64AttributeType, isOptional: true),
+ attribute(assetCreatedAtKey, type: .dateAttributeType, isOptional: false)
+ ]
+ assetEntity.uniquenessConstraints = [[assetIDKey]]
+
+ model.entities = [taskEntity, eventEntity, assetEntity]
+ return model
+ }
+
+ private static func attribute(
+ _ name: String,
+ type: NSAttributeType,
+ isOptional: Bool
+ ) -> NSAttributeDescription {
+ let attribute = NSAttributeDescription()
+ attribute.name = name
+ attribute.attributeType = type
+ attribute.isOptional = isOptional
+ return attribute
+ }
+
+ private static func entityDescription(in context: NSManagedObjectContext) -> NSEntityDescription {
+ NSEntityDescription.entity(forEntityName: taskEntityName, in: context)!
+ }
+
+ private static func eventEntityDescription(in context: NSManagedObjectContext) -> NSEntityDescription {
+ NSEntityDescription.entity(forEntityName: eventEntityName, in: context)!
+ }
+
+ private static func assetEntityDescription(in context: NSManagedObjectContext) -> NSEntityDescription {
+ NSEntityDescription.entity(forEntityName: assetEntityName, in: context)!
+ }
+
+ private static func existingTask(id: String, in context: NSManagedObjectContext) -> NSManagedObject? {
+ let request = NSFetchRequest<NSManagedObject>(entityName: taskEntityName)
+ request.fetchLimit = 1
+ request.predicate = NSPredicate(format: "%K == %@", idKey, id)
+ return try? context.fetch(request).first
+ }
+
+ private func taskIDsWithMatchingEvents(_ query: String) -> [String] {
+ guard let context else { return [] }
+
+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.eventEntityName)
+ request.predicate = NSPredicate(format: "%K CONTAINS[cd] %@", Self.eventTextKey, query)
+
+ guard let managedEvents = try? context.fetch(request) else {
+ return []
+ }
+
+ return Array(Set(managedEvents.compactMap { $0.value(forKey: Self.eventTaskIDKey) as? String }))
+ }
+
+ private func taskIDsWithMatchingAssets(_ query: String) -> [String] {
+ guard let context else { return [] }
+
+ let request = NSFetchRequest<NSManagedObject>(entityName: Self.assetEntityName)
+ request.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [
+ NSPredicate(format: "%K CONTAINS[cd] %@", Self.assetDisplayNameKey, query),
+ NSPredicate(format: "%K CONTAINS[cd] %@", Self.assetContentTypeKey, query),
+ NSPredicate(format: "%K CONTAINS[cd] %@", Self.assetURLStringKey, query)
+ ])
+
+ guard let managedAssets = try? context.fetch(request) else {
+ return []
+ }
+
+ return Array(Set(managedAssets.compactMap { $0.value(forKey: Self.assetTaskIDKey) as? String }))
+ }
+
+ private static func task(from managedTask: NSManagedObject) -> PointerPromptNotchTask? {
+ 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,
+ let status = PointerPromptTaskStatus(rawValue: rawStatus),
+ let createdAt = managedTask.value(forKey: createdAtKey) as? Date,
+ let updatedAt = managedTask.value(forKey: updatedAtKey) as? Date else {
+ return nil
+ }
+
+ let accentIndex = (managedTask.value(forKey: accentIndexKey) as? NSNumber)?.intValue ?? 0
+ return PointerPromptNotchTask(
+ id: id,
+ title: title,
+ detail: detail,
+ commandText: managedTask.value(forKey: commandTextKey) as? String ?? title,
+ status: status,
+ accentIndex: accentIndex,
+ createdAt: createdAt,
+ updatedAt: updatedAt
+ )
+ }
+
+ private static func event(from managedEvent: NSManagedObject) -> PointerPromptTaskEvent? {
+ guard let id = managedEvent.value(forKey: eventIDKey) as? String,
+ let taskID = managedEvent.value(forKey: eventTaskIDKey) as? String,
+ let rawRole = managedEvent.value(forKey: eventRoleKey) as? String,
+ let role = PointerPromptTaskEventRole(rawValue: rawRole),
+ let text = managedEvent.value(forKey: eventTextKey) as? String,
+ let createdAt = managedEvent.value(forKey: eventCreatedAtKey) as? Date else {
+ return nil
+ }
+
+ let sequence = (managedEvent.value(forKey: eventSequenceKey) as? NSNumber)?.intValue ?? 0
+ return PointerPromptTaskEvent(
+ id: id,
+ taskID: taskID,
+ role: role,
+ text: text,
+ sequence: sequence,
+ createdAt: createdAt
+ )
+ }
+
+ private static func asset(from managedAsset: NSManagedObject) -> PointerPromptTaskAsset? {
+ guard let id = managedAsset.value(forKey: assetIDKey) as? String,
+ let taskID = managedAsset.value(forKey: assetTaskIDKey) as? String,
+ let rawSource = managedAsset.value(forKey: assetSourceKey) as? String,
+ let source = PointerPromptTaskAssetSource(rawValue: rawSource),
+ let displayName = managedAsset.value(forKey: assetDisplayNameKey) as? String,
+ let contentType = managedAsset.value(forKey: assetContentTypeKey) as? String,
+ let urlString = managedAsset.value(forKey: assetURLStringKey) as? String,
+ let createdAt = managedAsset.value(forKey: assetCreatedAtKey) as? Date else {
+ return nil
+ }
+
+ return PointerPromptTaskAsset(
+ id: id,
+ taskID: taskID,
+ eventID: managedAsset.value(forKey: assetEventIDKey) as? String,
+ source: source,
+ displayName: displayName,
+ contentType: contentType,
+ urlString: urlString,
+ byteCount: (managedAsset.value(forKey: assetByteCountKey) as? NSNumber)?.int64Value,
+ createdAt: createdAt
+ )
+ }
+
+ private static let taskEntityName = "PointerPromptStoredTask"
+ private static let eventEntityName = "PointerPromptStoredTaskEvent"
+ private static let assetEntityName = "PointerPromptStoredTaskAsset"
+ private static let idKey = "id"
+ private static let titleKey = "title"
+ private static let detailKey = "detail"
+ private static let commandTextKey = "commandText"
+ private static let statusKey = "status"
+ private static let accentIndexKey = "accentIndex"
+ private static let createdAtKey = "createdAt"
+ private static let updatedAtKey = "updatedAt"
+ private static let eventIDKey = "id"
+ private static let eventTaskIDKey = "taskID"
+ 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 = "taskID"
+ private static let assetEventIDKey = "eventID"
+ private static let assetSourceKey = "source"
+ private static let assetDisplayNameKey = "displayName"
+ private static let assetContentTypeKey = "contentType"
+ private static let assetURLStringKey = "urlString"
+ private static let assetByteCountKey = "byteCount"
+ private static let assetCreatedAtKey = "createdAt"
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift b/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift
new file mode 100644
index 00000000..e5e4a7aa
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift
@@ -0,0 +1,248 @@
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+public struct PointerPromptFollowUpCandidate: Codable, Equatable, Sendable {
+ public var taskID: String
+ public var title: String
+ public var detail: String
+ public var commandText: String
+ public var status: PointerPromptTaskStatus
+ public var updatedAt: Date
+ public var recentEvents: [String]
+ public var assetNames: [String]
+
+ public init(
+ taskID: String,
+ title: String,
+ detail: String,
+ commandText: String,
+ status: PointerPromptTaskStatus,
+ updatedAt: Date,
+ recentEvents: [String] = [],
+ assetNames: [String] = []
+ ) {
+ self.taskID = taskID
+ self.title = title
+ self.detail = detail
+ self.commandText = commandText
+ self.status = status
+ self.updatedAt = updatedAt
+ self.recentEvents = recentEvents
+ self.assetNames = assetNames
+ }
+}
+
+public struct PointerPromptFollowUpResolverRequest: Equatable, Sendable {
+ public var text: String
+ public var candidates: [PointerPromptFollowUpCandidate]
+ public var sourceTraceID: String
+ public var routeRequest: AIModelRouteRequest
+
+ public init(
+ text: String,
+ candidates: [PointerPromptFollowUpCandidate],
+ sourceTraceID: String,
+ routeRequest: AIModelRouteRequest = AIModelRouteRequest(
+ jobType: .taskIntent,
+ privacyMode: .privacySensitive,
+ latencyTolerance: .interactive
+ )
+ ) {
+ self.text = text
+ self.candidates = candidates
+ self.sourceTraceID = sourceTraceID
+ self.routeRequest = routeRequest
+ }
+}
+
+public struct PointerPromptFollowUpResolverResult: Equatable, Sendable {
+ public var taskID: String?
+ public var confidence: Double
+ public var reason: String
+ public var trace: AIModelCallTrace
+
+ public init(taskID: String?, confidence: Double, reason: String, trace: AIModelCallTrace) {
+ self.taskID = taskID
+ self.confidence = confidence
+ self.reason = reason
+ self.trace = trace
+ }
+}
+
+public protocol PointerPromptFollowUpResolving: Sendable {
+ func resolveFollowUp(_ request: PointerPromptFollowUpResolverRequest) async -> PointerPromptFollowUpResolverResult
+}
+
+public struct ProcessBackedLocalLLMTaskFollowUpResolver: PointerPromptFollowUpResolving {
+ public static let schemaID = "task_followup_resolution_v1"
+
+ public var router: AIModelRouter
+ public var sidecarRunner: any LocalJSONSidecarRunning
+ public var encoder: JSONEncoder
+ public var decoder: JSONDecoder
+
+ public init(
+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),
+ encoder: JSONEncoder = JSONEncoder(),
+ decoder: JSONDecoder = JSONDecoder()
+ ) {
+ self.router = router
+ self.sidecarRunner = sidecarRunner
+ self.encoder = encoder
+ self.decoder = decoder
+ }
+
+ public func resolveFollowUp(
+ _ request: PointerPromptFollowUpResolverRequest
+ ) async -> PointerPromptFollowUpResolverResult {
+ let entry: AIModelRegistryEntry
+ do {
+ entry = try router.route(request.routeRequest.limitingProviders([.localRuntime]))
+ } catch {
+ return result(
+ entry: nil,
+ request: request,
+ status: .invalidOutput,
+ validationStatus: "routingFailed",
+ latencyMS: nil,
+ metadata: ["error": String(describing: error)]
+ )
+ }
+
+ let input = LocalLLMTaskFollowUpSidecarRequest(
+ command: request.text,
+ candidates: request.candidates,
+ sourceTraceID: request.sourceTraceID,
+ modelID: entry.modelID,
+ metadata: [
+ "schemaID": Self.schemaID,
+ "promptVersion": entry.promptVersion
+ ]
+ )
+ let sidecarResult = await sidecarRunner.run(
+ LocalJSONSidecarRequest(
+ environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER",
+ inputData: (try? encoder.encode(input)) ?? Data(),
+ timeoutMS: entry.timeoutMS,
+ metadata: [
+ "sidecar.role": "taskFollowUpResolution",
+ "modelID": entry.modelID
+ ]
+ )
+ )
+
+ guard sidecarResult.status == .completed else {
+ return result(
+ entry: entry,
+ request: request,
+ status: sidecarResult.status == .timedOut ? .timeout : .providerOutage,
+ validationStatus: "notValidated",
+ latencyMS: sidecarResult.latencyMS,
+ metadata: sidecarResult.metadata.merging([
+ "sidecar.stderr": sidecarResult.stderrText
+ ]) { current, _ in current }
+ )
+ }
+
+ do {
+ let response = try decoder.decode(LocalLLMTaskFollowUpSidecarResponse.self, from: sidecarResult.outputData)
+ let decisionData = Data(response.outputText.utf8)
+ let decision = try decoder.decode(LocalLLMTaskFollowUpDecision.self, from: decisionData)
+ let validCandidateIDs = Set(request.candidates.map(\.taskID))
+ let taskID = decision.isFollowUp && validCandidateIDs.contains(decision.taskID) ? decision.taskID : nil
+ return PointerPromptFollowUpResolverResult(
+ taskID: taskID,
+ confidence: min(max(decision.confidence, 0), 1),
+ reason: decision.reason,
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: .completed,
+ validationStatus: taskID == nil ? "newTask" : "matchedTask",
+ latencyMS: sidecarResult.latencyMS,
+ metadata: sidecarResult.metadata.merging(response.metadata) { current, _ in current }
+ )
+ )
+ } catch {
+ return result(
+ entry: entry,
+ request: request,
+ status: .invalidOutput,
+ validationStatus: "invalid",
+ latencyMS: sidecarResult.latencyMS,
+ metadata: sidecarResult.metadata.merging([
+ "error": String(describing: error)
+ ]) { current, _ in current }
+ )
+ }
+ }
+
+ private func result(
+ entry: AIModelRegistryEntry?,
+ request: PointerPromptFollowUpResolverRequest,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ latencyMS: Double?,
+ metadata: [String: String] = [:]
+ ) -> PointerPromptFollowUpResolverResult {
+ PointerPromptFollowUpResolverResult(
+ taskID: nil,
+ confidence: 0,
+ reason: metadata["error"] ?? metadata["reason"] ?? "",
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: status,
+ validationStatus: validationStatus,
+ latencyMS: latencyMS,
+ metadata: metadata
+ )
+ )
+ }
+
+ private func trace(
+ entry: AIModelRegistryEntry?,
+ request: PointerPromptFollowUpResolverRequest,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ latencyMS: Double?,
+ metadata: [String: String] = [:]
+ ) -> AIModelCallTrace {
+ AIModelCallTrace(
+ id: "model-call-\(request.sourceTraceID)",
+ role: entry?.role ?? .taskIntent,
+ provider: entry?.provider ?? .localRuntime,
+ modelID: entry?.modelID ?? "unrouted",
+ promptVersion: entry?.promptVersion ?? "unrouted",
+ schemaID: Self.schemaID,
+ latencyMS: latencyMS,
+ timeoutMS: entry?.timeoutMS ?? 0,
+ status: status,
+ validationStatus: validationStatus,
+ sourceTraceID: request.sourceTraceID,
+ metadata: metadata
+ )
+ }
+}
+
+private struct LocalLLMTaskFollowUpSidecarRequest: Codable, Equatable, Sendable {
+ var command: String
+ var candidates: [PointerPromptFollowUpCandidate]
+ var sourceTraceID: String
+ var modelID: String
+ var metadata: [String: String]
+}
+
+private struct LocalLLMTaskFollowUpSidecarResponse: Codable, Equatable, Sendable {
+ var outputText: String
+ var metadata: [String: String]
+}
+
+private struct LocalLLMTaskFollowUpDecision: Codable, Equatable, Sendable {
+ var isFollowUp: Bool
+ var taskID: String
+ var confidence: Double
+ var reason: String
+}
diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptTaskContracts.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptTaskContracts.swift
new file mode 100644
index 00000000..2fc37a28
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptTaskContracts.swift
@@ -0,0 +1,133 @@
+import Foundation
+
+public enum PointerPromptTaskStatus: String, Codable, Equatable, Sendable {
+ case running
+ case paused
+ case completed
+ case needsAttention
+ case failed
+}
+
+public struct PointerPromptNotchTask: Codable, Equatable, Identifiable, Sendable {
+ public var id: String
+ public var title: String
+ public var detail: String
+ public var commandText: String
+ public var status: PointerPromptTaskStatus
+ public var accentIndex: Int
+ public var createdAt: Date
+ public var updatedAt: Date
+
+ public init(
+ id: String,
+ title: String,
+ detail: String,
+ commandText: String = "",
+ status: PointerPromptTaskStatus,
+ accentIndex: Int,
+ createdAt: Date = Date(),
+ updatedAt: Date = Date()
+ ) {
+ self.id = id
+ self.title = title
+ self.detail = detail
+ self.commandText = commandText
+ self.status = status
+ self.accentIndex = accentIndex
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ }
+}
+
+public enum PointerPromptTaskEventRole: String, Codable, Equatable, Sendable {
+ case user
+ case assistant
+ case system
+ case tool
+}
+
+public struct PointerPromptTaskEvent: Codable, Equatable, Identifiable, Sendable {
+ public var id: String
+ public var taskID: String
+ public var role: PointerPromptTaskEventRole
+ public var text: String
+ public var sequence: Int
+ public var createdAt: Date
+
+ public init(
+ id: String,
+ taskID: String,
+ role: PointerPromptTaskEventRole,
+ text: String,
+ sequence: Int,
+ createdAt: Date = Date()
+ ) {
+ self.id = id
+ self.taskID = taskID
+ self.role = role
+ self.text = text
+ self.sequence = sequence
+ self.createdAt = createdAt
+ }
+}
+
+public enum PointerPromptTaskAssetSource: String, Codable, Equatable, Sendable {
+ case userUploaded
+ case agentReturned
+}
+
+public struct PointerPromptTaskAsset: Codable, Equatable, Identifiable, Sendable {
+ public var id: String
+ public var taskID: String
+ public var eventID: String?
+ public var source: PointerPromptTaskAssetSource
+ public var displayName: String
+ public var contentType: String
+ public var urlString: String
+ public var byteCount: Int64?
+ public var createdAt: Date
+
+ public init(
+ id: String,
+ taskID: String,
+ eventID: String? = nil,
+ source: PointerPromptTaskAssetSource,
+ displayName: String,
+ contentType: String,
+ urlString: String,
+ byteCount: Int64? = nil,
+ createdAt: Date = Date()
+ ) {
+ self.id = id
+ self.taskID = taskID
+ self.eventID = eventID
+ self.source = source
+ self.displayName = displayName
+ self.contentType = contentType
+ self.urlString = urlString
+ self.byteCount = byteCount
+ self.createdAt = createdAt
+ }
+}
+
+public struct PointerPromptTaskAssetDraft: Codable, Equatable, Sendable {
+ public var source: PointerPromptTaskAssetSource
+ public var displayName: String
+ public var contentType: String
+ public var urlString: String
+ public var byteCount: Int64?
+
+ public init(
+ source: PointerPromptTaskAssetSource = .userUploaded,
+ displayName: String,
+ contentType: String,
+ urlString: String,
+ byteCount: Int64? = nil
+ ) {
+ self.source = source
+ self.displayName = displayName
+ self.contentType = contentType
+ self.urlString = urlString
+ self.byteCount = byteCount
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
index 5fe1d944..43eaa6a3 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
@@ -218,6 +218,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
)
}
+ await coordinator?.waitIfPaused()
let launchStartedAt = Self.uptimeMilliseconds()
await coordinator?.recordToolEvent(
capability: .input,
@@ -261,6 +262,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
if !accessibilityCommands.isEmpty {
let accessibilityEngine = Self.accessibilityActionEngine(for: definition)
for (index, actionCommand) in accessibilityCommands.enumerated() {
+ await coordinator?.waitIfPaused()
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 60))
let actionStartedAt = Self.uptimeMilliseconds()
await coordinator?.recordToolEvent(
@@ -303,6 +305,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
var keyboardActionMS = 0.0
for (index, actionCommand) in commands.enumerated() {
+ await coordinator?.waitIfPaused()
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40))
let actionStartedAt = Self.uptimeMilliseconds()
await coordinator?.recordToolEvent(
@@ -376,7 +379,9 @@ public struct LocalAppTaskLiveRunner: Sendable {
}
runMetadata["latency.keyboardActionMS"] = Self.formatLatency(keyboardActionMS)
+ await coordinator?.waitIfPaused()
try? await Task.sleep(nanoseconds: 700_000_000)
+ await coordinator?.waitIfPaused()
let observationStartedAt = Self.uptimeMilliseconds()
await coordinator?.recordToolEvent(
capability: .perception,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
index 684a9d13..97582da6 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
@@ -10,6 +10,7 @@ public actor RunCoordinator {
private var lifecycleState: RunLifecycleState = .idle
private var requiresInputRelease = false
private var activeTraceID: String?
+ private var pauseContinuations: [CheckedContinuation<Void, Never>] = []
public init(
sessionQueue: LatestRunSessionQueue = LatestRunSessionQueue(),
@@ -61,6 +62,17 @@ public actor RunCoordinator {
public func resume(reason: String? = nil) async {
await transition(to: .running, reason: reason ?? "Run resumed")
+ let continuations = pauseContinuations
+ pauseContinuations.removeAll()
+ continuations.forEach { $0.resume() }
+ }
+
+ public func waitIfPaused() async {
+ guard lifecycleState == .paused else { return }
+
+ await withCheckedContinuation { continuation in
+ pauseContinuations.append(continuation)
+ }
}
public func complete(reason: String? = nil) async {
diff --git a/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift
index 669b253c..ec6ab3c3 100644
--- a/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift
+++ b/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift
@@ -1,5 +1,7 @@
import DonkeyContracts
+import Foundation
import SwiftUI
+import UniformTypeIdentifiers
public struct PointerPromptNotchStatusView: View {
private let state: PointerPromptState
@@ -12,12 +14,14 @@ public struct PointerPromptNotchStatusView: View {
@Binding private var commandText: String
private let commandInputTextHeight: CGFloat
private let isCommandInputExpanded: Bool
+ private let tasks: [PointerPromptNotchTask]
private let accentIndex: Int
private let commandSubmitted: @MainActor (String) -> Void
private let commandInputTextHeightChanged: @MainActor (CGFloat) -> Void
private let commandInputExpansionChanged: @MainActor (Bool) -> Void
- private let pauseRequested: @MainActor () -> Void
- private let resumeRequested: @MainActor () -> Void
+ private let assetsDropped: @MainActor ([PointerPromptTaskAssetDraft]) -> Void
+ private let pauseRequested: @MainActor (String) -> Void
+ private let resumeRequested: @MainActor (String) -> Void
private let updateRequested: @MainActor () -> Void
public init(
@@ -31,12 +35,14 @@ public struct PointerPromptNotchStatusView: View {
commandText: Binding<String>,
commandInputTextHeight: CGFloat,
isCommandInputExpanded: Bool,
+ tasks: [PointerPromptNotchTask] = [],
accentIndex: Int,
commandSubmitted: @escaping @MainActor (String) -> Void,
commandInputTextHeightChanged: @escaping @MainActor (CGFloat) -> Void,
commandInputExpansionChanged: @escaping @MainActor (Bool) -> Void,
- pauseRequested: @escaping @MainActor () -> Void,
- resumeRequested: @escaping @MainActor () -> Void,
+ assetsDropped: @escaping @MainActor ([PointerPromptTaskAssetDraft]) -> Void,
+ pauseRequested: @escaping @MainActor (String) -> Void,
+ resumeRequested: @escaping @MainActor (String) -> Void,
updateRequested: @escaping @MainActor () -> Void
) {
self.state = state
@@ -49,10 +55,12 @@ public struct PointerPromptNotchStatusView: View {
_commandText = commandText
self.commandInputTextHeight = commandInputTextHeight
self.isCommandInputExpanded = isCommandInputExpanded
+ self.tasks = tasks
self.accentIndex = accentIndex
self.commandSubmitted = commandSubmitted
self.commandInputTextHeightChanged = commandInputTextHeightChanged
self.commandInputExpansionChanged = commandInputExpansionChanged
+ self.assetsDropped = assetsDropped
self.pauseRequested = pauseRequested
self.resumeRequested = resumeRequested
self.updateRequested = updateRequested
@@ -108,6 +116,12 @@ public struct PointerPromptNotchStatusView: View {
y: isExpanded ? 12 : 0
)
.animation(isExpanded ? Self.openEnvelopeAnimation : Self.closeEnvelopeAnimation, value: isExpanded)
+ .contentShape(Rectangle())
+ .onDrop(
+ of: [UTType.fileURL],
+ isTargeted: nil,
+ perform: handleDroppedFileProviders
+ )
}
@ViewBuilder
@@ -211,8 +225,16 @@ public struct PointerPromptNotchStatusView: View {
VStack(spacing: 0) {
ScrollView(.vertical, showsIndicators: false) {
- currentTaskRow
- .padding(.top, 10)
+ VStack(spacing: 8) {
+ if tasks.isEmpty {
+ currentTaskRow
+ } else {
+ ForEach(tasks) { task in
+ taskRow(task)
+ }
+ }
+ }
+ .padding(.top, 10)
}
commandRow
@@ -299,9 +321,7 @@ public struct PointerPromptNotchStatusView: View {
Spacer()
- if isActiveTask {
- activeTaskControls
- } else if isWorking {
+ if isWorking {
activityBars(color: accentColor)
}
}
@@ -311,6 +331,37 @@ public struct PointerPromptNotchStatusView: View {
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
}
+ private func taskRow(_ task: PointerPromptNotchTask) -> some View {
+ HStack(spacing: 12) {
+ TaskArrowMark(color: accentColor(for: task.accentIndex))
+ .frame(width: 14, height: 14)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(task.title)
+ .font(.system(size: 13, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.9))
+ .lineLimit(1)
+
+ Text(taskStatusDescription(task))
+ .font(.system(size: 12, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.42))
+ .lineLimit(1)
+ }
+
+ Spacer()
+
+ if task.status == .running || task.status == .paused {
+ activeTaskControls(for: task)
+ } else {
+ taskStatusAccessory(task)
+ }
+ }
+ .padding(.horizontal, 12)
+ .frame(height: 48)
+ .background(Color.white.opacity(0.055))
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+
private var commandRow: some View {
PointerPromptComposer(
state: commandInputState,
@@ -335,6 +386,37 @@ public struct PointerPromptNotchStatusView: View {
commandSubmitted(text)
}
+ private func handleDroppedFileProviders(_ providers: [NSItemProvider]) -> Bool {
+ let fileProviders = providers.filter {
+ $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier)
+ }
+ guard !fileProviders.isEmpty else { return false }
+
+ let group = DispatchGroup()
+ let collector = DroppedAssetCollector()
+ for provider in fileProviders {
+ group.enter()
+ provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, _ in
+ defer { group.leave() }
+ guard let url = DroppedAssetUtilities.fileURL(from: item),
+ let draft = DroppedAssetUtilities.assetDraft(for: url) else {
+ return
+ }
+
+ collector.append(draft)
+ }
+ }
+ group.notify(queue: .main) {
+ let drafts = collector.values()
+ guard !drafts.isEmpty else { return }
+
+ Task { @MainActor in
+ assetsDropped(drafts)
+ }
+ }
+ return true
+ }
+
private var commandInputState: PointerPromptState {
PointerPromptState(
promptText: "Ask for follow-up changes",
@@ -346,20 +428,24 @@ public struct PointerPromptNotchStatusView: View {
)
}
- private var activeTaskControls: some View {
+ private func activeTaskControls(for task: PointerPromptNotchTask) -> some View {
HStack(spacing: 6) {
statusControlButton(
systemName: "play.fill",
label: "Resume",
- isEnabled: isCurrentTaskPaused,
- action: resumeRequested
+ isEnabled: task.status == .paused,
+ action: {
+ resumeRequested(task.id)
+ }
)
statusControlButton(
systemName: "pause.fill",
label: "Pause",
- isEnabled: !isCurrentTaskPaused,
- action: pauseRequested
+ isEnabled: task.status == .running,
+ action: {
+ pauseRequested(task.id)
+ }
)
}
}
@@ -394,7 +480,39 @@ public struct PointerPromptNotchStatusView: View {
.frame(width: 18, height: height)
}
+ @ViewBuilder
+ private func taskStatusAccessory(_ task: PointerPromptNotchTask) -> some View {
+ switch task.status {
+ case .running:
+ activityBars(color: accentColor(for: task.accentIndex))
+ case .paused:
+ Image(systemName: "pause.fill")
+ .font(.system(size: 10, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.5))
+ .frame(width: 18, height: 18)
+ case .completed:
+ Image(systemName: "checkmark")
+ .font(.system(size: 11, weight: .regular))
+ .foregroundStyle(accentColor(for: task.accentIndex))
+ .frame(width: 18, height: 18)
+ case .needsAttention:
+ Image(systemName: "exclamationmark")
+ .font(.system(size: 12, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.62))
+ .frame(width: 18, height: 18)
+ case .failed:
+ Image(systemName: "xmark")
+ .font(.system(size: 11, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.55))
+ .frame(width: 18, height: 18)
+ }
+ }
+
private var taskTitle: String {
+ if let primaryTask {
+ return primaryTask.title
+ }
+
if let taskDisplayText {
return taskDisplayText
}
@@ -410,6 +528,10 @@ public struct PointerPromptNotchStatusView: View {
}
private var statusDescription: String {
+ if let primaryTask {
+ return taskStatusDescription(primaryTask)
+ }
+
if isCurrentTaskPaused {
return "Paused"
}
@@ -425,15 +547,15 @@ public struct PointerPromptNotchStatusView: View {
}
private var isWorking: Bool {
- state.leadingSignalLevel == .thinking
+ primaryTask?.status == .running || state.leadingSignalLevel == .thinking
}
private var isActiveTask: Bool {
- isWorking || isCurrentTaskPaused
+ isWorking || isCurrentTaskPaused || primaryTask?.status == .paused
}
private var hasTaskDisplayText: Bool {
- taskDisplayText != nil
+ !tasks.isEmpty || taskDisplayText != nil
}
private var taskDisplayText: String? {
@@ -453,7 +575,34 @@ public struct PointerPromptNotchStatusView: View {
}
private var accentColor: Color {
- Self.accentColors[((accentIndex % Self.accentColors.count) + Self.accentColors.count) % Self.accentColors.count]
+ accentColor(for: primaryTask?.accentIndex ?? accentIndex)
+ }
+
+ private var primaryTask: PointerPromptNotchTask? {
+ tasks.first
+ }
+
+ private func isPrimaryTask(_ task: PointerPromptNotchTask) -> Bool {
+ task.id == primaryTask?.id
+ }
+
+ private func taskStatusDescription(_ task: PointerPromptNotchTask) -> String {
+ switch task.status {
+ case .running:
+ return task.detail.isEmpty ? "Running" : task.detail
+ case .paused:
+ return "Paused"
+ case .completed:
+ return task.detail.isEmpty ? "Done" : task.detail
+ case .needsAttention:
+ return task.detail.isEmpty ? "Needs attention" : task.detail
+ case .failed:
+ return task.detail.isEmpty ? "Stopped" : task.detail
+ }
+ }
+
+ private func accentColor(for index: Int) -> Color {
+ Self.accentColors[((index % Self.accentColors.count) + Self.accentColors.count) % Self.accentColors.count]
}
private static let accentColors: [Color] = [
@@ -506,3 +655,59 @@ private struct TaskArrowMark: View {
.accessibilityHidden(true)
}
}
+
+private final class DroppedAssetCollector: @unchecked Sendable {
+ private let lock = NSLock()
+ private var drafts: [PointerPromptTaskAssetDraft] = []
+
+ func append(_ draft: PointerPromptTaskAssetDraft) {
+ lock.lock()
+ drafts.append(draft)
+ lock.unlock()
+ }
+
+ func values() -> [PointerPromptTaskAssetDraft] {
+ lock.lock()
+ let snapshot = drafts
+ lock.unlock()
+ return snapshot
+ }
+}
+
+private enum DroppedAssetUtilities {
+ static func fileURL(from item: NSSecureCoding?) -> URL? {
+ if let url = item as? URL {
+ return url
+ }
+
+ if let data = item as? Data {
+ return URL(dataRepresentation: data, relativeTo: nil)
+ }
+
+ if let string = item as? String {
+ return URL(string: string)
+ }
+
+ if let string = item as? NSString {
+ return URL(string: string as String)
+ }
+
+ return nil
+ }
+
+ static func assetDraft(for url: URL) -> PointerPromptTaskAssetDraft? {
+ guard url.isFileURL else { return nil }
+
+ let contentType = (try? url.resourceValues(forKeys: [.contentTypeKey]).contentType?.preferredMIMEType)
+ ?? UTType(filenameExtension: url.pathExtension)?.preferredMIMEType
+ ?? "application/octet-stream"
+ let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
+ let byteCount = (attributes?[.size] as? NSNumber)?.int64Value
+ return PointerPromptTaskAssetDraft(
+ displayName: url.lastPathComponent,
+ contentType: contentType,
+ urlString: url.absoluteString,
+ byteCount: byteCount
+ )
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/RunCoordinatorTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/RunCoordinatorTests.swift
index a9e154ae..ec6bba92 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/RunCoordinatorTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/RunCoordinatorTests.swift
@@ -82,6 +82,41 @@ struct RunCoordinatorTests {
})
}
+ @Test
+ func waitIfPausedBlocksUntilResume() async {
+ let coordinator = RunCoordinator()
+
+ _ = await coordinator.start(
+ RunSession(
+ id: "session-paused-gate",
+ userGoal: "wait while paused",
+ targetID: "target-1"
+ )
+ )
+ await coordinator.pause(reason: "operator paused")
+
+ let gate = Task {
+ await coordinator.waitIfPaused()
+ return true
+ }
+ let completedBeforeResume = await withTaskGroup(of: Bool.self) { group in
+ group.addTask {
+ await gate.value
+ }
+ group.addTask {
+ try? await Task.sleep(nanoseconds: 50_000_000)
+ return false
+ }
+ let firstResult = await group.next() ?? false
+ group.cancelAll()
+ return firstResult
+ }
+ #expect(completedBeforeResume == false)
+
+ await coordinator.resume(reason: "operator resumed")
+ #expect(await gate.value == true)
+ }
+
@Test
func latestSessionQueueDropsStaleSessions() async {
let queue = LatestRunSessionQueue()
diff --git a/docs/architecture.md b/docs/architecture.md
index c7a00f01..5bd344e6 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -12,28 +12,34 @@ source of truth for behavior and boundaries remains
| |
| +----------------------+ +----------------------+ +---------------+ |
| | Pointer Prompt UI | | Runtime Setup UI | | Debug CLI | |
-| | typed/voice command | | install runtimes | | smoke tools | |
+| | text/voice/assets | | install runtimes | | smoke tools | |
| +----------+-----------+ +----------+-----------+ +-------+-------+ |
| | | | |
| v v v |
| +----------------------+ +----------------------+ +---------------+ |
-| | Command Intake | | Local Runtime Setup | | Manual Target | |
-| | text/transcript | | manifests/cache | | Capture | |
+| | Task Thread Intake | | Local Runtime Setup | | Manual Target | |
+| | route + persist | | manifests/cache | | Capture | |
| +----------+-----------+ +----------+-----------+ +-------+-------+ |
| | | | |
| v v v |
| +----------------------+ +----------------------+ +---------------+ |
-| | Task Intent Resolver |<---->| Runtime Registry | | Artifact Store| |
-| | validated TaskIntent | | sidecar executables | | traces/files | |
+| | Follow-up Resolver |<---->| Runtime Registry | | Artifact Store| |
+| | recent task match | | sidecar executables | | traces/files | |
| +----------+-----------+ +----------------------+ +-------+-------+ |
| | ^ |
| v | |
| +----------------------+ +----------------------+ +-------+-------+ |
-| | RunCoordinator |----->| Event Stream |----->| Status/Reports| |
-| | lifecycle + policy | | assistant/tool/etc. | | latency/replay| |
-| +----------+-----------+ +----------------------+ +---------------+ |
-| | |
-| v |
+| | Core Data Task Store |----->| Notch Task List |----->| Status/Reports| |
+| | tasks/events/assets | | recent threads | | latency/replay| |
+| +----------+-----------+ +----------------------+ +-------+-------+ |
+| | ^ |
+| v | |
+| +----------------------+ +----------------------+ | |
+| | Task Intent Resolver |<---->| Per-Task Coordinator |--------------+ |
+| | validated TaskIntent | | lifecycle + policy | |
+| +----------+-----------+ +----------+-----------+ |
+| | | |
+| v v |
| +----------------------+ +----------------------+ +---------------+ |
| | Local App Runner |----->| Capture/Observation |----->| Action Engine | |
| | dry-run or guarded | | AX/window/screenshot | | keyboard/AX | |
@@ -42,11 +48,45 @@ source of truth for behavior and boundaries remains
+--------------------------------------------------------------------------------+
```
-The app shell owns user entrypoints and setup. `RunCoordinator` owns lifecycle,
-event ordering, permission policy, bounded context assembly, and reflex trace
-publication. Capture, observation, model sidecars, task adaptation, and input
+The app shell owns entrypoints, durable task threads, setup, and per-task runtime
+coordination. Capture, observation, model sidecars, task adaptation, and input
execution stay behind narrow runtime boundaries.
+## Pointer Prompt Task Threads
+
+```text
++--------------------------------------------------------------------------------+
+| Durable Task Threads |
++--------------------------------------------------------------------------------+
+| |
+| +----------------------+ +----------------------+ +---------------+ |
+| | Cmd-Cmd Input | | Notch Composer | | File Drop | |
+| | text/voice | | follow-up text | | collapsed ok | |
+| +----------+-----------+ +----------+-----------+ +-------+-------+ |
+| | | | |
+| +-------------+---------------+ | |
+| | | |
+| v v |
+| +----------------------+ +----------------------+ +---------------+ |
+| | Recent Tasks |----->| Follow-up LLM |----->| Task Select | |
+| | updatedAt order | | match or new | | existing/new | |
+| +----------+-----------+ +----------------------+ +-------+-------+ |
+| ^ | |
+| | v |
+| +----------------------+ +----------------------+ +---------------+ |
+| | Core Data |<-----| Task Events |<-----| Agent Run | |
+| | task/event/asset | | user/assistant/tool | | command path | |
+| +----------+-----------+ +----------------------+ +-------+-------+ |
+| ^ | |
+| | v |
+| +----------------------+ +----------------------+ +---------------+ |
+| | Asset Files | | Coordinator Registry |----->| RunCoordinator| |
+| | App Support | | taskID -> run | | pause/resume | |
+| +----------------------+ +----------------------+ +---------------+ |
+| |
++--------------------------------------------------------------------------------+
+```
+
## Fast Local Runloop
```text
@@ -54,18 +94,18 @@ execution stay behind narrow runtime boundaries.
| Fast Local Navigation Hot Path |
+--------------------------------------------------------------------------------+
| |
-| user command or transcript |
+| selected task command |
| | |
| v |
| +----------------------+ +----------------------+ +---------------+ |
-| | Task Definitions |----->| Local LLM Parser |----->| TaskIntent | |
-| | built-in + JSON/JSONL| | sidecar JSON schema | | validated | |
+| | Task Context |----->| Local LLM Parser |----->| TaskIntent | |
+| | command/events/assets| | sidecar JSON schema | | validated | |
| +----------+-----------+ +----------------------+ +-------+-------+ |
| | | |
| v v |
| +----------------------+ +----------------------+ +---------------+ |
-| | Catalog Resolution |----->| Local App Adapter |----->| Run Request | |
-| | app/task available | | steps + verification | | target + plan | |
+| | Catalog Resolution |----->| Local App Adapter |----->| Task Run | |
+| | app/task available | | steps + verification | | per-task coord| |
| +----------------------+ +----------+-----------+ +-------+-------+ |
| | | |
| v v |
diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.md
index f04921e1..3eafff2a 100644
--- a/docs/guides/pointer-prompt-overlay.md
+++ b/docs/guides/pointer-prompt-overlay.md
@@ -8,6 +8,7 @@ Donkey supports a floating macOS pointer prompt overlay:
- double-tap Command and hold the second Command press to activate voice input
- shows a notch-anchored black status panel flush with the top center of the current screen
- sizes the notch status panel from `NSScreen.safeAreaInsets` and `auxiliaryTopLeftArea` / `auxiliaryTopRightArea`, with fallback dimensions for non-reporting displays
+- uses a common fixed collapsed notch slot on external monitors and Macs without a physical notch, keeping the same top-center position while treating the full slot as renderable space
- keeps status text below the physical notch void while the black panel visually extends the notch
- renders the resting collapsed notch as a slim arrow-only strip beside the physical notch, without adding black padding over the notch void
- starts the resting notch envelope as an arrow lane plus physical notch void plus empty trailing lane, so the arrow remains visible and hover expansion grows from the real collapsed strip
@@ -20,12 +21,12 @@ Donkey supports a floating macOS pointer prompt overlay:
- keeps the notch arrow mark pointed up-right at a fixed 45-degree angle
- uses regular-weight notch text; collapsed and expanded notch labels should not render bold text
- expands one notch status surface outward and downward together on hover, with width, height, bottom corner radius, and shadow using one native spring; collapse uses a short ease-out without a spring tail
-- matches the `/prototype` notch dimensions while using a native macOS spring envelope: surface `110x28` to `480x280`, interaction container `520x300`, corner radius `14` to `26`, and `spring(response: 0.55, dampingFraction: 0.82)`
+- uses a native macOS spring envelope from a shared collapsed top-center slot to the expanded `480x280` content surface, with interaction container `520x300`, corner radius `14` to `26`, and `spring(response: 0.55, dampingFraction: 0.82)`
- lays out collapsed and expanded notch content inside the animated, clipped surface so content reveals and reflows with the current surface width
- fades collapsed notch content out quickly, then fades expanded content in after the surface has started expanding
- shows an update button in the expanded notch header when Sparkle reports a valid appcast update
- accepts mouse clicks in the notch status panel so expanded header and command-row controls can invoke their actions
-- shows pause and resume controls for an active task in the expanded notch panel and routes them through the pointer-prompt command handler
+- shows per-task pause and resume controls for running or paused tasks in the expanded notch panel and routes them through the pointer-prompt command handler
- shows a black prompt modal with text input and a white voice waveform while active
- uses a wide pill-shaped prompt for single-line text, then expands to a rounded rectangle when text wraps at the max input width or the user inserts new lines
- places the waveform in a bottom toolbar that blends with the input background when the prompt is expanded
@@ -38,8 +39,11 @@ Donkey supports a floating macOS pointer prompt overlay:
- opens the prompt input centered on the current screen instead of following the cursor
- dismisses the centered prompt after submission and moves visible progress/result feedback into the notch status panel
- submits typed prompt text through the local-app command pipeline while keeping model parsing, task validation, and live input outside the SwiftUI rendering path
+- records each submitted typed or transcribed command as a durable, searchable Core Data task/run so a double-Command prompt submission immediately appears in the expanded notch menu with running, paused, completed, review, or failed status; multiple task runs may be active at once
+- routes new typed submissions through a local LLM follow-up classifier that compares the text to recently updated task runs, continues the matched run when confidence is high, and creates a fresh run when no recent task clearly matches
+- accepts user file drops on the notch surface, including the collapsed/non-expanded notch, and persists those files as user-uploaded task assets on the active or most recent task
-This is a visual, typed-command, and voice-command UI capability. Typed submissions go to the local-app command handler, which loads built-in plus local JSON/JSONL task definitions, prefers local-model task-intent parsing, validates the intent against the app-task catalog, and then runs the guarded local-app live runner. Voice submissions produce local transcript text through the Parakeet-only transcription boundary before entering that same command handler. Review-only document tasks can return a compact review summary such as the number of mapped fields. The overlay itself does not capture the screen, synthesize input, or require Accessibility permission. It does request microphone permission for local waveform capture and voice commands.
+This is a visual, typed-command, voice-command, and task-threading UI capability. Typed submissions first pass through task-thread routing: recent tasks are ordered by update time and a local LLM classifier decides whether the submission is a follow-up to one of them. Matched follow-ups append to that task's event history before the local-app command handler runs with the task context; unmatched submissions create a new task. The command handler loads built-in plus local JSON/JSONL task definitions, prefers local-model task-intent parsing, validates the intent against the app-task catalog, and then runs the guarded local-app live runner. Each durable task run gets its own runtime coordinator so pause/resume applies to the selected task rather than a global current run. Voice submissions produce local transcript text through the Parakeet-only transcription boundary before entering that same task-thread routing and command handler flow. Review-only document tasks can return a compact review summary such as the number of mapped fields. The overlay itself does not capture the screen, synthesize input, or require Accessibility permission. It does request microphone permission for local waveform capture and voice commands.
## Technical Guidelines
@@ -47,6 +51,7 @@ This is a visual, typed-command, and voice-command UI capability. Typed submissi
- Donkey runs with the accessory activation policy, and prompt focus must make the app active, make the panel key, then make the composer text view first responder. A blinking insertion point alone does not mean macOS is sending keyboard events to the panel.
- SwiftUI rendering stays in `DonkeyUI`; it receives `PointerPromptState` and `PointerPromptPlacement` from `DonkeyContracts`.
- Product state stays in `PointerPromptOverlayModel`.
+- Notch tasks are durable product state persisted through Core Data in Application Support. Treat each task as an agent run: task metadata drives the notch's recent slice, ordered task events preserve user messages, assistant/LLM responses, system notes, and tool summaries for back-and-forth history, and task assets can record files uploaded by the user or returned by the agent. Store search should include task title, detail, original command text, event text, and asset metadata. Recent task selection and follow-up classification should prioritize `updatedAt`, not original creation time.
- Treat the active modal as a compact black prompt surface with a text input and embedded waveform. It has no visible close button and no separate voice button.
- Single-line input should render as a full pill. Multiline input should render as a rounded rectangle with non-pill corners and a bottom toolbar matching the input background, containing the waveform without a divider between text and toolbar. The plus and permissions controls may remain available in code for future wiring, but should not render while non-functional.
- The text input should use 16pt light system UI text with ligatures disabled, matching thin `-apple-system` sans-serif web input rendering.
@@ -56,14 +61,14 @@ This is a visual, typed-command, and voice-command UI capability. Typed submissi
- The active prompt modal should use a capsule shape and keep transparent active overlay space passing clicks through to windows underneath after it dismisses.
- Pointer drawing and theme code may remain available for future features, but the prompt overlay should not render a visible cursor.
- Runtime placement remains fixed to `bottomRight` for compatibility with the existing view contract; the rendered input panel itself is centered and no longer uses pointer-relative geometry.
-- The notch status panel should keep its visual language aligned with the `/prototype` route without exposing agent names or implementation roles: a slim arrow-only resting mark beside the physical notch, a minimal one-line task label when collapsed and active, and a compact expanded surface with the arrow anchored left of the notch void in the same row as the physical notch. When no task text exists, the expanded surface should render the shared double-Command prompt composer in-place as a padded follow-up editor with a darker gray rounded-rectangle fill, normal macOS text scale, only a small circular send button in the toolbar, and multiline resizing up to the shared composer text-height cap before the text view scrolls. Opening or clicking the expanded status panel should focus the composer input. When task text exists, it should show the colored arrow, task title, status, active pause/resume controls when running, a scrollable task-item area, and the shared composer row.
+- The notch status panel should keep its visual language aligned with the `/prototype` route without exposing agent names or implementation roles: a slim arrow-only resting mark beside the physical notch when one exists, a minimal one-line task label when collapsed and active, and a compact expanded surface with the arrow anchored left of the notch void in the same row as the physical notch. On external monitors and Macs without a physical notch, the collapsed top-center slot should keep the same fixed size and position but have no unavailable void, so the whole slot can render status data. When no task text exists, the expanded surface should render the shared double-Command prompt composer in-place as a padded follow-up editor with a darker gray rounded-rectangle fill, normal macOS text scale, only a small circular send button in the toolbar, and multiline resizing up to the shared composer text-height cap before the text view scrolls. Opening or clicking the expanded status panel should focus the composer input. When task text exists, it should show the colored arrow, task title, status, active pause/resume controls when running, a scrollable task-item area, and the shared composer row.
- SwiftUI notch rendering should consume `PointerPromptNotchLayout` for derived surface/content frames, corner radii, and notch-safe content offsets instead of duplicating screen-geometry constants in the view.
- Hover activation should be bounded to the visible notch surface using controller-side mouse location checks. The transparent host panel and expanded interaction padding must not trigger expansion or keep the notch expanded by themselves.
- The native status panel should not animate its frame while the SwiftUI notch surface animates. When expansion starts, resize the panel to expanded render bounds with AppKit animations disabled, render the collapsed notch once in that expanded host, then flip SwiftUI expansion state on the next frame; after the short non-spring collapse finishes, resize it back to the resting surface bounds with animations disabled.
-- Expanded notch content must treat the physical notch void as unavailable layout space. The surface may cover the void, but text, buttons, and task rows should start below the detected void height while retaining the normal below-notch content height.
+- Expanded notch content must treat the physical notch void as unavailable layout space. The surface may cover the void, but text, buttons, and task rows should start below the detected void height while retaining the normal below-notch content height. Displays without a physical notch should use no void offset.
- Notch expansion should reveal from the top edge, growing width and height together so the expanded surface feels attached to the physical notch rather than growing from a lower corner. Use a single rendered surface with the prototype dimensions and a native spring for opening width, height, bottom corner radius, and shadow; use a short ease-out on close so there is no spring tail. Keep collapsed and expanded content inside that clipped surface so layout follows the animated width. Delay the expanded content fade-in so the surface leads the content.
- The expanded notch header may show an update button when `PointerPromptUpdateState` is actionable; clicking it should invoke Sparkle's standard update UI outside the SwiftUI view.
-- Expanded notch pause/resume controls should call the model/controller boundary and route through `PointerPromptCommandHandling`, keeping run coordination outside SwiftUI rendering.
+- Expanded notch pause/resume controls should call the model/controller boundary with the selected task ID and route through `PointerPromptCommandHandling`, keeping per-task run coordination outside SwiftUI rendering.
- The controller should derive notch geometry from the active `NSScreen`, prefer safe-area and auxiliary-top areas over hardcoded notch sizes, and keep visible status content below the top safe-area inset.
- Launch positioning, notch positioning, and double-Command activation handling belong in `PointerPromptOverlayController`, not the SwiftUI view.
- Double-Command is the prompt activation shortcut through `PointerPromptActivationShortcut.doubleCommand`.
@@ -83,7 +88,7 @@ swift build
swift run Donkey
```
-Launch Donkey and confirm the inactive overlay renders as a black notch extension at the top center, with status content below the physical notch area on notched displays. Hover the notch and confirm it expands downward into the current-task panel with a bottom command row, then collapses after the pointer leaves. With Sparkle configured to a local appcast that contains a newer signed update, confirm the expanded header shows an update button and clicking it opens Sparkle's update UI. Submit a command, expand the notch while it is running, and confirm pause/resume controls update the task state. Double-tap Command and release to confirm the black prompt capsule opens centered on the screen with keyboard focus and no visible close button, grant microphone permission if prompted, then speak or tap near the microphone and confirm the waveform responds to real audio levels. Type enough text to wrap and confirm the prompt changes from a pill into a rounded rectangle and remains centered as it grows. Press Shift-Return and confirm it inserts a newline; press Return and confirm it submits, dismisses the prompt, and shows working/result status in the notch panel. Move the mouse and confirm the active modal stays centered. Double-tap Command again but hold the second Command press, and confirm the same prompt modal appears with voice capture. Press Escape and confirm the active modal dismisses. Click outside the active modal and confirm it dismisses. Reactivate and drag the modal from non-input capsule areas. Confirm Command plus another key, Command-click, and a single Command tap do not activate the modal.
+Launch Donkey and confirm the inactive overlay renders as a black notch extension at the top center, with status content below the physical notch area on notched displays. On an external monitor or Mac without a physical notch, confirm the same collapsed top-center slot appears without a reserved void and collapsed status text can use the full slot width. Hover the notch and confirm it expands downward into the current-task panel with a bottom command row, then collapses after the pointer leaves. With Sparkle configured to a local appcast that contains a newer signed update, confirm the expanded header shows an update button and clicking it opens Sparkle's update UI. Submit multiple commands, expand the notch while they are running, and confirm each running or paused task row has its own pause/resume controls. Pause one task and confirm only that task changes to paused while other running tasks keep their running state; resume it and confirm it returns to running. Submit a follow-up from the expanded notch composer and confirm it appends to the matched recent task instead of creating a duplicate; submit an unrelated command and confirm it creates a new task. Drag a file onto the collapsed notch surface and confirm it persists as a user-uploaded asset on the active or most recent task. Double-tap Command and release to confirm the black prompt capsule opens centered on the screen with keyboard focus and no visible close button, grant microphone permission if prompted, then speak or tap near the microphone and confirm the waveform responds to real audio levels. Type enough text to wrap and confirm the prompt changes from a pill into a rounded rectangle and remains centered as it grows. Press Shift-Return and confirm it inserts a newline; press Return and confirm it submits, dismisses the prompt, and shows working/result status in the notch panel. Move the mouse and confirm the active modal stays centered. Double-tap Command again but hold the second Command press, and confirm the same prompt modal appears with voice capture. Press Escape and confirm the active modal dismisses. Click outside the active modal and confirm it dismisses. Reactivate and drag the modal from non-input capsule areas. Confirm Command plus another key, Command-click, and a single Command tap do not activate the modal.
## Source Entry Points
diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.py
index df28c4da..e3f2fe9d 100644
--- a/scripts/local-runtime-runners/donkey_runtime_runner.py
+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py
@@ -466,9 +466,17 @@ def health_check(request: dict[str, Any]) -> dict[str, Any]:
def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
command = request.get("command", "")
- task_definitions = request.get("taskDefinitions", [])
- prompt = task_intent_prompt(command, task_definitions)
- schema = task_intent_schema(task_definitions)
+ schema_id = (request.get("metadata") or {}).get("schemaID", "")
+ if schema_id == "task_followup_resolution_v1":
+ candidates = request.get("candidates", [])
+ prompt = task_followup_prompt(command, candidates)
+ schema = task_followup_schema(candidates)
+ max_tokens = 96
+ else:
+ task_definitions = request.get("taskDefinitions", [])
+ prompt = task_intent_prompt(command, task_definitions)
+ schema = task_intent_schema(task_definitions)
+ max_tokens = 128
body = {
"model": request.get("modelID") or MODEL_ID,
"prompt": prompt,
@@ -476,7 +484,7 @@ def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
"format": schema,
"options": {
"num_ctx": 2048,
- "num_predict": 128,
+ "num_predict": max_tokens,
"temperature": 0,
"top_p": 0.8,
},
@@ -503,6 +511,65 @@ def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
}
+def task_followup_prompt(command: str, candidates: list[dict[str, Any]]) -> str:
+ candidate_lines: list[str] = []
+ for index, candidate in enumerate(candidates, start=1):
+ events = " | ".join(
+ str(event)
+ for event in candidate.get("recentEvents", [])
+ if str(event).strip()
+ )
+ assets = ", ".join(
+ str(asset)
+ for asset in candidate.get("assetNames", [])
+ if str(asset).strip()
+ )
+ candidate_lines.append(
+ " ; ".join(
+ [
+ f"rank={index}",
+ f"taskID={candidate.get('taskID', '')}",
+ f"title={candidate.get('title', '')}",
+ f"detail={candidate.get('detail', '')}",
+ f"status={candidate.get('status', '')}",
+ f"original={candidate.get('commandText', '')}",
+ f"recentEvents={events}",
+ f"assets={assets}",
+ ]
+ )
+ )
+
+ return "\n".join(
+ [
+ "Decide whether the user's latest text is a follow-up to one recent task, then return strict JSON.",
+ "Recent tasks are ordered newest first. Prefer a newer task only when it plausibly matches.",
+ "A follow-up depends on previous task context, such as edits, refinements, references like it/that, answers to a question, or asset-related continuation.",
+ "Do not match only because the topics are generic or the user asks for a separate new action.",
+ "If no task clearly matches, set isFollowUp=false, taskID='', confidence below 0.55.",
+ "Do not include reasoning outside JSON.",
+ f"Latest user text: {command}",
+ "Recent task candidates:",
+ "\n".join(candidate_lines),
+ ]
+ )
+
+
+def task_followup_schema(candidates: list[dict[str, Any]]) -> dict[str, Any]:
+ task_ids = [str(item.get("taskID")) for item in candidates if item.get("taskID")]
+ task_ids = sorted(set(task_ids + [""]))
+ return {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["isFollowUp", "taskID", "confidence", "reason"],
+ "properties": {
+ "isFollowUp": {"type": "boolean"},
+ "taskID": {"type": "string", "enum": task_ids},
+ "confidence": {"type": "number", "minimum": 0, "maximum": 1},
+ "reason": {"type": "string"},
+ },
+ }
+
+
def task_intent_prompt(command: str, task_definitions: list[dict[str, Any]]) -> str:
task_lines: list[str] = []
for definition in task_definitions: