Skip to content

Open source CapCut alternative.

TypeScript

Lazy load overlay voice capture

David Le1dbbe018a643
diff --git a/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift b/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift
index c981515f..44a402a4 100644
--- a/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift
+++ b/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift
@@ -5,7 +5,7 @@ import Foundation
@MainActor
final class MicrophoneWaveformMeter {
- private let engine = AVAudioEngine()
+ private var engine: AVAudioEngine?
private let barCount = UserQueryState.defaultVoiceWaveformLevels.count
private var levels = UserQueryState.defaultVoiceWaveformLevels
private var isRunning = false
@@ -27,6 +27,7 @@ final class MicrophoneWaveformMeter {
guard isGranted else {
self?.isStarting = false
+ self?.isRecordingAudio = false
self?.publishSilence()
return
}
@@ -37,10 +38,11 @@ final class MicrophoneWaveformMeter {
}
func stop() {
- guard isRunning || isStarting else { return }
+ guard isRunning || isStarting || isRecordingAudio || engine != nil else { return }
- engine.inputNode.removeTap(onBus: 0)
- engine.stop()
+ engine?.inputNode.removeTap(onBus: 0)
+ engine?.stop()
+ engine = nil
isRunning = false
isStarting = false
isRecordingAudio = false
@@ -51,7 +53,7 @@ final class MicrophoneWaveformMeter {
func startAudioCapture() {
capturedSamples.removeAll(keepingCapacity: true)
- capturedSampleRateHz = Int(engine.inputNode.outputFormat(forBus: 0).sampleRate)
+ capturedSampleRateHz = currentInputSampleRateHz()
capturedStartedAt = Date()
isRecordingAudio = true
start()
@@ -91,8 +93,13 @@ final class MicrophoneWaveformMeter {
return
}
+ let engine = engine ?? AVAudioEngine()
+ self.engine = engine
let inputNode = engine.inputNode
let format = inputNode.outputFormat(forBus: 0)
+ if isRecordingAudio, capturedSampleRateHz == 0 {
+ capturedSampleRateHz = Int(format.sampleRate)
+ }
levels = UserQueryState.defaultVoiceWaveformLevels
publishLevels()
@@ -112,12 +119,20 @@ final class MicrophoneWaveformMeter {
isStarting = false
} catch {
inputNode.removeTap(onBus: 0)
+ self.engine = nil
isRunning = false
isStarting = false
+ isRecordingAudio = false
publishSilence()
}
}
+ private func currentInputSampleRateHz() -> Int {
+ guard let engine else { return 0 }
+
+ return Int(engine.inputNode.outputFormat(forBus: 0).sampleRate)
+ }
+
private func append(_ level: Double) {
levels.append(level)
if levels.count > barCount {
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift
index 53b4638b..59851b28 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift
@@ -84,7 +84,17 @@ final class UserQueryOverlayController {
}
private func makeInputHostingView(size: CGSize) -> NSHostingView<UserQueryOverlayRootView> {
- let hostingView = NSHostingView(rootView: UserQueryOverlayRootView(model: model))
+ let hostingView = NSHostingView(
+ rootView: UserQueryOverlayRootView(
+ model: model,
+ voiceInputRequested: { [weak self] in
+ self?.activateVoiceInputAtScreenCenter()
+ },
+ voiceInputFinished: { [weak self] in
+ self?.finishVoiceInput()
+ }
+ )
+ )
hostingView.frame = CGRect(origin: .zero, size: size)
hostingView.autoresizingMask = [.width, .height]
hostingView.wantsLayer = true
@@ -398,7 +408,6 @@ final class UserQueryOverlayController {
activateForKeyboardInput(inputPanel)
}
focusComposerTextInput()
- microphoneWaveformMeter.start()
return
}
@@ -424,7 +433,6 @@ final class UserQueryOverlayController {
guard let inputPanel else { return }
model.activate()
- microphoneWaveformMeter.start()
centerInputPanel()
activateForKeyboardInput(inputPanel)
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayRootView.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayRootView.swift
index c6a83525..9fbe1ebc 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayRootView.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayRootView.swift
@@ -4,6 +4,8 @@ import SwiftUI
struct UserQueryOverlayRootView: View {
@ObservedObject var model: UserQueryOverlayModel
+ var voiceInputRequested: @MainActor () -> Void = {}
+ var voiceInputFinished: @MainActor () -> Void = {}
var body: some View {
UserQueryStageView(
@@ -12,7 +14,9 @@ struct UserQueryOverlayRootView: View {
inputTextHeight: model.inputTextHeight,
isInputExpanded: model.isInputExpanded,
placement: model.placement,
- intentSink: model
+ intentSink: model,
+ voiceInputRequested: voiceInputRequested,
+ voiceInputFinished: voiceInputFinished
)
.frame(
width: contentSize.width,
diff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift
index 0b6502bb..ec27a001 100644
--- a/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift
+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryStageView.swift
@@ -11,6 +11,8 @@ public struct UserQueryStageView: View {
private let isInputExpanded: Bool
private let placement: UserQueryPlacement
private weak var intentSink: (any UserQueryIntentSink)?
+ private let voiceInputRequested: @MainActor () -> Void
+ private let voiceInputFinished: @MainActor () -> Void
public init(
state: UserQueryState,
@@ -18,7 +20,9 @@ public struct UserQueryStageView: View {
inputTextHeight: CGFloat = UserQueryLayout.composerInputTextMinimumHeight,
isInputExpanded: Bool = false,
placement: UserQueryPlacement = .bottomRight,
- intentSink: any UserQueryIntentSink
+ intentSink: any UserQueryIntentSink,
+ voiceInputRequested: @escaping @MainActor () -> Void = {},
+ voiceInputFinished: @escaping @MainActor () -> Void = {}
) {
self.state = state
self._messageText = messageText
@@ -26,6 +30,8 @@ public struct UserQueryStageView: View {
self.isInputExpanded = isInputExpanded
self.placement = placement
self.intentSink = intentSink
+ self.voiceInputRequested = voiceInputRequested
+ self.voiceInputFinished = voiceInputFinished
}
public var body: some View {
@@ -75,6 +81,8 @@ public struct UserQueryStageView: View {
submit: {
intentSink?.handle(.messageSubmitted(text: messageText))
},
+ voiceInputRequested: voiceInputRequested,
+ voiceInputFinished: voiceInputFinished,
inputTextHeightChanged: { height in
intentSink?.handle(.inputTextHeightChanged(height))
},
@@ -109,6 +117,8 @@ struct UserQueryComposer: View {
let toolbarStyle: UserQueryComposerToolbarStyle
let sizeProfile: UserQueryComposerSizeProfile
let submit: @MainActor () -> Void
+ let voiceInputRequested: @MainActor () -> Void
+ let voiceInputFinished: @MainActor () -> Void
let inputTextHeightChanged: @MainActor (CGFloat) -> Void
let inputExpansionChanged: @MainActor (Bool) -> Void
@@ -122,6 +132,8 @@ struct UserQueryComposer: View {
toolbarStyle: UserQueryComposerToolbarStyle = .waveformOnly,
sizeProfile: UserQueryComposerSizeProfile = .standard,
submit: @escaping @MainActor () -> Void,
+ voiceInputRequested: @escaping @MainActor () -> Void = {},
+ voiceInputFinished: @escaping @MainActor () -> Void = {},
inputTextHeightChanged: @escaping @MainActor (CGFloat) -> Void,
inputExpansionChanged: @escaping @MainActor (Bool) -> Void
) {
@@ -134,6 +146,8 @@ struct UserQueryComposer: View {
self.toolbarStyle = toolbarStyle
self.sizeProfile = sizeProfile
self.submit = submit
+ self.voiceInputRequested = voiceInputRequested
+ self.voiceInputFinished = voiceInputFinished
self.inputTextHeightChanged = inputTextHeightChanged
self.inputExpansionChanged = inputExpansionChanged
}
@@ -252,11 +266,7 @@ struct UserQueryComposer: View {
private var composerTrailingControls: some View {
HStack(spacing: UserQueryLayout.composerTrailingControlsSpacing) {
if state.isVoiceInputActive {
- VoiceWaveformView(levels: state.voiceWaveformLevels)
- .frame(
- width: UserQueryLayout.composerWaveformSize.width,
- height: UserQueryLayout.composerWaveformSize.height
- )
+ waveformButton
} else {
microphoneIcon
sendButton(size: UserQueryLayout.composerSendButtonSize)
@@ -270,28 +280,44 @@ struct UserQueryComposer: View {
}
private var microphoneIcon: some View {
- Image(systemName: "mic")
- .font(.system(size: 24, weight: .ultraLight))
- .symbolRenderingMode(.monochrome)
- .foregroundStyle(Color.white.opacity(microphoneOpacity))
- .frame(
- width: UserQueryLayout.composerMicrophoneIconSize,
- height: UserQueryLayout.composerMicrophoneIconSize
- )
- .background {
- if isMicrophoneEmphasized {
- Circle()
- .fill(Color.white.opacity(0.14))
+ Button(action: voiceInputRequested) {
+ Image(systemName: "mic")
+ .font(.system(size: 24, weight: .ultraLight))
+ .symbolRenderingMode(.monochrome)
+ .foregroundStyle(Color.white.opacity(microphoneOpacity))
+ .frame(
+ width: UserQueryLayout.composerMicrophoneIconSize,
+ height: UserQueryLayout.composerMicrophoneIconSize
+ )
+ .background {
+ if isMicrophoneEmphasized {
+ Circle()
+ .fill(Color.white.opacity(0.14))
+ }
}
- }
- .overlay {
- if isMicrophoneEmphasized {
- Circle()
- .stroke(Color.white.opacity(0.42), lineWidth: 1)
+ .overlay {
+ if isMicrophoneEmphasized {
+ Circle()
+ .stroke(Color.white.opacity(0.42), lineWidth: 1)
+ }
}
- }
- .accessibilityLabel(state.isVoiceInputActive ? "Voice input active" : "Voice input")
- .help(state.isVoiceInputActive ? "Voice input active" : "Voice input")
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Voice input")
+ .help("Voice input")
+ }
+
+ private var waveformButton: some View {
+ Button(action: voiceInputFinished) {
+ VoiceWaveformView(levels: state.voiceWaveformLevels)
+ .frame(
+ width: UserQueryLayout.composerWaveformSize.width,
+ height: UserQueryLayout.composerWaveformSize.height
+ )
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Finish voice input")
+ .help("Finish voice input")
}
private var followUpTrailingControls: some View {
diff --git a/docs/guides/user-query-overlay.md b/docs/guides/user-query-overlay.md
index f31ed7a8..85b8f719 100644
--- a/docs/guides/user-query-overlay.md
+++ b/docs/guides/user-query-overlay.md
@@ -65,7 +65,7 @@ quick local-app actions:
- Notch geometry comes from the active `NSScreen`, preferring safe-area and auxiliary-top metrics over hardcoded notch sizes. Content must stay out of the physical notch void; displays without a physical notch should use the same top-center composition without reserving unavailable space.
- `UserQueryNotchLayout` is the shared source for notch surface frames, content frames, corner radii, and notch-safe offsets. `canRenderTextInTopRow` describes whether text can draw in the top row, not whether that row exists.
- The prompt is a compact black composer: single-line text is pill-shaped, multiline text becomes a bounded rounded rectangle, Return submits, Shift-Return inserts a newline, Escape and outside clicks dismiss, and non-input capsule areas can drag the modal.
-- The centered composer keeps text and voice modes on the same input surface. Double-Command release opens focused text input, double-Command hold opens the same input with voice active, and typed text promotes the send button while the microphone affordance becomes secondary.
+- The centered composer keeps text and voice modes on the same input surface. Double-Command release opens focused text input without initializing microphone capture, double-Command hold opens the same input with voice active, and typed text promotes the send button while the microphone affordance becomes secondary. Voice capture starts only from explicit voice activation such as holding the second Command tap or pressing the microphone affordance.
- Voice capture and transcription remain separate. The controller records bounded local audio and publishes levels; transcription is model-backed through the hosted agent-harness boundary before transcript text enters the turn path.
- Local item prewarming must run off the main actor and must not eagerly scan protected user folders. Agent memory is stored in SQLite under Application Support and uses FTS5 plus deterministic local embeddings for retrieval; JSONL is only an explicit export/debug format. Cached local-item hits must still point to an existing path or bundle before they are used as an execution target. Runtime task definitions are the generic open/local-app interaction seeds plus generated or user-reviewed definitions loaded from memory.
- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility, AI visual targets, or keyboard input. Submit steps with an explicit structured `controlID` may execute as an Accessibility `AXPress` against button-like controls, or as a guarded coordinate click against an AI visual target when Accessibility is unavailable. Control bounds are carried into action traces.
@@ -88,7 +88,7 @@ Manually verify:
- The notch renders at the top center, respects physical notch safe areas, expands only from visible notch hover, and accepts expanded controls/clicks.
- First launch shows the permission setup after sign-in, explains Accessibility, Screenshots, and Microphone before requesting them, enables Continue only when all three are ready, and does not trigger Desktop/Documents/Downloads prompts during startup.
-- Double-Command release opens a centered focused text prompt; double-Command hold opens the same prompt with voice active; typed text shows a primary send button and a secondary microphone affordance; unrelated Command use does not activate the overlay.
+- Double-Command release opens a centered focused text prompt without starting microphone capture; double-Command hold opens the same prompt with voice active; pressing the microphone affordance starts voice capture; typed text shows a primary send button and a secondary microphone affordance; unrelated Command use does not activate the overlay.
- Typed, voice, and follow-up submissions create or update durable task threads, answer non-actionable conversation without showing action failure, show action status in the notch when work runs, and preserve per-task pause/resume behavior.
- Typed prompt and notch follow-up submissions show the spawn sequence: notch cue, desktop cursor emergence, direct travel to a known target or fallback holding point, typed submitted-turn label with tail-wag waiting animation, final response/result label, retargeting when the target becomes visible, persistent labels for conversational or attention states, and fade-out only for completed action-only turns.
- Stationary spawn labels render complete text without typewriter clipping, wrap to fit available width, select the cursor on click, and transition in place into a same-styled inline editor for tasked follow-ups without clipping the carried-over label.