Skip to content

Open source CapCut alternative.

TypeScript

feat(app): record the complete session in the thread transcript

David Le1f058b40e01e
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 71f23e56..2e30082c 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -267,6 +267,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
) async -> UserQueryCommandHandlingResult {
guard permissionPolicy.allowedCapabilities.contains(.input) else {
return await failHarnessRun(
+ command: command,
response: "Vision navigation needs input permission, which isn't granted.",
reason: "inputNotPermitted",
appName: "",
@@ -277,6 +278,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
guard let target = MacWindowResolver().frontmostUserAppTarget() else {
return await failHarnessRun(
+ command: command,
response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",
reason: "noFrontmostApp",
appName: "",
@@ -290,6 +292,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {
return await failHarnessRun(
+ command: command,
response: "The vision backend isn't configured (set DONKEY_WEB_BASE_URL), so I couldn't navigate by vision.",
reason: "visionBackendUnavailable",
appName: frontmostAppName,
@@ -419,6 +422,20 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
let transcript = ThreadTranscript(id: taskID)
transcript.begin(id: taskID, app: appName)
transcript.userMessage(command)
+ // The thread is the COMPLETE session record: the parsed understanding (or its absence) is part
+ // of the conversation, not just an internal step.
+ if let understanding {
+ var understood = "Understood request: \(understanding.restatedGoal ?? command)"
+ if let app = understanding.targetAppName, !app.isEmpty {
+ understood += " · target app: \(app)"
+ }
+ if understanding.needsClarification, let question = understanding.clarifyingQuestion, !question.isEmpty {
+ understood += " · needs clarification: \(question)"
+ }
+ transcript.systemEvent(understood)
+ } else {
+ transcript.systemEvent("Understanding was unavailable (timed out or failed); driving the raw command.")
+ }
VisionGroundingLog.emit("thread traceID=\(traceID) path=\(transcript.threadPath)")
// Always set onStep so every turn is recorded; the overlay narration/cursor is layered on top
@@ -426,6 +443,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
let onStep: (@Sendable (HarnessStepExecutionResult) async -> Void)? = { (step: HarnessStepExecutionResult) async -> Void in
await MainActor.run {
let narration = Self.stepNarration(for: step, planner: planner)
+ // Planning failures (unusable replies, retries) are part of the session and must be
+ // readable in the thread — a step that ends in run.failSafe is otherwise a mystery.
+ for planningError in planner.lastPlanningErrors {
+ transcript.error(planningError)
+ }
if let result = step.toolResult {
// The thread file gets the model's full thought summary (when thinking is on);
// the overlay/progress gets only the clipped one-line narration below. The full
@@ -486,6 +508,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// thread summary. A deterministic summary lands immediately; an LLM-written one replaces it in
// the background so the result isn't delayed by the summary call.
let finalDetail = runSteps.last?.toolResult?.summary ?? finalTask?.goal ?? command
+ transcript.systemEvent("Run finished: \(outcomeReason) after \(turns) step(s).")
transcript.response(finalDetail)
transcript.writeSummary(Self.deterministicThreadSummary(
command: command, app: appName, outcome: outcomeReason, steps: runSteps, finalDetail: finalDetail
@@ -630,7 +653,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
/// Fail-safe exit for the vision-navigation route when it can't even start (no frontmost app,
/// backend unconfigured, input not permitted). Mirrors the other non-local routes' lifecycle.
+ /// Even an aborted start gets a thread file: the thread is the session's complete record, and a
+ /// turn that produced nothing on disk is indistinguishable from a turn that never happened.
private func failHarnessRun(
+ command: String,
response: String,
reason: String,
appName: String,
@@ -639,6 +665,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
preparedTurnMetadata: [String: String]
) async -> UserQueryCommandHandlingResult {
VisionGroundingLog.emit("aborted traceID=\(traceID) reason=\(reason) app=\(appName)")
+ let transcript = ThreadTranscript(id: taskID)
+ transcript.begin(id: taskID, app: appName)
+ transcript.userMessage(command)
+ transcript.error("Run could not start (\(reason)).")
+ transcript.response(response)
let decision = AppHarnessDecision(
kind: .respond,
message: response,
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
index bc976559..f0bdedbb 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
@@ -39,6 +39,10 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
/// The model's full thought summary for the most recent step, when thinking is enabled. Persisted
/// to the thread transcript (not fed back into the per-step prompt, so context stays bounded).
public private(set) var lastThinking: String?
+ /// Planning failures hit while choosing the most recent step (unusable replies, retries, the
+ /// reason a step fell back to run.failSafe). Cleared at the start of each planNextStep; the route
+ /// writes them into the thread transcript so a failed step is diagnosable from the thread alone.
+ public private(set) var lastPlanningErrors: [String] = []
/// Names of the registered read-only tools (observe/verify/respond/lifecycle), derived from each
/// descriptor's safety class. A tool counts as an "action" for first-action timing exactly when it
@@ -95,12 +99,16 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
// empty tool name never reads as completion (a refusal/truncation would otherwise record as
// success); the runtime's stall guard remains the final backstop for genuine loops.
var retryNote: String?
+ lastPlanningErrors = []
let lastAttempt = Self.maxPlanAttempts - 1
for attempt in 0...lastAttempt {
let decision: Decision
do {
decision = try await decide(task: task, retryNote: retryNote, attempt: attempt)
} catch {
+ lastPlanningErrors.append(
+ "planning attempt \(attempt + 1)/\(Self.maxPlanAttempts) failed: \(String(describing: error).prefix(300))"
+ )
guard attempt < lastAttempt else { break }
retryNote = "Your previous reply could not be used (\(String(describing: error).prefix(200))). "
+ "Reply with exactly ONE JSON object naming one tool from AVAILABLE TOOLS, with every "
@@ -110,6 +118,9 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
lastNarration = decision.reason.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration
lastThinking = decision.thinking.flatMap { $0.isEmpty ? nil : $0 }
guard let toolName = decision.tool.flatMap({ $0.isEmpty ? nil : $0 }) else {
+ lastPlanningErrors.append(
+ "planning attempt \(attempt + 1)/\(Self.maxPlanAttempts): reply named no tool"
+ )
guard attempt < lastAttempt else {
return HarnessToolCall(name: "run.failSafe", input: ["reason": "plannerReturnedNoTool"])
}
@@ -125,6 +136,9 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
let required = requiredInputKeys[toolName], !required.isEmpty,
Set(providedInput.keys).isDisjoint(with: required) {
let keys = required.sorted().joined(separator: ", ")
+ lastPlanningErrors.append(
+ "planning attempt \(attempt + 1)/\(Self.maxPlanAttempts): chose \(toolName) without its required input (\(keys))"
+ )
retryNote = "Your previous reply chose \(toolName) but included none of its required input "
+ "(\(keys)). Re-issue \(toolName) with that input filled in, or choose a different tool."
continue
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
index 067fff4d..a260aecc 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
@@ -26,6 +26,8 @@ public final class ThreadTranscript: @unchecked Sendable {
case toolCall // the assistant invoking a tool
case toolResult // a tool's output
case response // the assistant's answer to the user
+ case event // a session lifecycle event (understanding parsed, run finished, …)
+ case error // something the session hit that wasn't a tool result (planner retry, aborted start, …)
}
public let directory: URL
@@ -96,6 +98,20 @@ public final class ThreadTranscript: @unchecked Sendable {
appendEntry(role: .assistant, kind: .response, title: nil, body: text, fenced: false)
}
+ /// A session lifecycle event. The thread file is the COMPLETE record of a session — not only the
+ /// tool turns — so things like the parsed understanding and the run's final outcome land here too.
+ public func systemEvent(_ text: String) {
+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
+ appendEntry(role: .system, kind: .event, title: nil, body: Self.clip(text, 2_000), fenced: false)
+ }
+
+ /// An error the session hit outside a tool result — a planner reply that couldn't be used, a run
+ /// that aborted before it started. These must be readable in the thread, not buried in logs.
+ public func error(_ text: String) {
+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
+ appendEntry(role: .system, kind: .error, title: nil, body: Self.clip(text, 2_000), fenced: false)
+ }
+
/// Persist the compacted thread summary (callers generate it).
public func writeSummary(_ markdown: String) {
lock.lock(); defer { lock.unlock() }
@@ -131,6 +147,7 @@ public final class ThreadTranscript: @unchecked Sendable {
case (.assistant, .toolCall): return "🔧"
case (.assistant, .response): return "💬"
case (.tool, _): return "📄"
+ case (.system, .error): return "⚠️"
case (.system, _): return "⚙️"
default: return "•"
}