Open source CapCut alternative.
TypeScript
feat(app): write the real conversation thread to markdown; block duplicate-action loops
David Le061d2f54e258
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex acaca56f..a4fc3b37 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -410,29 +410,42 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// planner's one-line reason, falling back to the tool's own summary), and after each step that// physically moved the pointer (a click), animate the overlay cursor traveling to that exact// target, so the visualization tracks what the harness is actually doing.- var onStep: (@Sendable (HarnessStepExecutionResult) async -> Void)?- if visualize != nil || progress != nil {- onStep = { (step: HarnessStepExecutionResult) async -> Void in- await MainActor.run {- // Every step narrates through the spawn label (a lightweight text update), so the- // user is kept informed even on steps that don't move the pointer — observe, shell,- // wait, verify. The cursor itself only travels (a heavier window-animating overlay- // playback) on steps that actually moved it; re-running that playback every step- // thrashes window layout, so it stays gated to real pointer moves.- let narration = Self.stepNarration(for: step, planner: planner)- if let progress, let narration {- progress(narration)- }- guard let present = visualize else { return }- let screenSize = (NSScreen.main ?? NSScreen.screens.first)?.frame.size ?? .zero- guard let plan = Self.cursorVisualizationPlan(- for: step,- appName: appName,- traceID: traceID,- screenSize: screenSize- ) else { return }- present(plan)+ // The thread: the real conversation record (like ChatGPT/Claude), written live as markdown —+ // user request, the assistant's thinking, each tool call and result, and the final answer — so+ // the full reasoning trace is readable (and renderable to the user later), and a stuck run is+ // visible instead of a mystery.+ let transcript = ThreadTranscript(id: taskID)+ transcript.begin(id: taskID, app: appName)+ transcript.userMessage(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+ // when a UI is attached.+ let onStep: (@Sendable (HarnessStepExecutionResult) async -> Void)? = { (step: HarnessStepExecutionResult) async -> Void in+ await MainActor.run {+ let narration = Self.stepNarration(for: step, planner: planner)+ if let result = step.toolResult {+ transcript.thinking(narration)+ transcript.toolCall(tool: result.toolName, input: step.task.toolHistory.last?.call.input ?? [:])+ transcript.toolResult(tool: result.toolName, status: result.status.rawValue, output: result.summary)}+ // Every step narrates through the spawn label (a lightweight text update), so the user+ // is kept informed even on steps that don't move the pointer — observe, shell, wait,+ // verify. The cursor itself only travels (a heavier window-animating overlay playback)+ // on steps that actually moved it; re-running that playback every step thrashes window+ // layout, so it stays gated to real pointer moves.+ if let progress, let narration {+ progress(narration)+ }+ guard let present = visualize else { return }+ let screenSize = (NSScreen.main ?? NSScreen.screens.first)?.frame.size ?? .zero+ guard let plan = Self.cursorVisualizationPlan(+ for: step,+ appName: appName,+ traceID: traceID,+ screenSize: screenSize+ ) else { return }+ present(plan)}}// Step budget is progress-based, not a fixed count: the runtime keeps going while the task@@ -464,6 +477,31 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {"complete traceID=\(traceID) app=\(appName) completed=\(completed) reason=\(outcomeReason) turns=\(turns) usedCache=\(anyTurnUsedCache) parseMS=\(Self.formatLatency(totalParseMS)) e2eTotalMS=\(Self.formatLatency(e2eTotalMS)) timeToFirstActionMS=\(Self.formatLatency(timeToFirstActionMS ?? 0)) avgPerTurnMS=\(Self.formatLatency(averagePerTurnMS))")+ // Record the assistant's final answer to close the turn, then write a compacted, structured+ // 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.response(finalDetail)+ transcript.writeSummary(Self.deterministicThreadSummary(+ command: command, app: appName, outcome: outcomeReason, steps: runSteps, finalDetail: finalDetail+ ))+ let threadText = (try? String(contentsOfFile: transcript.threadPath, encoding: .utf8)) ?? ""+ if !threadText.isEmpty {+ Task.detached {+ let prompt = """+ Summarize this conversation thread into a compact markdown brief with these exact \+ sections (omit a section only if truly empty): ## Goal, ## Progress, ## Key Decisions, \+ ## Next Steps, ## Critical Context. Be concrete and short.++ THREAD:+ \(threadText)+ """+ if let enhanced = await textGenerator.generate(prompt), !enhanced.isEmpty {+ transcript.writeSummary(enhanced)+ }+ }+ }+let baseMetadata = preparedTurnMetadata.merging(["appHarness.router": "harness","harness.app": appName,@@ -629,6 +667,44 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// MARK: - Generic Harness Task Execution+ /// A compacted, structured thread summary built deterministically from the run — written+ /// immediately, then replaced by an LLM-written version in the background. Mirrors the Hermes+ /// compaction sections so the summary stays consistent whether or not the LLM call lands.+ static func deterministicThreadSummary(+ command: String,+ app: String,+ outcome: String,+ steps: [HarnessStepExecutionResult],+ finalDetail: String+ ) -> String {+ let keyDecisions = steps.compactMap { step -> String? in+ guard let result = step.toolResult else { return nil }+ return "- `\(result.toolName)` → \(result.status.rawValue): \(result.summary.prefix(120))"+ }.joined(separator: "\n")+ let progress = outcome == "ok" ? "Completed." : "Ended: \(outcome)."+ let nextSteps = outcome == "ok"+ ? "- None — task complete."+ : "- Resume or retry; the task did not complete."+ return """+ # Thread Summary++ ## Goal+ \(command)++ ## Progress+ \(progress) \(steps.count) step(s)\(app.isEmpty ? "" : " in \(app)").++ ## Key Decisions+ \(keyDecisions.isEmpty ? "- (none)" : keyDecisions)++ ## Next Steps+ \(nextSteps)++ ## Critical Context+ \(finalDetail)+ """+ }+private func logSubmittedCommand(_ command: String,traceID: String,diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex 7dc2bf3b..19a5fd03 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -205,6 +205,9 @@ public enum DonkeyPrompts {conversation.respond (set input.response), then run.complete.- If a required detail is missing and you cannot safely proceed, use user.clarify(set input.question).+ - Once a state-changing action SUCCEEDS (a note created, a message sent, a file moved), do NOT+ do it again — repeating it, even with slightly different content, just makes duplicates.+ Verify the result and run.complete. Re-acting after success is the most common way to loop.- Verification must be evidence-backed: after acting, confirm the effect (a shell command'soutput/exit code, a re-observe, or state.verify) BEFORE choosing run.complete. A focused appis not evidence; only complete once the goal is confirmed by what you can see.diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftindex 5fe41afe..383968eb 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -234,6 +234,21 @@ public struct GenericHarnessRuntime: Sendable {return HarnessStepExecutionResult(task: updatedTask, toolResult: blocked, stoppedForGate: false)}+ // Don't re-run a state-changing action that already succeeded with the exact same input —+ // that just duplicates the effect (e.g. creating the same note 16 times). Block it before it+ // executes and tell the planner to verify and complete instead. Read-only tools are exempt+ // (re-observing is idempotent and useful).+ if let blocked = await duplicateActionRejection(call: call, task: task) {+ guard let updatedTask = await coordinator.recordToolResult(+ taskID: taskID,+ call: call,+ result: blocked+ ) else {+ return nil+ }+ return HarnessStepExecutionResult(task: updatedTask, toolResult: blocked, stoppedForGate: false)+ }+let result = await registry.execute(call,taskID: taskID,@@ -367,6 +382,34 @@ public struct GenericHarnessRuntime: Sendable {)}+ /// Rejects a state-changing call whose exact (tool, input) already succeeded earlier in this run —+ /// re-running it only duplicates the side effect. Read-only tools and lifecycle calls are exempt.+ /// Returns a failed result that tells the planner to verify and complete instead of repeating.+ private func duplicateActionRejection(+ call: HarnessToolCall,+ task: HarnessTaskState+ ) async -> HarnessToolResult? {+ guard !call.name.hasPrefix("run."), !call.name.hasPrefix("conversation.") else { return nil }+ let readOnlyNames = Set(+ await registry.descriptors().filter { $0.safetyClass == .readOnly }.map(\.name)+ )+ guard !readOnlyNames.contains(call.name) else { return nil }+ let signature = Self.canonicalInput(call.input)+ let alreadySucceeded = task.toolHistory.contains { record in+ record.resultStatus == .succeeded+ && record.call.name == call.name+ && Self.canonicalInput(record.call.input) == signature+ }+ guard alreadySucceeded else { return nil }+ return HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .failed,+ summary: "Already done: `\(call.name)` ran with this exact input and succeeded earlier in this run. Repeating it duplicates the effect. Verify the result (a read/observe or state.verify), then run.complete — do not run this again.",+ metadata: ["reason": "duplicateAction"]+ )+ }+private func applyLifecycleResult(taskID: String,call: HarnessToolCall,diff --git a/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swiftnew file mode 100644index 00000000..cb642ec5--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift@@ -0,0 +1,156 @@+import Foundation++/// The canonical, human-readable record of a thread — the real conversation, the way ChatGPT or+/// Claude keeps one, not a debug dump. Every turn is captured with who said it and what kind of+/// message it is (a user request, the assistant thinking, a tool call, a tool result, the assistant's+/// answer), so you can read the whole reasoning trace and, later, render it to the user.+///+/// Durable metadata stays in Core Data; the *contents* live here in markdown, one folder per thread+/// under `~/Library/Application Support/Donkey/Threads/<id>/`:+///+/// - `thread.md` — the full conversation, appended live (`tail -f` to watch it unfold).+/// - `summary.md` — a compacted, structured summary of the thread.+public final class ThreadTranscript: @unchecked Sendable {+ /// Who an entry is from.+ public enum Role: String, Sendable {+ case user+ case assistant+ case tool+ case system+ }++ /// What kind of message it is.+ public enum Kind: String, Sendable {+ case message // a plain user/system message+ case thinking // the assistant's reasoning for the next move+ case toolCall // the assistant invoking a tool+ case toolResult // a tool's output+ case response // the assistant's answer to the user+ }++ public let directory: URL+ private let threadURL: URL+ private let summaryURL: URL+ private let lock = NSLock()+ private let started = Date()++ public static func defaultRoot() -> URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("Threads", isDirectory: true)+ }++ public init(id: String, root: URL? = nil) {+ let base = (root ?? Self.defaultRoot()).appendingPathComponent(Self.slug(id), isDirectory: true)+ try? FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)+ self.directory = base+ self.threadURL = base.appendingPathComponent("thread.md")+ self.summaryURL = base.appendingPathComponent("summary.md")+ }++ public var threadPath: String { threadURL.path }++ /// Start the thread file with its header (only written once; later turns append).+ public func begin(id: String, app: String) {+ guard !FileManager.default.fileExists(atPath: threadURL.path) else { return }+ let header = """+ # Thread \(id)++ - **App:** \(app.isEmpty ? "(system tools / none)" : app)+ - **Started:** \(Self.stamp(started))++ """+ write(header, append: false)+ }++ /// A user request opens a turn.+ public func userMessage(_ text: String) {+ appendEntry(role: .user, kind: .message, title: nil, body: text, fenced: false)+ }++ /// The assistant's reasoning before a tool call.+ public func thinking(_ text: String?) {+ guard let text = text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else { return }+ appendEntry(role: .assistant, kind: .thinking, title: nil, body: text, fenced: false)+ }++ /// The assistant invoking a tool, with its input.+ public func toolCall(tool: String, input: [String: String]) {+ let body = input.isEmpty+ ? "(no input)"+ : input.sorted { $0.key < $1.key }+ .map { "\($0.key): \(Self.clip($0.value, 600))" }+ .joined(separator: "\n")+ appendEntry(role: .assistant, kind: .toolCall, title: tool, body: body, fenced: true)+ }++ /// A tool's result.+ public func toolResult(tool: String, status: String, output: String) {+ appendEntry(role: .tool, kind: .toolResult, title: "\(tool) → \(status)", body: Self.clip(output, 2_000), fenced: true)+ }++ /// The assistant's answer to the user, closing a turn.+ public func response(_ text: String) {+ appendEntry(role: .assistant, kind: .response, title: nil, body: text, fenced: false)+ }++ /// Persist the compacted thread summary (callers generate it).+ public func writeSummary(_ markdown: String) {+ lock.lock(); defer { lock.unlock() }+ try? markdown.write(to: summaryURL, atomically: true, encoding: .utf8)+ }++ // MARK: - Rendering++ /// One labeled block: a heading with role + kind (+ optional title), then the body.+ private func appendEntry(role: Role, kind: Kind, title: String?, body: String, fenced: Bool) {+ let label = "\(Self.icon(role, kind)) \(role.rawValue) · \(kind.rawValue)"+ let heading = title.map { "\(label) · `\($0)`" } ?? label+ let rendered = fenced ? "```\n\(body)\n```" : body+ let block = "\n### \(heading) \(Self.shortStamp(Date()))\n\n\(rendered)\n"+ write(block, append: true)+ }++ private func write(_ text: String, append: Bool) {+ lock.lock(); defer { lock.unlock() }+ if append, let handle = try? FileHandle(forWritingTo: threadURL) {+ handle.seekToEndOfFile()+ handle.write(Data(text.utf8))+ try? handle.close()+ } else {+ try? text.write(to: threadURL, atomically: true, encoding: .utf8)+ }+ }++ private static func icon(_ role: Role, _ kind: Kind) -> String {+ switch (role, kind) {+ case (.user, _): return "👤"+ case (.assistant, .thinking): return "🧠"+ case (.assistant, .toolCall): return "🔧"+ case (.assistant, .response): return "💬"+ case (.tool, _): return "📄"+ case (.system, _): return "⚙️"+ default: return "•"+ }+ }++ private static func clip(_ text: String, _ max: Int) -> String {+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.count > max ? String(trimmed.prefix(max)) + " …[clipped]" : trimmed+ }++ private static func slug(_ value: String) -> String {+ let s = value.lowercased().map { $0.isLetter || $0.isNumber ? $0 : "-" }+ return String(s).isEmpty ? "thread" : String(s)+ }++ private static func stamp(_ date: Date) -> String {+ let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime]+ return f.string(from: date)+ }++ private static func shortStamp(_ date: Date) -> String {+ let f = DateFormatter(); f.dateFormat = "HH:mm:ss"+ return "<sub>\(f.string(from: date))</sub>"+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 14d88c74..69d15c1e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -339,6 +339,29 @@ struct GenericHarnessTests {#expect(finalTask?.status == .failedSafe)}+ @Test+ func runBlocksRepeatingAnAlreadySucceededAction() async {+ // A planner that keeps re-issuing the same successful state-changing call (the duplicate-note+ // loop) must only execute it once; the repeats are blocked before they run, and the run stops.+ struct StubDuplicatePlanner: HarnessNextStepPlanning {+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ HarnessToolCall(name: "test.act", input: ["command": "make note"])+ }+ }+ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(stubTool(name: "test.act", safetyClass: .guardedInput))+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(id: "task-dup", threadID: "t", goal: "dup", grantedPermissions: [.lifecycle])++ let steps = await runtime.run(taskID: task.id, planner: StubDuplicatePlanner(), maxSteps: 30)++ // The action executes exactly once; everything after is a blocked duplicate, so no 16 copies.+ let realRuns = steps.filter { $0.toolResult?.toolName == "test.act" && $0.toolResult?.status == .succeeded }+ #expect(realRuns.count == 1)+ #expect(steps.contains { $0.toolResult?.metadata["reason"] == "duplicateAction" })+ }+@Testfunc runStopsWhenStepsStopMakingProgress() async {// Distinct calls that each succeed but never change the world model are still a stall.