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.

fix(voice): answer a key save once the voice workers are registered

shoudi zheng1e127f534966
diff --git a/apps/node-services/AGENTS.md b/apps/node-services/AGENTS.md
index 99e0bd33..fd2ce77a 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. 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
+ 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` (`node-services-internal` bearer), and every 60 seconds, so workers start, drain, or restart with a new key without restarting node-services. The reconcile route answers `{ready}` only after every wanted worker's health port reports it registered with LiveKit, or after 20 seconds, so TeamHub answers a key save once a voice session can be dispatched. 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/voice/service.ts b/apps/node-services/src/voice/service.ts
index 17aed044..d76b54ab 100644
--- a/apps/node-services/src/voice/service.ts
+++ b/apps/node-services/src/voice/service.ts
@@ -27,6 +27,9 @@ 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";
+/** Bounds how long a reconcile request waits for the wanted workers. */
+export const VOICE_READY_WAIT_MS = 20_000;
+const VOICE_READY_POLL_MS = 250;
type ProviderKeys = components["schemas"]["VoiceRuntimeProviderKeys"];
@@ -98,6 +101,20 @@ async function fetchProviderKeys(
};
}
+/** A LiveKit agents worker answers 2xx on its health port only once it is
+ * registered with LiveKit, so this is when it can take a dispatched job. */
+async function probeVoiceWorker(worker: VoiceWorker): Promise<boolean> {
+ try {
+ return (
+ await fetch(`http://127.0.0.1:${voiceWorkerPorts[worker]}/`, {
+ signal: AbortSignal.timeout(1_000),
+ })
+ ).ok;
+ } catch {
+ return false;
+ }
+}
+
/** Separate processes keep inference, recording and Agent work off each other's
* event loops. Workers follow TeamHub's effective provider keys: a reconcile
* starts, stops or replaces a worker, and only the failed worker restarts after
@@ -110,10 +127,12 @@ export async function startVoiceService(options: {
spawnWorker?: (worker: VoiceWorker, spec: VoiceWorkerSpawn) => ChildProcess;
installModels?: () => Promise<void>;
fetch?: typeof fetch;
+ probeWorker?: (worker: VoiceWorker) => Promise<boolean>;
}) {
const env = options.environment ?? process.env;
const config = readVoiceConfig(env);
const fetchImpl = options.fetch ?? fetch;
+ const probeWorker = options.probeWorker ?? probeVoiceWorker;
// 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");
@@ -133,6 +152,7 @@ export async function startVoiceService(options: {
}
: {};
let stopping = false;
+ const stopped = new AbortController();
const entries = new Map<
VoiceWorker,
{
@@ -276,13 +296,16 @@ export async function startVoiceService(options: {
});
}
};
- let running: Promise<void> | undefined;
+ let running: Promise<boolean> | undefined;
let again = false;
+ /** Resolves whether the last key fetch succeeded and was applied. */
const runReconcile = async () => {
+ let applied: boolean;
do {
again = false;
const result = await fetchProviderKeys(config, fetchImpl);
- if (stopping) return;
+ if (stopping) return false;
+ applied = result.ok;
if (result.ok) apply(result.keys);
else
options.logger.log("warn", "voice.reconcile_failed", {
@@ -290,10 +313,11 @@ export async function startVoiceService(options: {
...(result.status ? { status: result.status } : {}),
});
} while (again && !stopping);
+ return applied;
};
/** One reconcile runs at a time; triggers during it coalesce into one more. */
- const reconcile = (): Promise<void> => {
- if (stopping) return Promise.resolve();
+ const reconcile = (): Promise<boolean> => {
+ if (stopping) return Promise.resolve(false);
if (running) {
again = true;
return running;
@@ -314,6 +338,39 @@ export async function startVoiceService(options: {
const poll = setInterval(() => void reconcile(), VOICE_RECONCILE_POLL_MS);
const wantedWorkers = () =>
VOICE_WORKERS.filter((worker) => entries.get(worker)!.key);
+ const workersReady = async () =>
+ (
+ await Promise.all(
+ wantedWorkers().map(
+ async (worker) =>
+ Boolean(entries.get(worker)?.child) && (await probeWorker(worker)),
+ ),
+ )
+ ).every(Boolean);
+ /** Reconciles, then waits until every wanted worker can take a job, so the
+ * caller's next voice dispatch finds a registered worker. */
+ const reconcileAndWait = async () => {
+ if (!(await reconcile())) return false;
+ const deadline = Date.now() + VOICE_READY_WAIT_MS;
+ while (!stopping) {
+ if (await workersReady()) return !stopping;
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) return false;
+ await new Promise<void>((resolve) => {
+ const finish = () => {
+ clearTimeout(timer);
+ stopped.signal.removeEventListener("abort", finish);
+ resolve();
+ };
+ const timer = setTimeout(
+ finish,
+ Math.min(VOICE_READY_POLL_MS, remaining),
+ );
+ stopped.signal.addEventListener("abort", finish);
+ });
+ }
+ return false;
+ };
// 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({
@@ -340,34 +397,21 @@ export async function startVoiceService(options: {
);
if (request.method !== "POST")
return new Response(null, { status: 405, headers: { allow: "POST" } });
- void reconcile();
- return new Response(null, { status: 202 });
+ return reconcileAndWait().then((ready) => Response.json({ ready }));
},
readiness: async () => {
- const results = await Promise.all(
- wantedWorkers().map(async (worker) => {
- if (!entries.get(worker)?.child) return false;
- try {
- return (
- await fetch(`http://127.0.0.1:${voiceWorkerPorts[worker]}/`, {
- signal: AbortSignal.timeout(1_000),
- })
- ).ok;
- } catch {
- return false;
- }
- }),
- );
- return results.every(Boolean)
+ return (await workersReady())
? { ready: true }
: { ready: false, reason: "voice_worker_reconnecting" };
},
});
return {
- /** Runs one reconcile now, or joins the one in flight. */
+ /** Runs one reconcile now, or joins the one in flight; resolves whether
+ * the keys were read and applied. */
reconcile,
async stop() {
stopping = true;
+ stopped.abort();
clearInterval(poll);
unmount();
// Signal all workers together, so recorder flushing never waits for ASR.
diff --git a/apps/node-services/tests/voice-service.test.ts b/apps/node-services/tests/voice-service.test.ts
index 3b579c46..2ccb1d24 100644
--- a/apps/node-services/tests/voice-service.test.ts
+++ b/apps/node-services/tests/voice-service.test.ts
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { serviceCredential, type JsonLogger } from "@linger/service-kit/node";
import {
startVoiceService,
+ VOICE_READY_WAIT_MS,
VOICE_RECONCILE_POLL_MS,
type VoiceWorker,
type VoiceWorkerSpawn,
@@ -27,6 +28,7 @@ async function harness(
keys?: Record<string, unknown>;
env?: NodeJS.ProcessEnv;
failure?: "network" | number | "json";
+ healthy?: boolean;
} = {},
) {
vi.useFakeTimers();
@@ -58,6 +60,7 @@ async function harness(
spec: VoiceWorkerSpawn;
child: Worker;
}[] = [];
+ const health = { healthy: options.healthy ?? true };
const log = vi.fn();
let route: HttpRoute | undefined;
const unmount = vi.fn();
@@ -72,6 +75,7 @@ async function harness(
environment: { ...environment, ...options.env },
fetch: fetchImpl as unknown as typeof fetch,
installModels: async () => undefined,
+ probeWorker: async () => health.healthy,
spawnWorker: (worker, spec) => {
const child = new Worker();
spawned.push({ worker, spec, child });
@@ -89,6 +93,7 @@ async function harness(
return {
service,
shutdown,
+ health,
teamHub,
spawned,
of,
@@ -98,6 +103,15 @@ async function harness(
};
}
+function reconcileRequest() {
+ return new Request("http://x/v1/voice/workers:reconcile", {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${serviceCredential("node-services-internal", environment)}`,
+ },
+ });
+}
+
describe("voice worker reconcile", () => {
it("starts no worker without keys", async () => {
const { spawned, route, shutdown } = await harness();
@@ -216,18 +230,18 @@ describe("voice worker reconcile", () => {
const first = service.reconcile();
await vi.advanceTimersByTimeAsync(0);
const callsBefore = teamHub.calls;
- const notified = await route.fetch(
+ const notified = 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;
+ expect(await (await notified).json()).toEqual({ ready: true });
// The two overlapping triggers ran exactly one follow-up reconcile.
expect(teamHub.calls).toBe(callsBefore + 1);
expect(of("asr")).toHaveLength(1);
@@ -270,6 +284,81 @@ describe("voice worker reconcile", () => {
await shutdown();
});
+ it("answers a reconcile once the wanted workers are registered", async () => {
+ const { route, teamHub, health, shutdown, of } = await harness({
+ healthy: false,
+ });
+ teamHub.keys = { xai_api_key: XAI };
+ let answer: unknown;
+ const answered = Promise.resolve(route.fetch(reconcileRequest())).then(
+ async (response) => {
+ expect(response.status).toBe(200);
+ answer = await response.json();
+ },
+ );
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(of("live")).toHaveLength(1);
+ expect(answer).toBeUndefined();
+ health.healthy = true;
+ await vi.advanceTimersByTimeAsync(250);
+ await answered;
+ expect(answer).toEqual({ ready: true });
+ await shutdown();
+ });
+
+ it("answers not ready when the workers miss the wait", async () => {
+ const { route, teamHub, shutdown } = await harness({ healthy: false });
+ teamHub.keys = { soniox_api_key: SONIOX };
+ let answer: unknown;
+ const answered = Promise.resolve(route.fetch(reconcileRequest())).then(
+ async (response) => {
+ answer = await response.json();
+ },
+ );
+ await vi.advanceTimersByTimeAsync(VOICE_READY_WAIT_MS - 1_000);
+ expect(answer).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(1_000);
+ await answered;
+ expect(answer).toEqual({ ready: false });
+ await shutdown();
+ });
+
+ it("answers ready at once when no key wants a worker", async () => {
+ const { route, shutdown } = await harness({ healthy: false });
+ const response = await route.fetch(reconcileRequest());
+ expect(await response.json()).toEqual({ ready: true });
+ await shutdown();
+ });
+
+ it("answers not ready when TeamHub's keys cannot be read", async () => {
+ const { route, teamHub, shutdown, log } = await harness({
+ keys: { soniox_api_key: SONIOX },
+ });
+ teamHub.failure = 503;
+ const response = await route.fetch(reconcileRequest());
+ const body = await response.text();
+ expect(JSON.parse(body)).toEqual({ ready: false });
+ expect(body).not.toContain(SONIOX);
+ expect(JSON.stringify(log.mock.calls)).not.toContain(SONIOX);
+ await shutdown();
+ });
+
+ it("ends the readiness wait when the service stops", async () => {
+ const { route, teamHub, shutdown } = await harness({ healthy: false });
+ teamHub.keys = { xai_api_key: XAI };
+ let answer: unknown;
+ const answered = Promise.resolve(route.fetch(reconcileRequest())).then(
+ async (response) => {
+ answer = await response.json();
+ },
+ );
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(answer).toBeUndefined();
+ await shutdown();
+ await answered;
+ expect(answer).toEqual({ ready: false });
+ });
+
it("authenticates the reconcile route", async () => {
const { route, teamHub, shutdown } = await harness();
const calls = teamHub.calls;
diff --git a/apps/teamhub/internal/app/app.go b/apps/teamhub/internal/app/app.go
index fcea681f..dfeeba35 100644
--- a/apps/teamhub/internal/app/app.go
+++ b/apps/teamhub/internal/app/app.go
@@ -118,8 +118,9 @@ type App struct {
// voiceKeys resolves the Soniox and xAI keys at each use.
voiceKeys *voicekey.Service
// reconcileVoiceWorkers wakes the Node Services voice workers after a key
- // is saved; nil without a Node Services link.
- reconcileVoiceWorkers func(context.Context) error
+ // is saved and reports whether they are ready; nil without a Node Services
+ // link.
+ reconcileVoiceWorkers func(context.Context) (bool, error)
voiceRecordings *voicemedia.LocalStagingStore
accounts *account.Lifecycle
passwordHashes *account.HashLimiter
diff --git a/apps/teamhub/internal/app/feature_voice.go b/apps/teamhub/internal/app/feature_voice.go
index bb36c7e8..867583cf 100644
--- a/apps/teamhub/internal/app/feature_voice.go
+++ b/apps/teamhub/internal/app/feature_voice.go
@@ -18,9 +18,18 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicetranscription"
)
-// voiceReconcileTimeout bounds the best-effort wake of the Node Services voice
-// workers after a key is saved; their own periodic reconcile covers a miss.
-const voiceReconcileTimeout = 5 * time.Second
+// voiceReconcileTimeout bounds how long a key save waits for the Node Services
+// voice workers to register. It covers Node Services' key read and its 20 s
+// readiness wait; their own periodic reconcile covers a miss.
+const voiceReconcileTimeout = 30 * time.Second
+
+// voiceReconcileStatusError reports a reconcile answered with an unexpected
+// HTTP status.
+type voiceReconcileStatusError struct{ status int }
+
+func (e voiceReconcileStatusError) Error() string {
+ return fmt.Sprintf("Node Services voice reconcile returned HTTP %d", e.status)
+}
// registerVoice builds voice media while TEAMHUB_VOICE_MEDIA is on, or takes
// the plane a test injects; without LINGER_SECRET_SEED or ffmpeg it runs
@@ -97,21 +106,22 @@ func (a *App) buildVoiceMedia(cfg config.Config, injected voicemedia.Plane, obje
}
// newVoiceWorkerReconciler asks Node Services to start or stop its voice
-// workers for the keys now in effect. The request carries no key.
-func newVoiceWorkerReconciler(baseURL, token string) (func(context.Context) error, error) {
+// workers for the keys now in effect and reports whether every required worker
+// is ready to take a job. The request carries no key.
+func newVoiceWorkerReconciler(baseURL, token string) (func(context.Context) (bool, error), error) {
client, err := roomagent.NewAgentManagementClient(baseURL, token, &http.Client{Timeout: voiceReconcileTimeout})
if err != nil {
return nil, fmt.Errorf("configure Node Services voice reconcile: %w", err)
}
- return func(ctx context.Context) error {
+ return func(ctx context.Context) (bool, error) {
response, err := client.ReconcileVoiceWorkersWithResponse(ctx)
if err != nil {
- return err
+ return false, err
}
- if response.StatusCode() != http.StatusAccepted {
- return fmt.Errorf("Node Services voice reconcile returned HTTP %d", response.StatusCode())
+ if response.StatusCode() != http.StatusOK || response.JSON200 == nil {
+ return false, voiceReconcileStatusError{status: response.StatusCode()}
}
- return nil
+ return response.JSON200.Ready, nil
}, nil
}
diff --git a/apps/teamhub/internal/app/voice_provider_keys.go b/apps/teamhub/internal/app/voice_provider_keys.go
index 2e71ab34..a18a5892 100644
--- a/apps/teamhub/internal/app/voice_provider_keys.go
+++ b/apps/teamhub/internal/app/voice_provider_keys.go
@@ -43,25 +43,32 @@ func (a *App) saveVoiceProviderKey(c *gin.Context) {
a.internalError(c, "resolve voice provider key status", err)
return
}
- a.notifyVoiceWorkers(c.Request.Context())
+ a.awaitVoiceWorkers(c.Request.Context())
c.JSON(http.StatusOK, voiceProviderKeyModel(status))
}
}
-// notifyVoiceWorkers asks Node Services, in the background, to start the
-// voice workers the saved key enables. A failure only logs: the save stands
-// and Node Services' periodic reconcile picks the key up.
-func (a *App) notifyVoiceWorkers(requestContext context.Context) {
+// awaitVoiceWorkers asks Node Services to start the voice workers the saved
+// key enables and waits until they are registered with LiveKit, so a voice
+// session the client starts right after the save finds a worker to dispatch
+// to. A failure only logs: the save stands and Node Services' periodic
+// reconcile picks the key up.
+func (a *App) awaitVoiceWorkers(requestContext context.Context) {
if a.reconcileVoiceWorkers == nil {
return
}
- ctx, cancel := context.WithTimeout(context.WithoutCancel(requestContext), voiceReconcileTimeout)
- go func() {
- defer cancel()
- if err := a.reconcileVoiceWorkers(ctx); err != nil {
- a.logger.Warn("voice.reconcile_notify_failed", "error", err)
- }
- }()
+ ctx, cancel := context.WithTimeout(requestContext, voiceReconcileTimeout)
+ defer cancel()
+ ready, err := a.reconcileVoiceWorkers(ctx)
+ var statusErr voiceReconcileStatusError
+ switch {
+ case errors.As(err, &statusErr):
+ a.logger.Warn("voice.workers_not_ready", "reason", "status", "status", statusErr.status)
+ case err != nil:
+ a.logger.Warn("voice.workers_not_ready", "reason", "error", "error", err)
+ case !ready:
+ a.logger.Warn("voice.workers_not_ready", "reason", "not_ready")
+ }
}
func voiceProviderKeyModel(status voicekey.Status) httpapi.VoiceProviderKeyStatus {
diff --git a/apps/teamhub/internal/app/voice_provider_keys_test.go b/apps/teamhub/internal/app/voice_provider_keys_test.go
index 3ca1e16e..db9f8ff8 100644
--- a/apps/teamhub/internal/app/voice_provider_keys_test.go
+++ b/apps/teamhub/internal/app/voice_provider_keys_test.go
@@ -54,7 +54,7 @@ func (f voiceKeyCheck) Check(ctx context.Context, provider voicekey.Provider, ke
return f(ctx, provider, key)
}
-// syncBuffer collects log lines written from the background notify.
+// syncBuffer collects log lines written while a test reads them.
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
@@ -108,40 +108,77 @@ func putVoiceKey(a *App, provider, body string) *httptest.ResponseRecorder {
return response
}
-// A save answers with the new status, wakes Node Services once in the
-// background, and a failed wake only logs; the key appears in neither the
-// response nor the logs.
-func TestSaveVoiceProviderKeyNotifiesNodeServicesBestEffort(t *testing.T) {
+// A save answers only after Node Services reports its voice workers ready, so
+// a session started right after the save finds a registered worker.
+func TestSaveVoiceProviderKeyWaitsForVoiceWorkers(t *testing.T) {
a, logs := newVoiceKeyTestApp(t, voicekey.Config{Enabled: true, Box: testSecretBox(t)}, nil)
- notified := make(chan struct{}, 1)
- a.reconcileVoiceWorkers = func(ctx context.Context) error {
+ started := make(chan struct{})
+ release := make(chan struct{})
+ a.reconcileVoiceWorkers = func(ctx context.Context) (bool, error) {
if _, ok := ctx.Deadline(); !ok {
- t.Error("the reconcile notify has no deadline")
+ t.Error("the reconcile has no deadline")
}
- notified <- struct{}{}
- return errors.New("connection refused")
- }
- response := putVoiceKey(a, "soniox", `{"api_key":" `+testVoiceKey+` "}`)
- if response.Code != http.StatusOK || response.Body.String() != `{"can_save":true,"source":"stored"}` {
- t.Fatalf("save = %d %s", response.Code, response.Body)
+ close(started)
+ <-release
+ return true, nil
}
+ done := make(chan *httptest.ResponseRecorder, 1)
+ go func() { done <- putVoiceKey(a, "soniox", `{"api_key":" `+testVoiceKey+` "}`) }()
select {
- case <-notified:
+ case <-started:
case <-time.After(30 * time.Second):
- t.Fatal("Node Services was not notified")
+ t.Fatal("Node Services was not asked to reconcile")
}
- deadline := time.Now().Add(30 * time.Second)
- for !strings.Contains(logs.String(), "voice.reconcile_notify_failed") {
- if time.Now().After(deadline) {
- t.Fatalf("no notify failure log: %s", logs.String())
- }
- time.Sleep(10 * time.Millisecond)
+ select {
+ case response := <-done:
+ t.Fatalf("the save answered before the workers were ready: %d", response.Code)
+ case <-time.After(50 * time.Millisecond):
}
- if key, _ := a.voiceKeys.Effective(t.Context(), voicekey.Soniox); key != testVoiceKey {
- t.Fatalf("effective key = %q", key)
+ close(release)
+ response := <-done
+ if response.Code != http.StatusOK || response.Body.String() != `{"can_save":true,"source":"stored"}` {
+ t.Fatalf("save = %d %s", response.Code, response.Body)
+ }
+ if strings.Contains(logs.String(), "voice.workers_not_ready") {
+ t.Fatalf("ready workers logged as not ready: %s", logs.String())
}
- if strings.Contains(response.Body.String(), testVoiceKey) || strings.Contains(logs.String(), testVoiceKey) {
- t.Fatal("the key leaked into the response or the logs")
+}
+
+// Workers that are not ready, or a reconcile that fails, never fail the save;
+// they log the reason without the key.
+func TestSaveVoiceProviderKeyLogsVoiceWorkersNotReady(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ result func(context.Context) (bool, error)
+ reason string
+ }{
+ {"not ready", func(context.Context) (bool, error) { return false, nil }, `"reason":"not_ready"`},
+ {"status", func(context.Context) (bool, error) { return false, voiceReconcileStatusError{status: 503} }, `"reason":"status","status":503`},
+ {"error", func(context.Context) (bool, error) { return false, errors.New("connection refused") }, `"reason":"error"`},
+ {"timeout", func(ctx context.Context) (bool, error) {
+ timeout, cancel := context.WithTimeout(ctx, time.Millisecond)
+ defer cancel()
+ <-timeout.Done()
+ return false, timeout.Err()
+ }, `"reason":"error"`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ a, logs := newVoiceKeyTestApp(t, voicekey.Config{Enabled: true, Box: testSecretBox(t)}, nil)
+ a.reconcileVoiceWorkers = tc.result
+ response := putVoiceKey(a, "xai", `{"api_key":"`+testVoiceKey+`"}`)
+ if response.Code != http.StatusOK || response.Body.String() != `{"can_save":true,"source":"stored"}` {
+ t.Fatalf("save = %d %s", response.Code, response.Body)
+ }
+ if !strings.Contains(logs.String(), `"msg":"voice.workers_not_ready"`) || !strings.Contains(logs.String(), tc.reason) {
+ t.Fatalf("no not-ready log with %s: %s", tc.reason, logs.String())
+ }
+ if key, _ := a.voiceKeys.Effective(t.Context(), voicekey.XAI); key != testVoiceKey {
+ t.Fatalf("effective key = %q", key)
+ }
+ if strings.Contains(response.Body.String(), testVoiceKey) || strings.Contains(logs.String(), testVoiceKey) {
+ t.Fatal("the key leaked into the response or the logs")
+ }
+ })
}
}
@@ -167,9 +204,9 @@ func TestSaveVoiceProviderKeyErrors(t *testing.T) {
} {
t.Run(tc.name, func(t *testing.T) {
a, logs := newVoiceKeyTestApp(t, tc.cfg, tc.check)
- a.reconcileVoiceWorkers = func(context.Context) error {
+ a.reconcileVoiceWorkers = func(context.Context) (bool, error) {
t.Error("a refused save notified Node Services")
- return nil
+ return true, nil
}
response := putVoiceKey(a, tc.provider, tc.body)
if response.Code != tc.status || !strings.Contains(response.Body.String(), `"code":"`+tc.code+`"`) {
diff --git a/apps/web/src/features/apps/provider-key-form.tsx b/apps/web/src/features/apps/provider-key-form.tsx
index 058b1105..6c3ad6c5 100644
--- a/apps/web/src/features/apps/provider-key-form.tsx
+++ b/apps/web/src/features/apps/provider-key-form.tsx
@@ -16,6 +16,7 @@ export function ProviderKeyForm({
hint,
label,
onSaved,
+ pendingLabel = "Checking key...",
save,
}: {
/** The message shown under the field when `save` fails. */
@@ -23,6 +24,8 @@ export function ProviderKeyForm({
hint: string;
label: string;
onSaved?: () => void;
+ /** The Save button's text while `save` runs. */
+ pendingLabel?: string;
save: (apiKey: string) => Promise<unknown>;
}) {
const [apiKey, setApiKey] = useState("");
@@ -57,7 +60,7 @@ export function ProviderKeyForm({
tone="primary"
type="submit"
>
- {mutation.isPending ? "Checking key..." : "Save key"}
+ {mutation.isPending ? pendingLabel : "Save key"}
</Button>
</form>
);
diff --git a/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx b/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx
index 45b4a4b2..df85f655 100644
--- a/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx
+++ b/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx
@@ -225,6 +225,33 @@ describe("VoiceKeyDialog", () => {
expect(onReady).not.toHaveBeenCalled();
});
+ it("says voice is turning on while the save waits for it", async () => {
+ const runtime = createTestTeamHubRuntime();
+ let answer: (() => void) | undefined;
+ runtime.server.on(
+ "PUT",
+ "/v0/voice-provider-keys/{provider}",
+ () =>
+ new Promise((resolve) => {
+ answer = () => resolve({ source: "stored", can_save: true });
+ }),
+ );
+ renderDialog(runtime, noKeys);
+ fireEvent.change(screen.getByLabelText("Soniox API key"), {
+ target: { value: "soniox-key" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save key" }));
+ expect(
+ await screen.findByRole("button", { name: /Turning on voice/ }),
+ ).toBeDisabled();
+ answer!();
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("button", { name: /Turning on voice/ }),
+ ).toBeNull(),
+ );
+ });
+
it("explains that the deployment must configure a key it cannot save", () => {
const runtime = createTestTeamHubRuntime();
renderDialog(runtime, {
diff --git a/apps/web/src/features/rooms/voice-control/voice-key-dialog.tsx b/apps/web/src/features/rooms/voice-control/voice-key-dialog.tsx
index cdb833d9..8497936b 100644
--- a/apps/web/src/features/rooms/voice-control/voice-key-dialog.tsx
+++ b/apps/web/src/features/rooms/voice-control/voice-key-dialog.tsx
@@ -210,6 +210,8 @@ export function VoiceKeyDialog({
hint="Stored encrypted and never shown again."
key={provider}
label={`${details.name} API key`}
+ // TeamHub answers the save once the voice workers are up.
+ pendingLabel="Turning on voice…"
save={async (apiKey) => {
await teamHubData(
client.api.PUT("/v0/voice-provider-keys/{provider}", {
diff --git a/contracts/generated/go/nodeservicesinternal/openapi.gen.go b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
index 8ef66bdf..cde43f86 100644
--- a/contracts/generated/go/nodeservicesinternal/openapi.gen.go
+++ b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
@@ -2207,6 +2207,12 @@ type UpdateDocumentBlockSemanticOperation struct {
StableBlockId DocumentInternalId `json:"stable_block_id"`
}
+// VoiceWorkersReconcileResult defines model for VoiceWorkersReconcileResult.
+type VoiceWorkersReconcileResult struct {
+ // Ready Every worker the effective keys require is ready to take a job.
+ Ready bool `json:"ready"`
+}
+
// WikiRefreshBasePage defines model for WikiRefreshBasePage.
type WikiRefreshBasePage struct {
MarkdownContent []byte `json:"markdown_content"`
@@ -7015,6 +7021,7 @@ func (r ScanLocalComputerSkillsResponse) ContentType() string {
type ReconcileVoiceWorkersResponse struct {
Body []byte
HTTPResponse *http.Response
+ JSON200 *VoiceWorkersReconcileResult
JSON401 *Unauthenticated
}
@@ -9154,6 +9161,13 @@ func ParseReconcileVoiceWorkersResponse(rsp *http.Response) (*ReconcileVoiceWork
}
switch {
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
+ var dest VoiceWorkersReconcileResult
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON200 = &dest
+
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401:
var dest Unauthenticated
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
index b1b092cb..6162d245 100644
--- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts
+++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
@@ -557,8 +557,8 @@ export interface paths {
get?: never;
put?: never;
/**
- * Schedule a reconcile of the voice workers against TeamHub's effective provider keys
- * @description It only schedules the reconcile and never carries keys; workers read keys from TeamHub.
+ * Reconcile the voice workers against TeamHub's effective provider keys and wait for them
+ * @description Runs a reconcile, or joins the one in flight, then waits until every worker the effective keys require is registered and ready, up to a bounded wait. It never carries keys; workers read keys from TeamHub. `ready=false` means the wait ended first or the keys could not be read.
*/
post: operations["reconcileVoiceWorkers"];
delete?: never;
@@ -1181,6 +1181,10 @@ export interface components {
| "durability_invariant_failed";
document_id: components["schemas"]["DocumentInternalId"];
};
+ VoiceWorkersReconcileResult: {
+ /** @description Every worker the effective keys require is ready to take a job. */
+ ready: boolean;
+ };
LocalComputerToolCall: {
tenant_id: string;
owner_actor_id: string;
@@ -2864,12 +2868,14 @@ export interface operations {
};
requestBody?: never;
responses: {
- /** @description Reconcile scheduled. */
- 202: {
+ /** @description Reconcile ran; whether the required workers are ready. */
+ 200: {
headers: {
[name: string]: unknown;
};
- content?: never;
+ content: {
+ "application/json": components["schemas"]["VoiceWorkersReconcileResult"];
+ };
};
401: components["responses"]["Unauthenticated"];
};
diff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yaml
index 42005340..33c80345 100644
--- a/contracts/openapi/node-services-internal/openapi.yaml
+++ b/contracts/openapi/node-services-internal/openapi.yaml
@@ -1123,12 +1123,20 @@ paths:
/v1/voice/workers:reconcile:
post:
tags: [Voice]
- summary: Schedule a reconcile of the voice workers against TeamHub's effective provider keys
- description: It only schedules the reconcile and never carries keys; workers read keys from TeamHub.
+ summary: Reconcile the voice workers against TeamHub's effective provider keys and wait for them
+ description:
+ Runs a reconcile, or joins the one in flight, then waits until every
+ worker the effective keys require is registered and ready, up to a
+ bounded wait. It never carries keys; workers read keys from TeamHub.
+ `ready=false` means the wait ended first or the keys could not be read.
operationId: reconcileVoiceWorkers
responses:
- "202":
- description: Reconcile scheduled.
+ "200":
+ description: Reconcile ran; whether the required workers are ready.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/VoiceWorkersReconcileResult"
"401":
$ref: ../components/common.yaml#/components/responses/Unauthenticated
security:
@@ -2753,6 +2761,14 @@ components:
$ref: ../components/document-internal.yaml#/components/schemas/DurableAckEnvelope
DurabilityFailureEnvelope:
$ref: ../components/document-internal.yaml#/components/schemas/DurabilityFailureEnvelope
+ VoiceWorkersReconcileResult:
+ type: object
+ additionalProperties: false
+ required: [ready]
+ properties:
+ ready:
+ type: boolean
+ description: Every worker the effective keys require is ready to take a job.
LocalComputerToolCall:
type: object
additionalProperties: false