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): return to Linger from a floated voice window and resize it
Kilynea1851474227
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex b5fa6313..0cb0eaa0 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -102,14 +102,23 @@ build:assets` to check the initial JS budget.During Live, the Meeting entry offers to start a new Meeting even while anearlier one is saving. Both in-page voice windows retain a visible, draggabletitle bar: dark in browsers, the window's own surface colour in the desktop- app. Picture-in-picture keeps the browser title bar. The desktop app cannot- open Document Picture-in-Picture; when its preload offers- `lingerDesktop.voiceWindow`, `voice-pip.ts` opens the floating window with- `window.open("")` instead (the desktop main process allows only that call),- renders the same voice UI into it, and shows a Show Linger window button that- brings the main window forward while the call keeps running. A desktop app- without `voiceWindow` keeps the voice windows in the page, with no float- button, and on macOS out of the window drag strip.+ app. Picture-in-picture keeps the browser title bar. The desktop app floats+ them in its own always-on-top window, which stays up while the main window+ is minimized or closed to the tray: when the preload offers+ `window.lingerDesktop.voiceWindow`, `voice-pip.ts` opens it with+ `window.open("")` (the desktop main process allows only that call) and is+ the only place that knows which kind of window it got. A desktop app without that field keeps voice windows+ in the page with no float button. In the page on macOS they stay out of the+ window drag strip. In the page both windows resize by any edge or corner+ (`voice-window-resize.tsx`), down to a minimum size and never past the+ viewport; the corner grip also takes arrow keys. Dragging the title bar+ keeps the whole window inside the viewport too, and a window that grows+ where it sits, or whose viewport shrinks, moves back in. Neither window can+ be taller than the viewport leaves room for, so the header stays reachable.+ The size lasts while the window is open and is not stored. Voice Mode's expand button switches+ between its two preset sizes and drops a dragged size; a minimized+ recording resizes in width only. A floated window has no handles: the+ browser or the desktop app resizes it.- The compact primary rail reveals labels on hover and keyboard focus withoutmoving link hit areas or neighbouring links. A stationary pointer at an edgemust not trigger repeated hover enter/leave; sidebar expansion and Chat list@@ -132,6 +141,12 @@ build:assets` to check the initial JS budget.- Recording and Voice Mode distinguish the native window's close action fromback to tab through the shared PiP return detection. Back to tab keeps thesession running in the page and exposes a Float action; close ends it.+ Every floated window also draws its own return button, in the browser and+ in the desktop app: `returnVoicePipToPage` brings the tab or the main+ window to the front, reports the return itself and closes the floated+ window. Voice Mode then opens the Room the call started in; a recording+ stays on the page the main window shows. The desktop app's window has no+ back to tab button, so every other close of it ends the session.Recording moves one portal host between documents so paused state, Askdrafts and transcript scroll survive the move. Hide it while classifying anative close, and ignore a late result after unmount or a replacement window.diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.cssindex 88d488e8..666c102b 100644--- a/apps/web/src/app/globals.css+++ b/apps/web/src/app/globals.css@@ -5563,9 +5563,8 @@ button.question-choice:focus-visible {font-size: 12px;font-weight: 500;}-/* The desktop app cannot float voice windows into picture-in-picture, so they- always stay in the page; there the bar takes the window's own surface- instead of a browser-style dark frame. */+/* A voice window inside the desktop app's page takes the window's own surface+ for its bar instead of a browser-style dark frame. */:root[data-desktop-shell] .voice-window-title {background-color: var(--app-canvas);color: var(--app-ink);diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.test.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.test.tsxindex c7d70591..4209d254 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.test.tsx+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.test.tsx@@ -266,17 +266,23 @@ describe("Voice Mode mini window", () => {renderWindow();const panel = screen.getByRole("region", { name: "Voice Mode window" });expect(panel).toHaveStyle({ width: "320px" });- expect(panel).toHaveStyle({ maxHeight: "calc(min(480px, 70dvh) + 36px)" });+ expect(panel).toHaveStyle({+ maxHeight: "calc(min(480px, 70dvh, 100dvh - 68px) + 36px)",+ });fireEvent.click(screen.getByRole("button", { name: "Expand Voice Mode window" }),);expect(panel).toHaveStyle({ width: "560px" });- expect(panel).toHaveStyle({ maxHeight: "calc(min(760px, 86dvh) + 36px)" });+ expect(panel).toHaveStyle({+ maxHeight: "calc(min(760px, 86dvh, 100dvh - 68px) + 36px)",+ });fireEvent.click(screen.getByRole("button", { name: "Shrink Voice Mode window" }),);expect(panel).toHaveStyle({ width: "320px" });- expect(panel).toHaveStyle({ maxHeight: "calc(min(480px, 70dvh) + 36px)" });+ expect(panel).toHaveStyle({+ maxHeight: "calc(min(480px, 70dvh, 100dvh - 68px) + 36px)",+ });});it("floats over other windows as the one Voice Mode window", async () => {@@ -290,10 +296,17 @@ describe("Voice Mode mini window", () => {screen.queryByRole("region", { name: "Voice Mode window" }),).not.toBeInTheDocument();// The desktop sizes, places, and closes that window, so it shows no- // size or close button of its own.+ // size or close button and no resize grip of its own, only the way+ // back.expect(floating.queryByRole("button", { name: "Expand Voice Mode window" }),).not.toBeInTheDocument();+ expect(+ floating.queryByRole("button", { name: "Resize Voice Mode window" }),+ ).not.toBeInTheDocument();+ expect(+ floating.getByRole("button", { name: "Return Voice Mode to Linger" }),+ ).toHaveAttribute("title", "Back to Linger; Voice Mode continues");expect(floating.queryByRole("button", { name: "End Voice Mode" }),).not.toBeInTheDocument();@@ -376,50 +389,99 @@ describe("Voice Mode mini window", () => {}});- it("floats in the desktop app's own window and brings its main window back", async () => {+ it("returns from the browser's floating window by its return button", async () => {const fake = installFakeVoicePip();- const showMainWindow = vi.fn(async () => {});- const desktop = window as { lingerDesktop?: unknown };- desktop.lingerDesktop = { voiceWindow: { showMainWindow } };- const open = vi- .spyOn(window, "open")- .mockReturnValue(fake.pipWindow as unknown as Window);+ const focus = vi.spyOn(window, "focus").mockImplementation(() => {});try {renderWindow();- // In the page, one click floats the call into the desktop's window.+ await act(() => openVoicePip("voice-mode"));+ const floating = within(fake.document.body);await act(async () => {fireEvent.click(- screen.getByRole("button", { name: "Float Voice Mode window" }),+ await floating.findByRole("button", {+ name: "Return Voice Mode to Linger",+ }),);- await Promise.resolve();});- const floating = within(fake.document.body);- await floating.findByRole("region", { name: "Voice Mode window" });- expect(fake.requestWindow).not.toHaveBeenCalled();- expect(open).toHaveBeenCalledOnce();- expect(screen.getByTestId("location")).toHaveTextContent(- "/t/tenant-northstar/rooms/room-other/chat",+ // The tab comes to the front and the call goes on in the window inside+ // the page, on the conversation it started in.+ expect(focus).toHaveBeenCalledOnce();+ expect(fake.pipWindow.close).toHaveBeenCalledOnce();+ await waitFor(() =>+ expect(screen.getByTestId("location")).toHaveTextContent(+ "/t/tenant-northstar/rooms/room-voice/chat",+ ),);+ expect(+ screen.getByRole("region", { name: "Voice Mode window" }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Return Voice Mode to Linger" }),+ ).not.toBeInTheDocument();+ expect(voice.exit).not.toHaveBeenCalled();+ } finally {+ focus.mockRestore();+ fake.frame.remove();+ Reflect.deleteProperty(window, "documentPictureInPicture");+ resetVoicePipForTest();+ }+ });- // The way back opens the conversation and shows the main window; the- // floating window and the call stay.- fireEvent.click(- floating.getByRole("button", { name: "Show Linger window" }),- );- expect(showMainWindow).toHaveBeenCalledOnce();- expect(screen.getByTestId("location")).toHaveTextContent(- "/t/tenant-northstar/rooms/room-voice/chat",+ it("returns from the desktop app's window by its own button, and ends when that window closes", async () => {+ const fake = installFakeVoicePip();+ const open = vi.fn(() => fake.pipWindow as unknown as Window);+ const showMain = vi.fn(async () => {});+ const originalOpen = window.open;+ window.open = open;+ const desktop = window as { lingerDesktop?: unknown };+ desktop.lingerDesktop = {+ voiceWindow: { showMainWindow: showMain },+ };+ try {+ renderWindow();+ await act(() => openVoicePip("voice-mode"));+ const floating = within(fake.document.body);+ await act(async () => {+ fireEvent.click(+ await floating.findByRole("button", {+ name: "Return Voice Mode to Linger",+ }),+ );+ });+ expect(showMain).toHaveBeenCalledOnce();+ // The call goes on in the window inside the page, on its conversation,+ // with no return button there.+ await waitFor(() =>+ expect(screen.getByTestId("location")).toHaveTextContent(+ "/t/tenant-northstar/rooms/room-voice/chat",+ ),);- expect(voice.exit).not.toHaveBeenCalled();expect(- floating.getByRole("region", { name: "Voice Mode window" }),+ screen.getByRole("region", { name: "Voice Mode window" }),).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Return Voice Mode to Linger" }),+ ).not.toBeInTheDocument();+ expect(voice.exit).not.toHaveBeenCalled();- // Closing the floating window ends Voice Mode.- act(() => fake.pipWindow.close());+ await act(async () => {+ fireEvent.click(+ screen.getByRole("button", { name: "Float Voice Mode window" }),+ );+ });+ expect(open).toHaveBeenCalledTimes(2);+ expect(fake.requestWindow).not.toHaveBeenCalled();+ await floating.findByRole("region", { name: "Voice Mode window" });+ // The window's close button ends Voice Mode even as the main window+ // comes to the front.+ act(() => {+ fake.pipWindow.close();+ document.dispatchEvent(new Event("visibilitychange"));+ });await waitFor(() => expect(voice.exit).toHaveBeenCalledOnce());+ expect(showMain).toHaveBeenCalledOnce();} finally {- open.mockRestore();+ window.open = originalOpen;delete desktop.lingerDesktop;fake.frame.remove();Reflect.deleteProperty(window, "documentPictureInPicture");@@ -427,6 +489,123 @@ describe("Voice Mode mini window", () => {}});+ it("resizes by its edges and corners, inside the page and above a minimum", () => {+ renderWindow();+ const panel = screen.getByRole("region", { name: "Voice Mode window" });+ const onScreen = vi+ .spyOn(panel, "getBoundingClientRect")+ .mockReturnValue(new DOMRect(600, 100, 320, 300));+ const grip = screen.getByRole("button", {+ name: "Resize Voice Mode window",+ });+ fireEvent.pointerDown(grip, { button: 0, clientX: 920, clientY: 400 });+ fireEvent.pointerMove(grip, { clientX: 960, clientY: 500 });+ expect(panel).toHaveStyle({ height: "400px", width: "360px" });+ expect(panel).toHaveAttribute("data-size", "custom");+ // The corner stops 16px short of the page's edge, as a drag does.+ fireEvent.pointerMove(grip, { clientX: 5000, clientY: 5000 });+ expect(panel).toHaveStyle({+ height: `${window.innerHeight - 16 - 100}px`,+ width: `${window.innerWidth - 16 - 600}px`,+ });+ fireEvent.pointerMove(grip, { clientX: 0, clientY: 0 });+ expect(panel).toHaveStyle({ height: "200px", width: "260px" });+ fireEvent.pointerUp(grip);+ // A move after the drag ended changes nothing.+ fireEvent.pointerMove(grip, { clientX: 960, clientY: 500 });+ expect(panel).toHaveStyle({ height: "200px", width: "260px" });++ // The left edge moves that side and keeps the right one where it was.+ const left = panel.querySelector('[data-resize-edge="w"]')!;+ fireEvent.pointerDown(left, { button: 0, clientX: 600, clientY: 200 });+ fireEvent.pointerMove(left, { clientX: 500, clientY: 900 });+ fireEvent.pointerUp(left);+ expect(panel).toHaveStyle({ height: "300px", left: "500px" });+ expect(panel).toHaveStyle({ width: "420px" });++ // Arrow keys on the grip resize too.+ onScreen.mockReturnValue(new DOMRect(500, 100, 420, 300));+ fireEvent.keyDown(grip, { key: "ArrowRight" });+ expect(panel).toHaveStyle({ height: "300px", width: "428px" });+ fireEvent.keyDown(grip, { key: "ArrowUp", shiftKey: true });+ expect(panel).toHaveStyle({ height: "268px", width: "420px" });+ });++ it("goes back to a preset size from a dragged one", () => {+ renderWindow();+ const panel = screen.getByRole("region", { name: "Voice Mode window" });+ vi.spyOn(panel, "getBoundingClientRect").mockReturnValue(+ new DOMRect(200, 100, 320, 300),+ );+ const grip = screen.getByRole("button", {+ name: "Resize Voice Mode window",+ });+ fireEvent.pointerDown(grip, { button: 0, clientX: 520, clientY: 400 });+ fireEvent.pointerMove(grip, { clientX: 800, clientY: 400 });+ fireEvent.pointerUp(grip);+ expect(panel).toHaveStyle({ width: "600px" });+ // Wider than the expanded preset, so the button offers the compact one.+ fireEvent.click(+ screen.getByRole("button", { name: "Shrink Voice Mode window" }),+ );+ expect(panel).toHaveStyle({ width: "320px" });+ expect(panel).toHaveStyle({+ maxHeight: "calc(min(480px, 70dvh, 100dvh - 68px) + 36px)",+ });+ expect(panel.style.height).toBe("");+ expect(panel).toHaveAttribute("data-size", "compact");+ });++ it("cannot be dragged out of the viewport, and moves back in when it grows or the viewport shrinks", () => {+ const observed: (() => void)[] = [];+ const resize = () => observed.forEach((callback) => callback());+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: () => void) {+ observed.push(callback);+ }+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ renderWindow();+ const panel = screen.getByRole("region", { name: "Voice Mode window" });+ let height = 300;+ Object.defineProperty(panel, "offsetHeight", { get: () => height });+ const title = screen.getByText("Voice Mode", {+ selector: ".voice-window-title",+ });+ fireEvent.pointerDown(title, { button: 0, clientX: 800, clientY: 90 });+ fireEvent.pointerMove(window, { clientX: 5000, clientY: 5000 });+ fireEvent.pointerUp(window);+ expect(panel).toHaveStyle({+ left: `${window.innerWidth - 320 - 16}px`,+ top: `${window.innerHeight - 300 - 16}px`,+ });+ fireEvent.pointerDown(title, { button: 0, clientX: 800, clientY: 500 });+ fireEvent.pointerMove(window, { clientX: -5000, clientY: -5000 });+ fireEvent.pointerUp(window);+ expect(panel).toHaveStyle({ left: "16px", top: "16px" });++ // At the bottom of the page, a longer conversation makes it taller.+ fireEvent.pointerDown(title, { button: 0, clientX: 100, clientY: 30 });+ fireEvent.pointerMove(window, { clientX: 100, clientY: 5000 });+ fireEvent.pointerUp(window);+ expect(panel).toHaveStyle({ top: `${window.innerHeight - 300 - 16}px` });+ height = 480;+ act(() => resize());+ expect(panel).toHaveStyle({ top: `${window.innerHeight - 480 - 16}px` });++ // A shorter viewport moves it up until all of it shows again.+ vi.stubGlobal("innerHeight", 600);+ act(() => {+ window.dispatchEvent(new Event("resize"));+ });+ expect(panel).toHaveStyle({ top: `${600 - 480 - 16}px` });+ });+it("drags from anywhere on the header, including the title", () => {renderWindow();const panel = screen.getByRole("region", { name: "Voice Mode window" });@@ -505,13 +684,19 @@ describe("Voice Mode mini window", () => {]);});- it("keeps a dragged window inside the viewport", () => {- expect(clampPosition({ left: -500, top: -500 })).toEqual({+ it("keeps the whole window 16px inside the viewport", () => {+ const size = { height: 400, width: 320 };+ expect(clampPosition({ left: -500, top: -500 }, size)).toEqual({left: 16,top: 16,});- const far = clampPosition({ left: 99_999, top: 99_999 });- expect(far.left).toBe(window.innerWidth - 320 - 16);- expect(far.top).toBe(window.innerHeight - 120);+ expect(clampPosition({ left: 99_999, top: 99_999 }, size)).toEqual({+ left: window.innerWidth - 320 - 16,+ top: window.innerHeight - 400 - 16,+ });+ // Taller than the viewport: the header stays at the top of the page.+ expect(+ clampPosition({ left: 200, top: 300 }, { ...size, height: 5000 }),+ ).toEqual({ left: 200, top: 16 });});});diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.tsxindex 403ddf67..8681ed67 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.tsx+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-mini-window.tsx@@ -4,6 +4,7 @@ import {Mic01Icon,MicOff01Icon,Minimize01Icon,+ PictureInPictureExitIcon,PictureInPictureOnIcon,RotateLeft01Icon,VolumeHighIcon,@@ -18,6 +19,7 @@ import {useState,type CSSProperties,type PointerEvent as ReactPointerEvent,+ type RefObject,useSyncExternalStore,type ReactNode,} from "react";@@ -39,14 +41,19 @@ import { voiceModeStatusLabel } from "./voice-mode-presentation";import styles from "./voice-mode.module.css";import { registerVoiceWindow, type VoiceWindowAction } from "./voice-ui-bridge";import {- canShowDesktopMainWindow,onVoicePipClosedByHuman,openVoicePip,returnedToOpener,- showDesktopMainWindow,+ returnVoicePipToPage,useVoicePip,voicePipSupported,} from "./voice-pip";+import {+ containedVoiceWindowPosition,+ useKeptInViewport,+ VoiceWindowResizeHandles,+ type VoiceWindowBounds,+} from "./voice-window-resize";import { showVoiceNotice, useVoiceNotice } from "./voice-notice";import {useOptionalVoiceModeSession,@@ -54,10 +61,14 @@ import {type VoiceModeSession,} from "./voice-mode-session";+// The height of the conversation below the 36px title bar: never more than+// leaves the whole window 16px inside the page.const windowSizes = {- compact: { height: "min(480px,70dvh)", width: 320 },- expanded: { height: "min(760px,86dvh)", width: 560 },+ compact: { height: "min(480px,70dvh,100dvh - 68px)", width: 320 },+ expanded: { height: "min(760px,86dvh,100dvh - 68px)", width: 560 },} as const;+/** Still shows the header's controls and a few lines of the conversation. */+const minWindowSize = { height: 200, width: 260 };const windowGap = 16;const positionKey = "linger:voice-mode-window";/** Above this level the Human is speaking, not just breathing near the mic. */@@ -72,12 +83,14 @@ type WindowSize = keyof typeof windowSizes;/*** Floating window for the running Voice Mode session. It follows the Human* across Rooms, shows this session's turns and the Room's replies, and can be- * dragged anywhere on screen. Where the browser supports it, the window lives- * in an always-on-top picture-in-picture window instead, so it stays over other- * tabs and apps. Closing it, from its own button or the desktop's, ends Voice- * Mode: the window leaves at once while the session drains its last- * words in the background, and the Room composer shows that finishing state.- * The desktop's back to tab button only returns to the conversation.+ * dragged anywhere on screen and resized by its edges and corners. Where the+ * browser or the desktop app supports it, the window lives in an+ * always-on-top window of its own instead, so it stays over other tabs and+ * apps. Closing it, from its own button or the desktop's, ends Voice Mode:+ * the window leaves at once while the session drains its last words in the+ * background, and the Room composer shows that finishing state. The floating+ * window's return button, like the browser's back to tab button, only returns+ * to the conversation.*/export default function VoiceModeMiniWindow({anotherMeActorId,@@ -168,8 +181,8 @@ function MiniWindow({const notice = useVoiceNotice();const pip = useVoicePip("voice-mode");// One window: the desktop's close button on the floating one ends Voice Mode- // too. Its back to tab button instead returns to this conversation and keeps- // the call, which goes on in the window inside the page.+ // too. Its back to tab or return button instead returns to this conversation+ // and keeps the call, which goes on in the window inside the page.const exitRef = useRef(onExit);const openRoomRef = useRef(() => {});useLayoutEffect(() => {@@ -197,11 +210,26 @@ function MiniWindow({[],);- // Every session opens compact; only the expand button enlarges it.+ // Every session opens compact. The expand button switches between the two+ // preset sizes; dragging an edge or corner gives the window any other size,+ // which lasts until a preset is chosen again or the session ends.const [size, setSize] = useState<WindowSize>("compact");+ const [resized, setResized] = useState<{ height: number; width: number }>();const { width, height } = windowSizes[size];- const { consumeDrag, dragHandlers, place, position } =- useDraggablePosition(width);+ const large = resized+ ? resized.width >= windowSizes.expanded.width+ : size === "expanded";+ const choosePreset = (next: WindowSize) => {+ setResized(undefined);+ setSize(next);+ };+ const frameRef = useRef<HTMLElement>(null);+ const { consumeDrag, dragHandlers, moveTo, place, position, remember } =+ useDraggablePosition(+ resized?.width ?? width,+ frameRef,+ !pip && !leavingPip,+ );const windowControl = useRef<(action: VoiceWindowAction) => void>(() => {});useLayoutEffect(() => {windowControl.current = (action) => {@@ -211,7 +239,7 @@ function MiniWindow({else if (pip)showVoiceNotice("Drag the floating window to move or resize it.");else if (action === "expand" || action === "shrink")- setSize(action === "expand" ? "expanded" : "compact");+ choosePreset(action === "expand" ? "expanded" : "compact");else place(action === "move_left" ? "left" : "right");};});@@ -232,255 +260,273 @@ function MiniWindow({const state = session.state;const muted = session.muted;const listening = Boolean(state.microphoneActive) && !muted;- const toggleSize = () => {- const next: WindowSize = size === "compact" ? "expanded" : "compact";- setSize(next);- };if (leavingPip) return null;return createPortal(<sectionaria-label="Voice Mode window"className={pip- ? "flex h-dvh w-full flex-col overflow-hidden bg-app-canvas"- : "voice-mode-window app-floating-enter fixed z-[90] flex flex-col overflow-hidden rounded-xl bg-app-canvas shadow-xl transition-[width,max-height] duration-200 ease-out motion-reduce:transition-none"+ ? "flex h-dvh w-full flex-col bg-app-canvas"+ : `voice-mode-window app-floating-enter fixed z-[90] flex max-w-[calc(100vw-32px)] flex-col rounded-xl bg-app-canvas shadow-xl ${+ // A dragged edge is followed at once; only a preset eases in.+ resized+ ? "max-h-[calc(100dvh-32px)]"+ : "transition-[width,max-height] duration-200 ease-out motion-reduce:transition-none"+ }`}data-pip={pip ? true : undefined}- data-size={size}+ data-size={resized ? "custom" : size}+ ref={frameRef}style={pip? undefined- : { ...position, maxHeight: `calc(${height} + 36px)`, width }+ : resized+ ? { ...position, ...resized }+ : { ...position, maxHeight: `calc(${height} + 36px)`, width }}>- {pip ? null : (- <div- className="voice-window-title flex h-9 shrink-0 cursor-grab touch-none select-none items-center px-3 active:cursor-grabbing"- {...dragHandlers}- >- Voice Mode- </div>- )}- <header- className={`flex shrink-0 select-none items-center gap-2 border-b border-app-border px-3 py-2 ${- pip ? "" : "cursor-grab touch-none active:cursor-grabbing"- }`}- {...(pip ? {} : dragHandlers)}- >- <VoiceAvatarBeat listening={listening}>- <span className={styles.avatarSpin}>- <ActorAvatar- actorId={anotherMeActorId}- kind="agent"- name="Another Me"- size="xs"- />- </span>- </VoiceAvatarBeat>- <button- className="min-w-0 flex-1 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-app-focus"- onClick={() => {- if (!consumeDrag())- void navigate(`/t/${tenantId}/rooms/${roomId}/chat`);- }}- title="Open this conversation"- type="button"- >- <span className="block truncate text-[14px] font-medium leading-5 text-app-ink">- {roomName || "Voice Mode"}- </span>- <span className="block truncate text-[12px] leading-4 text-app-muted">- {voiceModeStatusLabel({ ...state, entered: session.entered })}- </span>- </button>- <span- className="flex shrink-0 items-center"- onPointerDown={(event) => event.stopPropagation()}+ {/* Clips the content to the window's corners; the resize handles sit+ outside it, on the border. */}+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-[inherit]">+ {pip ? null : (+ <div+ className="voice-window-title flex h-9 shrink-0 cursor-grab touch-none select-none items-center px-3 active:cursor-grabbing"+ {...dragHandlers}+ >+ Voice Mode+ </div>+ )}+ <header+ className={`flex shrink-0 select-none items-center gap-2 border-b border-app-border px-3 py-2 ${+ pip ? "" : "cursor-grab touch-none active:cursor-grabbing"+ }`}+ {...(pip ? {} : dragHandlers)}>- {state.canRetry ? (- <Button- // Names differ from the Room composer's controls so both can- // be on screen without two identically named buttons.- aria-label="Retry voice message from the voice window"- disabled={state.sending}- onClick={onRetry}- size="compactIcon"- tone="ghost"- >- <Icon icon={RotateLeft01Icon} size={16} />- </Button>- ) : null}- <Button- aria-label={muted ? "Unmute Voice Mode" : "Mute Voice Mode"}- aria-pressed={muted}- disabled={!state.microphoneActive}- onClick={() => void onMute(!muted)}- size="compactIcon"- tone="ghost"+ <VoiceAvatarBeat listening={listening}>+ <span className={styles.avatarSpin}>+ <ActorAvatar+ actorId={anotherMeActorId}+ kind="agent"+ name="Another Me"+ size="xs"+ />+ </span>+ </VoiceAvatarBeat>+ <button+ className="min-w-0 flex-1 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-app-focus"+ onClick={() => {+ if (!consumeDrag())+ void navigate(`/t/${tenantId}/rooms/${roomId}/chat`);+ }}+ title="Open this conversation"+ type="button">- {muted ? (- <Icon icon={MicOff01Icon} size={16} />- ) : (- <Icon icon={Mic01Icon} size={16} />- )}- </Button>- {soundOff === undefined ? null : (+ <span className="block truncate text-[14px] font-medium leading-5 text-app-ink">+ {roomName || "Voice Mode"}+ </span>+ <span className="block truncate text-[12px] leading-4 text-app-muted">+ {voiceModeStatusLabel({ ...state, entered: session.entered })}+ </span>+ </button>+ <span+ className="flex shrink-0 items-center"+ onPointerDown={(event) => event.stopPropagation()}+ >+ {state.canRetry ? (+ <Button+ // Names differ from the Room composer's controls so both can+ // be on screen without two identically named buttons.+ aria-label="Retry voice message from the voice window"+ disabled={state.sending}+ onClick={onRetry}+ size="compactIcon"+ tone="ghost"+ >+ <Icon icon={RotateLeft01Icon} size={16} />+ </Button>+ ) : null}<Button- aria-label={- soundOff- ? "Turn reply sound on from the voice window"- : "Turn reply sound off from the voice window"- }- aria-pressed={soundOff}- onClick={() => onSoundOff(!soundOff)}+ aria-label={muted ? "Unmute Voice Mode" : "Mute Voice Mode"}+ aria-pressed={muted}+ disabled={!state.microphoneActive}+ onClick={() => void onMute(!muted)}size="compactIcon"tone="ghost">- {soundOff ? (- <Icon icon={VolumeOffIcon} size={16} />+ {muted ? (+ <Icon icon={MicOff01Icon} size={16} />) : (- <Icon icon={VolumeHighIcon} size={16} />+ <Icon icon={Mic01Icon} size={16} />)}</Button>- )}- {/* Back in the page, one click floats the call again; the browser+ {soundOff === undefined ? null : (+ <Button+ aria-label={+ soundOff+ ? "Turn reply sound on from the voice window"+ : "Turn reply sound off from the voice window"+ }+ aria-pressed={soundOff}+ onClick={() => onSoundOff(!soundOff)}+ size="compactIcon"+ tone="ghost"+ >+ {soundOff ? (+ <Icon icon={VolumeOffIcon} size={16} />+ ) : (+ <Icon icon={VolumeHighIcon} size={16} />+ )}+ </Button>+ )}+ {/* Brings the call back into the conversation it started in, in+ the desktop app's main window or this browser tab. */}+ {pip ? (+ <Button+ aria-label="Return Voice Mode to Linger"+ onClick={() => returnVoicePipToPage("voice-mode")}+ size="compactIcon"+ title="Back to Linger; Voice Mode continues"+ tone="ghost"+ >+ <Icon icon={PictureInPictureExitIcon} size={16} />+ </Button>+ ) : null}+ {/* Back in the page, one click floats the call again; the browseropens that window only from a click in the page. */}- {/* The desktop app's floating window has no back to tab button; this- brings its main window forward and the call goes on. */}- {pip && canShowDesktopMainWindow() ? (- <Button- aria-label="Show Linger window"- onClick={() => {- void navigate(`/t/${tenantId}/rooms/${roomId}/chat`);- showDesktopMainWindow();- }}- size="compactIcon"- title="Show the Linger window; the call continues"- tone="ghost"- >- <Icon icon={Maximize01Icon} size={14} />- </Button>- ) : null}- {pip || !voicePipSupported() ? null : (- <Button- aria-label="Float Voice Mode window"- onClick={() => void openVoicePip("voice-mode")}- size="compactIcon"- title="Float over other tabs and apps"- tone="ghost"- >- <Icon icon={PictureInPictureOnIcon} size={16} />- </Button>- )}- {pip ? null : (- <Button- aria-label={- size === "compact"- ? "Expand Voice Mode window"- : "Shrink Voice Mode window"- }- onClick={toggleSize}- size="compactIcon"- tone="ghost"- >- {size === "compact" ? (- <Icon icon={Maximize01Icon} size={14} />- ) : (- <Icon icon={Minimize01Icon} size={14} />- )}- </Button>- )}- {/* The floating window's own close button ends Voice Mode there. */}- {pip ? null : (- <Button- aria-label="End Voice Mode"- onClick={onExit}- size="compactIcon"- tone="ghost"- >- <Icon icon={Cancel01Icon} size={16} />- </Button>+ {pip || !voicePipSupported() ? null : (+ <Button+ aria-label="Float Voice Mode window"+ onClick={() => void openVoicePip("voice-mode")}+ size="compactIcon"+ title="Float over other tabs and apps"+ tone="ghost"+ >+ <Icon icon={PictureInPictureOnIcon} size={16} />+ </Button>+ )}+ {pip ? null : (+ <Button+ aria-label={+ large+ ? "Shrink Voice Mode window"+ : "Expand Voice Mode window"+ }+ onClick={() => choosePreset(large ? "compact" : "expanded")}+ size="compactIcon"+ tone="ghost"+ >+ {large ? (+ <Icon icon={Minimize01Icon} size={14} />+ ) : (+ <Icon icon={Maximize01Icon} size={14} />+ )}+ </Button>+ )}+ {/* The floating window's own close button ends Voice Mode there. */}+ {pip ? null : (+ <Button+ aria-label="End Voice Mode"+ onClick={onExit}+ size="compactIcon"+ tone="ghost"+ >+ <Icon icon={Cancel01Icon} size={16} />+ </Button>+ )}+ </span>+ </header>+ <div+ aria-label="Voice Mode conversation"+ aria-live="polite"+ className="workspace-scrollbar min-h-24 flex-1 space-y-2 overflow-y-auto px-3 py-3"+ onScroll={(event) => {+ const element = event.currentTarget;+ followRef.current =+ element.scrollHeight - element.scrollTop - element.clientHeight <+ 24;+ }}+ ref={scrollRef}+ role="log"+ >+ {(transcript ? transcript.length : turns.length || replying.length) ||+ live ? null : (+ <p className="py-4 text-center text-xs text-app-muted">+ Start speaking. Your words and replies appear here.+ </p>)}- </span>- </header>- <div- aria-label="Voice Mode conversation"- aria-live="polite"- className="workspace-scrollbar min-h-24 flex-1 space-y-2 overflow-y-auto px-3 py-3"- onScroll={(event) => {- const element = event.currentTarget;- followRef.current =- element.scrollHeight - element.scrollTop - element.clientHeight <- 24;- }}- ref={scrollRef}- role="log"- >- {(transcript ? transcript.length : turns.length || replying.length) ||- live ? null : (- <p className="py-4 text-center text-xs text-app-muted">- Start speaking. Your words and replies appear here.- </p>- )}- {transcript ? (- transcript.map((line) => (- <Bubble- agent={line.speaker !== "you"}- author={- line.speaker === "you"- ? "You"- : session.target.recipient?.display_name || "Reply"- }- key={line.id}- own={line.speaker === "you"}- pending={line.pending}- text={line.text}- />- ))- ) : (- <>- {turns.map((message) => (+ {transcript ? (+ transcript.map((line) => (<Bubble- agent={message.author.kind === "agent"}- author={message.author.display_name}- key={message.id}- own={- currentActorId- ? message.author.id === currentActorId- : message.author.kind === "human"+ agent={line.speaker !== "you"}+ author={+ line.speaker === "you"+ ? "You"+ : session.target.recipient?.display_name || "Reply"}- text={message.raw_message}- />- ))}- {replying.map((run) => (- <Bubble- agent- author={run.agent.display_name}- key={run.id}- own={false}- pending- text="Working…"+ key={line.id}+ own={line.speaker === "you"}+ pending={line.pending}+ text={line.text}/>- ))}- {heard ? <Bubble author="You" own pending text={heard} /> : null}- </>- )}- {saying ? <Bubble author="You" own pending text={saying} /> : null}+ ))+ ) : (+ <>+ {turns.map((message) => (+ <Bubble+ agent={message.author.kind === "agent"}+ author={message.author.display_name}+ key={message.id}+ own={+ currentActorId+ ? message.author.id === currentActorId+ : message.author.kind === "human"+ }+ text={message.raw_message}+ />+ ))}+ {replying.map((run) => (+ <Bubble+ agent+ author={run.agent.display_name}+ key={run.id}+ own={false}+ pending+ text="Working…"+ />+ ))}+ {heard ? <Bubble author="You" own pending text={heard} /> : null}+ </>+ )}+ {saying ? <Bubble author="You" own pending text={saying} /> : null}+ </div>+ {notice ? (+ <p+ className="shrink-0 truncate border-t border-app-border px-3 py-1.5 text-[12px] text-app-muted"+ role="status"+ >+ {notice}+ </p>+ ) : null}+ {pendingMaterials ? (+ <p className="shrink-0 truncate border-t border-app-border px-3 py-1.5 text-[12px] text-app-muted">+ Next turn includes {pendingMaterials} selection+ {pendingMaterials === 1 ? "" : "s"}+ </p>+ ) : null}</div>- {notice ? (- <p- className="shrink-0 truncate border-t border-app-border px-3 py-1.5 text-[12px] text-app-muted"- role="status"- >- {notice}- </p>- ) : null}- {pendingMaterials ? (- <p className="shrink-0 truncate border-t border-app-border px-3 py-1.5 text-[12px] text-app-muted">- Next turn includes {pendingMaterials} selection- {pendingMaterials === 1 ? "" : "s"}- </p>- ) : null}+ {pip ? null : (+ <VoiceWindowResizeHandles+ bounds={viewportBounds}+ label="Resize Voice Mode window"+ min={minWindowSize}+ onResize={({ left, top, ...next }) => {+ setResized(next);+ moveTo({ left, top });+ }}+ onResizeEnd={remember}+ rect={() => frameRef.current?.getBoundingClientRect()}+ />+ )}</section>,pip?.document.body ?? document.body,);@@ -535,23 +581,35 @@ export function sessionMessages(.sort((left, right) => left.created_at.localeCompare(right.created_at));}-/** Header drag, clamped to the viewport and remembered per browser. */-function useDraggablePosition(width: number) {+/** Where the window is: header drag, kept whole inside the viewport and+ * remembered per browser. `width` is the width the window is going to, which+ * a preset eases into; its height follows its content, so it is measured. */+function useDraggablePosition(+ width: number,+ frame: RefObject<HTMLElement | null>,+ inPage: boolean,+) {const [position, setPosition] = useState<Position>(() =>- clampPosition(readPosition() ?? defaultPosition(width), width),+ clampPosition(readPosition() ?? defaultPosition(width), { width }),);const latest = useRef(position);useLayoutEffect(() => {latest.current = position;});- // Growing the window or shrinking the viewport keeps it fully on screen.- useEffect(() => {- const keepVisible = () =>- setPosition((current) => clampPosition(current, width));- keepVisible();- window.addEventListener("resize", keepVisible);- return () => window.removeEventListener("resize", keepVisible);- }, [width]);+ const contained = (next: Position) =>+ clampPosition(next, { height: frame.current?.offsetHeight, width });+ // Growing the window or shrinking the viewport keeps all of it on screen.+ // A floated window is not in the page, so its size says nothing here.+ useKeptInViewport(+ frame,+ position,+ setPosition,+ viewportBounds,+ inPage,+ width,+ );+ /** Stores where the window is now for the next session. */+ const remember = () => writePosition(latest.current);// Window listeners follow the pointer even when it leaves the header, and a// small threshold keeps a plain click on the title a click.const dragged = useRef(false);@@ -573,17 +631,17 @@ function useDraggablePosition(width: number) {dragged.current = true;next.preventDefault();setPosition(- clampPosition(- { left: next.clientX - offset.dx, top: next.clientY - offset.dy },- width,- ),+ contained({+ left: next.clientX - offset.dx,+ top: next.clientY - offset.dy,+ }),);};const end = () => {window.removeEventListener("pointermove", move);window.removeEventListener("pointerup", end);window.removeEventListener("pointercancel", end);- if (dragged.current) writePosition(latest.current);+ if (dragged.current) remember();};window.addEventListener("pointermove", move);window.addEventListener("pointerup", end);@@ -598,32 +656,50 @@ function useDraggablePosition(width: number) {};/** Moves the window to one side at its current height, as a drag would. */const place = (side: "left" | "right") => {- const next = clampPosition(- {- left: side === "left" ? windowGap : window.innerWidth,- top: latest.current.top,- },- width,- );+ const next = contained({+ left: side === "left" ? windowGap : window.innerWidth,+ top: latest.current.top,+ });setPosition(next);writePosition(next);};- return { consumeDrag, dragHandlers, place, position };+ return {+ consumeDrag,+ dragHandlers,+ moveTo: setPosition,+ place,+ position,+ remember,+ };}function defaultPosition(width: number): Position {return { left: window.innerWidth - width - windowGap, top: 72 };}+/** The position moved no further than keeps the whole window 16px inside the+ * viewport. Its height is known once it is in the page. */export function clampPosition(- { left, top }: Position,- width: number = windowSizes.compact.width,+ position: Position,+ {+ height = 0,+ width = windowSizes.compact.width,+ }: { height?: number; width?: number } = {},): Position {- const maxLeft = Math.max(windowGap, window.innerWidth - width - windowGap);- const maxTop = Math.max(windowGap, window.innerHeight - 120);+ return containedVoiceWindowPosition(+ position,+ { height, width },+ viewportBounds(),+ );+}++/** The part of the viewport the in-page window may cover. */+function viewportBounds(): VoiceWindowBounds {return {- left: Math.min(Math.max(windowGap, left), maxLeft),- top: Math.min(Math.max(windowGap, top), maxTop),+ bottom: window.innerHeight - windowGap,+ left: windowGap,+ right: window.innerWidth - windowGap,+ top: windowGap,};}diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.tsindex 764ec38c..b06357ec 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.ts+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.ts@@ -3,13 +3,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { defineGlobalProperty } from "@/test/global-properties";import {- canShowDesktopMainWindow,closeVoicePip,onVoicePipClosedByHuman,openVoicePip,resetVoicePipForTest,returnedToOpener,- showDesktopMainWindow,+ returnVoicePipToPage,voicePipSupported,} from "./voice-pip";@@ -35,6 +34,31 @@ function installFakeVoicePip() {return { document, frame, pipWindow, requestWindow };}+/** A stand-in for the desktop app's bridge and the window it lets the page open. */+function installFakeDesktopVoiceWindow() {+ const frame = window.document.createElement("iframe");+ window.document.body.append(frame);+ const document = frame.contentDocument!;+ const listeners: (() => void)[] = [];+ const voiceWindow = {+ document,+ addEventListener: (type: string, listener: () => void) => {+ if (type === "pagehide") listeners.push(listener);+ },+ close: vi.fn(() => listeners.splice(0).forEach((listener) => listener())),+ };+ const open = vi.fn(+ (_url?: string, _target?: string, _features?: string) =>+ voiceWindow as unknown as Window,+ );+ const showMain = vi.fn(async () => {});+ defineGlobalProperty(window, "open", { value: open });+ defineGlobalProperty(window, "lingerDesktop", {+ value: { voiceWindow: { showMainWindow: showMain } },+ });+ return { document, open, showMain, voiceWindow };+}+function removeFakeVoicePip() {document.querySelectorAll("iframe").forEach((frame) => frame.remove());Reflect.deleteProperty(window, "documentPictureInPicture");@@ -47,6 +71,8 @@ afterEach(() => {node.remove();});document.documentElement.removeAttribute("data-theme");+ document.documentElement.removeAttribute("data-desktop-shell");+ document.documentElement.removeAttribute("data-desktop-chrome");});describe("Voice Mode picture-in-picture window", () => {@@ -54,67 +80,132 @@ describe("Voice Mode picture-in-picture window", () => {await expect(openVoicePip("voice-mode")).resolves.toBeUndefined();});- it("stays in the page inside a desktop app that cannot float it", async () => {+ it("stays in the page inside a desktop app that offers no voice window", async () => {const fake = installFakeVoicePip();+ const open = vi.fn();+ defineGlobalProperty(window, "open", { value: open });const desktop = window as { lingerDesktop?: unknown };- desktop.lingerDesktop = {};- try {- expect(voicePipSupported()).toBe(false);- await expect(openVoicePip("voice-mode")).resolves.toBeUndefined();- expect(fake.requestWindow).not.toHaveBeenCalled();- } finally {- delete desktop.lingerDesktop;+ for (const bridge of [{}, { voiceWindow: {} }]) {+ desktop.lingerDesktop = bridge;+ try {+ expect(voicePipSupported()).toBe(false);+ await expect(openVoicePip("voice-mode")).resolves.toBeUndefined();+ expect(fake.requestWindow).not.toHaveBeenCalled();+ expect(open).not.toHaveBeenCalled();+ } finally {+ delete desktop.lingerDesktop;+ }}});- it("opens the desktop app's own window when its preload offers one", async () => {- // Electron exposes the browser API too but cannot open its window.- const fake = installFakeVoicePip();- const showMainWindow = vi.fn(async () => {});- const desktop = window as { lingerDesktop?: unknown };- desktop.lingerDesktop = { voiceWindow: { showMainWindow } };- const open = vi- .spyOn(window, "open")- .mockReturnValue(fake.pipWindow as unknown as Window);+ it("floats in the desktop app's own window where the app offers one", async () => {+ const browser = installFakeVoicePip();+ const fake = installFakeDesktopVoiceWindow();+ document.documentElement.setAttribute("data-desktop-shell", "");+ document.documentElement.setAttribute("data-desktop-chrome", "inset");+ expect(voicePipSupported()).toBe(true);++ await expect(openVoicePip("voice-mode")).resolves.toBe(fake.voiceWindow);+ expect(fake.open).toHaveBeenCalledOnce();+ expect(fake.open).toHaveBeenCalledWith(+ "",+ expect.stringMatching(/^linger-voice-window-\d+$/),+ "popup=yes,width=320,height=240",+ );+ expect(browser.requestWindow).not.toHaveBeenCalled();+ expect(fake.document.title).toBe("Voice Mode");+ // The window has a title bar of its own, so it leaves no room for the+ // main window's controls.+ const root = fake.document.documentElement;+ expect(root.hasAttribute("data-desktop-shell")).toBe(true);+ expect(root.hasAttribute("data-desktop-chrome")).toBe(false);++ await openVoicePip("recording");+ expect(fake.open).toHaveBeenLastCalledWith(+ "",+ expect.stringMatching(/^linger-voice-window-\d+$/),+ "popup=yes,width=420,height=720",+ );+ // A window still closing is never reused under the same name.+ expect(fake.open.mock.calls[0]?.[1]).not.toBe(fake.open.mock.calls[1]?.[1]);+ expect(fake.document.title).toBe("Meeting");+ });++ it("stays in the page when the desktop app refuses the window", async () => {+ const fake = installFakeDesktopVoiceWindow();+ fake.open.mockReturnValueOnce(null as unknown as Window);+ await expect(openVoicePip("voice-mode")).resolves.toBeUndefined();+ });++ it("returns from the desktop app's window only by its return button", async () => {+ const fake = installFakeDesktopVoiceWindow();+ const closedByHuman = vi.fn();+ const stop = onVoicePipClosedByHuman("voice-mode", closedByHuman);+ // No timing guess: the answer is there at once and no visibility change+ // of the page alters it.+ vi.useFakeTimers();try {- expect(voicePipSupported()).toBe(true);- expect(canShowDesktopMainWindow()).toBe(true);- await expect(openVoicePip("recording")).resolves.toBe(fake.pipWindow);- expect(fake.requestWindow).not.toHaveBeenCalled();- expect(open).toHaveBeenCalledWith(- "",- expect.stringMatching(/^linger-voice-window-\d+$/),- "popup=yes,width=420,height=720",- );- showDesktopMainWindow();- expect(showMainWindow).toHaveBeenCalledOnce();-- const closed = vi.fn();- onVoicePipClosedByHuman("recording", closed);- fake.pipWindow.close();- expect(closed).toHaveBeenCalledOnce();+ await openVoicePip("voice-mode");+ returnVoicePipToPage("recording");+ expect(fake.voiceWindow.close).not.toHaveBeenCalled();+ returnVoicePipToPage("voice-mode");+ expect(fake.showMain).toHaveBeenCalledOnce();+ expect(fake.voiceWindow.close).toHaveBeenCalledOnce();+ expect(closedByHuman).toHaveBeenCalledOnce();+ await expect(returnedToOpener()).resolves.toBe(true);++ // The window's close button, with the main window coming to the front+ // at that moment, is still a close.+ await openVoicePip("voice-mode");+ fake.voiceWindow.close();+ document.dispatchEvent(new Event("visibilitychange"));+ expect(closedByHuman).toHaveBeenCalledTimes(2);+ await expect(returnedToOpener()).resolves.toBe(false);+ expect(fake.showMain).toHaveBeenCalledOnce();} finally {- open.mockRestore();- delete desktop.lingerDesktop;+ vi.useRealTimers();+ stop();}});- it("stays in the page when the desktop app refuses the window", async () => {- const desktop = window as { lingerDesktop?: unknown };- desktop.lingerDesktop = {- voiceWindow: { showMainWindow: vi.fn(async () => {}) },- };- const open = vi.spyOn(window, "open").mockReturnValue(null);+ it("returns from the browser's window by the return button, bringing its tab to the front", async () => {+ const fake = installFakeVoicePip();+ const focus = vi.spyOn(window, "focus").mockImplementation(() => {});+ const closedByHuman = vi.fn();+ const stop = onVoicePipClosedByHuman("recording", closedByHuman);try {- await expect(openVoicePip("voice-mode")).resolves.toBeUndefined();+ await openVoicePip("recording");+ returnVoicePipToPage("voice-mode");+ expect(focus).not.toHaveBeenCalled();+ returnVoicePipToPage("recording");+ expect(focus).toHaveBeenCalledOnce();+ expect(fake.pipWindow.close).toHaveBeenCalledOnce();+ expect(closedByHuman).toHaveBeenCalledOnce();+ // The button says it returned; nothing waits on the page's visibility.+ vi.useFakeTimers();+ await expect(returnedToOpener()).resolves.toBe(true);+ vi.useRealTimers();++ // The browser's own close button is still judged by whether the page+ // came to the front.+ await openVoicePip("recording");+ fake.pipWindow.close();+ await expect(returnedToOpener(20)).resolves.toBe(false);+ expect(focus).toHaveBeenCalledOnce();} finally {- open.mockRestore();- delete desktop.lingerDesktop;+ vi.useRealTimers();+ focus.mockRestore();+ stop();}});- it("offers no way back to the main window outside the desktop app", () => {- expect(canShowDesktopMainWindow()).toBe(false);+ it("returns the call to the page even if the main window cannot be shown", async () => {+ const fake = installFakeDesktopVoiceWindow();+ fake.showMain.mockRejectedValueOnce(new Error("no window"));+ await openVoicePip("voice-mode");+ returnVoicePipToPage("voice-mode");+ expect(fake.voiceWindow.close).toHaveBeenCalledOnce();+ await expect(returnedToOpener()).resolves.toBe(true);});it("carries the page's styles and theme, including later ones", async () => {diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-pip.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-pip.tsindex 996f8f1c..2fb1fa42 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-pip.ts+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-pip.ts@@ -11,6 +11,27 @@ interface DocumentPictureInPicture {}): Promise<Window>;}+/**+ * The desktop app's floating window (`window.lingerDesktop.voiceWindow`): the+ * page opens a blank window under `desktopWindowTarget` and the app keeps it+ * on top, also while its main window is minimized or closed to the tray.+ */+interface DesktopVoiceWindow {+ showMainWindow(): Promise<void>;+}++/**+ * The window name the desktop app recognizes; it floats the window opened+ * under it. The suffix keeps a window that is still closing from being reused.+ */+const desktopWindowTarget = "linger-voice-window";+let desktopWindowCount = 0;++interface PipSize {+ height: number;+ width: number;+}+/** Voice Mode and Recording never run together; each asks for its own window. */export type VoicePipOwner = "voice-mode" | "recording";@@ -19,7 +40,13 @@ export type VoicePipOwner = "voice-mode" | "recording";const pipSizes = {"voice-mode": { height: 240, width: 320 },recording: { height: 720, width: 420 },-} satisfies Record<VoicePipOwner, { height: number; width: number }>;+} satisfies Record<VoicePipOwner, PipSize>;++// What the desktop shows as the window's name; browsers show the site instead.+const pipTitles = {+ "voice-mode": "Voice Mode",+ recording: "Meeting",+} satisfies Record<VoicePipOwner, string>;let pip: { owner: VoicePipOwner; window: Window } | undefined;const listeners = new Set<() => void>();@@ -27,72 +54,56 @@ const closedByHuman = new Set<(owner: VoicePipOwner) => void>();/** When this page last came to the front from the background. */let shownAt = Number.NEGATIVE_INFINITY;let watchingVisibility = false;+/** Set while the voice window's return button closes the floating window. */+let returning = false;+/** How the floating window last closed, when that is known for sure. */+let returnedByButton: boolean | undefined;function noteShown() {if (document.visibilityState === "visible") shownAt = performance.now();}-/**- * The window name the desktop app recognizes; it floats the window opened- * under it. The suffix keeps a window that is still closing from being reused.- */-const desktopWindowTarget = "linger-voice-window";-let desktopWindowCount = 0;--/** The desktop app's own window, standing in for the missing picture-in-picture. */-const desktopVoiceWindow: DocumentPictureInPicture = {- async requestWindow({ height, width } = {}) {- const opened = window.open(- "",- `${desktopWindowTarget}-${++desktopWindowCount}`,- `popup=yes,width=${width ?? 320},height=${height ?? 240}`,- );- if (!opened) throw new Error("The desktop app refused the voice window.");- return opened;- },-};--/** Set when the desktop app can open the floating window and bring the main one back. */-interface DesktopVoiceWindow {- showMainWindow(): Promise<void>;-}--function desktopBridge(): DesktopVoiceWindow | undefined {- return (+function desktopVoiceWindow(): DesktopVoiceWindow | undefined {+ const voiceWindow = (window as Window & {- lingerDesktop?: { voiceWindow?: DesktopVoiceWindow };+ lingerDesktop?: { voiceWindow?: Partial<DesktopVoiceWindow> };}).lingerDesktop?.voiceWindow;+ return typeof voiceWindow?.showMainWindow === "function"+ ? (voiceWindow as DesktopVoiceWindow)+ : undefined;}-/**- * Whether the floating window is the desktop app's, whose main window can be- * brought back from it. The browser's window has its own back to tab button.- */-export function canShowDesktopMainWindow() {- return desktopBridge() !== undefined;-}--/** Brings the desktop app's main window to the front; the call keeps running. */-export function showDesktopMainWindow() {- void desktopBridge()- ?.showMainWindow()- .catch(() => undefined);-}--function api(): DocumentPictureInPicture | undefined {- // The desktop app cannot open Document Picture-in-Picture windows, so it- // opens its own when its preload says it can; an older app without that- // keeps the voice windows in the page.- if (isDesktopShell()) return desktopBridge() ? desktopVoiceWindow : undefined;- return (+/** How this client opens the floating window, if it can. */+function floatingWindowOpener():+ | ((+ size: PipSize & { preferInitialWindowPlacement: boolean },+ ) => Promise<Window | null>)+ | undefined {+ if (desktopVoiceWindow())+ return ({ height, width }) =>+ Promise.resolve(+ window.open(+ "",+ `${desktopWindowTarget}-${++desktopWindowCount}`,+ `popup=yes,width=${width},height=${height}`,+ ),+ );+ // A desktop app without that window exposes the browser API but cannot open+ // its window, so there voice windows stay in the page and offer no float+ // button.+ if (isDesktopShell()) return undefined;+ const pictureInPicture = (window as Window & { documentPictureInPicture?: DocumentPictureInPicture }).documentPictureInPicture;+ return pictureInPicture+ ? (size) => pictureInPicture.requestWindow(size)+ : undefined;}-/** Whether this browser can float a voice window over other tabs and apps. */+/** Whether this client can float a voice window over other windows and apps. */export function voicePipSupported() {- return api() !== undefined;+ return floatingWindowOpener() !== undefined;}function publish(next: typeof pip) {@@ -104,7 +115,7 @@ function publish(next: typeof pip) {* Opens the always-on-top window a voice window moves into, so it stays* visible over other tabs and apps and can be dragged anywhere on the desktop.* The browser allows this only inside a click, so call it synchronously from- * the click handler. Resolves undefined when the browser refuses.+ * the click handler. Resolves undefined when the client refuses.*/export async function openVoicePip(owner: VoicePipOwner,@@ -112,26 +123,35 @@ export async function openVoicePip(preferInitialWindowPlacement = false,}: { preferInitialWindowPlacement?: boolean } = {},): Promise<Window | undefined> {- const pictureInPicture = api();- if (!pictureInPicture) return undefined;- // The browser allows one such window per tab; the newest owner takes it.+ const open = floatingWindowOpener();+ if (!open) return undefined;+ // A page gets one such window; the newest owner takes it.if (pip?.owner === owner) return pip.window;if (pip) closeVoicePip(pip.owner);if (!watchingVisibility) {document.addEventListener("visibilitychange", noteShown);watchingVisibility = true;}+ // The desktop app's window has no back to tab button, so there every close+ // that is not the return button is a close.+ const closesOnly = desktopVoiceWindow() !== undefined;try {- const opened = await pictureInPicture.requestWindow({+ const opened = await open({...pipSizes[owner],preferInitialWindowPlacement,});+ if (!opened) return undefined;+ returning = false;+ returnedByButton = undefined;+ opened.document.title = pipTitles[owner];const stopMirroring = mirrorStyles(opened.document);opened.addEventListener("pagehide", () => {stopMirroring();if (pip?.window !== opened) return;- // Closed from the window's own close button rather than from the page.+ // Closed from the window itself rather than from the page.publish(undefined);+ if (returning || closesOnly) returnedByButton = returning;+ returning = false;for (const listener of closedByHuman) listener(owner);});publish({ owner, window: opened });@@ -149,12 +169,29 @@ export function closeVoicePip(owner: VoicePipOwner) {}/**- * Whether closing the window brought the Human back to this page. The- * window's "back to tab" button closes it and brings its tab from the+ * The voice window's own return button: brings the desktop app's main window,+ * or this browser tab, to the front and closes the floating window, which its+ * owner then reads as a return through `returnedToOpener`. Call it from the+ * click; a browser lets a page come to the front only then.+ */+export function returnVoicePipToPage(owner: VoicePipOwner) {+ if (pip?.owner !== owner) return;+ returning = true;+ const desktop = desktopVoiceWindow();+ // The call still moves into the page if the main window cannot be shown.+ if (desktop) void desktop.showMainWindow().catch(() => undefined);+ else window.focus();+ pip.window.close();+}++/**+ * Whether closing the window brought the Human back to this page. The voice+ * window's own return button says so itself. A browser's window also has a+ * "back to tab" button, which closes it and brings its tab from the* background to the front; its close button does not. The browser reports- * neither, so this checks a moment later whether the page came to the front- * around the close. A close while this page was already in front is a close,- * even though focus lands on the page afterwards.+ * neither, so for those this checks a moment later whether the page came to+ * the front around the close. A close while this page was already in front is+ * a close, even though focus lands on the page afterwards.** Trade-off: back to tab on a page that stayed visible but unfocused (its* window on another screen, or only partly covered, while the Human works in@@ -162,8 +199,17 @@ export function closeVoicePip(owner: VoicePipOwner) {* call ends. Telling it apart by focus instead made the close button keep the* call whenever the page was in front; a close that ends the call is the* surer of the two, and starting Voice Mode again floats a new window.+ *+ * The desktop app's window needs no such guess: it has no back to tab button,+ * so only the voice window's return button returns and every other close is a+ * close.*/export function returnedToOpener(waitMs = 300): Promise<boolean> {+ if (returnedByButton !== undefined) {+ const returned = returnedByButton;+ returnedByButton = undefined;+ return Promise.resolve(returned);+ }const closedAt = performance.now();return new Promise((resolve) =>setTimeout(@@ -177,7 +223,7 @@ export function returnedToOpener(waitMs = 300): Promise<boolean> {);}-/** Runs when the Human closes this owner's window with the desktop's button. */+/** Runs when this owner's window closes from the window, not from the page. */export function onVoicePipClosedByHuman(owner: VoicePipOwner,listener: () => void,@@ -209,8 +255,11 @@ export function useVoicePip(owner: VoicePipOwner) {*/function mirrorStyles(target: Document) {const root = document.documentElement;+ // The floating window has a title bar of its own, so it takes no room for+ // window controls the way the desktop app's main window does on macOS.for (const { name, value } of Array.from(root.attributes))- target.documentElement.setAttribute(name, value);+ if (name !== "data-desktop-chrome")+ target.documentElement.setAttribute(name, value);const copy = (node: Node) => {if (node instanceof HTMLStyleElement ||@@ -232,4 +281,6 @@ export function resetVoicePipForTest() {listeners.clear();closedByHuman.clear();shownAt = Number.NEGATIVE_INFINITY;+ returning = false;+ returnedByButton = undefined;}diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-window-resize.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-window-resize.test.tsnew file mode 100644index 00000000..8010067a--- /dev/null+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-window-resize.test.ts@@ -0,0 +1,187 @@+// @vitest-environment jsdom+import { act, renderHook } from "@testing-library/react";+import { useState } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import {+ containedVoiceWindowPosition,+ resizedVoiceWindowRect,+ useKeptInViewport,+} from "./voice-window-resize";++const min = { height: 100, width: 200 };+const bounds = { bottom: 700, left: 10, right: 1000, top: 20 };+const start = { height: 300, left: 400, top: 200, width: 320 };++describe("resizing a voice window in the page", () => {+ it("moves only the dragged edges", () => {+ expect(resizedVoiceWindowRect(start, "e", 50, 999, min, bounds)).toEqual({+ ...start,+ width: 370,+ });+ expect(resizedVoiceWindowRect(start, "n", 999, -50, min, bounds)).toEqual({+ ...start,+ height: 350,+ top: 150,+ });+ expect(resizedVoiceWindowRect(start, "sw", -40, 60, min, bounds)).toEqual({+ height: 360,+ left: 360,+ top: 200,+ width: 360,+ });+ });++ it("stops at the minimum size and at the bounds", () => {+ expect(resizedVoiceWindowRect(start, "nw", 999, 999, min, bounds)).toEqual({+ height: 100,+ left: 520,+ top: 400,+ width: 200,+ });+ expect(+ resizedVoiceWindowRect(start, "nw", -999, -999, min, bounds),+ ).toEqual({ height: 480, left: 10, top: 20, width: 710 });+ expect(resizedVoiceWindowRect(start, "se", 999, 999, min, bounds)).toEqual({+ height: 500,+ left: 400,+ top: 200,+ width: 600,+ });+ });++ it("never pushes a window that is already too small or outside further", () => {+ // Narrower than the minimum, as in a narrow viewport: it may grow, and+ // shrinking leaves it as it is.+ const narrow = { ...start, width: 150 };+ expect(resizedVoiceWindowRect(narrow, "e", -80, 0, min, bounds)).toEqual(+ narrow,+ );+ // Hanging past the bottom of the page: the bottom edge can come back up+ // but goes no further down.+ const low = { ...start, top: 600 };+ expect(resizedVoiceWindowRect(low, "s", 80, 80, min, bounds)).toEqual(low);+ expect(resizedVoiceWindowRect(low, "s", 0, -80, min, bounds)).toEqual({+ ...low,+ height: 220,+ });+ });+});++describe("moving a voice window in the page", () => {+ const size = { height: 300, width: 320 };++ it("leaves a window that is inside the bounds where it is", () => {+ expect(+ containedVoiceWindowPosition({ left: 400, top: 200 }, size, bounds),+ ).toEqual({ left: 400, top: 200 });+ });++ it("stops the whole window at each side of the bounds", () => {+ expect(+ containedVoiceWindowPosition({ left: -50, top: -50 }, size, bounds),+ ).toEqual({ left: 10, top: 20 });+ expect(+ containedVoiceWindowPosition({ left: 9999, top: 9999 }, size, bounds),+ ).toEqual({ left: 1000 - 320, top: 700 - 300 });+ });++ it("keeps the top left of a window larger than the bounds in view", () => {+ expect(+ containedVoiceWindowPosition(+ { left: 400, top: 200 },+ { height: 900, width: 1200 },+ bounds,+ ),+ ).toEqual({ left: 10, top: 20 });+ });+});++describe("keeping a voice window in the viewport", () => {+ let observed: (() => void)[];+ let size: { height: number; width: number };+ const frame = () => {+ const element = document.createElement("div");+ Object.defineProperties(element, {+ offsetHeight: { get: () => size.height },+ offsetWidth: { get: () => size.width },+ });+ return { current: element };+ };+ const viewport = () => ({+ bottom: window.innerHeight,+ left: 0,+ right: window.innerWidth,+ top: 0,+ });+ const shrinkViewport = (width: number, height: number) => {+ vi.stubGlobal("innerWidth", width);+ vi.stubGlobal("innerHeight", height);+ act(() => {+ window.dispatchEvent(new Event("resize"));+ });+ };+ const render = (+ start: { left: number; top: number } | undefined,+ options: { enabled?: boolean; width?: number } = {},+ ) => {+ const ref = frame();+ return renderHook(() => {+ const [position, setPosition] = useState(start);+ useKeptInViewport(+ ref,+ position,+ setPosition,+ viewport,+ options.enabled ?? true,+ options.width,+ );+ return position;+ });+ };++ beforeEach(() => {+ observed = [];+ size = { height: 200, width: 200 };+ vi.stubGlobal("innerWidth", 1000);+ vi.stubGlobal("innerHeight", 800);+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: () => void) {+ observed.push(callback);+ }+ observe() {}+ disconnect() {}+ },+ );+ });++ it("moves the window back in when it grows or the viewport shrinks", () => {+ const { result } = render({ left: 700, top: 500 });+ expect(result.current).toEqual({ left: 700, top: 500 });++ size = { height: 400, width: 200 };+ act(() => observed.forEach((callback) => callback()));+ expect(result.current).toEqual({ left: 700, top: 400 });++ shrinkViewport(800, 700);+ expect(result.current).toEqual({ left: 600, top: 300 });+ });++ it("keeps a window easing into a new width in by that width", () => {+ const { result } = render({ left: 700, top: 0 }, { width: 400 });+ expect(result.current).toEqual({ left: 600, top: 0 });+ });++ it("leaves the window alone while disabled, unplaced or gone", () => {+ const disabled = render({ left: 700, top: 500 }, { enabled: false });+ const unplaced = render(undefined);+ const gone = render({ left: 700, top: 500 });+ gone.unmount();+ shrinkViewport(500, 400);+ expect(disabled.result.current).toEqual({ left: 700, top: 500 });+ expect(unplaced.result.current).toBeUndefined();+ expect(observed).toHaveLength(2);+ });+});diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-window-resize.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-window-resize.tsxnew file mode 100644index 00000000..12c065b6--- /dev/null+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-window-resize.tsx@@ -0,0 +1,287 @@+import {+ useLayoutEffect,+ useRef,+ type PointerEvent,+ type RefObject,+} from "react";++/** A voice window inside the page, in viewport pixels. */+export interface VoiceWindowRect {+ height: number;+ left: number;+ top: number;+ width: number;+}++/** The part of the viewport a voice window may cover. */+export interface VoiceWindowBounds {+ bottom: number;+ left: number;+ right: number;+ top: number;+}++interface MinSize {+ height: number;+ width: number;+}++export type VoiceWindowEdge = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw";++const allEdges: readonly VoiceWindowEdge[] = [+ "n",+ "s",+ "e",+ "w",+ "ne",+ "nw",+ "se",+ "sw",+];++// Each handle straddles the window's border, mostly outside it, so it does+// not cover a scrollbar or a control at the edge.+const handleClasses = {+ n: "inset-x-2 -top-1.5 h-2.5 cursor-ns-resize",+ s: "inset-x-2 -bottom-1.5 h-2.5 cursor-ns-resize",+ e: "inset-y-2 -right-1.5 w-2.5 cursor-ew-resize",+ w: "inset-y-2 -left-1.5 w-2.5 cursor-ew-resize",+ ne: "-top-1.5 -right-1.5 size-4 cursor-nesw-resize",+ nw: "-top-1.5 -left-1.5 size-4 cursor-nwse-resize",+ sw: "-bottom-1.5 -left-1.5 size-4 cursor-nesw-resize",+} satisfies Record<Exclude<VoiceWindowEdge, "se">, string>;++/**+ * Where the window is after `edge` moved by (dx, dy): the opposite edge stays+ * put, the window keeps at least `min` and stays inside `bounds`. A window+ * that already is smaller than `min` or reaches past `bounds` is never pushed+ * further that way.+ */+export function resizedVoiceWindowRect(+ start: VoiceWindowRect,+ edge: VoiceWindowEdge,+ dx: number,+ dy: number,+ min: MinSize,+ bounds: VoiceWindowBounds,+): VoiceWindowRect {+ let { left, top } = start;+ let right = start.left + start.width;+ let bottom = start.top + start.height;+ const minWidth = Math.min(min.width, start.width);+ const minHeight = Math.min(min.height, start.height);+ if (edge.includes("e"))+ right = Math.max(+ left + minWidth,+ Math.min(right + dx, Math.max(bounds.right, right)),+ );+ if (edge.includes("w"))+ left = Math.min(+ right - minWidth,+ Math.max(left + dx, Math.min(bounds.left, left)),+ );+ if (edge.includes("s"))+ bottom = Math.max(+ top + minHeight,+ Math.min(bottom + dy, Math.max(bounds.bottom, bottom)),+ );+ if (edge.includes("n"))+ top = Math.min(+ bottom - minHeight,+ Math.max(top + dy, Math.min(bounds.top, top)),+ );+ return { height: bottom - top, left, top, width: right - left };+}++/**+ * Where a window of `size` sits when it is moved to (left, top): no further+ * than keeps all of it inside `bounds`. A window larger than the bounds+ * starts at their top left, which keeps its header in view.+ */+export function containedVoiceWindowPosition(+ { left, top }: Pick<VoiceWindowRect, "left" | "top">,+ size: Pick<VoiceWindowRect, "height" | "width">,+ bounds: VoiceWindowBounds,+): Pick<VoiceWindowRect, "left" | "top"> {+ return {+ left: Math.max(bounds.left, Math.min(left, bounds.right - size.width)),+ top: Math.max(bounds.top, Math.min(top, bounds.bottom - size.height)),+ };+}++/**+ * Keeps an in-page voice window whole inside `bounds` while `enabled`: when+ * the viewport shrinks or the window grows, as it does when it opens from its+ * top row, `position` moves back in through `setPosition`. The window's size+ * on screen belongs to the position on screen, not to one a drag has asked+ * for and React has yet to draw, so this works from the position last drawn.+ * `width`, when given, stands in for the measured width, so a window easing+ * into a new width is kept in by the width it is going to.+ */+export function useKeptInViewport(+ frame: RefObject<HTMLElement | null>,+ position: Pick<VoiceWindowRect, "left" | "top"> | undefined,+ setPosition: (next: Pick<VoiceWindowRect, "left" | "top">) => void,+ bounds: () => VoiceWindowBounds,+ enabled: boolean,+ width?: number,+): void {+ const drawn = useRef({ bounds, position, setPosition });+ useLayoutEffect(() => {+ drawn.current = { bounds, position, setPosition };+ });+ useLayoutEffect(() => {+ const element = frame.current;+ if (!enabled || !element) return;+ const keepVisible = () => {+ const { bounds, position, setPosition } = drawn.current;+ if (!position) return;+ const next = containedVoiceWindowPosition(+ position,+ {+ height: element.offsetHeight,+ width: width ?? element.offsetWidth,+ },+ bounds(),+ );+ if (next.left !== position.left || next.top !== position.top)+ setPosition(next);+ };+ keepVisible();+ const observer = new ResizeObserver(keepVisible);+ observer.observe(element);+ window.addEventListener("resize", keepVisible);+ return () => {+ observer.disconnect();+ window.removeEventListener("resize", keepVisible);+ };+ }, [frame, enabled, width]);+}++/**+ * The edges and corners an in-page voice window is resized by. They sit on+ * the window's border, apart from the header that moves it. The bottom right+ * corner shows a grip and takes the keyboard: arrow keys resize in steps of+ * 8px, 32px with Shift.+ */+export function VoiceWindowResizeHandles({+ bounds,+ edges = allEdges,+ label,+ min,+ onResize,+ onResizeEnd,+ rect,+}: {+ /** Read when a resize starts, so it follows the viewport's size. */+ bounds: () => VoiceWindowBounds;+ /** A window minimized to one row is only as wide as the Human drags it. */+ edges?: readonly VoiceWindowEdge[];+ /** Names the grip, such as "Resize Voice Mode window". */+ label: string;+ min: MinSize;+ onResize: (rect: VoiceWindowRect) => void;+ onResizeEnd?: () => void;+ /** The window as it is on screen now. */+ rect: () => VoiceWindowRect | undefined;+}) {+ const drag = useRef<{+ bounds: VoiceWindowBounds;+ edge: VoiceWindowEdge;+ start: VoiceWindowRect;+ x: number;+ y: number;+ }>(undefined);+ const handlers = (edge: VoiceWindowEdge) => ({+ onPointerDown(event: PointerEvent<HTMLElement>) {+ const start = rect();+ if (event.button !== 0 || !start) return;+ // Keeps the drag from selecting text in the page behind.+ event.preventDefault();+ // The pointer keeps this handle, and its cursor, wherever it goes.+ event.currentTarget.setPointerCapture?.(event.pointerId);+ drag.current = {+ bounds: bounds(),+ edge,+ start,+ x: event.clientX,+ y: event.clientY,+ };+ },+ onPointerMove(event: PointerEvent<HTMLElement>) {+ const current = drag.current;+ if (!current) return;+ onResize(+ resizedVoiceWindowRect(+ current.start,+ current.edge,+ event.clientX - current.x,+ event.clientY - current.y,+ min,+ current.bounds,+ ),+ );+ },+ onPointerUp: end,+ onPointerCancel: end,+ onLostPointerCapture: end,+ });+ function end() {+ if (!drag.current) return;+ drag.current = undefined;+ onResizeEnd?.();+ }+ return (+ <>+ {edges.map((edge) =>+ edge === "se" ? (+ <button+ aria-label={label}+ className="group absolute -right-1.5 -bottom-1.5 z-10 size-5 cursor-nwse-resize touch-none rounded-sm focus-visible:outline-none"+ data-resize-edge={edge}+ key={edge}+ onKeyDown={(event) => {+ const step = event.shiftKey ? 32 : 8;+ const [dx, dy] =+ {+ ArrowDown: [0, step],+ ArrowLeft: [-step, 0],+ ArrowRight: [step, 0],+ ArrowUp: [0, -step],+ }[event.key] ?? [];+ const start = rect();+ if (dx === undefined || dy === undefined || !start) return;+ event.preventDefault();+ onResize(+ resizedVoiceWindowRect(start, edge, dx, dy, min, bounds()),+ );+ onResizeEnd?.();+ }}+ title="Drag to resize, or use the arrow keys"+ type="button"+ {...handlers(edge)}+ >+ <svg+ aria-hidden="true"+ className="absolute right-2.5 bottom-2.5 size-2 rounded-[1px] text-app-subtle opacity-70 group-hover:text-app-ink group-hover:opacity-100 group-focus-visible:text-app-ink group-focus-visible:opacity-100 group-focus-visible:shadow-[0_0_0_2px_var(--app-ring)]"+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ viewBox="0 0 8 8"+ >+ <path d="M7.5 0.5 0.5 7.5M7.5 4 4 7.5" />+ </svg>+ </button>+ ) : (+ <div+ aria-hidden="true"+ className={`absolute z-10 touch-none ${handleClasses[edge]}`}+ data-resize-edge={edge}+ key={edge}+ {...handlers(edge)}+ />+ ),+ )}+ </>+ );+}diff --git a/apps/web/src/features/rooms/voice-control/recording-window.test.tsx b/apps/web/src/features/rooms/voice-control/recording-window.test.tsxindex 573268b6..49011d12 100644--- a/apps/web/src/features/rooms/voice-control/recording-window.test.tsx+++ b/apps/web/src/features/rooms/voice-control/recording-window.test.tsx@@ -617,38 +617,6 @@ describe("Recording window", () => {expect(voice.leavePage).not.toHaveBeenCalled();});- it("brings the desktop app's main window back from its floating window", async () => {- const { frame, pipWindow, requestWindow } = stubPictureInPicture();- const showMainWindow = vi.fn(async () => {});- const desktop = window as { lingerDesktop?: unknown };- desktop.lingerDesktop = { voiceWindow: { showMainWindow } };- const open = vi- .spyOn(window, "open")- .mockReturnValue(pipWindow as unknown as Window);- try {- renderWindow(voiceValue());- // In the page the main window is already in front.- expect(- screen.queryByRole("button", { name: "Show Linger window" }),- ).toBeNull();- await act(() => openVoicePip("recording"));- expect(requestWindow).not.toHaveBeenCalled();- const floating = within(frame.contentDocument!.body);- fireEvent.click(- floating.getByRole("button", { name: "Show Linger window" }),- );- expect(showMainWindow).toHaveBeenCalledOnce();- // The recording is untouched and its window stays.- expect(- floating.getByRole("button", { name: "Stop recording" }),- ).toBeTruthy();- expect(screen.getByTestId("window-state")).toHaveTextContent("open");- } finally {- open.mockRestore();- delete desktop.lingerDesktop;- }- });-it("opens a new Meeting at full size after stopping a minimized recording", async () => {const { frame, pipWindow, requestWindow } = stubPictureInPicture();const firstVoice = voiceValue();@@ -744,6 +712,10 @@ describe("Recording window", () => {floating.getByRole("button", { name: "Minimize recording" }),);expect(pipWindow.resizeTo).toHaveBeenCalledWith(420, 136);+ // The floating window is resized by the desktop, not by a grip.+ expect(+ floating.queryByRole("button", { name: "Resize recording window" }),+ ).toBeNull();act(() => pipWindow.close());expect(@@ -843,6 +815,186 @@ describe("Recording window", () => {}});+ it("returns from the desktop app's window by its own button, and ends when that window closes", async () => {+ const desktop = stubDesktopVoiceWindow();+ const voice = voiceValue();+ renderWindow(voice);+ await act(() => openVoicePip("recording"));+ const floating = within(desktop.frame.contentDocument!.body);+ await act(async () => {+ fireEvent.click(+ floating.getByRole("button", { name: "Return recording to Linger" }),+ );+ });+ expect(desktop.showMain).toHaveBeenCalledOnce();+ expect(desktop.pipWindow.close).toHaveBeenCalledOnce();+ // The recording goes on in the page, with no return button there.+ expect(+ await screen.findByRole("region", { name: "Recording window" }),+ ).toBeVisible();+ expect(+ screen.queryByRole("button", { name: "Return recording to Linger" }),+ ).toBeNull();+ expect(voice.leavePage).not.toHaveBeenCalled();++ await act(async () => {+ fireEvent.click(+ screen.getByRole("button", { name: "Float recording window" }),+ );+ });+ expect(desktop.open).toHaveBeenCalledTimes(2);+ expect(desktop.requestWindow).not.toHaveBeenCalled();+ await floating.findByRole("region", { name: "Recording window" });+ // The window's close button ends the recording even as the main window+ // comes to the front.+ act(() => {+ desktop.pipWindow.close();+ document.dispatchEvent(new Event("visibilitychange"));+ });+ await waitFor(() => expect(voice.leavePage).toHaveBeenCalledOnce());+ expect(desktop.showMain).toHaveBeenCalledOnce();+ });++ it("returns from the browser's floating window by its return button without stopping", async () => {+ const { frame, pipWindow } = stubPictureInPicture();+ const focus = vi.spyOn(window, "focus").mockImplementation(() => {});+ try {+ const voice = voiceValue();+ renderWindow(voice);+ await act(() => openVoicePip("recording"));+ const floating = within(frame.contentDocument!.body);+ const back = floating.getByRole("button", {+ name: "Return recording to Linger",+ });+ expect(back.title).toBe("Back to Linger; recording continues");+ await act(async () => {+ fireEvent.click(back);+ });+ // The tab comes to the front and the recording goes on in the page.+ expect(focus).toHaveBeenCalledOnce();+ expect(pipWindow.close).toHaveBeenCalledOnce();+ expect(+ await screen.findByRole("region", { name: "Recording window" }),+ ).toBeVisible();+ expect(voice.leavePage).not.toHaveBeenCalled();+ } finally {+ focus.mockRestore();+ }+ });++ it("cannot be dragged out of the page, and moves back in when it opens or the page narrows", () => {+ const observed: (() => void)[] = [];+ const resize = () => observed.forEach((callback) => callback());+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: () => void) {+ observed.push(callback);+ }+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ renderWindow(voiceValue());+ const frame = screen.getByRole("region", { name: "Recording window" });+ let height = 500;+ Object.defineProperties(frame, {+ offsetHeight: { get: () => height },+ offsetWidth: { get: () => 420 },+ });+ vi.spyOn(frame, "getBoundingClientRect").mockImplementation(+ () => new DOMRect(500, 64, 420, height),+ );+ const titleBar = screen.getByRole("button", {+ name: "Minimize recording",+ }).parentElement!;+ fireEvent.pointerDown(titleBar, { button: 0, clientX: 700, clientY: 80 });+ fireEvent.pointerMove(window, { clientX: 5000, clientY: 5000 });+ fireEvent.pointerUp(window);+ expect(frame).toHaveStyle({+ left: `${window.innerWidth - 420}px`,+ top: `${window.innerHeight - 500}px`,+ });+ fireEvent.pointerDown(titleBar, { button: 0, clientX: 700, clientY: 80 });+ fireEvent.pointerMove(window, { clientX: -5000, clientY: -5000 });+ fireEvent.pointerUp(window);+ // It stays below the top of the page.+ expect(frame).toHaveStyle({ left: "0px", top: "36px" });++ // Minimized to its top row at the bottom of the page, then opened again.+ fireEvent.click(screen.getByRole("button", { name: "Minimize recording" }));+ height = 92;+ fireEvent.pointerDown(titleBar, { button: 0, clientX: 700, clientY: 80 });+ fireEvent.pointerMove(window, { clientX: 700, clientY: 5000 });+ fireEvent.pointerUp(window);+ expect(frame).toHaveStyle({ top: `${window.innerHeight - 92}px` });+ fireEvent.click(screen.getByRole("button", { name: "Open recording" }));+ height = 500;+ act(() => resize());+ expect(frame).toHaveStyle({ top: `${window.innerHeight - 500}px` });++ // A narrower page moves it left until all of it shows again.+ expect(frame).toHaveStyle({ left: "500px" });+ vi.stubGlobal("innerWidth", 800);+ act(() => {+ window.dispatchEvent(new Event("resize"));+ });+ expect(frame).toHaveStyle({ left: `${800 - 420}px` });+ });++ it("resizes in the page by its edges and corners, and only in width while minimized", () => {+ renderWindow(voiceValue());+ const frame = screen.getByRole("region", { name: "Recording window" });+ const surface = screen.getByRole("region", {+ name: "Hardware voice focus",+ });+ // Until it is resized the window is as tall as its content needs.+ expect(frame.style.height).toBe("");+ expect(surface).not.toHaveClass("flex-1");+ const onScreen = vi+ .spyOn(frame, "getBoundingClientRect")+ .mockReturnValue(new DOMRect(500, 64, 420, 500));+ const grip = screen.getByRole("button", {+ name: "Resize recording window",+ });+ fireEvent.pointerDown(grip, { button: 0, clientX: 920, clientY: 564 });+ fireEvent.pointerMove(grip, { clientX: 1000, clientY: 664 });+ fireEvent.pointerUp(grip);+ expect(frame).toHaveStyle({ left: "500px", top: "64px" });+ expect(frame).toHaveStyle({ height: "600px", width: "500px" });+ // The surface fills the height the Human chose.+ expect(surface).toHaveClass("flex-1");++ // The top left corner stops at the minimum size and keeps the opposite+ // corner where it was.+ onScreen.mockReturnValue(new DOMRect(500, 64, 500, 600));+ const corner = frame.querySelector('[data-resize-edge="nw"]')!;+ fireEvent.pointerDown(corner, { button: 0, clientX: 500, clientY: 64 });+ fireEvent.pointerMove(corner, { clientX: 5000, clientY: 5000 });+ fireEvent.pointerUp(corner);+ expect(frame).toHaveStyle({ left: "720px", top: "384px" });+ expect(frame).toHaveStyle({ height: "280px", width: "280px" });++ // Minimized to its top row, only the sides resize it.+ fireEvent.click(screen.getByRole("button", { name: "Minimize recording" }));+ expect(+ screen.queryByRole("button", { name: "Resize recording window" }),+ ).toBeNull();+ expect(frame.querySelector('[data-resize-edge="s"]')).toBeNull();+ expect(frame.style.height).toBe("");+ onScreen.mockReturnValue(new DOMRect(720, 384, 280, 92));+ const right = frame.querySelector('[data-resize-edge="e"]')!;+ fireEvent.pointerDown(right, { button: 0, clientX: 1000, clientY: 400 });+ fireEvent.pointerMove(right, { clientX: 5000, clientY: 400 });+ fireEvent.pointerUp(right);+ expect(frame).toHaveStyle({ width: `${window.innerWidth - 720}px` });+ expect(frame.style.height).toBe("");+ // Opening it again brings back the height it had.+ fireEvent.click(screen.getByRole("button", { name: "Open recording" }));+ expect(frame).toHaveStyle({ height: "280px" });+ });+it("ignores a pending native close after a new floating window opens", async () => {vi.useFakeTimers();try {@@ -1121,6 +1273,18 @@ function stubPictureInPicture() {return { frame, pipWindow, requestWindow };}+/** The desktop app's floating window, offered next to the browser's API. */+function stubDesktopVoiceWindow() {+ const browser = stubPictureInPicture();+ const open = vi.fn(() => browser.pipWindow);+ const showMain = vi.fn(async () => {});+ defineGlobalProperty(window, "open", { value: open });+ defineGlobalProperty(window, "lingerDesktop", {+ value: { voiceWindow: { showMainWindow: showMain } },+ });+ return { ...browser, open, showMain };+}+describe("Recording window placement", () => {it("stays at the top right of a pinch-zoomed view at its usual size", () => {// Zoomed 2×, looking at the part of the page from (300, 200).diff --git a/apps/web/src/features/rooms/voice-control/recording-window.tsx b/apps/web/src/features/rooms/voice-control/recording-window.tsxindex 1574ff8c..5264b395 100644--- a/apps/web/src/features/rooms/voice-control/recording-window.tsx+++ b/apps/web/src/features/rooms/voice-control/recording-window.tsx@@ -8,15 +8,20 @@ import {import { createPortal } from "react-dom";import {- canShowDesktopMainWindow,closeVoicePip,onVoicePipClosedByHuman,openVoicePip,returnedToOpener,- showDesktopMainWindow,+ returnVoicePipToPage,useVoicePip,voicePipSupported,} from "../chat/voice-mode/voice-pip";+import {+ containedVoiceWindowPosition,+ useKeptInViewport,+ VoiceWindowResizeHandles,+ type VoiceWindowBounds,+} from "../chat/voice-mode/voice-window-resize";import {RecordingAnswers,RecordingAskBox,@@ -47,13 +52,19 @@ interface ExpandedPipSize {}// Where the window sits in the page: 16px from the right, 64px from the top.const pageInset = { right: 16, top: 64, width: 420 };+/** Still shows the recording controls, the tabs and the Ask box. */+const minPageSize = { height: 280, width: 280 };+// The in-page window stays below the top of the page.+const pageTop = 36;/*** The one place a recording is watched and controlled from, whatever page is- * behind it. Where the browser supports it the window floats over other tabs- * and apps; otherwise it floats over the page. Minimizing it leaves only its- * top row and keeps recording; Stop, or closing the open floating window, ends- * the recording. Back to tab keeps recording in the page window.+ * behind it. Where the browser or the desktop app supports it the window+ * floats over other tabs and apps; otherwise it floats over the page, where+ * its edges and corners resize it. Minimizing it leaves only its top row and+ * keeps recording; Stop, or closing the open floating window, ends the+ * recording. The floating window's return button, like the browser's back to+ * tab button, keeps recording in the page window.*/export default function RecordingWindow() {const windowState = useRecordingWindow();@@ -66,7 +77,8 @@ export default function RecordingWindow() {const view = windowState.minimized ? undefined : lastView;// Hide the surface while distinguishing native close from back to tab,- // matching Voice Mode. Only back to tab keeps recording in the page.+ // matching Voice Mode. Only back to tab, or the desktop app's return+ // button, keeps recording in the page.const [floated, setFloated] = useState(false);const [backInPage, setBackInPage] = useState(false);if (pip && !floated) setFloated(true);@@ -197,8 +209,21 @@ export default function RecordingWindow() {const pinched = usePinchZoom();const [moved, setMoved] = useState<{ left: number; top: number }>();+ // The size the Human dragged the in-page window to, for as long as it is+ // open; until then it is 420px wide and as tall as its content needs. A+ // window resized while minimized has no height of its own yet.+ const [sized, setSized] = useState<{ height?: number; width: number }>();const frameRef = useRef<HTMLDivElement>(null);- // Keep the window inside the viewport when dragging its title bar.+ // A moved window stays whole inside the page when the viewport shrinks or+ // the window grows, as it does when it opens from its top row.+ useKeptInViewport(+ frameRef,+ moved,+ setMoved,+ pageBounds,+ Boolean(voice) && !pip && Boolean(moved),+ );+ // Keep the whole window inside the viewport when dragging its title bar.const startMove = (event: PointerEvent<HTMLDivElement>) => {if (event.button !== 0 || (event.target as Element).closest("button"))return;@@ -207,17 +232,14 @@ export default function RecordingWindow() {const rect = frame.getBoundingClientRect();const offsetX = event.clientX - rect.left;const offsetY = event.clientY - rect.top;+ const size = { height: frame.offsetHeight, width: frame.offsetWidth };const move = (next: globalThis.PointerEvent) =>- setMoved({- left: Math.min(- Math.max(next.clientX - offsetX, 0),- window.innerWidth - rect.width,- ),- top: Math.min(- Math.max(next.clientY - offsetY, 36),- window.innerHeight - 52,+ setMoved(+ keptInPage(+ { left: next.clientX - offsetX, top: next.clientY - offsetY },+ size,),- });+ );const end = () => {window.removeEventListener("pointermove", move);window.removeEventListener("pointerup", end);@@ -226,13 +248,16 @@ export default function RecordingWindow() {window.addEventListener("pointerup", end);};if (!voice) return null;+ // An open window the Human gave a height fills it; a minimized one is its+ // top row.+ const fill = Boolean(!pip && view && sized?.height);return createPortal(<divaria-label="Recording window"className={pip? "flex h-dvh w-full flex-col bg-app-canvas"- : "recording-window-frame app-floating-enter fixed top-16 right-4 z-[85] w-[420px] max-w-[calc(100vw-32px)]"+ : "recording-window-frame app-floating-enter fixed top-16 right-4 z-[85] flex max-h-[calc(100dvh-36px)] w-[420px] max-w-[calc(100vw-32px)] flex-col"}ref={frameRef}role="region"@@ -240,7 +265,13 @@ export default function RecordingWindow() {pip? undefined: moved- ? { left: moved.left, top: moved.top, right: "auto" }+ ? {+ height: fill ? sized?.height : undefined,+ left: moved.left,+ right: "auto",+ top: moved.top,+ width: sized?.width,+ }: pinched? pinchedPlacement(pinched): undefined@@ -248,6 +279,7 @@ export default function RecordingWindow() {><RecordingPanelautoStart={windowState.autoStart}+ fill={fill}floating={pip ? "pip" : "page"}onFloat={!pip && voicePipSupported()@@ -257,17 +289,52 @@ export default function RecordingWindow() {: undefined}onMoveStart={startMove}- onShowMain={- pip && canShowDesktopMainWindow() ? showDesktopMainWindow : undefined- }+ onReturn={pip ? () => returnVoicePipToPage("recording") : undefined}onViewChange={changeView}view={view}/>+ {/* A pinch-zoomed page places the window itself. */}+ {pip || (pinched && !moved) ? null : (+ <VoiceWindowResizeHandles+ bounds={pageBounds}+ edges={view ? undefined : ["e", "w"]}+ label="Resize recording window"+ min={minPageSize}+ onResize={({ height, left, top, width }) => {+ // Resizing places the window by its own corner from then on.+ setMoved({ left, top });+ setSized((current) => ({+ height: view ? height : current?.height,+ width,+ }));+ }}+ rect={() => frameRef.current?.getBoundingClientRect()}+ />+ )}</div>,portalHost,);}+/** The part of the page the in-page window may cover. */+function pageBounds(): VoiceWindowBounds {+ return {+ bottom: window.innerHeight,+ left: 0,+ right: window.innerWidth,+ top: pageTop,+ };+}++/** The in-page window's corner, moved no further than keeps the whole window+ * in the page. */+function keptInPage(+ position: { left: number; top: number },+ size: { height: number; width: number },+) {+ return containedVoiceWindowPosition(position, size, pageBounds());+}+/** Ends the recording and releases the microphone, as the Stop button does. */async function endRecording(voice: VoiceControlContextValue) {if (voice.leavePage) {@@ -331,18 +398,20 @@ export function pinchedPlacement(view: PinchZoom) {function RecordingPanel({autoStart,+ fill,floating,onFloat,onMoveStart,- onShowMain,+ onReturn,onViewChange,view,}: {autoStart: boolean;+ fill: boolean;floating: "page" | "pip";onFloat?: () => void;onMoveStart: (event: PointerEvent<HTMLDivElement>) => void;- onShowMain?: () => void;+ onReturn?: () => void;onViewChange: (view: RecordingView | undefined) => void;view?: RecordingView;}) {@@ -359,10 +428,11 @@ function RecordingPanel({return (<VoiceFocusSurfaceautoStart={autoStart}+ fill={fill}floating={floating}onFloat={onFloat}onMoveStart={onMoveStart}- onShowMain={onShowMain}+ onReturn={onReturn}onExit={() => {// Saving finishes in the background; the sidebar's Recording tool// shows its progress and reopens this window on request.diff --git a/apps/web/src/features/rooms/voice-control/voice-focus-surface.tsx b/apps/web/src/features/rooms/voice-control/voice-focus-surface.tsxindex 658d850d..c37bf438 100644--- a/apps/web/src/features/rooms/voice-control/voice-focus-surface.tsx+++ b/apps/web/src/features/rooms/voice-control/voice-focus-surface.tsx@@ -4,9 +4,9 @@ import {ArrowUp01Icon,Cancel01Icon,Loading03Icon,- Maximize01Icon,Mic01Icon,PauseIcon,+ PictureInPictureExitIcon,PictureInPictureOnIcon,PlayIcon,StopIcon,@@ -49,25 +49,29 @@ export interface RecordingPanels {*/export function VoiceFocusSurface({autoStart = false,+ fill = false,floating = "page",onExit,onFloat,onMoveStart,- onShowMain,+ onReturn,onViewChange,panels,view,}: {autoStart?: boolean;+ /** The in-page window has a height of its own, which the surface fills+ * instead of growing with its transcript. */+ fill?: boolean;/** A picture-in-picture window fills its own window instead of floating. */floating?: "page" | "pip";onExit: () => void;- /** Returns the page window to the always-on-top browser window. */+ /** Returns the page window to the always-on-top window. */onFloat?: () => void;/** Starts moving the in-page window from its title bar. */onMoveStart?: (event: PointerEvent<HTMLDivElement>) => void;- /** Brings the main window back, from a floating window of the desktop app. */- onShowMain?: () => void;+ /** Brings the always-on-top window back into the page. */+ onReturn?: () => void;onViewChange?: (view: RecordingView | undefined) => void;/** Present once a recording runs; before that only the transcript shows. */panels?: RecordingPanels;@@ -275,15 +279,15 @@ export function VoiceFocusSurface({<Icon icon={PictureInPictureOnIcon} /></button>) : null}- {onShowMain ? (+ {onReturn ? (<button- aria-label="Show Linger window"+ aria-label="Return recording to Linger"className={styles.windowButton}- onClick={onShowMain}- title="Show the Linger window; recording continues"+ onClick={onReturn}+ title="Back to Linger; recording continues"type="button">- <Icon icon={Maximize01Icon} />+ <Icon icon={PictureInPictureExitIcon} /></button>) : null}</div>@@ -296,11 +300,15 @@ export function VoiceFocusSurface({className={pip? "relative flex min-h-0 flex-1 flex-col bg-app-canvas text-app-ink"- : `relative flex max-h-[min(720px,calc(100dvh-132px))] min-h-0 flex-col overflow-hidden rounded-b-2xl bg-app-canvas text-app-ink ${styles.window}`+ : `relative flex min-h-0 flex-col overflow-hidden rounded-b-2xl bg-app-canvas text-app-ink ${styles.window} ${+ fill ? "flex-1" : "max-h-[min(720px,calc(100dvh-132px))]"+ }`}data-paused={paused || undefined}>- <header className="flex h-14 shrink-0 items-center gap-2 px-4">+ {/* A window narrower than its controls keeps their icons and drops+ the words, which stay as each control's name. */}+ <header className="@container flex h-14 shrink-0 items-center gap-2 px-4">{captureActive ? (<><span aria-hidden="true" className={styles.liveBars}>@@ -351,7 +359,9 @@ export function VoiceFocusSurface({) : (<Icon icon={PauseIcon} size={14} />)}- {paused ? "Resume" : "Pause"}+ <span className="@max-[255px]:sr-only">+ {paused ? "Resume" : "Pause"}+ </span></button>) : null}<button@@ -367,7 +377,9 @@ export function VoiceFocusSurface({) : (<Icon icon={Cancel01Icon} size={14} />)}- {captureActive ? "Stop" : "Close"}+ <span className="@max-[255px]:sr-only">+ {captureActive ? "Stop" : "Close"}+ </span></button></header>{confirmingStop ? (