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(web): hand off between Live and Meeting

muterC7a95b4fe5926
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index e8a2e59a..4af9df50 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -58,6 +58,10 @@ build:assets` to check the initial JS budget.
uses the red panda portrait on its warm brown tile.
- The login header uses the transparent horizontal Linger wordmark in
`public/linger-wordmark.svg`, with the proportions of `assets/logo-horizontal.svg`.
+- Switching between Meeting and Voice Mode ends the previous session and
+ releases its microphone before the new mode starts. Meeting saving can
+ continue in the background. If browser activation expires during the
+ switch, the new mode opens in the page and can be floated from there.
- The compact primary rail reveals labels on hover and keyboard focus without
moving link hit areas or neighbouring links. A stationary pointer at an edge
must not trigger repeated hover enter/leave; sidebar expansion and Chat list
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.tsx
index 687514e8..020a5418 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
@@ -72,6 +72,8 @@ export function VoiceModeControls(props: {
// the click then asks for a Soniox or xAI key.
const offered = supported || policy?.voice_available === true;
const [keyDialogOpen, setKeyDialogOpen] = useState(false);
+ const [starting, setStarting] = useState(false);
+ const [startError, setStartError] = useState<string>();
// Once Voice Mode is offered, its code loads in the background.
const prepare = voice?.prepare;
useEffect(() => {
@@ -84,25 +86,32 @@ export function VoiceModeControls(props: {
const entered = Boolean(here?.entered);
const closing = Boolean(here?.closing);
const enter = (next = modes) => {
- if (!voice || props.disabled || session) return;
+ if (!voice || props.disabled || session || starting) 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");
- voice.start(
- {
- accountId: props.target.accountId ?? "",
- recipient: props.target.recipient,
- roomId,
- roomName: props.target.roomName ?? "",
- tenantId,
- },
- props.prefix,
- next,
- );
+ setStarting(true);
+ setStartError(undefined);
+ void voice
+ .start(
+ {
+ accountId: props.target.accountId ?? "",
+ recipient: props.target.recipient,
+ roomId,
+ roomName: props.target.roomName ?? "",
+ tenantId,
+ },
+ props.prefix,
+ next,
+ () => openVoicePip("voice-mode"),
+ )
+ .catch((cause: unknown) => {
+ setStartError(
+ cause instanceof Error ? cause.message : "Unable to start Voice Mode",
+ );
+ })
+ .finally(() => setStarting(false));
};
if (!entered && !closing && (!props.empty || !offered)) return null;
if (!entered)
@@ -111,7 +120,8 @@ export function VoiceModeControls(props: {
<Button
aria-label={closing ? "Finishing Voice Mode" : "Start Voice Mode"}
title={
- closing
+ startError ??
+ (closing
? "Finishing last words and releasing the microphone"
: elsewhere
? `Voice Mode is on in ${elsewhere.target.roomName || "another Room"}`
@@ -119,16 +129,21 @@ export function VoiceModeControls(props: {
? "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"
+ : "Voice Mode: add a Soniox or xAI key to start")
}
className="message-composer-send"
- disabled={closing || props.disabled || Boolean(elsewhere)}
+ disabled={starting || closing || props.disabled || Boolean(elsewhere)}
onClick={() => enter()}
size="compactIcon"
tone="primary"
>
<Icon icon={AudioWave01Icon} size={16} />
</Button>
+ {startError ? (
+ <span className="sr-only" role="alert">
+ {startError}
+ </span>
+ ) : null}
{keyDialogOpen ? (
<LazyVoiceKeyDialog
onClose={() => setKeyDialogOpen(false)}
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session-engine.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session-engine.ts
index 12e48046..f8e52f87 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session-engine.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session-engine.ts
@@ -329,6 +329,7 @@ export function createVoiceModeSessionEngine({
let live: LiveView | undefined;
let entered = false;
let closing = false;
+ let exitPromise: Promise<void> | undefined;
let controller: VoiceModeController | undefined;
let stop: (() => void) | undefined;
const abortRef: { current: AbortController | undefined } = {
@@ -398,7 +399,9 @@ export function createVoiceModeSessionEngine({
abortRef,
binding: (roomId) => bindings.get(roomId),
entered: () => entered,
- exitByVoice: () => engine.exit(),
+ exitByVoice: () => {
+ void engine.exit();
+ },
hardware: () => deps().hardware ?? hardware,
modes,
onLevel: publishLevel,
@@ -421,9 +424,9 @@ export function createVoiceModeSessionEngine({
target,
});
},
- exit() {
+ exit({ switchingToMeeting = false } = {}) {
const current = run;
- if (!current || !entered) return;
+ if (!current || !entered) return exitPromise;
entered = false;
closing = true;
const before = controller?.getState() ?? idleState;
@@ -440,13 +443,17 @@ export function createVoiceModeSessionEngine({
abortRef.current?.abort();
// The window always closes: past the ceiling a stuck send or shutdown
// stops holding it, and unsent words still return to the draft.
+ const microphoneClosed = exiting?.pause();
const drained = Promise.race([
- Promise.all([exiting?.pause(), exiting?.whenDeliverySettles()]),
+ Promise.all([
+ microphoneClosed,
+ switchingToMeeting ? undefined : exiting?.whenDeliverySettles(),
+ ]),
new Promise<void>((resolve) =>
setTimeout(resolve, voiceModeExitCeilingMs),
),
]);
- void finishVoiceModeSession({
+ const finished = finishVoiceModeSession({
before,
binding: () => bindings.get(current.target.roomId),
controller: exiting,
@@ -466,6 +473,12 @@ export function createVoiceModeSessionEngine({
publishLevel(0);
snapshot();
});
+ // A mode switch must wait for the microphone even if the UI reaches its
+ // deadline for preserving the last turn.
+ exitPromise = Promise.all([finished, microphoneClosed]).then(() => {
+ exitPromise = undefined;
+ });
+ return exitPromise;
},
/** A composer that mounts mid-session resumes the live presentation. */
resume(roomId: string, binding: VoiceModeRoomBinding) {
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.test.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.test.tsx
index 2bd576d0..204b9284 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.test.tsx
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.test.tsx
@@ -1,9 +1,25 @@
-import { act, cleanup, render, waitFor } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { useEffect, type ReactNode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
+import { RecordingEntry } from "@/features/rooms/voice-control/recording-entry";
+import {
+ openRecordingWindow,
+ resetRecordingWindowForTest,
+} from "@/features/rooms/voice-control/recording-window-store";
+import {
+ VoiceControlContext,
+ type VoiceControlContextValue,
+} from "@/features/rooms/voice-control/voice-control-context";
import type { VoiceModeEvent } from "./voice-mode-controller";
import {
useOptionalVoiceModeSession,
@@ -15,6 +31,17 @@ const transport = vi.hoisted(() => ({
receive: undefined as undefined | ((event: VoiceModeEvent) => void),
close: vi.fn<() => Promise<void>>(async () => undefined),
open: vi.fn(async () => undefined),
+ openLive: vi.fn(async () => undefined),
+}));
+vi.mock("./live/voice-live-transport", () => ({
+ openVoiceLive: async () => {
+ await transport.openLive();
+ return {
+ close: transport.close,
+ commit: async () => undefined,
+ setMuted: async () => undefined,
+ };
+ },
}));
vi.mock("./voice-mode-transport", () => ({
openVoiceMode: async (input: {
@@ -80,16 +107,115 @@ function renderSession(children?: ReactNode) {
afterEach(async () => {
cleanup();
+ resetRecordingWindowForTest();
await act(async () => undefined);
vi.clearAllMocks();
});
describe("Voice Mode session", () => {
+ it.each(["recording", "finalizing"] as const)(
+ "releases a %s Meeting before opening Voice Mode",
+ async (status) => {
+ let released!: () => void;
+ const leavePage = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ released = resolve;
+ }),
+ );
+ const hardware = {
+ captureState: { status },
+ leavePage,
+ } as unknown as VoiceControlContextValue;
+ render(
+ <TeamHubRuntimeProvider runtime={runtime}>
+ <VoiceControlContext value={hardware}>
+ <VoiceModeSessionProvider>
+ <CaptureApi />
+ </VoiceModeSessionProvider>
+ </VoiceControlContext>
+ </TeamHubRuntimeProvider>,
+ );
+ openRecordingWindow();
+ const openWindow = vi.fn();
+ act(() => {
+ void api.start(
+ target,
+ prefix,
+ { dictation: false, live: true },
+ openWindow,
+ );
+ });
+ expect(leavePage).toHaveBeenCalledOnce();
+ expect(openWindow).not.toHaveBeenCalled();
+ expect(transport.openLive).not.toHaveBeenCalled();
+
+ await act(async () => released());
+ await waitFor(() => expect(transport.openLive).toHaveBeenCalledOnce());
+ expect(openWindow).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("allows the Meetings button during Voice Mode and waits for its microphone to close", async () => {
+ let floated!: () => void;
+ const floating = new Promise<void>((resolve) => {
+ floated = resolve;
+ });
+ let released!: () => void;
+ transport.close.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ released = resolve;
+ }),
+ );
+ const selectTargetRoom = vi.fn(async () => undefined);
+ const hardware = {
+ captureState: { status: "idle" },
+ composerMicrophoneActive: true,
+ selectTargetRoom,
+ } as unknown as VoiceControlContextValue;
+ render(
+ <TeamHubRuntimeProvider runtime={runtime}>
+ <VoiceControlContext value={hardware}>
+ <VoiceModeSessionProvider>
+ <CaptureApi />
+ <RecordingEntry
+ anotherMeRoomId="room-meeting"
+ tenantId={target.tenantId}
+ />
+ </VoiceModeSessionProvider>
+ </VoiceControlContext>
+ </TeamHubRuntimeProvider>,
+ );
+ act(() => {
+ void api.start(
+ target,
+ prefix,
+ { dictation: false, live: true },
+ () => floating,
+ );
+ });
+ await waitFor(() => expect(transport.openLive).toHaveBeenCalledOnce());
+ const meetings = screen.getByRole("button", { name: "Meetings" });
+ expect(meetings).toBeEnabled();
+ fireEvent.click(meetings);
+ expect(transport.close).not.toHaveBeenCalled();
+ await act(async () => floated());
+ expect(transport.close).toHaveBeenCalledOnce();
+ expect(selectTargetRoom).not.toHaveBeenCalled();
+
+ await act(async () => released());
+ await waitFor(() =>
+ expect(selectTargetRoom).toHaveBeenCalledExactlyOnceWith("room-meeting"),
+ );
+ expect(api.session).toBeUndefined();
+ });
+
it("keeps one transport across Room navigation and sends there directly", async () => {
const dispatch = vi.fn(async () => undefined);
const prepareSend = vi.fn(() => dispatch);
const view = renderSession(<VoiceRoomComposer prepareSend={prepareSend} />);
- act(() => api.start(target, prefix));
+ await act(() => api.start(target, prefix));
await waitFor(() => expect(transport.open).toHaveBeenCalledOnce());
act(() =>
@@ -136,7 +262,7 @@ describe("Voice Mode session", () => {
it("ends from anywhere, closing once and keeping unsent words for the Room", async () => {
renderSession();
- act(() => api.start(target, prefix));
+ await act(() => api.start(target, prefix));
await waitFor(() => expect(transport.open).toHaveBeenCalledOnce());
act(() =>
transport.receive?.({
@@ -146,7 +272,9 @@ describe("Voice Mode session", () => {
}),
);
- act(() => api.exit());
+ act(() => {
+ void api.exit();
+ });
expect(api.session?.closing).toBe(true);
await waitFor(() => expect(api.session).toBeUndefined());
expect(transport.close).toHaveBeenCalledOnce();
@@ -164,7 +292,7 @@ describe("Voice Mode session", () => {
() => new Promise(() => undefined),
);
renderSession();
- act(() => api.start(target, prefix));
+ await act(() => api.start(target, prefix));
await vi.waitFor(() => expect(transport.open).toHaveBeenCalledOnce());
await act(async () => undefined);
act(() =>
@@ -175,7 +303,9 @@ describe("Voice Mode session", () => {
}),
);
- act(() => api.exit());
+ act(() => {
+ void api.exit();
+ });
expect(api.session?.closing).toBe(true);
await act(async () => vi.advanceTimersByTime(voiceModeExitCeilingMs - 1));
expect(api.session?.closing).toBe(true);
@@ -193,8 +323,11 @@ describe("Voice Mode session", () => {
it("allows only one session at a time", async () => {
renderSession();
- act(() => api.start(target, prefix));
- act(() => api.start({ ...target, roomId: "room-other" }, prefix));
+ await act(async () => {
+ const started = api.start(target, prefix);
+ await api.start({ ...target, roomId: "room-other" }, prefix);
+ await started;
+ });
await waitFor(() => expect(transport.open).toHaveBeenCalledOnce());
expect(api.session?.target.roomId).toBe("room-voice");
});
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.tsx
index 45ac5921..d871f5f3 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.tsx
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-session.tsx
@@ -17,6 +17,10 @@ import type {
TeamHubVoiceLiveTurnMarker,
} from "@/features/teamhub/teamhub-types";
import { useOptionalVoiceControl } from "@/features/rooms/voice-control/voice-control-context";
+import {
+ closeRecordingWindow,
+ isRecordingWindowOpen,
+} from "@/features/rooms/voice-control/recording-window-store";
import type { VoiceLiveLine } from "./live/voice-live-arbiter";
import type { VoiceModeState } from "./voice-mode-controller";
import type { VoiceModePresentation } from "./voice-mode-presentation";
@@ -86,7 +90,9 @@ interface VoiceModeSessionApi {
target: VoiceModeSessionTarget,
prefix: VoiceTurnPrefix,
modes?: VoiceModeModes,
- ) => void;
+ openWindow?: () => void | Promise<unknown>,
+ ) => Promise<void>;
+ startMeeting: (startRecording: () => Promise<void>) => Promise<void>;
}
interface VoiceModeLevelStore {
@@ -138,11 +144,28 @@ export function VoiceModeSessionProvider({
const [session, setSession] = useState<VoiceModeSession>();
const bindings = useRef(new Map<string, VoiceModeRoomBinding>());
const engine = useRef<VoiceModeSessionEngine>(undefined);
+ const mounted = useRef(false);
const [levelStore] = useState(createLevelStore);
- useEffect(() => () => engine.current?.dispose(), []);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ engine.current?.dispose();
+ };
+ }, []);
const api = useMemo(() => {
// One shared load, so quick repeated starts still create one engine.
let loading: Promise<VoiceModeSessionEngine> | undefined;
+ let transition: Promise<void> | undefined;
+ const switchMode = (start: () => Promise<void>) => {
+ const operation = transition ? transition.then(start, start) : start();
+ transition = operation;
+ const clear = () => {
+ if (transition === operation) transition = undefined;
+ };
+ void operation.then(clear, clear);
+ return operation;
+ };
const load = () =>
(loading ??= import("./voice-mode-session-engine").then(
({ createVoiceModeSessionEngine }) =>
@@ -165,7 +188,9 @@ export function VoiceModeSessionProvider({
bindings.current.delete(roomId);
};
},
- exit: () => engine.current?.exit(),
+ exit: () => {
+ void engine.current?.exit();
+ },
retry: () => engine.current?.retry(),
setMuted: async (muted: boolean) => engine.current?.setMuted(muted),
setSoundOff: (soundOff: boolean) => engine.current?.setSoundOff(soundOff),
@@ -177,8 +202,42 @@ export function VoiceModeSessionProvider({
target: VoiceModeSessionTarget,
prefix: VoiceTurnPrefix,
modes?: VoiceModeModes,
+ openWindow?: () => void | Promise<unknown>,
) {
- void load().then((loaded) => loaded.start(target, prefix, modes));
+ return switchMode(async () => {
+ const control = deps.current.hardware;
+ const status = control?.captureState.status;
+ if (
+ control &&
+ control.listenerStatus !== "standby" &&
+ (isRecordingWindowOpen() ||
+ status === "starting" ||
+ status === "recording" ||
+ status === "finalizing")
+ ) {
+ const stop = control.leavePage
+ ? control.leavePage()
+ : control.stopCapture();
+ closeRecordingWindow();
+ await stop;
+ if (!mounted.current) return;
+ const { closeVoicePip } = await import("./voice-pip");
+ if (!mounted.current) return;
+ closeVoicePip("recording");
+ }
+ if (!mounted.current) return;
+ const floated = openWindow?.();
+ const loaded = await load();
+ if (mounted.current) loaded.start(target, prefix, modes);
+ await floated;
+ });
+ },
+ startMeeting(startRecording: () => Promise<void>) {
+ return switchMode(async () => {
+ const stopped = engine.current?.exit({ switchingToMeeting: true });
+ if (stopped) await stopped;
+ if (mounted.current) await startRecording();
+ });
},
level: { get: levelStore.get, subscribe: levelStore.subscribe },
};
diff --git a/apps/web/src/features/rooms/voice-control/recording-entry.tsx b/apps/web/src/features/rooms/voice-control/recording-entry.tsx
index bce274e7..c2cdcdc7 100644
--- a/apps/web/src/features/rooms/voice-control/recording-entry.tsx
+++ b/apps/web/src/features/rooms/voice-control/recording-entry.tsx
@@ -5,6 +5,7 @@ import {
import { use, useEffect, useEffectEvent, useRef, useState } from "react";
import { Icon } from "@/components/ui/icon";
+import { useOptionalVoiceModeSession } from "../chat/voice-mode/voice-mode-session";
import { LazyVoiceKeyDialog } from "./lazy-voice-key-dialog";
import { openRecordingWindow } from "./recording-window-store";
import {
@@ -28,6 +29,8 @@ export function RecordingEntry({
}) {
const livekit = useOptionalVoiceControl();
const voice = livekit;
+ const voiceMode = useOptionalVoiceModeSession();
+ const voiceInputBusy = voice?.composerMicrophoneActive && !voiceMode?.session;
// Recording transcribes with Soniox; xAI alone does not offer it.
const capabilities = use(VoiceCapabilitiesContext);
const retryConnection = use(VoiceConnectionRetryContext);
@@ -62,7 +65,7 @@ export function RecordingEntry({
? label
: !voice || !anotherMeRoomId
? "Meeting is loading"
- : voice.composerMicrophoneActive
+ : voiceInputBusy
? "Finish voice input first"
: standby
? "Recording is active in another tab"
@@ -76,20 +79,29 @@ export function RecordingEntry({
setKeyDialogOpen(true);
return;
}
- if (!voice || !anotherMeRoomId || pending || voice.composerMicrophoneActive)
- return;
+ if (!voice || !anotherMeRoomId || pending || voiceInputBusy) return;
setPending(true);
setError(undefined);
// Only this click may open the window that floats over other apps;
// the browser allows it for a few seconds after, enough to load it.
- const pip = import("../chat/voice-mode/voice-pip");
- void pip.then(({ openVoicePip }) => openVoicePip("recording"));
- void (async () => {
- await livekit?.selectTargetRoom?.(anotherMeRoomId);
- openRecordingWindow({ autoStart: true });
- })()
+ const startRecording = async () => {
+ const pip = import("../chat/voice-mode/voice-pip");
+ const opened = pip.then(({ openVoicePip }) => openVoicePip("recording"));
+ try {
+ await voice.selectTargetRoom?.(anotherMeRoomId);
+ await opened;
+ openRecordingWindow({
+ autoStart: !saving || Boolean(voiceMode?.session),
+ });
+ } catch (cause) {
+ await opened;
+ const { closeVoicePip } = await pip;
+ closeVoicePip("recording");
+ throw cause;
+ }
+ };
+ void (voiceMode ? voiceMode.startMeeting(startRecording) : startRecording())
.catch((cause: unknown) => {
- void pip.then(({ closeVoicePip }) => closeVoicePip("recording"));
setError(
cause instanceof Error ? cause.message : "Unable to open recording",
);
@@ -119,10 +131,7 @@ export function RecordingEntry({
disabled={
!connectionFailed &&
!needsKey &&
- (pending ||
- !voice ||
- !anotherMeRoomId ||
- voice.composerMicrophoneActive)
+ (pending || !voice || !anotherMeRoomId || voiceInputBusy)
}
onClick={start}
title={hint}
diff --git a/apps/web/src/features/rooms/voice-control/recording-window-store.ts b/apps/web/src/features/rooms/voice-control/recording-window-store.ts
index 017de6b6..b1e23208 100644
--- a/apps/web/src/features/rooms/voice-control/recording-window-store.ts
+++ b/apps/web/src/features/rooms/voice-control/recording-window-store.ts
@@ -79,6 +79,10 @@ export function useRecordingWindow() {
);
}
+export function isRecordingWindowOpen() {
+ return state.open;
+}
+
export function resetRecordingWindowForTest() {
state = closed;
listeners.clear();
diff --git a/apps/web/src/features/rooms/voice-control/recording-window.tsx b/apps/web/src/features/rooms/voice-control/recording-window.tsx
index 2bec1d28..7b8ea315 100644
--- a/apps/web/src/features/rooms/voice-control/recording-window.tsx
+++ b/apps/web/src/features/rooms/voice-control/recording-window.tsx
@@ -135,12 +135,16 @@ export default function RecordingWindow() {
// A recording that finished saving is reviewed in Another Me's chat.
const previousStatus = useRef(status);
useEffect(() => {
- if (status === "completed" && previousStatus.current !== "completed") {
+ if (
+ status === "completed" &&
+ previousStatus.current !== "completed" &&
+ !windowState.autoStart
+ ) {
closeVoicePip("recording");
closeRecordingWindow();
}
previousStatus.current = status;
- }, [status]);
+ }, [status, windowState.autoStart]);
const changeView = (next: RecordingView | undefined) => {
if (next) {
diff --git a/apps/web/src/features/rooms/voice-control/use-composer-microphone.ts b/apps/web/src/features/rooms/voice-control/use-composer-microphone.ts
index 09de7270..5fc8543f 100644
--- a/apps/web/src/features/rooms/voice-control/use-composer-microphone.ts
+++ b/apps/web/src/features/rooms/voice-control/use-composer-microphone.ts
@@ -1,6 +1,5 @@
import { useCallback } from "react";
-import { isActiveCapture } from "./voice-control-helpers";
import { tryAcquireVoicePublisherLease } from "./voice-publisher-lease";
import type { VoiceControlState } from "./use-voice-control-state";
@@ -19,13 +18,17 @@ export function useComposerMicrophone(
return useCallback(
async (options?: { resumeListening?: boolean }) => {
+ const recording = () => {
+ const status = refs.captureRef.current?.status;
+ return status === "starting" || status === "recording";
+ };
if (
refs.composerLeaseRef.current ||
refs.startPromiseRef.current ||
refs.enablePromiseRef.current
)
throw new Error("Another voice input is using the microphone");
- if (refs.captureRef.current && isActiveCapture(refs.captureRef.current)) {
+ if (recording()) {
throw new Error("Hardware recording is using the microphone");
}
// Chat dictation has a separate purpose and must not reuse a hardware
@@ -35,7 +38,7 @@ export function useComposerMicrophone(
refs.composerLeaseRef.current ||
refs.startPromiseRef.current ||
refs.enablePromiseRef.current ||
- (refs.captureRef.current && isActiveCapture(refs.captureRef.current))
+ recording()
)
throw new Error("Another voice input is using the microphone");
if (!refs.publisherLeaseRef.current) {
@@ -45,7 +48,8 @@ export function useComposerMicrophone(
if (
refs.composerLeaseRef.current ||
refs.startPromiseRef.current ||
- refs.enablePromiseRef.current
+ refs.enablePromiseRef.current ||
+ recording()
) {
release();
throw new Error("Another voice input is using the microphone");
diff --git a/apps/web/src/features/rooms/voice-control/use-voice-capture-commands.ts b/apps/web/src/features/rooms/voice-control/use-voice-capture-commands.ts
index 81f92031..e4312cc7 100644
--- a/apps/web/src/features/rooms/voice-control/use-voice-capture-commands.ts
+++ b/apps/web/src/features/rooms/voice-control/use-voice-capture-commands.ts
@@ -57,6 +57,7 @@ export function useVoiceCaptureCommands({
refs.startControllerRef.current = controller;
const operation = (async () => {
const target = await ensureTarget();
+ controller.signal.throwIfAborted();
// Publishing the microphone precedes Runtime subscription and ASR input.
// Wait for the current handshake even when the local track already exists,
// so the recorder cannot start ahead of live transcript coverage.
diff --git a/apps/web/src/features/rooms/voice-control/use-voice-session-lifecycle.ts b/apps/web/src/features/rooms/voice-control/use-voice-session-lifecycle.ts
index e09e8fb5..f623eebe 100644
--- a/apps/web/src/features/rooms/voice-control/use-voice-session-lifecycle.ts
+++ b/apps/web/src/features/rooms/voice-control/use-voice-session-lifecycle.ts
@@ -40,12 +40,9 @@ export function useVoiceSessionLifecycle(
refs.manuallyDisabledRef.current = true;
if (refs.leavePromiseRef.current) return refs.leavePromiseRef.current;
const session = refs.voiceSessionRef.current;
- if (
- !session &&
- !refs.roomRef.current &&
- !refs.enablePromiseRef.current &&
- !refs.startPromiseRef.current
- ) {
+ const starting = refs.startPromiseRef.current;
+ const enabling = refs.enablePromiseRef.current;
+ if (!session && !refs.roomRef.current && !enabling && !starting) {
if (refs.mountedRef.current) setListenerStatus("disabled");
return Promise.resolve();
}
@@ -53,7 +50,10 @@ export function useVoiceSessionLifecycle(
refs.startControllerRef.current?.abort();
requests.cancel();
refs.voiceSessionGenerationRef.current += 1;
- refs.capturePollGenerationRef.current += 1;
+ // An existing save keeps the same Capture ID and its poll must survive
+ // the microphone cleanup for the next mode.
+ if (capture?.status !== "finalizing" && capture?.status !== "recovering")
+ refs.capturePollGenerationRef.current += 1;
refs.voiceSessionRef.current = undefined;
const mediaCleanup = cleanupMedia();
refs.publisherLeaseRef.current?.();
@@ -73,7 +73,7 @@ export function useVoiceSessionLifecycle(
setCapture(capture, { status: "finalizing", capture });
}
}
- const operation = session
+ const released = session
? releaseVoiceSession(runtime.client, session, capture, (stopped) => {
if (
refs.mountedRef.current &&
@@ -83,6 +83,10 @@ export function useVoiceSessionLifecycle(
setCapture(stopped);
})
: Promise.resolve();
+ const operation = Promise.all([
+ released,
+ Promise.allSettled([starting, enabling]),
+ ]).then(() => undefined);
refs.leavePromiseRef.current = operation;
const clear = () => {
if (refs.leavePromiseRef.current === operation)
diff --git a/apps/web/src/features/rooms/voice-control/voice-control-provider.test.tsx b/apps/web/src/features/rooms/voice-control/voice-control-provider.test.tsx
index 403fc6eb..15dbf28e 100644
--- a/apps/web/src/features/rooms/voice-control/voice-control-provider.test.tsx
+++ b/apps/web/src/features/rooms/voice-control/voice-control-provider.test.tsx
@@ -27,7 +27,10 @@ import type {
TeamHubVoiceTranscriptEventPage,
} from "@/features/teamhub/teamhub-types";
import * as publisherLease from "./voice-publisher-lease";
-import { useVoiceControl } from "./voice-control-context";
+import {
+ useVoiceControl,
+ type VoiceControlContextValue,
+} from "./voice-control-context";
import { LiveKitVoiceControlProvider } from "./voice-control-provider";
import { VoiceFocusSurface } from "./voice-focus-surface";
import {
@@ -182,6 +185,58 @@ function spyVoiceRoute(
}
describe("LiveKit voice input lifecycle", () => {
+ it("lends the microphone to Voice Mode while the Meeting is saving", async () => {
+ const runtime = createTestTeamHubRuntime();
+ const accepted = acceptVoice(runtime);
+ const stop = spyVoiceRoute(
+ runtime,
+ accepted,
+ "POST",
+ "/v0/voice-captures/{captureSessionId}/stop",
+ );
+ const getCapture = accepted("GET", "/v0/voice-captures/{captureSessionId}");
+ runtime.server.on(
+ "GET",
+ "/v0/voice-captures/{captureSessionId}",
+ async (request) => {
+ const stopped = await stop.mock.results[0]?.value;
+ return stopped ?? getCapture(request);
+ },
+ );
+ let voice!: VoiceControlContextValue;
+ function CaptureVoice() {
+ const current = useVoiceControl();
+ useEffect(() => {
+ voice = current;
+ }, [current]);
+ return <ListenerState />;
+ }
+ render(
+ <TeamHubRuntimeProvider runtime={runtime}>
+ <MemoryRouter>
+ <LiveKitVoiceControlProvider tenantId="tenant-northstar">
+ <CaptureVoice />
+ </LiveKitVoiceControlProvider>
+ </MemoryRouter>
+ </TeamHubRuntimeProvider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Start" }));
+ await waitFor(() =>
+ expect(screen.getByLabelText("capture")).toHaveTextContent("recording:"),
+ );
+ await act(() => voice.leavePage?.());
+ expect(screen.getByLabelText("capture")).toHaveTextContent("finalizing:");
+
+ await act(async () => {
+ const release = await voice.acquireComposerMicrophone({
+ resumeListening: false,
+ });
+ expect(voice.captureState.status).toBe("finalizing");
+ await release();
+ });
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
it.each([3, 6])(
"keeps microphone retry errors out of recording startup until %i failures are resolved",
async (failures) => {
diff --git a/apps/web/src/features/rooms/voice-control/voice-focus-state.ts b/apps/web/src/features/rooms/voice-control/voice-focus-state.ts
index 8864dc1b..5a96b429 100644
--- a/apps/web/src/features/rooms/voice-control/voice-focus-state.ts
+++ b/apps/web/src/features/rooms/voice-control/voice-focus-state.ts
@@ -1,4 +1,10 @@
-import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import {
isTranscriptRecoveryPaused,
@@ -21,6 +27,12 @@ export function useVoiceArming(input: {
const [status, setStatus] = useState<ArmStatus>("pending");
const [error, setError] = useState<string>();
const generationRef = useRef(0);
+ useLayoutEffect(
+ () => () => {
+ generationRef.current += 1;
+ },
+ [],
+ );
const arm = useCallback(async () => {
if (!voice) return;
@@ -33,6 +45,7 @@ export function useVoiceArming(input: {
const askBrowser = async () => {
asked = true;
const available = await voice.discoverDevices();
+ if (generationRef.current !== generation) return;
const device =
(voice.boundDevice
? matchBoundVoiceMicrophone(available, voice.boundDevice)
@@ -47,6 +60,7 @@ export function useVoiceArming(input: {
? voice.startCapture()
: voice.startNewCapture();
if (!voice.boundDevice) await askBrowser();
+ if (generationRef.current !== generation) return;
try {
await begin();
} catch (cause) {
@@ -54,6 +68,7 @@ export function useVoiceArming(input: {
// rejected Start must keep its own reason.
if (asked || !isMicrophoneFailure(cause)) throw cause;
await askBrowser();
+ if (generationRef.current !== generation) return;
await begin();
}
if (generationRef.current === generation) setStatus("armed");