Skip to content

Open source CapCut alternative.

TypeScript

feat(app): notch reply mode, full-width titles, run-duration timing

David Lefbb300894154
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift
index 5aa3c181..9bb47dd4 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift
@@ -38,6 +38,9 @@ final class UserQueryOverlayController {
private var spawnDesktopEmergeWorkItems: [String: DispatchWorkItem] = [:]
private var hasPrewarmedInputPanel = false
private var lastStatusViewSnapshot: StatusPanelViewSnapshot?
+ /// Memoizes the measured chin-band height by (chin text + width) so the per-frame `notchMetrics()`
+ /// doesn't redo Core Text layout when the surfaced chin text hasn't changed.
+ private var chinHeightCache: (key: String, height: CGFloat)?
init(
model: UserQueryOverlayModel,
@@ -472,9 +475,12 @@ final class UserQueryOverlayController {
}
activateVoiceInputIfNeeded()
- positionStatusPanel()
+ // Build the notch metrics once per frame (the chin sizing does Core Text measurement) and feed
+ // both the panel position and the view update from it, instead of recomputing it for each.
+ let metrics = notchMetrics()
+ positionStatusPanel(metrics: metrics)
updateStatusHoverExpansion()
- updateStatusPanelView()
+ updateStatusPanelView(metrics: metrics)
updateSpawnOverlay()
resizeActivePanelIfNeeded(inputPanel)
updateMouseEventPassthrough(for: inputPanel)
@@ -502,13 +508,13 @@ final class UserQueryOverlayController {
)
}
- private func positionStatusPanel(disableAnimations: Bool = true) {
+ private func positionStatusPanel(metrics: NotchMetrics? = nil, disableAnimations: Bool = true) {
guard let statusPanel,
let screen = activeScreen() else {
return
}
- let metrics = notchMetrics(for: screen)
+ let metrics = metrics ?? notchMetrics(for: screen)
let frame = CGRect(
x: screen.frame.midX - metrics.surfaceSize.width / 2,
y: screen.frame.maxY - metrics.surfaceSize.height,
@@ -537,14 +543,14 @@ final class UserQueryOverlayController {
}
}
- private func updateStatusPanelView() {
- let metrics = notchMetrics()
+ private func updateStatusPanelView(metrics: NotchMetrics? = nil) {
+ let metrics = metrics ?? notchMetrics()
let snapshot = statusViewSnapshot(metrics: metrics)
let previousSnapshot = lastStatusViewSnapshot
guard snapshot != previousSnapshot else { return }
if snapshot.surfaceSize != previousSnapshot?.surfaceSize {
- positionStatusPanel()
+ positionStatusPanel(metrics: metrics)
}
lastStatusViewSnapshot = snapshot
@@ -581,7 +587,9 @@ final class UserQueryOverlayController {
accentIndex: model.notchAccentIndex,
spawnState: spawnCue,
spawnStates: model.spawnStates,
- selectedSpawnID: model.selectedSpawnID
+ selectedSpawnID: model.selectedSpawnID,
+ replyTargetTaskID: model.replyTargetTaskID,
+ needsLogin: model.needsLogin
)
}
@@ -608,6 +616,7 @@ final class UserQueryOverlayController {
isCommandInputExpanded: model.isNotchCommandInputExpanded,
tasks: model.notchTasks,
surfacedTasks: model.notchSurfacedTasks,
+ replyTargetTaskID: model.replyTargetTaskID,
accentIndex: model.notchAccentIndex,
spawnState: spawnCue,
commandSubmitted: { [weak self] text in
@@ -634,6 +643,14 @@ final class UserQueryOverlayController {
taskSelected: { [weak self] taskID in
self?.restoreSpawnPointer(forTaskID: taskID)
},
+ replyRequested: { [weak self] taskID in
+ guard let self else { return }
+ self.model.beginReply(toTaskID: taskID)
+ self.focusStatusComposerTextInputIfAvailable()
+ },
+ replyModeExited: { [weak self] in
+ self?.model.cancelReply()
+ },
approvePermissionRequested: { [weak self] taskID, alwaysAllow in
self?.model.approvePermissionGate(id: taskID, alwaysAllow: alwaysAllow)
},
@@ -642,6 +659,10 @@ final class UserQueryOverlayController {
},
updateRequested: { [weak self] in
self?.openAvailableUpdate()
+ },
+ needsLogin: model.needsLogin,
+ loginRequested: { [weak self] in
+ self?.model.requestLogin()
}
)
}
@@ -778,8 +799,9 @@ final class UserQueryOverlayController {
statusHoverPhase = .expanded
isStatusHostExpanded = true
isStatusExpanded = true
- // Opening the notch dismisses the completed pointers piled up in the collapsed surface.
- model.acknowledgeSurfacedCompletions()
+ // Opening the notch dismisses the surfaced terminal tasks (completed pointers and any held
+ // error chin) piled up in the collapsed surface.
+ model.acknowledgeSurfacedTasks()
updateStatusPanelView()
focusStatusComposerTextInputIfAvailable()
return
@@ -889,7 +911,8 @@ final class UserQueryOverlayController {
expandedContentHeight: statusExpandedContentHeight,
isExpanded: isStatusExpanded,
isHostExpanded: isStatusHostExpanded,
- screenWidth: NotchMetrics.defaultScreenWidth
+ screenWidth: NotchMetrics.defaultScreenWidth,
+ needsLogin: model.needsLogin
)
}
@@ -908,26 +931,86 @@ final class UserQueryOverlayController {
let voidHeight = hasNotch ? max(safeTop, NotchMetrics.fallbackVoidHeight) : 0
let voidWidth = hasNotch ? max(measuredVoidWidth, inferredVoidWidth(for: screen, safeTop: safeTop)) : 0
- return NotchMetrics(
+ // The chin band has to know its height before the surface frame is built, but that height
+ // depends on the collapsed width (how wide the chin text can wrap). Resolve the width from a
+ // zero-chin probe first, then size the band to the surfaced tasks' wrapped line count.
+ let widthProbe = NotchMetrics(
voidWidth: voidWidth,
voidHeight: voidHeight,
expandedContentHeight: statusExpandedContentHeight,
isExpanded: isStatusExpanded,
isHostExpanded: isStatusHostExpanded,
screenWidth: screen.frame.width,
- chinHeight: statusChinHeight
+ chinHeight: 0,
+ needsLogin: model.needsLogin
)
- }
+ let chinTextWidth = widthProbe.layout.collapsedSurfaceFrame.width - Self.statusChinHorizontalInset
- /// The collapsed chin hangs below the notch whenever a task is surfaced — running, or a completion
- /// the user hasn't dismissed yet. The notch view rotates which one's line it shows. Real notch only.
- private var statusChinHeight: CGFloat {
- model.notchSurfacedTasks.isEmpty ? 0 : Self.statusChinBandHeight
+ return NotchMetrics(
+ voidWidth: voidWidth,
+ voidHeight: voidHeight,
+ expandedContentHeight: statusExpandedContentHeight,
+ isExpanded: isStatusExpanded,
+ isHostExpanded: isStatusHostExpanded,
+ screenWidth: screen.frame.width,
+ chinHeight: statusChinHeight(textWidth: chinTextWidth),
+ needsLogin: model.needsLogin
+ )
}
- private static let statusChinBandHeight: CGFloat = 20
+ /// The collapsed chin hangs below the notch whenever a task is surfaced — running, a completion, or
+ /// a failure the user hasn't dismissed yet. The notch view rotates which one's line it shows. The
+ /// band fits one line by default and grows by a line-height to seat a wrapped second line (capped
+ /// there), keeping the bottom margin constant. Real notch only.
+ private func statusChinHeight(textWidth: CGFloat) -> CGFloat {
+ let surfaced = model.notchSurfacedTasks
+ guard !surfaced.isEmpty else { return 0 }
+ // Cache by the surfaced chin text + width: `notchMetrics()` runs every frame, but the wrapped-line
+ // Core Text measurement only needs to rerun when the text or available width actually changes.
+ let key = "\(Int(textWidth))|" + surfaced.map(\.chinDisplayText).joined(separator: "\u{1}")
+ if let cache = chinHeightCache, cache.key == key { return cache.height }
+ let lines = surfaced.reduce(1) { partial, task in
+ return max(partial, Self.chinLineCount(for: task.chinDisplayText, width: textWidth))
+ }
+ let height = CGFloat(lines) * Self.statusChinLineHeight + Self.statusChinBottomMargin
+ chinHeightCache = (key, height)
+ return height
+ }
+
+ /// Approximate how many lines (1 or 2) the chin text wraps to at `width`, by comparing its wrapped
+ /// height to a single line's height in the chin font. Used to grow the band for a second line.
+ private static func chinLineCount(for text: String, width: CGFloat) -> Int {
+ guard width > 0, !text.isEmpty, chinFontLineHeight > 0 else { return 1 }
+ let wrappedHeight = (text as NSString).boundingRect(
+ with: CGSize(width: width, height: .greatestFiniteMagnitude),
+ options: [.usesLineFragmentOrigin, .usesFontLeading],
+ attributes: [.font: NSFont.systemFont(ofSize: statusChinFontSize)]
+ ).height
+ let lines = Int((wrappedHeight / chinFontLineHeight).rounded())
+ return min(2, max(1, lines))
+ }
+
+ /// A single line's height in the chin font — constant, so measure it once instead of per call.
+ private static let chinFontLineHeight: CGFloat = ("Ag" as NSString).boundingRect(
+ with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
+ options: [.usesLineFragmentOrigin, .usesFontLeading],
+ attributes: [.font: NSFont.systemFont(ofSize: statusChinFontSize)]
+ ).height
+
+ /// Chin band geometry, mirroring the prototype: a `statusChinFontSize` line on a `…LineHeight`
+ /// leading, with a constant `…BottomMargin` below the last line. One line totals 23pt (15 + 8);
+ /// a second line adds another 15pt. `…HorizontalInset` is the chin's total left+right text inset.
+ private static let statusChinFontSize: CGFloat = 12
+ private static let statusChinLineHeight: CGFloat = 15
+ private static let statusChinBottomMargin: CGFloat = 8
+ private static let statusChinHorizontalInset: CGFloat = 24
private var statusExpandedContentHeight: CGFloat {
+ // Logged out: the expanded login is a short wide bar (label + Login button), not the full panel.
+ if model.needsLogin {
+ return NotchMetrics.loginExpandedContentHeight
+ }
+
if hasStatusTaskDisplayText || !model.notchTasks.isEmpty || model.updateState.headerButtonTitle != nil {
return NotchMetrics.expandedTaskContentHeight
}
@@ -1377,6 +1460,8 @@ private struct StatusPanelViewSnapshot: Equatable {
var spawnState: UserQuerySpawnState?
var spawnStates: [UserQuerySpawnState]
var selectedSpawnID: String?
+ var replyTargetTaskID: String?
+ var needsLogin: Bool
}
private enum StatusHoverPhase {
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
index 626835b7..bad85aa0 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
@@ -20,12 +20,22 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
@Published private(set) var notchTasks: [UserQueryNotchTask]
@Published private(set) var spawnStates: [UserQuerySpawnState] = []
@Published private(set) var selectedSpawnID: String?
+ /// Logged out: the notch renders a login call-to-action instead of the task surface. The app
+ /// delegate pushes this from the auth coordinator's session state (true while signed out after a
+ /// prior sign-in, i.e. an expired session) and clears it once sign-in completes.
+ @Published private(set) var needsLogin = false
var agentVisualizationPresenter: ((PointerCoachCursorGuideRequest, String?) -> Void)?
+ /// Fired when the notch Login button is tapped, so the app delegate can start the real sign-in
+ /// (the Google browser flow). The model never opens browsers or windows itself.
+ var loginActionRequested: (() -> Void)?
+ /// Fired when a hosted request fails authentication mid-run (an expired session). The app delegate
+ /// wires this to sign out, which flips the notch into login mode while the running tasks stay put.
+ var sessionExpired: (() -> Void)?
/// Fired when the Live session's optional audio streaming should start/stop,
/// so the mic owner can keep the engine running continuously.
var onLiveAudioStreamingChanged: ((Bool) -> Void)?
- private let commandHandler: any UserQueryCommandHandling
+ private var commandHandler: any UserQueryCommandHandling
private let taskStore: any UserQueryTaskStoring
private let followUpResolver: any UserQueryFollowUpResolving
private let voiceTranscriber: LocalVoiceTranscriptionAdapter
@@ -37,10 +47,26 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
/// The resume is deferred here and fired by `handleCommandRunResult` once that loop ends, so two loops
/// never run on one task and the tap is never silently dropped.
private var pendingResumeTaskIDs: Set<String> = []
- /// Completed tasks the user has already seen surfaced in the collapsed notch. Expanding the notch
- /// acknowledges them so their colored pointers stop floating in the collapsed surface; the tasks
- /// themselves stay in the expanded list until closed.
- private var acknowledgedCompletionIDs: Set<String> = []
+ /// The task an explicit Reply tap pinned the next submission to (a task waiting on the user — a
+ /// clarification or review). It routes the answer straight to that task instead of leaving the
+ /// follow-up resolver to guess, and the expanded panel dims every other row while it is set so the
+ /// user sees which thread their reply continues. Consumed by the next submission.
+ @Published private(set) var replyTargetTaskID: String?
+ /// Metadata flag marking a terminal task (completed or failed) as seen — set when the user expands
+ /// the notch. It lives on the task (and so is persisted through the task store) rather than in memory,
+ /// so an acknowledged failure stays dismissed across relaunches instead of re-surfacing every launch.
+ private static let seenMetadataKey = "notch.seen"
+
+ /// Clear the per-run metadata flags a task carries into a fresh running run: the "seen" dismissal (so
+ /// its next terminal state re-surfaces in the collapsed notch) and the streaming-answer flag (so a
+ /// streamed reply on the new run replaces the previous answer instead of appending to it). Applied at
+ /// every stopped→running transition — both the in-place resume (`updateTask`) and the matched-resume
+ /// seed (`taskForSubmittedCommand`), which bypasses `updateTask`.
+ private static func clearRunMetadata(_ metadata: inout [String: String]) {
+ metadata[seenMetadataKey] = nil
+ metadata[UserQueryNotchTask.streamingAnswerMetadataKey] = nil
+ }
+
private var lastActiveTaskID: String?
/// The task/spawn the in-flight Gemini Live turn reports into, so the user
/// sees the same cursor-and-task feedback as a local pipeline run.
@@ -100,6 +126,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
appCatalogRefreshLoop.start()
checkForUpdates()
startLiveSessionIfEnabled()
+ // A mid-run 401 from the hosted backend means the session expired: surface login (the app
+ // delegate wires `sessionExpired` to the auth coordinator) while the running tasks stay put.
+ self.commandHandler.onAuthenticationRequired = { [weak self] in
+ self?.handleSessionExpired()
+ }
autoResumeInterruptedTasks(restoration.autoResumeIDs)
}
@@ -108,6 +139,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
/// the cursor; progress narrates into the task's own row. Fires once, at launch.
private func autoResumeInterruptedTasks(_ taskIDs: [String]) {
guard !taskIDs.isEmpty else { return }
+ // Don't drive the harness while signed out — every planner step would 401. The interrupted
+ // tasks stay retryable and resume on the next launch (or manual retry) once signed in.
+ guard BackendSessionGate.shared.isAuthenticated else { return }
for taskID in taskIDs {
guard let context = commandContext(taskID: taskID, isFollowUp: false, source: .followUp, spawnID: nil) else {
continue
@@ -135,7 +169,10 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
/// and only becomes `isConnected` if it can authenticate, so when it is not
/// configured the existing command pipeline is used unchanged.
private func startLiveSessionIfEnabled() {
- guard liveController.isEnabled else { return }
+ // Self-gates on configuration AND on being signed in: the session mints a backend token to
+ // connect, which 401s while logged out. The app delegate calls `resumeLiveSession()` once the
+ // session is restored, so the always-on session comes back without a relaunch.
+ guard liveController.isEnabled, BackendSessionGate.shared.isAuthenticated else { return }
liveController.onComplexRequest = { [weak self] goal in
// The model explicitly delegated via agent_run: close out the Live
// turn and run the goal through the full local pipeline (never back
@@ -174,6 +211,19 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
Task { [liveController] in await liveController.start() }
}
+ /// Tear down the always-on Live session when the session signs out. The app delegate drives this
+ /// from the auth phase so a logged-out app stops reconnecting (each reconnect re-mints a token and
+ /// 401s). Paired with `resumeLiveSession()` on sign-in.
+ func suspendLiveSession() {
+ Task { [liveController] in await liveController.stop() }
+ }
+
+ /// Bring the Live session back after sign-in. `start()` self-guards on an existing session, so a
+ /// redundant call is a no-op.
+ func resumeLiveSession() {
+ startLiveSessionIfEnabled()
+ }
+
/// Stream optional microphone audio into the Live session (no-op unless audio
/// is enabled and the session is connected).
func streamLiveAudioFrames(_ samples: [Float], sampleRate: Double) {
@@ -205,6 +255,25 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
updateChecker.showUpdateUI()
}
+ /// Push the logged-out state into the notch. The app delegate drives this from the auth
+ /// coordinator's session phase.
+ func updateNeedsLogin(_ value: Bool) {
+ guard needsLogin != value else { return }
+ needsLogin = value
+ }
+
+ /// The notch Login button was tapped; hand off to the app delegate to start the sign-in flow.
+ func requestLogin() {
+ loginActionRequested?()
+ }
+
+ /// A hosted request returned 401 mid-run. Surface login once — ignored if already logged out, so a
+ /// burst of retrying calls doesn't re-fire — and let the app delegate sign out.
+ func handleSessionExpired() {
+ guard !needsLogin else { return }
+ sessionExpired?()
+ }
+
func handle(_ intent: UserQueryIntent) {
switch intent {
case .addContextRequested:
@@ -386,6 +455,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
private func runLocalCommand(_ text: String, source: AppHarnessTurnSource = .typedPrompt) {
let candidates = followUpCandidates()
let promptFollowUpTarget = promptSubmissionFollowUpTarget()
+ let replyTargetTaskID = consumePendingReplyTarget()
let spawnID: String?
if let promptFollowUpTarget {
updateSpawn(
@@ -408,7 +478,10 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
let confidenceThreshold = Self.followUpMatchConfidenceThreshold
Task { [weak self, followUpResolver] in
let matchedTaskID: String?
- if let taskID = promptFollowUpTarget?.taskID {
+ if let replyTargetTaskID {
+ // An explicit Reply pins the answer to that task — never re-routed by the resolver.
+ matchedTaskID = replyTargetTaskID
+ } else if let taskID = promptFollowUpTarget?.taskID {
matchedTaskID = taskID
} else if candidates.isEmpty {
matchedTaskID = nil
@@ -645,6 +718,44 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
}
}
+ /// The user tapped Reply on a task that is waiting on them (a clarification or a review). Pin the
+ /// next composer submission to that task so the answer continues it rather than starting a new task
+ /// or being matched elsewhere by the resolver; the controller focuses the input after this.
+ func beginReply(toTaskID taskID: String) {
+ // Any existing thread is repliable, whatever its state — running/permission-gated threads take
+ // the message as a queued follow-up downstream, the rest resume.
+ guard task(withID: taskID) != nil else {
+ return
+ }
+ // Tapping Reply on the row already targeted cancels reply mode and un-dims the other rows, so the
+ // user is never stuck in a dimmed state with no way back out short of sending a message.
+ if replyTargetTaskID == taskID {
+ replyTargetTaskID = nil
+ return
+ }
+ replyTargetTaskID = taskID
+ lastActiveTaskID = taskID
+ }
+
+ /// Leave reply mode without sending — the user tapped elsewhere in the notch chrome. No-op when no
+ /// reply is targeted, so a stray background tap in normal use does nothing.
+ func cancelReply() {
+ guard replyTargetTaskID != nil else { return }
+ replyTargetTaskID = nil
+ }
+
+ /// Take the pinned Reply target, if any, for the submission about to run. Cleared on read so it only
+ /// applies to the one answer (which also un-dims the rows), and dropped if the task is no longer
+ /// around (fall back to normal routing).
+ private func consumePendingReplyTarget() -> String? {
+ guard let taskID = replyTargetTaskID else { return nil }
+ replyTargetTaskID = nil
+ // Drop the pin only if the task vanished between the tap and the submit (e.g. it was closed);
+ // otherwise the message is pinned to it whatever its current state (`startCommandRun` routes a
+ // running/permission-gated target into a queued follow-up, a stopped/terminal one resumes).
+ return task(withID: taskID) != nil ? taskID : nil
+ }
+
func pauseTask(id taskID: String) {
guard task(withID: taskID)?.status == .running else { return }
@@ -701,22 +812,35 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
}
/// The tasks the collapsed notch keeps surfaced as floating pointers: anything running, plus
- /// completed tasks the user hasn't dismissed yet by expanding the notch.
+ /// terminal tasks (completed or failed) the user hasn't dismissed yet by expanding the notch. A
+ /// failure — like an auth error — holds the chin until acknowledged just as a completion does.
var notchSurfacedTasks: [UserQueryNotchTask] {
notchTasks.filter { task in
task.status == .running ||
- (task.status == .completed && !acknowledgedCompletionIDs.contains(task.id))
+ (Self.isSurfacedTerminalStatus(task.status) && !Self.isSeen(task))
}
}
- /// Marks every currently-completed task as seen so it stops surfacing in the collapsed notch.
- /// Called when the notch expands — the user is now looking at the full list.
- func acknowledgeSurfacedCompletions() {
- for task in notchTasks where task.status == .completed {
- acknowledgedCompletionIDs.insert(task.id)
+ /// Marks every currently-terminal task (completed or failed) as seen so it stops surfacing in the
+ /// collapsed notch. Called when the notch expands — the user is now looking at the full list. The
+ /// flag is written to the task store, so the dismissal sticks across relaunches.
+ func acknowledgeSurfacedTasks() {
+ for index in notchTasks.indices where Self.isSurfacedTerminalStatus(notchTasks[index].status) && !Self.isSeen(notchTasks[index]) {
+ var task = notchTasks[index]
+ task.metadata[Self.seenMetadataKey] = "true"
+ notchTasks[index] = task
+ taskStore.upsertTask(task)
}
}
+ private static func isSurfacedTerminalStatus(_ status: UserQueryTaskStatus) -> Bool {
+ status == .completed || status == .failed
+ }
+
+ private static func isSeen(_ task: UserQueryNotchTask) -> Bool {
+ task.metadata[seenMetadataKey] == "true"
+ }
+
/// Closes a task: removes it from the notch list and tears down its pointer.
/// Offered only for stopped (paused/interrupted/failed) and completed tasks —
/// the same affordance the prototype calls "close".
@@ -726,6 +850,10 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
notchTasks.removeAll { $0.id == taskID }
activeTaskIDs.remove(taskID)
+ // Closing the targeted task ends reply mode so the remaining rows don't stay dimmed.
+ if replyTargetTaskID == taskID {
+ replyTargetTaskID = nil
+ }
if lastActiveTaskID == taskID {
lastActiveTaskID = notchTasks.first?.id
}
@@ -1077,6 +1205,14 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
task.detail = Self.runningSeedDetail
task.status = .running
task.updatedAt = Date()
+ // Restamp the run-start: a resumed run's elapsed time should measure this run, not the idle
+ // gap since the task was first created (e.g. a task that failed, sat for hours, then resumed).
+ task.createdAt = Date()
+ // This branch seeds the task straight to running without going through `updateTask`, so it
+ // must apply the same fresh-run metadata reset (see `clearRunMetadata`): otherwise a replied-to
+ // thread keeps its stale "seen" (its next terminal state never re-surfaces) and "streaming
+ // answer" flag (the new streamed reply appends onto the old answer).
+ Self.clearRunMetadata(&task.metadata)
notchAccentIndex = UserQueryAccentPalette.normalizedIndex(task.accentIndex)
prependTask(task)
return task
@@ -1169,6 +1305,13 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
return { [weak self] update in
guard let self else { return }
+ // A streamed answer chunk accumulates onto the task's detail (the chin and the open row both
+ // read it), so the reply types itself out. It bypasses the label path below, which replaces.
+ if let answerDelta = update.answerDelta {
+ self.appendStreamedAnswer(taskID: taskID, delta: answerDelta, spawnID: spawnID)
+ return
+ }
+
let label = update.label?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if !label.isEmpty, self.task(withID: taskID)?.status == .running {
self.updateTask(id: taskID, detail: label)
@@ -1184,6 +1327,22 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
}
}
+ /// Append one streamed chunk of the assistant's final reply to the running task's detail. The first
+ /// chunk clears the per-step "Thinking" status and flips the streaming flag so the chin shows the
+ /// growing answer instead of the prompt; later chunks accumulate onto it. No-op once the task has
+ /// left the running state (a late chunk after completion must not reopen the row's status line).
+ private func appendStreamedAnswer(taskID: String, delta: String, spawnID: String?) {
+ guard let task = task(withID: taskID), task.status == .running else { return }
+ let isStreaming = task.metadata[UserQueryNotchTask.streamingAnswerMetadataKey] == "true"
+ let newDetail = isStreaming ? task.detail + delta : delta
+ var metadata = task.metadata
+ metadata[UserQueryNotchTask.streamingAnswerMetadataKey] = "true"
+ updateTask(id: taskID, detail: newDetail, metadata: metadata)
+ if let spawnID {
+ updateSpawn(id: spawnID, label: newDetail)
+ }
+ }
+
private func agentVisualizationHandler(
for spawnID: String?
) -> (@MainActor @Sendable (AgentVisualizationPlan) -> Void)? {
@@ -1276,6 +1435,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
guard let index = notchTasks.firstIndex(where: { $0.id == id }) else { return }
var task = notchTasks[index]
+ let wasRunning = task.status == .running
if let title {
task.title = title
}
@@ -1288,6 +1448,14 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
if let metadata {
task.metadata = metadata
}
+ // A stopped task re-entering running begins a fresh run: clear the per-run metadata flags and
+ // restamp the run-start so elapsed measures this run, not the idle gap before it. Gated on the
+ // prior status so the planner's per-step "still running" updates (and streamed-answer deltas,
+ // which re-pass the streaming flag) don't keep resetting it mid-run.
+ if status == .running, !wasRunning {
+ Self.clearRunMetadata(&task.metadata)
+ task.createdAt = Date()
+ }
task.updatedAt = Date()
notchTasks[index] = task
taskStore.upsertTask(task)
@@ -1323,11 +1491,13 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
timedOut.detail = "Timed out — resume"
return timedOut
case .waitingForClarification, .waitingForReview, .waitingForPermission:
- // Was blocked on the user; the loop that asked is gone. Surface a benign, resumable row
- // (it needs the user to continue anyway) without raising the collapsed attention glyph.
+ // Was blocked on the user; the loop that asked is gone. It comes back simply paused —
+ // a clean resumable/repliable row, not an "interrupted" one, since whether the app was
+ // restarted is irrelevant to the user. Paused also stays out of the collapsed attention
+ // glyph.
var restoredTask = task
- restoredTask.status = .needsAttention
- restoredTask.detail = "Interrupted"
+ restoredTask.status = .paused
+ restoredTask.detail = "Paused"
return restoredTask
default:
// paused, completed, failed, timedOut, interrupted, needsAttention, chatting: unchanged.
@@ -1418,15 +1588,14 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
/// by step as `runProgressHandler` streams the planner's narration in.
private static let runningSeedDetail = UserQueryActivity.Kind.working.label
+ /// The task's title is the user's prompt, whitespace-collapsed. It is NOT hard-truncated here: every
+ /// place that shows it (the collapsed bar, the prompt pill, each expanded row) renders it on a single
+ /// line and tail-truncates to its own available width, so the expanded row title spans the full row
+ /// rather than being clipped to a fixed character budget. Capped only by `collapsedDisplayText` so a
+ /// runaway prompt can't blob through the store.
private static func taskLabel(for text: String) -> String {
let collapsed = collapsedDisplayText(for: text)
- guard !collapsed.isEmpty else { return "New task" }
-
- let maxLength = 44
- guard collapsed.count > maxLength else { return collapsed }
-
- let endIndex = collapsed.index(collapsed.startIndex, offsetBy: maxLength)
- return String(collapsed[..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines) + "..."
+ return collapsed.isEmpty ? "New task" : collapsed
}
/// A cursor label stays a short status line; cap it so a long tool result never blobs over the
diff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swift
index 3326d90d..35c3a02a 100644
--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryNotchLayout.swift
@@ -19,6 +19,8 @@ public struct UserQueryNotchLayout: Equatable, Sendable {
/// Height of the chin band that hangs below the collapsed notch row while a task streams
/// (0 when there is nothing to stream). The notch row itself stays `collapsedVisibleHeight`.
public var chinHeight: CGFloat
+ /// Logged out: render the login call-to-action instead of the task surface.
+ public var needsLogin: Bool
public init(
voidWidth: CGFloat,
@@ -33,7 +35,8 @@ public struct UserQueryNotchLayout: Equatable, Sendable {
collapsedCornerRadius: CGFloat,
expandedCornerRadius: CGFloat,
canRenderTextInTopRow: Bool,
- chinHeight: CGFloat = 0
+ chinHeight: CGFloat = 0,
+ needsLogin: Bool = false
) {
self.voidWidth = voidWidth
self.voidHeight = voidHeight
@@ -48,6 +51,7 @@ public struct UserQueryNotchLayout: Equatable, Sendable {
self.expandedCornerRadius = expandedCornerRadius
self.canRenderTextInTopRow = canRenderTextInTopRow
self.chinHeight = chinHeight
+ self.needsLogin = needsLogin
}
public var shouldRenderExpandedTopRowVoidMarker: Bool {
@@ -81,6 +85,17 @@ public struct UserQueryNotchMetrics: Equatable, Sendable {
public var screenWidth: CGFloat
/// Chin band below the collapsed notch row while a task streams (0 otherwise).
public var chinHeight: CGFloat
+ /// Logged out: render the login call-to-action instead of the task surface. Collapsed shows just
+ /// the "Login to use Donkey" line; expanding reveals a wide, short bar with the Login button.
+ public var needsLogin: Bool
+
+ /// Height of the short collapsed login band that seats the "Login to use Donkey" line below the
+ /// void on a real notch. No-notch displays render the line inline in the top row.
+ public static let loginCollapsedBandHeight: CGFloat = 22
+
+ /// Expanded login content height: a short bar holding the label + Login button, not the full task
+ /// panel. The expanded surface adds the void top inset on top of this.
+ public static let loginExpandedContentHeight: CGFloat = 52
public init(
voidWidth: CGFloat,
@@ -89,7 +104,8 @@ public struct UserQueryNotchMetrics: Equatable, Sendable {
isExpanded: Bool,
isHostExpanded: Bool,
screenWidth: CGFloat,
- chinHeight: CGFloat = 0
+ chinHeight: CGFloat = 0,
+ needsLogin: Bool = false
) {
self.voidWidth = voidWidth
self.voidHeight = voidHeight
@@ -98,6 +114,7 @@ public struct UserQueryNotchMetrics: Equatable, Sendable {
self.isHostExpanded = isHostExpanded
self.screenWidth = screenWidth
self.chinHeight = chinHeight
+ self.needsLogin = needsLogin
}
public var surfaceSize: CGSize {
@@ -131,7 +148,8 @@ public struct UserQueryNotchMetrics: Equatable, Sendable {
collapsedCornerRadius: Self.collapsedCornerRadius,
expandedCornerRadius: Self.expandedCornerRadius,
canRenderTextInTopRow: canRenderTextInTopRow,
- chinHeight: effectiveChinHeight
+ chinHeight: effectiveChinHeight,
+ needsLogin: needsLogin
)
}
@@ -176,10 +194,17 @@ public struct UserQueryNotchMetrics: Equatable, Sendable {
x: 0,
y: 0,
width: collapsedSurfaceWidth,
- height: collapsedVisibleHeight + effectiveChinHeight
+ height: collapsedVisibleHeight + collapsedExtraHeight
)
}
+ /// The band below the collapsed notch row: the login call-to-action when logged out (real notch
+ /// only — no-notch displays render it inline), otherwise the streaming chin.
+ private var collapsedExtraHeight: CGFloat {
+ guard needsLogin else { return effectiveChinHeight }
+ return canRenderTextInTopRow ? 0 : Self.loginCollapsedBandHeight
+ }
+
private var expandedContentFrame: CGRect {
CGRect(
x: Self.expandedContentDesignFrame.minX,
@@ -190,6 +215,7 @@ public struct UserQueryNotchMetrics: Equatable, Sendable {
}
private var collapsedSurfaceWidth: CGFloat {
+ // Logged out keeps the normal collapsed width — the bar just reads "Login to use Donkey".
min(
Self.expandedContentDesignFrame.width,
max(
diff --git a/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swift
index 27830718..40df8d25 100644
--- a/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/UserQuerySpawnContracts.swift
@@ -76,15 +76,22 @@ public struct UserQuerySpawnProgressUpdate: Equatable, Sendable {
public var label: String?
public var targetHint: UserQuerySpawnTargetHint?
public var phase: UserQuerySpawnPhase?
+ /// One token-chunk of the assistant's final reply, streamed as it is generated. When set, the
+ /// model appends it to the running task's detail (the chin and the open row read that), so the
+ /// answer types itself out instead of popping in whole. A normal `label` update replaces the status
+ /// line; an `answerDelta` accumulates onto it.
+ public var answerDelta: String?
public init(
label: String? = nil,
targetHint: UserQuerySpawnTargetHint? = nil,
- phase: UserQuerySpawnPhase? = nil
+ phase: UserQuerySpawnPhase? = nil,
+ answerDelta: String? = nil
) {
self.label = label
self.targetHint = targetHint
self.phase = phase
+ self.answerDelta = answerDelta
}
}
diff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swift
index 005b66a5..cdb8825f 100644
--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryTaskContracts.swift
@@ -14,6 +14,16 @@ public enum UserQueryTaskStatus: String, Codable, Equatable, Sendable {
case timedOut
}
+public extension UserQueryTaskStatus {
+ /// The agent is blocked asking the user to respond (a clarification or a review). These are the only
+ /// states that surface a dedicated Reply button, since only here is the agent actively asking. Every
+ /// state is repliable by tapping the row (a running/permission-gated thread takes the reply as a
+ /// queued follow-up, the rest resume), so there is no separate "repliable" predicate — only this.
+ var isAwaitingUserResponse: Bool {
+ self == .waitingForClarification || self == .waitingForReview
+ }
+}
+
public struct UserQueryNotchTask: Codable, Equatable, Identifiable, Sendable {
public var id: String
public var title: String
@@ -48,6 +58,30 @@ public struct UserQueryNotchTask: Codable, Equatable, Identifiable, Sendable {
}
}
+public extension UserQueryNotchTask {
+ /// Metadata flag set while the assistant's final reply is streaming in token-by-token, so the chin
+ /// switches from echoing the prompt to showing the growing answer even though the task is still
+ /// running. Cleared implicitly once the task reaches a terminal status (which shows `detail` anyway).
+ static let streamingAnswerMetadataKey = "notch.streamingAnswer"
+
+ /// The single line the collapsed chin shows for this task: the user's prompt while it runs, the
+ /// assistant's reply as it streams in (and once answered, its `detail`). The chin renderer and the
+ /// chin-band height measurement both read this, so the band is always sized to the exact line it
+ /// renders — a running task can't show a wrapped prompt inside a band measured for a shorter seed.
+ var chinDisplayText: String {
+ if status == .running {
+ // Once the reply starts streaming, show the growing answer instead of the prompt.
+ if metadata[Self.streamingAnswerMetadataKey] == "true",
+ !detail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return detail
+ }
+ let prompt = commandText.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !prompt.isEmpty { return prompt }
+ }
+ return detail.isEmpty ? title : detail
+ }
+}
+
public enum UserQueryTaskEventRole: String, Codable, Equatable, Sendable {
case user
case assistant
diff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift
index 5f4cdadc..6b505314 100644
--- a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift
+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift
@@ -28,6 +28,9 @@ public struct UserQueryNotchStatusView: View {
private let isCommandInputExpanded: Bool
private let tasks: [UserQueryNotchTask]
private let surfacedTasks: [UserQueryNotchTask]
+ /// While the user is replying to a specific task (tapped Reply), this is that task; the expanded
+ /// panel dims every other row so it's clear the next message continues this one thread.
+ private let replyTargetTaskID: String?
private let accentIndex: Int
private let spawnState: UserQuerySpawnState?
private let commandSubmitted: @MainActor (String) -> Void
@@ -38,11 +41,20 @@ public struct UserQueryNotchStatusView: View {
private let resumeRequested: @MainActor (String) -> Void
private let dismissRequested: @MainActor (String) -> Void
private let taskSelected: @MainActor (String) -> Void
+ /// A task waiting on the user (a clarification or review) offers Reply; tapping it pins the composer
+ /// to that task and focuses the input so the user's next message answers it.
+ private let replyRequested: @MainActor (String) -> Void
+ /// Tapping the notch chrome outside a row, control, or the composer while replying leaves reply mode.
+ private let replyModeExited: @MainActor () -> Void
/// (taskID, alwaysAllow). `alwaysAllow` persists a standing rule for the
/// command signature; it is only offered for non-highRisk shell consent.
private let approvePermissionRequested: @MainActor (String, Bool) -> Void
private let denyPermissionRequested: @MainActor (String) -> Void
private let updateRequested: @MainActor () -> Void
+ /// Logged out: the notch renders a login call-to-action instead of the task surface, and the
+ /// Login button fires this to start the real sign-in (handled by the model/controller).
+ private let needsLogin: Bool
+ private let loginRequested: @MainActor () -> Void
public init(
state: UserQueryState,
@@ -58,6 +70,7 @@ public struct UserQueryNotchStatusView: View {
isCommandInputExpanded: Bool,
tasks: [UserQueryNotchTask] = [],
surfacedTasks: [UserQueryNotchTask] = [],
+ replyTargetTaskID: String? = nil,
accentIndex: Int,
spawnState: UserQuerySpawnState? = nil,
commandSubmitted: @escaping @MainActor (String) -> Void,
@@ -68,9 +81,13 @@ public struct UserQueryNotchStatusView: View {
resumeRequested: @escaping @MainActor (String) -> Void,
dismissRequested: @escaping @MainActor (String) -> Void,
taskSelected: @escaping @MainActor (String) -> Void,
+ replyRequested: @escaping @MainActor (String) -> Void = { _ in },
+ replyModeExited: @escaping @MainActor () -> Void = {},
approvePermissionRequested: @escaping @MainActor (String, Bool) -> Void,
denyPermissionRequested: @escaping @MainActor (String) -> Void,
- updateRequested: @escaping @MainActor () -> Void
+ updateRequested: @escaping @MainActor () -> Void,
+ needsLogin: Bool = false,
+ loginRequested: @escaping @MainActor () -> Void = {}
) {
self.state = state
self.updateState = updateState
@@ -85,6 +102,7 @@ public struct UserQueryNotchStatusView: View {
self.isCommandInputExpanded = isCommandInputExpanded
self.tasks = tasks
self.surfacedTasks = surfacedTasks
+ self.replyTargetTaskID = replyTargetTaskID
self.accentIndex = accentIndex
self.spawnState = spawnState
self.commandSubmitted = commandSubmitted
@@ -95,9 +113,13 @@ public struct UserQueryNotchStatusView: View {
self.resumeRequested = resumeRequested
self.dismissRequested = dismissRequested
self.taskSelected = taskSelected
+ self.replyRequested = replyRequested
+ self.replyModeExited = replyModeExited
self.approvePermissionRequested = approvePermissionRequested
self.denyPermissionRequested = denyPermissionRequested
self.updateRequested = updateRequested
+ self.needsLogin = needsLogin
+ self.loginRequested = loginRequested
}
public var body: some View {
@@ -133,6 +155,17 @@ public struct UserQueryNotchStatusView: View {
ZStack(alignment: .top) {
Color.black
+ // While replying, a tap on bare chrome (not a row, control, or the composer — those sit above
+ // this layer and take their own taps first) leaves reply mode. Only present while targeted, so
+ // it never interferes with normal taps.
+ if replyTargetTaskID != nil {
+ Rectangle()
+ .fill(Color.white.opacity(0.001))
+ .contentShape(Rectangle())
+ .onTapGesture { replyModeExited() }
+ .accessibilityHidden(true)
+ }
+
collapsedContentLayer
// The collapsed chrome fades out as the notch grows open and fades back in as it
// collapses, so it cross-dissolves with the expanded content rather than popping.
@@ -146,7 +179,7 @@ public struct UserQueryNotchStatusView: View {
value: surfaceIsOpen
)
- if !hasTaskDisplayText {
+ if !hasTaskDisplayText && !needsLogin {
expandedNotchArrow
.opacity(surfaceIsOpen ? 1 : 0)
.animation(
@@ -176,13 +209,76 @@ public struct UserQueryNotchStatusView: View {
@ViewBuilder
private var collapsedContentLayer: some View {
- if isResting {
+ if needsLogin {
+ loginCollapsedContent
+ } else if isResting {
restingCollapsedContent
} else {
regularCollapsedContent
}
}
+ /// Logged out, collapsed: the idle silhouette sits in the leading lane beside the void, and the
+ /// notch reads "Login to use Donkey". On a real notch the line sits in the band below the void;
+ /// a no-notch display renders the cursor and line inline in the top row. No button until expanded.
+ @ViewBuilder
+ private var loginCollapsedContent: some View {
+ let idleCursor = DonkeyCursorMark(color: accentColor, silhouette: true)
+ .frame(width: 14, height: 14)
+
+ if layout.canRenderTextInTopRow {
+ HStack(spacing: 7) {
+ idleCursor
+
+ Text(Self.loginHeadline)
+ .font(.system(size: 12, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.82))
+ .lineLimit(1)
+ .truncationMode(.tail)
+
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, max(10, layout.contentHorizontalInset))
+ .frame(width: collapsedSurfaceWidth, height: collapsedSurfaceHeight, alignment: .center)
+ } else {
+ let label = Text(Self.loginHeadline)
+ .font(.system(size: 12, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.82))
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 14)
+
+ ZStack(alignment: .top) {
+ idleCursor
+ .position(x: collapsedLeadingLaneCenterX, y: layout.collapsedVisibleHeight / 2)
+
+ VStack(spacing: 0) {
+ Spacer(minLength: 0).frame(height: layout.collapsedVisibleHeight)
+ label.frame(height: UserQueryNotchMetrics.loginCollapsedBandHeight)
+ }
+ }
+ .frame(width: collapsedSurfaceWidth, height: collapsedSurfaceHeight, alignment: .top)
+ }
+ }
+
+ /// The white Login pill, styled like the prototype's expanded login bar (and the Restart button).
+ private func loginButton() -> some View {
+ Button(action: loginRequested) {
+ Text("Login")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(Color.black.opacity(0.82))
+ .padding(.horizontal, 20)
+ .padding(.vertical, 8)
+ .background(Color.white)
+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Login")
+ }
+
+ private static let loginHeadline = "Login to use Donkey"
+
private var regularCollapsedContent: some View {
collapsedContent
.frame(width: collapsedSurfaceWidth, height: collapsedSurfaceHeight, alignment: .top)
@@ -200,6 +296,8 @@ public struct UserQueryNotchStatusView: View {
/// so the lane never crowds. With nothing surfaced it falls back to the idle silhouette.
@ViewBuilder
private func pointerCluster(size: CGFloat) -> some View {
+ // A failed task is a real task, so it keeps its own accent-colored pointer here (alongside the
+ // right-rail warning glyph and held chin); the lane only ever shows one pointer per surfaced task.
let cluster = Array(surfacedTasks.prefix(Self.maxClusterPointers))
if cluster.isEmpty {
DonkeyCursorMark(color: accentColor, silhouette: true)
@@ -308,13 +406,12 @@ public struct UserQueryNotchStatusView: View {
.position(x: collapsedTrailingLaneCenterX, y: layout.collapsedVisibleHeight / 2)
if layout.chinHeight > 0, let speaker {
- Text(speaker.detail.isEmpty ? speaker.title : speaker.detail)
- .font(.system(size: 13, weight: .regular))
- .foregroundStyle(Color.white.opacity(0.72))
- .lineLimit(1)
- .truncationMode(.tail)
+ chinLine(for: speaker)
.frame(width: max(0, collapsedSurfaceWidth - 24), alignment: .leading)
- .position(x: collapsedSurfaceWidth / 2, y: layout.collapsedVisibleHeight + layout.chinHeight / 2)
+ .position(
+ x: collapsedSurfaceWidth / 2,
+ y: layout.collapsedVisibleHeight + (layout.chinHeight - Self.chinBottomMargin) / 2
+ )
}
}
.frame(
@@ -325,11 +422,32 @@ public struct UserQueryNotchStatusView: View {
}
}
- /// The task currently surfaced in the chin. Running tasks (newest first) rotate round-robin; the
+ /// The chin line for a surfaced task. While the task runs it echoes what the user asked, so the
+ /// notch reads back the prompt rather than the planner's per-step narration. Once the agent answers,
+ /// the task's `detail` carries the reply (set to `result.summary` on completion), so the chin shows
+ /// the response. A failure is flagged by the red warning icon in the right rail (see
+ /// `collapsedRightSlot`), not inline here.
+ private func chinLine(for task: UserQueryNotchTask) -> some View {
+ Text(chinText(for: task))
+ .font(.system(size: Self.chinFontSize, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.72))
+ .lineLimit(2)
+ .truncationMode(.tail)
+ }
+
+ private func chinText(for task: UserQueryNotchTask) -> String {
+ task.chinDisplayText
+ }
+
+ /// The task currently surfaced in the chin. An unacknowledged failure outranks everything and holds
+ /// the chin until the user expands. Otherwise running tasks (newest first) rotate round-robin — the
/// clock is anchored to the newest task's start, so a freshly added task shows first (the view
/// re-renders on the task change) and then yields to the others. When nothing is running, the most
/// recent undismissed completion keeps narrating its result instead of leaving the chin empty.
private func rotatingChinTask(at date: Date) -> UserQueryNotchTask? {
+ if let errored = surfacedTasks.first(where: { $0.status == .failed }) {
+ return errored
+ }
let running = surfacedTasks.filter { $0.status == .running }
guard !running.isEmpty else {
return surfacedTasks.first { $0.status == .completed }
@@ -342,7 +460,9 @@ public struct UserQueryNotchStatusView: View {
private var expandedContent: some View {
Group {
- if hasTaskDisplayText {
+ if needsLogin {
+ loginExpandedContent
+ } else if hasTaskDisplayText {
expandedTaskContent
} else {
expandedCommandOnlyContent
@@ -359,6 +479,22 @@ public struct UserQueryNotchStatusView: View {
)
}
+ /// Logged out, expanded: a wide, short bar — the headline on the left, the Login pill on the right
+ /// (no task list, no command input). Mirrors the prototype's expanded login bar.
+ private var loginExpandedContent: some View {
+ HStack(spacing: 12) {
+ Text(Self.loginHeadline)
+ .font(.system(size: 16, weight: .regular))
+ .foregroundStyle(Color.white.opacity(0.92))
+
+ Spacer(minLength: 8)
+
+ loginButton()
+ }
+ .padding(.horizontal, 18)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
+ }
+
private var expandedTaskContent: some View {
VStack(spacing: 0) {
if updateState.headerButtonTitle != nil {
@@ -372,7 +508,11 @@ public struct UserQueryNotchStatusView: View {
currentTaskRow
} else {
ForEach(tasks) { task in
+ // While replying to one task, the others dim back (handled inside the row
+ // so an attention pointer can stay lit) — it's clear which thread the next
+ // message continues.
taskRow(task)
+ .animation(.easeOut(duration: 0.16), value: replyTargetTaskID)
}
}
}
@@ -598,14 +738,63 @@ public struct UserQueryNotchStatusView: View {
return parts.joined(separator: " ")
}
+ /// Trailing room a row's text leaves for the pinned top-right controls, by control set: a lone Close
+ /// (or Stop) button, or a Resume + Close pair. Permission rows carry their own banner controls.
+ private func controlsReserve(for task: UserQueryNotchTask) -> CGFloat {
+ if task.status == .waitingForPermission { return 0 }
+ return rowShowsControlPair(task) ? 74 : 44
+ }
+
+ /// Whether a row shows a two-button pair (Resume + Close, or Reply + Close) vs a single Close/Stop —
+ /// mirrors `stateControls`, so the title/subtext reserve the right trailing room for the controls.
+ private func rowShowsControlPair(_ task: UserQueryNotchTask) -> Bool {
+ switch task.status {
+ case .paused, .interrupted, .timedOut, .waitingForClarification, .waitingForReview:
+ return true
+ case .needsAttention:
+ return !task.commandText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ default:
+ return false
+ }
+ }
+
+ /// Trailing room the subtext leaves for the bottom-pinned elapsed time at its widest (e.g. "59m 59s").
+ private static let taskTimeColumnReserve: CGFloat = 52
+
+ /// Full opacity normally; while a reply is targeted, every row except the targeted one dims back so
+ /// the user sees which thread their next message answers.
+ private func rowReplyDimOpacity(for task: UserQueryNotchTask) -> Double {
+ guard let replyTargetTaskID else { return 1 }
+ return task.id == replyTargetTaskID ? 1 : 0.5
+ }
+
+ /// A task blocked on the user — the white attention state. Its pointer stays lit even when the row
+ /// dims for a reply, so every thread still waiting on the user reads at a glance.
+ private func isWaitingForReply(_ task: UserQueryNotchTask) -> Bool {
+ task.status.isAwaitingUserResponse
+ }
+
private func taskRow(_ task: UserQueryNotchTask) -> some View {
let isPermission = task.status == .waitingForPermission
+ // The reply dim is applied per-element rather than to the whole row so the pointer of a task that
+ // itself needs the user can stay lit while everything else recedes.
+ let contentDim = rowReplyDimOpacity(for: task)
+ let isReplyTarget = replyTargetTaskID == task.id
+ let pointerDim = isWaitingForReply(task) ? 1 : contentDim
return VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .top, spacing: 12) {
- // Colored pointer only while actively running; silhouette once stopped or finished.
- DonkeyCursorMark(color: accentColor(for: task.accentIndex), silhouette: task.status != .running)
+ // Colored pointer while actively running; silhouette once stopped or finished — but the
+ // reply target always shows its live accent color, so even a finished thread reads as
+ // active again while the user is replying to it.
+ DonkeyCursorMark(
+ color: accentColor(for: task.accentIndex),
+ silhouette: !isReplyTarget && task.status != .running
+ )
.frame(width: 14, height: 14)
.padding(.top, 1)
+ .opacity(pointerDim)
+ // A task waiting on the user gently pulses its pointer to call attention.
+ .modifier(AttentionPulse(active: isWaitingForReply(task)))
VStack(alignment: .leading, spacing: 4) {
Text(task.title)
@@ -613,6 +802,9 @@ public struct UserQueryNotchStatusView: View {
.foregroundStyle(Color.white.opacity(0.9))
.lineLimit(1)
.truncationMode(.tail)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ // First line runs all the way to just left of the pinned top-right controls.
+ .padding(.trailing, controlsReserve(for: task))
if !isPermission {
Text(taskStatusDescription(task))
@@ -621,15 +813,18 @@ public struct UserQueryNotchStatusView: View {
.lineLimit(5)
.truncationMode(.tail)
.fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ // Subtext runs to just left of the controls, or the bottom-pinned elapsed time.
+ .padding(.trailing, max(controlsReserve(for: task), Self.taskTimeColumnReserve))
}
}
.frame(maxWidth: .infinity, alignment: .leading)
- // Reserve room so long text never slides under the pinned controls / time (prototype: pr-[88px]).
- .padding(.trailing, isPermission ? 0 : 88)
+ .opacity(contentDim)
}
if isPermission {
permissionBanner(for: task)
+ .opacity(contentDim)
}
}
.padding(.horizontal, 12)
@@ -640,11 +835,19 @@ public struct UserQueryNotchStatusView: View {
// row renders at the same height and places the time identically; only genuinely long detail
// grows past it (and never crowds the time).
.frame(minHeight: 72)
- .background(Color.white.opacity(0.07))
+ // The cell fill recedes with the rest of the content while a reply targets another row.
+ .background(Color.white.opacity(0.07 * contentDim))
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
.contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
.onTapGesture {
- taskSelected(task.id)
+ // Every row is repliable. Tapping the active thread again leaves reply mode; tapping any
+ // other row pins it and focuses the composer, so the user can just start typing. (A running
+ // or permission-gated thread takes the message as a queued follow-up; the rest resume.)
+ if isReplyTarget {
+ replyModeExited()
+ } else {
+ replyRequested(task.id)
+ }
}
// Pinned to the full cell, matching the prototype insets: controls at top-8/right-12, elapsed
// time at bottom-2.5/right-12, so the time stays near the cell bottom as the subtext grows.
@@ -653,6 +856,7 @@ public struct UserQueryNotchStatusView: View {
topRightControls(task)
.padding(.top, 8)
.padding(.trailing, 12)
+ .opacity(contentDim)
}
}
.overlay(alignment: .bottomTrailing) {
@@ -660,6 +864,7 @@ public struct UserQueryNotchStatusView: View {
taskElapsedLabel(task)
.padding(.bottom, 10)
.padding(.trailing, 12)
+ .opacity(contentDim)
}
}
}
@@ -685,6 +890,10 @@ public struct UserQueryNotchStatusView: View {
NotchControlButton(systemName: "stop.fill", label: "Stop", isEnabled: true) {
pauseRequested(task.id)
}
+ case .waitingForClarification, .waitingForReview:
+ // The agent is blocked waiting on the user (the white attention glyph). Offer Reply so the
+ // user can answer the question (or respond to the review) right from the row, plus Close.
+ replyAndCloseControls(for: task)
case .paused, .interrupted, .timedOut:
// Paused (user), interrupted (changed course), and timed out (hit the step ceiling) all carry a
// goal and real progress, so they are retryable: offer Resume + Close.
@@ -698,8 +907,8 @@ public struct UserQueryNotchStatusView: View {
resumeAndCloseControls(for: task)
}
default:
- // Completed, failed, chatting, and the waiting states (e.g. a clarifying question) are all
- // dismissable straight from the row instead of showing a non-actionable status glyph.
+ // Completed, failed, and chatting only carry Close. A completed thread is still repliable,
+ // but by tapping the row (which activates it) rather than a button — see `taskRow`'s tap.
closeControl(for: task)
}
}
@@ -716,6 +925,23 @@ public struct UserQueryNotchStatusView: View {
}
}
+ /// A task waiting on the user gets Reply (answer the clarification / respond to the review) + Close.
+ /// Reply pins the composer to this task and focuses the input; the user's next message answers it.
+ @ViewBuilder
+ private func replyAndCloseControls(for task: UserQueryNotchTask) -> some View {
+ HStack(spacing: 6) {
+ NotchControlButton(label: "Reply", isEnabled: true) {
+ replyRequested(task.id)
+ } icon: {
+ MessageSquareReplyMark()
+ .frame(width: 12, height: 12)
+ }
+ NotchControlButton(systemName: "xmark", label: "Close", isEnabled: true) {
+ dismissRequested(task.id)
+ }
+ }
+ }
+
private func closeControl(for task: UserQueryNotchTask) -> some View {
NotchControlButton(systemName: "xmark", label: "Close", isEnabled: true) {
dismissRequested(task.id)
@@ -809,6 +1035,16 @@ public struct UserQueryNotchStatusView: View {
.accessibilityLabel("\(label) permission")
}
+ /// While replying, the composer is outlined in the targeted task's accent color so the input visibly
+ /// belongs to that thread (matching the row's lit pointer).
+ private var replyTargetAccentColor: Color? {
+ guard let replyTargetTaskID,
+ let task = tasks.first(where: { $0.id == replyTargetTaskID }) else {
+ return nil
+ }
+ return accentColor(for: task.accentIndex)
+ }
+
private var commandRow: some View {
UserQueryComposer(
state: commandInputState,
@@ -816,6 +1052,7 @@ public struct UserQueryNotchStatusView: View {
inputTextHeight: commandInputTextHeight,
isInputExpanded: isCommandInputExpanded,
surfaceFill: Color.white.opacity(0.085),
+ borderColor: replyTargetAccentColor,
forceExpandedSurface: true,
toolbarStyle: .followUp,
sizeProfile: .compact,
@@ -936,7 +1173,11 @@ public struct UserQueryNotchStatusView: View {
/// lonely clock; every state's full elapsed total lives in the expanded row.
@ViewBuilder
private var collapsedRightSlot: some View {
- if let task = primaryTask {
+ if surfacedErrorTask != nil {
+ // A surfaced failure (e.g. an auth error) raises the red warning glyph here while its message
+ // holds the chin, until the user expands to acknowledge it.
+ slotIcon("exclamationmark.bubble", color: Self.chinErrorColor)
+ } else if let task = primaryTask {
switch task.status {
case .waitingForClarification, .waitingForReview:
// Attention: the agent is blocked waiting for the user to answer or review something.
@@ -961,10 +1202,15 @@ public struct UserQueryNotchStatusView: View {
}
}
- private func slotIcon(_ systemName: String) -> some View {
+ /// The surfaced failure currently holding the chin, if any — drives the right-rail warning glyph.
+ private var surfacedErrorTask: UserQueryNotchTask? {
+ surfacedTasks.first { $0.status == .failed }
+ }
+
+ private func slotIcon(_ systemName: String, color: Color = Color.white.opacity(0.85)) -> some View {
Image(systemName: systemName)
.font(.system(size: 11, weight: .regular))
- .foregroundStyle(Color.white.opacity(0.85))
+ .foregroundStyle(color)
}
private func slotText(_ text: String, opacity: Double = 0.72) -> some View {
@@ -1073,6 +1319,15 @@ public struct UserQueryNotchStatusView: View {
private static let maxClusterPointers = 3
private static let clusterStepX: CGFloat = 8
private static let clusterStepY: CGFloat = 3
+ /// Chin text metrics, matching the band geometry the controller sizes (10pt on a 12pt line with an
+ /// 8pt bottom margin). The text is seated above that bottom margin so it stays constant as the band
+ /// grows for a second line.
+ private static let chinFontSize: CGFloat = 12
+ private static let chinBottomMargin: CGFloat = 8
+ /// The failed-chin warning red. Mirrors the prototype's `ERROR_RED` (rgb(255, 69, 58)) exactly — it
+ /// is the one place this hue is needed in the app, so it stays a literal rather than a shared token,
+ /// kept in sync with tasks.ts by value.
+ private static let chinErrorColor = Color(red: 1.0, green: 69.0 / 255.0, blue: 58.0 / 255.0)
/// The chin advances to the next running task every 2.6s, on a clock shared by all tasks.
private static let chinRotationInterval: TimeInterval = 2.6
private static let chinRotationAnchor = Date(timeIntervalSinceReferenceDate: 0)
@@ -1123,17 +1378,43 @@ private struct GrowingNotchShape: Shape {
/// A round row control (stop / resume / close). Like the prototype's control buttons it brightens its
/// fill on hover (white 12% → 20%), so the X and its siblings highlight under the cursor.
private struct NotchControlButton: View {
- let systemName: String
- let label: String
- var isEnabled: Bool = true
- let action: @MainActor () -> Void
+ private let icon: AnyView
+ private let label: String
+ private let isEnabled: Bool
+ private let action: @MainActor () -> Void
@State private var isHovering = false
- var body: some View {
- Button(action: action) {
+ /// SF Symbol control (stop / resume / close).
+ init(
+ systemName: String,
+ label: String,
+ isEnabled: Bool = true,
+ action: @escaping @MainActor () -> Void
+ ) {
+ self.init(label: label, isEnabled: isEnabled, action: action) {
Image(systemName: systemName)
.font(.system(size: 10, weight: .regular))
+ }
+ }
+
+ /// Custom-icon control (e.g. the ported lucide Reply glyph). The icon inherits the button's
+ /// foreground tint, so a stroked shape reads the same enabled/hover color as an SF Symbol.
+ init<Icon: View>(
+ label: String,
+ isEnabled: Bool = true,
+ action: @escaping @MainActor () -> Void,
+ @ViewBuilder icon: () -> Icon
+ ) {
+ self.icon = AnyView(icon())
+ self.label = label
+ self.isEnabled = isEnabled
+ self.action = action
+ }
+
+ var body: some View {
+ Button(action: action) {
+ icon
.foregroundStyle(Color.white.opacity(isEnabled ? 0.88 : 0.3))
.frame(width: 24, height: 24)
.background(Color.white.opacity(backgroundOpacity))
@@ -1154,6 +1435,77 @@ private struct NotchControlButton: View {
}
}
+/// A gentle, slow pulse (scale + fade) used to call attention to a task that is waiting on the user,
+/// without the urgency of the running-pointer pulse. Inert until `active`, so non-waiting rows are still.
+private struct AttentionPulse: ViewModifier {
+ let active: Bool
+ @State private var pulsing = false
+
+ func body(content: Content) -> some View {
+ content
+ .scaleEffect(active && pulsing ? 1.1 : 1.0)
+ .opacity(active && pulsing ? 0.7 : 1.0)
+ .onAppear { startIfNeeded() }
+ .onChange(of: active) { startIfNeeded() }
+ }
+
+ private func startIfNeeded() {
+ // Reset when inactive so a thread that re-enters a waiting state (e.g. a second clarification)
+ // re-arms the pulse instead of being blocked by the stale `pulsing` flag.
+ guard active else {
+ pulsing = false
+ return
+ }
+ guard !pulsing else { return }
+ withAnimation(.easeInOut(duration: 0.85).repeatForever(autoreverses: true)) {
+ pulsing = true
+ }
+ }
+}
+
+/// Lucide `message-square-reply`, ported from the icon set the prototype uses (24×24 viewBox, 2px round
+/// stroke) so the Reply control matches it. The bubble corners and the reply hook keep their 2px radius;
+/// the small tail roundings are simplified to straight joins at this size. Strokes in the current
+/// foreground style, so the enclosing button tints it like an SF Symbol.
+private struct MessageSquareReplyMark: View {
+ var body: some View {
+ GeometryReader { proxy in
+ let scale = min(proxy.size.width, proxy.size.height) / 24
+ Self.path(scale: scale)
+ .stroke(style: StrokeStyle(lineWidth: 2 * scale, lineCap: .round, lineJoin: .round))
+ }
+ .aspectRatio(1, contentMode: .fit)
+ .accessibilityHidden(true)
+ }
+
+ private static func path(scale: CGFloat) -> Path {
+ Path { p in
+ func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: x * scale, y: y * scale) }
+ let r = 2 * scale
+
+ // Speech bubble: a rounded rectangle with a reply tail at the bottom-left.
+ p.move(to: pt(4, 3))
+ p.addArc(tangent1End: pt(22, 3), tangent2End: pt(22, 19), radius: r)
+ p.addArc(tangent1End: pt(22, 19), tangent2End: pt(2, 19), radius: r)
+ p.addLine(to: pt(6.828, 19))
+ p.addLine(to: pt(3.212, 21.788))
+ p.addLine(to: pt(2, 21.286))
+ p.addArc(tangent1End: pt(2, 3), tangent2End: pt(22, 3), radius: r)
+ p.closeSubpath()
+
+ // Reply arrow chevron.
+ p.move(to: pt(10, 8))
+ p.addLine(to: pt(7, 11))
+ p.addLine(to: pt(10, 14))
+
+ // Hook from the arrow back up into the bubble.
+ p.move(to: pt(17, 14))
+ p.addArc(tangent1End: pt(17, 11), tangent2End: pt(7, 11), radius: r)
+ p.addLine(to: pt(7, 11))
+ }
+ }
+}
+
/// The donkey cursor glyph. Geometry is ported verbatim from the prototype's
/// `DonkeyCursor` SVG (100x100 viewBox) so the app and landing-page prototype
/// stay visually identical. The cursor's tip points up-right at `rotationDegrees`
diff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift
index fbaa9a83..583f6250 100644
--- a/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift
+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift
@@ -113,6 +113,9 @@ struct UserQueryComposer: View {
let inputTextHeight: CGFloat
let isInputExpanded: Bool
let surfaceFill: Color
+ /// When set, the follow-up surface is outlined in this color — used to tint the composer with the
+ /// accent of the task a reply is pinned to, so the input visibly belongs to that thread.
+ let borderColor: Color?
let forceExpandedSurface: Bool
let toolbarStyle: UserQueryComposerToolbarStyle
let sizeProfile: UserQueryComposerSizeProfile
@@ -128,6 +131,7 @@ struct UserQueryComposer: View {
inputTextHeight: CGFloat,
isInputExpanded: Bool,
surfaceFill: Color = .black,
+ borderColor: Color? = nil,
forceExpandedSurface: Bool = false,
toolbarStyle: UserQueryComposerToolbarStyle = .waveformOnly,
sizeProfile: UserQueryComposerSizeProfile = .standard,
@@ -142,6 +146,7 @@ struct UserQueryComposer: View {
self.inputTextHeight = inputTextHeight
self.isInputExpanded = isInputExpanded
self.surfaceFill = surfaceFill
+ self.borderColor = borderColor
self.forceExpandedSurface = forceExpandedSurface
self.toolbarStyle = toolbarStyle
self.sizeProfile = sizeProfile
@@ -201,6 +206,16 @@ struct UserQueryComposer: View {
)
.fill(surfaceFill)
}
+ .overlay {
+ if let borderColor {
+ RoundedRectangle(
+ cornerRadius: UserQueryLayout.followUpComposerCornerRadius,
+ style: .continuous
+ )
+ .strokeBorder(borderColor, lineWidth: 1.5)
+ }
+ }
+ .animation(.easeOut(duration: 0.16), value: borderColor)
.accessibilityElement(children: .contain)
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/TaskFollowUpInjectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/TaskFollowUpInjectionTests.swift
index 2a5ddcd9..9c814849 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/TaskFollowUpInjectionTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/TaskFollowUpInjectionTests.swift
@@ -281,7 +281,7 @@ struct TaskFollowUpInjectionTests {
func status(_ id: String) -> UserQueryTaskStatus? { result.tasks.first { $0.id == id }?.status }
#expect(status("recent") == .running)
#expect(status("stale") == .timedOut) // too old to auto-run → retryable row
- #expect(status("waiting") == .needsAttention) // was blocked on the user → manual resume
+ #expect(status("waiting") == .paused) // was blocked on the user → comes back paused
#expect(status("paused") == .paused) // user-paused stays paused
#expect(status("done") == .completed) // terminal states untouched
// The persisted updatedAt is preserved so elapsed-time stays the real run duration.