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: add FaceTime Audio control plane (#5307)

[._.]/ Adam Eivy54560606c2e7
diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsx
index 93e66689f9..2e0c6cc0cc 100644
--- a/client/src/components/settings/VoiceTab.jsx
+++ b/client/src/components/settings/VoiceTab.jsx
@@ -4,7 +4,7 @@ import { Save, Mic, Play, Zap, RefreshCw, Globe } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import {
- getVoiceStatus, getVoiceConfig, updateVoiceConfig, listVoices, testTts, fetchPiperVoice,
+ getVoiceStatus, getVoiceConfig, updateVoiceConfig, listVoices, testTts, fetchPiperVoice, getFaceTimeStatus, controlFaceTime,
} from '../../services/apiVoice';
import { getProviders, refreshProviderModels } from '../../services/apiProviders';
import { playWav, webSpeechSupported } from '../../services/voiceClient';
@@ -12,6 +12,7 @@ import { nanoAvailability } from '../../services/browserLlm';
import { readVoiceHidden, writeVoiceHidden } from '../../services/voiceVisibility';
import { formatVoiceLabel } from '../../lib/voiceLabel';
import FormField from '../ui/FormField';
+import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';
const SERVICE_LABELS = {
whisper: 'Whisper (STT)',
@@ -74,6 +75,7 @@ const ServiceBadge = ({ label, probe }) => {
const inputCls = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';
export function VoiceTab() {
+ const { isFeatureEnabled } = useInstanceFeatures();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [cfg, setCfg] = useState(null);
@@ -90,6 +92,9 @@ export function VoiceTab() {
const [refreshingModels, setRefreshingModels] = useState(false);
// On-device (Gemini Nano) availability for the fast-resolution tier-2 pill.
const [nanoStatus, setNanoStatus] = useState(null);
+ const [facetimeStatus, setFacetimeStatus] = useState(null);
+ const [facetimeAction, setFacetimeAction] = useState(null);
+ const [facetimeResult, setFacetimeResult] = useState(null);
const toggleWidgetHidden = (next) => {
writeVoiceHidden(next);
@@ -201,6 +206,22 @@ export function VoiceTab() {
await refreshStatus();
};
+ const refreshFaceTime = () => getFaceTimeStatus({ silent: true })
+ .then(setFacetimeStatus)
+ .catch(() => setFacetimeStatus(null));
+
+ const handleFaceTimeAction = async (action) => {
+ setFacetimeAction(action);
+ try {
+ setFacetimeResult(await controlFaceTime(action, { silent: true }));
+ } catch (err) {
+ setFacetimeResult({ ok: false, message: err.message });
+ } finally {
+ setFacetimeAction(null);
+ refreshFaceTime();
+ }
+ };
+
const handlePreviewVoice = async (voiceName) => {
if (!voiceName || previewingVoice) return;
setPreviewingVoice(voiceName);
@@ -242,6 +263,9 @@ export function VoiceTab() {
if (loading || !cfg) return <BrailleSpinner text="Loading voice settings" />;
+ const facetime = cfg.facetime || {};
+ const faceTimeDirty = !facetime.targetHandle?.trim() || !facetime.targetName?.trim();
+
const engine = cfg.tts.engine || 'kokoro';
const sttEngine = cfg.stt.engine || 'whisper';
const activeVoice = engine === 'kokoro' ? cfg.tts.kokoro?.voice : cfg.tts.piper?.voice;
@@ -326,6 +350,22 @@ export function VoiceTab() {
))}
</div>
+ {isFeatureEnabled('facetime') && <section className="border border-port-border rounded-lg p-4 space-y-3">
+ <h3 className="text-base font-semibold text-white">FaceTime Audio</h3>
+ <p className="text-xs text-gray-500">Machine-local macOS call control. Save your identity before testing; it is not shared with peers.</p>
+ <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>
+ </div>
+ <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>
+ </div>
+ {faceTimeDirty && <p className="text-xs text-port-warning">Set and save both identity fields before FaceTime controls are available.</p>}
+ {facetimeStatus && <ul className="text-xs text-gray-400">{Object.entries(facetimeStatus).map(([key, value]) => <li key={key}>{value.ok === 'ok' ? '✓' : '•'} {key}: {value.message}</li>)}</ul>}
+ {facetimeResult && <pre className="text-xs text-gray-400 whitespace-pre-wrap">{JSON.stringify(facetimeResult, null, 2)}</pre>}
+ </section>}
+
<div className="flex items-start gap-3 bg-port-bg border border-port-border rounded-lg p-3">
<Globe size={16} className="text-port-accent mt-0.5 shrink-0" />
<div className="text-xs text-gray-400 min-w-0">
diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.js
index 6e70be7b29..41f288e45a 100644
--- a/client/src/services/apiVoice.js
+++ b/client/src/services/apiVoice.js
@@ -27,3 +27,5 @@ export const testTts = (text, voice, engine) => {
export const getTtsStatus = (options) => api.get('/voice/tts/status', options);
export const unloadKokoroTts = (options) => api.post('/voice/tts/unload', {}, options);
export const controlWhisper = (action, options) => api.post('/voice/whisper', { action }, options);
+export const getFaceTimeStatus = (options) => api.get('/voice/facetime/status', options);
+export const controlFaceTime = (action, options) => api.post(`/voice/facetime/${action}`, {}, options);
diff --git a/docs/features/voice.md b/docs/features/voice.md
index e0fa54fa88..885cf73d76 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -15,6 +15,10 @@ PortOS includes an optional voice assistant with support for fully local operati
The TTS engine is selectable in **Settings → Voice → TTS engine**.
+### FaceTime Audio control plane
+
+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.
+
### 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.
diff --git a/package.json b/package.json
index cf58ce71fb..dd18f68c9b 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
"test:db": "npm run test:db --prefix server",
"setup:llm": "node scripts/setup-llm.js",
"setup:browser": "node scripts/setup-browser.js",
+ "setup:facetime": "node scripts/setup-facetime.js",
"setup:remote-desktop": "node scripts/setup-remote-desktop.js",
"fix:windows-console": "node scripts/fix-windows-console.js",
"setup:cert": "node scripts/setup-cert.js",
diff --git a/scripts/setup-facetime.js b/scripts/setup-facetime.js
new file mode 100644
index 0000000000..2a4ff4f487
--- /dev/null
+++ b/scripts/setup-facetime.js
@@ -0,0 +1,16 @@
+import { existsSync, mkdirSync } from 'fs';
+import { execFileSync } from 'node:child_process';
+import { dirname, join } from 'path';
+import { homedir } from 'os';
+
+if (process.platform !== 'darwin') {
+ console.error('FaceTime Audio setup requires macOS.');
+ process.exit(1);
+}
+
+const source = join(import.meta.dirname, '..', 'server', 'native', 'facetime-ax', 'main.swift');
+const output = join(homedir(), '.portos', 'voice', 'facetime-ax');
+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.');
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 78796676ee..eb307ec02f 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -22018,7 +22018,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 120
+ "line": 130
}
]
},
@@ -22029,7 +22029,18 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 125
+ "line": 135
+ }
+ ]
+ },
+ {
+ "method": "GET",
+ "path": "/api/voice/facetime/status",
+ "mountPath": "/api/voice",
+ "sources": [
+ {
+ "source": "server/routes/voice.js",
+ "line": 181
}
]
},
@@ -22040,7 +22051,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 177
+ "line": 201
}
]
},
@@ -22084,7 +22095,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 229
+ "line": 253
}
]
},
@@ -22095,7 +22106,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 154
+ "line": 164
}
]
},
@@ -22106,7 +22117,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 190
+ "line": 214
}
]
},
@@ -22117,7 +22128,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 255
+ "line": 279
}
]
},
@@ -22128,7 +22139,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 267
+ "line": 291
}
]
},
@@ -22139,7 +22150,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 171
+ "line": 195
}
]
},
@@ -22150,7 +22161,7 @@
"sources": [
{
"source": "server/routes/voice.js",
- "line": 279
+ "line": 303
}
]
},
@@ -22960,8 +22971,8 @@
],
"stats": {
"mounts": 145,
- "operations": 2071,
- "declarations": 2074,
+ "operations": 2072,
+ "declarations": 2075,
"sourceFiles": 224
}
}
diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.js
index 2d8d1e6fe6..d8be5e1484 100644
--- a/server/lib/instanceFeatureRegistry.js
+++ b/server/lib/instanceFeatureRegistry.js
@@ -58,6 +58,12 @@ export const INSTANCE_FEATURES = Object.freeze([
// installs on that behavior until the user explicitly changes the flag.
defaultEnabled: true,
}),
+ Object.freeze({
+ id: 'facetime',
+ label: 'FaceTime Audio',
+ description: 'Machine-local FaceTime Audio call controls and setup checks.',
+ defaultEnabled: false,
+ }),
]);
export const INSTANCE_FEATURE_IDS = Object.freeze(INSTANCE_FEATURES.map((feature) => feature.id));
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 87a2c2863a..8252f44c7e 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -330,6 +330,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },
{ 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.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/native/facetime-ax/main.swift b/server/native/facetime-ax/main.swift
new file mode 100644
index 0000000000..2442a3b505
--- /dev/null
+++ b/server/native/facetime-ax/main.swift
@@ -0,0 +1,53 @@
+import AppKit
+import ApplicationServices
+import Foundation
+
+enum State: String { case idle, dialing, connected, ended, unknown }
+
+struct Result: Encodable {
+ let ok: Bool
+ let command: String
+ let state: State
+ let authorized: Bool
+ let action: String
+ let message: String
+ let errorCode: String?
+}
+
+func emit(_ result: Result, exit: Int32 = 0) -> Never {
+ let data = try! JSONEncoder().encode(result)
+ FileHandle.standardOutput.write(data)
+ FileHandle.standardOutput.write(Data("\n".utf8))
+ Foundation.exit(exit)
+}
+
+let arguments = CommandLine.arguments
+guard arguments.count == 4, ["probe", "call", "answer", "hangup"].contains(arguments[1]) else {
+ emit(Result(ok: false, command: arguments.dropFirst().first ?? "unknown", state: .unknown, authorized: AXIsProcessTrusted(), action: "none", message: "usage: facetime-ax probe|call|answer|hangup <handle> <identity>", errorCode: "invalid-arguments"), exit: 2)
+}
+
+let command = arguments[1]
+let handle = arguments[2]
+let identity = arguments[3]
+let authorized = AXIsProcessTrusted()
+guard authorized else {
+ emit(Result(ok: false, command: command, state: .unknown, authorized: false, action: "none", message: "Accessibility permission is required", errorCode: "accessibility-denied"), exit: 1)
+}
+
+// This phase deliberately fails closed. Future phases provide the verified AX
+// element traversal; no coordinate click is ever acceptable here.
+if command == "probe" {
+ emit(Result(ok: true, command: command, state: .idle, authorized: true, action: "probe", message: "Accessibility authorization granted", errorCode: nil))
+}
+
+guard let escaped = handle.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
+ let url = URL(string: "facetime-audio://\(escaped)") else {
+ emit(Result(ok: false, command: command, state: .unknown, authorized: true, action: "none", message: "Invalid FaceTime handle", errorCode: "invalid-handle"), exit: 2)
+}
+
+if command == "call" {
+ NSWorkspace.shared.open(url)
+ emit(Result(ok: false, command: command, state: .dialing, authorized: true, action: "open-url", message: "FaceTime opened; semantic AX confirmation is unavailable", errorCode: "ambiguous-surface"), exit: 1)
+}
+
+emit(Result(ok: false, command: command, state: .unknown, authorized: true, action: "none", message: "No unambiguous FaceTime surface naming \(identity) was found", errorCode: "ambiguous-surface"), exit: 1)
diff --git a/server/routes/voice.js b/server/routes/voice.js
index 849ee60a48..7da8a5a2f8 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -8,8 +8,10 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';
import { checkAll, invalidateHealthCache } from '../services/voice/health.js';
+import * as facetimeBridge from '../services/voice/facetimeBridge.js';
import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice, startWhisper, stopWhisper } from '../services/voice/bootstrap.js';
import { synthesize, listVoices, VALID_ENGINES } from '../services/voice/tts.js';
import { readyState as kokoroReadyState, unloadKokoro, loadedModelKey as kokoroLoadedKey } from '../services/voice/tts-kokoro.js';
@@ -18,6 +20,8 @@ import { speakProactive, HHMM_RE, MAX_PROACTIVE_TEXT_LEN } from '../services/voi
const router = Router();
+const facetimeActionSchema = z.object({}).strict();
+
const validEngine = (v) => VALID_ENGINES.has(v) ? v : undefined;
// Shared cap for every REST endpoint that turns a text payload into TTS
@@ -36,6 +40,12 @@ const voiceConfigPatchSchema = z.object({
enabled: z.boolean().optional(),
trigger: z.enum(['push-to-talk', 'hotword', 'vad']).optional(),
hotkey: z.string().max(32).optional(),
+ facetime: z.object({
+ 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(),
+ blackHole16chLabel: z.string().trim().min(1).max(120).optional(),
+ }).partial().optional(),
stt: z.object({
engine: z.enum(['whisper', 'web-speech']).optional(),
endpoint: z.string().url().optional(),
@@ -165,6 +175,20 @@ router.get('/status', asyncHandler(async (_req, res) => {
});
}));
+// FaceTime Audio is machine-local and explicitly feature-gated. The helper is
+// never spawned by a read/status request; operators must press one of the
+// explicit control buttons.
+router.get('/facetime/status', asyncHandler(async (_req, res) => {
+ res.json(await facetimeBridge.checkSetup());
+}));
+
+for (const command of ['probe', 'call', 'hangup']) {
+ router.post(`/facetime/${command}`, asyncHandler(async (req, res) => {
+ validateRequest(facetimeActionSchema, req.body || {});
+ res.json(await facetimeBridge[command]());
+ }));
+}
+
// GET /api/voice/voices?engine=kokoro|piper — enumerate voices for the given
// engine (or the active one when unspecified). Query param lets the Settings
// page preview a different engine's voices without saving first.
diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.js
index 1ef37d68cb..122433ce5b 100644
--- a/server/services/instanceFeatures.js
+++ b/server/services/instanceFeatures.js
@@ -30,6 +30,12 @@ const DETECTORS = {
const { hasConfiguredInstances } = await import('./jira.js');
return hasConfiguredInstances();
},
+ facetime: async () => {
+ if (process.platform !== 'darwin') return false;
+ const { checkSetup } = await import('./voice/facetimeBridge.js');
+ const report = await checkSetup();
+ return report.helper?.ok === 'ok' && report.identity?.ok === 'ok';
+ },
};
const FEATURE_BY_ID = new Map(INSTANCE_FEATURES.map((feature) => [feature.id, feature]));
diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.js
index 52e04fdac3..f89e824ae5 100644
--- a/server/services/instanceFeatures.test.js
+++ b/server/services/instanceFeatures.test.js
@@ -10,6 +10,7 @@ const mock = vi.hoisted(() => ({
}));
vi.mock('./settings.js', () => ({
+ getSettings: vi.fn(async () => structuredClone(mock.settings)),
getSettingsWithStatus: vi.fn(async () => ({ corrupt: mock.corrupt, settings: structuredClone(mock.settings) })),
updateSettingsWith: mock.updateSettingsWith,
}));
@@ -171,7 +172,7 @@ describe('instance features', () => {
const { features } = await getInstanceFeatures();
expect(Object.fromEntries(features.map((f) => [f.id, f.enabled])))
- .toEqual({ post: true, datadog: true, jira: false, gsd: true, openclaw: true, health: true });
+ .toEqual({ post: true, datadog: true, jira: false, gsd: true, openclaw: true, health: true, facetime: false });
});
it('rejects an unknown feature id', async () => {
diff --git a/server/services/voice/config.js b/server/services/voice/config.js
index 0b0c12d76c..13833a3ef8 100644
--- a/server/services/voice/config.js
+++ b/server/services/voice/config.js
@@ -16,6 +16,15 @@ export const VOICE_DEFAULTS = Object.freeze({
trigger: 'push-to-talk',
hotkey: 'Space',
+ // FaceTime control-plane configuration is machine-local. It is deliberately
+ // nested under voice rather than the federation-facing instance profile.
+ facetime: {
+ targetHandle: '',
+ targetName: '',
+ blackHole2chLabel: 'BlackHole 2ch',
+ blackHole16chLabel: 'BlackHole 16ch',
+ },
+
stt: {
// 'web-speech' (browser-native, zero-latency, no server process needed) is the
// default. Falls back to 'whisper' (local whisper.cpp) for browsers without
diff --git a/server/services/voice/facetimeBridge.js b/server/services/voice/facetimeBridge.js
new file mode 100644
index 0000000000..0c1430055e
--- /dev/null
+++ b/server/services/voice/facetimeBridge.js
@@ -0,0 +1,77 @@
+// Machine-local FaceTime Audio control plane. The native helper owns all AX UI
+// interaction; this boundary accepts only its strict, one-object JSON protocol.
+
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { z } from 'zod';
+import { bufferedSpawn } from '../../lib/bufferedSpawn.js';
+import { getVoiceConfig, voiceHome } from './config.js';
+import { isInstanceFeatureEnabled } from '../instanceFeatures.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+export const FACETIME_COMMANDS = ['probe', 'call', 'answer', 'hangup'];
+const HELPER_NAME = process.platform === 'win32' ? 'facetime-ax.exe' : 'facetime-ax';
+const FACETIME_TIMEOUT_MS = 40_000;
+
+export const facetimeControlResultSchema = z.object({
+ ok: z.boolean(),
+ command: z.enum(FACETIME_COMMANDS),
+ state: z.enum(['idle', 'dialing', 'connected', 'ended', 'unknown']),
+ authorized: z.boolean(),
+ action: z.string().max(160),
+ message: z.string().max(1000),
+ errorCode: z.string().max(120).nullable(),
+}).strict();
+
+export const facetimeHelperPath = () => join(voiceHome(), HELPER_NAME);
+
+const identityReady = (config) => Boolean(config?.facetime?.targetHandle?.trim() && config?.facetime?.targetName?.trim());
+
+const fact = (ok, message) => ({ ok: ok ? 'ok' : 'missing', message });
+
+export async function checkSetup(config) {
+ const voiceConfig = config || await getVoiceConfig();
+ const facetime = voiceConfig.facetime || {};
+ const helper = facetimeHelperPath();
+ 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.`),
+ };
+}
+
+const setupFailure = (report) => Object.entries(report).find(([, value]) => value.ok !== 'ok')?.[0] || null;
+
+async function assertAvailable(config) {
+ if (!await isInstanceFeatureEnabled('facetime')) {
+ throw new ServerError('FaceTime Audio is disabled', { status: 409, code: 'feature-disabled' });
+ }
+ if (!identityReady(config)) {
+ throw new ServerError('FaceTime identity is not configured', { status: 409, code: 'identity' });
+ }
+}
+
+export async function run(command, config) {
+ const voiceConfig = config || await getVoiceConfig();
+ if (!FACETIME_COMMANDS.includes(command)) throw new ServerError('Unknown FaceTime command', { status: 400, code: 'VALIDATION_ERROR' });
+ await assertAvailable(voiceConfig);
+ const report = await checkSetup(voiceConfig);
+ const missing = setupFailure(report);
+ if (missing) throw new ServerError(`FaceTime setup incomplete: ${missing}`, { status: 409, code: missing });
+ const result = await bufferedSpawn(facetimeHelperPath(), [command, voiceConfig.facetime.targetHandle, voiceConfig.facetime.targetName], { timeoutMs: FACETIME_TIMEOUT_MS });
+ if (result.timedOut) throw new ServerError('FaceTime helper timed out', { status: 504, code: 'timeout' });
+ const parsed = facetimeControlResultSchema.safeParse(JSON.parse(result.stdout));
+ if (!parsed.success) throw new ServerError('FaceTime helper returned an invalid result', { status: 502, code: 'invalid-helper-result' });
+ if (!result.success || !parsed.data.ok) {
+ throw new ServerError(parsed.data.message || 'FaceTime helper failed', { status: 502, code: parsed.data.errorCode || 'helper-failed' });
+ }
+ return parsed.data;
+}
+
+export const probe = () => run('probe');
+export const call = () => run('call');
+export const answer = () => run('answer');
+export const hangup = () => run('hangup');
diff --git a/server/services/voice/facetimeBridge.test.js b/server/services/voice/facetimeBridge.test.js
new file mode 100644
index 0000000000..9b66f105f4
--- /dev/null
+++ b/server/services/voice/facetimeBridge.test.js
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { checkSetup, facetimeControlResultSchema } from './facetimeBridge.js';
+
+describe('FaceTime Audio control protocol', () => {
+ it('accepts only the strict helper result contract', () => {
+ const result = facetimeControlResultSchema.safeParse({
+ ok: true, command: 'probe', state: 'idle', authorized: true,
+ action: 'probe', message: 'ready', errorCode: null,
+ });
+ expect(result.success).toBe(true);
+ expect(facetimeControlResultSchema.safeParse({ ...result.data, identity: '[email protected]' }).success).toBe(false);
+ });
+
+ it('reports an unset identity without exposing an identity value', async () => {
+ const setup = await checkSetup({ facetime: { targetHandle: '', targetName: '' } });
+ expect(setup.identity.ok).toBe('missing');
+ expect(JSON.stringify(setup)).not.toContain('targetHandle');
+ });
+
+ it('refuses to run when identity is not configured', async () => {
+ const { run } = await import('./facetimeBridge.js');
+ await expect(run('probe', { facetime: { targetHandle: '', targetName: '' } }))
+ .rejects.toThrow();
+ });
+});
+
diff --git a/server/services/voice/health.js b/server/services/voice/health.js
index e059c2a239..a201a0f7b1 100644
--- a/server/services/voice/health.js
+++ b/server/services/voice/health.js
@@ -8,6 +8,7 @@ import { readyState as kokoroReadyState } from './tts-kokoro.js';
import { which } from './bootstrap.js';
import { resolveLlmEndpoint, authHeaders } from './llm.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
+import { checkSetup as checkFaceTimeSetup } from './facetimeBridge.js';
const PROBE_TIMEOUT_MS = 1500;
const CACHE_TTL_MS = 3000;
@@ -77,6 +78,7 @@ export const checkAll = async (cfg) => {
const state = kokoroReadyState();
out.kokoro = { ok: state === 'loaded', state };
}
+ out.facetime = await checkFaceTimeSetup(voice);
cache = { key: cacheKey, ts: Date.now(), value: out };
return out;