Open source CapCut alternative.
TypeScript
Implement pointer prompt spawn cursors
David Le1f76a6bea8d7
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex a8b8f2e2..4b48043c 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -32,12 +32,13 @@ struct DocumentFormFillReviewRequest: Equatable, Sendable {var traceID: String}-struct PointerPromptCommandContext: Equatable, Sendable {+struct PointerPromptCommandContext: Sendable {var task: PointerPromptNotchTaskvar recentEvents: [PointerPromptTaskEvent]var assets: [PointerPromptTaskAsset]var isFollowUp: Boolvar turnSource: AppHarnessTurnSource = .typedPrompt+ var spawnProgressChanged: (@MainActor @Sendable (PointerPromptSpawnProgressUpdate) -> Void)?}protocol PointerPromptCommandHandling: Sendable {@@ -103,6 +104,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {))if let cursorGuideRequest = cursorGuideResolution.guideRequest {+ await reportSpawnProgress(+ PointerPromptSpawnProgressUpdate(label: "Showing you"),+ context: context+ )let result = PointerPromptCommandHandlingResult(status: .completed,threadStatus: .chatting,@@ -142,6 +147,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {logRouting(command: command, traceID: traceID, taskID: taskID, routing: routing)switch routing.outcome.decision.kind {case .respond:+ await reportSpawnProgress(+ PointerPromptSpawnProgressUpdate(label: "Answering"),+ context: context+ )let result = PointerPromptCommandHandlingResult(status: .completed,threadStatus: .chatting,@@ -156,6 +165,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {logHandlingResult(result, stage: "conversation", hint: routingHint(for: routing))return resultcase .askClarification:+ await reportSpawnProgress(+ PointerPromptSpawnProgressUpdate(label: "Waiting for detail"),+ context: context+ )let result = PointerPromptCommandHandlingResult(status: .needsConfirmation,threadStatus: .waitingForClarification,@@ -184,6 +197,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {logHandlingResult(result, stage: "empty", hint: "Empty command; no action was run.")return resultcase .openReview, .runLocalTask:+ await reportSpawnProgress(+ PointerPromptSpawnProgressUpdate(label: "Finding destination"),+ context: context+ )break}@@ -207,6 +224,16 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)let resolution = localModelResult.resolutionlet parseLatencyMS = Self.uptimeMilliseconds() - parseStartedAt+ if let definition = resolution.definition {+ await reportSpawnProgress(+ PointerPromptSpawnProgressUpdate(+ label: "Opening \(definition.targetApp.appName)",+ targetHint: Self.spawnTargetHint(for: definition.targetApp),+ phase: .holding+ ),+ context: context+ )+ }logModelResolution(command: modelCommand,traceID: traceID,@@ -252,6 +279,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)if Self.shouldRespondWithoutLocalTask(resolution) {+ await reportSpawnProgress(+ PointerPromptSpawnProgressUpdate(label: "Answering"),+ context: context+ )let response = "I couldn't find a supported local action for that yet."let decision = AppHarnessDecision(kind: .respond,@@ -336,6 +367,24 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}+ private func reportSpawnProgress(+ _ update: PointerPromptSpawnProgressUpdate,+ context: PointerPromptCommandContext?+ ) async {+ guard let spawnProgressChanged = context?.spawnProgressChanged else { return }++ await spawnProgressChanged(update)+ }++ private static func spawnTargetHint(for target: LocalAppTarget) -> PointerPromptSpawnTargetHint {+ PointerPromptSpawnTargetHint(+ appName: target.appName,+ bundleIdentifier: target.bundleIdentifier,+ titleContains: target.titleContains,+ metadata: target.metadata+ )+ }+private func logRouting(command: String,traceID: String,diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swiftindex 7957ca77..e1f2f914 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift@@ -12,6 +12,7 @@ final class PointerPromptOverlayController {private let activationShortcut: PointerPromptActivationShortcutprivate let microphoneWaveformMeter = MicrophoneWaveformMeter()private let coachCursorController = PointerCoachCursorOverlayController()+ private let spawnOverlayController = PointerPromptSpawnOverlayController()private var statusPanel: NSPanel?private var statusHostingView: PointerPromptHostingView<PointerPromptNotchStatusView>?@@ -25,7 +26,9 @@ final class PointerPromptOverlayController {private var completedActivationTapCount = 0private var lastActivationTapCompletedAt: Date?private var activationHoldStartedAt: Date?+ private var spawnVoiceHoldStartedAt: Date?private var isVoiceInputActive = false+ private var activeSpawnVoiceInputID: String?private var isStatusExpanded = falseprivate var isStatusHostExpanded = false// Hover can produce enter/exit samples faster than SwiftUI's spring can settle.@@ -35,6 +38,7 @@ final class PointerPromptOverlayController {private var statusCollapseWorkItem: DispatchWorkItem?private var statusExpansionWorkItem: DispatchWorkItem?private var statusHostShrinkWorkItem: DispatchWorkItem?+ private var spawnDesktopEmergeWorkItems: [String: DispatchWorkItem] = [:]private var hasPrewarmedInputPanel = falseprivate var hasPrewarmedStatusPanelExpansion = falseprivate var lastStatusViewSnapshot: StatusPanelViewSnapshot?@@ -48,6 +52,12 @@ final class PointerPromptOverlayController {model.coachGuidePresenter = { [weak self] request inself?.coachCursorController.show(request: request)}+ spawnOverlayController.followUpSubmitted = { [weak self] spawnID, taskID, text in+ self?.model.submitSpawnFollowUp(spawnID: spawnID, taskID: taskID, text: text)+ }+ spawnOverlayController.selected = { [weak self] spawnID in+ self?.model.selectSpawn(id: spawnID)+ }microphoneWaveformMeter.onLevelsChanged = { [weak model] levels inmodel?.updateVoiceWaveformLevels(levels)}@@ -171,11 +181,13 @@ final class PointerPromptOverlayController {statusExpansionWorkItem = nilstatusHostShrinkWorkItem?.cancel()statusHostShrinkWorkItem = nil+ cancelSpawnDesktopEmergeWorkItems()statusHoverPhase = .collapsedstopActivationMonitoring()stopAppDeactivationMonitoring()microphoneWaveformMeter.stop()coachCursorController.close()+ spawnOverlayController.close()inputPanel?.close()inputPanel = nilstatusPanel?.close()@@ -278,11 +290,20 @@ final class PointerPromptOverlayController {return}+ if activeSpawnVoiceInputID != nil, !isActivationModifierDown {+ finishSpawnVoiceInput()+ resetActivationTapSequence()+ return+ }+if isCleanActivationModifierOnly {if activationTapStartedAt == nil {let now = Date()activationTapStartedAt = nowactivationTapIsClean = true+ if shouldStartSpawnVoiceHoldCandidate() {+ spawnVoiceHoldStartedAt = now+ }if shouldStartVoiceHoldCandidate(at: now) {activationHoldStartedAt = now}@@ -298,6 +319,7 @@ final class PointerPromptOverlayController {completedActivationTapCount = 0lastActivationTapCompletedAt = nilactivationHoldStartedAt = nil+ spawnVoiceHoldStartedAt = nilreturn}@@ -314,6 +336,7 @@ final class PointerPromptOverlayController {tapDuration <= activationShortcut.maximumTapDurationself.activationTapStartedAt = nilactivationTapIsClean = false+ spawnVoiceHoldStartedAt = nilguard completedCleanTap else {resetActivationTapSequence()@@ -348,6 +371,11 @@ final class PointerPromptOverlayController {completedActivationTapCount = 0lastActivationTapCompletedAt = nilactivationHoldStartedAt = nil+ spawnVoiceHoldStartedAt = nil+ }++ private func shouldStartSpawnVoiceHoldCandidate() -> Bool {+ !model.promptState.isActive && !model.spawnStates.isEmpty}private func shouldStartVoiceHoldCandidate(at now: Date) -> Bool {@@ -362,6 +390,9 @@ final class PointerPromptOverlayController {}private func activateVoiceInputIfNeeded() {+ activateSpawnVoiceInputIfNeeded()+ guard activeSpawnVoiceInputID == nil else { return }+guard let holdToVoiceInputDuration = activationShortcut.holdToVoiceInputDuration,let activationHoldStartedAt,activationTapIsClean,@@ -394,6 +425,48 @@ final class PointerPromptOverlayController {model.handle(.voiceInputRequested)}+ private func activateSpawnVoiceInputIfNeeded() {+ guard activeSpawnVoiceInputID == nil,+ let spawnVoiceHoldStartedAt,+ activationTapIsClean,+ Date().timeIntervalSince(spawnVoiceHoldStartedAt) >= spawnVoiceHoldDuration else {+ return+ }++ guard let spawnID = model.beginSpawnVoiceInput() else { return }+ guard spawnOverlayController.beginVoiceInput(spawnID: spawnID) else {+ model.cancelSpawnVoiceInput(spawnID: spawnID)+ return+ }++ activeSpawnVoiceInputID = spawnID+ microphoneWaveformMeter.startAudioCapture()+ }++ private var spawnVoiceHoldDuration: TimeInterval {+ activationShortcut.holdToVoiceInputDuration ?? 0.35+ }++ private func finishSpawnVoiceInput() {+ guard let spawnID = activeSpawnVoiceInputID else { return }++ activeSpawnVoiceInputID = nil+ spawnVoiceHoldStartedAt = nil+ let audio = microphoneWaveformMeter.finishAudioCapture()+ model.transcribeSpawnVoiceAudio(spawnID: spawnID, audio: audio) { [weak self] transcript in+ guard let self else { return }++ guard let transcript,+ !transcript.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ self.spawnOverlayController.cancelVoiceInput(spawnID: spawnID)+ self.model.cancelSpawnVoiceInput(spawnID: spawnID)+ return+ }++ self.spawnOverlayController.completeVoiceInput(spawnID: spawnID, text: transcript)+ }+ }+private func finishVoiceInput() {guard isVoiceInputActive else { return }@@ -436,6 +509,7 @@ final class PointerPromptOverlayController {positionStatusPanel()updateStatusHoverExpansion()updateStatusPanelView()+ updateSpawnOverlay()resizeActivePanelIfNeeded(inputPanel)updateMouseEventPassthrough(for: inputPanel)@@ -529,7 +603,8 @@ final class PointerPromptOverlayController {}private func statusViewSnapshot(metrics: NotchMetrics) -> StatusPanelViewSnapshot {- StatusPanelViewSnapshot(+ let spawnCue = notchSpawnCue(metrics: metrics)+ return StatusPanelViewSnapshot(state: model.promptState,updateState: model.updateState,layout: metrics.layout,@@ -541,12 +616,16 @@ final class PointerPromptOverlayController {notchCommandInputTextHeight: model.notchCommandInputTextHeight,isNotchCommandInputExpanded: model.isNotchCommandInputExpanded,notchTasks: model.notchTasks,- accentIndex: model.notchAccentIndex+ accentIndex: model.notchAccentIndex,+ spawnState: spawnCue,+ spawnStates: model.spawnStates,+ selectedSpawnID: model.selectedSpawnID)}private func notchStatusView(metrics: NotchMetrics) -> PointerPromptNotchStatusView {- PointerPromptNotchStatusView(+ let spawnCue = notchSpawnCue(metrics: metrics)+ return PointerPromptNotchStatusView(state: model.promptState,updateState: model.updateState,layout: metrics.layout,@@ -566,6 +645,7 @@ final class PointerPromptOverlayController {isCommandInputExpanded: model.isNotchCommandInputExpanded,tasks: model.notchTasks,accentIndex: model.notchAccentIndex,+ spawnState: spawnCue,commandSubmitted: { [weak self] text inself?.model.handle(.messageSubmitted(text: text))},@@ -590,10 +670,63 @@ final class PointerPromptOverlayController {)}+ private func notchSpawnCue(metrics: NotchMetrics) -> PointerPromptSpawnState? {+ spawnOverlayController.cueState(+ for: model.notchSpawnCue,+ screen: activeScreen(),+ notchMetrics: metrics+ )+ }+private func openAvailableUpdate() {model.showUpdateUI()}+ private func updateSpawnOverlay() {+ let screen = activeScreen()+ let metrics = notchMetrics(for: screen)+ scheduleSpawnDesktopEmergeIfNeeded()+ spawnOverlayController.update(+ spawnStates: model.spawnStates,+ selectedSpawnID: model.selectedSpawnID,+ screen: screen,+ notchMetrics: metrics+ )+ }++ private func scheduleSpawnDesktopEmergeIfNeeded() {+ let cueStates = model.spawnStates.filter { $0.phase == .notchCue }+ let cueIDs = Set(cueStates.map(\.id))+ for (spawnID, workItem) in spawnDesktopEmergeWorkItems where !cueIDs.contains(spawnID) {+ workItem.cancel()+ spawnDesktopEmergeWorkItems[spawnID] = nil+ }++ for (index, spawnState) in cueStates.enumerated()+ where spawnDesktopEmergeWorkItems[spawnState.id] == nil {+ let workItem = DispatchWorkItem { [weak self] in+ Task { @MainActor in+ guard let self else { return }++ self.model.markSpawnDesktopEmerged(id: spawnState.id)+ self.spawnDesktopEmergeWorkItems[spawnState.id] = nil+ }+ }+ spawnDesktopEmergeWorkItems[spawnState.id] = workItem+ DispatchQueue.main.asyncAfter(+ deadline: .now() + 0.24 + Double(index) * 0.05,+ execute: workItem+ )+ }+ }++ private func cancelSpawnDesktopEmergeWorkItems() {+ for workItem in spawnDesktopEmergeWorkItems.values {+ workItem.cancel()+ }+ spawnDesktopEmergeWorkItems = [:]+ }+private func updateStatusHoverExpansion() {guard let statusPanel else { return }@@ -1173,6 +1306,9 @@ private struct StatusPanelViewSnapshot: Equatable {var isNotchCommandInputExpanded: Boolvar notchTasks: [PointerPromptNotchTask]var accentIndex: Int+ var spawnState: PointerPromptSpawnState?+ var spawnStates: [PointerPromptSpawnState]+ var selectedSpawnID: String?}private enum StatusHoverPhase {diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swiftindex fa3743d8..800e9921 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift@@ -18,6 +18,8 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink@Published private(set) var isCurrentTaskPaused = false@Published private(set) var updateState: PointerPromptUpdateState@Published private(set) var notchTasks: [PointerPromptNotchTask]+ @Published private(set) var spawnStates: [PointerPromptSpawnState] = []+ @Published private(set) var selectedSpawnID: String?var coachGuidePresenter: ((PointerCoachCursorGuideRequest) -> Void)?private let commandHandler: any PointerPromptCommandHandling@@ -157,8 +159,52 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink}}+ func transcribeSpawnVoiceAudio(+ spawnID: String,+ audio: LocalVoiceAudioBuffer?,+ transcriptReceived: @escaping @MainActor (String?) -> Void+ ) {+ guard let audio else {+ updateSpawn(+ id: spawnID,+ label: "No voice captured",+ inputState: .collapsed+ )+ transcriptReceived(nil)+ return+ }++ updateSpawn(id: spawnID, label: "Transcribing...")+ let sourceTraceID = "pointer-prompt-spawn-voice-\(UUID().uuidString)"+ Task { [weak self, voiceTranscriber] in+ let result = await voiceTranscriber.transcribe(+ LocalVoiceTranscriptionRequest(+ audio: audio,+ sourceTraceID: sourceTraceID+ )+ )+ await MainActor.run {+ guard let self else { return }++ let transcript = result.transcript?.text.trimmingCharacters(in: .whitespacesAndNewlines)+ if transcript?.isEmpty == false {+ self.updateSpawn(id: spawnID, label: "Heard you")+ transcriptReceived(transcript)+ } else {+ self.updateSpawn(+ id: spawnID,+ label: "I didn't catch that",+ inputState: .collapsed+ )+ transcriptReceived(nil)+ }+ }+ }+ }+private func submitCommand(_ text: String, source: AppHarnessTurnSource = .typedPrompt) {let candidates = followUpCandidates()+ let spawnID = source == .voiceTranscript ? nil : beginSpawn(for: text)clearSubmissionInputs()promptState.isActive = falsepromptState.leadingSignalLevel = .thinking@@ -186,7 +232,12 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink}await MainActor.run {- self?.startCommandRun(text: text, matchedTaskID: matchedTaskID, source: source)+ self?.startCommandRun(+ text: text,+ matchedTaskID: matchedTaskID,+ source: source,+ spawnID: spawnID+ )}}}@@ -220,13 +271,111 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinksyncPrimaryTaskPausedFlag()}+ func markSpawnDesktopEmerged(id spawnID: String) {+ guard let index = spawnIndex(id: spawnID),+ spawnStates[index].phase == .notchCue else {+ return+ }++ var spawnState = spawnStates[index]+ spawnState.phase = .traveling+ spawnState.updatedAt = Date()+ spawnStates[index] = spawnState+ selectedSpawnID = spawnID+ }++ func selectSpawn(id spawnID: String) {+ guard spawnStates.contains(where: { $0.id == spawnID }) else { return }++ selectedSpawnID = spawnID+ }++ func beginSpawnVoiceInput() -> String? {+ let selectedID = selectedSpawnID.flatMap { id in+ spawn(withID: id).map { spawn -> String? in+ spawn.taskID != nil && (spawn.phase == .holding || spawn.phase == .traveling) ? id : nil+ } ?? nil+ } ?? nil+ guard let spawnID = selectedID ?? latestInteractableSpawnID() else { return nil }++ updateSpawn(+ id: spawnID,+ label: "Listening...",+ phase: .holding,+ inputState: .editing+ )+ selectedSpawnID = spawnID+ return spawnID+ }++ func completeSpawnVoiceInput(spawnID: String, transcript: String?) {+ let trimmedText = transcript?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ guard !trimmedText.isEmpty,+ let taskID = spawn(withID: spawnID)?.taskID else {+ updateSpawn(+ id: spawnID,+ label: "I didn't catch that",+ inputState: .collapsed+ )+ return+ }++ submitSpawnFollowUp(spawnID: spawnID, taskID: taskID, text: trimmedText)+ }++ func cancelSpawnVoiceInput(spawnID: String) {+ updateSpawn(+ id: spawnID,+ label: "Paused",+ inputState: .collapsed+ )+ }++ func submitSpawnFollowUp(spawnID: String, taskID: String, text: String) {+ let fallbackState = PointerPromptSpawnState(+ id: spawnID,+ taskID: taskID,+ commandText: text,+ label: "Routing follow-up",+ accentIndex: notchAccentIndex,+ phase: .holding+ )+ let state = spawn(withID: spawnID) ?? fallbackState+ guard let submission = PointerPromptSpawnLifecycle.followUpSubmission(+ from: state,+ text: text+ ) else { return }++ updateSpawn(+ id: submission.spawnID,+ taskID: submission.taskID,+ commandText: submission.text,+ label: "Routing follow-up",+ phase: .holding,+ inputState: .collapsed+ )+ startCommandRun(+ text: submission.text,+ matchedTaskID: submission.taskID,+ source: .followUp,+ spawnID: submission.spawnID+ )+ }+private func startCommandRun(text: String,matchedTaskID: String?,- source: AppHarnessTurnSource = .typedPrompt+ source: AppHarnessTurnSource = .typedPrompt,+ spawnID: String? = nil) {let isFollowUp = matchedTaskID != nillet task = taskForSubmittedCommand(text: text, matchedTaskID: matchedTaskID)+ updateSpawn(+ id: spawnID,+ taskID: task.id,+ label: "Finding destination",+ accentIndex: task.accentIndex+ )activeTaskIDs.insert(task.id)lastActiveTaskID = task.idappendTaskEvent(taskID: task.id, role: .user, text: text)@@ -240,7 +389,12 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkpromptState.leadingSignalLevel = .thinkingpromptState.promptText = task.titlesyncPrimaryTaskPausedFlag()- let context = commandContext(taskID: task.id, isFollowUp: isFollowUp, source: source)+ let context = commandContext(+ taskID: task.id,+ isFollowUp: isFollowUp,+ source: source,+ spawnID: spawnID+ )Task { [weak self, commandHandler] inlet result = await commandHandler.handleSubmittedCommand(text, context: context)await MainActor.run {@@ -263,6 +417,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkif let cursorGuideRequest = result.cursorGuideRequest {self.coachGuidePresenter?(cursorGuideRequest)}+ self.finishSpawn(id: spawnID, result: result)}}}@@ -318,6 +473,143 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkmax(92, notchCommandInputTextHeight + 60)}+ private func beginSpawn(+ for text: String,+ label: String = "Routing task",+ taskID: String? = nil,+ accentIndex: Int? = nil+ ) -> String {+ let spawnID = UUID().uuidString+ let displayText = Self.taskLabel(for: text)+ let spawnState = PointerPromptSpawnState(+ id: spawnID,+ taskID: taskID,+ commandText: text,+ label: label,+ accentIndex: accentIndex ?? Self.nextAccentIndex(after: notchAccentIndex),+ phase: .notchCue+ )+ spawnStates.append(spawnState)+ selectedSpawnID = spawnID+ promptState.promptText = displayText+ promptState.leadingSignalLevel = .thinking+ return spawnID+ }++ private func updateSpawn(+ id spawnID: String?,+ taskID: String? = nil,+ commandText: String? = nil,+ label: String? = nil,+ accentIndex: Int? = nil,+ targetHint: PointerPromptSpawnTargetHint? = nil,+ phase: PointerPromptSpawnPhase? = nil,+ inputState: PointerPromptSpawnInputState? = nil+ ) {+ guard let spawnID,+ let index = spawnIndex(id: spawnID) else {+ return+ }++ var spawnState = spawnStates[index]+ if let taskID {+ spawnState.taskID = taskID+ }+ if let commandText {+ spawnState.commandText = commandText+ }+ if let label,+ !label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ spawnState.label = label+ }+ if let accentIndex {+ spawnState.accentIndex = accentIndex+ }+ if let targetHint {+ spawnState.targetHint = targetHint+ }+ if let phase {+ if spawnState.phase != .notchCue || phase == .fading {+ spawnState.phase = phase+ }+ }+ if let inputState {+ spawnState.inputState = inputState+ }+ spawnState.updatedAt = Date()+ spawnStates[index] = spawnState+ }++ private func finishSpawn(+ id spawnID: String?,+ result: PointerPromptCommandHandlingResult+ ) {+ guard let spawnID,+ let index = spawnIndex(id: spawnID) else {+ return+ }++ var spawnState = spawnStates[index]+ spawnState.label = Self.spawnCompletionLabel(for: result)+ spawnState.updatedAt = Date()++ switch result.threadStatus {+ case .waitingForClarification, .waitingForReview, .needsAttention:+ spawnState.phase = .holding+ spawnStates[index] = spawnState+ case .running, .paused:+ spawnState.phase = .holding+ spawnStates[index] = spawnState+ case .chatting, .completed, .failed:+ spawnStates[index] = spawnState+ scheduleSpawnFade(id: spawnID)+ }+ }++ private func scheduleSpawnFade(id spawnID: String) {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in+ guard let self,+ let index = self.spawnIndex(id: spawnID) else {+ return+ }++ var spawnState = self.spawnStates[index]+ spawnState.phase = .fading+ spawnState.updatedAt = Date()+ self.spawnStates[index] = spawnState+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { [weak self] in+ self?.removeSpawn(id: spawnID)+ }+ }+ }++ var notchSpawnCue: PointerPromptSpawnState? {+ spawnStates.last { $0.phase == .notchCue }+ }++ private func spawnIndex(id spawnID: String) -> Int? {+ spawnStates.firstIndex { $0.id == spawnID }+ }++ private func spawn(withID spawnID: String) -> PointerPromptSpawnState? {+ spawnStates.first { $0.id == spawnID }+ }++ private func latestInteractableSpawnID() -> String? {+ spawnStates+ .last {+ $0.taskID != nil && ($0.phase == .holding || $0.phase == .traveling)+ }?+ .id+ }++ private func removeSpawn(id spawnID: String) {+ spawnStates.removeAll { $0.id == spawnID }+ if selectedSpawnID == spawnID {+ selectedSpawnID = latestInteractableSpawnID()+ }+ }+private func prependTask(_ task: PointerPromptNotchTask) {notchTasks.removeAll { $0.id == task.id }notchTasks.insert(task, at: 0)@@ -403,7 +695,8 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkprivate func commandContext(taskID: String,isFollowUp: Bool,- source: AppHarnessTurnSource = .typedPrompt+ source: AppHarnessTurnSource = .typedPrompt,+ spawnID: String? = nil) -> PointerPromptCommandContext? {guard let task = task(withID: taskID) else { return nil }@@ -412,10 +705,26 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkrecentEvents: Array(taskStore.loadEvents(taskID: taskID).suffix(10)),assets: taskStore.loadAssets(taskID: taskID),isFollowUp: isFollowUp,- turnSource: source+ turnSource: source,+ spawnProgressChanged: spawnProgressHandler(for: spawnID))}+ private func spawnProgressHandler(+ for spawnID: String?+ ) -> (@MainActor @Sendable (PointerPromptSpawnProgressUpdate) -> Void)? {+ guard let spawnID else { return nil }++ return { [weak self] update in+ self?.updateSpawn(+ id: spawnID,+ label: update.label,+ targetHint: update.targetHint,+ phase: update.phase+ )+ }+ }+private func followUpCandidates() -> [PointerPromptFollowUpCandidate] {taskStore.loadRecentTasks(limit: Self.followUpCandidateLimit)@@ -537,6 +846,27 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkresult.threadStatus}+ private static func spawnCompletionLabel(for result: PointerPromptCommandHandlingResult) -> String {+ switch result.threadStatus {+ case .waitingForClarification:+ return "Waiting for detail"+ case .waitingForReview:+ return "Waiting for your review"+ case .needsAttention:+ return "Needs your attention"+ case .running:+ return "Working"+ case .paused:+ return "Paused"+ case .chatting:+ return result.summary.isEmpty ? "Answered" : truncated(result.summary, maxLength: 42)+ case .completed:+ return "Done"+ case .failed:+ return "Stopped"+ }+ }+private static func nextAccentIndex(after currentIndex: Int) -> Int {let accentCount = 8var nextIndex = Int.random(in: 0..<accentCount)diff --git a/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swiftnew file mode 100644index 00000000..c25c58cd--- /dev/null+++ b/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift@@ -0,0 +1,417 @@+import AppKit+import DonkeyContracts+import DonkeyRuntime+import DonkeyUI+import SwiftUI++@MainActor+final class PointerPromptSpawnOverlayController {+ private let store = PointerPromptSpawnOverlayStore()+ private var panel: PointerPromptSpawnPanel?+ private var hostingView: PointerPromptSpawnHostingView<PointerPromptSpawnOverlayContainerView>?+ private var viewModelsByID: [String: PointerPromptSpawnOverlayViewModel] = [:]+ private var closeWorkItem: DispatchWorkItem?+ private var windowResolver = MacWindowResolver()++ var followUpSubmitted: ((String, String, String) -> Void)? {+ didSet {+ for viewModel in viewModelsByID.values {+ viewModel.followUpSubmitted = followUpSubmitted+ }+ }+ }++ var selected: ((String) -> Void)? {+ didSet {+ for viewModel in viewModelsByID.values {+ viewModel.selected = selected+ }+ }+ }++ func update(+ spawnStates: [PointerPromptSpawnState],+ selectedSpawnID: String?,+ screen: NSScreen?,+ notchMetrics: PointerPromptNotchMetrics+ ) {+ guard !spawnStates.isEmpty else {+ fadeAndCloseAll()+ return+ }++ closeWorkItem?.cancel()+ closeWorkItem = nil++ guard let screen else { return }++ ensurePanel(on: screen)+ let visibleSpawnStates = spawnStates.filter { $0.phase != .notchCue }+ let visibleIDs = Set(visibleSpawnStates.map(\.id))++ for spawnState in visibleSpawnStates {+ updateViewModel(+ for: spawnState,+ selectedSpawnID: selectedSpawnID,+ screen: screen,+ notchMetrics: notchMetrics+ )+ }++ for staleID in viewModelsByID.keys where !visibleIDs.contains(staleID) {+ fadeAndRemove(id: staleID)+ }+ }++ func close() {+ closeWorkItem?.cancel()+ closeWorkItem = nil+ for viewModel in viewModelsByID.values {+ viewModel.fadeOut()+ }+ panel?.close()+ panel = nil+ hostingView = nil+ store.viewModels = []+ viewModelsByID = [:]+ }++ private func ensurePanel(on screen: NSScreen) {+ if let panel {+ guard panel.frame.size != screen.frame.size || panel.frame.origin != screen.frame.origin else { return }++ panel.setFrame(screen.frame, display: true)+ hostingView?.frame = CGRect(origin: .zero, size: screen.frame.size)+ return+ }++ let hostingView = PointerPromptSpawnHostingView(rootView: PointerPromptSpawnOverlayContainerView(store: store))+ hostingView.frame = CGRect(origin: .zero, size: screen.frame.size)+ hostingView.autoresizingMask = [.width, .height]+ hostingView.wantsLayer = true+ hostingView.layer?.backgroundColor = NSColor.clear.cgColor+ hostingView.hitTestRegionProvider = { [weak self] in+ guard let self else { return [] }++ return self.store.viewModels+ .map(\.hitTestFrame)+ .filter { !$0.isNull }+ }++ let panel = PointerPromptSpawnPanel(+ contentRect: screen.frame,+ styleMask: [.borderless],+ backing: .buffered,+ defer: false+ )+ panel.title = "Donkey Spawn"+ panel.contentView = hostingView+ panel.backgroundColor = .clear+ panel.isOpaque = false+ panel.hasShadow = false+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.becomesKeyOnlyIfNeeded = false+ panel.ignoresMouseEvents = false+ panel.level = .statusBar+ panel.collectionBehavior = [+ .canJoinAllSpaces,+ .fullScreenAuxiliary,+ .ignoresCycle,+ .stationary+ ]+ panel.setFrame(screen.frame, display: true)+ panel.orderFrontRegardless()++ self.panel = panel+ self.hostingView = hostingView+ }++ private func updateViewModel(+ for spawnState: PointerPromptSpawnState,+ selectedSpawnID: String?,+ screen: NSScreen,+ notchMetrics: PointerPromptNotchMetrics+ ) {+ let viewModel = viewModel(for: spawnState)+ viewModel.setSelected(spawnState.id == selectedSpawnID)+ let destination = destinationPoint(+ for: spawnState.targetHint,+ viewModel: viewModel,+ screen: screen,+ notchMetrics: notchMetrics+ )++ if viewModel.state == nil {+ viewModel.show(+ state: spawnState,+ origin: spawnOrigin(in: screen, index: store.viewModels.firstIndex { $0.objectID == viewModel.objectID } ?? 0),+ destination: destination,+ screenSize: screen.frame.size+ )+ return+ }++ viewModel.update(+ state: spawnState,+ destination: destination,+ screenSize: screen.frame.size+ )+ if spawnState.phase == .fading {+ scheduleRemove(id: spawnState.id)+ }+ }++ private func viewModel(for spawnState: PointerPromptSpawnState) -> PointerPromptSpawnOverlayViewModel {+ if let viewModel = viewModelsByID[spawnState.id] {+ return viewModel+ }++ let viewModel = PointerPromptSpawnOverlayViewModel()+ viewModel.followUpSubmitted = followUpSubmitted+ viewModel.selected = selected+ viewModel.inputActivityChanged = { [weak self] isActive in+ self?.updateInputInteractivity(isActive: isActive)+ }+ viewModelsByID[spawnState.id] = viewModel+ store.viewModels.append(viewModel)+ return viewModel+ }++ private func updateInputInteractivity(isActive: Bool) {+ guard let panel else { return }++ if isActive {+ NSApp.activate(ignoringOtherApps: true)+ panel.orderFrontRegardless()+ panel.makeKeyAndOrderFront(nil)+ } else {+ panel.orderFrontRegardless()+ }+ }++ func beginVoiceInput(spawnID: String) -> Bool {+ guard let viewModel = viewModelsByID[spawnID] else { return false }++ viewModel.beginVoiceInput()+ return true+ }++ func completeVoiceInput(spawnID: String, text: String) {+ guard let viewModel = viewModelsByID[spawnID] else { return }++ viewModel.applyTranscribedInput(text, submit: !text.isEmpty)+ }++ func cancelVoiceInput(spawnID: String) {+ guard let viewModel = viewModelsByID[spawnID] else { return }++ viewModel.collapseInput()+ }++ func cueState(+ for spawnState: PointerPromptSpawnState?,+ screen: NSScreen?,+ notchMetrics: PointerPromptNotchMetrics+ ) -> PointerPromptSpawnState? {+ guard var spawnState,+ spawnState.phase == .notchCue,+ let screen else {+ return spawnState+ }++ let notchBottomY = max(+ notchMetrics.layout.collapsedVisibleHeight,+ notchMetrics.layout.voidHeight+ )+ let origin = CGPoint(x: screen.frame.width / 2, y: notchBottomY)+ let destination = destinationPoint(+ for: spawnState.targetHint,+ screen: screen,+ notchMetrics: notchMetrics+ )+ spawnState.notchCueAngleDegrees = PointerPromptSpawnGeometry.angleDegrees(+ from: origin,+ to: destination+ )+ return spawnState+ }++ private func fadeAndCloseAll() {+ guard panel != nil else { return }++ for viewModel in viewModelsByID.values {+ viewModel.fadeOut()+ }+ scheduleCloseAfterFade()+ }++ private func fadeAndRemove(id spawnID: String) {+ viewModelsByID[spawnID]?.fadeOut()+ scheduleRemove(id: spawnID)+ }++ private func scheduleRemove(id spawnID: String) {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.24) { [weak self] in+ guard let self else { return }++ self.viewModelsByID[spawnID] = nil+ self.store.viewModels.removeAll { viewModel in+ viewModel.state?.id == spawnID || viewModel.state == nil+ }+ if self.store.viewModels.isEmpty {+ self.scheduleCloseAfterFade()+ }+ }+ }++ private func scheduleCloseAfterFade() {+ closeWorkItem?.cancel()+ let workItem = DispatchWorkItem { [weak self] in+ Task { @MainActor in+ self?.panel?.close()+ self?.panel = nil+ self?.hostingView = nil+ self?.store.viewModels = []+ self?.viewModelsByID = [:]+ self?.closeWorkItem = nil+ }+ }+ closeWorkItem = workItem+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.24, execute: workItem)+ }++ private func spawnOrigin(in screen: NSScreen, index: Int) -> CGPoint {+ let stagger = CGFloat((index % 5) - 2) * 18+ return CGPoint(x: screen.frame.width / 2 + stagger, y: -24)+ }++ private func destinationPoint(+ for hint: PointerPromptSpawnTargetHint?,+ viewModel: PointerPromptSpawnOverlayViewModel,+ screen: NSScreen,+ notchMetrics: PointerPromptNotchMetrics+ ) -> CGPoint {+ guard !viewModel.freezesMovement else {+ return viewModel.destination+ }++ return destinationPoint(+ for: hint,+ screen: screen,+ notchMetrics: notchMetrics+ )+ }++ private func destinationPoint(+ for hint: PointerPromptSpawnTargetHint?,+ screen: NSScreen,+ notchMetrics: PointerPromptNotchMetrics+ ) -> CGPoint {+ let screenSize = screen.frame.size+ let fallback = PointerPromptSpawnGeometry.fallbackPoint(+ screenSize: screenSize,+ notchBottomY: max(+ notchMetrics.layout.collapsedVisibleHeight,+ notchMetrics.layout.voidHeight+ )+ )++ guard let hint else { return fallback }++ if let bounds = hint.bounds {+ return point(for: bounds, on: screen) ?? fallback+ }++ guard let target = resolvedWindowTarget(for: hint) else {+ return fallback+ }++ return point(for: target.bounds, on: screen) ?? fallback+ }++ private func resolvedWindowTarget(for hint: PointerPromptSpawnTargetHint) -> MacWindowTargetCandidate? {+ let candidates = windowResolver.enumerateCandidates()+ .filter {+ $0.isVisible &&+ $0.isOnScreen &&+ $0.safetyAssessment.status == .allowed &&+ matches($0, hint: hint)+ }++ return candidates+ .sorted {+ if $0.isFocused != $1.isFocused {+ return $0.isFocused && !$1.isFocused+ }+ if $0.isFrontmost != $1.isFrontmost {+ return $0.isFrontmost && !$1.isFrontmost+ }+ return $0.bounds.width * $0.bounds.height > $1.bounds.width * $1.bounds.height+ }+ .first+ }++ private func matches(+ _ candidate: MacWindowTargetCandidate,+ hint: PointerPromptSpawnTargetHint+ ) -> Bool {+ if let bundleIdentifier = hint.bundleIdentifier,+ candidate.bundleIdentifier != bundleIdentifier {+ return false+ }++ if let titleContains = hint.titleContains,+ candidate.title?.localizedCaseInsensitiveContains(titleContains) != true {+ return false+ }++ if hint.bundleIdentifier == nil,+ hint.titleContains == nil,+ let appName = hint.appName,+ candidate.appName?.localizedCaseInsensitiveContains(appName) != true {+ return false+ }++ return true+ }++ private func point(+ for bounds: WindowTargetBounds,+ on screen: NSScreen+ ) -> CGPoint? {+ guard bounds.hasPositiveArea else { return nil }++ let localPoint = CGPoint(+ x: CGFloat(bounds.x) - screen.frame.minX + CGFloat(bounds.width) / 2,+ y: CGFloat(bounds.y) + CGFloat(bounds.height) / 2+ )+ return PointerPromptSpawnGeometry.clampedPoint(+ localPoint,+ in: screen.frame.size+ )+ }+}++private final class PointerPromptSpawnPanel: NSPanel {+ override var canBecomeKey: Bool {+ true+ }++ override var canBecomeMain: Bool {+ true+ }+}++private final class PointerPromptSpawnHostingView<Content: View>: NSHostingView<Content> {+ var hitTestRegionProvider: (() -> [CGRect])?++ override func hitTest(_ point: NSPoint) -> NSView? {+ if let hitTestRegionProvider,+ !hitTestRegionProvider().contains(where: { $0.contains(point) }) {+ return nil+ }++ return super.hitTest(point)+ }+}diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptSpawnContracts.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptSpawnContracts.swiftnew file mode 100644index 00000000..493c4ff6--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptSpawnContracts.swift@@ -0,0 +1,172 @@+import CoreGraphics+import Foundation++public enum PointerPromptSpawnPhase: String, Codable, Equatable, Sendable {+ case notchCue+ case traveling+ case holding+ case fading+}++public enum PointerPromptSpawnInputState: String, Codable, Equatable, Sendable {+ case collapsed+ case editing+}++public struct PointerPromptSpawnTargetHint: Codable, Equatable, Sendable {+ public var appName: String?+ public var bundleIdentifier: String?+ public var titleContains: String?+ public var bounds: WindowTargetBounds?+ public var metadata: [String: String]++ public init(+ appName: String? = nil,+ bundleIdentifier: String? = nil,+ titleContains: String? = nil,+ bounds: WindowTargetBounds? = nil,+ metadata: [String: String] = [:]+ ) {+ self.appName = appName+ self.bundleIdentifier = bundleIdentifier+ self.titleContains = titleContains+ self.bounds = bounds+ self.metadata = metadata+ }+}++public struct PointerPromptSpawnState: Codable, Equatable, Identifiable, Sendable {+ public var id: String+ public var taskID: String?+ public var commandText: String+ public var label: String+ public var accentIndex: Int+ public var phase: PointerPromptSpawnPhase+ public var notchCueAngleDegrees: Double+ public var targetHint: PointerPromptSpawnTargetHint?+ public var inputState: PointerPromptSpawnInputState+ public var updatedAt: Date++ public init(+ id: String = UUID().uuidString,+ taskID: String? = nil,+ commandText: String,+ label: String,+ accentIndex: Int,+ phase: PointerPromptSpawnPhase = .notchCue,+ notchCueAngleDegrees: Double = PointerPromptSpawnGeometry.defaultExitAngleDegrees,+ targetHint: PointerPromptSpawnTargetHint? = nil,+ inputState: PointerPromptSpawnInputState = .collapsed,+ updatedAt: Date = Date()+ ) {+ self.id = id+ self.taskID = taskID+ self.commandText = commandText+ self.label = label+ self.accentIndex = accentIndex+ self.phase = phase+ self.notchCueAngleDegrees = notchCueAngleDegrees+ self.targetHint = targetHint+ self.inputState = inputState+ self.updatedAt = updatedAt+ }+}++public struct PointerPromptSpawnProgressUpdate: Equatable, Sendable {+ public var label: String?+ public var targetHint: PointerPromptSpawnTargetHint?+ public var phase: PointerPromptSpawnPhase?++ public init(+ label: String? = nil,+ targetHint: PointerPromptSpawnTargetHint? = nil,+ phase: PointerPromptSpawnPhase? = nil+ ) {+ self.label = label+ self.targetHint = targetHint+ self.phase = phase+ }+}++public struct PointerPromptSpawnFollowUpSubmission: Equatable, Sendable {+ public var spawnID: String+ public var taskID: String+ public var text: String++ public init(+ spawnID: String,+ taskID: String,+ text: String+ ) {+ self.spawnID = spawnID+ self.taskID = taskID+ self.text = text+ }+}++public enum PointerPromptSpawnLifecycle {+ public static func freezesMovement(+ inputState: PointerPromptSpawnInputState,+ draftText: String+ ) -> Bool {+ inputState == .editing ||+ !draftText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }++ public static func followUpSubmission(+ from state: PointerPromptSpawnState,+ text: String+ ) -> PointerPromptSpawnFollowUpSubmission? {+ let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmedText.isEmpty,+ let taskID = state.taskID else {+ return nil+ }++ return PointerPromptSpawnFollowUpSubmission(+ spawnID: state.id,+ taskID: taskID,+ text: trimmedText+ )+ }+}++public enum PointerPromptSpawnGeometry {+ public static let defaultExitAngleDegrees: Double = 90+ public static let fallbackVerticalOffset: CGFloat = 250+ public static let minimumScreenInset: CGFloat = 36++ public static func fallbackPoint(+ screenSize: CGSize,+ notchBottomY: CGFloat,+ verticalOffset: CGFloat = fallbackVerticalOffset,+ inset: CGFloat = minimumScreenInset+ ) -> CGPoint {+ clampedPoint(+ CGPoint(x: screenSize.width / 2, y: notchBottomY + verticalOffset),+ in: screenSize,+ inset: inset+ )+ }++ public static func clampedPoint(+ _ point: CGPoint,+ in screenSize: CGSize,+ inset: CGFloat = minimumScreenInset+ ) -> CGPoint {+ let maximumX = max(inset, screenSize.width - inset)+ let maximumY = max(inset, screenSize.height - inset)+ return CGPoint(+ x: min(max(point.x, inset), maximumX),+ y: min(max(point.y, inset), maximumY)+ )+ }++ public static func angleDegrees(from origin: CGPoint, to target: CGPoint) -> Double {+ atan2(target.y - origin.y, target.x - origin.x) * 180 / .pi+ }++ public static func labelTypingIdentity(spawnID: String, label: String) -> String {+ "\(spawnID):\(label)"+ }+}diff --git a/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swiftindex 902edc5b..95d01504 100644--- a/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift+++ b/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift@@ -4,6 +4,9 @@ import SwiftUIimport UniformTypeIdentifierspublic struct PointerPromptNotchStatusView: View {+ @State private var renderedSpawnCue: PointerPromptSpawnState?+ @State private var spawnCueIsExiting = false+private let state: PointerPromptStateprivate let updateState: PointerPromptUpdateStateprivate let layout: PointerPromptNotchLayout@@ -16,6 +19,7 @@ public struct PointerPromptNotchStatusView: View {private let isCommandInputExpanded: Boolprivate let tasks: [PointerPromptNotchTask]private let accentIndex: Int+ private let spawnState: PointerPromptSpawnState?private let commandSubmitted: @MainActor (String) -> Voidprivate let commandInputTextHeightChanged: @MainActor (CGFloat) -> Voidprivate let commandInputExpansionChanged: @MainActor (Bool) -> Void@@ -37,6 +41,7 @@ public struct PointerPromptNotchStatusView: View {isCommandInputExpanded: Bool,tasks: [PointerPromptNotchTask] = [],accentIndex: Int,+ spawnState: PointerPromptSpawnState? = nil,commandSubmitted: @escaping @MainActor (String) -> Void,commandInputTextHeightChanged: @escaping @MainActor (CGFloat) -> Void,commandInputExpansionChanged: @escaping @MainActor (Bool) -> Void,@@ -57,6 +62,7 @@ public struct PointerPromptNotchStatusView: View {self.isCommandInputExpanded = isCommandInputExpandedself.tasks = tasksself.accentIndex = accentIndex+ self.spawnState = spawnStateself.commandSubmitted = commandSubmittedself.commandInputTextHeightChanged = commandInputTextHeightChangedself.commandInputExpansionChanged = commandInputExpansionChanged@@ -106,6 +112,10 @@ public struct PointerPromptNotchStatusView: View {value: isExpanded)}++ if let renderedSpawnCue {+ spawnCueArrow(renderedSpawnCue)+ }}.frame(width: animatingSurfaceWidth, height: animatingSurfaceHeight, alignment: .top).clipShape(notchSurfaceShape(cornerRadius: animatingSurfaceCornerRadius))@@ -122,6 +132,10 @@ public struct PointerPromptNotchStatusView: View {isTargeted: nil,perform: handleDroppedFileProviders)+ .onAppear(perform: updateRenderedSpawnCue)+ .onChange(of: spawnCueIdentity) {+ updateRenderedSpawnCue()+ }}@ViewBuilder@@ -294,6 +308,24 @@ public struct PointerPromptNotchStatusView: View {.position(x: expandedNotchArrowX, y: expandedNotchArrowY)}+ private func spawnCueArrow(_ cue: PointerPromptSpawnState) -> some View {+ let exitOffset = spawnCueExitOffset(for: cue.notchCueAngleDegrees)++ return TaskArrowMark(+ color: accentColor(for: cue.accentIndex),+ rotationDegrees: spawnCueIsExiting ? cue.notchCueAngleDegrees : -45+ )+ .frame(width: 15, height: 15)+ .position(x: spawnCueArrowX, y: spawnCueArrowY)+ .offset(+ x: spawnCueIsExiting ? exitOffset.width : 0,+ y: spawnCueIsExiting ? exitOffset.height : 0+ )+ .opacity(spawnCueIsExiting ? 0 : 1)+ .animation(.easeInOut(duration: 0.16), value: spawnCueIsExiting)+ .accessibilityHidden(true)+ }+private var expandedUpdateHeader: some View {HStack {Spacer()@@ -334,6 +366,58 @@ public struct PointerPromptNotchStatusView: View {max(14, layout.collapsedVisibleHeight / 2)}+ private var spawnCueArrowX: CGFloat {+ layout.canRenderTextInTopRow+ ? max(16, layout.contentHorizontalInset + 6)+ : collapsedLeadingLaneCenterX+ }++ private var spawnCueArrowY: CGFloat {+ max(14, layout.collapsedVisibleHeight / 2)+ }++ private var spawnCueIdentity: String? {+ guard let spawnState,+ spawnState.phase == .notchCue else {+ return nil+ }++ return spawnState.id+ }++ private func updateRenderedSpawnCue() {+ guard let spawnState,+ spawnState.phase == .notchCue else {+ return+ }++ guard renderedSpawnCue?.id != spawnState.id else { return }++ renderedSpawnCue = spawnState+ spawnCueIsExiting = false+ let cueID = spawnState.id+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) {+ guard renderedSpawnCue?.id == cueID else { return }++ spawnCueIsExiting = true+ }+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.26) {+ guard renderedSpawnCue?.id == cueID else { return }++ renderedSpawnCue = nil+ spawnCueIsExiting = false+ }+ }++ private func spawnCueExitOffset(for angleDegrees: Double) -> CGSize {+ let radians = angleDegrees * .pi / 180+ let distance: CGFloat = 28+ return CGSize(+ width: cos(radians) * distance,+ height: sin(radians) * distance+ )+ }+private var expandedCommandOnlyTopPadding: CGFloat {layout.expandedCommandOnlyTopPadding}@@ -738,6 +822,7 @@ public struct PointerPromptNotchStatusView: View {private struct TaskArrowMark: View {var color: Color+ var rotationDegrees: Double = -45var body: some View {GeometryReader { proxy in@@ -753,7 +838,7 @@ private struct TaskArrowMark: View {.fill(color)}.aspectRatio(1, contentMode: .fit)- .rotationEffect(.degrees(-45))+ .rotationEffect(.degrees(rotationDegrees)).accessibilityHidden(true)}}diff --git a/apps/Donkey/Sources/DonkeyUI/PointerPromptSpawnOverlayView.swift b/apps/Donkey/Sources/DonkeyUI/PointerPromptSpawnOverlayView.swiftnew file mode 100644index 00000000..735bda5d--- /dev/null+++ b/apps/Donkey/Sources/DonkeyUI/PointerPromptSpawnOverlayView.swift@@ -0,0 +1,821 @@+import AppKit+import DonkeyContracts+import SwiftUI++@MainActor+public final class PointerPromptSpawnOverlayViewModel: ObservableObject {+ public let objectID = UUID().uuidString+ @Published public private(set) var state: PointerPromptSpawnState?+ @Published public private(set) var position: CGPoint = .zero+ @Published public private(set) var destination: CGPoint = .zero+ @Published public private(set) var screenSize: CGSize = .zero+ @Published public private(set) var opacity: Double = 0+ @Published public private(set) var isHolding = false+ @Published public private(set) var isSelected = false+ @Published public var inputText = ""+ @Published public var inputTextHeight: CGFloat = PointerPromptSpawnOverlayViewModel.inputMinimumTextHeight+ @Published public private(set) var isInputExpanded = false++ public var inputActivityChanged: ((Bool) -> Void)?+ public var followUpSubmitted: ((String, String, String) -> Void)?+ public var selected: ((String) -> Void)?++ private var animationGeneration = 0++ public init() {}++ public var isInputActive: Bool {+ state?.inputState == .editing+ }++ public var freezesMovement: Bool {+ PointerPromptSpawnLifecycle.freezesMovement(+ inputState: state?.inputState ?? .collapsed,+ draftText: inputText+ )+ }++ public var canSubmitInput: Bool {+ guard let state else { return false }++ return PointerPromptSpawnLifecycle.followUpSubmission(+ from: state,+ text: inputText+ ) != nil+ }++ public var hitTestFrame: CGRect {+ guard state != nil, isHolding else { return .null }++ let width: CGFloat = isInputActive ? 312 : 244+ let height: CGFloat = isInputActive ? 142 : 54+ let offset = labelOffset(in: screenSize)+ let origin = CGPoint(+ x: position.x + offset.width - width / 2,+ y: position.y + offset.height - height / 2+ )+ return cursorHitTestFrame+ .union(CGRect(origin: origin, size: CGSize(width: width, height: height)))+ .insetBy(dx: -14, dy: -14)+ }++ public var cursorHitTestFrame: CGRect {+ guard state != nil else { return .null }++ return CGRect(+ x: position.x - 22,+ y: position.y - 22,+ width: 44,+ height: 44+ )+ }++ public func labelOffset(in screenSize: CGSize) -> CGSize {+ let labelSize = CGSize(+ width: isInputActive ? 292 : 220,+ height: isInputActive ? 126 : 46+ )+ let margin: CGFloat = 20+ let rightOffset = Self.preferredLabelOffset+ let leftOffset = CGSize(width: -labelSize.width / 2 - 40, height: rightOffset.height)+ let upOffset = CGSize(width: rightOffset.width, height: -labelSize.height - 28)+ let upLeftOffset = CGSize(width: leftOffset.width, height: upOffset.height)++ if point(position, offsetBy: rightOffset, labelSize: labelSize, fitsIn: screenSize, margin: margin) {+ return rightOffset+ }+ if point(position, offsetBy: leftOffset, labelSize: labelSize, fitsIn: screenSize, margin: margin) {+ return leftOffset+ }+ if point(position, offsetBy: upOffset, labelSize: labelSize, fitsIn: screenSize, margin: margin) {+ return upOffset+ }+ return upLeftOffset+ }++ public func show(+ state: PointerPromptSpawnState,+ origin: CGPoint,+ destination: CGPoint,+ screenSize: CGSize+ ) {+ animationGeneration += 1+ self.state = state+ self.position = origin+ self.destination = destination+ self.screenSize = screenSize+ self.opacity = 0+ self.isHolding = false+ self.inputText = ""+ self.inputTextHeight = Self.inputMinimumTextHeight+ self.isInputExpanded = false+ inputActivityChanged?(false)++ let generation = animationGeneration+ DispatchQueue.main.async { [weak self] in+ guard let self, self.animationGeneration == generation else { return }++ withAnimation(Self.travelAnimation) {+ self.position = destination+ self.opacity = 1+ }+ self.finishTravelAfterDelay(generation: generation)+ }+ }++ public func update(+ state: PointerPromptSpawnState,+ destination: CGPoint,+ screenSize: CGSize+ ) {+ guard self.state?.id == state.id else {+ show(state: state, origin: position, destination: destination, screenSize: screenSize)+ return+ }++ self.state = stateWithPreservedLocalInput(state)+ self.screenSize = screenSize+ guard state.phase != .fading else {+ fadeOut()+ return+ }++ guard !freezesMovement else { return }+ guard distance(from: self.destination, to: destination) > 1 else { return }++ animationGeneration += 1+ let generation = animationGeneration+ self.destination = destination+ self.isHolding = false+ withAnimation(Self.travelAnimation) {+ self.position = destination+ self.opacity = 1+ }+ finishTravelAfterDelay(generation: generation)+ }++ public func fadeOut() {+ animationGeneration += 1+ inputActivityChanged?(false)+ withAnimation(.easeOut(duration: 0.18)) {+ opacity = 0+ }++ let generation = animationGeneration+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in+ guard let self, self.animationGeneration == generation else { return }++ self.state = nil+ self.isHolding = false+ self.inputText = ""+ self.inputTextHeight = Self.inputMinimumTextHeight+ self.isInputExpanded = false+ }+ }++ public func beginInput() {+ guard var state, isHolding else { return }++ selected?(state.id)+ state.inputState = .editing+ state.updatedAt = Date()+ self.state = state+ inputActivityChanged?(true)+ }++ public func beginVoiceInput() {+ guard var state else { return }++ selected?(state.id)+ state.inputState = .editing+ state.label = "Listening..."+ state.updatedAt = Date()+ self.state = state+ inputText = ""+ inputTextHeight = Self.inputMinimumTextHeight+ isInputExpanded = false+ isHolding = true+ inputActivityChanged?(true)+ }++ public func applyTranscribedInput(_ text: String, submit: Bool) {+ guard var state else { return }++ state.inputState = .editing+ state.label = text.isEmpty ? "I didn't catch that" : "Heard you"+ state.updatedAt = Date()+ self.state = state+ inputText = text+ inputActivityChanged?(true)+ if submit {+ submitInput()+ }+ }++ public func collapseInput() {+ guard var state else { return }++ inputText = ""+ inputTextHeight = Self.inputMinimumTextHeight+ isInputExpanded = false+ state.inputState = .collapsed+ state.updatedAt = Date()+ self.state = state+ inputActivityChanged?(false)+ }++ public func submitInput() {+ guard var state,+ let submission = PointerPromptSpawnLifecycle.followUpSubmission(+ from: state,+ text: inputText+ )+ else { return }++ inputText = ""+ inputTextHeight = Self.inputMinimumTextHeight+ isInputExpanded = false+ state.inputState = .collapsed+ state.updatedAt = Date()+ self.state = state+ inputActivityChanged?(false)+ followUpSubmitted?(submission.spawnID, submission.taskID, submission.text)+ }++ public func setSelected(_ isSelected: Bool) {+ guard self.isSelected != isSelected else { return }++ self.isSelected = isSelected+ }++ public func select() {+ guard let state else { return }++ selected?(state.id)+ }++ public func updateInputTextHeight(_ height: CGFloat) {+ let clamped = min(max(height, Self.inputMinimumTextHeight), Self.inputMaximumTextHeight)+ guard abs(inputTextHeight - clamped) > 0.5 else { return }++ inputTextHeight = clamped+ isInputExpanded = clamped > Self.inputMinimumTextHeight + 1 || inputText.contains("\n")+ }++ private func finishTravelAfterDelay(generation: Int) {+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.travelDuration) { [weak self] in+ guard let self, self.animationGeneration == generation else { return }++ self.isHolding = true+ if var state = self.state, state.phase == .traveling || state.phase == .notchCue {+ state.phase = .holding+ state.updatedAt = Date()+ self.state = state+ }+ }+ }++ private func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {+ hypot(lhs.x - rhs.x, lhs.y - rhs.y)+ }++ private func stateWithPreservedLocalInput(+ _ incomingState: PointerPromptSpawnState+ ) -> PointerPromptSpawnState {+ guard let currentState = state,+ currentState.id == incomingState.id,+ currentState.inputState == .editing+ else {+ return incomingState+ }++ var mergedState = incomingState+ mergedState.inputState = .editing+ return mergedState+ }++ private func point(+ _ point: CGPoint,+ offsetBy offset: CGSize,+ labelSize: CGSize,+ fitsIn screenSize: CGSize,+ margin: CGFloat+ ) -> Bool {+ let rect = CGRect(+ x: point.x + offset.width - labelSize.width / 2,+ y: point.y + offset.height - labelSize.height / 2,+ width: labelSize.width,+ height: labelSize.height+ )+ return rect.minX >= margin &&+ rect.minY >= margin &&+ rect.maxX <= screenSize.width - margin &&+ rect.maxY <= screenSize.height - margin+ }++ public static let travelDuration: TimeInterval = 0.82+ public static let inputMinimumTextHeight: CGFloat = 16+ public static let inputMaximumTextHeight: CGFloat = 76+ private static let preferredLabelOffset = CGSize(width: 138, height: 48)+ private static let travelAnimation = Animation.timingCurve(0.45, 0.05, 0.3, 1, duration: travelDuration)+}++@MainActor+public final class PointerPromptSpawnOverlayStore: ObservableObject {+ @Published public var viewModels: [PointerPromptSpawnOverlayViewModel] = []++ public init() {}+}++public struct PointerPromptSpawnOverlayContainerView: View {+ @ObservedObject private var store: PointerPromptSpawnOverlayStore++ public init(store: PointerPromptSpawnOverlayStore) {+ self.store = store+ }++ public var body: some View {+ ZStack(alignment: .topLeading) {+ Color.black.opacity(0.001)++ ForEach(store.viewModels, id: \.objectID) { viewModel in+ PointerPromptSpawnOverlayView(viewModel: viewModel)+ }+ }+ .ignoresSafeArea()+ }+}++public struct PointerPromptSpawnOverlayView: View {+ @ObservedObject private var viewModel: PointerPromptSpawnOverlayViewModel+ @FocusState private var labelIsFocused: Bool++ public init(viewModel: PointerPromptSpawnOverlayViewModel) {+ self.viewModel = viewModel+ }++ public var body: some View {+ GeometryReader { proxy in+ ZStack(alignment: .topLeading) {+ Color.black.opacity(0.001)++ if let state = viewModel.state {+ spawnSurface(state: state, screenSize: proxy.size)+ .position(viewModel.position)+ .opacity(viewModel.opacity)+ }+ }+ }+ .ignoresSafeArea()+ }++ private func spawnSurface(+ state: PointerPromptSpawnState,+ screenSize: CGSize+ ) -> some View {+ ZStack(alignment: .topLeading) {+ if viewModel.isHolding {+ Circle()+ .stroke(accentColor(for: state.accentIndex).opacity(0.68), lineWidth: 1.4)+ .frame(width: 36, height: 36)+ .scaleEffect(holdingPulseScale)+ .opacity(holdingPulseOpacity)+ .position(.zero)+ }++ if viewModel.isSelected {+ Circle()+ .stroke(Color.white.opacity(0.52), lineWidth: 1.2)+ .frame(width: 42, height: 42)+ .position(.zero)+ }++ cursor(state: state)+ .position(.zero)++ if viewModel.isHolding {+ stationaryLabel(state: state)+ .offset(+ x: viewModel.labelOffset(in: screenSize).width,+ y: viewModel.labelOffset(in: screenSize).height+ )+ .transition(.opacity.combined(with: .scale(scale: 0.96, anchor: .topLeading)))+ }+ }+ .contentShape(Rectangle())+ .onTapGesture {+ viewModel.select()+ }+ }++ private func cursor(state: PointerPromptSpawnState) -> some View {+ SpawnPointerShape()+ .fill(accentColor(for: state.accentIndex))+ .overlay {+ SpawnPointerShape()+ .stroke(Color.white.opacity(0.92), lineWidth: 1.5)+ }+ .shadow(color: Color.black.opacity(0.34), radius: 4, x: 0, y: 2)+ .frame(width: 28, height: 28)+ .rotationEffect(.degrees(cursorAngleDegrees + 50))+ .scaleEffect(viewModel.isHolding ? holdingCursorScale : 1)+ }++ private func stationaryLabel(state: PointerPromptSpawnState) -> some View {+ VStack(alignment: .leading, spacing: 8) {+ TypewriterText(+ text: state.label,+ identity: PointerPromptSpawnGeometry.labelTypingIdentity(+ spawnID: state.id,+ label: state.label+ )+ )+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.white)+ .lineLimit(2)+ .fixedSize(horizontal: false, vertical: true)++ if viewModel.isInputActive {+ compactInput+ }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 7)+ .frame(width: viewModel.isInputActive ? 292 : 220, alignment: .leading)+ .background {+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .fill(Color.black.opacity(0.82))+ }+ .overlay {+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .stroke(Color.white.opacity(viewModel.isInputActive ? 0.26 : 0.16), lineWidth: 1)+ .overlay {+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .stroke(Color.white.opacity(viewModel.isSelected ? 0.34 : 0), lineWidth: 1.4)+ }+ }+ .shadow(color: Color.black.opacity(0.32), radius: 10, x: 0, y: 5)+ .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous))+ .onTapGesture {+ viewModel.select()+ viewModel.beginInput()+ }+ .focusable(true)+ .focused($labelIsFocused)+ .onChange(of: labelIsFocused) {+ if labelIsFocused {+ viewModel.beginInput()+ }+ }+ }++ private var compactInput: some View {+ HStack(alignment: .bottom, spacing: 8) {+ SpawnLabelTextInput(+ text: $viewModel.inputText,+ isActive: viewModel.isInputActive,+ textHeightChanged: viewModel.updateInputTextHeight,+ submit: viewModel.submitInput,+ cancel: viewModel.collapseInput+ )+ .frame(height: viewModel.inputTextHeight)+ .padding(.horizontal, 10)+ .padding(.vertical, 8)+ .frame(minHeight: 34)+ .background(Color.white.opacity(0.09))+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))++ Button(action: viewModel.submitInput) {+ Image(systemName: "arrow.up")+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(Color.black.opacity(0.78))+ .frame(width: 26, height: 26)+ .background(Color.white.opacity(0.92))+ .clipShape(Circle())+ }+ .buttonStyle(.plain)+ .disabled(!viewModel.canSubmitInput)+ }+ .frame(width: 272)+ }++ private var cursorAngleDegrees: Double {+ PointerPromptSpawnGeometry.angleDegrees(+ from: viewModel.position,+ to: viewModel.destination+ )+ }++ private var holdingPulseScale: CGFloat {+ viewModel.freezesMovement ? 1.04 : 1.14+ }++ private var holdingPulseOpacity: Double {+ viewModel.freezesMovement ? 0.32 : 0.2+ }++ private var holdingCursorScale: CGFloat {+ viewModel.freezesMovement ? 1.02 : 1.08+ }++ private func accentColor(for index: Int) -> Color {+ Self.accentColors[((index % Self.accentColors.count) + Self.accentColors.count) % Self.accentColors.count]+ }++ private static let accentColors: [Color] = [+ Color(red: 0.114, green: 0.62, blue: 0.46),+ Color(red: 0.94, green: 0.62, blue: 0.15),+ Color(red: 0.83, green: 0.33, blue: 0.49),+ Color(red: 0.22, green: 0.54, blue: 0.87),+ Color(red: 0.5, green: 0.47, blue: 0.87),+ Color(red: 0.88, green: 0.35, blue: 0.28),+ Color(red: 0.24, green: 0.69, blue: 0.71),+ Color(red: 0.66, green: 0.34, blue: 0.79)+ ]+}++private struct TypewriterText: View {+ let text: String+ let identity: String+ @State private var visibleText = ""+ @State private var generation = UUID()++ var body: some View {+ Text(visibleText)+ .onAppear {+ restart()+ }+ .onChange(of: identity) {+ restart()+ }+ }++ private func restart() {+ let currentGeneration = UUID()+ generation = currentGeneration+ visibleText = ""++ let characters = Array(text)+ guard !characters.isEmpty else { return }++ for index in characters.indices {+ DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.026) {+ guard generation == currentGeneration else { return }++ visibleText = String(characters[...index])+ }+ }+ }+}++private struct SpawnLabelTextInput: NSViewRepresentable {+ @Binding var text: String+ let isActive: Bool+ let textHeightChanged: @MainActor (CGFloat) -> Void+ let submit: @MainActor () -> Void+ let cancel: @MainActor () -> Void++ func makeNSView(context: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.drawsBackground = false+ scrollView.borderType = .noBorder+ scrollView.hasVerticalScroller = false+ scrollView.hasHorizontalScroller = false+ scrollView.autohidesScrollers = true++ let textView = SpawnLabelTextView()+ textView.delegate = context.coordinator+ textView.shouldFocusWhenAttached = isActive+ textView.submit = {+ Task { @MainActor in+ submit()+ }+ }+ textView.cancel = {+ Task { @MainActor in+ cancel()+ }+ }+ textView.string = text+ textView.insertionPointColor = .white+ SpawnLabelTextStyle.apply(to: textView)+ textView.backgroundColor = .clear+ textView.drawsBackground = false+ textView.isRichText = false+ textView.importsGraphics = false+ textView.allowsUndo = true+ textView.isEditable = true+ textView.isSelectable = true+ textView.isHorizontallyResizable = false+ textView.isVerticallyResizable = true+ textView.minSize = CGSize(width: 0, height: PointerPromptSpawnOverlayViewModel.inputMinimumTextHeight)+ textView.maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)+ textView.autoresizingMask = [.width]+ textView.textContainerInset = .zero+ textView.textContainer?.lineFragmentPadding = 0+ textView.textContainer?.widthTracksTextView = true+ textView.textContainer?.heightTracksTextView = false+ scrollView.documentView = textView++ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ context.coordinator.parent = self+ guard let textView = scrollView.documentView as? SpawnLabelTextView else { return }++ textView.shouldFocusWhenAttached = isActive+ textView.submit = {+ Task { @MainActor in+ submit()+ }+ }+ textView.cancel = {+ Task { @MainActor in+ cancel()+ }+ }+ SpawnLabelTextStyle.apply(to: textView)++ if textView.string != text {+ textView.string = text+ SpawnLabelTextStyle.apply(to: textView)+ textView.needsDisplay = true+ }++ DispatchQueue.main.async {+ context.coordinator.updateTextContainerWidth(for: textView, in: scrollView)+ context.coordinator.reportTextHeight(for: textView)++ if isActive, textView.window?.firstResponder !== textView {+ textView.focusIfNeeded()+ }+ }+ }++ func makeCoordinator() -> Coordinator {+ Coordinator(parent: self)+ }++ @MainActor+ final class Coordinator: NSObject, NSTextViewDelegate {+ var parent: SpawnLabelTextInput++ init(parent: SpawnLabelTextInput) {+ self.parent = parent+ }++ func textDidChange(_ notification: Notification) {+ guard let textView = notification.object as? SpawnLabelTextView else { return }++ parent.text = textView.string+ textView.needsDisplay = true+ reportTextHeight(for: textView)+ textView.scrollRangeToVisible(textView.selectedRange())+ }++ func updateTextContainerWidth(+ for textView: NSTextView,+ in scrollView: NSScrollView+ ) {+ let width = max(1, scrollView.contentView.bounds.width)+ textView.textContainer?.containerSize = CGSize(width: width, height: .greatestFiniteMagnitude)+ let documentHeight = max(+ PointerPromptSpawnOverlayViewModel.inputMinimumTextHeight,+ measuredTextHeight(for: textView)+ )+ textView.frame = CGRect(x: 0, y: 0, width: width, height: documentHeight)+ }++ func reportTextHeight(for textView: NSTextView) {+ parent.textHeightChanged(measuredTextHeight(for: textView))+ }++ private func measuredTextHeight(for textView: NSTextView) -> CGFloat {+ guard let layoutManager = textView.layoutManager,+ let textContainer = textView.textContainer else {+ return PointerPromptSpawnOverlayViewModel.inputMinimumTextHeight+ }++ layoutManager.ensureLayout(for: textContainer)+ let usedRect = layoutManager.usedRect(for: textContainer)+ return ceil(max(+ PointerPromptSpawnOverlayViewModel.inputMinimumTextHeight,+ usedRect.height+ ))+ }+ }+}++private final class SpawnLabelTextView: NSTextView {+ var submit: (() -> Void)?+ var cancel: (() -> Void)?+ var shouldFocusWhenAttached = false++ override var acceptsFirstResponder: Bool {+ true+ }++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ focusIfNeeded()+ }++ func focusIfNeeded() {+ guard shouldFocusWhenAttached else { return }++ window?.makeFirstResponder(self)+ }++ override func keyDown(with event: NSEvent) {+ let isReturn = event.keyCode == 36 || event.keyCode == 76+ let isEscape = event.keyCode == 53+ let shouldInsertNewline = event.modifierFlags.contains(.shift)++ if isEscape {+ cancel?()+ return+ }++ if isReturn, !shouldInsertNewline {+ submit?()+ return+ }++ super.keyDown(with: event)+ }+}++@MainActor+private enum SpawnLabelTextStyle {+ static var font: NSFont {+ NSFont.systemFont(ofSize: 12, weight: .regular)+ }++ static func apply(to textView: NSTextView) {+ let textAttributes = attributes(color: .white, font: font)+ textView.font = font+ textView.textColor = .white+ textView.typingAttributes = textAttributes++ let textRange = NSRange(location: 0, length: textView.string.utf16.count)+ guard textRange.length > 0 else { return }++ textView.textStorage?.setAttributes(textAttributes, range: textRange)+ }++ static func attributes(+ color: NSColor,+ font: NSFont+ ) -> [NSAttributedString.Key: Any] {+ [+ .foregroundColor: color,+ .font: font,+ .ligature: 0+ ]+ }+}++private struct SpawnPointerShape: Shape {+ func path(in rect: CGRect) -> Path {+ var path = Path()+ let w = rect.width+ let h = rect.height++ path.move(to: svgPoint(x: 83.086, y: 5.6406, width: w, height: h))+ path.addLine(to: svgPoint(x: 10.453, y: 34.6836, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 11.13269, y: 51.0276, width: w, height: h),+ control1: svgPoint(x: 2.8514, y: 37.7227, width: w, height: h),+ control2: svgPoint(x: 3.3085, y: 48.6326, width: w, height: h)+ )+ path.addLine(to: svgPoint(x: 35.69469, y: 58.5471, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 41.44859, y: 64.301, width: w, height: h),+ control1: svgPoint(x: 38.44859, y: 59.39085, width: w, height: h),+ control2: svgPoint(x: 40.60489, y: 61.5471, width: w, height: h)+ )+ path.addLine(to: svgPoint(x: 48.96809, y: 88.863, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 65.31209, y: 89.54269, width: w, height: h),+ control1: svgPoint(x: 51.36649, y: 96.6911, width: w, height: h),+ control2: svgPoint(x: 62.27309, y: 97.1442, width: w, height: h)+ )+ path.addLine(to: svgPoint(x: 94.35509, y: 16.90969, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 83.08209, y: 5.63669, width: w, height: h),+ control1: svgPoint(x: 97.18709, y: 9.83159, width: w, height: h),+ control2: svgPoint(x: 90.15979, y: 2.80769, width: w, height: h)+ )+ path.closeSubpath()++ return path+ }++ private func svgPoint(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> CGPoint {+ CGPoint(+ x: x / 100 * width,+ y: y / 100 * height+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptSpawnGeometryTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptSpawnGeometryTests.swiftnew file mode 100644index 00000000..6e4c6b48--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptSpawnGeometryTests.swift@@ -0,0 +1,73 @@+import CoreGraphics+import DonkeyContracts+import Testing++@Suite+struct PointerPromptSpawnGeometryTests {+ @Test+ func fallbackPointSitsBelowNotchAndClampsInsideScreen() {+ let point = PointerPromptSpawnGeometry.fallbackPoint(+ screenSize: CGSize(width: 1200, height: 800),+ notchBottomY: 32+ )++ #expect(point.x == 600)+ #expect(point.y == 282)++ let shortScreenPoint = PointerPromptSpawnGeometry.fallbackPoint(+ screenSize: CGSize(width: 360, height: 260),+ notchBottomY: 40+ )++ #expect(shortScreenPoint.x == 180)+ #expect(shortScreenPoint.y == 224)+ }++ @Test+ func clampedPointRespectsMinimumInset() {+ let point = PointerPromptSpawnGeometry.clampedPoint(+ CGPoint(x: -20, y: 1000),+ in: CGSize(width: 500, height: 400),+ inset: 40+ )++ #expect(point.x == 40)+ #expect(point.y == 360)+ }++ @Test+ func cueAngleUsesTopLeftCoordinateSpace() {+ #expect(+ PointerPromptSpawnGeometry.angleDegrees(+ from: CGPoint(x: 100, y: 100),+ to: CGPoint(x: 100, y: 200)+ ) == 90+ )+ #expect(+ PointerPromptSpawnGeometry.angleDegrees(+ from: CGPoint(x: 100, y: 100),+ to: CGPoint(x: 0, y: 100)+ ) == 180+ )+ }++ @Test+ func labelTypingIdentityChangesWhenLabelChanges() {+ let first = PointerPromptSpawnGeometry.labelTypingIdentity(+ spawnID: "spawn-1",+ label: "Routing task"+ )+ let second = PointerPromptSpawnGeometry.labelTypingIdentity(+ spawnID: "spawn-1",+ label: "Opening Music"+ )++ #expect(first != second)+ #expect(+ first == PointerPromptSpawnGeometry.labelTypingIdentity(+ spawnID: "spawn-1",+ label: "Routing task"+ )+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptSpawnLifecycleTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptSpawnLifecycleTests.swiftnew file mode 100644index 00000000..9b1a6bc9--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptSpawnLifecycleTests.swift@@ -0,0 +1,85 @@+import DonkeyContracts+import Testing++@Suite+struct PointerPromptSpawnLifecycleTests {+ @Test+ func inputFreezeTracksEditingAndDirtyDrafts() {+ #expect(+ PointerPromptSpawnLifecycle.freezesMovement(+ inputState: .editing,+ draftText: ""+ )+ )+ #expect(+ PointerPromptSpawnLifecycle.freezesMovement(+ inputState: .collapsed,+ draftText: " clarify this "+ )+ )+ #expect(+ !PointerPromptSpawnLifecycle.freezesMovement(+ inputState: .collapsed,+ draftText: " \n"+ )+ )+ }++ @Test+ func followUpSubmissionRoutesToSameTask() throws {+ let state = PointerPromptSpawnState(+ id: "spawn-1",+ taskID: "task-1",+ commandText: "open music",+ label: "Waiting for detail",+ accentIndex: 3,+ phase: .holding+ )++ let submission = try #require(+ PointerPromptSpawnLifecycle.followUpSubmission(+ from: state,+ text: " play the next song "+ )+ )++ #expect(submission.spawnID == "spawn-1")+ #expect(submission.taskID == "task-1")+ #expect(submission.text == "play the next song")+ }++ @Test+ func followUpSubmissionRequiresTaskAndText() {+ let state = PointerPromptSpawnState(+ id: "spawn-1",+ taskID: nil,+ commandText: "answer this",+ label: "Answering",+ accentIndex: 0,+ phase: .holding+ )++ #expect(+ PointerPromptSpawnLifecycle.followUpSubmission(+ from: state,+ text: "more detail"+ ) == nil+ )++ let taskedState = PointerPromptSpawnState(+ id: "spawn-2",+ taskID: "task-2",+ commandText: "open notes",+ label: "Waiting",+ accentIndex: 1,+ phase: .holding+ )++ #expect(+ PointerPromptSpawnLifecycle.followUpSubmission(+ from: taskedState,+ text: " \n "+ ) == nil+ )+ }+}diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex 9cbc45fc..e872300c 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -8,6 +8,11 @@ quick local-app actions:- Double-tap Command and release to open a centered prompt with keyboard focus.- Double-tap Command and hold the second press to open the prompt in voice mode.- Show a top-center notch status surface for task progress, recent tasks, follow-up input, file drops, updates, and per-task pause/resume.+- When a typed prompt or notch follow-up is submitted, show a task spawn cue: the notch arrow rotates toward the exit direction, moves out of the notch, and a Donkey cursor overlay travels onto the desktop.+- Spawned cursors travel to a known safe visible target window when one is available. Otherwise they hold about 250 px below the notch near screen center as a loading/thinking state, then retarget if the destination becomes visible.+- Multiple spawned cursors can be present at the same time. The newest spawned cursor is selected by default, and clicking a cursor or its label selects it as the current agent.+- A stationary spawned cursor types compact progress text in its label. Clicking or focusing the label expands a smaller multiline follow-up input; while that input is focused or dirty, the cursor stays still until the user submits with Return or the send button, or collapses it with Escape.+- Holding Command while a spawned cursor is selected pauses that cursor for voice input. Donkey expands the cursor label into the compact input, records while Command is held, transcribes the speech into that input on release, submits it as a same-thread follow-up, and then lets the cursor retarget to the next action.- Keep prompt submissions, voice transcripts, and follow-ups on the same agent-harness path: task-thread routing, context assembly, conversational response, clarification, review, catalog-backed action parsing, task validation, and guarded local-app execution when a turn is actionable.- Resolve model-classified local-item requests against local apps, files, and folders by querying the current Mac with the SQLite-backed agent memory store, Spotlight/`mdfind`, and bounded filesystem fallback. If the requested local item cannot be found, keep the task safe and report that it was not found instead of falling back to a vague clarification.- Handle scriptable app tasks as guarded AppleScript automation when possible. Commands may use task metadata, generated source, or compact templates; completion is verified through generic task verification policy instead of requiring visible result text for every app.@@ -21,6 +26,7 @@ quick local-app actions:- `PointerPromptOverlayController` owns AppKit surfaces, placement, hover tracking, focus, keyboard shortcut recognition, dismissal, file-drop routing, and microphone level capture.- SwiftUI rendering lives in `DonkeyUI` and consumes state/contracts from `DonkeyContracts`. It should not perform command parsing, model calls, input execution, screen capture, or microphone capture.- `PointerPromptOverlayModel` owns product state. Durable task data is persisted through Core Data in Application Support.+- Spawn display state is typed state. The model emits progress, target hints, and current selection; the overlay controller resolves hints against safe visible windows and owns Command-hold voice capture for the selected spawn; SwiftUI only renders the notch cue, cursors, labels, selection state, and compact inputs.- Notch geometry comes from the active `NSScreen`, preferring safe-area and auxiliary-top metrics over hardcoded notch sizes. Content must stay out of the physical notch void; displays without a physical notch should use the same top-center composition without reserving unavailable space.- `PointerPromptNotchLayout` is the shared source for notch surface frames, content frames, corner radii, and notch-safe offsets. `canRenderTextInTopRow` describes whether text can draw in the top row, not whether that row exists.- The prompt is a compact black composer: single-line text is pill-shaped, multiline text becomes a bounded rounded rectangle, Return submits, Shift-Return inserts a newline, Escape and outside clicks dismiss, and non-input capsule areas can drag the modal.@@ -38,6 +44,9 @@ Manually verify:- The notch renders at the top center, respects physical notch safe areas, expands only from visible notch hover, and accepts expanded controls/clicks.- Double-Command release opens a centered focused text prompt; double-Command hold opens voice mode; unrelated Command use does not activate the overlay.- Typed, voice, and follow-up submissions create or update durable task threads, answer non-actionable conversation without showing action failure, show action status in the notch when work runs, and preserve per-task pause/resume behavior.+- Typed prompt and notch follow-up submissions show the spawn sequence: notch cue, desktop cursor emergence, direct travel to a known target or fallback holding point, typed progress label, retargeting when the target becomes visible, and fade-out for completed conversational turns.+- Stationary spawn labels expand on click/focus, accept compact multiline follow-up text, submit with Return or the send button, insert newlines with Shift-Return, collapse with Escape, and keep the cursor from moving while the draft is active.+- With multiple spawned cursors visible, clicking a cursor selects it; holding Command speaks to the selected/latest cursor, pauses movement during recording, shows transcription in that cursor's input, and resumes by submitting the transcript as a follow-up.- Open requests for installed apps, files, and folders launch or open the local item; missing local items show a not-found result and log the lookup provider/reason.- LLM-classified instructional prompts complete as chat/coaching turns and show the animated cursor with typed labels without moving the real pointer.- The prompt supports wrapping, Shift-Return newline insertion, Return submission, Escape dismissal, outside-click dismissal, and dragging from non-input areas.