Skip to content

Open source CapCut alternative.

TypeScript

test(harness): add a prompt eval harness

David Lee3a1b1e49822
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEvalRunner.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEvalRunner.swift
new file mode 100644
index 00000000..9db82a4d
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEvalRunner.swift
@@ -0,0 +1,236 @@
+import DonkeyAI
+import DonkeyContracts
+import DonkeyHarness
+import DonkeyRuntime
+import Foundation
+
+/// Prompt/planner evaluation harness: run the REAL agent loop end to end against the REAL hosted model,
+/// with the UI and the system stubbed out, and capture the tool calls the model chooses. It exists to
+/// answer one question per scenario — given this user turn, what does input → LLM → output actually
+/// produce? — so a change to the doctrine, the understanding boundary, a tool descriptor, or a skill can
+/// be evaluated, not eyeballed in the running app.
+///
+/// What is real: the request-understanding boundary, the per-step planner, every prompt and tool
+/// descriptor, and the full `GenericHarnessRuntime` loop (planning, stall guards, completion-evidence
+/// gate). What is stubbed: the executors. No command runs, no file is touched, no app is driven — each
+/// tool hands the planner a scripted observation instead, so the loop keeps moving and we record the plan.
+///
+/// These tests hit the network and cost model tokens, so they are opt-in exactly like the live smoke
+/// tests. Run with:
+///
+/// env DONKEY_PROMPT_EVAL=1 DONKEY_WEB_BASE_URL=http://localhost:3000 DONKEY_DEV_AUTH_BYPASS=1 \
+/// DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \
+/// swift test --filter HarnessPromptEvalTests
+///
+/// Add a scenario by constructing another `HarnessEvalScenario` (see `HarnessPromptEvalTests`); the
+/// runner is generic over the prompt and the scripted replies.
+
+/// A scripted reply a stubbed tool hands back to the planner. The system is stubbed, so a tool never
+/// touches the real Mac — it returns the observation the scenario wants the model to see next.
+struct HarnessEvalStub: Sendable {
+ var status: HarnessToolResultStatus = .succeeded
+ var summary: String
+ var facts: [String: String] = [:]
+ var visibleText: [String: String] = [:]
+
+ static func ok(
+ _ summary: String,
+ facts: [String: String] = [:],
+ visibleText: [String: String] = [:]
+ ) -> HarnessEvalStub {
+ HarnessEvalStub(status: .succeeded, summary: summary, facts: facts, visibleText: visibleText)
+ }
+
+ static func failed(_ summary: String) -> HarnessEvalStub {
+ HarnessEvalStub(status: .failed, summary: summary)
+ }
+}
+
+/// One prompt-eval scenario: a user turn plus scripted tool replies. `respond` returns a scripted reply
+/// for a given tool call, or nil to fall back to the runner's default (which serves the real built-in
+/// skill content for skill lookups and a generic success otherwise). Scenarios are data — add them
+/// freely; the runner does not change.
+struct HarnessEvalScenario: Sendable {
+ var name: String
+ var prompt: String
+ var frontmostApp: String
+ /// Runaway backstop. Each step is a real model call, so keep it modest; the loop normally ends when
+ /// the planner calls `run.complete`.
+ var maxSteps: Int
+ var respond: @Sendable (HarnessToolCall) -> HarnessEvalStub?
+
+ init(
+ name: String,
+ prompt: String,
+ frontmostApp: String = "Finder",
+ maxSteps: Int = 16,
+ respond: @escaping @Sendable (HarnessToolCall) -> HarnessEvalStub? = { _ in nil }
+ ) {
+ self.name = name
+ self.prompt = prompt
+ self.frontmostApp = frontmostApp
+ self.maxSteps = maxSteps
+ self.respond = respond
+ }
+}
+
+/// The captured outcome of a scenario: what the model understood, the ordered tool calls it chose, and
+/// the final lifecycle status — input → LLM → output, ready to assert on.
+struct HarnessEvalRun {
+ var understanding: HarnessRequestUnderstanding?
+ var records: [HarnessToolCallRecord]
+ var finalStatus: HarnessAgentStatus
+
+ var calls: [HarnessToolCall] { records.map(\.call) }
+ var toolNames: [String] { calls.map(\.name) }
+ var shellCommands: [String] { calls.filter { $0.name == "shell_exec" }.compactMap { $0.input["command"] } }
+ var completed: Bool { finalStatus == .completed }
+
+ func used(_ tool: String) -> Bool { toolNames.contains(tool) }
+
+ /// True if some `shell_exec` command contains all of the given substrings (case-insensitive) — the
+ /// usual shape of a plan assertion (e.g. a yt-dlp call that also passes `--download-sections`).
+ func anyShellMatches(_ needles: String...) -> Bool {
+ shellCommands.contains { command in
+ needles.allSatisfy { command.range(of: $0, options: .caseInsensitive) != nil }
+ }
+ }
+
+ /// A compact, human-readable transcript of the plan, for `swift test` output so a developer can eyeball
+ /// what the model did even when every assertion passes.
+ var transcript: String {
+ let lines = records.enumerated().map { index, record -> String in
+ let input = record.call.input
+ .sorted { $0.key < $1.key }
+ .map { key, value in "\(key)=\(value.count > 140 ? String(value.prefix(140)) + "…" : value)" }
+ .joined(separator: " ")
+ let suffix = input.isEmpty ? "" : " { \(input) }"
+ return " \(index + 1). \(record.call.name) → \(String(describing: record.resultStatus))\(suffix)"
+ }
+ return lines.joined(separator: "\n")
+ }
+}
+
+enum HarnessEvalRunner {
+ struct Config: Sendable {
+ var baseURL: URL
+ var clientID: String
+ var devAuthBypass: Bool
+ }
+
+ /// Returns the live config, or nil when the eval is not opted into. A nil result means the caller
+ /// should return early (skip) — these tests reach the real model and must never run by accident in a
+ /// plain `swift test`.
+ static func configFromEnvironment(
+ _ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) -> Config? {
+ guard environment["DONKEY_PROMPT_EVAL"] == "1" else { return nil }
+ guard let raw = environment["DONKEY_WEB_BASE_URL"], !raw.isEmpty, let url = URL(string: raw) else {
+ return nil
+ }
+ return Config(
+ baseURL: url,
+ clientID: environment["DONKEY_CLIENT_ID"] ?? "prompt-eval",
+ devAuthBypass: environment["DONKEY_DEV_AUTH_BYPASS"] == "1"
+ )
+ }
+
+ /// Run one scenario: real understanding, real planner, real descriptors, stub executors. Returns the
+ /// captured plan. `@MainActor` because the hosted planner and understanding boundary are main-actor
+ /// isolated (as they are in the app).
+ @MainActor
+ static func run(_ scenario: HarnessEvalScenario, config: Config) async -> HarnessEvalRun {
+ var configuration = DonkeyBackendInferenceConfiguration(
+ baseURL: config.baseURL,
+ clientID: config.clientID,
+ devAuthBypass: config.devAuthBypass
+ )
+ let conversationID = "prompt-eval-\(UUID().uuidString)"
+ configuration.conversationID = conversationID
+ let backend = DonkeyBackendInferenceClient(configuration: configuration)
+
+ // Real one-shot understanding of the turn (turnKind, restated goal, target app, parameters).
+ let understanding = await HostedHarnessRequestUnderstanding(backend: backend)
+ .understand(command: scenario.prompt, frontmostAppName: scenario.frontmostApp)
+
+ // Real tool surface; stub executors so the planner sees the true descriptors but nothing executes.
+ let descriptors = BuiltInHarnessToolCatalog.descriptors
+ let respond = scenario.respond
+ let tools = descriptors.map { descriptor in
+ HarnessTool(descriptor: descriptor) { context in
+ let reply = respond(context.call) ?? defaultReply(for: context.call)
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: reply.status,
+ summary: reply.summary,
+ observations: HarnessObservationDelta(visibleText: reply.visibleText, facts: reply.facts),
+ metadata: ["evalStub": "true"]
+ )
+ }
+ }
+ let registry = HarnessToolRegistry(tools: tools)
+
+ let coordinator = HarnessAgentCoordinator()
+ let goal = (understanding?.restatedGoal).flatMap { $0.isEmpty ? nil : $0 } ?? scenario.prompt
+ let agent = await coordinator.createAgent(
+ conversationID: conversationID,
+ goal: goal,
+ grantedPermissions: Set(HarnessPermission.allCases)
+ )
+
+ let planner = HostedHarnessStepPlanner(
+ backend: backend,
+ descriptors: descriptors,
+ appName: understanding?.targetAppName ?? "",
+ appGuidance: nil,
+ understanding: understanding
+ )
+
+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)
+ _ = await runtime.run(agentID: agent.id, planner: planner, maxSteps: scenario.maxSteps)
+
+ let final = await coordinator.agent(id: agent.id)
+ return HarnessEvalRun(
+ understanding: understanding,
+ records: final?.toolHistory ?? [],
+ finalStatus: final?.status ?? .failedSafe
+ )
+ }
+
+ /// Default stubbed reply when a scenario does not script the call. Skill lookups get the REAL built-in
+ /// `SKILL.md` (so the eval exercises the same guidance the planner reads in production), and everything
+ /// else gets a generic success carrying a fact so the step counts as progress and the loop advances.
+ private static func defaultReply(for call: HarnessToolCall) -> HarnessEvalStub {
+ switch call.name {
+ case "skill.search":
+ return .ok(
+ "Matching skills: media (audio/video — yt-dlp download, ffmpeg transcode/trim/subtitle), "
+ + "pdf (forms — pdf-fill, lit, qpdf), system-tools (safe shell technique). Load one for its full guide.",
+ facts: ["skills.found": "media,pdf,system-tools"]
+ )
+ case "skill.load", "app_skill", "skill_run":
+ let id = call.input["id"] ?? call.input["skill"] ?? call.input["name"] ?? call.input["app"] ?? ""
+ if let content = builtInSkill(matching: id) {
+ return .ok(content, facts: ["skill.loaded": id])
+ }
+ return .ok("Loaded.", facts: ["skill.loaded": id])
+ default:
+ return .ok("\(call.name) ran.", facts: ["lastStub": call.name])
+ }
+ }
+
+ /// Best-effort load of a built-in `SKILL.md` from the DonkeyRuntime resource bundle by a loose id
+ /// match, so the planner sees the real media/pdf/system-tools guidance. Returns nil for an unknown id.
+ private static func builtInSkill(matching id: String) -> String? {
+ let key = id.lowercased()
+ let known = ["media", "pdf", "system-tools", "documents", "images", "data", "web-capture"]
+ guard let match = known.first(where: { key.contains($0) }) else { return nil }
+ guard let url = DonkeyResourceBundle.runtime?.url(
+ forResource: "SKILL",
+ withExtension: "md",
+ subdirectory: "BuiltInSkills/\(match)"
+ ) else { return nil }
+ return try? String(contentsOf: url, encoding: .utf8)
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEvalTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEvalTests.swift
new file mode 100644
index 00000000..d472f2a6
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEvalTests.swift
@@ -0,0 +1,112 @@
+import DonkeyAI
+import DonkeyContracts
+import DonkeyHarness
+import Foundation
+import Testing
+
+/// Live prompt/planner evals: real model, stubbed system + UI, asserting on the plan the model produces.
+/// Opt-in (see `HarnessEvalRunner.configFromEnvironment`); a plain `swift test` returns early. Each test is
+/// a scenario — add more by following the same shape.
+@Suite
+@MainActor
+struct HarnessPromptEvalTests {
+ @Test
+ func clipsYouTubeAndOverlaysAKoreanTranslation() async {
+ guard let config = HarnessEvalRunner.configFromEnvironment() else { return }
+
+ let scenario = HarnessEvalScenario(
+ name: "korean-clip-overlay",
+ prompt: """
+ create a 1min clip of this and overlay the korean translation onto the video
+ https://www.youtube.com/watch?v=v8u_7PPEzZE. start at the 15min point
+ """,
+ frontmostApp: "Safari"
+ ) { call in
+ // Data stubs: hand the model believable results so it walks the whole download → translate →
+ // burn-in flow without touching the network or disk.
+ if call.name == "llm.generate" {
+ return .ok("Wrote subs.srt (Korean subtitles with timestamps).", facts: ["subs.srt": "exists"])
+ }
+ guard call.name == "shell_exec", let command = call.input["command"] else { return nil }
+ if command.contains("yt-dlp") {
+ return .ok("[download] 100% — clip.mp4 written (00:01:00, 1920x1080).", facts: ["clip.mp4": "exists"])
+ }
+ if command.contains("ffprobe") {
+ return .ok("duration=60.000000\nformat_name=mov,mp4,m4a,3gp,3g2,mj2")
+ }
+ if command.contains("ffmpeg"), command.range(of: "subtitles", options: .caseInsensitive) != nil {
+ return .ok("out.mp4 written with burned-in Korean subtitles.", facts: ["out.mp4": "exists"])
+ }
+ if command.contains("ffmpeg") {
+ return .ok("ffmpeg: wrote output.")
+ }
+ return nil
+ }
+
+ let run = await HarnessEvalRunner.run(scenario, config: config)
+ print("\n=== eval: \(scenario.name) (final: \(String(describing: run.finalStatus))) ===\n\(run.transcript)\n")
+
+ // It is an action turn, and the plan downloads with yt-dlp and burns subtitles in with ffmpeg.
+ #expect(run.understanding?.turnKind == .act)
+ #expect(run.anyShellMatches("yt-dlp"), "expected a yt-dlp download; shell calls: \(run.shellCommands)")
+ #expect(
+ run.anyShellMatches("ffmpeg", "subtitles"),
+ "expected an ffmpeg subtitle burn-in; shell calls: \(run.shellCommands)"
+ )
+ // The translation comes from the model (llm.generate) or from yt-dlp's own subtitle download.
+ #expect(
+ run.used("llm.generate") || run.anyShellMatches("yt-dlp", "sub"),
+ "expected a translation/transcription step; tools: \(run.toolNames)"
+ )
+ }
+
+ @Test
+ func fillsF1120FromADataFile() async {
+ guard let config = HarnessEvalRunner.configFromEnvironment() else { return }
+
+ let scenario = HarnessEvalScenario(
+ name: "fill-f1120-pdf",
+ prompt: "fill out f1120.pdf using 1120data.txt",
+ frontmostApp: "Finder"
+ ) { call in
+ // Data stubs: describe the form and the data so the model can plan the fill without real files.
+ if call.name == "files.describe" {
+ return .ok(
+ "f1120.pdf — AcroForm PDF, 6 pages, 48 fillable fields (text and checkbox). "
+ + "1120data.txt — UTF-8 text, 32 `key: value` lines."
+ )
+ }
+ guard call.name == "shell_exec", let command = call.input["command"] else { return nil }
+ // Discovery: the model usually locates the named files first. Tell it where they are so it can
+ // proceed to read + fill, instead of repeating the search.
+ if command.contains("find ") || command.hasPrefix("ls") || command.contains("mdfind") {
+ return .ok("./f1120.pdf\n./1120data.txt", facts: ["found": "f1120.pdf,1120data.txt"])
+ }
+ if command.contains("1120data.txt"), command.range(of: "cat|head|lit|read", options: .regularExpression) != nil {
+ return .ok("name: ACME Corp\nein: 12-3456789\ntax_year: 2025\ntotal_income: 1000000")
+ }
+ if command.contains("pdf-fill"), command.range(of: "describe|fields|--read|inspect", options: .regularExpression) != nil {
+ return .ok(#"{"type":"acroform","fields":[{"name":"f1_01","type":"text"},{"name":"c1_1","type":"checkbox"}]}"#)
+ }
+ if command.contains("pdf-fill") {
+ return .ok("Wrote f1120-filled.pdf (48 fields set).", facts: ["f1120-filled.pdf": "exists"])
+ }
+ return nil
+ }
+
+ let run = await HarnessEvalRunner.run(scenario, config: config)
+ print("\n=== eval: \(scenario.name) (final: \(String(describing: run.finalStatus))) ===\n\(run.transcript)\n")
+
+ #expect(run.understanding?.turnKind == .act)
+ // It reads the source data (cat/inspect the txt or describe it) before filling.
+ #expect(
+ run.used("files.describe") || run.shellCommands.contains { $0.contains("1120data.txt") },
+ "expected it to read the data file; shell calls: \(run.shellCommands)"
+ )
+ // It fills with the bundled form tool, not by driving a PDF GUI.
+ #expect(
+ run.anyShellMatches("pdf-fill") || run.anyShellMatches("lit"),
+ "expected a pdf-fill/lit fill step; shell calls: \(run.shellCommands)"
+ )
+ }
+}