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(web): keep voice entries visible and take voice keys in place
shoudi zheng614d5a885412
diff --git a/apps/web/src/features/apps/connect-app-flow.tsx b/apps/web/src/features/apps/connect-app-flow.tsxindex 7dc8c85a..29de435c 100644--- a/apps/web/src/features/apps/connect-app-flow.tsx+++ b/apps/web/src/features/apps/connect-app-flow.tsx@@ -13,7 +13,7 @@ import type {import { AppLogoTile } from "./app-logo";import { externalAppsQueryOptions } from "./connected-apps-queries";import { openOAuthUrl } from "./oauth-popup";-import { ProviderKeyForm } from "./provider-key-form";+import { ComposioKeyForm } from "./provider-key-form";import { ComposioKeyGuide } from "./provider-key-guide";import {isComposioKeyRejected,@@ -153,7 +153,7 @@ export function ConnectAppStatus({) : flow.canSaveKey ? (<><ComposioKeyGuide />- <ProviderKeyForm onSaved={flow.keySaved} />+ <ComposioKeyForm onSaved={flow.keySaved} /></>) : flow.keyRejected ? (<p className="text-app-muted">diff --git a/apps/web/src/features/apps/provider-key-form.tsx b/apps/web/src/features/apps/provider-key-form.tsxindex 567eb790..058b1105 100644--- a/apps/web/src/features/apps/provider-key-form.tsx+++ b/apps/web/src/features/apps/provider-key-form.tsx@@ -7,19 +7,29 @@ import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";import { externalAppsQueryOptions } from "./connected-apps-queries";-// A private deployment without COMPOSIO_API_KEY saves its key here. TeamHub-// checks the key before keeping it and never returns it.-export function ProviderKeyForm({ onSaved }: { onSaved?: () => void } = {}) {- const { client } = useTeamHubRuntime();- const queryClient = useQueryClient();+/**+ * Takes one provider API key and hands it to `save`. TeamHub checks a key+ * before keeping it and never returns it, so the field clears once it is saved.+ */+export function ProviderKeyForm({+ describeError = (error) => error.message,+ hint,+ label,+ onSaved,+ save,+}: {+ /** The message shown under the field when `save` fails. */+ describeError?: (error: Error) => string;+ hint: string;+ label: string;+ onSaved?: () => void;+ save: (apiKey: string) => Promise<unknown>;+}) {const [apiKey, setApiKey] = useState("");- const save = useMutation({- mutationFn: () => client.saveExternalProviderKey(apiKey.trim()),- onSuccess: async () => {+ const mutation = useMutation({+ mutationFn: () => save(apiKey.trim()),+ onSuccess: () => {setApiKey("");- await queryClient.invalidateQueries({- queryKey: externalAppsQueryOptions(client).queryKey,- });onSaved?.();},});@@ -28,14 +38,14 @@ export function ProviderKeyForm({ onSaved }: { onSaved?: () => void } = {}) {className="space-y-3"onSubmit={(event) => {event.preventDefault();- if (apiKey.trim()) save.mutate();+ if (apiKey.trim()) mutation.mutate();}}><FieldautoComplete="off"- error={save.error?.message}- hint="Use a key with full read and write access (Read All and Write All). It is stored encrypted and never shown again."- label="Composio API key"+ error={mutation.error ? describeError(mutation.error) : undefined}+ hint={hint}+ label={label}onChange={(event) => setApiKey(event.target.value)}spellCheck={false}type="password"@@ -43,12 +53,31 @@ export function ProviderKeyForm({ onSaved }: { onSaved?: () => void } = {}) {/><Buttondisabled={!apiKey.trim()}- loading={save.isPending}+ loading={mutation.isPending}tone="primary"type="submit">- {save.isPending ? "Checking key..." : "Save key"}+ {mutation.isPending ? "Checking key..." : "Save key"}</Button></form>);}++// A private deployment without COMPOSIO_API_KEY saves its key here.+export function ComposioKeyForm({ onSaved }: { onSaved?: () => void } = {}) {+ const { client } = useTeamHubRuntime();+ const queryClient = useQueryClient();+ return (+ <ProviderKeyForm+ hint="Use a key with full read and write access (Read All and Write All). It is stored encrypted and never shown again."+ label="Composio API key"+ onSaved={onSaved}+ save={async (apiKey) => {+ await client.saveExternalProviderKey(apiKey);+ await queryClient.invalidateQueries({+ queryKey: externalAppsQueryOptions(client).queryKey,+ });+ }}+ />+ );+}diff --git a/apps/web/src/features/rooms/cards/decision-provider-key-view.tsx b/apps/web/src/features/rooms/cards/decision-provider-key-view.tsxindex 6e15b388..22c8a9e4 100644--- a/apps/web/src/features/rooms/cards/decision-provider-key-view.tsx+++ b/apps/web/src/features/rooms/cards/decision-provider-key-view.tsx@@ -12,7 +12,7 @@ import { Icon, type IconSvgElement } from "@/components/ui/icon";import { ModalDialog } from "@/components/ui/modal-dialog";import { ConnectorsNotConfiguredMessage } from "@/features/apps/connect-app-flow";import { externalAppsQueryOptions } from "@/features/apps/connected-apps-queries";-import { ProviderKeyForm } from "@/features/apps/provider-key-form";+import { ComposioKeyForm } from "@/features/apps/provider-key-form";import { ComposioKeyGuide } from "@/features/apps/provider-key-guide";import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";@@ -122,7 +122,7 @@ export function ProviderKeyDecision({) : (<><ComposioKeyGuide />- <ProviderKeyForm onSaved={() => setOpen(false)} />+ <ComposioKeyForm onSaved={() => setOpen(false)} /></>)}</div>diff --git a/apps/web/src/features/rooms/chat/message-composer.tsx b/apps/web/src/features/rooms/chat/message-composer.tsxindex 59ae4d72..ebdfae87 100644--- a/apps/web/src/features/rooms/chat/message-composer.tsx+++ b/apps/web/src/features/rooms/chat/message-composer.tsx@@ -740,13 +740,18 @@ function ComposerSendControls({voiceModeTarget?.tenantId ?? "",Boolean(voiceModeTarget),);- // Without Soniox or xAI there is no Voice Mode, so the empty composer keeps- // its send button. Until the policy answers the voice entry keeps the slot,- // so a deployment with voice never flashes the send button first.+ // A deployment that cannot run voice has no Voice Mode, so the empty+ // composer keeps its send button; one that can shows Voice Mode even before+ // a key exists, and the button asks for the key. Older servers without+ // `voice_available` offer it only once Soniox or xAI is configured. Until+ // the policy answers the voice entry keeps the slot, so a deployment with+ // voice never flashes the send button first.const voiceOff =voicePolicy !== undefined &&- voicePolicy.voice_media_supported !== true &&- voicePolicy.live_supported !== true;+ !(+ voicePolicy.voice_available ??+ (voicePolicy.voice_media_supported || voicePolicy.live_supported === true)+ );return (<ComposerToolbarattachmentEnabled={attachmentEnabled}diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-materials-composer.test.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-materials-composer.test.tsxindex 0682f5ae..30563ffc 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-materials-composer.test.tsx+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-materials-composer.test.tsx@@ -117,17 +117,24 @@ beforeEach(() => {describe("voice material composer", () => {it.each([- [false, false, "Send message"],- [true, false, "Start Voice Mode"],- [false, true, "Start Voice Mode"],+ [false, false, undefined, "Send message"],+ [true, false, undefined, "Start Voice Mode"],+ [false, true, undefined, "Start Voice Mode"],+ // A deployment that runs voice offers it before any key is saved.+ [false, false, true, "Start Voice Mode"],+ [false, false, false, "Send message"],])(- "on an empty draft shows the right corner by the voice policy (dictation %s, live %s)",- async (dictation, live, shown) => {+ "on an empty draft shows the right corner by the voice policy (dictation %s, live %s, available %s)",+ async (dictation, live, available, shown) => {const runtime = createTestTeamHubRuntime();runtime.server.on("GET","/v0/tenants/{tenantId}/voice-media-policy",- () => ({ voice_media_supported: dictation, live_supported: live }),+ () => ({+ voice_media_supported: dictation,+ live_supported: live,+ ...(available === undefined ? {} : { voice_available: available }),+ }),);const view = render(<TeamHubRuntimeProvider runtime={runtime}>diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.test.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.test.tsxindex 18336c5c..5f489eac 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.test.tsx+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.test.tsx@@ -5,9 +5,12 @@ import {render,screen,waitFor,+ within,} from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, describe, expect, it, vi } from "vitest";import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";+import { teamHubErrorResponse } from "@/test/teamhub-test-server";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";import { useEffect, useLayoutEffect, useRef } from "react";import { useVoiceMediaPolicy } from "@/features/rooms/voice-control/use-voice-media-policy";@@ -435,3 +438,76 @@ describe("Voice Mode controls", () => {expect(transport.open).not.toHaveBeenCalled();});});++describe("Voice Mode without a voice key", () => {+ it("asks for a key when neither exists and enters Live once xAI is saved", async () => {+ const runtime = createTestTeamHubRuntime();+ const missing = { source: "none" as const, can_save: true };+ let saved = false;+ const liveSessions: unknown[] = [];+ runtime.server+ .on("GET", "/v0/tenants/{tenantId}/voice-media-policy", () =>+ saved+ ? {+ voice_available: true,+ voice_media_supported: false,+ live_supported: true,+ live_enabled: true,+ soniox_key: missing,+ xai_key: { source: "stored", can_save: true },+ }+ : {+ voice_available: true,+ voice_media_supported: false,+ live_supported: false,+ soniox_key: missing,+ xai_key: missing,+ },+ )+ .on("PUT", "/v0/voice-provider-keys/{provider}", ({ params }) => {+ expect(params.provider).toBe("xai");+ saved = true;+ return { source: "stored", can_save: true };+ })+ .on("POST", "/v0/rooms/{roomId}/voice-sessions", ({ body }) => {+ liveSessions.push(body);+ return teamHubErrorResponse(503, "VOICE_PROVIDER_UNAVAILABLE");+ });+ render(+ <QueryClientProvider client={new QueryClient()}>+ <TeamHubRuntimeProvider runtime={runtime}>+ <VoiceModeSessionProvider>+ <BoundControls+ target={{+ tenantId: "tenant-northstar",+ roomId: "room-another-me",+ }}+ disabled={false}+ empty+ onChange={vi.fn()}+ onSend={vi.fn()}+ />+ </VoiceModeSessionProvider>+ </TeamHubRuntimeProvider>+ </QueryClientProvider>,+ );+ fireEvent.click(+ await screen.findByRole("button", { name: "Start Voice Mode" }),+ );+ const dialog = await screen.findByRole("dialog", { name: "Turn on voice" });+ expect(+ within(dialog).getByRole("button", { name: "Soniox" }),+ ).toBeVisible();+ fireEvent.click(within(dialog).getByRole("button", { name: "xAI" }));+ fireEvent.change(within(dialog).getByLabelText("xAI API key"), {+ target: { value: "xai-key" },+ });+ fireEvent.click(within(dialog).getByRole("button", { name: "Save key" }));+ // Live opens its own session; the dictation transport stays unused.+ await waitFor(() =>+ expect(liveSessions).toEqual([{ purpose: "chat_live" }]),+ );+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(transport.open).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.tsxindex 0d261432..687514e8 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.tsx+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-controls.tsx@@ -7,7 +7,7 @@ import {VolumeHighIcon,VolumeOffIcon,} from "@hugeicons/core-free-icons";-import { useEffect, type CSSProperties } from "react";+import { useEffect, useState, type CSSProperties } from "react";import { Icon } from "@/components/ui/icon";import { Button } from "@/components/ui/button";import type {@@ -23,6 +23,7 @@ import {import styles from "./voice-mode.module.css";import { voiceModeStatusLabel } from "./voice-mode-presentation";import { openVoicePip } from "./voice-pip";+import { LazyVoiceKeyDialog } from "@/features/rooms/voice-control/lazy-voice-key-dialog";export type { VoiceModePresentation } from "./voice-mode-presentation";@@ -39,6 +40,15 @@ export interface VoiceModeTarget {const waveformDotCount = 160;const noVoiceModes: VoiceModeModes = { dictation: false, live: false };+function voiceModes(policy: TeamHubVoiceMediaPolicy | undefined) {+ return policy+ ? {+ dictation: policy.voice_media_supported === true,+ live: policy.live_supported === true,+ }+ : noVoiceModes;+}+/*** The Room composer's view of the app-level Voice Mode session: it starts the* session for this Room and shows its live controls, but the session itself@@ -56,13 +66,12 @@ export function VoiceModeControls(props: {const { roomId, tenantId } = props.target;// xAI makes Voice Mode a Live conversation; with Soniox alone it dictates.const policy = props.policy;- const modes: VoiceModeModes = policy- ? {- dictation: policy.voice_media_supported === true,- live: policy.live_supported === true,- }- : noVoiceModes;+ const modes: VoiceModeModes = voiceModes(policy);const supported = modes.dictation || modes.live;+ // A deployment that runs voice offers Voice Mode before any key exists;+ // the click then asks for a Soniox or xAI key.+ const offered = supported || policy?.voice_available === true;+ const [keyDialogOpen, setKeyDialogOpen] = useState(false);// Once Voice Mode is offered, its code loads in the background.const prepare = voice?.prepare;useEffect(() => {@@ -74,8 +83,12 @@ export function VoiceModeControls(props: {const elsewhere = session && !here ? session : undefined;const entered = Boolean(here?.entered);const closing = Boolean(here?.closing);- const enter = () => {- if (!voice || !supported || props.disabled || session) return;+ const enter = (next = modes) => {+ if (!voice || props.disabled || session) return;+ if (!next.dictation && !next.live) {+ if (offered) setKeyDialogOpen(true);+ return;+ }// Only this click may open the floating window that stays over other// tabs and apps, so it opens now while the session starts.void openVoicePip("voice-mode");@@ -88,31 +101,47 @@ export function VoiceModeControls(props: {tenantId,},props.prefix,- modes,+ next,);};- if (!entered && !closing && (!props.empty || !supported)) return null;+ if (!entered && !closing && (!props.empty || !offered)) return null;if (!entered)return (- <Button- aria-label={closing ? "Finishing Voice Mode" : "Start Voice Mode"}- title={- closing- ? "Finishing last words and releasing the microphone"- : elsewhere- ? `Voice Mode is on in ${elsewhere.target.roomName || "another Room"}`- : modes.live- ? "Voice Mode: a live conversation with Grok"- : "Voice Mode: sends when you finish speaking"- }- className="message-composer-send"- disabled={closing || props.disabled || !supported || Boolean(elsewhere)}- onClick={enter}- size="compactIcon"- tone="primary"- >- <Icon icon={AudioWave01Icon} size={16} />- </Button>+ <>+ <Button+ aria-label={closing ? "Finishing Voice Mode" : "Start Voice Mode"}+ title={+ closing+ ? "Finishing last words and releasing the microphone"+ : elsewhere+ ? `Voice Mode is on in ${elsewhere.target.roomName || "another Room"}`+ : modes.live+ ? "Voice Mode: a live conversation with Grok"+ : modes.dictation+ ? "Voice Mode: sends when you finish speaking"+ : "Voice Mode: add a Soniox or xAI key to start"+ }+ className="message-composer-send"+ disabled={closing || props.disabled || Boolean(elsewhere)}+ onClick={() => enter()}+ size="compactIcon"+ tone="primary"+ >+ <Icon icon={AudioWave01Icon} size={16} />+ </Button>+ {keyDialogOpen ? (+ <LazyVoiceKeyDialog+ onClose={() => setKeyDialogOpen(false)}+ onReady={(_provider, next) => {+ setKeyDialogOpen(false);+ enter(voiceModes(next));+ }}+ policy={policy}+ providers={["xai", "soniox"]}+ tenantId={tenantId}+ />+ ) : null}+ </>);const state = here!.state;const muted = here!.muted;diff --git a/apps/web/src/features/rooms/pocket-notes/pocket-note-panel.tsx b/apps/web/src/features/rooms/pocket-notes/pocket-note-panel.tsxindex df541d4d..dc647e76 100644--- a/apps/web/src/features/rooms/pocket-notes/pocket-note-panel.tsx+++ b/apps/web/src/features/rooms/pocket-notes/pocket-note-panel.tsx@@ -38,6 +38,7 @@ import {removePocketNote,storeTodayPocketNote,} from "./pocket-note-queries";+import { LazyVoiceKeyDialog } from "@/features/rooms/voice-control/lazy-voice-key-dialog";import { usePocketDictation } from "./use-pocket-dictation";import {PocketNoteEditor,@@ -262,6 +263,7 @@ function TodayPocketNote({update(before + fitted + tail);}+ const [keyDialogOpen, setKeyDialogOpen] = useState(false);const dictation = usePocketDictation({onTurn: insertSpoken,roomId: anotherMeRoomId,@@ -331,6 +333,13 @@ function TodayPocketNote({void stopDictation();return;}+ if (dictation.needsKey) {+ setKeyDialogOpen(true);+ return;+ }+ startDictation();+ }+ function startDictation() {setTruncated(false);anchor.current = editorRef.current?.selectionStart() ?? anchor.current;blockStart.current = anchor.current;@@ -405,6 +414,18 @@ function TodayPocketNote({onClick={toggleDictation}/>) : null}+ {keyDialogOpen ? (+ <LazyVoiceKeyDialog+ onClose={() => setKeyDialogOpen(false)}+ onReady={() => {+ setKeyDialogOpen(false);+ startDictation();+ }}+ policy={dictation.policy}+ providers={["soniox"]}+ tenantId={tenantId}+ />+ ) : null}</div></>);diff --git a/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.test.tsx b/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.test.tsxindex 1e025898..677dcf5b 100644--- a/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.test.tsx+++ b/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.test.tsx@@ -125,3 +125,41 @@ describe("Pocket Note dictation session lifecycle", () => {expect(connections[1]!.close).toHaveBeenCalledTimes(1);});});++describe("Pocket Note dictation availability", () => {+ it.each([+ [{ voice_available: true, voice_media_supported: false }, true, true],+ [{ voice_available: false, voice_media_supported: false }, false, true],+ // Older servers do not send voice_available.+ [{ voice_media_supported: false }, false, true],+ [{ voice_media_supported: true }, true, false],+ ])(+ "for policy %j offers dictation %s and asks for a key %s",+ async (policy, available, needsKey) => {+ const runtime = createTestTeamHubRuntime();+ runtime.server.on(+ "GET",+ "/v0/tenants/{tenantId}/voice-media-policy",+ () => policy,+ );+ const { result } = renderHook(+ () =>+ usePocketDictation({+ roomId: "room-1",+ tenantId: "tenant-1",+ onTurn: vi.fn(),+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) => (+ <TeamHubRuntimeProvider runtime={runtime}>+ {children}+ </TeamHubRuntimeProvider>+ ),+ },+ );+ await vi.waitFor(() => expect(result.current.policy).toBeDefined());+ expect(result.current.available).toBe(available);+ expect(result.current.needsKey).toBe(needsKey);+ },+ );+});diff --git a/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.ts b/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.tsindex dbad2dce..8f6bbe1c 100644--- a/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.ts+++ b/apps/web/src/features/rooms/pocket-notes/use-pocket-dictation.ts@@ -38,10 +38,11 @@ export function usePocketDictation({useLayoutEffect(() => {latest.current = { hardware, onTurn };});- // Dictation transcribes with Soniox.- const supported =- useVoiceMediaPolicy(tenantId, Boolean(roomId))?.voice_media_supported ===- true;+ // Dictation transcribes with Soniox. A deployment that runs voice offers it+ // before the key exists; older servers only once Soniox is configured.+ const policy = useVoiceMediaPolicy(tenantId, Boolean(roomId));+ const supported = policy?.voice_media_supported === true;+ const offered = policy?.voice_available ?? supported;const [state, setState] = useState(idle);const [level, setLevel] = useState(0);const [stopping, setStopping] = useState(false);@@ -120,7 +121,10 @@ export function usePocketDictation({state.status === "closing";return {- available: supported && Boolean(roomId),+ available: offered && Boolean(roomId),+ /** Starting asks for a Soniox key first. */+ needsKey: !supported,+ policy,active,// The Voice Runtime buffers published audio (up to 20s) until its ASR// stream opens, so speech is safe once the microphone track is live.diff --git a/apps/web/src/features/rooms/room-secondary-navigation.tsx b/apps/web/src/features/rooms/room-secondary-navigation.tsxindex 04bfddb1..b9e8e4d9 100644--- a/apps/web/src/features/rooms/room-secondary-navigation.tsx+++ b/apps/web/src/features/rooms/room-secondary-navigation.tsx@@ -215,7 +215,10 @@ export function RoomSecondaryNavigation({anotherMeRoomId={anotherMeRoomId}tenantId={tenant.id}/>- <RecordingEntry anotherMeRoomId={anotherMeRoomId} />+ <RecordingEntry+ anotherMeRoomId={anotherMeRoomId}+ tenantId={tenant.id}+ /></div><buttonaria-label="Hide Chat list"@@ -236,7 +239,10 @@ export function RoomSecondaryNavigation({anotherMeRoomId={anotherMeRoomId}tenantId={tenant.id}/>- <RecordingEntry anotherMeRoomId={anotherMeRoomId} />+ <RecordingEntry+ anotherMeRoomId={anotherMeRoomId}+ tenantId={tenant.id}+ /><buttonaria-keyshortcuts="Control+k Meta+k"aria-label="Search"diff --git a/apps/web/src/features/rooms/voice-control/lazy-voice-key-dialog.tsx b/apps/web/src/features/rooms/voice-control/lazy-voice-key-dialog.tsxnew file mode 100644index 00000000..666f524c--- /dev/null+++ b/apps/web/src/features/rooms/voice-control/lazy-voice-key-dialog.tsx@@ -0,0 +1,16 @@+import { lazy, Suspense, type ComponentProps } from "react";++const VoiceKeyDialog = lazy(async () => ({+ default: (await import("./voice-key-dialog")).VoiceKeyDialog,+}));++/** The voice key dialog, loaded only when a voice entry opens it. */+export function LazyVoiceKeyDialog(+ props: ComponentProps<typeof VoiceKeyDialog>,+) {+ return (+ <Suspense fallback={null}>+ <VoiceKeyDialog {...props} />+ </Suspense>+ );+}diff --git a/apps/web/src/features/rooms/voice-control/recording-entry.test.tsx b/apps/web/src/features/rooms/voice-control/recording-entry.test.tsxindex 0af977fa..608a2357 100644--- a/apps/web/src/features/rooms/voice-control/recording-entry.test.tsx+++ b/apps/web/src/features/rooms/voice-control/recording-entry.test.tsx@@ -14,7 +14,10 @@ function renderEntry(retryConnection?: () => void) {return render(<VoiceCapabilitiesContext value={undefined}><VoiceConnectionRetryContext value={retryConnection}>- <RecordingEntry anotherMeRoomId="another-me" />+ <RecordingEntry+ anotherMeRoomId="another-me"+ tenantId="tenant-northstar"+ /></VoiceConnectionRetryContext></VoiceCapabilitiesContext>,);diff --git a/apps/web/src/features/rooms/voice-control/recording-entry.tsx b/apps/web/src/features/rooms/voice-control/recording-entry.tsxindex 5f458299..37107bea 100644--- a/apps/web/src/features/rooms/voice-control/recording-entry.tsx+++ b/apps/web/src/features/rooms/voice-control/recording-entry.tsx@@ -2,9 +2,10 @@ import {Loading03Icon,AiTranscribeAudioIcon,} from "@hugeicons/core-free-icons";-import { use, useState } from "react";+import { use, useEffect, useEffectEvent, useRef, useState } from "react";import { Icon } from "@/components/ui/icon";+import { LazyVoiceKeyDialog } from "./lazy-voice-key-dialog";import { openRecordingWindow } from "./recording-window-store";import {isTranscriptRecoveryPaused,@@ -20,8 +21,10 @@ import {*/export function RecordingEntry({anotherMeRoomId,+ tenantId,}: {anotherMeRoomId?: string;+ tenantId: string;}) {const livekit = useOptionalVoiceControl();const voice = livekit;@@ -31,6 +34,10 @@ export function RecordingEntry({const connectionFailed = Boolean(retryConnection);const [error, setError] = useState<string>();const [pending, setPending] = useState(false);+ // Without a Soniox key the entry asks for one, then starts once voice runs.+ const needsKey = capabilities?.voiceMedia === false;+ const [keyDialogOpen, setKeyDialogOpen] = useState(false);+ const startWhenReady = useRef(false);const status = voice?.captureState?.status;const recording = status === "recording" || status === "starting";const saving =@@ -39,7 +46,7 @@ export function RecordingEntry({!(voice && isTranscriptRecoveryPaused(voice.captureState)));const standby = voice?.listenerStatus === "standby";// Until voice connects, including while it reconnects, the icon spins.- const connecting = !voice && !connectionFailed;+ const connecting = !voice && !connectionFailed && !needsKey;const label = recording? "Return to recording": saving@@ -51,18 +58,24 @@ export function RecordingEntry({error ??(connectionFailed? "Voice connection is unavailable. Click to retry."- : !voice || !anotherMeRoomId- ? "Meeting is loading"- : voice.composerMicrophoneActive- ? "Finish voice input first"- : standby- ? "Recording is active in another tab"- : label);+ : needsKey+ ? label+ : !voice || !anotherMeRoomId+ ? "Meeting is loading"+ : voice.composerMicrophoneActive+ ? "Finish voice input first"+ : standby+ ? "Recording is active in another tab"+ : label);function start() {if (retryConnection) {retryConnection();return;}+ if (needsKey) {+ setKeyDialogOpen(true);+ return;+ }if (!voice || !anotherMeRoomId || pending || voice.composerMicrophoneActive)return;setPending(true);@@ -84,41 +97,66 @@ export function RecordingEntry({.finally(() => setPending(false));}- if (capabilities?.voiceMedia === false) return null;+ // The engine for a just-saved key loads after the dialog closes; the+ // recording the Human asked for starts once it is here.+ const startSaved = useEffectEvent(() => start());+ const engineReady = Boolean(voice && anotherMeRoomId) && !needsKey;+ useEffect(() => {+ if (!startWhenReady.current || !engineReady) return;+ startWhenReady.current = false;+ startSaved();+ }, [engineReady]);++ if (capabilities?.voiceAvailable === false) return null;return (- // eslint-disable-next-line jsx-a11y/role-supports-aria-props -- aria-description is a valid ARIA global attribute missing from the rule data.- <button- aria-description={hint === label ? undefined : hint}- aria-label={label}- className="xs-nav-btn relative"- disabled={- !connectionFailed &&- (pending ||- !voice ||- !anotherMeRoomId ||- voice.composerMicrophoneActive)- }- onClick={start}- title={hint}- type="button"- >- {saving || connecting ? (- <Icon icon={Loading03Icon} className="animate-spin" size={16} />- ) : (- <Icon icon={AiTranscribeAudioIcon} size={16} />- )}- {recording || connectionFailed ? (- <span- aria-hidden="true"- className={`absolute top-1 right-1 size-2 rounded-full ring-2 ring-app-sidebar ${recording ? "bg-app-danger" : "bg-app-warning"}`}+ <>+ {/* eslint-disable-next-line jsx-a11y/role-supports-aria-props -- aria-description is a valid ARIA global attribute missing from the rule data. */}+ <button+ aria-description={hint === label ? undefined : hint}+ aria-label={label}+ className="xs-nav-btn relative"+ disabled={+ !connectionFailed &&+ !needsKey &&+ (pending ||+ !voice ||+ !anotherMeRoomId ||+ voice.composerMicrophoneActive)+ }+ onClick={start}+ title={hint}+ type="button"+ >+ {saving || connecting ? (+ <Icon icon={Loading03Icon} className="animate-spin" size={16} />+ ) : (+ <Icon icon={AiTranscribeAudioIcon} size={16} />+ )}+ {recording || connectionFailed ? (+ <span+ aria-hidden="true"+ className={`absolute top-1 right-1 size-2 rounded-full ring-2 ring-app-sidebar ${recording ? "bg-app-danger" : "bg-app-warning"}`}+ />+ ) : null}+ {error ? (+ <span className="sr-only" role="alert">+ {error}+ </span>+ ) : null}+ </button>+ {keyDialogOpen ? (+ <LazyVoiceKeyDialog+ onClose={() => setKeyDialogOpen(false)}+ onReady={() => {+ setKeyDialogOpen(false);+ startWhenReady.current = true;+ }}+ policy={capabilities?.policy}+ providers={["soniox"]}+ tenantId={tenantId}/>) : null}- {error ? (- <span className="sr-only" role="alert">- {error}- </span>- ) : null}- </button>+ </>);}diff --git a/apps/web/src/features/rooms/voice-control/use-voice-media-policy.ts b/apps/web/src/features/rooms/voice-control/use-voice-media-policy.tsindex 4e323047..901ccc72 100644--- a/apps/web/src/features/rooms/voice-control/use-voice-media-policy.ts+++ b/apps/web/src/features/rooms/voice-control/use-voice-media-policy.ts@@ -4,6 +4,31 @@ import { teamHubData } from "@/features/teamhub/teamhub-api";import { useOptionalTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";import type { TeamHubVoiceMediaPolicy } from "@/features/teamhub/teamhub-types";+type VoiceMediaPolicyListener = (+ tenantId: string,+ policy: TeamHubVoiceMediaPolicy,+) => void;+const policyListeners = new Set<VoiceMediaPolicyListener>();++/**+ * Hands a freshly read policy to every reader in this tab, so a key saved here+ * turns voice on without each reader polling. Other tabs see it on their next+ * read.+ */+export function publishVoiceMediaPolicy(+ tenantId: string,+ policy: TeamHubVoiceMediaPolicy,+) {+ for (const listener of policyListeners) listener(tenantId, policy);+}++export function subscribeVoiceMediaPolicy(listener: VoiceMediaPolicyListener) {+ policyListeners.add(listener);+ return () => {+ policyListeners.delete(listener);+ };+}+/*** The Voice media policy of `tenantId`, undefined until it answers for this* Space. `voice_media_supported` is Soniox transcription (meetings, dictation@@ -22,6 +47,9 @@ export function useVoiceMediaPolicy(useEffect(() => {if (!runtime || !enabled) return;const abort = new AbortController();+ const unsubscribe = subscribeVoiceMediaPolicy((published, policy) => {+ if (published === tenantId) setAnswer({ policy, tenantId });+ });void teamHubData(runtime.client.api.GET("/v0/tenants/{tenantId}/voice-media-policy", {params: { path: { tenantId } },@@ -33,7 +61,10 @@ export function useVoiceMediaPolicy(},() => undefined,);- return () => abort.abort();+ return () => {+ abort.abort();+ unsubscribe();+ };}, [enabled, runtime, tenantId]);return answer?.tenantId === tenantId ? answer.policy : undefined;}diff --git a/apps/web/src/features/rooms/voice-control/voice-backend-controller.tsx b/apps/web/src/features/rooms/voice-control/voice-backend-controller.tsxindex 58d83c9b..3693c1f2 100644--- a/apps/web/src/features/rooms/voice-control/voice-backend-controller.tsx+++ b/apps/web/src/features/rooms/voice-control/voice-backend-controller.tsx@@ -18,6 +18,7 @@ import {import type { TeamHubVoiceMediaPolicy } from "@/features/teamhub/teamhub-types";import type { TeamHubClient } from "@/features/teamhub/teamhub-client";import { voicePollRetryDelay } from "./voice-poll-retry";+import { subscribeVoiceMediaPolicy } from "./use-voice-media-policy";import {VoiceRequestScope,waitForVoiceDelay,@@ -116,8 +117,17 @@ export function VoiceBackendController({void attempt();};retryRef.current = retry;+ // A key saved in this tab publishes the policy that turned voice on, so+ // the LiveKit engine loads now instead of on the next reload.+ const unsubscribe = subscribeVoiceMediaPolicy((published, policy) => {+ if (published !== tenantId || controller.signal.aborted) return;+ setBackend(policy);+ setError(undefined);+ onChange((current) => ({ ...current, policy }));+ });void attempt();return () => {+ unsubscribe();controller.abort();if (retryRef.current === retry) retryRef.current = undefined;};diff --git a/apps/web/src/features/rooms/voice-control/voice-backend-provider.tsx b/apps/web/src/features/rooms/voice-control/voice-backend-provider.tsxindex ac51a857..68a3a04b 100644--- a/apps/web/src/features/rooms/voice-control/voice-backend-provider.tsx+++ b/apps/web/src/features/rooms/voice-control/voice-backend-provider.tsx@@ -50,7 +50,12 @@ function TenantVoiceControlProvider({const capabilities = useMemo(() =>ready && policy- ? { voiceMedia: policy.voice_media_supported }+ ? {+ policy,+ voiceAvailable:+ policy.voice_available ?? policy.voice_media_supported,+ voiceMedia: policy.voice_media_supported,+ }: undefined,[policy, ready],);diff --git a/apps/web/src/features/rooms/voice-control/voice-control-context.ts b/apps/web/src/features/rooms/voice-control/voice-control-context.tsindex b4b3b3d7..fc0e0e81 100644--- a/apps/web/src/features/rooms/voice-control/voice-control-context.ts+++ b/apps/web/src/features/rooms/voice-control/voice-control-context.ts@@ -1,6 +1,9 @@import { createContext, useContext } from "react";-import type { TeamHubVoiceCapture } from "@/features/teamhub/teamhub-types";+import type {+ TeamHubVoiceCapture,+ TeamHubVoiceMediaPolicy,+} from "@/features/teamhub/teamhub-types";import type { VoiceMicrophoneDevice } from "./microphone-devices";@@ -85,11 +88,16 @@ export interface VoiceControlContextValue {// What the deployment offers. Undefined while the workspace reads its voice// policy or loads the LiveKit engine; outside a workspace everything is offered.export interface VoiceCapabilities {+ /** Soniox transcription works now. */voiceMedia: boolean;+ /** The deployment can run voice, so its entries show even without a key. */+ voiceAvailable: boolean;+ /** The workspace's policy, for the key dialog's statuses. */+ policy?: TeamHubVoiceMediaPolicy;}export const VoiceCapabilitiesContext = createContext<VoiceCapabilities | undefined->({ voiceMedia: true });+>({ voiceAvailable: true, voiceMedia: true });// Present only once the voice backend stopped retrying on its own; calling it// tries again.diff --git a/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsx b/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsxindex f4108234..e09b0697 100644--- a/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsx+++ b/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsx@@ -22,7 +22,10 @@ describe("RecordingEntry", () => {},})}>- <RecordingEntry anotherMeRoomId="room_another_me" />+ <RecordingEntry+ anotherMeRoomId="room_another_me"+ tenantId="tenant-northstar"+ /></VoiceControlContext.Provider>,);expect(@@ -32,7 +35,10 @@ describe("RecordingEntry", () => {<VoiceControlContext.Providervalue={voiceValue({ captureState: pausedRecovery() })}>- <RecordingEntry anotherMeRoomId="room_another_me" />+ <RecordingEntry+ anotherMeRoomId="room_another_me"+ tenantId="tenant-northstar"+ /></VoiceControlContext.Provider>,);const meetings = screen.getByRole("button", { name: "Meetings" });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.tsxnew file mode 100644index 00000000..45b4a4b2--- /dev/null+++ b/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx@@ -0,0 +1,275 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { useEffect, useState, type ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";+import type { TeamHubVoiceMediaPolicy } from "@/features/teamhub/teamhub-types";+import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";+import { teamHubErrorResponse } from "@/test/teamhub-test-server";++import { RecordingEntry } from "./recording-entry";+import { openRecordingWindow } from "./recording-window-store";+import { subscribeVoiceMediaPolicy } from "./use-voice-media-policy";+import {+ VoiceCapabilitiesContext,+ VoiceControlContext,+ type VoiceControlContextValue,+} from "./voice-control-context";+import { VoiceKeyDialog } from "./voice-key-dialog";++vi.mock("./recording-window-store", () => ({ openRecordingWindow: vi.fn() }));+vi.mock("../chat/voice-mode/voice-pip", () => ({+ closeVoicePip: vi.fn(),+ openVoicePip: vi.fn(async () => undefined),+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++const missing = { source: "none" as const, can_save: true };+const noKeys: TeamHubVoiceMediaPolicy = {+ voice_available: true,+ voice_media_supported: false,+ live_supported: false,+ soniox_key: missing,+ xai_key: missing,+};+const sonioxSaved: TeamHubVoiceMediaPolicy = {+ ...noKeys,+ voice_media_supported: true,+ soniox_key: { source: "stored", can_save: true },+};++function renderWithRuntime(+ runtime: ReturnType<typeof createTestTeamHubRuntime>,+ children: ReactNode,+) {+ return render(+ <QueryClientProvider client={new QueryClient()}>+ <TeamHubRuntimeProvider runtime={runtime}>+ {children}+ </TeamHubRuntimeProvider>+ </QueryClientProvider>,+ );+}++/**+ * Stands in for the workspace voice provider: capabilities follow the+ * published policy, and the voice engine appears once Soniox works.+ */+function VoiceWorkspace({+ children,+ initial,+ selectTargetRoom,+}: {+ children: ReactNode;+ initial: TeamHubVoiceMediaPolicy;+ selectTargetRoom: () => Promise<void>;+}) {+ const [policy, setPolicy] = useState(initial);+ useEffect(+ () => subscribeVoiceMediaPolicy((_tenantId, next) => setPolicy(next)),+ [],+ );+ const voice = policy.voice_media_supported+ ? ({ selectTargetRoom } as unknown as VoiceControlContextValue)+ : null;+ return (+ <VoiceControlContext value={voice}>+ <VoiceCapabilitiesContext+ value={{+ policy,+ voiceAvailable:+ policy.voice_available ?? policy.voice_media_supported,+ voiceMedia: policy.voice_media_supported,+ }}+ >+ {children}+ </VoiceCapabilitiesContext>+ </VoiceControlContext>+ );+}++describe("Recording entry visibility", () => {+ it.each([+ [{ voice_available: true, voice_media_supported: false }, true],+ [{ voice_available: false, voice_media_supported: false }, false],+ // Older servers do not send voice_available.+ [{ voice_media_supported: false }, false],+ [{ voice_media_supported: true }, true],+ ])("for policy %j shows the entry: %s", (policy, shown) => {+ const runtime = createTestTeamHubRuntime();+ renderWithRuntime(+ runtime,+ <VoiceWorkspace initial={policy} selectTargetRoom={vi.fn()}>+ <RecordingEntry+ anotherMeRoomId="another-me"+ tenantId="tenant-northstar"+ />+ </VoiceWorkspace>,+ );+ expect(Boolean(screen.queryByRole("button", { name: "Meetings" }))).toBe(+ shown,+ );+ });+});++describe("Recording without a Soniox key", () => {+ it("asks for the key, waits for voice, then starts recording", async () => {+ const runtime = createTestTeamHubRuntime();+ let saved = false;+ let saves = 0;+ runtime.server+ .on("GET", "/v0/tenants/{tenantId}/voice-media-policy", () =>+ saved ? sonioxSaved : noKeys,+ )+ .on("PUT", "/v0/voice-provider-keys/{provider}", ({ body, params }) => {+ expect(params.provider).toBe("soniox");+ expect(body).toEqual({ api_key: "soniox-key" });+ saves += 1;+ saved = true;+ return { source: "stored", can_save: true };+ });+ const selectTargetRoom = vi.fn(async () => undefined);+ renderWithRuntime(+ runtime,+ <VoiceWorkspace initial={noKeys} selectTargetRoom={selectTargetRoom}>+ <RecordingEntry+ anotherMeRoomId="another-me"+ tenantId="tenant-northstar"+ />+ </VoiceWorkspace>,+ );+ const entry = screen.getByRole("button", { name: "Meetings" });+ expect(entry).toBeEnabled();+ fireEvent.click(entry);+ const dialog = await screen.findByRole("dialog", { name: "Soniox key" });+ fireEvent.change(within(dialog).getByLabelText("Soniox API key"), {+ target: { value: " soniox-key " },+ });+ fireEvent.click(within(dialog).getByRole("button", { name: "Save key" }));+ await waitFor(() => expect(openRecordingWindow).toHaveBeenCalledOnce());+ expect(openRecordingWindow).toHaveBeenCalledWith({ autoStart: true });+ expect(selectTargetRoom).toHaveBeenCalledWith("another-me");+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(saves).toBe(1);+ // One fresh read after the save; nothing polls.+ expect(+ runtime.server.requestsTo(+ "GET",+ "/v0/tenants/{tenantId}/voice-media-policy",+ ),+ ).toHaveLength(1);+ });+});++describe("VoiceKeyDialog", () => {+ function renderDialog(+ runtime: ReturnType<typeof createTestTeamHubRuntime>,+ policy: TeamHubVoiceMediaPolicy,+ onReady = vi.fn(),+ ) {+ renderWithRuntime(+ runtime,+ <VoiceKeyDialog+ onClose={vi.fn()}+ onReady={onReady}+ policy={policy}+ providers={["soniox"]}+ tenantId="tenant-northstar"+ />,+ );+ return onReady;+ }++ it.each([+ [+ "VOICE_KEY_REJECTED",+ 400,+ "Soniox rejected this key. Check it and try again.",+ ],+ [+ "VOICE_PROVIDER_UNAVAILABLE",+ 503,+ "Could not reach Soniox to check the key. Try again in a moment.",+ ],+ [+ "VOICE_KEY_STORAGE_UNAVAILABLE",+ 503,+ "This server cannot store keys. Whoever runs it must set TEAMHUB_SECRET_ENCRYPTION_KEY.",+ ],+ ])("keeps the dialog open on %s", async (code, status, message) => {+ const runtime = createTestTeamHubRuntime();+ runtime.server.on("PUT", "/v0/voice-provider-keys/{provider}", () =>+ // The prose is irrelevant: only the code picks the message.+ teamHubErrorResponse(status, code, "unrelated server prose"),+ );+ const onReady = renderDialog(runtime, noKeys);+ fireEvent.change(screen.getByLabelText("Soniox API key"), {+ target: { value: "bad-key" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Save key" }));+ expect(await screen.findByText(message)).toBeVisible();+ expect(screen.getByRole("dialog", { name: "Soniox key" })).toBeVisible();+ expect(screen.queryByText("unrelated server prose")).toBeNull();+ expect(onReady).not.toHaveBeenCalled();+ });++ it("explains that the deployment must configure a key it cannot save", () => {+ const runtime = createTestTeamHubRuntime();+ renderDialog(runtime, {+ ...noKeys,+ soniox_key: { source: "none", can_save: false },+ });+ expect(screen.queryByLabelText("Soniox API key")).toBeNull();+ expect(+ screen.getByText(/This server cannot save a Soniox key here/u),+ ).toBeVisible();+ expect(screen.getByText("SONIOX_API_KEY")).toBeVisible();+ });++ it("offers a retry when the fresh policy does not report voice", async () => {+ const runtime = createTestTeamHubRuntime();+ let reads = 0;+ runtime.server+ .on("GET", "/v0/tenants/{tenantId}/voice-media-policy", () => {+ reads += 1;+ return reads === 1+ ? teamHubErrorResponse(503, "UNAVAILABLE")+ : sonioxSaved;+ })+ .on("PUT", "/v0/voice-provider-keys/{provider}", () => ({+ source: "stored",+ can_save: true,+ }));+ const onReady = 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("alert")).toHaveTextContent(+ "The key is saved, but voice could not be turned on. Try again.",+ );+ expect(onReady).not.toHaveBeenCalled();+ expect(reads).toBe(1);++ fireEvent.click(screen.getByRole("button", { name: "Try again" }));+ await waitFor(() =>+ expect(onReady).toHaveBeenCalledWith("soniox", sonioxSaved),+ );+ expect(reads).toBe(2);+ expect(+ runtime.server.requestsTo("PUT", "/v0/voice-provider-keys/{provider}"),+ ).toHaveLength(1);+ });+});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.tsxnew file mode 100644index 00000000..cdb833d9--- /dev/null+++ b/apps/web/src/features/rooms/voice-control/voice-key-dialog.tsx@@ -0,0 +1,231 @@+import { useState } from "react";++import { Button } from "@/components/ui/button";+import { ModalDialog } from "@/components/ui/modal-dialog";+import { ProviderKeyForm } from "@/features/apps/provider-key-form";+import { ProviderKeyGuide } from "@/features/apps/provider-key-guide";+import { teamHubData } from "@/features/teamhub/teamhub-api";+import { TeamHubError } from "@/features/teamhub/teamhub-error";+import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";+import type {+ TeamHubVoiceMediaPolicy,+ TeamHubVoiceProvider,+ TeamHubVoiceProviderKeyStatus,+} from "@/features/teamhub/teamhub-types";++import { publishVoiceMediaPolicy } from "./use-voice-media-policy";++const providerDetails: Record<+ TeamHubVoiceProvider,+ {+ environmentVariable: string;+ href: string;+ name: string;+ purpose: string;+ steps: string[];+ }+> = {+ soniox: {+ environmentVariable: "SONIOX_API_KEY",+ href: "https://console.soniox.com/",+ name: "Soniox",+ purpose:+ "Transcribes meetings, Pocket Notes dictation and Voice Mode dictation.",+ steps: [+ "Open the Soniox Console and sign in or create an account.",+ "Create an API key.",+ "Copy the key, paste it below, and select Save key.",+ ],+ },+ xai: {+ environmentVariable: "XAI_API_KEY",+ href: "https://console.x.ai/",+ name: "xAI",+ purpose: "Turns Voice Mode into a live conversation with Grok.",+ steps: [+ "Open the xAI Console and sign in or create an account.",+ "Create an API key.",+ "Copy the key, paste it below, and select Save key.",+ ],+ },+};++function voiceProviderKeyStatus(+ policy: TeamHubVoiceMediaPolicy | undefined,+ provider: TeamHubVoiceProvider,+): TeamHubVoiceProviderKeyStatus | undefined {+ return provider === "soniox" ? policy?.soniox_key : policy?.xai_key;+}++/** Whether `policy` reports the voice that `provider`'s key turns on. */+function voiceReady(+ policy: TeamHubVoiceMediaPolicy,+ provider: TeamHubVoiceProvider,+) {+ return provider === "soniox"+ ? policy.voice_media_supported+ : policy.live_supported === true;+}++function describeSaveError(error: Error, provider: TeamHubVoiceProvider) {+ const { environmentVariable, name } = providerDetails[provider];+ switch (error instanceof TeamHubError ? error.code : undefined) {+ case "INVALID_REQUEST":+ return "Enter a valid API key.";+ case "VOICE_KEY_REJECTED":+ return `${name} rejected this key. Check it and try again.`;+ case "VOICE_KEY_FROM_ENVIRONMENT":+ return `This server sets the ${name} key with ${environmentVariable}, so it cannot be changed here.`;+ case "VOICE_KEY_STORAGE_UNAVAILABLE":+ return "This server cannot store keys. Whoever runs it must set TEAMHUB_SECRET_ENCRYPTION_KEY.";+ case "VOICE_PROVIDER_UNAVAILABLE":+ return `Could not reach ${name} to check the key. Try again in a moment.`;+ case "VOICE_MEDIA_OFF":+ return "Voice is turned off on this server.";+ default:+ return "Could not save the key. Try again.";+ }+}++/**+ * Takes the Soniox or xAI key a voice action needs, then reads this Space's+ * voice policy once and hands it to `onReady` when it reports that voice, so+ * the caller can continue the action that was clicked.+ */+export function VoiceKeyDialog({+ onClose,+ onReady,+ policy,+ providers,+ tenantId,+}: {+ onClose: () => void;+ onReady: (+ provider: TeamHubVoiceProvider,+ policy: TeamHubVoiceMediaPolicy,+ ) => void;+ /** The policy the caller holds, read only for each key's status. */+ policy: TeamHubVoiceMediaPolicy | undefined;+ providers: readonly TeamHubVoiceProvider[];+ tenantId: string;+}) {+ const { client } = useTeamHubRuntime();+ const [provider, setProvider] = useState(providers[0] ?? "soniox");+ // Set when the key is saved but the fresh policy did not turn voice on.+ const [turnOnFailed, setTurnOnFailed] = useState(false);+ const [retrying, setRetrying] = useState(false);++ async function turnOn() {+ const next = await teamHubData(+ client.api.GET("/v0/tenants/{tenantId}/voice-media-policy", {+ params: { path: { tenantId } },+ }),+ ).catch(() => undefined);+ if (next && voiceReady(next, provider)) {+ setTurnOnFailed(false);+ publishVoiceMediaPolicy(tenantId, next);+ onReady(provider, next);+ return;+ }+ setTurnOnFailed(true);+ }++ const details = providerDetails[provider];+ const status = voiceProviderKeyStatus(policy, provider);+ return (+ <ModalDialog+ closeOnBackdrop+ description={+ providers.length > 1+ ? "Voice needs a Soniox or xAI key. Keys are used by everyone on this server."+ : details.purpose+ }+ onClose={onClose}+ size="md"+ title={providers.length > 1 ? "Turn on voice" : `${details.name} key`}+ >+ <div className="space-y-4 px-5 py-5 text-sm text-app-body">+ {turnOnFailed ? (+ <>+ <p role="alert">+ The key is saved, but voice could not be turned on. Try again.+ </p>+ <Button+ loading={retrying}+ onClick={() => {+ setRetrying(true);+ void turnOn().finally(() => setRetrying(false));+ }}+ tone="primary"+ >+ Try again+ </Button>+ </>+ ) : (+ <>+ {providers.length > 1 ? (+ <div+ aria-label="Voice provider"+ className="flex gap-2"+ role="group"+ >+ {providers.map((option) => (+ <Button+ aria-pressed={option === provider}+ key={option}+ onClick={() => setProvider(option)}+ tone={option === provider ? "primary" : "secondary"}+ >+ {providerDetails[option].name}+ </Button>+ ))}+ </div>+ ) : null}+ {providers.length > 1 ? (+ <p className="text-muted-foreground">{details.purpose}</p>+ ) : null}+ {status?.can_save === false ? (+ <p>+ This server cannot save a {details.name} key here. Whoever runs+ it must set{" "}+ <code className="font-mono">{details.environmentVariable}</code>+ , or set{" "}+ <code className="font-mono">TEAMHUB_SECRET_ENCRYPTION_KEY</code>{" "}+ so keys can be saved here.+ </p>+ ) : (+ <>+ <ProviderKeyGuide+ href={details.href}+ steps={+ <ol className="list-decimal space-y-1.5 pl-5">+ {details.steps.map((step) => (+ <li key={step}>{step}</li>+ ))}+ </ol>+ }+ />+ <ProviderKeyForm+ describeError={(error) => describeSaveError(error, provider)}+ hint="Stored encrypted and never shown again."+ key={provider}+ label={`${details.name} API key`}+ save={async (apiKey) => {+ await teamHubData(+ client.api.PUT("/v0/voice-provider-keys/{provider}", {+ body: { api_key: apiKey },+ params: { path: { provider } },+ }),+ );+ // The Save button stays pending through this read.+ await turnOn();+ }}+ />+ </>+ )}+ </>+ )}+ </div>+ </ModalDialog>+ );+}diff --git a/apps/web/src/features/settings/api-keys-settings.tsx b/apps/web/src/features/settings/api-keys-settings.tsxindex 63adc13b..3c366943 100644--- a/apps/web/src/features/settings/api-keys-settings.tsx+++ b/apps/web/src/features/settings/api-keys-settings.tsx@@ -8,9 +8,16 @@ import { ModalDialog } from "@/components/ui/modal-dialog";import { StatusPill } from "@/components/ui/status-pill";import { AppLogoTile } from "@/features/apps/app-logo";import { externalAppsQueryOptions } from "@/features/apps/connected-apps-queries";-import { ProviderKeyForm } from "@/features/apps/provider-key-form";+import { ComposioKeyForm } from "@/features/apps/provider-key-form";import { ComposioKeyGuide } from "@/features/apps/provider-key-guide";+import { LazyVoiceKeyDialog } from "@/features/rooms/voice-control/lazy-voice-key-dialog";+import { useVoiceMediaPolicy } from "@/features/rooms/voice-control/use-voice-media-policy";import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";+import type {+ TeamHubVoiceProvider,+ TeamHubVoiceProviderKeyStatus,+} from "@/features/teamhub/teamhub-types";+import { useParams } from "react-router";/** Composio serves its own mark the same way it serves connector logos. */const composioLogoUrl = "https://logos.composio.dev/api/composio";@@ -19,10 +26,19 @@ const composioLogoUrl = "https://logos.composio.dev/api/composio";export function ApiKeysSettings() {const [dialogOpen, setDialogOpen] = useState(false);const [notice, setNotice] = useState<string>();+ const [voiceDialog, setVoiceDialog] = useState<TeamHubVoiceProvider>();+ // Voice keys matter only where this deployment can run voice; the policy+ // is read per Space, so Security outside a Space shows no voice rows.+ const tenantId = useParams().tenantId ?? "";+ const voicePolicy = useVoiceMediaPolicy(tenantId, Boolean(tenantId));function open() {setNotice(undefined);setDialogOpen(true);}+ function openVoice(provider: TeamHubVoiceProvider) {+ setNotice(undefined);+ setVoiceDialog(provider);+ }return (<section className="flex flex-col gap-3">@@ -35,6 +51,24 @@ export function ApiKeysSettings() {</header><div className="divide-y divide-border rounded-2xl border border-border bg-background"><ComposioKeyRow onOpen={open} />+ {voicePolicy?.voice_available ? (+ <>+ <VoiceKeyRow+ detail="Transcribes meetings, Pocket Notes dictation and Voice Mode dictation."+ environmentVariable="SONIOX_API_KEY"+ onOpen={() => openVoice("soniox")}+ status={voicePolicy.soniox_key}+ title="Soniox"+ />+ <VoiceKeyRow+ detail="Turns Voice Mode into a live conversation with Grok."+ environmentVariable="XAI_API_KEY"+ onOpen={() => openVoice("xai")}+ status={voicePolicy.xai_key}+ title="xAI"+ />+ </>+ ) : null}</div>{notice ? (@@ -63,7 +97,7 @@ export function ApiKeysSettings() {><div className="space-y-4 px-5 py-5 text-sm text-app-body"><ComposioKeyGuide />- <ProviderKeyForm+ <ComposioKeyFormonSaved={() => {setNotice("Composio key saved");setDialogOpen(false);@@ -72,10 +106,77 @@ export function ApiKeysSettings() {</div></ModalDialog>) : null}++ {voiceDialog ? (+ <LazyVoiceKeyDialog+ onClose={() => setVoiceDialog(undefined)}+ onReady={(provider) => {+ setNotice(`${provider === "soniox" ? "Soniox" : "xAI"} key saved`);+ setVoiceDialog(undefined);+ }}+ policy={voicePolicy}+ providers={[voiceDialog]}+ tenantId={tenantId}+ />+ ) : null}</section>);}+/** Where a server key comes from: its environment, a saved key, or nowhere. */+function KeySourcePill({+ source,+}: {+ source: TeamHubVoiceProviderKeyStatus["source"];+}) {+ return source === "environment" ? (+ <StatusPill>Set by your server</StatusPill>+ ) : source === "stored" ? (+ <StatusPill tone="success">Active</StatusPill>+ ) : (+ <StatusPill>Not set</StatusPill>+ );+}++function VoiceKeyRow({+ detail,+ environmentVariable,+ onOpen,+ status,+ title,+}: {+ detail: string;+ environmentVariable: string;+ onOpen: () => void;+ status: TeamHubVoiceProviderKeyStatus | undefined;+ title: string;+}) {+ return (+ <KeyRow+ actions={+ status?.can_save ? (+ <Button+ aria-label={`${status.source === "stored" ? "Replace" : "Add"} ${title} key`}+ onClick={onOpen}+ >+ {status.source === "stored" ? "Replace key" : "Add key"}+ </Button>+ ) : null+ }+ detail={+ status?.source === "environment"+ ? `${detail} Set with ${environmentVariable} on the server.`+ : status?.can_save === false+ ? `${detail} Set ${environmentVariable} on the server, or set TEAMHUB_SECRET_ENCRYPTION_KEY to save the key here.`+ : detail+ }+ logo={<AppLogoTile name={title} />}+ pill={status ? <KeySourcePill source={status.source} /> : null}+ title={title}+ />+ );+}+function KeyRow({actions,detail,@@ -125,15 +226,7 @@ function ComposioKeyRow({ onOpen }: { onOpen: () => void }) {}detail={detail}logo={<AppLogoTile name="Composio" url={composioLogoUrl} />}- pill={- !key ? null : key.source === "environment" ? (- <StatusPill>Set by your server</StatusPill>- ) : key.source === "stored" ? (- <StatusPill tone="success">Active</StatusPill>- ) : (- <StatusPill>Not set</StatusPill>- )- }+ pill={key ? <KeySourcePill source={key.source} /> : null}title="Composio"/>);diff --git a/apps/web/src/features/settings/settings-pages.test.tsx b/apps/web/src/features/settings/settings-pages.test.tsxindex a95d9b8c..91bdb036 100644--- a/apps/web/src/features/settings/settings-pages.test.tsx+++ b/apps/web/src/features/settings/settings-pages.test.tsx@@ -361,6 +361,66 @@ describe("Settings surfaces", () => {});});+describe("Voice API keys", () => {+ it("shows where each voice key comes from and saves one", async () => {+ const runtime = await testRuntime();+ let saved = false;+ runtime.server+ .on("GET", "/v0/tenants/{tenantId}/voice-media-policy", () => ({+ voice_available: true,+ voice_media_supported: saved,+ live_supported: true,+ soniox_key: saved+ ? { source: "stored", can_save: true }+ : { source: "none", can_save: true },+ xai_key: { source: "environment", can_save: false },+ }))+ .on("PUT", "/v0/voice-provider-keys/{provider}", ({ params }) => {+ expect(params.provider).toBe("soniox");+ saved = true;+ return { source: "stored", can_save: true };+ });+ renderSettings(runtime, "/t/tenant-northstar/settings/security");++ const addSoniox = await screen.findByRole("button", {+ name: "Add Soniox key",+ });+ expect(+ screen.getByText(/Turns Voice Mode into a live conversation/u),+ ).toHaveTextContent("Set with XAI_API_KEY on the server.");+ expect(screen.getByText("Set by your server")).toBeVisible();+ expect(screen.queryByRole("button", { name: /xAI key/u })).toBeNull();++ fireEvent.click(addSoniox);+ const dialog = await screen.findByRole("dialog", { name: "Soniox key" });+ fireEvent.change(within(dialog).getByLabelText("Soniox API key"), {+ target: { value: "soniox-key" },+ });+ fireEvent.click(within(dialog).getByRole("button", { name: "Save key" }));++ expect(await screen.findByText("Soniox key saved")).toBeVisible();+ expect(screen.queryByRole("dialog", { name: "Soniox key" })).toBeNull();+ expect(+ screen.getByRole("button", { name: "Replace Soniox key" }),+ ).toBeVisible();+ });++ it("hides the voice rows where the deployment cannot run voice", async () => {+ const runtime = await testRuntime();+ runtime.server.on(+ "GET",+ "/v0/tenants/{tenantId}/voice-media-policy",+ () => ({ voice_available: false, voice_media_supported: false }),+ );+ renderSettings(runtime, "/t/tenant-northstar/settings/security");++ expect(await screen.findByText("Composio")).toBeVisible();+ await act(async () => undefined);+ expect(screen.queryByText("Soniox")).toBeNull();+ expect(screen.queryByText("xAI")).toBeNull();+ });+});+async function testRuntime() {const runtime = createTestTeamHubRuntime();diff --git a/apps/web/src/features/teamhub/teamhub-types.ts b/apps/web/src/features/teamhub/teamhub-types.tsindex 70be3c0d..bb357fe9 100644--- a/apps/web/src/features/teamhub/teamhub-types.ts+++ b/apps/web/src/features/teamhub/teamhub-types.ts@@ -79,6 +79,9 @@ export type TeamHubDocumentTreeSummary =components["schemas"]["DocumentTreeSummary"];export type TeamHubVoiceSession = components["schemas"]["VoiceSession"];export type TeamHubVoiceMediaPolicy = components["schemas"]["VoiceMediaPolicy"];+export type TeamHubVoiceProvider = components["schemas"]["VoiceProvider"];+export type TeamHubVoiceProviderKeyStatus =+ components["schemas"]["VoiceProviderKeyStatus"];export type TeamHubVoiceConnectionCredential =components["schemas"]["VoiceConnectionCredential"];export type TeamHubVoiceCapture = components["schemas"]["VoiceCapture"];