Skip to content

Open source CapCut alternative.

TypeScript

feat(app): trace every model call and step into the thread file

David Lecab4a5048061
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
index c464b777..19532676 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
@@ -49,19 +49,33 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {
@MainActor
public final class HostedHarnessRequestUnderstanding {
private let backend: DonkeyBackendInferenceClient
+ /// Optional turn-trace sink. The one understanding call is recorded here with its clipped prompt,
+ /// clipped reply, and span, so even the pre-loop "what does this request mean?" decision is traceable
+ /// in the thread. nil means tracing is off.
+ private let trace: (any HarnessTurnTracing)?
- public init(backend: DonkeyBackendInferenceClient) {
+ public init(backend: DonkeyBackendInferenceClient, trace: (any HarnessTurnTracing)? = nil) {
self.backend = backend
+ self.trace = trace
}
/// Returns the parsed understanding, or `nil` on any provider/decode failure so the caller can
/// degrade to driving the raw command directly rather than dead-ending.
public func understand(command: String, frontmostAppName: String) async -> HarnessRequestUnderstanding? {
+ let prompt = DonkeyPrompts.requestUnderstanding(command: command, frontmostAppName: frontmostAppName)
+ let startedAt = RunTraceTimestamp.now()
do {
let response = try await backend.createResponse(responseRequest(command: command, frontmostAppName: frontmostAppName))
+ let endedAt = RunTraceTimestamp.now()
guard let text = RemoteInferenceResponseHelpers.outputText(from: response), !text.isEmpty else {
+ recordCall(prompt: prompt, response: "<no output text>",
+ finishReason: RemoteInferenceResponseHelpers.providerFinishReason(from: response),
+ status: .empty, startedAt: startedAt, endedAt: endedAt)
return nil
}
+ recordCall(prompt: prompt, response: text,
+ finishReason: RemoteInferenceResponseHelpers.providerFinishReason(from: response),
+ status: .ok, startedAt: startedAt, endedAt: endedAt)
let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)
let wire = try JSONDecoder().decode(UnderstandingWire.self, from: Data(json.utf8))
let restated = wire.restatedGoal?.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -75,10 +89,31 @@ public final class HostedHarnessRequestUnderstanding {
clarifyingQuestion: wire.clarifyingQuestion.flatMap { $0.isEmpty ? nil : $0 }
)
} catch {
+ recordCall(prompt: prompt, response: String(String(describing: error).prefix(500)),
+ finishReason: nil, status: .failed, startedAt: startedAt, endedAt: .now())
return nil
}
}
+ private func recordCall(
+ prompt: String,
+ response: String,
+ finishReason: String?,
+ status: TraceModelCallStatus,
+ startedAt: RunTraceTimestamp,
+ endedAt: RunTraceTimestamp
+ ) {
+ trace?.recordModelCall(TraceModelCall(
+ kind: .understanding,
+ prompt: prompt,
+ response: response,
+ finishReason: finishReason,
+ status: status,
+ startedAt: startedAt,
+ endedAt: endedAt
+ ))
+ }
+
// MARK: - Wire
private struct UnderstandingWire: Decodable {
diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
new file mode 100644
index 00000000..e57fb501
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
@@ -0,0 +1,101 @@
+import Foundation
+
+/// Why a model was called during a turn. Drives both the display label in the thread and how the
+/// trace manager attributes time: only `.plannerStep` calls count toward a step's "decision time",
+/// so a one-shot understanding or background summary call never inflates the next step's timing.
+public enum TraceModelCallKind: String, Codable, Equatable, Sendable {
+ /// The one-shot request-understanding call that runs before the loop.
+ case understanding
+ /// A per-step planning call (the first sample or a feedback-driven retry).
+ case plannerStep
+ /// The background call that rewrites the compacted thread summary.
+ case threadSummary
+}
+
+/// What came back from a model call. Distinguishes the failure shapes the planner already separates
+/// (empty reply vs. provider content filter vs. transport/decode error) so the thread shows which one
+/// happened instead of a generic failure.
+public enum TraceModelCallStatus: String, Codable, Equatable, Sendable {
+ /// A usable reply came back.
+ case ok
+ /// The reply carried no output text (e.g. truncated at the token cap).
+ case empty
+ /// The provider's content filter withheld the generated reply.
+ case filtered
+ /// A transport, timeout, or decode error before a reply could be used.
+ case failed
+}
+
+/// Which sensing modality produced the elements a step reasoned over — the answer to "did this step
+/// use Accessibility or AI vision?". Derived from the executed tool's own facts, not from any guess.
+public enum TraceModality: String, Codable, Equatable, Sendable {
+ /// Accessibility tree read (`ax.observe`).
+ case accessibility
+ /// Screenshot + AI vision parse (`vision.capture`).
+ case vision
+ /// The step did not sense (shell, wait, respond, verify, …).
+ case none
+}
+
+/// One model call captured for the thread trace: what was asked and what came back (both clipped by
+/// the renderer), the provider's finish reason, the attempt index for retried planning, the outcome,
+/// and the wall+monotonic span. The span is the whole point of the trace — it lets a slow turn be
+/// attributed to a specific call instead of a coarse end-to-end number.
+public struct TraceModelCall: Sendable {
+ public var kind: TraceModelCallKind
+ public var prompt: String
+ public var response: String
+ public var finishReason: String?
+ /// 1-based attempt for `.plannerStep` (1 is the first sample, 2+ are retries); nil for one-shot calls.
+ public var attempt: Int?
+ public var status: TraceModelCallStatus
+ public var startedAt: RunTraceTimestamp
+ public var endedAt: RunTraceTimestamp
+
+ public init(
+ kind: TraceModelCallKind,
+ prompt: String,
+ response: String,
+ finishReason: String? = nil,
+ attempt: Int? = nil,
+ status: TraceModelCallStatus,
+ startedAt: RunTraceTimestamp,
+ endedAt: RunTraceTimestamp
+ ) {
+ self.kind = kind
+ self.prompt = prompt
+ self.response = response
+ self.finishReason = finishReason
+ self.attempt = attempt
+ self.status = status
+ self.startedAt = startedAt
+ self.endedAt = endedAt
+ }
+
+ /// Elapsed milliseconds for this call, or nil if the monotonic clock went backwards.
+ public var durationMS: Double? { startedAt.milliseconds(until: endedAt) }
+}
+
+/// The recording surface the model boundaries depend on. The AI boundaries (`HostedHarnessStepPlanner`,
+/// `HostedHarnessRequestUnderstanding`) hold only this protocol, so they record without importing the
+/// runtime that writes files and stay testable with a recording double — the same split the harness
+/// uses for `HarnessThreadStoring`. The concrete `HarnessTurnTrace` lives in DonkeyRuntime and adds the
+/// per-step and per-turn methods the handler calls directly.
+///
+/// A nil recorder means tracing is off; every call site treats it as optional so the hot path is
+/// untouched when no trace is attached. `RunTraceTimestamp` (wall + monotonic) is the shared clock.
+public protocol HarnessTurnTracing: AnyObject, Sendable {
+ func recordModelCall(_ call: TraceModelCall)
+}
+
+public extension RunTraceTimestamp {
+ /// The current instant on both clocks. Durations are computed from the monotonic component (process
+ /// uptime, immune to wall-clock adjustments); the wall clock is for human-readable stamps. Bracket a
+ /// model call with `RunTraceTimestamp.now()` before and after to get its span.
+ static func now() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift b/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
new file mode 100644
index 00000000..64be5b1b
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
@@ -0,0 +1,136 @@
+import DonkeyContracts
+import Foundation
+
+/// The turn-trace manager: the single sink every model call and every executed step reports to, so a
+/// run's whole decision path — what was sent to the model, what came back, which sensing modality each
+/// step used, and where the time went — is traceable in the thread file.
+///
+/// It owns no file of its own; it renders through the turn's `ThreadTranscript` (kept as the sole
+/// writer of `thread.md`) and adds the timing the transcript can't see on its own. The model boundaries
+/// hold this as `any HarnessTurnTracing` and only `recordModelCall`; the command handler holds the
+/// concrete type and additionally drives `recordStep` / `recordTurnTiming`.
+///
+/// Timing model: a step's "decision time" is the sum of the planner calls made while choosing it
+/// (including retries); its "tool time" is the gap from the last planner reply to the step landing.
+/// One-shot calls (understanding, the background summary) are recorded for visibility but never counted
+/// toward a step, so they can't inflate the next step's timing.
+///
+/// Concurrency mirrors `ThreadTranscript`: a `final class` with an `NSLock` guarding the small timing
+/// accumulator, so it's callable synchronously from the planner's hot path and from the `@MainActor`
+/// step callback without actor hops.
+public final class HarnessTurnTrace: HarnessTurnTracing, @unchecked Sendable {
+ private let transcript: ThreadTranscript
+ private let now: @Sendable () -> RunTraceTimestamp
+ private let lock = NSLock()
+
+ /// Summed duration of the planner calls recorded since the last step landed — the upcoming step's
+ /// decision time. Reset each time a step is recorded.
+ private var pendingDecisionMS: Double = 0
+ /// When the most recent planner call returned, used to measure the tool time of the step it chose.
+ private var lastPlannerReplyAt: RunTraceTimestamp?
+
+ /// `now` is the clock used to stamp when a step lands (for tool-time); it defaults to the real
+ /// wall+monotonic clock and is injectable so tests can drive deterministic durations.
+ public init(
+ transcript: ThreadTranscript,
+ now: @escaping @Sendable () -> RunTraceTimestamp = RunTraceTimestamp.now
+ ) {
+ self.transcript = transcript
+ self.now = now
+ }
+
+ // MARK: - Model calls (HarnessTurnTracing)
+
+ public func recordModelCall(_ call: TraceModelCall) {
+ if call.kind == .plannerStep {
+ lock.lock()
+ pendingDecisionMS += call.durationMS ?? 0
+ lastPlannerReplyAt = call.endedAt
+ lock.unlock()
+ }
+ transcript.modelCall(
+ kindLabel: Self.label(for: call.kind),
+ prompt: call.prompt,
+ response: call.response,
+ finishReason: call.finishReason,
+ attempt: call.attempt,
+ durationMS: call.durationMS,
+ status: call.status.rawValue
+ )
+ }
+
+ // MARK: - Steps
+
+ /// Render one executed step with its timing attached: the decision time accumulated from this step's
+ /// planner calls, the tool time since the last planner reply, and the sensing modality / cache / size
+ /// derived by the caller from the executed tool's own facts.
+ public func recordStep(
+ number: Int,
+ thought: String?,
+ reason: String?,
+ tool: String,
+ input: [String: String],
+ status: String,
+ output: String,
+ planningErrors: [String],
+ modality: TraceModality,
+ cacheHit: Bool?,
+ elementCount: Int?
+ ) {
+ lock.lock()
+ let decisionMS = pendingDecisionMS > 0 ? pendingDecisionMS : nil
+ let toolMS = lastPlannerReplyAt?.milliseconds(until: now())
+ pendingDecisionMS = 0
+ lastPlannerReplyAt = nil
+ lock.unlock()
+
+ transcript.step(
+ number: number,
+ thought: thought,
+ reason: reason,
+ tool: tool,
+ input: input,
+ status: status,
+ output: output,
+ planningErrors: planningErrors,
+ decisionMS: decisionMS,
+ toolMS: toolMS,
+ modality: modality == .none ? nil : modality.rawValue,
+ cacheHit: cacheHit,
+ elementCount: elementCount
+ )
+ }
+
+ // MARK: - Turn
+
+ /// Close the turn with a compact timing summary so the whole-run cost (and the time to the first
+ /// real action) is readable at the foot of the thread alongside the per-step breakdown.
+ public func recordTurnTiming(
+ e2eTotalMS: Double,
+ timeToFirstActionMS: Double?,
+ steps: Int
+ ) {
+ var parts = ["total \(Self.durationLabel(e2eTotalMS))"]
+ if let timeToFirstActionMS {
+ parts.append("first action \(Self.durationLabel(timeToFirstActionMS))")
+ }
+ if steps > 0 {
+ parts.append("avg/step \(Self.durationLabel(e2eTotalMS / Double(steps)))")
+ }
+ transcript.systemEvent("⏱ Turn timing — \(parts.joined(separator: " · "))")
+ }
+
+ // MARK: - Helpers
+
+ private static func label(for kind: TraceModelCallKind) -> String {
+ switch kind {
+ case .understanding: return "understanding"
+ case .plannerStep: return "planner step"
+ case .threadSummary: return "thread summary"
+ }
+ }
+
+ private static func durationLabel(_ ms: Double) -> String {
+ ms >= 1_000 ? String(format: "%.1fs", ms / 1_000) : String(format: "%.0fms", ms)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
index 2a4b520a..154b5ecf 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
@@ -106,6 +106,12 @@ public final class ThreadTranscript: @unchecked Sendable {
/// retries hit while choosing this step open the block, so a step that needed recovery reads as
/// one unit instead of scattered entries. The thought is also where the model interprets the
/// previous step's output, so each block's output is reasoned about at the top of the next.
+ ///
+ /// The optional timing line closes the block with where the step's time went: how long the
+ /// model spent deciding vs. how long the tool took to run, which sensing modality the step used
+ /// (Accessibility vs. AI vision), whether that sensing came from cache, and how many elements it
+ /// saw. The trace manager fills these from real spans and the executed tool's own facts; all are
+ /// omitted when unknown so a non-sensing step (shell, wait, respond) stays clean.
public func step(
number: Int,
thought: String?,
@@ -114,7 +120,12 @@ public final class ThreadTranscript: @unchecked Sendable {
input: [String: String],
status: String,
output: String,
- planningErrors: [String] = []
+ planningErrors: [String] = [],
+ decisionMS: Double? = nil,
+ toolMS: Double? = nil,
+ modality: String? = nil,
+ cacheHit: Bool? = nil,
+ elementCount: Int? = nil
) {
var block = "\n## Step \(number) \(Self.shortStamp(Date()))\n"
for planningError in planningErrors {
@@ -130,6 +141,45 @@ public final class ThreadTranscript: @unchecked Sendable {
}
block += "\n**Action:** `\(tool)`\n```\n\(Self.inputBody(input))\n```\n"
block += "\n### 📄 Output — `\(status)`\n\n```\n\(Self.clip(output, 2_000))\n```\n"
+ if let timing = Self.timingLine(
+ decisionMS: decisionMS,
+ toolMS: toolMS,
+ modality: modality,
+ cacheHit: cacheHit,
+ elementCount: elementCount
+ ) {
+ block += "\n\(timing)\n"
+ }
+ write(block, append: true)
+ }
+
+ /// One model call, recorded so every decision and every piece of data exchanged with the model is
+ /// traceable in the thread: the clipped prompt that went out, the clipped reply that came back, the
+ /// provider's finish reason, the attempt index for retried planning, the outcome, and the call's
+ /// duration. The clip keeps a verbose prompt (full element list, tool descriptors, history) from
+ /// bloating the file while still showing what was asked. The duration is how a slow turn is pinned
+ /// to a specific call rather than a coarse end-to-end number.
+ public func modelCall(
+ kindLabel: String,
+ prompt: String,
+ response: String,
+ finishReason: String? = nil,
+ attempt: Int? = nil,
+ durationMS: Double? = nil,
+ status: String
+ ) {
+ var meta: [String] = []
+ if let duration = Self.durationLabel(durationMS) { meta.append("**Duration:** \(duration)") }
+ if let attempt { meta.append("**Attempt:** \(attempt)") }
+ if let finishReason = finishReason?.trimmingCharacters(in: .whitespacesAndNewlines), !finishReason.isEmpty {
+ meta.append("**Finish:** \(finishReason)")
+ }
+ meta.append("**Status:** \(status)")
+
+ var block = "\n### 🔮 model · \(kindLabel) \(Self.shortStamp(Date()))\n"
+ block += "\n\(meta.joined(separator: " · "))\n"
+ block += "\n**Prompt:**\n```\n\(Self.clip(prompt, 3_000))\n```\n"
+ block += "\n**Response:**\n```\n\(Self.clip(response, 2_000))\n```\n"
write(block, append: true)
}
@@ -198,6 +248,40 @@ public final class ThreadTranscript: @unchecked Sendable {
.joined(separator: "\n")
}
+ /// The compact "where did the time go" line that closes a step block, e.g.
+ /// `⏱ decision 8.4s · tool 0.3s · 👁️ vision · cache miss · 31 elems`. Returns nil when nothing is
+ /// known, so a step with no timing or sensing prints no trailing line.
+ private static func timingLine(
+ decisionMS: Double?,
+ toolMS: Double?,
+ modality: String?,
+ cacheHit: Bool?,
+ elementCount: Int?
+ ) -> String? {
+ var segments: [String] = []
+ if let decision = durationLabel(decisionMS) { segments.append("decision \(decision)") }
+ if let tool = durationLabel(toolMS) { segments.append("tool \(tool)") }
+ switch modality {
+ case "accessibility": segments.append("🌲 AX")
+ case "vision": segments.append("👁️ vision")
+ default: break
+ }
+ if let cacheHit, modality != nil, modality != "none" {
+ segments.append(cacheHit ? "cache hit" : "cache miss")
+ }
+ if let elementCount, modality != nil, modality != "none" {
+ segments.append("\(elementCount) elems")
+ }
+ guard !segments.isEmpty else { return nil }
+ return "<sub>⏱ \(segments.joined(separator: " · "))</sub>"
+ }
+
+ /// Human duration: `8.4s` for a second or more, `320ms` below that. nil for unknown/negative.
+ private static func durationLabel(_ ms: Double?) -> String? {
+ guard let ms, ms >= 0 else { return nil }
+ return ms >= 1_000 ? String(format: "%.1fs", ms / 1_000) : String(format: "%.0fms", ms)
+ }
+
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
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessTurnTraceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessTurnTraceTests.swift
new file mode 100644
index 00000000..14ed06bd
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessTurnTraceTests.swift
@@ -0,0 +1,178 @@
+import DonkeyContracts
+import Foundation
+import Testing
+@testable import DonkeyRuntime
+
+@Suite
+struct HarnessTurnTraceTests {
+ @Test
+ func recordsModelCallIntoThread() throws {
+ let transcript = makeTranscript()
+ let clock = FakeClock()
+ let trace = HarnessTurnTrace(transcript: transcript, now: clock.timestamp)
+
+ trace.recordModelCall(TraceModelCall(
+ kind: .understanding,
+ prompt: "Understand: open mail",
+ response: "{\"restatedGoal\":\"open Mail\"}",
+ finishReason: "STOP",
+ status: .ok,
+ startedAt: clock.timestamp(),
+ endedAt: clock.advanced(by: 1_500)
+ ))
+
+ let text = try threadText(transcript)
+ #expect(text.contains("### 🔮 model · understanding"))
+ #expect(text.contains("**Duration:** 1.5s"))
+ #expect(text.contains("Understand: open mail"))
+ #expect(text.contains("\"restatedGoal\":\"open Mail\""))
+ #expect(text.contains("**Status:** ok"))
+ }
+
+ @Test
+ func stepDecisionTimeSumsPlannerAttemptsAndToolTimeFollows() throws {
+ let transcript = makeTranscript()
+ let clock = FakeClock()
+ let trace = HarnessTurnTrace(transcript: transcript, now: clock.timestamp)
+
+ // Two planning attempts for the same step: 6s then 2.4s of decision time.
+ let a0 = clock.timestamp()
+ let a1 = clock.advanced(by: 6_000)
+ trace.recordModelCall(plannerCall(attempt: 1, started: a0, ended: a1))
+ let b0 = clock.timestamp()
+ let b1 = clock.advanced(by: 2_400)
+ trace.recordModelCall(plannerCall(attempt: 2, started: b0, ended: b1))
+
+ // The tool then runs for 300ms before the step lands.
+ clock.advance(by: 300)
+ trace.recordStep(
+ number: 1,
+ thought: nil,
+ reason: "Reading the screen.",
+ tool: "vision.capture",
+ input: [:],
+ status: "succeeded",
+ output: "Captured 12 element(s).",
+ planningErrors: [],
+ modality: .vision,
+ cacheHit: true,
+ elementCount: 12
+ )
+
+ let text = try threadText(transcript)
+ // 6000 + 2400 = 8400ms decision; 300ms tool; vision + cache hit + element count.
+ #expect(text.contains("⏱ decision 8.4s · tool 300ms · 👁️ vision · cache hit · 12 elems"))
+ }
+
+ @Test
+ func understandingDoesNotInflateNextStepDecisionTime() throws {
+ let transcript = makeTranscript()
+ let clock = FakeClock()
+ let trace = HarnessTurnTrace(transcript: transcript, now: clock.timestamp)
+
+ // A long understanding call before the loop must not count toward step 1's decision time.
+ let u0 = clock.timestamp()
+ let u1 = clock.advanced(by: 9_000)
+ trace.recordModelCall(TraceModelCall(
+ kind: .understanding, prompt: "p", response: "r", status: .ok, startedAt: u0, endedAt: u1
+ ))
+ let p0 = clock.timestamp()
+ let p1 = clock.advanced(by: 1_000)
+ trace.recordModelCall(plannerCall(attempt: 1, started: p0, ended: p1))
+ clock.advance(by: 50)
+ trace.recordStep(
+ number: 1, thought: nil, reason: nil, tool: "ax.observe", input: [:],
+ status: "succeeded", output: "ok", planningErrors: [], modality: .accessibility,
+ cacheHit: nil, elementCount: 7
+ )
+
+ let text = try threadText(transcript)
+ #expect(text.contains("decision 1.0s"))
+ #expect(!text.contains("decision 10.0s"))
+ #expect(text.contains("🌲 AX · 7 elems"))
+ }
+
+ @Test
+ func nonSensingStepShowsNoModalityOrCache() throws {
+ let transcript = makeTranscript()
+ let clock = FakeClock()
+ let trace = HarnessTurnTrace(transcript: transcript, now: clock.timestamp)
+
+ let p0 = clock.timestamp()
+ let p1 = clock.advanced(by: 500)
+ trace.recordModelCall(plannerCall(attempt: 1, started: p0, ended: p1))
+ clock.advance(by: 20)
+ trace.recordStep(
+ number: 1, thought: nil, reason: nil, tool: "shell_exec", input: ["command": "ls"],
+ status: "succeeded", output: "ok", planningErrors: [], modality: .none,
+ cacheHit: true, elementCount: 99
+ )
+
+ let text = try threadText(transcript)
+ // Exact timing line: decision + tool only, no modality/cache/element segments. (Broad "vision"
+ // checks would false-match the planner call's own JSON response rendered above.)
+ #expect(text.contains("<sub>⏱ decision 500ms · tool 20ms</sub>"))
+ #expect(!text.contains("👁️ vision"))
+ #expect(!text.contains("🌲 AX"))
+ #expect(!text.contains("cache hit"))
+ #expect(!text.contains("99 elems"))
+ }
+
+ @Test
+ func recordsTurnTimingSummary() throws {
+ let transcript = makeTranscript()
+ let trace = HarnessTurnTrace(transcript: transcript)
+ trace.recordTurnTiming(e2eTotalMS: 12_000, timeToFirstActionMS: 3_400, steps: 4)
+
+ let text = try threadText(transcript)
+ #expect(text.contains("⏱ Turn timing — total 12.0s · first action 3.4s · avg/step 3.0s"))
+ }
+
+ // MARK: - Helpers
+
+ private func plannerCall(attempt: Int, started: RunTraceTimestamp, ended: RunTraceTimestamp) -> TraceModelCall {
+ TraceModelCall(
+ kind: .plannerStep,
+ prompt: "GOAL: do the thing",
+ response: "{\"tool\":\"vision.capture\"}",
+ finishReason: "STOP",
+ attempt: attempt,
+ status: .ok,
+ startedAt: started,
+ endedAt: ended
+ )
+ }
+
+ private func makeTranscript() -> ThreadTranscript {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("harness-turn-trace-tests-\(UUID().uuidString)", isDirectory: true)
+ return ThreadTranscript(id: UUID().uuidString, root: root)
+ }
+
+ private func threadText(_ transcript: ThreadTranscript) throws -> String {
+ try String(contentsOfFile: transcript.threadPath, encoding: .utf8)
+ }
+}
+
+/// A deterministic monotonic clock for trace-timing tests: durations are exact because both the call
+/// spans and the manager's step-land stamp come from this same advanceable source.
+private final class FakeClock: @unchecked Sendable {
+ private let lock = NSLock()
+ private var nanos: UInt64 = 0
+
+ func timestamp() -> RunTraceTimestamp {
+ lock.lock(); defer { lock.unlock() }
+ return RunTraceTimestamp(wallClock: Date(timeIntervalSince1970: 0), monotonicUptimeNanoseconds: nanos)
+ }
+
+ @discardableResult
+ func advance(by milliseconds: Double) -> RunTraceTimestamp {
+ lock.lock()
+ nanos += UInt64(milliseconds * 1_000_000)
+ lock.unlock()
+ return timestamp()
+ }
+
+ /// Advance and return the new instant — reads as "the call ended `ms` later".
+ func advanced(by milliseconds: Double) -> RunTraceTimestamp { advance(by: milliseconds) }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ThreadTranscriptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ThreadTranscriptTests.swift
index 31d1b6a8..694052f4 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ThreadTranscriptTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ThreadTranscriptTests.swift
@@ -110,6 +110,70 @@ struct ThreadTranscriptTests {
#expect(text.contains("💬 assistant · response"))
}
+ @Test
+ func stepRendersTimingLineWithModalityCacheAndElements() throws {
+ let transcript = makeTranscript()
+ transcript.step(
+ number: 2,
+ thought: nil,
+ reason: "Reading the screen.",
+ tool: "vision.capture",
+ input: [:],
+ status: "succeeded",
+ output: "Captured 31 element(s).",
+ decisionMS: 8_400,
+ toolMS: 320,
+ modality: "vision",
+ cacheHit: false,
+ elementCount: 31
+ )
+
+ let text = try threadText(transcript)
+ #expect(text.contains("⏱ decision 8.4s · tool 320ms · 👁️ vision · cache miss · 31 elems"))
+ }
+
+ @Test
+ func stepOmitsTimingLineWhenNothingIsKnown() throws {
+ let transcript = makeTranscript()
+ transcript.step(
+ number: 1,
+ thought: nil,
+ reason: nil,
+ tool: "shell_exec",
+ input: ["command": "ls"],
+ status: "succeeded",
+ output: "ok"
+ )
+
+ let text = try threadText(transcript)
+ #expect(!text.contains("⏱"))
+ }
+
+ @Test
+ func modelCallRendersClippedPromptResponseAndMeta() throws {
+ let transcript = makeTranscript()
+ transcript.modelCall(
+ kindLabel: "planner step",
+ prompt: "GOAL: do the thing\nHISTORY: ...",
+ response: "{\"tool\":\"ax.observe\",\"input\":{}}",
+ finishReason: "STOP",
+ attempt: 2,
+ durationMS: 1_240,
+ status: "ok"
+ )
+
+ let text = try threadText(transcript)
+ #expect(text.contains("### 🔮 model · planner step"))
+ #expect(text.contains("**Duration:** 1.2s"))
+ #expect(text.contains("**Attempt:** 2"))
+ #expect(text.contains("**Finish:** STOP"))
+ #expect(text.contains("**Status:** ok"))
+ #expect(text.contains("**Prompt:**"))
+ #expect(text.contains("GOAL: do the thing"))
+ #expect(text.contains("**Response:**"))
+ #expect(text.contains("\"tool\":\"ax.observe\""))
+ }
+
private func makeTranscript() -> ThreadTranscript {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("thread-transcript-tests-\(UUID().uuidString)", isDirectory: true)