Skip to content

Open source CapCut alternative.

TypeScript

refactor(app): tear down dormant local-model sidecar runtime subsystem

David Le1f04e096ca86
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swift
index 2e54d464..1dba9332 100644
--- a/apps/Donkey/Package.swift
+++ b/apps/Donkey/Package.swift
@@ -12,10 +12,6 @@ let package = Package(
name: "Donkey",
targets: ["Donkey"]
),
- .executable(
- name: "DonkeyUIUnderstandingSidecar",
- targets: ["DonkeyUIUnderstandingSidecar"]
- ),
.library(
name: "DonkeyContracts",
targets: ["DonkeyContracts"]
@@ -90,12 +86,6 @@ let package = Package(
.define("DONKEY_DEBUG_OVERLAY", .when(configuration: .debug))
]
),
- .executableTarget(
- name: "DonkeyUIUnderstandingSidecar",
- dependencies: [
- "DonkeyRuntime"
- ]
- ),
.testTarget(
name: "DonkeyRuntimeTests",
dependencies: [
diff --git a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
index e868edb0..ddc72e04 100644
--- a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
+++ b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
@@ -54,64 +54,6 @@ struct ManualCaptureDebugLaunchHandler {
.run()
printLines(ReflexLatencyReportFormatter.lines(for: report))
return 0
- case .localRuntimeStatus:
- let manager = try LocalModelRuntimeSetupManager()
- printLines(
- ManualCaptureDebugCommandFormatter.lines(
- for: try manager.statuses()
- )
- )
- return 0
- case .localRuntimeSupport:
- let manager = try LocalModelRuntimeSetupManager()
- printLines(
- ManualCaptureDebugCommandFormatter.lines(
- for: try manager.supportSnapshot()
- )
- )
- return 0
- case .localRuntimeInstructions:
- let manager = try LocalModelRuntimeSetupManager()
- printLines(
- ManualCaptureDebugCommandFormatter.lines(
- for: manager.instructions()
- )
- )
- return 0
- case .installLocalRuntime(let options):
- let manager = try LocalModelRuntimeSetupManager()
- let installation = try manager.registerDownloadedRuntime(
- runtimeID: options.runtimeID,
- downloadedDirectory: options.sourceDirectory
- )
- let spec = try manager.status(for: options.runtimeID).spec
- printLines(
- ManualCaptureDebugCommandFormatter.lines(
- for: installation,
- spec: spec
- )
- )
- return 0
- case .repairLocalRuntime(let runtimeID):
- let manager = try LocalModelRuntimeSetupManager()
- let report = try await manager.repairRuntime(runtimeID: runtimeID)
- printLines([
- "local runtime repaired",
- "runtime=\(report.runtimeID.rawValue)",
- "download=\(report.downloadResult.state.rawValue)",
- "modelPreparation=\(report.modelPreparation.state.rawValue)",
- "health=\(report.health.state.rawValue)"
- ])
- return 0
- case .removeLocalRuntime(let runtimeID):
- let manager = try LocalModelRuntimeSetupManager()
- let removed = try manager.removeRuntime(runtimeID: runtimeID)
- printLines([
- "local runtime removed",
- "runtime=\(runtimeID.rawValue)",
- "removed=\(removed)"
- ])
- return 0
case .localAppTask(let options):
let result = await LocalAppUserQueryCommandHandler()
.handleSubmittedCommand(options.command)
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
index 0ed1b1af..27f78e35 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
@@ -50,9 +50,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
commandHandler: any UserQueryCommandHandling = LocalAppUserQueryCommandHandler(),
taskStore: any UserQueryTaskStoring = CoreDataUserQueryTaskStore(),
followUpResolver: any UserQueryFollowUpResolving = HostedTaskFollowUpResolver(),
- voiceTranscriber: LocalVoiceTranscriptionAdapter = LocalVoiceTranscriptionAdapter(
- runtime: ProcessBackedParakeetTranscriptionRuntime()
- ),
+ voiceTranscriber: LocalVoiceTranscriptionAdapter = LocalVoiceTranscriptionAdapter(),
updateChecker: any DonkeyUpdateChecking = SparkleUpdateController(),
liveController: GeminiLiveVoiceController = GeminiLiveVoiceController(),
theme: UserQueryTheme = UserQueryOverlayModel.bundledTheme()
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
index b0c54dc0..c3f09545 100644
--- a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
@@ -106,104 +106,6 @@ public enum LocalVoiceTranscriptionRuntimeError: Error, Equatable, Sendable {
case invalidOutput(String)
}
-public struct ProcessBackedParakeetTranscriptionRuntime: LocalVoiceTranscriptionRuntime {
- public var sidecarRunner: any LocalJSONSidecarRunning
- public var encoder: JSONEncoder
- public var decoder: JSONDecoder
-
- public init(
- sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),
- encoder: JSONEncoder = JSONEncoder(),
- decoder: JSONDecoder = JSONDecoder()
- ) {
- self.sidecarRunner = sidecarRunner
- self.encoder = encoder
- self.decoder = decoder
- }
-
- public func transcribe(
- audio: LocalVoiceAudioBuffer,
- model: AIModelRegistryEntry
- ) async throws -> LocalVoiceTranscript {
- let request = ParakeetSidecarRequest(
- audioID: audio.id,
- format: audio.format,
- sampleRateHz: audio.sampleRateHz,
- channelCount: audio.channelCount,
- durationMS: audio.durationMS,
- audioBase64: audio.data.base64EncodedString(),
- modelID: model.modelID,
- metadata: audio.metadata
- )
- let inputData = try encoder.encode(request)
- let result = await sidecarRunner.run(
- LocalJSONSidecarRequest(
- environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
- inputData: inputData,
- timeoutMS: model.timeoutMS,
- metadata: [
- "sidecar.role": "voiceTranscription",
- "modelID": model.modelID
- ]
- )
- )
- guard result.status == .completed else {
- throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable(
- result.metadata["sidecar.reason"] ?? result.status.rawValue
- )
- }
-
- do {
- let response = try decoder.decode(ParakeetSidecarResponse.self, from: result.outputData)
- return LocalVoiceTranscript(
- text: response.text,
- language: response.language,
- confidence: response.confidence,
- segments: response.segments,
- metadata: result.metadata.merging(response.metadata) { current, _ in current }
- .merging([
- "latency.parakeetTranscriptionMS": result.latencyMS.map { String(format: "%.3f", $0) } ?? ""
- ]) { current, _ in current }
- )
- } catch {
- throw LocalVoiceTranscriptionRuntimeError.invalidOutput(String(describing: error))
- }
- }
-}
-
-private struct ParakeetSidecarRequest: Codable, Equatable, Sendable {
- var audioID: String
- var format: String
- var sampleRateHz: Int
- var channelCount: Int
- var durationMS: Double
- var audioBase64: String
- var modelID: String
- var metadata: [String: String]
-}
-
-private struct ParakeetSidecarResponse: Codable, Equatable, Sendable {
- var text: String
- var language: String?
- var confidence: Double
- var segments: [String]
- var metadata: [String: String]
-
- init(
- text: String,
- language: String? = nil,
- confidence: Double = 0,
- segments: [String] = [],
- metadata: [String: String] = [:]
- ) {
- self.text = text
- self.language = language
- self.confidence = confidence
- self.segments = segments
- self.metadata = metadata
- }
-}
-
public enum LocalVoiceAudioNormalizer {
public static func parakeetCompatibleAudio(
from audio: LocalVoiceAudioBuffer
diff --git a/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift b/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift
index 3cf7b37d..fc1af114 100644
--- a/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift
+++ b/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift
@@ -56,291 +56,3 @@ public protocol AgentVisualizationPlanResolving: Sendable {
_ request: AgentVisualizationPlanResolverRequest
) async -> AgentVisualizationPlanResolverResult
}
-
-public struct ProcessBackedLocalLLMAgentVisualizationPlanResolver: AgentVisualizationPlanResolving {
- public static let schemaID = "agent_visualization_plan"
-
- public var router: AIModelRouter
- public var sidecarRunner: any LocalJSONSidecarRunning
- public var encoder: JSONEncoder
- public var decoder: JSONDecoder
- public var minimumConfidence: Double
-
- public init(
- router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),
- sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),
- encoder: JSONEncoder = JSONEncoder(),
- decoder: JSONDecoder = JSONDecoder(),
- minimumConfidence: Double = 0.62
- ) {
- self.router = router
- self.sidecarRunner = sidecarRunner
- self.encoder = encoder
- self.decoder = decoder
- self.minimumConfidence = minimumConfidence
- }
-
- public func resolveVisualizationPlan(
- _ request: AgentVisualizationPlanResolverRequest
- ) async -> AgentVisualizationPlanResolverResult {
- let entry: AIModelRegistryEntry
- do {
- entry = try router.route(request.routeRequest.limitingProviders([.localRuntime]))
- } catch {
- return result(
- entry: nil,
- request: request,
- status: .invalidOutput,
- validationStatus: "routingFailed",
- latencyMS: nil,
- metadata: ["error": String(describing: error)]
- )
- }
-
- let input = LocalLLMAgentVisualizationPlanSidecarRequest(
- command: request.command,
- runtimeCapabilities: request.runtimeCapabilities,
- cacheSnippets: request.cacheSnippets,
- sourceTraceID: request.sourceTraceID,
- modelID: entry.modelID,
- cacheDirectory: LocalModelRuntimeExecutableResolver().modelCacheDirectoryPath(
- environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER"
- ),
- metadata: [
- "schemaID": Self.schemaID,
- "promptVersion": entry.promptVersion
- ]
- )
- let sidecarResult = await sidecarRunner.run(
- LocalJSONSidecarRequest(
- environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER",
- inputData: (try? encoder.encode(input)) ?? Data(),
- timeoutMS: entry.timeoutMS,
- metadata: [
- "sidecar.role": "agentVisualizationPlan",
- "modelID": entry.modelID
- ]
- )
- )
-
- guard sidecarResult.status == .completed else {
- return result(
- entry: entry,
- request: request,
- status: sidecarResult.status == .timedOut ? .timeout : .providerOutage,
- validationStatus: "notValidated",
- latencyMS: sidecarResult.latencyMS,
- metadata: sidecarResult.metadata.merging([
- "sidecar.stderr": sidecarResult.stderrText
- ]) { current, _ in current }
- )
- }
-
- do {
- let response = try decoder.decode(
- LocalLLMAgentVisualizationPlanSidecarResponse.self,
- from: sidecarResult.outputData
- )
- let decision = try decoder.decode(
- AgentVisualizationPlanDecision.self,
- from: Data(response.outputText.utf8)
- )
- let confidence = min(max(decision.confidence, 0), 1)
- let visualizationPlan = Self.visualizationPlan(
- from: decision,
- confidence: confidence,
- minimumConfidence: minimumConfidence,
- sourceTraceID: request.sourceTraceID
- )
- let cursorRequest = visualizationPlan?.cursorOverlayRequest()
- return AgentVisualizationPlanResolverResult(
- visualizationPlan: visualizationPlan,
- cursorRequest: cursorRequest,
- confidence: confidence,
- reason: decision.reason,
- trace: trace(
- entry: entry,
- request: request,
- status: .completed,
- validationStatus: visualizationPlan == nil ? "notVisualization" : "visualizationDecoded",
- latencyMS: sidecarResult.latencyMS,
- metadata: sidecarResult.metadata.merging(response.metadata) { current, _ in current }
- )
- )
- } catch {
- return result(
- entry: entry,
- request: request,
- status: .invalidOutput,
- validationStatus: "invalid",
- latencyMS: sidecarResult.latencyMS,
- metadata: sidecarResult.metadata.merging([
- "error": String(describing: error)
- ]) { current, _ in current }
- )
- }
- }
-
- private static func visualizationPlan(
- from decision: AgentVisualizationPlanDecision,
- confidence: Double,
- minimumConfidence: Double,
- sourceTraceID: String
- ) -> AgentVisualizationPlan? {
- guard decision.shouldVisualize,
- confidence >= minimumConfidence,
- !decision.steps.isEmpty
- else {
- return nil
- }
-
- let title = nonEmpty(decision.title)
- ?? nonEmpty(decision.goal).map { "Show \($0)" }
- ?? "Show me"
- let steps = decision.steps.prefix(8).enumerated().compactMap { index, step -> AgentVisualizationStep? in
- guard let label = nonEmpty(step.label) else { return nil }
- return AgentVisualizationStep(
- id: "visual-step-\(index + 1)",
- kind: .explain,
- label: label,
- target: AgentVisualizationStepTarget(
- point: HotLoopPoint(
- x: min(max(step.x, 0.04), 0.96),
- y: min(max(step.y, 0.06), 0.94),
- space: .normalizedTarget
- ),
- description: label,
- source: .modelPlan,
- confidence: confidence,
- metadata: [
- "targetApp": decision.targetApp ?? "",
- "visualOnly": "true"
- ]
- ),
- travelDuration: step.travelDuration ?? 0.9,
- holdDuration: step.holdDuration ?? 1.8,
- metadata: [
- "targetApp": decision.targetApp ?? "",
- "model.stepIndex": String(index)
- ]
- )
- }
- guard !steps.isEmpty else { return nil }
-
- return AgentVisualizationPlan(
- title: title,
- executionMode: .visualOnly,
- sourceTraceID: sourceTraceID,
- steps: steps,
- verification: AgentVisualizationVerificationReport(
- status: .unverified,
- summary: decision.reason,
- confidence: confidence,
- evidenceCount: steps.count,
- metadata: [
- "modelDecision": "visualOnly",
- "targetApp": decision.targetApp ?? ""
- ]
- ),
- metadata: (decision.metadata ?? [:]).merging([
- "agentVisualization": "overlay-cursor",
- "goal": decision.goal ?? "",
- "targetApp": decision.targetApp ?? "",
- "source": "local-llm-agent-visualization",
- "realPointerMoved": "false",
- "visualOnly": "true"
- ]) { current, _ in current }
- )
- }
-
- private func result(
- entry: AIModelRegistryEntry?,
- request: AgentVisualizationPlanResolverRequest,
- status: AIModelCallStatus,
- validationStatus: String,
- latencyMS: Double?,
- metadata: [String: String] = [:]
- ) -> AgentVisualizationPlanResolverResult {
- AgentVisualizationPlanResolverResult(
- visualizationPlan: nil,
- cursorRequest: nil,
- confidence: 0,
- reason: metadata["error"] ?? metadata["reason"] ?? "",
- trace: trace(
- entry: entry,
- request: request,
- status: status,
- validationStatus: validationStatus,
- latencyMS: latencyMS,
- metadata: metadata
- )
- )
- }
-
- private func trace(
- entry: AIModelRegistryEntry?,
- request: AgentVisualizationPlanResolverRequest,
- status: AIModelCallStatus,
- validationStatus: String,
- latencyMS: Double?,
- metadata: [String: String] = [:]
- ) -> AIModelCallTrace {
- AIModelCallTrace(
- id: "model-call-\(request.sourceTraceID)",
- role: entry?.role ?? .taskIntent,
- provider: entry?.provider ?? .localRuntime,
- modelID: entry?.modelID ?? "unrouted",
- promptVersion: entry?.promptVersion ?? "unrouted",
- schemaID: Self.schemaID,
- latencyMS: latencyMS,
- timeoutMS: entry?.timeoutMS ?? 0,
- status: status,
- validationStatus: validationStatus,
- sourceTraceID: request.sourceTraceID,
- metadata: metadata
- )
- }
-
- private static func nonEmpty(_ value: String?) -> String? {
- guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines),
- !trimmed.isEmpty
- else {
- return nil
- }
- return trimmed
- }
-}
-
-private struct LocalLLMAgentVisualizationPlanSidecarRequest: Codable, Equatable, Sendable {
- var command: String
- var runtimeCapabilities: [String]
- var cacheSnippets: [String]
- var sourceTraceID: String
- var modelID: String
- var cacheDirectory: String?
- var metadata: [String: String]
-}
-
-private struct LocalLLMAgentVisualizationPlanSidecarResponse: Codable, Equatable, Sendable {
- var outputText: String
- var metadata: [String: String]
-}
-
-private struct AgentVisualizationPlanDecision: Codable, Equatable, Sendable {
- var shouldVisualize: Bool
- var title: String?
- var goal: String?
- var targetApp: String?
- var confidence: Double
- var reason: String
- var steps: [AgentVisualizationPlanStepDecision]
- var metadata: [String: String]?
-}
-
-private struct AgentVisualizationPlanStepDecision: Codable, Equatable, Sendable {
- var label: String
- var x: Double
- var y: Double
- var travelDuration: TimeInterval?
- var holdDuration: TimeInterval?
-}
diff --git a/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift
deleted file mode 100644
index bd59b973..00000000
--- a/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift
+++ /dev/null
@@ -1,291 +0,0 @@
-import CryptoKit
-import DonkeyContracts
-import DonkeyRuntime
-import Foundation
-
-public actor RemoteScreenshotParsingThrottle {
- private struct Entry {
- var fingerprint: String
- var timestamp: Date
- }
-
- private var entries: [String: Entry] = [:]
- private let minimumInterval: TimeInterval
-
- public init(minimumInterval: TimeInterval = 8) {
- self.minimumInterval = max(0, minimumInterval)
- }
-
- public func shouldAllow(
- targetID: String,
- imageFingerprint: String,
- now: Date = Date()
- ) -> Bool {
- if let existing = entries[targetID] {
- if existing.fingerprint == imageFingerprint {
- return false
- }
- if now.timeIntervalSince(existing.timestamp) < minimumInterval {
- return false
- }
- }
-
- entries[targetID] = Entry(fingerprint: imageFingerprint, timestamp: now)
- return true
- }
-}
-
-public struct RemoteScreenshotParsingLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {
- public var client: DonkeyBackendInferenceClient
-
- public init(client: DonkeyBackendInferenceClient) {
- self.client = client
- }
-
- public func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult {
- try await client.parseScreenshot(request)
- }
-
- public func understandStream(
- _ request: LocalUIUnderstandingRequest
- ) -> AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error> {
- AsyncThrowingStream { continuation in
- Task {
- do {
- let final = try await client.parseScreenshotStream(request) { partial in
- continuation.yield(.partial(partial))
- }
- continuation.yield(.final(final))
- continuation.finish()
- } catch {
- continuation.finish(throwing: error)
- }
- }
- }
- }
-
- func understand(
- _ request: LocalUIUnderstandingRequest,
- imageData: Data
- ) async throws -> LocalUIUnderstandingResult {
- try await client.parseScreenshot(request, imageData: imageData)
- }
-
- func understandStream(
- _ request: LocalUIUnderstandingRequest,
- imageData: Data
- ) -> AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error> {
- AsyncThrowingStream { continuation in
- Task {
- do {
- let final = try await client.parseScreenshotStream(
- request,
- imageData: imageData
- ) { partial in
- continuation.yield(.partial(partial))
- }
- continuation.yield(.final(final))
- continuation.finish()
- } catch {
- continuation.finish(throwing: error)
- }
- }
- }
- }
-}
-
-public struct RemoteFallbackLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {
- public var primary: any LocalUIUnderstandingRunning
- public var remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter
- public var throttle: RemoteScreenshotParsingThrottle
- public var minimumPrimaryConfidence: Double
-
- public init(
- primary: any LocalUIUnderstandingRunning = ProcessBackedLocalUIUnderstandingAdapter(),
- remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter,
- throttle: RemoteScreenshotParsingThrottle = RemoteScreenshotParsingThrottle(),
- minimumPrimaryConfidence: Double = 0.75
- ) {
- self.primary = primary
- self.remote = remote
- self.throttle = throttle
- self.minimumPrimaryConfidence = min(max(minimumPrimaryConfidence, 0), 1)
- }
-
- public func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult {
- let primaryResult = try? await primary.understand(request)
- if let primaryResult, primaryEvidenceIsGood(primaryResult) {
- return primaryResult
- }
-
- guard let imageFileURL = request.imageFileURL else {
- if let primaryResult {
- return primaryResult
- }
- throw LocalUIUnderstandingError.unavailable("missingImagePath")
- }
-
- let imageData: Data
- do {
- imageData = try Data(contentsOf: imageFileURL)
- } catch {
- if let primaryResult {
- return primaryResult
- }
- throw LocalUIUnderstandingError.unavailable("missingImageData")
- }
-
- let fingerprint = Self.fingerprint(for: imageData)
- let allowed = await throttle.shouldAllow(
- targetID: request.targetID,
- imageFingerprint: fingerprint
- )
- guard allowed else {
- if let primaryResult {
- return annotatedPrimaryResult(primaryResult, status: "throttled")
- }
- throw LocalUIUnderstandingError.unavailable("remoteScreenshotParsingThrottled")
- }
-
- do {
- var remoteResult = try await remote.understand(request, imageData: imageData)
- remoteResult.metadata = remoteResult.metadata.merging([
- "remoteScreenshotParsing.status": "used",
- "remoteScreenshotParsing.fingerprint": fingerprint
- ]) { current, _ in current }
- return bestResult(primary: primaryResult, remote: remoteResult)
- } catch {
- if let primaryResult {
- return annotatedPrimaryResult(primaryResult, status: "failed")
- }
- throw error
- }
- }
-
- public func understandStream(
- _ request: LocalUIUnderstandingRequest
- ) -> AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error> {
- AsyncThrowingStream { continuation in
- Task {
- do {
- try await streamUnderstanding(request, continuation: continuation)
- } catch {
- continuation.finish(throwing: error)
- }
- }
- }
- }
-
- private func streamUnderstanding(
- _ request: LocalUIUnderstandingRequest,
- continuation: AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error>.Continuation
- ) async throws {
- let primaryResult = try? await primary.understand(request)
- if let primaryResult, primaryEvidenceIsGood(primaryResult) {
- continuation.yield(.final(primaryResult))
- continuation.finish()
- return
- }
-
- guard let imageFileURL = request.imageFileURL else {
- if let primaryResult {
- continuation.yield(.final(primaryResult))
- continuation.finish()
- return
- }
- throw LocalUIUnderstandingError.unavailable("missingImagePath")
- }
-
- let imageData: Data
- do {
- imageData = try Data(contentsOf: imageFileURL)
- } catch {
- if let primaryResult {
- continuation.yield(.final(primaryResult))
- continuation.finish()
- return
- }
- throw LocalUIUnderstandingError.unavailable("missingImageData")
- }
-
- let fingerprint = Self.fingerprint(for: imageData)
- let allowed = await throttle.shouldAllow(
- targetID: request.targetID,
- imageFingerprint: fingerprint
- )
- guard allowed else {
- if let primaryResult {
- continuation.yield(.final(annotatedPrimaryResult(primaryResult, status: "throttled")))
- continuation.finish()
- return
- }
- throw LocalUIUnderstandingError.unavailable("remoteScreenshotParsingThrottled")
- }
-
- do {
- for try await event in remote.understandStream(request, imageData: imageData) {
- switch event {
- case .partial(var partial):
- partial.metadata = partial.metadata.merging([
- "remoteScreenshotParsing.status": "streaming",
- "remoteScreenshotParsing.fingerprint": fingerprint
- ]) { current, _ in current }
- continuation.yield(.partial(bestResult(primary: primaryResult, remote: partial)))
- case .final(var final):
- final.metadata = final.metadata.merging([
- "remoteScreenshotParsing.status": "used",
- "remoteScreenshotParsing.fingerprint": fingerprint
- ]) { current, _ in current }
- continuation.yield(.final(bestResult(primary: primaryResult, remote: final)))
- }
- }
- continuation.finish()
- } catch {
- if let primaryResult {
- continuation.yield(.final(annotatedPrimaryResult(primaryResult, status: "failed")))
- continuation.finish()
- return
- }
- throw error
- }
- }
-
- private func primaryEvidenceIsGood(_ result: LocalUIUnderstandingResult) -> Bool {
- result.confidence >= minimumPrimaryConfidence
- && (!result.controls.isEmpty || !result.visibleText.isEmpty || !result.formFields.isEmpty)
- }
-
- private func bestResult(
- primary: LocalUIUnderstandingResult?,
- remote: LocalUIUnderstandingResult
- ) -> LocalUIUnderstandingResult {
- guard let primary else {
- return remote
- }
-
- if remote.confidence >= primary.confidence || primary.controls.isEmpty {
- return remote
- }
-
- return annotatedPrimaryResult(primary, status: "primaryPreferred")
- }
-
- private func annotatedPrimaryResult(
- _ result: LocalUIUnderstandingResult,
- status: String
- ) -> LocalUIUnderstandingResult {
- LocalUIUnderstandingResult(
- visibleText: result.visibleText,
- controls: result.controls,
- formFields: result.formFields,
- confidence: result.confidence,
- metadata: result.metadata.merging([
- "remoteScreenshotParsing.status": status
- ]) { current, _ in current }
- )
- }
-
- private static func fingerprint(for data: Data) -> String {
- SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift
deleted file mode 100644
index 29f7532c..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift
+++ /dev/null
@@ -1,203 +0,0 @@
-import Foundation
-
-public enum LocalJSONSidecarStatus: String, Codable, Equatable, Sendable {
- case completed
- case unavailable
- case failed
- case timedOut
- case invalidOutput
-}
-
-public struct LocalJSONSidecarRequest: Equatable, Sendable {
- public var environmentVariableName: String
- public var inputData: Data
- public var timeoutMS: Int
- public var metadata: [String: String]
-
- public init(
- environmentVariableName: String,
- inputData: Data,
- timeoutMS: Int,
- metadata: [String: String] = [:]
- ) {
- self.environmentVariableName = environmentVariableName
- self.inputData = inputData
- self.timeoutMS = max(1, timeoutMS)
- self.metadata = metadata
- }
-}
-
-public struct LocalJSONSidecarResult: Equatable, Sendable {
- public var status: LocalJSONSidecarStatus
- public var outputData: Data
- public var exitCode: Int32?
- public var stderrText: String
- public var latencyMS: Double?
- public var metadata: [String: String]
-
- public init(
- status: LocalJSONSidecarStatus,
- outputData: Data = Data(),
- exitCode: Int32? = nil,
- stderrText: String = "",
- latencyMS: Double? = nil,
- metadata: [String: String] = [:]
- ) {
- self.status = status
- self.outputData = outputData
- self.exitCode = exitCode
- self.stderrText = stderrText
- self.latencyMS = latencyMS
- self.metadata = metadata
- }
-}
-
-public protocol LocalJSONSidecarRunning: Sendable {
- func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult
-}
-
-public struct ProcessBackedLocalJSONSidecarRunner: LocalJSONSidecarRunning {
- public var environment: [String: String]
- public var executableResolver: @Sendable (String, [String: String]) -> String?
- public var isExecutableFile: @Sendable (String) -> Bool
- public var now: @Sendable () -> Date
-
- public init(
- environment: [String: String] = ProcessInfo.processInfo.environment,
- executableResolver: @escaping @Sendable (String, [String: String]) -> String? = Self.defaultExecutablePath,
- isExecutableFile: @escaping @Sendable (String) -> Bool = { FileManager.default.isExecutableFile(atPath: $0) },
- now: @escaping @Sendable () -> Date = Date.init
- ) {
- self.environment = environment
- self.executableResolver = executableResolver
- self.isExecutableFile = isExecutableFile
- self.now = now
- }
-
- public func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {
- guard let executablePath = executableResolver(request.environmentVariableName, environment),
- !executablePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
- else {
- return LocalJSONSidecarResult(
- status: .unavailable,
- metadata: metadata(
- request: request,
- executablePath: nil,
- reason: "missingEnvironmentVariable"
- )
- )
- }
-
- guard isExecutableFile(executablePath) else {
- return LocalJSONSidecarResult(
- status: .unavailable,
- metadata: metadata(
- request: request,
- executablePath: executablePath,
- reason: "executableMissingOrNotExecutable"
- )
- )
- }
-
- let startedAt = now()
- let process = Process()
- process.executableURL = URL(fileURLWithPath: executablePath)
- let stdin = Pipe()
- let stdout = Pipe()
- let stderr = Pipe()
- let termination = DispatchSemaphore(value: 0)
- process.standardInput = stdin
- process.standardOutput = stdout
- process.standardError = stderr
- process.terminationHandler = { _ in
- termination.signal()
- }
-
- do {
- try process.run()
- try stdin.fileHandleForWriting.write(contentsOf: request.inputData)
- try stdin.fileHandleForWriting.close()
- } catch {
- return LocalJSONSidecarResult(
- status: .failed,
- stderrText: String(describing: error),
- latencyMS: startedAt.distance(to: now()) * 1_000,
- metadata: metadata(
- request: request,
- executablePath: executablePath,
- reason: "processLaunchFailed"
- )
- )
- }
-
- let timeout = DispatchTime.now() + .milliseconds(request.timeoutMS)
- if Self.waitForTermination(termination, timeout: timeout) == .timedOut {
- process.terminate()
- _ = Self.waitForTermination(termination, timeout: .now() + .seconds(1))
- let stderrData = stderr.fileHandleForReading.readDataToEndOfFile()
- return LocalJSONSidecarResult(
- status: .timedOut,
- exitCode: process.isRunning ? nil : process.terminationStatus,
- stderrText: String(decoding: stderrData, as: UTF8.self),
- latencyMS: startedAt.distance(to: now()) * 1_000,
- metadata: metadata(
- request: request,
- executablePath: executablePath,
- reason: "timeout"
- )
- )
- }
-
- let outputData = stdout.fileHandleForReading.readDataToEndOfFile()
- let stderrData = stderr.fileHandleForReading.readDataToEndOfFile()
- let stderrText = String(decoding: stderrData, as: UTF8.self)
- let status: LocalJSONSidecarStatus = process.terminationStatus == 0 ? .completed : .failed
-
- return LocalJSONSidecarResult(
- status: status,
- outputData: outputData,
- exitCode: process.terminationStatus,
- stderrText: stderrText,
- latencyMS: startedAt.distance(to: now()) * 1_000,
- metadata: metadata(
- request: request,
- executablePath: executablePath,
- reason: status == .completed ? "completed" : "nonZeroExit"
- )
- )
- }
-
- private func metadata(
- request: LocalJSONSidecarRequest,
- executablePath: String?,
- reason: String
- ) -> [String: String] {
- var values = request.metadata
- values["sidecar.environmentVariable"] = request.environmentVariableName
- values["sidecar.executablePath"] = executablePath ?? ""
- values["sidecar.reason"] = reason
- values["sidecar.timeoutMS"] = String(request.timeoutMS)
- return values
- }
-
- private static func waitForTermination(
- _ semaphore: DispatchSemaphore,
- timeout: DispatchTime
- ) -> DispatchTimeoutResult {
- semaphore.wait(timeout: timeout)
- }
-
- public static func defaultExecutablePath(
- environmentVariableName: String,
- environment: [String: String]
- ) -> String? {
- if let path = environment[environmentVariableName],
- !path.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
- return path
- }
-
- return LocalModelRuntimeExecutableResolver().executablePath(
- environmentVariableName: environmentVariableName
- )
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift
deleted file mode 100644
index c920d254..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift
+++ /dev/null
@@ -1,1247 +0,0 @@
-import CryptoKit
-import Foundation
-
-public enum LocalModelRuntimeID: String, Codable, CaseIterable, Equatable, Sendable {
- case parakeetTranscriber = "parakeet-transcriber"
- case screenshotSegmentationStub = "screenshot-segmentation-stub"
- case uiUnderstander = "ui-understander"
- case localLLM = "local-llm"
-}
-
-public enum LocalModelRuntimeInstallState: String, Codable, Equatable, Sendable {
- case installed
- case notInstalled
- case invalidExecutable
- case healthCheckFailed
-}
-
-public enum LocalModelRuntimeSetupError: Error, Equatable, Sendable {
- case unknownRuntime(String)
- case missingDownloadedExecutable(runtimeID: LocalModelRuntimeID, expectedRelativePath: String)
- case downloadedExecutableNotExecutable(runtimeID: LocalModelRuntimeID, path: String)
- case manifestRuntimeMismatch(expected: LocalModelRuntimeID, actual: LocalModelRuntimeID)
- case manifestUnsupportedPlatform(String)
- case manifestUnsupportedArchitecture(String)
- case manifestMissingExecutable(String)
- case manifestFileHashMismatch(relativePath: String)
- case manifestMissingDownloadURL(relativePath: String)
- case manifestMissingSignature
- case manifestUnknownSigningKey(String)
- case manifestInvalidSignature
-}
-
-public enum LocalModelRuntimeDownloadState: String, Codable, Equatable, Sendable {
- case idle
- case downloading
- case installed
- case failed
-}
-
-public enum LocalModelRuntimeHealthState: String, Codable, Equatable, Sendable {
- case healthy
- case unavailable
- case failed
- case invalidOutput
-}
-
-public enum LocalModelRuntimeModelPreparationState: String, Codable, Equatable, Sendable {
- case prepared
- case unavailable
- case failed
- case invalidOutput
-}
-
-public struct LocalModelRuntimeSpec: Codable, Equatable, Sendable {
- public var id: LocalModelRuntimeID
- public var displayName: String
- public var environmentVariableName: String
- public var expectedExecutableRelativePath: String
- public var modelName: String
- public var downloadPageURL: URL?
- public var manifestURL: URL?
- public var installSteps: [String]
- public var metadata: [String: String]
-
- public init(
- id: LocalModelRuntimeID,
- displayName: String,
- environmentVariableName: String,
- expectedExecutableRelativePath: String,
- modelName: String,
- downloadPageURL: URL? = nil,
- manifestURL: URL? = nil,
- installSteps: [String],
- metadata: [String: String] = [:]
- ) {
- self.id = id
- self.displayName = displayName
- self.environmentVariableName = environmentVariableName
- self.expectedExecutableRelativePath = expectedExecutableRelativePath
- self.modelName = modelName
- self.downloadPageURL = downloadPageURL
- self.manifestURL = manifestURL
- self.installSteps = installSteps
- self.metadata = metadata
- }
-}
-
-public struct LocalModelRuntimePackageFile: Codable, Equatable, Sendable {
- public var relativePath: String
- public var downloadURL: URL?
- public var sha256: String
- public var isExecutable: Bool
-
- public init(
- relativePath: String,
- downloadURL: URL? = nil,
- sha256: String,
- isExecutable: Bool = false
- ) {
- self.relativePath = relativePath
- self.downloadURL = downloadURL
- self.sha256 = sha256
- self.isExecutable = isExecutable
- }
-}
-
-public struct LocalModelRuntimePackageManifest: Codable, Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var runtimeVersion: String
- public var modelID: String
- public var platform: String
- public var architecture: String
- public var sidecarProtocolVersion: String
- public var minimumDonkeyVersion: String
- public var executableRelativePath: String
- public var files: [LocalModelRuntimePackageFile]
- public var signature: String?
- public var signingKeyID: String?
- public var releaseNotesURL: URL?
- public var metadata: [String: String]
-
- public init(
- runtimeID: LocalModelRuntimeID,
- runtimeVersion: String,
- modelID: String,
- platform: String = LocalModelRuntimePackageManifest.currentPlatform,
- architecture: String = LocalModelRuntimePackageManifest.currentArchitecture,
- sidecarProtocolVersion: String = "v1",
- minimumDonkeyVersion: String = "0.0.0",
- executableRelativePath: String,
- files: [LocalModelRuntimePackageFile],
- signature: String? = nil,
- signingKeyID: String? = nil,
- releaseNotesURL: URL? = nil,
- metadata: [String: String] = [:]
- ) {
- self.runtimeID = runtimeID
- self.runtimeVersion = runtimeVersion
- self.modelID = modelID
- self.platform = platform
- self.architecture = architecture
- self.sidecarProtocolVersion = sidecarProtocolVersion
- self.minimumDonkeyVersion = minimumDonkeyVersion
- self.executableRelativePath = executableRelativePath
- self.files = files
- self.signature = signature
- self.signingKeyID = signingKeyID
- self.releaseNotesURL = releaseNotesURL
- self.metadata = metadata
- }
-
- public static var currentPlatform: String { "macos" }
-
- public static var currentArchitecture: String {
- #if arch(arm64)
- "arm64"
- #elseif arch(x86_64)
- "x86_64"
- #else
- "unknown"
- #endif
- }
-}
-
-public struct LocalModelRuntimeInstallation: Codable, Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var executablePath: String
- public var downloadedDirectoryPath: String
- public var installedAt: Date
- public var runtimeVersion: String?
- public var modelID: String?
- public var sidecarProtocolVersion: String?
- public var metadata: [String: String]
-
- public init(
- runtimeID: LocalModelRuntimeID,
- executablePath: String,
- downloadedDirectoryPath: String,
- installedAt: Date,
- runtimeVersion: String? = nil,
- modelID: String? = nil,
- sidecarProtocolVersion: String? = nil,
- metadata: [String: String] = [:]
- ) {
- self.runtimeID = runtimeID
- self.executablePath = executablePath
- self.downloadedDirectoryPath = downloadedDirectoryPath
- self.installedAt = installedAt
- self.runtimeVersion = runtimeVersion
- self.modelID = modelID
- self.sidecarProtocolVersion = sidecarProtocolVersion
- self.metadata = metadata
- }
-}
-
-public struct LocalModelRuntimeStatus: Codable, Equatable, Sendable {
- public var spec: LocalModelRuntimeSpec
- public var state: LocalModelRuntimeInstallState
- public var installation: LocalModelRuntimeInstallation?
- public var metadata: [String: String]
-
- public init(
- spec: LocalModelRuntimeSpec,
- state: LocalModelRuntimeInstallState,
- installation: LocalModelRuntimeInstallation? = nil,
- metadata: [String: String] = [:]
- ) {
- self.spec = spec
- self.state = state
- self.installation = installation
- self.metadata = metadata
- }
-}
-
-public struct LocalModelRuntimeHealthReport: Codable, Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var state: LocalModelRuntimeHealthState
- public var runtimeVersion: String?
- public var modelID: String?
- public var sidecarProtocolVersion: String?
- public var latencyMS: Double?
- public var metadata: [String: String]
-
- public init(
- runtimeID: LocalModelRuntimeID,
- state: LocalModelRuntimeHealthState,
- runtimeVersion: String? = nil,
- modelID: String? = nil,
- sidecarProtocolVersion: String? = nil,
- latencyMS: Double? = nil,
- metadata: [String: String] = [:]
- ) {
- self.runtimeID = runtimeID
- self.state = state
- self.runtimeVersion = runtimeVersion
- self.modelID = modelID
- self.sidecarProtocolVersion = sidecarProtocolVersion
- self.latencyMS = latencyMS
- self.metadata = metadata
- }
-}
-
-public struct LocalModelRuntimeDownloadResult: Codable, Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var state: LocalModelRuntimeDownloadState
- public var installation: LocalModelRuntimeInstallation?
- public var metadata: [String: String]
-
- public init(
- runtimeID: LocalModelRuntimeID,
- state: LocalModelRuntimeDownloadState,
- installation: LocalModelRuntimeInstallation? = nil,
- metadata: [String: String] = [:]
- ) {
- self.runtimeID = runtimeID
- self.state = state
- self.installation = installation
- self.metadata = metadata
- }
-}
-
-public struct LocalModelRuntimeModelPreparationReport: Codable, Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var state: LocalModelRuntimeModelPreparationState
- public var cacheDirectory: String?
- public var modelID: String?
- public var latencyMS: Double?
- public var metadata: [String: String]
-
- public init(
- runtimeID: LocalModelRuntimeID,
- state: LocalModelRuntimeModelPreparationState,
- cacheDirectory: String? = nil,
- modelID: String? = nil,
- latencyMS: Double? = nil,
- metadata: [String: String] = [:]
- ) {
- self.runtimeID = runtimeID
- self.state = state
- self.cacheDirectory = cacheDirectory
- self.modelID = modelID
- self.latencyMS = latencyMS
- self.metadata = metadata
- }
-}
-
-public struct LocalModelRuntimeManifestSigningKey: Equatable, Sendable {
- public var keyID: String
- public var publicKeyBase64: String
-
- public init(keyID: String, publicKeyBase64: String) {
- self.keyID = keyID
- self.publicKeyBase64 = publicKeyBase64
- }
-}
-
-public struct LocalModelRuntimeRepairReport: Codable, Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var downloadResult: LocalModelRuntimeDownloadResult
- public var modelPreparation: LocalModelRuntimeModelPreparationReport
- public var health: LocalModelRuntimeHealthReport
- public var metadata: [String: String]
-
- public init(
- runtimeID: LocalModelRuntimeID,
- downloadResult: LocalModelRuntimeDownloadResult,
- modelPreparation: LocalModelRuntimeModelPreparationReport,
- health: LocalModelRuntimeHealthReport,
- metadata: [String: String] = [:]
- ) {
- self.runtimeID = runtimeID
- self.downloadResult = downloadResult
- self.modelPreparation = modelPreparation
- self.health = health
- self.metadata = metadata
- }
-}
-
-public struct LocalModelRuntimeSupportStatus: Codable, Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var displayName: String
- public var state: LocalModelRuntimeInstallState
- public var environmentVariableName: String
- public var runtimeVersion: String?
- public var modelID: String
- public var sidecarProtocolVersion: String?
- public var reason: String?
-
- public init(
- runtimeID: LocalModelRuntimeID,
- displayName: String,
- state: LocalModelRuntimeInstallState,
- environmentVariableName: String,
- runtimeVersion: String? = nil,
- modelID: String,
- sidecarProtocolVersion: String? = nil,
- reason: String? = nil
- ) {
- self.runtimeID = runtimeID
- self.displayName = displayName
- self.state = state
- self.environmentVariableName = environmentVariableName
- self.runtimeVersion = runtimeVersion
- self.modelID = modelID
- self.sidecarProtocolVersion = sidecarProtocolVersion
- self.reason = reason
- }
-}
-
-public struct LocalModelRuntimeSupportSnapshot: Codable, Equatable, Sendable {
- public var generatedAt: Date
- public var statuses: [LocalModelRuntimeSupportStatus]
-
- public init(
- generatedAt: Date,
- statuses: [LocalModelRuntimeSupportStatus]
- ) {
- self.generatedAt = generatedAt
- self.statuses = statuses
- }
-}
-
-public protocol LocalModelRuntimePackageDownloading: Sendable {
- func download(from url: URL) async throws -> Data
-}
-
-public struct URLSessionLocalModelRuntimePackageDownloader: LocalModelRuntimePackageDownloading {
- public init() {}
-
- public func download(from url: URL) async throws -> Data {
- let (data, _) = try await URLSession.shared.data(from: url)
- return data
- }
-}
-
-public struct LocalModelRuntimeInstallInstruction: Codable, Equatable, Sendable {
- public var spec: LocalModelRuntimeSpec
- public var setupDirectory: URL
-
- public init(spec: LocalModelRuntimeSpec, setupDirectory: URL) {
- self.spec = spec
- self.setupDirectory = setupDirectory
- }
-}
-
-public struct LocalModelRuntimeRegistry: Codable, Equatable, Sendable {
- public var installations: [String: LocalModelRuntimeInstallation]
-
- public init(installations: [String: LocalModelRuntimeInstallation] = [:]) {
- self.installations = installations
- }
-}
-
-public struct LocalModelRuntimeSetupManager: Sendable {
- public var baseDirectory: URL
- public var specs: [LocalModelRuntimeSpec]
- public var isExecutableFile: @Sendable (String) -> Bool
- public var now: @Sendable () -> Date
- public var trustedManifestSigningKeys: [String: String]
- public var requiresCryptographicManifestSignatures: Bool
-
- public init(
- baseDirectory: URL? = nil,
- specs: [LocalModelRuntimeSpec] = Self.defaultSpecs,
- isExecutableFile: @escaping @Sendable (String) -> Bool = { FileManager.default.isExecutableFile(atPath: $0) },
- now: @escaping @Sendable () -> Date = Date.init,
- trustedManifestSigningKeys: [LocalModelRuntimeManifestSigningKey] = Self.defaultTrustedManifestSigningKeys(),
- requiresCryptographicManifestSignatures: Bool = Self.defaultRequiresCryptographicManifestSignatures()
- ) throws {
- self.baseDirectory = try baseDirectory ?? Self.defaultBaseDirectory()
- self.specs = specs
- self.isExecutableFile = isExecutableFile
- self.now = now
- self.trustedManifestSigningKeys = Dictionary(
- uniqueKeysWithValues: trustedManifestSigningKeys.map { ($0.keyID, $0.publicKeyBase64) }
- )
- self.requiresCryptographicManifestSignatures = requiresCryptographicManifestSignatures
- }
-
- public static let defaultSpecs: [LocalModelRuntimeSpec] = []
-
- public static func defaultBaseDirectory() throws -> URL {
- try FileManager.default
- .url(
- for: .applicationSupportDirectory,
- in: .userDomainMask,
- appropriateFor: nil,
- create: true
- )
- .appendingPathComponent("Donkey", isDirectory: true)
- .appendingPathComponent("LocalModelRuntimes", isDirectory: true)
- }
-
- public static func defaultPackageManifestURL(for runtimeID: LocalModelRuntimeID) -> URL? {
- if let bundledURLs = Bundle.main.object(
- forInfoDictionaryKey: "DonkeyRuntimePackageManifestURLs"
- ) as? [String: String],
- let value = bundledURLs[runtimeID.rawValue],
- let url = URL(string: value) {
- return url
- }
-
- if let value = ProcessInfo.processInfo.environment[manifestURLEnvironmentName(for: runtimeID)],
- let url = URL(string: value) {
- return url
- }
-
- return ProcessInfo.processInfo.environment["DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS"]?
- .split(separator: ",")
- .compactMap { pair -> (String, String)? in
- let parts = pair.split(separator: "=", maxSplits: 1).map(String.init)
- guard parts.count == 2 else { return nil }
- return (parts[0], parts[1])
- }
- .first(where: { runtime, _ in runtime == runtimeID.rawValue })
- .flatMap { _, value in URL(string: value) }
- }
-
- private static func manifestURLEnvironmentName(for runtimeID: LocalModelRuntimeID) -> String {
- switch runtimeID {
- case .parakeetTranscriber:
- return "DONKEY_PARAKEET_RUNTIME_MANIFEST_URL"
- case .screenshotSegmentationStub:
- return "DONKEY_SCREENSHOT_SEGMENTATION_STUB_RUNTIME_MANIFEST_URL"
- case .uiUnderstander:
- return "DONKEY_UI_UNDERSTANDER_RUNTIME_MANIFEST_URL"
- case .localLLM:
- return "DONKEY_LOCAL_LLM_RUNTIME_MANIFEST_URL"
- }
- }
-
- public static func defaultTrustedManifestSigningKeys() -> [LocalModelRuntimeManifestSigningKey] {
- var keys: [LocalModelRuntimeManifestSigningKey] = []
- if let bundledKeys = Bundle.main.object(
- forInfoDictionaryKey: "DonkeyRuntimeManifestPublicKeys"
- ) as? [String: String] {
- keys.append(contentsOf: bundledKeys.map { keyID, publicKey in
- LocalModelRuntimeManifestSigningKey(keyID: keyID, publicKeyBase64: publicKey)
- })
- }
-
- keys.append(contentsOf: ProcessInfo.processInfo.environment["DONKEY_RUNTIME_MANIFEST_PUBLIC_KEYS"]?
- .split(separator: ",")
- .compactMap { pair -> LocalModelRuntimeManifestSigningKey? in
- let parts = pair.split(separator: "=", maxSplits: 1).map(String.init)
- guard parts.count == 2, !parts[0].isEmpty, !parts[1].isEmpty else {
- return nil
- }
- return LocalModelRuntimeManifestSigningKey(keyID: parts[0], publicKeyBase64: parts[1])
- } ?? [])
- return keys
- }
-
- public static func defaultRequiresCryptographicManifestSignatures() -> Bool {
- if let bundledValue = Bundle.main.object(
- forInfoDictionaryKey: "DonkeyRuntimeRequiresCryptographicManifestSignatures"
- ) as? Bool {
- return bundledValue
- }
- return ProcessInfo.processInfo.environment["DONKEY_RUNTIME_REQUIRE_CRYPTO_SIGNATURES"] == "1"
- }
-
- public func instructions() -> [LocalModelRuntimeInstallInstruction] {
- specs.map { spec in
- LocalModelRuntimeInstallInstruction(
- spec: spec,
- setupDirectory: baseDirectory.appendingPathComponent(spec.id.rawValue, isDirectory: true)
- )
- }
- }
-
- public func statuses() throws -> [LocalModelRuntimeStatus] {
- try specs.map { spec in
- try status(for: spec.id)
- }
- }
-
- public func status(for runtimeID: LocalModelRuntimeID) throws -> LocalModelRuntimeStatus {
- let spec = try spec(for: runtimeID)
- let registry = try loadRegistry()
- guard let installation = registry.installations[runtimeID.rawValue] else {
- return LocalModelRuntimeStatus(
- spec: spec,
- state: .notInstalled,
- metadata: ["reason": "noRegisteredRuntime"]
- )
- }
-
- let state: LocalModelRuntimeInstallState = isExecutableFile(installation.executablePath)
- ? .installed
- : .invalidExecutable
- return LocalModelRuntimeStatus(
- spec: spec,
- state: state,
- installation: installation,
- metadata: [
- "reason": state == .installed ? "installed" : "executableMissingOrNotExecutable"
- ]
- )
- }
-
- public func validateManifest(
- _ manifest: LocalModelRuntimePackageManifest,
- for runtimeID: LocalModelRuntimeID,
- requiresSignature: Bool = true
- ) throws {
- let spec = try spec(for: runtimeID)
- guard manifest.runtimeID == runtimeID else {
- throw LocalModelRuntimeSetupError.manifestRuntimeMismatch(
- expected: runtimeID,
- actual: manifest.runtimeID
- )
- }
- guard manifest.platform == LocalModelRuntimePackageManifest.currentPlatform else {
- throw LocalModelRuntimeSetupError.manifestUnsupportedPlatform(manifest.platform)
- }
- guard manifest.architecture == LocalModelRuntimePackageManifest.currentArchitecture else {
- throw LocalModelRuntimeSetupError.manifestUnsupportedArchitecture(manifest.architecture)
- }
- guard manifest.executableRelativePath == spec.expectedExecutableRelativePath,
- manifest.files.contains(where: { $0.relativePath == manifest.executableRelativePath && $0.isExecutable })
- else {
- throw LocalModelRuntimeSetupError.manifestMissingExecutable(manifest.executableRelativePath)
- }
- if requiresSignature,
- (manifest.signature?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true
- || manifest.signingKeyID?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true) {
- throw LocalModelRuntimeSetupError.manifestMissingSignature
- }
- try verifyManifestSignatureIfConfigured(manifest, requiresSignature: requiresSignature)
- }
-
- @discardableResult
- public func installDownloadedPackage(
- manifest: LocalModelRuntimePackageManifest,
- packageDirectory: URL,
- requiresSignature: Bool = true
- ) throws -> LocalModelRuntimeInstallation {
- try validateManifest(manifest, for: manifest.runtimeID, requiresSignature: requiresSignature)
- for file in manifest.files {
- let fileURL = safePackageURL(root: packageDirectory, relativePath: file.relativePath)
- let data = try Data(contentsOf: fileURL)
- guard Self.sha256Hex(data) == file.sha256.lowercased() else {
- throw LocalModelRuntimeSetupError.manifestFileHashMismatch(relativePath: file.relativePath)
- }
- if file.isExecutable {
- try FileManager.default.setAttributes(
- [.posixPermissions: 0o755],
- ofItemAtPath: fileURL.path
- )
- }
- }
-
- let managedDirectory = managedPackageDirectory(for: manifest)
- if FileManager.default.fileExists(atPath: managedDirectory.path) {
- try FileManager.default.removeItem(at: managedDirectory)
- }
- try FileManager.default.createDirectory(
- at: managedDirectory,
- withIntermediateDirectories: true
- )
- for file in manifest.files {
- let sourceURL = safePackageURL(root: packageDirectory, relativePath: file.relativePath)
- let destinationURL = safePackageURL(root: managedDirectory, relativePath: file.relativePath)
- try FileManager.default.createDirectory(
- at: destinationURL.deletingLastPathComponent(),
- withIntermediateDirectories: true
- )
- try FileManager.default.copyItem(at: sourceURL, to: destinationURL)
- if file.isExecutable {
- try FileManager.default.setAttributes(
- [.posixPermissions: 0o755],
- ofItemAtPath: destinationURL.path
- )
- }
- }
-
- let executableURL = safePackageURL(
- root: managedDirectory,
- relativePath: manifest.executableRelativePath
- )
- return try registerExecutable(
- runtimeID: manifest.runtimeID,
- executableURL: executableURL,
- downloadedDirectory: managedDirectory,
- runtimeVersion: manifest.runtimeVersion,
- modelID: manifest.modelID,
- sidecarProtocolVersion: manifest.sidecarProtocolVersion,
- metadata: [
- "installedBy": "donkey-local-runtime-download",
- "manifest.platform": manifest.platform,
- "manifest.architecture": manifest.architecture,
- "manifest.minimumDonkeyVersion": manifest.minimumDonkeyVersion,
- "manifest.signingKeyID": manifest.signingKeyID ?? "",
- "manifest.signaturePresent": String(manifest.signature != nil)
- ].merging(manifest.metadata) { current, _ in current }
- )
- }
-
- @discardableResult
- public func downloadAndInstall(
- manifest: LocalModelRuntimePackageManifest,
- downloader: any LocalModelRuntimePackageDownloading = URLSessionLocalModelRuntimePackageDownloader(),
- requiresSignature: Bool = true
- ) async throws -> LocalModelRuntimeDownloadResult {
- try validateManifest(manifest, for: manifest.runtimeID, requiresSignature: requiresSignature)
- let stagingDirectory = baseDirectory
- .appendingPathComponent("Downloads", isDirectory: true)
- .appendingPathComponent("\(manifest.runtimeID.rawValue)-\(UUID().uuidString)", isDirectory: true)
- do {
- try FileManager.default.createDirectory(
- at: stagingDirectory,
- withIntermediateDirectories: true
- )
- for file in manifest.files {
- guard let downloadURL = file.downloadURL else {
- throw LocalModelRuntimeSetupError.manifestMissingDownloadURL(relativePath: file.relativePath)
- }
- let data = try await downloader.download(from: downloadURL)
- guard Self.sha256Hex(data) == file.sha256.lowercased() else {
- throw LocalModelRuntimeSetupError.manifestFileHashMismatch(relativePath: file.relativePath)
- }
- let destination = safePackageURL(root: stagingDirectory, relativePath: file.relativePath)
- try FileManager.default.createDirectory(
- at: destination.deletingLastPathComponent(),
- withIntermediateDirectories: true
- )
- try data.write(to: destination, options: .atomic)
- if file.isExecutable {
- try FileManager.default.setAttributes(
- [.posixPermissions: 0o755],
- ofItemAtPath: destination.path
- )
- }
- }
- let installation = try installDownloadedPackage(
- manifest: manifest,
- packageDirectory: stagingDirectory,
- requiresSignature: requiresSignature
- )
- return LocalModelRuntimeDownloadResult(
- runtimeID: manifest.runtimeID,
- state: .installed,
- installation: installation,
- metadata: ["download.stagingDirectory": stagingDirectory.path]
- )
- } catch {
- try? FileManager.default.removeItem(at: stagingDirectory)
- throw error
- }
- }
-
- @discardableResult
- public func downloadAndInstall(
- runtimeID: LocalModelRuntimeID,
- downloader: any LocalModelRuntimePackageDownloading = URLSessionLocalModelRuntimePackageDownloader(),
- requiresSignature: Bool = true
- ) async throws -> LocalModelRuntimeDownloadResult {
- let spec = try spec(for: runtimeID)
- guard let manifestURL = spec.manifestURL else {
- throw LocalModelRuntimeSetupError.manifestMissingDownloadURL(relativePath: "manifest")
- }
- let manifestData = try await downloader.download(from: manifestURL)
- let manifest = try Self.decoder().decode(LocalModelRuntimePackageManifest.self, from: manifestData)
- return try await downloadAndInstall(
- manifest: manifest,
- downloader: downloader,
- requiresSignature: requiresSignature
- )
- }
-
- public func recheckHealth(
- runtimeID: LocalModelRuntimeID,
- timeoutMS: Int = 2_000
- ) async throws -> LocalModelRuntimeHealthReport {
- let status = try status(for: runtimeID)
- guard status.state == .installed,
- let installation = status.installation
- else {
- return LocalModelRuntimeHealthReport(
- runtimeID: runtimeID,
- state: .unavailable,
- metadata: status.metadata
- )
- }
-
- let requestData = try Self.encoder().encode(
- LocalModelRuntimeHealthRequest(
- operation: "healthCheck",
- protocolVersion: installation.sidecarProtocolVersion ?? "v1",
- runtimeID: runtimeID.rawValue,
- runtimeVersion: installation.runtimeVersion,
- modelID: installation.modelID ?? status.spec.modelName,
- cacheDirectory: modelCacheDirectory(for: installation).path,
- metadata: status.spec.metadata
- .merging(installation.metadata) { _, new in new }
- )
- )
- let runner = ProcessBackedLocalJSONSidecarRunner(
- environment: [status.spec.environmentVariableName: installation.executablePath],
- executableResolver: { environmentVariableName, environment in
- environment[environmentVariableName]
- }
- )
- let result = await runner.run(
- LocalJSONSidecarRequest(
- environmentVariableName: status.spec.environmentVariableName,
- inputData: requestData,
- timeoutMS: timeoutMS,
- metadata: ["operation": "healthCheck"]
- )
- )
-
- guard result.status == .completed else {
- return LocalModelRuntimeHealthReport(
- runtimeID: runtimeID,
- state: result.status == .unavailable ? .unavailable : .failed,
- latencyMS: result.latencyMS,
- metadata: result.metadata.merging([
- "sidecar.stderr": result.stderrText
- ]) { current, _ in current }
- )
- }
-
- guard let response = try? Self.decoder().decode(LocalModelRuntimeHealthResponse.self, from: result.outputData) else {
- return LocalModelRuntimeHealthReport(
- runtimeID: runtimeID,
- state: .invalidOutput,
- latencyMS: result.latencyMS,
- metadata: result.metadata
- )
- }
-
- let metadata = result.metadata.merging(response.metadata) { current, _ in current }
- guard response.status == "ok" else {
- return LocalModelRuntimeHealthReport(
- runtimeID: runtimeID,
- state: .failed,
- runtimeVersion: response.runtimeVersion,
- modelID: response.modelID,
- sidecarProtocolVersion: response.protocolVersion,
- latencyMS: result.latencyMS,
- metadata: metadata
- )
- }
- if ["missing", "notConfigured", "externalUnavailable"].contains(metadata["modelWeights.status"] ?? "") {
- return LocalModelRuntimeHealthReport(
- runtimeID: runtimeID,
- state: .failed,
- runtimeVersion: response.runtimeVersion,
- modelID: response.modelID,
- sidecarProtocolVersion: response.protocolVersion,
- latencyMS: result.latencyMS,
- metadata: metadata
- )
- }
-
- return LocalModelRuntimeHealthReport(
- runtimeID: runtimeID,
- state: .healthy,
- runtimeVersion: response.runtimeVersion,
- modelID: response.modelID,
- sidecarProtocolVersion: response.protocolVersion,
- latencyMS: result.latencyMS,
- metadata: metadata
- )
- }
-
- public func prepareModelWeights(
- runtimeID: LocalModelRuntimeID,
- timeoutMS: Int = 600_000
- ) async throws -> LocalModelRuntimeModelPreparationReport {
- let status = try status(for: runtimeID)
- guard status.state == .installed,
- let installation = status.installation
- else {
- return LocalModelRuntimeModelPreparationReport(
- runtimeID: runtimeID,
- state: .unavailable,
- metadata: status.metadata
- )
- }
-
- let cacheDirectory = modelCacheDirectory(for: installation)
- try FileManager.default.createDirectory(
- at: cacheDirectory,
- withIntermediateDirectories: true
- )
- let requestData = try Self.encoder().encode(
- LocalModelRuntimeModelPreparationRequest(
- operation: "prepareModelWeights",
- protocolVersion: installation.sidecarProtocolVersion ?? "v1",
- runtimeID: runtimeID.rawValue,
- runtimeVersion: installation.runtimeVersion,
- modelID: installation.modelID ?? status.spec.modelName,
- cacheDirectory: cacheDirectory.path,
- metadata: status.spec.metadata
- .merging(installation.metadata) { _, new in new }
- )
- )
- let runner = ProcessBackedLocalJSONSidecarRunner(
- environment: [status.spec.environmentVariableName: installation.executablePath],
- executableResolver: { environmentVariableName, environment in
- environment[environmentVariableName]
- }
- )
- let result = await runner.run(
- LocalJSONSidecarRequest(
- environmentVariableName: status.spec.environmentVariableName,
- inputData: requestData,
- timeoutMS: timeoutMS,
- metadata: ["operation": "prepareModelWeights"]
- )
- )
-
- guard result.status == .completed else {
- return LocalModelRuntimeModelPreparationReport(
- runtimeID: runtimeID,
- state: result.status == .unavailable ? .unavailable : .failed,
- cacheDirectory: cacheDirectory.path,
- modelID: installation.modelID ?? status.spec.modelName,
- latencyMS: result.latencyMS,
- metadata: result.metadata.merging([
- "sidecar.stderr": result.stderrText
- ]) { current, _ in current }
- )
- }
-
- guard let response = try? Self.decoder().decode(LocalModelRuntimeModelPreparationResponse.self, from: result.outputData) else {
- return LocalModelRuntimeModelPreparationReport(
- runtimeID: runtimeID,
- state: .invalidOutput,
- cacheDirectory: cacheDirectory.path,
- modelID: installation.modelID ?? status.spec.modelName,
- latencyMS: result.latencyMS,
- metadata: result.metadata
- )
- }
-
- return LocalModelRuntimeModelPreparationReport(
- runtimeID: runtimeID,
- state: response.status == "ok" ? .prepared : .failed,
- cacheDirectory: response.cacheDirectory ?? cacheDirectory.path,
- modelID: response.modelID ?? installation.modelID ?? status.spec.modelName,
- latencyMS: result.latencyMS,
- metadata: result.metadata.merging(response.metadata) { current, _ in current }
- )
- }
-
- @discardableResult
- public func registerDownloadedRuntime(
- runtimeID: LocalModelRuntimeID,
- downloadedDirectory: URL
- ) throws -> LocalModelRuntimeInstallation {
- let spec = try spec(for: runtimeID)
- let executableURL = downloadedDirectory.appendingPathComponent(
- spec.expectedExecutableRelativePath,
- isDirectory: false
- )
- guard FileManager.default.fileExists(atPath: executableURL.path) else {
- throw LocalModelRuntimeSetupError.missingDownloadedExecutable(
- runtimeID: runtimeID,
- expectedRelativePath: spec.expectedExecutableRelativePath
- )
- }
-
- return try registerExecutable(
- runtimeID: runtimeID,
- executableURL: executableURL,
- downloadedDirectory: downloadedDirectory
- )
- }
-
- @discardableResult
- public func registerExecutable(
- runtimeID: LocalModelRuntimeID,
- executableURL: URL,
- downloadedDirectory: URL,
- runtimeVersion: String? = nil,
- modelID: String? = nil,
- sidecarProtocolVersion: String? = nil,
- metadata: [String: String] = ["installedBy": "donkey-local-runtime-setup"]
- ) throws -> LocalModelRuntimeInstallation {
- guard isExecutableFile(executableURL.path) else {
- throw LocalModelRuntimeSetupError.downloadedExecutableNotExecutable(
- runtimeID: runtimeID,
- path: executableURL.path
- )
- }
-
- try FileManager.default.createDirectory(
- at: baseDirectory,
- withIntermediateDirectories: true
- )
- var registry = try loadRegistry()
- let installation = LocalModelRuntimeInstallation(
- runtimeID: runtimeID,
- executablePath: executableURL.path,
- downloadedDirectoryPath: downloadedDirectory.path,
- installedAt: now(),
- runtimeVersion: runtimeVersion,
- modelID: modelID,
- sidecarProtocolVersion: sidecarProtocolVersion,
- metadata: metadata
- )
- registry.installations[runtimeID.rawValue] = installation
- try saveRegistry(registry)
- return installation
- }
-
- public func configuredEnvironment() throws -> [String: String] {
- let registry = try loadRegistry()
- return specs.reduce(into: [:]) { result, spec in
- guard let installation = registry.installations[spec.id.rawValue],
- isExecutableFile(installation.executablePath)
- else {
- return
- }
- result[spec.environmentVariableName] = installation.executablePath
- }
- }
-
- public func executablePath(environmentVariableName: String) throws -> String? {
- try configuredEnvironment()[environmentVariableName]
- }
-
- public func modelCacheDirectoryPath(environmentVariableName: String) throws -> String? {
- guard let spec = specs.first(where: { $0.environmentVariableName == environmentVariableName }) else {
- return nil
- }
- let registry = try loadRegistry()
- guard let installation = registry.installations[spec.id.rawValue] else {
- return nil
- }
- return modelCacheDirectory(for: installation).path
- }
-
- @discardableResult
- public func removeRuntime(
- runtimeID: LocalModelRuntimeID,
- removePackageFiles: Bool = true,
- removeModelWeights: Bool = true
- ) throws -> Bool {
- _ = try spec(for: runtimeID)
- var registry = try loadRegistry()
- guard let installation = registry.installations.removeValue(forKey: runtimeID.rawValue) else {
- return false
- }
- try saveRegistry(registry)
-
- if removePackageFiles {
- let packageDirectory = URL(fileURLWithPath: installation.downloadedDirectoryPath, isDirectory: true)
- if packageDirectory.path.hasPrefix(baseDirectory.path),
- FileManager.default.fileExists(atPath: packageDirectory.path) {
- try FileManager.default.removeItem(at: packageDirectory)
- }
- }
-
- if removeModelWeights {
- let cacheDirectory = modelCacheDirectory(for: installation)
- if cacheDirectory.path.hasPrefix(baseDirectory.path),
- FileManager.default.fileExists(atPath: cacheDirectory.path) {
- try FileManager.default.removeItem(at: cacheDirectory)
- }
- }
-
- return true
- }
-
- public func repairRuntime(
- runtimeID: LocalModelRuntimeID,
- downloader: any LocalModelRuntimePackageDownloading = URLSessionLocalModelRuntimePackageDownloader()
- ) async throws -> LocalModelRuntimeRepairReport {
- let removed = try removeRuntime(runtimeID: runtimeID)
- let downloadResult = try await downloadAndInstall(runtimeID: runtimeID, downloader: downloader)
- let modelPreparation = try await prepareModelWeights(runtimeID: runtimeID)
- let health = try await recheckHealth(runtimeID: runtimeID)
- return LocalModelRuntimeRepairReport(
- runtimeID: runtimeID,
- downloadResult: downloadResult,
- modelPreparation: modelPreparation,
- health: health,
- metadata: ["removedExistingRuntime": String(removed)]
- )
- }
-
- public func supportSnapshot() throws -> LocalModelRuntimeSupportSnapshot {
- LocalModelRuntimeSupportSnapshot(
- generatedAt: now(),
- statuses: try statuses().map { status in
- LocalModelRuntimeSupportStatus(
- runtimeID: status.spec.id,
- displayName: status.spec.displayName,
- state: status.state,
- environmentVariableName: status.spec.environmentVariableName,
- runtimeVersion: status.installation?.runtimeVersion,
- modelID: status.installation?.modelID ?? status.spec.modelName,
- sidecarProtocolVersion: status.installation?.sidecarProtocolVersion,
- reason: status.metadata["reason"]
- )
- }
- )
- }
-
- public func supportExportData() throws -> Data {
- try Self.encoder().encode(supportSnapshot())
- }
-
- private func spec(for runtimeID: LocalModelRuntimeID) throws -> LocalModelRuntimeSpec {
- guard let spec = specs.first(where: { $0.id == runtimeID }) else {
- throw LocalModelRuntimeSetupError.unknownRuntime(runtimeID.rawValue)
- }
- return spec
- }
-
- private func verifyManifestSignatureIfConfigured(
- _ manifest: LocalModelRuntimePackageManifest,
- requiresSignature: Bool
- ) throws {
- guard requiresSignature else { return }
- guard let signingKeyID = manifest.signingKeyID,
- let signature = manifest.signature,
- !signingKeyID.isEmpty,
- !signature.isEmpty
- else {
- throw LocalModelRuntimeSetupError.manifestMissingSignature
- }
-
- guard let publicKeyBase64 = trustedManifestSigningKeys[signingKeyID] else {
- if requiresCryptographicManifestSignatures {
- throw LocalModelRuntimeSetupError.manifestUnknownSigningKey(signingKeyID)
- }
- return
- }
-
- guard let publicKeyData = Data(base64Encoded: publicKeyBase64),
- let signatureData = Data(base64Encoded: signature)
- else {
- throw LocalModelRuntimeSetupError.manifestInvalidSignature
- }
-
- let publicKey = try Curve25519.Signing.PublicKey(rawRepresentation: publicKeyData)
- let payload = try Self.signaturePayloadData(for: manifest)
- guard publicKey.isValidSignature(signatureData, for: payload) else {
- throw LocalModelRuntimeSetupError.manifestInvalidSignature
- }
- }
-
- private func loadRegistry() throws -> LocalModelRuntimeRegistry {
- let url = registryURL()
- guard FileManager.default.fileExists(atPath: url.path) else {
- return LocalModelRuntimeRegistry()
- }
- let data = try Data(contentsOf: url)
- return try Self.decoder().decode(LocalModelRuntimeRegistry.self, from: data)
- }
-
- private func saveRegistry(_ registry: LocalModelRuntimeRegistry) throws {
- try FileManager.default.createDirectory(
- at: baseDirectory,
- withIntermediateDirectories: true
- )
- let data = try Self.encoder().encode(registry)
- try data.write(to: registryURL(), options: .atomic)
- }
-
- private func registryURL() -> URL {
- baseDirectory.appendingPathComponent("runtime-installations.json", isDirectory: false)
- }
-
- private func safePackageURL(root: URL, relativePath: String) -> URL {
- relativePath
- .split(separator: "/")
- .reduce(root) { partialURL, component in
- partialURL.appendingPathComponent(String(component), isDirectory: false)
- }
- }
-
- private func managedPackageDirectory(for manifest: LocalModelRuntimePackageManifest) -> URL {
- baseDirectory
- .appendingPathComponent("Packages", isDirectory: true)
- .appendingPathComponent(manifest.runtimeID.rawValue, isDirectory: true)
- .appendingPathComponent(manifest.runtimeVersion, isDirectory: true)
- }
-
- private func modelCacheDirectory(for installation: LocalModelRuntimeInstallation) -> URL {
- let modelID = (installation.modelID ?? installation.runtimeID.rawValue)
- .replacingOccurrences(of: "/", with: "-")
- .replacingOccurrences(of: ":", with: "-")
- return baseDirectory
- .appendingPathComponent("ModelWeights", isDirectory: true)
- .appendingPathComponent(installation.runtimeID.rawValue, isDirectory: true)
- .appendingPathComponent(modelID, isDirectory: true)
- }
-
- private static func encoder() -> JSONEncoder {
- let encoder = JSONEncoder()
- encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
- encoder.dateEncodingStrategy = .iso8601
- return encoder
- }
-
- private static func decoder() -> JSONDecoder {
- let decoder = JSONDecoder()
- decoder.dateDecodingStrategy = .iso8601
- return decoder
- }
-
- public static func sha256Hex(_ data: Data) -> String {
- SHA256.hash(data: data)
- .map { String(format: "%02x", $0) }
- .joined()
- }
-
- public static func signaturePayloadData(
- for manifest: LocalModelRuntimePackageManifest
- ) throws -> Data {
- try encoder().encode(
- LocalModelRuntimePackageManifestSignaturePayload(
- runtimeID: manifest.runtimeID,
- runtimeVersion: manifest.runtimeVersion,
- modelID: manifest.modelID,
- platform: manifest.platform,
- architecture: manifest.architecture,
- sidecarProtocolVersion: manifest.sidecarProtocolVersion,
- minimumDonkeyVersion: manifest.minimumDonkeyVersion,
- executableRelativePath: manifest.executableRelativePath,
- files: manifest.files,
- signingKeyID: manifest.signingKeyID,
- releaseNotesURL: manifest.releaseNotesURL,
- metadata: manifest.metadata
- )
- )
- }
-}
-
-private struct LocalModelRuntimePackageManifestSignaturePayload: Codable, Equatable, Sendable {
- var runtimeID: LocalModelRuntimeID
- var runtimeVersion: String
- var modelID: String
- var platform: String
- var architecture: String
- var sidecarProtocolVersion: String
- var minimumDonkeyVersion: String
- var executableRelativePath: String
- var files: [LocalModelRuntimePackageFile]
- var signingKeyID: String?
- var releaseNotesURL: URL?
- var metadata: [String: String]
-}
-
-private struct LocalModelRuntimeHealthRequest: Codable, Equatable, Sendable {
- var operation: String
- var protocolVersion: String
- var runtimeID: String?
- var runtimeVersion: String?
- var modelID: String?
- var cacheDirectory: String?
- var metadata: [String: String]?
-}
-
-private struct LocalModelRuntimeHealthResponse: Codable, Equatable, Sendable {
- var status: String
- var runtimeID: String
- var runtimeVersion: String?
- var modelID: String?
- var protocolVersion: String
- var metadata: [String: String]
-}
-
-private struct LocalModelRuntimeModelPreparationRequest: Codable, Equatable, Sendable {
- var operation: String
- var protocolVersion: String
- var runtimeID: String
- var runtimeVersion: String?
- var modelID: String
- var cacheDirectory: String
- var metadata: [String: String]
-}
-
-private struct LocalModelRuntimeModelPreparationResponse: Codable, Equatable, Sendable {
- var status: String
- var runtimeID: String
- var modelID: String?
- var cacheDirectory: String?
- var metadata: [String: String]
-}
-
-public struct LocalModelRuntimeExecutableResolver: Sendable {
- public var setupManagerFactory: @Sendable () throws -> LocalModelRuntimeSetupManager
-
- public init(
- setupManagerFactory: @escaping @Sendable () throws -> LocalModelRuntimeSetupManager = {
- try LocalModelRuntimeSetupManager()
- }
- ) {
- self.setupManagerFactory = setupManagerFactory
- }
-
- public func executablePath(environmentVariableName: String) -> String? {
- try? setupManagerFactory().executablePath(environmentVariableName: environmentVariableName)
- }
-
- public func modelCacheDirectoryPath(environmentVariableName: String) -> String? {
- try? setupManagerFactory().modelCacheDirectoryPath(environmentVariableName: environmentVariableName)
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
index f0d158c5..e70a3897 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
@@ -171,76 +171,3 @@ public extension LocalUIUnderstandingRunning {
}
}
-public struct ProcessBackedLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {
- public var sidecarRunner: any LocalJSONSidecarRunning
- public var encoder: JSONEncoder
- public var decoder: JSONDecoder
- public var timeoutMS: Int
-
- public init(
- sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),
- encoder: JSONEncoder = JSONEncoder(),
- decoder: JSONDecoder = JSONDecoder(),
- timeoutMS: Int = 4_000
- ) {
- self.sidecarRunner = sidecarRunner
- self.encoder = encoder
- self.decoder = decoder
- self.timeoutMS = max(1, timeoutMS)
- }
-
- public func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult {
- let input = LocalUIUnderstandingSidecarRequest(
- traceID: request.traceID,
- targetID: request.targetID,
- imagePath: request.imageFileURL?.path,
- artifactURL: request.artifactURL?.absoluteString,
- cropBounds: request.cropBounds,
- pixelSize: request.pixelSize,
- metadata: request.metadata
- )
- let result = await sidecarRunner.run(
- LocalJSONSidecarRequest(
- environmentVariableName: "DONKEY_UI_UNDERSTANDER",
- inputData: try encoder.encode(input),
- timeoutMS: timeoutMS,
- metadata: [
- "sidecar.role": "uiUnderstanding",
- "targetID": request.targetID
- ]
- )
- )
-
- guard result.status == .completed else {
- throw LocalUIUnderstandingError.unavailable(
- result.metadata["sidecar.reason"] ?? result.status.rawValue
- )
- }
-
- do {
- let output = try decoder.decode(LocalUIUnderstandingResult.self, from: result.outputData)
- return LocalUIUnderstandingResult(
- visibleText: output.visibleText,
- controls: output.controls,
- formFields: output.formFields,
- confidence: output.confidence,
- metadata: result.metadata.merging(output.metadata) { current, _ in current }
- .merging([
- "latency.uiUnderstandingMS": result.latencyMS.map { String(format: "%.3f", $0) } ?? ""
- ]) { current, _ in current }
- )
- } catch {
- throw LocalUIUnderstandingError.invalidOutput(String(describing: error))
- }
- }
-}
-
-private struct LocalUIUnderstandingSidecarRequest: Codable, Equatable, Sendable {
- var traceID: String
- var targetID: String
- var imagePath: String?
- var artifactURL: String?
- var cropBounds: HotLoopRect?
- var pixelSize: HotLoopSize?
- var metadata: [String: String]
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
index aa3777f6..81f727d1 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
@@ -5,12 +5,6 @@ public enum ManualCaptureDebugCommand: Equatable, Sendable {
case listWindowCandidates
case manualCapture(ManualCaptureDebugCaptureOptions)
case dryRunLatencyReport(DryRunLatencyReportDebugOptions)
- case localRuntimeStatus
- case localRuntimeSupport
- case localRuntimeInstructions
- case installLocalRuntime(LocalRuntimeInstallDebugOptions)
- case repairLocalRuntime(LocalModelRuntimeID)
- case removeLocalRuntime(LocalModelRuntimeID)
case localAppTask(LocalAppTaskDebugOptions)
}
@@ -43,16 +37,6 @@ public struct DryRunLatencyReportDebugOptions: Equatable, Sendable {
}
}
-public struct LocalRuntimeInstallDebugOptions: Equatable, Sendable {
- public var runtimeID: LocalModelRuntimeID
- public var sourceDirectory: URL
-
- public init(runtimeID: LocalModelRuntimeID, sourceDirectory: URL) {
- self.runtimeID = runtimeID
- self.sourceDirectory = sourceDirectory
- }
-}
-
public struct LocalAppTaskDebugOptions: Equatable, Sendable {
public var command: String
@@ -68,7 +52,6 @@ public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, Cus
case invalidWindowID(String)
case invalidFrameCount(String)
case invalidBenchmarkMode(String)
- case invalidRuntimeID(String)
case invalidIdentifier(option: String, value: String)
case unsupportedOption(String)
@@ -86,8 +69,6 @@ public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, Cus
return "Invalid --frame-count value: \(value)."
case .invalidBenchmarkMode(let value):
return "Invalid --benchmark-mode value: \(value)."
- case .invalidRuntimeID(let value):
- return "Invalid --runtime-id value: \(value)."
case .invalidIdentifier(let option, let value):
return "Invalid \(option) value: \(value). Use letters, numbers, '.', '_', or '-'."
case .unsupportedOption(let option):
@@ -102,12 +83,6 @@ public enum ManualCaptureDebugCommandParser {
argument == "--list-window-candidates"
|| argument == "--manual-capture"
|| argument == "--dry-run-latency-report"
- || argument == "--local-runtime-status"
- || argument == "--local-runtime-support"
- || argument == "--local-runtime-instructions"
- || argument == "--install-local-runtime"
- || argument == "--repair-local-runtime"
- || argument == "--remove-local-runtime"
|| argument == "--local-app-task"
|| argument == "--command"
|| argument == "--window-id"
@@ -115,8 +90,6 @@ public enum ManualCaptureDebugCommandParser {
|| argument == "--trace-id"
|| argument == "--frame-count"
|| argument == "--benchmark-mode"
- || argument == "--runtime-id"
- || argument == "--runtime-source"
}
}
@@ -134,8 +107,6 @@ public enum ManualCaptureDebugCommandParser {
var traceID: String?
var frameCount = 30
var benchmarkMode = ReflexReplayBenchmarkMode.endToEndDryRun
- var runtimeID: LocalModelRuntimeID?
- var runtimeSource: URL?
var localAppTaskCommand: String?
var index = 0
@@ -151,24 +122,6 @@ public enum ManualCaptureDebugCommandParser {
case "--dry-run-latency-report":
try setMode(.dryRunLatencyReport, current: &mode)
index += 1
- case "--local-runtime-status":
- try setMode(.localRuntimeStatus, current: &mode)
- index += 1
- case "--local-runtime-support":
- try setMode(.localRuntimeSupport, current: &mode)
- index += 1
- case "--local-runtime-instructions":
- try setMode(.localRuntimeInstructions, current: &mode)
- index += 1
- case "--install-local-runtime":
- try setMode(.installLocalRuntime, current: &mode)
- index += 1
- case "--repair-local-runtime":
- try setMode(.repairLocalRuntime, current: &mode)
- index += 1
- case "--remove-local-runtime":
- try setMode(.removeLocalRuntime, current: &mode)
- index += 1
case "--local-app-task":
try setMode(.localAppTask, current: &mode)
index += 1
@@ -206,17 +159,6 @@ public enum ManualCaptureDebugCommandParser {
}
benchmarkMode = parsed
index += 2
- case "--runtime-id":
- let value = try value(after: argument, in: arguments, at: index)
- guard let parsed = LocalModelRuntimeID(rawValue: value) else {
- throw ManualCaptureDebugCommandParseError.invalidRuntimeID(value)
- }
- runtimeID = parsed
- index += 2
- case "--runtime-source":
- let value = try value(after: argument, in: arguments, at: index)
- runtimeSource = URL(fileURLWithPath: value)
- index += 2
default:
throw ManualCaptureDebugCommandParseError.unsupportedOption(argument)
}
@@ -261,86 +203,12 @@ public enum ManualCaptureDebugCommandParser {
mode: benchmarkMode
)
)
- case .localRuntimeStatus:
- guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil,
- localAppTaskCommand == nil
- else {
- throw ManualCaptureDebugCommandParseError.unsupportedOption(
- "runtime install options require --install-local-runtime"
- )
- }
- return .localRuntimeStatus
- case .localRuntimeSupport:
- guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil,
- localAppTaskCommand == nil
- else {
- throw ManualCaptureDebugCommandParseError.unsupportedOption(
- "runtime install options require a runtime lifecycle command"
- )
- }
- return .localRuntimeSupport
- case .localRuntimeInstructions:
- guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil,
- localAppTaskCommand == nil
- else {
- throw ManualCaptureDebugCommandParseError.unsupportedOption(
- "runtime install options require --install-local-runtime"
- )
- }
- return .localRuntimeInstructions
- case .installLocalRuntime:
- guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, localAppTaskCommand == nil
- else {
- throw ManualCaptureDebugCommandParseError.unsupportedOption(
- "capture or benchmark options are not supported with --install-local-runtime"
- )
- }
- guard let runtimeID else {
- throw ManualCaptureDebugCommandParseError.missingValue("--runtime-id")
- }
- guard let runtimeSource else {
- throw ManualCaptureDebugCommandParseError.missingValue("--runtime-source")
- }
- return .installLocalRuntime(
- LocalRuntimeInstallDebugOptions(
- runtimeID: runtimeID,
- sourceDirectory: runtimeSource
- )
- )
- case .repairLocalRuntime:
- guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeSource == nil, localAppTaskCommand == nil
- else {
- throw ManualCaptureDebugCommandParseError.unsupportedOption(
- "capture, benchmark, or source options are not supported with --repair-local-runtime"
- )
- }
- guard let runtimeID else {
- throw ManualCaptureDebugCommandParseError.missingValue("--runtime-id")
- }
- return .repairLocalRuntime(runtimeID)
- case .removeLocalRuntime:
- guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeSource == nil, localAppTaskCommand == nil
- else {
- throw ManualCaptureDebugCommandParseError.unsupportedOption(
- "capture, benchmark, or source options are not supported with --remove-local-runtime"
- )
- }
- guard let runtimeID else {
- throw ManualCaptureDebugCommandParseError.missingValue("--runtime-id")
- }
- return .removeLocalRuntime(runtimeID)
case .localAppTask:
guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil
+ benchmarkMode == .endToEndDryRun
else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
- "runtime, capture, or benchmark options are not supported with --local-app-task"
+ "capture or benchmark options are not supported with --local-app-task"
)
}
guard let localAppTaskCommand,
@@ -465,83 +333,6 @@ public enum ManualCaptureDebugCommandFormatter {
return lines
}
- public static func lines(
- for instructions: [LocalModelRuntimeInstallInstruction]
- ) -> [String] {
- var lines = ["local runtime setup instructions"]
- for instruction in instructions {
- lines.append("runtime=\(instruction.spec.id.rawValue)")
- lines.append("name=\(instruction.spec.displayName)")
- lines.append("model=\(instruction.spec.modelName)")
- lines.append("env=\(instruction.spec.environmentVariableName)")
- lines.append("expectedExecutable=\(instruction.spec.expectedExecutableRelativePath)")
- lines.append("setupDirectory=\(instruction.setupDirectory.path)")
- if let downloadPageURL = instruction.spec.downloadPageURL {
- lines.append("downloadPage=\(downloadPageURL.absoluteString)")
- }
- for (index, step) in instruction.spec.installSteps.enumerated() {
- lines.append("step\(index + 1)=\(step)")
- }
- }
- return lines
- }
-
- public static func lines(
- for statuses: [LocalModelRuntimeStatus]
- ) -> [String] {
- var lines = ["local runtime status"]
- for status in statuses {
- lines.append(
- [
- "runtime=\(status.spec.id.rawValue)",
- "state=\(status.state.rawValue)",
- "env=\(status.spec.environmentVariableName)",
- "executable=\(status.installation?.executablePath ?? "-")",
- "reason=\(status.metadata["reason"] ?? "-")"
- ]
- .joined(separator: " | ")
- )
- }
- return lines
- }
-
- public static func lines(
- for snapshot: LocalModelRuntimeSupportSnapshot
- ) -> [String] {
- var lines = [
- "local runtime support snapshot",
- "generatedAt=\(ISO8601DateFormatter().string(from: snapshot.generatedAt))"
- ]
- for status in snapshot.statuses {
- lines.append(
- [
- "runtime=\(status.runtimeID.rawValue)",
- "state=\(status.state.rawValue)",
- "runtimeVersion=\(status.runtimeVersion ?? "-")",
- "modelID=\(status.modelID)",
- "protocolVersion=\(status.sidecarProtocolVersion ?? "-")",
- "reason=\(status.reason ?? "-")"
- ]
- .joined(separator: " | ")
- )
- }
- return lines
- }
-
- public static func lines(
- for installation: LocalModelRuntimeInstallation,
- spec: LocalModelRuntimeSpec
- ) -> [String] {
- [
- "local runtime installed",
- "runtime=\(installation.runtimeID.rawValue)",
- "name=\(spec.displayName)",
- "env=\(spec.environmentVariableName)",
- "executable=\(installation.executablePath)",
- "downloadedDirectory=\(installation.downloadedDirectoryPath)"
- ]
- }
-
public static func lines(
status: String,
summary: String,
@@ -584,11 +375,5 @@ private enum ManualCaptureDebugCommandMode {
case listWindowCandidates
case manualCapture
case dryRunLatencyReport
- case localRuntimeStatus
- case localRuntimeSupport
- case localRuntimeInstructions
- case installLocalRuntime
- case repairLocalRuntime
- case removeLocalRuntime
case localAppTask
}
diff --git a/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift b/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift
deleted file mode 100644
index 01ae4f98..00000000
--- a/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift
+++ /dev/null
@@ -1,430 +0,0 @@
-import AppKit
-import DonkeyContracts
-import DonkeyRuntime
-import Foundation
-import ImageIO
-import UniformTypeIdentifiers
-
-private struct SidecarRequest: Codable {
- var operation: String?
- var protocolVersion: String?
- var runtimeID: String?
- var runtimeVersion: String?
- var modelID: String?
- var cacheDirectory: String?
- var traceID: String?
- var targetID: String?
- var imagePath: String?
- var artifactURL: String?
- var outputDirectory: String?
- var cropBounds: HotLoopRect?
- var pixelSize: HotLoopSize?
- var metadata: [String: String]?
-}
-
-private struct HealthResponse: Codable {
- var status: String
- var runtimeID: String
- var runtimeVersion: String
- var modelID: String
- var protocolVersion: String
- var metadata: [String: String]
-}
-
-private struct PreparationResponse: Codable {
- var status: String
- var runtimeID: String
- var modelID: String
- var cacheDirectory: String?
- var metadata: [String: String]
-}
-
-private struct ErrorResponse: Codable {
- var status: String
- var runtimeID: String
- var modelID: String
- var metadata: [String: String]
-}
-
-private struct DebugInspectionArtifactResponse: Codable {
- var status: String
- var runtimeID: String
- var modelID: String
- var artifacts: [DebugInspectionArtifact]
- var metadata: [String: String]
-}
-
-private struct DebugInspectionArtifact: Codable {
- var screenID: UInt32
- var screenshotPath: String
- var annotatedPath: String
- var framePath: String
- var elementCount: Int
- var metadata: [String: String]
-}
-
-private let runtimeID = ProcessInfo.processInfo.environment["DONKEY_RUNTIME_ID"] ?? "ui-understander"
-private let runtimeVersion = ProcessInfo.processInfo.environment["DONKEY_RUNTIME_VERSION"] ?? "0.3.0-runner"
-private let modelID = ProcessInfo.processInfo.environment["DONKEY_MODEL_ID"] ?? "local-ui-understanding-stubbed-visual"
-
-@main
-struct DonkeyUIUnderstandingSidecar {
- static func main() {
- do {
- let input = FileHandle.standardInput.readDataToEndOfFile()
- let request = try JSONDecoder().decode(SidecarRequest.self, from: input.isEmpty ? Data("{}".utf8) : input)
- let output: Data
- switch request.operation {
- case "healthCheck":
- output = try JSONEncoder().encode(health())
- case "prepareModelWeights":
- output = try JSONEncoder().encode(prepared(cacheDirectory: request.cacheDirectory))
- case "debugInspectAccessibility":
- output = try JSONEncoder().encode(try debugInspectAccessibility(request))
- default:
- output = try JSONEncoder().encode(try understand(request))
- }
- FileHandle.standardOutput.write(output)
- } catch {
- let payload = ErrorResponse(
- status: "error",
- runtimeID: runtimeID,
- modelID: modelID,
- metadata: [
- "runtime.backend": "local-ui-understanding-stubbed-visual",
- "reason": "uiUnderstandingSidecarFailed",
- "detail": String(describing: error)
- ]
- )
- if let output = try? JSONEncoder().encode(payload) {
- FileHandle.standardOutput.write(output)
- }
- }
- }
-
- private static func health() -> HealthResponse {
- HealthResponse(
- status: "ok",
- runtimeID: runtimeID,
- runtimeVersion: runtimeVersion,
- modelID: modelID,
- protocolVersion: "v1",
- metadata: [
- "runtime.backend": "local-ui-understanding-stubbed-visual",
- "modelWeights.status": "notRequired",
- "modelWeights.provider": "system"
- ]
- )
- }
-
- private static func prepared(cacheDirectory: String?) -> PreparationResponse {
- PreparationResponse(
- status: "ok",
- runtimeID: runtimeID,
- modelID: modelID,
- cacheDirectory: cacheDirectory,
- metadata: [
- "runtime.backend": "local-ui-understanding-stubbed-visual",
- "modelWeights.status": "notRequired",
- "modelWeights.provider": "system"
- ]
- )
- }
-
- private static func debugInspectAccessibility(_ request: SidecarRequest) throws -> DebugInspectionArtifactResponse {
- let outputDirectory = URL(
- fileURLWithPath: request.outputDirectory
- ?? request.artifactURL
- ?? FileManager.default.temporaryDirectory
- .appendingPathComponent("donkey-debug-ui-inspection", isDirectory: true)
- .path,
- isDirectory: true
- )
- try FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
-
- let minConfidence = Double(request.metadata?["minConfidence"] ?? "") ?? 0.25
- let startedAt = ProcessInfo.processInfo.systemUptime
- let results = try DebugUIAccessibilityInspectionService().inspect(
- scope: DebugUIInspectionScreenScope(rawValue: request.metadata?["screenScope"] ?? "") ?? .main,
- minConfidence: minConfidence,
- frontmostOnly: request.metadata?["frontmostOnly"] == "true",
- focusedOnly: request.metadata?["focusedOnly"] == "true",
- targetBundleIdentifiers: commaSeparatedList(request.metadata?["targetBundleIdentifiers"]),
- targetAppNames: commaSeparatedList(request.metadata?["targetAppNames"])
- )
- let encoder = JSONEncoder()
- encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
-
- let prefix = slug(request.traceID ?? request.targetID ?? "debug-ui")
- let artifacts = try results.map { result in
- let screenSlug = "\(prefix)-screen-\(result.snapshot.screenID)"
- let screenshotURL = outputDirectory.appendingPathComponent("\(screenSlug).png")
- let frameURL = outputDirectory.appendingPathComponent("\(screenSlug).frame.json")
- let annotatedURL = outputDirectory.appendingPathComponent("\(screenSlug).annotated.png")
-
- try result.snapshot.pngData.write(to: screenshotURL, options: .atomic)
- try encoder.encode(result.frame).write(to: frameURL, options: .atomic)
- let annotated = annotatedPNGData(
- screenshotPNGData: result.snapshot.pngData,
- frame: result.frame
- ) ?? result.snapshot.pngData
- try annotated.write(to: annotatedURL, options: .atomic)
-
- return DebugInspectionArtifact(
- screenID: result.snapshot.screenID,
- screenshotPath: screenshotURL.path,
- annotatedPath: annotatedURL.path,
- framePath: frameURL.path,
- elementCount: result.frame.elements.count,
- metadata: [
- "snapshot.fingerprint": result.snapshot.fingerprint,
- "pixel.width": String(result.snapshot.pixelSize.width),
- "pixel.height": String(result.snapshot.pixelSize.height)
- ]
- )
- }
- let elapsedMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
- return DebugInspectionArtifactResponse(
- status: "ok",
- runtimeID: runtimeID,
- modelID: modelID,
- artifacts: artifacts,
- metadata: [
- "runtime.backend": "accessibility-native-ui-detection",
- "targetID": request.targetID ?? "",
- "traceID": request.traceID ?? "",
- "artifact.count": String(artifacts.count),
- "element.count": String(artifacts.map(\.elementCount).reduce(0, +)),
- "latency.debugInspectAccessibilityMS": String(format: "%.3f", elapsedMS),
- "visibleSystemA11yToggled": "false",
- "rawPixelsPersisted": "true"
- ]
- )
- }
-
- private static func understand(_ request: SidecarRequest) throws -> LocalUIUnderstandingResult {
- guard let imagePath = request.imagePath, !imagePath.isEmpty else {
- return LocalUIUnderstandingResult(
- confidence: 0,
- metadata: [
- "runtime.backend": "local-ui-understanding-stubbed-visual",
- "reason": "missingImagePath"
- ]
- )
- }
-
- let imageURL = URL(fileURLWithPath: imagePath)
- let imageData = try Data(contentsOf: imageURL)
- let pixelSize = request.pixelSize ?? imagePixelSize(from: imageData)
- let startedAt = ProcessInfo.processInfo.systemUptime
- let trace = LocalUIElementDetectionService().detect(
- LocalUIElementDetectionRequest(
- traceID: request.traceID ?? "ui-understanding-\(UUID().uuidString)",
- screenshotPNGData: imageData,
- screenshotImagePath: imageURL.path,
- pixelSize: pixelSize,
- minConfidence: Double(request.metadata?["minConfidence"] ?? "") ?? 0.25,
- metadata: [
- "runtime.backend": "local-ui-element-detection-stubbed-visual",
- "targetID": request.targetID ?? ""
- ].merging(request.metadata ?? [:]) { current, _ in current }
- )
- )
- let elapsedMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
- let detectionService = LocalUIElementDetectionService()
- let result = detectionService.localUIUnderstandingResult(from: trace)
- let debugFrame = detectionService.debugInspectionFrame(from: trace)
- let annotatedURL = try writeAnnotatedScreenshot(
- request: request,
- imageURL: imageURL,
- screenshotPNGData: imageData,
- frame: debugFrame
- )
- return LocalUIUnderstandingResult(
- visibleText: result.visibleText,
- controls: result.controls,
- formFields: result.formFields,
- confidence: result.confidence,
- metadata: result.metadata.merging([
- "runtime.backend": "local-ui-element-detection-stubbed-visual",
- "nativeVisual.status": trace.metadata["nativeVisual.status"] ?? "unknown",
- "latency.localUIElementSidecarMS": String(format: "%.3f", elapsedMS),
- "debugInspection.element.count": String(debugFrame.elements.count),
- "debugInspection.annotatedPath": annotatedURL?.path ?? "",
- "directInputActionsAllowed": "false"
- ]) { current, _ in current }
- )
- }
-
- private static func writeAnnotatedScreenshot(
- request: SidecarRequest,
- imageURL: URL,
- screenshotPNGData: Data,
- frame: DebugUIInspectionFrame
- ) throws -> URL? {
- guard let annotated = annotatedPNGData(
- screenshotPNGData: screenshotPNGData,
- frame: frame
- ) else {
- return nil
- }
-
- let outputDirectory = URL(
- fileURLWithPath: request.outputDirectory
- ?? request.artifactURL
- ?? FileManager.default.temporaryDirectory
- .appendingPathComponent("donkey-debug-ui-inspection", isDirectory: true)
- .path,
- isDirectory: true
- )
- try FileManager.default.createDirectory(
- at: outputDirectory,
- withIntermediateDirectories: true
- )
- let filename = "\(slug(request.traceID ?? imageURL.deletingPathExtension().lastPathComponent)).annotated.png"
- let annotatedURL = outputDirectory.appendingPathComponent(filename)
- try annotated.write(to: annotatedURL, options: .atomic)
- return annotatedURL
- }
-
- private static func imagePixelSize(from data: Data) -> HotLoopSize {
- guard let source = CGImageSourceCreateWithData(data as CFData, nil),
- let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
- let width = properties[kCGImagePropertyPixelWidth] as? NSNumber,
- let height = properties[kCGImagePropertyPixelHeight] as? NSNumber
- else {
- return HotLoopSize(width: 1, height: 1, space: .screen)
- }
- return HotLoopSize(width: width.doubleValue, height: height.doubleValue, space: .screen)
- }
-
- private static func annotatedPNGData(
- screenshotPNGData: Data,
- frame: DebugUIInspectionFrame
- ) -> Data? {
- guard let source = CGImageSourceCreateWithData(screenshotPNGData as CFData, nil),
- let image = CGImageSourceCreateImageAtIndex(source, 0, nil)
- else {
- return nil
- }
-
- let width = image.width
- let height = image.height
- let colorSpace = CGColorSpaceCreateDeviceRGB()
- let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
- guard let context = CGContext(
- data: nil,
- width: width,
- height: height,
- bitsPerComponent: 8,
- bytesPerRow: 0,
- space: colorSpace,
- bitmapInfo: bitmapInfo
- ) else {
- return nil
- }
-
- context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
- context.setLineWidth(2)
- for element in frame.elements {
- let rect = CGRect(
- x: element.bbox.x,
- y: Double(height) - element.bbox.y - element.bbox.height,
- width: element.bbox.width,
- height: element.bbox.height
- ).integral
- guard rect.width > 1, rect.height > 1 else { continue }
-
- let border = nsColor(hex: element.visualStyle.borderColor) ?? .systemBlue
- context.setStrokeColor(border.cgColor)
- context.setFillColor(border.withAlphaComponent(0.13).cgColor)
- context.fill(rect)
- context.stroke(rect)
-
- let label = annotationLabel(for: element)
- guard !label.isEmpty else { continue }
- let labelHeight: CGFloat = 18
- let labelWidth = min(
- CGFloat(width) - rect.minX - 4,
- max(44, CGFloat(label.count) * 6.7 + 10)
- )
- let labelY = min(CGFloat(height) - labelHeight - 2, max(2, rect.maxY - labelHeight))
- let labelRect = CGRect(
- x: rect.minX,
- y: labelY,
- width: labelWidth,
- height: labelHeight
- )
- context.setFillColor(border.withAlphaComponent(0.82).cgColor)
- context.fill(labelRect)
-
- let nsContext = NSGraphicsContext(cgContext: context, flipped: false)
- NSGraphicsContext.saveGraphicsState()
- NSGraphicsContext.current = nsContext
- (label as NSString).draw(
- in: labelRect.insetBy(dx: 4, dy: 2),
- withAttributes: [
- .foregroundColor: NSColor.white,
- .font: NSFont.systemFont(ofSize: 10, weight: .semibold)
- ]
- )
- NSGraphicsContext.restoreGraphicsState()
- }
-
- guard let output = context.makeImage() else {
- return nil
- }
- let data = NSMutableData()
- guard let destination = CGImageDestinationCreateWithData(
- data,
- UTType.png.identifier as CFString,
- 1,
- nil
- ) else {
- return nil
- }
- CGImageDestinationAddImage(destination, output, nil)
- guard CGImageDestinationFinalize(destination) else {
- return nil
- }
- return data as Data
- }
-
- private static func annotationLabel(for element: DebugUIElement) -> String {
- let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
- let title = label.isEmpty ? element.type.rawValue : label
- let cappedTitle = title.count > 34 ? "\(title.prefix(31))..." : title
- return cappedTitle
- }
-
- private static func nsColor(hex: String) -> NSColor? {
- let trimmed = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
- guard trimmed.count == 6,
- let value = Int(trimmed, radix: 16)
- else {
- return nil
- }
- return NSColor(
- calibratedRed: CGFloat((value >> 16) & 0xFF) / 255,
- green: CGFloat((value >> 8) & 0xFF) / 255,
- blue: CGFloat(value & 0xFF) / 255,
- alpha: 1
- )
- }
-
- private static func slug(_ value: String) -> String {
- let slug = value
- .lowercased()
- .split { !$0.isLetter && !$0.isNumber }
- .prefix(8)
- .joined(separator: "-")
- return slug.isEmpty ? "debug-ui" : slug
- }
-
- private static func commaSeparatedList(_ value: String?) -> [String] {
- (value ?? "")
- .split(separator: ",")
- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
- .filter { !$0.isEmpty }
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 24b2486d..0765ed31 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -207,91 +207,6 @@ struct AIHarnessAdapterTests {
#expect(result.trace.metadata["audio.prepared.format"] == "wav")
}
- @Test
- func processBackedParakeetRuntimeDecodesSidecarTranscript() async throws {
- let runtime = ProcessBackedParakeetTranscriptionRuntime(
- sidecarRunner: FakeSidecarRunner(
- result: LocalJSONSidecarResult(
- status: .completed,
- outputData: Data("""
- {"text":"show weather","language":"en","confidence":0.94,"segments":["show weather"],"metadata":{"decoder":"fake-parakeet"}}
- """.utf8),
- metadata: ["sidecar.reason": "completed"]
- )
- )
- )
- let transcript = try await runtime.transcribe(
- audio: LocalVoiceAudioBuffer(
- id: "audio-sidecar",
- durationMS: 800,
- data: Data([1, 2, 3])
- ),
- model: try AIModelRouter(registry: localVoiceRegistry()).route(
- AIModelRouteRequest(
- jobType: .voiceTranscription,
- requiredCapabilities: [.audioInput],
- allowedProviders: [.localRuntime]
- )
- )
- )
-
- #expect(transcript.text == "show weather")
- #expect(transcript.language == "en")
- #expect(transcript.metadata["decoder"] == "fake-parakeet")
- }
-
- @Test
- func processBackedParakeetRuntimeFailsClearlyWhenUnavailable() async throws {
- let runtime = ProcessBackedParakeetTranscriptionRuntime(
- sidecarRunner: FakeSidecarRunner(
- result: LocalJSONSidecarResult(
- status: .unavailable,
- metadata: ["sidecar.reason": "missingEnvironmentVariable"]
- )
- )
- )
-
- await #expect(throws: LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("missingEnvironmentVariable")) {
- _ = try await runtime.transcribe(
- audio: LocalVoiceAudioBuffer(id: "audio-missing", durationMS: 10, data: Data()),
- model: try AIModelRouter(registry: localVoiceRegistry()).route(
- AIModelRouteRequest(
- jobType: .voiceTranscription,
- requiredCapabilities: [.audioInput],
- allowedProviders: [.localRuntime]
- )
- )
- )
- }
- }
-
- @Test
- func localJSONSidecarRunnerReportsMissingEnvAndNonzeroExit() async {
- let missing = await ProcessBackedLocalJSONSidecarRunner(environment: [:]).run(
- LocalJSONSidecarRequest(
- environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
- inputData: Data("{}".utf8),
- timeoutMS: 100
- )
- )
- #expect(missing.status == .unavailable)
- #expect(missing.metadata["sidecar.reason"] == "missingEnvironmentVariable")
-
- let failed = await ProcessBackedLocalJSONSidecarRunner(
- environment: ["DONKEY_TEST_SIDECAR": "/bin/false"]
- )
- .run(
- LocalJSONSidecarRequest(
- environmentVariableName: "DONKEY_TEST_SIDECAR",
- inputData: Data("{}".utf8),
- timeoutMS: 100
- )
- )
- #expect(failed.status == .failed)
- #expect(failed.exitCode != 0)
- #expect(failed.metadata["sidecar.reason"] == "nonZeroExit")
- }
-
@Test
func hostedFollowUpResolverLetsBackendSelectResponsesModel() async throws {
let httpClient = FakeAIHTTPClient(
@@ -1041,14 +956,6 @@ private actor RecordingVoiceRuntime: LocalVoiceTranscriptionRuntime {
}
}
-private struct FakeSidecarRunner: LocalJSONSidecarRunning {
- var result: LocalJSONSidecarResult
-
- func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {
- result
- }
-}
-
private final class FakeAIHTTPClient: AIHTTPClient, @unchecked Sendable {
var data: Data
var statusCode: Int
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
index 5ac02ef3..cf585d86 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
@@ -588,187 +588,6 @@ struct DonkeyBackendInferenceClientTests {
#expect(fused.elements.map(\.id).contains("ai-small-icon"))
}
- @Test
- func remoteFallbackDoesNotCallBackendWhenPrimaryEvidenceIsGood() async throws {
- let httpClient = FixtureHTTPClient(
- data: try JSONEncoder().encode(LocalUIUnderstandingResult(confidence: 0.9)),
- statusCode: 200
- )
- let adapter = RemoteFallbackLocalUIUnderstandingAdapter(
- primary: StaticUIUnderstandingRunner(
- result: LocalUIUnderstandingResult(
- controls: [
- LocalUIUnderstandingControl(
- id: "native-search",
- label: "Search",
- kind: .searchField,
- confidence: 0.86
- )
- ],
- confidence: 0.86
- )
- ),
- remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter(
- client: DonkeyBackendInferenceClient(
- configuration: configuration(),
- httpClient: httpClient
- )
- )
- )
-
- let result = try await adapter.understand(
- LocalUIUnderstandingRequest(
- traceID: "trace-good-primary",
- targetID: "target-1"
- )
- )
-
- #expect(result.controls.first?.id == "native-search")
- #expect(httpClient.requests.isEmpty)
- }
-
- @Test
- func remoteFallbackThrottlesUnchangedScreenshots() async throws {
- let imageURL = FileManager.default.temporaryDirectory
- .appendingPathComponent("donkey-remote-screenshot-\(UUID().uuidString).png")
- try Data("same-image".utf8).write(to: imageURL)
- defer {
- try? FileManager.default.removeItem(at: imageURL)
- }
-
- let remoteResult = LocalUIUnderstandingResult(
- controls: [
- LocalUIUnderstandingControl(
- id: "remote-button",
- label: "Continue",
- kind: .button,
- confidence: 0.9
- )
- ],
- confidence: 0.9
- )
- let httpClient = FixtureHTTPClient(
- data: try JSONEncoder().encode(remoteResult),
- statusCode: 200
- )
- let adapter = RemoteFallbackLocalUIUnderstandingAdapter(
- primary: StaticUIUnderstandingRunner(
- result: LocalUIUnderstandingResult(confidence: 0.1)
- ),
- remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter(
- client: DonkeyBackendInferenceClient(
- configuration: configuration(),
- httpClient: httpClient
- )
- ),
- throttle: RemoteScreenshotParsingThrottle(minimumInterval: 60)
- )
- let request = LocalUIUnderstandingRequest(
- traceID: "trace-throttle",
- targetID: "target-throttle",
- imageFileURL: imageURL,
- pixelSize: HotLoopSize(width: 100, height: 100, space: .window)
- )
-
- let first = try await adapter.understand(request)
- let second = try await adapter.understand(request)
-
- #expect(first.controls.first?.id == "remote-button")
- #expect(second.metadata["remoteScreenshotParsing.status"] == "throttled")
- #expect(httpClient.requests.count == 1)
- }
-
- @Test
- func remoteFallbackStreamsPartialAndFinalScreenshotEvidence() async throws {
- let imageURL = FileManager.default.temporaryDirectory
- .appendingPathComponent("donkey-remote-screenshot-stream-\(UUID().uuidString).png")
- try Data("stream-image".utf8).write(to: imageURL)
- defer {
- try? FileManager.default.removeItem(at: imageURL)
- }
-
- let partial = LocalUIUnderstandingResult(
- controls: [
- LocalUIUnderstandingControl(
- id: "partial-row",
- label: "Partial Row",
- kind: .listItem,
- confidence: 0.62
- )
- ],
- confidence: 0.62,
- metadata: ["screenshotParser.stream": "partial"]
- )
- let final = LocalUIUnderstandingResult(
- controls: [
- LocalUIUnderstandingControl(
- id: "partial-row",
- label: "Partial Row",
- kind: .listItem,
- confidence: 0.62
- ),
- LocalUIUnderstandingControl(
- id: "final-play",
- label: "Play",
- kind: .button,
- confidence: 0.91
- )
- ],
- confidence: 0.91,
- metadata: ["screenshotParser.stream": "final"]
- )
- let encoder = JSONEncoder()
- let responseText = [
- "event: partial",
- "data: \(String(data: try encoder.encode(partial), encoding: .utf8)!)",
- "",
- "event: final",
- "data: \(String(data: try encoder.encode(final), encoding: .utf8)!)",
- "",
- ].joined(separator: "\n")
- let httpClient = FixtureHTTPClient(
- data: Data(responseText.utf8),
- statusCode: 200,
- headerFields: ["Content-Type": "text/event-stream"]
- )
- let adapter = RemoteFallbackLocalUIUnderstandingAdapter(
- primary: StaticUIUnderstandingRunner(result: LocalUIUnderstandingResult(confidence: 0.1)),
- remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter(
- client: DonkeyBackendInferenceClient(
- configuration: configuration(),
- httpClient: httpClient
- )
- ),
- throttle: RemoteScreenshotParsingThrottle(minimumInterval: 60)
- )
-
- let stream = adapter.understandStream(
- LocalUIUnderstandingRequest(
- traceID: "trace-stream-fallback",
- targetID: "target-stream-fallback",
- imageFileURL: imageURL,
- pixelSize: HotLoopSize(width: 100, height: 100, space: .window)
- )
- )
- var eventSummaries: [String] = []
- for try await event in stream {
- switch event {
- case .partial(let result):
- eventSummaries.append("partial:\(result.controls.map(\.id).joined(separator: ",")):\(result.metadata["remoteScreenshotParsing.status"] ?? "")")
- case .final(let result):
- eventSummaries.append("final:\(result.controls.map(\.id).joined(separator: ",")):\(result.metadata["remoteScreenshotParsing.status"] ?? "")")
- }
- }
-
- #expect(eventSummaries == [
- "partial:partial-row:streaming",
- "final:partial-row,final-play:used",
- ])
- let request = try #require(httpClient.requests.first)
- let object = try #require(request.httpBodyJSONObject)
- #expect(object["stream"] as? Bool == true)
- }
-
@Test
func configurationUsesWebBaseEnvironmentURL() throws {
let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment([
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift
deleted file mode 100644
index 9577baf9..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift
+++ /dev/null
@@ -1,634 +0,0 @@
-@testable import DonkeyRuntime
-import CryptoKit
-import Foundation
-import Testing
-
-@Suite
-struct LocalModelRuntimeSetupTests {
- @Test
- func setupInstructionsAreEmptyWhenHostedModelsAreDefault() throws {
- let root = temporaryDirectory()
- defer { try? FileManager.default.removeItem(at: root) }
-
- let manager = try LocalModelRuntimeSetupManager(baseDirectory: root)
- let instructions = manager.instructions()
-
- #expect(instructions.isEmpty)
- }
-
- @Test
- func registerDownloadedRuntimeStoresExecutablePathInApplicationSupportRegistry() throws {
- let root = temporaryDirectory()
- let download = temporaryDirectory()
- defer {
- try? FileManager.default.removeItem(at: root)
- try? FileManager.default.removeItem(at: download)
- }
- let executableURL = try makeExecutable(
- root: download,
- relativePath: "bin/donkey-screenshot-segmentation-stub"
- )
- let manager = try runtimeManager(baseDirectory: root)
-
- let installation = try manager.registerDownloadedRuntime(
- runtimeID: .screenshotSegmentationStub,
- downloadedDirectory: download
- )
- let status = try manager.status(for: .screenshotSegmentationStub)
- let environment = try manager.configuredEnvironment()
-
- #expect(installation.executablePath == executableURL.path)
- #expect(status.state == .installed)
- #expect(status.installation?.downloadedDirectoryPath == download.path)
- #expect(environment["DONKEY_SCREENSHOT_SEGMENTATION_STUB"] == executableURL.path)
- }
-
- @Test
- func registerDownloadedRuntimeFailsWhenExecutableIsMissingOrNotExecutable() throws {
- let root = temporaryDirectory()
- let download = temporaryDirectory()
- defer {
- try? FileManager.default.removeItem(at: root)
- try? FileManager.default.removeItem(at: download)
- }
- let manager = try runtimeManager(baseDirectory: root)
-
- #expect(throws: LocalModelRuntimeSetupError.missingDownloadedExecutable(
- runtimeID: .parakeetTranscriber,
- expectedRelativePath: "bin/donkey-parakeet-transcriber"
- )) {
- _ = try manager.registerDownloadedRuntime(
- runtimeID: .parakeetTranscriber,
- downloadedDirectory: download
- )
- }
-
- let executableURL = try makeFile(
- root: download,
- relativePath: "bin/donkey-parakeet-transcriber",
- permissions: 0o644
- )
- #expect(throws: LocalModelRuntimeSetupError.downloadedExecutableNotExecutable(
- runtimeID: .parakeetTranscriber,
- path: executableURL.path
- )) {
- _ = try manager.registerDownloadedRuntime(
- runtimeID: .parakeetTranscriber,
- downloadedDirectory: download
- )
- }
- }
-
- @Test
- func processRunnerResolvesAppManagedRuntimeWhenShellEnvironmentIsMissing() async throws {
- let root = temporaryDirectory()
- let download = temporaryDirectory()
- defer {
- try? FileManager.default.removeItem(at: root)
- try? FileManager.default.removeItem(at: download)
- }
- let executableURL = URL(fileURLWithPath: "/bin/cat")
- let manager = try runtimeManager(baseDirectory: root)
- try manager.registerExecutable(
- runtimeID: .parakeetTranscriber,
- executableURL: executableURL,
- downloadedDirectory: download
- )
- let resolver = LocalModelRuntimeExecutableResolver {
- try runtimeManager(baseDirectory: root)
- }
- let runner = ProcessBackedLocalJSONSidecarRunner(
- environment: [:],
- executableResolver: { environmentVariableName, _ in
- resolver.executablePath(environmentVariableName: environmentVariableName)
- }
- )
-
- let result = await runner.run(
- LocalJSONSidecarRequest(
- environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
- inputData: Data("{\"ok\":true}".utf8),
- timeoutMS: 1_000
- )
- )
-
- #expect(result.status == .completed)
- #expect(String(decoding: result.outputData, as: UTF8.self) == "{\"ok\":true}")
- #expect(result.metadata["sidecar.executablePath"] == executableURL.path)
- }
-
- @Test
- func manifestDownloadVerifiesSignatureMetadataChecksumsAndCachesPackage() async throws {
- let root = temporaryDirectory()
- defer { try? FileManager.default.removeItem(at: root) }
- let executableData = Data("#!/bin/sh\necho ok\n".utf8)
- let modelData = Data("fake-model".utf8)
- let manifest = LocalModelRuntimePackageManifest(
- runtimeID: .uiUnderstander,
- runtimeVersion: "1.0.0",
- modelID: "local-ui-understander",
- executableRelativePath: "bin/donkey-ui-understander",
- files: [
- LocalModelRuntimePackageFile(
- relativePath: "bin/donkey-ui-understander",
- downloadURL: URL(string: "https://example.test/ui/bin")!,
- sha256: LocalModelRuntimeSetupManager.sha256Hex(executableData),
- isExecutable: true
- ),
- LocalModelRuntimePackageFile(
- relativePath: "models/ui-understander.bin",
- downloadURL: URL(string: "https://example.test/ui/model")!,
- sha256: LocalModelRuntimeSetupManager.sha256Hex(modelData)
- )
- ],
- signature: "signed-for-test",
- signingKeyID: "test-key"
- )
- let manager = try runtimeManager(baseDirectory: root)
-
- let result = try await manager.downloadAndInstall(
- manifest: manifest,
- downloader: FakeRuntimeDownloader(files: [
- URL(string: "https://example.test/ui/bin")!: executableData,
- URL(string: "https://example.test/ui/model")!: modelData
- ])
- )
- let status = try manager.status(for: .uiUnderstander)
-
- #expect(result.state == .installed)
- #expect(status.state == .installed)
- #expect(status.installation?.runtimeVersion == "1.0.0")
- #expect(status.installation?.modelID == "local-ui-understander")
- #expect(status.installation?.downloadedDirectoryPath.contains("/Packages/ui-understander/1.0.0") == true)
- #expect(FileManager.default.fileExists(atPath: status.installation?.executablePath ?? "") == true)
- }
-
- @Test
- func cryptographicManifestSignatureIsVerifiedWhenKeyIsTrusted() async throws {
- let root = temporaryDirectory()
- defer { try? FileManager.default.removeItem(at: root) }
- let executableData = Data("#!/bin/sh\necho ok\n".utf8)
- let privateKey = Curve25519.Signing.PrivateKey()
- let publicKeyBase64 = privateKey.publicKey.rawRepresentation.base64EncodedString()
- var manifest = LocalModelRuntimePackageManifest(
- runtimeID: .uiUnderstander,
- runtimeVersion: "1.0.0",
- modelID: "local-ui-understander",
- executableRelativePath: "bin/donkey-ui-understander",
- files: [
- LocalModelRuntimePackageFile(
- relativePath: "bin/donkey-ui-understander",
- downloadURL: URL(string: "https://example.test/ui/bin")!,
- sha256: LocalModelRuntimeSetupManager.sha256Hex(executableData),
- isExecutable: true
- )
- ],
- signingKeyID: "test-release-key"
- )
- let payload = try LocalModelRuntimeSetupManager.signaturePayloadData(for: manifest)
- manifest.signature = try privateKey.signature(for: payload).base64EncodedString()
- let manager = try runtimeManager(
- baseDirectory: root,
- trustedManifestSigningKeys: [
- LocalModelRuntimeManifestSigningKey(
- keyID: "test-release-key",
- publicKeyBase64: publicKeyBase64
- )
- ],
- requiresCryptographicManifestSignatures: true
- )
-
- let result = try await manager.downloadAndInstall(
- manifest: manifest,
- downloader: FakeRuntimeDownloader(files: [
- URL(string: "https://example.test/ui/bin")!: executableData
- ])
- )
-
- #expect(result.state == .installed)
- }
-
- @Test
- func cryptographicManifestSignatureRejectsUnknownKeyAndBadSignature() async throws {
- let root = temporaryDirectory()
- defer { try? FileManager.default.removeItem(at: root) }
- let executableData = Data("#!/bin/sh\necho ok\n".utf8)
- let privateKey = Curve25519.Signing.PrivateKey()
- var manifest = LocalModelRuntimePackageManifest(
- runtimeID: .screenshotSegmentationStub,
- runtimeVersion: "1.0.0",
- modelID: "stubbed-screenshot-segmentation",
- executableRelativePath: "bin/donkey-screenshot-segmentation-stub",
- files: [
- LocalModelRuntimePackageFile(
- relativePath: "bin/donkey-screenshot-segmentation-stub",
- downloadURL: URL(string: "https://example.test/segmentation-stub/bin")!,
- sha256: LocalModelRuntimeSetupManager.sha256Hex(executableData),
- isExecutable: true
- )
- ],
- signingKeyID: "unknown-key"
- )
- let payload = try LocalModelRuntimeSetupManager.signaturePayloadData(for: manifest)
- manifest.signature = try privateKey.signature(for: payload).base64EncodedString()
- let manager = try runtimeManager(
- baseDirectory: root,
- requiresCryptographicManifestSignatures: true
- )
-
- await #expect(throws: LocalModelRuntimeSetupError.manifestUnknownSigningKey("unknown-key")) {
- _ = try await manager.downloadAndInstall(
- manifest: manifest,
- downloader: FakeRuntimeDownloader(files: [
- URL(string: "https://example.test/segmentation-stub/bin")!: executableData
- ])
- )
- }
-
- let trustedManager = try runtimeManager(
- baseDirectory: root,
- trustedManifestSigningKeys: [
- LocalModelRuntimeManifestSigningKey(
- keyID: "unknown-key",
- publicKeyBase64: privateKey.publicKey.rawRepresentation.base64EncodedString()
- )
- ],
- requiresCryptographicManifestSignatures: true
- )
- var tampered = manifest
- tampered.runtimeVersion = "2.0.0"
-
- await #expect(throws: LocalModelRuntimeSetupError.manifestInvalidSignature) {
- _ = try await trustedManager.downloadAndInstall(
- manifest: tampered,
- downloader: FakeRuntimeDownloader(files: [
- URL(string: "https://example.test/segmentation-stub/bin")!: executableData
- ])
- )
- }
- }
-
- @Test
- func manifestDownloadRejectsMissingSignatureAndBadChecksums() async throws {
- let root = temporaryDirectory()
- defer { try? FileManager.default.removeItem(at: root) }
- let data = Data("#!/bin/sh\necho ok\n".utf8)
- let manager = try runtimeManager(baseDirectory: root)
- let unsigned = LocalModelRuntimePackageManifest(
- runtimeID: .screenshotSegmentationStub,
- runtimeVersion: "1.0.0",
- modelID: "stubbed-screenshot-segmentation",
- executableRelativePath: "bin/donkey-screenshot-segmentation-stub",
- files: [
- LocalModelRuntimePackageFile(
- relativePath: "bin/donkey-screenshot-segmentation-stub",
- downloadURL: URL(string: "https://example.test/segmentation-stub/bin")!,
- sha256: LocalModelRuntimeSetupManager.sha256Hex(data),
- isExecutable: true
- )
- ]
- )
-
- await #expect(throws: LocalModelRuntimeSetupError.manifestMissingSignature) {
- _ = try await manager.downloadAndInstall(
- manifest: unsigned,
- downloader: FakeRuntimeDownloader(files: [URL(string: "https://example.test/segmentation-stub/bin")!: data])
- )
- }
-
- let signedWithBadHash = LocalModelRuntimePackageManifest(
- runtimeID: .screenshotSegmentationStub,
- runtimeVersion: "1.0.0",
- modelID: "stubbed-screenshot-segmentation",
- executableRelativePath: "bin/donkey-screenshot-segmentation-stub",
- files: [
- LocalModelRuntimePackageFile(
- relativePath: "bin/donkey-screenshot-segmentation-stub",
- downloadURL: URL(string: "https://example.test/segmentation-stub/bin")!,
- sha256: "bad",
- isExecutable: true
- )
- ],
- signature: "signed",
- signingKeyID: "test-key"
- )
-
- await #expect(throws: LocalModelRuntimeSetupError.manifestFileHashMismatch(relativePath: "bin/donkey-screenshot-segmentation-stub")) {
- _ = try await manager.downloadAndInstall(
- manifest: signedWithBadHash,
- downloader: FakeRuntimeDownloader(files: [URL(string: "https://example.test/segmentation-stub/bin")!: data])
- )
- }
- }
-
- @Test
- func recheckHealthRunsSidecarHealthProtocol() async throws {
- let root = temporaryDirectory()
- let download = temporaryDirectory()
- defer {
- try? FileManager.default.removeItem(at: root)
- try? FileManager.default.removeItem(at: download)
- }
- let healthExecutable = try makeHealthExecutable(
- root: download,
- relativePath: "bin/donkey-parakeet-transcriber",
- runtimeID: "parakeet-transcriber",
- runtimeVersion: "1.2.3",
- modelID: "nvidia/parakeet-tdt-0.6b-v3"
- )
- let manager = try runtimeManager(baseDirectory: root)
- try manager.registerExecutable(
- runtimeID: .parakeetTranscriber,
- executableURL: healthExecutable,
- downloadedDirectory: download,
- runtimeVersion: "1.2.3",
- modelID: "nvidia/parakeet-tdt-0.6b-v3",
- sidecarProtocolVersion: "v1"
- )
-
- let report = try await manager.recheckHealth(runtimeID: .parakeetTranscriber)
-
- #expect(report.state == .healthy)
- #expect(report.runtimeVersion == "1.2.3")
- #expect(report.modelID == "nvidia/parakeet-tdt-0.6b-v3")
- }
-
- @Test
- func recheckHealthFailsWhenModelWeightsAreMissing() async throws {
- let root = temporaryDirectory()
- let download = temporaryDirectory()
- defer {
- try? FileManager.default.removeItem(at: root)
- try? FileManager.default.removeItem(at: download)
- }
- let healthExecutable = try makeHealthExecutable(
- root: download,
- relativePath: "bin/donkey-local-llm",
- runtimeID: "local-llm",
- runtimeVersion: "1.2.3",
- modelID: "qwen2.5-0.5b-instruct-q4_k_m",
- metadataJSON: #"{"modelWeights.status":"missing","modelWeights.provider":"donkey-managed-download"}"#
- )
- let manager = try runtimeManager(baseDirectory: root)
- try manager.registerExecutable(
- runtimeID: .localLLM,
- executableURL: healthExecutable,
- downloadedDirectory: download,
- runtimeVersion: "1.2.3",
- modelID: "qwen2.5-0.5b-instruct-q4_k_m",
- sidecarProtocolVersion: "v1"
- )
-
- let report = try await manager.recheckHealth(runtimeID: .localLLM)
-
- #expect(report.state == .failed)
- #expect(report.metadata["modelWeights.status"] == "missing")
- }
-
- @Test
- func prepareModelWeightsRunsSidecarPreparationProtocol() async throws {
- let root = temporaryDirectory()
- let download = temporaryDirectory()
- defer {
- try? FileManager.default.removeItem(at: root)
- try? FileManager.default.removeItem(at: download)
- }
- let executable = try makeModelPreparationExecutable(
- root: download,
- relativePath: "bin/donkey-ui-understander",
- runtimeID: "ui-understander",
- modelID: "local-ui-understander"
- )
- let manager = try runtimeManager(baseDirectory: root)
- try manager.registerExecutable(
- runtimeID: .uiUnderstander,
- executableURL: executable,
- downloadedDirectory: download,
- runtimeVersion: "1.0.0",
- modelID: "local-ui-understander",
- sidecarProtocolVersion: "v1",
- metadata: [
- "modelWeights.downloadURL": "https://example.test/ui/model.bin",
- "modelWeights.sha256": "abc",
- "modelWeights.filename": "ui.bin"
- ]
- )
-
- let report = try await manager.prepareModelWeights(runtimeID: .uiUnderstander)
-
- #expect(report.state == .prepared)
- #expect(report.modelID == "local-ui-understander")
- #expect(report.cacheDirectory?.contains("/ModelWeights/ui-understander/local-ui-understander") == true)
- #expect(report.metadata["modelWeights.status"] == "downloaded")
- }
-
- @Test
- func removeRuntimeClearsRegistryAndManagedFiles() throws {
- let root = temporaryDirectory()
- let download = root.appendingPathComponent("Packages/screenshot-segmentation-stub/1.0.0", isDirectory: true)
- defer { try? FileManager.default.removeItem(at: root) }
- let executable = try makeExecutable(
- root: download,
- relativePath: "bin/donkey-screenshot-segmentation-stub"
- )
- let manager = try runtimeManager(baseDirectory: root)
- try manager.registerExecutable(
- runtimeID: .screenshotSegmentationStub,
- executableURL: executable,
- downloadedDirectory: download,
- runtimeVersion: "1.0.0",
- modelID: "stubbed-screenshot-segmentation"
- )
-
- let removed = try manager.removeRuntime(runtimeID: .screenshotSegmentationStub)
- let status = try manager.status(for: .screenshotSegmentationStub)
-
- #expect(removed)
- #expect(status.state == .notInstalled)
- #expect(!FileManager.default.fileExists(atPath: download.path))
- }
-
- @Test
- func supportExportOmitsUserDataAndHasNoDefaultLocalModelStatus() throws {
- let root = temporaryDirectory()
- defer { try? FileManager.default.removeItem(at: root) }
- let manager = try LocalModelRuntimeSetupManager(baseDirectory: root)
-
- let snapshot = try manager.supportSnapshot()
- let exportData = try manager.supportExportData()
- let exportText = String(decoding: exportData, as: UTF8.self)
-
- #expect(snapshot.statuses.isEmpty)
- #expect(!exportText.contains("parakeet-transcriber"))
- #expect(!exportText.contains(root.path))
- }
-
- private func runtimeManager(
- baseDirectory: URL,
- trustedManifestSigningKeys: [LocalModelRuntimeManifestSigningKey] = [],
- requiresCryptographicManifestSignatures: Bool = false
- ) throws -> LocalModelRuntimeSetupManager {
- try LocalModelRuntimeSetupManager(
- baseDirectory: baseDirectory,
- specs: fixtureRuntimeSpecs,
- trustedManifestSigningKeys: trustedManifestSigningKeys,
- requiresCryptographicManifestSignatures: requiresCryptographicManifestSignatures
- )
- }
-
- private var fixtureRuntimeSpecs: [LocalModelRuntimeSpec] {
- [
- LocalModelRuntimeSpec(
- id: .parakeetTranscriber,
- displayName: "Parakeet voice transcription",
- environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
- expectedExecutableRelativePath: "bin/donkey-parakeet-transcriber",
- modelName: "nvidia/parakeet-tdt-0.6b-v3",
- downloadPageURL: nil,
- manifestURL: nil,
- installSteps: []
- ),
- LocalModelRuntimeSpec(
- id: .screenshotSegmentationStub,
- displayName: "Screenshot segmentation stub",
- environmentVariableName: "DONKEY_SCREENSHOT_SEGMENTATION_STUB",
- expectedExecutableRelativePath: "bin/donkey-screenshot-segmentation-stub",
- modelName: "stubbed-screenshot-segmentation",
- downloadPageURL: nil,
- manifestURL: nil,
- installSteps: []
- ),
- LocalModelRuntimeSpec(
- id: .uiUnderstander,
- displayName: "Local UI understanding",
- environmentVariableName: "DONKEY_UI_UNDERSTANDER",
- expectedExecutableRelativePath: "bin/donkey-ui-understander",
- modelName: "local-ui-understander",
- downloadPageURL: nil,
- manifestURL: nil,
- installSteps: []
- ),
- LocalModelRuntimeSpec(
- id: .localLLM,
- displayName: "Local LLM",
- environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER",
- expectedExecutableRelativePath: "bin/donkey-local-llm",
- modelName: "qwen2.5-0.5b-instruct-q4_k_m",
- downloadPageURL: nil,
- manifestURL: nil,
- installSteps: []
- )
- ]
- }
-
- private func makeExecutable(
- root: URL,
- relativePath: String
- ) throws -> URL {
- try makeFile(root: root, relativePath: relativePath, permissions: 0o755)
- }
-
- private func makeExecutable(
- root: URL,
- relativePath: String,
- data: Data
- ) throws -> URL {
- try makeFile(root: root, relativePath: relativePath, permissions: 0o755, data: data)
- }
-
- private func makeFile(
- root: URL,
- relativePath: String,
- permissions: Int,
- data: Data = Data("#!/bin/sh\ncat\n".utf8)
- ) throws -> URL {
- let url = relativePath
- .split(separator: "/")
- .reduce(root) { partialURL, component in
- partialURL.appendingPathComponent(String(component), isDirectory: false)
- }
- try FileManager.default.createDirectory(
- at: url.deletingLastPathComponent(),
- withIntermediateDirectories: true
- )
- try data.write(to: url)
- try FileManager.default.setAttributes(
- [.posixPermissions: permissions],
- ofItemAtPath: url.path
- )
- return url
- }
-
- private func makeHealthExecutable(
- root: URL,
- relativePath: String,
- runtimeID: String,
- runtimeVersion: String,
- modelID: String,
- metadataJSON: String = #"{"health":"ok"}"#
- ) throws -> URL {
- let script = """
- #!/bin/sh
- cat >/dev/null
- printf '{"status":"ok","runtimeID":"\(runtimeID)","runtimeVersion":"\(runtimeVersion)","modelID":"\(modelID)","protocolVersion":"v1","metadata":\(metadataJSON)}'
- """
- let url = relativePath
- .split(separator: "/")
- .reduce(root) { partialURL, component in
- partialURL.appendingPathComponent(String(component), isDirectory: false)
- }
- try FileManager.default.createDirectory(
- at: url.deletingLastPathComponent(),
- withIntermediateDirectories: true
- )
- try Data(script.utf8).write(to: url)
- try FileManager.default.setAttributes(
- [.posixPermissions: 0o755],
- ofItemAtPath: url.path
- )
- return url
- }
-
- private func makeModelPreparationExecutable(
- root: URL,
- relativePath: String,
- runtimeID: String,
- modelID: String
- ) throws -> URL {
- let script = """
- #!/bin/sh
- REQUEST="$(cat)"
- CACHE="$(printf '%s' "$REQUEST" | sed -n 's/.*"cacheDirectory"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p' | head -n 1)"
- mkdir -p "$CACHE"
- printf '{"status":"ok","runtimeID":"\(runtimeID)","modelID":"\(modelID)","cacheDirectory":"%s","metadata":{"modelWeights.status":"downloaded"}}' "$CACHE"
- """
- let url = relativePath
- .split(separator: "/")
- .reduce(root) { partialURL, component in
- partialURL.appendingPathComponent(String(component), isDirectory: false)
- }
- try FileManager.default.createDirectory(
- at: url.deletingLastPathComponent(),
- withIntermediateDirectories: true
- )
- try Data(script.utf8).write(to: url)
- try FileManager.default.setAttributes(
- [.posixPermissions: 0o755],
- ofItemAtPath: url.path
- )
- return url
- }
-
- private func temporaryDirectory() -> URL {
- FileManager.default.temporaryDirectory
- .appendingPathComponent("donkey-runtime-setup-tests-\(UUID().uuidString)", isDirectory: true)
- }
-}
-
-private struct FakeRuntimeDownloader: LocalModelRuntimePackageDownloading {
- var files: [URL: Data]
-
- func download(from url: URL) async throws -> Data {
- try #require(files[url])
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
index cfa12c8a..610e6412 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
@@ -58,44 +58,6 @@ struct ManualCaptureDebugCommandTests {
}
}
- @Test
- func localRuntimeInstallCommandsParseStatusInstructionsAndInstall() throws {
- #expect(try ManualCaptureDebugCommandParser.parse(
- arguments: ["Donkey", "--local-runtime-status"]
- ) == .localRuntimeStatus)
- #expect(try ManualCaptureDebugCommandParser.parse(
- arguments: ["Donkey", "--local-runtime-support"]
- ) == .localRuntimeSupport)
- #expect(try ManualCaptureDebugCommandParser.parse(
- arguments: ["Donkey", "--local-runtime-instructions"]
- ) == .localRuntimeInstructions)
-
- let command = try ManualCaptureDebugCommandParser.parse(
- arguments: [
- "Donkey",
- "--install-local-runtime",
- "--runtime-id",
- "screenshot-segmentation-stub",
- "--runtime-source",
- "/tmp/segmentation-stub-runtime"
- ]
- )
-
- #expect(command == .installLocalRuntime(
- LocalRuntimeInstallDebugOptions(
- runtimeID: .screenshotSegmentationStub,
- sourceDirectory: URL(fileURLWithPath: "/tmp/segmentation-stub-runtime")
- )
- ))
-
- #expect(try ManualCaptureDebugCommandParser.parse(
- arguments: ["Donkey", "--repair-local-runtime", "--runtime-id", "screenshot-segmentation-stub"]
- ) == .repairLocalRuntime(.screenshotSegmentationStub))
- #expect(try ManualCaptureDebugCommandParser.parse(
- arguments: ["Donkey", "--remove-local-runtime", "--runtime-id", "screenshot-segmentation-stub"]
- ) == .removeLocalRuntime(.screenshotSegmentationStub))
- }
-
@Test
func localAppTaskCommandParsesSubmittedCommand() throws {
let command = try ManualCaptureDebugCommandParser.parse(
@@ -112,21 +74,6 @@ struct ManualCaptureDebugCommandTests {
))
}
- @Test
- func invalidLocalRuntimeIDReturnsCommandError() throws {
- #expect(throws: ManualCaptureDebugCommandParseError.invalidRuntimeID("weather")) {
- _ = try ManualCaptureDebugCommandParser.parse(
- arguments: [
- "--install-local-runtime",
- "--runtime-id",
- "weather",
- "--runtime-source",
- "/tmp/runtime"
- ]
- )
- }
- }
-
@Test
func missingWindowIDValueReturnsCommandError() throws {
#expect(throws: ManualCaptureDebugCommandParseError.missingValue("--window-id")) {
@@ -193,29 +140,6 @@ struct ManualCaptureDebugCommandTests {
])
}
- @Test
- func runtimeSetupFormattersPrintInstructionsAndStatus() throws {
- let manager = try LocalModelRuntimeSetupManager(baseDirectory: temporaryDirectory())
- let instructionLines = ManualCaptureDebugCommandFormatter.lines(
- for: manager.instructions()
- )
- let statusLines = ManualCaptureDebugCommandFormatter.lines(
- for: try manager.statuses()
- )
-
- #expect(instructionLines.contains("local runtime setup instructions"))
- #expect(instructionLines.contains("runtime=parakeet-transcriber"))
- #expect(instructionLines.contains("expectedExecutable=bin/donkey-parakeet-transcriber"))
- #expect(statusLines.contains("local runtime status"))
- #expect(statusLines.contains("runtime=screenshot-segmentation-stub | state=notInstalled | env=DONKEY_SCREENSHOT_SEGMENTATION_STUB | executable=- | reason=noRegisteredRuntime"))
-
- let supportLines = ManualCaptureDebugCommandFormatter.lines(
- for: try manager.supportSnapshot()
- )
- #expect(supportLines.contains("local runtime support snapshot"))
- #expect(supportLines.contains { $0.contains("runtime=local-llm") })
- }
-
@Test
func manualCaptureModeCanDriveExistingServiceWithExplicitWindowID() async throws {
let root = temporaryDirectory()
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/PointerCoachCursorGuideResolverTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerCoachCursorGuideResolverTests.swift
deleted file mode 100644
index e7c1fb9f..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/PointerCoachCursorGuideResolverTests.swift
+++ /dev/null
@@ -1,161 +0,0 @@
-import DonkeyAI
-import DonkeyContracts
-import DonkeyRuntime
-import Foundation
-import Testing
-
-@Suite
-struct AgentVisualizationPlanResolverTests {
- @Test
- func localLLMResolverBuildsPlanFromStructuredModelOutput() async throws {
- let sidecar = RecordingAgentVisualizationSidecarRunner(
- result: LocalJSONSidecarResult(
- status: .completed,
- outputData: sidecarResponseData(outputText: """
- {
- "shouldVisualize": true,
- "title": "Show Export Controls",
- "goal": "export the design",
- "targetApp": "Design App",
- "confidence": 0.91,
- "reason": "The user asked for visual instruction inside an app.",
- "steps": [
- {"label": "Open the export menu", "x": 0.82, "y": 0.18, "travelDuration": 0.4, "holdDuration": 0.8},
- {"label": "Choose the file type", "x": 0.72, "y": 0.36}
- ],
- "metadata": {"modelDecision": "coach"}
- }
- """)
- )
- )
- let resolver = ProcessBackedLocalLLMAgentVisualizationPlanResolver(
- router: AIModelRouter(registry: registry()),
- sidecarRunner: sidecar
- )
-
- let result = await resolver.resolveVisualizationPlan(
- AgentVisualizationPlanResolverRequest(
- command: "please demonstrate the export flow",
- runtimeCapabilities: ["app_open: open local item"],
- cacheSnippets: ["local_resolution_cache: name=\"Design App\" kind=application"],
- sourceTraceID: "trace-visualization"
- )
- )
-
- let cursorRequest = try #require(result.cursorRequest)
- let visualizationPlan = try #require(result.visualizationPlan)
- #expect(result.confidence == 0.91)
- #expect(result.trace.validationStatus == "visualizationDecoded")
- #expect(visualizationPlan.executionMode == .visualOnly)
- #expect(visualizationPlan.usesRealPointer == false)
- #expect(visualizationPlan.metadata["source"] == "local-llm-agent-visualization")
- #expect(visualizationPlan.steps.map(\.label) == ["Open the export menu", "Choose the file type"])
- #expect(cursorRequest.title == "Show Export Controls")
- #expect(cursorRequest.metadata["source"] == "local-llm-agent-visualization")
- #expect(cursorRequest.metadata["modelDecision"] == "coach")
- #expect(cursorRequest.steps.map(\.label) == ["Open the export menu", "Choose the file type"])
- #expect(cursorRequest.steps.first?.target.x == 0.82)
-
- let requests = await sidecar.requests()
- let request = try #require(requests.first)
- #expect(request.environmentVariableName == "DONKEY_LOCAL_LLM_RUNNER")
- #expect(request.metadata["sidecar.role"] == "agentVisualizationPlan")
- let input = try JSONDecoder().decode(AgentVisualizationSidecarInputProbe.self, from: request.inputData)
- #expect(input.command == "please demonstrate the export flow")
- #expect(input.runtimeCapabilities == ["app_open: open local item"])
- #expect(input.cacheSnippets == ["local_resolution_cache: name=\"Design App\" kind=application"])
- #expect(input.metadata["schemaID"] == ProcessBackedLocalLLMAgentVisualizationPlanResolver.schemaID)
- }
-
- @Test
- func localLLMResolverDoesNotCreatePlanWhenModelSaysNo() async throws {
- let sidecar = RecordingAgentVisualizationSidecarRunner(
- result: LocalJSONSidecarResult(
- status: .completed,
- outputData: sidecarResponseData(outputText: """
- {
- "shouldVisualize": false,
- "title": null,
- "goal": null,
- "targetApp": null,
- "confidence": 0.88,
- "reason": "This is an actionable app command, not a visual-only visualization request.",
- "steps": []
- }
- """)
- )
- )
- let resolver = ProcessBackedLocalLLMAgentVisualizationPlanResolver(
- router: AIModelRouter(registry: registry()),
- sidecarRunner: sidecar
- )
-
- let result = await resolver.resolveVisualizationPlan(
- AgentVisualizationPlanResolverRequest(
- command: "show me the weather for SF",
- sourceTraceID: "trace-no-visualization"
- )
- )
-
- #expect(result.cursorRequest == nil)
- #expect(result.visualizationPlan == nil)
- #expect(result.confidence == 0.88)
- #expect(result.trace.validationStatus == "notVisualization")
- }
-
- private func registry() -> AIModelRegistry {
- AIModelRegistry(
- entries: [
- AIModelRegistryEntry(
- id: "local-visualization-test",
- role: .taskIntent,
- provider: .localRuntime,
- modelID: "local-visualization-model",
- endpoint: URL(string: "local://visualization")!,
- capabilities: [.textInput, .structuredOutputs],
- timeoutMS: 1_000,
- promptVersion: "agent-visualization-test",
- evalStatus: .candidate,
- docsURL: URL(string: "https://example.test/model")!
- )
- ]
- )
- }
-
- private func sidecarResponseData(outputText: String) -> Data {
- (try? JSONEncoder().encode(AgentVisualizationSidecarResponseProbe(
- outputText: outputText,
- metadata: ["sidecar": "test"]
- ))) ?? Data()
- }
-}
-
-private actor RecordingAgentVisualizationSidecarRunner: LocalJSONSidecarRunning {
- private let result: LocalJSONSidecarResult
- private var recordedRequests: [LocalJSONSidecarRequest] = []
-
- init(result: LocalJSONSidecarResult) {
- self.result = result
- }
-
- func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {
- recordedRequests.append(request)
- return result
- }
-
- func requests() -> [LocalJSONSidecarRequest] {
- recordedRequests
- }
-}
-
-private struct AgentVisualizationSidecarInputProbe: Decodable {
- var command: String
- var runtimeCapabilities: [String]
- var cacheSnippets: [String]
- var metadata: [String: String]
-}
-
-private struct AgentVisualizationSidecarResponseProbe: Encodable {
- var outputText: String
- var metadata: [String: String]
-}