Skip to content
TypeScript

test(web): chat tests run in a real browser (#20870)

Julius Marmingeb827ca48d728
diff --git a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx
new file mode 100644
index 00000000000..790fb481174
--- /dev/null
+++ b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx
@@ -0,0 +1,154 @@
+import {
+ ASSISTANT_CITATION_MAX_COMMENT_LENGTH,
+ EnvironmentId,
+ MessageId,
+ ThreadId,
+} from "@t3tools/contracts";
+import { act, useState, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
+
+const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
+vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ observeAssistantCitationCommentSource: mocks.observeSource,
+}));
+vi.mock(import("@tanstack/react-router"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useNavigate: () => vi.fn(),
+ Link: (({ children }: { children: ReactNode }) => <a>{children}</a>) as never,
+}));
+
+import { AssistantCitationChip } from "./AssistantCitationChip";
+
+const citation = {
+ version: 1 as const,
+ environmentId: EnvironmentId.make("environment"),
+ threadId: ThreadId.make("thread"),
+ messageId: MessageId.make("source"),
+ text: "hello",
+ start: 0,
+ end: 5,
+ prefix: "",
+ suffix: "",
+};
+
+let root: Root;
+let container: HTMLDivElement;
+let sourceAnchor: AssistantCitationSourceAnchor;
+
+async function mount(onSave = vi.fn(() => true)) {
+ function Composer() {
+ const [open, setOpen] = useState(true);
+ return (
+ <AssistantCitationChip
+ citation={citation}
+ composer
+ commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
+ />
+ );
+ }
+ await act(async () => root.render(<Composer />));
+ return onSave;
+}
+
+const textarea = () =>
+ document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on selected text"]');
+
+async function typeComment(value: string) {
+ const input = textarea()!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
+ input,
+ value,
+ );
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+async function removeSource() {
+ const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
+ await act(async () => onUnavailable());
+}
+
+async function clickButton(label: string) {
+ const button = [...document.querySelectorAll("button")].find(
+ (element) => element.textContent?.trim() === label,
+ );
+ expect(button, `button ${label}`).toBeDefined();
+ await act(async () => button!.click());
+}
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
+ mocks.dispose.mockClear();
+ const source = document.createElement("p");
+ source.textContent = "hello";
+ document.body.append(source);
+ const range = document.createRange();
+ range.selectNodeContents(source);
+ sourceAnchor = { source, range, viewport: document.body } as AssistantCitationSourceAnchor;
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+});
+
+describe("citation comment source disappearance", () => {
+ it("preserves an over-length draft at the composer until it can be shortened and saved", async () => {
+ const onSave = await mount();
+ const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
+ await typeComment(draft);
+ await removeSource();
+
+ expect(textarea()?.value).toBe(draft);
+ expect(textarea()?.getAttribute("aria-invalid")).toBe("true");
+ expect(onSave).not.toHaveBeenCalled();
+ expect(mocks.dispose).toHaveBeenCalled();
+ expect(mocks.observeSource).toHaveBeenCalledTimes(1);
+
+ await typeComment("shortened comment");
+ await clickButton("Save");
+ expect(onSave).toHaveBeenCalledWith("shortened comment");
+ expect(textarea()).toBeNull();
+ });
+
+ it("preserves a rejected save and allows a later retry", async () => {
+ const onSave = await mount(vi.fn(() => false));
+ await typeComment("keep this draft");
+ await removeSource();
+
+ expect(onSave).toHaveBeenCalledWith("keep this draft");
+ expect(textarea()?.value).toBe("keep this draft");
+ onSave.mockReturnValue(true);
+ await clickButton("Save");
+ expect(onSave).toHaveBeenLastCalledWith("keep this draft");
+ expect(textarea()).toBeNull();
+ });
+
+ it("still allows explicit cancellation after source disappearance", async () => {
+ const onSave = await mount(vi.fn(() => false));
+ await typeComment("discard this draft");
+ await removeSource();
+ onSave.mockClear();
+ await clickButton("Cancel");
+ expect(onSave).not.toHaveBeenCalled();
+ expect(textarea()).toBeNull();
+ });
+
+ it("saves and closes when the source disappears with a valid draft", async () => {
+ const onSave = await mount();
+ await typeComment("saved comment");
+ await removeSource();
+ expect(onSave).toHaveBeenCalledWith("saved comment");
+ expect(textarea()).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/chat/AssistantCitationChip.test.tsx b/apps/web/src/components/chat/AssistantCitationChip.test.tsx
deleted file mode 100644
index 60ab6eae29c..00000000000
--- a/apps/web/src/components/chat/AssistantCitationChip.test.tsx
+++ /dev/null
@@ -1,150 +0,0 @@
-import {
- ASSISTANT_CITATION_MAX_COMMENT_LENGTH,
- EnvironmentId,
- MessageId,
- ThreadId,
-} from "@t3tools/contracts";
-import { act, useState, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
-
-const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
-vi.mock("./AssistantCitationSource", () => ({
- observeAssistantCitationCommentSource: mocks.observeSource,
-}));
-vi.mock("@tanstack/react-router", () => ({
- useNavigate: () => vi.fn(),
- Link: ({ children }: { children: ReactNode }) => <a>{children}</a>,
-}));
-vi.mock("../ui/popover", () => ({
- Popover: ({ children }: { children: ReactNode }) => <>{children}</>,
- PopoverTrigger: ({ children }: { children: ReactNode }) => <button>{children}</button>,
- PopoverPopup: ({ children }: { children: ReactNode }) => <>{children}</>,
-}));
-vi.mock("../ui/button", () => ({
- Button: (props: React.ComponentProps<"button">) => <button {...props} />,
-}));
-
-import { PopoverPopup } from "../ui/popover";
-import { AssistantCitationChip } from "./AssistantCitationChip";
-
-const citation = {
- version: 1 as const,
- environmentId: EnvironmentId.make("environment"),
- threadId: ThreadId.make("thread"),
- messageId: MessageId.make("source"),
- text: "hello",
- start: 0,
- end: 5,
- prefix: "",
- suffix: "",
-};
-const sourceAnchor = {
- source: {},
- range: {},
- viewport: {},
-} as AssistantCitationSourceAnchor;
-
-let renderer: ReactTestRenderer;
-
-function mount(onSave = vi.fn(() => true)) {
- function Composer() {
- const [open, setOpen] = useState(true);
- return (
- <AssistantCitationChip
- citation={citation}
- composer
- commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
- />
- );
- }
- act(() => {
- renderer = create(<Composer />);
- });
- return onSave;
-}
-
-function typeComment(value: string) {
- act(() => renderer.root.findByType("textarea").props.onChange({ currentTarget: { value } }));
-}
-
-function removeSource() {
- const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
- act(() => onUnavailable());
-}
-
-function clickButton(label: string) {
- act(() =>
- renderer.root
- .findAllByType("button")
- .find((button) => button.props.children === label)!
- .props.onClick(),
- );
-}
-
-beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
- mocks.dispose.mockClear();
-});
-
-afterEach(() => {
- act(() => renderer?.unmount());
- vi.unstubAllGlobals();
-});
-
-describe("citation comment source disappearance", () => {
- it("preserves an over-length draft at the composer until it can be shortened and saved", () => {
- const onSave = mount();
- const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
- typeComment(draft);
- removeSource();
-
- expect(renderer.root.findByType("textarea").props.value).toBe(draft);
- expect(renderer.root.findByType("textarea").props["aria-invalid"]).toBe(true);
- expect(renderer.root.findByType(PopoverPopup).props.anchor).toBeUndefined();
- expect(renderer.root.findByType(PopoverPopup).props.side).toBe("top");
- expect(onSave).not.toHaveBeenCalled();
- expect(mocks.dispose).toHaveBeenCalled();
- expect(mocks.observeSource).toHaveBeenCalledTimes(1);
-
- typeComment("shortened comment");
- clickButton("Save");
- expect(onSave).toHaveBeenCalledWith("shortened comment");
- expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
- });
-
- it("preserves a rejected save and allows a later retry", () => {
- const onSave = mount(vi.fn(() => false));
- typeComment("keep this draft");
- removeSource();
-
- expect(onSave).toHaveBeenCalledWith("keep this draft");
- expect(renderer.root.findByType("textarea").props.value).toBe("keep this draft");
- expect(renderer.root.findByType(PopoverPopup).props.anchor).toBeUndefined();
- onSave.mockReturnValue(true);
- clickButton("Save");
- expect(onSave).toHaveBeenLastCalledWith("keep this draft");
- expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
- });
-
- it("still allows explicit cancellation after source disappearance", () => {
- const onSave = mount(vi.fn(() => false));
- typeComment("discard this draft");
- removeSource();
- onSave.mockClear();
- clickButton("Cancel");
- expect(onSave).not.toHaveBeenCalled();
- expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
- });
-
- it("saves and closes when the source disappears with a valid draft", () => {
- const onSave = mount();
- typeComment("saved comment");
- removeSource();
- expect(onSave).toHaveBeenCalledWith("saved comment");
- expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
- });
-});
diff --git a/apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx
new file mode 100644
index 00000000000..2b84755ece9
--- /dev/null
+++ b/apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx
@@ -0,0 +1,162 @@
+import { RunId } from "@t3tools/contracts";
+import { act, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import type { TurnDiffFileChange } from "../../types";
+import { ChangedFilesCard, ChangedFilesTree } from "./ChangedFilesTree";
+
+let root: Root;
+let container: HTMLDivElement;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+async function render(node: ReactNode) {
+ await act(async () => root.render(node));
+}
+
+function file(path: string, additions = 1, deletions = 0): TurnDiffFileChange {
+ return { path, kind: "modified", additions, deletions };
+}
+
+const text = () => container.textContent ?? "";
+
+function buttonWithText(label: string) {
+ const button = [...container.querySelectorAll("button")].find((element) =>
+ element.textContent?.includes(label),
+ );
+ expect(button, `button ${label}`).toBeDefined();
+ return button!;
+}
+
+describe("ChangedFilesCard", () => {
+ it("summarizes a single file with a singular label", async () => {
+ await render(
+ <ChangedFilesCard
+ runId={RunId.make("run-1")}
+ files={[file("README.md", 2, 1)]}
+ allDirectoriesExpanded
+ resolvedTheme="light"
+ onToggleAllDirectories={() => {}}
+ onOpenTurnDiff={() => {}}
+ />,
+ );
+
+ expect(text()).toContain("1 changed file");
+ expect(text()).not.toContain("1 changed files");
+ });
+
+ it("shows collapsed folders and root files together, and opens a folder on click", async () => {
+ const onOpenTurnDiff = vi.fn();
+ await render(
+ <ChangedFilesCard
+ runId={RunId.make("run-1")}
+ files={[
+ file("apps/web/src/App.tsx", 120, 20),
+ file("apps/web/src/App.test.tsx", 30, 2),
+ file("packages/shared/src/git.ts", 15, 4),
+ file("README.md", 3),
+ ]}
+ allDirectoriesExpanded={false}
+ resolvedTheme="light"
+ onToggleAllDirectories={() => {}}
+ onOpenTurnDiff={onOpenTurnDiff}
+ />,
+ );
+
+ expect(text()).toContain("apps/web/src");
+ expect(text()).toContain("packages/shared/src");
+ expect(text()).toContain("README.md");
+ expect(text()).not.toContain("App.tsx");
+ expect(text()).not.toContain("git.ts");
+
+ await act(async () => buttonWithText("apps/web/src").click());
+ expect(text()).toContain("App.tsx");
+ expect(text()).toContain("App.test.tsx");
+ expect(text()).not.toContain("git.ts");
+
+ await act(async () => buttonWithText("App.test.tsx").click());
+ expect(onOpenTurnDiff).toHaveBeenCalledWith(RunId.make("run-1"), "apps/web/src/App.test.tsx");
+ });
+});
+
+describe("ChangedFilesTree", () => {
+ const cases = [
+ {
+ name: "a compacted single-chain directory",
+ files: [file("apps/web/src/index.ts"), file("apps/web/src/main.ts")],
+ collapsed: ["apps/web/src"],
+ expanded: ["apps/web/src", "index.ts", "main.ts"],
+ },
+ {
+ name: "a branch point after a compacted prefix",
+ files: [
+ file("apps/server/src/git/Layers/GitCore.ts"),
+ file("apps/server/src/provider/Layers/CodexAdapter.ts"),
+ ],
+ collapsed: ["apps/server/src"],
+ expanded: [
+ "apps/server/src",
+ "git/Layers",
+ "provider/Layers",
+ "GitCore.ts",
+ "CodexAdapter.ts",
+ ],
+ },
+ {
+ name: "mixed root files and nested compacted directories",
+ files: [
+ file("README.md"),
+ file("packages/shared/src/git.ts"),
+ file("packages/contracts/src/orchestration.ts"),
+ ],
+ collapsed: ["README.md", "packages"],
+ expanded: [
+ "README.md",
+ "packages",
+ "shared/src",
+ "contracts/src",
+ "git.ts",
+ "orchestration.ts",
+ ],
+ },
+ ];
+
+ it.each(cases)(
+ "follows collapse-all and expand-all for $name",
+ async ({ files, collapsed, expanded }) => {
+ const tree = (allDirectoriesExpanded: boolean) => (
+ <ChangedFilesTree
+ runId={RunId.make("turn-1")}
+ files={files}
+ allDirectoriesExpanded={allDirectoriesExpanded}
+ resolvedTheme="light"
+ onOpenTurnDiff={() => {}}
+ />
+ );
+ await render(tree(false));
+ const visibleWhenCollapsed = [...container.querySelectorAll("button")].map((button) =>
+ button.textContent?.trim(),
+ );
+ for (const label of expanded) {
+ expect(visibleWhenCollapsed.some((value) => value?.startsWith(label))).toBe(
+ collapsed.includes(label),
+ );
+ }
+
+ await render(tree(true));
+ for (const label of expanded) expect(text()).toContain(label);
+ },
+ );
+});
diff --git a/apps/web/src/components/chat/ChangedFilesTree.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.test.tsx
deleted file mode 100644
index 77e549c53e2..00000000000
--- a/apps/web/src/components/chat/ChangedFilesTree.test.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-import { RunId } from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vite-plus/test";
-
-import { ChangedFilesCard, ChangedFilesTree } from "./ChangedFilesTree";
-
-describe("ChangedFilesCard", () => {
- it("keeps its compact header sticky while preserving singular labels", () => {
- const markup = renderToStaticMarkup(
- <ChangedFilesCard
- runId={RunId.make("run-1")}
- files={[{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }]}
- allDirectoriesExpanded
- resolvedTheme="light"
- onToggleAllDirectories={() => {}}
- onOpenTurnDiff={() => {}}
- />,
- );
-
- expect(markup).toContain('data-changed-files-state="tree"');
- expect(markup).toContain('aria-label="Open diff"');
- expect(markup).toContain('role="group" aria-label="2 additions, 1 deletions"');
- expect(markup).toContain("1 changed file");
- expect(markup).not.toContain("1 changed files");
- });
-
- it("shows collapsed folders and root files together", () => {
- const markup = renderToStaticMarkup(
- <ChangedFilesCard
- runId={RunId.make("run-1")}
- files={[
- { path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 },
- { path: "apps/web/src/App.test.tsx", kind: "modified", additions: 30, deletions: 2 },
- {
- path: "packages/shared/src/git.ts",
- kind: "modified",
- additions: 15,
- deletions: 4,
- },
- { path: "README.md", kind: "modified", additions: 3, deletions: 0 },
- ]}
- allDirectoriesExpanded={false}
- resolvedTheme="light"
- onToggleAllDirectories={() => {}}
- onOpenTurnDiff={() => {}}
- />,
- );
-
- expect(markup).toContain('data-changed-files-state="tree"');
- expect(markup).toContain('aria-expanded="false"');
- expect(markup).toContain("apps/web/src");
- expect(markup).not.toContain("App.tsx");
- expect(markup).toContain("packages/shared/src");
- expect(markup).not.toContain("git.ts");
- expect(markup).toContain("README.md");
- expect(markup).not.toContain("Show all");
- expect(markup).not.toContain("App.test.tsx");
- });
-
- it("keeps the folder tree visible when folders are collapsed", () => {
- const markup = renderToStaticMarkup(
- <ChangedFilesCard
- runId={RunId.make("run-1")}
- files={[{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 }]}
- allDirectoriesExpanded={false}
- resolvedTheme="light"
- onToggleAllDirectories={() => {}}
- onOpenTurnDiff={() => {}}
- />,
- );
-
- expect(markup).toContain('data-changed-files-state="tree"');
- expect(markup).toContain("1 changed file");
- expect(markup).toContain("apps/web/src");
- expect(markup).not.toContain("Show all");
- expect(markup).not.toContain("App.tsx");
- });
-});
-
-describe("ChangedFilesTree", () => {
- it.each([
- {
- name: "a compacted single-chain directory",
- files: [
- { path: "apps/web/src/index.ts", kind: "modified", additions: 2, deletions: 1 },
- { path: "apps/web/src/main.ts", kind: "modified", additions: 3, deletions: 0 },
- ],
- visibleLabels: ["apps/web/src"],
- hiddenLabels: ["index.ts", "main.ts"],
- },
- {
- name: "a branch point after a compacted prefix",
- files: [
- {
- path: "apps/server/src/git/Layers/GitCore.ts",
- kind: "modified",
- additions: 4,
- deletions: 3,
- },
- {
- path: "apps/server/src/provider/Layers/CodexAdapter.ts",
- kind: "modified",
- additions: 7,
- deletions: 2,
- },
- ],
- visibleLabels: ["apps/server/src"],
- hiddenLabels: ["git", "provider", "GitCore.ts", "CodexAdapter.ts"],
- },
- {
- name: "mixed root files and nested compacted directories",
- files: [
- { path: "README.md", kind: "modified", additions: 1, deletions: 0 },
- { path: "packages/shared/src/git.ts", kind: "modified", additions: 8, deletions: 2 },
- {
- path: "packages/contracts/src/orchestration.ts",
- kind: "modified",
- additions: 13,
- deletions: 3,
- },
- ],
- visibleLabels: ["README.md", "packages"],
- hiddenLabels: ["shared/src", "contracts/src", "git.ts", "orchestration.ts"],
- },
- ])(
- "renders $name collapsed on the first render when collapse-all is active",
- ({ files, visibleLabels, hiddenLabels }) => {
- const markup = renderToStaticMarkup(
- <ChangedFilesTree
- runId={RunId.make("turn-1")}
- files={files}
- allDirectoriesExpanded={false}
- resolvedTheme="light"
- onOpenTurnDiff={() => {}}
- />,
- );
-
- for (const label of visibleLabels) {
- expect(markup).toContain(label);
- }
- for (const label of hiddenLabels) {
- expect(markup).not.toContain(label);
- }
- },
- );
-
- it.each([
- {
- name: "a compacted single-chain directory",
- files: [
- { path: "apps/web/src/index.ts", kind: "modified", additions: 2, deletions: 1 },
- { path: "apps/web/src/main.ts", kind: "modified", additions: 3, deletions: 0 },
- ],
- visibleLabels: ["apps/web/src", "index.ts", "main.ts"],
- },
- {
- name: "a branch point after a compacted prefix",
- files: [
- {
- path: "apps/server/src/git/Layers/GitCore.ts",
- kind: "modified",
- additions: 4,
- deletions: 3,
- },
- {
- path: "apps/server/src/provider/Layers/CodexAdapter.ts",
- kind: "modified",
- additions: 7,
- deletions: 2,
- },
- ],
- visibleLabels: [
- "apps/server/src",
- "git/Layers",
- "provider/Layers",
- "GitCore.ts",
- "CodexAdapter.ts",
- ],
- },
- {
- name: "mixed root files and nested compacted directories",
- files: [
- { path: "README.md", kind: "modified", additions: 1, deletions: 0 },
- { path: "packages/shared/src/git.ts", kind: "modified", additions: 8, deletions: 2 },
- {
- path: "packages/contracts/src/orchestration.ts",
- kind: "modified",
- additions: 13,
- deletions: 3,
- },
- ],
- visibleLabels: [
- "README.md",
- "packages",
- "shared/src",
- "contracts/src",
- "git.ts",
- "orchestration.ts",
- ],
- },
- ])(
- "renders $name expanded on the first render when expand-all is active",
- ({ files, visibleLabels }) => {
- const markup = renderToStaticMarkup(
- <ChangedFilesTree
- runId={RunId.make("turn-1")}
- files={files}
- allDirectoriesExpanded
- resolvedTheme="light"
- onOpenTurnDiff={() => {}}
- />,
- );
-
- for (const label of visibleLabels) {
- expect(markup).toContain(label);
- }
- },
- );
-});
diff --git a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
new file mode 100644
index 00000000000..887f61abcbe
--- /dev/null
+++ b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
@@ -0,0 +1,60 @@
+import "../../index.css";
+
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+import { ComposerBannerStack } from "./ComposerBannerStack";
+
+let root: Root;
+let container: HTMLDivElement;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+const nextFrame = () =>
+ act(() => new Promise<void>((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0))));
+
+async function render(width: number, description: string) {
+ container.style.width = `${width}px`;
+ await act(async () =>
+ root.render(
+ <ComposerBannerStack
+ items={[{ id: "usage", variant: "info", icon: null, title: "Usage limits", description }]}
+ />,
+ ),
+ );
+ await nextFrame();
+}
+
+const hasDetails = () => container.querySelector('[aria-label="Show notice details"]') !== null;
+
+it("only offers notice details when the description cannot fit", async () => {
+ await render(700, "OpenCode");
+ expect(hasDetails()).toBe(false);
+
+ await render(700, "OpenCode ".repeat(40));
+ expect(hasDetails()).toBe(true);
+
+ container.style.width = "4000px";
+ await nextFrame();
+ expect(hasDetails()).toBe(false);
+
+ await render(4000, "OpenCode");
+ expect(hasDetails()).toBe(false);
+
+ // A narrow composer hides the description entirely, so details are the only way to read it.
+ container.style.width = "300px";
+ await nextFrame();
+ expect(hasDetails()).toBe(true);
+});
diff --git a/apps/web/src/components/chat/ComposerBannerStack.test.tsx b/apps/web/src/components/chat/ComposerBannerStack.test.tsx
deleted file mode 100644
index e567a3bf769..00000000000
--- a/apps/web/src/components/chat/ComposerBannerStack.test.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { cloneElement, type ReactElement, type ReactNode } from "react";
-import { act, create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, expect, it, vi } from "vite-plus/test";
-
-import { ComposerBannerStack } from "./ComposerBannerStack";
-
-vi.mock("../ui/popover", () => ({
- Popover: "popover",
- PopoverTrigger: ({ render, children }: { render: ReactElement; children: ReactNode }) =>
- cloneElement(render, {}, children),
- PopoverPopup: "popup",
-}));
-vi.mock("../ui/button", () => ({ Button: "button" }));
-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
-
-let renderer: ReactTestRenderer;
-afterEach(async () => {
- if (renderer) await act(() => renderer.unmount());
- vi.unstubAllGlobals();
-});
-
-it("only offers notice details when the description cannot fit", async () => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- let resize = () => {};
- let mutate = () => {};
- vi.stubGlobal(
- "MutationObserver",
- class {
- constructor(callback: () => void) {
- mutate = callback;
- }
- observe() {}
- disconnect() {}
- },
- );
- vi.stubGlobal(
- "ResizeObserver",
- class {
- constructor(private readonly callback: (entries: { target: unknown }[]) => void) {}
- observe(target: unknown) {
- resize = () => this.callback([{ target }]);
- }
- disconnect() {}
- },
- );
- let position = "static";
- vi.stubGlobal("getComputedStyle", () => ({ position }));
- let availableWidth = 200;
- const nested = { clientWidth: 100, scrollWidth: 80 };
- const text = {
- querySelectorAll: () => [nested],
- get clientWidth() {
- return (
- availableWidth -
- (renderer?.root.findAllByProps({ "aria-label": "Show notice details" }).length ? 28 : 0)
- );
- },
- scrollWidth: 80,
- };
- await act(() => {
- renderer = create(
- <ComposerBannerStack
- items={[
- {
- id: "usage",
- variant: "info",
- icon: null,
- title: "Usage limits",
- description: "OpenCode",
- },
- ]}
- />,
- {
- createNodeMock: (element) =>
- element.type === "span" ? text : element.type === "button" ? { offsetWidth: 24 } : null,
- },
- );
- });
- const details = () => renderer.root.findAllByProps({ "aria-label": "Show notice details" });
- expect(details()).toHaveLength(0);
- text.scrollWidth = 300;
- await act(() => resize());
- expect(details()).toHaveLength(1);
- availableWidth = 308;
- await act(() => resize());
- expect(details()).toHaveLength(0);
- text.scrollWidth = 80;
- await act(() => resize());
- expect(details()).toHaveLength(0);
- nested.scrollWidth = 500;
- await act(() => mutate());
- expect(details()).toHaveLength(1);
- nested.scrollWidth = 80;
- await act(() => mutate());
- expect(details()).toHaveLength(0);
- position = "absolute";
- await act(() => resize());
- expect(details()).toHaveLength(1);
- position = "static";
- await act(() => resize());
- expect(details()).toHaveLength(0);
-});
diff --git a/apps/web/src/components/chat/ComposerCommandMenu.test.tsx b/apps/web/src/components/chat/ComposerCommandMenu.test.tsx
index d26510ce0ae..574edeb50f0 100644
--- a/apps/web/src/components/chat/ComposerCommandMenu.test.tsx
+++ b/apps/web/src/components/chat/ComposerCommandMenu.test.tsx
@@ -1,8 +1,6 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import { ProviderDriverKind } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { ComposerCommandMenu, composerSuggestionOptionId } from "./ComposerCommandMenu";
+import { composerSuggestionOptionId } from "./ComposerCommandMenu";
describe("composerSuggestionOptionId", () => {
it("keeps whitespace, escape-like paths, and malformed UTF-16 distinct", () => {
@@ -27,102 +25,3 @@ describe("composerSuggestionOptionId", () => {
);
});
});
-
-describe("ComposerCommandMenu", () => {
- it("renders slash commands with their descriptions", () => {
- const markup = renderToStaticMarkup(
- <ComposerCommandMenu
- listId="test-suggestions"
- items={[
- {
- id: "slash:model",
- type: "slash-command",
- command: "model",
- label: "/model",
- description: "Switch response model for this thread",
- },
- ]}
- resolvedTheme="dark"
- isLoading={false}
- triggerKind="slash-command"
- activeItemId="slash:model"
- onHighlightedItemChange={() => {}}
- onSelect={() => {}}
- />,
- );
-
- expect(markup).toContain("/model");
- expect(markup).toContain("Switch response model for this thread");
- });
-
- it("shows the app source for an app skill", () => {
- const markup = renderToStaticMarkup(
- <ComposerCommandMenu
- listId="test-suggestions"
- items={[
- {
- id: "skill:codex:browser",
- type: "skill",
- provider: ProviderDriverKind.make("codex"),
- skill: {
- name: "browser",
- path: "/Users/maria/.codex/plugins/browser/skills/browser/SKILL.md",
- scope: "user",
- enabled: true,
- },
- label: "Browser",
- description: "Open and control the in-app browser",
- },
- ]}
- resolvedTheme="dark"
- isLoading={false}
- triggerKind="skill"
- activeItemId="skill:codex:browser"
- onHighlightedItemChange={() => {}}
- onSelect={() => {}}
- />,
- );
-
- expect(markup).toContain("Browser");
- expect(markup).toContain('data-slot="badge"');
- expect(markup).toContain(">App Skill</span>");
- expect(markup).toContain("Open and control the in-app browser");
- expect(markup).toContain("<svg");
- });
-
- it("shows the repo source for a slash skill", () => {
- const markup = renderToStaticMarkup(
- <ComposerCommandMenu
- listId="test-suggestions"
- items={[
- {
- id: "skill:codex:ask-matt",
- type: "skill",
- provider: ProviderDriverKind.make("codex"),
- skill: {
- name: "ask-matt",
- displayName: "Ask Matt",
- path: "/skills/ask-matt/SKILL.md",
- scope: "repo",
- enabled: true,
- },
- label: "/skill:ask-matt",
- description: "Find the right skill or workflow",
- },
- ]}
- resolvedTheme="dark"
- isLoading={false}
- triggerKind="slash-command"
- activeItemId="skill:codex:ask-matt"
- onHighlightedItemChange={() => {}}
- onSelect={() => {}}
- />,
- );
-
- expect(markup).toContain('<span class="text-secondary-label">/skill:</span>Ask Matt');
- expect(markup).toContain('data-slot="badge"');
- expect(markup).toContain("lucide-folder");
- expect(markup).toContain(">Repo</span>");
- expect(markup).toContain("Find the right skill or workflow");
- });
-});
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.browser.test.tsx
new file mode 100644
index 00000000000..d6cbd23d026
--- /dev/null
+++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.browser.test.tsx
@@ -0,0 +1,84 @@
+import { RuntimeRequestId, type ProviderApprovalOption } from "@t3tools/contracts";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
+
+let root: Root;
+let container: HTMLDivElement;
+const onRespond = vi.fn(async () => undefined);
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ onRespond.mockClear();
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+});
+
+async function render(options?: ReadonlyArray<ProviderApprovalOption>) {
+ await act(async () =>
+ root.render(
+ <ComposerPendingApprovalActions
+ requestId={RuntimeRequestId.make("approval-1")}
+ canRespond
+ isResponding={false}
+ options={options}
+ onRespondToApproval={onRespond}
+ />,
+ ),
+ );
+}
+
+const rowLabels = () =>
+ [...container.querySelectorAll("button")]
+ .map((button) => button.textContent?.trim())
+ .filter(Boolean);
+
+async function openMore() {
+ await act(async () =>
+ container.querySelector<HTMLElement>('[aria-label="More approval options"]')!.click(),
+ );
+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+}
+
+describe("ComposerPendingApprovalActions", () => {
+ it("keeps the main decisions in the row and sends a secondary decision from the menu", async () => {
+ await render();
+ expect(rowLabels()).toEqual(["Decline", "Approve"]);
+
+ const items = await openMore();
+ expect(items.map((item) => item.textContent?.trim())).toEqual([
+ "Cancel",
+ "Always allow this session",
+ ]);
+ await act(async () => items[1]!.click());
+ expect(onRespond).toHaveBeenCalledWith(RuntimeRequestId.make("approval-1"), "acceptForSession");
+ });
+
+ it("keeps provider labels, including secondary ones, where the user can find them", async () => {
+ await render([
+ { decision: "decline", label: "Deny" },
+ { decision: "acceptAlways", label: "Always allow Safari" },
+ { decision: "accept", label: "Allow once" },
+ ]);
+ expect(rowLabels()).toEqual(["Deny", "Allow once"]);
+ expect((await openMore()).map((item) => item.textContent?.trim())).toEqual([
+ "Always allow Safari",
+ ]);
+
+ await act(async () =>
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent?.trim() === "Allow once")!
+ .click(),
+ );
+ expect(onRespond).toHaveBeenCalledWith(RuntimeRequestId.make("approval-1"), "accept");
+ });
+});
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
deleted file mode 100644
index 039f9259ff8..00000000000
--- a/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { RuntimeRequestId } from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vite-plus/test";
-
-import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
-
-describe("ComposerPendingApprovalActions", () => {
- it("keeps the main decisions visible and secondary decisions in the menu", () => {
- const markup = renderToStaticMarkup(
- <ComposerPendingApprovalActions
- requestId={RuntimeRequestId.make("approval-1")}
- canRespond
- isResponding={false}
- onRespondToApproval={async () => undefined}
- />,
- );
-
- expect(markup).toContain(">Decline<");
- expect(markup).toContain(">Approve<");
- expect(markup).not.toContain(">Cancel<");
- expect(markup).not.toContain("Always allow this session");
- });
-
- it("keeps secondary provider labels out of the compact action row", () => {
- const markup = renderToStaticMarkup(
- <ComposerPendingApprovalActions
- requestId={RuntimeRequestId.make("approval-safari")}
- canRespond
- isResponding={false}
- options={[
- { decision: "decline", label: "Decline" },
- { decision: "acceptAlways", label: "Always allow Safari" },
- { decision: "accept", label: "Approve" },
- ]}
- onRespondToApproval={async () => undefined}
- />,
- );
-
- expect(markup).not.toContain("Always allow Safari");
- expect(markup).toContain(">Approve<");
- expect(markup).not.toContain("Always allow this session");
- });
-
- it("preserves provider labels for the main decisions", () => {
- const markup = renderToStaticMarkup(
- <ComposerPendingApprovalActions
- requestId={RuntimeRequestId.make("approval-1")}
- canRespond
- isResponding={false}
- options={[
- { decision: "accept", label: "Allow once" },
- { decision: "decline", label: "Deny" },
- ]}
- onRespondToApproval={async () => undefined}
- />,
- );
-
- expect(markup).toContain("Allow once");
- expect(markup).toContain("Deny");
- expect(markup).not.toContain(">Approve<");
- expect(markup).not.toContain(">Decline<");
- });
-});
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
deleted file mode 100644
index 7170a593d90..00000000000
--- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { RuntimeRequestId } from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vite-plus/test";
-
-import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
-
-describe("ComposerPendingApprovalPanel", () => {
- it("keeps the complete command readable in the compact row", () => {
- const detail = `bun run release -- ${"x".repeat(500)}\nsecond line`;
- const markup = renderToStaticMarkup(
- <ComposerPendingApprovalPanel
- approval={{
- requestId: RuntimeRequestId.make("approval-1"),
- requestKind: "command",
- createdAt: "2026-07-18T00:00:00.000Z",
- detail,
- responseCapability: "live",
- }}
- pendingCount={1}
- />,
- );
-
- expect(markup).toContain(detail);
- expect(markup).not.toContain("Command approval requested");
- });
-
- it("falls back to the approval kind when the provider sends an empty detail", () => {
- const markup = renderToStaticMarkup(
- <ComposerPendingApprovalPanel
- approval={{
- requestId: RuntimeRequestId.make("approval-2"),
- requestKind: "file-read",
- responseCapability: "live" as const,
- createdAt: "2026-07-18T00:00:00.000Z",
- detail: "",
- }}
- pendingCount={1}
- />,
- );
-
- expect(markup).toContain("File read approval");
- });
-
- it("shows the app name and message for an MCP access request", () => {
- const markup = renderToStaticMarkup(
- <ComposerPendingApprovalPanel
- approval={{
- requestId: RuntimeRequestId.make("approval-safari"),
- requestKind: "mcp-elicitation",
- responseCapability: "live" as const,
- createdAt: "2026-08-24T00:00:00.000Z",
- appName: "Safari",
- detail: "Allow ChatGPT to use Safari?",
- }}
- pendingCount={1}
- />,
- );
-
- expect(markup).toContain(">Safari<");
- expect(markup).toContain("Allow ChatGPT to use Safari?");
- });
-
- it("preserves the full app name and approval message", () => {
- const appName = "A".repeat(200);
- const detail = "Allow ChatGPT to access the selected application?";
- const markup = renderToStaticMarkup(
- <ComposerPendingApprovalPanel
- approval={{
- requestId: RuntimeRequestId.make("approval-long-app-name"),
- requestKind: "mcp-elicitation",
- responseCapability: "live" as const,
- createdAt: "2026-08-24T00:00:00.000Z",
- appName,
- detail,
- }}
- pendingCount={1}
- />,
- );
-
- expect(markup).toContain(appName);
- expect(markup).toContain(detail);
- });
-});
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx
similarity index 69%
rename from apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.test.tsx
rename to apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx
index 6e5103d1ec1..5b5893b5ad5 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx
@@ -1,6 +1,6 @@
import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
-import { act, useState, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, useState } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
import {
@@ -8,16 +8,10 @@ import {
type PendingUserInputDraftAnswer,
} from "../../pendingUserInput";
-vi.mock("../ui/collapsible", () => {
- const Children = ({ children }: { children: ReactNode }) => <>{children}</>;
- return {
- Collapsible: Children,
- CollapsiblePanel: Children,
- CollapsibleTrigger: Children,
- };
-});
-
-vi.mock("../ChatMarkdown", () => ({ default: ({ text }: { text: string }) => <p>{text}</p> }));
+vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ default: (({ text }: { text: string }) => <p>{text}</p>) as never,
+}));
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
@@ -72,51 +66,44 @@ function Questions({ initialIndex = 0 }: { initialIndex?: number }) {
);
}
-let renderer: ReactTestRenderer | undefined;
+let root: Root;
+let container: HTMLDivElement;
beforeEach(() => {
vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("window", {
- setTimeout: globalThis.setTimeout,
- clearTimeout: globalThis.clearTimeout,
- });
- vi.stubGlobal("document", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
+ await act(async () => root.unmount());
+ container.remove();
vi.unstubAllGlobals();
vi.useRealTimers();
});
+function buttonWithText(text: string) {
+ const button = [...document.querySelectorAll("button")].find((element) =>
+ element.textContent?.includes(text),
+ );
+ expect(button, `button ${text}`).toBeDefined();
+ return button!;
+}
+
async function chooseOption() {
- await act(async () => {
- renderer!.root
- .findAllByType("button")
- .find((button) =>
- button.findAllByType("span").some((span) => span.children.includes("Incremental")),
- )!
- .props.onClick();
- });
+ await act(async () => buttonWithText("Incremental").click());
}
async function navigate(label: string) {
- await act(async () => {
- renderer!.root
- .findAllByType("button")
- .find((button) => button.children.includes(label))!
- .props.onClick();
- });
+ await act(async () => buttonWithText(label).click());
}
function activeIndex() {
- return renderer!.root.findByType("output").children.join("");
+ return container.querySelector("output")!.textContent;
}
it("does not skip the next unanswered question after manual advance", async () => {
- await act(async () => {
- renderer = create(<Questions />);
- });
+ await act(async () => root.render(<Questions />));
await chooseOption();
await navigate("Next");
expect(activeIndex()).toBe("1");
@@ -129,9 +116,7 @@ it("does not skip the next unanswered question after manual advance", async () =
});
it("does not undo previous-question navigation with a stale timer", async () => {
- await act(async () => {
- renderer = create(<Questions initialIndex={1} />);
- });
+ await act(async () => root.render(<Questions initialIndex={1} />));
await chooseOption();
await navigate("Previous");
await act(async () => vi.advanceTimersByTime(200));
@@ -139,9 +124,7 @@ it("does not undo previous-question navigation with a stale timer", async () =>
});
it("still auto-advances once after the answer draft rerenders the same question", async () => {
- await act(async () => {
- renderer = create(<Questions />);
- });
+ await act(async () => root.render(<Questions />));
await chooseOption();
await act(async () => vi.advanceTimersByTime(200));
expect(activeIndex()).toBe("1");
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.browser.test.tsx
similarity index 61%
rename from apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.test.tsx
rename to apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.browser.test.tsx
index ffffe2a338c..478ac9ed0db 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.browser.test.tsx
@@ -1,18 +1,12 @@
import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
-import { act, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vite-plus/test";
-vi.mock("../ui/collapsible", () => {
- const Children = ({ children }: { children: ReactNode }) => <>{children}</>;
- return {
- Collapsible: Children,
- CollapsiblePanel: Children,
- CollapsibleTrigger: Children,
- };
-});
-
-vi.mock("../ChatMarkdown", () => ({ default: ({ text }: { text: string }) => <p>{text}</p> }));
+vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ default: (({ text }: { text: string }) => <p>{text}</p>) as never,
+}));
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
@@ -21,11 +15,6 @@ const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId
it("cancels an answer's pending auto-submit on revocation and resumes after a new grant", async () => {
vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("window", {
- setTimeout: globalThis.setTimeout,
- clearTimeout: globalThis.clearTimeout,
- });
- vi.stubGlobal("document", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
const onToggleOption = vi.fn();
const onAdvance = vi.fn();
const onDismiss = vi.fn();
@@ -58,25 +47,21 @@ it("cancels an answer's pending auto-submit on revocation and resumes after a ne
onDismiss={onDismiss}
/>
);
- let renderer: ReactTestRenderer | undefined;
- const chooseOption = () => {
- const option = renderer!.root
- .findAllByType("button")
- .find((button) =>
- button.findAllByType("span").some((span) => span.children.includes("Incremental")),
- );
- expect(option).toBeDefined();
- option!.props.onClick();
- };
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ // A disabled button swallows the click, as it would for a user.
+ const chooseOption = () =>
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent?.includes("Incremental"))!
+ .click();
try {
- await act(async () => {
- renderer = create(panel(false));
- });
+ await act(async () => root.render(panel(false)));
await act(async () => chooseOption());
expect(onToggleOption).toHaveBeenCalledWith("approach", "Incremental");
expect(onAdvance).not.toHaveBeenCalled();
- await act(async () => renderer!.update(panel(true)));
+ await act(async () => root.render(panel(true)));
await act(async () => {
chooseOption();
vi.runAllTimers();
@@ -84,7 +69,7 @@ it("cancels an answer's pending auto-submit on revocation and resumes after a ne
expect(onToggleOption).toHaveBeenCalledTimes(1);
expect(onAdvance).not.toHaveBeenCalled();
- await act(async () => renderer!.update(panel(false)));
+ await act(async () => root.render(panel(false)));
await act(async () => {
chooseOption();
vi.runAllTimers();
@@ -92,7 +77,8 @@ it("cancels an answer's pending auto-submit on revocation and resumes after a ne
expect(onToggleOption).toHaveBeenCalledTimes(2);
expect(onAdvance).toHaveBeenCalledTimes(1);
} finally {
- await act(async () => renderer?.unmount());
+ await act(async () => root.unmount());
+ container.remove();
vi.unstubAllGlobals();
vi.useRealTimers();
}
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
deleted file mode 100644
index 377b49d3a6b..00000000000
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vite-plus/test";
-
-import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
-
-const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
-import type { PendingUserInput } from "../../session-logic";
-
-const prompt: PendingUserInput = {
- requestId: RuntimeRequestId.make("request-1"),
- responseCapability: "live" as const,
- createdAt: "2026-08-15T00:00:00.000Z",
- questions: [
- {
- id: "question-1",
- header: "Approach",
- question: "Which approach should the migration take?",
- options: [
- { label: "Incremental", description: "Move one module at a time" },
- { label: "Big bang", description: "Move everything in one release" },
- ],
- multiSelect: false,
- },
- ],
- dismissible: true,
-};
-
-function renderPanel(pendingUserInput: PendingUserInput = prompt) {
- return renderToStaticMarkup(
- <ComposerPendingUserInputPanel
- pendingUserInputs={[pendingUserInput]}
- cwd="/repo"
- threadRef={threadRef}
- respondingRequestIds={[]}
- answers={{}}
- questionIndex={0}
- onToggleOption={() => {}}
- onAdvance={() => {}}
- onDismiss={() => {}}
- />,
- );
-}
-
-describe("ComposerPendingUserInputPanel", () => {
- it("renders the header as a disclosure control for the question body", () => {
- const markup = renderPanel();
-
- const toggle = markup.match(/<button[^>]*data-pending-user-input-toggle="[^"]*"[^>]*>/)?.[0];
- expect(toggle).toBeDefined();
- expect(toggle).toContain('data-pending-user-input-toggle="expanded"');
- expect(toggle).toContain('aria-expanded="true"');
- expect(toggle).toContain('type="button"');
-
- const controlledId = toggle?.match(/aria-controls="([^"]+)"/)?.[1];
- expect(controlledId).toBeDefined();
- expect(markup).toMatch(new RegExp(`<div[^>]*\\sid="${controlledId}"`));
- });
-
- it("offers dismiss only for async questions", () => {
- expect(renderPanel()).toContain("data-pending-user-input-dismiss");
- expect(renderPanel({ ...prompt, dismissible: false })).not.toContain(
- "data-pending-user-input-dismiss",
- );
- });
-
- it("starts expanded so the question and its options are visible", () => {
- const markup = renderPanel();
-
- expect(markup).toContain("Approach");
- expect(markup).toContain("Which approach should the migration take?");
- expect(markup).toContain("Incremental");
- expect(markup).toContain("Big bang");
- });
-
- it("links URLs in the question text", () => {
- const url = "https://accounts.t3.codes/device?user_code=RTJS-TQGS";
- const question = prompt.questions[0]!;
- const markup = renderPanel({
- ...prompt,
- questions: [{ ...question, question: `Authorize BeeBox at ${url} and confirm.` }],
- });
-
- expect(markup).toMatch(new RegExp(`<a[^>]*href="${url.replace(/[?.]/g, "\\$&")}"`));
- });
-});
diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.test.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.test.tsx
deleted file mode 100644
index d951f1e21fe..00000000000
--- a/apps/web/src/components/chat/ComposerPrimaryActions.test.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { createElement } from "react";
-import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, describe, expect, it, vi } from "vite-plus/test";
-
-const stageArtworkState = vi.hoisted(() => ({
- mode: "none" as "artwork" | "none",
- variant: null as "nightly" | "dev" | null,
-}));
-
-vi.mock("~/hooks/useSettings", () => ({
- useEnvironmentIdentificationMode: () => stageArtworkState.mode,
-}));
-vi.mock("../SidebarStageBackdrop", () => ({
- StageBackdropButtonArt: ({ variant }: { variant: string }) => `stage-${variant}`,
- useSidebarStageBackdropVariant: (enabled = true) => (enabled ? stageArtworkState.variant : null),
-}));
-
-import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
-
-function renderPendingActions(isRunning: boolean) {
- return renderToStaticMarkup(
- createElement(ComposerPrimaryActions, {
- compact: true,
- canOperateThread: true,
- pendingAction: {
- questionIndex: 0,
- isLastQuestion: true,
- canAdvance: true,
- isResponding: false,
- isComplete: true,
- },
- isRunning,
- canInterrupt: isRunning,
- showPlanFollowUpPrompt: false,
- promptHasText: false,
- isSendBusy: false,
- sendDisabledReason: null,
- isConnecting: false,
- isEnvironmentUnavailable: false,
- isPreparingWorktree: false,
- hasSendableContent: false,
- onPreviousPendingQuestion: () => {},
- onInterrupt: () => {},
- onImplementPlanInNewThread: () => {},
- }),
- );
-}
-
-function renderSendButton(sendDisabledReason: string | null = null) {
- return renderToStaticMarkup(
- createElement(ComposerPrimaryActions, {
- compact: true,
- canOperateThread: true,
- pendingAction: null,
- isRunning: false,
- canInterrupt: false,
- showPlanFollowUpPrompt: false,
- promptHasText: true,
- isSendBusy: false,
- sendDisabledReason,
- isConnecting: false,
- isEnvironmentUnavailable: false,
- isPreparingWorktree: false,
- hasSendableContent: true,
- onPreviousPendingQuestion: () => {},
- onInterrupt: () => {},
- onImplementPlanInNewThread: () => {},
- }),
- );
-}
-
-afterEach(() => {
- stageArtworkState.mode = "none";
- stageArtworkState.variant = null;
-});
-
-describe("ComposerPrimaryActions", () => {
- it("disables and labels the send button while feedback is uploading", () => {
- const markup = renderSendButton("Sending feedback");
-
- expect(markup).toContain("disabled");
- expect(markup).toContain('aria-label="Sending feedback"');
- });
-
- it("offers Stop generation while a running turn is waiting for user input", () => {
- expect(renderPendingActions(true)).toContain('aria-label="Stop generation"');
- });
-
- it("does not offer Stop generation for a pending request without a running turn", () => {
- expect(renderPendingActions(false)).not.toContain('aria-label="Stop generation"');
- });
-
- it("renders stage artwork inside the send button when artwork identification is active", () => {
- stageArtworkState.mode = "artwork";
- stageArtworkState.variant = "nightly";
-
- const markup = renderSendButton();
-
- expect(markup).toContain("stage-nightly");
- });
-
- it("hides stage artwork when artwork identification is inactive", () => {
- stageArtworkState.variant = "nightly";
-
- const markup = renderSendButton();
-
- expect(markup).not.toContain("stage-nightly");
- });
-});
diff --git a/apps/web/src/components/chat/ComposerStashMenu.test.tsx b/apps/web/src/components/chat/ComposerStashMenu.test.tsx
deleted file mode 100644
index 47b59a7f592..00000000000
--- a/apps/web/src/components/chat/ComposerStashMenu.test.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import { EnvironmentId } from "@t3tools/contracts";
-import { describe, expect, it } from "vite-plus/test";
-
-import { ComposerStashMenu } from "./ComposerStashMenu";
-
-describe("ComposerStashMenu", () => {
- it("shows saved image thumbnails and incomplete image states", () => {
- const markup = renderToStaticMarkup(
- <ComposerStashMenu
- entries={[
- {
- id: "with-images",
- createdAt: new Date(0).toISOString(),
- prompt: "Compare these screenshots",
- attachments: [
- {
- id: "image-one",
- name: "before.png",
- mimeType: "image/png",
- sizeBytes: 128,
- dataUrl: "data:image/png;base64,AA==",
- },
- ],
- droppedImageNames: ["after.png"],
- unreadableImageNames: [],
- pendingImageCount: 0,
- },
- {
- id: "saving-images",
- createdAt: new Date(0).toISOString(),
- prompt: "Save this image",
- attachments: [],
- droppedImageNames: [],
- unreadableImageNames: [],
- pendingImageCount: 1,
- },
- ]}
- stashShortcutLabel="Ctrl+S"
- onRestore={() => {}}
- onDelete={() => {}}
- onClose={() => {}}
- />,
- );
-
- expect(markup).toContain('src="data:image/png;base64,AA=="');
- expect(markup).toContain("1 image dropped");
- expect(markup).toContain("saving 1 image");
- });
-
- it("labels mixed file and image stashes without treating images as files", () => {
- const markup = renderToStaticMarkup(
- <ComposerStashMenu
- entries={[
- {
- id: "mixed-attachments",
- createdAt: new Date(0).toISOString(),
- prompt: "",
- attachments: [
- {
- id: "image-one",
- name: "before.png",
- mimeType: "image/png",
- sizeBytes: 128,
- dataUrl: "data:image/png;base64,AA==",
- },
- ],
- files: [
- {
- id: "file-one",
- name: "report.pdf",
- mimeType: "application/pdf",
- sizeBytes: 42,
- attachmentId: "pending-report-pdf",
- environmentId: EnvironmentId.make("environment-1"),
- },
- ],
- droppedImageNames: [],
- },
- ]}
- stashShortcutLabel={null}
- onRestore={() => {}}
- onDelete={() => {}}
- onClose={() => {}}
- />,
- );
-
- expect(markup).toContain("(2 attachments)");
- expect(markup).not.toContain("(2 files)");
- });
-});
diff --git a/apps/web/src/components/chat/HighlightedCodeLines.browser.test.tsx b/apps/web/src/components/chat/HighlightedCodeLines.browser.test.tsx
new file mode 100644
index 00000000000..b4c1af4bd9e
--- /dev/null
+++ b/apps/web/src/components/chat/HighlightedCodeLines.browser.test.tsx
@@ -0,0 +1,54 @@
+import { getSharedHighlighter } from "@pierre/diffs";
+import { toHtml } from "hast-util-to-html";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vite-plus/test";
+
+import { createIncrementalHighlightedDocument } from "../../lib/incrementalHighlighting";
+import { HighlightedCodeLines } from "./HighlightedCodeLines";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+// React writes inline styles through CSSOM, so normalize Shiki's style strings the same way.
+function normalizedHtml(html: string) {
+ const host = document.createElement("div");
+ host.innerHTML = html;
+ for (const element of host.querySelectorAll<HTMLElement>("*")) {
+ const style = element.style.cssText;
+ const attributes = [...element.attributes].toSorted((a, b) => a.name.localeCompare(b.name));
+ for (const { name } of attributes) element.removeAttribute(name);
+ for (const { name, value } of attributes) element.setAttribute(name, value);
+ if (style) element.style.cssText = style;
+ }
+ return host.innerHTML;
+}
+
+it("streams Shiki HTML into the DOM, keeping finished lines mounted", async () => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ const highlighter = await getSharedHighlighter({
+ langs: ["typescript"],
+ themes: ["pierre-dark", "pierre-light"],
+ preferredHighlighter: "shiki-wasm",
+ });
+ const code =
+ 'const html = "<img src=x onerror=alert(1)>";\n\n/* multi\nline */\n\tconst x = 1;\n';
+ for (const theme of ["pierre-dark", "pierre-light"] as const) {
+ const highlight = createIncrementalHighlightedDocument(highlighter, "typescript", theme);
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ let firstLine: Element | null = null;
+ for (let end = 0; end <= code.length; end++) {
+ const tree = highlight(code.slice(0, end));
+ await act(async () => root.render(<HighlightedCodeLines root={tree} />));
+ expect(normalizedHtml(container.innerHTML)).toBe(normalizedHtml(toHtml(tree)));
+ if (end > code.indexOf("\n")) {
+ firstLine ??= container.querySelector("code > .line");
+ expect(container.querySelector("code > .line")).toBe(firstLine);
+ }
+ }
+ expect(container.querySelector("img")).toBeNull();
+ await act(async () => root.unmount());
+ }
+});
diff --git a/apps/web/src/components/chat/HighlightedCodeLines.test.tsx b/apps/web/src/components/chat/HighlightedCodeLines.test.tsx
deleted file mode 100644
index 66af6dcc5ed..00000000000
--- a/apps/web/src/components/chat/HighlightedCodeLines.test.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { getSharedHighlighter } from "@pierre/diffs";
-import { toHtml } from "hast-util-to-html";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vite-plus/test";
-
-import { createIncrementalHighlightedDocument } from "../../lib/incrementalHighlighting";
-import { HighlightedCodeLines } from "./HighlightedCodeLines";
-
-describe("highlighted code lines", () => {
- it("preserves Shiki HTML, including colors, escaping, whitespace, and blank lines", async () => {
- const highlighter = await getSharedHighlighter({
- langs: ["typescript"],
- themes: ["pierre-dark", "pierre-light"],
- preferredHighlighter: "shiki-wasm",
- });
- for (const theme of ["pierre-dark", "pierre-light"] as const) {
- const highlight = createIncrementalHighlightedDocument(highlighter, "typescript", theme);
- const code =
- 'const html = "<img src=x onerror=alert(1)>";\n\n/* multi\nline */\n\tconst x = 1;\n';
- for (let end = 0; end <= code.length; end++) {
- const root = highlight(code.slice(0, end));
- expect(renderToStaticMarkup(<HighlightedCodeLines root={root} />)).toBe(toHtml(root));
- }
- }
- });
-});
diff --git a/apps/web/src/components/chat/OpenInPicker.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx
similarity index 52%
rename from apps/web/src/components/chat/OpenInPicker.test.tsx
rename to apps/web/src/components/chat/OpenInPicker.browser.test.tsx
index a2d9e175b9c..3b7a4a55992 100644
--- a/apps/web/src/components/chat/OpenInPicker.test.tsx
+++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx
@@ -1,8 +1,8 @@
import { AuthOrchestrationOperateScope, EnvironmentId, type EditorId } from "@t3tools/contracts";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import { AsyncResult } from "effect/reactivity";
-import { cloneElement, useState, type ReactElement, type ReactNode } from "react";
-import { act, create, type ReactTestRenderer } from "react-test-renderer";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { RemoteOpenState } from "../../remoteOpen";
@@ -15,102 +15,63 @@ const state = vi.hoisted(() => ({
openUrl: vi.fn(),
setPreferred: vi.fn(),
markHintSeen: vi.fn(),
- keydown: null as ((event: KeyboardEvent) => void) | null,
listeners: new Set<() => void>(),
}));
-vi.mock("../../state/session", async () => {
+vi.mock(import("../../state/session"), async (importOriginal) => {
const { useSyncExternalStore } = await import("react");
const readEnvironmentScope = (environmentId: string, scope: string) =>
scope === AuthOrchestrationOperateScope && state.allowed.has(environmentId);
return {
- readEnvironmentScope,
- useEnvironmentScope: (environmentId: string, scope: string) =>
+ ...(await importOriginal()),
+ readEnvironmentScope: readEnvironmentScope as never,
+ useEnvironmentScope: ((environmentId: string, scope: string) =>
useSyncExternalStore(
(listener) => {
state.listeners.add(listener);
return () => state.listeners.delete(listener);
},
() => readEnvironmentScope(environmentId, scope),
- ),
+ )) as never,
};
});
-vi.mock("../../state/shell", () => ({ shellEnvironment: { openInEditor: "openInEditor" } }));
-vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.run }));
-vi.mock("../../state/environments", () => ({ useEnvironment: () => ({ label: "Test host" }) }));
-vi.mock("../../editorPreferences", async (importOriginal) => {
- const actual = await importOriginal<typeof import("../../editorPreferences")>();
+vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useAtomCommand: (() => state.run) as never,
+}));
+vi.mock(import("../../state/environments"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useEnvironment: (() => ({ label: "Test host" })) as never,
+}));
+vi.mock(import("../../editorPreferences"), async (importOriginal) => {
+ const actual = await importOriginal();
return {
...actual,
usePreferredEditor: (available: readonly EditorId[]) => {
const [preferred, setPreferred] = actual.usePreferredEditor(available);
- return [
- preferred,
- (editor: EditorId) => {
- state.setPreferred(editor);
- setPreferred(editor);
- },
- ] as const;
+ const recordPreferred: typeof setPreferred = (editor) => {
+ state.setPreferred(editor);
+ setPreferred(editor);
+ };
+ return [preferred, recordPreferred] as const;
},
};
});
-vi.mock("../../remoteOpen", () => ({
+vi.mock(import("../../remoteOpen"), async (importOriginal) => ({
+ ...(await importOriginal()),
useRemoteOpenState: () => state.remote,
useRemoteCapableEditors: () => state.clientEditors,
- useRemoteOpenHint: () => [false, state.markHintSeen],
+ useRemoteOpenHint: () => [false, state.markHintSeen] as const,
openRemoteEditorUrl: state.openUrl,
}));
-vi.mock("../../keybindings", () => ({
- isOpenFavoriteEditorShortcut: () => true,
- shortcutLabelForCommand: () => "Ctrl+O",
-}));
-vi.mock("../ui/button", () => ({ Button: "button" }));
-vi.mock("../ui/group", () => ({ Group: "div", GroupSeparator: "span" }));
-vi.mock("../ui/menu", () => ({
- Menu: ({
- open,
- onOpenChange,
- children,
- }: {
- open?: boolean;
- onOpenChange?: (open: boolean) => void;
- children: ReactNode;
- }) => {
- const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
- const visible = open ?? uncontrolledOpen;
- return (
- <div
- data-menu-open={visible}
- onDoubleClick={() => {
- setUncontrolledOpen(!visible);
- onOpenChange?.(!visible);
- }}
- >
- {children}
- </div>
- );
- },
- MenuTrigger: ({
- render,
- children,
- disabled,
- }: {
- render: ReactElement<{ disabled?: boolean }>;
- children: ReactNode;
- disabled?: boolean;
- }) => cloneElement(render, disabled === undefined ? {} : { disabled }, children),
- MenuPopup: "section",
- MenuItem: "button",
- MenuItemLabel: "span",
- MenuShortcut: "span",
-}));
import { OpenInPicker } from "./OpenInPicker";
const primary = EnvironmentId.make("primary");
const selected = EnvironmentId.make("selected");
const editors: readonly EditorId[] = ["vscode"];
-let renderer: ReactTestRenderer | undefined;
+let root: Root;
+let container: HTMLDivElement;
beforeEach(() => {
state.allowed.clear();
@@ -120,33 +81,20 @@ beforeEach(() => {
state.openUrl.mockReset().mockResolvedValue(true);
state.setPreferred.mockReset();
state.markHintSeen.mockReset();
- state.keydown = null;
state.listeners.clear();
+ window.localStorage.clear();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("navigator", { platform: "Linux" });
- const events = new EventTarget();
- const storage = new Map<string, string>();
- vi.stubGlobal("window", {
- localStorage: {
- getItem: (key: string) => storage.get(key) ?? null,
- setItem: (key: string, value: string) => storage.set(key, value),
- removeItem: (key: string) => storage.delete(key),
- },
- dispatchEvent: (event: Event) => events.dispatchEvent(event),
- addEventListener: (type: string, callback: EventListener) => {
- events.addEventListener(type, callback);
- if (type === "keydown") state.keydown = callback;
- },
- removeEventListener: (type: string, callback: EventListener) => {
- events.removeEventListener(type, callback);
- if (state.keydown === callback) state.keydown = null;
- },
- });
+ vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
+ await act(async () => root.unmount());
+ document.body.replaceChildren();
+ window.localStorage.clear();
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -163,17 +111,32 @@ async function renderPicker(availableEditors: readonly EditorId[] = editors, pan
compact={!panel}
/>
);
- if (renderer) renderer.update(node);
- else renderer = create(node);
+ root.render(node);
});
}
-function primaryButton() {
- return renderer!.root.findByProps({ "aria-label": "Open file in preferred editor" });
+function byLabel(label: string) {
+ const element = document.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`);
+ expect(element, label).not.toBeNull();
+ return element!;
}
-function keyboardEvent() {
- return { preventDefault: vi.fn() } as unknown as KeyboardEvent;
+const primaryButton = () => byLabel("Open file in preferred editor");
+const menuItems = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+
+async function click(element: HTMLElement) {
+ await act(async () => element.click());
+}
+
+async function pressOpenFavorite() {
+ const event = new KeyboardEvent("keydown", {
+ key: "o",
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ await act(async () => window.dispatchEvent(event));
+ return event;
}
it.each(["local-exec", "remote-links"] as const)(
@@ -184,16 +147,15 @@ it.each(["local-exec", "remote-links"] as const)(
state.remote =
mode === "local-exec" ? { mode } : { mode, host: { kind: "ssh-alias", host: "test-host" } };
await renderPicker(["cursor", "vscode"], true);
- expect(renderer!.root.findByProps({ "aria-label": "Open in Cursor" })).toBeDefined();
- await act(async () => {
- renderer!.root.findByProps({ children: "VS Code" }).parent!.props.onClick();
- });
+ byLabel("Open in Cursor");
+ await click(byLabel("Choose editor"));
+ await click(menuItems().find((item) => item.textContent?.includes("VS Code"))!);
expect(window.localStorage.getItem("t3code:last-editor")).toBe('"vscode"');
- const openButton = renderer!.root.findByProps({ "aria-label": "Open in VS Code" });
+ const openButton = byLabel("Open in VS Code");
expect(state.run).not.toHaveBeenCalled();
expect(state.openUrl).not.toHaveBeenCalled();
- await act(async () => openButton.props.onClick());
+ await click(openButton);
if (mode === "local-exec") {
expect(state.run).toHaveBeenCalledExactlyOnceWith({
environmentId: selected,
@@ -211,39 +173,33 @@ describe("host editor access", () => {
it("uses the selected grant for both the button and a retained shortcut", async () => {
state.allowed.add(selected);
await renderPicker();
- const open = primaryButton().props.onClick;
- const keydown = state.keydown!;
+ // Revoke without rerendering: the mounted button and shortcut must re-check the grant.
state.allowed.delete(selected);
state.allowed.add(primary);
- const event = keyboardEvent();
- await act(async () => {
- open();
- keydown(event);
- });
+ await click(primaryButton());
+ const event = await pressOpenFavorite();
expect(state.run).not.toHaveBeenCalled();
expect(state.setPreferred).not.toHaveBeenCalled();
- expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
await renderPicker();
- expect(primaryButton().props.disabled).toBe(true);
- expect(renderer!.root.findByProps({ "aria-label": "Choose editor" }).props.disabled).toBe(true);
- expect(state.keydown).toBeNull();
+ expect(primaryButton().disabled).toBe(true);
+ expect(byLabel("Choose editor").disabled).toBe(true);
+ expect((await pressOpenFavorite()).defaultPrevented).toBe(false);
});
it("closes an open picker on revocation and launches only after a fresh grant", async () => {
state.allowed.add(selected);
await renderPicker();
- await act(async () => {
- renderer!.root.findByProps({ "data-menu-open": false }).props.onDoubleClick();
- });
- expect(renderer!.root.findByProps({ "data-menu-open": true })).toBeDefined();
+ await click(byLabel("Choose editor"));
+ expect(menuItems().length).toBeGreaterThan(0);
state.allowed.delete(selected);
await renderPicker();
- expect(renderer!.root.findByProps({ "data-menu-open": false })).toBeDefined();
+ expect(menuItems()).toHaveLength(0);
state.allowed.add(selected);
await renderPicker();
- expect(renderer!.root.findByProps({ "data-menu-open": false })).toBeDefined();
- await act(async () => primaryButton().props.onClick());
+ expect(menuItems()).toHaveLength(0);
+ await click(primaryButton());
expect(state.run).toHaveBeenCalledExactlyOnceWith({
environmentId: selected,
input: { cwd: "/work/project", editor: "vscode" },
@@ -255,8 +211,8 @@ describe("client editor links", () => {
it("opens an SSH editor URL without host operate permission", async () => {
state.remote = { mode: "remote-links", host: { kind: "ssh-alias", host: "test-host" } };
await renderPicker();
- expect(primaryButton().props.disabled).toBe(false);
- await act(async () => primaryButton().props.onClick());
+ expect(primaryButton().disabled).toBe(false);
+ await click(primaryButton());
expect(state.openUrl).toHaveBeenCalledExactlyOnceWith(
"vscode://vscode-remote/ssh-remote+test-host/work/project",
);
@@ -269,10 +225,9 @@ describe("client editor links", () => {
state.remote = { mode: "remote-links", host: { kind: "ssh-alias", host: "test-host" } };
state.openUrl.mockResolvedValue(false);
await renderPicker();
- const event = keyboardEvent();
- await act(async () => state.keydown!(event));
+ const event = await pressOpenFavorite();
expect(state.openUrl).toHaveBeenCalledOnce();
- expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(event.defaultPrevented).toBe(true);
expect(state.run).not.toHaveBeenCalled();
expect(state.setPreferred).not.toHaveBeenCalled();
expect(state.markHintSeen).not.toHaveBeenCalled();
diff --git a/apps/web/src/components/chat/ProviderModelPicker.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
similarity index 64%
rename from apps/web/src/components/chat/ProviderModelPicker.test.tsx
rename to apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
index 3867fcb2bad..537e701ba2c 100644
--- a/apps/web/src/components/chat/ProviderModelPicker.test.tsx
+++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
@@ -4,8 +4,9 @@ import {
ProviderInstanceId,
type ServerProvider,
} from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vite-plus/test";
+import { act, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { deriveProviderInstanceEntries } from "../../providerInstances";
import { ProviderModelPicker } from "./ProviderModelPicker";
@@ -28,6 +29,23 @@ function providerEntry(instanceId: string, driver: string) {
return deriveProviderInstanceEntries([provider])[0]!;
}
+afterEach(() => {
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+});
+
+// Returns the trigger's visible text, which is what the user reads before opening the picker.
+async function triggerText(node: ReactNode) {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => root.render(node));
+ const text = container.querySelector("button")?.textContent ?? "";
+ await act(async () => root.unmount());
+ return text;
+}
+
function renderPicker(input: {
instanceId: string;
driver: string;
@@ -38,7 +56,7 @@ function renderPicker(input: {
}) {
const instanceId = ProviderInstanceId.make(input.instanceId);
const entry = providerEntry(input.instanceId, input.driver);
- return renderToStaticMarkup(
+ return triggerText(
<ProviderModelPicker
environmentId={null}
activeInstanceId={instanceId}
@@ -53,38 +71,38 @@ function renderPicker(input: {
}
describe("ProviderModelPicker", () => {
- it("shows a neutral aggregate value without a representative model or availability badge", () => {
- const markup = renderPicker({
+ it("shows a neutral aggregate value without a representative model or availability badge", async () => {
+ const label = await renderPicker({
instanceId: "codex_personal",
driver: "codex",
model: "gpt-5",
options: [{ slug: "gpt-5", name: "GPT 5", isUnavailable: true }],
triggerLabel: "Mixed values",
});
- expect(markup).toContain("Mixed values");
- expect(markup).not.toContain("GPT 5");
- expect(markup).not.toContain("Unavailable");
+ expect(label).toContain("Mixed values");
+ expect(label).not.toContain("GPT 5");
+ expect(label).not.toContain("Unavailable");
});
it.each(["", ANTIGRAVITY_DEFAULT_MODEL])(
"shows a choice prompt before Antigravity has an account catalog for %s",
- (model) => {
- const markup = renderPicker({
+ async (model) => {
+ const label = await renderPicker({
instanceId: "antigravity",
driver: "antigravity",
model,
options: [],
});
- expect(markup).toContain("Choose model");
- expect(markup).not.toContain(ANTIGRAVITY_DEFAULT_MODEL);
+ expect(label).toContain("Choose model");
+ expect(label).not.toContain(ANTIGRAVITY_DEFAULT_MODEL);
},
);
it.each([{ aliases: [ANTIGRAVITY_DEFAULT_MODEL] }, { isDefault: true }])(
"shows the actual default model for an Antigravity marker with %j",
- (defaultMetadata) => {
- const markup = renderPicker({
+ async (defaultMetadata) => {
+ const label = await renderPicker({
instanceId: "google_work",
driver: "antigravity",
model: ANTIGRAVITY_DEFAULT_MODEL,
@@ -94,44 +112,44 @@ describe("ProviderModelPicker", () => {
],
});
- expect(markup).toContain("Gemini Pro");
- expect(markup).not.toContain("Gemini Fast");
- expect(markup).not.toContain(ANTIGRAVITY_DEFAULT_MODEL);
+ expect(label).toContain("Gemini Pro");
+ expect(label).not.toContain("Gemini Fast");
+ expect(label).not.toContain(ANTIGRAVITY_DEFAULT_MODEL);
},
);
it.each(["opencode", "antigravity"])(
"keeps the selected model label when the %s account catalog does not contain it",
- (driver) => {
- const markup = renderPicker({
+ async (driver) => {
+ const label = await renderPicker({
instanceId: "team_runtime",
driver,
model: "missing-model",
options: [{ slug: "fallback", name: "Fallback model" }],
});
- expect(markup).toContain("missing-model");
- expect(markup).not.toContain("Fallback model");
+ expect(label).toContain("missing-model");
+ expect(label).not.toContain("Fallback model");
},
);
it.each(["codex", "claudeAgent", "cursor", "grok"])(
"uses the first option label for a missing %s model",
- (driver) => {
- const markup = renderPicker({
+ async (driver) => {
+ const label = await renderPicker({
instanceId: `${driver}_work`,
driver,
model: "missing-model",
options: [{ slug: "fallback-model", name: "Fallback model" }],
});
- expect(markup).toContain("Fallback model");
- expect(markup).not.toContain(">missing-model<");
+ expect(label).toContain("Fallback model");
+ expect(label).not.toContain("missing-model");
},
);
- it("prefers a matching model for OpenCode", () => {
- const markup = renderPicker({
+ it("prefers a matching model for OpenCode", async () => {
+ const label = await renderPicker({
instanceId: "custom_runtime",
driver: "opencode",
model: "openrouter/selected",
@@ -141,12 +159,12 @@ describe("ProviderModelPicker", () => {
],
});
- expect(markup).toContain("Selected model");
- expect(markup).not.toContain("Fallback model");
+ expect(label).toContain("Selected model");
+ expect(label).not.toContain("Fallback model");
});
- it("uses the first option when the active instance entry is missing", () => {
- const markup = renderPicker({
+ it("uses the first option when the active instance entry is missing", async () => {
+ const label = await renderPicker({
instanceId: "missing_instance",
driver: "opencode",
model: "missing-model",
@@ -154,13 +172,13 @@ describe("ProviderModelPicker", () => {
includeEntry: false,
});
- expect(markup).toContain("Fallback model");
- expect(markup).not.toContain(">missing-model<");
+ expect(label).toContain("Fallback model");
+ expect(label).not.toContain("missing-model");
});
- it("keeps instance initials visible in the resting trigger", () => {
+ it("keeps instance initials visible in the resting trigger", async () => {
const activeEntry = providerEntry("codex_personal", "codex");
- const markup = renderToStaticMarkup(
+ const label = await triggerText(
<ProviderModelPicker
environmentId={null}
activeInstanceId={activeEntry.instanceId}
@@ -173,6 +191,6 @@ describe("ProviderModelPicker", () => {
/>,
);
- expect(markup).toContain(">CP</span>");
+ expect(label).toContain("CP");
});
});
diff --git a/apps/web/src/components/chat/ProviderStatusBanner.test.tsx b/apps/web/src/components/chat/ProviderStatusBanner.test.tsx
index ac6455c2383..61e7455dad5 100644
--- a/apps/web/src/components/chat/ProviderStatusBanner.test.tsx
+++ b/apps/web/src/components/chat/ProviderStatusBanner.test.tsx
@@ -1,11 +1,9 @@
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import {
getProviderStatusBannerKey,
getProviderStatusMessage,
- ProviderStatusBanner,
shouldShowProviderStatusBanner,
} from "./ProviderStatusBanner";
@@ -70,26 +68,6 @@ describe("ProviderStatusBanner", () => {
expect(shouldShowProviderStatusBanner(status, null)).toBe(true);
expect(shouldShowProviderStatusBanner(status, getProviderStatusBannerKey(status))).toBe(false);
});
-
- it("renders an accessible dismiss control for provider warnings", () => {
- const markup = renderToStaticMarkup(
- <ProviderStatusBanner status={warningProvider()} onDismiss={() => {}} />,
- );
-
- expect(markup).toContain('role="alert"');
- expect(markup).toContain('aria-label="Dismiss Codex provider warning"');
- });
-
- it("labels error dismiss controls with the correct severity", () => {
- const markup = renderToStaticMarkup(
- <ProviderStatusBanner
- status={{ ...warningProvider(), status: "error" }}
- onDismiss={() => {}}
- />,
- );
-
- expect(markup).toContain('aria-label="Dismiss Codex provider error"');
- });
});
describe("getProviderStatusMessage", () => {
diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
new file mode 100644
index 00000000000..a18f1bcfdc8
--- /dev/null
+++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
@@ -0,0 +1,164 @@
+import { act, type ComponentProps } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+const state = vi.hoisted(() => ({
+ projection: null as unknown,
+ workflow: null as unknown,
+}));
+
+vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ deriveThreadQueueWorkflowState: (() => state.workflow) as never,
+}));
+
+vi.mock(import("../../state/entities"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useThreadProjection: (() => state.projection) as never,
+}));
+
+vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useAtomCommand: (() => async () => undefined) as never,
+}));
+
+vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useAssetUrls: ((_environmentId: never, resources: ReadonlyArray<{ attachmentId: string }>) =>
+ resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,
+}));
+
+import { QueuedRunsControl } from "./QueuedRunsControl";
+
+const roots: Root[] = [];
+
+afterEach(async () => {
+ await act(async () => {
+ for (const root of roots.splice(0)) root.unmount();
+ });
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+});
+
+const baseProps = {
+ environmentId: "environment:test" as never,
+ optimisticMessages: [],
+ threadId: "thread:test" as never,
+ editingRunId: null,
+ onEditQueuedRun: () => undefined,
+ onCancelEdit: () => undefined,
+} satisfies ComponentProps<typeof QueuedRunsControl>;
+
+async function render(props: Partial<ComponentProps<typeof QueuedRunsControl>> = {}) {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ roots.push(root);
+ await act(async () => root.render(<QueuedRunsControl {...baseProps} {...props} />));
+ return container;
+}
+
+const labels = (container: HTMLElement) =>
+ [...container.querySelectorAll("[aria-label]")].map((element) =>
+ element.getAttribute("aria-label"),
+ );
+
+describe("QueuedRunsControl automatic completion delivery", () => {
+ it("does not render a queue control when only hidden delivery remains", async () => {
+ state.projection = {
+ projection: {
+ messages: [
+ {
+ delegatedCompletion: {
+ parentRunId: "run:parent",
+ generation: 1,
+ taskIds: ["task:child"],
+ },
+ id: "message:completion",
+ },
+ ],
+ },
+ };
+ state.workflow = {
+ activeRun: { id: "run:active" },
+ canPromoteToSteer: true,
+ canReorder: true,
+ queuedRuns: [],
+ };
+
+ const view = await render();
+
+ expect(view.childElementCount).toBe(0);
+ });
+});
+
+describe("QueuedRunsControl attachments and edit mode", () => {
+ const workflowWithAttachment = () => ({
+ activeRun: { id: "run:active" },
+ canPromoteToSteer: true,
+ canReorder: true,
+ queuedRuns: [
+ {
+ run: { id: "run:queued", userMessageId: "message:queued" },
+ text: "Queued with a screenshot",
+ attachments: [
+ {
+ type: "image",
+ id: "attachment-1",
+ name: "screenshot.png",
+ mimeType: "image/png",
+ sizeBytes: 128,
+ },
+ ],
+ },
+ ],
+ });
+
+ it("renders an attachment thumbnail on the queued row", async () => {
+ state.projection = { projection: { messages: [] } };
+ state.workflow = workflowWithAttachment();
+
+ const view = await render();
+
+ expect(view.querySelector("img")?.getAttribute("src")).toBe("https://assets.test/attachment-1");
+ expect(view.textContent).toContain("Queued with a screenshot");
+ expect(labels(view)).toContain("Edit queued message");
+ expect(labels(view)).toContain("Reorder queued message (drag, or press the arrow keys)");
+ expect(labels(view)).not.toContain("Move queued message up");
+ });
+
+ it("drops the optimistic pending row once the projection holds its message", async () => {
+ state.projection = {
+ projection: { messages: [{ id: "message:acknowledged", text: "hello" }] },
+ };
+ state.workflow = {
+ activeRun: { id: "run:active" },
+ canPromoteToSteer: true,
+ canReorder: true,
+ queuedRuns: [],
+ };
+
+ const view = await render({
+ optimisticMessages: [
+ {
+ id: "message:acknowledged" as never,
+ inputIntent: "queued_turn",
+ text: "hello",
+ attachments: [],
+ },
+ ],
+ });
+
+ expect(view.childElementCount).toBe(0);
+ });
+
+ it("keeps the original queued message visible while editing", async () => {
+ state.projection = { projection: { messages: [] } };
+ state.workflow = workflowWithAttachment();
+
+ const view = await render({ editingRunId: "run:queued" as never });
+
+ expect(view.textContent).toContain("Queued with a screenshot");
+ });
+});
diff --git a/apps/web/src/components/chat/QueuedRunsControl.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.test.tsx
deleted file mode 100644
index 5aa400bb00a..00000000000
--- a/apps/web/src/components/chat/QueuedRunsControl.test.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it, vi } from "vite-plus/test";
-
-const state = vi.hoisted(() => ({
- projection: null as unknown,
- workflow: null as unknown,
-}));
-
-vi.mock("@t3tools/client-runtime/environment", () => ({
- scopeThreadRef: () => ({}) as never,
-}));
-
-vi.mock("@t3tools/client-runtime/state/thread-workflows", () => ({
- deriveThreadQueueWorkflowState: () => state.workflow,
-}));
-
-vi.mock("../../state/entities", () => ({
- useThreadProjection: () => state.projection,
-}));
-
-vi.mock("../../state/threads", () => ({
- threadEnvironment: {
- cancelQueuedRun: Symbol("cancelQueuedRun"),
- promoteQueuedRun: Symbol("promoteQueuedRun"),
- reorderQueuedRun: Symbol("reorderQueuedRun"),
- },
-}));
-
-vi.mock("../../state/use-atom-command", () => ({
- useAtomCommand: () => async () => undefined,
-}));
-
-vi.mock("../../assets/assetUrls", () => ({
- useAssetUrls: (_environmentId: never, resources: ReadonlyArray<{ attachmentId: string }>) =>
- resources.map((resource) => `https://assets.test/${resource.attachmentId}`),
-}));
-
-import { QueuedRunsControl } from "./QueuedRunsControl";
-
-describe("QueuedRunsControl automatic completion delivery", () => {
- it("does not render a queue control when only hidden delivery remains", () => {
- state.projection = {
- projection: {
- messages: [
- {
- delegatedCompletion: {
- parentRunId: "run:parent",
- generation: 1,
- taskIds: ["task:child"],
- },
- id: "message:completion",
- },
- ],
- },
- };
- state.workflow = {
- activeRun: { id: "run:active" },
- canPromoteToSteer: true,
- canReorder: true,
- queuedRuns: [],
- };
-
- const html = renderToStaticMarkup(
- <QueuedRunsControl
- environmentId={"environment:test" as never}
- optimisticMessages={[]}
- threadId={"thread:test" as never}
- editingRunId={null}
- onEditQueuedRun={() => undefined}
- onCancelEdit={() => undefined}
- />,
- );
-
- expect(html).toBe("");
- });
-});
-
-describe("QueuedRunsControl attachments and edit mode", () => {
- const workflowWithAttachment = () => ({
- activeRun: { id: "run:active" },
- canPromoteToSteer: true,
- canReorder: true,
- queuedRuns: [
- {
- run: { id: "run:queued", userMessageId: "message:queued" },
- text: "Queued with a screenshot",
- attachments: [
- {
- type: "image",
- id: "attachment-1",
- name: "screenshot.png",
- mimeType: "image/png",
- sizeBytes: 128,
- },
- ],
- },
- ],
- });
-
- it("renders an attachment thumbnail on the queued row", () => {
- state.projection = { projection: { messages: [] } };
- state.workflow = workflowWithAttachment();
-
- const html = renderToStaticMarkup(
- <QueuedRunsControl
- environmentId={"environment:test" as never}
- optimisticMessages={[]}
- threadId={"thread:test" as never}
- editingRunId={null}
- onEditQueuedRun={() => undefined}
- onCancelEdit={() => undefined}
- />,
- );
-
- expect(html).toContain("https://assets.test/attachment-1");
- expect(html).toContain("Queued with a screenshot");
- expect(html).toContain("Edit queued message");
- expect(html).toContain("Reorder queued message");
- expect(html).not.toContain("Move queued message up");
- });
-
- it("drops the optimistic pending row once the projection holds its message", () => {
- state.projection = {
- projection: { messages: [{ id: "message:acknowledged", text: "hello" }] },
- };
- state.workflow = {
- activeRun: { id: "run:active" },
- canPromoteToSteer: true,
- canReorder: true,
- queuedRuns: [],
- };
-
- const html = renderToStaticMarkup(
- <QueuedRunsControl
- environmentId={"environment:test" as never}
- optimisticMessages={[
- {
- id: "message:acknowledged" as never,
- inputIntent: "queued_turn",
- text: "hello",
- attachments: [],
- },
- ]}
- threadId={"thread:test" as never}
- editingRunId={null}
- onEditQueuedRun={() => undefined}
- onCancelEdit={() => undefined}
- />,
- );
-
- expect(html).toBe("");
- });
-
- it("keeps the original queued message visible while editing", () => {
- state.projection = { projection: { messages: [] } };
- state.workflow = workflowWithAttachment();
-
- const html = renderToStaticMarkup(
- <QueuedRunsControl
- environmentId={"environment:test" as never}
- optimisticMessages={[]}
- threadId={"thread:test" as never}
- editingRunId={"run:queued" as never}
- onEditQueuedRun={() => undefined}
- onCancelEdit={() => undefined}
- />,
- );
-
- expect(html).toContain("Queued with a screenshot");
- });
-});
diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.browser.test.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.browser.test.tsx
new file mode 100644
index 00000000000..e780a635075
--- /dev/null
+++ b/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.browser.test.tsx
@@ -0,0 +1,86 @@
+import { EnvironmentId, ThreadId, ScheduledTaskId, type ScheduledTask } from "@t3tools/contracts";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+const state = vi.hoisted(() => ({ allowed: true, toggle: vi.fn(), run: vi.fn() }));
+vi.mock(import("../../state/session"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useEnvironmentScope: () => state.allowed,
+ readEnvironmentScope: () => state.allowed,
+}));
+// The panel reads the run permission through an atom; the grant is the boundary under test.
+vi.mock(import("@effect/atom-react"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useAtomValue: (() => state.allowed) as never,
+}));
+vi.mock(import("@tanstack/react-router"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useNavigate: () => vi.fn(),
+}));
+vi.mock(import("../../state/use-atom-command"), async (importOriginal) => {
+ const { serverEnvironment } = await import("../../state/server");
+ return {
+ ...(await importOriginal()),
+ useAtomCommand: ((command: unknown) =>
+ command === serverEnvironment.setScheduledTaskEnabled ? state.toggle : state.run) as never,
+ };
+});
+vi.mock(import("../../state/query"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useEnvironmentQuery: (() => ({ data: { tasks: [task] }, error: null })) as never,
+}));
+
+import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel";
+const environmentId = EnvironmentId.make("remote");
+const threadId = ThreadId.make("thread");
+const task = {
+ id: ScheduledTaskId.make("task"),
+ threadId,
+ title: "Daily review",
+ enabled: true,
+ schedule: { type: "interval", everyMs: 60000 },
+ lastRunStatus: "never",
+} as ScheduledTask;
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ state.allowed = true;
+ state.toggle.mockReset().mockResolvedValue({ _tag: "Success" });
+ state.run.mockReset().mockResolvedValue({ _tag: "Success" });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+async function renderPanel() {
+ await act(async () =>
+ root.render(<ThreadAutomationsPanel environmentId={environmentId} threadId={threadId} />),
+ );
+}
+
+const byLabel = (label: string) => container.querySelector<HTMLElement>(`[aria-label="${label}"]`)!;
+
+it.each([true, false])("runs scheduled work only with task permission (%s)", async (allowed) => {
+ state.allowed = allowed;
+ await renderPanel();
+ await act(async () => byLabel("Run Daily review now").click());
+ expect(state.run).toHaveBeenCalledTimes(allowed ? 1 : 0);
+});
+
+it("rejects a retained toggle after task permission is revoked", async () => {
+ await renderPanel();
+ state.allowed = false;
+ await act(async () => byLabel("Pause Daily review").click());
+ expect(state.toggle).not.toHaveBeenCalled();
+
+ state.allowed = true;
+ await act(async () => byLabel("Pause Daily review").click());
+ expect(state.toggle).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.test.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.test.tsx
deleted file mode 100644
index d91f6b35ac8..00000000000
--- a/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.test.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { EnvironmentId, ThreadId, ScheduledTaskId, type ScheduledTask } from "@t3tools/contracts";
-import { act, create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
-
-const state = vi.hoisted(() => ({ allowed: true, toggle: vi.fn(), run: vi.fn() }));
-vi.mock("../../state/session", () => ({
- useEnvironmentScope: () => state.allowed,
- readEnvironmentScope: () => state.allowed,
-}));
-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.allowed }));
-vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));
-vi.mock("../settings/ScheduledTasksSettings", () => ({
- relativeLabel: () => "later",
- scheduleLabel: () => "daily",
-}));
-vi.mock("../../state/server", () => ({
- serverEnvironment: {
- scheduledTasksLive: () => null,
- setScheduledTaskEnabled: "toggle",
- runScheduledTaskNow: { permissionAtom: () => null },
- },
-}));
-vi.mock("../../state/use-atom-command", () => ({
- useAtomCommand: (command: string) => (command === "toggle" ? state.toggle : state.run),
-}));
-vi.mock("../../state/query", () => ({
- useEnvironmentQuery: () => ({ data: { tasks: [task] }, error: null }),
-}));
-vi.mock("../ui/tooltip", () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => children,
- TooltipTrigger: ({ render }: { render: React.ReactNode }) => render,
- TooltipPopup: () => null,
-}));
-vi.mock("../ui/toast", () => ({
- toastManager: { add: vi.fn() },
- stackedThreadToast: (x: unknown) => x,
-}));
-
-import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel";
-const environmentId = EnvironmentId.make("remote");
-const threadId = ThreadId.make("thread");
-const task = {
- id: ScheduledTaskId.make("task"),
- threadId,
- title: "Daily review",
- enabled: true,
- schedule: { type: "interval", everyMs: 60000 },
- lastRunStatus: "never",
-} as ScheduledTask;
-let renderer: ReactTestRenderer;
-beforeEach(() => {
- state.allowed = true;
- state.toggle.mockReset().mockResolvedValue({ _tag: "Success" });
- state.run.mockReset().mockResolvedValue({ _tag: "Success" });
-});
-afterEach(async () => {
- if (renderer) await act(async () => renderer.unmount());
-});
-
-it.each([true, false])("runs scheduled work only with task permission (%s)", async (allowed) => {
- state.allowed = allowed;
- await act(async () => {
- renderer = create(<ThreadAutomationsPanel environmentId={environmentId} threadId={threadId} />);
- });
- const run = renderer.root.findAllByProps({ "aria-label": "Run Daily review now" })[0]!;
- await act(async () => {
- await run.props.onClick();
- });
- expect(state.run).toHaveBeenCalledTimes(allowed ? 1 : 0);
-});
-
-it("rejects a retained toggle after task permission is revoked", async () => {
- await act(async () => {
- renderer = create(<ThreadAutomationsPanel environmentId={environmentId} threadId={threadId} />);
- });
- const toggle = renderer.root
- .findAllByProps({ "aria-label": "Pause Daily review" })
- .find((node) => node.props.onCheckedChange)!;
- state.allowed = false;
- await act(async () => {
- await toggle.props.onCheckedChange(false);
- });
- expect(state.toggle).not.toHaveBeenCalled();
-});
diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.test.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.test.tsx
deleted file mode 100644
index a9f1867f39d..00000000000
--- a/apps/web/src/components/chat/ThreadDetailsPanel.test.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-import type { EnvironmentId, T3ProjectFileScript, ThreadId } from "@t3tools/contracts";
-import { renderToStaticMarkup } from "react-dom/server";
-import { PopoverCreateHandle } from "../ui/popover";
-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-const testState = vi.hoisted(() => ({
- useT3ProjectFileScripts: vi.fn(),
- projectScriptsControl: vi.fn(),
-}));
-
-vi.mock("../../hooks/useT3ProjectFileScripts", () => ({
- useT3ProjectFileScripts: (...args: ReadonlyArray<unknown>) =>
- testState.useT3ProjectFileScripts(...args),
-}));
-vi.mock("../BranchToolbar", () => ({
- BranchToolbar: () => null,
-}));
-vi.mock("../ProjectScriptsControl", () => ({
- default: (props: unknown) => {
- testState.projectScriptsControl(props);
- return null;
- },
-}));
-vi.mock("./ThreadAutomationsPanel", () => ({
- ThreadAutomationsPanel: () => null,
-}));
-vi.mock("./ThreadRelationshipsControl", () => ({
- ThreadRelationshipsPanel: () => null,
-}));
-vi.mock("./ThreadDetailsCard", () => ({
- ThreadDetailsCard: ({ children }: { children: (density: "full") => React.ReactNode }) =>
- children("full"),
-}));
-
-import { ThreadDetailsPanel, type ThreadDetailsPanelProps } from "./ThreadDetailsPanel";
-
-describe("ThreadDetailsPanel", () => {
- beforeEach(() => {
- testState.useT3ProjectFileScripts.mockReset();
- testState.projectScriptsControl.mockReset();
- });
-
- it("passes checked-in t3.json scripts to the project scripts control", () => {
- const environmentId = "environment:thread-details" as EnvironmentId;
- const gitCwd = "/tmp/thread-details-project";
- const fileScripts = [
- {
- name: "Check project",
- command: "vp check",
- icon: "test",
- },
- ] satisfies ReadonlyArray<T3ProjectFileScript>;
- testState.useT3ProjectFileScripts.mockReturnValue(fileScripts);
-
- const props: ThreadDetailsPanelProps = {
- anchor: { current: null },
- handle: PopoverCreateHandle(),
- onPresentationChange: vi.fn(),
- environmentId,
- threadId: "thread:thread-details" as ThreadId,
- activeProjectName: undefined,
- activeProjectScripts: [],
- preferredScriptId: null,
- keybindings: [],
- availableEditors: [],
- showOpenInPicker: false,
- gitCwd,
- isGitRepo: false,
- envLocked: false,
- availableEnvironments: [],
- onEnvironmentChange: vi.fn(),
- onEnvModeChange: vi.fn(),
- envMode: "local",
- startFromOrigin: false,
- onStartFromOriginChange: vi.fn(),
- onComposerFocusRequest: vi.fn(),
- onRunProjectScript: vi.fn(),
- onAddProjectScript: vi.fn() as ThreadDetailsPanelProps["onAddProjectScript"],
- onUpdateProjectScript: vi.fn() as ThreadDetailsPanelProps["onUpdateProjectScript"],
- onDeleteProjectScript: vi.fn() as ThreadDetailsPanelProps["onDeleteProjectScript"],
- };
-
- renderToStaticMarkup(<ThreadDetailsPanel {...props} />);
-
- expect(testState.useT3ProjectFileScripts).toHaveBeenCalledWith(environmentId, gitCwd);
- expect(testState.projectScriptsControl).toHaveBeenCalledWith(
- expect.objectContaining({
- displayMode: "panel",
- scripts: [],
- fileScripts,
- }),
- );
- });
-});
diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx
similarity index 52%
rename from apps/web/src/components/chat/ThreadDetailsPrRow.test.tsx
rename to apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx
index a072b997d6e..9c04d135e69 100644
--- a/apps/web/src/components/chat/ThreadDetailsPrRow.test.tsx
+++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx
@@ -1,7 +1,7 @@
import { EnvironmentId, type PullRequestCheck } from "@t3tools/contracts";
-import { act, cloneElement, type ReactElement, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, expect, it, vi } from "vite-plus/test";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
status: "success" as PullRequestCheck["status"],
@@ -9,11 +9,13 @@ const state = vi.hoisted(() => ({
perform: vi.fn(),
}));
-vi.mock("~/state/entities", () => ({ useServerConfigs: () => new Map() }));
-vi.mock("~/state/pullRequests", () => ({ pullRequestEnvironment: {} }));
-vi.mock("~/hooks/useLiveRefresh", () => ({ useLiveRefresh: () => {} }));
-vi.mock("~/state/query", () => ({
- useEnvironmentQuery: () => ({
+vi.mock(import("~/state/entities"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useServerConfigs: (() => new Map()) as never,
+}));
+vi.mock(import("~/state/query"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useEnvironmentQuery: (() => ({
data: {
number: 1,
title: "Test PR",
@@ -38,47 +40,33 @@ vi.mock("~/state/query", () => ({
dataUpdatedAt: 1,
isPending: false,
refresh: vi.fn(),
- }),
+ })) as never,
}));
-vi.mock("../pullRequest/usePullRequestActions", () => ({
+vi.mock(import("../pullRequest/usePullRequestActions"), async (importOriginal) => ({
+ ...(await importOriginal()),
usePullRequestActionRunner: () => ({ actionPending: false, perform: state.perform }),
- usePullRequestHandoffs: () => ({ handoff: null, startHandoff: vi.fn() }),
-}));
-vi.mock("../ui/popover", () => ({
- Popover: ({ children }: { children: ReactNode }) => children,
- PopoverTrigger: ({ render, children }: { render: ReactElement; children: ReactNode }) =>
- cloneElement(render, undefined, children),
- PopoverPopup: () => null,
-}));
-vi.mock("../ui/tooltip", () => ({
- Tooltip: ({ children }: { children: ReactNode }) => children,
- TooltipTrigger: ({ render, children }: { render: ReactElement; children: ReactNode }) =>
- cloneElement(render, undefined, children),
- TooltipPopup: () => null,
-}));
-vi.mock("../ui/alert-dialog", () => ({
- AlertDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
- open ? <div role="alertdialog">{children}</div> : null,
- AlertDialogPopup: ({ children }: { children: ReactNode }) => children,
- AlertDialogHeader: ({ children }: { children: ReactNode }) => children,
- AlertDialogTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,
- AlertDialogDescription: ({ children }: { children: ReactNode }) => children,
- AlertDialogFooter: ({ children }: { children: ReactNode }) => children,
- AlertDialogClose: () => null,
+ usePullRequestHandoffs: () => ({ handoff: null, startAsk: vi.fn(), startHandoff: vi.fn() }),
}));
import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow";
-let renderer: ReactTestRenderer;
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
afterEach(() => {
- act(() => renderer?.unmount());
+ act(() => root.unmount());
+ document.body.replaceChildren();
vi.unstubAllGlobals();
state.status = "success";
state.extraStatus = null;
});
it("requires a new merge click after passing checks become pending and pass again", () => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const render = () => (
<ThreadDetailsPrRow
environmentId={EnvironmentId.make("environment")}
@@ -93,26 +81,23 @@ it("requires a new merge click after passing checks become pending and pass agai
);
const clickMerge = () =>
act(() => {
- renderer.root
- .findAllByType("button")
- .find((button) => button.children.includes("Merge"))!
- .props.onClick();
+ [...container.querySelectorAll("button")]
+ .find((button) => button.textContent?.trim() === "Merge")!
+ .click();
});
- const dialogs = () => renderer.root.findAllByProps({ role: "alertdialog" });
+ const dialogs = () => [...document.querySelectorAll('[role="alertdialog"]')];
- act(() => {
- renderer = create(render());
- });
+ act(() => root.render(render()));
clickMerge();
expect(dialogs()).toHaveLength(1);
act(() => {
state.status = "pending";
- renderer.update(render());
+ root.render(render());
});
expect(dialogs()).toHaveLength(0);
act(() => {
state.status = "success";
- renderer.update(render());
+ root.render(render());
});
expect(dialogs()).toHaveLength(0);
clickMerge();
@@ -127,11 +112,10 @@ it.each<[PullRequestCheck["status"], PullRequestCheck["status"], string]>([
["success", "pending", "1/2"],
["failure", "pending", "1/2"],
])("shows a count only while checks run (%s, %s)", (status, extraStatus, count) => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
state.status = status;
state.extraStatus = extraStatus;
act(() => {
- renderer = create(
+ root.render(
<ThreadDetailsPrRow
environmentId={EnvironmentId.make("environment")}
pr={null}
@@ -144,8 +128,8 @@ it.each<[PullRequestCheck["status"], PullRequestCheck["status"], string]>([
/>,
);
});
- const text = renderer.root
- .findAllByType("span")
- .map((span) => span.children.filter((child) => typeof child === "string").join(""));
- expect(text.filter((value) => /^\d+\/\d+$/.test(value))).toEqual(count ? [count] : []);
+ const counts = [...container.querySelectorAll("*")]
+ .map((element) => element.textContent?.trim() ?? "")
+ .filter((value) => /^\d+\/\d+$/.test(value));
+ expect(new Set(counts)).toEqual(new Set(count ? [count] : []));
});
diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.browser.test.tsx
similarity index 65%
rename from apps/web/src/components/chat/ThreadDetailsPrRows.test.tsx
rename to apps/web/src/components/chat/ThreadDetailsPrRows.browser.test.tsx
index 95262329fd0..8da4e948d23 100644
--- a/apps/web/src/components/chat/ThreadDetailsPrRows.test.tsx
+++ b/apps/web/src/components/chat/ThreadDetailsPrRows.browser.test.tsx
@@ -1,31 +1,32 @@
import { EnvironmentId, ThreadId, type ThreadPullRequestLink } from "@t3tools/contracts";
import { act } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
-import { afterEach, expect, it, vi } from "vite-plus/test";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const watchCommand = vi.hoisted(() => vi.fn());
-vi.mock("./ThreadDetailsPrRow", () => ({
+// The row queries its own pull request; this test covers only which rows the list shows.
+vi.mock(import("./ThreadDetailsPrRow"), async (importOriginal) => ({
+ ...(await importOriginal()),
ThreadDetailsPrRow: ({
number,
onStopWatching,
}: {
number: number;
- onStopWatching?: () => void;
+ onStopWatching?: (() => void) | undefined;
}) => (
- <span
- data-row={String(number)}
- data-watched={onStopWatching ? "" : undefined}
- onClick={onStopWatching}
- />
+ <div data-row={String(number)}>
+ {onStopWatching ? <button onClick={onStopWatching}>Stop watching #{number}</button> : null}
+ </div>
),
}));
-vi.mock("~/state/entities", () => ({ useProjects: () => [] }));
-vi.mock("~/state/threads", () => ({ threadEnvironment: {} }));
-vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => watchCommand }));
-vi.mock("~/lib/openPullRequestLink", () => ({
- parseChangeRequestUrl: () => null,
- findProjectOnChangeRequestHost: () => undefined,
+vi.mock(import("~/state/entities"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useProjects: () => [],
+}));
+vi.mock(import("~/state/use-atom-command"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useAtomCommand: (() => watchCommand) as never,
}));
import { ThreadDetailsPrRows } from "./ThreadDetailsPrRows";
@@ -60,16 +61,23 @@ const bottom = link(1, "layer-one", "main", "2026-01-01T00:00:10.000Z");
const top = link(2, "layer-two", "layer-one", "2026-01-01T00:00:20.000Z");
const other = link(3, "unrelated", "main", "2026-01-01T00:00:05.000Z");
-let renderer: ReactTestRenderer;
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
afterEach(() => {
- act(() => renderer?.unmount());
+ act(() => root.unmount());
+ container.remove();
vi.unstubAllGlobals();
});
function render(links: ReadonlyArray<ThreadPullRequestLink>, current: ThreadPullRequestLink) {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
act(() => {
- renderer = create(
+ root.render(
<ThreadDetailsPrRows
threadRef={{
environmentId: EnvironmentId.make("environment"),
@@ -92,18 +100,16 @@ function render(links: ReadonlyArray<ThreadPullRequestLink>, current: ThreadPull
});
}
-const rows = () => renderer.root.findAllByType("span").map((node) => node.props["data-row"]);
-const toggleLabel = () =>
- renderer.root
- .findAllByType("button")
- .at(-1)
- ?.children.filter((child) => typeof child === "string")
- .join("");
+const rows = () =>
+ [...container.querySelectorAll("[data-row]")].map((node) => node.getAttribute("data-row"));
+const toggleButton = () =>
+ [...container.querySelectorAll("button")].find((button) =>
+ /^(Show \d+ more|Show less)$/.test(button.textContent?.trim() ?? ""),
+ );
+const toggleLabel = () => toggleButton()?.textContent?.trim();
function toggle() {
- act(() => {
- (renderer.root.findAllByType("button").at(-1)!.props as { onClick: () => void }).onClick();
- });
+ act(() => toggleButton()!.click());
}
it("shows only the current pull request until the rest are asked for", () => {
@@ -143,14 +149,12 @@ it("lets only watched pull requests stop their watch", () => {
};
render([other, watched, top], top);
toggle();
- const spans = renderer.root.findAllByType("span");
- expect(
- spans
- .filter((node) => node.props["data-watched"] !== undefined)
- .map((node) => node.props["data-row"]),
- ).toEqual(["1"]);
+ const stopButtons = [...container.querySelectorAll("button")].filter((button) =>
+ button.textContent?.startsWith("Stop watching"),
+ );
+ expect(stopButtons.map((button) => button.textContent)).toEqual(["Stop watching #1"]);
- act(() => spans.find((node) => node.props["data-row"] === "1")!.props.onClick());
+ act(() => stopButtons[0]!.click());
expect(watchCommand).toHaveBeenCalledWith({
environmentId: EnvironmentId.make("environment"),
input: {
diff --git a/apps/web/src/components/chat/ThreadErrorBanner.test.tsx b/apps/web/src/components/chat/ThreadErrorBanner.test.tsx
index a3dbb27515a..418fdf0adb5 100644
--- a/apps/web/src/components/chat/ThreadErrorBanner.test.tsx
+++ b/apps/web/src/components/chat/ThreadErrorBanner.test.tsx
@@ -1,4 +1,3 @@
-import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -6,7 +5,6 @@ import {
getThreadErrorBannerKey,
isThreadErrorBannerDismissedForSession,
shouldShowThreadErrorBanner,
- ThreadErrorBanner,
} from "./ThreadErrorBanner";
describe("ThreadErrorBanner", () => {
@@ -69,20 +67,4 @@ describe("ThreadErrorBanner", () => {
it("never shows a null error", () => {
expect(shouldShowThreadErrorBanner("env:thread-e", null, false)).toBe(false);
});
- it("aligns the warning and dismiss icons with the first line of a multi-line error", () => {
- const markup = renderToStaticMarkup(
- <ThreadErrorBanner
- error={"The first error line\ncontinues on a second line"}
- onDismiss={() => {}}
- />,
- );
-
- expect(markup).toContain('role="alert"');
- expect(markup).toContain('aria-label="Dismiss error"');
- expect(markup).not.toContain("controlAlignment");
- expect(markup).toContain("flex gap-2 items-start");
- expect(markup).toContain("min-h-7 pt-1 sm:min-h-6 sm:pt-0.5");
- expect(markup).toContain("h-lh w-4");
- expect(markup).toContain("h-lh self-start");
- });
});
diff --git a/apps/web/src/components/chat/ThreadFindProvider.test.tsx b/apps/web/src/components/chat/ThreadFindProvider.browser.test.tsx
similarity index 89%
rename from apps/web/src/components/chat/ThreadFindProvider.test.tsx
rename to apps/web/src/components/chat/ThreadFindProvider.browser.test.tsx
index b2830fd7440..16924d250f2 100644
--- a/apps/web/src/components/chat/ThreadFindProvider.test.tsx
+++ b/apps/web/src/components/chat/ThreadFindProvider.browser.test.tsx
@@ -1,5 +1,5 @@
-import { act, createRef, useContext, useState } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, createRef, useContext, useState, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
import { afterEach, expect, it, vi } from "vite-plus/test";
import {
EnvironmentId,
@@ -51,7 +51,14 @@ vi.mock("~/state/query", async () => {
});
vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
-let renderer: ReactTestRenderer | undefined;
+type Rendered = { update: (node: ReactNode) => void; unmount: () => void };
+function render(node: ReactNode): Rendered {
+ const root = createRoot(document.createElement("div"));
+ root.render(node);
+ return { update: (next) => root.render(next), unmount: () => root.unmount() };
+}
+
+let renderer: Rendered | undefined;
afterEach(async () => {
if (renderer) await act(async () => renderer?.unmount());
renderer = undefined;
@@ -60,7 +67,6 @@ afterEach(async () => {
});
it("keeps navigation and pending responses out of the surrounding chat and unrelated children", async () => {
- vi.stubGlobal("window", new EventTarget());
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const controls = createRef<ThreadFindControls>();
const parentRender = vi.fn();
@@ -99,7 +105,7 @@ it("keeps navigation and pending responses out of the surrounding chat and unrel
});
query.value = { ...query.value, data: response(0), isPending: false };
await act(async () => {
- renderer = create(<Chat />);
+ renderer = render(<Chat />);
});
await act(async () => controls.current?.open());
await act(async () => bar.onQueryChange("COD4"));
diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.test.tsx
index 2d4ea8cc1f5..05a97c9e81a 100644
--- a/apps/web/src/components/chat/ThreadRelationshipsControl.test.tsx
+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.test.tsx
@@ -1,22 +1,10 @@
import { describe, expect, it } from "vite-plus/test";
-import { renderToStaticMarkup } from "react-dom/server";
-import { resolveThreadLineageWindow, ThreadLineageRowList } from "./ThreadRelationshipsControl";
+import { resolveThreadLineageWindow } from "./ThreadRelationshipsControl";
const rows = Array.from({ length: 20 }, (_, index) => `row-${index}`);
-function renderRowList(visibleCount: number) {
- const { visibleRows, hiddenCount } = resolveThreadLineageWindow(rows, visibleCount);
- return renderToStaticMarkup(
- <ThreadLineageRowList hiddenCount={hiddenCount} onShowMore={() => {}}>
- {visibleRows.map((row) => (
- <li key={row}>{row}</li>
- ))}
- </ThreadLineageRowList>,
- );
-}
-
-describe("thread lineage row list", () => {
+describe("thread lineage window", () => {
it("shows six rows before the first expansion", () => {
const { visibleRows, hiddenCount } = resolveThreadLineageWindow(rows, 6);
@@ -24,26 +12,8 @@ describe("thread lineage row list", () => {
expect(hiddenCount).toBe(14);
});
- it("offers one page at a time", () => {
- expect(renderRowList(6)).toContain("Show 12 more");
- expect(renderRowList(6 + 12)).toContain("Show 2 more");
- });
-
- it("omits the expansion affordance when everything fits", () => {
- const markup = renderRowList(rows.length);
-
- expect(markup).not.toContain("more");
+ it("hides nothing when everything fits", () => {
+ expect(resolveThreadLineageWindow(rows, rows.length).hiddenCount).toBe(0);
expect(resolveThreadLineageWindow(rows.slice(0, 6), 6).hiddenCount).toBe(0);
});
-
- it("keeps the rows in a bounded, labelled scroll region and the button outside it", () => {
- const markup = renderRowList(6);
- const list = /<ul([^>]*)>/.exec(markup)?.[1] ?? "";
-
- expect(list).toContain('aria-label="Related threads"');
- expect(list).toContain("max-h-[13.5rem]");
- expect(list).toContain("overflow-y-auto");
- expect(list).toContain("overscroll-contain");
- expect(markup.indexOf("</ul>")).toBeLessThan(markup.indexOf("<button"));
- });
});
diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
index fea9cefda1f..10665e273fc 100644
--- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
@@ -85,7 +85,7 @@ export function resolveThreadLineageWindow<Row>(
return { visibleRows, hiddenCount: rows.length - visibleRows.length };
}
-export function ThreadLineageRowList(props: {
+function ThreadLineageRowList(props: {
readonly hiddenCount: number;
readonly onShowMore: () => void;
readonly children: ReactNode;
diff --git a/apps/web/src/components/chat/composerEventScope.browser.test.tsx b/apps/web/src/components/chat/composerEventScope.browser.test.tsx
new file mode 100644
index 00000000000..46523cdcd1c
--- /dev/null
+++ b/apps/web/src/components/chat/composerEventScope.browser.test.tsx
@@ -0,0 +1,110 @@
+import { act, useLayoutEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { ComposerHandleContext, type ComposerHandleRef } from "../../composerHandleContext";
+import {
+ isInsideCollapsedComposerControls,
+ isInsideComposerFloatingLayer,
+ isInsideRestingComposerControlScope,
+ useComposerMenuProps,
+} from "./composerEventScope";
+
+function elementInside(html: string) {
+ const host = document.createElement("div");
+ host.innerHTML = html;
+ document.body.append(host);
+ return host.querySelector("[data-target]")!;
+}
+
+afterEach(() => {
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+});
+
+describe("composer menu focus", () => {
+ it.each([
+ [
+ "an open menu",
+ '<div data-chat-composer-floating-layer="true"><button data-target></button></div>',
+ true,
+ ],
+ ["an unmounted menu", null, true],
+ ["another control", "<input data-target />", false],
+ ])("closes while focus is on %s", async (_label, html, shouldFocusComposer) => {
+ const editor = document.createElement("textarea");
+ document.body.append(editor);
+ const focused = html === null ? null : (elementInside(html) as HTMLElement);
+ focused?.focus();
+ const composerRef = {
+ current: { focusAtEnd: () => editor.focus() },
+ } as unknown as ComposerHandleRef;
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ let menuProps: ReturnType<typeof useComposerMenuProps> | undefined;
+ function Probe() {
+ const props = useComposerMenuProps();
+ useLayoutEffect(() => {
+ menuProps = props;
+ }, [props]);
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ await act(async () =>
+ root.render(
+ <ComposerHandleContext value={composerRef}>
+ <Probe />
+ </ComposerHandleContext>,
+ ),
+ );
+ try {
+ expect(menuProps?.finalFocus?.()).toBe(false);
+ expect(document.activeElement).toBe(shouldFocusComposer ? editor : focused);
+ } finally {
+ await act(async () => root.unmount());
+ }
+ });
+});
+
+describe("composer event scopes", () => {
+ it.each([
+ '<div data-chat-composer-resting-controls="true"><button data-target></button></div>',
+ "<div data-composer-context-control><button data-target></button></div>",
+ '<div data-chat-composer-resting-images="true"><img data-target /></div>',
+ ])("recognizes events from resting composer controls in %s", (html) => {
+ expect(isInsideRestingComposerControlScope(elementInside(html))).toBe(true);
+ });
+
+ it("includes composer-owned floating layers in the resting control scope", () => {
+ const target = elementInside(
+ '<div data-chat-composer-floating-layer="true"><button data-target></button></div>',
+ );
+ expect(isInsideComposerFloatingLayer(target)).toBe(true);
+ expect(isInsideRestingComposerControlScope(target)).toBe(true);
+ });
+
+ it("leaves unrelated floating layers outside the composer scope", () => {
+ const target = elementInside(
+ '<div data-slot="popover-popup"><button data-target></button></div>',
+ );
+ expect(isInsideComposerFloatingLayer(target)).toBe(false);
+ expect(isInsideRestingComposerControlScope(target)).toBe(false);
+ });
+
+ it("leaves ordinary composer targets outside the portaled control scope", () => {
+ expect(
+ isInsideRestingComposerControlScope(elementInside("<button data-target></button>")),
+ ).toBe(false);
+ expect(isInsideRestingComposerControlScope(null)).toBe(false);
+ });
+
+ it("recognizes banner and drawer controls docked above the surface", () => {
+ const target = elementInside(
+ '<div data-chat-composer-collapsed-controls="true"><button data-target></button></div>',
+ );
+ expect(isInsideCollapsedComposerControls(target)).toBe(true);
+ expect(isInsideCollapsedComposerControls(elementInside("<span data-target></span>"))).toBe(
+ false,
+ );
+ expect(isInsideCollapsedComposerControls(null)).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/chat/composerEventScope.test.ts b/apps/web/src/components/chat/composerEventScope.test.ts
deleted file mode 100644
index f40c9a68e6e..00000000000
--- a/apps/web/src/components/chat/composerEventScope.test.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import { act, createElement, useLayoutEffect } from "react";
-import { create } from "react-test-renderer";
-import { afterEach, describe, expect, it, vi } from "vite-plus/test";
-
-import { ComposerHandleContext, type ComposerHandleRef } from "../../composerHandleContext";
-import {
- isInsideCollapsedComposerControls,
- isInsideComposerFloatingLayer,
- isInsideRestingComposerControlScope,
- useComposerMenuProps,
-} from "./composerEventScope";
-
-class FakeElement {
- constructor(private readonly matchingSelector: string | null) {}
-
- closest(selector: string): FakeElement | null {
- return this.matchingSelector !== null &&
- selector.split(",").some((candidate) => candidate === this.matchingSelector)
- ? this
- : null;
- }
-}
-
-afterEach(() => {
- vi.unstubAllGlobals();
-});
-
-describe("composer menu focus", () => {
- it.each([
- ["an open menu", '[data-chat-composer-floating-layer="true"]', true],
- ["an unmounted menu", null, true],
- ["another control", "input", false],
- ])("closes while focus is on %s", async (_label, selector, shouldFocusComposer) => {
- const body = new FakeElement(null);
- const editor = new FakeElement(null);
- const activeElement = selector === null ? body : new FakeElement(selector);
- const document = { body, activeElement };
- const composerRef = {
- current: { focusAtEnd: () => (document.activeElement = editor) },
- } as unknown as ComposerHandleRef;
- vi.stubGlobal("Element", FakeElement);
- vi.stubGlobal("document", document);
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- let menuProps: ReturnType<typeof useComposerMenuProps> | undefined;
- function Probe() {
- const props = useComposerMenuProps();
- useLayoutEffect(() => {
- menuProps = props;
- }, [props]);
- return null;
- }
- const renderer = await act(() =>
- create(createElement(ComposerHandleContext, { value: composerRef }, createElement(Probe))),
- );
- try {
- expect(menuProps?.finalFocus?.()).toBe(false);
- expect(document.activeElement).toBe(shouldFocusComposer ? editor : activeElement);
- } finally {
- await act(() => renderer.unmount());
- }
- });
-});
-
-describe("composer event scopes", () => {
- it("recognizes events from the portaled resting controls", () => {
- vi.stubGlobal("Element", FakeElement);
-
- const target = new FakeElement('[data-chat-composer-resting-controls="true"]');
- expect(isInsideRestingComposerControlScope(target as unknown as EventTarget)).toBe(true);
- });
-
- it("recognizes events from the composer context strip controls", () => {
- vi.stubGlobal("Element", FakeElement);
-
- const target = new FakeElement("[data-composer-context-control]");
- expect(isInsideRestingComposerControlScope(target as unknown as EventTarget)).toBe(true);
- });
-
- it("keeps resting image previews focused without expanding their subtree", () => {
- vi.stubGlobal("Element", FakeElement);
-
- const target = new FakeElement('[data-chat-composer-resting-images="true"]');
- expect(isInsideRestingComposerControlScope(target as unknown as EventTarget)).toBe(true);
- });
-
- it("includes composer-owned floating layers in the resting control scope", () => {
- vi.stubGlobal("Element", FakeElement);
-
- const target = new FakeElement('[data-chat-composer-floating-layer="true"]');
- expect(isInsideComposerFloatingLayer(target as unknown as EventTarget)).toBe(true);
- expect(isInsideRestingComposerControlScope(target as unknown as EventTarget)).toBe(true);
- });
-
- it("leaves unrelated floating layers outside the composer scope", () => {
- vi.stubGlobal("Element", FakeElement);
-
- const target = new FakeElement('[data-slot="popover-popup"]');
- expect(isInsideComposerFloatingLayer(target as unknown as EventTarget)).toBe(false);
- expect(isInsideRestingComposerControlScope(target as unknown as EventTarget)).toBe(false);
- });
-
- it("leaves ordinary composer targets outside the portaled control scope", () => {
- vi.stubGlobal("Element", FakeElement);
-
- const target = new FakeElement(null);
- expect(isInsideRestingComposerControlScope(target as unknown as EventTarget)).toBe(false);
- expect(isInsideRestingComposerControlScope(null)).toBe(false);
- });
-
- it("recognizes banner and drawer controls docked above the surface", () => {
- vi.stubGlobal("Element", FakeElement);
-
- const target = new FakeElement('[data-chat-composer-collapsed-controls="true"]');
- expect(isInsideCollapsedComposerControls(target as unknown as EventTarget)).toBe(true);
- expect(isInsideCollapsedComposerControls(new FakeElement(null) as unknown as EventTarget)).toBe(
- false,
- );
- expect(isInsideCollapsedComposerControls(null)).toBe(false);
- });
-});
diff --git a/apps/web/src/components/chat/composerThreadImport.browser.test.tsx b/apps/web/src/components/chat/composerThreadImport.browser.test.tsx
new file mode 100644
index 00000000000..c0dbf9af16c
--- /dev/null
+++ b/apps/web/src/components/chat/composerThreadImport.browser.test.tsx
@@ -0,0 +1,105 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { act, useRef } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { importComposerThreadAttachment } from "./composerThreadImport";
+import { THREAD_CONTEXT_DROP_EVENT, useThreadContextDrop } from "./threadContextDrag";
+
+function deferredFile() {
+ let resolve!: (file: File) => void;
+ const promise = new Promise<File>((resolveFile) => {
+ resolve = resolveFile;
+ });
+ return { promise, resolve };
+}
+
+describe("importComposerThreadAttachment from a thread drop", () => {
+ it.each(["expand", "draft switch", "environment switch", "unmount"])(
+ "keeps import ownership correct after %s while loading",
+ async (change) => {
+ const target = new EventTarget();
+ const transcript = deferredFile();
+ const pendingImports = new Map<string, number>();
+ const attached: string[] = [];
+ const expandedAtDrop: boolean[] = [];
+ let importing!: Promise<void>;
+ function Composer({
+ environmentId,
+ targetKey,
+ expanded,
+ }: {
+ environmentId: EnvironmentId;
+ targetKey: string;
+ expanded: boolean;
+ }) {
+ const targetRef = useRef<EventTarget | null>(target);
+ useThreadContextDrop(targetRef, environmentId, targetKey, (_refs, isActive) => {
+ expandedAtDrop.push(expanded);
+ importing = importComposerThreadAttachment({
+ targetKey,
+ pendingImports,
+ countReservedAttachments: () => pendingImports.get(targetKey) ?? 0,
+ load: () => transcript.promise,
+ isActive,
+ attach: async (file) => {
+ attached.push(file.name);
+ return true;
+ },
+ onLimitReached: () => {
+ throw new Error("The slot should be available");
+ },
+ });
+ });
+ return null;
+ }
+
+ const props = {
+ environmentId: EnvironmentId.make("destination"),
+ targetKey: "draft",
+ expanded: false,
+ };
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ const root = createRoot(document.createElement("div"));
+ try {
+ act(() => root.render(<Composer {...props} />));
+ act(() => target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })));
+ expect(pendingImports.get("draft")).toBe(1);
+ if (change === "unmount") {
+ act(() => root.unmount());
+ } else {
+ act(() =>
+ root.render(
+ <Composer
+ {...props}
+ expanded
+ {...(change === "draft switch" ? { targetKey: "another-draft" } : {})}
+ {...(change === "environment switch"
+ ? { environmentId: EnvironmentId.make("another-environment") }
+ : {})}
+ />,
+ ),
+ );
+ if (change !== "expand") {
+ act(() => root.render(<Composer {...props} />));
+ }
+ }
+ transcript.resolve(new File(["transcript"], "thread.txt"));
+ await act(async () => importing);
+ expect(attached).toEqual(change === "expand" ? ["thread.txt"] : []);
+ expect(pendingImports.size).toBe(0);
+ if (change === "expand") {
+ act(() =>
+ target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })),
+ );
+ await act(async () => importing);
+ expect(expandedAtDrop).toEqual([false, true]);
+ expect(attached).toEqual(["thread.txt", "thread.txt"]);
+ }
+ } finally {
+ if (change !== "unmount") act(() => root.unmount());
+ vi.unstubAllGlobals();
+ }
+ },
+ );
+});
diff --git a/apps/web/src/components/chat/composerThreadImport.test.ts b/apps/web/src/components/chat/composerThreadImport.test.ts
index 3be253dfda9..446191854fd 100644
--- a/apps/web/src/components/chat/composerThreadImport.test.ts
+++ b/apps/web/src/components/chat/composerThreadImport.test.ts
@@ -1,6 +1,4 @@
-import { EnvironmentId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
-import { act, createElement, useRef } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
@@ -8,7 +6,6 @@ import {
importComposerThreadAttachment,
remainingComposerAttachmentSlots,
} from "./composerThreadImport";
-import { THREAD_CONTEXT_DROP_EVENT, useThreadContextDrop } from "./threadContextDrag";
function deferredFile() {
let resolve!: (file: File) => void;
@@ -21,96 +18,6 @@ function deferredFile() {
}
describe("importComposerThreadAttachment", () => {
- it.each(["expand", "draft switch", "environment switch", "unmount"])(
- "keeps import ownership correct after %s while loading",
- async (change) => {
- const target = new EventTarget();
- const transcript = deferredFile();
- const pendingImports = new Map<string, number>();
- const attached: string[] = [];
- const expandedAtDrop: boolean[] = [];
- let importing!: Promise<void>;
- function Composer({
- environmentId,
- targetKey,
- expanded,
- }: {
- environmentId: EnvironmentId;
- targetKey: string;
- expanded: boolean;
- }) {
- const targetRef = useRef<EventTarget | null>(target);
- useThreadContextDrop(targetRef, environmentId, targetKey, (_refs, isActive) => {
- expandedAtDrop.push(expanded);
- importing = importComposerThreadAttachment({
- targetKey,
- pendingImports,
- countReservedAttachments: () => pendingImports.get(targetKey) ?? 0,
- load: () => transcript.promise,
- isActive,
- attach: async (file) => {
- attached.push(file.name);
- return true;
- },
- onLimitReached: () => {
- throw new Error("The slot should be available");
- },
- });
- });
- return null;
- }
-
- const props = {
- environmentId: EnvironmentId.make("destination"),
- targetKey: "draft",
- expanded: false,
- };
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- let renderer: ReactTestRenderer | undefined;
- try {
- act(() => {
- renderer = create(createElement(Composer, props));
- });
- act(() => target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })));
- expect(pendingImports.get("draft")).toBe(1);
- if (change === "unmount") {
- act(() => renderer?.unmount());
- } else {
- act(() =>
- renderer?.update(
- createElement(Composer, {
- ...props,
- expanded: true,
- ...(change === "draft switch" ? { targetKey: "another-draft" } : {}),
- ...(change === "environment switch"
- ? { environmentId: EnvironmentId.make("another-environment") }
- : {}),
- }),
- ),
- );
- if (change !== "expand") {
- act(() => renderer?.update(createElement(Composer, props)));
- }
- }
- transcript.resolve(new File(["transcript"], "thread.txt"));
- await act(async () => importing);
- expect(attached).toEqual(change === "expand" ? ["thread.txt"] : []);
- expect(pendingImports.size).toBe(0);
- if (change === "expand") {
- act(() =>
- target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })),
- );
- await act(async () => importing);
- expect(expandedAtDrop).toEqual([false, true]);
- expect(attached).toEqual(["thread.txt", "thread.txt"]);
- }
- } finally {
- act(() => renderer?.unmount());
- vi.unstubAllGlobals();
- }
- },
- );
-
it("rejects the next drop before loading when the draft takes the final slot", async () => {
const targetKey = DraftId.make("thread-import-synchronous-admission");
const store = useComposerDraftStore.getState();
diff --git a/apps/web/src/components/chat/useComposerFocusState.test.tsx b/apps/web/src/components/chat/useComposerFocusState.browser.test.tsx
similarity index 79%
rename from apps/web/src/components/chat/useComposerFocusState.test.tsx
rename to apps/web/src/components/chat/useComposerFocusState.browser.test.tsx
index dd90f55c95a..da35cf05d39 100644
--- a/apps/web/src/components/chat/useComposerFocusState.test.tsx
+++ b/apps/web/src/components/chat/useComposerFocusState.browser.test.tsx
@@ -26,24 +26,8 @@ function ComposerProbe() {
}
beforeEach(async () => {
- // The probe has no DOM output, but ReactDOM needs an event target.
- const document = {
- nodeType: 9,
- addEventListener() {},
- removeEventListener() {},
- };
- const container = {
- nodeType: 1,
- tagName: "DIV",
- namespaceURI: "http://www.w3.org/1999/xhtml",
- ownerDocument: document,
- addEventListener() {},
- removeEventListener() {},
- };
- vi.stubGlobal("document", document);
- vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- root = createRoot(container as unknown as HTMLElement);
+ root = createRoot(document.createElement("div"));
await act(() => root.render(<ComposerProbe />));
});
diff --git a/apps/web/src/components/chat/useComposerMenuState.test.tsx b/apps/web/src/components/chat/useComposerMenuState.browser.test.tsx
similarity index 82%
rename from apps/web/src/components/chat/useComposerMenuState.test.tsx
rename to apps/web/src/components/chat/useComposerMenuState.browser.test.tsx
index f0f0c1ceb08..b444497032a 100644
--- a/apps/web/src/components/chat/useComposerMenuState.test.tsx
+++ b/apps/web/src/components/chat/useComposerMenuState.browser.test.tsx
@@ -30,25 +30,10 @@ async function renderMenu(hidden: boolean) {
}
beforeEach(() => {
- const document = {
- nodeType: 9,
- addEventListener() {},
- removeEventListener() {},
- };
- const container = {
- nodeType: 1,
- tagName: "DIV",
- namespaceURI: "http://www.w3.org/1999/xhtml",
- ownerDocument: document,
- addEventListener() {},
- removeEventListener() {},
- };
- vi.stubGlobal("document", document);
- vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
committedOpen = [];
closePopup = vi.fn();
- root = createRoot(container as unknown as HTMLElement);
+ root = createRoot(document.createElement("div"));
});
afterEach(async () => {
diff --git a/apps/web/src/components/chat/useComposerTriggerState.test.tsx b/apps/web/src/components/chat/useComposerTriggerState.browser.test.tsx
similarity index 90%
rename from apps/web/src/components/chat/useComposerTriggerState.test.tsx
rename to apps/web/src/components/chat/useComposerTriggerState.browser.test.tsx
index 387db3e4f58..03225f5249b 100644
--- a/apps/web/src/components/chat/useComposerTriggerState.test.tsx
+++ b/apps/web/src/components/chat/useComposerTriggerState.browser.test.tsx
@@ -25,23 +25,8 @@ async function updatePrompt(text: string, cursor = text.length) {
}
beforeEach(async () => {
- const document = {
- nodeType: 9,
- addEventListener() {},
- removeEventListener() {},
- };
- const container = {
- nodeType: 1,
- tagName: "DIV",
- namespaceURI: "http://www.w3.org/1999/xhtml",
- ownerDocument: document,
- addEventListener() {},
- removeEventListener() {},
- };
- vi.stubGlobal("document", document);
- vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- root = createRoot(container as unknown as HTMLElement);
+ root = createRoot(document.createElement("div"));
await act(() =>
root.render(
<StrictMode>
diff --git a/apps/web/src/components/chat/useThreadFind.test.tsx b/apps/web/src/components/chat/useThreadFind.browser.test.tsx
similarity index 94%
rename from apps/web/src/components/chat/useThreadFind.test.tsx
rename to apps/web/src/components/chat/useThreadFind.browser.test.tsx
index 4f534cbfa17..1b4080ba998 100644
--- a/apps/web/src/components/chat/useThreadFind.test.tsx
+++ b/apps/web/src/components/chat/useThreadFind.browser.test.tsx
@@ -1,5 +1,5 @@
-import { act, useLayoutEffect } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, useLayoutEffect, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
EnvironmentId,
@@ -39,7 +39,14 @@ vi.mock("~/state/query", () => ({
vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
-let renderer: ReactTestRenderer | undefined;
+type Rendered = { update: (node: ReactNode) => void; unmount: () => void };
+function render(node: ReactNode): Rendered {
+ const root = createRoot(document.createElement("div"));
+ root.render(node);
+ return { update: (next) => root.render(next), unmount: () => root.unmount() };
+}
+
+let renderer: Rendered | undefined;
let find: ReturnType<typeof useThreadFind>;
const a = EnvironmentId.make("environment:a");
const b = EnvironmentId.make("environment:b");
@@ -68,7 +75,6 @@ function Probe({
return null;
}
beforeEach(() => {
- vi.stubGlobal("window", new EventTarget());
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
});
afterEach(async () => {
@@ -93,7 +99,7 @@ describe("V2 find state", () => {
it("reveals an early match and updates its count without requesting another jump", async () => {
await act(async () => {
- renderer = create(<Probe environmentId={a} progressive />);
+ renderer = render(<Probe environmentId={a} progressive />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("needle"));
@@ -136,7 +142,7 @@ describe("V2 find state", () => {
vi.useFakeTimers();
queries.pending = true;
await act(async () => {
- renderer = create(<Probe environmentId={a} progressive />);
+ renderer = render(<Probe environmentId={a} progressive />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("needle"));
@@ -170,7 +176,7 @@ describe("V2 find state", () => {
it("requests a fresh jump when the same search wraps to the same match from a new position", async () => {
queries.results.set(a, messageResult(0));
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
find.timelineProps.findPositionReaderRef.current = () => ({
@@ -219,7 +225,7 @@ describe("V2 find state", () => {
};
queries.results.set(a, initial);
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -253,7 +259,7 @@ describe("V2 find state", () => {
};
queries.results.set(a, initial);
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -285,7 +291,7 @@ describe("V2 find state", () => {
};
queries.results.set(a, initial);
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -328,7 +334,7 @@ describe("V2 find state", () => {
};
queries.results.set(a, initial);
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -368,7 +374,7 @@ describe("V2 find state", () => {
};
queries.results.set(a, initial);
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -391,7 +397,7 @@ describe("V2 find state", () => {
it("starts from the viewport and steps from the server-selected match", async () => {
queries.results.set(a, messageResult(4));
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
find.timelineProps.findPositionReaderRef.current = () => ({
@@ -440,7 +446,7 @@ describe("V2 find state", () => {
it("accumulates rapid navigation against the same match until the response arrives", async () => {
queries.results.set(a, messageResult(4));
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -470,7 +476,7 @@ describe("V2 find state", () => {
vi.useFakeTimers();
queries.results.set(a, messageResult(4));
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -514,7 +520,7 @@ describe("V2 find state", () => {
vi.useFakeTimers();
queries.results.set(a, messageResult(4));
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -547,7 +553,7 @@ describe("V2 find state", () => {
it("does not navigate the previous result while a new match is loading", async () => {
queries.results.set(a, messageResult(0));
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -569,7 +575,7 @@ describe("V2 find state", () => {
it("keeps the reading-position start when Enter is pressed before results arrive", async () => {
queries.pending = true;
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
find.timelineProps.findPositionReaderRef.current = () => ({
@@ -592,7 +598,7 @@ describe("V2 find state", () => {
it("shows Searching only when the query has no result yet", async () => {
queries.pending = true;
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("COD4"));
@@ -615,7 +621,7 @@ describe("V2 find state", () => {
it("keeps search unavailable when the server does not support it", async () => {
await act(async () => {
- renderer = create(<Probe environmentId={a} enabled={false} />);
+ renderer = render(<Probe environmentId={a} enabled={false} />);
});
await act(async () => {
find.open();
@@ -628,7 +634,7 @@ describe("V2 find state", () => {
it("closes search when support disappears without restoring stale queries", async () => {
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => find.open());
await act(async () => find.barProps.onQueryChange("needle"));
@@ -657,7 +663,7 @@ describe("V2 find state", () => {
match: { entryId: "plan-item", runId, occurrence: 0 },
});
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => {
find.open();
@@ -691,7 +697,7 @@ describe("V2 find state", () => {
match: null,
});
await act(async () => {
- renderer = create(<Probe environmentId={a} />);
+ renderer = render(<Probe environmentId={a} />);
});
await act(async () => {
find.open();