Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { spawnSync } from 'child_process';
import { describe, expect, it, vi } from 'vitest';
import { pinPlatform } from '../../lib/testHelper.js';
// run() reaches the helper only after the feature flag, a helper binary, and
// a readable audio-device list all pass. Those are live-install facts, so the
// helper-result cases below substitute them and leave every other test on the
// real implementations.
const helperRun = vi.hoisted(() => ({
voiceHome: null,
facetimeEnabled: null,
spawnImpl: null,
}));
vi.mock('./config.js', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, voiceHome: () => helperRun.voiceHome || actual.voiceHome() };
});
vi.mock('../instanceFeatures.js', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
isInstanceFeatureEnabled: (...args) => (
helperRun.facetimeEnabled === null
? actual.isInstanceFeatureEnabled(...args)
: Promise.resolve(helperRun.facetimeEnabled)
),
};
});
vi.mock('../../lib/bufferedSpawn.js', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
bufferedSpawn: (cmd, args, opts) => (
helperRun.spawnImpl ? helperRun.spawnImpl(cmd, args, opts) : actual.bufferedSpawn(cmd, args, opts)
),
};
});
import { CALL_AUDIO_DEVICE_RATE, FACETIME_COMMANDS, blockingSetupFailure, checkAudioDevice, checkLocalSetup, checkSetup, facetimeControlResultSchema, run } from './facetimeBridge.js';
const device = (overrides = {}) => ({
name: 'BlackHole 16ch',
sampleRate: CALL_AUDIO_DEVICE_RATE,
inputChannels: 16,
outputChannels: 16,
...overrides,
});
describe('FaceTime Audio control protocol', () => {
// swiftc compiles are runner-budgeted, not product behavior: a cold/contended
// full-suite worker can take >10s on the default testTimeout, so these
// compile tests carry their own budget (same reasoning as vitest.config.js).
it.runIf(process.platform === 'darwin')('compiles the native helper and preserves its strict JSON boundary', () => {
const sourceDir = join(import.meta.dirname, '..', '..', 'native', 'facetime-ax');
const tempDir = mkdtempSync(join(process.env.PORTOS_TEST_TMPDIR || tmpdir(), 'portos-facetime-ax-'));
const helper = join(tempDir, 'facetime-ax');
try {
const compiled = spawnSync('swiftc', ['-warnings-as-errors', join(sourceDir, 'identityMatcher.swift'), join(sourceDir, 'main.swift'), '-o', helper], { encoding: 'utf8' });
expect(compiled.status, compiled.stderr).toBe(0);
const probe = spawnSync(helper, ['probe', '+15551234567', 'Example Caller'], { encoding: 'utf8' });
const parsed = JSON.parse(probe.stdout);
expect(Object.hasOwn(parsed, 'errorCode')).toBe(true);
expect(facetimeControlResultSchema.safeParse(parsed).success).toBe(true);
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
}, 60_000);
it.runIf(process.platform === 'darwin')('matches only the configured semantic identity', () => {
const sourceDir = join(import.meta.dirname, '..', '..', 'native', 'facetime-ax');
const tempDir = mkdtempSync(join(process.env.PORTOS_TEST_TMPDIR || tmpdir(), 'portos-facetime-identity-'));
const runner = join(tempDir, 'main.swift');
const binary = join(tempDir, 'identity-test');
try {
writeFileSync(runner, `import Foundation
let matcher = IdentityMatcher(handle: "+15551234567", identity: "Example Caller")
guard matcher.matches(["Incoming call from Example Caller"]) else { exit(1) }
guard matcher.matches(["Incoming call from +1 (555) 123-4567"]) else { exit(2) }
guard !matcher.matches(["Incoming call from Example Callers"]) else { exit(3) }
guard !matcher.matches(["Incoming call from +44 1555 123 4567"]) else { exit(4) }
`);
const compiled = spawnSync('swiftc', ['-warnings-as-errors', join(sourceDir, 'identityMatcher.swift'), runner, '-o', binary], { encoding: 'utf8' });
expect(compiled.status, compiled.stderr).toBe(0);
const result = spawnSync(binary, [], { encoding: 'utf8' });
expect(result.status, result.stderr).toBe(0);
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
}, 60_000);
it.runIf(process.platform === 'darwin')('reports unconfirmed native actions as failures and preserves observed states', () => {
const sourceDir = join(import.meta.dirname, '..', '..', 'native', 'facetime-ax');
const tempDir = mkdtempSync(join(process.env.PORTOS_TEST_TMPDIR || tmpdir(), 'portos-facetime-confirmation-'));
const runner = join(tempDir, 'main.swift');
const binary = join(tempDir, 'confirmation-test');
try {
// Exercise the native serialization/exit boundary without reading AX
// surfaces, pressing controls, or waiting on a real call.
const source = readFileSync(join(sourceDir, 'main.swift'), 'utf8');
const declarations = source.slice(0, source.indexOf('let arguments = CommandLine.arguments'));
writeFileSync(runner, `${declarations}
let state = CommandLine.arguments[2] == "unconfirmed"
? waitForState([], matcher: IdentityMatcher(handle: "+15551234567", identity: "Example Caller"), timeout: 0)
: State(rawValue: CommandLine.arguments[2])
completeAction(command: CommandLine.arguments[1], confirmedState: state, action: "test-action", message: "confirmed")
`);
const compiled = spawnSync('swiftc', ['-warnings-as-errors', join(sourceDir, 'identityMatcher.swift'), runner, '-o', binary], { encoding: 'utf8' });
expect(compiled.status, compiled.stderr).toBe(0);
for (const [command, state] of [['answer', 'unconfirmed'], ['hangup', 'unconfirmed'], ['answer', 'connected'], ['hangup', 'ended'], ['hangup', 'idle']]) {
const result = spawnSync(binary, [command, state], { encoding: 'utf8' });
const confirmed = state !== 'unconfirmed';
expect(result.status, result.stderr).toBe(confirmed ? 0 : 1);
const parsed = facetimeControlResultSchema.parse(JSON.parse(result.stdout));
expect(parsed).toMatchObject({
ok: confirmed, command, state: confirmed ? state : 'unknown',
action: 'test-action', errorCode: confirmed ? null : 'state-unconfirmed',
});
}
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
}, 60_000);
it.runIf(process.platform === 'darwin')('keeps unreadable AX snapshots unknown instead of confirming a disconnect', () => {
const sourceDir = join(import.meta.dirname, '..', '..', 'native', 'facetime-ax');
const tempDir = mkdtempSync(join(process.env.PORTOS_TEST_TMPDIR || tmpdir(), 'portos-facetime-snapshot-'));
const runner = join(tempDir, 'main.swift');
const binary = join(tempDir, 'snapshot-test');
try {
// Run the native state/JSON boundary with synthetic AppKit/AX responses.
// No live app state is read and no controls are pressed.
const source = readFileSync(join(sourceDir, 'main.swift'), 'utf8');
const declarations = source.slice(0, source.indexOf('let arguments = CommandLine.arguments'));
writeFileSync(runner, `${declarations}
// These local symbols shadow AppKit/AX entrypoints so no live AX reads occur.
struct NSRunningApplication {
let processIdentifier: pid_t
let bundleIdentifier: String? = "com.apple.FaceTime"
let localizedName: String? = nil
let executableURL: URL? = nil
static func runningApplications(withBundleIdentifier bundle: String) -> [NSRunningApplication] {
bundle == "com.apple.FaceTime" ? [NSRunningApplication(processIdentifier: 100)] : []
}
}
struct NSWorkspace {
static let shared = NSWorkspace()
let runningApplications: [NSRunningApplication] = []
}
let scenario = CommandLine.arguments[1]
func AXUIElementCopyAttributeNames(_ element: AXUIElement, _ names: UnsafeMutablePointer<CFArray?>) -> AXError {
names.pointee = [] as CFArray
return .success
}
func AXUIElementCopyActionNames(_ element: AXUIElement, _ names: UnsafeMutablePointer<CFArray?>) -> AXError {
if scenario == "actions-error" { return .cannotComplete }
names.pointee = [kAXPressAction] as CFArray
return .success
}
func AXUIElementCopyAttributeValue(_ element: AXUIElement, _ attr: CFString, _ output: UnsafeMutablePointer<CFTypeRef?>) -> AXError {
var pid: pid_t = 0
guard AXUIElementGetPid(element, &pid) == .success else { return .illegalArgument }
let name = attr as String
if name == kAXChildrenAttribute as String {
if pid == 100 { output.pointee = [AXUIElementCreateApplication(101)] as CFArray; return .success }
if pid == 101 {
if scenario == "children-error" { return .cannotComplete }
if scenario == "children-malformed" { output.pointee = ["wrong"] as CFArray; return .success }
if scenario == "children-not-array" { output.pointee = "wrong" as CFString; return .success }
output.pointee = [AXUIElementCreateApplication(102), AXUIElementCreateApplication(103)] as CFArray
return .success
}
return scenario == "leaf-no-value" ? .noValue : .attributeUnsupported
}
if name == kAXRoleAttribute as String {
if scenario == "role-error" && pid == 102 { return .cannotComplete }
if scenario == "role-missing" && pid == 102 { return .noValue }
let roles: [pid_t: String] = [100: kAXApplicationRole as String, 101: kAXGroupRole as String, 102: kAXStaticTextRole as String, 103: kAXButtonRole as String]
output.pointee = roles[pid]! as CFString
return .success
}
if name == kAXTitleAttribute as String && pid == 102 { output.pointee = "Example Caller" as CFString; return .success }
if name == kAXTitleAttribute as String && pid == 103 { output.pointee = "Hang up" as CFString; return .success }
return .noValue
}
let matcher = IdentityMatcher(handle: "+15551234567", identity: "Example Caller")
let observed = probe(matcher: matcher)
emit(Result(ok: true, command: "probe", state: observed, authorized: true, action: "probe", message: "synthetic", errorCode: nil))
`);
const compiled = spawnSync('swiftc', ['-warnings-as-errors', join(sourceDir, 'identityMatcher.swift'), runner, '-o', binary], { encoding: 'utf8' });
expect(compiled.status, compiled.stderr).toBe(0);
for (const [scenario, state] of [
['connected', 'connected'], ['leaf-no-value', 'connected'],
['children-error', 'unknown'], ['children-malformed', 'unknown'],
['children-not-array', 'unknown'], ['actions-error', 'unknown'],
['role-error', 'unknown'], ['role-missing', 'unknown'],
]) {
const result = spawnSync(binary, [scenario], { encoding: 'utf8' });
expect(result.status, `${scenario}: ${result.stderr}`).toBe(0);
expect(facetimeControlResultSchema.parse(JSON.parse(result.stdout)), scenario)
.toMatchObject({ ok: true, command: 'probe', state });
}
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
}, 60_000);
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('feature detection never spawns the audio-device probe', async () => {
const spawned = [];
helperRun.spawnImpl = async (cmd) => {
spawned.push(cmd);
return { success: true, code: 0, signal: null, stdout: '{}', stderr: '', timedOut: false };
};
const restorePlatform = pinPlatform('darwin');
try {
const { detectFeatureConfiguration } = await import('../instanceFeatures.js');
await detectFeatureConfiguration();
expect(spawned).not.toContain('system_profiler');
} finally {
helperRun.spawnImpl = null;
restorePlatform();
}
});
it('checkLocalSetup returns the helper and identity facts that checkSetup composes', async () => {
const config = { facetime: { targetHandle: '', targetName: '' } };
const local = await checkLocalSetup(config);
const full = await checkSetup(config);
expect(Object.keys(local).sort()).toEqual(['helper', 'identity']);
expect(full).toMatchObject(local);
expect(Object.keys(full).sort()).toEqual(['accessibility', 'blackHole16ch', 'blackHole2ch', 'helper', 'identity', 'platform']);
});
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: '' } }))
.rejects.toThrow();
});
it('leaves Accessibility enforcement to the explicitly invoked helper', () => {
expect(blockingSetupFailure({
helper: { ok: 'ok' },
identity: { ok: 'ok' },
accessibility: { ok: 'missing' },
})).toBeNull();
expect(blockingSetupFailure({
helper: { ok: 'missing' },
accessibility: { ok: 'missing' },
})).toBe('helper');
});
describe('answer command (phase 4 — inbound)', () => {
it('is one of the commands the strict helper contract accepts', () => {
expect(FACETIME_COMMANDS).toContain('answer');
});
it('accepts the same strict result contract answer/hangup share with probe/call', () => {
const result = facetimeControlResultSchema.safeParse({
ok: true, command: 'answer', state: 'connected', authorized: true,
action: 'press-notification-action', message: 'Answered the incoming call', errorCode: null,
});
expect(result.success).toBe(true);
});
it('rejects an answer result naming a caller — the contract has no field for one', () => {
// The whole point of the fail-closed helper boundary: there is no way
// to report who called, so a leak would have to smuggle it through an
// existing field, and the schema being `.strict()` with a fixed field
// set means nothing extra fits.
const result = facetimeControlResultSchema.safeParse({
ok: true, command: 'answer', state: 'connected', authorized: true,
action: 'press-notification-action', message: 'Answered the incoming call', errorCode: null,
callerIdentity: '[email protected]',
});
expect(result.success).toBe(false);
});
it('is exposed and, like every other command, refuses to run when identity is not configured', async () => {
const { answer, run } = await import('./facetimeBridge.js');
expect(typeof answer).toBe('function');
await expect(run('answer', { facetime: { targetHandle: '', targetName: '' } }))
.rejects.toThrow();
});
});
describe('helper stdout', () => {
const readyConfig = {
facetime: { targetHandle: '+15551234567', targetName: 'Example Caller' },
};
const audioProbe = JSON.stringify({
SPAudioDataType: [{
_items: [
{ _name: 'BlackHole 2ch', coreaudio_device_srate: '48000', coreaudio_device_input: '2', coreaudio_device_output: '2' },
{ _name: 'BlackHole 16ch', coreaudio_device_srate: '48000', coreaudio_device_input: '16', coreaudio_device_output: '16' },
],
}],
});
const validResult = {
ok: true, command: 'probe', state: 'idle', authorized: true,
action: 'probe', message: 'ready', errorCode: null,
};
async function withReadyHelper(helperResult, body) {
const tempDir = mkdtempSync(join(process.env.PORTOS_TEST_TMPDIR || tmpdir(), 'portos-facetime-run-'));
const helperName = process.platform === 'win32' ? 'facetime-ax.exe' : 'facetime-ax';
writeFileSync(join(tempDir, helperName), '');
helperRun.voiceHome = tempDir;
helperRun.facetimeEnabled = true;
helperRun.spawnImpl = async (cmd) => (
cmd === 'system_profiler'
? { success: true, code: 0, signal: null, stdout: audioProbe, stderr: '', timedOut: false }
: helperResult
);
// FaceTime setup refuses every non-macOS host before it reads helper
// stdout. Pin darwin so the 502 contract is what this test actually hits.
const restorePlatform = pinPlatform('darwin');
try {
return await body();
} finally {
helperRun.voiceHome = null;
helperRun.facetimeEnabled = null;
helperRun.spawnImpl = null;
restorePlatform();
rmSync(tempDir, { recursive: true, force: true });
}
}
it('returns the parsed helper result when stdout matches the contract', async () => {
await withReadyHelper(
{ success: true, code: 0, signal: null, stdout: JSON.stringify(validResult), stderr: '', timedOut: false },
async () => {
await expect(run('probe', readyConfig)).resolves.toEqual(validResult);
},
);
});
it('reports non-JSON helper stdout as invalid-helper-result instead of a syntax failure', async () => {
await withReadyHelper(
{ success: false, code: 1, signal: null, stdout: 'dyld: library not loaded\n', stderr: '', timedOut: false },
async () => {
await expect(run('probe', readyConfig)).rejects.toMatchObject({
name: 'ServerError',
status: 502,
code: 'invalid-helper-result',
});
},
);
});
it('preserves a native confirmation failure at the bridge boundary', async () => {
const unconfirmed = {
...validResult, ok: false, command: 'hangup', state: 'unknown',
action: 'press-call-action', message: 'FaceTime action was sent, but its resulting state could not be confirmed',
errorCode: 'state-unconfirmed',
};
await withReadyHelper(
{ success: false, code: 1, signal: null, stdout: JSON.stringify(unconfirmed), stderr: '', timedOut: false },
async () => {
await expect(run('hangup', readyConfig)).rejects.toMatchObject({ status: 502, code: 'state-unconfirmed' });
},
);
});
});
});