Skip to content

Open source CapCut alternative.

TypeScript

fix(app): surface Live answers with task feedback, delegation, and shell consent

David Le6498ecb9ccc1
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
index 29efed82..2406a96b 100644
--- a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
@@ -4,10 +4,20 @@ import DonkeyHarness
import DonkeyRuntime
import Foundation
+/// A shell command the Live model wants to run that needs the user's consent
+/// (allow once / always allow) before it can execute.
+struct GeminiLiveShellConsentRequest: Equatable, Sendable {
+ var command: String
+ var signature: String
+ var tier: String
+ var allowAlways: Bool
+ var summary: String
+}
+
/// Drives the always-on Gemini Live session for the app: streams text (and
/// optionally audio) into the session, executes the model's tool calls against
-/// the Donkey Command Layer, and surfaces anything the model didn't handle with
-/// a tool call back to the normal command pipeline.
+/// the Donkey Command Layer, and surfaces the model's answers and delegations
+/// back to the overlay.
///
/// Entirely gated by `GeminiLiveConfiguration.enabled`; when disabled, nothing
/// here runs and the existing pipeline is unchanged.
@@ -18,13 +28,26 @@ final class GeminiLiveVoiceController {
private let registry: HarnessToolRegistry
private var session: GeminiLiveSession?
private var eventTask: Task<Void, Never>?
+ /// The model's in-flight text answer, accumulated across `.textOut` chunks
+ /// and flushed to `onResponse` when the turn completes.
+ private var pendingResponseText = ""
+ /// The audio-mode answer transcription, used when no text parts arrived.
+ private var pendingResponseTranscript = ""
+ /// A consent-gated tool call held until the user decides in the notch UI.
+ private var pendingConsent: (call: HarnessToolCall, liveCall: AIRealtimeToolCall, session: GeminiLiveSession)?
- /// Invoked for transcripts/requests the model did not satisfy with a tool
- /// call (e.g. a complex request). Wire this to the overlay's submit path.
+ /// Invoked when the model explicitly delegates a task it can't do with the
+ /// fast tools (the `agent_run` function call), with the structured goal.
+ /// Wire this to the overlay's local-pipeline submit path.
var onComplexRequest: ((String) -> Void)?
/// Invoked after a Command Layer tool runs, with a short status summary, so
/// the UI can reflect that the model acted.
var onActed: ((String) -> Void)?
+ /// Invoked with the model's completed answer for the current turn.
+ var onResponse: ((String) -> Void)?
+ /// Invoked when a shell command needs allow-once / always-allow consent.
+ /// The decision comes back through `resolvePendingConsent`.
+ var onConsentNeeded: ((GeminiLiveShellConsentRequest) -> Void)?
/// Invoked when optional microphone streaming should start (`true`) or stop
/// (`false`). Always paired — a `true` is always followed by a `false` when
/// the session disconnects or stops — so the mic owner never gets stuck on.
@@ -42,7 +65,7 @@ final class GeminiLiveVoiceController {
init(
configuration: GeminiLiveConfiguration = .fromEnvironment(),
- systemInstruction: String = GeminiLiveVoiceController.defaultSystemInstruction,
+ systemInstruction: String = DonkeyPrompts.realtimeCommandSystemInstruction,
visionAuthProvider: @escaping @Sendable () async throws -> GeminiVertexVisionPlanner.VertexAuth = {
try await GeminiVertexVisionPlanner.mintAuth(
backend: DonkeyBackendInferenceClient(configuration: try DonkeyBackendInferenceConfiguration.fromEnvironment())
@@ -65,7 +88,7 @@ final class GeminiLiveVoiceController {
guard configuration.enabled, session == nil else { return }
let session = GeminiLiveSession(
systemInstruction: systemInstruction,
- functionDescriptors: DonkeyCommandLayer.descriptors + [Self.visionControlDescriptor],
+ functionDescriptors: DonkeyCommandLayer.descriptors + [Self.visionControlDescriptor, Self.agentRunDescriptor],
connectionProvider: Self.makeConnectionProvider()
)
self.session = session
@@ -124,8 +147,17 @@ final class GeminiLiveVoiceController {
updateAudioStreaming()
case .toolCalls(let calls):
await execute(calls)
+ case .textOut(let text):
+ pendingResponseText += text
case .finalTranscript(let text):
- onComplexRequest?(text)
+ // The model's own answer transcription (audio mode). It is OUTPUT,
+ // never a user request — surface it as the answer, don't re-run it.
+ pendingResponseTranscript = text
+ case .turnComplete:
+ flushResponse()
+ case .interrupted:
+ pendingResponseText = ""
+ pendingResponseTranscript = ""
case .closed:
isConnected = false
updateAudioStreaming()
@@ -134,6 +166,24 @@ final class GeminiLiveVoiceController {
}
}
+ /// Deliver the model's completed answer for this turn, preferring text parts
+ /// over the audio transcription when both arrived.
+ private func flushResponse() {
+ let answer = pendingResponseText.isEmpty ? pendingResponseTranscript : pendingResponseText
+ pendingResponseText = ""
+ pendingResponseTranscript = ""
+ let trimmed = answer.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ onResponse?(trimmed)
+ }
+
+ /// The task id consent grants and tool executions are keyed on for this
+ /// session-wide Live "task".
+ static let liveTaskID = "gemini-live"
+
+ /// Permissions the Live session's Command Layer tools run with.
+ static let liveGrantedPermissions: Set<HarnessPermission> = [.appControl, .input, .appLookup, .skillLookup]
+
private func execute(_ calls: [AIRealtimeToolCall]) async {
guard let session else { return }
var results: [AIRealtimeToolResult] = []
@@ -148,13 +198,44 @@ final class GeminiLiveVoiceController {
launchVision(call)
continue
}
+ // Explicit delegation to the desktop agent: hand the structured goal
+ // to the local pipeline (which has its own UI and reporting) and let
+ // the Live turn finish immediately.
+ if toolName == Self.agentRunToolName {
+ let goal = (call.arguments["goal"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !goal.isEmpty else {
+ results.append(AIRealtimeToolResult(
+ id: call.id,
+ name: call.name,
+ response: ["status": "invalidInput", "summary": "agent_run needs a non-empty `goal`."]
+ ))
+ continue
+ }
+ onComplexRequest?(goal)
+ results.append(AIRealtimeToolResult(
+ id: call.id,
+ name: call.name,
+ response: [
+ "status": "delegated",
+ "summary": "Handed off to the desktop agent; it reports its progress and result to the user directly. Tell the user it's underway."
+ ]
+ ))
+ continue
+ }
let toolCall = HarnessToolCall(id: call.id, name: toolName, input: call.arguments)
let result = await registry.execute(
toolCall,
- taskID: "gemini-live",
+ taskID: Self.liveTaskID,
worldModel: HarnessWorldModel(),
- grantedPermissions: [.appControl, .input, .appLookup]
+ grantedPermissions: Self.liveGrantedPermissions
)
+ // Shell consent: hold the call, surface allow-once / always-allow in
+ // the notch, and answer the session when the user decides — the same
+ // gate the harness path uses, so nothing state-changing runs silently.
+ if result.status == .waitingForPermission, result.metadata["gate"] == "shellConsent" {
+ holdForConsent(call: toolCall, liveCall: call, session: session, result: result)
+ continue
+ }
onActed?(result.summary)
// Forward the full execution detail (stdout/stderr/exitCode/reason,
// plus tool-specific facts) so the model can read output and
@@ -163,7 +244,7 @@ final class GeminiLiveVoiceController {
response.removeValue(forKey: "executor")
response["status"] = result.status.rawValue
response["summary"] = result.summary
- // Surface a clarification gate (e.g. music_play asking what to play)
+ // Surface a clarification gate (e.g. a skill script asking for a missing detail)
// so the model asks the user instead of guessing or stalling.
if result.status == .waitingForUser, let question = result.question {
response["needsUserInput"] = "true"
@@ -178,6 +259,76 @@ final class GeminiLiveVoiceController {
if !results.isEmpty { try? await session.sendToolResults(results) }
}
+ // MARK: - Shell consent
+
+ /// Park a consent-gated shell command and surface the decision UI. A newer
+ /// gated command supersedes a parked one (the old call is answered as
+ /// declined so the session never hangs on it).
+ private func holdForConsent(
+ call: HarnessToolCall,
+ liveCall: AIRealtimeToolCall,
+ session: GeminiLiveSession,
+ result: HarnessToolResult
+ ) {
+ if let superseded = pendingConsent {
+ answerConsent(superseded, status: "declined", summary: "Superseded by a newer command awaiting approval.")
+ }
+ pendingConsent = (call, liveCall, session)
+ let request = GeminiLiveShellConsentRequest(
+ command: result.metadata["shell.command"] ?? call.input["command"] ?? "",
+ signature: result.metadata["shell.signature"] ?? "",
+ tier: result.metadata["shell.tier"] ?? "",
+ allowAlways: result.metadata["shell.allowAlways"] == "true",
+ summary: result.summary
+ )
+ onConsentNeeded?(request)
+ }
+
+ /// The user decided on the parked command: grant (once or always) and
+ /// re-execute it, or decline it, then answer the waiting Live tool call.
+ func resolvePendingConsent(approved: Bool, alwaysAllow: Bool) async {
+ guard let pending = pendingConsent else { return }
+ pendingConsent = nil
+ guard approved else {
+ answerConsent(pending, status: "declined", summary: "The user declined to run the command.")
+ return
+ }
+ let command = pending.call.input["command"] ?? pending.call.input["cmd"] ?? ""
+ let classification = ShellCommandClassifier.classify(command)
+ if alwaysAllow, classification.tier != .highRisk {
+ await ShellPermissionPolicyStore.shared.allowAlways(classification.signature, tier: classification.tier)
+ } else {
+ await ShellPermissionPolicyStore.shared.grantOnce(taskID: Self.liveTaskID, signature: classification.signature)
+ }
+ let result = await registry.execute(
+ pending.call,
+ taskID: Self.liveTaskID,
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: Self.liveGrantedPermissions
+ )
+ onActed?(result.summary)
+ var response = result.metadata
+ response.removeValue(forKey: "executor")
+ response["status"] = result.status.rawValue
+ response["summary"] = result.summary
+ try? await pending.session.sendToolResults([
+ AIRealtimeToolResult(id: pending.liveCall.id, name: pending.liveCall.name, response: response)
+ ])
+ }
+
+ private func answerConsent(
+ _ pending: (call: HarnessToolCall, liveCall: AIRealtimeToolCall, session: GeminiLiveSession),
+ status: String,
+ summary: String
+ ) {
+ let result = AIRealtimeToolResult(
+ id: pending.liveCall.id,
+ name: pending.liveCall.name,
+ response: ["status": status, "summary": summary]
+ )
+ Task { try? await pending.session.sendToolResults([result]) }
+ }
+
/// Run the vision escalation in a separate task (NOT the event-consumer task)
/// and answer the model's `vision_control` call when the drive completes.
private func launchVision(_ call: AIRealtimeToolCall) {
@@ -258,6 +409,24 @@ final class GeminiLiveVoiceController {
return raw
}
+ // MARK: - Agent delegation
+
+ static let agentRunToolName = "agent_run"
+
+ /// Explicit, typed escalation to the full desktop agent (the generic harness
+ /// loop with understanding, planning, consent gates, and verification). The
+ /// model calls this instead of guessing when the fast tools can't do the task.
+ static let agentRunDescriptor = HarnessToolDescriptor(
+ name: agentRunToolName,
+ pluginID: "donkey.agent",
+ summary: "Delegate a task to the full desktop agent, which plans multi-step work, drives app GUIs, and asks the user for consent when needed. Use when the fast tools can't complete the request — multi-step workflows, tasks inside an app's UI beyond a single command, or anything you cannot verify with the tools you have. Do not use it for questions you can answer directly or single commands shell_exec covers.",
+ inputSchema: [
+ "goal": "The task to accomplish, restated as one concrete imperative sentence carrying the user's specifics (titles, names, values)."
+ ],
+ requiredPermissions: [.appControl, .input],
+ safetyClass: .guardedInput
+ )
+
// MARK: - Vision escalation
static let visionControlToolName = "vision_control"
@@ -270,26 +439,13 @@ final class GeminiLiveVoiceController {
static let visionControlDescriptor = HarnessToolDescriptor(
name: visionControlToolName,
pluginID: "donkey.vision",
- summary: "Operate an app by looking at the screen (a vision agent clicks/types). Use ONLY when a task must happen inside a specific app the fast tools can't drive — e.g. searching for and playing something in Spotify (music_play controls Apple Music only).",
+ summary: "Operate an app by looking at the screen (a vision agent clicks/types). Use ONLY when a task must happen inside a specific app the fast tools can't drive — typically when the app's skill (from app_skill) says it must be driven by vision, or when scripting it failed.",
inputSchema: [
- "app": "The app to operate, e.g. Spotify.",
- "goal": "What to accomplish in the app, e.g. play Coldplay's most popular song."
+ "app": "The app to operate.",
+ "goal": "What to accomplish in the app, stated concretely."
],
requiredPermissions: [.input, .screenCapture],
safetyClass: .guardedInput
)
- // Cross-tool policy only. Each tool's purpose, parameters, examples, and
- // safety constraints live in its registered function declaration (see
- // CommandLayerFunctionDeclarations / DonkeyCommandLayer), not here.
- static let defaultSystemInstruction = """
- You are Donkey, a fast macOS assistant. Act directly and immediately with the \
- registered tools, preferring shell_exec for anything the more specific tools \
- don't cover. music_play controls Apple Music only — it CANNOT control Spotify. \
- When a task must happen in a specific app that no fast tool can operate (e.g. \
- searching for and playing a song in Spotify), call vision_control with the app \
- and goal; a vision agent will operate the screen. Discover before guessing rather \
- than inventing names or values. Read each tool's returned output and retry or \
- adjust on failure. Keep replies short.
- """
}
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
index 56b07699..e65a0a2e 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
@@ -34,9 +34,16 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
private let appCatalogRefreshLoop: LocalAppDynamicCatalogRefreshLoop
private var activeTaskIDs: Set<String> = []
private var lastActiveTaskID: String?
+ /// The task/spawn the in-flight Gemini Live turn reports into, so the user
+ /// sees the same cursor-and-task feedback as a local pipeline run.
+ private var liveTurn: (taskID: String, spawnID: String?)?
+ private var liveTurnWatchdog: Task<Void, Never>?
private static let notchTaskDisplayLimit = 12
private static let followUpCandidateLimit = 8
private static let followUpMatchConfidenceThreshold = 0.62
+ /// How long a Live turn may stay silent (no tool, no answer) before the task
+ /// is failed instead of spinning forever.
+ private static let liveTurnSilenceLimitSeconds: TimeInterval = 75
init(
aiProvider: any AIHarnessSnapshotProviding = AIHarnessBoundary(),
@@ -90,15 +97,34 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
/// configured the existing command pipeline is used unchanged.
private func startLiveSessionIfEnabled() {
guard liveController.isEnabled else { return }
- liveController.onComplexRequest = { [weak self] text in
- // Anything the Live model didn't satisfy with a tool call runs through
- // the full local pipeline (never back through Live — no loop).
- self?.runLocalCommand(text, source: .typedPrompt)
+ liveController.onComplexRequest = { [weak self] goal in
+ // The model explicitly delegated via agent_run: close out the Live
+ // turn and run the goal through the full local pipeline (never back
+ // through Live — no loop). The pipeline has its own task/spawn UI.
+ guard let self else { return }
+ self.finishLiveTurn(detail: "Handed off to the desktop agent", status: .completed)
+ self.runLocalCommand(goal, source: .typedPrompt)
}
liveController.onActed = { [weak self] summary in
guard let self else { return }
self.promptState.leadingSignalLevel = .ready
self.promptState.promptText = summary
+ guard let liveTurn = self.liveTurn else { return }
+ self.updateSpawn(id: liveTurn.spawnID, label: Self.collapsedDisplayText(for: summary), phase: .holding)
+ self.updateTask(id: liveTurn.taskID, detail: summary, status: .running)
+ self.appendTaskEvent(taskID: liveTurn.taskID, role: .system, text: summary)
+ self.restartLiveTurnWatchdog()
+ }
+ liveController.onResponse = { [weak self] answer in
+ guard let self else { return }
+ self.promptState.leadingSignalLevel = .ready
+ self.promptState.promptText = answer
+ guard let liveTurn = self.liveTurn else { return }
+ self.appendTaskEvent(taskID: liveTurn.taskID, role: .assistant, text: answer)
+ self.finishLiveTurn(detail: answer, status: .completed)
+ }
+ liveController.onConsentNeeded = { [weak self] request in
+ self?.presentLiveShellConsent(request)
}
// Forward start/stop of optional audio streaming to the mic owner. The
// controller emits a paired false on disconnect/stop, so continuous
@@ -224,15 +250,99 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
runLocalCommand(text, source: source)
}
+ /// Send a turn to the Live session with the same visible lifecycle as a
+ /// local run: a task in the rail and a spawn cursor that narrates tool
+ /// activity, consent gates, and the final answer.
private func routeToLiveSession(_ text: String) {
+ if liveTurn != nil {
+ finishLiveTurn(detail: "Changed course", status: .interrupted)
+ }
+ let spawnID = beginSpawn(for: text)
+ let task = taskForSubmittedCommand(
+ text: text,
+ matchedTaskID: nil,
+ reservedAccentIndex: spawn(withID: spawnID)?.accentIndex
+ )
+ updateSpawn(id: spawnID, taskID: task.id, accentIndex: task.accentIndex)
+ activeTaskIDs.insert(task.id)
+ lastActiveTaskID = task.id
+ appendTaskEvent(taskID: task.id, role: .user, text: text)
clearSubmissionInputs()
promptState.isActive = false
promptState.isVoiceInputActive = false
promptState.leadingSignalLevel = .thinking
- promptState.promptText = "On it"
+ promptState.promptText = task.title
+ liveTurn = (task.id, spawnID)
+ restartLiveTurnWatchdog()
Task { [liveController] in await liveController.sendText(text) }
}
+ /// Close out the in-flight Live turn's task and spawn.
+ private func finishLiveTurn(detail: String?, status: UserQueryTaskStatus) {
+ liveTurnWatchdog?.cancel()
+ liveTurnWatchdog = nil
+ guard let turn = liveTurn else { return }
+ liveTurn = nil
+ updateTask(id: turn.taskID, detail: detail, status: status)
+ activeTaskIDs.remove(turn.taskID)
+ syncPrimaryTaskPausedFlag()
+ guard let spawnID = turn.spawnID, let index = spawnIndex(id: spawnID) else { return }
+ var spawnState = spawnStates[index]
+ switch status {
+ case .completed:
+ spawnState.label = detail.map(Self.collapsedDisplayText(for:)) ?? "Done"
+ case .failed:
+ spawnState.label = "Stopped"
+ default:
+ spawnState.label = Self.collapsedDisplayText(for: detail ?? spawnState.label)
+ }
+ spawnState.updatedAt = Date()
+ spawnStates[index] = spawnState
+ if !UserQuerySpawnLifecycle.keepsVisibleResult(for: status) {
+ scheduleSpawnFade(id: spawnID, after: 2.0)
+ }
+ }
+
+ /// Fail the Live turn if the session stays silent (no tool call, no answer)
+ /// past the limit, instead of leaving the task spinning.
+ private func restartLiveTurnWatchdog() {
+ liveTurnWatchdog?.cancel()
+ let limit = Self.liveTurnSilenceLimitSeconds
+ liveTurnWatchdog = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64(limit * 1_000_000_000))
+ guard !Task.isCancelled else { return }
+ await MainActor.run {
+ guard let self, self.liveTurn != nil else { return }
+ self.finishLiveTurn(detail: "No response — try again or rephrase.", status: .failed)
+ self.promptState.leadingSignalLevel = .idle
+ }
+ }
+ }
+
+ /// Surface a Live-path shell consent in the notch using the same task
+ /// metadata the harness consent UI reads, marked so approval routes back to
+ /// the Live controller instead of the harness lifecycle.
+ private func presentLiveShellConsent(_ request: GeminiLiveShellConsentRequest) {
+ guard let turn = liveTurn else { return }
+ liveTurnWatchdog?.cancel()
+ updateSpawn(id: turn.spawnID, label: "Waiting for approval", phase: .holding)
+ updateTask(
+ id: turn.taskID,
+ detail: request.summary,
+ status: .waitingForPermission,
+ metadata: [
+ "genericHarness.shellConsent.command": request.command,
+ "genericHarness.shellConsent.tier": request.tier,
+ "genericHarness.shellConsent.allowAlways": request.allowAlways ? "true" : "false",
+ "live.shellConsent": "true"
+ ]
+ )
+ appendTaskEvent(taskID: turn.taskID, role: .system, text: request.summary)
+ promptState.leadingSignalLevel = .ready
+ promptState.promptText = request.summary
+ syncPrimaryTaskPausedFlag()
+ }
+
private func runLocalCommand(_ text: String, source: AppHarnessTurnSource = .typedPrompt) {
let candidates = followUpCandidates()
let promptFollowUpTarget = promptSubmissionFollowUpTarget()
@@ -399,33 +509,45 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
Task { [weak self, commandHandler] in
let result = await commandHandler.handleSubmittedCommand(text, context: context)
await MainActor.run {
- guard let self else { return }
- self.updateTask(
- id: task.id,
- title: isFollowUp ? nil : result.taskLabel,
- detail: result.summary,
- status: Self.taskStatus(for: result),
- metadata: result.metadata
- )
- self.appendTaskEvent(taskID: task.id, role: .assistant, text: result.summary)
- self.activeTaskIDs.remove(task.id)
- self.refreshPromptStateAfterRunResult(
+ self?.handleCommandRunResult(
taskID: task.id,
+ spawnID: spawnID,
+ isFollowUp: isFollowUp,
result: result
)
- let cursorOverlayRequest = result.cursorOverlayRequest
- if let cursorOverlayRequest {
- self.agentVisualizationPresenter?(cursorOverlayRequest, spawnID)
- }
- self.finishSpawn(
- id: spawnID,
- result: result,
- minimumFadeDelay: cursorOverlayRequest.map(Self.visualizationPlaybackDuration)
- )
}
}
}
+ /// Apply a finished pipeline run to the task rail, prompt pill, cursor
+ /// replay, and spawn — shared by fresh submissions and post-approval resumes.
+ private func handleCommandRunResult(
+ taskID: String,
+ spawnID: String?,
+ isFollowUp: Bool,
+ result: UserQueryCommandHandlingResult
+ ) {
+ updateTask(
+ id: taskID,
+ title: isFollowUp ? nil : result.taskLabel,
+ detail: result.summary,
+ status: Self.taskStatus(for: result),
+ metadata: result.metadata
+ )
+ appendTaskEvent(taskID: taskID, role: .assistant, text: result.summary)
+ activeTaskIDs.remove(taskID)
+ refreshPromptStateAfterRunResult(taskID: taskID, result: result)
+ let cursorOverlayRequest = result.cursorOverlayRequest
+ if let cursorOverlayRequest {
+ agentVisualizationPresenter?(cursorOverlayRequest, spawnID)
+ }
+ finishSpawn(
+ id: spawnID,
+ result: result,
+ minimumFadeDelay: cursorOverlayRequest.map(Self.visualizationPlaybackDuration)
+ )
+ }
+
func pauseTask(id taskID: String) {
guard task(withID: taskID)?.status == .running else { return }
@@ -468,6 +590,21 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
return
}
+ // A Live-path shell consent resolves through the Live controller, which
+ // re-executes the held command and reports back via onActed/onResponse.
+ if task.metadata["live.shellConsent"] == "true" {
+ updateTask(id: taskID, detail: "Approved — running", status: .running, metadata: [:])
+ if let turn = liveTurn, turn.taskID == taskID {
+ updateSpawn(id: turn.spawnID, label: "Approved — running")
+ restartLiveTurnWatchdog()
+ }
+ syncPrimaryTaskPausedFlag()
+ Task { [liveController] in
+ await liveController.resolvePendingConsent(approved: true, alwaysAllow: alwaysAllow)
+ }
+ return
+ }
+
activeTaskIDs.insert(taskID)
lastActiveTaskID = taskID
let detail = Self.permissionApprovalDetail(for: task)
@@ -476,17 +613,36 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
promptState.leadingSignalLevel = .thinking
promptState.promptText = task.title
syncPrimaryTaskPausedFlag()
+ let spawnID = spawnStates.first { $0.taskID == taskID }?.id
+ let context = commandContext(taskID: taskID, isFollowUp: true, spawnID: spawnID)
Task { [weak self, commandHandler] in
let approved = await commandHandler.approvePermissionGate(taskID: taskID, alwaysAllow: alwaysAllow)
+ guard approved else {
+ await MainActor.run {
+ guard let self else { return }
+ self.updateTask(id: taskID, detail: "Approval unavailable", status: .needsAttention)
+ self.activeTaskIDs.remove(taskID)
+ self.syncPrimaryTaskPausedFlag()
+ }
+ return
+ }
+ // The grant only recorded consent; the loop already exited at the
+ // gate. Re-run it so the approved command actually executes.
+ let result = await commandHandler.continueApprovedCommand(taskID: taskID, context: context)
await MainActor.run {
guard let self else { return }
- if approved {
- self.updateTask(id: taskID, detail: "Permission approved", status: .running)
- } else {
- self.updateTask(id: taskID, detail: "Approval unavailable", status: .needsAttention)
+ guard let result else {
+ self.updateTask(id: taskID, detail: "Could not resume the task", status: .needsAttention)
self.activeTaskIDs.remove(taskID)
+ self.syncPrimaryTaskPausedFlag()
+ return
}
- self.syncPrimaryTaskPausedFlag()
+ self.handleCommandRunResult(
+ taskID: taskID,
+ spawnID: spawnID,
+ isFollowUp: true,
+ result: result
+ )
}
}
}
diff --git a/apps/Donkey/Sources/DonkeyAI/AIRealtimeSession.swift b/apps/Donkey/Sources/DonkeyAI/AIRealtimeSession.swift
index ed40dddb..f9121334 100644
--- a/apps/Donkey/Sources/DonkeyAI/AIRealtimeSession.swift
+++ b/apps/Donkey/Sources/DonkeyAI/AIRealtimeSession.swift
@@ -32,10 +32,14 @@ public enum AIRealtimeEvent: Equatable, Sendable {
case partialTranscript(String)
case finalTranscript(String)
case toolCalls([AIRealtimeToolCall])
+ /// A chunk of the model's text answer (text response modality).
+ case textOut(String)
case audioOut(Data)
/// User barged in; discard any buffered output audio.
case interrupted
case generationComplete
+ /// The model finished its turn; any buffered text/transcript is complete.
+ case turnComplete
/// Server will close the socket soon; reconnect within `timeLeftMS`.
case goAway(timeLeftMS: Int)
/// Opaque handle to resume this session after a reconnect.
diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveProtocol.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveProtocol.swift
index 8944d4bf..443539e3 100644
--- a/apps/Donkey/Sources/DonkeyAI/GeminiLiveProtocol.swift
+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveProtocol.swift
@@ -113,6 +113,9 @@ public enum GeminiLiveProtocol {
if let modelTurn = serverContent["modelTurn"] as? [String: Any],
let parts = modelTurn["parts"] as? [[String: Any]] {
for part in parts {
+ if let text = part["text"] as? String, !text.isEmpty {
+ events.append(.textOut(text))
+ }
if let inlineData = part["inlineData"] as? [String: Any],
let base64 = inlineData["data"] as? String,
let audio = Data(base64Encoded: base64) {
@@ -128,6 +131,7 @@ public enum GeminiLiveProtocol {
let text = outputTranscription["text"] as? String, !text.isEmpty {
events.append(.finalTranscript(text))
}
+ events.append(.turnComplete)
}
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveHybridSpotifySmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveHybridSpotifySmokeTests.swift
index 5200d432..6e171ae6 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveHybridSpotifySmokeTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveHybridSpotifySmokeTests.swift
@@ -9,10 +9,11 @@ import Testing
/// Live, doubly-gated: the **hybrid** flow through the REAL production controller.
/// `GeminiLiveVoiceController` runs the fast realtime command session
/// (`gemini-live-2.5-flash`) with the Command Layer tools plus the `vision_control`
-/// escalation. For "play Coldplay on Spotify" — which `music_play` can't do
-/// (Apple-Music only) — the 2.5 model calls `vision_control`, and the controller
-/// runs the gemini-3.5 `VertexVisionDriver` to operate Spotify. The test only feeds
-/// the controller a text turn and verifies real Coldplay playback.
+/// escalation. For "play Coldplay on Spotify" — whose installed skill
+/// (`app_skill` → spotify-operate) says the app must be driven by vision — the
+/// 2.5 model calls `vision_control`, and the controller runs the gemini-3.5
+/// `VertexVisionDriver` to operate Spotify. The test only feeds the controller a
+/// text turn and verifies real Coldplay playback.
///
/// Behavior probe: both the model's choice to escalate and the vision grounding are
/// probabilistic — read the printed line (validated: escalates, ~8 vision turns,
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveMusicPlaybackLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveMusicPlaybackLiveSmokeTests.swift
index 2d1eeea7..581dbed2 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveMusicPlaybackLiveSmokeTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveMusicPlaybackLiveSmokeTests.swift
@@ -11,7 +11,8 @@ import Testing
/// (`gemini-live-2.5-flash` on Vertex) and the Donkey Command Layer harness
/// registry. The test only hands the controller a text turn ("play some cold play")
/// and verifies a music app actually starts playing; the controller does the real
-/// work (model → `music_play` tool → harness execution).
+/// work (model → `app_skill` discovery → `skill_run` script execution, or an
+/// equivalent route the model chooses).
///
/// Gated behind `DONKEY_LIVE_SMOKE=1`; no-ops otherwise. To run it live:
///
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift
index 3d92ece0..591d8aa0 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift
@@ -33,12 +33,14 @@ struct GeminiLiveTests {
#expect(names.contains(command.rawValue))
}
- // music_play has a required `query` and an optional `app`.
- let music = declarations.first { ($0["name"] as? String) == "music_play" }
- let parameters = music?["parameters"] as? [String: Any]
+ // skill_run requires the ids app_skill advertises; the script input is
+ // optional (some scripts take none).
+ let skillRun = declarations.first { ($0["name"] as? String) == "skill_run" }
+ let parameters = skillRun?["parameters"] as? [String: Any]
let required = parameters?["required"] as? [String] ?? []
- #expect(required.contains("query"))
- #expect(!required.contains("app"))
+ #expect(required.contains("skillID"))
+ #expect(required.contains("scriptID"))
+ #expect(!required.contains("input"))
}
@Test
@@ -104,7 +106,7 @@ struct GeminiLiveTests {
// declared name (this regressed vision_control → `default_vision_control`).
#expect(GeminiLiveVoiceController.canonicalToolName("vision_control") == "vision_control")
#expect(GeminiLiveVoiceController.canonicalToolName("default_vision_control") == "vision_control")
- #expect(GeminiLiveVoiceController.canonicalToolName("default_api.music_play") == "music_play")
+ #expect(GeminiLiveVoiceController.canonicalToolName("default_api.skill_run") == "skill_run")
#expect(GeminiLiveVoiceController.canonicalToolName("apps_list") == "apps_list")
}
@@ -137,6 +139,45 @@ struct GeminiLiveTests {
])])
}
+ @Test
+ func parsesModelTurnTextAndTurnCompletion() {
+ // Text-modality answers arrive as modelTurn text parts; they are the
+ // model's ANSWER and must surface as textOut, never as a transcript.
+ let textFrame = Data(#"""
+ {"serverContent":{"modelTurn":{"parts":[{"text":"Your largest file is movie.mkv (4.2 GB)."}]}}}
+ """#.utf8)
+ #expect(GeminiLiveProtocol.parseServerEvents(textFrame) == [
+ .textOut("Your largest file is movie.mkv (4.2 GB).")
+ ])
+
+ // turnComplete closes the turn so buffered text can flush; an audio-mode
+ // output transcription on the same frame is delivered first.
+ let completeFrame = Data(#"""
+ {"serverContent":{"turnComplete":true,"outputTranscription":{"text":"Done."}}}
+ """#.utf8)
+ #expect(GeminiLiveProtocol.parseServerEvents(completeFrame) == [
+ .finalTranscript("Done."),
+ .turnComplete
+ ])
+
+ let bareComplete = Data(#"{"serverContent":{"turnComplete":true}}"#.utf8)
+ #expect(GeminiLiveProtocol.parseServerEvents(bareComplete) == [.turnComplete])
+ }
+
+ @Test
+ @MainActor
+ func agentRunDescriptorIsAValidRegisteredEscalation() {
+ // The delegation escalation must be a valid LLM function identifier and
+ // require the structured goal it hands to the local pipeline.
+ let descriptor = GeminiLiveVoiceController.agentRunDescriptor
+ #expect(descriptor.name == "agent_run")
+ #expect(descriptor.inputSchema.keys.contains("goal"))
+ let declarations = CommandLayerFunctionDeclarations.declarations(from: [descriptor])
+ let parameters = declarations.first?["parameters"] as? [String: Any]
+ let required = parameters?["required"] as? [String] ?? []
+ #expect(required.contains("goal"))
+ }
+
@Test
func setupMessageDoesNotDoublePrefixVertexModelPath() {
let vertexModel = "projects/p/locations/global/publishers/google/models/gemini-2.0-flash-live-001"