Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(node-services): start voice workers from TeamHub's provider keys

shoudi zhengf17ab5c1d70f
diff --git a/apps/node-services/AGENTS.md b/apps/node-services/AGENTS.md
index 23af3a68..ebe71c2a 100644
--- a/apps/node-services/AGENTS.md
+++ b/apps/node-services/AGENTS.md
@@ -16,7 +16,7 @@
role's readiness ok); roles must not register their own probes.
- The `document` role keeps its own port (4321 by default) on its own worker
thread (`src/document/main.ts`) because it installs jsdom globals and
- replaces the global `Request`/`Response`. The `voice` role supervises separate ASR, recorder and Live child processes (ports 4324–4326); it does not run audio jobs on the main thread. Other roles run on the main thread
+ replaces the global `Request`/`Response`. The `voice` role supervises separate ASR, recorder and Live child processes (ports 4324–4326); it does not run audio jobs on the main thread. Voice workers follow TeamHub's effective provider keys (`GET /internal/v1/voice/provider-keys` with the `voice-runtime` credential): a Soniox key runs ASR and recorder, an xAI key runs Live. The role reconciles at startup, on TeamHub's `POST /v1/voice/workers:reconcile` notification (`node-services-internal` bearer), and every 60 seconds, so workers start, drain, or restart with a new key without restarting node-services. Keys reach a worker only through its environment; a failed key fetch leaves the running workers unchanged. Other roles run on the main thread
and must not install process globals.
- `NODE_SERVICES_ROLES` selects roles as a comma-separated list. An unset or
empty value starts every role; an unknown role fails startup. Selected roles
diff --git a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
index 8af7a491..ef9fc141 100644
--- a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
+++ b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
@@ -10,7 +10,7 @@ import {
type ExecutionContextRef,
} from "../context-ref.js";
import { AgentLifecycleCoordinator } from "../lifecycle-coordinator.js";
-import { hasBearerToken } from "../../service-bearer-auth.js";
+import { hasBearerToken } from "../../../service-bearer-auth.js";
import {
parseLocalPlacement,
type LocalAgentRunnerManagement,
diff --git a/apps/node-services/src/agent/service-bearer-auth.ts b/apps/node-services/src/service-bearer-auth.ts
similarity index 100%
rename from apps/node-services/src/agent/service-bearer-auth.ts
rename to apps/node-services/src/service-bearer-auth.ts
diff --git a/apps/node-services/src/voice/config.ts b/apps/node-services/src/voice/config.ts
new file mode 100644
index 00000000..fcf9173b
--- /dev/null
+++ b/apps/node-services/src/voice/config.ts
@@ -0,0 +1,21 @@
+import { serviceCredential } from "@linger/service-kit/node";
+import { teamHubBaseUrl } from "../teamhub-base-url.js";
+
+export interface VoiceConfig {
+ readonly teamHubBaseUrl: string;
+ /** Reads provider keys from TeamHub; undefined without LINGER_SECRET_SEED. */
+ readonly teamHubCredential: string | undefined;
+ /** Authenticates TeamHub's reconcile notifications. */
+ readonly managementCredential: string | undefined;
+}
+
+export function readVoiceConfig(environment: NodeJS.ProcessEnv): VoiceConfig {
+ return Object.freeze({
+ teamHubBaseUrl: teamHubBaseUrl(environment),
+ teamHubCredential: serviceCredential("voice-runtime", environment),
+ managementCredential: serviceCredential(
+ "node-services-internal",
+ environment,
+ ),
+ });
+}
diff --git a/apps/node-services/src/voice/service.ts b/apps/node-services/src/voice/service.ts
index 376b1dd5..4e481696 100644
--- a/apps/node-services/src/voice/service.ts
+++ b/apps/node-services/src/voice/service.ts
@@ -1,7 +1,10 @@
import { spawn, type ChildProcess } from "node:child_process";
+import { randomBytes } from "node:crypto";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import type { JsonLogger } from "@linger/service-kit/node";
+import { isRecord } from "@linger/service-kit";
+import { sha256Hex, type JsonLogger } from "@linger/service-kit/node";
+import type { components } from "@linger/wire-contracts/teamhub-internal/types";
import type { HttpHost } from "../http-host.js";
import {
installModelPackages,
@@ -9,6 +12,8 @@ import {
modelPackagesInstalled,
modelPackagesRoot,
} from "../model-packages.js";
+import { hasBearerToken } from "../service-bearer-auth.js";
+import { readVoiceConfig, type VoiceConfig } from "./config.js";
export type VoiceWorker = "asr" | "recorder" | "live";
export const voiceWorkerPorts = {
@@ -16,28 +21,99 @@ export const voiceWorkerPorts = {
recorder: 4325,
live: 4326,
} as const;
+const VOICE_WORKERS = ["asr", "recorder", "live"] as const;
// LiveKit drains for 2 s, then allows jobs 68 s to save their final media.
export const VOICE_DRAIN_MS = 72_000;
+/** Catches a reconcile notification that TeamHub could not deliver. */
+export const VOICE_RECONCILE_POLL_MS = 60_000;
+const RECONCILE_PATH = "/v1/voice/workers:reconcile";
+
+type ProviderKeys = components["schemas"]["VoiceRuntimeProviderKeys"];
+
+export interface VoiceWorkerSpawn {
+ readonly args: string[];
+ readonly env: NodeJS.ProcessEnv;
+}
/** Soniox runs transcription and recording; xAI runs Live on its own. */
-export function selectedVoiceWorkers(env: NodeJS.ProcessEnv): VoiceWorker[] {
- return [
- ...(env.SONIOX_API_KEY?.trim() ? (["asr", "recorder"] as const) : []),
- ...(env.XAI_API_KEY?.trim() ? (["live"] as const) : []),
- ];
+export function workerKeys(
+ keys: ProviderKeys,
+): Map<VoiceWorker, { variable: string; key: string }> {
+ const soniox = keys.soniox_api_key?.trim();
+ const xai = keys.xai_api_key?.trim();
+ const workers = new Map<VoiceWorker, { variable: string; key: string }>();
+ if (soniox) {
+ workers.set("asr", { variable: "SONIOX_API_KEY", key: soniox });
+ workers.set("recorder", { variable: "SONIOX_API_KEY", key: soniox });
+ }
+ if (xai) workers.set("live", { variable: "XAI_API_KEY", key: xai });
+ return workers;
+}
+
+type FetchResult =
+ | { readonly ok: true; readonly keys: ProviderKeys }
+ | { readonly ok: false; readonly reason: string; readonly status?: number };
+
+async function fetchProviderKeys(
+ config: VoiceConfig,
+ fetchImpl: typeof fetch,
+): Promise<FetchResult> {
+ if (!config.teamHubCredential)
+ return { ok: false, reason: "credential_missing" };
+ let response: Response;
+ try {
+ response = await fetchImpl(
+ new URL("/internal/v1/voice/provider-keys", config.teamHubBaseUrl),
+ {
+ headers: { authorization: `Bearer ${config.teamHubCredential}` },
+ signal: AbortSignal.timeout(10_000),
+ },
+ );
+ } catch {
+ return { ok: false, reason: "teamhub_unreachable" };
+ }
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ return { ok: false, reason: "teamhub_status", status: response.status };
+ }
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch {
+ return { ok: false, reason: "invalid_response" };
+ }
+ if (!isRecord(body)) return { ok: false, reason: "invalid_response" };
+ const { soniox_api_key: soniox, xai_api_key: xai } = body;
+ if (
+ (soniox !== undefined && typeof soniox !== "string") ||
+ (xai !== undefined && typeof xai !== "string")
+ )
+ return { ok: false, reason: "invalid_response" };
+ return {
+ ok: true,
+ keys: {
+ ...(soniox ? { soniox_api_key: soniox } : {}),
+ ...(xai ? { xai_api_key: xai } : {}),
+ },
+ };
}
/** Separate processes keep inference, recording and Agent work off each other's
- * event loops. Only the failed worker restarts; accepted Tasks belong to TeamHub. */
+ * event loops. Workers follow TeamHub's effective provider keys: a reconcile
+ * starts, stops or replaces a worker, and only the failed worker restarts after
+ * a crash. Both act on one entry per worker; a generation number makes every
+ * pending start, restart or drain from a superseded process a no-op. */
export async function startVoiceService(options: {
logger: JsonLogger;
http: HttpHost;
environment?: NodeJS.ProcessEnv;
- spawnWorker?: (worker: VoiceWorker) => ChildProcess;
+ spawnWorker?: (worker: VoiceWorker, spec: VoiceWorkerSpawn) => ChildProcess;
installModels?: () => Promise<void>;
+ fetch?: typeof fetch;
}) {
const env = options.environment ?? process.env;
- const workers = selectedVoiceWorkers(env);
+ const config = readVoiceConfig(env);
+ const fetchImpl = options.fetch ?? fetch;
// The VAD model's native package, when the runtime ships it separately: the
// workers wait for its first download and find it on NODE_PATH.
const models = modelPackageNames("voice");
@@ -54,39 +130,24 @@ export async function startVoiceService(options: {
const entries = new Map<
VoiceWorker,
{
+ /** The key this worker should run with; absent means stopped. */
+ key?: { variable: string; key: string };
+ digest?: string;
+ generation: number;
child?: ChildProcess;
exited?: Promise<void>;
retry?: NodeJS.Timeout;
failures: number;
}
- >();
+ >(VOICE_WORKERS.map((worker) => [worker, { generation: 0, failures: 0 }]));
const launch =
options.spawnWorker ??
- ((worker: VoiceWorker) => {
- const entry = fileURLToPath(
- import.meta.resolve("@linger/voice-runtime/worker"),
- );
- return spawn(
- process.execPath,
- [
- ...(entry.endsWith(".ts")
- ? ["--import", "tsx"]
- : ["--conditions=linger-production"]),
- entry,
- "start",
- ...(worker === "asr" ? [] : [`--${worker}`]),
- ],
- {
- env: {
- ...env,
- ...modelPath,
- VOICE_WORKER_PORT: String(voiceWorkerPorts[worker]),
- },
- stdio: ["ignore", "inherit", "inherit", "ipc"],
- detached: process.platform !== "win32",
- },
- );
- });
+ ((_worker: VoiceWorker, spec: VoiceWorkerSpawn) =>
+ spawn(process.execPath, spec.args, {
+ env: spec.env,
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
+ detached: process.platform !== "win32",
+ }));
const killGroup = (child: ChildProcess) => {
if (!child.pid) return;
try {
@@ -97,18 +158,69 @@ export async function startVoiceService(options: {
options.logger.log("error", "voice.worker_cleanup_failed", { error });
}
};
+ const drain = async (
+ child: ChildProcess,
+ exited: Promise<void> | undefined,
+ ) => {
+ const timer = setTimeout(() => killGroup(child), VOICE_DRAIN_MS);
+ child.kill("SIGTERM");
+ try {
+ await exited;
+ } finally {
+ clearTimeout(timer);
+ }
+ };
const start = (worker: VoiceWorker) => {
- if (stopping) return;
- const entry = entries.get(worker) ?? { failures: 0 };
- entries.set(worker, entry);
+ const entry = entries.get(worker)!;
+ const key = entry.key;
+ if (stopping || !key) return;
+ const generation = entry.generation;
+ const current = () => !stopping && generation === entry.generation;
const startedAt = Date.now();
+ function restart(error: unknown) {
+ if (!current()) return;
+ options.logger.log("warn", "voice.worker_restarting", { worker, error });
+ entry.failures = Date.now() - startedAt > 60_000 ? 0 : entry.failures + 1;
+ entry.retry = setTimeout(
+ () => {
+ entry.retry = undefined;
+ if (current()) start(worker);
+ },
+ Math.min(30_000, 1_000 * 2 ** Math.min(entry.failures - 1, 5)),
+ );
+ }
if (!modelPackagesInstalled(models, env)) {
- install().then(() => start(worker), restart);
+ install().then(() => {
+ if (current()) start(worker);
+ }, restart);
return;
}
+ const workerEntry = fileURLToPath(
+ import.meta.resolve("@linger/voice-runtime/worker"),
+ );
let child: ChildProcess;
try {
- child = launch(worker);
+ // Keys travel only in the child's environment. Both provider variables
+ // are set explicitly, so a key inherited by node-services never wins.
+ child = launch(worker, {
+ args: [
+ ...(workerEntry.endsWith(".ts")
+ ? ["--import", "tsx"]
+ : ["--conditions=linger-production"]),
+ workerEntry,
+ "start",
+ ...(worker === "asr" ? [] : [`--${worker}`]),
+ ],
+ env: {
+ ...env,
+ ...modelPath,
+ SONIOX_API_KEY: "",
+ XAI_API_KEY: "",
+ [key.variable]: key.key,
+ TEAMHUB_BASE_URL: config.teamHubBaseUrl,
+ VOICE_WORKER_PORT: String(voiceWorkerPorts[worker]),
+ },
+ });
} catch (error) {
restart(error);
return;
@@ -119,32 +231,109 @@ export async function startVoiceService(options: {
const finish = (error?: unknown) => {
if (settled) return;
settled = true;
- entry.child = undefined;
+ if (entry.child === child) entry.child = undefined;
killGroup(child);
resolve();
- if (!stopping) restart(error);
+ restart(error);
};
child.once("error", finish);
child.once("exit", (code, signal) => finish({ code, signal }));
});
- function restart(error: unknown) {
- options.logger.log("warn", "voice.worker_restarting", { worker, error });
- entry.failures = Date.now() - startedAt > 60_000 ? 0 : entry.failures + 1;
- entry.retry = setTimeout(
- () => start(worker),
- Math.min(30_000, 1_000 * 2 ** Math.min(entry.failures - 1, 5)),
- );
+ };
+ const apply = (keys: ProviderKeys) => {
+ const wanted = workerKeys(keys);
+ for (const worker of VOICE_WORKERS) {
+ const entry = entries.get(worker)!;
+ const key = wanted.get(worker);
+ const digest = key ? sha256Hex(key.key) : undefined;
+ // An unchanged key leaves a running, restarting or installing worker alone.
+ if (digest === entry.digest) continue;
+ entry.generation += 1;
+ const generation = entry.generation;
+ clearTimeout(entry.retry);
+ entry.retry = undefined;
+ entry.key = key;
+ entry.digest = digest;
+ entry.failures = 0;
+ options.logger.log("info", "voice.worker_reconciled", {
+ worker,
+ action: !key ? "stop" : entry.child ? "replace" : "start",
+ });
+ const child = entry.child;
+ if (!child) {
+ start(worker);
+ continue;
+ }
+ // The replacement binds the same port, so it waits for the old drain.
+ void drain(child, entry.exited).then(() => {
+ if (generation === entry.generation) start(worker);
+ });
}
};
- for (const worker of workers) start(worker);
+ let running: Promise<void> | undefined;
+ let again = false;
+ const runReconcile = async () => {
+ do {
+ again = false;
+ const result = await fetchProviderKeys(config, fetchImpl);
+ if (stopping) return;
+ if (result.ok) apply(result.keys);
+ else
+ options.logger.log("warn", "voice.reconcile_failed", {
+ reason: result.reason,
+ ...(result.status ? { status: result.status } : {}),
+ });
+ } while (again && !stopping);
+ };
+ /** One reconcile runs at a time; triggers during it coalesce into one more. */
+ const reconcile = (): Promise<void> => {
+ if (stopping) return Promise.resolve();
+ if (running) {
+ again = true;
+ return running;
+ }
+ running = runReconcile().finally(() => {
+ running = undefined;
+ });
+ return running;
+ };
+ // TeamHub may still be starting; a failed first reconcile retries on the poll.
+ void reconcile();
+ const poll = setInterval(() => void reconcile(), VOICE_RECONCILE_POLL_MS);
+ const wantedWorkers = () =>
+ VOICE_WORKERS.filter((worker) => entries.get(worker)!.key);
// Readiness may fail while media reconnects; liveness continues to keep the
// Agent and other media workers running. No provider credentials are returned.
const unmount = options.http.mount({
- prefixes: ["/voice/health"],
- fetch: () => Response.json({ workers }),
+ prefixes: ["/voice/health", RECONCILE_PATH],
+ fetch: (request) => {
+ if (new URL(request.url).pathname !== RECONCILE_PATH)
+ return Response.json({ workers: wantedWorkers() });
+ if (
+ !config.managementCredential ||
+ !hasBearerToken(
+ request.headers.get("authorization") ?? undefined,
+ config.managementCredential,
+ )
+ )
+ return Response.json(
+ {
+ error: {
+ code: "UNAUTHENTICATED",
+ message: "Service bearer token is required",
+ request_id: `request_${randomBytes(16).toString("hex")}`,
+ },
+ },
+ { status: 401 },
+ );
+ if (request.method !== "POST")
+ return new Response(null, { status: 405, headers: { allow: "POST" } });
+ void reconcile();
+ return new Response(null, { status: 202 });
+ },
readiness: async () => {
const results = await Promise.all(
- workers.map(async (worker) => {
+ wantedWorkers().map(async (worker) => {
if (!entries.get(worker)?.child) return false;
try {
return (
@@ -163,22 +352,18 @@ export async function startVoiceService(options: {
},
});
return {
+ /** Runs one reconcile now, or joins the one in flight. */
+ reconcile,
async stop() {
stopping = true;
+ clearInterval(poll);
unmount();
// Signal all workers together, so recorder flushing never waits for ASR.
await Promise.all(
[...entries.values()].map(async (entry) => {
clearTimeout(entry.retry);
const child = entry.child;
- if (!child) return;
- const timer = setTimeout(() => killGroup(child), VOICE_DRAIN_MS);
- child.kill("SIGTERM");
- try {
- await entry.exited;
- } finally {
- clearTimeout(timer);
- }
+ if (child) await drain(child, entry.exited);
}),
);
},
diff --git a/apps/node-services/tests/agent/test-support/runner-credential-authority.ts b/apps/node-services/tests/agent/test-support/runner-credential-authority.ts
index ee730b5d..e7b4b540 100644
--- a/apps/node-services/tests/agent/test-support/runner-credential-authority.ts
+++ b/apps/node-services/tests/agent/test-support/runner-credential-authority.ts
@@ -8,7 +8,7 @@ import {
type RunnerCredentialAuthenticator,
type RunnerGatewayCredential,
} from "../../../src/agent/runner-gateway/runner-credential-authority.js";
-import { hasBearerToken } from "../../../src/agent/service-bearer-auth.js";
+import { hasBearerToken } from "../../../src/service-bearer-auth.js";
export const TEST_RUNNER_SIGNING_KEY =
"runner-signing-key-that-is-at-least-32-bytes";
diff --git a/apps/node-services/tests/model-packages.test.ts b/apps/node-services/tests/model-packages.test.ts
index fe1a9074..3baea84b 100644
--- a/apps/node-services/tests/model-packages.test.ts
+++ b/apps/node-services/tests/model-packages.test.ts
@@ -237,14 +237,29 @@ describe("features that need model packages", () => {
const service = await startVoiceService({
logger: { log: vi.fn() } as unknown as JsonLogger,
http: { mount: () => () => {} } as unknown as HttpHost,
- environment: { ...environment, XAI_API_KEY: "test" },
+ environment: {
+ ...environment,
+ LINGER_SECRET_SEED: "model-packages-test-seed-0123456789abcdef",
+ },
+ fetch: async () => Response.json({ xai_api_key: "test" }),
spawnWorker,
installModels,
});
- expect(installModels).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(installModels).toHaveBeenCalledOnce());
expect(spawnWorker).not.toHaveBeenCalled();
installed();
- await vi.waitFor(() => expect(spawnWorker).toHaveBeenCalledWith("live"));
+ await vi.waitFor(() =>
+ expect(spawnWorker).toHaveBeenCalledWith(
+ "live",
+ expect.objectContaining({
+ env: expect.objectContaining({
+ NODE_PATH: expect.stringContaining(
+ models.modelPackagesRoot(environment),
+ ),
+ }),
+ }),
+ ),
+ );
const stopping = service.stop();
(spawnWorker.mock.results[0]!.value as EventEmitter).emit("exit", 0, null);
await stopping;
diff --git a/apps/node-services/tests/voice-service.test.ts b/apps/node-services/tests/voice-service.test.ts
index 93b196d9..3b579c46 100644
--- a/apps/node-services/tests/voice-service.test.ts
+++ b/apps/node-services/tests/voice-service.test.ts
@@ -1,65 +1,318 @@
import { EventEmitter } from "node:events";
import type { ChildProcess } from "node:child_process";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { serviceCredential, type JsonLogger } from "@linger/service-kit/node";
import {
startVoiceService,
- selectedVoiceWorkers,
+ VOICE_RECONCILE_POLL_MS,
type VoiceWorker,
+ type VoiceWorkerSpawn,
} from "../src/voice/service.js";
-import type { HttpHost } from "../src/http-host.js";
-import type { JsonLogger } from "@linger/service-kit/node";
+import type { HttpHost, HttpRoute } from "../src/http-host.js";
class Worker extends EventEmitter {
kill = vi.fn(() => true);
}
+const environment = {
+ LINGER_SECRET_SEED: "voice-service-test-seed-0123456789abcdef",
+ TEAMHUB_BASE_URL: "http://teamhub.test",
+};
+const SONIOX = "soniox-key-1";
+const XAI = "xai-key-1";
+
afterEach(() => vi.useRealTimers());
-describe("unified voice supervision", () => {
- it("only starts configured media capabilities", () => {
- expect(selectedVoiceWorkers({})).toEqual([]);
- expect(selectedVoiceWorkers({ SONIOX_API_KEY: "test" })).toEqual([
- "asr",
- "recorder",
- ]);
- expect(selectedVoiceWorkers({ XAI_API_KEY: "test" })).toEqual(["live"]);
+
+async function harness(
+ options: {
+ keys?: Record<string, unknown>;
+ env?: NodeJS.ProcessEnv;
+ failure?: "network" | number | "json";
+ } = {},
+) {
+ vi.useFakeTimers();
+ const teamHub = {
+ keys: options.keys ?? {},
+ failure: options.failure,
+ calls: 0,
+ pending: [] as (() => void)[],
+ hold: false,
+ };
+ const fetchImpl = vi.fn(async (url: URL | string, init?: RequestInit) => {
+ teamHub.calls += 1;
+ expect(String(url)).toBe(
+ "http://teamhub.test/internal/v1/voice/provider-keys",
+ );
+ expect(new Headers(init?.headers).get("authorization")).toBe(
+ `Bearer ${serviceCredential("voice-runtime", environment)}`,
+ );
+ if (teamHub.hold)
+ await new Promise<void>((resolve) => teamHub.pending.push(resolve));
+ if (teamHub.failure === "network") throw new TypeError("fetch failed");
+ if (typeof teamHub.failure === "number")
+ return new Response("{}", { status: teamHub.failure });
+ if (teamHub.failure === "json") return new Response("not json");
+ return Response.json(teamHub.keys);
+ });
+ const spawned: {
+ worker: VoiceWorker;
+ spec: VoiceWorkerSpawn;
+ child: Worker;
+ }[] = [];
+ const log = vi.fn();
+ let route: HttpRoute | undefined;
+ const unmount = vi.fn();
+ const service = await startVoiceService({
+ logger: { log } as unknown as JsonLogger,
+ http: {
+ mount: (mounted: HttpRoute) => {
+ route = mounted;
+ return unmount;
+ },
+ } as unknown as HttpHost,
+ environment: { ...environment, ...options.env },
+ fetch: fetchImpl as unknown as typeof fetch,
+ installModels: async () => undefined,
+ spawnWorker: (worker, spec) => {
+ const child = new Worker();
+ spawned.push({ worker, spec, child });
+ return child as unknown as ChildProcess;
+ },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ const of = (worker: VoiceWorker) =>
+ spawned.filter((entry) => entry.worker === worker);
+ const shutdown = async () => {
+ const stopped = service.stop();
+ for (const { child } of spawned) child.emit("exit", 0, null);
+ await stopped;
+ };
+ return {
+ service,
+ shutdown,
+ teamHub,
+ spawned,
+ of,
+ log,
+ route: route!,
+ unmount,
+ };
+}
+
+describe("voice worker reconcile", () => {
+ it("starts no worker without keys", async () => {
+ const { spawned, route, shutdown } = await harness();
+ expect(spawned).toHaveLength(0);
+ const health = await route.fetch(new Request("http://x/voice/health"));
+ expect(await health.json()).toEqual({ workers: [] });
+ expect(await route.readiness!()).toEqual({ ready: true });
+ await shutdown();
+ });
+
+ it("starts workers as keys appear, with the key only in the child env", async () => {
+ const { spawned, of, teamHub, service, shutdown, log } = await harness();
+ teamHub.keys = { soniox_api_key: SONIOX };
+ await service.reconcile();
+ expect(spawned.map(({ worker }) => worker)).toEqual(["asr", "recorder"]);
+ for (const { spec } of spawned) {
+ expect(spec.env.SONIOX_API_KEY).toBe(SONIOX);
+ expect(spec.env.XAI_API_KEY).toBe("");
+ expect(spec.env.TEAMHUB_BASE_URL).toBe("http://teamhub.test");
+ expect(spec.args.join(" ")).not.toContain(SONIOX);
+ }
+ expect(of("recorder")[0]!.spec.args).toContain("--recorder");
+ teamHub.keys = { soniox_api_key: SONIOX, xai_api_key: XAI };
+ await service.reconcile();
+ expect(of("live")).toHaveLength(1);
+ expect(of("live")[0]!.spec.env).toMatchObject({
+ XAI_API_KEY: XAI,
+ SONIOX_API_KEY: "",
+ });
+ expect(of("live")[0]!.spec.args.join(" ")).not.toContain(XAI);
+ expect(JSON.stringify(log.mock.calls)).not.toMatch(/soniox-key|xai-key/);
+ await shutdown();
+ });
+
+ it("never passes an inherited key to a worker", async () => {
+ const { spawned, teamHub, service, shutdown, of } = await harness({
+ env: { SONIOX_API_KEY: "inherited", XAI_API_KEY: "inherited" },
+ });
+ expect(spawned).toHaveLength(0);
+ teamHub.keys = { xai_api_key: XAI };
+ await service.reconcile();
+ expect(spawned).toHaveLength(1);
+ expect(of("live")[0]!.spec.env.SONIOX_API_KEY).toBe("");
+ expect(of("live")[0]!.spec.env.XAI_API_KEY).toBe(XAI);
+ await shutdown();
+ });
+
+ it("restarts nothing for unchanged keys and only the worker whose key changed", async () => {
+ const { spawned, of, teamHub, service, shutdown } = await harness({
+ keys: { soniox_api_key: SONIOX, xai_api_key: XAI },
+ });
+ expect(spawned).toHaveLength(3);
+ await service.reconcile();
+ await vi.advanceTimersByTimeAsync(VOICE_RECONCILE_POLL_MS);
+ expect(spawned).toHaveLength(3);
expect(
- selectedVoiceWorkers({ SONIOX_API_KEY: "test", XAI_API_KEY: "test" }),
- ).toEqual(["asr", "recorder", "live"]);
+ spawned.every(({ child }) => child.kill.mock.calls.length === 0),
+ ).toBe(true);
+ teamHub.keys = { soniox_api_key: SONIOX, xai_api_key: "xai-key-2" };
+ await service.reconcile();
+ const oldLive = of("live")[0]!.child;
+ expect(oldLive.kill).toHaveBeenCalledWith("SIGTERM");
+ // The replacement waits for the old process to leave the port.
+ expect(of("live")).toHaveLength(1);
+ oldLive.emit("exit", 0, null);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(of("live")).toHaveLength(2);
+ expect(of("live")[1]!.spec.env.XAI_API_KEY).toBe("xai-key-2");
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(of("live")).toHaveLength(2);
+ expect(of("asr")).toHaveLength(1);
+ expect(of("recorder")).toHaveLength(1);
+ await shutdown();
+ });
+
+ it("drains a worker whose key was removed and keeps it stopped after it exits", async () => {
+ const { of, teamHub, service, shutdown, route } = await harness({
+ keys: { soniox_api_key: SONIOX, xai_api_key: XAI },
+ });
+ teamHub.keys = { soniox_api_key: SONIOX };
+ await service.reconcile();
+ const live = of("live")[0]!.child;
+ expect(live.kill).toHaveBeenCalledWith("SIGTERM");
+ live.emit("exit", 1, null);
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(of("live")).toHaveLength(1);
+ const health = await route.fetch(new Request("http://x/voice/health"));
+ expect(await health.json()).toEqual({ workers: ["asr", "recorder"] });
+ await shutdown();
+ });
+
+ it("does not start a second process while a worker is in restart backoff", async () => {
+ const { of, teamHub, service, shutdown } = await harness({
+ keys: { xai_api_key: XAI },
+ });
+ of("live")[0]!.child.emit("exit", 1, null);
+ await service.reconcile();
+ await vi.advanceTimersByTimeAsync(999);
+ expect(of("live")).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(of("live")).toHaveLength(2);
+ // A key removed during backoff cancels the pending restart.
+ of("live")[1]!.child.emit("exit", 1, null);
+ teamHub.keys = {};
+ await service.reconcile();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(of("live")).toHaveLength(2);
+ await shutdown();
+ });
+
+ it("runs one reconcile at a time and coalesces overlapping triggers", async () => {
+ const { of, teamHub, service, shutdown, route } = await harness();
+ const token = serviceCredential("node-services-internal", environment);
+ teamHub.hold = true;
+ teamHub.keys = { soniox_api_key: SONIOX };
+ const first = service.reconcile();
+ await vi.advanceTimersByTimeAsync(0);
+ const callsBefore = teamHub.calls;
+ const notified = await route.fetch(
+ new Request("http://x/v1/voice/workers:reconcile", {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}` },
+ }),
+ );
+ expect(notified.status).toBe(202);
+ await vi.advanceTimersByTimeAsync(VOICE_RECONCILE_POLL_MS);
+ expect(teamHub.calls).toBe(callsBefore);
+ teamHub.hold = false;
+ teamHub.pending.splice(0).forEach((resolve) => resolve());
+ await first;
+ // The two overlapping triggers ran exactly one follow-up reconcile.
+ expect(teamHub.calls).toBe(callsBefore + 1);
+ expect(of("asr")).toHaveLength(1);
+ expect(of("recorder")).toHaveLength(1);
+ await shutdown();
+ });
+
+ it.each(["network", 401, 503, "json"] as const)(
+ "keeps current workers when TeamHub fails (%s)",
+ async (failure) => {
+ const { spawned, teamHub, service, shutdown, log } = await harness({
+ keys: { soniox_api_key: SONIOX },
+ });
+ teamHub.failure = failure;
+ teamHub.keys = {};
+ await service.reconcile();
+ expect(spawned).toHaveLength(2);
+ expect(spawned.every(({ child }) => !child.kill.mock.calls.length)).toBe(
+ true,
+ );
+ expect(log).toHaveBeenCalledWith(
+ "warn",
+ "voice.reconcile_failed",
+ expect.objectContaining({ reason: expect.any(String) }),
+ );
+ expect(JSON.stringify(log.mock.calls)).not.toContain(SONIOX);
+ await shutdown();
+ },
+ );
+
+ it("retries a failed startup reconcile on the poll", async () => {
+ const { spawned, teamHub, shutdown } = await harness({
+ keys: { soniox_api_key: SONIOX },
+ failure: "network",
+ });
+ expect(spawned).toHaveLength(0);
+ teamHub.failure = undefined;
+ await vi.advanceTimersByTimeAsync(VOICE_RECONCILE_POLL_MS);
+ expect(spawned).toHaveLength(2);
+ await shutdown();
});
+
+ it("authenticates the reconcile route", async () => {
+ const { route, teamHub, shutdown } = await harness();
+ const calls = teamHub.calls;
+ for (const authorization of [undefined, "Bearer wrong"]) {
+ const response = await route.fetch(
+ new Request("http://x/v1/voice/workers:reconcile", {
+ method: "POST",
+ ...(authorization ? { headers: { authorization } } : {}),
+ }),
+ );
+ expect(response.status).toBe(401);
+ expect((await response.json()).error.code).toBe("UNAUTHENTICATED");
+ }
+ await vi.advanceTimersByTimeAsync(0);
+ expect(teamHub.calls).toBe(calls);
+ await shutdown();
+ });
+
it("restarts only the failed worker and drains all media before returning", async () => {
- vi.useFakeTimers();
- const children = new Map<VoiceWorker, Worker[]>();
- const unmount = vi.fn();
- const service = await startVoiceService({
- logger: { log: vi.fn() } as unknown as JsonLogger,
- http: { mount: () => unmount } as unknown as HttpHost,
- environment: { SONIOX_API_KEY: "test", XAI_API_KEY: "test" },
- spawnWorker: (worker) => {
- const child = new Worker();
- children.set(worker, [...(children.get(worker) ?? []), child]);
- return child as unknown as ChildProcess;
- },
+ const { of, service, unmount, teamHub } = await harness({
+ keys: { soniox_api_key: SONIOX, xai_api_key: XAI },
});
- children.get("live")![0]!.emit("exit", 1, null);
+ of("live")[0]!.child.emit("exit", 1, null);
await vi.advanceTimersByTimeAsync(1000);
- expect(children.get("live")).toHaveLength(2);
- expect(children.get("recorder")).toHaveLength(1);
- expect(children.get("asr")).toHaveLength(1);
+ expect(of("live")).toHaveLength(2);
+ expect(of("recorder")).toHaveLength(1);
+ expect(of("asr")).toHaveLength(1);
let drained = false;
const stopping = service.stop().then(() => {
drained = true;
});
for (const worker of ["asr", "recorder", "live"] as const)
- expect(children.get(worker)!.at(-1)!.kill).toHaveBeenCalledWith(
- "SIGTERM",
- );
- children.get("live")!.at(-1)!.emit("exit", 0, null);
- children.get("asr")![0]!.emit("exit", 0, null);
+ expect(of(worker).at(-1)!.child.kill).toHaveBeenCalledWith("SIGTERM");
+ of("live").at(-1)!.child.emit("exit", 0, null);
+ of("asr")[0]!.child.emit("exit", 0, null);
await vi.advanceTimersByTimeAsync(2000);
expect(drained).toBe(false);
- children.get("recorder")![0]!.emit("exit", 0, null);
+ of("recorder")[0]!.child.emit("exit", 0, null);
await stopping;
- await vi.advanceTimersByTimeAsync(30000);
- expect(children.get("live")).toHaveLength(2);
+ const calls = teamHub.calls;
+ await vi.advanceTimersByTimeAsync(VOICE_RECONCILE_POLL_MS * 2);
+ expect(of("live")).toHaveLength(2);
+ expect(teamHub.calls).toBe(calls);
expect(unmount).toHaveBeenCalledOnce();
});
});