Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: capture live meeting audio through the call-host bridge
[._.]/ Adam Eivy5d6193177241
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex ec140757f6..f592ad8c59 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -100,7 +100,7 @@ grep -i "what you want to do" client/src/lib/README.md| `appIdentity.js` | `PORTOS_APP_ID` — stable id of the baseline PortOS app (mirrors `server/lib/appIdentity.js`). Dependency-free so a module reachable from a node-env server test (e.g. `components/apps/constants.js`) can identify PortOS without importing `services/apiCore.js`, which pulls in React via `ui/Toast`. `apiCore.js` re-exports it, so `import { PORTOS_APP_ID } from '../services/api'` still works. || `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. || `assessmentTuningNotice.js` | `tuningNoticeChip(entry)` — the short form of how a measured local-model assessment says its launch configuration did NOT take effect. `tuningApplied === false` covers two opposite cases and `tuningKey` separates them: a TUNED run whose knobs never reached the daemon (`tuning not applied`), versus an UNTUNED run PortOS could not put back on backend defaults (`not at defaults`) — #4759. Shared by `ModelThroughputReport.jsx`'s table cell and `LocalModelAssessments.jsx`'s result toast; the long form is the server's exclusion reason in `getAssessmentReport`. |-| `callAudioBridge.js` | Pure device/format helpers for the FaceTime call-host page (`pages/VoiceCallHost.jsx`, #5308). `missingCallHostApis(scope)` lists every required browser API this browser lacks (MediaStreamTrackProcessor/Generator, AudioWorklet, `enumerateDevices`, `setSinkId`, Web Locks) so the page names all the gaps at once instead of one per reload; `findAudioDevice(devices, label, kind)` matches a device label EXACTLY after trim+case-fold (a substring match would resolve "BlackHole 1" to the 16ch device, indistinguishable from a dead call); `describeDeviceProblem(devices, {inputLabel, outputLabel})` returns the one blocking message or `null`, and deliberately blames MICROPHONE PERMISSION rather than a missing driver when every label comes back blank — an ungranted tab enumerates unlabeled devices, and "reinstall BlackHole" would send the user to fix the wrong thing. Format side: `downmixToMono(channels)` (BlackHole 16ch carries the call on all channels; truncates to the shortest rather than reading past one), `resampleTo16k(samples, fromRate)` (linear, 48k→16k for whisper), `floatToInt16` (CLAMPED — wrapping would flip a hot sample's sign into an audible click), `rmsLevel` for the input meter, and `buildTestTone` (faded in/out so it cannot click through the call). Plus `CALL_HOST_LOCK` (the Web Lock name that stops a second tab double-answering) and `CALL_FRAME_SAMPLES`. |+| `callAudioBridge.js` | Pure device/format helpers for the call-host page (`pages/VoiceCallHost.jsx`, #5308 + #5311) — shared by its Call mode (FaceTime Audio) and its Capture system audio mode (meeting transcription). `missingCallHostApis(scope)` lists every required browser API this browser lacks (MediaStreamTrackProcessor/Generator, AudioWorklet, `enumerateDevices`, `setSinkId`, Web Locks) so the page names all the gaps at once instead of one per reload; `findAudioDevice(devices, label, kind)` matches a device label EXACTLY after trim+case-fold (a substring match would resolve "BlackHole 1" to the 16ch device, indistinguishable from a dead call); `describeDeviceProblem(devices, {inputLabel, outputLabel})` returns the one blocking message or `null`, and deliberately blames MICROPHONE PERMISSION rather than a missing driver when every label comes back blank — an ungranted tab enumerates unlabeled devices, and "reinstall BlackHole" would send the user to fix the wrong thing; `outputLabel` is OPTIONAL — capture mode only listens, so omitting it skips the output-device check entirely rather than reporting a device named "undefined" as missing. Format side: `downmixToMono(channels)` (BlackHole 16ch carries the call on all channels; truncates to the shortest rather than reading past one), `resampleTo16k(samples, fromRate)` (linear, 48k→16k for whisper), `floatToInt16` (CLAMPED — wrapping would flip a hot sample's sign into an audible click), `rmsLevel` for the input meter, and `buildTestTone` (faded in/out so it cannot click through the call). Plus `CALL_HOST_LOCK` (the Web Lock name that stops a second tab double-answering — shared by both modes, since they read the same physical device) and `CALL_FRAME_SAMPLES`. || `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. **`openAnalysisMic({ getUserMedia })`** → `{ stream, processing }` is the ONE way a pitch-analysis surface opens a mic: it requests `ANALYSIS_AUDIO_CONSTRAINTS` (echo cancellation / noise suppression / AGC off — plain booleans, never `{ exact }`, so a browser that can't honor one still opens the mic) and reads `track.getSettings()` back so the UI can say what actually stuck. `readAppliedProcessing(stream)` reports each stage as `true` / `false` / `null` (browser didn't say — never collapse unknown into off) and `hasUnwantedProcessing(p)` gates the warning. Memo capture deliberately keeps the speech-tuned defaults; Whisper wants them. || `bareUrl.js` | `parseBareUrl(text)` — the normalized URL when a capture's entire text is a URL, else null. Client mirror of the authoritative `server/lib/bareUrl.js` (parity enforced by `server/lib/bareUrl.mirror.test.js`), so the brain capture boxes preview the exact filing decision the server will make. Use this — not the looser `utils/urlNormalize.js` `isUrl` — anywhere the answer must match the server. || `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` — single-video YouTube URL detection. Client mirror of `YOUTUBE_INGEST_URL_RE` in `server/services/youtubeIngest.js` (behavioral parity pinned by `server/lib/youtubeUrl.mirror.test.js`); deliberately excludes playlists and channels. Quick Capture uses it to swap to the ingest submit path and reveal the ingest options panel. Also `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. |diff --git a/client/src/lib/callAudioBridge.js b/client/src/lib/callAudioBridge.jsindex 1322afe10d..f109b69cd8 100644--- a/client/src/lib/callAudioBridge.js+++ b/client/src/lib/callAudioBridge.js@@ -58,6 +58,11 @@ export function findAudioDevice(devices, label, kind) {* device: a browser that has not been granted microphone access returns* unlabeled entries, and telling the user to reinstall BlackHole then would* send them to fix the wrong thing.+ *+ * `outputLabel` is optional: capture mode only listens (BlackHole 16ch in),+ * it never plays a reply back into anything, so it has no BlackHole 2ch+ * requirement. Omitting it skips the output check entirely rather than+ * reporting a device named "undefined" as missing.*/export function describeDeviceProblem(devices, { inputLabel, outputLabel } = {}) {if (!Array.isArray(devices)) return 'Could not read this Mac’s audio devices.';@@ -67,7 +72,7 @@ export function describeDeviceProblem(devices, { inputLabel, outputLabel } = {})if (!findAudioDevice(devices, inputLabel, 'audioinput')) {return `No audio input named “${inputLabel}”. Install BlackHole and set FaceTime’s output to it.`;}- if (!findAudioDevice(devices, outputLabel, 'audiooutput')) {+ if (outputLabel && !findAudioDevice(devices, outputLabel, 'audiooutput')) {return `No audio output named “${outputLabel}”. Install BlackHole and set FaceTime’s microphone to it.`;}return null;diff --git a/client/src/lib/callAudioBridge.test.js b/client/src/lib/callAudioBridge.test.jsindex 9b7cbf335a..b91a5abfc5 100644--- a/client/src/lib/callAudioBridge.test.js+++ b/client/src/lib/callAudioBridge.test.js@@ -89,6 +89,13 @@ describe('call host device selection', () => {expect(describeDeviceProblem(noOutput, { inputLabel: 'BlackHole 16ch', outputLabel: 'BlackHole 2ch' })).toMatch(/BlackHole 2ch/);expect(describeDeviceProblem(null, {})).toMatch(/Could not read/);});++ it('skips the output check entirely when no outputLabel is given', () => {+ // Meeting capture only listens — it never plays a reply back, so it has+ // no BlackHole 2ch requirement. A missing output device must not block it.+ const noOutput = devices().filter((device) => device.label !== 'BlackHole 2ch');+ expect(describeDeviceProblem(noOutput, { inputLabel: 'BlackHole 16ch' })).toBeNull();+ });});describe('call host audio format', () => {diff --git a/client/src/pages/VoiceCallHost.jsx b/client/src/pages/VoiceCallHost.jsxindex a19cdfe31b..10b46b1917 100644--- a/client/src/pages/VoiceCallHost.jsx+++ b/client/src/pages/VoiceCallHost.jsx@@ -1,20 +1,27 @@/**- * The FaceTime Audio call host.+ * The FaceTime Audio call host — and its second mode, meeting capture.*- * This page is the audio path for a call: it opens BlackHole 16ch (what- * FaceTime plays INTO), streams it to the server as 16 kHz mono PCM, and plays- * the assistant's reply back out through BlackHole 2ch (what FaceTime listens- * to as its microphone). It has to run in a real browser tab on the Mac- * because device permissions and `setSinkId` need a real browser profile.+ * Both modes share one audio bridge: a browser tab opens BlackHole 16ch+ * (what FaceTime, Zoom, or Meet plays INTO) and streams it to the server as+ * 16 kHz mono PCM. It has to run in a real browser tab on the Mac because+ * device permissions and `setSinkId` need a real browser profile.+ *+ * - **Call** plays the assistant's reply back out through BlackHole 2ch+ * (what FaceTime listens to as its microphone) — the full voice pipeline.+ * - **Capture system audio** only transcribes. It never talks back and needs+ * no BlackHole 2ch: it whisper-transcribes the meeting continuously and,+ * on stop, files the transcript into the daily journal and the Brain+ * inbox for review — no AI provider is called along the way.** Everything here fails closed and says why. A bridge that half-works drops- * the call audio silently, so a missing API, a missing device, an ungranted+ * audio silently, so a missing API, a missing device, an ungranted* permission, and a second tab each produce their own message rather than a* spinner that never resolves.*/import { useCallback, useEffect, useRef, useState } from 'react';-import { Mic, MicOff, PhoneCall, Volume2 } from 'lucide-react';+import { Mic, MicOff, PhoneCall, Radio, Volume2 } from 'lucide-react';import socket from '../services/socket';+import { useDrawerTab } from '../hooks';import {CALL_FRAME_SAMPLES,CALL_HOST_LOCK,@@ -44,11 +51,21 @@ registerProcessor('portos-call-tap', CallTapProcessor);const DEFAULT_INPUT_LABEL = 'BlackHole 16ch';const DEFAULT_OUTPUT_LABEL = 'BlackHole 2ch';+const MODES = ['call', 'capture'];export default function VoiceCallHost() {+ // Deep-linkable mode, not local state: `?mode=capture` is shareable and+ // survives a reload, same convention as a drawer's active tab.+ const [mode, setMode] = useDrawerTab('mode', 'call', MODES);+ // Read inside callbacks that only close over `[]`/`[teardown]` deps, so a+ // mode switch between mount and the next attach/detach isn't missed.+ const modeRef = useRef(mode);+ modeRef.current = mode;+const [blocked, setBlocked] = useState(null);const [attached, setAttached] = useState(false);const [callState, setCallState] = useState(null);+ const [captureState, setCaptureState] = useState(null);const [level, setLevel] = useState(0);const [notice, setNotice] = useState(null);const audio = useRef({ context: null, stream: null, node: null, source: null, outputId: null, pending: [] });@@ -67,7 +84,9 @@ export default function VoiceCallHost() {// Play one WAV into BlackHole 2ch. `setSinkId` is what makes this land in the// call instead of the room's speakers, so a failure to route is surfaced- // rather than played anyway.+ // rather than played anyway. Capture mode never receives a voice:call:tts+ // event (the server never emits one for a capture session), so this only+ // ever runs for a call.const playToCall = useCallback(async (wav) => {const element = new Audio();const blob = new Blob([wav], { type: 'audio/wav' });@@ -91,7 +110,9 @@ export default function VoiceCallHost() {}// The lock is the local half of single-attach; the server refuses a second- // host too, but the lock catches it before any device is opened.+ // host too, but the lock catches it before any device is opened. One lock+ // name for both modes — they read the same physical BlackHole device, so+ // a second tab must be refused regardless of which mode it picks.//// `locks.request` resolves only when its CALLBACK settles, and holding a// lock means never settling — so awaiting the request itself would hang@@ -112,14 +133,22 @@ export default function VoiceCallHost() {return;}+ const currentMode = modeRef.current;const devices = await navigator.mediaDevices.enumerateDevices().catch(() => null);- const problem = describeDeviceProblem(devices, { inputLabel: DEFAULT_INPUT_LABEL, outputLabel: DEFAULT_OUTPUT_LABEL });+ const problem = describeDeviceProblem(devices, {+ inputLabel: DEFAULT_INPUT_LABEL,+ // Capture only listens — it never plays a reply back, so it has no+ // BlackHole 2ch requirement.+ outputLabel: currentMode === 'call' ? DEFAULT_OUTPUT_LABEL : undefined,+ });if (problem) {setBlocked(problem);return;}const input = devices.find((device) => device.label === DEFAULT_INPUT_LABEL && device.kind === 'audioinput');- const output = devices.find((device) => device.label === DEFAULT_OUTPUT_LABEL && device.kind === 'audiooutput');+ const output = currentMode === 'call'+ ? devices.find((device) => device.label === DEFAULT_OUTPUT_LABEL && device.kind === 'audiooutput')+ : null;let stream;try {@@ -157,6 +186,8 @@ export default function VoiceCallHost() {carry.push(...resampled);// Ship fixed-size frames so the server's endpointer sees a steady// resolution regardless of the render quantum this browser chose.+ // Both modes ride the same wire event — the server routes it to+ // whichever host (call or capture) this socket currently holds.while (carry.length >= CALL_FRAME_SAMPLES) {const pcm = floatToInt16(Float32Array.from(carry.slice(0, CALL_FRAME_SAMPLES)));carry = carry.slice(CALL_FRAME_SAMPLES);@@ -165,13 +196,19 @@ export default function VoiceCallHost() {};source.connect(node);- audio.current = { context, stream, node, source, outputId: output.deviceId, pending: [] };- socket.emit('voice:call:attach');+ audio.current = { context, stream, node, source, outputId: output?.deviceId ?? null, pending: [] };+ // Two literal emits, not a computed event name — a computed+ // `socket.emit(x ? 'a' : 'b')` is invisible to the static+ // socket-event-catalog scan (`scripts/generate-socket-event-catalog.js`),+ // which greps for `socket.emit('literal')`.+ if (currentMode === 'call') socket.emit('voice:call:attach');+ else socket.emit('voice:capture:start');setBlocked(null);}, []);const stop = useCallback(() => {- socket.emit('voice:call:detach');+ if (modeRef.current === 'call') socket.emit('voice:call:detach');+ else socket.emit('voice:capture:stop');teardown();lockRelease.current?.();lockRelease.current = null;@@ -179,22 +216,44 @@ export default function VoiceCallHost() {}, [teardown]);useEffect(() => {- const onState = (snapshot) => {+ const onCallState = (snapshot) => {if (snapshot?.error === 'host-taken') {setBlocked('Another tab owns the call host.');setAttached(false);return;}+ if (snapshot?.error === 'capture-active') {+ setBlocked('Meeting capture is running on this tab — stop it before attaching a call.');+ setAttached(false);+ return;+ }setCallState(snapshot);setAttached(Boolean(snapshot?.hostAttached));};+ const onCaptureState = (snapshot) => {+ if (snapshot?.error === 'host-taken') {+ setBlocked('Another tab is already capturing a meeting.');+ setAttached(false);+ return;+ }+ if (snapshot?.error === 'call-active') {+ setBlocked('A FaceTime call is active on this tab — hang up before starting a capture.');+ setAttached(false);+ return;+ }+ setCaptureState(snapshot);+ setAttached(Boolean(snapshot?.hostAttached));+ };const onTts = ({ wav }) => { if (wav) playToCall(wav); };- socket.on('voice:call:state', onState);+ socket.on('voice:call:state', onCallState);+ socket.on('voice:capture:state', onCaptureState);socket.on('voice:call:tts', onTts);return () => {- socket.off('voice:call:state', onState);+ socket.off('voice:call:state', onCallState);+ socket.off('voice:capture:state', onCaptureState);socket.off('voice:call:tts', onTts);- socket.emit('voice:call:detach');+ if (modeRef.current === 'call') socket.emit('voice:call:detach');+ else socket.emit('voice:capture:stop');teardown();lockRelease.current?.();lockRelease.current = null;@@ -217,25 +276,60 @@ export default function VoiceCallHost() {source.start();};+ const isCall = mode === 'call';+ const statusText = attached+ ? (isCall+ ? `Attached · call ${callState?.state || 'idle'}${callState?.turns ? ` · ${callState.turns} turns` : ''}`+ : `Capturing · ${captureState?.turns || 0} utterance${captureState?.turns === 1 ? '' : 's'} transcribed`)+ : (isCall ? 'Not attached — no call audio reaches PortOS.' : 'Not capturing — nothing is being transcribed.');+return (<div className="mx-auto max-w-2xl space-y-4 p-4"><header className="space-y-1"><h1 className="flex items-center gap-2 text-xl font-semibold text-white"><PhoneCall size={20} />Call host</h1><p className="text-sm text-gray-400">- Keep this tab open on the Mac running PortOS. It carries the audio for a FaceTime Audio- call: FaceTime plays into {DEFAULT_INPUT_LABEL}, and PortOS answers through {DEFAULT_OUTPUT_LABEL}.+ Keep this tab open on the Mac running PortOS. In <strong>Call</strong> mode it carries the+ audio for a FaceTime Audio call: FaceTime plays into {DEFAULT_INPUT_LABEL}, and PortOS+ answers through {DEFAULT_OUTPUT_LABEL}. In <strong>Capture system audio</strong> mode it only+ listens to {DEFAULT_INPUT_LABEL} and transcribes — route any meeting app's output there via a+ Multi-Output Device to capture it into the daily journal and the Brain inbox.</p></header>+ <div role="tablist" aria-label="Call host mode" className="flex gap-2">+ <button+ type="button"+ role="tab"+ aria-selected={isCall}+ disabled={attached}+ onClick={() => setMode('call')}+ className={`flex min-h-[44px] items-center gap-2 rounded px-3 text-sm disabled:opacity-50 ${isCall ? 'bg-port-accent/20 text-port-accent' : 'border border-port-border text-gray-300 hover:bg-port-border/50'}`}+ >+ <PhoneCall size={16} />Call+ </button>+ <button+ type="button"+ role="tab"+ aria-selected={!isCall}+ disabled={attached}+ onClick={() => setMode('capture')}+ className={`flex min-h-[44px] items-center gap-2 rounded px-3 text-sm disabled:opacity-50 ${!isCall ? 'bg-port-accent/20 text-port-accent' : 'border border-port-border text-gray-300 hover:bg-port-border/50'}`}+ >+ <Radio size={16} />Capture system audio+ </button>+ </div>+{blocked && <p role="alert" className="rounded border border-port-error bg-port-error/10 p-3 text-sm text-port-error">{blocked}</p>}{notice && <p role="status" className="rounded border border-port-warning bg-port-warning/10 p-3 text-sm text-port-warning">{notice}</p>}<section className="space-y-3 rounded-lg border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-center gap-2">{attached- ? <button type="button" onClick={stop} className="flex min-h-[44px] items-center gap-2 rounded border border-port-border px-3 text-sm text-gray-300 hover:bg-port-border/50"><MicOff size={16} />Detach call host</button>- : <button type="button" onClick={start} className="flex min-h-[44px] items-center gap-2 rounded bg-port-accent/20 px-3 text-sm text-port-accent hover:bg-port-accent/30"><Mic size={16} />Attach call host</button>}- <button type="button" onClick={playTestTone} disabled={!attached} className="flex min-h-[44px] items-center gap-2 rounded border border-port-border px-3 text-sm text-gray-300 hover:bg-port-border/50 disabled:opacity-50"><Volume2 size={16} />Test tone</button>+ ? <button type="button" onClick={stop} className="flex min-h-[44px] items-center gap-2 rounded border border-port-border px-3 text-sm text-gray-300 hover:bg-port-border/50"><MicOff size={16} />{isCall ? 'Detach call host' : 'Stop capture'}</button>+ : <button type="button" onClick={start} className="flex min-h-[44px] items-center gap-2 rounded bg-port-accent/20 px-3 text-sm text-port-accent hover:bg-port-accent/30"><Mic size={16} />{isCall ? 'Attach call host' : 'Start capture'}</button>}+ {isCall && (+ <button type="button" onClick={playTestTone} disabled={!attached} className="flex min-h-[44px] items-center gap-2 rounded border border-port-border px-3 text-sm text-gray-300 hover:bg-port-border/50 disabled:opacity-50"><Volume2 size={16} />Test tone</button>+ )}</div><div>@@ -245,9 +339,7 @@ export default function VoiceCallHost() {</div></div>- <p role="status" className="text-xs text-gray-400">- {attached ? `Attached · call ${callState?.state || 'idle'}${callState?.turns ? ` · ${callState.turns} turns` : ''}` : 'Not attached — no call audio reaches PortOS.'}- </p>+ <p role="status" className="text-xs text-gray-400">{statusText}</p></section></div>);diff --git a/client/src/pages/VoiceCallHost.test.jsx b/client/src/pages/VoiceCallHost.test.jsxindex 0c35c78b2d..282f0cffa2 100644--- a/client/src/pages/VoiceCallHost.test.jsx+++ b/client/src/pages/VoiceCallHost.test.jsx@@ -1,5 +1,6 @@import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';vi.mock('../services/socket', () => {const handlers = new Map();@@ -41,7 +42,7 @@ afterEach(() => { vi.unstubAllGlobals(); });describe('VoiceCallHost', () => {it('says nothing reaches PortOS until the host is attached', () => {- render(<VoiceCallHost />);+ render(<VoiceCallHost />, { wrapper: MemoryRouter });expect(screen.getByText(/Not attached — no call audio reaches PortOS/)).toBeTruthy();expect(socket.emit).not.toHaveBeenCalledWith('voice:call:attach');});@@ -49,7 +50,7 @@ describe('VoiceCallHost', () => {it('names every missing browser API at once instead of one per reload', async () => {vi.stubGlobal('MediaStreamTrackProcessor', undefined);vi.stubGlobal('AudioWorkletNode', undefined);- render(<VoiceCallHost />);+ render(<VoiceCallHost />, { wrapper: MemoryRouter });await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });@@ -63,7 +64,7 @@ describe('VoiceCallHost', () => {it('refuses to open a device when another tab holds the lock', async () => {navigator.locks.request = vi.fn((_name, _options, fn) => Promise.resolve(fn(false)));- render(<VoiceCallHost />);+ render(<VoiceCallHost />, { wrapper: MemoryRouter });await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });@@ -73,7 +74,7 @@ describe('VoiceCallHost', () => {it('reports the specific missing device rather than a generic failure', async () => {navigator.mediaDevices.enumerateDevices.mockResolvedValue([devices[1]]);- render(<VoiceCallHost />);+ render(<VoiceCallHost />, { wrapper: MemoryRouter });await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });@@ -86,7 +87,7 @@ describe('VoiceCallHost', () => {// getUserMedia succeeding is as far as jsdom goes; the AudioContext work// after it belongs to the browser, so the assertion is the constraint set.navigator.mediaDevices.getUserMedia.mockRejectedValue(new Error('no audio hardware'));- render(<VoiceCallHost />);+ render(<VoiceCallHost />, { wrapper: MemoryRouter });await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });@@ -102,7 +103,7 @@ describe('VoiceCallHost', () => {});it('surfaces the server refusing a second host', async () => {- render(<VoiceCallHost />);+ render(<VoiceCallHost />, { wrapper: MemoryRouter });act(() => socket.__fire('voice:call:state', { error: 'host-taken' }));@@ -110,7 +111,7 @@ describe('VoiceCallHost', () => {});it('reflects live call state once the server reports it attached', async () => {- render(<VoiceCallHost />);+ render(<VoiceCallHost />, { wrapper: MemoryRouter });act(() => socket.__fire('voice:call:state', { hostAttached: true, state: 'listening', active: true, turns: 2 }));@@ -119,8 +120,90 @@ describe('VoiceCallHost', () => {});it('detaches on unmount so a closed tab does not leave a phantom host', () => {- const { unmount } = render(<VoiceCallHost />);+ const { unmount } = render(<VoiceCallHost />, { wrapper: MemoryRouter });unmount();expect(socket.emit).toHaveBeenCalledWith('voice:call:detach');});});++describe('VoiceCallHost — meeting capture mode', () => {+ const renderCapturing = () => render(<VoiceCallHost />, {+ wrapper: ({ children }) => <MemoryRouter initialEntries={['/?mode=capture']}>{children}</MemoryRouter>,+ });++ it('is reachable by URL, needs no output device, and emits voice:capture:start (not voice:call:attach)', async () => {+ // Only the input half of the bridge exists — capture never plays a reply+ // back, so it must not block on a missing BlackHole 2ch. jsdom has no+ // real Web Audio API, so the pieces past getUserMedia are minimally+ // stubbed here (the existing call-mode tests instead stop the flow by+ // making getUserMedia reject — that would hide the emitted event name).+ navigator.mediaDevices.enumerateDevices.mockResolvedValue([+ { label: 'BlackHole 16ch', kind: 'audioinput', deviceId: 'in-1' },+ ]);+ navigator.mediaDevices.getUserMedia.mockResolvedValue({});+ vi.stubGlobal('AudioContext', function FakeAudioContext() {+ this.sampleRate = 48000;+ this.audioWorklet = { addModule: () => Promise.resolve() };+ this.createMediaStreamSource = () => ({ connect: () => {} });+ this.close = () => {};+ });+ vi.stubGlobal('AudioWorkletNode', function FakeAudioWorkletNode() {+ this.port = {};+ this.disconnect = () => {};+ });+ renderCapturing();++ await act(async () => { fireEvent.click(screen.getByText('Start capture')); });++ expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledWith({+ audio: {+ deviceId: { exact: 'in-1' },+ echoCancellation: false,+ noiseSuppression: false,+ autoGainControl: false,+ },+ });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(socket.emit).toHaveBeenCalledWith('voice:capture:start');+ expect(socket.emit).not.toHaveBeenCalledWith('voice:call:attach');+ });++ it('still requires the input device by name', async () => {+ navigator.mediaDevices.enumerateDevices.mockResolvedValue([]);+ renderCapturing();++ await act(async () => { fireEvent.click(screen.getByText('Start capture')); });++ expect((await screen.findByRole('alert')).textContent).toMatch(/microphone access/);+ expect(navigator.mediaDevices.getUserMedia).not.toHaveBeenCalled();+ });++ it('hides the test tone control — capture never plays anything back', () => {+ renderCapturing();+ expect(screen.queryByText('Test tone')).toBeNull();+ });++ it('reflects live capture state once the server reports it attached', async () => {+ renderCapturing();++ act(() => socket.__fire('voice:capture:state', { hostAttached: true, active: true, turns: 3 }));++ expect(await screen.findByText(/Capturing · 3 utterances transcribed/)).toBeTruthy();+ expect(screen.getByText('Stop capture')).toBeTruthy();+ });++ it('surfaces the mutual-exclusion refusal when a call is active on this tab', async () => {+ renderCapturing();++ act(() => socket.__fire('voice:capture:state', { error: 'call-active' }));++ expect((await screen.findByRole('alert')).textContent).toMatch(/FaceTime call is active/);+ });++ it('stops the capture (not the call) on unmount', () => {+ const { unmount } = renderCapturing();+ unmount();+ expect(socket.emit).toHaveBeenCalledWith('voice:capture:stop');+ expect(socket.emit).not.toHaveBeenCalledWith('voice:call:detach');+ });+});diff --git a/docs/features/voice.md b/docs/features/voice.mdindex 645c49f941..df0b3be95e 100644--- a/docs/features/voice.md+++ b/docs/features/voice.md@@ -65,6 +65,34 @@ a hangup.`Caller` and `PortOS`. The call audio is never persisted, and the configuredhandle never appears in the transcript or its metadata.+### Meeting capture++The call-host page's second mode: **/voice/call-host?mode=capture** (or the+**Capture system audio** tab on the same page) turns live audio from a+Zoom/Meet/FaceTime meeting into a timestamped transcript in the daily journal+and the Brain inbox — no dialing, no reply, no LLM call.++**Setup.** Reads the same BlackHole 16ch device as the call bridge, so it+needs no separate driver — but only the input half: capture never plays+anything back, so BlackHole 2ch is not required. Route the meeting app's+output to BlackHole 16ch (a macOS Multi-Output Device lets you also hear it+through your speakers at the same time).++**Capturing.** Press **Start capture**; PortOS transcribes continuously with+the same whisper.cpp STT and energy-based endpointing (700 ms trailing+silence) the call bridge uses, but stops there — it never runs the LLM/tools+pipeline, so no AI provider is called while a meeting is being captured.+Press **Stop capture** (or close the tab) to finalize: the transcript is+appended to the daily journal under a "Meeting capture" heading with+start/stop timestamps, and filed as a Brain inbox item with auto-classify+off — exactly like a manually-typed thought with classification skipped. The+usual summarize/tag flow applies only once you ask for it from the inbox.++**Mutually exclusive with a call.** Both modes read the same BlackHole+device and the same host tab, so starting one while the other is active on+this tab is refused with a specific reason rather than fighting over the+device.+### Why Kokoro is the defaultKokoro is a 82M-parameter frontier TTS model that runs in-process via ONNX Runtime + transformers.js — **no Python, no extra binaries, cross-platform**. Quality is significantly higher than Piper (more natural prosody, expressive pacing). First synthesis after server start has a 2–3 s cold start as the model loads; warm calls are 200–500 ms per sentence on CPU.@@ -185,7 +213,9 @@ Barge-in works by aborting the shared `AbortController` tied to the current turnSocket events are documented in `server/sockets/voice.js` — including thecall-host bridge (`voice:call:attach` / `voice:call:audio` / `voice:call:detach`-inbound, `voice:call:state` / `voice:call:tts` outbound).+inbound, `voice:call:state` / `voice:call:tts` outbound) and meeting capture,+which reuses the same `voice:call:audio` PCM frames (`voice:capture:start` /+`voice:capture:stop` inbound, `voice:capture:state` outbound).## Troubleshootingdiff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex f1ec155ed4..661c31230a 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -333,7 +333,7 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },{ id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice', 'voice-settings'], keywords: ['mic', 'microphone', 'speech', 'tts', 'whisper', 'kokoro'] },{ id: 'nav.settings.facetime', path: '/settings/voice', label: 'FaceTime Audio', section: 'Settings', feature: 'facetime', aliases: ['facetime', 'facetime-audio', 'call-settings'], keywords: ['facetime', 'audio call', 'call', 'hang up', 'blackhole'] },- { id: 'nav.settings.call-host', path: '/voice/call-host', label: 'Call Host', section: 'Settings', feature: 'facetime', aliases: ['call-host', 'voice-call-host', 'facetime-call-host', 'audio-bridge'], keywords: ['facetime', 'call audio', 'blackhole', 'bridge', 'attach', 'microphone', 'speaker', 'call host'] },+ { id: 'nav.settings.call-host', path: '/voice/call-host', label: 'Call Host', section: 'Settings', feature: 'facetime', aliases: ['call-host', 'voice-call-host', 'facetime-call-host', 'audio-bridge', 'meeting-capture', 'capture-audio'], keywords: ['facetime', 'call audio', 'blackhole', 'bridge', 'attach', 'microphone', 'speaker', 'call host', 'meeting capture', 'transcribe meeting', 'record meeting'] },{ id: 'nav.ambient', path: '/ambient', label: 'Ambient', section: 'Dev Tools', aliases: ['ambient', 'ambient-mode', 'ambient mode'], keywords: ['idle', 'background', 'display', 'screensaver', 'fullscreen'] },{ id: 'nav.capabilities', path: '/capabilities', label: 'Capabilities', section: 'Dev Tools', aliases: ['capabilities', 'capability-map', 'integrations'], keywords: ['status', 'setup', 'checklist', 'connected systems', 'integrations', 'providers', 'health overview'] },diff --git a/server/lib/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.jsonindex 50568bacf3..b16242c22f 100644--- a/server/lib/socketEventCatalog.generated.json+++ b/server/lib/socketEventCatalog.generated.json@@ -1916,7 +1916,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 469+ "line": 581}]},@@ -2554,6 +2554,19 @@}]},+ {+ "event": "literal",+ "directions": [+ "client-to-server"+ ],+ "sources": [+ {+ "direction": "client-to-server",+ "source": "client/src/pages/VoiceCallHost.jsx",+ "line": 203+ }+ ]+ },{"event": "llamaServer:download","directions": [@@ -4532,12 +4545,12 @@{"direction": "client-to-server","source": "client/src/pages/VoiceCallHost.jsx",- "line": 169+ "line": 204},{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 418+ "line": 432}]},@@ -4550,12 +4563,12 @@{"direction": "client-to-server","source": "client/src/pages/VoiceCallHost.jsx",- "line": 163+ "line": 194},{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 437+ "line": 459}]},@@ -4568,17 +4581,17 @@{"direction": "client-to-server","source": "client/src/pages/VoiceCallHost.jsx",- "line": 174+ "line": 210},{"direction": "client-to-server","source": "client/src/pages/VoiceCallHost.jsx",- "line": 197+ "line": 255},{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 464+ "line": 498}]},@@ -4591,17 +4604,22 @@{"direction": "server-to-client","source": "client/src/pages/VoiceCallHost.jsx",- "line": 192+ "line": 248},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 384+ "line": 398},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 425+ "line": 440+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 447}]},@@ -4614,12 +4632,86 @@{"direction": "server-to-client","source": "client/src/pages/VoiceCallHost.jsx",- "line": 193+ "line": 250},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 401+ "line": 415+ }+ ]+ },+ {+ "event": "voice:capture:start",+ "directions": [+ "client-to-server"+ ],+ "sources": [+ {+ "direction": "client-to-server",+ "source": "client/src/pages/VoiceCallHost.jsx",+ "line": 205+ },+ {+ "direction": "client-to-server",+ "source": "server/sockets/voice.js",+ "line": 536+ }+ ]+ },+ {+ "event": "voice:capture:state",+ "directions": [+ "server-to-client"+ ],+ "sources": [+ {+ "direction": "server-to-client",+ "source": "client/src/pages/VoiceCallHost.jsx",+ "line": 249+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 512+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 540+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 545+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 550+ }+ ]+ },+ {+ "event": "voice:capture:stop",+ "directions": [+ "client-to-server"+ ],+ "sources": [+ {+ "direction": "client-to-server",+ "source": "client/src/pages/VoiceCallHost.jsx",+ "line": 211+ },+ {+ "direction": "client-to-server",+ "source": "client/src/pages/VoiceCallHost.jsx",+ "line": 256+ },+ {+ "direction": "client-to-server",+ "source": "server/sockets/voice.js",+ "line": 563}]},@@ -4637,17 +4729,17 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 244+ "line": 258},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 268+ "line": 282},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 273+ "line": 287}]},@@ -4670,7 +4762,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 261+ "line": 275}]},@@ -4688,67 +4780,82 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 152+ "line": 166},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 165+ "line": 179},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 174+ "line": 188},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 179+ "line": 193},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 183+ "line": 197},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 199+ "line": 213},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 208+ "line": 222},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 213+ "line": 227},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 217+ "line": 231},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 223+ "line": 237},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 276+ "line": 290},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 411+ "line": 425},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 433+ "line": 455+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 523+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 559+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 577}]},@@ -4766,17 +4873,17 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 153+ "line": 167},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 233+ "line": 247},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 245+ "line": 259}]},@@ -4810,12 +4917,12 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 227+ "line": 241},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 453+ "line": 478}]},@@ -4833,7 +4940,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 361+ "line": 375}]},@@ -4851,7 +4958,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 369+ "line": 383}]},@@ -4900,7 +5007,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 236+ "line": 250}]},@@ -4918,7 +5025,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 321+ "line": 335}]},@@ -4954,7 +5061,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 203+ "line": 217}]},@@ -5003,7 +5110,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 169+ "line": 183}]},@@ -5021,7 +5128,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 284+ "line": 298}]},@@ -5052,7 +5159,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 339+ "line": 353}]},@@ -5076,9 +5183,9 @@}],"stats": {- "events": 258,- "clientToServer": 59,- "serverToClient": 208,+ "events": 262,+ "clientToServer": 62,+ "serverToClient": 209,"bidirectional": 9,"sourceFiles": 104}diff --git a/server/services/voice/callSession.js b/server/services/voice/callSession.jsindex 3516cfb77b..75e26e2e41 100644--- a/server/services/voice/callSession.js+++ b/server/services/voice/callSession.js@@ -224,7 +224,10 @@ export async function endCall(reason = 'ended') {if (transcript.length) {try {- await deps.appendJournal(getToday(), `FaceTime Audio call\n${renderTranscript(transcript)}`, { source: 'voice' });+ // getToday() is async (it reads the configured timezone) — unawaited it+ // resolved to a pending Promise, which appendJournal's isIsoDate() guard+ // always rejects, so the call transcript was silently never written.+ await deps.appendJournal(await getToday(), `FaceTime Audio call\n${renderTranscript(transcript)}`, { source: 'voice' });} catch (error) {console.error(`❌ voice call: journal append failed: ${error.message}`);}diff --git a/server/services/voice/captureSession.js b/server/services/voice/captureSession.jsnew file mode 100644index 0000000000..dce13286c9--- /dev/null+++ b/server/services/voice/captureSession.js@@ -0,0 +1,163 @@+/**+ * A live meeting-capture session — the second mode on the call-host page.+ *+ * Reuses the same BlackHole capture path and STT endpointing as the FaceTime+ * call session, but never runs the LLM/tools pipeline: it only accumulates a+ * timestamped transcript while the session is active. On stop it appends the+ * transcript to the daily journal and files it as a Brain inbox item for+ * manual review — the usual summarize/tag flow applies only once the user+ * asks for it. **No AI provider is called by this module**, per the+ * cold-bootstrap policy in AGENTS.md: a captured meeting sits in the inbox+ * exactly like a manually-typed thought with auto-classify off, not like one+ * that gets silently classified in the background.+ *+ * One capture, one host — the same single-attach rule as the call session+ * (`callSession.js`), and mutually exclusive with an active FaceTime call:+ * both want the same BlackHole input device and the same host tab. That+ * exclusion is enforced by the socket layer (`server/sockets/voice.js`),+ * which is the one place that already knows about both sessions.+ */++import { appendJournal, getToday } from '../brainJournal.js';+import { createInboxLog } from '../brainStorage.js';++export const CAPTURE_STATES = ['idle', 'listening', 'ended'];++const initialState = () => ({+ state: 'idle',+ startedAt: null,+ transcript: [], // { text, at }+ endedReason: null,+});++let session = initialState();+let host = null;+let listener = null;++// Injectable so the write path can be driven with stubs instead of the real+// journal/inbox services and a real clock.+let deps = { appendJournal, getToday, createInboxLog, now: Date.now };++/** Test seam — override the write path/clock, or restore the real ones. */+export const __setCaptureSessionDeps = (overrides = {}) => {+ deps = { appendJournal, getToday, createInboxLog, now: Date.now, ...overrides };+};++const publicState = () => ({+ state: session.state,+ active: session.state === 'listening',+ hostAttached: Boolean(host),+ startedAt: session.startedAt,+ endedReason: session.endedReason,+ turns: session.transcript.length,+});++const emitState = () => {+ const snapshot = publicState();+ try {+ listener?.(snapshot);+ } catch (error) {+ console.error(`❌ voice capture: state listener failed: ${error.message}`);+ }+ return snapshot;+};++/** Register the sink for `voice:capture:state` broadcasts. */+export const setCaptureStateListener = (fn) => { listener = fn; };++export const getCaptureState = () => publicState();+export const getCaptureHost = () => host;+export const isCaptureActive = () => publicState().active;++/**+ * Claim the single capture-host slot.+ *+ * Refused rather than displaced, mirroring `callSession.attachHost` — two+ * tabs reading the same BlackHole device would each try to transcribe, and+ * the loser would have no way to know it had been silently muted.+ */+export function attachCaptureHost(socket) {+ if (host && host !== socket && host.connected !== false) return { ok: false, reason: 'host-taken' };+ host = socket;+ console.log(`🎙️ voice capture: host attached (${socket?.id ?? 'socket'})`);+ return { ok: true, state: emitState() };+}++export async function detachCaptureHost(socket) {+ if (host !== socket) return publicState();+ host = null;+ console.log('🎙️ voice capture: host detached');+ // Losing the host loses the audio path, so a running capture is ended+ // rather than left listening with nothing feeding it.+ if (publicState().active) return endCapture('host-detached');+ return emitState();+}++/** Begin accumulating a transcript. Fails closed when nothing holds the slot. */+export function startCapture(socket) {+ if (host !== socket) return { ok: false, reason: 'no-capture-host' };+ if (publicState().active) return { ok: false, reason: 'capture-in-progress' };+ session = { ...initialState(), state: 'listening', startedAt: deps.now() };+ return { ok: true, state: emitState() };+}++/** Record one transcribed utterance, timestamped as it arrived. */+export function recordUtterance(text) {+ const trimmed = (text || '').trim();+ if (!trimmed || !publicState().active) return publicState();+ session.transcript.push({ text: trimmed, at: deps.now() });+ return emitState();+}++/** HH:MM:SS in UTC — deterministic regardless of the host machine's locale/timezone. */+export const formatClockTime = (ms) => new Date(ms).toISOString().slice(11, 19);++const renderTranscript = (transcript) => transcript+ .map((turn) => `[${formatClockTime(turn.at)}] ${turn.text}`)+ .join('\n');++/**+ * End the capture and write the transcript down.+ *+ * Both writes are best-effort: a failed write must not leave the session+ * stuck `listening`, because the state is what gates starting the next+ * capture. The journal and inbox writes are independent — a failure in one+ * must not skip the other.+ */+export async function endCapture(reason = 'ended') {+ if (session.state !== 'listening') return publicState();+ const transcript = session.transcript;+ const startedAt = session.startedAt;+ const endedAt = deps.now();+ session.endedReason = reason;+ session.state = 'ended';+ emitState();++ if (transcript.length) {+ const body = `Meeting capture\n${formatClockTime(startedAt)}–${formatClockTime(endedAt)} UTC\n${renderTranscript(transcript)}`;+ try {+ await deps.appendJournal(await deps.getToday(), body, { source: 'voice' });+ } catch (error) {+ console.error(`❌ voice capture: journal append failed: ${error.message}`);+ }+ try {+ // Same shape as a manually-typed thought with auto-classify off+ // (brain.js captureThought's `mode === 'off'` path): needs_review, no+ // `ai` metadata, because no provider was ever invoked for it.+ await deps.createInboxLog({ capturedText: body, source: 'voice', status: 'needs_review' });+ } catch (error) {+ console.error(`❌ voice capture: inbox capture failed: ${error.message}`);+ }+ }++ session = { ...initialState(), endedReason: reason };+ return emitState();+}++/** Test helper — drop all state between cases. */+export const __resetCaptureSession = () => {+ session = initialState();+ host = null;+ listener = null;+ __setCaptureSessionDeps();+};diff --git a/server/services/voice/captureSession.test.js b/server/services/voice/captureSession.test.jsnew file mode 100644index 0000000000..30ce168d92--- /dev/null+++ b/server/services/voice/captureSession.test.js@@ -0,0 +1,222 @@+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';++vi.mock('../brainJournal.js', () => ({ appendJournal: vi.fn(), getToday: vi.fn() }));+vi.mock('../brainStorage.js', () => ({ createInboxLog: vi.fn() }));++import {+ __resetCaptureSession,+ __setCaptureSessionDeps,+ attachCaptureHost,+ detachCaptureHost,+ endCapture,+ formatClockTime,+ getCaptureHost,+ getCaptureState,+ isCaptureActive,+ recordUtterance,+ setCaptureStateListener,+ startCapture,+} from './captureSession.js';++const socket = (id = 'host-1') => ({ id, connected: true, emit: vi.fn() });++let clock;+let appendJournal;+let getToday;+let createInboxLog;++const install = (overrides = {}) => {+ clock = 1_000_000;+ appendJournal = vi.fn().mockResolvedValue({});+ getToday = vi.fn().mockResolvedValue('2026-08-29');+ createInboxLog = vi.fn().mockResolvedValue({ id: 'inbox-1' });+ __setCaptureSessionDeps({ appendJournal, getToday, createInboxLog, now: () => clock, ...overrides });+};++beforeEach(() => {+ __resetCaptureSession();+ install();+});++afterEach(() => { __resetCaptureSession(); });++describe('meeting capture session', () => {+ it('refuses to start without an attached capture host', () => {+ expect(startCapture(socket())).toEqual({ ok: false, reason: 'no-capture-host' });+ expect(getCaptureState()).toMatchObject({ state: 'idle', active: false, hostAttached: false });+ });++ it('gives the single host slot to the first tab and refuses the second', () => {+ const first = socket('host-1');+ expect(attachCaptureHost(first)).toMatchObject({ ok: true });+ expect(attachCaptureHost(socket('host-2'))).toEqual({ ok: false, reason: 'host-taken' });+ // Re-attaching the incumbent is a reconnect, not a second owner.+ expect(attachCaptureHost(first)).toMatchObject({ ok: true });+ });++ it('refuses a second capture while one is running', () => {+ const host = socket();+ attachCaptureHost(host);+ expect(startCapture(host)).toMatchObject({ ok: true });+ expect(startCapture(host)).toEqual({ ok: false, reason: 'capture-in-progress' });+ });++ it('accumulates timestamped utterances only while listening', () => {+ const host = socket();+ attachCaptureHost(host);+ startCapture(host);++ clock += 5_000;+ recordUtterance('Let’s start the standup.');+ clock += 12_000;+ recordUtterance(' ');++ expect(getCaptureState()).toMatchObject({ turns: 1, active: true });+ // A blank/whitespace-only transcript segment is not a turn.+ expect(recordUtterance('nobody is listening yet')).toMatchObject({ turns: 2 });+ });++ it('ignores utterances recorded outside an active capture', () => {+ expect(recordUtterance('too early')).toMatchObject({ turns: 0 });+ });++ it('writes a timestamped transcript to the journal and files a review-only inbox item', async () => {+ const host = socket();+ attachCaptureHost(host);+ startCapture(host);+ clock = 1_000_000;+ recordUtterance('Kickoff: ship the capture mode.');+ clock = 1_030_000;+ recordUtterance('Assign the doc pass to Sam.');++ await endCapture('stopped');++ const expectedBody = 'Meeting capture\n00:16:40–00:17:10 UTC\n'+ + '[00:16:40] Kickoff: ship the capture mode.\n'+ + '[00:17:10] Assign the doc pass to Sam.';+ expect(appendJournal).toHaveBeenCalledWith('2026-08-29', expectedBody, { source: 'voice' });+ expect(createInboxLog).toHaveBeenCalledWith({ capturedText: expectedBody, source: 'voice', status: 'needs_review' });+ expect(getCaptureState()).toMatchObject({ state: 'idle', active: false, endedReason: 'stopped' });+ });++ it('writes nothing for a capture where nobody said anything', async () => {+ const host = socket();+ attachCaptureHost(host);+ startCapture(host);++ await endCapture('stopped');++ expect(appendJournal).not.toHaveBeenCalled();+ expect(createInboxLog).not.toHaveBeenCalled();+ });++ it('never invokes an AI provider — only the journal and inbox writes', async () => {+ // The whole point of this module: capture never classifies. There is no+ // provider/classifier dependency to call in the first place, so this+ // pins the deps surface rather than a runtime behavior.+ const host = socket();+ attachCaptureHost(host);+ startCapture(host);+ recordUtterance('one turn');++ await endCapture('stopped');++ expect(createInboxLog).toHaveBeenCalledWith(expect.not.objectContaining({ ai: expect.anything() }));+ });++ it('still resets when the journal write fails, and still files the inbox item', async () => {+ const host = socket();+ attachCaptureHost(host);+ startCapture(host);+ recordUtterance('hello');+ appendJournal.mockRejectedValue(new Error('disk full'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await endCapture('stopped');++ // A failed write must not leave the session `listening`, or no further+ // capture could ever be started.+ expect(getCaptureState()).toMatchObject({ state: 'idle', active: false });+ expect(createInboxLog).toHaveBeenCalled();+ consoleError.mockRestore();+ });++ it('still resets when the inbox write fails after a successful journal write', async () => {+ const host = socket();+ attachCaptureHost(host);+ startCapture(host);+ recordUtterance('hello');+ createInboxLog.mockRejectedValue(new Error('write failed'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await endCapture('stopped');++ expect(appendJournal).toHaveBeenCalled();+ expect(getCaptureState()).toMatchObject({ state: 'idle', active: false });+ consoleError.mockRestore();+ });++ it('ends the capture when the host tab goes away', async () => {+ const tab = socket();+ attachCaptureHost(tab);+ startCapture(tab);+ recordUtterance('mid-sentence');++ await detachCaptureHost(tab);++ expect(getCaptureState()).toMatchObject({ hostAttached: false, active: false, endedReason: 'host-detached' });+ expect(appendJournal).toHaveBeenCalled();+ });++ it('ignores a detach from a tab that never owned the slot', async () => {+ const owner = socket('host-1');+ attachCaptureHost(owner);+ startCapture(owner);++ await detachCaptureHost(socket('host-2'));++ expect(getCaptureState()).toMatchObject({ hostAttached: true, active: true });+ });++ it('broadcasts every state change to the registered listener', async () => {+ const states = [];+ setCaptureStateListener((snapshot) => states.push(snapshot.state));+ const host = socket();+ attachCaptureHost(host);+ startCapture(host);+ recordUtterance('hi');+ await endCapture('stopped');++ expect(states).toEqual(expect.arrayContaining(['listening', 'ended']));+ });++ it('survives a listener that throws', () => {+ setCaptureStateListener(() => { throw new Error('socket gone'); });+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const host = socket();++ expect(attachCaptureHost(host)).toMatchObject({ ok: true });+ consoleError.mockRestore();+ });++ it('exposes the current host for the socket layer to gate on', () => {+ const host = socket();+ expect(getCaptureHost()).toBeNull();+ attachCaptureHost(host);+ expect(getCaptureHost()).toBe(host);+ });++ it('reports active only while listening', async () => {+ const host = socket();+ attachCaptureHost(host);+ expect(isCaptureActive()).toBe(false);+ startCapture(host);+ expect(isCaptureActive()).toBe(true);+ await endCapture('stopped');+ expect(isCaptureActive()).toBe(false);+ });++ it('formats a clock time in UTC regardless of host locale', () => {+ expect(formatClockTime(Date.UTC(2026, 7, 29, 3, 4, 5))).toBe('03:04:05');+ });+});diff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex 6738470b06..4733fe8206 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -12,6 +12,9 @@// Call host (FaceTime Audio bridge):// Inbound: voice:call:attach | voice:call:audio | voice:call:detach// Outbound: voice:call:state | voice:call:tts+// Meeting capture (same page, same audio bridge, no LLM — STT only):+// Inbound: voice:capture:start | voice:call:audio | voice:capture:stop+// Outbound: voice:capture:stateimport { runTurn } from '../services/voice/pipeline.js';import { getVoiceConfig } from '../services/voice/config.js';@@ -23,6 +26,7 @@ import {} from '../services/voice/voiceOutput.js';import { isIsoDate } from '../services/brainJournal.js';import { pcmToWavBuffer } from '../lib/chiptuneRender.js';+import { transcribe } from '../services/voice/stt.js';import { CALL_AUDIO_SAMPLE_RATE, createCallEndpointer, pcmToFloat } from '../services/voice/callEndpointing.js';import {attachHost,@@ -35,6 +39,16 @@ import {recordTurn,setCallStateListener,} from '../services/voice/callSession.js';+import {+ attachCaptureHost,+ detachCaptureHost,+ endCapture,+ getCaptureHost,+ isCaptureActive,+ recordUtterance,+ setCaptureStateListener,+ startCapture,+} from '../services/voice/captureSession.js';// Cap by messages (each user utterance + assistant reply is ~2). 24 → ~12 turns.const HISTORY_MESSAGES = 24;@@ -418,6 +432,14 @@ export const registerVoiceHandlers = (socket) => {socket.on('voice:call:attach', async () => {try {if (!(await ensureEnabled('call'))) return;+ // Mutually exclusive with meeting capture: both want the same BlackHole+ // input device and the same host tab, and a call also wants BlackHole+ // 2ch to talk back through — running both at once would fight over the+ // device rather than fail closed with a clear reason.+ if (isCaptureActive() || getCaptureHost() === socket) {+ socket.emit('voice:call:state', { error: 'capture-active', hostAttached: false, active: false, state: 'idle' });+ return;+ }const claim = attachHost(socket);if (!claim.ok) {// Refused, not displaced: two tabs reading the same device would each@@ -436,7 +458,9 @@ export const registerVoiceHandlers = (socket) => {socket.on('voice:call:audio', async (payload = {}) => {try {- if (getCallHost() !== socket || !call.endpointer) return;+ const asCallHost = getCallHost() === socket && call.endpointer;+ const asCaptureHost = getCaptureHost() === socket && capture.endpointer;+ if (!asCallHost && !asCaptureHost) return;const { pcm } = payload || {};const bytes = audioByteLength(pcm);if (!bytes || bytes > MAX_CALL_FRAME_BYTES) return;@@ -444,18 +468,28 @@ export const registerVoiceHandlers = (socket) => {? new Int16Array(pcm.buffer, pcm.byteOffset, Math.floor(pcm.byteLength / 2)): new Int16Array(pcm);- const utterance = call.endpointer.push(view);- // Barge-in: the caller talking over a reply cancels it, exactly as- // pressing the widget's interrupt does.- if (call.endpointer.speaking && call.busy) {- state.ctrl?.abort();- state.pendingDestructive = null;- socket.emit('voice:interrupt', { reason: 'barge-in' });+ if (asCallHost) {+ const utterance = call.endpointer.push(view);+ // Barge-in: the caller talking over a reply cancels it, exactly as+ // pressing the widget's interrupt does.+ if (call.endpointer.speaking && call.busy) {+ state.ctrl?.abort();+ state.pendingDestructive = null;+ socket.emit('voice:interrupt', { reason: 'barge-in' });+ }+ if (!utterance) return;+ noteCallerSpeech();+ if (call.busy) return;+ await runCallUtterance(utterance);+ return;}- if (!utterance) return;- noteCallerSpeech();- if (call.busy) return;- await runCallUtterance(utterance);++ // Meeting capture: STT only, never the LLM/tools pipeline (no+ // cold-bootstrap AI calls — see AGENTS.md). Utterances are queued and+ // transcribed one at a time so a burst of speech can't run two whisper+ // requests concurrently and interleave the transcript out of order.+ const utterance = capture.endpointer.push(view);+ if (utterance) enqueueCaptureUtterance(utterance);} catch (err) {console.error(`❌ voice:call:audio failed: ${err.message}`);}@@ -466,6 +500,84 @@ export const registerVoiceHandlers = (socket) => {emitCallState(await detachHost(socket));});+ // ---------------------------------------------------------------------------+ // Meeting capture — the same call-host page's other mode. Reads the same+ // BlackHole 16ch device and rides the same `voice:call:audio` PCM frames,+ // but only transcribes: it never runs the LLM/tools pipeline and never+ // plays anything back. Stopping finalizes whatever is still buffered in the+ // endpointer, then writes the transcript to the journal and the inbox.+ // ---------------------------------------------------------------------------+ const capture = { endpointer: null, queue: Promise.resolve() };++ const emitCaptureState = (snapshot) => socket.emit('voice:capture:state', snapshot);++ const runCaptureUtterance = async (utterance) => {+ try {+ const { text } = await transcribe(+ pcmToWavBuffer(pcmToFloat(utterance.pcm), { sampleRate: CALL_AUDIO_SAMPLE_RATE }),+ { mimeType: 'audio/wav' },+ );+ if (text) emitCaptureState(recordUtterance(text));+ } catch (err) {+ console.error(`🎙️ capture transcribe failed: ${err.message}`);+ socket.emit('voice:error', { stage: 'capture', message: err.message });+ }+ };++ // Serialize onto a per-socket queue (AGENTS.md: async handlers mutating+ // shared module-level state must not fire concurrently) rather than+ // dropping an utterance that arrives mid-transcription — a dropped chunk+ // here is lost meeting content, not a superseded turn like call barge-in.+ const enqueueCaptureUtterance = (utterance) => {+ capture.queue = capture.queue.then(() => runCaptureUtterance(utterance));+ return capture.queue;+ };++ socket.on('voice:capture:start', async () => {+ try {+ if (!(await ensureEnabled('capture'))) return;+ if (isCallActive() || getCallHost() === socket) {+ socket.emit('voice:capture:state', { error: 'call-active', hostAttached: false, active: false, state: 'idle' });+ return;+ }+ const claim = attachCaptureHost(socket);+ if (!claim.ok) {+ socket.emit('voice:capture:state', { error: claim.reason, hostAttached: false, active: false, state: 'idle' });+ return;+ }+ const started = startCapture(socket);+ if (!started.ok) {+ socket.emit('voice:capture:state', { error: started.reason, hostAttached: true, active: false, state: 'idle' });+ return;+ }+ capture.endpointer = createCallEndpointer();+ capture.queue = Promise.resolve();+ setCaptureStateListener(emitCaptureState);+ emitCaptureState(started.state);+ } catch (err) {+ console.error(`❌ voice:capture:start failed: ${err.message}`);+ socket.emit('voice:error', { stage: 'capture', message: err.message });+ }+ });++ socket.on('voice:capture:stop', async () => {+ try {+ if (getCaptureHost() !== socket) return;+ // Finalize whatever speech is still buffered rather than dropping the+ // last few seconds of the meeting on the floor.+ const pending = capture.endpointer?.flush();+ if (pending) enqueueCaptureUtterance(pending);+ await capture.queue.catch(() => {});+ capture.endpointer = null;+ const ended = await endCapture('stopped');+ emitCaptureState(ended);+ emitCaptureState(await detachCaptureHost(socket));+ } catch (err) {+ console.error(`❌ voice:capture:stop failed: ${err.message}`);+ socket.emit('voice:error', { stage: 'capture', message: err.message });+ }+ });+socket.on('disconnect', () => {// Drop this tab from the voice-output registry; if it was the sole// recipient, output is promoted to another live tab so proactive audio@@ -492,6 +604,13 @@ export const registerVoiceHandlers = (socket) => {call.endpointer = null;detachHost(socket).catch((err) => console.error(`❌ voice call detach failed: ${err.message}`));}+ // Same for meeting capture — best-effort, no final flush of whatever was+ // still mid-utterance (matches the call path above, which drops its own+ // in-flight endpointer buffer on disconnect the same way).+ if (getCaptureHost() === socket) {+ capture.endpointer = null;+ detachCaptureHost(socket).catch((err) => console.error(`❌ voice capture detach failed: ${err.message}`));+ }});};diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.jsindex b34b2f2aeb..86f94c1fc5 100644--- a/server/sockets/voice.test.js+++ b/server/sockets/voice.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Force the enabled-gate open so the validation tests below deterministically// exercise the size/text guards (ensureEnabled runs BEFORE every guard; with@@ -12,12 +12,23 @@ vi.mock(import('../services/voice/config.js'), async (importOriginal) => {};});+// Meeting capture transcribes over the network (whisper.cpp's HTTP server);+// stub it so the capture-routing tests below run offline and deterministically.+vi.mock('../services/voice/stt.js', () => ({ transcribe: vi.fn() }));+const { truncateOnWordBoundary, registerVoiceHandlers } = await import('./voice.js');const {getVoiceOutputSocket,emitVoiceOutput,__resetVoiceOutput,} = await import('../services/voice/voiceOutput.js');+const { transcribe } = await import('../services/voice/stt.js');+const { attachHost: attachCallHost, __resetCallSession } = await import('../services/voice/callSession.js');+const {+ __resetCaptureSession,+ __setCaptureSessionDeps,+ getCaptureState,+} = await import('../services/voice/captureSession.js');// Minimal fake socket: records on() handlers so tests can fire inbound events,// and captures emit() calls. No real Socket.IO needed — the voice:ui:index /@@ -257,3 +268,120 @@ describe('voice:output single-recipient wiring', () => {expect(getVoiceOutputSocket()).toBe(b);});});++describe('voice:capture socket handlers (meeting capture)', () => {+ // ~20 ms of 16 kHz mono, matching the call-host page's frame size (see+ // callAudioBridge.js CALL_FRAME_SAMPLES). Loud enough to clear the+ // endpointer's RMS threshold (0.015) and long enough, over several frames,+ // to clear its 250 ms minimum-utterance floor; the silent run after it+ // clears the 700 ms trailing-silence endpoint.+ const FRAME_SAMPLES = 320;+ const loudFrame = () => {+ const frame = new Int16Array(FRAME_SAMPLES);+ for (let i = 0; i < FRAME_SAMPLES; i += 1) frame[i] = Math.round(Math.sin(i / 8) * 20000);+ return frame;+ };+ const silentFrame = () => new Int16Array(FRAME_SAMPLES);+ const flushMicrotasks = () => new Promise((resolve) => setImmediate(resolve));++ let appendJournal;+ let createInboxLog;++ beforeEach(() => {+ __resetCallSession();+ __resetCaptureSession();+ appendJournal = vi.fn().mockResolvedValue({});+ createInboxLog = vi.fn().mockResolvedValue({ id: 'inbox-1' });+ __setCaptureSessionDeps({+ appendJournal,+ getToday: vi.fn().mockResolvedValue('2026-08-29'),+ createInboxLog,+ now: Date.now,+ });+ transcribe.mockReset();+ });++ afterEach(() => {+ __resetCallSession();+ __resetCaptureSession();+ });++ it('registers the capture start/stop handlers', () => {+ const socket = makeFakeSocket();+ registerVoiceHandlers(socket);+ expect(socket.has('voice:capture:start')).toBe(true);+ expect(socket.has('voice:capture:stop')).toBe(true);+ });++ it('claims the single capture-host slot and refuses a second tab', async () => {+ const first = makeFakeSocket();+ const second = makeFakeSocket();+ registerVoiceHandlers(first);+ registerVoiceHandlers(second);++ await first.fire('voice:capture:start');+ await second.fire('voice:capture:start');++ const refusal = second.emitted.find((e) => e.event === 'voice:capture:state');+ expect(refusal.payload).toMatchObject({ error: 'host-taken' });+ });++ it('refuses to start a capture on a tab already hosting a FaceTime call', async () => {+ const socket = makeFakeSocket();+ registerVoiceHandlers(socket);+ attachCallHost(socket); // same tab already owns the call-host slot++ await socket.fire('voice:capture:start');++ const state = socket.emitted.find((e) => e.event === 'voice:capture:state');+ expect(state.payload).toMatchObject({ error: 'call-active' });+ });++ it('refuses to attach a call host on a tab already capturing', async () => {+ const socket = makeFakeSocket();+ registerVoiceHandlers(socket);+ await socket.fire('voice:capture:start');++ await socket.fire('voice:call:attach');++ const state = socket.emitted.find((e) => e.event === 'voice:call:state');+ expect(state.payload).toMatchObject({ error: 'capture-active' });+ });++ it('transcribes meeting audio through STT only — never the LLM/tools pipeline — and files the journal + inbox on stop', async () => {+ const socket = makeFakeSocket();+ registerVoiceHandlers(socket);+ transcribe.mockResolvedValue({ text: 'let’s ship the capture mode', latencyMs: 5 });++ await socket.fire('voice:capture:start');+ expect(getCaptureState()).toMatchObject({ active: true });++ for (let i = 0; i < 14; i += 1) socket.fire('voice:call:audio', { pcm: loudFrame() });+ for (let i = 0; i < 36; i += 1) socket.fire('voice:call:audio', { pcm: silentFrame() });+ await flushMicrotasks();++ // One STT call for the one utterance — routed away from runTurn entirely,+ // so nothing from the LLM/tools pipeline ever fired.+ expect(transcribe).toHaveBeenCalledTimes(1);+ expect(socket.emitted.some((e) => e.event === 'voice:llm:done')).toBe(false);+ const states = socket.emitted.filter((e) => e.event === 'voice:capture:state');+ expect(states.some((e) => e.payload.turns === 1)).toBe(true);++ await socket.fire('voice:capture:stop');++ expect(appendJournal).toHaveBeenCalledTimes(1);+ expect(appendJournal.mock.calls[0][1]).toContain('let’s ship the capture mode');+ expect(appendJournal.mock.calls[0][2]).toEqual({ source: 'voice' });+ expect(createInboxLog).toHaveBeenCalledWith(expect.objectContaining({ status: 'needs_review', source: 'voice' }));+ // No AI provider call anywhere in this flow — createInboxLog never carries+ // classifier metadata, matching the auto-classify-off inbox shape.+ expect(createInboxLog).toHaveBeenCalledWith(expect.not.objectContaining({ ai: expect.anything() }));+ });++ it('ignores voice:call:audio on a tab that never attached either host', () => {+ const socket = makeFakeSocket();+ registerVoiceHandlers(socket);+ expect(() => socket.fire('voice:call:audio', { pcm: loudFrame() })).not.toThrow();+ expect(transcribe).not.toHaveBeenCalled();+ });+});