Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(desktop): free on-device dictation on Windows

AdityaUmalebee939541233
diff --git a/electron/capabilities.cjs b/electron/capabilities.cjs
index 15ad767c8c..b976ca7bcb 100644
--- a/electron/capabilities.cjs
+++ b/electron/capabilities.cjs
@@ -13,6 +13,7 @@ function nativeDesktopActions(platform) {
appleMediaPermissions: appleNative,
applePrivacySettings: appleNative,
appleSpeech: appleNative,
+ windowsSpeech: normalizedPlatform(platform) === "win32",
});
}
@@ -144,12 +145,14 @@ function desktopCapabilities({
screenPreview.reasonCode =
hostPlatform === "linux" ? "headless-session" : "unsupported-platform";
}
- // Off the Mac the page listens itself and Fish Audio turns each clip into text (src/lib/fish-speech.ts).
- const fishListening = hostPlatform === "win32" || hostPlatform === "linux";
+ // Windows listens through its own recognizer (speech-helper-windows.ps1). On Linux the page listens itself and Fish
+ // Audio turns each clip into text (src/lib/fish-speech.ts).
+ const isWindows = hostPlatform === "win32";
+ const fishListening = hostPlatform === "linux";
const dictation = {
- available: isMac || fishListening,
- engine: isMac ? "apple-speech" : fishListening ? "fish-audio" : "none",
- onDevice: isMac,
+ available: isMac || isWindows || fishListening,
+ engine: isMac ? "apple-speech" : isWindows ? "windows-speech" : fishListening ? "fish-audio" : "none",
+ onDevice: isMac || isWindows,
};
if (!dictation.available) dictation.reasonCode = "unsupported-platform";
const localComputer = {
diff --git a/electron/capabilities.test.mjs b/electron/capabilities.test.mjs
index ff6c6f1c9f..6ee621e111 100644
--- a/electron/capabilities.test.mjs
+++ b/electron/capabilities.test.mjs
@@ -20,12 +20,14 @@ describe("desktop capabilities", () => {
appleMediaPermissions: false,
applePrivacySettings: false,
appleSpeech: false,
+ windowsSpeech: false,
});
- expect(nativeDesktopActions("win32")).toEqual(nativeDesktopActions("linux"));
+ expect(nativeDesktopActions("win32")).toEqual({ ...nativeDesktopActions("linux"), windowsSpeech: true });
expect(nativeDesktopActions("darwin")).toEqual({
appleMediaPermissions: true,
applePrivacySettings: true,
appleSpeech: true,
+ windowsSpeech: false,
});
});
@@ -127,12 +129,11 @@ describe("desktop capabilities", () => {
expect(reasonOf("desktop-host-stopped")).toBe("cua-driver-unavailable");
});
- it.each(["win32", "linux"])("listens through Fish Audio on %s, but not from a server's page", (platform) => {
- expect(desktopCapabilities({ platform, env: { DISPLAY: ":0" } }).dictation).toEqual({
- available: true,
- engine: "fish-audio",
- onDevice: false,
- });
+ it.each([
+ ["win32", { available: true, engine: "windows-speech", onDevice: true }],
+ ["linux", { available: true, engine: "fish-audio", onDevice: false }],
+ ])("listens on %s, but not from a server's page", (platform, dictation) => {
+ expect(desktopCapabilities({ platform, env: { DISPLAY: ":0" } }).dictation).toEqual(dictation);
expect(desktopCapabilities({ platform, remote: true }).dictation).toEqual({
available: false,
engine: "none",
diff --git a/electron/main.mjs b/electron/main.mjs
index cf9dc9c154..6a7ae4baa8 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -2343,7 +2343,7 @@ ipcMain.handle("desktop:relaunch", localOnly("desktop:relaunch", (event) => {
return true;
}));
-const talk = installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions.appleSpeech,
+const talk = installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions.appleSpeech, windowsSpeech: nativeActions.windowsSpeech,
speech: { start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy }, packaged: app.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog, t: nativeT });
ipcMain.handle("companion:state", localOnly("companion:state", () => desktopCompanionState()));
@@ -3087,7 +3087,7 @@ app.on("before-quit", (e) => {
try {
desktopCompanionRelay?.close?.();
} catch {}
- if (nativeActions.appleSpeech) stopSpeech();
+ if (nativeActions.appleSpeech || nativeActions.windowsSpeech) stopSpeech();
const ownedHelperCleanup = Promise.race([
Promise.all([
stopCua().catch(() => {}),
diff --git a/electron/resources/speech-helper-windows.ps1 b/electron/resources/speech-helper-windows.ps1
new file mode 100644
index 0000000000..b10572a5cf
--- /dev/null
+++ b/electron/resources/speech-helper-windows.ps1
@@ -0,0 +1,112 @@
+# Windows dictation through the speech recognizer built into Windows (System.Speech): on this computer, offline, no key.
+# Same output as speech-helper.swift, one JSON object per line on stdout:
+# {"partial":true,"text":"..."} while recognizing
+# {"partial":false,"text":"..."} final result, then exit 0
+# {"error":"..."} then exit 1
+# Commands arrive on stdin, one per line: "finish" ends the audio and sends the final result. stdin closing because the
+# app is gone exits at once without one; the app stops a session by ending this process.
+# -EndpointMs N finishes after N milliseconds without a changed transcript (calls); dictation leaves it 0.
+param([int]$EndpointMs = 0)
+
+$ErrorActionPreference = 'Stop'
+[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
+
+function Send-Line($line) {
+ [Console]::Out.WriteLine(($line | ConvertTo-Json -Compress))
+ [Console]::Out.Flush()
+}
+
+function Join-Text($left, $right) {
+ if ($left -and $right) { return "$left $right" }
+ if ($left) { return $left }
+ return $right
+}
+
+try {
+ Add-Type -AssemblyName System.Speech
+ $installed = @([System.Speech.Recognition.SpeechRecognitionEngine]::InstalledRecognizers())
+} catch {
+ Send-Line @{ error = 'speech-unavailable' }
+ exit 1
+}
+if ($installed.Count -eq 0) {
+ Send-Line @{ error = 'speech-language-missing' }
+ exit 1
+}
+# The person's display language first, then the same language in another region, then any installed recognizer.
+$culture = [System.Globalization.CultureInfo]::CurrentUICulture
+$recognizer = $installed | Where-Object { $_.Culture.Name -eq $culture.Name } | Select-Object -First 1
+if (-not $recognizer) {
+ $recognizer = $installed | Where-Object { $_.Culture.TwoLetterISOLanguageName -eq $culture.TwoLetterISOLanguageName } | Select-Object -First 1
+}
+if (-not $recognizer) { $recognizer = $installed[0] }
+
+try {
+ $engine = New-Object System.Speech.Recognition.SpeechRecognitionEngine($recognizer)
+ $engine.LoadGrammar((New-Object System.Speech.Recognition.DictationGrammar))
+ $engine.SetInputToDefaultAudioDevice()
+} catch {
+ Send-Line @{ error = 'helper-start-failed' }
+ exit 1
+}
+
+Register-ObjectEvent -InputObject $engine -EventName SpeechHypothesized -SourceIdentifier 'omb-heard' | Out-Null
+Register-ObjectEvent -InputObject $engine -EventName SpeechRecognized -SourceIdentifier 'omb-recognized' | Out-Null
+Register-ObjectEvent -InputObject $engine -EventName RecognizeCompleted -SourceIdentifier 'omb-completed' | Out-Null
+
+$commands = New-Object System.IO.StreamReader([Console]::OpenStandardInput())
+$command = $commands.ReadLineAsync()
+$committed = ''
+$shown = ''
+$changedAt = [DateTime]::UtcNow
+$finishing = $false
+$engine.RecognizeAsync([System.Speech.Recognition.RecognizeMode]::Multiple)
+
+while ($true) {
+ foreach ($received in @(Get-Event)) {
+ Remove-Event -EventIdentifier $received.EventIdentifier
+ switch ($received.SourceIdentifier) {
+ 'omb-heard' {
+ $text = Join-Text $committed $received.SourceEventArgs.Result.Text
+ if ($text -ne $shown) {
+ $shown = $text
+ $changedAt = [DateTime]::UtcNow
+ Send-Line @{ partial = $true; text = $text }
+ }
+ }
+ 'omb-recognized' {
+ $committed = Join-Text $committed $received.SourceEventArgs.Result.Text
+ $shown = $committed
+ $changedAt = [DateTime]::UtcNow
+ Send-Line @{ partial = $true; text = $committed }
+ }
+ 'omb-completed' {
+ if ($received.SourceEventArgs.Error) {
+ Send-Line @{ error = 'helper-exited' }
+ exit 1
+ }
+ Send-Line @{ partial = $false; text = $committed }
+ exit 0
+ }
+ }
+ }
+ if (-not $finishing -and $command.IsCompleted) {
+ $line = $null
+ if (-not $command.IsFaulted) { $line = $command.Result }
+ if ($null -eq $line) {
+ $engine.RecognizeAsyncCancel()
+ exit 0
+ }
+ if ($line.Trim() -eq 'finish') {
+ $finishing = $true
+ $engine.RecognizeAsyncStop()
+ } else {
+ $command = $commands.ReadLineAsync()
+ }
+ }
+ if (-not $finishing -and $EndpointMs -gt 0 -and $shown -and ([DateTime]::UtcNow - $changedAt).TotalMilliseconds -ge $EndpointMs) {
+ $finishing = $true
+ $engine.RecognizeAsyncStop()
+ }
+ Start-Sleep -Milliseconds 50
+}
diff --git a/electron/speech.mjs b/electron/speech.mjs
index 6b7c0a83c2..266e063da1 100644
--- a/electron/speech.mjs
+++ b/electron/speech.mjs
@@ -1,4 +1,5 @@
// macOS privacy enforcement requires the code calling Speech/AVFoundation to launch with its own Info.plist identity.
+// Windows listens through its built-in recognizer, driven by resources/speech-helper-windows.ps1 over stdin/stdout.
import { execFile, spawn } from "node:child_process";
import {
closeSync,
@@ -27,6 +28,7 @@ import {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SRC = path.join(__dirname, "resources", "speech-helper.swift");
const INFO = path.join(__dirname, "resources", "speech-helper-Info.plist");
+const WINDOWS_HELPER = path.join(__dirname, "resources", "speech-helper-windows.ps1");
// A signed app bundle must never be rewritten: lazy compilation would break its seal.
const BUNDLE = app.isPackaged
? path.join(process.resourcesPath, "OpenMausBot Speech.app")
@@ -77,6 +79,107 @@ function speechTarget(target) {
};
}
+/** One helper line at a time: transcripts reach the page only while this session is current; the end says why it stopped. */
+function speechLines(speechSession, sink) {
+ const transcript = createSpeechTranscript();
+ let reportedError = null;
+ let completed = false;
+ return {
+ line(raw) {
+ const line = raw.trim();
+ if (!line) return;
+ try {
+ const parsed = JSON.parse(line);
+ if (typeof parsed.error === "string") reportedError = parsed.error;
+ if (parsed.partial === false && typeof parsed.text === "string") completed = true;
+ // A stopped or replaced helper can flush one last chunk: never into the session that replaced it.
+ if (child === speechSession) sink.transcript(transcript(parsed));
+ } catch {
+ }
+ },
+ end(code) {
+ if (reportedError) {
+ sink.end({ code: 1, reason: reportedError });
+ } else if (completed && code === 0) {
+ sink.end({ code: 0, reason: "completed" });
+ } else {
+ sink.end({ code: 1, reason: "helper-exited" });
+ }
+ },
+ };
+}
+
+const windowsPowerShell = () =>
+ path.win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
+
+// The script is read from the app (inside the asar archive when packaged) and run from a session folder PowerShell can open.
+function startWindowsSpeech(sink, endpointMs) {
+ let sessionDir;
+ let script;
+ try {
+ sessionDir = mkdtempSync(path.join(app.getPath("temp"), "openmausbot-speech-"));
+ script = path.join(sessionDir, "speech-helper.ps1");
+ writeFileSync(script, readFileSync(WINDOWS_HELPER));
+ } catch {
+ if (sessionDir) rmSync(sessionDir, { recursive: true, force: true });
+ sink.end({ code: 1, reason: "helper-start-failed" });
+ return;
+ }
+ const speechSession = { proc: null, owner: sink.owner, target: sink };
+ child = speechSession;
+ const lines = speechLines(speechSession, sink);
+ const forgetWindow = sink.whenGone(() => stopSpeech(sink.owner));
+ let cleaned = false;
+ const cleanup = () => {
+ if (cleaned) return;
+ cleaned = true;
+ forgetWindow();
+ // Windows can still hold the script open for a moment (a virus scan): a folder left in temp must not stop the end.
+ try {
+ rmSync(sessionDir, { recursive: true, force: true });
+ } catch {}
+ };
+ speechSession.cleanup = cleanup;
+ const ended = (end) => {
+ cleanup();
+ if (child !== speechSession) return;
+ child = null;
+ end();
+ };
+ let proc;
+ try {
+ // stdin is the helper's lifeline too: when this app is gone the pipe closes and the helper exits.
+ proc = spawn(
+ windowsPowerShell(),
+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", script, "-EndpointMs", String(endpointMs)],
+ { stdio: ["pipe", "pipe", "ignore"], windowsHide: true },
+ );
+ } catch {
+ ended(() => sink.end({ code: 1, reason: "helper-start-failed" }));
+ return;
+ }
+ speechSession.proc = proc;
+ speechSession.stop = () => proc.kill();
+ speechSession.finish = () => proc.stdin.write("finish\n");
+ proc.stdin.on("error", () => {});
+ let buf = "";
+ proc.stdout.setEncoding("utf8");
+ proc.stdout.on("data", (chunk) => {
+ buf += chunk;
+ let nl;
+ while ((nl = buf.indexOf("\n")) !== -1) {
+ lines.line(buf.slice(0, nl));
+ buf = buf.slice(nl + 1);
+ }
+ });
+ proc.on("close", (code) => {
+ lines.line(buf);
+ buf = "";
+ ended(() => lines.end(code));
+ });
+ proc.on("error", () => ended(() => sink.end({ code: 1, reason: "helper-start-failed" })));
+}
+
export function speechBusy() {
return child !== null;
}
@@ -86,7 +189,7 @@ export function startSpeech(target, options = {}) {
stopSpeech();
running?.target.replaced();
const sink = speechTarget(target);
- if (process.platform !== "darwin") {
+ if (process.platform !== "darwin" && process.platform !== "win32") {
sink.end({ code: 2, reason: "unsupported-platform" });
return;
}
@@ -94,6 +197,10 @@ export function startSpeech(target, options = {}) {
const endpointMs = Number.isFinite(requested) && requested > 0
? Math.min(5_000, Math.max(250, Math.round(requested)))
: 0;
+ if (process.platform === "win32") {
+ startWindowsSpeech(sink, endpointMs);
+ return;
+ }
const args = endpointMs ? ["--endpoint-ms", String(endpointMs)] : [];
const release = [...new Set(Array.isArray(options?.finishOnRelease) ? options.finishOnRelease : [])]
.filter((name) => RELEASE_MODIFIERS.includes(name));
@@ -118,16 +225,17 @@ export function startSpeech(target, options = {}) {
let lifeline;
const speechSession = {
- proc: null, outputPath, errorPath, stopPath, finishPath, sessionDir,
+ proc: null, outputPath, errorPath, sessionDir,
+ // The Mac helper watches these marker files.
+ stop: () => writeFileSync(stopPath, "stop"),
+ finish: () => writeFileSync(finishPath, "finish"),
owner: sink.owner, target: sink,
};
child = speechSession;
const forgetWindow = sink.whenGone(() => stopSpeech(sink.owner));
let buf = "";
let offset = 0;
- let reportedError = null;
- let completed = false;
- const transcript = createSpeechTranscript();
+ const lines = speechLines(speechSession, sink);
const drain = () => {
let content;
@@ -141,17 +249,8 @@ export function startSpeech(target, options = {}) {
offset = content.length;
let nl;
while ((nl = buf.indexOf("\n")) !== -1) {
- const line = buf.slice(0, nl).trim();
+ lines.line(buf.slice(0, nl));
buf = buf.slice(nl + 1);
- if (!line) continue;
- try {
- const parsed = JSON.parse(line);
- if (typeof parsed.error === "string") reportedError = parsed.error;
- if (parsed.partial === false && typeof parsed.text === "string") completed = true;
- // A stopped or replaced helper can flush one last chunk: never into the session that replaced it.
- if (child === speechSession) sink.transcript(transcript(parsed));
- } catch {
- }
}
};
let cleaned = false;
@@ -215,13 +314,7 @@ export function startSpeech(target, options = {}) {
// stopSpeech() clears child before the stop marker, so intentional TTS muting never looks like the end of a spoken turn.
if (child !== speechSession) return;
child = null;
- if (reportedError) {
- sink.end({ code: 1, reason: reportedError });
- } else if (completed && code === 0) {
- sink.end({ code: 0, reason: "completed" });
- } else {
- sink.end({ code: 1, reason: "helper-exited" });
- }
+ lines.end(code);
});
proc.on("error", failed);
} catch {
@@ -244,13 +337,13 @@ export function stopSpeech(owner) {
return;
}
try {
- writeFileSync(speechSession.stopPath, "stop");
+ speechSession.stop();
} catch {}
}
export function finishSpeech(owner) {
if (!ownedBy(owner)) return;
try {
- writeFileSync(child.finishPath, "finish");
+ child.finish();
} catch {}
}
diff --git a/electron/speech.test.mjs b/electron/speech.test.mjs
index 973ee6d9b5..9e39e3a97d 100644
--- a/electron/speech.test.mjs
+++ b/electron/speech.test.mjs
@@ -1,5 +1,6 @@
import { EventEmitter } from "node:events";
-import { appendFileSync, existsSync } from "node:fs";
+import { appendFileSync, existsSync, readFileSync } from "node:fs";
+import path from "node:path";
import { tmpdir } from "node:os";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -7,10 +8,19 @@ const fixture = vi.hoisted(() => ({ launches: [], onLaunch: null }));
vi.mock("electron", () => ({ app: { isPackaged: true, getPath: () => tmpdir() } }));
vi.mock("node:child_process", async (importOriginal) => ({
...await importOriginal(),
- spawn: (_file, args) => {
+ spawn: (file, args, options) => {
const proc = new EventEmitter();
const arg = flag => args[args.indexOf(flag) + 1];
- fixture.launches.push({ proc, args, output: arg("-o"), stop: arg("--stop-file"), finish: arg("--finish-file") });
+ if (args.includes("-File")) {
+ // Windows: the helper talks over pipes. A copy of its script is read while it runs.
+ proc.stdout = Object.assign(new EventEmitter(), { setEncoding: () => {} });
+ proc.stdin = Object.assign(new EventEmitter(), { written: [], write(data) { this.written.push(data); return true; } });
+ proc.kill = () => { proc.killed = true; return true; };
+ const script = arg("-File");
+ fixture.launches.push({ proc, file, args, options, script, scriptText: readFileSync(script, "utf8") });
+ } else {
+ fixture.launches.push({ proc, args, output: arg("-o"), stop: arg("--stop-file"), finish: arg("--finish-file") });
+ }
fixture.onLaunch();
return proc;
},
@@ -208,3 +218,73 @@ describe.skipIf(platform === "win32")("native speech file transport", () => {
expect(fixture.launches.at(-1).args).not.toContain("--finish-on-release");
});
});
+
+describe("Windows speech helper", () => {
+ beforeEach(() => {
+ Object.defineProperty(process, "platform", { value: "win32" });
+ });
+ const say = (session, ...lines) => session.proc.stdout.emit("data", lines.map(line => `${JSON.stringify(line)}\r\n`).join(""));
+
+ it("listens through Windows' own recognizer in PowerShell, with no key, and hands the page what it hears", async () => {
+ const session = await launch();
+ expect(path.win32.basename(session.file).toLowerCase()).toBe("powershell.exe");
+ expect(session.args).toEqual(expect.arrayContaining(["-NoProfile", "-NonInteractive", "-File", session.script]));
+ expect(session.args.slice(-2)).toEqual(["-EndpointMs", "0"]);
+ expect(session.options).toMatchObject({ windowsHide: true, stdio: ["pipe", "pipe", "ignore"] });
+ expect(session.scriptText).toContain("System.Speech.Recognition.SpeechRecognitionEngine");
+ expect(speechBusy()).toBe(true);
+ say(session, { partial: true, text: "hello" });
+ session.proc.stdout.emit("data", `${JSON.stringify({ partial: true, text: "hello there" }).slice(0, 9)}`);
+ session.proc.stdout.emit("data", `${JSON.stringify({ partial: true, text: "hello there" }).slice(9)}\r\n`);
+ say(session, { partial: false, text: "hello there" });
+ session.proc.emit("close", 0);
+ expect(session.events).toEqual([
+ { channel: "speech:transcript", body: { partial: true, text: "hello" } },
+ { channel: "speech:transcript", body: { partial: true, text: "hello there" } },
+ { channel: "speech:transcript", body: { partial: false, text: "hello there" } },
+ { channel: "speech:end", body: { code: 0, reason: "completed" } },
+ ]);
+ expect(existsSync(session.script)).toBe(false);
+ expect(speechBusy()).toBe(false);
+ });
+
+ it("asks the helper to end a call's turn after the quiet the call chose", async () => {
+ await start({ transcript: () => {}, end: () => {}, replaced: () => {} }, { endpointMs: 900, finishOnRelease: ["control"] });
+ const session = fixture.launches.at(-1);
+ expect(session.args.slice(-2)).toEqual(["-EndpointMs", "900"]);
+ expect(session.args).not.toContain("--finish-on-release");
+ });
+
+ it("finishes through the helper's input, and a stop ends the helper without a late result", async () => {
+ const session = await launch();
+ finishSpeech(session.win);
+ expect(session.proc.stdin.written).toEqual(["finish\n"]);
+ expect(session.proc.killed).toBeUndefined();
+ stopSpeech(session.win);
+ expect(session.proc.killed).toBe(true);
+ expect(speechBusy()).toBe(false);
+ say(session, { partial: false, text: "too late" });
+ session.proc.emit("close", 1);
+ expect(session.events).toEqual([]);
+ expect(existsSync(session.script)).toBe(false);
+ });
+
+ it("passes on the helper's own reason when it cannot listen", async () => {
+ const session = await launch();
+ say(session, { error: "speech-language-missing" });
+ session.proc.emit("close", 1);
+ expect(session.events).toEqual([
+ { channel: "speech:transcript", body: { error: "speech-language-missing" } },
+ { channel: "speech:end", body: { code: 1, reason: "speech-language-missing" } },
+ ]);
+ });
+
+ it("ends with a start failure when PowerShell cannot run", async () => {
+ const session = await launch();
+ session.proc.emit("error", new Error("spawn ENOENT"));
+ session.proc.emit("close", -4058);
+ expect(session.events).toEqual([{ channel: "speech:end", body: { code: 1, reason: "helper-start-failed" } }]);
+ expect(speechBusy()).toBe(false);
+ });
+});
+
diff --git a/electron/talk-main.mjs b/electron/talk-main.mjs
index e03e574b40..f806f1f46a 100644
--- a/electron/talk-main.mjs
+++ b/electron/talk-main.mjs
@@ -12,24 +12,26 @@ export { isTalkPanel } from "./talk-panel.mjs";
* is ready. `speech`: speech.mjs's start/stop/finish/busy. `packaged`: asks go to `localRequest`, this computer's own
* server; in development to `devUrl`, whose Vite /api proxy reaches `pnpm dev:server`.
*/
-export function installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech, speech, packaged, devUrl, nativeImage, iconPath, openLink, reveal, log, fetch = globalThis.fetch, t = nativeText.englishText.t }) {
+export function installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech, windowsSpeech = false, speech, packaged, devUrl, nativeImage, iconPath, openLink, reveal, log, fetch = globalThis.fetch, t = nativeText.englishText.t }) {
const callPresence = createCallPresence();
+ // The page's microphone listens through the Mac's or Windows' own speech helper; the talk shortcut stays Mac only.
+ const nativeSpeech = appleSpeech || windowsSpeech;
let shortcut = null, session = null, panel = null, theme = null;
ipcMain.handle("speech:start", localOnly("speech:start", (event, options) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (!win) return;
- if (!appleSpeech) {
+ if (!nativeSpeech) {
win.webContents.send("speech:end", { code: 2, reason: "unsupported-platform" });
return;
}
speech.start(win, options);
}));
ipcMain.handle("speech:stop", localOnly("speech:stop", (event) => {
- if (appleSpeech) speech.stop(BrowserWindow.fromWebContents(event.sender));
+ if (nativeSpeech) speech.stop(BrowserWindow.fromWebContents(event.sender));
}));
ipcMain.handle("speech:finish", localOnly("speech:finish", (event) => {
- if (appleSpeech) speech.finish(BrowserWindow.fromWebContents(event.sender));
+ if (nativeSpeech) speech.finish(BrowserWindow.fromWebContents(event.sender));
}));
ipcMain.handle("talk-shortcut:state", localOnly("talk-shortcut:state", () => shortcut?.state() ?? TALK_SHORTCUT_UNAVAILABLE));
ipcMain.handle("talk-shortcut:set", localOnly("talk-shortcut:set", (_event, change) => shortcut?.set({
diff --git a/electron/talk-main.node-test.mjs b/electron/talk-main.node-test.mjs
index f2cf4a63cb..3ecd1fb904 100644
--- a/electron/talk-main.node-test.mjs
+++ b/electron/talk-main.node-test.mjs
@@ -17,7 +17,7 @@ const json = body => Promise.resolve(new Response(JSON.stringify(body), { status
const names = windows => windows.map(win => win?.name ?? null);
const englishLabels = { labels: TALK_LABELS, dismiss: "Dismiss", release: "Let go to send" };
-function harness({ packaged = true, appleSpeech = true, remote = false, register, serve = () => undefined } = {}) {
+function harness({ packaged = true, appleSpeech = true, windowsSpeech = false, remote = false, register, serve = () => undefined } = {}) {
const h = { handlers: new Map(), guards: new Map(), started: [], stopped: [], finished: [], requests: [], links: [], reveals: 0, log: [],
registered: new Map(), windows: [], busy: false, fail: {}, away: false, starting: false };
const owners = new Map();
@@ -49,7 +49,7 @@ function harness({ packaged = true, appleSpeech = true, remote = false, register
const guard = kind => (channel, handler) => { h.guards.set(channel, kind); return handler; };
h.talk = installTalk({
ipcMain: { handle: (channel, handler) => h.handlers.set(channel, handler) },
- localOnly: guard("localOnly"), localOrHome: guard("localOrHome"), BrowserWindow: FakeBrowserWindow, appleSpeech,
+ localOnly: guard("localOnly"), localOrHome: guard("localOrHome"), BrowserWindow: FakeBrowserWindow, appleSpeech, windowsSpeech,
speech: {
start: (target, options) => { h.started.push([target, options]); },
stop: failing("stop", owner => { h.stopped.push(owner); }),
@@ -86,7 +86,7 @@ test("every list of the app's windows leaves the talk box out", () => {
});
test("main hands the talk wiring its speech sinks, this computer's own server and window, and closes it first on quit", () => {
- assert.match(main, /const talk = installTalk\(\{ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions\.appleSpeech,\s*speech: \{ start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy \},/);
+ assert.match(main, /const talk = installTalk\(\{ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions\.appleSpeech,\s*windowsSpeech: nativeActions\.windowsSpeech,\s*speech: \{ start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy \},/);
assert.match(main, /packaged: app\.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog, t: nativeT \}\);/);
assert.match(main, /talk\.start\(\{ globalShortcut, screen, prefs: desktopPrefs, remote: \(\) => Boolean\(desktopRemoteAccess\), away: \(\) => homeWindow\.current\(\)\.kind !== "computer", starting: \(\) => !serverReady, localRequest: localServerRequest, dataDir: \(\) => runningDataDir \}\);/);
assert.match(main, /app\.on\("before-quit", \(e\) => \{\s*talk\.close\(\);/);
@@ -135,10 +135,18 @@ test("a page's speech stop and finish name that page's own window, so they touch
elsewhere.handle("speech:finish", { sender: win.webContents });
assert.deepEqual(win.webContents.sent, [["speech:end", { code: 2, reason: "unsupported-platform" }]]);
assert.deepEqual([elsewhere.started, elsewhere.stopped, elsewhere.finished], [[], [], []]);
+
+ const windows = harness({ appleSpeech: false, windowsSpeech: true });
+ const typing = windows.page("page");
+ windows.handle("speech:start", { sender: typing.webContents });
+ windows.handle("speech:finish", { sender: typing.webContents });
+ windows.handle("speech:stop", { sender: typing.webContents });
+ assert.deepEqual(typing.webContents.sent, []);
+ assert.deepEqual([windows.started.length, names(windows.stopped), names(windows.finished)], [1, ["page"], ["page"]]);
});
test("the shortcut is offered only with Apple speech, on a desktop that is not a remote client of another computer", () => {
- for (const options of [{ appleSpeech: false }, { remote: true }]) {
+ for (const options of [{ appleSpeech: false }, { appleSpeech: false, windowsSpeech: true }, { remote: true }]) {
const h = harness(options);
h.start();
assert.equal(h.handle("talk-shortcut:state", {}).available, false);
diff --git a/src/lib/call-mode.test.ts b/src/lib/call-mode.test.ts
index f898997241..6a5bc8627b 100644
--- a/src/lib/call-mode.test.ts
+++ b/src/lib/call-mode.test.ts
@@ -36,6 +36,14 @@ describe("call mode", () => {
expect(callModeHint("turns", { config: chosen })).toBe(t("call.mode.turnsHint"));
});
+ it("says listening stays on a Windows computer unless a saved Fish Audio key does the hearing", () => {
+ const dictation = { available: true, engine: "windows-speech", onDevice: true } as const;
+ cacheDesktopCapabilities({ ...initialDesktopCapabilities(), dictation });
+ expect(callModeHint("turns", { config: null })).toBe(t("call.mode.turnsHint"));
+ const savedFish = { savedKeys: { fishAudioKey: { configured: true } } } as unknown as ConfigStatus;
+ expect(callModeHint("turns", { config: savedFish })).toBe(t("call.mode.turnsHintFish"));
+ });
+
it("says the OpenAI key stays on the Cloud when the chat is on the person's Cloud", () => {
const live = callModeHint("live", { cloudHome: true });
expect(live).toContain("A Live call sends your voice to OpenAI, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. The OpenAI key stays in the Cloud.");
diff --git a/src/lib/call-mode.ts b/src/lib/call-mode.ts
index 522f024136..94b7125522 100644
--- a/src/lib/call-mode.ts
+++ b/src/lib/call-mode.ts
@@ -4,7 +4,7 @@ import type { LiveProvider, LiveSettings } from "../../shared/wire";
import type { ConfigStatus } from "@/state/store";
import { desktopCapabilitiesNow } from "./desktop";
import { t } from "./i18n";
-import { scribeChosen } from "./speech";
+import { pageRecords, scribeChosen } from "./speech";
export type CallMode = "turns" | "live";
export const CALL_MODE_KEY = "openmausbot.callMode.v1";
@@ -52,9 +52,9 @@ export function liveKeyFormKey(live: Partial<Pick<LiveSettings, "provider" | "az
export function callModeHint(mode: CallMode, where: { cloudHome?: boolean; config?: ConfigStatus | null } = {}): string {
if (mode === "live") return `${t("call.mode.liveHint")} ${liveDisclosure(where)}`;
- const { dictation } = desktopCapabilitiesNow();
- if (dictation.available && scribeChosen(where.config)) return t("call.mode.turnsHintEleven");
- return t(dictation.engine === "fish-audio" ? "call.mode.turnsHintFish" : "call.mode.turnsHint");
+ const capabilities = desktopCapabilitiesNow();
+ if (capabilities.dictation.available && scribeChosen(where.config)) return t("call.mode.turnsHintEleven");
+ return t(pageRecords(capabilities, where.config) ? "call.mode.turnsHintFish" : "call.mode.turnsHint");
}
export function effectiveCallMode(stored: CallMode, { turnsHere, canLive }: { turnsHere: boolean; canLive: boolean }): CallMode {
diff --git a/src/lib/desktop.test.ts b/src/lib/desktop.test.ts
index 2b07a47ca0..4833c3280d 100644
--- a/src/lib/desktop.test.ts
+++ b/src/lib/desktop.test.ts
@@ -74,7 +74,7 @@ describe("the bridge that resets a switch's approval to Ask", () => {
describe("initial desktop capabilities", () => {
it.each([
["darwin", { available: true, engine: "apple-speech", onDevice: true }],
- ["win32", { available: true, engine: "fish-audio", onDevice: false }],
+ ["win32", { available: true, engine: "windows-speech", onDevice: true }],
["linux", { available: true, engine: "fish-audio", onDevice: false }],
["freebsd", { available: false, engine: "none", onDevice: false, reasonCode: "unsupported-platform" }],
])("report dictation on %s", async (platform, dictation) => {
diff --git a/src/lib/desktop.ts b/src/lib/desktop.ts
index f8541083dc..9932d29a9f 100644
--- a/src/lib/desktop.ts
+++ b/src/lib/desktop.ts
@@ -33,11 +33,12 @@ export function initialDesktopCapabilities(): DesktopCapabilities {
const platform = typeof window === "undefined" ? undefined : window.ogb?.platform;
if (!platform) return browserCapabilities;
const isMac = platform === "darwin";
- const fishListening = platform === "win32" || platform === "linux";
+ const isWindows = platform === "win32";
+ const fishListening = platform === "linux";
const dictation: DesktopCapabilities["dictation"] = {
- available: isMac || fishListening,
- engine: isMac ? "apple-speech" : fishListening ? "fish-audio" : "none",
- onDevice: isMac,
+ available: isMac || isWindows || fishListening,
+ engine: isMac ? "apple-speech" : isWindows ? "windows-speech" : fishListening ? "fish-audio" : "none",
+ onDevice: isMac || isWindows,
};
if (!dictation.available) dictation.reasonCode = "unsupported-platform";
return {
diff --git a/src/lib/speech.test.ts b/src/lib/speech.test.ts
index 88441ca5b7..42157f49d8 100644
--- a/src/lib/speech.test.ts
+++ b/src/lib/speech.test.ts
@@ -9,6 +9,7 @@ const withDictation = (dictation: DesktopCapabilities["dictation"]): DesktopCapa
({ ...initialDesktopCapabilities(), dictation });
const FISH = { available: true, engine: "fish-audio", onDevice: false } as const;
const APPLE = { available: true, engine: "apple-speech", onDevice: true } as const;
+const WINDOWS = { available: true, engine: "windows-speech", onDevice: true } as const;
const savedFish = { savedKeys: { fishAudioKey: { configured: true } } } as unknown as ConfigStatus;
afterEach(() => {
@@ -36,6 +37,31 @@ describe("speechBridge", () => {
});
});
+describe("Windows dictation", () => {
+ it("listens on the computer through the desktop app's helper when no key is saved", () => {
+ const ogb = { speechStart: vi.fn() };
+ vi.stubGlobal("window", { ogb });
+ cacheDesktopCapabilities(withDictation(WINDOWS));
+ expect(missingListenKey(withDictation(WINDOWS), null)).toBeNull();
+ expect(listensHere(withDictation(WINDOWS), null)).toBe(true);
+ expect(speechBridge(null)).toBe(ogb);
+ expect(recordsClips(speechBridge(null))).toBe(false);
+ });
+
+ it("keeps hearing through a saved Fish Audio key, as before", () => {
+ vi.stubGlobal("window", { ogb: { speechStart: vi.fn() } });
+ cacheDesktopCapabilities(withDictation(WINDOWS));
+ expect(listensHere(withDictation(WINDOWS), savedFish)).toBe(true);
+ expect(speechBridge(savedFish)).toBe(fishSpeech);
+ });
+
+ it("still asks for the DeepSeek key while DeepSeek is the voice", () => {
+ const deepseekVoice = { tts: { provider: "deepseek" } } as unknown as ConfigStatus;
+ expect(missingListenKey(withDictation(WINDOWS), deepseekVoice)).toBe("deepseek");
+ expect(listensHere(withDictation(WINDOWS), deepseekVoice)).toBe(false);
+ });
+});
+
describe("DeepSeek listening", () => {
const deepseek = { tts: { provider: "deepseek" }, savedKeys: { fishAudioKey: { configured: true } } } as unknown as ConfigStatus;
const deepseekSaved = { ...deepseek, deepseek: { configured: true } } as unknown as ConfigStatus;
diff --git a/src/lib/speech.ts b/src/lib/speech.ts
index 042bbf0ddd..b3dc97f175 100644
--- a/src/lib/speech.ts
+++ b/src/lib/speech.ts
@@ -26,8 +26,17 @@ export function ownElevenLabsKey(config: ConfigStatus | null | undefined): boole
export const scribeChosen = (config: ConfigStatus | null | undefined) =>
config?.tts?.hearWith === "elevenlabs" && ownElevenLabsKey(config);
+/** Windows hears for free on the computer, until the person saves a key the server can hear with: then that key, as
+ * before Windows had its own helper. */
+const windowsKeyHears = (capabilities: DesktopCapabilities, config: ConfigStatus | null | undefined) =>
+ capabilities.dictation.engine === "windows-speech" && fishListeningReady(config);
+
+/** The page records and the server hears, rather than the desktop app's own helper. */
+export const pageRecords = (capabilities: DesktopCapabilities, config: ConfigStatus | null | undefined) =>
+ capabilities.dictation.engine === "fish-audio" || windowsKeyHears(capabilities, config);
+
function serverHears(capabilities: DesktopCapabilities, config: ConfigStatus | null | undefined): boolean {
- return capabilities.dictation.engine === "fish-audio"
+ return pageRecords(capabilities, config)
|| (capabilities.dictation.available && (deepseekHears(config) || scribeChosen(config)));
}
@@ -37,7 +46,7 @@ export function speechBridge(config: ConfigStatus | null | undefined): SpeechBri
const capabilities = desktopCapabilitiesNow();
if (capabilities.dictation.available && scribeChosen(config)) return fishSpeech;
if (capabilities.dictation.available && deepseekHears(config)) return deepseekSpeech;
- return capabilities.dictation.engine === "fish-audio" ? fishSpeech : globalThis.window?.ogb;
+ return pageRecords(capabilities, config) ? fishSpeech : globalThis.window?.ogb;
}
/** The page's recorder hears a clip only at its end, so stopping the mic must finish it. */
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 2bcf3b3df2..1e2c6923fc 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -46,7 +46,7 @@ const __APP_VERSION__: string;
};
dictation: {
available: boolean;
- engine: "apple-speech" | "fish-audio" | "none";
+ engine: "apple-speech" | "windows-speech" | "fish-audio" | "none";
onDevice: boolean;
reasonCode?: string;
};