Skip to content

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

feat: carry FaceTime Audio call audio through BlackHole into the voice pipeline (#5308)

[._.]/ Adam Eivye4300dd3ca3d
diff --git a/client/src/App.jsx b/client/src/App.jsx
index fb48b7a3d8..ea069be4b3 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -89,6 +89,7 @@ const Privacy = lazyWithReload(() => import('./pages/Privacy'));
const Agents = lazyWithReload(() => import('./pages/Agents'));
const Uploads = lazyWithReload(() => import('./pages/Uploads'));
const Settings = lazyWithReload(() => import('./pages/Settings'));
+const VoiceCallHost = lazyWithReload(() => import('./pages/VoiceCallHost'));
const ApiExplorer = lazyWithReload(() => import('./pages/ApiExplorer'));
const LocalLlmPlayground = lazyWithReload(() => import('./pages/LocalLlmPlayground'));
const Models = lazyWithReload(() => import('./pages/Models'));
@@ -327,6 +328,10 @@ export default function App() {
<Route path="settings/spotify" element={<RedirectWithSearch to="/brain/spotify" />} />
<Route path="settings/youtube" element={<RedirectWithSearch to="/brain/youtube" />} />
<Route path="settings/:tab" element={<Settings />} />
+ {/* The FaceTime call host runs in its own tab on the Mac — device
+ permissions and setSinkId need a real browser profile, and the
+ page holds a Web Lock so a second tab cannot double-answer. */}
+ <Route path="voice/call-host" element={<VoiceCallHost />} />
<Route path="api-reference" element={<Navigate to="/api-reference/catalog" replace />} />
<Route path="api-reference/:tab" element={<ApiExplorer />} />
<Route path="models" element={<Navigate to="/models/performance" replace />} />
diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsx
index 2e0c6cc0cc..e1ca37448e 100644
--- a/client/src/components/settings/VoiceTab.jsx
+++ b/client/src/components/settings/VoiceTab.jsx
@@ -356,7 +356,13 @@ export function VoiceTab() {
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<FormField label="Target name"><input id="facetime-target-name" value={facetime.targetName || ''} onChange={(e) => patch('facetime.targetName', e.target.value)} className={inputCls} /></FormField>
<FormField label="Target handle" hint="E.164 phone number or email address."><input id="facetime-target-handle" value={facetime.targetHandle || ''} onChange={(e) => patch('facetime.targetHandle', e.target.value)} className={inputCls} /></FormField>
+ <FormField label="Maximum call length" hint="Minutes before PortOS hangs up on its own."><input id="facetime-max-call-minutes" type="number" min="1" max="120" value={facetime.maxCallMinutes ?? 15} onChange={(e) => patch('facetime.maxCallMinutes', Number(e.target.value))} className={inputCls} /></FormField>
</div>
+ {/* Two-way audio needs a real browser tab on this Mac: device
+ permissions and setSinkId do not work from the server. */}
+ <p className="text-xs text-gray-400">
+ Call audio runs in its own tab — <Link to="/voice/call-host" className="text-port-accent underline">open the call host</Link> on this Mac and attach it before placing a call. Without it, PortOS can dial but nobody can hear the call.
+ </p>
<div className="flex flex-wrap gap-2">
{['probe', 'call', 'hangup'].map((action) => <button key={action} type="button" onClick={() => handleFaceTimeAction(action)} disabled={saving || faceTimeDirty || facetimeAction !== null} className="px-3 py-2 rounded bg-port-border text-sm text-white disabled:opacity-50">{facetimeAction === action ? 'Working…' : action === 'call' ? 'Test call' : action[0].toUpperCase() + action.slice(1)}</button>)}
<button type="button" onClick={refreshFaceTime} className="px-3 py-2 rounded bg-port-bg border border-port-border text-sm text-white">Check setup</button>
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d0e0bd0459..ec140757f6 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -100,6 +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`. |
| `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.js
new file mode 100644
index 0000000000..1322afe10d
--- /dev/null
+++ b/client/src/lib/callAudioBridge.js
@@ -0,0 +1,140 @@
+/**
+ * Pure device/format helpers for the FaceTime call-host page.
+ *
+ * The page itself is unavoidably impure — real devices, a real AudioWorklet, a
+ * real Web Lock — so everything that can be decided from plain data lives here
+ * instead: which device to open, whether the browser can do the job at all,
+ * and the PCM conversion the server expects.
+ *
+ * The whole module fails CLOSED by construction: an absent capability, an
+ * absent device, and a device that is present but wrong all produce a specific
+ * message rather than a best guess, because a bridge that half-works drops the
+ * user's call audio on the floor silently.
+ */
+
+export const CALL_AUDIO_SAMPLE_RATE = 16_000;
+/** One Web Lock so a second tab cannot double-answer the same call. */
+export const CALL_HOST_LOCK = 'portos-facetime-call-host';
+/** ~20 ms of 16 kHz mono — small enough to endpoint on, big enough not to flood. */
+export const CALL_FRAME_SAMPLES = 320;
+
+// Browser APIs with no fallback worth having. `setSinkId` is what routes the
+// reply into BlackHole 2ch; without it the assistant would talk to the room
+// instead of into the call.
+const REQUIRED_APIS = Object.freeze([
+ { name: 'MediaStreamTrackProcessor', test: (scope) => typeof scope?.MediaStreamTrackProcessor === 'function' },
+ { name: 'MediaStreamTrackGenerator', test: (scope) => typeof scope?.MediaStreamTrackGenerator === 'function' },
+ { name: 'AudioWorklet', test: (scope) => typeof scope?.AudioWorkletNode === 'function' },
+ { name: 'mediaDevices.enumerateDevices', test: (scope) => typeof scope?.navigator?.mediaDevices?.enumerateDevices === 'function' },
+ { name: 'HTMLMediaElement.setSinkId', test: (scope) => typeof scope?.HTMLMediaElement?.prototype?.setSinkId === 'function' },
+ { name: 'navigator.locks', test: (scope) => typeof scope?.navigator?.locks?.request === 'function' },
+]);
+
+/** Every required API this browser is missing, in the order they are listed. */
+export function missingCallHostApis(scope = globalThis) {
+ return REQUIRED_APIS.filter((api) => !api.test(scope)).map((api) => api.name);
+}
+
+const normalize = (value) => String(value ?? '').trim().toLowerCase();
+
+/**
+ * Find a device by its human label.
+ *
+ * Matched exactly (after trimming and case-folding) rather than by substring:
+ * "BlackHole 16ch" contains "BlackHole 1", and picking the wrong virtual
+ * device is indistinguishable from a dead call.
+ */
+export function findAudioDevice(devices, label, kind) {
+ if (!Array.isArray(devices)) return null;
+ const wanted = normalize(label);
+ if (!wanted) return null;
+ return devices.find((device) => normalize(device?.label) === wanted && (!kind || device?.kind === kind)) || null;
+}
+
+/**
+ * Why the bridge cannot start, or `null` when it can.
+ *
+ * An empty device list is reported as a permission problem, not as a missing
+ * 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.
+ */
+export function describeDeviceProblem(devices, { inputLabel, outputLabel } = {}) {
+ if (!Array.isArray(devices)) return 'Could not read this Mac’s audio devices.';
+ if (!devices.some((device) => normalize(device?.label))) {
+ return 'Grant this tab microphone access so it can see the audio devices by name.';
+ }
+ 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')) {
+ return `No audio output named “${outputLabel}”. Install BlackHole and set FaceTime’s microphone to it.`;
+ }
+ return null;
+}
+
+/** Average N planar channels into one. BlackHole 16ch carries the call on all of them. */
+export function downmixToMono(channels) {
+ if (!channels?.length) return new Float32Array(0);
+ if (channels.length === 1) return Float32Array.from(channels[0]);
+ const length = Math.min(...channels.map((channel) => channel.length));
+ const mono = new Float32Array(length);
+ for (let index = 0; index < length; index += 1) {
+ let sum = 0;
+ for (const channel of channels) sum += channel[index];
+ mono[index] = sum / channels.length;
+ }
+ return mono;
+}
+
+/**
+ * Resample to 16 kHz by linear interpolation.
+ *
+ * Whisper wants 16 kHz and the devices run at 48 kHz. Linear is enough for
+ * speech at a 3:1 ratio and costs nothing; anything fancier would need a
+ * filter bank in an AudioWorklet's render quantum budget.
+ */
+export function resampleTo16k(samples, fromRate) {
+ if (!samples?.length || !fromRate) return new Float32Array(0);
+ if (fromRate === CALL_AUDIO_SAMPLE_RATE) return Float32Array.from(samples);
+ const ratio = fromRate / CALL_AUDIO_SAMPLE_RATE;
+ const length = Math.floor(samples.length / ratio);
+ const output = new Float32Array(length);
+ for (let index = 0; index < length; index += 1) {
+ const position = index * ratio;
+ const left = Math.floor(position);
+ const right = Math.min(left + 1, samples.length - 1);
+ const fraction = position - left;
+ output[index] = samples[left] * (1 - fraction) + samples[right] * fraction;
+ }
+ return output;
+}
+
+/** Float -1..1 → Int16, clamped. The wire format the server endpoints on. */
+export function floatToInt16(samples) {
+ const output = new Int16Array(samples?.length || 0);
+ for (let index = 0; index < output.length; index += 1) {
+ const clamped = Math.max(-1, Math.min(1, samples[index]));
+ output[index] = Math.round(clamped * 32767);
+ }
+ return output;
+}
+
+/** 0..1 level for the input meter. */
+export function rmsLevel(samples) {
+ if (!samples?.length) return 0;
+ let sum = 0;
+ for (let index = 0; index < samples.length; index += 1) sum += samples[index] * samples[index];
+ return Math.sqrt(sum / samples.length);
+}
+
+/** One second of a 440 Hz tone, for confirming the call can hear PortOS. */
+export function buildTestTone(sampleRate = CALL_AUDIO_SAMPLE_RATE, seconds = 1, frequency = 440) {
+ const samples = new Float32Array(Math.max(0, Math.round(sampleRate * seconds)));
+ for (let index = 0; index < samples.length; index += 1) {
+ // Faded in and out so the tone cannot click through the call.
+ const envelope = Math.min(1, Math.min(index, samples.length - index) / (sampleRate * 0.01));
+ samples[index] = Math.sin((2 * Math.PI * frequency * index) / sampleRate) * 0.3 * envelope;
+ }
+ return samples;
+}
diff --git a/client/src/lib/callAudioBridge.test.js b/client/src/lib/callAudioBridge.test.js
new file mode 100644
index 0000000000..9b7cbf335a
--- /dev/null
+++ b/client/src/lib/callAudioBridge.test.js
@@ -0,0 +1,156 @@
+import { describe, expect, it } from 'vitest';
+import {
+ CALL_AUDIO_SAMPLE_RATE,
+ buildTestTone,
+ describeDeviceProblem,
+ downmixToMono,
+ findAudioDevice,
+ floatToInt16,
+ missingCallHostApis,
+ resampleTo16k,
+ rmsLevel,
+} from './callAudioBridge.js';
+
+const fullScope = () => ({
+ MediaStreamTrackProcessor: function processor() {},
+ MediaStreamTrackGenerator: function generator() {},
+ AudioWorkletNode: function worklet() {},
+ HTMLMediaElement: { prototype: { setSinkId: () => {} } },
+ navigator: { mediaDevices: { enumerateDevices: () => {} }, locks: { request: () => {} } },
+});
+
+const devices = () => [
+ { label: 'BlackHole 16ch', kind: 'audioinput', deviceId: 'in-1' },
+ { label: 'BlackHole 2ch', kind: 'audiooutput', deviceId: 'out-1' },
+ { label: 'MacBook Pro Microphone', kind: 'audioinput', deviceId: 'in-2' },
+];
+
+describe('call host capability probe', () => {
+ it('passes a browser with every required API', () => {
+ expect(missingCallHostApis(fullScope())).toEqual([]);
+ });
+
+ it.each([
+ ['MediaStreamTrackProcessor'],
+ ['MediaStreamTrackGenerator'],
+ ['AudioWorklet'],
+ ['mediaDevices.enumerateDevices'],
+ ['HTMLMediaElement.setSinkId'],
+ ['navigator.locks'],
+ ])('names %s when it is missing', (missing) => {
+ const scope = fullScope();
+ if (missing === 'AudioWorklet') delete scope.AudioWorkletNode;
+ else if (missing === 'mediaDevices.enumerateDevices') scope.navigator.mediaDevices = {};
+ else if (missing === 'HTMLMediaElement.setSinkId') scope.HTMLMediaElement = { prototype: {} };
+ else if (missing === 'navigator.locks') scope.navigator.locks = {};
+ else delete scope[missing];
+
+ expect(missingCallHostApis(scope)).toEqual([missing]);
+ });
+
+ it('reports every gap at once rather than one per reload', () => {
+ expect(missingCallHostApis({})).toHaveLength(6);
+ });
+});
+
+describe('call host device selection', () => {
+ it('matches a device label exactly, ignoring case and padding', () => {
+ expect(findAudioDevice(devices(), ' blackhole 16CH ', 'audioinput')).toMatchObject({ deviceId: 'in-1' });
+ expect(findAudioDevice(devices(), 'BlackHole 2ch', 'audiooutput')).toMatchObject({ deviceId: 'out-1' });
+ });
+
+ it('never resolves a prefix to a different virtual device', () => {
+ // "BlackHole 1" is a prefix of "BlackHole 16ch"; a substring match here
+ // would silently open the wrong device, which is indistinguishable from a
+ // dead call.
+ expect(findAudioDevice(devices(), 'BlackHole 1', 'audioinput')).toBeNull();
+ expect(findAudioDevice(devices(), 'BlackHole 16ch', 'audiooutput')).toBeNull();
+ expect(findAudioDevice(null, 'BlackHole 16ch')).toBeNull();
+ expect(findAudioDevice(devices(), '')).toBeNull();
+ });
+
+ it('passes a correctly configured machine', () => {
+ expect(describeDeviceProblem(devices(), { inputLabel: 'BlackHole 16ch', outputLabel: 'BlackHole 2ch' })).toBeNull();
+ });
+
+ it('blames permission, not the driver, when labels are blank', () => {
+ // An ungranted tab enumerates devices with empty labels. Telling the user
+ // to reinstall BlackHole there sends them to fix the wrong thing.
+ const unlabeled = [{ label: '', kind: 'audioinput' }, { label: '', kind: 'audiooutput' }];
+ expect(describeDeviceProblem(unlabeled, { inputLabel: 'BlackHole 16ch', outputLabel: 'BlackHole 2ch' }))
+ .toMatch(/microphone access/);
+ });
+
+ it('names which half of the bridge is missing', () => {
+ const noInput = devices().filter((device) => device.label !== 'BlackHole 16ch');
+ const noOutput = devices().filter((device) => device.label !== 'BlackHole 2ch');
+
+ expect(describeDeviceProblem(noInput, { inputLabel: 'BlackHole 16ch', outputLabel: 'BlackHole 2ch' })).toMatch(/BlackHole 16ch/);
+ expect(describeDeviceProblem(noOutput, { inputLabel: 'BlackHole 16ch', outputLabel: 'BlackHole 2ch' })).toMatch(/BlackHole 2ch/);
+ expect(describeDeviceProblem(null, {})).toMatch(/Could not read/);
+ });
+});
+
+describe('call host audio format', () => {
+ it('averages every channel of the 16ch device into one', () => {
+ const mono = downmixToMono([Float32Array.from([1, 0]), Float32Array.from([0, 1]), Float32Array.from([0.5, 0.5])]);
+ expect(Array.from(mono)).toEqual([0.5, 0.5]);
+ expect(Array.from(downmixToMono([Float32Array.from([0.25])]))).toEqual([0.25]);
+ expect(downmixToMono([])).toHaveLength(0);
+ });
+
+ it('truncates to the shortest channel rather than reading past one', () => {
+ const mono = downmixToMono([Float32Array.from([1, 1, 1]), Float32Array.from([1])]);
+ expect(Array.from(mono)).toEqual([1]);
+ });
+
+ it('resamples 48 kHz down to the 16 kHz whisper wants', () => {
+ const input = new Float32Array(4800);
+ for (let index = 0; index < input.length; index += 1) input[index] = Math.sin(index / 20);
+
+ const output = resampleTo16k(input, 48_000);
+
+ expect(output).toHaveLength(1600);
+ // A 3:1 decimation lands sample 0 on sample 0 and sample 1 on sample 3.
+ expect(output[0]).toBeCloseTo(input[0], 5);
+ expect(output[1]).toBeCloseTo(input[3], 5);
+ });
+
+ it('passes 16 kHz through untouched and copies rather than aliases', () => {
+ const input = Float32Array.from([0.1, 0.2]);
+ const output = resampleTo16k(input, CALL_AUDIO_SAMPLE_RATE);
+
+ expect(output[0]).toBeCloseTo(0.1, 5);
+ expect(output[1]).toBeCloseTo(0.2, 5);
+ output[0] = 1;
+ expect(input[0]).toBeCloseTo(0.1, 5);
+ });
+
+ it('returns nothing for empty input or an unknown rate', () => {
+ expect(resampleTo16k(new Float32Array(0), 48_000)).toHaveLength(0);
+ expect(resampleTo16k(Float32Array.from([1]), 0)).toHaveLength(0);
+ });
+
+ it('clamps to Int16 instead of wrapping a hot sample to silence', () => {
+ // Wrapping would turn a loud sample into a loud sample of the OPPOSITE
+ // sign — an audible click on every peak.
+ expect(Array.from(floatToInt16(Float32Array.from([0, 1, -1, 2, -2])))).toEqual([0, 32767, -32767, 32767, -32767]);
+ expect(floatToInt16(null)).toHaveLength(0);
+ });
+
+ it('measures level for the input meter', () => {
+ expect(rmsLevel(Float32Array.from([0, 0]))).toBe(0);
+ expect(rmsLevel(Float32Array.from([1, -1]))).toBe(1);
+ expect(rmsLevel(new Float32Array(0))).toBe(0);
+ });
+
+ it('builds a test tone that fades in and out so it cannot click', () => {
+ const tone = buildTestTone(CALL_AUDIO_SAMPLE_RATE, 1);
+
+ expect(tone).toHaveLength(CALL_AUDIO_SAMPLE_RATE);
+ expect(Math.abs(tone[0])).toBeLessThan(0.01);
+ expect(Math.abs(tone[tone.length - 1])).toBeLessThan(0.01);
+ expect(Math.max(...tone)).toBeGreaterThan(0.25);
+ expect(buildTestTone(CALL_AUDIO_SAMPLE_RATE, 0)).toHaveLength(0);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 74c102bca5..05f4cc7b06 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -75,6 +75,7 @@ export * from './appIdentity.js';
export * from './applyManuscriptEdits.js';
export * from './assessmentTuningNotice.js';
export * from './audioRecorder.js';
+export * from './callAudioBridge.js';
export * from './bareUrl.js';
export * from './boundedMap.js';
export * from './buildStamp.js';
diff --git a/client/src/pages/VoiceCallHost.jsx b/client/src/pages/VoiceCallHost.jsx
new file mode 100644
index 0000000000..a19cdfe31b
--- /dev/null
+++ b/client/src/pages/VoiceCallHost.jsx
@@ -0,0 +1,254 @@
+/**
+ * The FaceTime Audio call host.
+ *
+ * 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.
+ *
+ * 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
+ * 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 socket from '../services/socket';
+import {
+ CALL_FRAME_SAMPLES,
+ CALL_HOST_LOCK,
+ buildTestTone,
+ describeDeviceProblem,
+ downmixToMono,
+ floatToInt16,
+ missingCallHostApis,
+ resampleTo16k,
+ rmsLevel,
+} from '../lib/callAudioBridge';
+
+// A worklet has to be loaded from a URL, and this one is four lines, so it is
+// built from source at runtime rather than carried as a separate build entry.
+// It does no processing: the pure helpers do the downmix/resample/quantize on
+// the main thread, where they can be tested without an audio graph.
+const WORKLET_SOURCE = `
+class CallTapProcessor extends AudioWorkletProcessor {
+ process(inputs) {
+ const channels = inputs[0];
+ if (channels?.length) this.port.postMessage(channels.map((c) => new Float32Array(c)));
+ return true;
+ }
+}
+registerProcessor('portos-call-tap', CallTapProcessor);
+`;
+
+const DEFAULT_INPUT_LABEL = 'BlackHole 16ch';
+const DEFAULT_OUTPUT_LABEL = 'BlackHole 2ch';
+
+export default function VoiceCallHost() {
+ const [blocked, setBlocked] = useState(null);
+ const [attached, setAttached] = useState(false);
+ const [callState, setCallState] = 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: [] });
+ const lockRelease = useRef(null);
+
+ const teardown = useCallback(() => {
+ const current = audio.current;
+ current.node?.port?.close?.();
+ current.node?.disconnect?.();
+ current.source?.disconnect?.();
+ current.stream?.getTracks?.().forEach((track) => track.stop());
+ current.context?.close?.();
+ audio.current = { context: null, stream: null, node: null, source: null, outputId: current.outputId, pending: [] };
+ setLevel(0);
+ }, []);
+
+ // 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.
+ const playToCall = useCallback(async (wav) => {
+ const element = new Audio();
+ const blob = new Blob([wav], { type: 'audio/wav' });
+ element.src = URL.createObjectURL(blob);
+ try {
+ if (audio.current.outputId) await element.setSinkId(audio.current.outputId);
+ await element.play();
+ } catch (error) {
+ setNotice(`Could not play into the call: ${error.message}`);
+ } finally {
+ element.addEventListener('ended', () => URL.revokeObjectURL(element.src), { once: true });
+ }
+ }, []);
+
+ const start = useCallback(async () => {
+ setNotice(null);
+ const missing = missingCallHostApis(window);
+ if (missing.length) {
+ setBlocked(`This browser is missing ${missing.join(', ')}. Use Chrome on the Mac running PortOS.`);
+ return;
+ }
+
+ // 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.
+ //
+ // `locks.request` resolves only when its CALLBACK settles, and holding a
+ // lock means never settling — so awaiting the request itself would hang
+ // here forever while holding the lock. The grant decision is surfaced out
+ // of the callback instead, and the held promise is left open on purpose.
+ const granted = await new Promise((resolve) => {
+ navigator.locks.request(CALL_HOST_LOCK, { ifAvailable: true }, (held) => {
+ if (!held) {
+ resolve(false);
+ return null;
+ }
+ resolve(true);
+ return new Promise((release) => { lockRelease.current = release; });
+ }).catch(() => resolve(false));
+ });
+ if (!granted) {
+ setBlocked('Another tab owns the call host. Close it, or use that tab instead.');
+ return;
+ }
+
+ const devices = await navigator.mediaDevices.enumerateDevices().catch(() => null);
+ const problem = describeDeviceProblem(devices, { inputLabel: DEFAULT_INPUT_LABEL, outputLabel: DEFAULT_OUTPUT_LABEL });
+ 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');
+
+ let stream;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({
+ // Every processing stage is off: this is not a room microphone, it is
+ // the far end of a phone call, and echo cancellation would chew holes
+ // in it. Plain booleans, never `{ exact }`, so a browser that cannot
+ // honour one still opens the device.
+ audio: {
+ deviceId: { exact: input.deviceId },
+ echoCancellation: false,
+ noiseSuppression: false,
+ autoGainControl: false,
+ },
+ });
+ } catch (error) {
+ setBlocked(`Could not open ${DEFAULT_INPUT_LABEL}: ${error.message}`);
+ return;
+ }
+
+ const context = new AudioContext();
+ const url = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }));
+ try {
+ await context.audioWorklet.addModule(url);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ const source = context.createMediaStreamSource(stream);
+ const node = new AudioWorkletNode(context, 'portos-call-tap');
+ let carry = [];
+ node.port.onmessage = (event) => {
+ const mono = downmixToMono(event.data);
+ setLevel(rmsLevel(mono));
+ const resampled = resampleTo16k(mono, context.sampleRate);
+ carry.push(...resampled);
+ // Ship fixed-size frames so the server's endpointer sees a steady
+ // resolution regardless of the render quantum this browser chose.
+ while (carry.length >= CALL_FRAME_SAMPLES) {
+ const pcm = floatToInt16(Float32Array.from(carry.slice(0, CALL_FRAME_SAMPLES)));
+ carry = carry.slice(CALL_FRAME_SAMPLES);
+ socket.emit('voice:call:audio', { pcm: pcm.buffer });
+ }
+ };
+ source.connect(node);
+
+ audio.current = { context, stream, node, source, outputId: output.deviceId, pending: [] };
+ socket.emit('voice:call:attach');
+ setBlocked(null);
+ }, []);
+
+ const stop = useCallback(() => {
+ socket.emit('voice:call:detach');
+ teardown();
+ lockRelease.current?.();
+ lockRelease.current = null;
+ setAttached(false);
+ }, [teardown]);
+
+ useEffect(() => {
+ const onState = (snapshot) => {
+ if (snapshot?.error === 'host-taken') {
+ setBlocked('Another tab owns the call host.');
+ setAttached(false);
+ return;
+ }
+ setCallState(snapshot);
+ setAttached(Boolean(snapshot?.hostAttached));
+ };
+ const onTts = ({ wav }) => { if (wav) playToCall(wav); };
+ socket.on('voice:call:state', onState);
+ socket.on('voice:call:tts', onTts);
+ return () => {
+ socket.off('voice:call:state', onState);
+ socket.off('voice:call:tts', onTts);
+ socket.emit('voice:call:detach');
+ teardown();
+ lockRelease.current?.();
+ lockRelease.current = null;
+ };
+ }, [playToCall, teardown]);
+
+ const playTestTone = async () => {
+ const context = audio.current.context || new AudioContext();
+ const tone = buildTestTone(context.sampleRate, 1);
+ const buffer = context.createBuffer(1, tone.length, context.sampleRate);
+ buffer.copyToChannel(tone, 0);
+ const source = context.createBufferSource();
+ source.buffer = buffer;
+ const destination = context.createMediaStreamDestination();
+ source.connect(destination);
+ const element = new Audio();
+ element.srcObject = destination.stream;
+ if (audio.current.outputId) await element.setSinkId(audio.current.outputId).catch(() => {});
+ await element.play().catch((error) => setNotice(`Test tone failed: ${error.message}`));
+ source.start();
+ };
+
+ 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}.
+ </p>
+ </header>
+
+ {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>
+ </div>
+
+ <div>
+ <p className="mb-1 text-xs text-gray-500" id="call-host-level-label">Input level</p>
+ <div aria-labelledby="call-host-level-label" role="meter" aria-valuenow={Math.round(level * 100)} aria-valuemin={0} aria-valuemax={100} className="h-2 w-full overflow-hidden rounded bg-port-bg">
+ <div className="h-full bg-port-accent transition-[width]" style={{ width: `${Math.min(100, Math.round(level * 140))}%` }} />
+ </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>
+ </section>
+ </div>
+ );
+}
diff --git a/client/src/pages/VoiceCallHost.test.jsx b/client/src/pages/VoiceCallHost.test.jsx
new file mode 100644
index 0000000000..0c35c78b2d
--- /dev/null
+++ b/client/src/pages/VoiceCallHost.test.jsx
@@ -0,0 +1,126 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../services/socket', () => {
+ const handlers = new Map();
+ return {
+ default: {
+ emit: vi.fn(),
+ on: vi.fn((event, fn) => handlers.set(event, fn)),
+ off: vi.fn((event) => handlers.delete(event)),
+ __fire: (event, payload) => handlers.get(event)?.(payload),
+ },
+ };
+});
+
+import socket from '../services/socket';
+import VoiceCallHost from './VoiceCallHost';
+
+const grantCapabilities = () => {
+ vi.stubGlobal('MediaStreamTrackProcessor', function processor() {});
+ vi.stubGlobal('MediaStreamTrackGenerator', function generator() {});
+ vi.stubGlobal('AudioWorkletNode', function worklet() {});
+ window.HTMLMediaElement.prototype.setSinkId = () => Promise.resolve();
+ navigator.mediaDevices = { enumerateDevices: vi.fn(), getUserMedia: vi.fn() };
+ // Mirrors the real API: the returned promise settles with the CALLBACK's
+ // result, so a held lock never resolves it.
+ navigator.locks = { request: vi.fn((_name, _options, fn) => Promise.resolve(fn(true))) };
+};
+
+const devices = [
+ { label: 'BlackHole 16ch', kind: 'audioinput', deviceId: 'in-1' },
+ { label: 'BlackHole 2ch', kind: 'audiooutput', deviceId: 'out-1' },
+];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ grantCapabilities();
+});
+
+afterEach(() => { vi.unstubAllGlobals(); });
+
+describe('VoiceCallHost', () => {
+ it('says nothing reaches PortOS until the host is attached', () => {
+ render(<VoiceCallHost />);
+ expect(screen.getByText(/Not attached — no call audio reaches PortOS/)).toBeTruthy();
+ expect(socket.emit).not.toHaveBeenCalledWith('voice:call:attach');
+ });
+
+ it('names every missing browser API at once instead of one per reload', async () => {
+ vi.stubGlobal('MediaStreamTrackProcessor', undefined);
+ vi.stubGlobal('AudioWorkletNode', undefined);
+ render(<VoiceCallHost />);
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toMatch(/MediaStreamTrackProcessor/);
+ expect(alert.textContent).toMatch(/AudioWorklet/);
+ // Nothing was opened and nothing was claimed on a browser that cannot do it.
+ expect(navigator.mediaDevices.enumerateDevices).not.toHaveBeenCalled();
+ expect(socket.emit).not.toHaveBeenCalledWith('voice:call:attach');
+ });
+
+ 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 />);
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+
+ expect((await screen.findByRole('alert')).textContent).toMatch(/Another tab owns the call host/);
+ expect(navigator.mediaDevices.getUserMedia).not.toHaveBeenCalled();
+ });
+
+ it('reports the specific missing device rather than a generic failure', async () => {
+ navigator.mediaDevices.enumerateDevices.mockResolvedValue([devices[1]]);
+ render(<VoiceCallHost />);
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+
+ expect((await screen.findByRole('alert')).textContent).toMatch(/BlackHole 16ch/);
+ expect(navigator.mediaDevices.getUserMedia).not.toHaveBeenCalled();
+ });
+
+ it('opens the exact device with every processing stage off', async () => {
+ navigator.mediaDevices.enumerateDevices.mockResolvedValue(devices);
+ // 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 />);
+
+ await act(async () => { fireEvent.click(screen.getByText('Attach call host')); });
+
+ await waitFor(() => expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledWith({
+ audio: {
+ deviceId: { exact: 'in-1' },
+ echoCancellation: false,
+ noiseSuppression: false,
+ autoGainControl: false,
+ },
+ }));
+ expect((await screen.findByRole('alert')).textContent).toMatch(/no audio hardware/);
+ });
+
+ it('surfaces the server refusing a second host', async () => {
+ render(<VoiceCallHost />);
+
+ act(() => socket.__fire('voice:call:state', { error: 'host-taken' }));
+
+ expect((await screen.findByRole('alert')).textContent).toMatch(/Another tab owns the call host/);
+ });
+
+ it('reflects live call state once the server reports it attached', async () => {
+ render(<VoiceCallHost />);
+
+ act(() => socket.__fire('voice:call:state', { hostAttached: true, state: 'listening', active: true, turns: 2 }));
+
+ expect(await screen.findByText(/Attached · call listening · 2 turns/)).toBeTruthy();
+ expect(screen.getByText('Detach call host')).toBeTruthy();
+ });
+
+ it('detaches on unmount so a closed tab does not leave a phantom host', () => {
+ const { unmount } = render(<VoiceCallHost />);
+ unmount();
+ expect(socket.emit).toHaveBeenCalledWith('voice:call:detach');
+ });
+});
diff --git a/docs/features/voice.md b/docs/features/voice.md
index 885cf73d76..645c49f941 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -19,6 +19,52 @@ The TTS engine is selectable in **Settings → Voice → TTS engine**.
FaceTime Audio controls are off by default and remain machine-local. On macOS, run `npm run setup:facetime`, grant the installed helper Accessibility permission in System Settings, choose the configured BlackHole devices in FaceTime, then enable **FaceTime Audio** in Settings → Features. Set a target name and E.164 phone number or email in Settings → Voice, save, and use **Probe**, **Test call**, or **Hang up**. The helper refuses ambiguous FaceTime surfaces and never uses coordinate clicks.
+### FaceTime Audio call bridge
+
+The control plane can dial and hang up. Carrying the conversation takes two
+virtual audio devices and a browser tab.
+
+**Devices.** `npm run setup:facetime` offers to run `brew install blackhole-2ch
+blackhole-16ch`. BlackHole is GPLv3 and is never bundled — PortOS asks, you
+install it, and declining is fine (dial and hang up keep working without it).
+In FaceTime, set the **output** to BlackHole 16ch and the **microphone** to
+BlackHole 2ch. Both must run at 48 kHz; **Settings → Voice → Check setup**
+verifies the label, rate, and channel count of each and names the exact problem
+when one is wrong. A device list that cannot be read at all reports that
+plainly rather than claiming the device is missing.
+
+**Call host.** Open **/voice/call-host** in a browser tab on the Mac running
+PortOS and press **Attach call host**. Device permissions and `setSinkId` need
+a real browser profile, so this cannot live on the server. The page reads
+BlackHole 16ch (what FaceTime plays into), streams it to PortOS as 16 kHz mono
+PCM, and plays each reply back through BlackHole 2ch (what FaceTime hears as
+its microphone). An input-level meter and a one-second test tone confirm both
+directions before you rely on them.
+
+The page **fails closed and says why**: a browser missing any required API
+names all of them at once, a missing or misconfigured device is named
+specifically, an unlabeled device list is reported as a missing microphone
+permission rather than a missing driver, and a second tab is refused — it holds
+a Web Lock, and the server refuses a second host independently, so two tabs can
+never double-answer one call.
+
+**Turns.** A phone call has no push-to-talk, so the server decides where a turn
+ends: energy-based voice activity detection with 700 ms of trailing silence and
+a 20-second ceiling per utterance. Each utterance runs the **existing** voice
+pipeline — same persona, tools, confirm gate, and TTS settings as the widget.
+Speaking over a reply interrupts it, exactly as the widget's barge-in does.
+
+**Ending.** The call ends when the caller hangs up, after 60 seconds of caller
+silence, at the configured maximum call length (Settings → Voice, default 15
+minutes), or when the call-host tab goes away — a call nobody can hear is ended
+rather than left running. The helper's own view of the FaceTime window is the
+source of truth throughout: a probe that fails is treated as unknown, never as
+a hangup.
+
+**What is kept.** A text transcript is appended to the daily journal, labelled
+`Caller` and `PortOS`. The call audio is never persisted, and the configured
+handle never appears in the transcript or its metadata.
+
### Why Kokoro is the default
Kokoro 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.
@@ -134,7 +180,12 @@ Barge-in works by aborting the shared `AbortController` tied to the current turn
| GET | `/api/voice/voices` | Voices for the active TTS engine |
| POST | `/api/voice/test` | Body `{ text }`, returns WAV bytes — verifies TTS |
-Socket events are documented in `server/sockets/voice.js`.
+| GET | `/api/voice/facetime/status` | BlackHole device + helper + identity preflight |
+| POST | `/api/voice/facetime/{probe,call,answer,hangup}` | Machine-local call control |
+
+Socket events are documented in `server/sockets/voice.js` — including the
+call-host bridge (`voice:call:attach` / `voice:call:audio` / `voice:call:detach`
+inbound, `voice:call:state` / `voice:call:tts` outbound).
## Troubleshooting
diff --git a/scripts/setup-facetime.js b/scripts/setup-facetime.js
index 2a4ff4f487..4e4df11a7a 100644
--- a/scripts/setup-facetime.js
+++ b/scripts/setup-facetime.js
@@ -1,5 +1,6 @@
import { existsSync, mkdirSync } from 'fs';
import { execFileSync } from 'node:child_process';
+import { createInterface } from 'node:readline/promises';
import { dirname, join } from 'path';
import { homedir } from 'os';
@@ -14,3 +15,29 @@ if (!existsSync(source)) throw new Error('FaceTime helper source is missing');
mkdirSync(dirname(output), { recursive: true });
execFileSync('swiftc', ['-O', source, '-o', output], { stdio: 'inherit' });
console.log('✅ FaceTime Audio helper installed. Grant it Accessibility access before use.');
+
+// BlackHole is GPLv3 and is deliberately NOT bundled: PortOS asks, the user
+// installs it themselves through their own Homebrew. Declining is a supported
+// outcome — the control plane (dial / hang up) works without it; only the
+// two-way audio bridge needs the virtual devices.
+const BREW_ARGS = ['install', 'blackhole-2ch', 'blackhole-16ch'];
+const alreadyInstalled = () => {
+ const probe = execFileSync('system_profiler', ['SPAudioDataType', '-json'], { encoding: 'utf8' });
+ return /blackhole 2ch/i.test(probe) && /blackhole 16ch/i.test(probe);
+};
+
+if (alreadyInstalled()) {
+ console.log('✅ BlackHole 2ch and 16ch are already installed.');
+} else if (!process.stdin.isTTY) {
+ console.log(`ℹ️ Two-way call audio needs BlackHole. Install it yourself with: brew ${BREW_ARGS.join(' ')}`);
+} else {
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ const answer = (await rl.question(`Install BlackHole virtual audio devices (GPLv3, via Homebrew)?\n brew ${BREW_ARGS.join(' ')}\nRun it now? [y/N] `)).trim().toLowerCase();
+ rl.close();
+ if (answer === 'y' || answer === 'yes') {
+ execFileSync('brew', BREW_ARGS, { stdio: 'inherit' });
+ console.log('✅ BlackHole installed. In FaceTime, set output to BlackHole 16ch and microphone to BlackHole 2ch.');
+ } else {
+ console.log(`ℹ️ Skipped. Two-way call audio stays unavailable until you run: brew ${BREW_ARGS.join(' ')}`);
+ }
+}
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 305392cb07..2a1a210a3b 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -22183,7 +22183,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 130
+ "line": 131
}
]
},
@@ -22194,7 +22194,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 135
+ "line": 136
}
]
},
@@ -22205,7 +22205,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 181
+ "line": 182
}
]
},
@@ -22216,7 +22216,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 201
+ "line": 202
}
]
},
@@ -22260,7 +22260,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 253
+ "line": 254
}
]
},
@@ -22271,7 +22271,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 164
+ "line": 165
}
]
},
@@ -22282,7 +22282,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 214
+ "line": 215
}
]
},
@@ -22293,7 +22293,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 279
+ "line": 280
}
]
},
@@ -22304,7 +22304,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 291
+ "line": 292
}
]
},
@@ -22315,7 +22315,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 195
+ "line": 196
}
]
},
@@ -22326,7 +22326,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 303
+ "line": 304
}
]
},
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 46cfa3b169..f1ec155ed4 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -333,6 +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.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.json
index dff2495778..50568bacf3 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": 353
+ "line": 469
}
]
},
@@ -4523,6 +4523,106 @@
}
]
},
+ {
+ "event": "voice:call:attach",
+ "directions": [
+ "client-to-server"
+ ],
+ "sources": [
+ {
+ "direction": "client-to-server",
+ "source": "client/src/pages/VoiceCallHost.jsx",
+ "line": 169
+ },
+ {
+ "direction": "client-to-server",
+ "source": "server/sockets/voice.js",
+ "line": 418
+ }
+ ]
+ },
+ {
+ "event": "voice:call:audio",
+ "directions": [
+ "client-to-server"
+ ],
+ "sources": [
+ {
+ "direction": "client-to-server",
+ "source": "client/src/pages/VoiceCallHost.jsx",
+ "line": 163
+ },
+ {
+ "direction": "client-to-server",
+ "source": "server/sockets/voice.js",
+ "line": 437
+ }
+ ]
+ },
+ {
+ "event": "voice:call:detach",
+ "directions": [
+ "client-to-server"
+ ],
+ "sources": [
+ {
+ "direction": "client-to-server",
+ "source": "client/src/pages/VoiceCallHost.jsx",
+ "line": 174
+ },
+ {
+ "direction": "client-to-server",
+ "source": "client/src/pages/VoiceCallHost.jsx",
+ "line": 197
+ },
+ {
+ "direction": "client-to-server",
+ "source": "server/sockets/voice.js",
+ "line": 464
+ }
+ ]
+ },
+ {
+ "event": "voice:call:state",
+ "directions": [
+ "server-to-client"
+ ],
+ "sources": [
+ {
+ "direction": "server-to-client",
+ "source": "client/src/pages/VoiceCallHost.jsx",
+ "line": 192
+ },
+ {
+ "direction": "server-to-client",
+ "source": "server/sockets/voice.js",
+ "line": 384
+ },
+ {
+ "direction": "server-to-client",
+ "source": "server/sockets/voice.js",
+ "line": 425
+ }
+ ]
+ },
+ {
+ "event": "voice:call:tts",
+ "directions": [
+ "server-to-client"
+ ],
+ "sources": [
+ {
+ "direction": "server-to-client",
+ "source": "client/src/pages/VoiceCallHost.jsx",
+ "line": 193
+ },
+ {
+ "direction": "server-to-client",
+ "source": "server/sockets/voice.js",
+ "line": 401
+ }
+ ]
+ },
{
"event": "voice:dictation",
"directions": [
@@ -4537,17 +4637,17 @@
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 224
+ "line": 244
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 248
+ "line": 268
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 253
+ "line": 273
}
]
},
@@ -4570,7 +4670,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 241
+ "line": 261
}
]
},
@@ -4588,57 +4688,67 @@
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 132
+ "line": 152
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 145
+ "line": 165
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 154
+ "line": 174
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 159
+ "line": 179
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 163
+ "line": 183
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 179
+ "line": 199
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 188
+ "line": 208
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 193
+ "line": 213
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 197
+ "line": 217
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 203
+ "line": 223
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 256
+ "line": 276
+ },
+ {
+ "direction": "server-to-client",
+ "source": "server/sockets/voice.js",
+ "line": 411
+ },
+ {
+ "direction": "server-to-client",
+ "source": "server/sockets/voice.js",
+ "line": 433
}
]
},
@@ -4656,24 +4766,25 @@
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 133
+ "line": 153
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 213
+ "line": 233
},
{
"direction": "server-to-client",
"source": "server/sockets/voice.js",
- "line": 225
+ "line": 245
}
]
},
{
"event": "voice:interrupt",
"directions": [
- "client-to-server"
+ "client-to-server",
+ "server-to-client"
],
"sources": [
{
@@ -4699,7 +4810,12 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 207
+ "line": 227
+ },
+ {
+ "direction": "server-to-client",
+ "source": "server/sockets/voice.js",
+ "line": 453
}
]
},
@@ -4717,7 +4833,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 341
+ "line": 361
}
]
},
@@ -4735,7 +4851,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 349
+ "line": 369
}
]
},
@@ -4784,7 +4900,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 216
+ "line": 236
}
]
},
@@ -4802,7 +4918,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 301
+ "line": 321
}
]
},
@@ -4838,7 +4954,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 183
+ "line": 203
}
]
},
@@ -4887,7 +5003,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 149
+ "line": 169
}
]
},
@@ -4905,7 +5021,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 264
+ "line": 284
}
]
},
@@ -4936,7 +5052,7 @@
{
"direction": "client-to-server",
"source": "server/sockets/voice.js",
- "line": 319
+ "line": 339
}
]
},
@@ -4960,10 +5076,10 @@
}
],
"stats": {
- "events": 253,
- "clientToServer": 56,
- "serverToClient": 205,
- "bidirectional": 8,
- "sourceFiles": 103
+ "events": 258,
+ "clientToServer": 59,
+ "serverToClient": 208,
+ "bidirectional": 9,
+ "sourceFiles": 104
}
}
diff --git a/server/routes/voice.js b/server/routes/voice.js
index 7da8a5a2f8..318e16b4ab 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -41,6 +41,7 @@ const voiceConfigPatchSchema = z.object({
trigger: z.enum(['push-to-talk', 'hotword', 'vad']).optional(),
hotkey: z.string().max(32).optional(),
facetime: z.object({
+ maxCallMinutes: z.number().int().min(1).max(120).optional(),
targetHandle: z.string().trim().max(254).refine((value) => value === '' || /^\+?[1-9]\d{6,14}$/.test(value) || z.string().email().safeParse(value).success, 'Must be an E.164 phone number or email address').optional(),
targetName: z.string().trim().max(120).optional(),
blackHole2chLabel: z.string().trim().min(1).max(120).optional(),
diff --git a/server/services/voice/callEndpointing.js b/server/services/voice/callEndpointing.js
new file mode 100644
index 0000000000..04583bbffa
--- /dev/null
+++ b/server/services/voice/callEndpointing.js
@@ -0,0 +1,148 @@
+/**
+ * Turn a continuous PCM stream from the call host into discrete utterances.
+ *
+ * A browser microphone turn is bounded by the user releasing push-to-talk. A
+ * phone call has no such signal, so the server has to decide where one turn
+ * ends: energy-based voice activity detection plus a trailing-silence timeout.
+ *
+ * Time is derived from the SAMPLE COUNT, never a wall clock — a stream that
+ * arrives in bursts (a delayed socket flush) must endpoint exactly where a
+ * smoothly-paced one would, and it makes the whole contract testable with
+ * synthetic PCM and no sleeping.
+ */
+
+export const CALL_AUDIO_SAMPLE_RATE = 16_000;
+
+export const ENDPOINTING_DEFAULTS = Object.freeze({
+ sampleRate: CALL_AUDIO_SAMPLE_RATE,
+ // Trailing silence that ends a turn. Long enough to survive a mid-sentence
+ // breath, short enough that the reply does not feel late.
+ silenceMs: 700,
+ // Hard ceiling on one utterance, so a held-open line or a noisy room cannot
+ // buffer without bound.
+ maxUtteranceMs: 20_000,
+ // Below this RMS (0..1) a frame is silence. Call audio arrives through a
+ // virtual device with no gain staging, so this is deliberately low.
+ rmsThreshold: 0.015,
+ // Utterances shorter than this are a cough or a line click, not speech.
+ minUtteranceMs: 250,
+ // Audio kept from just BEFORE speech was detected, so the first consonant
+ // is not clipped off the front of the transcript.
+ preRollMs: 200,
+});
+
+const msToSamples = (ms, sampleRate) => Math.max(1, Math.round((ms / 1000) * sampleRate));
+const samplesToMs = (samples, sampleRate) => Math.round((samples / sampleRate) * 1000);
+
+/** Root-mean-square level of Int16 PCM, normalized to 0..1. */
+export function pcmRms(samples) {
+ if (!samples?.length) return 0;
+ let sum = 0;
+ for (let index = 0; index < samples.length; index += 1) {
+ const value = samples[index] / 32768;
+ sum += value * value;
+ }
+ return Math.sqrt(sum / samples.length);
+}
+
+/** Int16 PCM → Float32 in -1..1, the shape `pcmToWavBuffer` expects. */
+export function pcmToFloat(samples) {
+ const floats = new Float32Array(samples.length);
+ for (let index = 0; index < samples.length; index += 1) floats[index] = samples[index] / 32768;
+ return floats;
+}
+
+const concat = (chunks, length) => {
+ const merged = new Int16Array(length);
+ let offset = 0;
+ for (const chunk of chunks) {
+ merged.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return merged;
+};
+
+/**
+ * Create a stateful endpointer.
+ *
+ * `push(chunk)` returns a completed utterance or `null`. Every chunk is
+ * classified whole, so the caller controls the resolution by choosing its
+ * chunk size (the call host sends ~20 ms frames).
+ */
+export function createCallEndpointer(options = {}) {
+ const config = { ...ENDPOINTING_DEFAULTS, ...options };
+ const silenceSamples = msToSamples(config.silenceMs, config.sampleRate);
+ const maxSamples = msToSamples(config.maxUtteranceMs, config.sampleRate);
+ const minSamples = msToSamples(config.minUtteranceMs, config.sampleRate);
+ const preRollSamples = msToSamples(config.preRollMs, config.sampleRate);
+
+ let speaking = false;
+ let voiced = [];
+ let voicedLength = 0;
+ let trailingSilence = 0;
+ // Rolling pre-roll buffer, only kept while NOT speaking.
+ let preRoll = [];
+ let preRollLength = 0;
+
+ const reset = () => {
+ speaking = false;
+ voiced = [];
+ voicedLength = 0;
+ trailingSilence = 0;
+ preRoll = [];
+ preRollLength = 0;
+ };
+
+ const finish = (reason) => {
+ // Trailing silence is dropped from the audio but not from the decision —
+ // it is what ended the turn, and shipping it to STT only adds latency.
+ const keep = reason === 'silence' ? Math.max(0, voicedLength - trailingSilence) : voicedLength;
+ const merged = concat(voiced, voicedLength).subarray(0, keep);
+ reset();
+ if (merged.length < minSamples) return null;
+ return { pcm: merged, durationMs: samplesToMs(merged.length, config.sampleRate), reason };
+ };
+
+ return {
+ get speaking() { return speaking; },
+
+ push(chunk) {
+ if (!chunk?.length) return null;
+ const loud = pcmRms(chunk) >= config.rmsThreshold;
+
+ if (!speaking) {
+ if (!loud) {
+ // Keep only the tail: an idle line must not grow a buffer.
+ preRoll.push(chunk);
+ preRollLength += chunk.length;
+ while (preRollLength - preRoll[0].length >= preRollSamples) {
+ preRollLength -= preRoll.shift().length;
+ }
+ return null;
+ }
+ speaking = true;
+ voiced = preRoll;
+ voicedLength = preRollLength;
+ preRoll = [];
+ preRollLength = 0;
+ }
+
+ voiced.push(chunk);
+ voicedLength += chunk.length;
+ trailingSilence = loud ? 0 : trailingSilence + chunk.length;
+
+ if (trailingSilence >= silenceSamples) return finish('silence');
+ // The ceiling is checked last so a turn that both fell silent and hit the
+ // cap on the same chunk is reported as the ordinary silence endpoint.
+ if (voicedLength >= maxSamples) return finish('max-duration');
+ return null;
+ },
+
+ /** End whatever is buffered — the call dropped or the host detached. */
+ flush() {
+ return speaking ? finish('flush') : null;
+ },
+
+ reset,
+ };
+}
diff --git a/server/services/voice/callEndpointing.test.js b/server/services/voice/callEndpointing.test.js
new file mode 100644
index 0000000000..85567fa7ee
--- /dev/null
+++ b/server/services/voice/callEndpointing.test.js
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest';
+import {
+ CALL_AUDIO_SAMPLE_RATE,
+ ENDPOINTING_DEFAULTS,
+ createCallEndpointer,
+ pcmRms,
+ pcmToFloat,
+} from './callEndpointing.js';
+
+// 20 ms frames, the size the call host ships.
+const FRAME = Math.round(CALL_AUDIO_SAMPLE_RATE * 0.02);
+
+const frame = (amplitude) => {
+ const pcm = new Int16Array(FRAME);
+ // A square wave keeps RMS equal to the amplitude, so a case can state the
+ // level it means instead of a number that happens to work.
+ for (let index = 0; index < FRAME; index += 1) pcm[index] = index % 2 ? amplitude : -amplitude;
+ return pcm;
+};
+const speech = () => frame(8000);
+const silence = () => frame(0);
+const framesFor = (ms) => Math.ceil(ms / 20);
+
+const feed = (endpointer, chunks) => {
+ const results = [];
+ for (const chunk of chunks) {
+ const utterance = endpointer.push(chunk);
+ if (utterance) results.push(utterance);
+ }
+ return results;
+};
+
+describe('call endpointing', () => {
+ it('measures level and converts to the float PCM the WAV encoder takes', () => {
+ expect(pcmRms(silence())).toBe(0);
+ expect(pcmRms(speech())).toBeCloseTo(8000 / 32768, 4);
+ expect(pcmRms(new Int16Array(0))).toBe(0);
+
+ const floats = pcmToFloat(Int16Array.from([0, 16384, -16384]));
+ expect(Array.from(floats)).toEqual([0, 0.5, -0.5]);
+ });
+
+ it('ends a turn after the configured trailing silence, not before', () => {
+ const endpointer = createCallEndpointer();
+ const speechFrames = Array.from({ length: framesFor(600) }, speech);
+
+ // One frame short of the silence window: still listening.
+ const early = feed(endpointer, [...speechFrames, ...Array.from({ length: framesFor(ENDPOINTING_DEFAULTS.silenceMs) - 1 }, silence)]);
+ expect(early).toHaveLength(0);
+ expect(endpointer.speaking).toBe(true);
+
+ const [utterance] = feed(endpointer, [silence()]);
+ expect(utterance.reason).toBe('silence');
+ expect(endpointer.speaking).toBe(false);
+ // The trailing silence is dropped, the leading pre-roll is kept.
+ expect(utterance.durationMs).toBeGreaterThanOrEqual(600);
+ expect(utterance.durationMs).toBeLessThan(600 + ENDPOINTING_DEFAULTS.silenceMs);
+ });
+
+ it('keeps pre-roll so the first consonant is not clipped', () => {
+ const endpointer = createCallEndpointer();
+ // A long idle stretch must not grow the buffer beyond the pre-roll window.
+ feed(endpointer, Array.from({ length: framesFor(10_000) }, silence));
+ const [utterance] = feed(endpointer, [
+ ...Array.from({ length: framesFor(400) }, speech),
+ ...Array.from({ length: framesFor(ENDPOINTING_DEFAULTS.silenceMs) }, silence),
+ ]);
+
+ expect(utterance.durationMs).toBeGreaterThan(400);
+ expect(utterance.durationMs).toBeLessThanOrEqual(400 + ENDPOINTING_DEFAULTS.preRollMs + 20);
+ });
+
+ it('caps one utterance so a held-open line cannot buffer without bound', () => {
+ const endpointer = createCallEndpointer();
+ const [utterance] = feed(endpointer, Array.from({ length: framesFor(30_000) }, speech));
+
+ expect(utterance.reason).toBe('max-duration');
+ expect(utterance.durationMs).toBeGreaterThanOrEqual(ENDPOINTING_DEFAULTS.maxUtteranceMs);
+ expect(utterance.durationMs).toBeLessThan(ENDPOINTING_DEFAULTS.maxUtteranceMs + 100);
+ });
+
+ it('drops a click too short to be speech', () => {
+ const endpointer = createCallEndpointer({ preRollMs: 0 });
+ const results = feed(endpointer, [
+ speech(),
+ ...Array.from({ length: framesFor(ENDPOINTING_DEFAULTS.silenceMs) }, silence),
+ ]);
+
+ expect(results).toHaveLength(0);
+ expect(endpointer.speaking).toBe(false);
+ });
+
+ it('endpoints identically whether audio arrives smoothly or in one burst', () => {
+ // A delayed socket flush must not move the turn boundary — the reason the
+ // decision is driven by sample count rather than arrival time.
+ const chunks = [
+ ...Array.from({ length: framesFor(500) }, speech),
+ ...Array.from({ length: framesFor(ENDPOINTING_DEFAULTS.silenceMs) }, silence),
+ ];
+ const smooth = feed(createCallEndpointer(), chunks);
+ const burst = feed(createCallEndpointer(), [
+ new Int16Array(chunks.slice(0, framesFor(500)).flatMap((c) => Array.from(c))),
+ new Int16Array(chunks.slice(framesFor(500)).flatMap((c) => Array.from(c))),
+ ]);
+
+ expect(burst[0].durationMs).toBe(smooth[0].durationMs);
+ expect(burst[0].reason).toBe(smooth[0].reason);
+ });
+
+ it('flushes buffered speech when the call drops mid-sentence', () => {
+ const endpointer = createCallEndpointer();
+ feed(endpointer, Array.from({ length: framesFor(500) }, speech));
+
+ const flushed = endpointer.flush();
+ expect(flushed.reason).toBe('flush');
+ expect(endpointer.speaking).toBe(false);
+ // A second flush has nothing left to report.
+ expect(endpointer.flush()).toBeNull();
+ });
+
+ it('reports nothing for an idle line', () => {
+ const endpointer = createCallEndpointer();
+ expect(feed(endpointer, Array.from({ length: framesFor(5_000) }, silence))).toHaveLength(0);
+ expect(endpointer.flush()).toBeNull();
+ expect(endpointer.push(new Int16Array(0))).toBeNull();
+ });
+});
diff --git a/server/services/voice/callSession.js b/server/services/voice/callSession.js
new file mode 100644
index 0000000000..3516cfb77b
--- /dev/null
+++ b/server/services/voice/callSession.js
@@ -0,0 +1,244 @@
+/**
+ * The one active FaceTime Audio call.
+ *
+ * Phase 1 gave PortOS a control plane that can dial and hang up; the call-host
+ * page gives it ears and a mouth. This module owns the state in between: which
+ * call is up, whether anyone can hear it, when to give up, and what is written
+ * down afterwards.
+ *
+ * Three deliberate constraints:
+ *
+ * - **One call, one host.** A second call-host tab is refused rather than
+ * allowed to double-answer, mirroring the single-attach shell-session
+ * pattern. Without an attached host there is no call, because a call nobody
+ * can hear is worse than no call at all.
+ * - **The helper is the source of truth.** State follows what `probe()` reports
+ * about the real FaceTime window, not what PortOS believes it asked for — a
+ * call the user picked up or declined on their phone has to be observed.
+ * - **Only text is kept.** The transcript goes to the daily journal like any
+ * other voice turn. The audio is never persisted, and the configured handle
+ * never appears in what is written down.
+ */
+
+import { appendJournal, getToday } from '../brainJournal.js';
+import * as facetimeBridge from './facetimeBridge.js';
+import { getVoiceConfig } from './config.js';
+
+export const CALL_STATES = ['idle', 'dialing', 'connected', 'listening', 'speaking', 'ended'];
+export const PROBE_INTERVAL_MS = 2_000;
+// A caller who has said nothing for this long has walked away or hung up
+// somewhere PortOS cannot see.
+export const SILENCE_HANGUP_MS = 60_000;
+const DEFAULT_MAX_CALL_MINUTES = 15;
+
+const initialState = () => ({
+ state: 'idle',
+ startedAt: null,
+ lastVoiceAt: null,
+ endedReason: null,
+ transcript: [],
+});
+
+let session = initialState();
+let host = null;
+let timer = null;
+let listener = null;
+
+// Injectable so the state machine can be driven with stubs and fake timers
+// instead of a real helper and a real call.
+let deps = { probe: facetimeBridge.probe, call: facetimeBridge.call, hangup: facetimeBridge.hangup, appendJournal, now: Date.now };
+
+/** Test seam — override the helper/clock, or restore the real ones. */
+export const __setCallSessionDeps = (overrides = {}) => {
+ deps = { probe: facetimeBridge.probe, call: facetimeBridge.call, hangup: facetimeBridge.hangup, appendJournal, now: Date.now, ...overrides };
+};
+
+const publicState = () => ({
+ state: session.state,
+ active: session.state !== 'idle' && session.state !== 'ended',
+ hostAttached: Boolean(host),
+ startedAt: session.startedAt,
+ endedReason: session.endedReason,
+ turns: session.transcript.length,
+});
+
+const emitState = () => {
+ const snapshot = publicState();
+ // The host page and the Mind tab both render call state, so it is broadcast
+ // rather than replied to whoever last acted.
+ try {
+ listener?.(snapshot);
+ } catch (error) {
+ console.error(`❌ voice call: state listener failed: ${error.message}`);
+ }
+ return snapshot;
+};
+
+/** Register the sink for `voice:call:state` broadcasts. */
+export const setCallStateListener = (fn) => { listener = fn; };
+
+export const getCallState = () => publicState();
+export const getCallHost = () => host;
+export const isCallActive = () => publicState().active;
+
+/**
+ * Claim the single call-host slot.
+ *
+ * Returns `{ ok: false, reason: 'host-taken' }` rather than displacing the
+ * incumbent: two tabs reading the same BlackHole device would each answer, and
+ * the loser would have no way to know it had been silently muted.
+ */
+export function attachHost(socket) {
+ if (host && host !== socket && host.connected !== false) return { ok: false, reason: 'host-taken' };
+ host = socket;
+ console.log(`📞 voice call: host attached (${socket?.id ?? 'socket'})`);
+ return { ok: true, state: emitState() };
+}
+
+export async function detachHost(socket) {
+ if (host !== socket) return publicState();
+ host = null;
+ console.log('📞 voice call: host detached');
+ // Losing the host loses the audio path, so an in-flight call is ended rather
+ // than left running deaf.
+ if (publicState().active) return endCall('host-detached');
+ return emitState();
+}
+
+const stopPolling = () => {
+ if (timer) clearInterval(timer);
+ timer = null;
+};
+
+const setState = (next) => {
+ if (session.state === next) return publicState();
+ session.state = next;
+ return emitState();
+};
+
+const maxCallMs = async () => {
+ const config = await getVoiceConfig();
+ const minutes = Number(config?.facetime?.maxCallMinutes);
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_MAX_CALL_MINUTES) * 60_000;
+};
+
+/**
+ * One poll tick: reconcile with the helper, then apply the give-up rules.
+ *
+ * Exported so a test can step the machine deterministically rather than
+ * racing a real interval.
+ */
+export async function pollCall() {
+ if (!publicState().active) return publicState();
+
+ let observed = null;
+ try {
+ observed = await deps.probe();
+ } catch (error) {
+ // A helper that cannot answer is not evidence the call ended, so the poll
+ // is skipped rather than treated as a hangup.
+ console.error(`❌ voice call: probe failed: ${error.message}`);
+ return publicState();
+ }
+
+ if (observed?.state === 'ended' || observed?.state === 'idle') return endCall('remote-hangup');
+ if (observed?.state === 'connected' && session.state === 'dialing') setState('listening');
+
+ const now = deps.now();
+ if (now - (session.lastVoiceAt ?? session.startedAt) >= SILENCE_HANGUP_MS) return endCall('caller-silent');
+ if (now - session.startedAt >= await maxCallMs()) return endCall('max-duration');
+ return publicState();
+}
+
+const startPolling = () => {
+ stopPolling();
+ timer = setInterval(() => {
+ // Runs outside the request lifecycle: an unhandled rejection here would
+ // take the process down rather than reach error middleware.
+ pollCall().catch((error) => console.error(`❌ voice call: poll failed: ${error.message}`));
+ }, PROBE_INTERVAL_MS);
+ timer.unref?.();
+};
+
+/**
+ * Place a call. Fails closed when nothing can carry the audio.
+ */
+export async function startCall({ openingLine = '', context = null } = {}) {
+ if (!host) return { ok: false, reason: 'no-call-host' };
+ if (publicState().active) return { ok: false, reason: 'call-in-progress' };
+
+ session = { ...initialState(), state: 'dialing', startedAt: deps.now(), lastVoiceAt: deps.now() };
+ emitState();
+ try {
+ await deps.call();
+ } catch (error) {
+ session.endedReason = 'dial-failed';
+ setState('idle');
+ return { ok: false, reason: 'dial-failed', message: error.message };
+ }
+ startPolling();
+ return { ok: true, state: publicState(), openingLine, context };
+}
+
+/** Record one side of the conversation. Speaker labels only — never the handle. */
+export function recordTurn(speaker, text) {
+ const trimmed = (text || '').trim();
+ if (!trimmed || !publicState().active) return publicState();
+ session.transcript.push({ speaker: speaker === 'assistant' ? 'assistant' : 'caller', text: trimmed });
+ if (speaker !== 'assistant') session.lastVoiceAt = deps.now();
+ return publicState();
+}
+
+/** The caller started talking — used for barge-in and the silence timer. */
+export function noteCallerSpeech() {
+ if (!publicState().active) return publicState();
+ session.lastVoiceAt = deps.now();
+ return publicState();
+}
+
+export const markSpeaking = () => (publicState().active ? setState('speaking') : publicState());
+export const markListening = () => (publicState().active ? setState('listening') : publicState());
+
+const renderTranscript = (transcript) => transcript
+ .map((turn) => `${turn.speaker === 'assistant' ? 'PortOS' : 'Caller'}: ${turn.text}`)
+ .join('\n');
+
+/**
+ * End the call and write the transcript down.
+ *
+ * The journal append is best-effort: a failed write must not leave the session
+ * stuck `connected`, because the state is what gates placing the next call.
+ */
+export async function endCall(reason = 'ended') {
+ if (session.state === 'idle') return publicState();
+ stopPolling();
+ const transcript = session.transcript;
+ session.endedReason = reason;
+ setState('ended');
+
+ try {
+ await deps.hangup();
+ } catch (error) {
+ console.error(`❌ voice call: hangup failed: ${error.message}`);
+ }
+
+ if (transcript.length) {
+ try {
+ await deps.appendJournal(getToday(), `FaceTime Audio call\n${renderTranscript(transcript)}`, { source: 'voice' });
+ } catch (error) {
+ console.error(`❌ voice call: journal append failed: ${error.message}`);
+ }
+ }
+
+ session = { ...initialState(), endedReason: reason };
+ return emitState();
+}
+
+/** Test helper — drop all state between cases. */
+export const __resetCallSession = () => {
+ stopPolling();
+ session = initialState();
+ host = null;
+ listener = null;
+ __setCallSessionDeps();
+};
diff --git a/server/services/voice/callSession.test.js b/server/services/voice/callSession.test.js
new file mode 100644
index 0000000000..482b4af73d
--- /dev/null
+++ b/server/services/voice/callSession.test.js
@@ -0,0 +1,260 @@
+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
+
+vi.mock('./config.js', () => ({ getVoiceConfig: vi.fn() }));
+vi.mock('../brainJournal.js', () => ({ appendJournal: vi.fn(), getToday: () => '2026-08-29' }));
+vi.mock('./facetimeBridge.js', () => ({ probe: vi.fn(), call: vi.fn(), hangup: vi.fn() }));
+
+import { getVoiceConfig } from './config.js';
+import {
+ PROBE_INTERVAL_MS,
+ SILENCE_HANGUP_MS,
+ __resetCallSession,
+ __setCallSessionDeps,
+ attachHost,
+ detachHost,
+ endCall,
+ getCallState,
+ markSpeaking,
+ noteCallerSpeech,
+ pollCall,
+ recordTurn,
+ setCallStateListener,
+ startCall,
+} from './callSession.js';
+
+const socket = (id = 'host-1') => ({ id, connected: true, emit: vi.fn() });
+
+let clock;
+let probe;
+let call;
+let hangup;
+let appendJournal;
+
+const install = (overrides = {}) => {
+ clock = 1_000_000;
+ probe = vi.fn().mockResolvedValue({ state: 'connected' });
+ call = vi.fn().mockResolvedValue({ state: 'dialing' });
+ hangup = vi.fn().mockResolvedValue({ state: 'ended' });
+ appendJournal = vi.fn().mockResolvedValue({});
+ __setCallSessionDeps({ probe, call, hangup, appendJournal, now: () => clock, ...overrides });
+};
+
+beforeEach(() => {
+ __resetCallSession();
+ install();
+ getVoiceConfig.mockResolvedValue({ facetime: { maxCallMinutes: 15 } });
+});
+
+afterEach(() => { __resetCallSession(); });
+
+describe('FaceTime call session', () => {
+ it('refuses to dial without an attached call host', async () => {
+ // A call nobody can hear is worse than no call: this is the fail-closed
+ // gate, not a convenience check.
+ expect(await startCall()).toEqual({ ok: false, reason: 'no-call-host' });
+ expect(call).not.toHaveBeenCalled();
+ expect(getCallState()).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(attachHost(first)).toMatchObject({ ok: true });
+ expect(attachHost(socket('host-2'))).toEqual({ ok: false, reason: 'host-taken' });
+ // Re-attaching the incumbent is a reconnect, not a second owner.
+ expect(attachHost(first)).toMatchObject({ ok: true });
+ });
+
+ it('reaches connected through a probe, not through what it asked for', async () => {
+ attachHost(socket());
+ probe.mockResolvedValue({ state: 'dialing' });
+
+ expect(await startCall({ openingLine: 'Hi' })).toMatchObject({ ok: true, openingLine: 'Hi' });
+ expect(getCallState().state).toBe('dialing');
+
+ // Still ringing: the helper has not seen a pickup, so neither has PortOS.
+ await pollCall();
+ expect(getCallState().state).toBe('dialing');
+
+ probe.mockResolvedValue({ state: 'connected' });
+ await pollCall();
+ expect(getCallState()).toMatchObject({ state: 'listening', active: true });
+ });
+
+ it('refuses a second call while one is up', async () => {
+ attachHost(socket());
+ await startCall();
+ expect(await startCall()).toEqual({ ok: false, reason: 'call-in-progress' });
+ expect(call).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports a failed dial without leaving the session stuck dialing', async () => {
+ attachHost(socket());
+ call.mockRejectedValue(new Error('helper timed out'));
+
+ expect(await startCall()).toMatchObject({ ok: false, reason: 'dial-failed', message: 'helper timed out' });
+ expect(getCallState()).toMatchObject({ state: 'idle', active: false });
+ });
+
+ it('treats a probe failure as unknown, never as a hangup', async () => {
+ attachHost(socket());
+ await startCall();
+ probe.mockRejectedValue(new Error('helper crashed'));
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await pollCall();
+
+ expect(getCallState().active).toBe(true);
+ expect(hangup).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ it('ends when the caller hangs up on their own device', async () => {
+ attachHost(socket());
+ await startCall();
+ probe.mockResolvedValue({ state: 'ended' });
+
+ await pollCall();
+
+ expect(getCallState()).toMatchObject({ state: 'idle', active: false, endedReason: 'remote-hangup' });
+ });
+
+ it('hangs up after the caller has been silent, measuring from the last thing they said', async () => {
+ attachHost(socket());
+ await startCall();
+
+ clock += SILENCE_HANGUP_MS - 1_000;
+ recordTurn('caller', 'Still here');
+ await pollCall();
+ expect(getCallState().active).toBe(true);
+
+ clock += SILENCE_HANGUP_MS;
+ await pollCall();
+ expect(getCallState().endedReason).toBe('caller-silent');
+ });
+
+ it('hangs up at the configured ceiling even on a talkative call', async () => {
+ getVoiceConfig.mockResolvedValue({ facetime: { maxCallMinutes: 2 } });
+ attachHost(socket());
+ await startCall();
+
+ for (let elapsed = 0; elapsed < 3 * 60_000; elapsed += 10_000) {
+ clock += 10_000;
+ noteCallerSpeech();
+ await pollCall();
+ }
+
+ expect(getCallState().endedReason).toBe('max-duration');
+ expect(hangup).toHaveBeenCalled();
+ });
+
+ it.each([
+ ['an absent setting', {}],
+ ['a nonsense setting', { maxCallMinutes: 0 }],
+ ])('falls back to the 15-minute default for %s', async (_label, facetime) => {
+ getVoiceConfig.mockResolvedValue({ facetime });
+ attachHost(socket());
+ await startCall();
+
+ clock += 14 * 60_000;
+ noteCallerSpeech();
+ await pollCall();
+ expect(getCallState().active).toBe(true);
+
+ clock += 2 * 60_000;
+ noteCallerSpeech();
+ await pollCall();
+ expect(getCallState().endedReason).toBe('max-duration');
+ });
+
+ it('writes the transcript to the journal with speaker labels and no handle', async () => {
+ attachHost(socket());
+ await startCall();
+ recordTurn('caller', 'What is on my calendar?');
+ markSpeaking();
+ recordTurn('assistant', 'Two meetings this afternoon.');
+
+ await endCall('remote-hangup');
+
+ expect(appendJournal).toHaveBeenCalledWith(
+ '2026-08-29',
+ 'FaceTime Audio call\nCaller: What is on my calendar?\nPortOS: Two meetings this afternoon.',
+ { source: 'voice' },
+ );
+ });
+
+ it('writes nothing for a call where no one said anything', async () => {
+ attachHost(socket());
+ await startCall();
+
+ await endCall('caller-silent');
+
+ expect(appendJournal).not.toHaveBeenCalled();
+ });
+
+ it('still resets when the journal write fails', async () => {
+ attachHost(socket());
+ await startCall();
+ recordTurn('caller', 'Hello');
+ appendJournal.mockRejectedValue(new Error('disk full'));
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await endCall('remote-hangup');
+
+ // A failed write must not leave the session `active`, or no further call
+ // could ever be placed.
+ expect(getCallState()).toMatchObject({ state: 'idle', active: false });
+ consoleError.mockRestore();
+ });
+
+ it('ends the call when the host tab goes away', async () => {
+ const tab = socket();
+ attachHost(tab);
+ await startCall();
+
+ await detachHost(tab);
+
+ expect(getCallState()).toMatchObject({ hostAttached: false, active: false, endedReason: 'host-detached' });
+ expect(hangup).toHaveBeenCalled();
+ });
+
+ it('ignores a detach from a tab that never owned the slot', async () => {
+ const owner = socket('host-1');
+ attachHost(owner);
+ await startCall();
+
+ await detachHost(socket('host-2'));
+
+ expect(getCallState()).toMatchObject({ hostAttached: true, active: true });
+ });
+
+ it('broadcasts every state change to the registered listener', async () => {
+ const states = [];
+ setCallStateListener((snapshot) => states.push(snapshot.state));
+ attachHost(socket());
+ await startCall();
+ await pollCall();
+ await endCall('remote-hangup');
+
+ expect(states).toContain('dialing');
+ expect(states).toContain('listening');
+ expect(states).toContain('ended');
+ });
+
+ it('survives a listener that throws', async () => {
+ setCallStateListener(() => { throw new Error('socket gone'); });
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ attachHost(socket());
+
+ expect(await startCall()).toMatchObject({ ok: true });
+ consoleError.mockRestore();
+ });
+
+ it('polls on the documented interval', () => {
+ expect(PROBE_INTERVAL_MS).toBe(2_000);
+ });
+
+ it('ignores turns recorded outside a call', () => {
+ expect(recordTurn('caller', 'nobody is listening')).toMatchObject({ turns: 0 });
+ expect(noteCallerSpeech()).toMatchObject({ active: false });
+ });
+});
diff --git a/server/services/voice/config.js b/server/services/voice/config.js
index 13833a3ef8..5b719db41b 100644
--- a/server/services/voice/config.js
+++ b/server/services/voice/config.js
@@ -23,6 +23,8 @@ export const VOICE_DEFAULTS = Object.freeze({
targetName: '',
blackHole2chLabel: 'BlackHole 2ch',
blackHole16chLabel: 'BlackHole 16ch',
+ // Hard ceiling on one call, so a line left open cannot run all day.
+ maxCallMinutes: 15,
},
stt: {
diff --git a/server/services/voice/facetimeBridge.js b/server/services/voice/facetimeBridge.js
index 0c1430055e..7236dc121e 100644
--- a/server/services/voice/facetimeBridge.js
+++ b/server/services/voice/facetimeBridge.js
@@ -25,6 +25,59 @@ export const facetimeControlResultSchema = z.object({
export const facetimeHelperPath = () => join(voiceHome(), HELPER_NAME);
+// The call audio path needs two virtual devices at the rate FaceTime runs at.
+// Anything else is a misconfiguration the user has to fix in Audio MIDI Setup,
+// so the check names the specific device rather than reporting "audio broken".
+export const CALL_AUDIO_DEVICE_RATE = 48_000;
+const AUDIO_PROBE_TIMEOUT_MS = 10_000;
+
+const deviceChannels = (item, direction) => {
+ const raw = item?.[`coreaudio_device_${direction}`];
+ const parsed = Number.parseInt(String(raw ?? '').replace(/[^0-9]/g, ''), 10);
+ return Number.isFinite(parsed) ? parsed : 0;
+};
+
+/**
+ * Read the machine's audio devices.
+ *
+ * Returns `null` — not `[]` — when the list could not be read at all, so a
+ * failed probe is never reported as "the device is missing" and the user is
+ * not sent to reinstall something that is already there.
+ */
+export async function listAudioDevices() {
+ if (process.platform !== 'darwin') return null;
+ const result = await bufferedSpawn('system_profiler', ['SPAudioDataType', '-json'], { timeoutMs: AUDIO_PROBE_TIMEOUT_MS });
+ if (result.timedOut || !result.success) return null;
+ let parsed;
+ try {
+ parsed = JSON.parse(result.stdout);
+ } catch {
+ return null;
+ }
+ const items = parsed?.SPAudioDataType?.[0]?._items;
+ if (!Array.isArray(items)) return null;
+ return items.map((item) => ({
+ name: String(item?._name ?? ''),
+ sampleRate: Number.parseInt(String(item?.coreaudio_device_srate ?? '').replace(/[^0-9]/g, ''), 10) || 0,
+ inputChannels: deviceChannels(item, 'input'),
+ outputChannels: deviceChannels(item, 'output'),
+ }));
+}
+
+/** Grade one BlackHole device against the label, rate, and channel count. */
+export function checkAudioDevice(devices, label, channels) {
+ if (devices === null) return fact(false, `Could not read this Mac's audio devices to verify ${label}.`);
+ const device = devices.find((entry) => entry.name.trim().toLowerCase() === label.trim().toLowerCase());
+ if (!device) return fact(false, `Install ${label} with: brew install blackhole-${channels}ch`);
+ if (device.sampleRate !== CALL_AUDIO_DEVICE_RATE) {
+ return fact(false, `Set ${label} to ${CALL_AUDIO_DEVICE_RATE} Hz in Audio MIDI Setup (currently ${device.sampleRate || 'unknown'} Hz).`);
+ }
+ if (Math.max(device.inputChannels, device.outputChannels) < channels) {
+ return fact(false, `${label} reports fewer than ${channels} channels — reinstall it with: brew install blackhole-${channels}ch`);
+ }
+ return fact(true, `${label} is present at ${CALL_AUDIO_DEVICE_RATE} Hz with ${channels} channels.`);
+}
+
const identityReady = (config) => Boolean(config?.facetime?.targetHandle?.trim() && config?.facetime?.targetName?.trim());
const fact = (ok, message) => ({ ok: ok ? 'ok' : 'missing', message });
@@ -33,13 +86,14 @@ export async function checkSetup(config) {
const voiceConfig = config || await getVoiceConfig();
const facetime = voiceConfig.facetime || {};
const helper = facetimeHelperPath();
+ const devices = await listAudioDevices();
return {
platform: fact(process.platform === 'darwin', 'FaceTime Audio control requires macOS.'),
helper: fact(existsSync(helper), 'Run npm run setup:facetime to compile the FaceTime helper.'),
identity: fact(identityReady(voiceConfig), 'Set a target name and E.164 phone number or email address.'),
accessibility: fact(false, 'Grant Accessibility access to facetime-ax in System Settings > Privacy & Security > Accessibility.'),
- blackHole2ch: fact(false, `Install/select ${facetime.blackHole2chLabel || 'BlackHole 2ch'} in FaceTime audio settings.`),
- blackHole16ch: fact(false, `Install/select ${facetime.blackHole16chLabel || 'BlackHole 16ch'} in FaceTime audio settings.`),
+ blackHole2ch: checkAudioDevice(devices, facetime.blackHole2chLabel || 'BlackHole 2ch', 2),
+ blackHole16ch: checkAudioDevice(devices, facetime.blackHole16chLabel || 'BlackHole 16ch', 16),
};
}
diff --git a/server/services/voice/facetimeBridge.test.js b/server/services/voice/facetimeBridge.test.js
index 9b66f105f4..66b5b827f1 100644
--- a/server/services/voice/facetimeBridge.test.js
+++ b/server/services/voice/facetimeBridge.test.js
@@ -1,5 +1,13 @@
import { describe, expect, it } from 'vitest';
-import { checkSetup, facetimeControlResultSchema } from './facetimeBridge.js';
+import { CALL_AUDIO_DEVICE_RATE, checkAudioDevice, checkSetup, facetimeControlResultSchema } from './facetimeBridge.js';
+
+const device = (overrides = {}) => ({
+ name: 'BlackHole 16ch',
+ sampleRate: CALL_AUDIO_DEVICE_RATE,
+ inputChannels: 16,
+ outputChannels: 16,
+ ...overrides,
+});
describe('FaceTime Audio control protocol', () => {
it('accepts only the strict helper result contract', () => {
@@ -17,6 +25,39 @@ describe('FaceTime Audio control protocol', () => {
expect(JSON.stringify(setup)).not.toContain('targetHandle');
});
+ describe('BlackHole device check', () => {
+ it('passes a device present at the right rate and channel count', () => {
+ expect(checkAudioDevice([device()], 'BlackHole 16ch', 16).ok).toBe('ok');
+ // The label is what the user sees in Audio MIDI Setup, so casing and
+ // stray whitespace must not decide whether the call can run.
+ expect(checkAudioDevice([device({ name: ' blackhole 16CH ' })], 'BlackHole 16ch', 16).ok).toBe('ok');
+ });
+
+ it('distinguishes could-not-read from not-installed', () => {
+ // A failed probe must never send the user to reinstall a device that is
+ // already there, so the two answers carry different remedies.
+ const unreadable = checkAudioDevice(null, 'BlackHole 2ch', 2);
+ const absent = checkAudioDevice([], 'BlackHole 2ch', 2);
+
+ expect(unreadable.ok).toBe('missing');
+ expect(unreadable.message).toMatch(/Could not read/);
+ expect(absent.message).toMatch(/brew install blackhole-2ch/);
+ });
+
+ it('names the actual misconfiguration rather than failing generically', () => {
+ expect(checkAudioDevice([device({ sampleRate: 44_100 })], 'BlackHole 16ch', 16).message)
+ .toMatch(/48000 Hz.*currently 44100 Hz/);
+ // The 2ch driver answering to the 16ch label is the common mistake.
+ expect(checkAudioDevice([device({ inputChannels: 2, outputChannels: 2 })], 'BlackHole 16ch', 16).message)
+ .toMatch(/fewer than 16 channels/);
+ });
+
+ it('reads either direction, since a virtual device may report only one', () => {
+ expect(checkAudioDevice([device({ inputChannels: 0 })], 'BlackHole 16ch', 16).ok).toBe('ok');
+ expect(checkAudioDevice([device({ outputChannels: 0 })], 'BlackHole 16ch', 16).ok).toBe('ok');
+ });
+ });
+
it('refuses to run when identity is not configured', async () => {
const { run } = await import('./facetimeBridge.js');
await expect(run('probe', { facetime: { targetHandle: '', targetName: '' } }))
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index ba168f3c29..6738470b06 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -9,6 +9,9 @@
// | voice:dailyLog:appended | voice:error | voice:idle
// | voice:screenshot:request
// | voice:speak | voice:output:primary | voice:output:detached
+// Call host (FaceTime Audio bridge):
+// Inbound: voice:call:attach | voice:call:audio | voice:call:detach
+// Outbound: voice:call:state | voice:call:tts
import { runTurn } from '../services/voice/pipeline.js';
import { getVoiceConfig } from '../services/voice/config.js';
@@ -19,6 +22,19 @@ import {
releaseVoiceOutput,
} from '../services/voice/voiceOutput.js';
import { isIsoDate } from '../services/brainJournal.js';
+import { pcmToWavBuffer } from '../lib/chiptuneRender.js';
+import { CALL_AUDIO_SAMPLE_RATE, createCallEndpointer, pcmToFloat } from '../services/voice/callEndpointing.js';
+import {
+ attachHost,
+ detachHost,
+ getCallHost,
+ isCallActive,
+ markListening,
+ markSpeaking,
+ noteCallerSpeech,
+ recordTurn,
+ setCallStateListener,
+} from '../services/voice/callSession.js';
// Cap by messages (each user utterance + assistant reply is ~2). 24 → ~12 turns.
const HISTORY_MESSAGES = 24;
@@ -34,6 +50,10 @@ const MAX_TEXT_LEN = 4000;
// (runaway / malicious client). The client already does word-boundary
// truncation; we re-do it server-side so the guarantee holds end-to-end.
const MAX_UI_TEXT_CHARS = 8000;
+// One PCM frame from the call host. The page ships ~20 ms of 16 kHz mono Int16
+// (640 bytes); 64 KB is two seconds of headroom for a delayed flush and rejects
+// a runaway client without ever clipping a normal burst.
+const MAX_CALL_FRAME_BYTES = 64 * 1024;
// Truncate on the last whitespace boundary (space / newline / tab) so the
// tail isn't a partial token, then append an ellipsis. Mirrors the
@@ -350,6 +370,102 @@ export const registerVoiceHandlers = (socket) => {
claimVoiceOutput(socket);
});
+ // ---------------------------------------------------------------------------
+ // Call host — the FaceTime Audio bridge.
+ //
+ // The page is a plain browser tab reading BlackHole, so it speaks the same
+ // socket the widget does. What differs is the shape of the input: a
+ // continuous PCM stream with no push-to-talk, endpointed here into the same
+ // `runTurn` utterances the microphone produces, and the destination of the
+ // reply, which is played into the call rather than out of the speakers.
+ // ---------------------------------------------------------------------------
+ const call = { endpointer: null, busy: false };
+
+ const emitCallState = (snapshot) => socket.emit('voice:call:state', snapshot);
+
+ const runCallUtterance = async (utterance) => {
+ call.busy = true;
+ markSpeaking();
+ let spoken = '';
+ try {
+ await runTurn({
+ audio: pcmToWavBuffer(pcmToFloat(utterance.pcm), { sampleRate: CALL_AUDIO_SAMPLE_RATE }),
+ mimeType: 'audio/wav',
+ history: state.history,
+ state,
+ // The pipeline speaks the widget's event vocabulary; only the audio is
+ // re-addressed, so persona, tools, and the confirm gate are unchanged.
+ emit: (event, data) => {
+ if (event === 'voice:tts:audio') {
+ spoken = data?.sentence || spoken;
+ socket.emit('voice:call:tts', data);
+ return;
+ }
+ if (event === 'voice:transcript' && data?.text) recordTurn('caller', data.text);
+ socket.emit(event, data);
+ },
+ });
+ if (spoken) recordTurn('assistant', spoken);
+ } catch (err) {
+ console.error(`📞 call turn failed: ${err.message}`);
+ socket.emit('voice:error', { stage: 'call', message: err.message });
+ } finally {
+ call.busy = false;
+ markListening();
+ }
+ };
+
+ socket.on('voice:call:attach', async () => {
+ try {
+ if (!(await ensureEnabled('call'))) return;
+ const claim = attachHost(socket);
+ if (!claim.ok) {
+ // Refused, not displaced: two tabs reading the same device would each
+ // answer, and the loser could not tell it had been muted.
+ socket.emit('voice:call:state', { error: claim.reason, hostAttached: false, active: false, state: 'idle' });
+ return;
+ }
+ call.endpointer = createCallEndpointer();
+ setCallStateListener(emitCallState);
+ emitCallState(claim.state);
+ } catch (err) {
+ console.error(`❌ voice:call:attach failed: ${err.message}`);
+ socket.emit('voice:error', { stage: 'call', message: err.message });
+ }
+ });
+
+ socket.on('voice:call:audio', async (payload = {}) => {
+ try {
+ if (getCallHost() !== socket || !call.endpointer) return;
+ const { pcm } = payload || {};
+ const bytes = audioByteLength(pcm);
+ if (!bytes || bytes > MAX_CALL_FRAME_BYTES) return;
+ const view = Buffer.isBuffer(pcm) || ArrayBuffer.isView(pcm)
+ ? 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 (!utterance) return;
+ noteCallerSpeech();
+ if (call.busy) return;
+ await runCallUtterance(utterance);
+ } catch (err) {
+ console.error(`❌ voice:call:audio failed: ${err.message}`);
+ }
+ });
+
+ socket.on('voice:call:detach', async () => {
+ call.endpointer = null;
+ emitCallState(await detachHost(socket));
+ });
+
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
@@ -370,5 +486,15 @@ export const registerVoiceHandlers = (socket) => {
state.uiTextWaiters.clear();
textWaiters.forEach((resolve) => resolve(null));
unregisterEchoBuffer(state.recentTts);
+ // A closed tab is a detached host: the call loses its audio path, so the
+ // session ends rather than running on deaf.
+ if (getCallHost() === socket) {
+ call.endpointer = null;
+ detachHost(socket).catch((err) => console.error(`❌ voice call detach failed: ${err.message}`));
+ }
});
};
+
+// Re-exported for the call-host page's own smoke checks and for tests that
+// assert the frame cap without standing up a socket.
+export { MAX_CALL_FRAME_BYTES };