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.
test(web): replace module mocks with existing seams so more files share an environment
shoudi zhenga1e8c1b2ea9d
diff --git a/apps/web/src/components/read-only-blocknote-document.test.tsx b/apps/web/src/components/read-only-blocknote-document.test.tsxindex 1944470e..0415a628 100644--- a/apps/web/src/components/read-only-blocknote-document.test.tsx+++ b/apps/web/src/components/read-only-blocknote-document.test.tsx@@ -2,29 +2,23 @@ import { act, cleanup, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ReadOnlyBlockNoteDocument } from "./read-only-blocknote-document";-import { renderMermaidSvg } from "@/features/rooms/mermaid-preview-adapter";--vi.mock("@/features/rooms/mermaid-preview-adapter", async (importOriginal) => ({- ...(await importOriginal<- typeof import("@/features/rooms/mermaid-preview-adapter")- >()),- renderMermaidSvg: vi- .fn()- .mockResolvedValue(- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120"><text>Diagram</text></svg>',- ),-}));+import { serveMermaidRuntime } from "@/test/mermaid-runtime";describe("ReadOnlyBlockNoteDocument", () => {- beforeEach(() =>+ beforeEach(() => {+ serveMermaidRuntime((source) =>+ source.startsWith("invalid")+ ? new Error("Invalid diagram")+ : '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120"><text>Diagram</text></svg>',+ );vi.stubGlobal("ResizeObserver",class {observe() {}disconnect() {}},- ),- );+ );+ });afterEach(() => {cleanup();vi.unstubAllGlobals();@@ -54,9 +48,6 @@ describe("ReadOnlyBlockNoteDocument", () => {});it("reports a Mermaid error without showing raw source in reading mode", async () => {- vi.mocked(renderMermaidSvg).mockRejectedValueOnce(- new Error("Invalid diagram"),- );const view = render(<ReadOnlyBlockNoteDocumentariaLabel="Wiki page"diff --git a/apps/web/src/features/auth/use-logout.test.tsx b/apps/web/src/features/auth/use-logout.test.tsxindex b21dc1d1..99b9b9a3 100644--- a/apps/web/src/features/auth/use-logout.test.tsx+++ b/apps/web/src/features/auth/use-logout.test.tsx@@ -7,7 +7,15 @@ import {waitFor,} from "@testing-library/react";import { MemoryRouter, Route, Routes, useLocation } from "react-router";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type Mock,+} from "vitest";import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";import { browserRoomMessageOutbox } from "@/features/rooms/chat/room-message-outbox";@@ -16,23 +24,39 @@ import {writeRoomComposerDraft,} from "@/features/rooms/room-drafts";import { teamHubAuthenticationSignals } from "@/features/teamhub/teamhub-authentication";+import { registerOpenDocumentSession } from "@/features/rooms/documents/room-document-local-copies";+import { defineGlobalProperty } from "@/test/global-properties";import { LOGOUT_UNSAVED_DOCUMENT_MESSAGE, useLogout } from "./use-logout";-const localCopies = vi.hoisted(() => ({- delete: vi.fn(async (_input: { actorIds: readonly string[] }) => undefined),- unsaved: vi.fn(() => false),-}));+// Document editors open in this tab, one per actor; logout must close exactly+// the signed-in actors' sessions before deleting their local copies.+let documentEditsUnsaved: boolean;+let closeDocumentSession: Mock<(actorId: string) => Promise<void>>;+let unregisterDocumentSessions: (() => void)[] = [];++function openDocumentSessions(actorIds: readonly string[]) {+ for (const actorId of actorIds) {+ unregisterDocumentSessions.push(+ registerOpenDocumentSession({+ actorId,+ close: () => closeDocumentSession(actorId),+ documentId: "document-1",+ hasUnsavedChanges: () => documentEditsUnsaved,+ }),+ );+ }+}-vi.mock("@/features/rooms/documents/room-document-local-copies", () => ({- deleteRoomDocumentLocalCopies: localCopies.delete,- hasUnsavedRoomDocumentChanges: localCopies.unsaved,-}));+afterEach(() => {+ for (const unregister of unregisterDocumentSessions) unregister();+ unregisterDocumentSessions = [];+});beforeEach(() => {- localCopies.delete.mockClear();- localCopies.unsaved.mockReset().mockReturnValue(false);+ documentEditsUnsaved = false;+ closeDocumentSession = vi.fn(async (_actorId: string) => undefined);const values = new Map<string, string>();- Object.defineProperty(window, "localStorage", {+ defineGlobalProperty(window, "localStorage", {configurable: true,value: {clear: () => values.clear(),@@ -87,7 +111,7 @@ describe("useLogout", () => {id: "session-1",});expect(readRoomComposerDraft(draftScope).body).toBe("private draft");- expect(localCopies.delete).not.toHaveBeenCalled();+ expect(closeDocumentSession).not.toHaveBeenCalled();expect(clearOutbox).toHaveBeenCalledOnce();expect(clearOutbox).toHaveBeenCalledWith(identity.account.id);expect(screen.getByRole("button", { name: "Log out" })).toBeEnabled();@@ -144,9 +168,9 @@ describe("useLogout", () => {"global-search-recent.v2:tenant-northstar",),).toBeNull();- expect(localCopies.delete).toHaveBeenCalledExactlyOnceWith({- actorIds: identity.actors.map((actor) => actor.id),- });+ expect(closeDocumentSession.mock.calls).toEqual(+ identity.actors.map((actor) => [actor.id]),+ );});renderLogout(runtime, undefined, queryClient);fireEvent.click(screen.getByRole("button", { name: "Log out" }));@@ -156,7 +180,7 @@ describe("useLogout", () => {await act(async () => finishOutbox());await waitFor(() => expect(revoke).toHaveBeenCalledOnce());expect(screen.getByTestId("location")).not.toHaveTextContent("/login");- expect(localCopies.delete).not.toHaveBeenCalled();+ expect(closeDocumentSession).not.toHaveBeenCalled();expect(queryClient.getQueryData(["teamhub", "private"])).toBe("cached");expect(broadcast).not.toHaveBeenCalled();await act(async () => finishLogout());@@ -189,7 +213,7 @@ describe("useLogout", () => {vi.spyOn(browserRoomMessageOutbox, "clearAccount").mockResolvedValue();const revoke = vi.fn(() => undefined);runtime.server.on("POST", "/v0/auth/logout", revoke);- localCopies.unsaved.mockReturnValue(true);+ documentEditsUnsaved = true;const confirm = vi.spyOn(window, "confirm").mockReturnValue(false);renderLogout(runtime);@@ -206,9 +230,9 @@ describe("useLogout", () => {);expect(revoke).toHaveBeenCalledOnce();await waitFor(() =>- expect(localCopies.delete).toHaveBeenCalledWith({- actorIds: identity.actors.map((actor) => actor.id),- }),+ expect(closeDocumentSession.mock.calls).toEqual(+ identity.actors.map((actor) => [actor.id]),+ ),);});@@ -248,7 +272,10 @@ describe("useLogout", () => {});async function testRuntime() {const runtime = createTestTeamHubRuntime();-+ openDocumentSessions([+ ...runtime.seed.identity.actors.map((actor) => actor.id),+ "actor-signed-out",+ ]);return runtime;}function LogoutProbe() {diff --git a/apps/web/src/features/local-models/local-models-page.test.tsx b/apps/web/src/features/local-models/local-models-page.test.tsxindex d43241ed..48c00ed4 100644--- a/apps/web/src/features/local-models/local-models-page.test.tsx+++ b/apps/web/src/features/local-models/local-models-page.test.tsx@@ -20,6 +20,8 @@ import {} from "@/test/teamhub-test-runtime";import { teamHubErrorResponse } from "@/test/teamhub-test-server";+import { localComputersQueryOptions } from "@/features/local-computer/local-computer-queries";+import { ModelsPage } from "./local-models-page";import type { LocalModelsView } from "./local-models-queries";import {@@ -113,10 +115,16 @@ function CurrentSearch() {return <p>Address search: {useLocation().search}</p>;}-function renderPage(fixture: Fixture, search = "") {+// The page suspends until the Computer inventory loads, and React holds a+// revealed Suspense boundary for 300 ms; loading the inventory first renders+// the page at once.+async function renderPage(fixture: Fixture, search = "") {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});+ await queryClient.ensureQueryData(+ localComputersQueryOptions(fixture.runtime.client, tenantId),+ );render(<QueryClientProvider client={queryClient}><TeamHubRuntimeProvider runtime={fixture.runtime}>@@ -235,7 +243,7 @@ afterEach(() => {describe("LocalModelsPage", () => {it("lists every model once with its status, as the Computer reported it", async () => {- renderPage(setup());+ await renderPage(setup());await findModels();expect(statuses()).toEqual([@@ -288,7 +296,7 @@ describe("LocalModelsPage", () => {models: [absent("qwen3.5-9b:Q4_K_M", "Qwen3.5 9B", "system", true)],}),]);- renderPage(fixture, "?computer=computer-mac");+ await renderPage(fixture, "?computer=computer-mac");await findModels();expect(statuses()).toEqual(["Spark-X2.6 4B: Not downloaded · 2.6 GB · Recommended",@@ -296,7 +304,7 @@ describe("LocalModelsPage", () => {]);cleanup();- renderPage(fixture, "?computer=computer-win");+ await renderPage(fixture, "?computer=computer-win");await waitFor(() =>expect(statuses()).toEqual(["Qwen3.5 9B: Not downloaded · 2.6 GB · Recommended",@@ -305,7 +313,7 @@ describe("LocalModelsPage", () => {});it("expands one row at a time to show a model's details", async () => {- renderPage(setup());+ await renderPage(setup());await findModels();fireEvent.click(screen.getByRole("button", { name: "Qwen3 Coder 30B" }));@@ -330,7 +338,7 @@ describe("LocalModelsPage", () => {});it("shows the Computer's pools and hardware in Details", async () => {- renderPage(setup());+ await renderPage(setup());await findModels();fireEvent.click(screen.getByRole("button", { name: "Details" }));@@ -349,7 +357,7 @@ describe("LocalModelsPage", () => {it("shows memory other apps use in a pool's bar", async () => {const shared = gpuPool(0, 24, [{ gb: 4, id: "small", name: "Small" }]);// Another process holds 15 GB of the card next to the model.- renderPage(+ await renderPage(setup([labView({ pools: [{ ...shared, used_bytes: gb(19) }] })]),);await findModels();@@ -366,7 +374,7 @@ describe("LocalModelsPage", () => {it("downloads on click and follows the snapshots the Computer sends", async () => {const fixture = setup();- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(@@ -436,7 +444,7 @@ describe("LocalModelsPage", () => {error: { code, detail: "retries exhausted" },}),]);- renderPage(fixture);+ await renderPage(fixture);await findModels();expect(statusOf("Llama 3.3 70B")).toBe("Download stopped");@@ -465,7 +473,7 @@ describe("LocalModelsPage", () => {}),]);const answer = holdActions(fixture, () => accepted("download"));- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(@@ -483,7 +491,7 @@ describe("LocalModelsPage", () => {error: { code: "DOWNLOAD_FAILED" },}),]);- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Llama 3.3 70B" }));@@ -516,7 +524,7 @@ describe("LocalModelsPage", () => {memory_bytes: gb(10),}),]);- renderPage(fixture);+ await renderPage(fixture);await findModels();expect(statusOf("Llama 3.3 70B")).toBe("Couldn't load");@@ -548,7 +556,7 @@ describe("LocalModelsPage", () => {it("loads at once when the pool has room", async () => {const fixture = setup();- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Load Gemma 3 27B" }));@@ -566,7 +574,7 @@ describe("LocalModelsPage", () => {it("offers to unload the model holding the memory before loading another", async () => {const fixture = setup();- renderPage(fixture, "?computer=computer-mac");+ await renderPage(fixture, "?computer=computer-mac");await findModels();expect(statuses()).toContain("Llama 3.3 70B: Couldn't load");@@ -616,7 +624,7 @@ describe("LocalModelsPage", () => {it("says so when nothing else in the pool can be unloaded", async () => {const mac = macView();- renderPage(+ await renderPage(setup([{...mac,@@ -644,7 +652,7 @@ describe("LocalModelsPage", () => {it("asks before unloading a model an Agent uses, and not otherwise", async () => {const fixture = setup();- renderPage(fixture);+ await renderPage(fixture);await findModels();expect(@@ -695,7 +703,7 @@ describe("LocalModelsPage", () => {it("warns which Agents lose their model before removing it", async () => {const fixture = setup();- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Qwen3 Coder 30B" }));@@ -733,7 +741,7 @@ describe("LocalModelsPage", () => {used_by: [{ agent_id: "agent-writer", name: "Writer" }],};const fixture = setup([view]);- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Gemma 3 27B" }));@@ -752,7 +760,7 @@ describe("LocalModelsPage", () => {it("opens a Computer the viewer may read but does not own", async () => {// The owned-Computer inventory is empty; the library API allows the read.const fixture = setup([labView({ viewer_is_owner: false })], []);- renderPage(fixture, "?computer=computer-lab");+ await renderPage(fixture, "?computer=computer-lab");await findModels();expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent(@@ -776,7 +784,7 @@ describe("LocalModelsPage", () => {[labView({ viewer_is_owner: false }), macView()],[inventoryComputer(macView())],);- renderPage(fixture, "?computer=computer-lab");+ await renderPage(fixture, "?computer=computer-lab");await findModels();// Not the viewer's own Mac: lab-118, read-only.@@ -795,7 +803,7 @@ describe("LocalModelsPage", () => {"disables an open %s confirmation once the Computer goes offline",async (opener, title, confirm) => {const fixture = setup([labView()]);- renderPage(fixture);+ await renderPage(fixture);await findModels();if (opener === "Remove from computer")fireEvent.click(@@ -820,7 +828,7 @@ describe("LocalModelsPage", () => {it("disables an open Unload confirmation once the model is no longer loaded", async () => {const fixture = setup([labView()]);- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Unload Qwen3 Coder 30B" }),@@ -851,7 +859,7 @@ describe("LocalModelsPage", () => {reads += 1;return fixture.views[params.computerId!];});- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Load Gemma 3 27B" }));@@ -878,7 +886,7 @@ describe("LocalModelsPage", () => {it("spins and disables the row's button while an unload is sent", async () => {const fixture = setup();const answer = holdActions(fixture, () => accepted("unload"));- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(@@ -913,7 +921,7 @@ describe("LocalModelsPage", () => {const answer = holdActions(fixture, () =>teamHubErrorResponse(409, "LOCAL_MODEL_NO_ROOM", "raw refusal detail"),);- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Load Gemma 3 27B" }));@@ -934,7 +942,7 @@ describe("LocalModelsPage", () => {fixture.runtime.server.on("POST", actionPath, () =>teamHubErrorResponse(409, "LOCAL_MODEL_NO_ROOM", "raw refusal detail"),);- renderPage(fixture);+ await renderPage(fixture);await findModels();fireEvent.click(screen.getByRole("button", { name: "Load Gemma 3 27B" }));@@ -945,7 +953,7 @@ describe("LocalModelsPage", () => {});it("shows what an offline Computer last reported with every action off", async () => {- renderPage(+ await renderPage(setup([labView({computer: {@@ -976,7 +984,7 @@ describe("LocalModelsPage", () => {});it("lets only the owner act and tells everyone else why", async () => {- renderPage(setup([labView({ viewer_is_owner: false })]));+ await renderPage(setup([labView({ viewer_is_owner: false })]));await findModels();expect(screen.getByRole("status")).toHaveTextContent(@@ -1009,7 +1017,7 @@ describe("LocalModelsPage", () => {] as const)("explains a Computer without a model library (%s)",async (code, title, body) => {- renderPage(+ await renderPage(setup([labView({available: false,@@ -1033,7 +1041,7 @@ describe("LocalModelsPage", () => {);it("sends a Tenant without Computers to Computers", async () => {- renderPage(setup([], []));+ await renderPage(setup([], []));const empty = await screen.findByRole("region", {name: "No computers yet",@@ -1043,7 +1051,7 @@ describe("LocalModelsPage", () => {});it("renders a model that fits nowhere without a placement", async () => {- renderPage(setup());+ await renderPage(setup());await findModels();expect(statuses()).toContain(@@ -1060,7 +1068,7 @@ describe("LocalModelsPage", () => {it("shows a loaded model's endpoint without a gateway model id", async () => {const lab = labView();- renderPage(+ await renderPage(setup([withModel(lab, "qwen3-coder-30b:Q4_K_M", {endpoint: { base_url: "http://127.0.0.1:18100/v1" },@@ -1077,7 +1085,7 @@ describe("LocalModelsPage", () => {});it("keeps the chosen Computer in the address", async () => {- renderPage(setup(), "?computer=computer-mac");+ await renderPage(setup(), "?computer=computer-mac");await findModels();expect(statuses()[0]).toBe("GPT-OSS 20B: Loaded · Memory · 14.3 GB");expect(screen.getByText("14.3 GB of 51.2 GB memory in use")).toBeVisible();@@ -1109,7 +1117,7 @@ describe("LocalModelsPage", () => {onStatus: () => () => undefined,},};- renderPage(setup());+ await renderPage(setup());await waitFor(() =>expect(@@ -1137,7 +1145,7 @@ describe("LocalModelsPage", () => {family: "gemma",vision: true,});- renderPage(setup([visionLab]));+ await renderPage(setup([visionLab]));await findModels();const coderCard = card("Qwen3 Coder 30B");@@ -1193,7 +1201,7 @@ describe("LocalModelsPage", () => {state: "failed",},);- renderPage(setup([view]));+ await renderPage(setup([view]));await findModels();const loadedCard = card("Qwen3 Coder 30B");@@ -1225,7 +1233,7 @@ describe("LocalModelsPage", () => {it("shows live download rate and ETA when bytes_per_second is reported", async () => {const mb = 1024 * 1024;- renderPage(+ await renderPage(setup([withModel(labView(), "gpt-oss-20b:Q4_K_M", {download: {@@ -1305,7 +1313,7 @@ describe("Model source", () => {it("opens on the source in use and explains BYOK on hover", async () => {const fixture = setup([labView()]);withSource(fixture, byokStatus);- renderPage(fixture);+ await renderPage(fixture);const tabs = await screen.findByRole("tablist", { name: "Model source" });expect(@@ -1360,7 +1368,7 @@ describe("Model source", () => {viewer_is_owner: true,});});- renderPage(fixture);+ await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: "Subscription" }));fireEvent.click(@@ -1414,7 +1422,7 @@ describe("Model source", () => {{ status: 504 },),);- renderPage(fixture);+ await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: "Subscription" }));fireEvent.click(@@ -1449,7 +1457,7 @@ describe("Model source", () => {viewer_is_owner: true,});});- renderPage(fixture);+ await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));expect(@@ -1509,7 +1517,7 @@ describe("Model source", () => {runtime: "claude",runtime_model: "",});- renderPage(fixture);+ await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));const baseUrl = screen.getByLabelText("Base URL");@@ -1558,7 +1566,7 @@ describe("Model source", () => {it("lists the models again on request with the key as typed", async () => {const fixture = setup([labView()]);const { listings } = withSource(fixture, byokStatus);- renderPage(fixture);+ await renderPage(fixture);expect(await screen.findByText("2 models listed.")).toBeInTheDocument();expect(listings).toEqual([@@ -1594,7 +1602,7 @@ describe("Model source", () => {{ status: 409 },),);- renderPage(fixture);+ await renderPage(fixture);expect(await screen.findByText(@@ -1612,7 +1620,7 @@ describe("Model source", () => {runtime: "claude",runtime_model: "",});- renderPage(fixture);+ await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));fireEvent.change(screen.getByLabelText("Base URL"), {@@ -1642,7 +1650,7 @@ describe("Model source", () => {viewer_is_owner: true,});});- renderPage(fixture);+ await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: "Local model" }));fireEvent.click(diff --git a/apps/web/src/features/memory/wiki-graph-report-cards.test.tsx b/apps/web/src/features/memory/wiki-graph-report-cards.test.tsxindex c0aae660..a898d00d 100644--- a/apps/web/src/features/memory/wiki-graph-report-cards.test.tsx+++ b/apps/web/src/features/memory/wiki-graph-report-cards.test.tsx@@ -1,25 +1,41 @@import { act, fireEvent, render, screen } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";++import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";+import { defineGlobalProperty } from "@/test/global-properties";+import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";+import { WikiGraphReportCards } from "./wiki-graph-report-cards";import type { NodeMoment } from "./wiki-graph-model";-const { reports } = vi.hoisted(() => ({- reports: { data: [], isPending: false },-}));-vi.mock("./wiki-period-reports", async (importOriginal) => ({- ...(await importOriginal<typeof import("./wiki-period-reports")>()),- usePeriodReports: () => reports,- usePeriodReport: () => ({ isPending: false }),-}));-afterEach(() => vi.restoreAllMocks());-Object.defineProperty(HTMLElement.prototype, "scrollTo", {- configurable: true,- value: vi.fn(),-});++// No reports exist yet: the lists are cached fresh, so nothing is fetched.+function noReportsWrapper() {+ const queryClient = new QueryClient();+ for (const kind of ["daily", "weekly"]) {+ queryClient.setQueryData(+ ["teamhub", "tenant-northstar", "personal-memory", `${kind}-entries`],+ [],+ );+ }+ const runtime = createTestTeamHubRuntime();+ return function NoReports({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <TeamHubRuntimeProvider runtime={runtime}>+ {children}+ </TeamHubRuntimeProvider>+ </QueryClientProvider>+ );+ };+}it("preserves the requested card on resize and observes each mounted track only once", () => {+ defineGlobalProperty(HTMLElement.prototype, "scrollTo", { value: vi.fn() });const observers: {callback: ResizeObserverCallback;observe: ReturnType<typeof vi.fn>;@@ -56,7 +72,9 @@ it("preserves the requested card on resize and observes each mounted track onlyonSelectReport: vi.fn(),onPeriodChange: vi.fn(),};- const view = render(<WikiGraphReportCards {...props} granularity="day" />);+ const view = render(<WikiGraphReportCards {...props} granularity="day" />, {+ wrapper: noReportsWrapper(),+ });expect(screen.queryByText("Attachment")).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: "Topic" }),diff --git a/apps/web/src/features/rooms/chat/message-html-fragment.test.tsx b/apps/web/src/features/rooms/chat/message-html-fragment.test.tsxindex 20d359ac..7eb2342b 100644--- a/apps/web/src/features/rooms/chat/message-html-fragment.test.tsx+++ b/apps/web/src/features/rooms/chat/message-html-fragment.test.tsx@@ -1,7 +1,7 @@import { act, fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";-import { writeClipboardText } from "@/lib/clipboard";+import { defineGlobalProperty } from "@/test/global-properties";import {fragmentDownloadFileName,@@ -9,10 +9,6 @@ import {} from "./html-fragment-host";import { MessageHtmlFragment } from "./message-html-fragment";-vi.mock("@/lib/clipboard", () => ({- writeClipboardText: vi.fn(async () => undefined),-}));-describe("MessageHtmlFragment", () => {it("inlines hosted HTML in a script-only sandbox iframe", () => {render(@@ -57,6 +53,8 @@ describe("MessageHtmlFragment", () => {it("exposes copy and download actions without save-as-artifact", async () => {const html = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';+ const writeText = vi.fn(async (_text: string) => undefined);+ defineGlobalProperty(navigator, "clipboard", { value: { writeText } });render(<MessageHtmlFragment html={html} title="Architecture diagram" />);fireEvent.click(screen.getByRole("button", { name: "Widget actions" }));@@ -74,7 +72,7 @@ describe("MessageHtmlFragment", () => {screen.getByRole("menuitem", { name: "Copy to clipboard" }),);await vi.waitFor(() => {- expect(writeClipboardText).toHaveBeenCalledWith(html);+ expect(writeText).toHaveBeenCalledWith(html);});});diff --git a/apps/web/src/features/rooms/chat/profile-card-content.test.tsx b/apps/web/src/features/rooms/chat/profile-card-content.test.tsxindex 0a645c44..6ad2326d 100644--- a/apps/web/src/features/rooms/chat/profile-card-content.test.tsx+++ b/apps/web/src/features/rooms/chat/profile-card-content.test.tsx@@ -1,12 +1,15 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { render, screen } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { render as renderUi, screen } from "@testing-library/react";+import type { ReactElement } from "react";+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";import { MemoryRouter } from "react-router";import { MessageCard } from "./message-card";import { anotherMeQueryKey } from "@/features/rooms/room-queries";-import type { TeamHubApi } from "@/features/teamhub/teamhub-api";-import { createHttpTeamHubClient } from "@/features/teamhub/teamhub-client";-import { TeamHubTestServer } from "@/test/teamhub-test-server";+import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";+import {+ createTestTeamHubRuntime,+ type TestTeamHubRuntime,+} from "@/test/teamhub-test-runtime";import { profilePreview, useProfileCardContent } from "./profile-card-content";@@ -22,29 +25,32 @@ function profileDocument(backgroundOverview: string) {};}-const runtime = vi.hoisted(() => ({- client: {- api: undefined as TeamHubApi | undefined,- getPersonalProfile: vi.fn(),- listExternalApps: vi.fn(),- },-}));-vi.mock("@/features/teamhub/teamhub-runtime", () => ({- useOptionalTeamHubRuntime: () => runtime,-}));-+let runtime: TestTeamHubRuntime;+// The fixtures carry only the fields the card reads.+let getPersonalProfile: Mock<(...args: unknown[]) => Promise<unknown>>;+let listExternalApps: Mock<(...args: unknown[]) => Promise<unknown>>;beforeEach(() => {- const server = new TeamHubTestServer().on(- "GET",- "/v0/tenants/{tenantId}/another-me",- () => ({ room_id: "room-1", agent_actor_id: "agent-1" }),- );- runtime.client.api = createHttpTeamHubClient({- fetchRequest: server.fetch,- onAuthenticationRequired: () => undefined,- }).api;+ runtime = createTestTeamHubRuntime();+ runtime.server.on("GET", "/v0/tenants/{tenantId}/another-me", () => ({+ room_id: "room-1",+ agent_actor_id: "agent-1",+ }));+ getPersonalProfile = vi.spyOn(+ runtime.client,+ "getPersonalProfile",+ ) as unknown as typeof getPersonalProfile;+ listExternalApps = vi.spyOn(runtime.client, "listExternalApps");});+const render = (ui: ReactElement) =>+ renderUi(ui, {+ wrapper: ({ children }) => (+ <TeamHubRuntimeProvider runtime={runtime}>+ {children}+ </TeamHubRuntimeProvider>+ ),+ });+function CardDetails({ roomId = "room-1" }: { roomId?: string }) {const content = useProfileCardContent({children: "Original summary",@@ -80,9 +86,7 @@ describe("Profile card content", () => {])("only enhances the owner's delivery in room %s by %s",async (roomId, authorId, enhanced) => {- runtime.client.getPersonalProfile- .mockClear()- .mockResolvedValue({ current: null });+ getPersonalProfile.mockClear().mockResolvedValue({ current: null });const client = new QueryClient({defaultOptions: { queries: { retry: false } },});@@ -121,7 +125,7 @@ describe("Profile card content", () => {);expect(screen.queryByRole("link", { name: "Open" })).toBeNull();expect(screen.queryByRole("img", { name: "Jenny avatar" })).toBeNull();- expect(runtime.client.getPersonalProfile).not.toHaveBeenCalled();+ expect(getPersonalProfile).not.toHaveBeenCalled();expect(screen.getByText("Role — Original summary")).toBeVisible();expect(screen.queryByText("Enhanced summary")).toBeNull();}@@ -166,7 +170,7 @@ describe("Profile card content", () => {});it("shows the published excerpt", async () => {- runtime.client.getPersonalProfile.mockResolvedValue({+ getPersonalProfile.mockResolvedValue({current: {profile: profileDocument("A sufficiently detailed paragraph drawn directly from the published profile.",@@ -180,7 +184,7 @@ describe("Profile card content", () => {});it("shows all recorded apps and excludes other available apps without reading the summary", async () => {- runtime.client.getPersonalProfile.mockResolvedValue({+ getPersonalProfile.mockResolvedValue({current: {profile: profileDocument("A sufficiently detailed description of the subject's work.",@@ -188,7 +192,7 @@ describe("Profile card content", () => {source_apps: ["gmail", "github"],},});- runtime.client.listExternalApps.mockResolvedValue({+ listExternalApps.mockResolvedValue({apps: [{ key: "gmail", display_name: "Gmail" },{ key: "github", display_name: "GitHub" },@@ -204,17 +208,15 @@ describe("Profile card content", () => {});it("keeps the original summary if the Profile is unavailable", async () => {- runtime.client.getPersonalProfile.mockRejectedValue(- new Error("unavailable"),- );+ getPersonalProfile.mockRejectedValue(new Error("unavailable"));renderDetails();expect(await screen.findByText("Original summary")).toBeVisible();expect(screen.queryByRole("list", { name: /Profile sources/ })).toBeNull();});it("does not infer sources for a Profile whose source record is unknown", async () => {- runtime.client.listExternalApps.mockClear();- runtime.client.getPersonalProfile.mockResolvedValue({+ listExternalApps.mockClear();+ getPersonalProfile.mockResolvedValue({current: {profile: profileDocument("A long enough description mentioning Gmail but with no source record.",@@ -224,7 +226,7 @@ describe("Profile card content", () => {renderDetails();expect(await screen.findByText(/mentioning Gmail/)).toBeVisible();expect(screen.queryByRole("list", { name: "Profile sources" })).toBeNull();- expect(runtime.client.listExternalApps).not.toHaveBeenCalled();+ expect(listExternalApps).not.toHaveBeenCalled();});it("does not show cached personal Profile data in a different room", async () => {diff --git a/apps/web/src/features/rooms/chat/room-chat-direct-rooms.test.tsx b/apps/web/src/features/rooms/chat/room-chat-direct-rooms.test.tsxindex 07c21fe7..65d829f5 100644--- a/apps/web/src/features/rooms/chat/room-chat-direct-rooms.test.tsx+++ b/apps/web/src/features/rooms/chat/room-chat-direct-rooms.test.tsx@@ -1,3 +1,4 @@+import { defineGlobalProperty } from "@/test/global-properties";import { acceptRoomCreation } from "@/test/teamhub-test-runtime";import { teamHubErrorResponse } from "@/test/teamhub-test-server";import {@@ -23,54 +24,16 @@ import {servePeerActive,readTenantAgents,readAgentAvailability,+ openPanelTab,} from "./room-chat.fixtures";-const openPanelTab = vi.fn();--vi.mock("../room-connectivity", async () => {- const actual = await vi.importActual<typeof import("../room-connectivity")>(- "../room-connectivity",- );- return {- ...actual,- // Keep the standalone Chat defaults; only spy panel opens from message entities.- useRoomOutletContext: () => ({- focusPanelMessageId: null,- lastAppliedRoomSeq: 0,- messagePresentations: {},- openPanelTab,- recordMessagePresentation: () => undefined,- status: "connected" as const,- }),- };-});-beforeEach(() => {- Object.defineProperty(window, "localStorage", {+ defineGlobalProperty(window, "localStorage", {configurable: true,value: createTestStorage(),});});-vi.mock("@/components/read-only-blocknote-document-loader", () => ({- ReadOnlyBlockNoteDocumentLoader: ({- ariaLabel,- markdown,- }: {- ariaLabel: string;- markdown: string;- }) => (- <article aria-label={ariaLabel} data-editable="false">- {markdown- .split(/\n+/)- .filter(Boolean)- .map((line) => (- <p key={line}>{line.replace(/^#+\s*/, "")}</p>- ))}- </article>- ),-}));-describe("Room Chat", () => {beforeEach(async () => {openPanelTab.mockReset();diff --git a/apps/web/src/features/rooms/chat/room-chat-documents.test.tsx b/apps/web/src/features/rooms/chat/room-chat-documents.test.tsxindex fc99cbcd..ef7fee7b 100644--- a/apps/web/src/features/rooms/chat/room-chat-documents.test.tsx+++ b/apps/web/src/features/rooms/chat/room-chat-documents.test.tsx@@ -1,3 +1,4 @@+import { defineGlobalProperty } from "@/test/global-properties";import {showDocument,seedRoomDocument,@@ -30,54 +31,16 @@ import {readShareableDocuments,queriesTo,listRoomMessages,+ openPanelTab,} from "./room-chat.fixtures";-const openPanelTab = vi.fn();--vi.mock("../room-connectivity", async () => {- const actual = await vi.importActual<typeof import("../room-connectivity")>(- "../room-connectivity",- );- return {- ...actual,- // Keep the standalone Chat defaults; only spy panel opens from message entities.- useRoomOutletContext: () => ({- focusPanelMessageId: null,- lastAppliedRoomSeq: 0,- messagePresentations: {},- openPanelTab,- recordMessagePresentation: () => undefined,- status: "connected" as const,- }),- };-});-beforeEach(() => {- Object.defineProperty(window, "localStorage", {+ defineGlobalProperty(window, "localStorage", {configurable: true,value: createTestStorage(),});});-vi.mock("@/components/read-only-blocknote-document-loader", () => ({- ReadOnlyBlockNoteDocumentLoader: ({- ariaLabel,- markdown,- }: {- ariaLabel: string;- markdown: string;- }) => (- <article aria-label={ariaLabel} data-editable="false">- {markdown- .split(/\n+/)- .filter(Boolean)- .map((line) => (- <p key={line}>{line.replace(/^#+\s*/, "")}</p>- ))}- </article>- ),-}));-describe("Room Chat", () => {beforeEach(async () => {openPanelTab.mockReset();diff --git a/apps/web/src/features/rooms/chat/room-chat-timeline.test.tsx b/apps/web/src/features/rooms/chat/room-chat-timeline.test.tsxindex 1a3b29ee..f4ebf3d1 100644--- a/apps/web/src/features/rooms/chat/room-chat-timeline.test.tsx+++ b/apps/web/src/features/rooms/chat/room-chat-timeline.test.tsx@@ -1,3 +1,4 @@+import { defineGlobalProperty } from "@/test/global-properties";import { type TestRouteHandler } from "@/test/teamhub-test-server";import { type InfiniteData } from "@tanstack/react-query";import {@@ -29,54 +30,16 @@ import {testQueryClient,createTestTeamHubRuntime,listRoomMessages,+ openPanelTab,} from "./room-chat.fixtures";-const openPanelTab = vi.fn();--vi.mock("../room-connectivity", async () => {- const actual = await vi.importActual<typeof import("../room-connectivity")>(- "../room-connectivity",- );- return {- ...actual,- // Keep the standalone Chat defaults; only spy panel opens from message entities.- useRoomOutletContext: () => ({- focusPanelMessageId: null,- lastAppliedRoomSeq: 0,- messagePresentations: {},- openPanelTab,- recordMessagePresentation: () => undefined,- status: "connected" as const,- }),- };-});-beforeEach(() => {- Object.defineProperty(window, "localStorage", {+ defineGlobalProperty(window, "localStorage", {configurable: true,value: createTestStorage(),});});-vi.mock("@/components/read-only-blocknote-document-loader", () => ({- ReadOnlyBlockNoteDocumentLoader: ({- ariaLabel,- markdown,- }: {- ariaLabel: string;- markdown: string;- }) => (- <article aria-label={ariaLabel} data-editable="false">- {markdown- .split(/\n+/)- .filter(Boolean)- .map((line) => (- <p key={line}>{line.replace(/^#+\s*/, "")}</p>- ))}- </article>- ),-}));-describe("Room Chat", () => {beforeEach(async () => {openPanelTab.mockReset();diff --git a/apps/web/src/features/rooms/chat/room-chat.fixtures.tsx b/apps/web/src/features/rooms/chat/room-chat.fixtures.tsxindex 636eea92..e70682ce 100644--- a/apps/web/src/features/rooms/chat/room-chat.fixtures.tsx+++ b/apps/web/src/features/rooms/chat/room-chat.fixtures.tsx@@ -9,7 +9,7 @@ import {QueryClientProvider,} from "@tanstack/react-query";import { act, render } from "@testing-library/react";-import { Suspense } from "react";+import { Suspense, type ReactNode } from "react";import { createMemoryRouter, RouterProvider } from "react-router";import { vi } from "vitest";@@ -34,6 +34,10 @@ import {roomQueryOptions,teamHubIdentityQueryOptions,} from "../room-queries";+import {+ RoomChromeProvider,+ type RoomOutletContext,+} from "../room-connectivity";import { RoomChat } from "./room-chat";import { roomMessageSender } from "./room-message-sender";@@ -78,6 +82,26 @@ export function repliedRunScenario() {};}+// Panel opens from message entities go to this spy; the rest is the standalone+// Chat context.+export const openPanelTab = vi.fn<RoomOutletContext["openPanelTab"]>();++const testRoomChrome: RoomOutletContext = {+ focusPanelMessageId: null,+ lastAppliedRoomSeq: 0,+ messagePresentations: {},+ openPanelTab,+ openProfile: () => undefined,+ recordMessagePresentation: () => undefined,+ status: "connected",+};++export function TestRoomChrome({ children }: { children: ReactNode }) {+ return (+ <RoomChromeProvider value={testRoomChrome}>{children}</RoomChromeProvider>+ );+}+export function renderRoomChat(runtime: TeamHubRuntime,queryClient: QueryClient,@@ -112,6 +136,7 @@ export function renderRoomChat(</Suspense></TeamHubRuntimeProvider></QueryClientProvider>,+ { wrapper: TestRoomChrome },);return router;diff --git a/apps/web/src/features/rooms/chat/room-chat.test.tsx b/apps/web/src/features/rooms/chat/room-chat.test.tsxindex 9ff95ea5..d551d446 100644--- a/apps/web/src/features/rooms/chat/room-chat.test.tsx+++ b/apps/web/src/features/rooms/chat/room-chat.test.tsx@@ -1,3 +1,4 @@+import { defineGlobalProperty } from "@/test/global-properties";import { seedRoomUpload } from "@/test/document-scenarios";import { QueryClientProvider } from "@tanstack/react-query";import {@@ -35,54 +36,17 @@ import {loadedRoomChatQueryClient,testQueryClient,createTestTeamHubRuntime,+ openPanelTab,+ TestRoomChrome,} from "./room-chat.fixtures";-const openPanelTab = vi.fn();--vi.mock("../room-connectivity", async () => {- const actual = await vi.importActual<typeof import("../room-connectivity")>(- "../room-connectivity",- );- return {- ...actual,- // Keep the standalone Chat defaults; only spy panel opens from message entities.- useRoomOutletContext: () => ({- focusPanelMessageId: null,- lastAppliedRoomSeq: 0,- messagePresentations: {},- openPanelTab,- recordMessagePresentation: () => undefined,- status: "connected" as const,- }),- };-});-beforeEach(() => {- Object.defineProperty(window, "localStorage", {+ defineGlobalProperty(window, "localStorage", {configurable: true,value: createTestStorage(),});});-vi.mock("@/components/read-only-blocknote-document-loader", () => ({- ReadOnlyBlockNoteDocumentLoader: ({- ariaLabel,- markdown,- }: {- ariaLabel: string;- markdown: string;- }) => (- <article aria-label={ariaLabel} data-editable="false">- {markdown- .split(/\n+/)- .filter(Boolean)- .map((line) => (- <p key={line}>{line.replace(/^#+\s*/, "")}</p>- ))}- </article>- ),-}));-describe("Room Chat", () => {beforeEach(async () => {openPanelTab.mockReset();@@ -293,6 +257,7 @@ describe("Room Chat", () => {</Suspense></TeamHubRuntimeProvider></QueryClientProvider>,+ { wrapper: TestRoomChrome },);await screen.findByText(/Reviewed the checklist/);@@ -328,6 +293,7 @@ describe("Room Chat", () => {</Suspense></TeamHubRuntimeProvider></QueryClientProvider>,+ { wrapper: TestRoomChrome },);await screen.findByLabelText("Message Room");diff --git a/apps/web/src/features/rooms/chat/thread-panel.test.tsx b/apps/web/src/features/rooms/chat/thread-panel.test.tsxindex 53f8fe64..a0852e08 100644--- a/apps/web/src/features/rooms/chat/thread-panel.test.tsx+++ b/apps/web/src/features/rooms/chat/thread-panel.test.tsx@@ -1,3 +1,4 @@+import { defineGlobalProperty } from "@/test/global-properties";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import {act,@@ -34,33 +35,15 @@ import { roomMessagesQueryKey } from "../room-queries";import { requestThreadComposerFocus } from "./thread-composer-focus";import { roomMessageSender } from "./room-message-sender";import { ThreadPanel } from "./thread-panel";+import { openPanelTab, TestRoomChrome } from "./room-chat.fixtures";import { teamHubData } from "@/features/teamhub/teamhub-api";import type { TeamHubClient } from "@/features/teamhub/teamhub-client";-const openPanelTab = vi.fn();--vi.mock("../room-connectivity", async () => {- const actual = await vi.importActual<typeof import("../room-connectivity")>(- "../room-connectivity",- );- return {- ...actual,- useRoomOutletContext: () => ({- focusPanelMessageId: null,- lastAppliedRoomSeq: 0,- messagePresentations: {},- openPanelTab,- recordMessagePresentation: () => undefined,- status: "connected" as const,- }),- };-});-describe("ThreadPanel", () => {beforeEach(() => {openPanelTab.mockReset();const store = new Map<string, string>();- Object.defineProperty(window, "localStorage", {+ defineGlobalProperty(window, "localStorage", {configurable: true,value: {get length() {@@ -479,9 +462,14 @@ describe("ThreadPanel", () => {);const dock = await screen.findByTestId("agent-streaming-status-dock");- expect(- within(dock).getByRole("button", { name: "Open Agent status activity" }),- ).toHaveAttribute("title", "Codex: Run stopped");+ // The status line picks the shown entry in an effect after the dock mounts.+ await waitFor(() =>+ expect(+ within(dock).getByRole("button", {+ name: "Open Agent status activity",+ }),+ ).toHaveAttribute("title", "Codex: Run stopped"),+ );expect(dock.compareDocumentPosition(screen.getByLabelText("Reply in Thread")) &Node.DOCUMENT_POSITION_FOLLOWING,@@ -1019,9 +1007,14 @@ describe("ThreadPanel", () => {);const dock = await screen.findByTestId("agent-streaming-status-dock");- expect(- within(dock).getByRole("button", { name: "Open Agent status activity" }),- ).toHaveAttribute("title", "Codex: Run stopped");+ // The status line picks the shown entry in an effect after the dock mounts.+ await waitFor(() =>+ expect(+ within(dock).getByRole("button", {+ name: "Open Agent status activity",+ }),+ ).toHaveAttribute("title", "Codex: Run stopped"),+ );expect(dock).not.toHaveTextContent("Lev8 GTM");});@@ -1278,7 +1271,9 @@ function wrap(return (<QueryClientProvider client={queryClient}><TeamHubRuntimeProvider runtime={runtime}>- <MemoryRouter>{ui}</MemoryRouter>+ <TestRoomChrome>+ <MemoryRouter>{ui}</MemoryRouter>+ </TestRoomChrome></TeamHubRuntimeProvider></QueryClientProvider>);diff --git a/apps/web/src/features/rooms/chat/use-room-chat-navigation.test.tsx b/apps/web/src/features/rooms/chat/use-room-chat-navigation.test.tsxindex 22e18b2e..3570e623 100644--- a/apps/web/src/features/rooms/chat/use-room-chat-navigation.test.tsx+++ b/apps/web/src/features/rooms/chat/use-room-chat-navigation.test.tsx@@ -17,14 +17,10 @@ import { artifactPreviewCache } from "../files/artifact-preview-cache";import { documentCardVersionQueryKey } from "../files/use-document-card-metadata";import { documentQueryKey, roomDocumentsQueryKey } from "../room-queries";import { useRoomChatNavigation } from "./use-room-chat-navigation";+import { openPanelTab, TestRoomChrome } from "./room-chat.fixtures";import { teamHubData } from "@/features/teamhub/teamhub-api";import type { TeamHubClient } from "@/features/teamhub/teamhub-client";-const openPanelTab = vi.fn();-vi.mock("../room-connectivity", () => ({- useRoomOutletContext: () => ({ openPanelTab }),-}));-beforeEach(() => openPanelTab.mockReset());function deferredDocument() {@@ -40,7 +36,7 @@ function wrapper(queryClient: QueryClient) {return (<MemoryRouter><QueryClientProvider client={queryClient}>- {children}+ <TestRoomChrome>{children}</TestRoomChrome></QueryClientProvider></MemoryRouter>);diff --git a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.test.ts b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.test.tsindex 1bcdc01a..fa0b1f82 100644--- a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.test.ts+++ b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.test.ts@@ -11,19 +11,19 @@ import {type VoicePageSource,} from "./voice-live-arbiter";-const pageTools = vi.hoisted(() => ({ runs: [] as unknown[] }));-vi.mock("./voice-live-page-tools", () => ({+let pageActions: unknown[] = [];+const pageTools = {pageReady: async () => undefined,readPageTargets: () => "e1 Pocket Note",- runPageAction: vi.fn(async (request: unknown) => {- pageTools.runs.push(request);- return { status: "done" };- }),-}));+ runPageAction: async (request: unknown) => {+ pageActions.push(request);+ return { status: "done" as const };+ },+};afterEach(() => {vi.useRealTimers();- pageTools.runs = [];+ pageActions = [];});function fixture(page?: VoicePageSource) {@@ -45,6 +45,7 @@ function fixture(page?: VoicePageSource) {onTranscript: (lines) => {transcript = lines;},+ pageTools,...(page ? { page } : {}),});return {@@ -204,7 +205,7 @@ describe("voice live arbiter", () => {clickable: "e1 Pocket Note",});expect(results.p1).toEqual({ status: "done" });- expect(pageTools.runs).toEqual([{ action: "scroll", target: "down" }]);+ expect(pageActions).toEqual([{ action: "scroll", target: "down" }]);f.arbiter.dispose();});diff --git a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.ts b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.tsindex aad35f15..7a962a25 100644--- a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.ts+++ b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-arbiter.ts@@ -11,6 +11,8 @@ import {} from "./voice-live-page-tools";import { readVoicePage, type VoicePageState } from "./voice-page-reader";+const voiceLivePageTools = { pageReady, readPageTargets, runPageAction };+/** The voice window keeps this many exchanges of the call. */const transcriptLines = 200;@@ -102,9 +104,12 @@ export function createVoiceLiveArbiter(options: {onTranscript: (lines: readonly VoiceLiveLine[]) => void;/** The page the Human sees; when given, where they are is kept in sync. */page?: VoicePageSource;+ /** The page tools the live model calls; defaults to this page's. */+ pageTools?: typeof voiceLivePageTools;}) {let disposed = false;const page = options.page;+ const pageTools = options.pageTools ?? voiceLivePageTools;const send = (event: TeamHubVoiceLiveClientEvent) => {if (disposed || !options.active()) return false;options.send(event);@@ -219,11 +224,11 @@ export function createVoiceLiveArbiter(options: {try {if (event.tool === "read_page") {// A list still loading would read as an empty page.- await pageReady();+ await pageTools.pageReady();return reply({status: "ok",page: (page?.read ?? readVoicePage)(),- clickable: readPageTargets(+ clickable: pageTools.readPageTargets(options.context,// Runtime's placeholder when the model gave no focus.text.replace(/^visible page$/u, ""),@@ -247,7 +252,7 @@ export function createVoiceLiveArbiter(options: {return reply({ status: "outcome_unknown" });pageActions.add(callId);if (!text) return reply({ status: "failed", detail: "Empty request." });- const result = await runPageAction(+ const result = await pageTools.runPageAction(JSON.parse(text) as Record<string, unknown>,options.context,() => !disposed && options.active(),diff --git a/apps/web/src/features/rooms/chat/voice-mode/message-voice-selection-control.test.tsx b/apps/web/src/features/rooms/chat/voice-mode/message-voice-selection-control.test.tsxindex a9ed8cbc..1b2ab828 100644--- a/apps/web/src/features/rooms/chat/voice-mode/message-voice-selection-control.test.tsx+++ b/apps/web/src/features/rooms/chat/voice-mode/message-voice-selection-control.test.tsx@@ -1,7 +1,14 @@-import { fireEvent, render, screen } from "@testing-library/react";-import { useState } from "react";+import { fireEvent, render as renderUi, screen } from "@testing-library/react";+import { useState, type ReactElement, type ReactNode } from "react";++import { defineGlobalProperty } from "@/test/global-properties";import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ VoiceMaterialsContext,+ type VoiceMaterials,+} from "./voice-materials-context";+import { MessageVoiceSelectionControl } from "./message-voice-selection-control";const context = vi.hoisted(() => ({@@ -11,30 +18,47 @@ const context = vi.hoisted(() => ({addSelection: vi.fn(),}));-vi.mock("./voice-materials-context", () => ({- useOptionalVoiceMaterials: () => (context.enabled ? context : undefined),-}));+// Read on every render, so a test configures the context before rendering.+function VoiceMaterialsFromTest({ children }: { children: ReactNode }) {+ return (+ <VoiceMaterialsContext+ value={+ context.enabled ? (context as unknown as VoiceMaterials) : undefined+ }+ >+ {children}+ </VoiceMaterialsContext>+ );+}++function render(ui: ReactElement) {+ return renderUi(ui, { wrapper: VoiceMaterialsFromTest });+}beforeEach(() => {// jsdom has no layout; place every selection at a fixed rectangle.- Element.prototype.getBoundingClientRect = () =>- ({- top: 0,- bottom: 800,- left: 0,- right: 1200,- width: 1200,- height: 800,- }) as DOMRect;- Range.prototype.getBoundingClientRect = () =>- ({- top: 100,- bottom: 120,- left: 40,- right: 200,- width: 160,- height: 20,- }) as DOMRect;+ defineGlobalProperty(Element.prototype, "getBoundingClientRect", {+ value: () =>+ ({+ top: 0,+ bottom: 800,+ left: 0,+ right: 1200,+ width: 1200,+ height: 800,+ }) as DOMRect,+ });+ defineGlobalProperty(Range.prototype, "getBoundingClientRect", {+ value: () =>+ ({+ top: 100,+ bottom: 120,+ left: 40,+ right: 200,+ width: 160,+ height: 20,+ }) as DOMRect,+ });context.enabled = true;context.voiceModeEntered = true;context.error = undefined;diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.tsxindex b357330e..4e9f52c5 100644--- a/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.tsx+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.tsx@@ -14,7 +14,7 @@ import {} from "../../room-drafts";import type { TeamHubRoom } from "@/features/teamhub/teamhub-types";-interface VoiceMaterials {+export interface VoiceMaterials {/** Room whose next voice turn receives these materials. */roomId: string;/** False while collecting from another Room: only Message text crosses over. */@@ -28,7 +28,7 @@ interface VoiceMaterials {setVoiceModeEntered: (entered: boolean) => void;}-const VoiceMaterialsContext = createContext<VoiceMaterials | undefined>(+export const VoiceMaterialsContext = createContext<VoiceMaterials | undefined>(undefined,);diff --git a/apps/web/src/features/rooms/documents/document-version-presentation.test.tsx b/apps/web/src/features/rooms/documents/document-version-presentation.test.tsxindex b17b5541..bf93f015 100644--- a/apps/web/src/features/rooms/documents/document-version-presentation.test.tsx+++ b/apps/web/src/features/rooms/documents/document-version-presentation.test.tsx@@ -1,5 +1,5 @@import { render, screen } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import {createDocumentTestRuntime,@@ -7,14 +7,6 @@ import {} from "@/test/document-scenarios";import { DocumentVersionPreview } from "./document-version-preview";-vi.mock("@/features/rooms/files/artifact-content-renderer-loader", () => ({- ArtifactContentRendererLoader: ({- presentation,- }: {- presentation: string;- }) => <div data-testid="presentation">{presentation}</div>,-}));-describe("Document Version knowledge presentation", () => {it.each(["wiki_source", "wiki_page", "room"] as const)("uses knowledge presentation only for generated Wiki pages, not %s sources",@@ -45,9 +37,12 @@ describe("Document Version knowledge presentation", () => {}}/>,);- expect(await screen.findByTestId("presentation")).toHaveTextContent(- bindingKind === "wiki_page" ? "knowledge" : "default",- );+ const title = await screen.findByText("Original");+ expect(+ title+ .closest(".read-only-blocknote-document")!+ .className.includes("read-only-blocknote-document--knowledge"),+ ).toBe(bindingKind === "wiki_page");},);});diff --git a/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsx b/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsxindex 2ddb9a68..a3e708e4 100644--- a/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsx+++ b/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsx@@ -1,5 +1,10 @@-import { fireEvent, render, screen, within } from "@testing-library/react";-import { createRef, type ReactNode } from "react";+import {+ fireEvent,+ render as renderUi,+ screen,+ within,+} from "@testing-library/react";+import { createRef, type ReactElement, type ReactNode } from "react";import {afterEach,beforeAll,@@ -10,6 +15,11 @@ import {vi,} from "vitest";+import {+ VoiceMaterialsContext,+ type VoiceMaterials,+} from "../chat/voice-mode/voice-materials-context";+import { DocumentVoiceSelectionControl } from "./document-voice-selection-control";const context = vi.hoisted(() => ({@@ -20,15 +30,28 @@ const context = vi.hoisted(() => ({addSelection: vi.fn(),}));-vi.mock("../chat/voice-mode/voice-materials-context", () => ({- useOptionalVoiceMaterials: () => (context.enabled ? context : undefined),-}));+// Read on every render, so a test configures the context before rendering.+function VoiceMaterialsFromTest({ children }: { children: ReactNode }) {+ return (+ <VoiceMaterialsContext+ value={+ context.enabled ? (context as unknown as VoiceMaterials) : undefined+ }+ >+ {children}+ </VoiceMaterialsContext>+ );+}++function render(ui: ReactElement) {+ return renderUi(ui, { wrapper: VoiceMaterialsFromTest });+}// React binds its own document selectionchange listener on its first render.// Render once before any test so a test that counts document listeners counts// only the control's, whichever test runs first.beforeAll(() => {- render(<span />).unmount();+ renderUi(<span />).unmount();});beforeEach(() => {diff --git a/apps/web/src/features/rooms/documents/room-document-knowledge-presentation.test.tsx b/apps/web/src/features/rooms/documents/room-document-knowledge-presentation.test.tsxindex 2a3aabe4..398de70b 100644--- a/apps/web/src/features/rooms/documents/room-document-knowledge-presentation.test.tsx+++ b/apps/web/src/features/rooms/documents/room-document-knowledge-presentation.test.tsx@@ -16,15 +16,7 @@ import {openLocalDocumentSession,} from "@/test/local-document-session";import { knowledgeHiddenBlockIds } from "./room-document-knowledge-presentation";--vi.mock("../mermaid-preview-adapter", async (importOriginal) => ({- ...(await importOriginal<typeof import("../mermaid-preview-adapter")>()),- renderMermaidSvg: vi- .fn()- .mockResolvedValue(- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120"><text>Outreach diagram</text></svg>',- ),-}));+import { serveMermaidRuntime } from "@/test/mermaid-runtime";const wikiMarkdown = `---okf_version: "0.2"@@ -90,6 +82,12 @@ function parse(markdown: string) {}describe("Wiki knowledge reading projection", () => {+ beforeEach(() =>+ serveMermaidRuntime(+ () =>+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120"><text>Outreach diagram</text></svg>',+ ),+ );it.each(["Sources"])("hides %s and its nested file blocks without changing the document",(heading) => {diff --git a/apps/web/src/features/rooms/documents/room-document-mermaid-code-block.test.ts b/apps/web/src/features/rooms/documents/room-document-mermaid-code-block.test.tsindex 7dd0a272..7ee3c6f7 100644--- a/apps/web/src/features/rooms/documents/room-document-mermaid-code-block.test.ts+++ b/apps/web/src/features/rooms/documents/room-document-mermaid-code-block.test.ts@@ -6,22 +6,15 @@ import * as Y from "yjs";import { roomDocumentCommentSchema } from "./room-document-comment-schema";import { mermaidSourceFromCodeBlock } from "./room-document-mermaid-code-block";--vi.mock("../mermaid-preview-adapter", async (importOriginal) => {- const original =- await importOriginal<typeof import("../mermaid-preview-adapter")>();- return {- ...original,- renderMermaidSvg: vi- .fn()- .mockResolvedValue(- '<svg xmlns="http://www.w3.org/2000/svg"><text>Diagram</text></svg>',- ),- };-});+import { defineGlobalProperty } from "@/test/global-properties";+import { serveMermaidRuntime } from "@/test/mermaid-runtime";describe("Room Document Mermaid code block", () => {beforeEach(() => {+ serveMermaidRuntime(+ () =>+ '<svg xmlns="http://www.w3.org/2000/svg"><text>Diagram</text></svg>',+ );vi.stubGlobal("ResizeObserver",class {@@ -291,8 +284,7 @@ describe("Room Document Mermaid code block", () => {it("copies the complete source through the Clipboard API", async () => {const writeText = vi.fn().mockResolvedValue(undefined);- Object.defineProperty(window.navigator, "clipboard", {- configurable: true,+ defineGlobalProperty(window.navigator, "clipboard", {value: { writeText },});const editor = BlockNoteEditor.create({diff --git a/apps/web/src/features/rooms/sharing/shared-room-history-page.test.tsx b/apps/web/src/features/rooms/sharing/shared-room-history-page.test.tsxindex f0389f10..8b84314f 100644--- a/apps/web/src/features/rooms/sharing/shared-room-history-page.test.tsx+++ b/apps/web/src/features/rooms/sharing/shared-room-history-page.test.tsx@@ -1,12 +1,20 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { render, screen, fireEvent, waitFor } from "@testing-library/react";import { MemoryRouter } from "react-router";-import { describe, it, expect, vi } from "vitest";+import { beforeEach, describe, it, expect, vi, type Mock } from "vitest";+import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";+import {+ createTestTeamHubRuntime,+ type TestTeamHubRuntime,+} from "@/test/teamhub-test-runtime";import { SharedRoomHistoryPage } from "./shared-room-history-page";-const { read } = vi.hoisted(() => ({ read: vi.fn() }));-vi.mock("@/features/teamhub/teamhub-runtime", () => ({- useTeamHubRuntime: () => ({ client: { roomHistory: { read } } }),-}));+let runtime: TestTeamHubRuntime;+// The fixtures carry only the fields the page reads.+let read: Mock<(...args: unknown[]) => Promise<unknown>>;+beforeEach(() => {+ runtime = createTestTeamHubRuntime();+ read = vi.spyOn(runtime.client.roomHistory, "read") as unknown as typeof read;+});const token = `room_share_${"a".repeat(43)}`;const message = {id: "message_1",@@ -37,9 +45,11 @@ function open() {new QueryClient({ defaultOptions: { queries: { retry: false } } })}>- <MemoryRouter initialEntries={[`/shared-room-history#${token}`]}>- <SharedRoomHistoryPage />- </MemoryRouter>+ <TeamHubRuntimeProvider runtime={runtime}>+ <MemoryRouter initialEntries={[`/shared-room-history#${token}`]}>+ <SharedRoomHistoryPage />+ </MemoryRouter>+ </TeamHubRuntimeProvider></QueryClientProvider>,);}diff --git a/apps/web/src/features/rooms/voice-control/recording-entry.test.tsx b/apps/web/src/features/rooms/voice-control/recording-entry.test.tsxindex 608a2357..3133e038 100644--- a/apps/web/src/features/rooms/voice-control/recording-entry.test.tsx+++ b/apps/web/src/features/rooms/voice-control/recording-entry.test.tsx@@ -6,8 +6,6 @@ import {VoiceConnectionRetryContext,} from "./voice-control-context";-vi.mock("./recording-window-store", () => ({ openRecordingWindow: vi.fn() }));-afterEach(cleanup);function renderEntry(retryConnection?: () => void) {diff --git a/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx b/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsxindex df85f655..a57cdf31 100644--- a/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx+++ b/apps/web/src/features/rooms/voice-control/voice-key-dialog.test.tsx@@ -16,7 +16,12 @@ import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";import { teamHubErrorResponse } from "@/test/teamhub-test-server";import { RecordingEntry } from "./recording-entry";-import { openRecordingWindow } from "./recording-window-store";+import {+ resetRecordingWindowForTest,+ useRecordingWindow,+ type RecordingWindowState,+} from "./recording-window-store";+import { resetVoicePipForTest } from "../chat/voice-mode/voice-pip";import { subscribeVoiceMediaPolicy } from "./use-voice-media-policy";import {VoiceCapabilitiesContext,@@ -25,17 +30,22 @@ import {} from "./voice-control-context";import { VoiceKeyDialog } from "./voice-key-dialog";-vi.mock("./recording-window-store", () => ({ openRecordingWindow: vi.fn() }));-vi.mock("../chat/voice-mode/voice-pip", () => ({- closeVoicePip: vi.fn(),- openVoicePip: vi.fn(async () => undefined),-}));-afterEach(() => {cleanup();vi.clearAllMocks();+ resetRecordingWindowForTest();+ resetVoicePipForTest();});+/** Records every Recording window state the page publishes. */+function RecordingWindowProbe({ seen }: { seen: RecordingWindowState[] }) {+ const state = useRecordingWindow();+ useEffect(() => {+ seen.push(state);+ }, [seen, state]);+ return null;+}+const missing = { source: "none" as const, can_save: true };const noKeys: TeamHubVoiceMediaPolicy = {voice_available: true,@@ -141,6 +151,7 @@ describe("Recording without a Soniox key", () => {return { source: "stored", can_save: true };});const selectTargetRoom = vi.fn(async () => undefined);+ const recordingWindow: RecordingWindowState[] = [];renderWithRuntime(runtime,<VoiceWorkspace initial={noKeys} selectTargetRoom={selectTargetRoom}>@@ -148,6 +159,7 @@ describe("Recording without a Soniox key", () => {anotherMeRoomId="another-me"tenantId="tenant-northstar"/>+ <RecordingWindowProbe seen={recordingWindow} /></VoiceWorkspace>,);const entry = screen.getByRole("button", { name: "Meetings" });@@ -158,8 +170,18 @@ describe("Recording without a Soniox key", () => {target: { value: " soniox-key " },});fireEvent.click(within(dialog).getByRole("button", { name: "Save key" }));- await waitFor(() => expect(openRecordingWindow).toHaveBeenCalledOnce());- expect(openRecordingWindow).toHaveBeenCalledWith({ autoStart: true });+ const closed = {+ open: false,+ minimized: false,+ autoStart: false,+ ending: false,+ };+ await waitFor(() =>+ expect(recordingWindow).toEqual([+ closed,+ { ...closed, open: true, autoStart: true },+ ]),+ );expect(selectTargetRoom).toHaveBeenCalledWith("another-me");expect(screen.queryByRole("dialog")).toBeNull();expect(saves).toBe(1);diff --git a/apps/web/src/features/rooms/voice-control/voice-recovery-panel.test.tsx b/apps/web/src/features/rooms/voice-control/voice-recovery-panel.test.tsxindex f5662ae3..18269fd0 100644--- a/apps/web/src/features/rooms/voice-control/voice-recovery-panel.test.tsx+++ b/apps/web/src/features/rooms/voice-control/voice-recovery-panel.test.tsx@@ -1,24 +1,33 @@import { fetchDouble } from "@/features/teamhub/teamhub-client-test-support";import {act,- cleanup,fireEvent,- render,+ render as renderUi,screen,} from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactElement } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";import {createHttpTeamHubClient,type TeamHubClient,} from "@/features/teamhub/teamhub-client";+import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";import type { TeamHubVoiceCapture } from "@/features/teamhub/teamhub-types";+import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";import { VoiceRecoveryPanel } from "./voice-recovery-panel";let client: TeamHubClient;const transport = vi.fn<typeof fetch>();-vi.mock("@/features/teamhub/teamhub-runtime", () => ({- useTeamHubRuntime: () => ({ client }),-}));+const render = (ui: ReactElement) => {+ const runtime = { ...createTestTeamHubRuntime(), client };+ return renderUi(ui, {+ wrapper: ({ children }) => (+ <TeamHubRuntimeProvider runtime={runtime}>+ {children}+ </TeamHubRuntimeProvider>+ ),+ });+};const capture = (id = "capture-a"): TeamHubVoiceCapture => ({id,room_id: "room",@@ -54,10 +63,8 @@ beforeEach(() => {fetchRequest: fetchDouble((url, init) => transport(url, init)),});});-afterEach(() => {- cleanup();- vi.useRealTimers();-});+// src/test/setup.ts unmounts, runs the pending fake timers and frames, then+// restores real timers; dropping them here would stall later files' frames.describe("transcript recovery request lifecycle", () => {it("unlocks a hung recovery request and lets the user retry", async () => {diff --git a/apps/web/src/features/wiki/wiki-home-page.test.tsx b/apps/web/src/features/wiki/wiki-home-page.test.tsxindex 79381392..588b0c66 100644--- a/apps/web/src/features/wiki/wiki-home-page.test.tsx+++ b/apps/web/src/features/wiki/wiki-home-page.test.tsx@@ -1,7 +1,7 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { fireEvent, render, screen } from "@testing-library/react";import { createMemoryRouter, RouterProvider } from "react-router";-import { expect, it, vi } from "vitest";+import { expect, it } from "vitest";import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";import { WikiHomePage } from "./wiki-home-page";@@ -11,12 +11,6 @@ import {wikiDocument,} from "./wiki.test-support";-vi.mock("@/components/read-only-blocknote-document-loader", () => ({- ReadOnlyBlockNoteDocumentLoader: ({ markdown }: { markdown: string }) => (- <article>{markdown}</article>- ),-}));-it("shows real collection pages on the Wiki tab and returns to Profile", async () => {const runtime = createTestTeamHubRuntime();const page = wikiDocument("project-one", "Launch.md", "wiki_page");diff --git a/apps/web/src/features/wiki/wiki-preview-page.test.tsx b/apps/web/src/features/wiki/wiki-preview-page.test.tsxindex de3d5eb3..41a3817e 100644--- a/apps/web/src/features/wiki/wiki-preview-page.test.tsx+++ b/apps/web/src/features/wiki/wiki-preview-page.test.tsx@@ -1,7 +1,7 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { render, screen } from "@testing-library/react";import { createMemoryRouter, RouterProvider } from "react-router";-import { expect, it, vi } from "vitest";+import { expect, it } from "vitest";import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";import { WikiPreviewPage } from "./wiki-preview-page";@@ -11,23 +11,6 @@ import {wikiDocument,} from "./wiki.test-support";-vi.mock("@/components/read-only-blocknote-document-loader", () => ({- ReadOnlyBlockNoteDocumentLoader: ({- markdown,- resolveLink,- }: {- markdown: string;- resolveLink: (reference: string) => string | null | undefined;- }) => (- <article>- {markdown}- <a href={resolveLink("../clients/contactout.md") ?? undefined}>- ContactOut- </a>- </article>- ),-}));-it("opens a page being written in the published page layout", async () => {const runtime = createTestTeamHubRuntime();const contactOut = wikiDocument("client-one", "ContactOut.md", "wiki_page");@@ -51,7 +34,7 @@ it("opens a page being written in the published page layout", async () => {"GET","/v0/tenants/{tenantId}/personal-wiki/preview",() => ({- "projects/lev8.md": `---\n${JSON.stringify({ type: "Project", title: "Lev8" })}\n---\n\n# Lev8\n\nVisitor identity.\n`,+ "projects/lev8.md": `---\n${JSON.stringify({ type: "Project", title: "Lev8" })}\n---\n\n# Lev8\n\nVisitor identity.\n\n[ContactOut](../clients/contactout.md)\n`,}),);const router = createMemoryRouter(@@ -81,7 +64,7 @@ it("opens a page being written in the published page layout", async () => {"title","Not published yet. This page may still change.",);- expect(screen.getByText(/Visitor identity\./)).toBeVisible();+ expect(await screen.findByText(/Visitor identity\./)).toBeVisible();expect(screen.getByRole("link", { name: "ContactOut" })).toHaveAttribute("href","/t/tenant-northstar/documents/client-one",diff --git a/apps/web/src/test/mermaid-runtime.ts b/apps/web/src/test/mermaid-runtime.tsnew file mode 100644index 00000000..bd08516f--- /dev/null+++ b/apps/web/src/test/mermaid-runtime.ts@@ -0,0 +1,60 @@+import { onTestFinished, vi } from "vitest";++import type {+ MermaidPreviewRequest,+ MermaidPreviewResponse,+} from "@/features/rooms/mermaid-preview-protocol";++/**+ * Stands in for the sandboxed Mermaid runtime, which jsdom cannot load: every+ * runtime frame the adapter appends reports ready and answers its render+ * request through the real message protocol, with the SVG `answer` returns or+ * the error it returns. Call it from a test or `beforeEach`; it stops when the+ * test finishes.+ */+export function serveMermaidRuntime(+ answer: (source: string) => string | Error,+) {+ const observer = new MutationObserver((records) => {+ for (const record of records) {+ for (const node of record.addedNodes) {+ if (+ node instanceof HTMLIFrameElement &&+ node.title === "Mermaid rendering runtime"+ )+ serveFrame(node);+ }+ }+ });+ observer.observe(document.body, { childList: true });+ onTestFinished(() => observer.disconnect());++ function serveFrame(frame: HTMLIFrameElement) {+ const runtime = frame.contentWindow!;+ const reply = (data: MermaidPreviewResponse) =>+ queueMicrotask(() =>+ window.dispatchEvent(+ new MessageEvent("message", { data, source: runtime }),+ ),+ );+ vi.spyOn(runtime, "postMessage").mockImplementation(((+ request: MermaidPreviewRequest,+ ) => {+ const result = answer(request.source);+ reply(+ result instanceof Error+ ? {+ error: result.message,+ kind: "linger.mermaid.error",+ requestId: request.requestId,+ }+ : {+ kind: "linger.mermaid.result",+ requestId: request.requestId,+ svg: result,+ },+ );+ }) as Window["postMessage"]);+ reply({ kind: "linger.mermaid.ready" });+ }+}diff --git a/apps/web/src/test/vitest-isolation.test.ts b/apps/web/src/test/vitest-isolation.test.tsindex 92a31a88..2e797f48 100644--- a/apps/web/src/test/vitest-isolation.test.ts+++ b/apps/web/src/test/vitest-isolation.test.ts@@ -14,9 +14,7 @@ describe("Vitest isolation partition", () => {it("splits the real test files without losing any", () => {const root = fileURLToPath(new URL("../..", import.meta.url));const { isolated, shared } = partitionTestFiles(root, "src/**/*.test.tsx");- expect(isolated).toContain(- "src/features/rooms/documents/document-voice-selection-control.test.tsx",- );+ expect(isolated).toContain("src/features/rooms/room-surface.test.tsx");expect(shared).toContain("src/features/rooms/room-navigation.test.tsx");expect(isolated.filter((file) => shared.includes(file))).toEqual([]);});