diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml index 65364f1ed0..ede31ab81a 100644 --- a/.github/workflows/frontend.yml +++ b/.github/workflows/frontend.yml @@ -55,6 +55,12 @@ jobs: "$HOME/.ao/build-cache/wake-helper/effects-tests" xcrun swiftc -module-cache-path "$HOME/.ao/build-cache/wake-helper/tests" native/wake-helper/WakePolicy.swift native/wake-helper/WakeLowPower.swift native/wake-helper/LowPowerTests.swift -o "$HOME/.ao/build-cache/wake-helper/low-power-tests" "$HOME/.ao/build-cache/wake-helper/low-power-tests" + - name: Compile dictation helper for both macOS architectures + run: | + node scripts/build-dictation-helper.mjs --arch x64 + lipo dictation-helper/Orchestrator.app/Contents/MacOS/Orchestrator -verify_arch x86_64 + node scripts/build-dictation-helper.mjs --arch arm64 + lipo dictation-helper/Orchestrator.app/Contents/MacOS/Orchestrator -verify_arch arm64 - name: Test repair installer packaging and guards run: node --test scripts/build-mac-repair-installer.node-test.mjs - name: Compile helper for both macOS architectures diff --git a/.gitignore b/.gitignore index 3826c18dcc..5970cfa0af 100644 --- a/.gitignore +++ b/.gitignore @@ -108,3 +108,4 @@ pnpm-lock.yaml .serena/ /frontend/wake-helper/ +/frontend/dictation-helper/ diff --git a/frontend/e2e/support/fake-bridge.ts b/frontend/e2e/support/fake-bridge.ts index fab0d00c87..43873fee26 100644 --- a/frontend/e2e/support/fake-bridge.ts +++ b/frontend/e2e/support/fake-bridge.ts @@ -74,6 +74,12 @@ export async function installFakeBridge(page: Page, opts: FakeBridgeOptions = {} // resolves — an incomplete object would throw the moment the app touched // a missing method. const ao = { + dictation: { + start: async () => undefined, + stop: async () => undefined, + cancel: async () => undefined, + onEvent: unsubscribe, + }, app: { getVersion: async () => version, chooseDirectory: async () => null, @@ -983,6 +989,12 @@ export async function installFakeAgent(page: Page, opts: FakeAgentOptions = {}): ...(error ? { error } : {}), }); const ao = { + dictation: { + start: async () => undefined, + stop: async () => undefined, + cancel: async () => undefined, + onEvent: unsubscribe, + }, app: { getVersion: async () => version, chooseDirectory: async () => null, diff --git a/frontend/forge.config.test.ts b/frontend/forge.config.test.ts index b2668a3534..ee43998c1a 100644 --- a/frontend/forge.config.test.ts +++ b/frontend/forge.config.test.ts @@ -123,6 +123,12 @@ describe("native runtime resources", () => { expect(extraResourcesForPlatform("win32")).not.toContain("wake-helper"); }); + it("bundles the dictation helper only on macOS", () => { + expect(extraResourcesForPlatform("darwin")).toContain("dictation-helper"); + expect(extraResourcesForPlatform("linux")).not.toContain("dictation-helper"); + expect(extraResourcesForPlatform("win32")).not.toContain("dictation-helper"); + }); + it("bundles cloudflared only on macOS", () => { expect(extraResourcesForPlatform("darwin")).toContain("cloudflared"); expect(extraResourcesForPlatform("linux")).not.toContain("cloudflared"); @@ -135,6 +141,9 @@ describe("native runtime resources", () => { mkdirSync(join(resources, "wake-helper"), { recursive: true }); writeFileSync(join(resources, "update-helper", "ao-update-progress"), ""); writeFileSync(join(resources, "wake-helper", "ao-wake"), ""); + const dictationHelper = join(resources, "dictation-helper", "Orchestrator.app", "Contents", "MacOS"); + mkdirSync(dictationHelper, { recursive: true }); + writeFileSync(join(dictationHelper, "Orchestrator"), ""); const hook = config.hooks?.postPackage; if (typeof hook !== "function") throw new Error("postPackage hook missing"); await expect(hook(config, { platform: "darwin", arch: "arm64", outputPaths: [fixtureDir] })).rejects.toThrow("packaged cloudflared missing"); @@ -193,6 +202,13 @@ describe("macOS signing", () => { }); }); + it("lets the dictation helper bundle and its executable record audio", () => { + const helper = "/Applications/Orchestrator.app/Contents/Resources/dictation-helper/Orchestrator.app"; + const audio = { entitlements: ["com.apple.security.device.audio-input"] }; + expect(macSignOptionsForFile(helper)).toEqual(audio); + expect(macSignOptionsForFile(`${helper}/Contents/MacOS/Orchestrator`)).toEqual(audio); + }); + it("keeps electron-osx-sign defaults for every other bundle file", () => { const foreign = join(fixtureDir, "elsewhere", "agent-orchestrator"); mkdirSync(join(fixtureDir, "elsewhere"), { recursive: true }); diff --git a/frontend/forge.config.ts b/frontend/forge.config.ts index 32990f6b14..66fbfc035a 100644 --- a/frontend/forge.config.ts +++ b/frontend/forge.config.ts @@ -101,7 +101,7 @@ export function extraResourcesForPlatform(platform: NodeJS.Platform): string[] { "browser-extension", "agent-browser", "resources/acp-runtime", - ...(platform === "darwin" ? ["update-helper", "wake-helper", "cloudflared", "assets/mac/en.lproj"] : []), + ...(platform === "darwin" ? ["update-helper", "wake-helper", "dictation-helper", "cloudflared", "assets/mac/en.lproj"] : []), ...(platform === "darwin" || platform === "linux" ? ["tmux"] : []), "assets/icon.png", "assets/icon.ico", @@ -131,7 +131,17 @@ const ACP_RUNTIME_NODE_ENTITLEMENTS = [ "com.apple.security.cs.allow-unsigned-executable-memory", ]; +// The dictation helper records the microphone itself (it disclaims the app as +// its responsible process), and the hardened runtime blocks audio input +// without this entitlement. osx-sign signs its executable, then its bundle. +const DICTATION_HELPER_PATHS = [ + "/Contents/Resources/dictation-helper/Orchestrator.app", + "/Contents/Resources/dictation-helper/Orchestrator.app/Contents/MacOS/Orchestrator", +]; +const DICTATION_HELPER_ENTITLEMENTS = ["com.apple.security.device.audio-input"]; + export function macSignOptionsForFile(filePath: string): { entitlements?: string[] } { + if (DICTATION_HELPER_PATHS.some((helper) => filePath.endsWith(helper))) return { entitlements: DICTATION_HELPER_ENTITLEMENTS }; // Cheap gate first: optionsForFile is invoked for every Mach-O in the // bundle, and only the nested Node path can need an override. if (!filePath.endsWith(ACP_RUNTIME_NODE_PATH)) return {}; @@ -225,6 +235,9 @@ const config: ForgeConfig = { const wakeBuild = spawnSync(process.execPath, [path.resolve("scripts/build-wake-helper.mjs"), "--arch", arch], { stdio: "inherit" }); if (wakeBuild.error) throw wakeBuild.error; if (wakeBuild.status !== 0) throw new Error("macOS wake helper build failed"); + const dictationBuild = spawnSync(process.execPath, [path.resolve("scripts/build-dictation-helper.mjs"), "--arch", arch], { stdio: "inherit" }); + if (dictationBuild.error) throw dictationBuild.error; + if (dictationBuild.status !== 0) throw new Error("macOS dictation helper build failed"); } const { owner, name } = parseReleaseRepo(process.env.AO_RELEASE_REPO); const yml = [ @@ -263,6 +276,7 @@ const config: ForgeConfig = { const helper = path.join(resourcesPath, "update-helper", "ao-update-progress"); if (!existsSync(helper)) throw new Error(`packaged macOS update helper missing from ${helper}`); if (!existsSync(path.join(resourcesPath, "wake-helper", "ao-wake"))) throw new Error(`packaged macOS wake helper missing from ${resourcesPath}`); + if (!existsSync(path.join(resourcesPath, "dictation-helper", "Orchestrator.app", "Contents", "MacOS", "Orchestrator"))) throw new Error(`packaged macOS dictation helper missing from ${resourcesPath}`); // Run it: remote access depends on this signed copy starting, not just existing. const cloudflared = path.join(resourcesPath, "cloudflared", "cloudflared"); if (!existsSync(cloudflared)) throw new Error(`packaged cloudflared missing from ${cloudflared}`); diff --git a/frontend/native/dictation-helper/Info.plist b/frontend/native/dictation-helper/Info.plist new file mode 100644 index 0000000000..347c40a0f0 --- /dev/null +++ b/frontend/native/dictation-helper/Info.plist @@ -0,0 +1,29 @@ + + + + + CFBundleIdentifier + dev.agent-orchestrator.desktop.dictation + CFBundleName + Orchestrator + CFBundleDisplayName + Orchestrator + CFBundleExecutable + Orchestrator + CFBundleIconFile + icon + CFBundlePackageType + APPL + CFBundleInfoDictionaryVersion + 6.0 + LSMinimumSystemVersion + 11.0 + + LSUIElement + + NSMicrophoneUsageDescription + Orchestrator uses the microphone to dictate messages. + NSSpeechRecognitionUsageDescription + Orchestrator turns your speech into message text. + + diff --git a/frontend/native/dictation-helper/main.swift b/frontend/native/dictation-helper/main.swift new file mode 100644 index 0000000000..1156b89454 --- /dev/null +++ b/frontend/native/dictation-helper/main.swift @@ -0,0 +1,184 @@ +import AVFoundation +import Foundation +import Speech + +// Streams one dictation as JSON lines on stdout. "stop" on stdin (or EOF) +// ends the audio and waits for the final transcript; "cancel" exits at once. + +let output = DispatchQueue(label: "ao.dictation.output") + +// Serialized on the output queue: the meter's levels come from the real-time +// audio thread, which must not do this work. +func emit(_ event: [String: Any]) { + output.async { + guard let data = try? JSONSerialization.data(withJSONObject: event) else { return } + FileHandle.standardOutput.write(data) + FileHandle.standardOutput.write(Data([0x0A])) + } +} + +func finish(_ event: [String: Any], code: Int32) -> Never { + emit(event) + output.sync {} + exit(code) +} + +func fail(_ message: String) -> Never { + finish(["type": "error", "message": message], code: 1) +} + +// Loudness of one render cycle of the first channel, mapped from -60...-10 dBFS onto 0...1. +func level(_ samples: UnsafePointer, count: Int) -> Double { + var sum: Float = 0 + for index in 0.. 0, format.channelCount > 0 else { fail("No microphone found.") } + let request = self.request + input.installTap(onBus: 0, bufferSize: 4096, format: format) { buffer, _ in + request.append(buffer) + } + // The tap hands over about 100 ms at a time, too late for the meter. A sink + // node runs every render cycle, so levels leave within a few milliseconds. + let sink = AVAudioSinkNode { _, frameCount, audio in + let buffers = UnsafeMutableAudioBufferListPointer(UnsafeMutablePointer(mutating: audio)) + guard frameCount > 0, let samples = buffers.first?.mData?.assumingMemoryBound(to: Float.self) else { return noErr } + emit(["type": "levels", "values": [level(samples, count: Int(frameCount))]]) + return noErr + } + engine.attach(sink) + engine.connect(input, to: sink, format: format) + + task = recognizer.recognitionTask(with: request) { [weak self] result, error in + guard let self else { return } + if let result { + self.hear(result) + if result.isFinal { finish(["type": "end", "text": self.text], code: 0) } + emit(["type": "text", "text": self.text]) + } else if error != nil { + // Stopping with no speech also ends here; keep whatever was heard. + if self.stopping { finish(["type": "end", "text": self.text], code: 0) } + fail(error?.localizedDescription ?? "Dictation stopped.") + } + } + + engine.prepare() + do { try engine.start() } catch { fail("Could not start the microphone.") } + emit(["type": "listening"]) + } + + // The recognizer reports one utterance at a time: partial results while it + // hears words (their timestamps are all zero), then, at a pause, the ended + // utterance with real audio timestamps. The next partial starts a new + // utterance. An ended utterance can come back revised (the final result on + // stop often does); its words start inside that utterance's audio, so it + // replaces the utterance instead of adding a copy. + private func hear(_ result: SFSpeechRecognitionResult) { + let heard = result.bestTranscription.formattedString + let segments = result.bestTranscription.segments + let ended = result.speechRecognitionMetadata != nil || result.isFinal + let end = segments.last.map { $0.timestamp + $0.duration } + let index: Int? + if ended, let start = segments.first?.timestamp { + // The ended utterance whose audio this result starts in, else the open one. + index = utterances.lastIndex { $0.end.map { start < $0 - 0.05 } ?? true } + } else { + index = utterances.isEmpty || utterances[utterances.count - 1].end != nil ? nil : utterances.count - 1 + } + if heard.isEmpty { + if let index, utterances[index].end == nil { utterances.remove(at: index) } + } else if let index { + utterances[index] = (heard, ended ? end : nil) + // Anything heard after a revised utterance was part of it. + utterances.removeSubrange((index + 1)...) + } else { + utterances.append((heard, ended ? end : nil)) + } + text = utterances.map(\.text).joined(separator: " ") + } + + func stop() { + guard !stopping else { return } + stopping = true + // Stopped before access was granted and listening began: nothing to finish. + guard task != nil else { finish(["type": "end", "text": ""], code: 0) } + emit(["type": "finishing"]) + engine.stop() + engine.inputNode.removeTap(onBus: 0) + request.endAudio() + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in + finish(["type": "end", "text": self?.text ?? ""], code: 0) + } + } +} + +// macOS asks the responsible process (the app or terminal that launched AO) +// for speech and microphone access, and kills the helper when that process +// has no usage strings. Relaunch once so the helper is responsible for itself +// and macOS reads the usage strings embedded in this binary. +@_silgen_name("responsibility_spawnattrs_setdisclaim") +func responsibility_spawnattrs_setdisclaim(_ attrs: UnsafeMutablePointer, _ disclaim: Int32) -> Int32 + +var disclaimedChild: pid_t = 0 + +if getenv("AO_DICTATION_DISCLAIMED") == nil, let executable = Bundle.main.executablePath { + setenv("AO_DICTATION_DISCLAIMED", "1", 1) + var attrs: posix_spawnattr_t? + posix_spawnattr_init(&attrs) + _ = responsibility_spawnattrs_setdisclaim(&attrs, 1) + let argv: [UnsafeMutablePointer?] = [strdup(executable), nil] + if posix_spawn(&disclaimedChild, executable, nil, &attrs, argv, environ) == 0 { + signal(SIGTERM) { _ in + kill(disclaimedChild, SIGTERM) + exit(0) + } + var status: Int32 = 0 + waitpid(disclaimedChild, &status, 0) + exit((status & 0x7f) == 0 ? (status >> 8) & 0xff : 1) + } +} + +let dictation = Dictation() + +Thread.detachNewThread { + while let line = readLine() { + if line == "cancel" { exit(0) } + if line == "stop" { break } + } + DispatchQueue.main.async { dictation.stop() } +} + +SFSpeechRecognizer.requestAuthorization { status in + guard status == .authorized else { + fail("Allow Speech Recognition for Orchestrator in System Settings > Privacy & Security.") + } + AVCaptureDevice.requestAccess(for: .audio) { granted in + guard granted else { + fail("Allow Microphone access for Orchestrator in System Settings > Privacy & Security.") + } + DispatchQueue.main.async { dictation.start() } + } +} + +dispatchMain() diff --git a/frontend/package.json b/frontend/package.json index 6d993a238d..226e208b06 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -19,9 +19,10 @@ "cloudflared:prepare": "node ./scripts/prepare-cloudflared.mjs", "build:daemon": "node ./scripts/build-daemon.mjs", "build:wake-helper": "node ./scripts/build-wake-helper.mjs", + "build:dictation-helper": "node ./scripts/build-dictation-helper.mjs", "build:host": "node ./scripts/build-host-bundle.mjs", "build:browser-extension": "node ./scripts/build-browser-extension.mjs", - "predev": "npm run build:daemon -- --dev && npm run build:browser-extension && node ./scripts/build-wake-helper.mjs --if-supported && node ./scripts/ensure-browser-runtime.mjs && npm run build:acp-runtime", + "predev": "npm run build:daemon -- --dev && npm run build:browser-extension && node ./scripts/build-wake-helper.mjs --if-supported && node ./scripts/build-dictation-helper.mjs --if-supported && node ./scripts/ensure-browser-runtime.mjs && npm run build:acp-runtime", "dev": "electron-forge start", "dev:web": "node ./scripts/dev-web.mjs", "build": "npm run package", diff --git a/frontend/scripts/build-dictation-helper.mjs b/frontend/scripts/build-dictation-helper.mjs new file mode 100644 index 0000000000..679dd3d0d2 --- /dev/null +++ b/frontend/scripts/build-dictation-helper.mjs @@ -0,0 +1,49 @@ +import { spawnSync } from "node:child_process"; +import { copyFileSync, mkdirSync, rmSync } from "node:fs"; +import { homedir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const frontend = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +/** Where the built helper's executable lives, inside its app bundle. */ +export const DICTATION_HELPER_EXECUTABLE = path.join("dictation-helper", "Orchestrator.app", "Contents", "MacOS", "Orchestrator"); + +// An app bundle, not a bare binary, so macOS names it Orchestrator and shows +// the app icon when it asks for microphone and speech recognition access. +export function buildDictationHelper({ arch = process.arch } = {}) { + if (process.platform !== "darwin") throw new Error("The dictation helper must be built on macOS"); + const cpu = arch === "arm64" ? "arm64" : arch === "x64" ? "x86_64" : undefined; + if (!cpu) throw new Error(`Unsupported macOS dictation helper architecture: ${arch}`); + const source = path.join(frontend, "native/dictation-helper"); + const output = path.join(frontend, "dictation-helper"); + const bundle = path.join(output, "Orchestrator.app"); + const cache = path.join(homedir(), ".ao/build-cache/dictation-helper", arch); + rmSync(output, { recursive: true, force: true }); + mkdirSync(path.join(bundle, "Contents", "MacOS"), { recursive: true }); + mkdirSync(path.join(bundle, "Contents", "Resources"), { recursive: true }); + mkdirSync(cache, { recursive: true }); + copyFileSync(path.join(source, "Info.plist"), path.join(bundle, "Contents", "Info.plist")); + copyFileSync(path.join(frontend, "assets", "icon.icns"), path.join(bundle, "Contents", "Resources", "icon.icns")); + const compile = spawnSync("xcrun", [ + "swiftc", "-target", `${cpu}-apple-macosx11.0`, "-O", path.join(source, "main.swift"), + "-module-cache-path", cache, "-o", path.join(frontend, DICTATION_HELPER_EXECUTABLE), + ], { stdio: "inherit" }); + if (compile.error) throw compile.error; + if (compile.status !== 0) throw new Error(`macOS dictation helper compilation failed (${compile.status})`); + // Ad-hoc seal the bundle so its Info.plist and icon are part of its identity; + // release signing re-signs it with the app. + const seal = spawnSync("codesign", ["--force", "--sign", "-", bundle], { stdio: "inherit" }); + if (seal.error) throw seal.error; + if (seal.status !== 0) throw new Error(`macOS dictation helper signing failed (${seal.status})`); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const args = process.argv.slice(2); + if (args.length === 1 && args[0] === "--if-supported") { + if (process.platform === "darwin") buildDictationHelper(); + process.exit(0); + } + if (args.length !== 0 && (args.length !== 2 || args[0] !== "--arch")) throw new Error("Usage: build-dictation-helper.mjs [--arch arm64|x64]"); + buildDictationHelper({ arch: args[1] ?? process.arch }); +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 10d434608c..8386f70fd0 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -54,6 +54,7 @@ import { readEditorSettings, writeEditorPreference } from "./main/editor-setting import { createEditorHandoff } from "./main/editor-handoff"; import { discoverMacTerminalApps } from "./main/mac-terminal-apps"; import { registerCliLinkIpc } from "./main/cli-link-ipc"; +import { registerDictationIpc } from "./main/dictation"; import { launchCommand } from "./main/launch-command"; import { blocksRenderFrameNavigation, cloudArtifactPrefix } from "./main/render-frame-guard"; import { agentPageRequestAllowed } from "./main/render-frame-network"; @@ -1172,6 +1173,8 @@ async function createWindowInternal(): Promise { mainWindow.on("unmaximize", pushMaximized); mainWindow.on("blur", () => { keybindingRecordingActive = false; + // Leaving the app (switching apps, hiding, minimizing) finishes dictation. + dictation.stop(); }); shellWebContents.on("render-process-gone", () => { keybindingRecordingActive = false; @@ -2775,6 +2778,13 @@ ipcMain.handle("editorHandoff:copyWorkspacePath", (event, sessionId: string) => return editorHandoff.copyWorkspacePath(typeof sessionId === "string" ? sessionId : ""); }); ipcMain.handle("app:getVersion", () => app.getVersion()); +const dictation = registerDictationIpc( + path.join( + app.isPackaged ? process.resourcesPath : app.getAppPath(), + "dictation-helper", "Orchestrator.app", "Contents", "MacOS", "Orchestrator", + ), + getShellWebContents, +); ipcMain.handle("app:openExternal", async (_event, url: string) => { await openAllowedAppExternalURL(url, shell); }); diff --git a/frontend/src/main/browser-view-host.test.ts b/frontend/src/main/browser-view-host.test.ts index 1ed67fa633..4e20594ae3 100644 --- a/frontend/src/main/browser-view-host.test.ts +++ b/frontend/src/main/browser-view-host.test.ts @@ -734,6 +734,11 @@ describe("browser shortcut matching", () => { expect(shouldHandleAppShortcutInBrowserContext("next-session", { ...chord, key: "}", code: "BracketRight", shift: true }, true)).toBe(true); }); + it("leaves ⌘D to the page instead of starting dictation", () => { + const chord = { key: "d", code: "KeyD", ctrl: false, meta: true, shift: false, alt: false }; + expect(shouldHandleAppShortcutInBrowserContext("dictate", chord, true)).toBe(false); + }); + it("leaves Space and Shift+Space to Chromium so browser form controls can accept spaces", () => { const input = { key: " ", control: false, meta: false, shift: false, alt: false, type: "keyDown" }; expect(browserShortcutAction(input, false)).toBeNull(); diff --git a/frontend/src/main/browser-view-host.ts b/frontend/src/main/browser-view-host.ts index 22249288af..d4980220e8 100644 --- a/frontend/src/main/browser-view-host.ts +++ b/frontend/src/main/browser-view-host.ts @@ -316,6 +316,8 @@ export function shouldHandleAppShortcutInBrowserContext( ): boolean { if (id === "new-shell-terminal" || id === "close-shell-terminal") return false; + // Dictation types into the chat composer, never a page; ⌘D belongs to the page. + if (id === "dictate") return false; return ( browserShortcutAction( { diff --git a/frontend/src/main/dictation.ts b/frontend/src/main/dictation.ts new file mode 100644 index 0000000000..a25455e1d9 --- /dev/null +++ b/frontend/src/main/dictation.ts @@ -0,0 +1,56 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { createInterface } from "node:readline"; +import { app, ipcMain, type WebContents } from "electron"; +import type { DictationEvent } from "../shared/dictation"; + +// One dictation at a time, run by the native helper and streamed to the shell +// renderer. Returns `stop`, which finishes a running dictation and keeps its text. +export function registerDictationIpc(helperPath: string, shellWebContents: () => WebContents | null): { stop(): void } { + let helper: ChildProcess | null = null; + const stop = () => { + helper?.stdin?.write("stop\n"); + }; + app.on("will-quit", () => helper?.kill()); + + ipcMain.handle("dictation:start", (event) => { + if (process.platform !== "darwin" || event.sender !== shellWebContents()) return; + const sender = event.sender; + const previous = helper; + const child = spawn(helperPath, [], { stdio: ["pipe", "pipe", "ignore"] }); + helper = child; + // A helper that was replaced or cancelled is still shutting down; its + // events, exit included, belong to a dictation that already ended. + const send = (message: DictationEvent) => { + if (helper === child && !sender.isDestroyed()) sender.send("dictation:event", message); + }; + previous?.kill(); + // A stop written while the helper is exiting would otherwise throw EPIPE in main. + child.stdin?.on("error", () => undefined); + createInterface({ input: child.stdout! }).on("line", (line) => { + try { + send(JSON.parse(line) as DictationEvent); + } catch { + // Not a protocol line. + } + }); + child.on("error", () => send({ type: "error", message: "Dictation is not available." })); + // "close", not "exit": exit can arrive before the last stdout lines, so the + // renderer would hear "exit" ahead of the helper's final "end". + child.on("close", () => { + send({ type: "exit" }); + if (helper === child) helper = null; + }); + }); + + ipcMain.handle("dictation:stop", (event) => { + if (event.sender === shellWebContents()) stop(); + }); + + ipcMain.handle("dictation:cancel", (event) => { + if (event.sender !== shellWebContents()) return; + helper?.stdin?.write("cancel\n"); + helper = null; + }); + + return { stop }; +} diff --git a/frontend/src/preload.ts b/frontend/src/preload.ts index 324d8363e9..5d7922e9f4 100644 --- a/frontend/src/preload.ts +++ b/frontend/src/preload.ts @@ -27,6 +27,7 @@ import { type TrayOpenSessionTarget, } from "./shared/tray"; import type { DaemonStatus } from "./shared/daemon-status"; +import type { DictationEvent } from "./shared/dictation"; import type { RemoteHostView } from "./main/remotes-ipc"; import type { ConnectedHostView } from "./main/remote-registry"; import type { RemoteHealth } from "./main/remote-request"; @@ -192,6 +193,18 @@ function isRendererQueuePurgeRequest(value: unknown): value is RendererTelemetry const binaryRequestsInFlight = new Set(); const api = { + dictation: { + start: () => ipcRenderer.invoke("dictation:start") as Promise, + stop: () => ipcRenderer.invoke("dictation:stop") as Promise, + cancel: () => ipcRenderer.invoke("dictation:cancel") as Promise, + onEvent: (listener: (event: DictationEvent) => void) => { + const handler = (_event: Electron.IpcRendererEvent, message: DictationEvent) => listener(message); + ipcRenderer.on("dictation:event", handler); + return () => { + ipcRenderer.removeListener("dictation:event", handler); + }; + }, + }, app: { getVersion: () => ipcRenderer.invoke("app:getVersion") as Promise, chooseDirectory: (input?: string | { title?: string; defaultPath?: string }) => ipcRenderer.invoke("app:chooseDirectory", input) as Promise, diff --git a/frontend/src/renderer/components/KeyboardShortcutsDialog.test.tsx b/frontend/src/renderer/components/KeyboardShortcutsDialog.test.tsx index e7d4068f25..fa8752ec77 100644 --- a/frontend/src/renderer/components/KeyboardShortcutsDialog.test.tsx +++ b/frontend/src/renderer/components/KeyboardShortcutsDialog.test.tsx @@ -43,11 +43,13 @@ describe("KeyboardShortcutsDialog", () => { render(); for (const { id } of APP_SHORTCUTS) { - if (id === "keyboard-shortcuts") continue; + // Dictation is listed only in Developer mode, which is off here. + if (id === "keyboard-shortcuts" || id === "dictate") continue; const label = enMessages[shortcutLabelKeys[id] as keyof typeof enMessages] as string; expect(screen.getAllByText(label), `${id} (${label})`).toHaveLength(1); } expect(screen.getByText("Jump to session 1–9")).toBeInTheDocument(); + expect(screen.queryByText("Dictate")).toBeNull(); }); it("uses macOS symbols in Apple's modifier order and spells them out for screen readers", () => { diff --git a/frontend/src/renderer/components/KeyboardShortcutsDialog.tsx b/frontend/src/renderer/components/KeyboardShortcutsDialog.tsx index 793e09777f..69c35fb7d6 100644 --- a/frontend/src/renderer/components/KeyboardShortcutsDialog.tsx +++ b/frontend/src/renderer/components/KeyboardShortcutsDialog.tsx @@ -15,6 +15,7 @@ import type { MessageKey } from "../i18n/messages"; import { useCommandPaletteEnabled } from "../hooks/useCommandPaletteEnabled"; import { useRestoreFocusOnClose } from "../hooks/useRestoreFocusOnClose"; import { useKeybindingsStore } from "../stores/keybindings-store"; +import { useUiStore } from "../stores/ui-store"; import { X } from "lucide-react"; import { cn } from "@/lib/utils"; import { @@ -121,9 +122,13 @@ export const KeyboardShortcutsDialog = memo(function KeyboardShortcutsDialog({ const overrides = useKeybindingsStore((state) => state.overrides); const paletteShortcuts: readonly AppShortcutId[] = ["command-palette", "quick-open-file"]; // The dialog's own chord sits in the header, so it is not repeated as a row. + // Dictation is in preview behind Developer mode. + const developerMode = useUiStore((state) => state.developerMode); const availableShortcuts = APP_SHORTCUTS.filter( (shortcut) => - shortcut.id !== "keyboard-shortcuts" && (!paletteShortcuts.includes(shortcut.id) || isCommandPaletteEnabled), + shortcut.id !== "keyboard-shortcuts" && + (!paletteShortcuts.includes(shortcut.id) || isCommandPaletteEnabled) && + (shortcut.id !== "dictate" || developerMode), ); const helpBindings = effectiveShortcutBindings("keyboard-shortcuts", isMac, overrides); diff --git a/frontend/src/renderer/components/NewChatPage.tsx b/frontend/src/renderer/components/NewChatPage.tsx index 62eb7d1bae..a02d03beb2 100644 --- a/frontend/src/renderer/components/NewChatPage.tsx +++ b/frontend/src/renderer/components/NewChatPage.tsx @@ -11,7 +11,7 @@ import { PLAN_REFUSAL_CODES } from "../lib/cloud-cp/client"; import { chatDraftScopeKey, readChatSessionDraft, writeChatAttachments, writeChatComposerText } from "../lib/chat-drafts"; import { clientForHost, labelForHost } from "../lib/host-clients"; import { sessionNavigateTarget } from "../lib/navigate-to-session"; -import { openComposerModelPicker } from "../lib/composer-shortcuts"; +import { openComposerModelPicker, toggleComposerDictation } from "../lib/composer-shortcuts"; import { useSessionShortcut } from "../hooks/useAppShortcut"; import { CLOUD_PROJECT_KIND, STANDALONE_PROJECT_KIND, STANDALONE_WORKSPACE_ID } from "../types/workspace"; import type { ChatConfigOption, ChatConfigOptionValue, ChatModel, ConversationSnapshot, TurnSettings } from "../types/conversation"; @@ -49,6 +49,7 @@ export function NewChatPage({ projectId, hostId }: { projectId: string; hostId?: targetRef.current = { projectId, hostId }; // The session's own composer shortcuts, before the session exists. useSessionShortcut("model-picker", openComposerModelPicker); + useSessionShortcut("dictate", toggleComposerDictation); const mounted = useRef(true); useEffect(() => { mounted.current = true; diff --git a/frontend/src/renderer/components/SessionView.tsx b/frontend/src/renderer/components/SessionView.tsx index fe03dbca6a..22925cb0b7 100644 --- a/frontend/src/renderer/components/SessionView.tsx +++ b/frontend/src/renderer/components/SessionView.tsx @@ -112,7 +112,7 @@ import { useCloudSessionPresence } from "../hooks/useCloudSessionPresence"; import { SessionPeopleControl } from "./SessionPeople"; import { SharedProjectPanel } from "./SharedProjectPanel"; import { focusAfterPaint, useSessionShortcut } from "../hooks/useAppShortcut"; -import { openComposerModelPicker } from "../lib/composer-shortcuts"; +import { openComposerModelPicker, toggleComposerDictation } from "../lib/composer-shortcuts"; import { inspectorIsOpen, useResolvedTheme, useUiStore, type InspectorView } from "../stores/ui-store"; import { useSideChatsAvailable } from "../lib/side-chats"; import { @@ -1953,6 +1953,7 @@ export function SessionView({ sessionId, cloudOrgId, projectId, hostId }: Sessio hasInspector, ); useSessionShortcut("model-picker", openComposerModelPicker, hasInspector); + useSessionShortcut("dictate", toggleComposerDictation, hasInspector); const inspectorMotionReadyRef = useRef(null); const handleInspectorCloseAnimationComplete = useCallback(() => { diff --git a/frontend/src/renderer/components/chat/ChatComposer.tsx b/frontend/src/renderer/components/chat/ChatComposer.tsx index abf9e5e00f..b8f8010747 100644 --- a/frontend/src/renderer/components/chat/ChatComposer.tsx +++ b/frontend/src/renderer/components/chat/ChatComposer.tsx @@ -50,7 +50,10 @@ import { type ReactNode, type Ref, } from "react"; -import { ArrowUp, CornerUpRight, Loader2, Paperclip, Play, Plus, Square, X } from "lucide-react"; +import { ArrowUp, CornerUpRight, Loader2, Mic, Paperclip, Play, Plus, Square, X } from "lucide-react"; +import { isMacPlatform } from "../../lib/platform"; +import { useDictation } from "./useDictation"; +import { DictationMeter } from "./DictationMeter"; import { OptionMenu, OptionMenuContent, OptionMenuLabel, OptionMenuTrigger } from "../ui/option-menu"; import { ComposerMenuRow } from "./TurnSettingsBar"; import { Button } from "../ui/button"; @@ -468,6 +471,13 @@ export const ChatComposer = memo(function ChatComposer({ */ const editor = useRef(null); + const dictation = useDictation({ + onText: (text) => editor.current?.dictate(text), + onEnd: (keep) => editor.current?.endDictation(keep), + }); + const dictating = dictation.phase !== "idle"; + // Dictation is in preview: macOS only, behind Developer mode. + const canDictate = useUiStore((state) => state.developerMode) && isMacPlatform(); const filePicker = useRef(null); const addMenuTrigger = useRef(null); const [addMenuBox, setAddMenuBox] = useState<{ lift: number; shift: number; width: number }>(); @@ -1295,6 +1305,8 @@ export const ChatComposer = memo(function ChatComposer({ // second transport whose local admission rejection would look like a real // provider failure. if (submitInFlight.current) return submitInFlight.current; + // Sending keeps what was dictated so far and stops listening. + dictation.detach(); // Sending a recalled message makes it the message, not a history position. historyBrowse.current = null; restoreFocusAfterSubmission.current = @@ -1698,6 +1710,10 @@ export const ChatComposer = memo(function ChatComposer({ function onKeyDown(event: KeyboardEvent) { if (event.nativeEvent.isComposing || event.keyCode === 229) return; + // Typing takes over from dictation, so the next transcript update cannot overwrite it. + if (dictating && !event.metaKey && !event.ctrlKey && (event.key.length === 1 || event.key === "Backspace" || event.key === "Delete")) { + dictation.detach(); + } // Enter is handled in Lexical before a newline is inserted; this handler is // only for menu navigation and escape while a completion menu is open. const liveSnapshot = editor.current?.getSnapshot(); @@ -2052,6 +2068,7 @@ export const ChatComposer = memo(function ChatComposer({ + {dictation.error} +

+ ) : null} {steerRefusal ?? steerOutcomeNotice ? (

{translateDraft(steerRefusal ?? steerOutcomeNotice)} @@ -2192,6 +2214,43 @@ export const ChatComposer = memo(function ChatComposer({ Steer ) : null} + {canDictate ? ( + + + + + + + {dictating ? "Finish dictation" : "Dictate"} + + ) : null} diff --git a/frontend/src/renderer/components/chat/ComposerEditor.tsx b/frontend/src/renderer/components/chat/ComposerEditor.tsx index 82c3f3bfdd..22edbf0649 100644 --- a/frontend/src/renderer/components/chat/ComposerEditor.tsx +++ b/frontend/src/renderer/components/chat/ComposerEditor.tsx @@ -19,16 +19,19 @@ import { COMMAND_PRIORITY_HIGH, DecoratorNode, getDOMSelectionFromTarget, + HISTORY_MERGE_TAG, HISTORY_PUSH_TAG, KEY_ENTER_COMMAND, KEY_ESCAPE_COMMAND, KEY_TAB_COMMAND, + TextNode, type EditorConfig, type LexicalEditor, type LexicalNode, type NodeKey, type RangeSelection, type SerializedLexicalNode, + type SerializedTextNode, type Spread, } from "lexical"; import { @@ -80,6 +83,13 @@ export type ComposerEditorHandle = { /** Where a collapsed caret sits relative to the whole text; undefined for a range. */ caretBoundary(): { atStart: boolean; atEnd: boolean } | undefined; insertToken(trigger: ComposerTrigger, value: string): void; + /** + * Shows a dictation transcript at the caret (or the end), replacing the one + * shown before it, so the words appear as they are recognized. + */ + dictate(text: string): void; + /** Ends the dictated run: kept as ordinary text, or removed. */ + endDictation(keep: boolean): void; /** Inserts a file reference chip at the caret (or the end) that sends `wire`. */ insertReference(path: string, display: string, wire: string): void; /** @@ -159,6 +169,50 @@ type SerializedComposerTokenNode = Spread< SerializedLexicalNode >; +/** How long a dictated letter takes to fade in (the `stream-char` animation in styles.css). */ +const DICTATION_FADE_MS = 300; +/** Letters that arrive together fade in this far apart, left to right. */ +const DICTATION_LETTER_STAGGER_MS = 14; + +/** + * One letter of a dictation in progress. A letter fades in once, when it first + * appears (the streamed-prose `stream-char` fade), after a delay that staggers + * the letters of a word. Revisions change the letter in place, and copies + * Lexical makes later (clone, split) never fade, so nothing flashes. The run + * becomes plain text once the last fade has finished. + */ +class DictationLetterNode extends TextNode { + __fadeDelay: number | undefined; + + static getType(): string { + return "dictation-letter"; + } + + static clone(node: DictationLetterNode): DictationLetterNode { + return new DictationLetterNode(node.__text, node.__key); + } + + static importJSON(serialized: SerializedTextNode): DictationLetterNode { + return new DictationLetterNode(serialized.text).updateFromJSON(serialized); + } + + constructor(text: string, key?: NodeKey, fadeDelay?: number) { + super(text, key); + this.__fadeDelay = fadeDelay; + } + + createDOM(config: EditorConfig, editor?: LexicalEditor): HTMLElement { + const dom = super.createDOM(config, editor); + if (this.__fadeDelay !== undefined) { + dom.classList.add("stream-char"); + // Hidden until its turn, then fades in like the rest. + dom.style.animationDelay = `${this.__fadeDelay}ms`; + dom.style.animationFillMode = "backwards"; + } + return dom; + } +} + class ComposerTokenNode extends DecoratorNode { __kind: TokenKind; __value: string; @@ -493,6 +547,8 @@ const EditorBridge = forwardRef< } >(function EditorBridge({ disabled, enterSends, promptSuggestion, onDismissSuggestion, onEmptyChange, attachedImages, onChange, onComplete, onEnter }, ref) { const [editor] = useLexicalComposerContext(); + /** The dictated letters, after an empty anchor node, and when the last fade ends. */ + const dictation = useRef<{ anchor: NodeKey; keys: NodeKey[]; prefix: string; settled: number } | null>(null); useEffect(() => editor.setEditable(!disabled), [disabled, editor]); @@ -523,6 +579,70 @@ const EditorBridge = forwardRef< $insertComposerToken(trigger, value); }, { discrete: true }); }, + dictate: (text) => { + const continuing = dictation.current !== null; + editor.update(() => { + let run = dictation.current; + if (!run) { + if (!text) return; + let selection = $getSelection(); + if (!$isRangeSelection(selection)) { + $getRoot().selectEnd(); + selection = $getSelection(); + } + if (!$isRangeSelection(selection)) return; + const { anchor } = selection; + const before = anchor.type === "text" ? anchor.getNode().getTextContent().slice(0, anchor.offset) : ""; + // Holds the run's place; it stays empty. + const anchorNode = new DictationLetterNode(""); + selection.insertNodes([anchorNode]); + run = { anchor: anchorNode.getKey(), keys: [], prefix: before && !/\s$/.test(before) ? " " : "", settled: 0 }; + dictation.current = run; + } + const letters = Array.from(run.prefix + text); + const nodes = run.keys.map((key) => $getNodeByKey(key)).filter($isTextNode); + let last: TextNode | null = $getNodeByKey(run.anchor); + if (!last) return; + const keys: NodeKey[] = []; + let arriving = 0; + letters.forEach((letter, index) => { + let node = nodes[index]; + if (node) { + // A revised letter changes in place, so it does not flash. + if (node.getTextContent() !== letter) node.setTextContent(letter); + } else { + const delay = arriving++ * DICTATION_LETTER_STAGGER_MS; + node = new DictationLetterNode(letter, undefined, delay); + last!.insertAfter(node); + run!.settled = Math.max(run!.settled, performance.now() + delay + DICTATION_FADE_MS); + } + last = node; + keys.push(node.getKey()); + }); + for (const extra of nodes.slice(letters.length)) extra.remove(); + run.keys = keys; + last.selectEnd(); + }, continuing ? { discrete: true, tag: HISTORY_MERGE_TAG } : { discrete: true }); + }, + endDictation: (keep) => { + const run = dictation.current; + dictation.current = null; + if (!run) return; + const finish = () => editor.update(() => { + const letters = run.keys.map((key) => $getNodeByKey(key)).filter($isTextNode); + const anchor = $getNodeByKey(run.anchor); + const text = letters.map((letter) => letter.getTextContent()).join(""); + if (keep && text && anchor) { + const plain = $createTextNode(text); + anchor.insertAfter(plain); + plain.selectEnd(); + } + for (const node of [anchor, ...letters]) node?.remove(); + }, { discrete: true, tag: HISTORY_MERGE_TAG }); + // Kept letters become plain text after their fades, so none is cut short. + if (keep) window.setTimeout(finish, Math.max(run.settled - performance.now(), 0)); + else finish(); + }, insertReference: (path, display, wire) => { editor.update(() => { $insertComposerReference(path, display, wire); @@ -669,6 +789,8 @@ export const ComposerEditor = forwardRef< enterSends: boolean; /** Hides the text while a send is in flight; the draft is still held for recovery. */ concealed?: boolean; + /** While dictating, the words arrive on their own: no caret, placeholder or suggestion. */ + dictating?: boolean; label: string; placeholder: string; promptSuggestion?: ComposerPromptSuggestion; @@ -688,6 +810,7 @@ export const ComposerEditor = forwardRef< disabled, enterSends, concealed, + dictating, label, placeholder, promptSuggestion, @@ -708,7 +831,7 @@ export const ComposerEditor = forwardRef< const suggestionDescriptionId = useId(); const [dismissedSuggestionId, setDismissedSuggestionId] = useState(); const [empty, setEmpty] = useState(true); - const suggestion = empty && !disabled && !concealed && promptSuggestion?.id !== dismissedSuggestionId + const suggestion = empty && !disabled && !concealed && !dictating && promptSuggestion?.id !== dismissedSuggestionId ? promptSuggestion : undefined; const dismissSuggestion = useCallback(() => { @@ -719,7 +842,7 @@ export const ComposerEditor = forwardRef< }, [promptSuggestion]); const initialConfig = { namespace: "AOChatComposer", - nodes: [ComposerTokenNode], + nodes: [ComposerTokenNode, DictationLetterNode], editable: !disabled, theme: { paragraph: "m-0" }, onError(error: Error) { @@ -741,10 +864,20 @@ export const ComposerEditor = forwardRef< ? "min-h-[4.5rem] whitespace-pre-wrap break-words" : "pointer-events-none absolute inset-x-0 top-0", )}> - {suggestion ? {suggestion.text} : } + {suggestion ? {suggestion.text} : ( + // Both stay mounted in one grid cell, so turning dictation on or off crossfades them. + + + + + + {t("chat.dictation.placeholder")} + + + )} ), - [placeholder, suggestion], + [dictating, placeholder, suggestion, t], ); return ( @@ -778,6 +911,7 @@ export const ComposerEditor = forwardRef< className={cn( "chat-composer-scrollbar max-h-40 min-h-[4.5rem] w-full overflow-y-auto overscroll-contain bg-transparent py-1 pl-[7px] pr-0 text-base! leading-relaxed text-foreground caret-foreground outline-none selection:bg-foreground selection:text-on-foreground", suggestion && "absolute inset-0 overflow-visible overscroll-auto", + dictating && "caret-transparent", concealed ? "invisible" : disabled && "opacity-50", )} /> diff --git a/frontend/src/renderer/components/chat/DictationMeter.tsx b/frontend/src/renderer/components/chat/DictationMeter.tsx new file mode 100644 index 0000000000..21ab7e85d2 --- /dev/null +++ b/frontend/src/renderer/components/chat/DictationMeter.tsx @@ -0,0 +1,79 @@ +import { useEffect, useRef } from "react"; +import { aoBridge } from "../../lib/bridge"; +import { cn } from "../../lib/utils"; + +const BARS = 11; +const MIDDLE = (BARS - 1) / 2; +/** Bar heights, 1px apart, from the resting dot to the pill's inner height. */ +const HEIGHTS = ["h-[3px]", "h-[4px]", "h-[5px]", "h-[6px]", "h-[7px]", "h-[8px]", "h-[9px]", "h-[10px]", "h-[11px]", "h-[12px]", "h-[13px]", "h-[14px]", "h-[15px]", "h-[16px]", "h-[17px]", "h-[18px]", "h-[19px]", "h-[20px]"]; +const BAR = "w-[3px] rounded-full bg-current"; +/** How tall each bar may grow: full in the middle, about a third at the ends. */ +const REACH = Array.from({ length: BARS }, (_, bar) => { + const distance = Math.abs(bar - MIDDLE) / MIDDLE; + return 1 - 0.65 * distance * distance; +}); +/** Helper levels at or below this are room noise; speech sits well above it. */ +const NOISE_FLOOR = 0.2; +const SPEECH_SPAN = 0.6; +/** The bars catch up with louder sound within a frame or two, and settle back gently. */ +const ATTACK_S = 0.03; +const RELEASE_S = 0.14; +/** A standing wave over the bell, so the bars rise and fall in place instead of travelling sideways. */ +const WAVE_DEPTH = 0.22; +const WAVE_HZ = 1.6; + +/** + * The microphone level as a row of bars that grow up and down from the + * middle: tallest in the centre, with a gentle standing wave across them. + * Drawn straight to the bars each frame, outside React. + */ +export function DictationMeter({ listening }: { listening: boolean }) { + const row = useRef(null); + + useEffect(() => { + const bars = Array.from(row.current?.children ?? []) as HTMLElement[]; + const draw = (level: number, seconds: number) => { + const swing = Math.cos(seconds * WAVE_HZ * 2 * Math.PI); + bars.forEach((bar, index) => { + const wave = 1 - WAVE_DEPTH * (0.5 + 0.5 * Math.sin((index / (BARS - 1)) * 3 * Math.PI) * swing); + const step = Math.round(level * REACH[index] * wave * (HEIGHTS.length - 1)); + const className = `${BAR} ${HEIGHTS[step]}`; + if (bar.className !== className) bar.className = className; + }); + }; + if (!listening) { + draw(0, 0); + return; + } + + let loudness = 0; + const unsubscribe = aoBridge.dictation.onEvent((event) => { + if (event.type === "levels") loudness = Math.max(loudness, ...event.values); + }); + let position = 0; + let last = performance.now(); + let frame = 0; + const tick = (now: number) => { + const dt = Math.min((now - last) / 1000, 0.05); + last = now; + const speech = Math.min(Math.max((loudness - NOISE_FLOOR) / SPEECH_SPAN, 0), 1); + loudness = 0; + position += (speech - position) * (1 - Math.exp(-dt / (speech > position ? ATTACK_S : RELEASE_S))); + draw(position, now / 1000); + frame = requestAnimationFrame(tick); + }; + frame = requestAnimationFrame(tick); + return () => { + cancelAnimationFrame(frame); + unsubscribe(); + }; + }, [listening]); + + return ( +