Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Listen through Fish Audio where the Mac helper is absent
aivsomkar6fc18476b879
diff --git a/src/components/CallView.tsx b/src/components/CallView.tsxindex 3242f38c58..e85d941e42 100644--- a/src/components/CallView.tsx+++ b/src/components/CallView.tsx@@ -26,6 +26,7 @@ import { callStarted } from "@/lib/product-events";import { useDesktopCapabilities } from "./DesktopCapabilities";import { callCapabilityHelp, type CallCapabilityHelp } from "@/lib/call-capability";import { onCallStartRequest } from "@/lib/call-start-request";+import { speechBridge } from "@/lib/speech";import { VoiceSetupDialog } from "./VoiceSetupDialog";import { openBotSettings } from "./bot-panel/panel-link";import { MENU_SHEET } from "./menu-recipe";@@ -101,7 +102,7 @@ export function CallTargetButton({const active = onCall || onLiveCall;const remoteClient = globalThis.window?.ogb?.remoteClient?.active === true;const capabilityHelp = capabilitiesReady- ? callCapabilityHelp(capabilities, Boolean(window.ogb?.speechStart))+ ? callCapabilityHelp(capabilities, Boolean(speechBridge()?.speechStart)): null;const supported = capabilitiesReady && !capabilityHelp;const localVoice = localSystemVoiceActive();@@ -512,7 +513,7 @@ function Call({ bot }: { bot: Bot }) {}, []);const hush = useCallback(() => {- void window.ogb?.speechStop();+ void speechBridge()?.speechStop();}, []);const listen = useCallback(() => {@@ -520,7 +521,7 @@ function Call({ bot }: { bot: Bot }) {move("listening");setHeard("");setNote(null);- void window.ogb?.speechStart({ endpointMs: CALL_ENDPOINT_MS }).catch(() => {+ void speechBridge()?.speechStart({ endpointMs: CALL_ENDPOINT_MS }).catch(() => {if (alive.current && currentCall() === bot.id) {setNote("The microphone couldn't start. Check Microphone and Speech Recognition access.");}@@ -560,7 +561,7 @@ function Call({ bot }: { bot: Bot }) {}, [bot.id]);useEffect(() => {- const bridge = window.ogb;+ const bridge = speechBridge();if (!bridge) return;const offTranscript = bridge.onSpeechTranscript((line) => {if (!alive.current || currentCall() !== bot.id || phaseRef.current !== "listening") return;@@ -633,7 +634,7 @@ function Call({ bot }: { bot: Bot }) {move("sending");dispatch({ type: "send", botId: bot.id, text: said, threadId: bot.threadId });});- const offEnd = bridge.onSpeechEnd(({ code, reason }) => {+ const offEnd = bridge.onSpeechEnd(({ code, reason, message }) => {if (!alive.current || currentCall() !== bot.id) return;if (code === 2) {setNote("Calls need macOS dictation, which isn't available here yet.");@@ -641,13 +642,14 @@ function Call({ bot }: { bot: Bot }) {}if (code === 1) {setNote(- reason === "helper-build-failed"+ message ??+ (reason === "helper-build-failed"? "The dictation helper couldn't be built. Install Apple's Command Line Tools and try again.": reason === "dictation-disabled"? "Turn on Dictation in System Settings → Keyboard, then try again.": reason === "speech-not-authorized"? "Allow Speech Recognition in System Settings → Privacy & Security, then try again."- : "Dictation couldn't start. Try again.",+ : "Dictation couldn't start. Try again."),);return;}@@ -658,7 +660,7 @@ function Call({ bot }: { bot: Bot }) {return () => {offTranscript();offEnd();- void window.ogb?.speechStop();+ void speechBridge()?.speechStop();};// eslint-disable-next-line react-hooks/exhaustive-deps}, [bot.id, bot.threadId, dispatch, hush, listen, move, sayThenListen]);diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 03b87f85df..3e00314ab6 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -71,7 +71,6 @@ import { ApprovalChip, ComposerPlusMenu, GoalToggle, TeachTaskButton } from "./Cimport { PhonePlus } from "./PhonePlus";import { useThreadApproval } from "./thread-approval";import { useStackedField, useTallPill } from "./composer-wrap";-import { useDesktopCapabilities } from "./DesktopCapabilities";import { ComposerReplyStrip } from "./ReplyQuote";import { escapeCancelsReply } from "@/lib/replies";import { useThreadRefs } from "./ThreadRefs";@@ -127,7 +126,6 @@ export function Composer({const locked = setupLocked || Boolean(bot?.awaitingThreadSnapshot);const { state, dispatch } = useStore();const { threads, currentBotId } = useThreadRefs();- const { capabilities } = useDesktopCapabilities();const advanced = useAdvancedMode();// On a phone the composer is a dock: a round + (attach and every other tool), then one pill with the field, the mic and the voice button.const singleRow = useMediaQuery(PHONE_LAYOUT);@@ -221,9 +219,7 @@ export function Composer({},[text, editText, editAttachments],);- const { recording, speechError, toggle: toggleMic, stop: stopDictation } = useComposerDictation({- draftId, text, onText: editText, available: capabilities.dictation.available,- });+ const { recording, ready: micReady, speechError, toggle: toggleMic, stop: stopDictation } = useComposerDictation({ draftId, text, onText: editText });const [caret, setCaret] = useState(0);const shellRef = useRef<HTMLDivElement>(null);const tall = useTallPill(shellRef, simpleDock);@@ -963,7 +959,7 @@ export function Composer({<Square size={simpleDock ? 10 : 14} className="fill-current" /></button>)}- {!locked && !busy && capabilities.dictation.available && (+ {!locked && !busy && micReady && (<buttononClick={toggleMic}aria-label={recording ? t("composer.dictation.stop") : t("composer.dictation.start")}diff --git a/src/components/ComposerPlusMenu.tsx b/src/components/ComposerPlusMenu.tsxindex 0f6b88a74b..06afbe282e 100644--- a/src/components/ComposerPlusMenu.tsx+++ b/src/components/ComposerPlusMenu.tsx@@ -11,6 +11,7 @@ import {import { useAdvancedMode } from "@/lib/interface-mode";import { CALL_MODES, effectiveCallMode, useCallMode } from "@/lib/call-mode";import { callCapabilityHelp } from "@/lib/call-capability";+import { speechBridge } from "@/lib/speech";import { requestCallStart } from "@/lib/call-start-request";import { useOnCall } from "@/lib/call";import { isLiveCallRunning, useLiveMedia } from "@/lib/live-call-media";@@ -186,7 +187,7 @@ export function ComposerPlusMenu({ onAttach, goal, teach, approval, callBotId, econst media = useLiveMedia();const turnsHere = !ready || capabilities.dictation.available;const callMode = effectiveCallMode(storedMode, { turnsHere, canLive: true });- const turnsHelp = turnsHere ? null : callCapabilityHelp(capabilities, Boolean(window.ogb?.speechStart));+ const turnsHelp = turnsHere ? null : callCapabilityHelp(capabilities, Boolean(speechBridge()?.speechStart));const { state } = useStore();// As the call button, which hides while Live is the mode and its line is held on another device.const lineHeldElsewhere = callMode === "live" && liveLineHeldElsewhere(media, state.liveCall);diff --git a/src/components/GroupCallView.tsx b/src/components/GroupCallView.tsxindex de30496846..f112b6554b 100644--- a/src/components/GroupCallView.tsx+++ b/src/components/GroupCallView.tsx@@ -15,6 +15,7 @@ import { cn } from "@/lib/cn";import { BotAvatar } from "./Avatar";import { CallTargetButton, type CallButtonPlacement } from "./CallView";import { useAdvancedMode } from "@/lib/interface-mode";+import { speechBridge } from "@/lib/speech";import { useDesktopCapabilities } from "./DesktopCapabilities";import { isRoutineApproval, isSkillApproval, pendingApprovals, spokenApprovalPrompt } from "./PendingApproval";@@ -121,7 +122,7 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {}, []);const hush = useCallback(() => {- void window.ogb?.speechStop();+ void speechBridge()?.speechStop();}, []);const listen = useCallback(() => {@@ -130,7 +131,7 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {setSpeakingMemberId(null);setHeard("");setNote(null);- void window.ogb?.speechStart({ endpointMs: CALL_ENDPOINT_MS }).catch(() => {+ void speechBridge()?.speechStart({ endpointMs: CALL_ENDPOINT_MS }).catch(() => {if (alive.current && currentCall() === group.id) {setNote("The microphone couldn't start. Check Microphone and Speech Recognition access.");}@@ -213,7 +214,7 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {}, [group.id]);useEffect(() => {- const bridge = window.ogb;+ const bridge = speechBridge();if (!bridge) return;const offTranscript = bridge.onSpeechTranscript((line) => {if (!alive.current || currentCall() !== group.id || phaseRef.current !== "listening") return;@@ -310,7 +311,7 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {dispatch({ type: "sendGroup", groupId: group.id, text: routed.text, threadId: group.threadId });scheduleListen(false, 600);});- const offEnd = bridge.onSpeechEnd(({ code, reason }) => {+ const offEnd = bridge.onSpeechEnd(({ code, reason, message }) => {if (!alive.current || currentCall() !== group.id) return;if (code === 2) {setNote("Calls need macOS dictation, which isn't available here yet.");@@ -318,13 +319,14 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {}if (code === 1) {setNote(- reason === "helper-build-failed"+ message ??+ (reason === "helper-build-failed"? "The dictation helper couldn't be built. Install Apple's Command Line Tools and try again.": reason === "dictation-disabled"? "Turn on Dictation in System Settings → Keyboard, then try again.": reason === "speech-not-authorized"? "Allow Speech Recognition in System Settings → Privacy & Security, then try again."- : "Dictation couldn't start. Try again.",+ : "Dictation couldn't start. Try again."),);return;}@@ -335,7 +337,7 @@ function GroupCall({ group, members }: { group: Group; members: Bot[] }) {return () => {offTranscript();offEnd();- void window.ogb?.speechStop();+ void speechBridge()?.speechStop();};// eslint-disable-next-line react-hooks/exhaustive-deps}, [dispatch, enqueueSpeech, group.id, group.threadId, hush, listen, move, scheduleListen]);diff --git a/src/components/bot-panel/SettingsPage.tsx b/src/components/bot-panel/SettingsPage.tsxindex 4744917ee9..816810ebaa 100644--- a/src/components/bot-panel/SettingsPage.tsx+++ b/src/components/bot-panel/SettingsPage.tsx@@ -5,6 +5,7 @@ import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { CALL_MODES, effectiveCallMode, setCallMode, useCallMode, type CallMode } from "@/lib/call-mode";import { callCapabilityHelp } from "@/lib/call-capability";+import { speechBridge } from "@/lib/speech";import { firstSentence } from "@/lib/soul";import { currentTaskBot, useStore, type Bot } from "@/state/store";import type { ApprovalMode } from "../../../shared/approval-mode";@@ -68,7 +69,7 @@ export function SettingsPage({ bot, derived, onOpen, editingInstructions = false// As the call button: where this device cannot listen in turns, a call is always Live.const turnsHere = !ready || capabilities.dictation.available;const callMode = effectiveCallMode(storedCallMode, { turnsHere, canLive: true });- const turnsHelp = turnsHere ? null : callCapabilityHelp(capabilities, Boolean(window.ogb?.speechStart));+ const turnsHelp = turnsHere ? null : callCapabilityHelp(capabilities, Boolean(speechBridge()?.speechStart));const callOptions: SegmentOption<CallMode>[] = CALL_MODES.map((entry) => ({value: entry.id,label: t(entry.label),diff --git a/src/lib/call.ts b/src/lib/call.tsindex b58bd36db8..4ba61eedad 100644--- a/src/lib/call.ts+++ b/src/lib/call.ts@@ -1,6 +1,7 @@// Read by the SSE fold too: auto-speak stands down for the bot on a call, or the two deadlock over the speaker.import { useSyncExternalStore } from "react";+import { speechBridge } from "./speech";import { speaker } from "./tts";let current: string | null = null;@@ -18,7 +19,7 @@ export function startCall(targetId: string) {if (current === targetId) return;// Silence both halves before ownership changes: the old overlay may not unmount until React's next render.speaker.stop();- void window.ogb?.speechStop?.();+ void speechBridge()?.speechStop?.();current = targetId;notify();}@@ -29,7 +30,7 @@ export function endCall(targetId?: string): boolean {if (current === null) return false;current = null;speaker.stop();- void window.ogb?.speechStop?.();+ void speechBridge()?.speechStop?.();notify();return true;}diff --git a/src/lib/fish-speech.test.ts b/src/lib/fish-speech.test.tsnew file mode 100644index 0000000000..2c8a952c15--- /dev/null+++ b/src/lib/fish-speech.test.ts@@ -0,0 +1,264 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const sent = vi.hoisted(() => ({ api: vi.fn() }));+vi.mock("@/state/api", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/state/api")>()), api: sent.api }));++import { ApiError } from "@/state/api";+import { t } from "./i18n";+import { createClip, createEndpointer, encodeWav, fishSpeech, rms } from "./fish-speech";++const FRAME_MS = 64;+const loud = () => new Float32Array(1024).fill(0.2);+const quiet = () => new Float32Array(1024);+const heardFor = (feed: (level: number) => string, level: number, frames: number) => {+ let last = "";+ for (let i = 0; i < frames; i += 1) last = feed(level);+ return last;+};++describe("endpointer", () => {+ it("hears speech only after a few loud frames in a row", () => {+ const feed = createEndpointer(850);+ expect(feed(0.2)).toBe("waiting");+ expect(feed(0)).toBe("waiting");+ expect(heardFor(feed, 0.2, 2)).toBe("waiting");+ expect(feed(0.2)).toBe("speaking");+ });++ it("ends a call turn after the endpoint of quiet that follows speech", () => {+ const feed = createEndpointer(850);+ heardFor(feed, 0.2, 5);+ expect(heardFor(feed, 0, Math.ceil(850 / FRAME_MS) - 1)).toBe("speaking");+ expect(feed(0)).toBe("done");+ });++ it("never ends on quiet alone before speech, and stops a call turn at 60 s", () => {+ const feed = createEndpointer(850);+ expect(heardFor(feed, 0, Math.floor(60_000 / FRAME_MS) - 1)).toBe("waiting");+ expect(heardFor(feed, 0, 2)).toBe("done");+ });++ it("keeps a manual capture going through quiet and stops it at 5 minutes", () => {+ const feed = createEndpointer(undefined);+ heardFor(feed, 0.2, 5);+ expect(heardFor(feed, 0, Math.floor(10_000 / FRAME_MS))).toBe("speaking");+ expect(heardFor(feed, 0, Math.ceil(300_000 / FRAME_MS))).toBe("done");+ });+});++describe("clip", () => {+ const fill = (clip: ReturnType<typeof createClip>, feed: ReturnType<typeof createEndpointer>, levels: number[]) => {+ for (const level of levels) clip.push(level ? loud() : quiet(), level, feed(level));+ };++ it("is empty when nothing was said", () => {+ const clip = createClip();+ fill(clip, createEndpointer(850), Array(40).fill(0));+ expect(clip.spoke).toBe(false);+ expect(clip.frames()).toEqual([]);+ });++ it("keeps about 400 ms before speech and a short tail after it", () => {+ const clip = createClip();+ fill(clip, createEndpointer(850), [...Array(60).fill(0), ...Array(10).fill(0.2), ...Array(14).fill(0)]);+ expect(clip.spoke).toBe(true);+ const levels = clip.frames().map(rms);+ const first = levels.findIndex((level) => level > 0);+ const last = levels.findLastIndex((level) => level > 0);+ expect(first).toBeGreaterThanOrEqual(Math.ceil(400 / FRAME_MS));+ expect(first).toBeLessThan(Math.ceil(600 / FRAME_MS));+ expect(levels.length - 1 - last).toBe(Math.ceil(400 / FRAME_MS));+ });+});++describe("encodeWav", () => {+ it("writes 16-bit mono PCM at the given rate, clamped", () => {+ const wav = encodeWav([new Float32Array([0, 1, -1, 2])], 16_000);+ const view = new DataView(wav.buffer);+ const text = (at: number) => String.fromCharCode(...wav.slice(at, at + 4));+ expect([text(0), text(8), text(36)]).toEqual(["RIFF", "WAVE", "data"]);+ expect(view.getUint16(22, true)).toBe(1);+ expect(view.getUint32(24, true)).toBe(16_000);+ expect(view.getUint16(34, true)).toBe(16);+ expect(view.getUint32(40, true)).toBe(8);+ expect([0, 1, 2, 3].map((i) => view.getInt16(44 + i * 2, true))).toEqual([0, 32767, -32768, 32767]);+ });+});++describe("Fish Audio listener", () => {+ let process: ((frame: Float32Array) => void) | undefined;+ let tracksStopped: number;+ let contextsClosed: number;+ let getUserMedia: ReturnType<typeof vi.fn>;+ const lines: unknown[] = [];+ const ends: unknown[] = [];+ const offs: Array<() => void> = [];++ class FakeProcessor {+ onaudioprocess: ((event: { inputBuffer: { getChannelData: () => Float32Array } }) => void) | null = null;+ connect() {}+ disconnect() {}+ }+ class FakeContext {+ destination = {};+ constructor(readonly options: { sampleRate: number }) {}+ createMediaStreamSource() { return { connect() {}, disconnect() {} }; }+ createScriptProcessor() {+ const processor = new FakeProcessor();+ process = (frame) => processor.onaudioprocess?.({ inputBuffer: { getChannelData: () => frame } });+ return processor;+ }+ async resume() {}+ async close() { contextsClosed += 1; }+ }+ const stream = () => ({ getTracks: () => [{ stop: () => { tracksStopped += 1; } }] });++ beforeEach(() => {+ process = undefined;+ tracksStopped = 0;+ contextsClosed = 0;+ lines.length = 0;+ ends.length = 0;+ sent.api.mockReset();+ sent.api.mockResolvedValue({ text: "hello bot" });+ getUserMedia = vi.fn(async () => stream());+ vi.stubGlobal("navigator", { mediaDevices: { getUserMedia } });+ vi.stubGlobal("AudioContext", FakeContext);+ offs.push(fishSpeech.onSpeechTranscript((line) => lines.push(line)), fishSpeech.onSpeechEnd((info) => ends.push(info)));+ });++ afterEach(async () => {+ await fishSpeech.speechStop();+ offs.splice(0).forEach((off) => off());+ vi.unstubAllGlobals();+ });++ const feed = (frame: () => Float32Array, count: number) => { for (let i = 0; i < count; i += 1) process!(frame()); };+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++ it("hears a call turn: one 'hearing you' line, the clip uploaded as WAV, then the text and a completed end", async () => {+ await fishSpeech.speechStart({ endpointMs: 850 });+ expect(getUserMedia).toHaveBeenCalledWith({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } });+ feed(quiet, 5);+ feed(loud, 10);+ expect(lines).toEqual([{ partial: true, text: "…" }]);+ feed(quiet, 14);+ await settle();+ const [path, init] = sent.api.mock.calls[0]!;+ expect(path).toBe("/api/tts/transcribe");+ expect(init.method).toBe("POST");+ expect(init.headers).toEqual({ "content-type": "audio/wav" });+ expect(new TextDecoder().decode(init.body.slice(0, 4))).toBe("RIFF");+ expect(lines).toEqual([{ partial: true, text: "…" }, { partial: false, text: "hello bot" }]);+ expect(ends).toEqual([{ code: 0, reason: "completed" }]);+ expect(tracksStopped).toBe(1);+ expect(contextsClosed).toBe(1);+ });++ it("ends a turn that heard no speech without sending anything", async () => {+ await fishSpeech.speechStart({ endpointMs: 850 });+ feed(quiet, 20);+ await fishSpeech.speechFinish();+ expect(sent.api).not.toHaveBeenCalled();+ expect(ends).toEqual([{ code: 0, reason: "completed" }]);+ expect(tracksStopped).toBe(1);+ });++ it("ends a turn with no text without a final line, so a call listens once", async () => {+ sent.api.mockResolvedValue({ text: " " });+ await fishSpeech.speechStart({ endpointMs: 850 });+ feed(loud, 5);+ await fishSpeech.speechFinish();+ await settle();+ expect(lines.filter((line) => (line as { partial: boolean }).partial === false)).toEqual([]);+ expect(ends).toEqual([{ code: 0, reason: "completed" }]);+ });++ it("captures a manual clip until it is finished, with no partial line", async () => {+ await fishSpeech.speechStart();+ feed(loud, 5);+ feed(quiet, 40);+ expect(sent.api).not.toHaveBeenCalled();+ await fishSpeech.speechFinish();+ await settle();+ expect(sent.api).toHaveBeenCalledOnce();+ expect(lines).toEqual([{ partial: false, text: "hello bot" }]);+ expect(ends).toEqual([{ code: 0, reason: "completed" }]);+ });++ it("emits nothing when stopped while listening", async () => {+ await fishSpeech.speechStart({ endpointMs: 850 });+ feed(loud, 5);+ lines.length = 0;+ await fishSpeech.speechStop();+ await settle();+ expect(sent.api).not.toHaveBeenCalled();+ expect({ lines, ends }).toEqual({ lines: [], ends: [] });+ expect(tracksStopped).toBe(1);+ });++ it("aborts the upload and emits nothing when stopped while it is in flight", async () => {+ let signal: AbortSignal | undefined;+ sent.api.mockImplementation((_path, init) => new Promise((_resolve, reject) => {+ signal = init.signal;+ signal!.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));+ }));+ await fishSpeech.speechStart();+ feed(loud, 5);+ await fishSpeech.speechFinish();+ await fishSpeech.speechStop();+ await settle();+ expect(signal!.aborted).toBe(true);+ expect({ lines, ends }).toEqual({ lines: [], ends: [] });+ });++ it("never speaks for a session that was replaced during the upload", async () => {+ let release!: (value: { text: string }) => void;+ sent.api.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }));+ await fishSpeech.speechStart();+ feed(loud, 5);+ await fishSpeech.speechFinish();+ await fishSpeech.speechStart({ endpointMs: 850 });+ release({ text: "stale" });+ await settle();+ expect({ lines, ends }).toEqual({ lines: [], ends: [] });+ });++ it("releases a microphone that was granted after the session was stopped", async () => {+ let grant!: (value: ReturnType<typeof stream>) => void;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => { grant = resolve; }));+ const started = fishSpeech.speechStart({ endpointMs: 850 });+ await fishSpeech.speechStop();+ grant(stream());+ await started;+ expect(tracksStopped).toBe(1);+ expect(contextsClosed).toBe(1);+ expect({ lines, ends }).toEqual({ lines: [], ends: [] });+ });++ it("ends a finish that arrives before the microphone opened", async () => {+ getUserMedia.mockImplementationOnce(() => new Promise(() => {}));+ void fishSpeech.speechStart();+ await fishSpeech.speechFinish();+ expect(ends).toEqual([{ code: 0, reason: "completed" }]);+ });++ it.each([+ ["NotAllowedError", { code: 1, reason: "microphone-blocked", message: t("call.live.micBlocked") }],+ ["NotFoundError", { code: 1, reason: "microphone-missing", message: t("call.live.micMissing") }],+ ["AbortError", { code: 1, reason: "microphone-failed" }],+ ])("ends a %s microphone failure with a reason", async (name, end) => {+ getUserMedia.mockRejectedValueOnce(Object.assign(new Error(name), { name }));+ await fishSpeech.speechStart({ endpointMs: 850 });+ expect(ends).toEqual([end]);+ });++ it("reports the server's message when the upload fails", async () => {+ sent.api.mockRejectedValue(new ApiError("Fish Audio rejected that API key.", 502));+ await fishSpeech.speechStart();+ feed(loud, 5);+ await fishSpeech.speechFinish();+ await settle();+ expect(ends).toEqual([{ code: 1, reason: "transcribe-failed", message: "Fish Audio rejected that API key." }]);+ });+});diff --git a/src/lib/fish-speech.ts b/src/lib/fish-speech.tsnew file mode 100644index 0000000000..06980b26e1--- /dev/null+++ b/src/lib/fish-speech.ts@@ -0,0 +1,233 @@+// Take turns and dictation where the Mac's speech helper does not exist: the page records the mic, trims silence, and+// the harness sends each clip to Fish Audio. It speaks the same five-method contract as window.ogb's speech bridge.+import { api, ApiError } from "@/state/api";+import { t } from "./i18n";++export type SpeechBridge = Required<+ Pick<NonNullable<Window["ogb"]>, "speechStart" | "speechStop" | "speechFinish" | "onSpeechTranscript" | "onSpeechEnd">+>;+type Line = Parameters<Parameters<SpeechBridge["onSpeechTranscript"]>[0]>[0];+type End = Parameters<Parameters<SpeechBridge["onSpeechEnd"]>[0]>[0];++export const SAMPLE_RATE = 16_000;+const FRAME_SAMPLES = 1024;+const FRAME_MS = (FRAME_SAMPLES / SAMPLE_RATE) * 1000;+const SPEECH_RMS = 0.015;+const SPEECH_FRAMES = 3;+const LEAD_MS = 400;+const TAIL_MS = 400;+const CALL_TURN_MAX_MS = 60_000;+const MANUAL_MAX_MS = 5 * 60_000;+const UPLOAD_TIMEOUT_MS = 70_000;++export function rms(frame: Float32Array): number {+ let sum = 0;+ for (const sample of frame) sum += sample * sample;+ return Math.sqrt(sum / (frame.length || 1));+}++export type Heard = "waiting" | "speaking" | "done";++/** `endpointMs` set: quiet that long after speech ends the turn. Unset: only the cap ends it. */+export function createEndpointer(endpointMs: number | undefined, frameMs = FRAME_MS) {+ const cap = endpointMs === undefined ? MANUAL_MAX_MS : CALL_TURN_MAX_MS;+ let loud = 0;+ let quiet = 0;+ let elapsed = 0;+ let spoke = false;+ return (level: number): Heard => {+ elapsed += frameMs;+ if (level > SPEECH_RMS) {+ loud += 1;+ quiet = 0;+ if (loud >= SPEECH_FRAMES) spoke = true;+ } else {+ loud = 0;+ if (spoke) quiet += frameMs;+ }+ if (elapsed >= cap || (endpointMs !== undefined && spoke && quiet >= endpointMs)) return "done";+ return spoke ? "speaking" : "waiting";+ };+}++/** Keeps the last LEAD_MS before speech starts and, once it does, everything up to a short tail after the last loud frame. */+export function createClip(frameMs = FRAME_MS) {+ const lead = Math.ceil(LEAD_MS / frameMs) + SPEECH_FRAMES;+ const tail = Math.ceil(TAIL_MS / frameMs);+ let frames: Float32Array[] = [];+ let spoke = false;+ let lastLoud = -1;+ return {+ push(frame: Float32Array, level: number, heard: Heard) {+ frames.push(frame);+ if (!spoke && heard === "waiting" && frames.length > lead) frames = frames.slice(-lead);+ if (heard !== "waiting") spoke = true;+ if (level > SPEECH_RMS) lastLoud = frames.length - 1;+ },+ get spoke() {+ return spoke;+ },+ frames: () => (spoke ? frames.slice(0, lastLoud + 1 + tail) : []),+ };+}++export function encodeWav(frames: Float32Array[], rate = SAMPLE_RATE): Uint8Array<ArrayBuffer> {+ const samples = frames.reduce((n, frame) => n + frame.length, 0);+ const out = new DataView(new ArrayBuffer(44 + samples * 2));+ const text = (at: number, value: string) => [...value].forEach((c, i) => out.setUint8(at + i, c.charCodeAt(0)));+ text(0, "RIFF");+ out.setUint32(4, 36 + samples * 2, true);+ text(8, "WAVEfmt ");+ out.setUint32(16, 16, true);+ out.setUint16(20, 1, true);+ out.setUint16(22, 1, true);+ out.setUint32(24, rate, true);+ out.setUint32(28, rate * 2, true);+ out.setUint16(32, 2, true);+ out.setUint16(34, 16, true);+ text(36, "data");+ out.setUint32(40, samples * 2, true);+ let at = 44;+ for (const frame of frames) {+ for (const sample of frame) {+ const clamped = Math.max(-1, Math.min(1, sample));+ out.setInt16(at, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);+ at += 2;+ }+ }+ return new Uint8Array(out.buffer);+}++type Mic = { stream: MediaStream; context: AudioContext; source: MediaStreamAudioSourceNode; processor: ScriptProcessorNode };+type Session =+ | { phase: "idle" }+ | { phase: "opening" }+ | { phase: "listening"; mic: Mic; clip: ReturnType<typeof createClip> }+ | { phase: "transcribing"; abort: AbortController };++const transcriptListeners = new Set<(line: Line) => void>();+const endListeners = new Set<(info: End) => void>();+// Every start, stop and finish bumps this, so a late mic grant or upload can never speak for the next session.+let generation = 0;+let session: Session = { phase: "idle" };++const emitTranscript = (line: Line) => Array.from(transcriptListeners).forEach((fn) => fn(line));+const emitEnd = (info: End) => Array.from(endListeners).forEach((fn) => fn(info));+const completed = (): End => ({ code: 0, reason: "completed" });++function release(mic: Mic) {+ mic.processor.onaudioprocess = null;+ mic.source.disconnect();+ mic.processor.disconnect();+ for (const track of mic.stream.getTracks()) track.stop();+ void mic.context.close().catch(() => {});+}++function teardown() {+ generation += 1;+ if (session.phase === "listening") release(session.mic);+ if (session.phase === "transcribing") session.abort.abort();+ session = { phase: "idle" };+}++function micFailure(error: unknown): End {+ const name = (error as { name?: string } | null)?.name;+ if (name === "NotAllowedError") return { code: 1, reason: "microphone-blocked", message: t("call.live.micBlocked") };+ if (name === "NotFoundError") return { code: 1, reason: "microphone-missing", message: t("call.live.micMissing") };+ return { code: 1, reason: "microphone-failed" };+}++async function upload(gen: number, frames: Float32Array[], abort: AbortController) {+ try {+ const { text } = await api<{ text?: string }>("/api/tts/transcribe", {+ method: "POST",+ body: encodeWav(frames),+ headers: { "content-type": "audio/wav" },+ signal: abort.signal,+ timeoutMs: UPLOAD_TIMEOUT_MS,+ });+ if (gen !== generation) return;+ session = { phase: "idle" };+ // An empty final would make a call listen twice: once for it, once for the end.+ if (text?.trim()) emitTranscript({ partial: false, text });+ emitEnd(completed());+ } catch (error) {+ if (gen !== generation) return;+ session = { phase: "idle" };+ emitEnd({ code: 1, reason: "transcribe-failed", ...(error instanceof ApiError ? { message: error.message } : {}) });+ }+}++function finishCapture(gen: number) {+ if (gen !== generation || session.phase !== "listening") return;+ const { mic, clip } = session;+ release(mic);+ if (!clip.spoke) {+ session = { phase: "idle" };+ return emitEnd(completed());+ }+ const abort = new AbortController();+ session = { phase: "transcribing", abort };+ void upload(gen, clip.frames(), abort);+}++export const fishSpeech: SpeechBridge = {+ async speechStart(options) {+ teardown();+ const gen = generation;+ session = { phase: "opening" };+ let stream: MediaStream | undefined;+ let mic: Mic;+ try {+ stream = await navigator.mediaDevices.getUserMedia({+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },+ });+ const context = new AudioContext({ sampleRate: SAMPLE_RATE });+ mic = { stream, context, source: context.createMediaStreamSource(stream), processor: context.createScriptProcessor(FRAME_SAMPLES, 1, 1) };+ } catch (error) {+ stream?.getTracks().forEach((track) => track.stop());+ if (gen !== generation) return;+ session = { phase: "idle" };+ return emitEnd(micFailure(error));+ }+ if (gen !== generation) return release(mic);+ const endpointed = options?.endpointMs !== undefined;+ const hear = createEndpointer(options?.endpointMs);+ const clip = createClip();+ let announced = false;+ mic.processor.onaudioprocess = (event) => {+ if (gen !== generation) return;+ const frame = new Float32Array(event.inputBuffer.getChannelData(0));+ const level = rms(frame);+ const heard = hear(level);+ clip.push(frame, level, heard);+ if (endpointed && !announced && heard !== "waiting") {+ announced = true;+ emitTranscript({ partial: true, text: "…" });+ }+ if (heard === "done") finishCapture(gen);+ };+ mic.source.connect(mic.processor);+ mic.processor.connect(mic.context.destination);+ void mic.context.resume().catch(() => {});+ session = { phase: "listening", mic, clip };+ },+ async speechStop() {+ teardown();+ },+ async speechFinish() {+ if (session.phase === "listening") return finishCapture(generation);+ if (session.phase === "opening") {+ teardown();+ emitEnd(completed());+ }+ },+ onSpeechTranscript(cb) {+ transcriptListeners.add(cb);+ return () => transcriptListeners.delete(cb);+ },+ onSpeechEnd(cb) {+ endListeners.add(cb);+ return () => endListeners.delete(cb);+ },+};diff --git a/src/lib/push-to-talk.ts b/src/lib/push-to-talk.tsindex cf46b1e944..e56e89869c 100644--- a/src/lib/push-to-talk.ts+++ b/src/lib/push-to-talk.ts@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from "react";import { currentCall } from "./call";+import { speechBridge } from "./speech";type ModifierEvent = Pick<KeyboardEvent, "altKey" | "ctrlKey" | "code" | "repeat">;@@ -28,7 +29,7 @@ export function usePushToTalk(targetId: string, enabled: boolean, onError: () =>}, [enabled]);useEffect(() => {- const bridge = window.ogb;+ const bridge = speechBridge();if (!bridge?.speechFinish) return;const finish = () => {diff --git a/src/lib/speech.test.ts b/src/lib/speech.test.tsnew file mode 100644index 0000000000..3794332e3c--- /dev/null+++ b/src/lib/speech.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import type { ConfigStatus } from "@/state/store";+import { cacheDesktopCapabilities, initialDesktopCapabilities } from "./desktop";+import { fishSpeech } from "./fish-speech";+import { fishListeningReady, listensHere, speechBridge } from "./speech";++const withDictation = (dictation: DesktopCapabilities["dictation"]): DesktopCapabilities =>+ ({ ...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 savedFish = { savedKeys: { fishAudioKey: { configured: true } } } as unknown as ConfigStatus;++afterEach(() => {+ vi.unstubAllGlobals();+ cacheDesktopCapabilities(initialDesktopCapabilities());+});++describe("speechBridge", () => {+ it("is the page's own Fish Audio listener where the engine is fish-audio", () => {+ vi.stubGlobal("window", { ogb: { speechStart: vi.fn() } });+ cacheDesktopCapabilities(withDictation(FISH));+ expect(speechBridge()).toBe(fishSpeech);+ });++ it("is the desktop app's helper everywhere else", () => {+ const ogb = { speechStart: vi.fn() };+ vi.stubGlobal("window", { ogb });+ cacheDesktopCapabilities(withDictation(APPLE));+ expect(speechBridge()).toBe(ogb);+ });++ it("is nothing in a browser", () => {+ vi.stubGlobal("window", {});+ expect(speechBridge()).toBeUndefined();+ });+});++describe("listening readiness", () => {+ it("needs a saved Fish Audio key to listen through Fish Audio", () => {+ expect(fishListeningReady(savedFish)).toBe(true);+ expect(fishListeningReady(null)).toBe(false);+ expect(listensHere(withDictation(FISH), savedFish)).toBe(true);+ expect(listensHere(withDictation(FISH), null)).toBe(false);+ });++ it("needs no key for the Mac's own recognizer, and nothing where dictation is unavailable", () => {+ expect(listensHere(withDictation(APPLE), null)).toBe(true);+ expect(listensHere(withDictation({ available: false, engine: "none", onDevice: false }), savedFish)).toBe(false);+ });+});diff --git a/src/lib/speech.ts b/src/lib/speech.tsnew file mode 100644index 0000000000..9850b427dd--- /dev/null+++ b/src/lib/speech.ts@@ -0,0 +1,18 @@+import { keyEntry, savedState } from "@/components/keys/key-catalog";+import type { ConfigStatus } from "@/state/store";+import { desktopCapabilitiesNow } from "./desktop";+import { fishSpeech, type SpeechBridge } from "./fish-speech";++/** The speech bridge this computer listens through: the page's own Fish Audio listener, or the desktop app's helper. */+export function speechBridge(): SpeechBridge | Window["ogb"] {+ return desktopCapabilitiesNow().dictation.engine === "fish-audio" ? fishSpeech : globalThis.window?.ogb;+}++export function fishListeningReady(config: ConfigStatus | null | undefined): boolean {+ return savedState(keyEntry("fishAudio"), config).configured;+}++/** Whether speech can be heard here: the engine is there and, through Fish Audio, so is a saved key. */+export function listensHere(capabilities: DesktopCapabilities, config: ConfigStatus | null | undefined): boolean {+ return capabilities.dictation.available && (capabilities.dictation.engine !== "fish-audio" || fishListeningReady(config));+}diff --git a/src/lib/use-composer-dictation.fish.test.ts b/src/lib/use-composer-dictation.fish.test.tsnew file mode 100644index 0000000000..8a16e57bf1--- /dev/null+++ b/src/lib/use-composer-dictation.fish.test.ts@@ -0,0 +1,94 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { t } from "./i18n";++const fixture = vi.hoisted(() => ({+ config: { savedKeys: { fishAudioKey: { configured: true } } } as unknown,+}));+const fish = vi.hoisted(() => {+ const listeners = { line: undefined as undefined | ((line: unknown) => void), end: undefined as undefined | ((info: unknown) => void) };+ return {+ listeners,+ speechStart: vi.fn(async () => {}),+ speechStop: vi.fn(async () => {}),+ speechFinish: vi.fn(async () => {}),+ onSpeechTranscript: (cb: (line: unknown) => void) => { listeners.line = cb; return () => {}; },+ onSpeechEnd: (cb: (info: unknown) => void) => { listeners.end = cb; return () => {}; },+ };+});+vi.mock("./fish-speech", () => ({ fishSpeech: fish }));+vi.mock("@/state/store", () => ({ useStore: () => ({ state: { config: fixture.config } }) }));+vi.mock("@/components/DesktopCapabilities", async () => {+ const { initialDesktopCapabilities } = await import("./desktop");+ const capabilities = { ...initialDesktopCapabilities(), dictation: { available: true, engine: "fish-audio", onDevice: false } };+ return { useDesktopCapabilities: () => ({ capabilities, ready: true }) };+});++import { cacheDesktopCapabilities, initialDesktopCapabilities } from "./desktop";+import { useComposerDictation } from "./use-composer-dictation";++type Dictation = ReturnType<typeof useComposerDictation>;++describe("composer dictation through Fish Audio", () => {+ let root: Root;+ let container: HTMLDivElement;+ let dictation: Dictation;+ let typed: string[];++ beforeEach(() => {+ cacheDesktopCapabilities({ ...initialDesktopCapabilities(), dictation: { available: true, engine: "fish-audio", onDevice: false } });+ fixture.config = { savedKeys: { fishAudioKey: { configured: true } } };+ typed = [];+ vi.clearAllMocks();+ const onText = (text: string) => typed.push(text);+ const Probe = () => { dictation = useComposerDictation({ draftId: "d", text: "", onText }); return null; };+ container = document.createElement("div");+ root = createRoot(container);+ flushSync(() => root.render(createElement(Probe)));+ });++ afterEach(() => {+ flushSync(() => root.unmount());+ cacheDesktopCapabilities(initialDesktopCapabilities());+ });++ const toggle = () => flushSync(() => dictation.toggle());++ it("finishes and transcribes when the mic is clicked off, keeping the session until its end arrives", () => {+ toggle();+ expect(fish.speechStart).toHaveBeenCalledOnce();+ toggle();+ expect(fish.speechFinish).toHaveBeenCalledOnce();+ expect(fish.speechStop).not.toHaveBeenCalled();+ expect(dictation.recording).toBe(true);+ flushSync(() => fish.listeners.line!({ partial: false, text: "hello" }));+ flushSync(() => fish.listeners.end!({ code: 0, reason: "completed" }));+ expect(typed).toEqual(["hello"]);+ expect(dictation.recording).toBe(false);+ expect(fish.speechStop).not.toHaveBeenCalled();+ });++ it("discards the clip when dictation is stopped some other way", () => {+ toggle();+ flushSync(() => dictation.stop());+ expect(fish.speechStop).toHaveBeenCalledOnce();+ expect(fish.speechFinish).not.toHaveBeenCalled();+ expect(dictation.recording).toBe(false);+ });++ it("shows the message a failed end carries", () => {+ toggle();+ flushSync(() => fish.listeners.end!({ code: 1, reason: "microphone-blocked", message: t("call.live.micBlocked") }));+ expect(dictation.speechError).toBe(t("call.live.micBlocked"));+ });++ it("is not ready without a saved Fish Audio key", () => {+ expect(dictation.ready).toBe(true);+ fixture.config = null;+ flushSync(() => root.render(createElement(() => { dictation = useComposerDictation({ draftId: "d", text: "", onText: () => {} }); return null; })));+ expect(dictation.ready).toBe(false);+ });+});diff --git a/src/lib/use-composer-dictation.ts b/src/lib/use-composer-dictation.tsindex 28fc86d5f0..3601b698e5 100644--- a/src/lib/use-composer-dictation.ts+++ b/src/lib/use-composer-dictation.ts@@ -1,19 +1,26 @@import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";+import { useDesktopCapabilities } from "@/components/DesktopCapabilities";import { withOpenSettings } from "@/components/OpenSystemSettings";+import { useStore } from "@/state/store";import { t } from "./i18n";+import { fishSpeech } from "./fish-speech";+import { listensHere, speechBridge } from "./speech";-export function useComposerDictation({ draftId, text, onText, available }: {+export function useComposerDictation({ draftId, text, onText }: {draftId: string;text: string;onText: (text: string) => void;- available: boolean;}) {+ const { capabilities } = useDesktopCapabilities();+ const ready = listensHere(capabilities, useStore().state.config);const [recording, setRecording] = useState(false);const [speechError, setSpeechError] = useState<ReactNode>(null);const draft = useRef({ id: draftId, text });draft.current = { id: draftId, text };const session = useRef({ draftId: "", base: "" });const cancel = useRef<(() => void) | null>(null);+ // Fish Audio hears the clip only at its end, so stopping the mic must finish it.+ const finish = useRef<(() => void) | null>(null);const stop = useCallback(() => {cancel.current?.();setRecording(false);@@ -21,7 +28,7 @@ export function useComposerDictation({ draftId, text, onText, available }: {useEffect(() => {if (!recording) return;- const bridge = window.ogb;+ const bridge = speechBridge();if (!bridge || session.current.draftId !== draftId) {setRecording(false);return;@@ -37,6 +44,7 @@ export function useComposerDictation({ draftId, text, onText, available }: {setRecording(false);};cancel.current = cancelSession;+ finish.current = bridge === fishSpeech ? () => void fishSpeech.speechFinish() : null;const offTranscript = bridge.onSpeechTranscript((line) => {if (!active || draft.current.id !== draftId) return;if (draft.current.text !== lastText) {@@ -48,7 +56,7 @@ export function useComposerDictation({ draftId, text, onText, available }: {draft.current.text = lastText;onText(lastText);});- const offEnd = bridge.onSpeechEnd(({ code, reason }) => {+ const offEnd = bridge.onSpeechEnd(({ code, reason, message }) => {if (!active || draft.current.id !== draftId) return;active = false;setRecording(false);@@ -56,8 +64,8 @@ export function useComposerDictation({ draftId, text, onText, available }: {setSpeechError(t("composer.dictation.macOnly"));} else if (code === 1) {// A refused permission comes with a way to the pane that grants it.- setSpeechError(reason === "speech-not-authorized" ? withOpenSettings(t("composer.dictation.permission"), "speech")- : t(reason === "dictation-disabled" ? "composer.dictation.disabled" : "composer.dictation.failed"));+ setSpeechError(message ?? (reason === "speech-not-authorized" ? withOpenSettings(t("composer.dictation.permission"), "speech")+ : t(reason === "dictation-disabled" ? "composer.dictation.disabled" : "composer.dictation.failed")));}});void bridge.speechStart().catch(() => {@@ -67,6 +75,7 @@ export function useComposerDictation({ draftId, text, onText, available }: {});return () => {if (cancel.current === cancelSession) cancel.current = null;+ finish.current = null;offTranscript();offEnd();if (active) {@@ -77,14 +86,15 @@ export function useComposerDictation({ draftId, text, onText, available }: {}, [recording, draftId, onText]);const toggle = () => {- if (!available || !window.ogb) {+ if (!ready || !speechBridge()) {setSpeechError(t("composer.dictation.unavailable"));} else if (recording) {- stop();+ if (finish.current) finish.current();+ else stop();} else {session.current = { draftId, base: text };setRecording(true);}};- return { recording, speechError, toggle, stop };+ return { recording, ready, speechError, toggle, stop };}diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex 40c6b4bf56..b5df1e60cc 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" | "none";+ engine: "apple-speech" | "fish-audio" | "none";onDevice: boolean;reasonCode?: string;};@@ -319,7 +319,7 @@ const __APP_VERSION__: string;onSpeechTranscript(cb: (line: { partial?: boolean; text?: string; error?: string }) => void,): () => void;- onSpeechEnd(cb: (info: { code: number | null; reason?: string }) => void): () => void;+ onSpeechEnd(cb: (info: { code: number | null; reason?: string; message?: string }) => void): () => void;/** Absolute path of a dropped File ("" when the drag carried no* file on disk). Absent in older builds of the shell. */getPathForFile?(file: File): string;