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