diff --git a/apps/app/src/components/commands/CommandPalette.test.tsx b/apps/app/src/components/commands/CommandPalette.test.tsx index e0075271b3b..4472b478b39 100644 --- a/apps/app/src/components/commands/CommandPalette.test.tsx +++ b/apps/app/src/components/commands/CommandPalette.test.tsx @@ -120,6 +120,7 @@ const testState = vi.hoisted(() => ({ const modeState = vi.hoisted(() => ({ activeRecents: [] as ThreadListEntry[], archivedRecents: [] as ThreadListEntry[], + archivedRecentsEnabled: false, threadDraftIds: new Set(), searchResponse: undefined as ThreadSearchResponse | undefined, recentLoading: false, @@ -243,11 +244,14 @@ vi.mock("@/hooks/queries/sidebar-navigation-query", () => ({ })); vi.mock("@/hooks/queries/palette-thread-queries", () => ({ - usePaletteRecentArchivedThreads: () => ({ - data: modeState.archivedRecents, - isLoading: false, - isError: false, - }), + usePaletteRecentArchivedThreads: ({ enabled }: { enabled: boolean }) => { + modeState.archivedRecentsEnabled = enabled; + return { + data: modeState.archivedRecents, + isLoading: false, + isError: false, + }; + }, })); vi.mock("@/hooks/queries/thread-queries", async (importOriginal) => { @@ -414,6 +418,7 @@ afterEach(() => { testState.plugins.length = 0; modeState.activeRecents = []; modeState.archivedRecents = []; + modeState.archivedRecentsEnabled = false; modeState.threadDraftIds.clear(); modeState.searchResponse = undefined; modeState.recentLoading = false; @@ -1109,6 +1114,22 @@ describe("CommandPalette", () => { ); }); + it("loads archived recents only while Archived is selected and the query is empty", async () => { + const { store } = renderPalette(); + openThreadSearch(); + await screen.findByRole("combobox", { name: "Search threads" }); + expect(modeState.archivedRecentsEnabled).toBe(false); + + act(() => store.set(paletteThreadLifecyclesAtom, ["active", "archived"])); + expect(modeState.archivedRecentsEnabled).toBe(true); + + fireEvent.change(searchField(), { target: { value: "match" } }); + expect(modeState.archivedRecentsEnabled).toBe(false); + + fireEvent.change(searchField(), { target: { value: " " } }); + expect(modeState.archivedRecentsEnabled).toBe(true); + }); + it("operates the lifecycle filter with the keyboard without selecting a result", async () => { modeState.activeRecents = [makeThread("active")]; const { store } = renderPalette(); diff --git a/apps/app/src/components/plugin/theme-preview-fixture-anatomy.test.ts b/apps/app/src/components/plugin/theme-preview-fixture-anatomy.test.ts index 1d110350a65..3902355f421 100644 --- a/apps/app/src/components/plugin/theme-preview-fixture-anatomy.test.ts +++ b/apps/app/src/components/plugin/theme-preview-fixture-anatomy.test.ts @@ -1,6 +1,11 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { describe, expect, it } from "vitest"; +import { + SIDEBAR_ROW_INTERACTIVE_STATE_CLASS, + SIDEBAR_ROW_OPEN_IN_SPLIT_STATE_CLASS, + SIDEBAR_ROW_SELECTED_STATE_CLASS, +} from "@bb/shared-ui/sidebar-row-classes"; const REPO_ROOT = resolve(import.meta.dirname, "../../../../.."); const THEME_PREVIEW_TAXONOMY = resolve( @@ -10,28 +15,62 @@ const THEME_PREVIEW_TAXONOMY = resolve( interface FixtureAnchor { file: string; - mustContain: readonly string[]; + mustContain?: readonly string[]; + classLists?: readonly (readonly string[])[]; because: string; } -const SHARED_FIXTURE_ANCHORS: readonly FixtureAnchor[] = [ +const MOCK_ROW_CLASS_CONTRACTS = [ { - file: "apps/app/src/components/ui/sidebar.tsx", - mustContain: ["fixed inset-y-0", "bg-sidebar text-sidebar-foreground"], - because: - "The mock sidebar carries `fixed bg-sidebar` so theme blocks scoped to `.fixed.bg-sidebar` (token overrides, noise overlays) apply to it exactly as they do in the app.", + name: "SIDEBAR_ROW_INTERACTIVE_STATE_CLASS", + value: SIDEBAR_ROW_INTERACTIVE_STATE_CLASS, + classes: [ + "hover:bg-sidebar-accent", + "hover:text-sidebar-accent-foreground", + ], }, { - file: "packages/shared-ui/src/components/ui/sidebar-row-classes.ts", - mustContain: [ - "SIDEBAR_ROW_BASE_CLASS =", - "SIDEBAR_ROW_INTERACTIVE_STATE_CLASS =", - "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground", - "SIDEBAR_ROW_SELECTED_STATE_CLASS =", - "SIDEBAR_ROW_OPEN_IN_SPLIT_STATE_CLASS =", + name: "SIDEBAR_ROW_SELECTED_STATE_CLASS", + value: SIDEBAR_ROW_SELECTED_STATE_CLASS, + classes: [ + "bg-state-active", + "bb-sidebar-selected-row", + "text-sidebar-foreground", ], + }, + { + name: "SIDEBAR_ROW_OPEN_IN_SPLIT_STATE_CLASS", + value: SIDEBAR_ROW_OPEN_IN_SPLIT_STATE_CLASS, + classes: ["bb-sidebar-open-in-split-row"], + }, +] as const; + +const MIRROR_NOTE = + "Theme Preview's mock (plugins/theme-preview/app.tsx) mirrors this, so update it together with this anchor."; + +const STRING_LITERAL_PATTERNS = [/"([^"\n]*)"/g, /'([^'\n]*)'/g, /`([^`]*)`/g]; + +function sourceClassLists(source: string): Set[] { + return STRING_LITERAL_PATTERNS.flatMap((pattern) => + Array.from( + source.matchAll(pattern), + (match) => new Set(match[1].split(/\s+/)), + ), + ); +} + +function hasClassList(source: string, classes: readonly string[]): boolean { + return sourceClassLists(source).some((tokens) => + classes.every((token) => tokens.has(token)), + ); +} + +const SHARED_FIXTURE_ANCHORS: readonly FixtureAnchor[] = [ + { + file: "apps/app/src/components/ui/sidebar.tsx", + classLists: [["fixed", "bg-sidebar", "text-sidebar-foreground"]], because: - "Mock thread and settings rows keep BB's shared row geometry and rest, hover, selected, and split states.", + "The mock sidebar carries `fixed bg-sidebar` so theme blocks scoped to `.fixed.bg-sidebar` (token overrides, noise overlays) apply to it exactly as they do in the app.", }, { file: "apps/app/src/components/sidebar/SectionSidebar.tsx", @@ -44,11 +83,6 @@ const SHARED_FIXTURE_ANCHORS: readonly FixtureAnchor[] = [ because: "Mock sidebars use BB's shared button primitive, section-label token, padding, and project-row anatomy.", }, - { - file: "packages/shared-ui/src/components/ui/context-selection.ts", - mustContain: ['CONTEXT_SELECTION_SURFACE_CLASS = "bg-state-active"'], - because: "The open thread's row in the mock paints state-active.", - }, { file: "apps/app/src/components/ui/theme.css", mustContain: [ @@ -141,8 +175,8 @@ const VIEW_FIXTURE_ANCHORS: Record = { 'aria-label="Thread table of contents"', 'label="Agent messages"', 'label="Your messages"', - "bg-popover", ], + classLists: [["bg-popover"]], because: "The held-open fixture keeps the real message-role tabs and popover surface.", }, @@ -155,8 +189,7 @@ const VIEW_FIXTURE_ANCHORS: Record = { { file: "plugins/git/ui/info/GitInfoRows.tsx", mustContain: [' = { new: [ { file: "apps/app/src/views/RootComposeView.tsx", - mustContain: [ - 'ROOT_COMPOSE_SIDEBAR_ACTION_ALIGNED_TOP_PADDING_CLASS = "pt-14"', - "{promptBox}", - ], + mustContain: ["{promptBox}"], + classLists: [["pt-14"]], because: "The New thread projection opens on the composer alone, aligned under the sidebar actions.", }, { file: "apps/app/src/views/RootComposeHome.tsx", - mustContain: ['ROOT_COMPOSE_MAX_WIDTH_CLASS = "max-w-[760px]"'], + classLists: [["max-w-[760px]"]], because: "The New thread projection keeps BB's home column width.", }, { @@ -204,9 +235,9 @@ const VIEW_FIXTURE_ANCHORS: Record = { "data-split-pane-id", "data-focused", "data-pane-focus-scrim", - '"bg-background/30"', " = { }, { file: "apps/app/src/components/ui/settings-section.tsx", - mustContain: [ - "rounded-lg border border-border bg-card px-4 py-3.5", - "flex flex-col gap-2.5", - "text-xs leading-snug text-subtle-foreground/75", + classLists: [ + ["rounded-lg", "border", "border-border", "bg-card", "px-4", "py-3.5"], + ["flex-col", "gap-2.5"], + ["text-xs", "leading-snug", "text-subtle-foreground/75"], ], because: "The Appearance projection keeps BB's section card, responsive rows, and supporting-copy hierarchy.", @@ -285,15 +316,31 @@ describe("Theme Preview fixture anatomy", () => { } }); + it("keeps the shared sidebar row states the mock rows copy", () => { + for (const contract of MOCK_ROW_CLASS_CONTRACTS) { + expect( + contract.value.split(/\s+/), + `Mock thread and settings rows copy BB's shared hover, selected, and split row states.\n${MIRROR_NOTE}\nExpected ${contract.name} to include: ${contract.classes.join(" ")}`, + ).toEqual(expect.arrayContaining([...contract.classes])); + } + }); + for (const anchor of FIXTURE_ANCHORS) { it(`still matches ${anchor.file}`, () => { const source = readFileSync(resolve(REPO_ROOT, anchor.file), "utf8"); - for (const needle of anchor.mustContain) { + const mirrorNote = `${anchor.because}\n${MIRROR_NOTE}`; + for (const needle of anchor.mustContain ?? []) { expect( source, - `${anchor.because}\nTheme Preview's mock (plugins/theme-preview/app.tsx) mirrors this, so update it together with this anchor.\nExpected ${anchor.file} to contain: ${needle}`, + `${mirrorNote}\nExpected ${anchor.file} to contain: ${needle}`, ).toContain(needle); } + for (const classes of anchor.classLists ?? []) { + expect( + hasClassList(source, classes), + `${mirrorNote}\nExpected one class list in ${anchor.file} to include, in any order: ${classes.join(" ")}`, + ).toBe(true); + } }); } }); diff --git a/apps/app/src/components/promptbox/banner/ProviderCliBanner.test.tsx b/apps/app/src/components/promptbox/banner/ProviderCliBanner.test.tsx index a05d6d8dc56..6c147ba315d 100644 --- a/apps/app/src/components/promptbox/banner/ProviderCliBanner.test.tsx +++ b/apps/app/src/components/promptbox/banner/ProviderCliBanner.test.tsx @@ -1,24 +1,27 @@ +// @vitest-environment jsdom + +import { cleanup, render, screen } from "@testing-library/react"; import type { ComponentProps } from "react"; -import { renderToStaticMarkup } from "react-dom/server"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { ProviderCliBanner } from "./ProviderCliBanner"; +afterEach(() => { + cleanup(); +}); + function renderBanner( props: Omit, "onAction">, ) { - const markup = renderToStaticMarkup( - {}} />, - ); + render( {}} />); return { - markup, - text: markup.replace(/<[^>]+>/g, ""), - button: markup.match(/]*)>(.*?)<\/button>/), + text: screen.getByRole("alert").textContent, + button: screen.getByRole("button"), }; } describe("ProviderCliBanner", () => { it("uses the selected provider's identity and update requirement", () => { - const { markup, text, button } = renderBanner({ + const { text, button } = renderBanner({ displayName: "Example Agent", installed: true, currentVersion: "0.135.0", @@ -27,12 +30,14 @@ describe("ProviderCliBanner", () => { actionRunning: false, }); - expect(markup).toContain('aria-label="Example Agent update required"'); + expect( + screen.getByRole("region", { name: "Example Agent update required" }), + ).toBeTruthy(); expect(text).toContain( "Update Example Agent before starting a thread. Installed 0.135.0; version 0.136.0 or newer is required.", ); - expect(button?.[2]).toBe("Update Example Agent"); - expect(button?.[1]).not.toContain('disabled=""'); + expect(button.textContent).toBe("Update Example Agent"); + expect(button.hasAttribute("disabled")).toBe(false); }); it("shows update progress without repeating an ambiguous version fallback", () => { @@ -46,12 +51,12 @@ describe("ProviderCliBanner", () => { }); expect(text).toContain("Installed 0.135.0; a newer version is required."); - expect(button?.[2]).toContain("Updating…"); - expect(button?.[1]).toContain('disabled=""'); + expect(button.textContent).toContain("Updating…"); + expect(button.hasAttribute("disabled")).toBe(true); }); it("asks for an install instead of a version when the CLI is missing", () => { - const { markup, text, button } = renderBanner({ + const { text, button } = renderBanner({ displayName: "Claude Code", installed: false, currentVersion: null, @@ -60,9 +65,11 @@ describe("ProviderCliBanner", () => { actionRunning: false, }); - expect(markup).toContain('aria-label="Claude Code not installed"'); + expect( + screen.getByRole("region", { name: "Claude Code not installed" }), + ).toBeTruthy(); expect(text).toContain("Install Claude Code before starting a thread."); expect(text).not.toContain("version"); - expect(button?.[2]).toBe("Install Claude Code"); + expect(button.textContent).toBe("Install Claude Code"); }); }); diff --git a/apps/app/src/components/promptbox/banner/ThreadMachineStatus.test.tsx b/apps/app/src/components/promptbox/banner/ThreadMachineStatus.test.tsx index 0252b0ab832..91fe1adc7b3 100644 --- a/apps/app/src/components/promptbox/banner/ThreadMachineStatus.test.tsx +++ b/apps/app/src/components/promptbox/banner/ThreadMachineStatus.test.tsx @@ -1,5 +1,7 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import { describe, expect, it } from "vitest"; +// @vitest-environment jsdom + +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; import { ThreadMachineStatusBanner } from "./ThreadMachineStatus"; const provider = { @@ -14,8 +16,12 @@ const provider = { supportsSuspend: true, }; +afterEach(() => { + cleanup(); +}); + function renderBanner(phase: "suspending" | "suspended" | "resuming") { - const markup = renderToStaticMarkup( + const { container } = render( , ); return { - markup, - status: markup - .match(/role="status">(.*?)<\/div>/)?.[1] - ?.replace(/<[^>]+>/g, ""), - buttons: [...markup.matchAll(/]*)>(.*?)<\/button>/g)], + markup: container.innerHTML, + status: screen.getByRole("status"), + buttons: screen.queryAllByRole("button"), }; } @@ -41,12 +45,12 @@ describe("ThreadMachineStatusBanner", () => { it("names the paused state generically and keeps the provider icon", () => { const { markup, status, buttons } = renderBanner("suspended"); - expect(status).toBe("Machine is paused"); - expect(markup).toContain('data-icon="Cloud"'); + expect(status.textContent).toBe("Machine is paused"); + expect(status.querySelector('[data-icon="Cloud"]')).not.toBeNull(); expect(markup).not.toContain("Modal sandbox ugxe6e"); expect(markup).not.toContain(provider.displayName); - expect(buttons.map((button) => button[2])).toEqual(["Resume"]); - expect(buttons[0]?.[1]).not.toContain('disabled=""'); + expect(buttons.map((button) => button.textContent)).toEqual(["Resume"]); + expect(buttons[0]?.hasAttribute("disabled")).toBe(false); }); it.each([ @@ -55,7 +59,7 @@ describe("ThreadMachineStatusBanner", () => { ] as const)("renders the durable %s phase", (phase, expected) => { const { status, buttons } = renderBanner(phase); - expect(status).toBe(expected); + expect(status.textContent).toBe(expected); expect(buttons).toEqual([]); }); }); diff --git a/apps/app/src/components/promptbox/banner/ThreadPromptContextBanner.test.tsx b/apps/app/src/components/promptbox/banner/ThreadPromptContextBanner.test.tsx index 601949ba60b..233d106ae2d 100644 --- a/apps/app/src/components/promptbox/banner/ThreadPromptContextBanner.test.tsx +++ b/apps/app/src/components/promptbox/banner/ThreadPromptContextBanner.test.tsx @@ -47,9 +47,7 @@ function Banner({ const isReadOnly = archivedSection !== null || environmentGoneSection !== null; return ( - + { }); it("summarizes child threads with a header and total count", () => { - const markup = renderToMarkup( + const { container } = render( { /> , ); + const markup = container.innerHTML; expect(markup).toContain('aria-label="Child threads"'); expect(markup).toContain('aria-label="1 active child thread"'); @@ -359,7 +358,10 @@ describe("ThreadPromptContextBanner", () => { expect(markup).toContain(">1<"); expect(markup).toContain('data-icon="ChildThread"'); expect(markup).toContain("animate-shine-icon"); - expect(markup).toMatch(/animate-shine[^"]*font-normal/); + const label = screen.getByText("Active child threads").classList; + expect(label.contains("animate-shine")).toBe(true); + expect(label.contains("font-normal")).toBe(true); + expect(label.contains("font-medium")).toBe(false); }); it("lists child threads with needs-input and working glyphs when expanded", () => { diff --git a/apps/app/src/components/sidebar/PluginThreadList.hidden.test.tsx b/apps/app/src/components/sidebar/PluginThreadList.hidden.test.tsx new file mode 100644 index 00000000000..db78675ebeb --- /dev/null +++ b/apps/app/src/components/sidebar/PluginThreadList.hidden.test.tsx @@ -0,0 +1,87 @@ +// @vitest-environment jsdom + +import { act, cleanup, render } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { setPluginSlotRegistrations } from "@/lib/plugin-slots"; +import { CORE_THREAD_ACTIONS } from "@/lib/thread-actions/core-thread-actions"; +import { + resetThreadActionRegistryForTest, + ThreadActionCollectors, + ThreadActionSurfaceVisibility, +} from "@/lib/thread-actions/thread-action-registry"; +import { makePluginRegistrationSet } from "@/test/fixtures/plugins"; +import { + loadPluginThreadListReplacement, + seedSidebarQueryClient, + SidebarThreadListHarness, + stubPluginRpcFetch, +} from "@/test/fixtures/sidebar-thread-list"; +import { PluginThreadList } from "./PluginThreadList"; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + resetThreadActionRegistryForTest(); +}); + +class InertObserver { + observe() {} + unobserve() {} + disconnect() {} + takeRecords() { + return []; + } +} + +it("a hidden plugin thread list mounts no rows and subscribes no thread ids", async () => { + resetThreadActionRegistryForTest(); + stubPluginRpcFetch((method) => ({ + result: method === "listPreferences" ? { preferences: {} } : null, + })); + vi.stubGlobal("IntersectionObserver", InertObserver); + vi.stubGlobal("ResizeObserver", InertObserver); + const replacement = await loadPluginThreadListReplacement({ + withNotifications: false, + }); + const seen: (readonly string[])[] = []; + setPluginSlotRegistrations( + "recorder", + makePluginRegistrationSet({ + threadActions: [ + { + id: "recorder", + title: "Recorder", + icon: "Notification", + group: "9_test", + useData: ({ threadIds }) => { + if (seen.at(-1) !== threadIds) seen.push(threadIds); + return null; + }, + item: () => null, + }, + ], + }), + ); + const rendered = render( + + {}} + /> + + {}} /> + + , + ); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 300)); + }); + expect( + rendered.container.querySelectorAll("[data-sidebar-windowed-item]").length, + ).toBeGreaterThan(100); + expect( + rendered.container.querySelectorAll("[data-sidebar-thread-id]"), + ).toHaveLength(0); + expect(seen.length).toBeGreaterThan(0); + expect(seen.every((ids) => ids.length === 0)).toBe(true); +}); diff --git a/apps/app/src/components/sidebar/sidebar.bench.test.tsx b/apps/app/src/components/sidebar/sidebar.bench.test.tsx index 9be730e9a89..0e88b819a8b 100644 --- a/apps/app/src/components/sidebar/sidebar.bench.test.tsx +++ b/apps/app/src/components/sidebar/sidebar.bench.test.tsx @@ -1,61 +1,27 @@ // @vitest-environment jsdom import { writeFileSync } from "node:fs"; -import { resolve } from "node:path"; import { act, cleanup, render } from "@testing-library/react"; import type { ReactNode } from "react"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { MemoryRouter } from "react-router-dom"; -import { TooltipProvider } from "@bb/shared-ui/tooltip"; -import { createStore, Provider as JotaiProvider } from "jotai"; +import type { QueryClient } from "@tanstack/react-query"; import { afterEach, describe, expect, it, vi } from "vitest"; import { z } from "zod"; -import { - defaultUiPreferences, - PERSONAL_PROJECT_ID, - UI_PREFERENCE_KEYS, - type ThreadListEntry, - type ThreadStatus, -} from "@bb/domain"; +import type { ThreadListEntry } from "@bb/domain"; import type { SidebarBootstrapResponse } from "@bb/server-contract"; -import { - makeHost, - makeThreadListEntry, -} from "@bb/test-helpers/domain-fixtures"; -import { makeProjectWithThreadsResponse } from "@/test/fixtures/projects"; -import { - hostsQueryKey, - sidebarNavigationQueryKey, - uiPreferencesQueryKey, -} from "@/hooks/queries/query-keys"; +import { sidebarNavigationQueryKey } from "@/hooks/queries/query-keys"; import { updateCachedThreadListStatusState } from "@/hooks/cache-owners/query-cache"; -import { - Sidebar, - SidebarContent, - SidebarProvider, -} from "@/components/ui/sidebar"; -import { isPluginAppDefinition } from "@/lib/plugin-app-definition"; -import { installPluginRuntime } from "@/lib/plugin-frontend"; -import type { ResolvedReplacement } from "@/lib/plugin-slot-resolvers"; -import { - setPluginSlotRegistrations, - type PluginThreadListSlot, -} from "@/lib/plugin-slots"; import { CORE_THREAD_ACTIONS } from "@/lib/thread-actions/core-thread-actions"; +import { ThreadActionCollectors } from "@/lib/thread-actions/thread-action-registry"; import { - resetThreadActionRegistryForTest, - ThreadActionCollectors, - ThreadActionSurfaceVisibility, -} from "@/lib/thread-actions/thread-action-registry"; -import { makePluginRegistrationSet } from "@/test/fixtures/plugins"; -import { collectPluginAppRegistrations } from "@get-bb/plugin-sdk/internal/plugin-app-collector"; + loadPluginThreadListReplacement, + seedSidebarQueryClient, + SidebarThreadListHarness, + stubPluginRpcFetch, +} from "@/test/fixtures/sidebar-thread-list"; import { PluginThreadList } from "./PluginThreadList"; -import { SidebarThreadEntriesTestProvider } from "@/test/sidebarThreadEntriesTestProvider"; const BENCH_ENABLED = process.env.BB_SIDEBAR_BENCH === "1"; const THREAD_COUNT = Number(process.env.BB_SIDEBAR_BENCH_THREADS ?? 3000); -const PROJECT_COUNT = 40; -const SECTION_COUNT = 8; const ITERATIONS = 5; function rejectingSdk(path = "sdk"): unknown { @@ -85,67 +51,6 @@ vi.mock("@/lib/ws", () => ({ const notificationListRequests: string[][] = []; -function stubPluginRpcFetch(): void { - vi.stubGlobal( - "fetch", - async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - if (!url.includes("/rpc/")) { - return new Response("{}", { status: 404 }); - } - const method = url.split("/rpc/")[1] ?? ""; - let result: unknown = null; - if (method === "listPreferences") { - result = { preferences: {} }; - } else if (method === "threadNotifications.list") { - const { threadIds } = z - .object({ threadIds: z.array(z.string()) }) - .parse(JSON.parse(String(init?.body))); - notificationListRequests.push(threadIds); - result = { - threads: Object.fromEntries( - threadIds.flatMap((id) => { - const level = CONFIGURED_NOTIFICATION_LEVELS.get(id); - return level === undefined ? [] : [[id, level]]; - }), - ), - }; - } else if (method === "threadNotifications.keyed") { - const { keys } = z - .object({ keys: z.array(z.string()) }) - .parse(JSON.parse(String(init?.body))); - notificationListRequests.push(keys); - result = Object.fromEntries( - keys.map((id) => [ - id, - CONFIGURED_NOTIFICATION_LEVELS.get(id) ?? { - own: "inherit", - ancestorCap: null, - }, - ]), - ); - } else if (method === "setPreference" || method === "resetPreference") { - result = JSON.parse(String(init?.body ?? "{}")); - } - return new Response( - JSON.stringify({ - ok: true, - result, - keyTags: Object.fromEntries( - notificationListRequests - .at(-1) - ?.map((id) => [id, [`thread:${id}`]]) ?? [], - ), - }), - { - status: 200, - headers: { "content-type": "application/json" }, - }, - ); - }, - ); -} - const CONFIGURED_NOTIFICATION_LEVELS = new Map( Array.from({ length: 100 }, (_, index) => [ `thr_${index * 13}`, @@ -153,42 +58,49 @@ const CONFIGURED_NOTIFICATION_LEVELS = new Map( ]), ); -async function loadPluginAppThreadActions(pluginId: string) { - installPluginRuntime(); - const module: { default?: unknown } = await import( - /* @vite-ignore */ resolve( - __dirname, - `../../../../../plugins/${pluginId}/app.tsx`, - ) - ); - if (!isPluginAppDefinition(module.default)) { - throw new Error(`${pluginId}'s app.tsx exports no plugin app definition`); - } - const collected = collectPluginAppRegistrations(module.default); - setPluginSlotRegistrations( - pluginId, - makePluginRegistrationSet({ threadActions: collected.threadActions }), - ); - return collected; -} - -async function loadPluginThreadListReplacement({ - withNotifications, -}: { - withNotifications: boolean; -}): Promise> { - if (withNotifications) { - await loadPluginAppThreadActions("push-notifications"); - } - const collected = await loadPluginAppThreadActions("thread-list"); - const registration = collected.threadLists[0]; - if (registration === undefined) { - throw new Error("thread-list plugin registered no thread list"); - } - return { - kind: "plugin", - registration: { ...registration, pluginId: "thread-list", generation: 1 }, - }; +function stubNotificationRpcFetch(): void { + stubPluginRpcFetch((method, body) => { + let result: unknown = null; + if (method === "listPreferences") { + result = { preferences: {} }; + } else if (method === "threadNotifications.list") { + const { threadIds } = z + .object({ threadIds: z.array(z.string()) }) + .parse(JSON.parse(body)); + notificationListRequests.push(threadIds); + result = { + threads: Object.fromEntries( + threadIds.flatMap((id) => { + const level = CONFIGURED_NOTIFICATION_LEVELS.get(id); + return level === undefined ? [] : [[id, level]]; + }), + ), + }; + } else if (method === "threadNotifications.keyed") { + const { keys } = z + .object({ keys: z.array(z.string()) }) + .parse(JSON.parse(body)); + notificationListRequests.push(keys); + result = Object.fromEntries( + keys.map((id) => [ + id, + CONFIGURED_NOTIFICATION_LEVELS.get(id) ?? { + own: "inherit", + ancestorCap: null, + }, + ]), + ); + } else if (method === "setPreference" || method === "resetPreference") { + result = JSON.parse(body); + } + return { + result, + keyTags: Object.fromEntries( + notificationListRequests.at(-1)?.map((id) => [id, [`thread:${id}`]]) ?? + [], + ), + }; + }); } vi.mock("@/hooks/useLocalPathPicker", () => ({ @@ -214,72 +126,6 @@ vi.mock("@/components/thread/ThreadActionsProvider", () => ({ }), })); -const STATUSES: ThreadStatus[] = ["idle", "active", "idle", "idle", "error"]; - -function buildBootstrap(threadCount: number): SidebarBootstrapResponse { - const sections = Array.from({ length: SECTION_COUNT }, (_, index) => ({ - id: `sec_${index}`, - name: `Section ${index}`, - createdAt: index, - updatedAt: index, - })); - const projects = Array.from({ length: PROJECT_COUNT }, (_, index) => - makeProjectWithThreadsResponse({ - id: `proj_${index}`, - name: `Project ${index}`, - threads: [], - }), - ); - const personalProject = makeProjectWithThreadsResponse({ - id: PERSONAL_PROJECT_ID, - name: "Personal", - threads: [], - }); - const roots: ThreadListEntry[] = []; - for (let index = 0; index < threadCount; index += 1) { - const projectIndex = index % (PROJECT_COUNT + 1); - const project = - projectIndex === PROJECT_COUNT - ? personalProject - : projects[projectIndex]!; - const isChild = index % 10 === 9 && roots.length > 0; - const parent = isChild ? roots[roots.length - 1]! : null; - const status = STATUSES[index % STATUSES.length]!; - const thread = makeThreadListEntry({ - id: `thr_${index}`, - projectId: parent?.projectId ?? project.id, - title: `Thread ${index} about @project:${project.id}`, - titleFallback: `Thread ${index}`, - parentThreadId: parent?.id ?? null, - sectionId: - parent === null && index % 2 === 0 - ? `sec_${index % SECTION_COUNT}` - : null, - pinnedAt: parent === null && index % 150 === 0 ? 1_000 + index : null, - status, - runtime: { displayStatus: status }, - createdAt: 1_000_000 - index, - updatedAt: 2_000_000 - index, - latestAttentionAt: 2_000_000 - index, - lastReadAt: index % 3 === 0 ? null : 3_000_000, - environmentId: `env_${index % 200}`, - environmentHostId: "host_test", - environmentName: `env ${index % 200}`, - environmentBranchName: `feature/${index % 200}`, - environmentIsWorktree: index % 4 !== 0, - environmentWorkspaceDisplayKind: - index % 4 !== 0 ? "managed-worktree" : "other", - }); - if (parent === null) roots.push(thread); - const target = - thread.projectId === PERSONAL_PROJECT_ID - ? personalProject - : projects.find((candidate) => candidate.id === thread.projectId)!; - target.threads.push(thread); - } - return { sections, projects, personalProject }; -} - function median(samples: number[]): number { const sorted = [...samples].sort((a, b) => a - b); return sorted[Math.floor(sorted.length / 2)] ?? 0; @@ -376,54 +222,18 @@ interface BenchResults { queryObserversPerRow: number; } -function seedQueryClient(threadCount = THREAD_COUNT): QueryClient { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false, gcTime: Infinity } }, - }); - queryClient.setQueryData( - sidebarNavigationQueryKey(), - buildBootstrap(threadCount), - ); - queryClient.setQueryData(uiPreferencesQueryKey(), { - preferences: Object.fromEntries( - UI_PREFERENCE_KEYS.map((key) => [ - key, - { revision: 1, value: defaultUiPreferences[key] }, - ]), - ), - }); - queryClient.setQueryData(hostsQueryKey(false), [ - makeHost({ id: "host_test", name: "bee" }), - ]); - return queryClient; -} - async function runScenario( list: string, queryClient: QueryClient, body: ReactNode, ): Promise { const restoreViewport = installViewport(); - const tree = ( - - - - - - - - {body} - - - - - - - - ); - const mountStart = performance.now(); - const rendered = render(tree); + const rendered = render( + + {body} + , + ); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); @@ -551,14 +361,14 @@ describe.skipIf(!BENCH_ENABLED)("sidebar thread list benchmark", () => { `mounts and updates the plugin list with ${THREAD_COUNT} threads`, { timeout: 180_000 }, async () => { - stubPluginRpcFetch(); + stubNotificationRpcFetch(); const replacement = await loadPluginThreadListReplacement({ withNotifications: true, }); collected.push( await runScenario( "plugin", - seedQueryClient(), + seedSidebarQueryClient(THREAD_COUNT), <> { if (out) writeFileSync(out, `${JSON.stringify(collected, null, 2)}\n`); }); }); - -describe("hidden sidebar thread list", () => { - it("mounts no rows and subscribes no thread ids", async () => { - resetThreadActionRegistryForTest(); - stubPluginRpcFetch(); - vi.stubGlobal( - "IntersectionObserver", - class { - observe() {} - unobserve() {} - disconnect() {} - takeRecords() { - return []; - } - }, - ); - vi.stubGlobal( - "ResizeObserver", - class { - observe() {} - unobserve() {} - disconnect() {} - }, - ); - const replacement = await loadPluginThreadListReplacement({ - withNotifications: false, - }); - const seen: (readonly string[])[] = []; - setPluginSlotRegistrations( - "recorder", - makePluginRegistrationSet({ - threadActions: [ - { - id: "recorder", - title: "Recorder", - icon: "Notification", - group: "9_test", - useData: ({ threadIds }) => { - if (seen.at(-1) !== threadIds) seen.push(threadIds); - return null; - }, - item: () => null, - }, - ], - }), - ); - const rendered = render( - - - - - - - - - {}} - /> - - {}} - /> - - - - - - - - - , - ); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 300)); - }); - expect( - rendered.container.querySelectorAll("[data-sidebar-windowed-item]") - .length, - ).toBeGreaterThan(100); - expect( - rendered.container.querySelectorAll("[data-sidebar-thread-id]"), - ).toHaveLength(0); - expect(seen.every((ids) => ids.length === 0)).toBe(true); - vi.unstubAllGlobals(); - }); -}); diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx index 9c6b109620b..db4c6948c20 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx @@ -1021,11 +1021,9 @@ describe("ThreadTimelineRows actions", () => { return 1; }); vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); - const scrollIntoView = vi.fn(); - Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { - configurable: true, - value: scrollIntoView, - }); + const scrollIntoView = vi + .spyOn(HTMLElement.prototype, "scrollIntoView") + .mockImplementation(() => {}); const { container } = renderWithRouter( { return 1; }); vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); - Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { - configurable: true, - value: vi.fn(), - }); + vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation( + () => {}, + ); const { container } = renderWithRouter( { vi.spyOn(window, "cancelAnimationFrame").mockImplementation((id) => { frames.delete(id); }); - Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { - configurable: true, - value: vi.fn(), - }); + vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation( + () => {}, + ); const view = renderWithRouter( { vi.spyOn(window, "cancelAnimationFrame").mockImplementation((id) => { frames.delete(id); }); - Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { - configurable: true, - value: vi.fn(), - }); + vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation( + () => {}, + ); const onLoadOlderRows = vi.fn(() => page); const { container } = renderWithRouter( , @@ -1253,10 +1248,9 @@ describe("ThreadTimelineRows actions", () => { return 1; }); vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); - Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { - configurable: true, - value: vi.fn(), - }); + vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation( + () => {}, + ); const { container } = renderWithRouter( , @@ -1746,10 +1740,9 @@ describe("ThreadTimelineRows actions", () => { return 1; }); vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); - Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { - configurable: true, - value: vi.fn(), - }); + vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation( + () => {}, + ); const { container } = renderWithRouter( , diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.grid.test.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.grid.test.tsx index 58ce6807eea..1536beb5ae7 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.grid.test.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.grid.test.tsx @@ -1,50 +1,39 @@ -import type { ReactNode } from "react"; -import { renderToStaticMarkup } from "react-dom/server"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { BottomAnchoredScrollBody } from "@/components/ui/bottom-anchored-scroll-body"; - -afterEach(() => { - vi.unstubAllGlobals(); -}); +// @vitest-environment jsdom -function renderBody(scrollOverlay?: ReactNode): string { - return renderToStaticMarkup( - Footer} - maxWidthClassName="max-w-none" - scrollAnchorThreadId="thread-a" - scrollOverlay={scrollOverlay} - > -
row-a
-
, - ); -} +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import { BottomAnchoredScrollBody } from "@/components/ui/bottom-anchored-scroll-body"; -function classTokens(className: string | undefined): string[] { - return className?.split(/\s+/) ?? []; -} +afterEach(cleanup); describe("BottomAnchoredScrollBody grid", () => { it("stacks the scroll port and overlay in one explicit minmax(auto,1fr) row", () => { - vi.stubGlobal("CSS", { supports: () => false }); - const markup = renderBody(); - const grid = markup.match( - /^
/, - ); - const overlay = markup.match( - /
} + maxWidthClassName="max-w-none" + scrollOverlay={} + > +
row-a
+ , ); - const gridTokens = classTokens(grid?.[1]); + const grid = container.firstElementChild; + const viewport = container.querySelector("[data-page-scroll-viewport]"); + const overlay = screen.getByRole("navigation").parentElement; - expect(gridTokens).toContain("grid"); + expect(grid?.classList.contains("grid")).toBe(true); expect( - gridTokens.filter((token) => token.startsWith("grid-rows-")), + [...(grid?.classList ?? [])].filter((token) => + token.startsWith("grid-rows-"), + ), ).toEqual(["grid-rows-[minmax(auto,1fr)]"]); - for (const item of [grid?.[2], overlay?.[1]]) { - expect(classTokens(item)).toEqual( - expect.arrayContaining(["row-start-1", "col-start-1", "min-h-0"]), - ); + for (const item of [viewport, overlay]) { + expect(item?.parentElement).toBe(grid); + for (const token of ["row-start-1", "col-start-1", "min-h-0"]) { + expect(item?.classList.contains(token), token).toBe(true); + } } - expect(classTokens(grid?.[2])).toContain("thread-scrollbar"); + expect(overlay?.hasAttribute("data-scroll-overlay")).toBe(true); + expect(viewport?.classList.contains("thread-scrollbar")).toBe(true); }); }); diff --git a/apps/app/src/components/ui/route-loading-skeleton.test.tsx b/apps/app/src/components/ui/route-loading-skeleton.test.tsx index 8a2cb018516..e23ad94cef8 100644 --- a/apps/app/src/components/ui/route-loading-skeleton.test.tsx +++ b/apps/app/src/components/ui/route-loading-skeleton.test.tsx @@ -1,38 +1,41 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import { describe, expect, it } from "vitest"; +// @vitest-environment jsdom + +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; import { RouteLoadingSkeleton } from "./route-loading-skeleton"; +const STANDALONE_BLEED_CLASSES = ["-mx-4", "-mt-4", "md:-mx-5", "md:-mt-5"]; + +afterEach(() => { + cleanup(); +}); + function renderSkeleton(isBoundedPane: boolean) { - const markup = renderToStaticMarkup( - , - ); - const match = markup.match( - /^
]*data-testid="route-loading-skeleton"[^>]*>
); + const skeleton = screen.getByRole("status", { name: "Loading" }); + const header = skeleton.firstElementChild; + if (header === null) throw new Error("Skeleton header row is missing"); + return { skeleton: skeleton.classList, header: header.classList }; } describe("RouteLoadingSkeleton", () => { it("bleeds through standalone page padding", () => { const { skeleton, header } = renderSkeleton(false); - expect(skeleton).toEqual( - expect.arrayContaining(["-mx-4", "-mt-4", "md:-mx-5", "md:-mt-5"]), - ); - expect(header).toContain("pl-12"); + for (const token of STANDALONE_BLEED_CLASSES) { + expect(skeleton.contains(token), token).toBe(true); + } + expect(header.contains("pl-12")).toBe(true); }); it("keeps bounded-pane placeholders inside their pane", () => { const { skeleton, header } = renderSkeleton(true); - expect(skeleton).toContain("flex"); - for (const token of ["-mx-4", "-mt-4", "md:-mx-5", "md:-mt-5"]) { - expect(skeleton).not.toContain(token); + expect(skeleton.contains("flex")).toBe(true); + for (const token of STANDALONE_BLEED_CLASSES) { + expect(skeleton.contains(token), token).toBe(false); } - expect(header).toContain("px-4"); - expect(header).not.toContain("pl-12"); + expect(header.contains("px-4")).toBe(true); + expect(header.contains("pl-12")).toBe(false); }); }); diff --git a/apps/app/src/components/ui/scroll-to-bottom-button.test.tsx b/apps/app/src/components/ui/scroll-to-bottom-button.test.tsx index 31343ae1b01..4a25b064ec9 100644 --- a/apps/app/src/components/ui/scroll-to-bottom-button.test.tsx +++ b/apps/app/src/components/ui/scroll-to-bottom-button.test.tsx @@ -1,40 +1,44 @@ +// @vitest-environment jsdom + import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { renderToStaticMarkup } from "react-dom/server"; -import { describe, expect, it } from "vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; import { APP_PAGE_HEADER_SURFACE_CLASS } from "@/components/layout/AppPageHeader"; import { ScrollToBottomButton } from "./scroll-to-bottom-button"; +afterEach(() => { + cleanup(); +}); + function renderButton(visible: boolean) { - const markup = renderToStaticMarkup( - {}} />, - ); - const button = markup.match( - /