Open source CapCut alternative.
TypeScript
refactor(app): source Gemini and detector config from code, not env [rebuild]
David Le95611ea443a5
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 5127b450..331b192b 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -1750,13 +1750,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {}}- /// Escape hatch to suppress the cosmetic animated-cursor playback (set `DONKEY_DISABLE_CURSOR_VIZ=1`).- /// The playback animates an overlay window's frame, which can trip a re-entrant AppKit layout crash on- /// some macOS builds; turning it off lets a run proceed (the harness still does the real vision input- /// and the text narration still updates).- static var cursorVisualizationDisabled: Bool {- ProcessInfo.processInfo.environment["DONKEY_DISABLE_CURSOR_VIZ"] == "1"- }+ /// Escape hatch to suppress the cosmetic animated-cursor playback. The playback animates an overlay+ /// window's frame, which can trip a re-entrant AppKit layout crash on some macOS builds; flip this to+ /// `true` to let a run proceed (the harness still does the real vision input and text narration).+ static let cursorVisualizationDisabled = falseprivate static func uptimeMilliseconds() -> Double {ProcessInfo.processInfo.systemUptime * 1_000diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swiftindex 85df55d0..ab8a0e1c 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift@@ -116,7 +116,7 @@ public struct DonkeyBackendInferenceConfiguration: Equatable, Sendable {return DonkeyBackendInferenceConfiguration(baseURL: baseURL,clientID: environment["DONKEY_CLIENT_ID"] ?? stableClientID(),- devAuthBypass: boolEnvironmentValue(environment["DONKEY_DEV_AUTH_BYPASS"])+ devAuthBypass: false)}@@ -141,15 +141,6 @@ public struct DonkeyBackendInferenceConfiguration: Equatable, Sendable {return trimmedValue?.isEmpty == false ? trimmedValue : nil}- private static func boolEnvironmentValue(_ value: String?) -> Bool {- switch trimmed(value)?.lowercased() {- case "1", "true", "yes", "on":- return true- default:- return false- }- }-private static func stableClientID() -> String {let key = "DonkeyBackendInferenceClientID"if let existing = UserDefaults.standard.string(forKey: key), !existing.isEmpty {diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swiftindex 2e4e9149..3d499b78 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift@@ -23,18 +23,17 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {/// this key instead of minting a Vertex token via the backend. Dev-only — a/// client-held key; prod uses the keyless Vertex path.public var apiKey: String?- /// Live model id for the Developer-API path (`GEMINI_LIVE_MODEL`). The Vertex- /// path ignores this (its model comes from the backend mint response).+ /// Live model id for the Developer-API path. The Vertex path ignores this (its+ /// model comes from the backend mint response).public var model: String- /// Model used for the per-turn vision driver (`GEMINI_VISION_MODEL`). This is a+ /// Model used for the per-turn vision driver. This is a/// turn-based `generateContent` model (not Live/bidi) running the built-in/// `computer_use` tool — a stronger model for screenshot grounding than the fast/// realtime command model.public var visionModel: String- /// Whether the Developer-API Live session requests AUDIO response modality- /// (`GEMINI_LIVE_AUDIO_OUTPUT`). The default Dev-API model is audio-output only,- /// so this defaults true; set falsey when pointing `GEMINI_LIVE_MODEL` at a- /// TEXT-capable Live model. Ignored on the Vertex path (always TEXT).+ /// Whether the Developer-API Live session requests AUDIO response modality. The+ /// default Dev-API model is audio-output only, so this defaults true; set falsey+ /// with a TEXT-capable Live model. Ignored on the Vertex path (always TEXT).public var liveAudioOutput: Bool/// Default Developer-API Live (command) model — the realtime, tool-calling@@ -62,24 +61,19 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {self.liveAudioOutput = liveAudioOutput}- /// Build from environment.- ///- /// - `GEMINI_LIVE_ENABLED` (bool) — the always-on Live session, **on by- /// default**; set to a falsey value to opt out.- /// - `GEMINI_LIVE_AUDIO` (bool) — also stream microphone audio (optional).- ///- /// The model id is owned by the backend (`GEMINI_LIVE_MODEL` there); the- /// client never selects it.+ /// Build from environment. Only `GEMINI_API_KEY` (a secret, dev-only) is read;+ /// the always-on Live session and its audio behavior are fixed in code. The+ /// model id is owned by the backend; the client never selects it.public static func fromEnvironment(_ environment: [String: String] = ProcessInfo.processInfo.environment) -> GeminiLiveConfiguration {GeminiLiveConfiguration(- enabled: boolValue(environment["GEMINI_LIVE_ENABLED"], default: true),- audioEnabled: boolValue(environment["GEMINI_LIVE_AUDIO"]),+ enabled: true,+ audioEnabled: false,apiKey: trimmed(environment["GEMINI_API_KEY"]),- model: trimmed(environment["GEMINI_LIVE_MODEL"]) ?? defaultModel,- visionModel: trimmed(environment["GEMINI_VISION_MODEL"]) ?? defaultVisionModel,- liveAudioOutput: boolValue(environment["GEMINI_LIVE_AUDIO_OUTPUT"], default: true)+ model: defaultModel,+ visionModel: defaultVisionModel,+ liveAudioOutput: true)}@@ -87,17 +81,4 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {let trimmedValue = value?.trimmingCharacters(in: .whitespacesAndNewlines)return trimmedValue?.isEmpty == false ? trimmedValue : nil}-- private static func boolValue(_ value: String?, default defaultValue: Bool = false) -> Bool {- switch trimmed(value)?.lowercased() {- case .none:- return defaultValue- case "1", "true", "yes", "on":- return true- case "0", "false", "no", "off":- return false- default:- return defaultValue- }- }}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConnectionFactory.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConnectionFactory.swiftindex 47e395e1..f8f914d2 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConnectionFactory.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConnectionFactory.swift@@ -5,8 +5,8 @@ import Foundation////// - **Developer API** (`GEMINI_API_KEY` set): connect directly to/// `generativelanguage.googleapis.com` with the key in the query string, using-/// the client-configured model (`GEMINI_LIVE_MODEL`, default-/// `GeminiLiveConfiguration.defaultModel` — an audio-output-only model). No+/// the hardcoded `GeminiLiveConfiguration.defaultModel` (an audio-output-only+/// model). No/// backend round-trip. Dev-only — a client-held key./// - **Vertex AI** (no key): mint a short-lived OAuth token via the backend/// (`DonkeyBackendInferenceClient.mintLiveConnection`); the model + endpoint@@ -38,7 +38,7 @@ public enum GeminiLiveConnectionFactory {// The key authenticates via the query string, so there's no bearer token.// The default Dev-API model is audio-output only, so `audioOutput` defaults// true (tool calls + output transcription still flow even when TEXT is- // rejected); set `GEMINI_LIVE_AUDIO_OUTPUT=0` for a TEXT-capable model.+ // rejected); use a TEXT-capable model to change that.return GeminiLiveConnection(url: url, bearerToken: nil, model: model, audioOutput: audioOutput)}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVoiceTranscriptionRuntime.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVoiceTranscriptionRuntime.swiftindex 24493499..bcac892f 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiVoiceTranscriptionRuntime.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVoiceTranscriptionRuntime.swift@@ -14,7 +14,7 @@ import Foundation/// stays on the backend. This is the production path.public struct GeminiVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {/// Turn-based transcription model. A fast flash model is plenty for short voice- /// commands; override with `GEMINI_TRANSCRIPTION_MODEL`.+ /// commands; bump here when adopting a newer transcription model.public static let defaultModel = "gemini-2.5-flash"private static let prompt =@@ -35,7 +35,7 @@ public struct GeminiVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {environment: [String: String] = ProcessInfo.processInfo.environment) {self.apiKey = GeminiGenerateContent.trimmed(apiKey ?? environment["GEMINI_API_KEY"])- self.model = GeminiGenerateContent.trimmed(model ?? environment["GEMINI_TRANSCRIPTION_MODEL"]) ?? Self.defaultModel+ self.model = GeminiGenerateContent.trimmed(model) ?? Self.defaultModelself.httpClient = httpClientself.environment = environment}@@ -45,8 +45,8 @@ public struct GeminiVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {model entry: AIModelRegistryEntry) async throws -> LocalVoiceTranscript {// Use the routed entry's model when it carries a usable one for this runtime; otherwise fall- // back to `self.model` (the env override, else the constant). The metadata reports what was- // used. `self.model` already folds env override over the constant.+ // back to `self.model` (an init-supplied model, else the constant). The metadata reports+ // what was used.let requestModel = Self.resolvedModel(entry: entry, fallback: model)let request: URLRequestif let apiKey {diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swiftindex 1f61746c..6f470989 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift@@ -18,7 +18,7 @@ public struct LocalUIElementNativeVisualDetector: Sendable {tesseractPath: String? = nil) {_ = maxAnalysisDimension- self.algorithm = algorithm ?? Self.algorithmFromEnvironment()+ self.algorithm = algorithm ?? .borderUIself.interactableDetector = GenericInteractableDetector(magickPath: magickPath,tesseractPath: tesseractPath@@ -393,21 +393,6 @@ public struct LocalUIElementNativeVisualDetector: Sendable {return box.kind}- private static func algorithmFromEnvironment(- environment: [String: String] = ProcessInfo.processInfo.environment- ) -> NativeVisualDetectionAlgorithm {- let value = environment["DONKEY_NATIVE_VISUAL_DETECTOR"]?- .trimmingCharacters(in: .whitespacesAndNewlines)- .lowercased()- switch value {- case "interactables", "interactables-v2", "generic-interactables", "generic-interactables-v2":- return .interactablesV2- case "border", "border-ui", "generic-border", "generic-border-ui":- return .borderUI- default:- return .borderUI- }- }}private struct NativeVisualDetectionResult: Equatable, Sendable {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swiftindex 8c0c5c7e..a113a71e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift@@ -632,19 +632,6 @@ struct DonkeyBackendInferenceClientTests {#expect(configuration.devAuthBypass == false)}- @Test- func configurationReadsDevAuthBypassEnvironment() throws {- let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment([- "DONKEY_WEB_BASE_URL": "https://web.donkey.example",- "DONKEY_CLIENT_ID": "client-env",- "DONKEY_DEV_AUTH_BYPASS": "1",- ])-- #expect(configuration.baseURL.absoluteString == "https://web.donkey.example")- #expect(configuration.clientID == "client-env")- #expect(configuration.devAuthBypass == true)- }-@Testfunc configurationUsesBundledWebBaseURL() throws {let fixture = try temporaryBundle(info: [diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swiftindex 591d8aa0..46c7ab4a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift@@ -8,19 +8,13 @@ import Testingstruct GeminiLiveTests {@Testfunc configurationParsesEnvironment() {- // Live is on by default with no env set; audio off.- let defaults = GeminiLiveConfiguration.fromEnvironment([:])- #expect(defaults.enabled)- #expect(defaults.audioEnabled == false)-- // Explicit opt-out.- let disabled = GeminiLiveConfiguration.fromEnvironment(["GEMINI_LIVE_ENABLED": "false"])- #expect(disabled.enabled == false)-- // Optional audio opt-in.- let withAudio = GeminiLiveConfiguration.fromEnvironment(["GEMINI_LIVE_AUDIO": "true"])- #expect(withAudio.enabled)- #expect(withAudio.audioEnabled)+ // Live is always on with audio off and audio-output on; only GEMINI_API_KEY+ // is read from the environment, the rest is fixed in code.+ let config = GeminiLiveConfiguration.fromEnvironment([:])+ #expect(config.enabled)+ #expect(config.audioEnabled == false)+ #expect(config.liveAudioOutput)+ #expect(config.apiKey == nil)}@Test@@ -67,19 +61,17 @@ struct GeminiLiveTests {@Testfunc developerAPIProviderUsesKeyModelAndAudioOutput() async throws {// GEMINI_API_KEY → connect directly to the Developer API with the key in- // the query string, the configured model, and AUDIO output (gemini-3.1- // Live is audio-only).+ // the query string, the hardcoded default model, and AUDIO output.let config = GeminiLiveConfiguration.fromEnvironment([- "GEMINI_API_KEY": "test-key-123",- "GEMINI_LIVE_MODEL": "gemini-3.1-flash-live-preview"+ "GEMINI_API_KEY": "test-key-123"])#expect(config.apiKey == "test-key-123")- #expect(config.model == "gemini-3.1-flash-live-preview")+ #expect(config.model == GeminiLiveConfiguration.defaultModel)let connection = try await GeminiLiveConnectionFactory.makeProvider(configuration: config)()#expect(connection.bearerToken == nil)#expect(connection.audioOutput)- #expect(connection.model == "gemini-3.1-flash-live-preview")+ #expect(connection.model == GeminiLiveConfiguration.defaultModel)#expect(connection.url.absoluteString.contains("generativelanguage.googleapis.com"))#expect(connection.url.query?.contains("key=test-key-123") == true)}@@ -94,9 +86,6 @@ struct GeminiLiveTests {#expect(defaults.apiKey == nil)#expect(defaults.model == GeminiLiveConfiguration.defaultModel)#expect(defaults.visionModel == "gemini-3.5-flash")- // GEMINI_VISION_MODEL overrides the vision model.- let overridden = GeminiLiveConfiguration.fromEnvironment(["GEMINI_VISION_MODEL": "gemini-2.5-pro"])- #expect(overridden.visionModel == "gemini-2.5-pro")}@Testdiff --git a/apps/Donkey/docs/fast-command-layer-and-gemini-live.md b/apps/Donkey/docs/fast-command-layer-and-gemini-live.mdindex e0e408cc..4d60d5cd 100644--- a/apps/Donkey/docs/fast-command-layer-and-gemini-live.md+++ b/apps/Donkey/docs/fast-command-layer-and-gemini-live.md@@ -113,13 +113,11 @@ from bypassing it.`GeminiLiveConnectionFactory.makeProvider` picks the connection path from config:- **Developer API** (`GEMINI_API_KEY` set): connect directly to- `wss://generativelanguage.googleapis.com/ws/...BidiGenerateContent?key=<KEY>` with the- client-configured model (`GEMINI_LIVE_MODEL`, default `GeminiLiveConfiguration.defaultModel`). No- backend round-trip. **Dev-only** — a client-held key; not for production. The default Dev-API model- is **audio-output only**: the session requests `AUDIO` response modality- (`GeminiLiveConnection.audioOutput`, controlled by `GEMINI_LIVE_AUDIO_OUTPUT`, default on); tool- calls and output transcription still flow, which is all the Command Layer needs. Point- `GEMINI_LIVE_MODEL` at a TEXT-capable Live model and set `GEMINI_LIVE_AUDIO_OUTPUT=0` to get TEXT.+ `wss://generativelanguage.googleapis.com/ws/...BidiGenerateContent?key=<KEY>` with the hardcoded+ `GeminiLiveConfiguration.defaultModel`. No backend round-trip. **Dev-only** — a client-held key;+ not for production. That model is **audio-output only**: the session requests `AUDIO` response+ modality (`GeminiLiveConnection.audioOutput`, on by default in code); tool calls and output+ transcription still flow, which is all the Command Layer needs.- **Vertex AI** (no key — production): the backend authenticates with Google Cloud OAuth(service-account) credentials. `DonkeyBackendInferenceClient.mintLiveConnection()` →`POST /api/inference/live-token/` (`site/src/app/api/inference/live-token/route.ts` +@@ -133,16 +131,14 @@ Both produce a single `GeminiLiveConnection` (url + optional bearer + model + au### Configuration+Everything about the Live session — always-on, mic audio off, audio-output on, model ids, and the+Vertex `global` location — is fixed in code. Only two secrets are read from the environment; both are+optional depending on the auth path.+| Variable | Where | Meaning ||---|---|---|-| `GEMINI_LIVE_ENABLED` | client | Always-on Live session. **On by default**; set falsey to opt out. |-| `GEMINI_LIVE_AUDIO` | client | Also stream microphone audio (optional). Off by default. |-| `GEMINI_API_KEY` | client | **Dev-only.** When set, route the Live session through the Developer-API key path instead of Vertex. Default/production is keyless Vertex. |-| `GEMINI_LIVE_MODEL` | client (dev) / backend (Vertex) | Realtime command Live model. Vertex default `gemini-live-2.5-flash`; Dev-API default `gemini-2.5-flash-native-audio-preview-09-2025`. |-| `GEMINI_LIVE_AUDIO_OUTPUT` | client (dev) | Request AUDIO response modality on the Dev-API path. **On by default** (the default Dev-API model is audio-only); set falsey only with a TEXT-capable `GEMINI_LIVE_MODEL`. |-| `GEMINI_VISION_MODEL` | client | Turn-based **vision** model (default `gemini-3.5-flash`). A stronger, non-Live model used only when a task needs the screen — see below. |+| `GEMINI_API_KEY` | client | **Dev-only secret.** When set, route the Live session through the Developer-API key path instead of Vertex. Default/production is keyless Vertex. || `GOOGLE_APPLICATION_CREDENTIALS_JSON` | backend | Vertex service-account JSON used to mint tokens. |-| `GEMINI_VERTEX_LOCATION` | backend | Vertex location (default `global`). |### Two models: realtime command vs vision@@ -162,7 +158,7 @@ dropped while audio is streaming to avoid double-handling.## Continuous audio-When `GEMINI_LIVE_AUDIO` is enabled and the session connects, the model fires+Mic-audio streaming is off in code today. When it is on and the session connects, the model fires`onLiveAudioStreamingChanged(true)`; `UserQueryOverlayController` calls`MicrophoneWaveformMeter.startContinuousListening()`, which keeps the engine running (and ignoresUI-driven `stop()`s) so audio streams beyond the voice-capture window. Tear down via@@ -170,10 +166,9 @@ UI-driven `stop()`s) so audio streams beyond the voice-capture window. Tear down## Configuration recap-Live runs against Vertex AI using backend-minted OAuth tokens (no client-held API key). Enable/audio-are client toggles (`GEMINI_LIVE_ENABLED` on by default, `GEMINI_LIVE_AUDIO` opt-in). The backend-route needs `GOOGLE_APPLICATION_CREDENTIALS_JSON` and optionally `GEMINI_VERTEX_LOCATION` /-`GEMINI_LIVE_MODEL`.+Live runs against Vertex AI using backend-minted OAuth tokens (no client-held API key). It is always+on, at the `global` Vertex location, all fixed in code. The backend route needs+`GOOGLE_APPLICATION_CREDENTIALS_JSON`.## Testing