feat(chat): dictate into the composer with native macOS speech recognition (#7611)

* feat(chat): dictate into the composer with native macOS speech recognition

* feat(chat): pill meter, live fading transcript and Orchestrator-branded helper for dictation

* chore(desktop): package, sign and CI-build the dictation helper

* fix(chat): ignore events from a dictation helper that was replaced

* feat(chat): prompt 'Start speaking' in the empty composer while dictating

* feat(chat): crossfade the composer placeholder into 'Start speaking'

* fix(chat): keep the dictation placeholder in place while it crossfades

* fix(chat): read the dictation helper's last output before reporting its exit

* feat(chat): finish dictation when the app loses focus or quits

* feat(chat): show dictation only in Developer mode

* fix(chat): address dictation review: browser panel keeps ⌘D, one composer owns a dictation

- Leave ⌘D to pages in the in-app browser panel.
- Track the owning composer so a second composer's transcript never lands in the first.
- End at once when stopped before listening began.
- Finish dictation when the user types, so the next update cannot overwrite it.
- Hide Dictate from shortcut lists outside Developer mode.
- Serialize helper output off the real-time audio thread; name Orchestrator in permission errors.

* fix(chat): subscribe to dictation events only while dictating; fix CI

- useDictation listens only while its composer owns a dictation, so composers never touch the bridge at mount (test bridges without dictation crashed every chat suite).
- Add dictation to the e2e fake bridges (renderer-smoke typecheck).
- Add the Russian strings that landed on main after these keys.
- Give the cloudflared packaging test a dictation helper so it still fails on cloudflared.

* test: add dictation to the renderer test bridge
This commit is contained in:
ronish authored and GitHub committed 2026-11-03 09:00:24 +05:30
1 parent ca08ac681e
commit 2895333c5d
39 files changed
+877 -12

No files matched your search

+6
View File
@@ -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
+1
View File
@@ -108,3 +108,4 @@ pnpm-lock.yaml
.serena/
/frontend/wake-helper/
/frontend/dictation-helper/
+12
View File
@@ -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,
+16
View File
@@ -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 });
+15 -1
View File
@@ -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}`);
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>dev.agent-orchestrator.desktop.dictation</string>
<key>CFBundleName</key>
<string>Orchestrator</string>
<key>CFBundleDisplayName</key>
<string>Orchestrator</string>
<key>CFBundleExecutable</key>
<string>Orchestrator</string>
<key>CFBundleIconFile</key>
<string>icon</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>LSMinimumSystemVersion</key>
<string>11.0</string>
<!-- A background helper: no Dock icon or menu bar. -->
<key>LSUIElement</key>
<true/>
<key>NSMicrophoneUsageDescription</key>
<string>Orchestrator uses the microphone to dictate messages.</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Orchestrator turns your speech into message text.</string>
</dict>
</plist>
+184
View File
@@ -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<Float>, count: Int) -> Double {
var sum: Float = 0
for index in 0..<count { sum += samples[index] * samples[index] }
let decibels = 20 * log10(max(sqrt(sum / Float(count)), 1e-6))
return (Double(min(max((decibels + 60) / 50, 0), 1)) * 1000).rounded() / 1000
}
final class Dictation {
private let engine = AVAudioEngine()
private let request = SFSpeechAudioBufferRecognitionRequest()
private var task: SFSpeechRecognitionTask?
private var text = ""
/** What was heard, one utterance per pause. `end` is the audio time an ended utterance ran to. */
private var utterances: [(text: String, end: TimeInterval?)] = []
private var stopping = false
func start() {
guard let recognizer = SFSpeechRecognizer(locale: Locale.current) ?? SFSpeechRecognizer(), recognizer.isAvailable else {
fail("Speech recognition is not available for your language.")
}
request.shouldReportPartialResults = true
if #available(macOS 13, *) { request.addsPunctuation = true }
if recognizer.supportsOnDeviceRecognition { request.requiresOnDeviceRecognition = true }
let input = engine.inputNode
let format = input.outputFormat(forBus: 0)
guard format.sampleRate > 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<posix_spawnattr_t?>, _ 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<CChar>?] = [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()
+2 -1
View File
@@ -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",
@@ -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 });
}
+10
View File
@@ -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<void> {
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);
});
@@ -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();
+2
View File
@@ -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(
{
+56
View File
@@ -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 };
}
+13
View File
@@ -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<string>();
const api = {
dictation: {
start: () => ipcRenderer.invoke("dictation:start") as Promise<void>,
stop: () => ipcRenderer.invoke("dictation:stop") as Promise<void>,
cancel: () => ipcRenderer.invoke("dictation:cancel") as Promise<void>,
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<string>,
chooseDirectory: (input?: string | { title?: string; defaultPath?: string }) => ipcRenderer.invoke("app:chooseDirectory", input) as Promise<string | null>,
@@ -43,11 +43,13 @@ describe("KeyboardShortcutsDialog", () => {
render(<KeyboardShortcutsDialog open onOpenChange={vi.fn()} isMac />);
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", () => {
@@ -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);
@@ -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;
@@ -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<string | null>(null);
const handleInspectorCloseAnimationComplete = useCallback(() => {
@@ -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<ComposerEditorHandle>(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<HTMLInputElement>(null);
const addMenuTrigger = useRef<HTMLButtonElement>(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<HTMLDivElement>) {
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({
<ComposerEditor
ref={editor}
dictating={dictating}
images={composerImages}
promptSuggestion={willQueue || starting || editingQueuedTurnId || staged ? undefined : promptSuggestion}
disabled={Boolean(disabled || queuedEditRecovery || (!optimisticSend && (submitting || draftMutationPending)))}
@@ -2097,6 +2114,11 @@ export const ChatComposer = memo(function ChatComposer({
{/* A refused steer is an ordinary outcome, not a failure: the text is still
in the box and the message says which of "send it instead" and "try again
in a moment" applies. */}
{dictation.error ? (
<p role="status" className="px-1.5 text-xs leading-snug text-warning">
{dictation.error}
</p>
) : null}
{steerRefusal ?? steerOutcomeNotice ? (
<p role="status" className="px-1.5 text-xs leading-snug text-warning">
{translateDraft(steerRefusal ?? steerOutcomeNotice)}
@@ -2192,6 +2214,43 @@ export const ChatComposer = memo(function ChatComposer({
Steer
</Button>
) : null}
{canDictate ? (
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex">
<Button
type="button"
variant="ghost"
size="none"
disabled={!dictating && controlsDisabled}
// Keep focus in the editor, where the words appear.
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
editor.current?.focus();
dictation.toggle();
}}
data-shortcut-target="dictate"
aria-label={dictating ? "Finish dictation" : "Dictate"}
aria-pressed={dictating}
className={cn(
// Important: the chat surface's button rule (styles.css) would otherwise drop width from the transition.
"mr-1 h-7 overflow-hidden rounded-full p-0 transition-[width,background-color,color]! duration-200! ease-[cubic-bezier(0.23,1,0.32,1)]! active:translate-y-0! active:transform-none! active:scale-100! motion-reduce:transition-none!",
dictating
? "w-[76px] bg-foreground text-on-foreground hover:bg-foreground/90! hover:text-on-foreground dark:hover:bg-foreground/90!"
: "w-7 text-muted-foreground hover:bg-interactive-active! hover:text-foreground",
)}
>
{dictating ? (
<DictationMeter listening={dictation.phase === "listening"} />
) : (
<Mic aria-hidden="true" className="size-3.5" />
)}
</Button>
</span>
</TooltipTrigger>
<TooltipContent side="bottom">{dictating ? "Finish dictation" : "Dictate"}</TooltipContent>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex">
@@ -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<JSX.Element> {
__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<TextNode>(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<string>();
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 ? <span data-testid="prompt-suggestion">{suggestion.text}</span> : <FadingPlaceholder text={placeholder} />}
{suggestion ? <span data-testid="prompt-suggestion">{suggestion.text}</span> : (
// Both stay mounted in one grid cell, so turning dictation on or off crossfades them.
<span className="grid *:col-start-1 *:row-start-1 *:transition-[opacity,filter] *:duration-300 *:ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:*:transition-none">
<span aria-hidden={dictating} className={dictating ? "opacity-0 blur-[2px]" : "opacity-100 blur-0"}>
<FadingPlaceholder text={placeholder} />
</span>
<span aria-hidden={!dictating} className={dictating ? "opacity-100 blur-0" : "opacity-0 blur-[2px]"}>
{t("chat.dictation.placeholder")}
</span>
</span>
)}
</div>
),
[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",
)}
/>
@@ -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<HTMLSpanElement>(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 (
<span ref={row} aria-hidden="true" className="flex h-5 items-center gap-0.5">
{Array.from({ length: BARS }, (_, index) => (
<span key={index} className={cn(BAR, HEIGHTS[0])} />
))}
</span>
);
}
@@ -0,0 +1,128 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { aoBridge } from "../../lib/bridge";
import type { DictationEvent } from "../../../shared/dictation";
export type DictationPhase = "idle" | "starting" | "listening" | "finishing";
/** The composer whose dictation is running. Starting another one finishes it first. */
let owner: { end(keep: boolean): void } | null = null;
type DictationTarget = {
/** Shows the transcript so far in place of the previous one. */
onText(text: string): void;
/** Ends the dictated run: kept as typed text, or removed. */
onEnd(keep: boolean): void;
};
/**
* Native macOS dictation for one composer. The transcript streams into the
* composer while the user speaks; microphone levels go straight to the meter
* (see DictationMeter) so they never re-render the composer.
*/
export function useDictation(target: DictationTarget) {
const [phase, setPhase] = useState<DictationPhase>("idle");
const [error, setError] = useState<string>();
const targetRef = useRef(target);
targetRef.current = target;
const self = useRef<{ end(keep: boolean): void }>(null!);
const owns = () => owner === self.current;
// Listening only while this composer owns a dictation.
const unsubscribe = useRef<(() => void) | null>(null);
const end = useCallback((keep: boolean) => {
if (owner === self.current) owner = null;
unsubscribe.current?.();
unsubscribe.current = null;
setPhase("idle");
targetRef.current.onEnd(keep);
}, []);
self.current ??= { end };
const onEvent = useCallback((event: DictationEvent) => {
switch (event.type) {
case "listening":
setPhase("listening");
break;
case "finishing":
setPhase("finishing");
break;
case "text":
targetRef.current.onText(event.text);
break;
case "end":
targetRef.current.onText(event.text);
end(true);
break;
case "error":
setError(event.message);
end(true);
break;
case "exit":
setError("Dictation stopped unexpectedly.");
end(true);
break;
}
}, [end]);
useEffect(() => {
if (!error) return;
const timer = window.setTimeout(() => setError(undefined), 6000);
return () => window.clearTimeout(timer);
}, [error]);
/** Stops listening at once, keeping or dropping the dictated text. */
const halt = useCallback((keep: boolean) => {
if (!owns()) return;
end(keep);
void aoBridge.dictation.cancel();
}, [end]);
useEffect(() => () => {
if (!owns()) return;
owner = null;
unsubscribe.current?.();
void aoBridge.dictation.cancel();
}, []);
const start = useCallback(() => {
// The main process replaces the running helper; the composer it belonged to keeps its words.
owner?.end(true);
owner = self.current;
unsubscribe.current = aoBridge.dictation.onEvent(onEvent);
setError(undefined);
setPhase("starting");
void aoBridge.dictation.start();
}, [onEvent]);
/** Ends the audio and waits for the recognizer's final wording. */
const stop = useCallback(() => {
if (!owns()) return;
setPhase("finishing");
void aoBridge.dictation.stop();
}, []);
useEffect(() => {
if (phase === "idle") return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape") return;
// Escape belongs to dictation while it runs, not to menus or the page behind.
event.preventDefault();
event.stopPropagation();
stop();
};
window.addEventListener("keydown", onKeyDown, true);
return () => window.removeEventListener("keydown", onKeyDown, true);
}, [phase, stop]);
const toggle = useCallback(() => {
if (!owns()) start();
else if (phase !== "finishing") stop();
}, [phase, start, stop]);
return {
phase,
error,
toggle,
detach: useCallback(() => halt(true), [halt]),
};
}
@@ -20,6 +20,7 @@ import { isMacPlatform } from "../../lib/platform";
import { aoBridge } from "../../lib/bridge";
import { cn } from "../../lib/utils";
import { useKeybindingsStore } from "../../stores/keybindings-store";
import { useUiStore } from "../../stores/ui-store";
import { Button } from "../ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
import { ConfirmDialog } from "../ConfirmDialog";
@@ -218,9 +219,12 @@ export function KeyboardShortcutsContent({
return () => body.removeEventListener("scroll", toTop);
}, [bounded]);
const developerMode = useUiStore((state) => state.developerMode);
const filteredShortcuts = useMemo(() => {
const needles = searchText(query).split(/\s+/).filter(Boolean);
return APP_SHORTCUTS.filter((shortcut) => {
// Dictation is in preview behind Developer mode.
if (shortcut.id === "dictate" && !developerMode) return false;
if (modifiedOnly && !Object.hasOwn(overrides, shortcut.id)) return false;
const labels = effectiveShortcutBindings(shortcut.id, isMac, overrides)
.map((candidate) => `${shortcutBindingLabel(candidate, isMac)} ${bindingDescription(candidate, isMac)}`)
@@ -228,7 +232,7 @@ export function KeyboardShortcutsContent({
const haystack = searchText(`${shortcutLabel(shortcut.id, t)} ${shortcutCategoryLabel(shortcut.category, t)} ${labels}`);
return needles.every((needle) => haystack.includes(needle));
});
}, [isMac, overrides, query, modifiedOnly, t]);
}, [developerMode, isMac, overrides, query, modifiedOnly, t]);
const mutate = async (id: AppShortcutId, operation: () => Promise<void>) => {
if (savingRef.current) return false;
+2
View File
@@ -1984,6 +1984,7 @@
"shortcut.jump-to-session": "Zu Sitzung 1–9 springen",
"shortcut.keyboard-shortcuts": "Tastenkürzel anzeigen",
"shortcut.model-picker": "Modell wählen",
"shortcut.dictate": "Diktieren",
"shortcut.modified": "Geändert",
"shortcut.movedBody": "{{binding}} von {{from}} nach {{to}} verschoben",
"shortcut.new-session": "Neue Sitzung",
@@ -3249,6 +3250,7 @@
"chat.draftDiscard.stay": "Bleiben",
"chat.draftDiscard.leaveAnyway": "Trotzdem verlassen",
"chat.promptSuggestion.description": "Vorschlag für die nächste Nachricht: {{prompt}}. Mit Tab übernehmen oder mit Escape verwerfen.",
"chat.dictation.placeholder": "Sprich jetzt",
"chat.edit.abandonRecovery": "Bearbeitungswiederherstellung aufgeben",
"chat.welcome.heading": "Woran möchten Sie arbeiten?",
"chat.welcome.artifactHeading": "What do you want to create?",
+2
View File
@@ -2375,6 +2375,7 @@
"shortcut.jump-to-session": "Jump to session 1–9",
"shortcut.keyboard-shortcuts": "Show keyboard shortcuts",
"shortcut.model-picker": "Choose model",
"shortcut.dictate": "Dictate",
"shortcut.modified": "Modified",
"shortcut.moreBindings_one": "{{count}} alternative shortcut. Choose Customize to view all bindings.",
"shortcut.moreBindings_other": "{{count}} alternative shortcuts. Choose Customize to view all bindings.",
@@ -3239,6 +3240,7 @@
"chat.draftDiscard.stay": "Stay",
"chat.draftDiscard.leaveAnyway": "Leave anyway",
"chat.promptSuggestion.description": "Suggested next message: {{prompt}}. Press Tab to use it, or Escape to dismiss.",
"chat.dictation.placeholder": "Start speaking",
"chat.edit.abandonRecovery": "Abandon edit recovery",
"chat.welcome.heading": "What do you want to work on?",
"chat.welcome.artifactHeading": "What do you want to create?",
+2
View File
@@ -2017,6 +2017,7 @@
"shortcut.jump-to-session": "Ir a la sesión 1–9",
"shortcut.keyboard-shortcuts": "Mostrar atajos de teclado",
"shortcut.model-picker": "Elegir modelo",
"shortcut.dictate": "Dictar",
"shortcut.modified": "Modificado",
"shortcut.movedBody": "{{binding}} movido de {{from}} a {{to}}",
"shortcut.new-session": "Nueva sesión",
@@ -3307,6 +3308,7 @@
"chat.draftDiscard.stay": "Quedarse",
"chat.draftDiscard.leaveAnyway": "Salir de todos modos",
"chat.promptSuggestion.description": "Mensaje siguiente sugerido: {{prompt}}. Pulsa Tab para usarlo o Escape para descartarlo.",
"chat.dictation.placeholder": "Empieza a hablar",
"chat.edit.abandonRecovery": "Abandonar recuperación de edición",
"chat.welcome.heading": "¿En qué quieres trabajar?",
"chat.welcome.artifactHeading": "What do you want to create?",
+2
View File
@@ -2017,6 +2017,7 @@
"shortcut.jump-to-session": "Aller à la session 1–9",
"shortcut.keyboard-shortcuts": "Afficher les raccourcis clavier",
"shortcut.model-picker": "Choisir le modèle",
"shortcut.dictate": "Dicter",
"shortcut.modified": "Modifié",
"shortcut.movedBody": "{{binding}} déplacé de {{from}} vers {{to}}",
"shortcut.new-session": "Nouvelle session",
@@ -3307,6 +3308,7 @@
"chat.draftDiscard.stay": "Rester",
"chat.draftDiscard.leaveAnyway": "Quitter quand même",
"chat.promptSuggestion.description": "Message suivant suggéré : {{prompt}}. Appuyez sur Tab pour l’utiliser ou sur Échap pour l’ignorer.",
"chat.dictation.placeholder": "Commencez à parler",
"chat.edit.abandonRecovery": "Abandonner la récupération de la modification",
"chat.welcome.heading": "Sur quoi voulez-vous travailler ?",
"chat.welcome.artifactHeading": "What do you want to create?",
+2
View File
@@ -1984,6 +1984,7 @@
"shortcut.jump-to-session": "セッション 1–9 に移動",
"shortcut.keyboard-shortcuts": "キーボードショートカットを表示",
"shortcut.model-picker": "モデルを選択",
"shortcut.dictate": "音声入力",
"shortcut.modified": "変更済み",
"shortcut.movedBody": "{{binding}} を {{from}} から {{to}} に移動しました",
"shortcut.new-session": "新しいセッション",
@@ -3249,6 +3250,7 @@
"chat.draftDiscard.stay": "留まる",
"chat.draftDiscard.leaveAnyway": "離れる",
"chat.promptSuggestion.description": "次のメッセージの提案: {{prompt}}。Tab キーで使用、Escape キーで閉じます。",
"chat.dictation.placeholder": "話してください",
"chat.edit.abandonRecovery": "編集の復旧を中止",
"chat.welcome.heading": "何に取り組みますか?",
"chat.welcome.artifactHeading": "What do you want to create?",
+1
View File
@@ -28,6 +28,7 @@ export const shortcutLabelKeys: Record<AppShortcutId, MessageKey> = {
"open-in-editor": "shortcut.open-in-editor",
"copy-session-path": "shortcut.copy-session-path",
"model-picker": "shortcut.model-picker",
dictate: "shortcut.dictate",
"open-orchestrator": "shortcut.open-orchestrator",
"toggle-browser-devtools": "titlebar.devtools",
};
+2
View File
@@ -1984,6 +1984,7 @@
"shortcut.jump-to-session": "세션 1–9로 이동",
"shortcut.keyboard-shortcuts": "키보드 단축키 표시",
"shortcut.model-picker": "모델 선택",
"shortcut.dictate": "받아쓰기",
"shortcut.modified": "수정됨",
"shortcut.movedBody": "{{binding}}을(를) {{from}}에서 {{to}}(으)로 이동했습니다",
"shortcut.new-session": "새 세션",
@@ -3249,6 +3250,7 @@
"chat.draftDiscard.stay": "머무르기",
"chat.draftDiscard.leaveAnyway": "그래도 나가기",
"chat.promptSuggestion.description": "다음 메시지 제안: {{prompt}}. Tab 키로 사용하거나 Escape 키로 닫으세요.",
"chat.dictation.placeholder": "말씀하세요",
"chat.edit.abandonRecovery": "편집 복구 포기",
"chat.welcome.heading": "무엇을 작업하고 싶으신가요?",
"chat.welcome.artifactHeading": "What do you want to create?",
+2
View File
@@ -2017,6 +2017,7 @@
"shortcut.jump-to-session": "Ir para a sessão 1–9",
"shortcut.keyboard-shortcuts": "Mostrar atalhos de teclado",
"shortcut.model-picker": "Escolher modelo",
"shortcut.dictate": "Ditar",
"shortcut.modified": "Modificado",
"shortcut.movedBody": "{{binding}} movido de {{from}} para {{to}}",
"shortcut.new-session": "Nova sessão",
@@ -3307,6 +3308,7 @@
"chat.draftDiscard.stay": "Ficar",
"chat.draftDiscard.leaveAnyway": "Sair mesmo assim",
"chat.promptSuggestion.description": "Próxima mensagem sugerida: {{prompt}}. Pressione Tab para usar ou Escape para dispensar.",
"chat.dictation.placeholder": "Comece a falar",
"chat.edit.abandonRecovery": "Abandonar recuperação da edição",
"chat.welcome.heading": "Em que você quer trabalhar?",
"chat.welcome.artifactHeading": "What do you want to create?",
+2
View File
@@ -2453,6 +2453,7 @@
"shortcut.jump-to-session": "Перейти к сессии 1–9",
"shortcut.keyboard-shortcuts": "Показать горячие клавиши",
"shortcut.model-picker": "Выбрать модель",
"shortcut.dictate": "Диктовка",
"shortcut.modified": "Изменено",
"shortcut.moreBindings_one": "{{count}} альтернативное сочетание клавиш. Выберите «Настроить», чтобы увидеть все сочетания.",
"shortcut.moreBindings_few": "{{count}} альтернативных сочетания клавиш. Выберите «Настроить», чтобы увидеть все сочетания.",
@@ -3364,6 +3365,7 @@
"chat.draftDiscard.stay": "Остаться",
"chat.draftDiscard.leaveAnyway": "Всё равно выйти",
"chat.promptSuggestion.description": "Предлагаемое следующее сообщение: {{prompt}}. Нажмите Tab, чтобы использовать его, или Escape, чтобы отклонить.",
"chat.dictation.placeholder": "Начните говорить",
"chat.edit.abandonRecovery": "Отказаться от восстановления изменения",
"chat.welcome.heading": "Над чем вы хотите поработать?",
"chat.welcome.artifactHeading": "Что вы хотите создать?",
+2
View File
@@ -2041,6 +2041,7 @@
"shortcut.jump-to-session": "跳转到会话 1–9",
"shortcut.keyboard-shortcuts": "显示键盘快捷键",
"shortcut.model-picker": "选择模型",
"shortcut.dictate": "听写",
"shortcut.modified": "已修改",
"shortcut.movedBody": "{{binding}} 已从 {{from}} 移至 {{to}}",
"shortcut.new-session": "新建会话",
@@ -3231,6 +3232,7 @@
"chat.draftDiscard.stay": "留下",
"chat.draftDiscard.leaveAnyway": "仍然离开",
"chat.promptSuggestion.description": "建议的下一条消息:{{prompt}}。按 Tab 使用,或按 Escape 关闭。",
"chat.dictation.placeholder": "请开始说话",
"chat.edit.abandonRecovery": "放弃编辑恢复",
"chat.welcome.heading": "你想做什么?",
"chat.welcome.artifactHeading": "What do you want to create?",
+6
View File
@@ -6,6 +6,12 @@ export type { FeatureBuild } from "../../main/feature-builds";
export const aoBridge: AoBridge =
window.ao ??
({
dictation: {
start: async () => undefined,
stop: async () => undefined,
cancel: async () => undefined,
onEvent: () => () => undefined,
},
app: {
getVersion: async () => "0.0.0-preview",
chooseDirectory: async () => null,
@@ -11,3 +11,10 @@ export function openComposerModelPicker(): void {
picker.focus();
picker.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
}
/** ⌘D: starts or finishes dictation in the focused chat composer, else the first one on screen. */
export function toggleComposerDictation(): void {
const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>("[data-shortcut-target='dictate']:not([disabled])"));
const active = document.activeElement;
(buttons.find((button) => active && button.closest("form")?.contains(active)) ?? buttons[0])?.click();
}
+6
View File
@@ -128,6 +128,12 @@ if (typeof window !== "undefined") {
document.elementFromPoint = (() => null) as typeof document.elementFromPoint;
window.ao = {
dictation: {
start: async () => undefined,
stop: async () => undefined,
cancel: async () => undefined,
onEvent: () => () => undefined,
},
app: {
getVersion: async () => "0.0.0-test",
chooseDirectory: async () => null,
+10
View File
@@ -0,0 +1,10 @@
export type DictationEvent =
| { type: "listening" }
/** Loudness in 0...1, one value per 10 ms of audio, oldest first. */
| { type: "levels"; values: number[] }
| { type: "text"; text: string }
/** Listening stopped; the final wording follows as "end". */
| { type: "finishing" }
| { type: "end"; text: string }
| { type: "error"; message: string }
| { type: "exit" };
+1
View File
@@ -158,6 +158,7 @@ describe("default shortcuts", () => {
["open-in-editor", chord({ key: "o", meta: true })],
["copy-session-path", chord({ key: "C", meta: true, shift: true })],
["model-picker", chord({ key: "M", meta: true, shift: true })],
["dictate", chord({ key: "d", meta: true })],
["open-orchestrator", chord({ key: "O", meta: true, shift: true })],
] as const)("macOS binds %s to its chord", (id, pressed) => {
expect(matchesAppShortcut(id, pressed, true)).toBe(true);
+5
View File
@@ -55,6 +55,7 @@ export type AppShortcutId =
| "open-in-editor"
| "copy-session-path"
| "model-picker"
| "dictate"
| "open-orchestrator"
| "toggle-browser-devtools";
@@ -105,6 +106,7 @@ export const APP_SHORTCUTS: readonly ShortcutDefinition[] = [
{ id: "open-in-editor", label: "Open in editor", category: "Session" },
{ id: "copy-session-path", label: "Copy session path", category: "Session" },
{ id: "model-picker", label: "Choose model", category: "Session" },
{ id: "dictate", label: "Dictate", category: "Session" },
{ id: "open-orchestrator", label: "Open orchestrator", category: "Session" },
{ id: "toggle-sidebar", label: "Toggle sidebar", category: "Panels" },
{ id: "toggle-inspector", label: "Toggle inspector", category: "Panels" },
@@ -199,6 +201,9 @@ export function defaultShortcutBindings(id: AppShortcutId, isMac: boolean): read
return [isMac ? binding("c", { meta: true, shift: true }) : binding("l", { ctrl: true, shift: true })];
case "model-picker":
return [binding("m", { ...primary, shift: true })];
// Plain Ctrl+D is end-of-input in a terminal, so other platforms add Alt.
case "dictate":
return [isMac ? binding("d", { meta: true }) : binding("d", { ctrl: true, alt: true })];
// Ctrl+Shift+O is Open in editor on Windows/Linux (plain Ctrl+O is
// readline), so that platform takes G for "go to orchestrator".
case "open-orchestrator":