Open source CapCut alternative.
TypeScript
Add one-button local runtime setup flow
David Le401f4b96446d
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex db4a5415..1649b9fb 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -4,6 +4,7 @@ import Darwin@MainActorfinal class DonkeyAppDelegate: NSObject, NSApplicationDelegate {private var overlayController: PointerPromptOverlayController?+ private var runtimeOnboardingController: LocalRuntimeOnboardingWindowController?func applicationDidFinishLaunching(_ notification: Notification) {if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {@@ -23,6 +24,10 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {let controller = PointerPromptOverlayController(model: model)overlayController = controllercontroller.show()++ let runtimeOnboardingController = LocalRuntimeOnboardingWindowController()+ self.runtimeOnboardingController = runtimeOnboardingController+ runtimeOnboardingController.showIfSetupNeeded()}func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {diff --git a/apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swift b/apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swiftnew file mode 100644index 00000000..0fc7f1d1--- /dev/null+++ b/apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swift@@ -0,0 +1,219 @@+import AppKit+import DonkeyRuntime+import SwiftUI++@MainActor+final class LocalRuntimeOnboardingWindowController: NSWindowController {+ private let model: LocalRuntimeOnboardingModel++ init(model: LocalRuntimeOnboardingModel = LocalRuntimeOnboardingModel()) {+ self.model = model+ let view = LocalRuntimeOnboardingView(model: model)+ let hostingController = NSHostingController(rootView: view)+ let window = NSWindow(contentViewController: hostingController)+ window.title = "Donkey Setup"+ window.styleMask = [.titled, .closable, .miniaturizable]+ window.setContentSize(NSSize(width: 480, height: 260))+ window.isReleasedWhenClosed = false+ super.init(window: window)+ }++ required init?(coder: NSCoder) {+ nil+ }++ func showIfSetupNeeded() {+ Task {+ await model.refresh()+ guard model.needsSetup else { return }+ showWindow(nil)+ window?.center()+ NSApp.activate(ignoringOtherApps: true)+ }+ }+}++@MainActor+final class LocalRuntimeOnboardingModel: ObservableObject {+ @Published private(set) var state: LocalRuntimeSetupViewState = .checking+ @Published private(set) var summary = "Checking Donkey setup..."+ @Published private(set) var detail = "Donkey uses local model runtimes for voice, screenshots, and UI understanding."++ private let manager: LocalModelRuntimeSetupManager+ private var retryRuntimeIDs: [LocalModelRuntimeID] = []++ init(manager: LocalModelRuntimeSetupManager? = nil) {+ self.manager = manager ?? (try! LocalModelRuntimeSetupManager())+ }++ var needsSetup: Bool {+ state != .ready+ }++ var setupButtonTitle: String {+ switch state {+ case .checking:+ return "Checking..."+ case .setupNeeded:+ return "Set Up"+ case .needsAttention:+ return "Retry Setup"+ case .settingUp:+ return "Setting Up..."+ case .ready:+ return "Ready"+ }+ }++ var setupButtonDisabled: Bool {+ state == .checking || state == .settingUp || state == .ready+ }++ func refresh() async {+ state = .checking+ do {+ let statuses = try manager.statuses()+ let missingCount = statuses.filter { $0.state != .installed }.count+ if missingCount == 0 {+ retryRuntimeIDs.removeAll()+ state = .ready+ summary = "Donkey is ready."+ detail = "Required local runtimes are installed and available to the app."+ } else {+ retryRuntimeIDs = statuses+ .filter { $0.state != .installed }+ .map(\.spec.id)+ state = .setupNeeded+ summary = "Finish local setup."+ detail = "Donkey will download, verify, install, and health-check the required local runtime packages."+ }+ } catch {+ state = .needsAttention+ summary = "Setup needs attention."+ detail = "Could not read local runtime setup: \(String(describing: error))"+ }+ }++ func setup() async {+ state = .settingUp+ summary = "Setting up Donkey..."+ detail = "Downloading and verifying local runtime packages."++ do {+ let statuses = try manager.statuses()+ let missingRuntimeIDs = statuses+ .filter { $0.state != .installed }+ .map(\.spec.id)+ let runtimeIDsToInstall = manager.instructions()+ .map(\.spec.id)+ .filter { runtimeID in+ missingRuntimeIDs.contains(runtimeID) || retryRuntimeIDs.contains(runtimeID)+ }++ for (index, runtimeID) in runtimeIDsToInstall.enumerated() {+ do {+ _ = try await manager.downloadAndInstall(runtimeID: runtimeID)+ } catch LocalModelRuntimeSetupError.manifestMissingDownloadURL {+ retryRuntimeIDs = Array(runtimeIDsToInstall[index...])+ openDownloadPage(runtimeID)+ throw LocalRuntimeOnboardingError.automaticPackageUnavailable+ } catch {+ retryRuntimeIDs = Array(runtimeIDsToInstall[index...])+ throw error+ }+ }++ let healthFailures = try await recheckInstalledRuntimes()+ if healthFailures.isEmpty {+ retryRuntimeIDs.removeAll()+ state = .ready+ summary = "Donkey is ready."+ detail = "Local runtimes are installed, verified, and healthy."+ } else {+ retryRuntimeIDs = healthFailures+ state = .needsAttention+ summary = "Setup needs attention."+ detail = "A runtime installed but did not pass its health check. Retry setup to reinstall the failed runtime."+ }+ } catch LocalRuntimeOnboardingError.automaticPackageUnavailable {+ state = .needsAttention+ summary = "Runtime packages are not ready for automatic setup yet."+ detail = "Opened the runtime download page. Retry setup after the compatible package is available; already installed runtimes will be kept."+ } catch {+ state = .needsAttention+ summary = "Setup failed."+ detail = "\(String(describing: error)) Retry setup to continue from the failed runtime."+ }+ }++ private func recheckInstalledRuntimes() async throws -> [LocalModelRuntimeID] {+ var failedRuntimeIDs: [LocalModelRuntimeID] = []+ for instruction in manager.instructions() {+ let report = try await manager.recheckHealth(runtimeID: instruction.spec.id)+ guard report.state == .healthy else {+ failedRuntimeIDs.append(instruction.spec.id)+ continue+ }+ }+ return failedRuntimeIDs+ }++ private func openDownloadPage(_ runtimeID: LocalModelRuntimeID) {+ guard let url = manager.instructions()+ .first(where: { $0.spec.id == runtimeID })?+ .spec+ .downloadPageURL+ else {+ return+ }+ NSWorkspace.shared.open(url)+ }+}++enum LocalRuntimeSetupViewState: Equatable {+ case checking+ case setupNeeded+ case settingUp+ case ready+ case needsAttention+}++private enum LocalRuntimeOnboardingError: Error {+ case automaticPackageUnavailable+}++private struct LocalRuntimeOnboardingView: View {+ @ObservedObject var model: LocalRuntimeOnboardingModel++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ VStack(alignment: .leading, spacing: 8) {+ Text("Set Up Donkey")+ .font(.title2.weight(.semibold))+ Text(model.summary)+ .font(.headline)+ Text(model.detail)+ .foregroundStyle(.secondary)+ .font(.callout)+ .fixedSize(horizontal: false, vertical: true)+ }++ Spacer(minLength: 0)++ HStack {+ Spacer()+ Button(model.setupButtonTitle) {+ Task { await model.setup() }+ }+ .keyboardShortcut(.defaultAction)+ .disabled(model.setupButtonDisabled)+ .controlSize(.large)+ }+ }+ .padding(24)+ .frame(minWidth: 480, minHeight: 260)+ .task {+ await model.refresh()+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swiftindex d52aef1a..5a7bb290 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift@@ -1,3 +1,4 @@+import CryptoKitimport Foundationpublic enum LocalModelRuntimeID: String, Codable, CaseIterable, Equatable, Sendable {@@ -10,12 +11,34 @@ public enum LocalModelRuntimeInstallState: String, Codable, Equatable, Sendablecase installedcase notInstalledcase 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+}++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 struct LocalModelRuntimeSpec: Codable, Equatable, Sendable {@@ -25,6 +48,7 @@ public struct LocalModelRuntimeSpec: Codable, Equatable, Sendable {public var expectedExecutableRelativePath: Stringpublic var modelName: Stringpublic var downloadPageURL: URL?+ public var manifestURL: URL?public var installSteps: [String]public var metadata: [String: String]@@ -35,6 +59,7 @@ public struct LocalModelRuntimeSpec: Codable, Equatable, Sendable {expectedExecutableRelativePath: String,modelName: String,downloadPageURL: URL? = nil,+ manifestURL: URL? = nil,installSteps: [String],metadata: [String: String] = [:]) {@@ -44,16 +69,97 @@ public struct LocalModelRuntimeSpec: Codable, Equatable, Sendable {self.expectedExecutableRelativePath = expectedExecutableRelativePathself.modelName = modelNameself.downloadPageURL = downloadPageURL+ self.manifestURL = manifestURLself.installSteps = installStepsself.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: LocalModelRuntimeIDpublic var executablePath: Stringpublic var downloadedDirectoryPath: Stringpublic var installedAt: Date+ public var runtimeVersion: String?+ public var modelID: String?+ public var sidecarProtocolVersion: String?public var metadata: [String: String]public init(@@ -61,12 +167,18 @@ public struct LocalModelRuntimeInstallation: Codable, Equatable, Sendable {executablePath: String,downloadedDirectoryPath: String,installedAt: Date,+ runtimeVersion: String? = nil,+ modelID: String? = nil,+ sidecarProtocolVersion: String? = nil,metadata: [String: String] = [:]) {self.runtimeID = runtimeIDself.executablePath = executablePathself.downloadedDirectoryPath = downloadedDirectoryPathself.installedAt = installedAt+ self.runtimeVersion = runtimeVersion+ self.modelID = modelID+ self.sidecarProtocolVersion = sidecarProtocolVersionself.metadata = metadata}}@@ -90,6 +202,66 @@ public struct LocalModelRuntimeStatus: Codable, Equatable, Sendable {}}+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 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: LocalModelRuntimeSpecpublic var setupDirectory: URL@@ -135,9 +307,9 @@ public struct LocalModelRuntimeSetupManager: Sendable {modelName: "nvidia/parakeet-tdt-0.6b-v3",downloadPageURL: URL(string: "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3"),installSteps: [- "Download the Donkey-compatible Parakeet runtime package after installing Donkey.",- "Choose that downloaded runtime folder in Donkey setup.",- "Donkey validates bin/donkey-parakeet-transcriber and records the path in Application Support."+ "Click Set Up in Donkey after installing the app.",+ "Donkey downloads and verifies the compatible Parakeet runtime package.",+ "Donkey records bin/donkey-parakeet-transcriber in Application Support."],metadata: ["sidecar.role": "voiceTranscription"]),@@ -149,9 +321,9 @@ public struct LocalModelRuntimeSetupManager: Sendable {modelName: "ultralytics/yolo26n-seg",downloadPageURL: URL(string: "https://docs.ultralytics.com/models/yolo26/"),installSteps: [- "Download the Donkey-compatible YOLO26 segmentation runtime package after installing Donkey.",- "Choose that downloaded runtime folder in Donkey setup.",- "Donkey validates bin/donkey-yolo-segmenter and records the path in Application Support."+ "Click Set Up in Donkey after installing the app.",+ "Donkey downloads and verifies the compatible YOLO26 segmentation runtime package.",+ "Donkey records bin/donkey-yolo-segmenter in Application Support."],metadata: ["sidecar.role": "screenshotSegmentation"]),@@ -163,9 +335,9 @@ public struct LocalModelRuntimeSetupManager: Sendable {modelName: "local-ui-understander",downloadPageURL: nil,installSteps: [- "Download the Donkey-compatible local UI-understanding runtime package after installing Donkey.",- "Choose that downloaded runtime folder in Donkey setup.",- "Donkey validates bin/donkey-ui-understander and records the path in Application Support."+ "Click Set Up in Donkey after installing the app.",+ "Donkey downloads and verifies the compatible UI-understanding runtime package.",+ "Donkey records bin/donkey-ui-understander in Application Support."],metadata: ["sidecar.role": "uiUnderstanding"])@@ -222,6 +394,244 @@ public struct LocalModelRuntimeSetupManager: Sendable {)}+ 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+ }+ }++ @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"+ )+ )+ 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),+ response.status == "ok"+ else {+ return LocalModelRuntimeHealthReport(+ runtimeID: runtimeID,+ state: .invalidOutput,+ latencyMS: result.latencyMS,+ metadata: result.metadata+ )+ }++ return LocalModelRuntimeHealthReport(+ runtimeID: runtimeID,+ state: .healthy,+ runtimeVersion: response.runtimeVersion,+ modelID: response.modelID,+ sidecarProtocolVersion: response.protocolVersion,+ latencyMS: result.latencyMS,+ metadata: result.metadata.merging(response.metadata) { current, _ in current }+ )+ }+@discardableResultpublic func registerDownloadedRuntime(runtimeID: LocalModelRuntimeID,@@ -250,7 +660,11 @@ public struct LocalModelRuntimeSetupManager: Sendable {public func registerExecutable(runtimeID: LocalModelRuntimeID,executableURL: URL,- downloadedDirectory: 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(@@ -269,7 +683,10 @@ public struct LocalModelRuntimeSetupManager: Sendable {executablePath: executableURL.path,downloadedDirectoryPath: downloadedDirectory.path,installedAt: now(),- metadata: ["installedBy": "donkey-local-runtime-setup"]+ runtimeVersion: runtimeVersion,+ modelID: modelID,+ sidecarProtocolVersion: sidecarProtocolVersion,+ metadata: metadata)registry.installations[runtimeID.rawValue] = installationtry saveRegistry(registry)@@ -321,6 +738,21 @@ public struct LocalModelRuntimeSetupManager: Sendable {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 static func encoder() -> JSONEncoder {let encoder = JSONEncoder()encoder.outputFormatting = [.prettyPrinted, .sortedKeys]@@ -333,6 +765,26 @@ public struct LocalModelRuntimeSetupManager: Sendable {decoder.dateDecodingStrategy = .iso8601return decoder}++ public static func sha256Hex(_ data: Data) -> String {+ SHA256.hash(data: data)+ .map { String(format: "%02x", $0) }+ .joined()+ }+}++private struct LocalModelRuntimeHealthRequest: Codable, Equatable, Sendable {+ var operation: String+ var protocolVersion: 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]}public struct LocalModelRuntimeExecutableResolver: Sendable {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swiftindex 6ca85a30..8d2df68c 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift@@ -121,6 +121,137 @@ struct LocalModelRuntimeSetupTests {#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 LocalModelRuntimeSetupManager(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 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 LocalModelRuntimeSetupManager(baseDirectory: root)+ let unsigned = LocalModelRuntimePackageManifest(+ runtimeID: .yoloSegmenter,+ runtimeVersion: "1.0.0",+ modelID: "ultralytics/yolo26n-seg",+ executableRelativePath: "bin/donkey-yolo-segmenter",+ files: [+ LocalModelRuntimePackageFile(+ relativePath: "bin/donkey-yolo-segmenter",+ downloadURL: URL(string: "https://example.test/yolo/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/yolo/bin")!: data])+ )+ }++ let signedWithBadHash = LocalModelRuntimePackageManifest(+ runtimeID: .yoloSegmenter,+ runtimeVersion: "1.0.0",+ modelID: "ultralytics/yolo26n-seg",+ executableRelativePath: "bin/donkey-yolo-segmenter",+ files: [+ LocalModelRuntimePackageFile(+ relativePath: "bin/donkey-yolo-segmenter",+ downloadURL: URL(string: "https://example.test/yolo/bin")!,+ sha256: "bad",+ isExecutable: true+ )+ ],+ signature: "signed",+ signingKeyID: "test-key"+ )++ await #expect(throws: LocalModelRuntimeSetupError.manifestFileHashMismatch(relativePath: "bin/donkey-yolo-segmenter")) {+ _ = try await manager.downloadAndInstall(+ manifest: signedWithBadHash,+ downloader: FakeRuntimeDownloader(files: [URL(string: "https://example.test/yolo/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 LocalModelRuntimeSetupManager(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")+ }+private func makeExecutable(root: URL,relativePath: String@@ -150,8 +281,45 @@ struct LocalModelRuntimeSetupTests {return url}+ private func makeHealthExecutable(+ root: URL,+ relativePath: String,+ runtimeID: String,+ runtimeVersion: String,+ modelID: String+ ) throws -> URL {+ let script = """+ #!/bin/sh+ cat >/dev/null+ printf '{"status":"ok","runtimeID":"\(runtimeID)","runtimeVersion":"\(runtimeVersion)","modelID":"\(modelID)","protocolVersion":"v1","metadata":{"health":"ok"}}'+ """+ 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/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.mdindex fb115985..5b4c381e 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -46,7 +46,7 @@ Donkey also supports the first AI harness model registry and router boundary. `ADonkey also supports a reusable local JSON sidecar runner for local model processes. `ProcessBackedLocalJSONSidecarRunner` reads executable paths from environment variables first, then from Donkey's app-managed local runtime registry, validates executability, sends request JSON on stdin, captures stdout/stderr, records exit status and latency metadata, and returns explicit unavailable or failed statuses. Current model sidecars use `DONKEY_YOLO_SEGMENTER`, `DONKEY_PARAKEET_TRANSCRIBER`, and `DONKEY_UI_UNDERSTANDER`.-Donkey also supports the first post-install local runtime setup boundary. The app does not ship model weights or local model binaries. `LocalModelRuntimeSetupManager` describes the required Parakeet, YOLO26, and UI-understanding runtime packages, provides user-facing download/setup instructions, validates a user-downloaded runtime folder, and records the executable paths in `~/Library/Application Support/Donkey/LocalModelRuntimes/runtime-installations.json`. After registration, sidecar calls can resolve app-managed executables without shell environment variables. Developer launch arguments can print setup instructions, show install status, or register a downloaded runtime folder.+Donkey also supports the first post-install local runtime setup boundary. The app does not ship model weights or local model binaries. `LocalModelRuntimeSetupManager` describes the required Parakeet, YOLO26, and UI-understanding runtime packages, provides user-facing download/setup instructions, validates user-downloaded runtime folders, downloads manifest-backed package files, enforces SHA-256 checksums and required signature metadata, caches verified package files under Application Support, and records executable paths in `~/Library/Application Support/Donkey/LocalModelRuntimes/runtime-installations.json`. After registration, sidecar calls can resolve app-managed executables without shell environment variables. The first-run setup window exposes one setup button that downloads, verifies, installs, registers, and health-checks all required runtimes, with one overall ready or retryable needs-attention state. Retry keeps completed runtime installs and resumes at failed or not-yet-attempted runtimes. Developer launch arguments can print setup instructions, show install status, or register a downloaded runtime folder.Donkey also supports the first provider-neutral planner-hint adapter boundary using OpenAI's Responses API. `OpenAIPlannerHintAdapter` reads `OPENAI_API_KEY` from the environment, routes through the model registry, sends a structured-output Responses request with `store: false`, decodes a strict planner-hint JSON response, and records a model-call trace with role, provider, model id, prompt version, schema id, latency, timeout, validation status, and source trace/state ids. Missing credentials, cancellation, timeout, rate limit, invalid output, and provider outage return traceable failures without stopping the reflex loop. Official OpenAI docs were rechecked on May 16, 2026 for the Responses API, `text.format` JSON schema structured outputs, `store: false`, and current model registry default guidance.@@ -117,7 +117,7 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.- Keep local voice transcription as a Parakeet-only model-routed local runtime job. Transcription output is transcript text only and must enter the same validated command path as typed input before any task can run. If `DONKEY_PARAKEET_TRANSCRIBER` is missing or fails, the voice path fails clearly; it must not silently fall back to Whisper or any remote transcription provider.- Keep local model runtimes behind JSON sidecars. Use `DONKEY_YOLO_SEGMENTER`, `DONKEY_PARAKEET_TRANSCRIBER`, and `DONKEY_UI_UNDERSTANDER` for developer overrides, then Donkey's app-managed runtime registry for normal user installs. Return explicit unavailable results when executables are absent.-- Do not bundle model weights in the app. Users download compatible runtime packages after app install; Donkey validates the selected folder and records executable paths under Application Support.+- Do not bundle model weights in the app. Users download compatible runtime packages after app install; Donkey validates manifests, checksums, signature metadata, executable paths, and health checks, then records executable paths under Application Support.- Keep privacy-sensitive Responses API calls configured with `store: false` unless an explicit later policy changes that default.- Treat provider failures as sidecar failures. Missing credentials, timeout, rate limit, invalid output, or outage should leave the controller running on local state and existing valid hints.- Keep memory writes source-linked and scoped. Model-proposed memory writes must pass the deterministic approver before storage; target and user records require TTL or explicit durable retention.@@ -137,7 +137,7 @@ From `apps/Donkey/`:swift test```-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection, YOLO sidecar decoding and unavailable states, local UI-understanding observation decoding, local runtime setup instructions/status/registration, app-managed sidecar executable resolution, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parsing fallback and alias expansion, local task-definition loading, local-app catalog resolution and app availability checks, local task-context intake, Accessibility control discovery, document form-fill review planning, local-app navigation request construction, generic dry-run step projection, guarded keyboard and Accessibility command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles, component latency fields, replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, Parakeet-only local voice-transcription routing, Parakeet sidecar decoding and unavailable states, local JSON sidecar missing-env/nonzero-exit states, OpenAI Responses request shaping and failure handling, semantic memory retrieval, remote-bound redaction, model-call observability, provider-decoded memory proposal approval, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection, YOLO sidecar decoding and unavailable states, local UI-understanding observation decoding, local runtime setup instructions/status/registration, manifest-backed runtime download, checksum/signature enforcement, managed package cache install, health recheck, app-managed sidecar executable resolution, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parsing fallback and alias expansion, local task-definition loading, local-app catalog resolution and app availability checks, local task-context intake, Accessibility control discovery, document form-fill review planning, local-app navigation request construction, generic dry-run step projection, guarded keyboard and Accessibility command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles, component latency fields, replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, Parakeet-only local voice-transcription routing, Parakeet sidecar decoding and unavailable states, local JSON sidecar missing-env/nonzero-exit states, OpenAI Responses request shaping and failure handling, semantic memory retrieval, remote-bound redaction, model-call observability, provider-decoded memory proposal approval, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.Manual smoke commands:@@ -186,6 +186,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- YOLO screenshot segmentation runner boundary lives in `apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift`.- Local JSON sidecar running lives in `apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift`.- Local model runtime setup lives in `apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift`.+- First-run local runtime setup UI lives in `apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swift`.- Local UI-understanding observation lives in `apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift`.- Slow-planner sidecar triggers, snapshots, validated hint bus, and hint-aware controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift`.- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.diff --git a/plans/22-local-runtime-onboarding.md b/plans/22-local-runtime-onboarding.mdnew file mode 100644index 00000000..50b76110--- /dev/null+++ b/plans/22-local-runtime-onboarding.md@@ -0,0 +1,175 @@+# Local Runtime Onboarding Plan++This plan captures the installer and onboarding work Donkey should borrow from OpenWhispr's local model setup, adapted to Donkey's generic sidecar architecture.++OpenWhispr is stronger today at productized local transcription setup: it has packaged native binaries, a settings/control-panel flow, first-use model download, model choices, installation rechecks, and clear troubleshooting. Donkey should borrow those product patterns without copying the speech-app architecture. Donkey's local runtimes must remain generic sidecars that produce transcripts, observations, masks, memory proposals, or planner hints, never direct input actions.++## Goal++Make local model runtime setup feel like a normal post-install app flow:++1. Donkey ships without model weights.+2. The app exposes one setup action that downloads the compatible runtime packages.+3. Donkey validates expected executables, records them in Application Support, and health-checks them.+4. Users do not need to choose model folders or understand runtime-specific setup.+5. Sidecar execution works without users exporting shell environment variables.+6. If setup fails, users can retry the same setup action; already completed runtime installs are kept, failed or not-yet-attempted runtimes are retried, and repair, upgrade, and support diagnostics can exist behind that simple flow rather than as first-run choices.++## Borrow From OpenWhispr++- First-run setup UI for local model runtimes.+- One first-run setup button that performs download, validation, installation, registration, and health checks.+- Internal model/package status states for diagnostics: missing, downloading, installed, invalid, health-check failed, upgrade available.+- Checksum and signature validation for downloaded packages.+- Automatic installation recheck as part of setup and repair.+- Published runtime packages separate from the main app.+- Explicit cache/package locations.+- Troubleshooting copy for permissions, disk space, stale binaries, and slow performance.++## Donkey-Specific Design++Donkey should keep its current generic sidecar boundary:++- Parakeet sidecar returns transcript text only.+- YOLO sidecar returns segmentation masks only.+- UI-understanding sidecar returns visible text, controls, form fields, and confidence only.+- Sidecar output feeds observation, transcript, memory proposal, or planner-hint paths only.+- The action engine remains the only owner of OS input.++The app-managed runtime registry remains under:++```text+~/Library/Application Support/Donkey/LocalModelRuntimes/runtime-installations.json+```++Developer environment variables remain supported as overrides:++```text+DONKEY_PARAKEET_TRANSCRIBER+DONKEY_YOLO_SEGMENTER+DONKEY_UI_UNDERSTANDER+```++## Implementation Slices++### 1. Runtime Package Manifest++Define a signed manifest format for each runtime package:++- runtime id+- runtime version+- model id/version+- platform and architecture+- executable relative path+- model file relative paths+- expected SHA-256 hashes+- minimum Donkey version+- sidecar protocol version+- download URL+- release notes URL++Donkey rejects a package when the manifest is missing, unsigned, unsupported, mismatched, missing its executable, or hash-invalid. The current implementation enforces SHA-256 checksums and requires signature metadata. Cryptographic signature verification can be strengthened once the release signing key is finalized.++### 2. First-Run Setup UI++Add a small runtime setup surface reachable on first launch and from settings:++- Shows one overall setup state and one primary setup button.+- The setup button downloads, verifies, installs, registers, and health-checks all required runtimes.+- Failed setup returns to a retryable state with the same single button. Retry keeps completed runtimes and resumes at failed or not-yet-attempted runtimes.+- Explains that model weights are not bundled with the app.+- Does not expose per-runtime controls during first-run setup.+- Does not block typed-command MVP unless the requested feature needs the missing runtime.++### 3. Download And Install Flow++Support app-driven downloads where possible:++- Download to a temporary Application Support staging directory.+- Verify checksum and required signature metadata before registration.+- Move verified package files into a managed runtime directory.+- Mark executable permissions when needed.+- Record the installation in the runtime registry.+- Delete partial downloads after failure.++Manual folder registration remains available through developer launch arguments only.++### 4. Health Checks++Each runtime package should expose a cheap health command through the same process boundary:++```json+{"operation":"healthCheck","protocolVersion":"v1"}+```++Expected response:++```json+{+ "status": "ok",+ "runtimeID": "...",+ "runtimeVersion": "...",+ "modelID": "...",+ "protocolVersion": "v1",+ "metadata": {}+}+```++Health-check failures produce actionable status metadata and do not silently fall back.++### 5. Upgrade And Repair++Add runtime lifecycle operations:++- check for updates from the manifest channel+- download update+- verify before replacing current runtime+- keep one previous good runtime until new runtime health-checks pass+- rollback on failed install+- remove runtime and clear registry entry++### 6. Reporting And Support++Expose setup evidence in reports:++- installed runtime versions+- health-check status+- executable path source: env override or app registry+- package hash status+- model version+- protocol version++Add a support/debug export that omits user data and includes runtime setup status.++## Acceptance Criteria++- A fresh Donkey install can show local runtime setup instructions without Terminal env vars. Supported.+- A user can start app-managed runtime setup from one first-run button. Supported.+- Donkey refuses missing, non-executable, mismatched, unsigned, or hash-invalid runtime packages. Supported for executable presence, signature metadata, platform/architecture/runtime mismatch, and SHA-256 file hashes.+- Sidecar calls resolve registered executables from Application Support when env vars are absent. Supported.+- The first-run setup window avoids per-runtime customization and reports one overall ready or needs-attention state. Supported.+- `swift test` covers manifest validation, package download, checksum/signature enforcement, managed cache install, registration, health recheck, and app-registry sidecar resolution. Supported.+- Docs explain that model weights are downloaded after install and are not bundled in the app. Supported.++## Current Code Boundary++Already supported:++- `LocalModelRuntimeSetupManager` runtime specs, setup instructions, registration, status, and app-managed executable resolution.+- First-run local runtime setup window with one setup button that drives download, validation, install, registration, and health checks.+- Manifest-backed package download and managed cache install under Application Support.+- SHA-256 package file validation and required signature metadata.+- Sidecar health-check protocol through the existing JSON process runner.+- `ProcessBackedLocalJSONSidecarRunner` env-first then app-registry executable lookup.+- Debug commands:+ - `--local-runtime-instructions`+ - `--install-local-runtime --runtime-id <id> --runtime-source <folder>`+ - `--local-runtime-status`++Still needed:++- Publish real Donkey-compatible runtime package manifests and downloadable files.+- Finalize cryptographic signature verification with release signing keys.+- Settings-menu entry to reopen the setup window after first launch.+- Behind-the-scenes upgrade/repair/remove flows.+- Support/debug export.diff --git a/plans/master-plan.md b/plans/master-plan.mdindex cc3058c8..ddf06fc9 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -16,6 +16,7 @@ Supporting plans:- `plans/03-fast-controller.md`- `plans/05-action-engine.md`- `plans/06-benchmarking.md`+- `plans/22-local-runtime-onboarding.md`Completed supporting plans:@@ -55,7 +56,7 @@ The normal Weather benchmark path should work without a remote model call. A tin## Supported Boundary-- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, local model runtime setup/registration in Application Support, in-memory reflex trace retention, and stage-split latency reports are supported.+- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, first-run local runtime setup UI, manifest-backed runtime download/cache/registration in Application Support, sidecar health recheck, in-memory reflex trace retention, and stage-split latency reports are supported.- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, screenshot segmentation model-candidate catalog and runner boundary with Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`), process-backed YOLO sidecar decoding through `DONKEY_YOLO_SEGMENTER` or app-managed runtime registration, local UI-understanding sidecar decoding through `DONKEY_UI_UNDERSTANDER` or app-managed runtime registration, swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, dry-run action projection, generic local-app task intent contracts, data-driven task definitions, local JSON/JSONL task-definition loading, Ollama-compatible local-model command parsing to validated `TaskIntent`, deterministic parsing as fallback/validator, catalog command resolution, target-app availability checks, local task-context intake, Accessibility control discovery, document form-fill review planning, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard and Accessibility command templates, macOS app launch/focus, guarded macOS keyboard input, guarded `AXPress`/`AXSetValue` backend, pointer-prompt typed command submission, Accessibility visible-text observation when trusted, visible-text verification, component latency reporting, and built-in task definitions for Weather lookup, media playback, and document form-fill are supported. This is not yet a complete live fast-navigation agent: model binaries are user-downloaded after app install rather than bundled, UI-understanding is an adapter boundary rather than a default live observation path, and there is no manually verified live command-to-result Weather trace yet.- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with injected backends, the narrow macOS keyboard backend for local-app tasks, the narrow macOS Accessibility backend for discovered nodes, and replayable command traces are supported.- Slow AI boundary: local-model task-intent parsing, Parakeet-only local voice-transcription model routing and process-backed sidecar tracing through `DONKEY_PARAKEET_TRANSCRIBER` or app-managed runtime registration, structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, bounded semantic memory retrieval contracts, remote-bound redaction hooks, aggregate model-call observability reports, provider-decoded memory proposal handling through the deterministic approver, and replay/eval scaffolding are supported as optional sidecar pieces. NVIDIA Parakeet TDT 0.6B v3 is the selected local voice-transcription default with no Whisper fallback. This is not yet the complete AI harness because the pointer-prompt microphone capture path still needs to feed the Parakeet runtime and live sidecar binaries still need machine-local installation/benchmark evidence.@@ -84,13 +85,13 @@ Recent commits completed these pieces:- current slice: generic local-app task catalog, local-model command parser, deterministic fallback parser, app availability check, and dry-run adapter boundary, with Weather lookup represented as built-in benchmark data.- `d6e48c9`: archived plans, which was premature for this milestone.-The code now includes the first generic local-app task catalog, local JSON/JSONL task-definition loader, local task context provider, Accessibility control discovery/action planning, document form-fill review planner, Ollama-compatible local-model command parser, deterministic fallback parser, app availability check, dry-run adapter boundary, local-app live runner, macOS launch/focus, keyboard-input and Accessibility-input backends, pointer-prompt typed command wiring, sample app-task definitions across weather/media/document domains, YOLO26 screenshot segmentation model-candidate metadata and process-backed sidecar backend, local UI-understanding sidecar adapter, Parakeet-only local voice-transcription routing and sidecar runtime, shared JSON sidecar runner, post-install local runtime setup instructions/registration, semantic memory retrieval contracts, redaction hooks, aggregate model-call observability, provider-decoded memory proposal handling, and expanded latency reporting. It does not yet bundle model binaries, wire pointer-prompt microphone buffers into Parakeet, make local UI understanding the default live observation fallback, or include a manually verified live command-to-result Weather trace.+The code now includes the first generic local-app task catalog, local JSON/JSONL task-definition loader, local task context provider, Accessibility control discovery/action planning, document form-fill review planner, Ollama-compatible local-model command parser, deterministic fallback parser, app availability check, dry-run adapter boundary, local-app live runner, macOS launch/focus, keyboard-input and Accessibility-input backends, pointer-prompt typed command wiring, sample app-task definitions across weather/media/document domains, YOLO26 screenshot segmentation model-candidate metadata and process-backed sidecar backend, local UI-understanding sidecar adapter, Parakeet-only local voice-transcription routing and sidecar runtime, shared JSON sidecar runner, first-run local runtime setup UI, manifest-backed runtime download/cache/registration, checksum/signature metadata enforcement, sidecar health recheck, semantic memory retrieval contracts, redaction hooks, aggregate model-call observability, provider-decoded memory proposal handling, and expanded latency reporting. It does not yet publish real Donkey-compatible runtime packages, wire pointer-prompt microphone buffers into Parakeet, make local UI understanding the default live observation fallback, or include a manually verified live command-to-result Weather trace.## What Should Be Done Next1. Wire pointer-prompt microphone buffers into the Parakeet-only `LocalVoiceTranscriptionAdapter`, display transcript text, and submit that text through the same validated command-intent path as typed input.2. Integrate `ProcessBackedLocalUIUnderstandingAdapter` into live observation only when Accessibility/metadata are insufficient and a bounded screenshot/crop artifact is available; its output must remain an observation, never a direct action.-3. Package and publish Donkey-compatible runtime downloads, then run real machine-local sidecar binaries registered by the app-managed installer for YOLO, Parakeet, and UI understanding, and record benchmark evidence for weather/media/document tasks.+3. Follow `plans/22-local-runtime-onboarding.md` to publish real Donkey-compatible runtime package manifests/files, finalize release-key cryptographic signature verification, keep first-run setup to one app-managed button, add behind-the-scenes repair/remove flows, then run real machine-local sidecar binaries registered by the app-managed installer for YOLO, Parakeet, and UI understanding and record benchmark evidence for weather/media/document tasks.4. Connect semantic memory retrieval, redaction, aggregate model observability, and provider-decoded memory proposal handling into the live slow-planner/model-call paths, not just contract tests.5. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent, task definitions, app-knowledge updates, observation summaries, transcripts, memory proposals, or planner hints, never direct input.