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 markdown and timeline tests run in a real browser (#20905)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 06:10 UTC
da7c4f234db35096af2c16d5e24c60dbe9495583
11 files changed
+2405
-4521
apps/web/src/components/ChatMarkdown.assets.browser.test.tsx
new
+70
@@ -0,0 +1,70 @@
1
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
+import { AsyncResult } from "effect/reactivity";
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
+const mint = vi.hoisted(() => vi.fn());
8
+// Atoms derived from the server config run in the real registry over a missing config.
9
+vi.mock(import("../state/server"), async (original) => {
10
+ const actual = await original();
11
+ const { Atom } = await import("effect/reactivity");
12
+ const noConfig = Atom.make(null);
13
+ return {
14
+ ...actual,
15
+ serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
16
+ };
17
+});
18
+vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
19
+ ...(await original()),
20
+ useAtomQueryRunner: (() => mint) as never,
21
+}));
22
+vi.mock(import("../state/session"), async (original) => ({
23
+ ...(await original()),
24
+ readEnvironmentScope: () => false,
25
+ useEnvironmentScope: () => false,
26
+ readPreparedConnection: (() => ({ httpBaseUrl: "https://host.test" })) as never,
27
+}));
28
+
29
+import ChatMarkdown from "./ChatMarkdown";
30
+
31
+const roots: Root[] = [];
32
+beforeEach(() => vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true));
33
+afterEach(async () => {
34
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
35
+ document.body.replaceChildren();
36
+ vi.unstubAllGlobals();
37
+});
38
+
39
+it("opens host media through server authorization before the client grant loads", async () => {
40
+ mint.mockResolvedValue(
41
+ AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }),
42
+ );
43
+ const onImageExpand = vi.fn();
44
+ const container = document.body.appendChild(document.createElement("div"));
45
+ const root = createRoot(container);
46
+ roots.push(root);
47
+ await act(async () =>
48
+ root.render(
49
+ <ChatMarkdown
50
+ cwd="/repo"
51
+ threadRef={{
52
+ environmentId: EnvironmentId.make("media-environment"),
53
+ threadId: ThreadId.make("media-thread"),
54
+ }}
55
+ text="[Open image](/tmp/image.png)"
56
+ onImageExpand={onImageExpand}
57
+ />,
58
+ ),
59
+ );
60
+ const link = container.querySelector<HTMLAnchorElement>('a[href="/tmp/image.png"]');
61
+ expect(link).not.toBeNull();
62
+ await act(async () => link!.click());
63
+ await vi.waitFor(() =>
64
+ expect(onImageExpand).toHaveBeenCalledWith(
65
+ expect.objectContaining({
66
+ images: [expect.objectContaining({ src: "https://host.test/api/assets/image.png" })],
67
+ }),
68
+ ),
69
+ );
70
+});
apps/web/src/components/ChatMarkdown.assets.test.tsx
deleted
-119
@@ -1,119 +0,0 @@
1
-import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
-import { AsyncResult } from "effect/reactivity";
3
-import { act, type ComponentProps, type ReactNode } from "react";
4
-import { create, type ReactTestRenderer } from "react-test-renderer";
5
-import { expect, it, vi } from "vite-plus/test";
6
-
7
-const mint = vi.hoisted(() => vi.fn());
8
-// Atoms derived from the server config run in a real registry over a missing
9
-// config; every other subscription reads nothing.
10
-vi.mock("@effect/atom-react", async () => {
11
- const { AtomRegistry } = await import("effect/reactivity");
12
- const registry = AtomRegistry.make();
13
- const derived = new Set(["markdown-server-config-fields", "pull-request-link-mode"]);
14
- return {
15
- useAtomValue: (atom: { readonly label?: readonly [string, ...unknown[]] }) =>
16
- derived.has(atom.label?.[0] ?? "") ? registry.get(atom as never) : null,
17
- };
18
-});
19
-vi.mock("../state/server", async () => {
20
- const { Atom } = await import("effect/reactivity");
21
- const noConfig = Atom.make(null);
22
- return {
23
- serverEnvironment: { configValueAtom: () => noConfig },
24
- environmentServerConfigsAtom: Atom.make(new Map()),
25
- };
26
-});
27
-vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
28
-vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => undefined }));
29
-vi.mock("../hooks/useSettings", async (importOriginal) => {
30
- const actual = await importOriginal<typeof import("../hooks/useSettings")>();
31
- const settings = actual.getClientSettings();
32
- return {
33
- ...actual,
34
- useClientSettings: (select: (value: typeof settings) => unknown) => select(settings),
35
- };
36
-});
37
-vi.mock("./ui/tooltip", async () => {
38
- const { cloneElement, isValidElement } = await import("react");
39
- return {
40
- Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
41
- TooltipTrigger({
42
- render,
43
- children,
44
- }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
45
- if (!isValidElement(render)) return <>{children}</>;
46
- return children === undefined ? render : cloneElement(render, undefined, children);
47
- },
48
- TooltipPopup: () => null,
49
- };
50
-});
51
-vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => mint }));
52
-vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
53
-vi.mock("../state/session", async (importOriginal) => ({
54
- ...(await importOriginal<typeof import("../state/session")>()),
55
- readEnvironmentScope: () => false,
56
- useEnvironmentScope: () => false,
57
- readPreparedConnection: () => ({ httpBaseUrl: "https://host.test" }),
58
-}));
59
-vi.mock("../state/entities", () => ({
60
- readEnvironmentSupportsServerBrowser: () => false,
61
- readThreadShell: () => null,
62
- useProjects: () => [],
63
- useServerConfigs: () => new Map(),
64
-}));
65
-vi.mock("../remoteOpen", () => ({
66
- useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
67
-}));
68
-vi.mock("../editorPreferences", () => ({
69
- useOpenInPreferredEditor: () => vi.fn(),
70
- usePreferredEditor: () => [null, vi.fn()],
71
-}));
72
-vi.mock("~/lib/openPullRequestLink", () => ({
73
- findProjectForChangeRequest: () => undefined,
74
- matchesLinkedPullRequestUrl: () => false,
75
- parseChangeRequestUrl: () => null,
76
- useOpenChangeRequestLink: () => vi.fn(),
77
-}));
78
-
79
-import ChatMarkdown from "./ChatMarkdown";
80
-
81
-it("opens host media through server authorization before the client grant loads", async () => {
82
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
83
- mint.mockResolvedValue(
84
- AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }),
85
- );
86
- const onImageExpand = vi.fn();
87
- const threadRef = {
88
- environmentId: EnvironmentId.make("media-environment"),
89
- threadId: ThreadId.make("media-thread"),
90
- };
91
- let renderer: ReactTestRenderer | undefined;
92
- try {
93
- await act(async () => {
94
- renderer = create(
95
- <ChatMarkdown
96
- cwd="/repo"
97
- threadRef={threadRef}
98
- text="[Open image](/tmp/image.png)"
99
- onImageExpand={onImageExpand}
100
- />,
101
- );
102
- });
103
- await act(async () => {
104
- const link = renderer!.root
105
- .findAllByType("a")
106
- .find((node) => node.props.href === "/tmp/image.png");
107
- expect(link).toBeDefined();
108
- link!.props.onClick({ preventDefault: vi.fn(), stopPropagation: vi.fn() });
109
- });
110
- expect(onImageExpand).toHaveBeenCalledWith(
111
- expect.objectContaining({
112
- images: [expect.objectContaining({ src: "https://host.test/api/assets/image.png" })],
113
- }),
114
- );
115
- } finally {
116
- await act(async () => renderer?.unmount());
117
- vi.unstubAllGlobals();
118
- }
119
-});
apps/web/src/components/ChatMarkdown.browser.test.tsx
new
+848
@@ -0,0 +1,848 @@
1
+import { EnvironmentId } from "@t3tools/contracts";
2
+import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
3
+import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
4
+import { act, type ReactElement } 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 { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
9
+import { MarkdownFindContext } from "./chat/markdownFindContext";
10
+import { useThreadFindHighlights } from "./chat/threadFindHighlights";
11
+import { setMarkdownTaskChecked } from "./files/filePreviewMode";
12
+
13
+// Atoms derived from the server config run in the real registry over a missing config.
14
+vi.mock(import("../state/server"), async (original) => {
15
+ const actual = await original();
16
+ const { Atom } = await import("effect/reactivity");
17
+ const noConfig = Atom.make(null);
18
+ return {
19
+ ...actual,
20
+ serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
21
+ };
22
+});
23
+// A standard client session, so environment-owned file links can open.
24
+vi.mock(import("../state/session"), async (original) => {
25
+ const { AuthStandardClientScopes } = await import("@t3tools/contracts");
26
+ const granted = new Set<string>(AuthStandardClientScopes);
27
+ const hasScope = (environmentId: unknown, scope: string) =>
28
+ environmentId !== null && granted.has(scope);
29
+ return {
30
+ ...(await original()),
31
+ useEnvironmentScope: hasScope as never,
32
+ readEnvironmentScope: hasScope as never,
33
+ };
34
+});
35
+vi.mock(import("../remoteOpen"), async (original) => ({
36
+ ...(await original()),
37
+ useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
38
+}));
39
+// A rendered diagram is an SVG; real Mermaid layout is not what these tests exercise.
40
+vi.mock(import("./chat/MermaidDiagram"), async (original) => ({
41
+ ...(await original()),
42
+ MermaidDiagram: () => <svg aria-label="Diagram" />,
43
+}));
44
+
45
+import ChatMarkdown from "./ChatMarkdown";
46
+
47
+const roots: Root[] = [];
48
+
49
+beforeEach(() => {
50
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
51
+});
52
+
53
+afterEach(async () => {
54
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
55
+ document.body.replaceChildren();
56
+ CSS.highlights.clear();
57
+ vi.restoreAllMocks();
58
+ vi.unstubAllGlobals();
59
+});
60
+
61
+async function render(element: ReactElement) {
62
+ const container = document.body.appendChild(document.createElement("div"));
63
+ const root = createRoot(container);
64
+ roots.push(root);
65
+ await act(async () => root.render(element));
66
+ return {
67
+ container,
68
+ rerender: (next: ReactElement) => act(async () => root.render(next)),
69
+ };
70
+}
71
+
72
+async function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) {
73
+ return (await render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />)).container;
74
+}
75
+
76
+function linkTexts(container: HTMLElement) {
77
+ return [...container.querySelectorAll("a")].map((link) => link.textContent);
78
+}
79
+
80
+function buttonsLabelled(container: HTMLElement, label: string) {
81
+ return [...container.querySelectorAll<HTMLButtonElement>("button")].filter(
82
+ (button) => button.getAttribute("aria-label") === label,
83
+ );
84
+}
85
+
86
+function fileOptions(container: HTMLElement) {
87
+ return [...container.querySelectorAll("button")]
88
+ .map((button) => button.getAttribute("aria-label"))
89
+ .filter((label) => label?.startsWith("File options for "));
90
+}
91
+
92
+describe("ChatMarkdown bare anchor placeholders", () => {
93
+ it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
94
+ "preserves unmatched %s without linking later blocks",
95
+ async (token) => {
96
+ const container = await renderText(
97
+ `- **"From ${token}"** appears in the header.\n\n- **Tests:** cover inheritance.\n\nThe deferred move continues on B.\n\nSee <a href="https://example.com">the link</a>.`,
98
+ );
99
+ expect(container.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
100
+ expect(linkTexts(container)).toEqual(["the link"]);
101
+ expect(container.querySelectorAll("li")).toHaveLength(2);
102
+ expect([...container.querySelectorAll("p")].map((p) => p.textContent)).toContain(
103
+ "The deferred move continues on B.",
104
+ );
105
+ },
106
+ );
107
+
108
+ it.each(["</a> ", "<div>more</div>\n</a>"])(
109
+ "preserves a paired anchor closing in the raw block %s",
110
+ async (closing) => {
111
+ const container = await renderText(`See <a>label\n\n${closing}\n\nfinish`);
112
+ expect(container.querySelector("p")?.textContent).toBe("See label");
113
+ },
114
+ );
115
+
116
+ it("preserves a paired anchor after comment-looking raw text", async () => {
117
+ const container = await renderText("See <a>label<script><!-- </script> --></a>");
118
+ expect(container.querySelector("p")?.textContent).toBe("See label -->");
119
+ });
120
+
121
+ it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
122
+ "ignores apparent closing anchors inside %s",
123
+ async (html) => {
124
+ const container = await renderText(`Before <A>.\n\n${html}\n\nAfter.`);
125
+ expect(container.querySelector("p")?.textContent).toBe("Before <A>.");
126
+ expect(container.querySelectorAll("a")).toHaveLength(0);
127
+ },
128
+ );
129
+
130
+ it("preserves paired HTML anchors, details, markdown links, and inline code", async () => {
131
+ const container = await renderText(
132
+ 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>',
133
+ );
134
+ expect(linkTexts(container)).toEqual(["label", "", "docs"]);
135
+ expect(container.querySelector("code")?.textContent).toBe("<A>");
136
+ expect(container.querySelector("[data-markdown-details]")?.textContent).toContain("More");
137
+ });
138
+});
139
+
140
+describe("ChatMarkdown context references", () => {
141
+ it("renders text and image references through the chip renderer, with readable fallback", async () => {
142
+ const text =
143
+ "See [Terminal output](t3-context://v1/terminal/term-1) and .";
144
+ const { container, rerender } = await render(
145
+ <ChatMarkdown
146
+ cwd={undefined}
147
+ text={text}
148
+ renderContextReference={({ kind, label }) => (
149
+ <button>
150
+ {kind}: {label}
151
+ </button>
152
+ )}
153
+ />,
154
+ );
155
+ expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual([
156
+ "terminal: Terminal output",
157
+ "image: Error image",
158
+ ]);
159
+ expect(container.querySelectorAll("img, a")).toHaveLength(0);
160
+ await rerender(<ChatMarkdown cwd={undefined} text={text} />);
161
+ expect(container.textContent).toBe("See Terminal output and Error image.");
162
+ expect(container.querySelectorAll("img, a, button")).toHaveLength(0);
163
+ });
164
+
165
+ it("reads formatted context labels through nested markup instead of the context id", async () => {
166
+ const seen: Array<string> = [];
167
+ await render(
168
+ <ChatMarkdown
169
+ cwd={undefined}
170
+ text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
171
+ renderContextReference={({ kind, label }) => {
172
+ seen.push(`${kind}: ${label}`);
173
+ return <button>{label}</button>;
174
+ }}
175
+ />,
176
+ );
177
+ expect(new Set(seen)).toEqual(new Set(["terminal: Bold code"]));
178
+ });
179
+});
180
+
181
+describe("ChatMarkdown favicon privacy", () => {
182
+ it("suppresses private link images while preserving public links across updates", async () => {
183
+ const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
184
+ const { container, rerender } = await render(markdown("https://example.com"));
185
+ expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([
186
+ "https://www.google.com/s2/favicons?domain=example.com&sz=32",
187
+ ]);
188
+ for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
189
+ await rerender(markdown(url));
190
+ expect(container.querySelectorAll("img")).toHaveLength(0);
191
+ }
192
+ await rerender(markdown("https://example.com"));
193
+ expect(container.querySelectorAll("img")).toHaveLength(1);
194
+ await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1"));
195
+ expect(container.querySelectorAll("img")).toHaveLength(0);
196
+ expect(container.querySelector("a svg")).not.toBeNull();
197
+ });
198
+});
199
+
200
+describe("ChatMarkdown streaming", () => {
201
+ it("runs only a complete single-line shell block after a click", async () => {
202
+ const onRunShellCommand = vi.fn();
203
+ const message = (text: string, isStreaming = false) => (
204
+ <ChatMarkdown
205
+ cwd="/tmp/project"
206
+ text={text}
207
+ isStreaming={isStreaming}
208
+ onRunShellCommand={onRunShellCommand}
209
+ />
210
+ );
211
+ const { container, rerender } = await render(message("```bash\necho hello\n```", true));
212
+ const runButtons = () => buttonsLabelled(container, "Run in terminal");
213
+ expect(runButtons()).toHaveLength(0);
214
+
215
+ await rerender(message("```bash\necho hello\n```"));
216
+ await act(async () => runButtons()[0]!.click());
217
+ expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
218
+
219
+ for (const text of [
220
+ "~~~bash\necho tilde\n~~~",
221
+ "> ```bash\n> echo quote\n> ```",
222
+ "````bash\necho four\n````",
223
+ ]) {
224
+ await rerender(message(text));
225
+ expect(runButtons()).toHaveLength(1);
226
+ }
227
+
228
+ for (const text of [
229
+ "```bash\necho one\necho two\n```",
230
+ "```typescript\necho hello\n```",
231
+ "```bash\n\n```",
232
+ "```bash\necho hello\n\n```",
233
+ "```bash\necho hello\\\n```",
234
+ "```bash\necho safe \u202e#\n```",
235
+ "```bash\necho incomplete",
236
+ "~~~bash\necho incomplete",
237
+ "````bash\necho incomplete\n```",
238
+ '<pre><code class="language-bash">echo html</code></pre>',
239
+ ]) {
240
+ await rerender(message(text));
241
+ expect(runButtons()).toHaveLength(0);
242
+ }
243
+ });
244
+
245
+ it("does not retokenize completed lines when streaming finishes", async () => {
246
+ const highlighter = await getSyntaxHighlighterPromise("typescript");
247
+ const highlight = vi.spyOn(highlighter, "codeToHast");
248
+ const text = "```typescript\nconst completed = 1;\nconst current = 2;";
249
+ const { rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
250
+ await vi.waitFor(() => expect(highlight).toHaveBeenCalled());
251
+ highlight.mockClear();
252
+ await rerender(<ChatMarkdown cwd="/tmp/project" text={text + "\n```"} />);
253
+ expect(highlight.mock.calls.every(([code]) => !code.includes("const completed"))).toBe(true);
254
+ });
255
+
256
+ it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
257
+ const highlighter = await getSyntaxHighlighterPromise("text");
258
+ const codeToHast = highlighter.codeToHast.bind(highlighter);
259
+ let fail = true;
260
+ vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
261
+ if (fail) throw new Error("Temporary highlighter failure");
262
+ return codeToHast(...args);
263
+ });
264
+ vi.spyOn(console, "error").mockImplementation(() => {});
265
+ vi.spyOn(console, "warn").mockImplementation(() => {});
266
+
267
+ const { container, rerender } = await render(
268
+ <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
269
+ );
270
+ const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
271
+ const initialWrap = codeBlock.dataset.wrap === "true";
272
+ await act(async () =>
273
+ buttonsLabelled(container, initialWrap ? "Disable line wrap" : "Wrap lines")[0]!.click(),
274
+ );
275
+ expect(container.querySelectorAll(".chat-markdown-shiki")).toHaveLength(0);
276
+
277
+ fail = false;
278
+ await rerender(
279
+ <ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
280
+ );
281
+ await vi.waitFor(() =>
282
+ expect(container.querySelectorAll(".chat-markdown-shiki")).toHaveLength(1),
283
+ );
284
+ expect(container.querySelector('[data-language="text"]')).toBe(codeBlock);
285
+ expect(codeBlock.dataset.wrap).toBe(String(!initialWrap));
286
+ });
287
+
288
+ it("preserves code controls and details without highlighting an unchanged fence again", async () => {
289
+ const highlighter = await getSyntaxHighlighterPromise("text");
290
+ const highlight = vi.spyOn(highlighter, "codeToHast");
291
+ const writeText = vi
292
+ .spyOn(navigator.clipboard, "writeText")
293
+ .mockImplementation(async () => undefined);
294
+ const text = [
295
+ "```text",
296
+ "First code block",
297
+ "```",
298
+ "",
299
+ "<details><summary>More</summary>",
300
+ "",
301
+ "Details content",
302
+ "",
303
+ "</details>",
304
+ "",
305
+ "Streaming reply",
306
+ ].join("\n");
307
+
308
+ const { container, rerender } = await render(
309
+ <ChatMarkdown cwd="/tmp/project" text={text} isStreaming />,
310
+ );
311
+ const codeBlock = container.querySelector<HTMLElement>('[data-language="text"]')!;
312
+ const initialWrap = codeBlock.dataset.wrap === "true";
313
+ await act(async () => {
314
+ buttonsLabelled(container, initialWrap ? "Disable line wrap" : "Wrap lines")[0]!.click();
315
+ buttonsLabelled(container, "Copy code")[0]!.click();
316
+ });
317
+ await act(async () =>
318
+ container.querySelector<HTMLButtonElement>("[data-markdown-details-summary]")!.click(),
319
+ );
320
+ const details = container.querySelector<HTMLElement>("[data-markdown-details]")!;
321
+ expect(details.dataset.markdownDetailsOpen).toBe("true");
322
+ expect(container.textContent).toContain("Details content");
323
+ expect(writeText).toHaveBeenCalledWith("First code block\n");
324
+ expect(highlight).toHaveBeenCalledTimes(1);
325
+
326
+ for (let index = 0; index < 10; index += 1) {
327
+ await rerender(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
328
+ }
329
+
330
+ expect(highlight).toHaveBeenCalledTimes(1);
331
+ expect(container.querySelector('[data-language="text"]')).toBe(codeBlock);
332
+ expect(codeBlock.dataset.wrap).toBe(String(!initialWrap));
333
+ expect(container.querySelector("[data-markdown-details]")).toBe(details);
334
+ expect(details.dataset.markdownDetailsOpen).toBe("true");
335
+ await rerender(
336
+ <ChatMarkdown
337
+ cwd="/tmp/project"
338
+ text={text.replace("First code block", "Updated code block")}
339
+ isStreaming
340
+ />,
341
+ );
342
+ const copy = [
343
+ ...buttonsLabelled(container, "Copied"),
344
+ ...buttonsLabelled(container, "Copy code"),
345
+ ][0]!;
346
+ await act(async () => copy.click());
347
+ expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
348
+ expect(highlight).toHaveBeenCalledTimes(2);
349
+ });
350
+
351
+ it("edits the current task text and marker after reusing a renderer", async () => {
352
+ let editedText: string | undefined;
353
+ let rerender: (next: ReactElement) => Promise<void> = async () => {};
354
+ const message = (text: string): ReactElement => (
355
+ <ChatMarkdown
356
+ cwd="/tmp/project"
357
+ text={text}
358
+ onTaskListChange={({ markerOffset, checked }) => {
359
+ editedText = setMarkdownTaskChecked(text, markerOffset, checked);
360
+ void rerender(message(editedText));
361
+ }}
362
+ />
363
+ );
364
+ const rendered = await render(message("- [ ] First\n- [ ] Second"));
365
+ rerender = rendered.rerender;
366
+ const { container } = rendered;
367
+ const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
368
+ const original = checkboxes()[1]!;
369
+ await rerender(message("- [ ] A longer first task\n- [ ] Second"));
370
+ expect(checkboxes()[1]).toBe(original);
371
+
372
+ await act(async () => original.click());
373
+ expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
374
+ await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
375
+ });
376
+});
377
+
378
+describe("ChatMarkdown skill chips", () => {
379
+ it("updates digit-leading skill labels when discovered skills change", async () => {
380
+ const text = "Use $2spec with a $20k budget.";
381
+ const { container, rerender } = await render(<ChatMarkdown cwd="/tmp/project" text={text} />);
382
+ expect(container.textContent).not.toContain("2Spec");
383
+
384
+ await rerender(
385
+ <ChatMarkdown
386
+ cwd="/tmp/project"
387
+ text={text}
388
+ skills={[
389
+ { name: "2spec", displayName: "2Spec" },
390
+ { name: "20k", displayName: "MoneySkill" },
391
+ ]}
392
+ />,
393
+ );
394
+ expect(container.textContent).toContain("2Spec");
395
+ expect(container.textContent).toContain("$20k budget");
396
+ expect(container.textContent).not.toContain("MoneySkill");
397
+
398
+ await rerender(<ChatMarkdown cwd="/tmp/project" text={text} skills={[]} />);
399
+ expect(container.textContent).not.toContain("2Spec");
400
+ });
401
+});
402
+
403
+describe("ChatMarkdown file citations", () => {
404
+ it.each([true, false])(
405
+ "renders Codex file citations as file chips with parseRawHtml=%s",
406
+ async (parseRawHtml) => {
407
+ const container = await renderText(
408
+ 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.',
409
+ { lineBreaks: !parseRawHtml, parseRawHtml },
410
+ );
411
+ expect(container.textContent).not.toContain("codex-file-citation");
412
+ expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
413
+ },
414
+ );
415
+
416
+ it("leaves an unfinished streaming citation visible until it is complete", async () => {
417
+ const container = await renderText(
418
+ 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"',
419
+ { isStreaming: true },
420
+ );
421
+ expect(container.textContent).toContain(":codex-file-citation");
422
+ expect(fileOptions(container)).toEqual([]);
423
+ });
424
+
425
+ it.each([
426
+ ':codex-file-citation{purpose="output"}',
427
+ ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
428
+ 'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
429
+ ])("leaves %s literal", async (text) => {
430
+ const container = await renderText(text);
431
+ expect(container.textContent).toContain(text.replace("\\", ""));
432
+ expect(fileOptions(container)).toEqual([]);
433
+ });
434
+
435
+ it("preserves Codex file citation examples inside code", async () => {
436
+ const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
437
+ const container = await renderText(
438
+ `Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``,
439
+ );
440
+ expect(container.textContent?.match(/:codex-file-citation/g)).toHaveLength(2);
441
+ expect(fileOptions(container)).toEqual([]);
442
+ });
443
+
444
+ it("does not create a nested link for citations inside link text", async () => {
445
+ const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
446
+ const container = await renderText(`[See ${directive}](https://example.com)`);
447
+ expect(container.textContent).toContain("codex-file-citation");
448
+ expect(fileOptions(container)).toEqual([]);
449
+ });
450
+
451
+ it("renders file citations created by over-indented list recovery", async () => {
452
+ const container = await renderText(
453
+ '- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}',
454
+ );
455
+ expect(container.querySelector("pre")).toBeNull();
456
+ expect(container.querySelector("li")?.textContent).toContain("Created ");
457
+ expect(fileOptions(container)).toEqual(["File options for report.xlsx"]);
458
+ });
459
+
460
+ it("disambiguates Codex citations with the same basename", async () => {
461
+ const container = await renderText(
462
+ 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.',
463
+ );
464
+ expect(container.textContent).toContain("index.ts · project/src");
465
+ expect(container.textContent).toContain("index.ts · project/test");
466
+ });
467
+
468
+ it("preserves rejected citations created by over-indented list recovery", async () => {
469
+ const malformed = await renderText(
470
+ 'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}',
471
+ );
472
+ expect(malformed.querySelector("li")?.textContent).toBe(
473
+ 'Bad :codex-file-citation{purpose="output"}',
474
+ );
475
+ const nestedLink = await renderText(
476
+ 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)',
477
+ );
478
+ expect(nestedLink.textContent).toContain(
479
+ 'Bad :codex-file-citation{path="/tmp/project/report.xlsx"}',
480
+ );
481
+ });
482
+});
483
+
484
+describe("ChatMarkdown Codex follow-up suggestions", () => {
485
+ it.each([true, false])("renders the label with parseRawHtml=%s", async (parseRawHtml) => {
486
+ const container = await renderText(
487
+ 'Done.\n\n- :codex-followup[Prepare print version]{prompt="Prepare the document for printing."}',
488
+ { lineBreaks: !parseRawHtml, parseRawHtml },
489
+ );
490
+ expect(container.textContent).toContain("Prepare print version");
491
+ expect(container.textContent).not.toContain("codex-followup");
492
+ expect(container.textContent).not.toContain("Prepare the document for printing.");
493
+ });
494
+
495
+ it("keeps the label of a malformed follow-up created by over-indented list recovery", async () => {
496
+ const container = await renderText("- Next :codex-followup[Prepare print version]");
497
+ expect(container.querySelector("li")?.textContent).toBe(
498
+ "Next :codex-followup[Prepare print version]",
499
+ );
500
+ });
501
+});
502
+
503
+const ARTIFACT_TEMPLATE_DIRECTIVE =
504
+ '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
505
+
506
+describe("ChatMarkdown artifact-template cards", () => {
507
+ it.each([true, false])(
508
+ "offers the Codex template from its card with parseRawHtml=%s",
509
+ async (parseRawHtml) => {
510
+ const onUseArtifactTemplate = vi.fn();
511
+ const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE, {
512
+ parseRawHtml,
513
+ onUseArtifactTemplate,
514
+ });
515
+ expect(container.textContent).not.toContain("::artifact-template");
516
+ expect(container.textContent).toContain("Hello World");
517
+ expect(container.textContent).toContain("Document template");
518
+ expect(container.querySelector("p div")).toBeNull();
519
+ const use = [...container.querySelectorAll("button")].find(
520
+ (button) => button.textContent === "Use template",
521
+ )!;
522
+ await act(async () => use.click());
523
+ expect(onUseArtifactTemplate).toHaveBeenCalledWith(
524
+ expect.objectContaining({
525
+ skillName: "artifact-template-hello-world",
526
+ displayName: "Hello World",
527
+ }),
528
+ );
529
+ },
530
+ );
531
+
532
+ it("renders a passive card outside a composer-backed timeline", async () => {
533
+ const container = await renderText(ARTIFACT_TEMPLATE_DIRECTIVE);
534
+ expect(container.textContent).toContain("Hello World");
535
+ expect(container.textContent).not.toContain("Use template");
536
+ });
537
+
538
+ it.each([
539
+ '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}',
540
+ ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1),
541
+ `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
542
+ ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
543
+ ])("leaves %s literal", async (text) => {
544
+ const container = await renderText(text);
545
+ expect(container.textContent).toContain("::artifact-template");
546
+ expect(container.textContent).not.toContain("Document template");
547
+ });
548
+
549
+ it("preserves artifact-template examples inside code", async () => {
550
+ const container = await renderText(
551
+ `\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``,
552
+ );
553
+ expect(container.textContent?.match(/::artifact-template/g)).toHaveLength(2);
554
+ expect(container.textContent).not.toContain("Document template");
555
+ });
556
+});
557
+
558
+describe("ChatMarkdown headings", () => {
559
+ it("exposes headings below the host heading without changing their tags", async () => {
560
+ const container = await renderText("# Top\n\n## Section\n\n###### Fine print", {
561
+ headingLevelOffset: 3,
562
+ });
563
+ expect(
564
+ [...container.querySelectorAll("h1, h2, h6")].map((heading) => [
565
+ heading.tagName,
566
+ heading.getAttribute("aria-level"),
567
+ ]),
568
+ ).toEqual([
569
+ ["H1", "4"],
570
+ ["H2", "5"],
571
+ ["H6", "6"],
572
+ ]);
573
+ const flat = await renderText("# Top");
574
+ expect(flat.querySelector("h1")?.hasAttribute("aria-level")).toBe(false);
575
+ });
576
+
577
+ it("never gives two headings the same id, even when a suffix matches another heading", async () => {
578
+ const container = await renderText(
579
+ '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install',
580
+ { parseRawHtml: true },
581
+ );
582
+ expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([
583
+ "user-content-setup",
584
+ "user-content-setup-1",
585
+ "user-content-setup-1-1",
586
+ "user-content-install-1",
587
+ "user-content-install",
588
+ "user-content-install-2",
589
+ ]);
590
+ });
591
+});
592
+
593
+describe("ChatMarkdown Windows file links", () => {
594
+ const environmentId = EnvironmentId.make("env-windows");
595
+ const renderWindows = (text: string, parseRawHtml: boolean) =>
596
+ renderText(text, {
597
+ cwd: "C:/Users/shawn/project",
598
+ environmentId,
599
+ lineBreaks: !parseRawHtml,
600
+ parseRawHtml,
601
+ });
602
+ const fileHrefs = (container: HTMLElement) =>
603
+ [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) =>
604
+ chip.getAttribute("href"),
605
+ );
606
+
607
+ it.each([
608
+ ["drive paths", "[Open](C:/Users/shawn/project/src/main.ts)"],
609
+ ["backslashes", String.raw`[Open](C:\Users\shawn\project\src\main.ts)`],
610
+ ["reference links", "[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"],
611
+ ])("resolves %s to the workspace file", async (_, text) => {
612
+ for (const parseRawHtml of [true, false]) {
613
+ const container = await renderWindows(text, parseRawHtml);
614
+ expect(fileHrefs(container)).toEqual(["C:/Users/shawn/project/src/main.ts"]);
615
+ }
616
+ });
617
+
618
+ it("keeps backslashes CommonMark would read as escapes", async () => {
619
+ for (const parseRawHtml of [true, false]) {
620
+ const container = await renderWindows(
621
+ String.raw`[settings](C:\Users\shawn\.claude\settings.json)`,
622
+ parseRawHtml,
623
+ );
624
+ expect(fileHrefs(container)).toEqual(["C:/Users/shawn/.claude/settings.json"]);
625
+ }
626
+ });
627
+
628
+ it("distinguishes same-named backslash paths but not the same file twice", async () => {
629
+ for (const parseRawHtml of [true, false]) {
630
+ const distinct = await renderWindows(
631
+ String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`,
632
+ parseRawHtml,
633
+ );
634
+ expect(distinct.textContent).toContain("index.ts · project/src");
635
+ expect(distinct.textContent).toContain("index.ts · project/test");
636
+ const path = String.raw`C:\Users\shawn\project\src\main.ts`;
637
+ const same = await renderWindows(`[Source](${path}) and \`${path}\``, parseRawHtml);
638
+ expect(fileHrefs(same)).toHaveLength(2);
639
+ expect(same.textContent).not.toContain("main.ts ·");
640
+ }
641
+ });
642
+
643
+ it("still rejects unsafe schemes", async () => {
644
+ for (const parseRawHtml of [true, false]) {
645
+ const container = await renderWindows(
646
+ "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))",
647
+ parseRawHtml,
648
+ );
649
+ expect(container.innerHTML).not.toContain("javascript:");
650
+ expect(container.innerHTML).not.toContain("d:alert");
651
+ expect(fileHrefs(container)).toEqual([]);
652
+ }
653
+ });
654
+});
655
+
656
+describe("ChatMarkdown in-page links", () => {
657
+ it.each([true, false])(
658
+ "scrolls a table-of-contents link to its heading without touching the URL (parseRawHtml=%s)",
659
+ async (parseRawHtml) => {
660
+ const scrollIntoView = vi
661
+ .spyOn(HTMLElement.prototype, "scrollIntoView")
662
+ .mockImplementation(() => {});
663
+ const href = window.location.href;
664
+ const container = await renderText(
665
+ "- [Operating model](#1-operating-model)\n- [Missing](#nowhere)\n\n## 1. Operating model\n\n## 1. Operating model",
666
+ { parseRawHtml },
667
+ );
668
+ const headings = [...container.querySelectorAll("h2")];
669
+ expect(headings.map((heading) => heading.id)).toEqual([
670
+ "user-content-1-operating-model",
671
+ "user-content-1-operating-model-1",
672
+ ]);
673
+ const [tocLink, missingLink] = [...container.querySelectorAll("a")];
674
+ await act(async () => tocLink!.click());
675
+ expect(scrollIntoView.mock.contexts).toEqual([headings[0]]);
676
+ await act(async () => missingLink!.click());
677
+ expect(scrollIntoView).toHaveBeenCalledTimes(1);
678
+ expect(window.location.href).toBe(href);
679
+ },
680
+ );
681
+});
682
+
683
+describe("ChatMarkdown thread find", () => {
684
+ function FindProbe(props: {
685
+ container: HTMLElement;
686
+ query: string;
687
+ activeOccurrence?: number;
688
+ children: ReactElement;
689
+ }) {
690
+ useThreadFindHighlights({
691
+ container: props.container,
692
+ query: props.query,
693
+ activeRowId: "row",
694
+ activeOccurrence: props.activeOccurrence ?? 0,
695
+ onActiveRange: () => {},
696
+ });
697
+ return (
698
+ <div data-timeline-row-id="row">
699
+ <div data-thread-find-text>
700
+ <MarkdownFindContext value={props.query !== ""}>{props.children}</MarkdownFindContext>
701
+ </div>
702
+ </div>
703
+ );
704
+ }
705
+ const frame = () =>
706
+ act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
707
+ const activeHighlights = () =>
708
+ [...(CSS.highlights.get("t3-thread-find-active") ?? [])].map((range) =>
709
+ (range as Range).toString(),
710
+ );
711
+
712
+ it("opens a disclosure only when find selects a match inside it", async () => {
713
+ const container = document.body.appendChild(document.createElement("div"));
714
+ const root = createRoot(container);
715
+ roots.push(root);
716
+ const markdown = (
717
+ <ChatMarkdown
718
+ cwd={undefined}
719
+ text={[
720
+ "Visible needle.",
721
+ "<details><summary>Unrelated</summary><p>nothing here</p></details>",
722
+ "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",
723
+ ].join("\n\n")}
724
+ />
725
+ );
726
+ const show = (query: string, activeOccurrence: number) =>
727
+ act(() =>
728
+ root.render(
729
+ <FindProbe container={container} query={query} activeOccurrence={activeOccurrence}>
730
+ {markdown}
731
+ </FindProbe>,
732
+ ),
733
+ );
734
+ const openStates = () =>
735
+ [...container.querySelectorAll<HTMLElement>("[data-markdown-details-open]")].map(
736
+ (node) => node.dataset.markdownDetailsOpen,
737
+ );
738
+
739
+ await show("", 0);
740
+ expect(container.textContent).not.toContain("nothing here");
741
+ await show("needle", 0);
742
+ await frame();
743
+ expect(openStates()).toEqual(["false", "false", "false"]);
744
+ expect(container.textContent).toContain("nothing here");
745
+ expect(activeHighlights()).toEqual(["needle"]);
746
+ expect(CSS.highlights.get("t3-thread-find")?.size ?? 0).toBe(0);
747
+
748
+ await show("needle", 1);
749
+ await frame();
750
+ await frame();
751
+ expect(openStates()).toEqual(["false", "true", "true"]);
752
+ expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1);
753
+ });
754
+
755
+ it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
756
+ const container = document.body.appendChild(document.createElement("div"));
757
+ const root = createRoot(container);
758
+ roots.push(root);
759
+ const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
760
+ const show = (query: string) =>
761
+ act(() =>
762
+ root.render(
763
+ <FindProbe container={container} query={query}>
764
+ <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
765
+ </FindProbe>,
766
+ ),
767
+ );
768
+ const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
769
+
770
+ await show("Needle");
771
+ await frame();
772
+ expect(diagrams()).toBe(2);
773
+ await show("Alpha");
774
+ await frame();
775
+ await frame();
776
+ expect(diagrams()).toBe(1);
777
+ await vi.waitFor(() => expect(activeHighlights()).toEqual(["Alpha"]));
778
+ });
779
+
780
+ it.each([
781
+ {
782
+ text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",
783
+ query: "SearchSourceAlpha",
784
+ count: 1,
785
+ },
786
+ {
787
+ text: "★ Insight ─────\nfirst line\nsecond line",
788
+ query: "first line second",
789
+ count: 0,
790
+ lineBreaks: true,
791
+ },
792
+ { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },
793
+ { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },
794
+ { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },
795
+ { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },
796
+ { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },
797
+ {
798
+ text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",
799
+ query: "Hidden needle",
800
+ count: 1,
801
+ },
802
+ { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, withTemplate: true },
803
+ {
804
+ text: ARTIFACT_TEMPLATE_DIRECTIVE,
805
+ query: "Document template",
806
+ count: 1,
807
+ withTemplate: true,
808
+ },
809
+ { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, withTemplate: true },
810
+ { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, withTemplate: true },
811
+ ])(
812
+ "highlights the indexed occurrences of $query in $text",
813
+ async ({ text, query, count, lineBreaks, user, withTemplate }) => {
814
+ const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
815
+ const container = document.body.appendChild(document.createElement("div"));
816
+ const root = createRoot(container);
817
+ roots.push(root);
818
+ await act(() =>
819
+ root.render(
820
+ <FindProbe container={container} query={query}>
821
+ <ChatMarkdown
822
+ text={text}
823
+ cwd={undefined}
824
+ skills={skills}
825
+ lineBreaks={lineBreaks ?? false}
826
+ parseRawHtml={!user}
827
+ onUseArtifactTemplate={withTemplate ? () => undefined : undefined}
828
+ />
829
+ </FindProbe>,
830
+ ),
831
+ );
832
+ await frame();
833
+ const ranges = [...CSS.highlights.values()].flatMap((value) => [...value]);
834
+ expect(ranges.map((range) => (range as Range).toString())).toEqual(
835
+ Array.from({ length: count }, () => query),
836
+ );
837
+ const segments =
838
+ searchableMessageSegments(
839
+ { role: user ? "user" : "assistant", text, streaming: false },
840
+ undefined,
841
+ skills,
842
+ ) ?? [];
843
+ expect(
844
+ segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),
845
+ ).toBe(count);
846
+ },
847
+ );
848
+});
apps/web/src/components/ChatMarkdown.logic.test.ts
new
+55
@@ -0,0 +1,55 @@
1
+import { EnvironmentId } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import {
5
+ canUseMarkdownFileShellActions,
6
+ shouldUseMarkdownFileBrowserPrimaryAction,
7
+} from "./ChatMarkdown";
8
+
9
+describe("canUseMarkdownFileShellActions", () => {
10
+ const environmentId = EnvironmentId.make("environment-1");
11
+
12
+ it("allows editor and file manager actions only for resolved local environments", () => {
13
+ expect(canUseMarkdownFileShellActions(environmentId, "local-exec", true)).toBe(true);
14
+ expect(canUseMarkdownFileShellActions(environmentId, "local-exec", false)).toBe(false);
15
+ expect(canUseMarkdownFileShellActions(environmentId, "remote-links", true)).toBe(false);
16
+ expect(canUseMarkdownFileShellActions(environmentId, "remote-unavailable", true)).toBe(false);
17
+ expect(canUseMarkdownFileShellActions(null, "local-exec", true)).toBe(false);
18
+ });
19
+});
20
+
21
+describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
22
+ const html = { iconPath: "/tmp/report.html", canOpenInBrowser: true };
23
+
24
+ it("uses the browser only when it is the sole action, except for PDFs", () => {
25
+ expect(
26
+ shouldUseMarkdownFileBrowserPrimaryAction({
27
+ ...html,
28
+ canOpenInEditor: false,
29
+ canOpenInPanel: false,
30
+ }),
31
+ ).toBe(true);
32
+ expect(
33
+ shouldUseMarkdownFileBrowserPrimaryAction({
34
+ ...html,
35
+ canOpenInEditor: true,
36
+ canOpenInPanel: false,
37
+ }),
38
+ ).toBe(false);
39
+ expect(
40
+ shouldUseMarkdownFileBrowserPrimaryAction({
41
+ ...html,
42
+ canOpenInEditor: false,
43
+ canOpenInPanel: true,
44
+ }),
45
+ ).toBe(false);
46
+ expect(
47
+ shouldUseMarkdownFileBrowserPrimaryAction({
48
+ iconPath: "/tmp/report.pdf",
49
+ canOpenInEditor: true,
50
+ canOpenInBrowser: true,
51
+ canOpenInPanel: true,
52
+ }),
53
+ ).toBe(true);
54
+ });
55
+});
apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx
renamed
+90
-102
@@ -7,12 +7,13 @@ import {
7
type EditorId,
8
type ThreadLinkedPullRequest,
9
} from "@t3tools/contracts";
10
-import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
10
import { AsyncResult } from "effect/reactivity";
12
-import { cloneElement, type ReactElement, type ReactNode } from "react";
13
-import { act, create, type ReactTestRenderer } from "react-test-renderer";
11
+import { act } from "react";
12
+import { createRoot, type Root } from "react-dom/client";
13
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
14
15
+import { useRightPanelStore } from "../rightPanelStore";
16
+
17
const state = vi.hoisted(() => ({
18
allowed: true,
19
listeners: new Set<() => void>(),
@@ -23,48 +24,30 @@ const state = vi.hoisted(() => ({
24
openFile: vi.fn(),
25
openExternal: vi.fn(),
26
copy: vi.fn(),
26
- toast: vi.fn(),
27
linkedPullRequest: null as ThreadLinkedPullRequest | null,
28
}));
29
30
-vi.mock("@effect/atom-react", async () => {
31
- const { AtomRegistry } = await import("effect/reactivity");
32
- const registry = AtomRegistry.make();
33
- return { useAtomValue: (atom: never) => registry.get(atom) };
34
-});
35
-vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
36
-vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => undefined }));
37
-vi.mock("../hooks/useSettings", () => ({
38
- getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
39
- useClientSettings: (select?: (value: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
40
- select ? select(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS,
41
-}));
42
-vi.mock("./ui/tooltip", () => ({
43
- Tooltip: ({ children }: { children: ReactNode }) => children,
44
- TooltipTrigger: ({ render, children }: { render: ReactElement; children?: ReactNode }) =>
45
- children === undefined ? render : cloneElement(render, undefined, children),
46
- TooltipPopup: () => null,
47
-}));
48
-vi.mock("./chat/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
49
-vi.mock("./ui/toast", () => ({
50
- toastManager: { add: state.toast },
51
- stackedThreadToast: (value: unknown) => value,
52
-}));
53
-vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.search }));
54
-vi.mock("../state/use-atom-command", () => ({
55
- useAtomCommand: (command: string) =>
56
- command === "updateMetadata" ? state.updateMetadata : state.openEditor,
30
+vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
31
+ ...(await original()),
32
+ useAtomQueryRunner: (() => state.search) as never,
33
}));
58
-vi.mock("../state/session", async () => {
34
+vi.mock(import("../state/use-atom-command"), async (original) => {
35
+ const { threadEnvironment } = await import("../state/threads");
36
+ return {
37
+ ...(await original()),
38
+ useAtomCommand: ((command: unknown) =>
39
+ command === threadEnvironment.updateMetadata
40
+ ? state.updateMetadata
41
+ : state.openEditor) as never,
42
+ };
43
+});
44
+vi.mock(import("../state/session"), async (original) => {
45
const { useSyncExternalStore } = await import("react");
46
const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
47
id !== null &&
48
(scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
49
return {
64
- environmentSession: {
65
- sessionStateAtom: () => ({}),
66
- preparedConnectionValueAtom: () => ({}),
67
- },
50
+ ...(await original()),
51
readEnvironmentScope,
52
useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
53
useSyncExternalStore(
@@ -76,59 +59,57 @@ vi.mock("../state/session", async () => {
59
),
60
};
61
});
79
-vi.mock("../state/server", async () => {
62
+// Atoms derived from the server config run in the real registry over this config.
63
+vi.mock(import("../state/server"), async (original) => {
64
+ const actual = await original();
65
const { Atom } = await import("effect/reactivity");
66
const config = Atom.make(() => serverConfig);
67
return {
83
- serverEnvironment: { configValueAtom: () => config },
68
+ ...actual,
69
+ serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
70
environmentServerConfigsAtom: Atom.make(
71
() => new Map([[threadRef.environmentId, serverConfig]]),
86
- ),
72
+ ) as never,
73
};
74
});
89
-vi.mock("../state/threads", () => ({
90
- threadEnvironment: { updateMetadata: "updateMetadata" },
91
-}));
92
-vi.mock("../state/entities", () => ({
93
- readEnvironmentSupportsServerBrowser: () => false,
94
- readThreadShell: () => ({ linkedPullRequest: state.linkedPullRequest }),
95
- useProjects: () => [{ id: linkedPullRequest.projectId, environmentId: threadRef.environmentId }],
75
+vi.mock(import("../state/entities"), async (original) => ({
76
+ ...(await original()),
77
+ readThreadShell: (() => ({ linkedPullRequest: state.linkedPullRequest })) as never,
78
+ useProjects: (() => [
79
+ { id: linkedPullRequest.projectId, environmentId: threadRef.environmentId },
80
+ ]) as never,
81
}));
97
-vi.mock("../rightPanelStore", () => ({
98
- useRightPanelStore: { getState: () => ({ openFile: state.openFile }) },
82
+vi.mock(import("../remoteOpen"), async (original) => ({
83
+ ...(await original()),
84
+ useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
85
}));
100
-vi.mock("../remoteOpen", () => ({
101
- useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
86
+vi.mock(import("../hooks/useLocalStorage"), async (original) => ({
87
+ ...(await original()),
88
+ useLocalStorage: (() => ["vscode", vi.fn()]) as never,
89
+ getLocalStorageItem: (() => "vscode") as never,
90
}));
103
-vi.mock("../hooks/useLocalStorage", () => ({
104
- useLocalStorage: () => ["vscode", vi.fn()],
105
- getLocalStorageItem: () => "vscode",
106
- setLocalStorageItem: vi.fn(),
91
+vi.mock(import("../localApi"), async (original) => ({
92
+ ...(await original()),
93
+ readLocalApi: () =>
94
+ ({
95
+ contextMenu: { show: state.choose },
96
+ shell: { openExternal: state.openExternal },
97
+ }) as never,
98
}));
108
-vi.mock("../hooks/useCopyToClipboard", () => ({
109
- writeTextToClipboard: state.copy,
110
- useCopyToClipboard: () => ({ copyToClipboard: state.copy, isCopied: false }),
111
-}));
112
-vi.mock("../localApi", () => ({
113
- readLocalApi: () => ({
114
- contextMenu: { show: state.choose },
115
- shell: { openExternal: state.openExternal },
116
- }),
117
-}));
118
-vi.mock("~/lib/openPullRequestLink", () => ({
99
+vi.mock(import("~/lib/openPullRequestLink"), async (original) => ({
100
+ ...(await original()),
101
resolvePullRequestPreviewTarget: () => null,
120
- findProjectForChangeRequest: (projects: readonly { id: ProjectId }[]) => projects[0],
102
+ findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
103
matchesLinkedPullRequestUrl: (candidate: ThreadLinkedPullRequest, href: string) =>
104
candidate.url === href,
123
- parseChangeRequestUrl: (href: string) =>
105
+ parseChangeRequestUrl: ((href: string) =>
106
href === linkedPullRequest.url
107
? {
108
host: "github.com",
109
repository: linkedPullRequest.repository,
110
number: linkedPullRequest.number,
111
}
130
- : null,
131
- useOpenChangeRequestLink: () => vi.fn(),
112
+ : null) as never,
113
}));
114
115
import ChatMarkdown from "./ChatMarkdown";
@@ -149,7 +130,8 @@ const serverConfig = {
130
shellRevealInFileManagerKind: "xdg-open",
131
environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
132
};
152
-let renderer: ReactTestRenderer | undefined;
133
+const roots: Root[] = [];
134
+let container: HTMLDivElement;
135
136
beforeEach(() => {
137
state.allowed = true;
@@ -162,53 +144,60 @@ beforeEach(() => {
144
state.openFile.mockReset();
145
state.openExternal.mockReset().mockResolvedValue(undefined);
146
state.copy.mockReset().mockResolvedValue(undefined);
165
- state.toast.mockReset();
147
+ useRightPanelStore.setState({ openFile: state.openFile });
148
+ vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy);
149
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
167
- vi.stubGlobal("window", {});
168
- vi.stubGlobal("navigator", { clipboard: { writeText: state.copy } });
150
});
151
152
afterEach(async () => {
172
- await act(async () => renderer?.unmount());
173
- renderer = undefined;
153
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
154
+ document.body.replaceChildren();
155
+ vi.restoreAllMocks();
156
vi.unstubAllGlobals();
157
});
158
159
async function renderMarkdown(text: string) {
178
- await act(async () => {
179
- renderer = create(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
180
- });
181
-}
182
-
183
-function menuEvent() {
184
- return { preventDefault: vi.fn(), stopPropagation: vi.fn(), clientX: 10, clientY: 10 };
160
+ container = document.body.appendChild(document.createElement("div"));
161
+ const root = createRoot(container);
162
+ roots.push(root);
163
+ await act(async () =>
164
+ root.render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />),
165
+ );
166
}
167
168
function anchor() {
188
- return renderer!.root.findByType("a");
169
+ return container.querySelector("a")!;
170
}
171
172
async function openContextMenu() {
192
- await act(async () => anchor().props.onContextMenu(menuEvent()));
173
+ await act(async () => {
174
+ anchor().dispatchEvent(
175
+ new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }),
176
+ );
177
+ });
178
}
179
180
function offeredActions() {
181
return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
182
}
183
184
+async function setAllowed(allowed: boolean) {
185
+ await act(async () => {
186
+ state.allowed = allowed;
187
+ for (const listener of state.listeners) listener();
188
+ });
189
+}
190
+
191
it("removes host actions after revocation while keeping file preview and copying", async () => {
192
await renderMarkdown("[Readme](docs/readme.md)");
193
await openContextMenu();
194
expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
203
- await act(async () => {
204
- state.allowed = false;
205
- for (const listener of state.listeners) listener();
206
- });
195
+ await setAllowed(false);
196
state.choose.mockResolvedValue("copy-full");
197
await openContextMenu();
198
expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
210
- expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md");
211
- await act(async () => anchor().props.onClick(menuEvent()));
199
+ await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
200
+ await act(async () => anchor().click());
201
expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
202
expect(state.openEditor).not.toHaveBeenCalled();
203
});
@@ -263,7 +252,7 @@ it.each([false, true])(
252
await renderMarkdown(`[Review](${linkedPullRequest.url})`);
253
await openContextMenu();
254
expect(offeredActions()).toEqual(["open-external", "copy-link"]);
266
- expect(state.openExternal).toHaveBeenCalledWith(linkedPullRequest.url);
255
+ await vi.waitFor(() => expect(state.openExternal).toHaveBeenCalledWith(linkedPullRequest.url));
256
expect(state.updateMetadata).not.toHaveBeenCalled();
257
},
258
);
@@ -290,18 +279,17 @@ it.each(["link-to-thread", "unlink-from-thread"])(
279
});
280
expect(state.updateMetadata).not.toHaveBeenCalled();
281
293
- await act(async () => {
294
- state.allowed = true;
295
- for (const listener of state.listeners) listener();
296
- });
282
+ await setAllowed(true);
283
state.choose.mockResolvedValue(action);
284
await openContextMenu();
299
- expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
300
- environmentId: threadRef.environmentId,
301
- input: {
302
- threadId: threadRef.threadId,
303
- linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
304
- },
305
- });
285
+ await vi.waitFor(() =>
286
+ expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
287
+ environmentId: threadRef.environmentId,
288
+ input: {
289
+ threadId: threadRef.threadId,
290
+ linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
291
+ },
292
+ }),
293
+ );
294
},
295
);
apps/web/src/components/ChatMarkdown.test.tsx
deleted
-1391
@@ -1,1391 +0,0 @@
1
-// @vitest-environment jsdom
2
-
3
-import { EnvironmentId, type AuthEnvironmentScope } from "@t3tools/contracts";
4
-import { createRoot } from "react-dom/client";
5
-import { useThreadFindHighlights } from "./chat/threadFindHighlights";
6
-import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
7
-import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
8
-
9
-import { MarkdownFindContext } from "./chat/markdownFindContext";
10
-import { act, type ComponentProps, type ReactNode } from "react";
11
-import { renderToStaticMarkup } from "react-dom/server";
12
-import { create, type ReactTestRenderer } from "react-test-renderer";
13
-import { describe, expect, it, vi } from "vite-plus/test";
14
-
15
-import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
16
-import { GitHubIcon } from "./Icons";
17
-import { Button } from "./ui/button";
18
-import { setMarkdownTaskChecked } from "./files/filePreviewMode";
19
-
20
-vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => null }));
21
-// Atoms derived from the server config run in a real registry over a missing
22
-// config; every other subscription reads nothing.
23
-vi.mock("@effect/atom-react", async () => {
24
- const { AtomRegistry } = await import("effect/reactivity");
25
- const registry = AtomRegistry.make();
26
- const derived = new Set(["markdown-server-config-fields", "pull-request-link-mode"]);
27
- return {
28
- useAtomValue: (atom: { readonly label?: readonly [string, ...unknown[]] }) =>
29
- derived.has(atom.label?.[0] ?? "") ? registry.get(atom as never) : null,
30
- };
31
-});
32
-vi.mock("../state/server", async () => {
33
- const { Atom } = await import("effect/reactivity");
34
- const noConfig = Atom.make(null);
35
- return {
36
- serverEnvironment: { configValueAtom: () => noConfig },
37
- environmentServerConfigsAtom: Atom.make(new Map()),
38
- };
39
-});
40
-vi.mock("./chat/MermaidDiagram", () => ({
41
- // Real Mermaid needs layout APIs jsdom lacks; a rendered diagram is an SVG.
42
- MermaidDiagram: () => <svg aria-label="Diagram" />,
43
-}));
44
-vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
45
-vi.mock("../hooks/useSettings", async (importOriginal) => {
46
- const actual = await importOriginal<typeof import("../hooks/useSettings")>();
47
- const settings = actual.getClientSettings();
48
- return {
49
- ...actual,
50
- useClientSettings: (select?: (value: typeof settings) => unknown) =>
51
- select ? select(settings) : settings,
52
- };
53
-});
54
-vi.mock("./ui/tooltip", async () => {
55
- const { cloneElement, isValidElement } = await import("react");
56
- return {
57
- Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
58
- TooltipTrigger({
59
- render,
60
- children,
61
- }: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
62
- if (!isValidElement(render)) return <>{children}</>;
63
- return children === undefined ? render : cloneElement(render, undefined, children);
64
- },
65
- TooltipPopup: () => null,
66
- };
67
-});
68
-vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
69
-vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
70
-vi.mock("../state/session", async (importOriginal) => {
71
- const actual = await importOriginal<typeof import("../state/session")>();
72
- const { AuthStandardClientScopes } = await import("@t3tools/contracts");
73
- const grantedScopes = new Set<AuthEnvironmentScope>(AuthStandardClientScopes);
74
- const hasScope = (environmentId: EnvironmentId | null, scope: AuthEnvironmentScope) =>
75
- environmentId !== null && grantedScopes.has(scope);
76
- return {
77
- ...actual,
78
- useEnvironmentScope: hasScope,
79
- readEnvironmentScope: hasScope,
80
- };
81
-});
82
-vi.mock("../state/entities", () => ({
83
- readThreadShell: () => null,
84
- useProjects: () => [],
85
- useServerConfigs: () => new Map(),
86
-}));
87
-vi.mock("../remoteOpen", () => ({
88
- useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
89
-}));
90
-vi.mock("../editorPreferences", () => ({
91
- useOpenInPreferredEditor: () => vi.fn(),
92
- usePreferredEditor: () => [null, vi.fn()],
93
-}));
94
-vi.mock("~/lib/openPullRequestLink", () => ({
95
- findProjectOnChangeRequestHost: () => undefined,
96
- parseChangeRequestUrl: () => null,
97
- resolvePullRequestPreviewTarget: () => null,
98
- useOpenChangeRequestLink: () => vi.fn(),
99
-}));
100
-
101
-import ChatMarkdown, {
102
- canUseMarkdownFileShellActions,
103
- hasMarkdownFilePrimaryAction,
104
- shouldUseMarkdownFileBrowserPrimaryAction,
105
-} from "./ChatMarkdown";
106
-
107
-function codeButton(renderer: ReactTestRenderer, label: string) {
108
- const button = renderer.root
109
- .findAllByType(Button)
110
- .find((instance) => instance.props["aria-label"] === label);
111
- if (!button) throw new Error(`Missing code button: ${label}`);
112
- return button.props as ComponentProps<typeof Button>;
113
-}
114
-
115
-describe("ChatMarkdown bare anchor placeholders", () => {
116
- it.each(["<A>", "<a>", "<a >", "<a/>", "<A/>", "<a />"])(
117
- "preserves unmatched %s without linking later blocks",
118
- (token) => {
119
- const text = `- **"From ${token}"** appears in the header.\n\n- **Tests:** cover inheritance.\n\nThe deferred move continues on B.\n\nSee <a href="https://example.com">the link</a>.`;
120
- const document = new DOMParser().parseFromString(
121
- renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
122
- "text/html",
123
- );
124
-
125
- expect(document.querySelector("strong")?.textContent).toBe(`"From ${token}"`);
126
- expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
127
- "the link",
128
- ]);
129
- expect(document.querySelectorAll("li")).toHaveLength(2);
130
- expect(
131
- [...document.querySelectorAll("p")].map((paragraph) => paragraph.textContent),
132
- ).toContain("The deferred move continues on B.");
133
- },
134
- );
135
-
136
- it.each(["</a> ", "<div>more</div>\n</a>"])(
137
- "preserves a paired anchor closing in the raw block %s",
138
- (closing) => {
139
- const document = new DOMParser().parseFromString(
140
- renderToStaticMarkup(
141
- <ChatMarkdown cwd="/tmp/project" text={`See <a>label\n\n${closing}\n\nfinish`} />,
142
- ),
143
- "text/html",
144
- );
145
- expect(document.querySelector("p")?.textContent).toBe("See label");
146
- },
147
- );
148
-
149
- it("preserves a paired anchor after comment-looking raw text", () => {
150
- const document = new DOMParser().parseFromString(
151
- renderToStaticMarkup(
152
- <ChatMarkdown cwd="/tmp/project" text="See <a>label<script><!-- </script> --></a>" />,
153
- ),
154
- "text/html",
155
- );
156
- expect(document.querySelector("p")?.textContent).toBe("See label -->");
157
- });
158
-
159
- it.each(["<!-- </a> -->", '<div title="</a>">more</div>', '<script>"</a>"</script>'])(
160
- "ignores apparent closing anchors inside %s",
161
- (html) => {
162
- const document = new DOMParser().parseFromString(
163
- renderToStaticMarkup(
164
- <ChatMarkdown cwd="/tmp/project" text={`Before <A>.\n\n${html}\n\nAfter.`} />,
165
- ),
166
- "text/html",
167
- );
168
- expect(document.querySelector("p")?.textContent).toBe("Before <A>.");
169
- expect(document.querySelectorAll("a")).toHaveLength(0);
170
- },
171
- );
172
-
173
- it("preserves paired HTML anchors, details, markdown links, and inline code", () => {
174
- const text =
175
- 'Bare <a>label</a>, <a id="section"></a>, `<A>`, and [docs](https://example.com).\n\n<details><summary>More</summary>Details</details>';
176
- const document = new DOMParser().parseFromString(
177
- renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />),
178
- "text/html",
179
- );
180
-
181
- expect([...document.querySelectorAll("a")].map((link) => link.textContent)).toEqual([
182
- "label",
183
- "",
184
- "docs",
185
- ]);
186
- expect(document.querySelector("code")?.textContent).toBe("<A>");
187
- expect(document.querySelector("[data-markdown-details]")?.textContent).toContain("More");
188
- });
189
-});
190
-
191
-describe("ChatMarkdown context references", () => {
192
- it("renders text and image references through the chip renderer, with readable fallback", async () => {
193
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
194
- let renderer: ReactTestRenderer | undefined;
195
- const text =
196
- "See [Terminal output](t3-context://v1/terminal/term-1) and .";
197
- try {
198
- await act(async () => {
199
- renderer = create(
200
- <ChatMarkdown
201
- cwd={undefined}
202
- text={text}
203
- renderContextReference={({ kind, label }) => (
204
- <button>
205
- {kind}: {label}
206
- </button>
207
- )}
208
- />,
209
- );
210
- });
211
- expect(
212
- renderer!.root.findAllByType("button").map((button) => button.children.join("")),
213
- ).toEqual(["terminal: Terminal output", "image: Error image"]);
214
- expect(renderer!.root.findAllByType("img")).toHaveLength(0);
215
- expect(renderer!.root.findAllByType("a")).toHaveLength(0);
216
- await act(async () => {
217
- renderer!.update(<ChatMarkdown cwd={undefined} text={text} />);
218
- });
219
- expect(renderer!.root.findAllByType("span").map((span) => span.children.join(""))).toEqual([
220
- "Terminal output",
221
- "Error image",
222
- ]);
223
- expect(renderer!.root.findAllByType("img")).toHaveLength(0);
224
- } finally {
225
- await act(async () => {
226
- renderer?.unmount();
227
- });
228
- vi.unstubAllGlobals();
229
- }
230
- });
231
-
232
- it("reads formatted context labels through nested markup instead of the context id", async () => {
233
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
234
- let renderer: ReactTestRenderer | undefined;
235
- const seen: Array<string> = [];
236
- try {
237
- await act(async () => {
238
- renderer = create(
239
- <ChatMarkdown
240
- cwd={undefined}
241
- text="See [**Bold** `code`](t3-context://v1/terminal/term-1)."
242
- renderContextReference={({ kind, label }) => {
243
- seen.push(`${kind}: ${label}`);
244
- return <button>{label}</button>;
245
- }}
246
- />,
247
- );
248
- });
249
- expect(seen).toEqual(["terminal: Bold code"]);
250
- } finally {
251
- await act(async () => {
252
- renderer?.unmount();
253
- });
254
- vi.unstubAllGlobals();
255
- }
256
- });
257
-});
258
-
259
-describe("ChatMarkdown favicon privacy", () => {
260
- it("suppresses private link images while preserving public links across updates", async () => {
261
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
262
- let renderer: ReactTestRenderer | undefined;
263
- const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
264
- try {
265
- await act(async () => {
266
- renderer = create(markdown("https://example.com"));
267
- });
268
- expect(renderer!.root.findAllByType("img").map((image) => image.props.src)).toEqual([
269
- "https://www.google.com/s2/favicons?domain=example.com&sz=32",
270
- ]);
271
- for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
272
- await act(async () => {
273
- renderer!.update(markdown(url));
274
- });
275
- expect(renderer!.root.findAllByType("img")).toHaveLength(0);
276
- }
277
- await act(async () => {
278
- renderer!.update(markdown("https://example.com"));
279
- });
280
- expect(renderer!.root.findAllByType("img")).toHaveLength(1);
281
- await act(async () => {
282
- renderer!.update(markdown("https://github.com/pingdotgg/t3code/pull/1"));
283
- });
284
- expect(renderer!.root.findAllByType("img")).toHaveLength(0);
285
- expect(renderer!.root.findAllByType(GitHubIcon)).toHaveLength(1);
286
- } finally {
287
- await act(async () => {
288
- renderer?.unmount();
289
- });
290
- vi.unstubAllGlobals();
291
- }
292
- });
293
-});
294
-
295
-describe("ChatMarkdown streaming", () => {
296
- it("runs only a complete single-line shell block after a click", async () => {
297
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
298
- const onRunShellCommand = vi.fn();
299
- let renderer: ReactTestRenderer | undefined;
300
- const message = (text: string, isStreaming = false) => (
301
- <ChatMarkdown
302
- cwd="/tmp/project"
303
- text={text}
304
- isStreaming={isStreaming}
305
- onRunShellCommand={onRunShellCommand}
306
- />
307
- );
308
- try {
309
- await act(async () => {
310
- renderer = create(message("```bash\necho hello\n```", true));
311
- });
312
- const mounted = renderer!;
313
- expect(
314
- mounted.root
315
- .findAllByType(Button)
316
- .some((button) => button.props["aria-label"] === "Run in terminal"),
317
- ).toBe(false);
318
-
319
- await act(async () => {
320
- mounted.update(message("```bash\necho hello\n```"));
321
- });
322
- await act(async () => {
323
- codeButton(mounted, "Run in terminal").onClick?.({} as never);
324
- });
325
- expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello");
326
-
327
- for (const text of [
328
- "~~~bash\necho tilde\n~~~",
329
- "> ```bash\n> echo quote\n> ```",
330
- "````bash\necho four\n````",
331
- ]) {
332
- await act(async () => {
333
- mounted.update(message(text));
334
- });
335
- expect(codeButton(mounted, "Run in terminal")).toBeDefined();
336
- }
337
-
338
- for (const text of [
339
- "```bash\necho one\necho two\n```",
340
- "```typescript\necho hello\n```",
341
- "```bash\n\n```",
342
- "```bash\necho hello\n\n```",
343
- "```bash\necho hello\\\n```",
344
- "```bash\necho safe \u202e#\n```",
345
- "```bash\necho incomplete",
346
- "~~~bash\necho incomplete",
347
- "````bash\necho incomplete\n```",
348
- '<pre><code class="language-bash">echo html</code></pre>',
349
- ]) {
350
- await act(async () => {
351
- mounted.update(message(text));
352
- });
353
- expect(
354
- mounted.root
355
- .findAllByType(Button)
356
- .some((button) => button.props["aria-label"] === "Run in terminal"),
357
- ).toBe(false);
358
- }
359
- } finally {
360
- await act(async () => renderer?.unmount());
361
- vi.unstubAllGlobals();
362
- }
363
- });
364
-
365
- it("does not retokenize completed lines when streaming finishes", async () => {
366
- const highlighter = await getSyntaxHighlighterPromise("typescript");
367
- const highlight = vi.spyOn(highlighter, "codeToHast");
368
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
369
- let renderer: ReactTestRenderer | undefined;
370
- const text = "```typescript\nconst completed = 1;\nconst current = 2;";
371
- try {
372
- await act(async () => {
373
- renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
374
- });
375
- expect(highlight).toHaveBeenCalled();
376
- highlight.mockClear();
377
- await act(async () => {
378
- renderer!.update(<ChatMarkdown cwd="/tmp/project" text={text + "\n```"} />);
379
- });
380
- expect(highlight.mock.calls.every(([code]) => !code.includes("const completed"))).toBe(true);
381
- } finally {
382
- await act(async () => renderer?.unmount());
383
- vi.unstubAllGlobals();
384
- vi.restoreAllMocks();
385
- }
386
- });
387
-
388
- it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
389
- const highlighter = await getSyntaxHighlighterPromise("text");
390
- const codeToHast = highlighter.codeToHast.bind(highlighter);
391
- let fail = true;
392
- vi.spyOn(highlighter, "codeToHast").mockImplementation((...args) => {
393
- if (fail) throw new Error("Temporary highlighter failure");
394
- return codeToHast(...args);
395
- });
396
- vi.spyOn(console, "error").mockImplementation(() => {});
397
- vi.spyOn(console, "warn").mockImplementation(() => {});
398
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
399
- let renderer: ReactTestRenderer | undefined;
400
-
401
- try {
402
- await act(async () => {
403
- renderer = create(
404
- <ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
405
- );
406
- });
407
- const mounted = renderer!;
408
- const codeBlock = mounted.root.findByProps({ "data-language": "text" });
409
- const initialWrap = codeBlock.props["data-wrap"] === "true";
410
- const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
411
- await act(async () => {
412
- wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
413
- });
414
- expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(0);
415
-
416
- fail = false;
417
- await act(async () => {
418
- mounted.update(
419
- <ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
420
- );
421
- });
422
- expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(1);
423
- expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
424
- expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
425
- } finally {
426
- await act(async () => renderer?.unmount());
427
- vi.unstubAllGlobals();
428
- vi.restoreAllMocks();
429
- }
430
- });
431
-
432
- it("preserves code controls and details without highlighting an unchanged fence again", async () => {
433
- const highlighter = await getSyntaxHighlighterPromise("text");
434
- const highlight = vi.spyOn(highlighter, "codeToHast");
435
- const writeText = vi.fn(async (_text: string) => {});
436
- vi.stubGlobal("navigator", { clipboard: { writeText } });
437
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
438
- vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
439
- let renderer: ReactTestRenderer | undefined;
440
- const text = [
441
- "```text",
442
- "First code block",
443
- "```",
444
- "",
445
- "<details><summary>More</summary>",
446
- "",
447
- "Details content",
448
- "",
449
- "</details>",
450
- "",
451
- "Streaming reply",
452
- ].join("\n");
453
-
454
- try {
455
- await act(async () => {
456
- renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} isStreaming />);
457
- });
458
- const mounted = renderer!;
459
- const codeBlock = mounted.root.findByProps({ "data-language": "text" });
460
- const initialWrap = codeBlock.props["data-wrap"] === "true";
461
- const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
462
- const copy = codeButton(mounted, "Copy code");
463
- await act(async () => {
464
- wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
465
- copy.onClick?.({} as Parameters<NonNullable<typeof copy.onClick>>[0]);
466
- });
467
-
468
- const detailsButton = mounted.root.find(
469
- (instance) =>
470
- instance.type === "button" && instance.props["data-markdown-details-summary"] === "",
471
- );
472
- await act(async () => {
473
- detailsButton.props.onClick({ nativeEvent: new Event("click") });
474
- });
475
- const details = mounted.root.findByProps({ "data-markdown-details": "" });
476
- expect(details.props["data-markdown-details-open"]).toBe("true");
477
- expect(writeText).toHaveBeenCalledWith("First code block\n");
478
- expect(highlight).toHaveBeenCalledTimes(1);
479
-
480
- for (let index = 0; index < 10; index += 1) {
481
- await act(async () => {
482
- mounted.update(<ChatMarkdown cwd="/tmp/project" text={`${text} ${index}`} isStreaming />);
483
- });
484
- }
485
-
486
- expect(highlight).toHaveBeenCalledTimes(1);
487
- expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
488
- expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
489
- expect(mounted.root.findByProps({ "data-markdown-details": "" })).toBe(details);
490
- expect(details.props["data-markdown-details-open"]).toBe("true");
491
- await act(async () => {
492
- mounted.update(
493
- <ChatMarkdown
494
- cwd="/tmp/project"
495
- text={text.replace("First code block", "Updated code block")}
496
- isStreaming
497
- />,
498
- );
499
- });
500
- const copyUpdated = codeButton(mounted, "Copied");
501
- await act(async () => {
502
- copyUpdated.onClick?.({} as Parameters<NonNullable<typeof copyUpdated.onClick>>[0]);
503
- });
504
- expect(writeText).toHaveBeenLastCalledWith("Updated code block\n");
505
- expect(highlight).toHaveBeenCalledTimes(2);
506
- } finally {
507
- await act(async () => renderer?.unmount());
508
- vi.useRealTimers();
509
- vi.unstubAllGlobals();
510
- vi.restoreAllMocks();
511
- }
512
- });
513
-
514
- it("edits the current task text and marker after reusing a renderer", async () => {
515
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
516
- let renderer: ReactTestRenderer | undefined;
517
- let editedText: string | undefined;
518
- const message = (text: string) => (
519
- <ChatMarkdown
520
- cwd="/tmp/project"
521
- text={text}
522
- onTaskListChange={({ markerOffset, checked }) => {
523
- editedText = setMarkdownTaskChecked(text, markerOffset, checked);
524
- renderer!.update(message(editedText));
525
- }}
526
- />
527
- );
528
-
529
- try {
530
- await act(async () => {
531
- renderer = create(message("- [ ] First\n- [ ] Second"));
532
- });
533
- const mounted = renderer!;
534
- const originalInput = mounted.root.findAllByType("input")[1]!;
535
- await act(async () => {
536
- mounted.update(message("- [ ] A longer first task\n- [ ] Second"));
537
- });
538
-
539
- const input = mounted.root.findAllByType("input")[1]!;
540
- const listItem = mounted.root.findAllByType("li")[1]!;
541
- const { onChange } = input.props as ComponentProps<"input">;
542
- if (!onChange) throw new Error("Task checkbox has no edit handler");
543
- await act(async () => {
544
- onChange({
545
- currentTarget: {
546
- checked: true,
547
- closest: () => ({
548
- dataset: { listItemOffset: String(listItem.props["data-list-item-offset"]) },
549
- }),
550
- },
551
- } as unknown as Parameters<typeof onChange>[0]);
552
- });
553
-
554
- expect(input).toBe(originalInput);
555
- expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
556
- expect(mounted.root.findAllByType("input")[1]!.props.checked).toBe(true);
557
- } finally {
558
- await act(async () => renderer?.unmount());
559
- vi.unstubAllGlobals();
560
- }
561
- });
562
-});
563
-
564
-describe("canUseMarkdownFileShellActions", () => {
565
- const environmentId = EnvironmentId.make("environment-1");
566
-
567
- it("allows editor and file manager actions for local environments", () => {
568
- expect(canUseMarkdownFileShellActions(environmentId, "local-exec", true)).toBe(true);
569
- });
570
-
571
- it("hides shell actions until the environment mode is resolved", () => {
572
- expect(canUseMarkdownFileShellActions(environmentId, "local-exec", false)).toBe(false);
573
- });
574
-
575
- it("hides editor and file manager actions for remote environments", () => {
576
- expect(canUseMarkdownFileShellActions(environmentId, "remote-links", true)).toBe(false);
577
- expect(canUseMarkdownFileShellActions(environmentId, "remote-unavailable", true)).toBe(false);
578
- });
579
-
580
- it("hides shell actions when no environment owns the markdown", () => {
581
- expect(canUseMarkdownFileShellActions(null, "local-exec", true)).toBe(false);
582
- });
583
-});
584
-
585
-describe("hasMarkdownFilePrimaryAction", () => {
586
- it("keeps the chip interactive when an editor, browser, or panel can open it", () => {
587
- expect(
588
- hasMarkdownFilePrimaryAction({
589
- canOpenInEditor: true,
590
- canOpenInBrowser: false,
591
- canOpenInPanel: false,
592
- }),
593
- ).toBe(true);
594
- expect(
595
- hasMarkdownFilePrimaryAction({
596
- canOpenInEditor: false,
597
- canOpenInBrowser: true,
598
- canOpenInPanel: false,
599
- }),
600
- ).toBe(true);
601
- expect(
602
- hasMarkdownFilePrimaryAction({
603
- canOpenInEditor: false,
604
- canOpenInBrowser: false,
605
- canOpenInPanel: true,
606
- }),
607
- ).toBe(true);
608
- });
609
-
610
- it("removes the link affordance when no primary action can open the file", () => {
611
- expect(
612
- hasMarkdownFilePrimaryAction({
613
- canOpenInEditor: false,
614
- canOpenInBrowser: false,
615
- canOpenInPanel: false,
616
- }),
617
- ).toBe(false);
618
- });
619
-});
620
-
621
-describe("ChatMarkdown skill chips", () => {
622
- it("updates digit-leading skill labels when discovered skills change", async () => {
623
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
624
- let renderer: ReactTestRenderer | undefined;
625
- const text = "Use $2spec with a $20k budget.";
626
- try {
627
- await act(async () => {
628
- renderer = create(<ChatMarkdown cwd="/tmp/project" text={text} />);
629
- });
630
- const mounted = renderer!;
631
- const labels = (label: string) =>
632
- mounted.root.findAllByType("span").filter((node) => node.children.includes(label));
633
- expect(labels("2Spec")).toHaveLength(0);
634
-
635
- await act(async () => {
636
- mounted.update(
637
- <ChatMarkdown
638
- cwd="/tmp/project"
639
- text={text}
640
- skills={[
641
- { name: "2spec", displayName: "2Spec" },
642
- { name: "20k", displayName: "MoneySkill" },
643
- ]}
644
- />,
645
- );
646
- });
647
- expect(labels("2Spec")).toHaveLength(1);
648
- expect(labels("MoneySkill")).toHaveLength(0);
649
-
650
- await act(async () => {
651
- mounted.update(<ChatMarkdown cwd="/tmp/project" text={text} skills={[]} />);
652
- });
653
- expect(labels("2Spec")).toHaveLength(0);
654
- } finally {
655
- await act(async () => renderer?.unmount());
656
- vi.unstubAllGlobals();
657
- }
658
- });
659
-});
660
-
661
-describe("ChatMarkdown file option chips", () => {
662
- it("keeps the fallback button text selectable", () => {
663
- const html = renderToStaticMarkup(
664
- <ChatMarkdown cwd="/tmp/project" text="[Source](/tmp/project/src/main.ts)" />,
665
- );
666
-
667
- expect(html).toContain("<button");
668
- expect(html).toContain('aria-haspopup="menu"');
669
- expect(html).toContain("select-text");
670
- });
671
-
672
- it.each([true, false])(
673
- "renders Codex file citations as file chips with parseRawHtml=%s",
674
- (parseRawHtml) => {
675
- const html = renderToStaticMarkup(
676
- <ChatMarkdown
677
- cwd="/tmp/project"
678
- text={
679
- 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.'
680
- }
681
- lineBreaks={!parseRawHtml}
682
- parseRawHtml={parseRawHtml}
683
- />,
684
- );
685
-
686
- expect(html).not.toContain("codex-file-citation");
687
- expect(html).toContain("chat-markdown-file-link");
688
- expect(html).toContain(
689
- 'data-markdown-copy="[report.xlsx](/tmp/project/outputs/report.xlsx)"',
690
- );
691
- expect(html).toContain("report.xlsx");
692
- },
693
- );
694
-
695
- it("leaves an unfinished streaming citation visible until it is complete", () => {
696
- const html = renderToStaticMarkup(
697
- <ChatMarkdown
698
- cwd="/tmp/project"
699
- text={'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"'}
700
- isStreaming
701
- />,
702
- );
703
-
704
- expect(html).toContain(":codex-file-citation");
705
- expect(html).not.toContain("chat-markdown-file-link");
706
- });
707
-
708
- it("leaves malformed and similarly named file directives literal", () => {
709
- for (const text of [
710
- ':codex-file-citation{purpose="output"}',
711
- ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
712
- ]) {
713
- const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
714
-
715
- expect(html).toContain(text.replaceAll('"', """));
716
- expect(html).not.toContain("chat-markdown-file-link");
717
- }
718
- });
719
-
720
- it("preserves Codex file citation examples inside code", () => {
721
- const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
722
- const html = renderToStaticMarkup(
723
- <ChatMarkdown
724
- cwd="/tmp/project"
725
- text={`Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``}
726
- />,
727
- );
728
-
729
- expect(html.match(/:codex-file-citation/g)).toHaveLength(2);
730
- expect(html).not.toContain("chat-markdown-file-link");
731
- });
732
-
733
- it("preserves escaped Codex file citations as literal text", () => {
734
- const html = renderToStaticMarkup(
735
- <ChatMarkdown
736
- cwd="/tmp/project"
737
- text={'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
738
- />,
739
- );
740
-
741
- expect(html).toContain(":codex-file-citation");
742
- expect(html).not.toContain("chat-markdown-file-link");
743
- });
744
-
745
- it("does not create a nested link for citations inside link text", () => {
746
- const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
747
- const html = renderToStaticMarkup(
748
- <ChatMarkdown cwd="/tmp/project" text={`[See ${directive}](https://example.com)`} />,
749
- );
750
- const renderedText = html.replace(/<[^>]+>/g, "");
751
-
752
- expect(renderedText).toContain("codex-file-citation");
753
- expect(html).not.toContain("chat-markdown-file-link");
754
- });
755
-
756
- it("renders file citations created by over-indented list recovery", () => {
757
- const html = renderToStaticMarkup(
758
- <ChatMarkdown
759
- cwd="/tmp/project"
760
- text={'- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
761
- />,
762
- );
763
-
764
- expect(html).not.toContain("<pre>");
765
- expect(html).toContain("Created ");
766
- expect(html).toContain("chat-markdown-file-link");
767
- expect(html).toContain("report.xlsx");
768
- });
769
-
770
- it("disambiguates Codex citations with the same basename", () => {
771
- const html = renderToStaticMarkup(
772
- <ChatMarkdown
773
- cwd="/tmp/project"
774
- text={
775
- 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.'
776
- }
777
- />,
778
- );
779
-
780
- expect(html).toContain("index.ts · project/src");
781
- expect(html).toContain("index.ts · project/test");
782
- });
783
-
784
- it("preserves rejected citations created by over-indented list recovery", () => {
785
- const malformedHtml = renderToStaticMarkup(
786
- <ChatMarkdown
787
- cwd="/tmp/project"
788
- text={'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}'}
789
- />,
790
- );
791
- const nestedLinkHtml = renderToStaticMarkup(
792
- <ChatMarkdown
793
- cwd="/tmp/project"
794
- text={
795
- 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)'
796
- }
797
- />,
798
- );
799
- const nestedLinkText = nestedLinkHtml.replace(/<[^>]+>/g, "");
800
-
801
- expect(malformedHtml).toContain(
802
- "<li>Bad :codex-file-citation{purpose="output"}</li>",
803
- );
804
- expect(nestedLinkText).toContain(
805
- "Bad :codex-file-citation{path="/tmp/project/report.xlsx"}",
806
- );
807
- });
808
-});
809
-
810
-describe("ChatMarkdown Codex follow-up suggestions", () => {
811
- it.each([true, false])("renders the label with parseRawHtml=%s", (parseRawHtml) => {
812
- const html = renderToStaticMarkup(
813
- <ChatMarkdown
814
- cwd="/tmp/project"
815
- text={
816
- 'Done.\n\n- :codex-followup[Prepare print version]{prompt="Prepare the document for printing."}'
817
- }
818
- lineBreaks={!parseRawHtml}
819
- parseRawHtml={parseRawHtml}
820
- />,
821
- );
822
-
823
- expect(html).toContain("Prepare print version");
824
- expect(html).not.toContain("codex-followup");
825
- expect(html).not.toContain("Prepare the document for printing.");
826
- });
827
-
828
- it("keeps the label of a malformed follow-up created by over-indented list recovery", () => {
829
- const html = renderToStaticMarkup(
830
- <ChatMarkdown
831
- cwd="/tmp/project"
832
- text="- Next :codex-followup[Prepare print version]"
833
- />,
834
- );
835
-
836
- expect(html).toContain("<li>Next :codex-followup[Prepare print version]</li>");
837
- });
838
-});
839
-
840
-const ARTIFACT_TEMPLATE_DIRECTIVE =
841
- '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
842
-
843
-describe("ChatMarkdown artifact-template cards", () => {
844
- it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
845
- const html = renderToStaticMarkup(
846
- <ChatMarkdown
847
- cwd="/tmp/project"
848
- text={ARTIFACT_TEMPLATE_DIRECTIVE}
849
- parseRawHtml={parseRawHtml}
850
- onUseArtifactTemplate={() => undefined}
851
- />,
852
- );
853
-
854
- expect(html).not.toContain("::artifact-template");
855
- expect(html).toContain("data-chat-markdown-artifact-template");
856
- expect(html).toContain('data-artifact-kind="document"');
857
- expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
858
- expect(html).toContain('data-skill-name="artifact-template-hello-world"');
859
- expect(html).toContain("Hello World");
860
- expect(html).toContain("Document template");
861
- expect(html).toContain("Use template");
862
- expect(html).not.toContain("<p><div");
863
- });
864
-
865
- it("renders a passive card outside a composer-backed timeline", () => {
866
- const html = renderToStaticMarkup(
867
- <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
868
- );
869
-
870
- expect(html).toContain("data-chat-markdown-artifact-template");
871
- expect(html).not.toContain("Use template");
872
- });
873
-
874
- it("leaves malformed and unfinished artifact-template directives literal", () => {
875
- const malformed =
876
- '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
877
- const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
878
-
879
- for (const text of [malformed, unfinished]) {
880
- const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
881
- expect(html).toContain("::artifact-template");
882
- expect(html).not.toContain("data-chat-markdown-artifact-template");
883
- }
884
- });
885
-
886
- it("leaves escaped and similarly named artifact-template directives literal", () => {
887
- for (const text of [
888
- `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
889
- ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
890
- ]) {
891
- const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
892
-
893
- expect(html).toContain("::artifact-template");
894
- expect(html).not.toContain("data-chat-markdown-artifact-template");
895
- }
896
- });
897
-
898
- it("preserves artifact-template examples inside code", () => {
899
- const html = renderToStaticMarkup(
900
- <ChatMarkdown
901
- cwd="/tmp/project"
902
- text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
903
- />,
904
- );
905
-
906
- expect(html.match(/::artifact-template/g)).toHaveLength(2);
907
- expect(html).not.toContain("data-chat-markdown-artifact-template");
908
- });
909
-});
910
-
911
-describe("ChatMarkdown heading levels", () => {
912
- it("exposes headings below the host heading without changing their tags", () => {
913
- const html = renderToStaticMarkup(
914
- <ChatMarkdown
915
- cwd="/tmp/project"
916
- text={"# Top\n\n## Section\n\n###### Fine print"}
917
- headingLevelOffset={3}
918
- />,
919
- );
920
-
921
- expect(html).toContain('<h1 id="user-content-top" aria-level="4">Top</h1>');
922
- expect(html).toContain('<h2 id="user-content-section" aria-level="5">Section</h2>');
923
- expect(html).toContain('<h6 id="user-content-fine-print" aria-level="6">Fine print</h6>');
924
- });
925
-
926
- it("leaves heading levels alone when the markdown is not nested", () => {
927
- const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text="# Top" />);
928
-
929
- expect(html).toContain('<h1 id="user-content-top">Top</h1>');
930
- });
931
-});
932
-
933
-describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
934
- it("uses the browser when it is the only available primary action", () => {
935
- expect(
936
- shouldUseMarkdownFileBrowserPrimaryAction({
937
- iconPath: "/tmp/report.html",
938
- canOpenInEditor: false,
939
- canOpenInBrowser: true,
940
- canOpenInPanel: false,
941
- }),
942
- ).toBe(true);
943
- });
944
-
945
- it("preserves the normal editor and panel defaults for HTML files", () => {
946
- expect(
947
- shouldUseMarkdownFileBrowserPrimaryAction({
948
- iconPath: "/tmp/report.html",
949
- canOpenInEditor: true,
950
- canOpenInBrowser: true,
951
- canOpenInPanel: false,
952
- }),
953
- ).toBe(false);
954
- expect(
955
- shouldUseMarkdownFileBrowserPrimaryAction({
956
- iconPath: "/tmp/report.html",
957
- canOpenInEditor: false,
958
- canOpenInBrowser: true,
959
- canOpenInPanel: true,
960
- }),
961
- ).toBe(false);
962
- });
963
-
964
- it("continues to open PDF files in the browser by default", () => {
965
- expect(
966
- shouldUseMarkdownFileBrowserPrimaryAction({
967
- iconPath: "/tmp/report.pdf",
968
- canOpenInEditor: true,
969
- canOpenInBrowser: true,
970
- canOpenInPanel: true,
971
- }),
972
- ).toBe(true);
973
- });
974
-});
975
-
976
-describe("ChatMarkdown Windows file links", () => {
977
- const environmentId = EnvironmentId.make("env-windows");
978
-
979
- it.each([true, false])("preserves drive paths with parseRawHtml=%s", (parseRawHtml) => {
980
- const html = renderToStaticMarkup(
981
- <ChatMarkdown
982
- cwd="C:/Users/shawn/project"
983
- environmentId={environmentId}
984
- text="[Open](C:/Users/shawn/project/src/main.ts)"
985
- lineBreaks={!parseRawHtml}
986
- parseRawHtml={parseRawHtml}
987
- />,
988
- );
989
-
990
- expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
991
- expect(html).toContain("chat-markdown-file-link");
992
- });
993
-
994
- it.each([true, false])("normalizes backslashes with parseRawHtml=%s", (parseRawHtml) => {
995
- const html = renderToStaticMarkup(
996
- <ChatMarkdown
997
- cwd="C:/Users/shawn/project"
998
- environmentId={environmentId}
999
- text={String.raw`[Open](C:\Users\shawn\project\src\main.ts)`}
1000
- lineBreaks={!parseRawHtml}
1001
- parseRawHtml={parseRawHtml}
1002
- />,
1003
- );
1004
-
1005
- expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
1006
- expect(html).toContain("chat-markdown-file-link");
1007
- });
1008
-
1009
- it.each([true, false])(
1010
- "keeps backslashes CommonMark would read as escapes with parseRawHtml=%s",
1011
- (parseRawHtml) => {
1012
- const html = renderToStaticMarkup(
1013
- <ChatMarkdown
1014
- cwd="C:/Users/shawn/project"
1015
- environmentId={environmentId}
1016
- text={String.raw`[settings](C:\Users\shawn\.claude\settings.json)`}
1017
- lineBreaks={!parseRawHtml}
1018
- parseRawHtml={parseRawHtml}
1019
- />,
1020
- );
1021
-
1022
- expect(html).toContain('href="C:/Users/shawn/.claude/settings.json"');
1023
- },
1024
- );
1025
-
1026
- it.each([true, false])(
1027
- "distinguishes same-named backslash paths with parseRawHtml=%s",
1028
- (parseRawHtml) => {
1029
- const html = renderToStaticMarkup(
1030
- <ChatMarkdown
1031
- cwd="C:/Users/shawn/project"
1032
- environmentId={environmentId}
1033
- text={String.raw`[Source](C:\Users\shawn\project\src\index.ts) and [Test](C:\Users\shawn\project\test\index.ts)`}
1034
- lineBreaks={!parseRawHtml}
1035
- parseRawHtml={parseRawHtml}
1036
- />,
1037
- );
1038
-
1039
- expect(html).toContain("index.ts · project/src");
1040
- expect(html).toContain("index.ts · project/test");
1041
- },
1042
- );
1043
-
1044
- it.each([true, false])(
1045
- "does not disambiguate the same file in links and inline code with parseRawHtml=%s",
1046
- (parseRawHtml) => {
1047
- const path = String.raw`C:\Users\shawn\project\src\main.ts`;
1048
- const html = renderToStaticMarkup(
1049
- <ChatMarkdown
1050
- cwd="C:/Users/shawn/project"
1051
- environmentId={environmentId}
1052
- text={`[Source](${path}) and \`${path}\``}
1053
- lineBreaks={!parseRawHtml}
1054
- parseRawHtml={parseRawHtml}
1055
- />,
1056
- );
1057
-
1058
- expect(html.match(/chat-markdown-file-link/g)).toHaveLength(2);
1059
- expect(html).not.toContain("main.ts ·");
1060
- },
1061
- );
1062
-
1063
- it.each([true, false])("preserves reference links with parseRawHtml=%s", (parseRawHtml) => {
1064
- const html = renderToStaticMarkup(
1065
- <ChatMarkdown
1066
- cwd="C:/Users/shawn/project"
1067
- environmentId={environmentId}
1068
- text={"[Open][source]\n\n[source]: C:/Users/shawn/project/src/main.ts"}
1069
- lineBreaks={!parseRawHtml}
1070
- parseRawHtml={parseRawHtml}
1071
- />,
1072
- );
1073
-
1074
- expect(html).toContain('href="C:/Users/shawn/project/src/main.ts"');
1075
- expect(html).toContain("chat-markdown-file-link");
1076
- });
1077
-
1078
- it.each([true, false])("still rejects unsafe schemes with parseRawHtml=%s", (parseRawHtml) => {
1079
- const html = renderToStaticMarkup(
1080
- <ChatMarkdown
1081
- cwd="C:/Users/shawn/project"
1082
- environmentId={environmentId}
1083
- text="[unsafe](javascript:alert(1)) and [unknown](d:alert(1))"
1084
- lineBreaks={!parseRawHtml}
1085
- parseRawHtml={parseRawHtml}
1086
- />,
1087
- );
1088
-
1089
- expect(html).not.toContain("javascript:");
1090
- expect(html).not.toContain("d:alert");
1091
- expect(html).not.toContain("chat-markdown-file-link");
1092
- });
1093
-});
1094
-
1095
-it("opens a disclosure only when find selects a match inside it", async () => {
1096
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1097
- vi.stubGlobal(
1098
- "Highlight",
1099
- class extends Set<Range> {
1100
- constructor(...ranges: Range[]) {
1101
- super(ranges);
1102
- }
1103
- },
1104
- );
1105
- const highlights = new Map<string, Set<Range>>();
1106
- vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1107
- const container = document.createElement("div");
1108
- document.body.append(container);
1109
- const root = createRoot(container);
1110
- const openStates = () =>
1111
- [...container.querySelectorAll("[data-markdown-details-open]")].map((node) =>
1112
- node.getAttribute("data-markdown-details-open"),
1113
- );
1114
- function Probe({
1115
- activeOccurrence,
1116
- searching = true,
1117
- }: {
1118
- activeOccurrence: number;
1119
- searching?: boolean;
1120
- }) {
1121
- useThreadFindHighlights({
1122
- container,
1123
- query: searching ? "needle" : "",
1124
- activeRowId: "row",
1125
- activeOccurrence,
1126
- onActiveRange: () => {},
1127
- });
1128
- return (
1129
- <div data-timeline-row-id="row">
1130
- <div data-thread-find-text>
1131
- <MarkdownFindContext value={searching}>
1132
- <ChatMarkdown
1133
- cwd={undefined}
1134
- text={[
1135
- "Visible needle.",
1136
- "<details><summary>Unrelated</summary><p>nothing here</p></details>",
1137
- "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",
1138
- ].join("\n\n")}
1139
- />
1140
- </MarkdownFindContext>
1141
- </div>
1142
- </div>
1143
- );
1144
- }
1145
- const frame = () =>
1146
- act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1147
- try {
1148
- await act(() => root.render(<Probe activeOccurrence={0} searching={false} />));
1149
- expect(container.textContent).not.toContain("nothing here");
1150
- await act(() => root.render(<Probe activeOccurrence={0} />));
1151
- await frame();
1152
- expect(openStates()).toEqual(["false", "false", "false"]);
1153
- expect(container.textContent).toContain("nothing here");
1154
- expect(
1155
- [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1156
- ).toEqual(["needle"]);
1157
- expect(highlights.get("t3-thread-find")?.size).toBe(0);
1158
-
1159
- await act(() => root.render(<Probe activeOccurrence={1} />));
1160
- await frame();
1161
- await frame();
1162
- expect(openStates()).toEqual(["false", "true", "true"]);
1163
- expect(highlights.get("t3-thread-find-active")?.size).toBe(1);
1164
- } finally {
1165
- await act(() => root.unmount());
1166
- container.remove();
1167
- vi.unstubAllGlobals();
1168
- }
1169
-});
1170
-
1171
-it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {
1172
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1173
- vi.stubGlobal(
1174
- "Highlight",
1175
- class extends Set<Range> {
1176
- constructor(...ranges: Range[]) {
1177
- super(ranges);
1178
- }
1179
- },
1180
- );
1181
- const highlights = new Map<string, Set<Range>>();
1182
- vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1183
- const container = document.createElement("div");
1184
- document.body.append(container);
1185
- const root = createRoot(container);
1186
- const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";
1187
- function Probe({ query }: { query: string }) {
1188
- useThreadFindHighlights({
1189
- container,
1190
- query,
1191
- activeRowId: "row",
1192
- activeOccurrence: 0,
1193
- onActiveRange: () => {},
1194
- });
1195
- return (
1196
- <div data-timeline-row-id="row">
1197
- <div data-thread-find-text>
1198
- <MarkdownFindContext value={true}>
1199
- <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />
1200
- </MarkdownFindContext>
1201
- </div>
1202
- </div>
1203
- );
1204
- }
1205
- const frame = () =>
1206
- act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1207
- const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;
1208
- try {
1209
- await act(() => root.render(<Probe query="Needle" />));
1210
- await frame();
1211
- expect(diagrams()).toBe(2);
1212
- await act(() => root.render(<Probe query="Alpha" />));
1213
- await frame();
1214
- await frame();
1215
- expect(diagrams()).toBe(1);
1216
- expect(
1217
- [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),
1218
- ).toEqual(["Alpha"]);
1219
- } finally {
1220
- await act(() => root.unmount());
1221
- container.remove();
1222
- vi.unstubAllGlobals();
1223
- }
1224
-});
1225
-
1226
-it.each([
1227
- {
1228
- text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",
1229
- query: "SearchSourceAlpha",
1230
- count: 1,
1231
- },
1232
- {
1233
- text: "★ Insight ─────\nfirst line\nsecond line",
1234
- query: "first line second",
1235
- count: 0,
1236
- lineBreaks: true,
1237
- },
1238
- { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },
1239
- { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },
1240
- { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },
1241
- { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },
1242
- { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },
1243
- {
1244
- text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",
1245
- query: "Hidden needle",
1246
- count: 1,
1247
- },
1248
- { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, withTemplate: true },
1249
- { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Document template", count: 1, withTemplate: true },
1250
- { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, withTemplate: true },
1251
- { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, withTemplate: true },
1252
-])(
1253
- "highlights the indexed occurrences of $query in $text",
1254
- async ({ text, query, count, lineBreaks, user, withTemplate }) => {
1255
- const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];
1256
- const highlights = new Map<string, Set<Range>>();
1257
- vi.stubGlobal(
1258
- "Highlight",
1259
- class extends Set<Range> {
1260
- constructor(...ranges: Range[]) {
1261
- super(ranges);
1262
- }
1263
- },
1264
- );
1265
- vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });
1266
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1267
- const container = document.createElement("div");
1268
- document.body.append(container);
1269
- const root = createRoot(container);
1270
- function Probe() {
1271
- useThreadFindHighlights({
1272
- container,
1273
- query,
1274
- activeRowId: "row",
1275
- activeOccurrence: 0,
1276
- onActiveRange: () => {},
1277
- });
1278
- return (
1279
- <div data-timeline-row-id="row">
1280
- <div data-thread-find-text>
1281
- <MarkdownFindContext value={true}>
1282
- <ChatMarkdown
1283
- text={text}
1284
- cwd={undefined}
1285
- skills={skills}
1286
- lineBreaks={lineBreaks ?? false}
1287
- parseRawHtml={!user}
1288
- onUseArtifactTemplate={withTemplate ? () => undefined : undefined}
1289
- />
1290
- </MarkdownFindContext>
1291
- </div>
1292
- </div>
1293
- );
1294
- }
1295
- try {
1296
- await act(() => root.render(<Probe />));
1297
- await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
1298
- const ranges = [...highlights.values()].flatMap((value) => [...value]);
1299
- expect(ranges.map((range) => range.toString())).toEqual(
1300
- Array.from({ length: count }, () => query),
1301
- );
1302
- const segments =
1303
- searchableMessageSegments(
1304
- { role: user ? "user" : "assistant", text, streaming: false },
1305
- undefined,
1306
- skills,
1307
- ) ?? [];
1308
- expect(
1309
- segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),
1310
- ).toBe(count);
1311
- } finally {
1312
- await act(() => root.unmount());
1313
- container.remove();
1314
- vi.unstubAllGlobals();
1315
- }
1316
- },
1317
-);
1318
-
1319
-describe("ChatMarkdown heading ids", () => {
1320
- it("never gives two headings the same id, even when a suffix matches another heading", () => {
1321
- const html = renderToStaticMarkup(
1322
- <ChatMarkdown
1323
- cwd="/tmp/project"
1324
- parseRawHtml
1325
- text={
1326
- '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install'
1327
- }
1328
- />,
1329
- );
1330
- const ids = [...html.matchAll(/<h2 id="([^"]+)"/g)].map((match) => match[1]);
1331
- expect(ids).toEqual([
1332
- "user-content-setup",
1333
- "user-content-setup-1",
1334
- "user-content-setup-1-1",
1335
- "user-content-install-1",
1336
- "user-content-install",
1337
- "user-content-install-2",
1338
- ]);
1339
- expect(new Set(ids).size).toBe(ids.length);
1340
- });
1341
-});
1342
-
1343
-describe("ChatMarkdown in-page links", () => {
1344
- it.each([true, false])(
1345
- "scrolls a table-of-contents link to its heading without touching the URL (parseRawHtml=%s)",
1346
- async (parseRawHtml) => {
1347
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1348
- const { createRoot } = await import("react-dom/client");
1349
- const container = document.createElement("div");
1350
- document.body.append(container);
1351
- const root = createRoot(container);
1352
- window.history.replaceState(null, "", "/#/env/thread");
1353
- const scrollIntoView = vi.fn();
1354
- HTMLElement.prototype.scrollIntoView = scrollIntoView;
1355
- try {
1356
- await act(async () => {
1357
- root.render(
1358
- <ChatMarkdown
1359
- cwd="/tmp/project"
1360
- parseRawHtml={parseRawHtml}
1361
- text={
1362
- "- [Operating model](#1-operating-model)\n- [Missing](#nowhere)\n\n## 1. Operating model\n\n## 1. Operating model"
1363
- }
1364
- />,
1365
- );
1366
- });
1367
- const headings = [...container.querySelectorAll("h2")];
1368
- expect(headings.map((heading) => heading.id)).toEqual([
1369
- "user-content-1-operating-model",
1370
- "user-content-1-operating-model-1",
1371
- ]);
1372
-
1373
- const [tocLink, missingLink] = [...container.querySelectorAll("a")];
1374
- const click = () => new MouseEvent("click", { bubbles: true, cancelable: true });
1375
- const tocClick = click();
1376
- tocLink!.dispatchEvent(tocClick);
1377
- expect(tocClick.defaultPrevented).toBe(true);
1378
- expect(scrollIntoView.mock.contexts).toEqual([headings[0]]);
1379
-
1380
- const missingClick = click();
1381
- missingLink!.dispatchEvent(missingClick);
1382
- expect(missingClick.defaultPrevented).toBe(true);
1383
- expect(scrollIntoView).toHaveBeenCalledTimes(1);
1384
- expect(window.location.hash).toBe("#/env/thread");
1385
- } finally {
1386
- await act(async () => root.unmount());
1387
- container.remove();
1388
- }
1389
- },
1390
- );
1391
-});
apps/web/src/components/ChatMarkdown.tsx
+1
-1
@@ -257,7 +257,7 @@ export function canUseMarkdownFileShellActions(
257
return environmentId !== null && isRemoteOpenResolved && remoteOpenMode === "local-exec";
258
}
259
260
-export function hasMarkdownFilePrimaryAction(input: {
260
+function hasMarkdownFilePrimaryAction(input: {
261
canOpenInEditor: boolean;
262
canOpenInBrowser: boolean;
263
canOpenInPanel: boolean;
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
new
+1262
@@ -0,0 +1,1262 @@
1
+import { RegistryProvider } from "@effect/atom-react";
2
+import {
3
+ ApprovalRequestId,
4
+ CheckpointRef,
5
+ EnvironmentId,
6
+ MessageId,
7
+ RunId,
8
+ ThreadId,
9
+} from "@t3tools/contracts";
10
+import type { LegendListRef } from "@legendapp/list/react";
11
+import { act, createRef, useState, type ComponentProps, type ReactElement } from "react";
12
+import { createRoot, type Root } from "react-dom/client";
13
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
14
+import { userEvent } from "vite-plus/test/browser";
15
+
16
+import "~/index.css";
17
+
18
+import { serverEnvironment } from "../../state/server";
19
+import { PullRequestLinkPreview } from "../pullRequest/PullRequestLinkPreview";
20
+import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "../ui/tooltip";
21
+import { MessagesTimeline } from "./MessagesTimeline";
22
+import { readTimelinePosition } from "./timelineScrollAnchoring";
23
+import { useComposerFocusState } from "./useComposerFocusState";
24
+
25
+const pullRequestQuery = vi.hoisted(() => ({ error: "Pull request not found" }));
26
+vi.mock(import("~/state/query"), async (original) => ({
27
+ ...(await original()),
28
+ useEnvironmentQuery: (() => ({
29
+ data: null,
30
+ dataUpdatedAt: 0,
31
+ error: pullRequestQuery.error,
32
+ failure: null,
33
+ isPending: false,
34
+ isSuccess: false,
35
+ refresh: () => {},
36
+ })) as never,
37
+}));
38
+
39
+const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
40
+const CREATED_AT = "2026-03-17T19:12:28.000Z";
41
+
42
+type TimelineProps = ComponentProps<typeof MessagesTimeline>;
43
+type Entry = TimelineProps["timelineEntries"][number];
44
+
45
+// The timeline remembers scroll position and open disclosures per thread key,
46
+// so every render gets a fresh thread.
47
+let threadCount = 0;
48
+
49
+function baseProps(): Omit<TimelineProps, "timelineEntries"> {
50
+ threadCount += 1;
51
+ return {
52
+ isWorking: false,
53
+ activeTurnInProgress: false,
54
+ listRef: createRef<LegendListRef | null>(),
55
+ latestRun: null,
56
+ turnDiffSummaries: [],
57
+ runs: [],
58
+ routeThreadKey: `environment-local:thread-${threadCount}`,
59
+ onOpenTurnDiff: () => {},
60
+ onOpenThread: () => {},
61
+ onForkFromRun: async () => {},
62
+ onRollbackCheckpoint: () => {},
63
+ supportsConversationRollback: false,
64
+ onRevertToTurnCount: () => {},
65
+ isRevertingCheckpoint: false,
66
+ onImageExpand: () => {},
67
+ activeThreadEnvironmentId: ENVIRONMENT_ID,
68
+ markdownCwd: undefined,
69
+ resolvedTheme: "light",
70
+ timestampFormat: "locale",
71
+ workspaceRoot: undefined,
72
+ anchorMessageId: null,
73
+ onAnchorReady: () => {},
74
+ onAnchorSizeChanged: () => {},
75
+ contentInsetEndAdjustment: 0,
76
+ liveFollowEnabled: true,
77
+ onIsAtEndChange: () => {},
78
+ onManualNavigation: () => {},
79
+ };
80
+}
81
+
82
+function message(
83
+ text: string,
84
+ overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {},
85
+ id = "message-1",
86
+): Entry {
87
+ return {
88
+ id: `entry-${id}`,
89
+ kind: "message",
90
+ createdAt: CREATED_AT,
91
+ message: {
92
+ id: MessageId.make(id),
93
+ role: "user",
94
+ text,
95
+ runId: null,
96
+ createdAt: CREATED_AT,
97
+ updatedAt: CREATED_AT,
98
+ streaming: false,
99
+ ...overrides,
100
+ },
101
+ };
102
+}
103
+
104
+function work(id: string, entry: Record<string, unknown>): Entry {
105
+ return {
106
+ id,
107
+ kind: "work",
108
+ createdAt: CREATED_AT,
109
+ entry: { id, createdAt: CREATED_AT, ...entry },
110
+ } as Entry;
111
+}
112
+
113
+function v2Item(type: string, fields: Record<string, unknown>) {
114
+ const id = (fields.id as string | undefined) ?? type;
115
+ return {
116
+ position: 0,
117
+ visibility: "local",
118
+ sourceThreadId: "thread-1",
119
+ sourceItemId: id,
120
+ item: {
121
+ id,
122
+ threadId: "thread-1",
123
+ runId: "run-1",
124
+ nodeId: null,
125
+ providerThreadId: null,
126
+ providerTurnId: null,
127
+ nativeItemRef: null,
128
+ parentItemId: null,
129
+ ordinal: 0,
130
+ status: "completed",
131
+ title: null,
132
+ startedAt: null,
133
+ completedAt: null,
134
+ updatedAt: {},
135
+ type,
136
+ ...fields,
137
+ },
138
+ } as never;
139
+}
140
+
141
+function longText(tail = "deep hidden detail only after expand") {
142
+ return Array.from({ length: 9 }, (_, index) =>
143
+ index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
144
+ ).join("\n");
145
+}
146
+
147
+const roots: Root[] = [];
148
+let container: HTMLDivElement;
149
+
150
+beforeEach(() => {
151
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
152
+});
153
+
154
+afterEach(async () => {
155
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
156
+ document.body.replaceChildren();
157
+ vi.unstubAllGlobals();
158
+});
159
+
160
+async function renderElement(element: ReactElement) {
161
+ container = document.body.appendChild(document.createElement("div"));
162
+ container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
163
+ const root = createRoot(container);
164
+ roots.push(root);
165
+ await act(async () => root.render(element));
166
+ return container;
167
+}
168
+
169
+function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
170
+ return renderElement(
171
+ <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
172
+ );
173
+}
174
+
175
+function text() {
176
+ return container.textContent ?? "";
177
+}
178
+
179
+function buttons(name: string | RegExp) {
180
+ return [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
181
+ const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
182
+ return typeof name === "string" ? label === name : name.test(label);
183
+ });
184
+}
185
+
186
+function button(name: string | RegExp) {
187
+ const [match] = buttons(name);
188
+ if (!match) throw new Error(`Missing button: ${String(name)}`);
189
+ return match;
190
+}
191
+
192
+async function click(element: HTMLElement) {
193
+ await act(async () => element.click());
194
+}
195
+
196
+describe("MessagesTimeline work rows", () => {
197
+ it("shows dynamic tool input without cached output when the row is expanded", async () => {
198
+ await renderTimeline([
199
+ work("tool-with-cached-output", {
200
+ label: "Example tool",
201
+ toolTitle: "Example tool",
202
+ tone: "tool",
203
+ itemType: "dynamic_tool",
204
+ toolLifecycleStatus: "completed",
205
+ toolData: {
206
+ input: { query: "KEEP_TOOL_INPUT" },
207
+ output: { text: "RAW_CACHED_TOOL_OUTPUT" },
208
+ },
209
+ }),
210
+ ]);
211
+ await click(button("Example tool"));
212
+ expect(text()).toContain("KEEP_TOOL_INPUT");
213
+ expect(text()).not.toContain("RAW_CACHED_TOOL_OUTPUT");
214
+ await click(button("Example tool"));
215
+ await vi.waitFor(() => expect(text()).not.toContain("KEEP_TOOL_INPUT"));
216
+ });
217
+
218
+ it("expands and collapses a tool call through its header", async () => {
219
+ await renderTimeline([
220
+ work("work-standalone", {
221
+ toolCallId: "call-standalone",
222
+ label: "Run lint",
223
+ tone: "tool",
224
+ itemType: "command_execution",
225
+ command: "pnpm lint",
226
+ toolLifecycleStatus: "completed",
227
+ }),
228
+ ]);
229
+ const header = () => container.querySelector<HTMLElement>("[aria-expanded]")!;
230
+ expect(header().getAttribute("aria-expanded")).toBe("false");
231
+ await click(header());
232
+ expect(header().getAttribute("aria-expanded")).toBe("true");
233
+ await click(header());
234
+ expect(header().getAttribute("aria-expanded")).toBe("false");
235
+ });
236
+
237
+ it("leads an unanswered question row with the question text", async () => {
238
+ await renderTimeline([
239
+ work("question-work", {
240
+ label: "User input requested",
241
+ tone: "tool",
242
+ questionAnswer: {
243
+ requestId: ApprovalRequestId.make("question-request"),
244
+ answers: {},
245
+ questionTextById: { scope: "Which repository?" },
246
+ attachmentsByQuestionId: {},
247
+ },
248
+ }),
249
+ ]);
250
+ const toggle = button("Which repository?");
251
+ expect(toggle.getAttribute("aria-expanded")).toBe("false");
252
+ const before = text().match(/Which repository\?/g)?.length ?? 0;
253
+ expect(before).toBeGreaterThan(0);
254
+ await click(toggle);
255
+ expect(text().match(/Which repository\?/g)?.length).toBe(before + 1);
256
+ });
257
+
258
+ it("collapses settled tool runs behind a generated summary and names a failure", async () => {
259
+ await renderTimeline([
260
+ work("work-1", {
261
+ label: "Ran command",
262
+ command: "vp lint",
263
+ tone: "tool",
264
+ itemType: "command_execution",
265
+ toolLifecycleStatus: "completed",
266
+ }),
267
+ work("work-2", {
268
+ label: "Run lint",
269
+ command: "vp test run",
270
+ tone: "tool",
271
+ itemType: "command_execution",
272
+ toolLifecycleStatus: "failed",
273
+ }),
274
+ ]);
275
+ const summary = button(/^Ran 2 commands/);
276
+ expect(summary.getAttribute("aria-label")).toContain("tool call failed");
277
+ expect(text()).not.toContain("vp lint");
278
+ await click(summary);
279
+ await vi.waitFor(() => expect(text()).toContain("vp lint"));
280
+ });
281
+
282
+ it("keeps mixed work logs neutral after a later tool call succeeds", async () => {
283
+ await renderTimeline([
284
+ work("work-failed", {
285
+ label: "Run search",
286
+ tone: "tool",
287
+ itemType: "command_execution",
288
+ toolLifecycleStatus: "failed",
289
+ }),
290
+ work("work-info", { label: "Status updated", tone: "info" }),
291
+ work("work-completed", {
292
+ label: "Run tests",
293
+ tone: "tool",
294
+ itemType: "command_execution",
295
+ toolLifecycleStatus: "completed",
296
+ }),
297
+ ]);
298
+ expect(button("Ran 2 commands and received 1 update")).toBeDefined();
299
+ });
300
+
301
+ it("marks a failed tool inside an expanded work log", async () => {
302
+ await renderTimeline([
303
+ work("work-info", { label: "Status updated", tone: "info" }),
304
+ work("work-1", {
305
+ label: "Glob",
306
+ tone: "tool",
307
+ toolLifecycleStatus: "failed",
308
+ detail: "No files found",
309
+ }),
310
+ ]);
311
+ await click(button(/^Received 1 update/));
312
+ await vi.waitFor(() =>
313
+ expect(container.querySelector('[aria-label="Tool call failed"]')).not.toBeNull(),
314
+ );
315
+ });
316
+
317
+ it("renders context compaction entries in the normal work log", async () => {
318
+ await renderTimeline([work("work-1", { label: "Context compacted", tone: "info" })]);
319
+ expect(text()).toContain("Context compacted");
320
+ });
321
+
322
+ it("formats changed file paths from the workspace root", async () => {
323
+ await renderTimeline(
324
+ [
325
+ work("context-info", { label: "Session started", tone: "info" }),
326
+ work("work-1", {
327
+ label: "Updated files",
328
+ tone: "tool",
329
+ itemType: "file_change",
330
+ toolLifecycleStatus: "completed",
331
+ changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
332
+ }),
333
+ ],
334
+ { workspaceRoot: "C:/Users/mike/dev-stuff/t3code" },
335
+ );
336
+ await click(button(/^Received 1 update/));
337
+ await vi.waitFor(() => expect(text()).toContain("t3code/apps/web/src/session-logic.ts"));
338
+ expect(text()).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
339
+ });
340
+
341
+ it("renders T3 MCP dynamic tools with their pretty name", async () => {
342
+ const item = {
343
+ id: "tool-t3-thread-read",
344
+ type: "dynamic_tool",
345
+ toolName: "mcp__t3-code__t3_thread_read",
346
+ input: { threadId: "thread-child" },
347
+ output: { messages: [] },
348
+ };
349
+ await renderTimeline([
350
+ work("context-info", { label: "Session started", tone: "info" }),
351
+ work(item.id, {
352
+ runId: null,
353
+ label: item.toolName,
354
+ tone: "tool",
355
+ itemType: item.type,
356
+ toolTitle: item.toolName,
357
+ toolLifecycleStatus: "completed",
358
+ toolData: { input: item.input, output: item.output },
359
+ structuredPayload: v2Item("dynamic_tool", item),
360
+ projectedItem: v2Item("dynamic_tool", item),
361
+ }),
362
+ ]);
363
+ await click(button(/^Received 1 update/));
364
+ await vi.waitFor(() => expect(text()).toContain("Read a T3 thread"));
365
+ expect(text()).not.toContain("mcp__t3-code__t3_thread_read");
366
+ });
367
+
368
+ it("keeps a provider retry collapsed in the work log", async () => {
369
+ const retryItem = {
370
+ id: "provider-error",
371
+ status: "running",
372
+ title: "Provider retry",
373
+ failure: {
374
+ class: "transport_error",
375
+ message: "The response stream disconnected.",
376
+ code: "responseStreamDisconnected",
377
+ retryable: true,
378
+ },
379
+ retry: { attempt: 2, maxAttempts: 5, retryDelayMs: null },
380
+ };
381
+ await renderTimeline(
382
+ [
383
+ work("provider-error", {
384
+ runId: "run-1",
385
+ label: "Retrying provider (2/5)",
386
+ detail: retryItem.failure.message,
387
+ tone: "info",
388
+ itemType: "error",
389
+ toolLifecycleStatus: "inProgress",
390
+ projectedItem: v2Item("error", retryItem),
391
+ }),
392
+ ],
393
+ {
394
+ isWorking: true,
395
+ activeTurnInProgress: true,
396
+ latestRun: {
397
+ runId: RunId.make("run-1"),
398
+ status: "running",
399
+ startedAt: CREATED_AT,
400
+ completedAt: null,
401
+ },
402
+ },
403
+ );
404
+ expect(text()).toContain("Retrying provider (2/5)");
405
+ expect(text()).not.toContain("Structured details");
406
+ });
407
+
408
+ it.each([
409
+ [
410
+ "**Viewing image first** with *care*, ~~old~~ `code` and [context](https://example.com)",
411
+ "Viewing image first with care, old code and context",
412
+ 1,
413
+ ],
414
+ ["first paragraph\n\nsecond paragraph", "first paragraph second paragraph", 0],
415
+ ["- first\n- second", "first second", 0],
416
+ ["first \nsecond", "first second", 0],
417
+ ["", "image description", 0],
418
+ ["", "Thought", 0],
419
+ ["---", "Thought", 0],
420
+ ] as const)(
421
+ "shows plain text for a V2 reasoning preview: %s",
422
+ async (markdown, expected, strongCount) => {
423
+ await renderTimeline([
424
+ work("reasoning-preview", {
425
+ label: markdown,
426
+ detail: markdown,
427
+ tone: "thinking",
428
+ itemType: "reasoning",
429
+ toolLifecycleStatus: "completed",
430
+ }),
431
+ ]);
432
+ const row = () => container.querySelector<HTMLElement>("[role=button][aria-expanded]")!;
433
+ const preview = () => row().textContent!.replace(/\s+/g, " ");
434
+ expect(preview()).toContain(expected);
435
+ expect(container.querySelectorAll("strong")).toHaveLength(0);
436
+ await click(row());
437
+ expect(container.querySelectorAll("strong")).toHaveLength(strongCount);
438
+ await click(row());
439
+ expect(preview()).toContain(expected);
440
+ await vi.waitFor(() => expect(container.querySelectorAll("strong")).toHaveLength(0));
441
+ },
442
+ );
443
+});
444
+
445
+describe("MessagesTimeline messages", () => {
446
+ it("preserves XML-like tags and comparisons in user messages as text", async () => {
447
+ const source = [
448
+ 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
449
+ 'Before <nested data-value="a&b">inside</nested> after',
450
+ "</global-agent-instructions> in your context?",
451
+ "Comparison: 2 < 3 and 5 > 4.",
452
+ ];
453
+ await renderTimeline([message(source.join("\n"))]);
454
+ for (const line of source) expect(text()).toContain(line);
455
+ expect(container.querySelector("global-agent-instructions, nested")).toBeNull();
456
+ });
457
+
458
+ it("preserves XML-like source inside user code spans and fences", async () => {
459
+ await renderTimeline([
460
+ message(
461
+ [
462
+ 'Inline `<tag attr="x">`',
463
+ "",
464
+ "```xml",
465
+ '<root><child enabled="true" /></root>',
466
+ "```",
467
+ ].join("\n"),
468
+ ),
469
+ ]);
470
+ expect(container.querySelector("code[data-inline-code]")?.textContent).toBe('<tag attr="x">');
471
+ expect(text()).toContain('<root><child enabled="true" /></root>');
472
+ });
473
+
474
+ it("does not show markdown titles in user messages", async () => {
475
+ await renderTimeline([
476
+ message(
477
+ '[link](https://example.com "link tip") ',
478
+ ),
479
+ ]);
480
+ expect(container.querySelector('a[href="https://example.com"]')).not.toBeNull();
481
+ expect(container.querySelector('img[src="https://example.com/image.png"]')).not.toBeNull();
482
+ expect(container.querySelector('[title="link tip"], [title="image tip"]')).toBeNull();
483
+ });
484
+
485
+ it("renders unsafe user HTML as inert source text", async () => {
486
+ const source =
487
+ '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
488
+ await renderTimeline([message(source)]);
489
+ expect(text()).toContain(source);
490
+ expect(container.querySelector("script, img")).toBeNull();
491
+ expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
492
+ });
493
+
494
+ it("renders sanitized raw HTML in assistant messages", async () => {
495
+ await renderTimeline([
496
+ message(
497
+ [
498
+ '<details onclick="globalThis.__t3Xss = 1">',
499
+ "<summary>Safe details</summary>",
500
+ "<script>globalThis.__t3Xss = 2</script>",
501
+ '<img src="x" onerror="globalThis.__t3Xss = 3">',
502
+ '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
503
+ "</details>",
504
+ ].join(""),
505
+ { role: "assistant" },
506
+ ),
507
+ ]);
508
+ expect(container.querySelector("[data-markdown-details]")?.textContent).toContain(
509
+ "Safe details",
510
+ );
511
+ expect(text()).not.toContain("<details");
512
+ expect(container.querySelector("script, [onclick], [onerror]")).toBeNull();
513
+ expect(container.innerHTML).not.toContain("javascript:");
514
+ await click(button("Safe details"));
515
+ expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
516
+ });
517
+
518
+ it("collapses long user messages behind a toggle and keeps their copy button", async () => {
519
+ await renderTimeline([message(longText())]);
520
+ const toggle = button("Show full message");
521
+ expect(toggle.getAttribute("aria-expanded")).toBe("false");
522
+ expect(buttons("Copy message")).toHaveLength(1);
523
+ await click(toggle);
524
+ expect(button("Show less").getAttribute("aria-expanded")).toBe("true");
525
+ });
526
+
527
+ it("does not offer a collapse toggle for short user messages", async () => {
528
+ await renderTimeline([message("Short prompt.")]);
529
+ expect(buttons(/Show full message|Show less/)).toHaveLength(0);
530
+ });
531
+
532
+ it("identifies user-role messages sent by another agent", async () => {
533
+ await renderTimeline([
534
+ message("Review this area", { createdBy: "agent", creationSource: "provider" }),
535
+ ]);
536
+ expect(text()).toContain("Sent by another agent");
537
+ await act(async () => roots.pop()!.unmount());
538
+ await renderTimeline([message("Review this area")]);
539
+ expect(text()).not.toContain("Sent by another agent");
540
+ });
541
+
542
+ it("shows steer intent ahead of committed user messages", async () => {
543
+ await renderTimeline([message("Adjust the current turn", { inputIntent: "steer" })]);
544
+ expect(text().indexOf("Steer")).toBeGreaterThanOrEqual(0);
545
+ expect(text().indexOf("Steer")).toBeLessThan(text().indexOf("Adjust the current turn"));
546
+ });
547
+
548
+ it("renders inline terminal labels as chips", async () => {
549
+ await renderTimeline([
550
+ message(
551
+ [
552
+ longText("yoo what's @terminal-1:1-5 mean"),
553
+ "",
554
+ "<terminal_context>",
555
+ "- Terminal 1 lines 1-5:",
556
+ " 1 | julius@mac effect-http-ws-cli % bun i",
557
+ " 2 | bun install v1.3.9 (cf6cdbbb)",
558
+ "</terminal_context>",
559
+ ].join("\n"),
560
+ ),
561
+ ]);
562
+ expect(text()).toContain("Terminal 1 lines 1-5");
563
+ expect(text()).toContain("yoo what's");
564
+ expect(text()).not.toContain("terminal_context");
565
+ expect(buttons("Show full message")).toHaveLength(1);
566
+ });
567
+
568
+ it("renders chips for standalone element-pick context messages", async () => {
569
+ await renderTimeline([
570
+ message(
571
+ [
572
+ "<element_context>",
573
+ "- <SubmitButton> (Button.tsx:12):",
574
+ " url: https://example.com/dashboard",
575
+ " selector: button.submit",
576
+ " source: /repo/src/Button.tsx:12:5",
577
+ " html:",
578
+ ' <button class="submit">Save</button>',
579
+ "</element_context>",
580
+ ].join("\n"),
581
+ ),
582
+ ]);
583
+ expect(text()).toContain("SubmitButton");
584
+ expect(text()).not.toContain("element_context");
585
+ });
586
+
587
+ it("renders review comment contexts as structured cards instead of raw tags", async () => {
588
+ await renderTimeline([
589
+ message(
590
+ [
591
+ '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
592
+ "Wadduo",
593
+ "```diff",
594
+ "@@ -0,0 +47,2 @@",
595
+ '+ it("keeps valid zero-usage snapshots", () => {',
596
+ "+ expect(snapshot).not.toBeNull();",
597
+ "```",
598
+ "</review_comment>",
599
+ ].join("\n"),
600
+ ),
601
+ ]);
602
+ expect(text()).toContain("contextWindow.test.ts L47 to L58");
603
+ expect(text()).not.toContain("review_comment");
604
+ });
605
+
606
+ it("renders file review comments as source code", async () => {
607
+ await renderTimeline([
608
+ message(
609
+ [
610
+ '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
611
+ "Clarify this.",
612
+ "```md",
613
+ "# Plan",
614
+ "- Step one",
615
+ "```",
616
+ "</review_comment>",
617
+ ].join("\n"),
618
+ ),
619
+ ]);
620
+ expect(text()).toContain("plan.md L1 to L2");
621
+ expect(text()).not.toContain("review_comment");
622
+ });
623
+
624
+ it("collapses superseded attempt output behind a disclosure", async () => {
625
+ const runId = RunId.make("run-steered");
626
+ const attempt = (id: string, ordinal: number, status: string) =>
627
+ ({
628
+ id,
629
+ runId,
630
+ attemptOrdinal: ordinal,
631
+ rootNodeId: `node-${id}`,
632
+ status,
633
+ completedAt: null,
634
+ }) as never;
635
+ await renderTimeline(
636
+ [
637
+ {
638
+ ...message(
639
+ "Partial response from the old attempt",
640
+ { role: "assistant", runId },
641
+ "superseded-response",
642
+ ),
643
+ attempt: attempt("attempt-1", 1, "superseded"),
644
+ } as Entry,
645
+ {
646
+ ...message(
647
+ "Current response remains visible",
648
+ { role: "assistant", runId, streaming: true },
649
+ "active-response",
650
+ ),
651
+ attempt: attempt("attempt-2", 2, "running"),
652
+ } as Entry,
653
+ ],
654
+ {
655
+ latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
656
+ },
657
+ );
658
+ expect(text()).toContain("Current response remains visible");
659
+ expect(text()).not.toContain("Partial response from the old attempt");
660
+ const disclosure = button(/Superseded attempt/);
661
+ expect(disclosure.textContent).toContain("Cut off by a steer");
662
+ await click(disclosure);
663
+ expect(text()).toContain("Partial response from the old attempt");
664
+ });
665
+
666
+ it("forks from a completed assistant response", async () => {
667
+ const onForkFromRun = vi.fn(async () => {});
668
+ await renderTimeline(
669
+ [
670
+ {
671
+ ...message("Done", { role: "assistant", runId: RunId.make("run-1") }, "assistant-1"),
672
+ projectedItem: v2Item("assistant_message", {
673
+ id: "assistant-item-1",
674
+ messageId: "assistant-1",
675
+ text: "Done",
676
+ streaming: false,
677
+ }),
678
+ } as Entry,
679
+ ],
680
+ { onForkFromRun },
681
+ );
682
+ await click(button("Fork from this response"));
683
+ expect(onForkFromRun).toHaveBeenCalledWith({ sourceThreadId: "thread-1", runId: "run-1" });
684
+ });
685
+
686
+ it("opens the changed files of an assistant response", async () => {
687
+ const assistantMessageId = MessageId.make("assistant-with-files");
688
+ const runId = RunId.make("run-with-files");
689
+ const onOpenTurnDiff = vi.fn();
690
+ await renderTimeline(
691
+ [message("Updated the fixture.", { role: "assistant", runId }, assistantMessageId)],
692
+ {
693
+ onOpenTurnDiff,
694
+ latestRun: { runId, status: "completed", startedAt: CREATED_AT, completedAt: CREATED_AT },
695
+ turnDiffSummaries: [
696
+ {
697
+ runId,
698
+ checkpointTurnCount: 1,
699
+ checkpointRef: CheckpointRef.make("checkpoint-with-files"),
700
+ status: "ready",
701
+ files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
702
+ assistantMessageId,
703
+ completedAt: CREATED_AT,
704
+ },
705
+ ],
706
+ },
707
+ );
708
+ expect(text()).toContain("1 changed file");
709
+ await click(button("Open diff"));
710
+ expect(onOpenTurnDiff).toHaveBeenCalledWith(runId, "README.md");
711
+ });
712
+});
713
+
714
+describe("MessagesTimeline attachments", () => {
715
+ const withAttachment = (attachment: Record<string, unknown>) =>
716
+ message("Read the report.", {
717
+ attachments: [
718
+ {
719
+ type: "file",
720
+ name: "report.pdf",
721
+ mimeType: "application/pdf",
722
+ sizeBytes: 42,
723
+ ...attachment,
724
+ },
725
+ ] as never,
726
+ });
727
+
728
+ it("offers preview and download actions for PDF attachments", async () => {
729
+ await renderTimeline([
730
+ withAttachment({
731
+ id: "attachment-report-pdf",
732
+ previewUrl: "https://environment.test/api/assets/report.pdf",
733
+ }),
734
+ ]);
735
+ expect(buttons("Preview report.pdf")).toHaveLength(1);
736
+ expect(buttons("Download report.pdf")).toHaveLength(1);
737
+ expect(container.querySelector('img[alt="report.pdf"]')).toBeNull();
738
+ });
739
+
740
+ it("does not create a download URL before the download is requested", async () => {
741
+ await renderTimeline([withAttachment({ id: "attachment-report-pdf" })]);
742
+ expect(buttons("Download report.pdf")).toHaveLength(1);
743
+ expect(container.querySelector("a[href]")).toBeNull();
744
+ });
745
+
746
+ it("does not download an optimistic file before the server supplies its attachment ID", async () => {
747
+ await renderTimeline([withAttachment({ id: "composer-local-report", downloadable: false })]);
748
+ expect(text()).toContain("report.pdf");
749
+ expect(buttons("Download report.pdf")).toHaveLength(0);
750
+ });
751
+
752
+ it("renders unknown attachment types as inert rows instead of crashing", async () => {
753
+ await renderTimeline([
754
+ withAttachment({
755
+ type: "recording",
756
+ id: "attachment-voice-memo",
757
+ name: "voice-memo.ogg",
758
+ mimeType: "audio/ogg",
759
+ }),
760
+ ]);
761
+ expect(text()).toContain("voice-memo.ogg");
762
+ expect(buttons("Download voice-memo.ogg")).toHaveLength(0);
763
+ expect(container.querySelector("a[href], img")).toBeNull();
764
+ });
765
+
766
+ it("shows SnapShot window details only after the preview resolves", async () => {
767
+ const snapShot = (previewUrl?: string) =>
768
+ message("First prompt.", {
769
+ attachments: [
770
+ {
771
+ type: "image",
772
+ id: "attachment-1",
773
+ name: "screenshot.png",
774
+ mimeType: "image/png",
775
+ sizeBytes: 1,
776
+ ...(previewUrl ? { previewUrl } : {}),
777
+ source: {
778
+ kind: "snap-shot",
779
+ capturedAt: CREATED_AT,
780
+ appName: "Terminal",
781
+ windowTitle: "t3code — Tests",
782
+ appIconDataUrl: "data:image/png;base64,aWNvbg==",
783
+ },
784
+ },
785
+ ] as never,
786
+ });
787
+ await renderTimeline([snapShot()]);
788
+ expect(text()).toContain("screenshot.png");
789
+ expect(text()).not.toContain("t3code — Tests");
790
+ await act(async () => roots.pop()!.unmount());
791
+ await renderTimeline([snapShot("data:image/png;base64,iVBORw0KGgo=")]);
792
+ expect(text()).toContain("Terminal");
793
+ expect(text()).toContain("t3code — Tests");
794
+ });
795
+});
796
+
797
+describe("MessagesTimeline history and thread links", () => {
798
+ it("loads earlier turns from a control ahead of the bounded timeline", async () => {
799
+ const onLoadEarlier = vi.fn();
800
+ await renderTimeline([message("Recent activity")], {
801
+ historyControls: {
802
+ hasMoreHistory: true,
803
+ loading: false,
804
+ error: "Earlier activity could not be loaded.",
805
+ onLoadEarlier,
806
+ },
807
+ });
808
+ expect(text()).toContain("Earlier activity could not be loaded.");
809
+ expect(text().indexOf("Load earlier turns")).toBeLessThan(text().indexOf("Recent activity"));
810
+ await click(button("Load earlier turns"));
811
+ expect(onLoadEarlier).toHaveBeenCalledOnce();
812
+ });
813
+
814
+ it("keeps an empty bounded timeline busy while earlier history loads", async () => {
815
+ await renderTimeline([], {
816
+ historyControls: {
817
+ hasMoreHistory: true,
818
+ loading: true,
819
+ error: null,
820
+ onLoadEarlier: () => {},
821
+ },
822
+ });
823
+ expect(text()).toContain("Loading earlier turns…");
824
+ expect(button("Load earlier turns")).toHaveProperty("disabled", true);
825
+ expect(text()).not.toContain("Send a message to start the conversation.");
826
+ });
827
+
828
+ it("opens the parent thread from the top of an empty subagent timeline", async () => {
829
+ const onOpenThread = vi.fn();
830
+ await renderTimeline([], {
831
+ onOpenThread,
832
+ parentThreadLink: { threadId: ThreadId.make("thread-parent"), title: "Architecture audit" },
833
+ });
834
+ expect(text()).toContain("Subagent of");
835
+ expect(text()).toContain("Architecture audit");
836
+ expect(text()).not.toContain("Send a message to start the conversation");
837
+ await click(button("Open parent thread"));
838
+ expect(onOpenThread).toHaveBeenCalledWith("thread-parent");
839
+ });
840
+
841
+ it("does not render the transient V2 interruption request", async () => {
842
+ await renderTimeline([
843
+ {
844
+ id: "interrupt-request",
845
+ kind: "event",
846
+ createdAt: CREATED_AT,
847
+ projectedItem: v2Item("run_interrupt_request", {
848
+ id: "interrupt-request",
849
+ message: "Waiting for the provider to stop.",
850
+ }),
851
+ } as Entry,
852
+ ]);
853
+ expect(text()).not.toContain("Interrupt requested");
854
+ expect(text()).not.toContain("Waiting for the provider to stop.");
855
+ });
856
+
857
+ it("opens created threads from a lean row", async () => {
858
+ const onOpenThread = vi.fn();
859
+ await renderTimeline(
860
+ [
861
+ {
862
+ id: "thread-created",
863
+ kind: "event",
864
+ createdAt: CREATED_AT,
865
+ projectedItem: v2Item("thread_created", {
866
+ id: "thread-created",
867
+ nodeId: "node-1",
868
+ ordinal: 1,
869
+ title: "Claude research thread",
870
+ targetThreadId: "thread-2",
871
+ targetRunId: "run-2",
872
+ targetProviderInstanceId: "claude-default",
873
+ targetModel: "claude-sonnet-4-6",
874
+ }),
875
+ } as Entry,
876
+ ],
877
+ { onOpenThread },
878
+ );
879
+ expect(text()).toContain("Claude research thread");
880
+ expect(text()).not.toContain("Work Log");
881
+ await click(button("Open Claude research thread"));
882
+ expect(onOpenThread).toHaveBeenCalledWith("thread-2");
883
+ });
884
+
885
+ it("renders context handoffs as from → to model endpoints instead of the summary", async () => {
886
+ const provider = (instanceId: string, driver: string, slug: string, name: string) => ({
887
+ instanceId,
888
+ driver,
889
+ enabled: true,
890
+ installed: true,
891
+ version: null,
892
+ status: "ready",
893
+ auth: {},
894
+ checkedAt: CREATED_AT,
895
+ models: [{ slug, name, isCustom: false, capabilities: null }],
896
+ slashCommands: [],
897
+ skills: [],
898
+ });
899
+ const providers = [
900
+ provider("codex_personal", "codex", "gpt-5.6-sol", "GPT 5.6 Sol"),
901
+ provider("claudeAgent", "claudeAgent", "claude-fable-5", "Claude Fable 5"),
902
+ ] as never;
903
+ const handoff = (fields: Record<string, unknown>) =>
904
+ ({
905
+ id: "handoff-1",
906
+ kind: "event",
907
+ createdAt: CREATED_AT,
908
+ projectedItem: v2Item("handoff", {
909
+ id: "handoff-1",
910
+ runId: "run-2",
911
+ title: "Provider handoff",
912
+ contextHandoffId: "handoff-1",
913
+ fromProviderThreadIds: ["provider-thread-1"],
914
+ toProviderThreadId: "provider-thread-2",
915
+ strategy: "full_thread_summary",
916
+ summary: "Full conversation context for provider handoff.",
917
+ fromProviderInstanceIds: ["codex_personal"],
918
+ toProviderInstanceId: "claudeAgent",
919
+ ...fields,
920
+ }),
921
+ }) as Entry;
922
+ const show = async (entry: Entry, props: Partial<TimelineProps> = {}) => {
923
+ for (const root of roots.splice(0)) await act(async () => root.unmount());
924
+ await renderElement(
925
+ <RegistryProvider
926
+ initialValues={[[serverEnvironment.providersValueAtom(ENVIRONMENT_ID), providers]]}
927
+ >
928
+ <MessagesTimeline {...baseProps()} timelineEntries={[entry]} {...props} />
929
+ </RegistryProvider>,
930
+ );
931
+ };
932
+
933
+ await show(
934
+ handoff({
935
+ fromModelSelections: [{ instanceId: "codex_personal", model: "gpt-5.6-sol" }],
936
+ toModel: "claude-fable-5",
937
+ }),
938
+ );
939
+ expect(text()).toContain("Context handoff");
940
+ expect(text()).toContain("GPT 5.6 Sol");
941
+ expect(text()).toContain("Claude Fable 5");
942
+ expect(text()).not.toContain("Full conversation context");
943
+
944
+ await show(handoff({}), {
945
+ runs: [
946
+ {
947
+ id: "run-1",
948
+ ordinal: 1,
949
+ providerInstanceId: "codex_personal",
950
+ modelSelection: { instanceId: "codex_personal", model: "gpt-5.6-sol" },
951
+ },
952
+ {
953
+ id: "run-2",
954
+ ordinal: 2,
955
+ providerInstanceId: "claudeAgent",
956
+ modelSelection: { instanceId: "claudeAgent", model: "claude-fable-5" },
957
+ },
958
+ ] as never,
959
+ });
960
+ expect(text()).toContain("GPT 5.6 Sol");
961
+ expect(text()).toContain("Claude Fable 5");
962
+
963
+ await show(handoff({}));
964
+ expect(text()).toContain("Codex Personal");
965
+ expect(text()).not.toContain("Full conversation context");
966
+ });
967
+});
968
+
969
+describe("MessagesTimeline subagents", () => {
970
+ it.each(
971
+ (
972
+ [
973
+ {
974
+ status: "running",
975
+ progress: "Reading src/index.ts",
976
+ result: null,
977
+ preview: "Reading src/index.ts",
978
+ },
979
+ {
980
+ status: "completed",
981
+ progress: "Reading src/index.ts",
982
+ result: "Tests should be isolated.",
983
+ preview: "Tests should be isolated.",
984
+ },
985
+ {
986
+ status: "running",
987
+ progress: "Reading src/index.ts",
988
+ result: "Partial streamed answer",
989
+ preview: "Reading src/index.ts",
990
+ },
991
+ {
992
+ status: "running",
993
+ progress: undefined,
994
+ result: "Streaming answer so far",
995
+ preview: "Streaming answer so far",
996
+ },
997
+ {
998
+ status: "cancelled",
999
+ progress: "Reading src/index.ts",
1000
+ result: "Partial output before cancel",
1001
+ preview: "Partial output before cancel",
1002
+ },
1003
+ {
1004
+ status: "completed",
1005
+ progress: "Audited 12 packages",
1006
+ result: " \n\t ",
1007
+ preview: "Audited 12 packages",
1008
+ },
1009
+ ] as const
1010
+ ).flatMap((scenario) => [1, 2].map((count) => ({ ...scenario, count }))),
1011
+ )(
1012
+ "shows $count $status subagents with '$preview', grouping only multiple agents",
1013
+ async ({ status, progress, result, preview, count }) => {
1014
+ const onOpenThread = vi.fn();
1015
+ await renderTimeline(
1016
+ Array.from(
1017
+ { length: count },
1018
+ (_, index) =>
1019
+ ({
1020
+ id: `subagent-progress-${index}`,
1021
+ kind: "event",
1022
+ createdAt: CREATED_AT,
1023
+ projectedItem: v2Item("subagent", {
1024
+ id: `subagent-progress-${index}`,
1025
+ nodeId: `node-subagent-${index}`,
1026
+ providerThreadId: "provider-thread-1",
1027
+ providerTurnId: "provider-turn-1",
1028
+ ordinal: 1,
1029
+ status,
1030
+ title: "Package audit",
1031
+ subagentId: `node-subagent-${index}`,
1032
+ origin: "provider_native",
1033
+ driver: "claudeAgent",
1034
+ providerInstanceId: "claudeAgent",
1035
+ childThreadId: "thread-subagent-1",
1036
+ prompt: "Inspect the package",
1037
+ progress,
1038
+ result,
1039
+ }),
1040
+ }) as Entry,
1041
+ ),
1042
+ { onOpenThread },
1043
+ );
1044
+ const children = () => buttons("Open Package audit");
1045
+ // A settled run folds its work behind a "Worked for" summary.
1046
+ const fold = buttons(/^Worked for/)[0];
1047
+ if (fold) await click(fold);
1048
+ if (count > 1) {
1049
+ expect(children()).toHaveLength(0);
1050
+ await click(button(`${count} subagents`));
1051
+ } else {
1052
+ expect(buttons(`${count} subagents`)).toHaveLength(0);
1053
+ }
1054
+ expect(children()).toHaveLength(count);
1055
+ expect(text()).toContain(preview);
1056
+ expect(text()).not.toContain("Inspect the package");
1057
+ if (result?.trim() && result !== preview) expect(text()).not.toContain(result);
1058
+ if (progress && progress !== preview) expect(text()).not.toContain(progress);
1059
+ await click(children()[0]!);
1060
+ expect(onOpenThread).toHaveBeenCalledWith("thread-subagent-1");
1061
+ if (count > 1) {
1062
+ await click(button(`${count} subagents`));
1063
+ await vi.waitFor(() => expect(children()).toHaveLength(0));
1064
+ }
1065
+ },
1066
+ );
1067
+});
1068
+
1069
+describe("timeline tooltip scroll dismissal", () => {
1070
+ const openPopup = () =>
1071
+ document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent ?? null;
1072
+
1073
+ async function renderTooltip(pullRequest: boolean, outside: boolean) {
1074
+ const tooltip = pullRequest ? (
1075
+ <PullRequestLinkPreview
1076
+ link={<button>message link</button>}
1077
+ originalUrl="https://example.com"
1078
+ target={{
1079
+ environmentId: ENVIRONMENT_ID,
1080
+ input: { projectId: "project-1" as never, repository: "pingdotgg/t3code", number: 1 },
1081
+ }}
1082
+ />
1083
+ ) : (
1084
+ <Tooltip>
1085
+ <TooltipTrigger delay={50}>message link</TooltipTrigger>
1086
+ <TooltipPopup>https://example.com</TooltipPopup>
1087
+ </Tooltip>
1088
+ );
1089
+ await renderElement(
1090
+ <>
1091
+ <TooltipScrollDismissArea>
1092
+ <div data-testid="scrollable" className="h-[100px] overflow-auto">
1093
+ {outside ? null : tooltip}
1094
+ <div className="h-[1000px]" />
1095
+ </div>
1096
+ </TooltipScrollDismissArea>
1097
+ {outside ? tooltip : null}
1098
+ </>,
1099
+ );
1100
+ return {
1101
+ trigger: container.querySelector<HTMLButtonElement>("button")!,
1102
+ scrollable: container.querySelector<HTMLElement>('[data-testid="scrollable"]')!,
1103
+ };
1104
+ }
1105
+
1106
+ async function scroll(scrollable: HTMLElement) {
1107
+ await act(async () => {
1108
+ scrollable.scrollTop += 50;
1109
+ scrollable.dispatchEvent(new Event("scroll"));
1110
+ });
1111
+ }
1112
+
1113
+ it.each([false, true])(
1114
+ "closes a hovered tooltip on scroll but keeps a focused one (pull request=%s)",
1115
+ async (pullRequest) => {
1116
+ const { trigger, scrollable } = await renderTooltip(pullRequest, false);
1117
+ await userEvent.hover(trigger);
1118
+ await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1119
+ await scroll(scrollable);
1120
+ await vi.waitFor(() => expect(openPopup()).toBeNull());
1121
+
1122
+ await userEvent.unhover(trigger);
1123
+ await userEvent.keyboard("{Tab}");
1124
+ expect(document.activeElement).toBe(trigger);
1125
+ await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1126
+ await scroll(scrollable);
1127
+ expect(openPopup()).toBe("https://example.com");
1128
+ expect(document.activeElement).toBe(trigger);
1129
+ },
1130
+ );
1131
+
1132
+ it("leaves tooltips outside the timeline open when it scrolls", async () => {
1133
+ const { trigger, scrollable } = await renderTooltip(false, true);
1134
+ await userEvent.hover(trigger);
1135
+ await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1136
+ await scroll(scrollable);
1137
+ expect(openPopup()).toBe("https://example.com");
1138
+ });
1139
+
1140
+ it("keeps a hovered tooltip open on a wheel that does not scroll", async () => {
1141
+ const { trigger, scrollable } = await renderTooltip(false, false);
1142
+ await userEvent.hover(trigger);
1143
+ await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1144
+ await act(async () => {
1145
+ scrollable.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: 100 }));
1146
+ });
1147
+ expect(openPopup()).toBe("https://example.com");
1148
+ });
1149
+});
1150
+
1151
+describe("MessagesTimeline scroll position", () => {
1152
+ const tall = (index: number) =>
1153
+ message(
1154
+ `Message ${index}\n\n${"Long paragraph. ".repeat(80)}`,
1155
+ { role: "assistant" },
1156
+ `message-${index}`,
1157
+ );
1158
+ const tallEntries = Array.from({ length: 12 }, (_, index) => tall(index));
1159
+
1160
+ async function waitForList(props: ReturnType<typeof baseProps>) {
1161
+ await vi.waitFor(() => {
1162
+ const viewport = props.listRef.current?.getScrollableNode();
1163
+ expect(viewport?.scrollHeight ?? 0).toBeGreaterThan(viewport?.clientHeight ?? 0);
1164
+ });
1165
+ return props.listRef.current!.getScrollableNode()!;
1166
+ }
1167
+
1168
+ it("remembers a manual reading position when the chat closes", async () => {
1169
+ const props = baseProps();
1170
+ function Chat() {
1171
+ const [liveFollowEnabled, setLiveFollowEnabled] = useState(true);
1172
+ // The chat view stops following the live edge when the reader scrolls.
1173
+ return (
1174
+ <div className="contents" onWheelCapture={() => setLiveFollowEnabled(false)}>
1175
+ <MessagesTimeline
1176
+ {...props}
1177
+ timelineEntries={tallEntries}
1178
+ liveFollowEnabled={liveFollowEnabled}
1179
+ />
1180
+ </div>
1181
+ );
1182
+ }
1183
+ await renderElement(<Chat />);
1184
+ const viewport = await waitForList(props);
1185
+ await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true));
1186
+
1187
+ await userEvent.wheel(viewport, { delta: { y: -600 } });
1188
+ await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(false));
1189
+ const offset = viewport.scrollTop;
1190
+ await act(async () => roots.pop()!.unmount());
1191
+ expect(readTimelinePosition(props.routeThreadKey)).toMatchObject({
1192
+ atEnd: false,
1193
+ scrollOffset: offset,
1194
+ });
1195
+ });
1196
+
1197
+ it("restores the composer after closing tool output only at the end", async () => {
1198
+ const props = baseProps();
1199
+ function Thread() {
1200
+ const composer = useComposerFocusState();
1201
+ return (
1202
+ <>
1203
+ <button onClick={() => composer.setIsComposerScrollCollapsed(true)}>Collapse</button>
1204
+ <output>{composer.isComposerScrollCollapsed ? "collapsed" : "resting"}</output>
1205
+ <MessagesTimeline
1206
+ {...props}
1207
+ onToolOutputCollapsedAtEnd={composer.restoreAfterTimelineReachedEnd}
1208
+ timelineEntries={[
1209
+ ...tallEntries,
1210
+ work("tool", {
1211
+ label: "Run command",
1212
+ tone: "tool",
1213
+ toolLifecycleStatus: "completed",
1214
+ detail: "Command output",
1215
+ }),
1216
+ ]}
1217
+ />
1218
+ </>
1219
+ );
1220
+ }
1221
+ await renderElement(<Thread />);
1222
+ const composerState = () => container.querySelector("output")!.textContent;
1223
+ const viewport = await waitForList(props);
1224
+ await click(button("Collapse"));
1225
+ const toggle = () => button("Command output");
1226
+ await click(toggle());
1227
+ await click(toggle());
1228
+ await vi.waitFor(() => expect(composerState()).toBe("resting"));
1229
+
1230
+ await click(button("Collapse"));
1231
+ await userEvent.wheel(viewport, { delta: { y: -2000 } });
1232
+ await click(toggle());
1233
+ await click(toggle());
1234
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1235
+ expect(composerState()).toBe("collapsed");
1236
+ });
1237
+});
1238
+
1239
+describe("MessagesTimeline send anchor", () => {
1240
+ it("reports the anchored sent message once it is laid out", async () => {
1241
+ const onAnchorReady = vi.fn();
1242
+ const sent = message("Newest prompt.", {}, "message-2");
1243
+ await renderTimeline([message("Earlier reply.", { role: "assistant" }), sent], {
1244
+ anchorMessageId: MessageId.make("message-2"),
1245
+ onAnchorReady,
1246
+ contentInsetEndAdjustment: 144,
1247
+ });
1248
+ await vi.waitFor(() =>
1249
+ expect(onAnchorReady).toHaveBeenCalledWith(MessageId.make("message-2"), 1),
1250
+ );
1251
+ });
1252
+
1253
+ it("does not anchor a follow-up user message that is not the newest turn", async () => {
1254
+ const onAnchorReady = vi.fn();
1255
+ await renderTimeline([message("First prompt."), message("Newest prompt.", {}, "message-2")], {
1256
+ anchorMessageId: MessageId.make("message-2"),
1257
+ onAnchorReady,
1258
+ });
1259
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1260
+ expect(onAnchorReady).not.toHaveBeenCalled();
1261
+ });
1262
+});
apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+78
@@ -34,6 +34,14 @@ import {
34
liveWorkEntryLabel,
35
normalizeCompactToolLabel,
36
resolveAssistantMessageCopyState,
37
+ resolveTimelineIsAtEnd,
38
+ resolveTimelineMinimapHasPersistentGutter,
39
+ resolveTimelineMinimapHeightStyle,
40
+ resolveTimelineMinimapHitStripWidth,
41
+ resolveTimelineMinimapIndexFromPointer,
42
+ resolveTimelineMinimapInteractiveWidth,
43
+ resolveTimelineMinimapNavigationInteractive,
44
+ resolveTimelineMinimapTopPercent,
45
resolveWorkGroupScrollIndex,
46
shouldFollowWorkGroupAppend,
47
threadReadLabelPrefix,
@@ -5464,3 +5472,73 @@ describe("shouldCollapseUserMessage", () => {
5472
expect(shouldCollapseUserMessage(text)).toBe(false);
5473
});
5474
});
5475
+
5476
+describe("timeline end and minimap geometry", () => {
5477
+ it("treats the follow re-arm band above the content bottom as the live edge", () => {
5478
+ expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
5479
+ expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();
5480
+ expect(
5481
+ resolveTimelineIsAtEnd({
5482
+ isAtEnd: false,
5483
+ contentLength: 2000,
5484
+ scroll: 1170,
5485
+ scrollLength: 800,
5486
+ }),
5487
+ ).toBe(true);
5488
+ expect(
5489
+ resolveTimelineIsAtEnd({
5490
+ isAtEnd: false,
5491
+ contentLength: 2000,
5492
+ scroll: 900,
5493
+ scrollLength: 800,
5494
+ }),
5495
+ ).toBe(false);
5496
+ expect(
5497
+ resolveTimelineIsAtEnd({
5498
+ isAtEnd: true,
5499
+ contentLength: 2100,
5500
+ scroll: 1170,
5501
+ scrollLength: 800,
5502
+ }),
5503
+ ).toBe(false);
5504
+ expect(resolveTimelineIsAtEnd({ isNearEnd: true, isAtEnd: false })).toBe(false);
5505
+ expect(resolveTimelineIsAtEnd({ isAtEnd: false })).toBe(false);
5506
+ });
5507
+
5508
+ it("maps the minimap rail to rows and sizes its hit strip from the free gutter", () => {
5509
+ expect(resolveTimelineMinimapHeightStyle(5)).toBe("min(32px, calc(100vh - 18rem))");
5510
+ expect(resolveTimelineMinimapTopPercent(2, 5)).toBe(50);
5511
+ const rail = { itemCount: 101, railTop: 100, railHeight: 500 };
5512
+ expect(resolveTimelineMinimapIndexFromPointer({ ...rail, pointerY: 350 })).toBe(50);
5513
+ expect(resolveTimelineMinimapIndexFromPointer({ ...rail, pointerY: 999 })).toBe(100);
5514
+
5515
+ expect(resolveTimelineMinimapHasPersistentGutter(832, 768)).toBe(false);
5516
+ expect(resolveTimelineMinimapHasPersistentGutter(863, 768)).toBe(false);
5517
+ expect(resolveTimelineMinimapHasPersistentGutter(864, 768)).toBe(true);
5518
+ expect(resolveTimelineMinimapHasPersistentGutter(1400, 1152)).toBe(true);
5519
+ expect(resolveTimelineMinimapHasPersistentGutter(1200, 1152)).toBe(false);
5520
+ expect(resolveTimelineMinimapHasPersistentGutter(2560, 2560)).toBe(false);
5521
+
5522
+ expect(resolveTimelineMinimapHitStripWidth(768, 768)).toBe(0);
5523
+ expect(resolveTimelineMinimapHitStripWidth(792, 768)).toBe(0);
5524
+ expect(resolveTimelineMinimapHitStripWidth(820, 768)).toBe(14);
5525
+ expect(resolveTimelineMinimapHitStripWidth(872, 768)).toBe(40);
5526
+ expect(resolveTimelineMinimapHitStripWidth(1400, 768)).toBe(40);
5527
+ expect(resolveTimelineMinimapHitStripWidth(2560, 2560)).toBe(0);
5528
+ expect(resolveTimelineMinimapHitStripWidth(1204, 1152)).toBe(14);
5529
+ expect(resolveTimelineMinimapHitStripWidth(0, 0)).toBe(0);
5530
+ expect(resolveTimelineMinimapHitStripWidth(Number.NaN, 768)).toBe(0);
5531
+
5532
+ expect(resolveTimelineMinimapNavigationInteractive(40)).toBe(true);
5533
+ expect(resolveTimelineMinimapNavigationInteractive(14)).toBe(true);
5534
+ expect(resolveTimelineMinimapNavigationInteractive(8)).toBe(false);
5535
+ expect(resolveTimelineMinimapNavigationInteractive(0)).toBe(false);
5536
+
5537
+ expect(resolveTimelineMinimapInteractiveWidth(0, false)).toBe(0);
5538
+ expect(resolveTimelineMinimapInteractiveWidth(14, false)).toBe(14);
5539
+ expect(resolveTimelineMinimapInteractiveWidth(40, false)).toBe(40);
5540
+ for (const width of [0, 14, 40]) {
5541
+ expect(resolveTimelineMinimapInteractiveWidth(width, true)).toBe("22rem");
5542
+ }
5543
+ });
5544
+});
apps/web/src/components/chat/MessagesTimeline.test.tsx
deleted
-2907
@@ -1,2907 +0,0 @@
1
-// @vitest-environment jsdom
2
-
3
-import {
4
- ApprovalRequestId,
5
- CheckpointRef,
6
- EnvironmentId,
7
- MessageId,
8
- ProjectId,
9
- RunId,
10
- ThreadId,
11
-} from "@t3tools/contracts";
12
-import {
13
- act,
14
- createRef,
15
- useLayoutEffect,
16
- useState,
17
- type ReactNode,
18
- type Ref,
19
- type ReactElement,
20
-} from "react";
21
-import { renderToStaticMarkup } from "react-dom/server";
22
-import { createRoot } from "react-dom/client";
23
-import { create, type ReactTestRenderer } from "react-test-renderer";
24
-import { shouldUseRestingComposerLayout } from "../composerFooterLayout";
25
-import { useComposerFocusState } from "./useComposerFocusState";
26
-import { beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test";
27
-import type { LegendListRef } from "@legendapp/list/react";
28
-
29
-const activityTestState = vi.hoisted(() => ({
30
- expanded: false,
31
- expandedRuns: false,
32
- subagentTooltips: false,
33
-}));
34
-
35
-vi.mock("../ui/tooltip", async (importOriginal) => {
36
- const original = await importOriginal<typeof import("../ui/tooltip")>();
37
- return {
38
- ...original,
39
- Tooltip: (props: { children?: ReactNode }) =>
40
- activityTestState.subagentTooltips ? props.children : <original.Tooltip {...props} />,
41
- TooltipTrigger: (props: { children?: ReactNode; render?: ReactElement }) =>
42
- activityTestState.subagentTooltips ? (
43
- <>
44
- {props.render}
45
- {props.children}
46
- </>
47
- ) : (
48
- <original.TooltipTrigger {...props} />
49
- ),
50
- TooltipPopup: (props: { children?: ReactNode }) =>
51
- activityTestState.subagentTooltips ? props.children : <original.TooltipPopup {...props} />,
52
- };
53
-});
54
-
55
-vi.mock("../DiffWorkerPoolProvider", () => ({
56
- DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => children,
57
-}));
58
-
59
-vi.mock("./MessagesTimeline.logic", async (importOriginal) => {
60
- const logic = await importOriginal<typeof import("./MessagesTimeline.logic")>();
61
- return {
62
- ...logic,
63
- deriveMessagesTimelineRowsWithState(
64
- input: Parameters<typeof logic.deriveMessagesTimelineRowsWithState>[0],
65
- previous: Parameters<typeof logic.deriveMessagesTimelineRowsWithState>[1],
66
- ) {
67
- if (activityTestState.expandedRuns) {
68
- input = { ...input, expandedRunIds: new Set([RunId.make("run-1")]) };
69
- }
70
- const projection = logic.deriveMessagesTimelineRowsWithState(input, previous);
71
- if (!activityTestState.expanded) return projection;
72
- return logic.deriveMessagesTimelineRowsWithState({
73
- ...input,
74
- expandedWorkGroupIds: new Set(
75
- projection.rows.flatMap((row) =>
76
- row.kind === "work-toggle" || row.kind === "work-live" ? [row.groupId] : [],
77
- ),
78
- ),
79
- });
80
- },
81
- };
82
-});
83
-
84
-beforeEach(() => {
85
- activityTestState.subagentTooltips = false;
86
- activityTestState.expanded = false;
87
- activityTestState.expandedRuns = false;
88
-});
89
-
90
-const legendListTestState = vi.hoisted(() => ({
91
- data: undefined as unknown,
92
- onScroll: undefined as (() => void) | undefined,
93
-}));
94
-
95
-vi.mock("@legendapp/list/react", async () => {
96
- const { useLayoutEffect } = await import("react");
97
- const legendListTestId = "legend-list";
98
-
99
- const LegendList = (props: {
100
- data: Array<{ id: string }>;
101
- keyExtractor: (item: { id: string }) => string;
102
- renderItem: (args: { item: { id: string } }) => ReactNode;
103
- ListHeaderComponent?: ReactNode;
104
- ListFooterComponent?: ReactNode;
105
- anchoredEndSpace?: {
106
- anchorIndex: number;
107
- anchorMaxSize?: number;
108
- anchorOffset?: number;
109
- onReady?: (info: { anchorIndex: number }) => void;
110
- onSizeChanged?: (size: number) => void;
111
- };
112
- maintainScrollAtEnd?:
113
- | boolean
114
- | {
115
- animated?: boolean;
116
- on?: {
117
- dataChange?: boolean;
118
- itemLayout?: boolean;
119
- layout?: boolean;
120
- };
121
- };
122
- maintainVisibleContentPosition?:
123
- | boolean
124
- | {
125
- data?: boolean;
126
- size?: boolean;
127
- shouldRestorePosition?: boolean;
128
- };
129
- className?: string;
130
- contentInsetEndAdjustment?: number;
131
- onScroll?: () => void;
132
- ref?: Ref<LegendListRef>;
133
- }) => {
134
- useLayoutEffect(() => {
135
- legendListTestState.data = props.data;
136
- legendListTestState.onScroll = props.onScroll;
137
- });
138
- if (props.anchoredEndSpace) {
139
- props.anchoredEndSpace.onSizeChanged?.(240);
140
- props.anchoredEndSpace.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
141
- }
142
- return (
143
- <div
144
- data-testid={legendListTestId}
145
- data-class-name={props.className}
146
- data-anchor-index={props.anchoredEndSpace?.anchorIndex}
147
- data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
148
- data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
149
- data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
150
- data-content-inset-end={props.contentInsetEndAdjustment}
151
- data-maintain-visible-content-position={
152
- typeof props.maintainVisibleContentPosition === "object"
153
- ? "object"
154
- : props.maintainVisibleContentPosition
155
- }
156
- data-maintain-visible-content-position-data={
157
- typeof props.maintainVisibleContentPosition === "object"
158
- ? props.maintainVisibleContentPosition.data
159
- : undefined
160
- }
161
- data-maintain-visible-content-position-size={
162
- typeof props.maintainVisibleContentPosition === "object"
163
- ? props.maintainVisibleContentPosition.size
164
- : undefined
165
- }
166
- data-maintain-visible-content-position-restore={
167
- typeof props.maintainVisibleContentPosition === "object"
168
- ? Boolean(props.maintainVisibleContentPosition.shouldRestorePosition)
169
- : undefined
170
- }
171
- data-maintain-scroll-at-end={props.maintainScrollAtEnd ? "enabled" : undefined}
172
- data-maintain-scroll-at-end-animated={
173
- typeof props.maintainScrollAtEnd === "object"
174
- ? props.maintainScrollAtEnd.animated
175
- : undefined
176
- }
177
- data-maintain-scroll-at-end-data-change={
178
- typeof props.maintainScrollAtEnd === "object"
179
- ? props.maintainScrollAtEnd.on?.dataChange
180
- : undefined
181
- }
182
- data-maintain-scroll-at-end-item-layout={
183
- typeof props.maintainScrollAtEnd === "object"
184
- ? props.maintainScrollAtEnd.on?.itemLayout
185
- : undefined
186
- }
187
- data-maintain-scroll-at-end-layout={
188
- typeof props.maintainScrollAtEnd === "object"
189
- ? props.maintainScrollAtEnd.on?.layout
190
- : undefined
191
- }
192
- >
193
- {props.ListHeaderComponent}
194
- {props.data.map((item) => (
195
- <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
196
- ))}
197
- {props.ListFooterComponent}
198
- </div>
199
- );
200
- };
201
-
202
- return { LegendList };
203
-});
204
-
205
-function MockFileDiff(props: {
206
- fileDiff: { name?: string | null; prevName?: string | null };
207
- renderCustomHeader?: (fileDiff: {
208
- name?: string | null;
209
- prevName?: string | null;
210
- }) => React.ReactNode;
211
-}) {
212
- return (
213
- <div data-testid="file-diff">
214
- {props.renderCustomHeader?.(props.fileDiff)}
215
- {props.fileDiff.name ?? props.fileDiff.prevName ?? "diff"}
216
- </div>
217
- );
218
-}
219
-
220
-vi.mock("@pierre/diffs/react", () => {
221
- return { FileDiff: MockFileDiff };
222
-});
223
-
224
-function matchMedia() {
225
- return {
226
- matches: false,
227
- addEventListener: () => {},
228
- removeEventListener: () => {},
229
- };
230
-}
231
-
232
-let MessagesTimeline: typeof import("./MessagesTimeline").MessagesTimeline;
233
-
234
-const ElementStub = function ElementStub() {};
235
-function stubDomGlobals() {
236
- const classList = {
237
- add: () => {},
238
- remove: () => {},
239
- toggle: () => {},
240
- contains: () => false,
241
- };
242
-
243
- vi.stubGlobal("Element", ElementStub);
244
- vi.stubGlobal("getComputedStyle", undefined);
245
- vi.stubGlobal("localStorage", {
246
- getItem: () => null,
247
- setItem: () => {},
248
- removeItem: () => {},
249
- clear: () => {},
250
- });
251
- vi.stubGlobal("window", {
252
- Element: ElementStub,
253
- localStorage: globalThis.localStorage,
254
- matchMedia,
255
- addEventListener: () => {},
256
- removeEventListener: () => {},
257
- requestAnimationFrame: (callback: FrameRequestCallback) => {
258
- callback(0);
259
- return 0;
260
- },
261
- cancelAnimationFrame: () => {},
262
- desktopBridge: undefined,
263
- });
264
- vi.stubGlobal("document", {
265
- documentElement: {
266
- classList,
267
- offsetHeight: 0,
268
- },
269
- });
270
-}
271
-
272
-beforeEach(stubDomGlobals);
273
-// Cold transformation of the full chat dependency graph needs extra time on slower CI workers.
274
-beforeAll(async () => {
275
- Object.defineProperty(window, "matchMedia", { value: matchMedia, configurable: true });
276
- ({ MessagesTimeline } = await import("./MessagesTimeline"));
277
-}, 120_000);
278
-
279
-const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
280
-const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
281
-
282
-describe("timeline tooltip scroll dismissal", () => {
283
- it.each([
284
- "hover",
285
- "delayed hover",
286
- "focus",
287
- "hover then focus",
288
- "outside timeline",
289
- "wheel without scroll",
290
- "pr hover",
291
- "pr delayed hover",
292
- "pr focus",
293
- "pr hover then focus",
294
- ])("handles %s through the real tooltip interactions", async (scenario) => {
295
- const isPullRequest = scenario.startsWith("pr ");
296
- const interaction = isPullRequest ? scenario.slice(3) : scenario;
297
- vi.unstubAllGlobals();
298
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
299
- vi.useFakeTimers();
300
- const { Tooltip, TooltipTrigger, TooltipPopup, TooltipScrollDismissArea } =
301
- await vi.importActual<typeof import("../ui/tooltip")>("../ui/tooltip");
302
- const container = document.createElement("div");
303
- document.body.append(container);
304
- const root = createRoot(container);
305
- const onMouseEnter = vi.fn();
306
- const query = await import("~/state/query");
307
- const querySpy = isPullRequest
308
- ? vi.spyOn(query, "useEnvironmentQuery").mockReturnValue({
309
- data: null,
310
- dataUpdatedAt: 0,
311
- error: "Pull request not found",
312
- failure: null,
313
- isPending: false,
314
- isSuccess: false,
315
- refresh: vi.fn(),
316
- })
317
- : null;
318
- const { PullRequestLinkPreview } = await import("../pullRequest/PullRequestLinkPreview");
319
- const tooltip = isPullRequest ? (
320
- <PullRequestLinkPreview
321
- link={<button onMouseEnter={onMouseEnter}>message link</button>}
322
- originalUrl="https://example.com"
323
- target={{
324
- environmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
325
- input: {
326
- projectId: ProjectId.make("project-1"),
327
- repository: "pingdotgg/t3code",
328
- number: 1,
329
- },
330
- }}
331
- />
332
- ) : (
333
- <Tooltip>
334
- <TooltipTrigger delay={50} onMouseEnter={onMouseEnter}>
335
- message link
336
- </TooltipTrigger>
337
- <TooltipPopup>https://example.com</TooltipPopup>
338
- </Tooltip>
339
- );
340
- try {
341
- await act(async () => {
342
- root.render(
343
- <>
344
- <TooltipScrollDismissArea>
345
- <div data-testid="scrollable">
346
- {interaction === "outside timeline" ? null : tooltip}
347
- </div>
348
- </TooltipScrollDismissArea>
349
- {interaction === "outside timeline" ? tooltip : null}
350
- </>,
351
- );
352
- });
353
- const trigger = container.querySelector<HTMLButtonElement>("button")!;
354
- const scrollable = container.querySelector<HTMLElement>('[data-testid="scrollable"]')!;
355
- await act(async () => {
356
- if (interaction !== "focus") {
357
- trigger.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
358
- trigger.dispatchEvent(new MouseEvent("mouseenter"));
359
- trigger.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
360
- }
361
- if (interaction === "focus" || interaction === "hover then focus") {
362
- document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab" }));
363
- trigger.focus();
364
- }
365
- if (interaction !== "delayed hover") {
366
- await vi.advanceTimersByTimeAsync(isPullRequest ? 400 : 60);
367
- }
368
- });
369
- expect(onMouseEnter).toHaveBeenCalledTimes(interaction === "focus" ? 0 : 1);
370
- expect(
371
- document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent ?? null,
372
- ).toBe(interaction === "delayed hover" ? null : "https://example.com");
373
-
374
- await act(async () => {
375
- scrollable.dispatchEvent(
376
- interaction === "wheel without scroll"
377
- ? new WheelEvent("wheel", { bubbles: true, deltaY: 100 })
378
- : new Event("scroll"),
379
- );
380
- await vi.advanceTimersByTimeAsync(isPullRequest ? 1000 : 100);
381
- });
382
- expect(
383
- document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent ?? null,
384
- ).toBe(
385
- interaction === "hover" || interaction === "delayed hover" ? null : "https://example.com",
386
- );
387
- if (interaction === "focus" || interaction === "hover then focus") {
388
- expect(document.activeElement).toBe(trigger);
389
- }
390
- } finally {
391
- await act(async () => root.unmount());
392
- querySpy?.mockRestore();
393
- container.remove();
394
- vi.useRealTimers();
395
- vi.unstubAllGlobals();
396
- }
397
- });
398
-});
399
-
400
-function buildProps() {
401
- return {
402
- isWorking: false,
403
- activeTurnInProgress: false,
404
- listRef: createRef<LegendListRef | null>(),
405
- latestRun: null,
406
- turnDiffSummaries: [],
407
- runs: [],
408
- routeThreadKey: "environment-local:thread-1",
409
- onOpenTurnDiff: () => {},
410
- onOpenThread: () => {},
411
- onForkFromRun: async () => {},
412
- onRollbackCheckpoint: () => {},
413
- supportsConversationRollback: false,
414
- onRevertToTurnCount: () => {},
415
- isRevertingCheckpoint: false,
416
- openingVideoAttachmentId: null,
417
- onImageExpand: () => {},
418
- activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
419
- markdownCwd: undefined,
420
- resolvedTheme: "light" as const,
421
- timestampFormat: "locale" as const,
422
- workspaceRoot: undefined,
423
- anchorMessageId: null,
424
- onAnchorReady: () => {},
425
- onAnchorSizeChanged: () => {},
426
- contentInsetEndAdjustment: 0,
427
- liveFollowEnabled: true,
428
- onIsAtEndChange: () => {},
429
- onManualNavigation: () => {},
430
- };
431
-}
432
-
433
-function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
434
- return Array.from({ length: 9 }, (_, index) =>
435
- index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
436
- ).join("\n");
437
-}
438
-
439
-function buildUserTimelineEntry(text: string) {
440
- return {
441
- id: "entry-1",
442
- kind: "message" as const,
443
- createdAt: MESSAGE_CREATED_AT,
444
- message: {
445
- id: MessageId.make("message-1"),
446
- role: "user" as const,
447
- text,
448
- runId: null,
449
- createdAt: MESSAGE_CREATED_AT,
450
- updatedAt: MESSAGE_CREATED_AT,
451
- streaming: false,
452
- },
453
- };
454
-}
455
-
456
-function buildAssistantTimelineEntry(text: string) {
457
- const entry = buildUserTimelineEntry(text);
458
- return {
459
- ...entry,
460
- message: {
461
- ...entry.message,
462
- role: "assistant" as const,
463
- },
464
- };
465
-}
466
-
467
-function buildSnapShotTimelineEntry(previewUrl?: string) {
468
- const entry = buildUserTimelineEntry("First prompt.");
469
- return {
470
- ...entry,
471
- message: {
472
- ...entry.message,
473
- attachments: [
474
- {
475
- type: "image" as const,
476
- id: "attachment-1",
477
- name: "screenshot.png",
478
- mimeType: "image/png",
479
- sizeBytes: 1,
480
- ...(previewUrl ? { previewUrl } : {}),
481
- source: {
482
- kind: "snap-shot" as const,
483
- capturedAt: "2026-03-17T19:12:28.000Z",
484
- appName: "Terminal",
485
- windowTitle: "t3code — Tests",
486
- appIconDataUrl: "data:image/png;base64,aWNvbg==",
487
- },
488
- },
489
- ],
490
- },
491
- };
492
-}
493
-
494
-describe("MessagesTimeline", () => {
495
- it("shows dynamic tool input without cached output when the row is expanded", async () => {
496
- activityTestState.expanded = true;
497
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
498
- vi.stubGlobal("requestAnimationFrame", () => 0);
499
- vi.stubGlobal("cancelAnimationFrame", () => {});
500
- let renderer: ReactTestRenderer | undefined;
501
- try {
502
- await act(() => {
503
- renderer = create(
504
- <MessagesTimeline
505
- {...buildProps()}
506
- timelineEntries={[
507
- {
508
- id: "tool-with-cached-output",
509
- kind: "work",
510
- createdAt: MESSAGE_CREATED_AT,
511
- entry: {
512
- id: "tool-with-cached-output",
513
- createdAt: MESSAGE_CREATED_AT,
514
- label: "Example tool",
515
- toolTitle: "Example tool",
516
- tone: "tool",
517
- itemType: "dynamic_tool",
518
- toolLifecycleStatus: "completed",
519
- toolData: {
520
- input: { query: "KEEP_TOOL_INPUT" },
521
- output: { text: "RAW_CACHED_TOOL_OUTPUT" },
522
- },
523
- },
524
- },
525
- ]}
526
- />,
527
- );
528
- });
529
- const row = renderer!.root.findByProps({ "aria-label": "Example tool" });
530
- await act(() => row.props.onClick());
531
- const visible = JSON.stringify(renderer!.toJSON());
532
- expect(visible).toContain("KEEP_TOOL_INPUT");
533
- expect(visible).not.toContain("RAW_CACHED_TOOL_OUTPUT");
534
- await act(() => row.props.onClick());
535
- expect(JSON.stringify(renderer!.toJSON())).not.toContain("KEEP_TOOL_INPUT");
536
- } finally {
537
- await act(() => renderer?.unmount());
538
- }
539
- });
540
-
541
- it("leads an unanswered question row with the question text", async () => {
542
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
543
- vi.stubGlobal("requestAnimationFrame", () => 0);
544
- vi.stubGlobal("cancelAnimationFrame", () => {});
545
- let renderer: ReactTestRenderer | undefined;
546
- try {
547
- await act(() => {
548
- renderer = create(
549
- <MessagesTimeline
550
- {...buildProps()}
551
- timelineEntries={[
552
- {
553
- id: "question-entry",
554
- kind: "work",
555
- createdAt: MESSAGE_CREATED_AT,
556
- entry: {
557
- id: "question-work",
558
- createdAt: MESSAGE_CREATED_AT,
559
- label: "User input requested",
560
- tone: "tool",
561
- questionAnswer: {
562
- requestId: ApprovalRequestId.make("question-request"),
563
- answers: {},
564
- questionTextById: { scope: "Which repository?" },
565
- attachmentsByQuestionId: {},
566
- },
567
- },
568
- },
569
- ]}
570
- />,
571
- );
572
- });
573
- const questionToggle = renderer!.root.find(
574
- (node) =>
575
- node.props["aria-label"] === "Which repository?" && node.props["aria-expanded"] === false,
576
- );
577
- const markup = JSON.stringify(renderer!.toJSON());
578
- expect(markup.match(/Which repository\?/g)).toHaveLength(2);
579
- await act(() => questionToggle.props.onClick());
580
- expect(JSON.stringify(renderer!.toJSON()).match(/Which repository\?/g)).toHaveLength(3);
581
- } finally {
582
- await act(() => renderer?.unmount());
583
- }
584
- });
585
-
586
- it.each([
587
- { toolLifecycleStatus: "inProgress", isAtEnd: true },
588
- { toolLifecycleStatus: "inProgress", isAtEnd: false },
589
- { toolLifecycleStatus: "completed", isAtEnd: true },
590
- { toolLifecycleStatus: "completed", isAtEnd: false },
591
- ] as const)(
592
- "restores the composer after closing $toolLifecycleStatus tool output only at the end: $isAtEnd",
593
- async ({ toolLifecycleStatus, isAtEnd }) => {
594
- const frames = new Map<number, FrameRequestCallback>();
595
- let nextFrame = 0;
596
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
597
- frames.set(++nextFrame, callback);
598
- return nextFrame;
599
- });
600
- vi.stubGlobal("cancelAnimationFrame", (frame: number) => frames.delete(frame));
601
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
602
- const flushFrame = () =>
603
- act(() => {
604
- const callbacks = [...frames.values()];
605
- frames.clear();
606
- callbacks.forEach((callback) => callback(0));
607
- });
608
- const props = buildProps();
609
- const runId = RunId.make("tool-output-run");
610
- let timelineIsAtEnd = isAtEnd;
611
- props.listRef.current = {
612
- getState: () => ({ isAtEnd: timelineIsAtEnd }),
613
- getScrollableNode: () => null,
614
- } as unknown as LegendListRef;
615
- let isResting = false;
616
- let composerState: ReturnType<typeof useComposerFocusState> | undefined;
617
- function ThreadProbe() {
618
- const composer = useComposerFocusState();
619
- useLayoutEffect(() => {
620
- composerState = composer;
621
- isResting = shouldUseRestingComposerLayout({
622
- isExistingThread: true,
623
- isMobileViewport: false,
624
- isScrollCollapsed: composer.isComposerScrollCollapsed,
625
- hasExpandedChrome: false,
626
- hasMultilinePrompt: false,
627
- timelineOverflows: true,
628
- });
629
- });
630
- return (
631
- <MessagesTimeline
632
- {...props}
633
- isWorking={toolLifecycleStatus === "inProgress"}
634
- runningRunId={toolLifecycleStatus === "inProgress" ? runId : null}
635
- onToolOutputCollapsedAtEnd={composer.restoreAfterTimelineReachedEnd}
636
- timelineEntries={[
637
- {
638
- id: "running-tool",
639
- kind: "work",
640
- createdAt: MESSAGE_CREATED_AT,
641
- entry: {
642
- id: "running-tool",
643
- ...(toolLifecycleStatus === "inProgress" ? { runId } : {}),
644
- createdAt: MESSAGE_CREATED_AT,
645
- label: "Run command",
646
- tone: "tool",
647
- toolLifecycleStatus,
648
- detail: "Command output",
649
- },
650
- },
651
- ]}
652
- />
653
- );
654
- }
655
- let renderer: ReactTestRenderer | undefined;
656
- try {
657
- await act(() => {
658
- renderer = create(<ThreadProbe />);
659
- });
660
- await act(() => composerState!.setIsComposerScrollCollapsed(true));
661
- const toggle = renderer!.root.findByProps({ "aria-expanded": false });
662
- await act(() => toggle.props.onClick());
663
- await flushFrame();
664
- await flushFrame();
665
- expect(isResting).toBe(true);
666
-
667
- timelineIsAtEnd = false;
668
- await act(() => toggle.props.onClick());
669
- await flushFrame();
670
- timelineIsAtEnd = isAtEnd;
671
- await flushFrame();
672
- expect(isResting).toBe(!isAtEnd);
673
- } finally {
674
- await act(() => renderer?.unmount());
675
- }
676
- },
677
- );
678
-
679
- it.each([true, false])(
680
- "keeps the end in view when tool output toggles only at the end: %s",
681
- async (isAtEnd) => {
682
- const frames = new Map<number, FrameRequestCallback>();
683
- let nextFrame = 0;
684
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
685
- frames.set(++nextFrame, callback);
686
- return nextFrame;
687
- });
688
- vi.stubGlobal("cancelAnimationFrame", (frame: number) => frames.delete(frame));
689
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
690
- const flushFrame = () =>
691
- act(() => {
692
- const callbacks = [...frames.values()];
693
- frames.clear();
694
- callbacks.forEach((callback) => callback(0));
695
- });
696
- const viewport = { scrollTop: 400, scrollHeight: 1000 };
697
- const props = buildProps();
698
- props.listRef.current = {
699
- getState: () => ({ isAtEnd }),
700
- getScrollableNode: () => viewport,
701
- } as unknown as LegendListRef;
702
- let renderer: ReactTestRenderer | undefined;
703
- try {
704
- await act(() => {
705
- renderer = create(
706
- <MessagesTimeline
707
- {...props}
708
- timelineEntries={[
709
- {
710
- id: "tool",
711
- kind: "work",
712
- createdAt: MESSAGE_CREATED_AT,
713
- entry: {
714
- id: "tool",
715
- createdAt: MESSAGE_CREATED_AT,
716
- label: "Run command",
717
- tone: "tool",
718
- toolLifecycleStatus: "completed",
719
- detail: "Command output",
720
- },
721
- },
722
- ]}
723
- />,
724
- );
725
- });
726
- const toggle = renderer!.root.findByProps({ "aria-expanded": false });
727
- const list = renderer!.root.find(
728
- (node) => node.props.ListFooterComponent !== undefined && node.props.onItemSizeChanged,
729
- );
730
- for (const scrollHeight of [1300, 900]) {
731
- await act(() => toggle.props.onClick());
732
- viewport.scrollHeight = scrollHeight;
733
- await flushFrame();
734
- expect(viewport.scrollTop).toBe(isAtEnd ? scrollHeight : 400);
735
- viewport.scrollHeight = scrollHeight + 200;
736
- await act(() => list.props.onItemSizeChanged());
737
- expect(viewport.scrollTop).toBe(isAtEnd ? scrollHeight + 200 : 400);
738
- await flushFrame();
739
- await flushFrame();
740
- viewport.scrollTop = 400;
741
- }
742
- } finally {
743
- await act(() => renderer?.unmount());
744
- }
745
- },
746
- );
747
-
748
- function stubFollowTimeline(routeThreadKey: string) {
749
- const frames = new Map<number, FrameRequestCallback>();
750
- let nextFrame = 0;
751
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
752
- frames.set(++nextFrame, callback);
753
- return nextFrame;
754
- });
755
- vi.stubGlobal("cancelAnimationFrame", (frame: number) => frames.delete(frame));
756
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
757
- const props = { ...buildProps(), routeThreadKey };
758
- const timeline = {
759
- props,
760
- scrollTop: 1400,
761
- flushFrame: () =>
762
- act(() => {
763
- const callbacks = [...frames.values()];
764
- frames.clear();
765
- callbacks.forEach((callback) => callback(0));
766
- }),
767
- };
768
- const viewport = {
769
- get scrollTop() {
770
- return timeline.scrollTop;
771
- },
772
- getBoundingClientRect: () => ({ top: 0 }),
773
- };
774
- props.listRef.current = {
775
- getScrollableNode: () => viewport,
776
- getState: () => ({
777
- data: legendListTestState.data,
778
- scroll: timeline.scrollTop,
779
- scrollLength: 600,
780
- contentLength: 2000,
781
- indexByKey: () => 0,
782
- positionAtIndex: () => 0,
783
- sizeAtIndex: () => 2000,
784
- elementAtIndex: () => ({ getBoundingClientRect: () => ({ top: -timeline.scrollTop }) }),
785
- }),
786
- } as unknown as LegendListRef;
787
- return timeline;
788
- }
789
-
790
- it("remembers a manual reading position when the chat closes before the next frame", async () => {
791
- const { readTimelinePosition } = await import("./timelineScrollAnchoring");
792
- const timeline = stubFollowTimeline("environment-local:manual-departure");
793
- const { props } = timeline;
794
- function ChatProbe() {
795
- const [liveFollowEnabled, setLiveFollowEnabled] = useState(true);
796
- return (
797
- <MessagesTimeline
798
- {...props}
799
- timelineEntries={[buildUserTimelineEntry("First prompt")]}
800
- liveFollowEnabled={liveFollowEnabled}
801
- onManualNavigation={() => setLiveFollowEnabled(false)}
802
- />
803
- );
804
- }
805
- let renderer: ReactTestRenderer | undefined;
806
- try {
807
- await act(() => {
808
- renderer = create(<ChatProbe />);
809
- });
810
- await timeline.flushFrame();
811
- expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true);
812
-
813
- timeline.scrollTop = 1300;
814
- await act(() => {
815
- renderer?.root.findByType(MessagesTimeline).props.onManualNavigation?.();
816
- legendListTestState.onScroll?.();
817
- });
818
- await act(() => renderer?.unmount());
819
- renderer = undefined;
820
-
821
- expect(readTimelinePosition(props.routeThreadKey)).toMatchObject({
822
- atEnd: false,
823
- scrollOffset: 1300,
824
- });
825
- } finally {
826
- await act(() => renderer?.unmount());
827
- }
828
- });
829
-
830
- it("keeps a following thread's intent while its timeline is held for the next thread", async () => {
831
- const { readTimelinePosition } = await import("./timelineScrollAnchoring");
832
- const timeline = stubFollowTimeline("environment-local:held-departure");
833
- const { props } = timeline;
834
- timeline.scrollTop = 1300;
835
- const render = (held: boolean) => (
836
- <MessagesTimeline
837
- {...props}
838
- timelineEntries={[buildUserTimelineEntry("First prompt")]}
839
- liveFollowEnabled={!held}
840
- paintOnly={held}
841
- />
842
- );
843
- let renderer: ReactTestRenderer | undefined;
844
- try {
845
- await act(() => {
846
- renderer = create(render(false));
847
- });
848
- await timeline.flushFrame();
849
- expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true);
850
-
851
- await act(() => renderer?.update(render(true)));
852
- await timeline.flushFrame();
853
-
854
- expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true);
855
- } finally {
856
- await act(() => renderer?.unmount());
857
- }
858
- });
859
-
860
- it("remembers a first send held near the top as a reading position", async () => {
861
- const { readTimelinePosition } = await import("./timelineScrollAnchoring");
862
- const timeline = stubFollowTimeline("environment-local:anchored-first-send");
863
- const { props } = timeline;
864
- timeline.scrollTop = 1300;
865
- let renderer: ReactTestRenderer | undefined;
866
- try {
867
- await act(() => {
868
- renderer = create(
869
- <MessagesTimeline
870
- {...props}
871
- timelineEntries={[buildUserTimelineEntry("First prompt")]}
872
- anchorMessageId={MessageId.make("message-1")}
873
- liveFollowEnabled
874
- />,
875
- );
876
- });
877
- await timeline.flushFrame();
878
-
879
- expect(readTimelinePosition(props.routeThreadKey)).toMatchObject({
880
- atEnd: false,
881
- scrollOffset: 1300,
882
- });
883
- } finally {
884
- await act(() => renderer?.unmount());
885
- }
886
- });
887
-
888
- it("preserves arbitrary XML-like tags and comparisons in rendered user messages", async () => {
889
- const { MessagesTimeline } = await import("./MessagesTimeline");
890
- const markup = renderToStaticMarkup(
891
- <MessagesTimeline
892
- {...buildProps()}
893
- timelineEntries={[
894
- buildUserTimelineEntry(
895
- [
896
- 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
897
- 'Before <nested data-value="a&b">inside</nested> after',
898
- "</global-agent-instructions> in your context?",
899
- "Comparison: 2 < 3 and 5 > 4.",
900
- ].join("\n"),
901
- ),
902
- ]}
903
- />,
904
- );
905
-
906
- expect(markup).toContain("<global-agent-instructions scope="workspace">");
907
- expect(markup).toContain(
908
- "Before <nested data-value="a&b">inside</nested> after",
909
- );
910
- expect(markup).toContain("</global-agent-instructions> in your context?");
911
- expect(markup).toContain("Comparison: 2 < 3 and 5 > 4.");
912
- });
913
-
914
- it("preserves XML-like source inside user code spans and fences", async () => {
915
- const { MessagesTimeline } = await import("./MessagesTimeline");
916
- const markup = renderToStaticMarkup(
917
- <MessagesTimeline
918
- {...buildProps()}
919
- timelineEntries={[
920
- buildUserTimelineEntry(
921
- [
922
- 'Inline `<tag attr="x">`',
923
- "",
924
- "```xml",
925
- '<root><child enabled="true" /></root>',
926
- "```",
927
- ].join("\n"),
928
- ),
929
- ]}
930
- />,
931
- );
932
-
933
- expect(markup).toContain('<code data-inline-code=""><tag attr="x"></code>');
934
- expect(markup).toContain("<root><child enabled="true" /></root>");
935
- });
936
-
937
- it("does not render markdown title attributes in user messages", async () => {
938
- const { MessagesTimeline } = await import("./MessagesTimeline");
939
- const markup = renderToStaticMarkup(
940
- <MessagesTimeline
941
- {...buildProps()}
942
- timelineEntries={[
943
- buildUserTimelineEntry(
944
- '[link](https://example.com "link tip") ',
945
- ),
946
- ]}
947
- />,
948
- );
949
-
950
- expect(markup).toContain('href="https://example.com"');
951
- expect(markup).toContain('src="https://example.com/image.png"');
952
- expect(markup).not.toContain('title="link tip"');
953
- expect(markup).not.toContain('title="image tip"');
954
- });
955
-
956
- it("renders unsafe user HTML as inert source text", async () => {
957
- const { MessagesTimeline } = await import("./MessagesTimeline");
958
- const markup = renderToStaticMarkup(
959
- <MessagesTimeline
960
- {...buildProps()}
961
- timelineEntries={[
962
- buildUserTimelineEntry(
963
- '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">',
964
- ),
965
- ]}
966
- />,
967
- );
968
-
969
- expect(markup).toContain("<script>globalThis.__t3Xss = 1</script>");
970
- expect(markup).toContain(
971
- "<img src="x" onerror="globalThis.__t3Xss = 2">",
972
- );
973
- expect(markup).not.toMatch(/<script(?:\s|>)/i);
974
- expect(markup).not.toMatch(/<img(?:\s|>)/i);
975
- });
976
-
977
- it("continues to render sanitized raw HTML in assistant messages", async () => {
978
- const { MessagesTimeline } = await import("./MessagesTimeline");
979
- const markup = renderToStaticMarkup(
980
- <MessagesTimeline
981
- {...buildProps()}
982
- timelineEntries={[
983
- buildAssistantTimelineEntry("<details><summary>More</summary>Details</details>"),
984
- ]}
985
- />,
986
- );
987
-
988
- expect(markup).toContain('data-markdown-details=""');
989
- expect(markup).toContain("More");
990
- expect(markup).not.toContain("<details>");
991
- });
992
-
993
- it("sanitizes executable HTML while preserving supported assistant markup", async () => {
994
- const { MessagesTimeline } = await import("./MessagesTimeline");
995
- const markup = renderToStaticMarkup(
996
- <MessagesTimeline
997
- {...buildProps()}
998
- timelineEntries={[
999
- buildAssistantTimelineEntry(
1000
- [
1001
- '<details open onclick="globalThis.__t3Xss = 1">',
1002
- "<summary>Safe details</summary>",
1003
- "<script>globalThis.__t3Xss = 2</script>",
1004
- '<img src="x" onerror="globalThis.__t3Xss = 3">',
1005
- '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
1006
- "</details>",
1007
- ].join(""),
1008
- ),
1009
- ]}
1010
- />,
1011
- );
1012
-
1013
- expect(markup).toContain('data-markdown-details=""');
1014
- expect(markup).toContain("Safe details");
1015
- expect(markup).not.toMatch(/<script(?:\s|>)/i);
1016
- expect(markup).not.toContain("onclick=");
1017
- expect(markup).not.toContain("onerror=");
1018
- expect(markup).not.toContain("javascript:");
1019
- expect(markup).not.toContain("globalThis.__t3Xss");
1020
- });
1021
- it("renders progressive history controls ahead of the bounded timeline", () => {
1022
- const markup = renderToStaticMarkup(
1023
- <MessagesTimeline
1024
- {...buildProps()}
1025
- timelineEntries={[buildUserTimelineEntry("Recent activity")]}
1026
- historyControls={{
1027
- hasMoreHistory: true,
1028
- loading: false,
1029
- error: "Earlier activity could not be loaded.",
1030
- onLoadEarlier: () => {},
1031
- }}
1032
- />,
1033
- );
1034
-
1035
- expect(markup).toContain('aria-label="Load earlier turns"');
1036
- expect(markup).toContain("Load earlier turns");
1037
- expect(markup).toContain("Earlier activity could not be loaded.");
1038
- expect(markup.indexOf("Load earlier turns")).toBeLessThan(markup.indexOf("Recent activity"));
1039
- });
1040
-
1041
- it("keeps an empty bounded timeline actionable while earlier history loads", () => {
1042
- const markup = renderToStaticMarkup(
1043
- <MessagesTimeline
1044
- {...buildProps()}
1045
- timelineEntries={[]}
1046
- historyControls={{
1047
- hasMoreHistory: true,
1048
- loading: true,
1049
- error: null,
1050
- onLoadEarlier: () => {},
1051
- }}
1052
- />,
1053
- );
1054
-
1055
- expect(markup).toContain("Loading earlier turns…");
1056
- expect(markup).toContain("disabled");
1057
- expect(markup).not.toContain("Send a message to start the conversation.");
1058
- });
1059
-
1060
- it("uses the larger leading inset only when the top fade is enabled", () => {
1061
- const timelineEntries = [buildUserTimelineEntry("Hello")];
1062
-
1063
- const compactMarkup = renderToStaticMarkup(
1064
- <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} />,
1065
- );
1066
- const fadedMarkup = renderToStaticMarkup(
1067
- <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} topFadeEnabled />,
1068
- );
1069
-
1070
- expect(compactMarkup).toContain('class="h-3 sm:h-4"');
1071
- expect(compactMarkup).not.toContain("topbar-scroll-fade");
1072
- expect(fadedMarkup).toContain('class="h-[var(--workspace-titlebar-scroll-fade-height)]"');
1073
- expect(fadedMarkup).toContain("topbar-scroll-fade");
1074
- });
1075
-
1076
- it("keeps assistant changed-files headers sticky below the thread header", () => {
1077
- const assistantMessageId = MessageId.make("message-assistant-with-files");
1078
- const runId = RunId.make("run-with-files");
1079
- const markup = renderToStaticMarkup(
1080
- <MessagesTimeline
1081
- {...buildProps()}
1082
- latestRun={{
1083
- runId,
1084
- status: "completed",
1085
- startedAt: MESSAGE_CREATED_AT,
1086
- completedAt: MESSAGE_CREATED_AT,
1087
- }}
1088
- timelineEntries={[
1089
- {
1090
- id: "entry-assistant-with-files",
1091
- kind: "message",
1092
- createdAt: MESSAGE_CREATED_AT,
1093
- message: {
1094
- id: assistantMessageId,
1095
- role: "assistant",
1096
- text: "Updated the fixture.",
1097
- runId,
1098
- createdAt: MESSAGE_CREATED_AT,
1099
- updatedAt: MESSAGE_CREATED_AT,
1100
- streaming: false,
1101
- },
1102
- },
1103
- ]}
1104
- turnDiffSummaries={[
1105
- {
1106
- runId,
1107
- checkpointTurnCount: 1,
1108
- checkpointRef: CheckpointRef.make("checkpoint-with-files"),
1109
- status: "ready",
1110
- files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
1111
- assistantMessageId,
1112
- completedAt: MESSAGE_CREATED_AT,
1113
- },
1114
- ]}
1115
- />,
1116
- );
1117
-
1118
- expect(markup).toContain("sticky top-2 z-10");
1119
- expect(markup).not.toContain("self-start");
1120
- expect(markup).toContain("whitespace-nowrap");
1121
- expect(markup).toContain("size-3");
1122
- expect(markup).not.toContain('aria-label="Collapse all folders"');
1123
- expect(markup).toContain('aria-label="Open diff"');
1124
- expect(markup).toContain("1 changed file");
1125
- });
1126
-
1127
- it("treats the follow re-arm band above the content bottom as the live edge", async () => {
1128
- const {
1129
- resolveTimelineIsAtEnd,
1130
- resolveTimelineMinimapHasPersistentGutter,
1131
- resolveTimelineMinimapHeightStyle,
1132
- resolveTimelineMinimapHitStripWidth,
1133
- resolveTimelineMinimapIndexFromPointer,
1134
- resolveTimelineMinimapInteractiveWidth,
1135
- resolveTimelineMinimapNavigationInteractive,
1136
- resolveTimelineMinimapTopPercent,
1137
- } = await import("./MessagesTimeline.logic");
1138
-
1139
- expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
1140
- expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();
1141
- expect(
1142
- resolveTimelineIsAtEnd({
1143
- isAtEnd: false,
1144
- contentLength: 2000,
1145
- scroll: 1170,
1146
- scrollLength: 800,
1147
- }),
1148
- ).toBe(true);
1149
- expect(
1150
- resolveTimelineIsAtEnd({
1151
- isAtEnd: false,
1152
- contentLength: 2000,
1153
- scroll: 900,
1154
- scrollLength: 800,
1155
- }),
1156
- ).toBe(false);
1157
- expect(
1158
- resolveTimelineIsAtEnd({
1159
- isAtEnd: true,
1160
- contentLength: 2100,
1161
- scroll: 1170,
1162
- scrollLength: 800,
1163
- }),
1164
- ).toBe(false);
1165
- expect(resolveTimelineIsAtEnd({ isNearEnd: true, isAtEnd: false })).toBe(false);
1166
- expect(resolveTimelineIsAtEnd({ isAtEnd: false })).toBe(false);
1167
-
1168
- expect(resolveTimelineMinimapHeightStyle(5)).toBe("min(32px, calc(100vh - 18rem))");
1169
- expect(resolveTimelineMinimapTopPercent(2, 5)).toBe(50);
1170
- expect(
1171
- resolveTimelineMinimapIndexFromPointer({
1172
- itemCount: 101,
1173
- railTop: 100,
1174
- railHeight: 500,
1175
- pointerY: 350,
1176
- }),
1177
- ).toBe(50);
1178
- expect(
1179
- resolveTimelineMinimapIndexFromPointer({
1180
- itemCount: 101,
1181
- railTop: 100,
1182
- railHeight: 500,
1183
- pointerY: 999,
1184
- }),
1185
- ).toBe(100);
1186
- expect(resolveTimelineMinimapHasPersistentGutter(832, 768)).toBe(false);
1187
- expect(resolveTimelineMinimapHasPersistentGutter(863, 768)).toBe(false);
1188
- expect(resolveTimelineMinimapHasPersistentGutter(864, 768)).toBe(true);
1189
- expect(resolveTimelineMinimapHasPersistentGutter(1400, 1152)).toBe(true);
1190
- expect(resolveTimelineMinimapHasPersistentGutter(1200, 1152)).toBe(false);
1191
- expect(resolveTimelineMinimapHasPersistentGutter(2560, 2560)).toBe(false);
1192
-
1193
- expect(resolveTimelineMinimapHitStripWidth(768, 768)).toBe(0);
1194
- expect(resolveTimelineMinimapHitStripWidth(792, 768)).toBe(0);
1195
- expect(resolveTimelineMinimapHitStripWidth(820, 768)).toBe(14);
1196
- expect(resolveTimelineMinimapHitStripWidth(872, 768)).toBe(40);
1197
- expect(resolveTimelineMinimapHitStripWidth(1400, 768)).toBe(40);
1198
- expect(resolveTimelineMinimapHitStripWidth(2560, 2560)).toBe(0);
1199
- expect(resolveTimelineMinimapHitStripWidth(1204, 1152)).toBe(14);
1200
- expect(resolveTimelineMinimapHitStripWidth(0, 0)).toBe(0);
1201
- expect(resolveTimelineMinimapHitStripWidth(Number.NaN, 768)).toBe(0);
1202
-
1203
- expect(resolveTimelineMinimapNavigationInteractive(40)).toBe(true);
1204
- expect(resolveTimelineMinimapNavigationInteractive(14)).toBe(true);
1205
- expect(resolveTimelineMinimapNavigationInteractive(8)).toBe(false);
1206
- expect(resolveTimelineMinimapNavigationInteractive(0)).toBe(false);
1207
-
1208
- expect(resolveTimelineMinimapInteractiveWidth(0, false)).toBe(0);
1209
- expect(resolveTimelineMinimapInteractiveWidth(14, false)).toBe(14);
1210
- expect(resolveTimelineMinimapInteractiveWidth(40, false)).toBe(40);
1211
- expect(resolveTimelineMinimapInteractiveWidth(0, true)).toBe("22rem");
1212
- expect(resolveTimelineMinimapInteractiveWidth(14, true)).toBe("22rem");
1213
- expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");
1214
- });
1215
-
1216
- it("anchors a sent attachment message using its measured height", () => {
1217
- const onAnchorReady = vi.fn();
1218
- const onAnchorSizeChanged = vi.fn();
1219
- const firstEntry = buildAssistantTimelineEntry("Earlier reply.");
1220
- const secondEntry = {
1221
- ...buildUserTimelineEntry("Newest prompt."),
1222
- id: "entry-2",
1223
- message: {
1224
- ...buildUserTimelineEntry("Newest prompt.").message,
1225
- id: MessageId.make("message-2"),
1226
- attachments: [
1227
- {
1228
- type: "image" as const,
1229
- id: "attachment-1",
1230
- name: "screenshot.png",
1231
- mimeType: "image/png",
1232
- sizeBytes: 1,
1233
- previewUrl: "data:image/png;base64,iVBORw0KGgo=",
1234
- },
1235
- ],
1236
- },
1237
- };
1238
- const markup = renderToStaticMarkup(
1239
- <MessagesTimeline
1240
- {...buildProps()}
1241
- anchorMessageId={secondEntry.message.id}
1242
- onAnchorReady={onAnchorReady}
1243
- onAnchorSizeChanged={onAnchorSizeChanged}
1244
- contentInsetEndAdjustment={144}
1245
- timelineEntries={[firstEntry, secondEntry]}
1246
- />,
1247
- );
1248
-
1249
- expect(markup).toContain('data-anchor-index="1"');
1250
- expect(markup).toContain('data-anchor-offset="24"');
1251
- expect(markup).toContain('data-anchor-on-ready="true"');
1252
- expect(markup).not.toContain("data-anchor-max-size=");
1253
- expect(markup).toContain('data-content-inset-end="144"');
1254
- expect(markup).toContain("[overflow-anchor:none]");
1255
- expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
1256
- expect(markup).toContain('data-maintain-visible-content-position="object"');
1257
- expect(markup).toContain('data-maintain-visible-content-position-data="true"');
1258
- expect(markup).toContain('data-maintain-visible-content-position-size="true"');
1259
- expect(markup).toContain('data-maintain-visible-content-position-restore="true"');
1260
- expect(onAnchorReady).toHaveBeenCalledOnce();
1261
- expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
1262
- expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
1263
- });
1264
-
1265
- it("renders SnapShot window details after the preview resolves", () => {
1266
- const onAnchorReady = vi.fn();
1267
- const firstEntry = buildSnapShotTimelineEntry("data:image/png;base64,iVBORw0KGgo=");
1268
- const markup = renderToStaticMarkup(
1269
- <MessagesTimeline
1270
- {...buildProps()}
1271
- anchorMessageId={firstEntry.message.id}
1272
- onAnchorReady={onAnchorReady}
1273
- contentInsetEndAdjustment={144}
1274
- timelineEntries={[firstEntry]}
1275
- />,
1276
- );
1277
-
1278
- expect(markup).toContain("Terminal");
1279
- expect(markup).toContain("t3code — Tests");
1280
- expect(markup).toContain('src="data:image/png;base64,aWNvbg=="');
1281
- expect(onAnchorReady).toHaveBeenCalledOnce();
1282
- expect(onAnchorReady).toHaveBeenCalledWith(firstEntry.message.id, 0);
1283
- });
1284
-
1285
- it("does not render SnapShot window details before the preview resolves", () => {
1286
- const markup = renderToStaticMarkup(
1287
- <MessagesTimeline {...buildProps()} timelineEntries={[buildSnapShotTimelineEntry()]} />,
1288
- );
1289
-
1290
- expect(markup).toContain("screenshot.png");
1291
- expect(markup).not.toContain("Terminal");
1292
- expect(markup).not.toContain("t3code — Tests");
1293
- expect(markup).not.toContain('src="data:image/png;base64,aWNvbg=="');
1294
- expect(markup).not.toContain("h-28 w-52 max-w-full");
1295
- });
1296
-
1297
- it("does not reserve end space for a follow-up user message", () => {
1298
- const onAnchorReady = vi.fn();
1299
- const firstEntry = buildUserTimelineEntry("First prompt.");
1300
- const secondEntry = {
1301
- ...buildUserTimelineEntry("Newest prompt."),
1302
- id: "entry-2",
1303
- message: {
1304
- ...buildUserTimelineEntry("Newest prompt.").message,
1305
- id: MessageId.make("message-2"),
1306
- },
1307
- };
1308
- const markup = renderToStaticMarkup(
1309
- <MessagesTimeline
1310
- {...buildProps()}
1311
- anchorMessageId={secondEntry.message.id}
1312
- onAnchorReady={onAnchorReady}
1313
- timelineEntries={[firstEntry, secondEntry]}
1314
- />,
1315
- );
1316
-
1317
- expect(markup).not.toContain("data-anchor-index=");
1318
- expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
1319
- expect(onAnchorReady).not.toHaveBeenCalled();
1320
- });
1321
-
1322
- it("offers preview and download actions for PDF attachments", () => {
1323
- const entry = {
1324
- ...buildUserTimelineEntry("Read the report."),
1325
- message: {
1326
- ...buildUserTimelineEntry("Read the report.").message,
1327
- attachments: [
1328
- {
1329
- type: "file" as const,
1330
- id: "attachment-report-pdf",
1331
- name: "report.pdf",
1332
- mimeType: "application/pdf",
1333
- sizeBytes: 42,
1334
- previewUrl: "https://environment.test/api/assets/report.pdf",
1335
- },
1336
- ],
1337
- },
1338
- };
1339
-
1340
- const markup = renderToStaticMarkup(
1341
- <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
1342
- );
1343
-
1344
- expect(markup).toContain('aria-label="Preview report.pdf"');
1345
- expect(markup).toContain('aria-label="Download report.pdf"');
1346
- expect(markup).not.toContain('alt="report.pdf"');
1347
- });
1348
-
1349
- it("renders a file download button without creating its URL in advance", () => {
1350
- const entry = {
1351
- ...buildUserTimelineEntry("Read the report."),
1352
- message: {
1353
- ...buildUserTimelineEntry("Read the report.").message,
1354
- attachments: [
1355
- {
1356
- type: "file" as const,
1357
- id: "attachment-report-pdf",
1358
- name: "report.pdf",
1359
- mimeType: "application/pdf",
1360
- sizeBytes: 42,
1361
- },
1362
- ],
1363
- },
1364
- };
1365
-
1366
- const markup = renderToStaticMarkup(
1367
- <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
1368
- );
1369
-
1370
- expect(markup).toContain('aria-label="Preview report.pdf"');
1371
- expect(markup).toContain('aria-label="Download report.pdf"');
1372
- expect(markup).not.toContain("<a ");
1373
- });
1374
-
1375
- it("does not download an optimistic file before the server supplies its attachment ID", () => {
1376
- const entry = {
1377
- ...buildUserTimelineEntry("Read the report."),
1378
- message: {
1379
- ...buildUserTimelineEntry("Read the report.").message,
1380
- attachments: [
1381
- {
1382
- type: "file" as const,
1383
- id: "composer-local-report",
1384
- name: "report.pdf",
1385
- mimeType: "application/pdf",
1386
- sizeBytes: 42,
1387
- downloadable: false,
1388
- },
1389
- ],
1390
- },
1391
- };
1392
-
1393
- const markup = renderToStaticMarkup(
1394
- <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
1395
- );
1396
-
1397
- expect(markup).toContain("report.pdf");
1398
- expect(markup).not.toContain('aria-label="Download report.pdf"');
1399
- });
1400
-
1401
- it("renders unknown attachment types as inert rows instead of crashing", () => {
1402
- const entry = {
1403
- ...buildUserTimelineEntry("Play the recording."),
1404
- message: {
1405
- ...buildUserTimelineEntry("Play the recording.").message,
1406
- attachments: [
1407
- {
1408
- type: "recording",
1409
- id: "attachment-voice-memo",
1410
- name: "voice-memo.ogg",
1411
- mimeType: "audio/ogg",
1412
- sizeBytes: 42,
1413
- },
1414
- ],
1415
- },
1416
- };
1417
-
1418
- const markup = renderToStaticMarkup(
1419
- <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
1420
- );
1421
-
1422
- expect(markup).toContain("voice-memo.ogg");
1423
- expect(markup).not.toContain('aria-label="Download voice-memo.ogg"');
1424
- expect(markup).not.toContain('alt="voice-memo.ogg"');
1425
- expect(markup).not.toContain("<a ");
1426
- });
1427
-
1428
- it("keeps reserved end space when tool work starts while reading history", () => {
1429
- const runId = RunId.make("run-with-active-tool");
1430
- const firstEntry = buildUserTimelineEntry("Run the command.");
1431
- const markup = renderToStaticMarkup(
1432
- <MessagesTimeline
1433
- {...buildProps()}
1434
- isWorking
1435
- activeTurnInProgress
1436
- latestRun={{
1437
- runId,
1438
- status: "running",
1439
- startedAt: MESSAGE_CREATED_AT,
1440
- completedAt: null,
1441
- }}
1442
- anchorMessageId={firstEntry.message.id}
1443
- liveFollowEnabled={false}
1444
- timelineEntries={[
1445
- firstEntry,
1446
- {
1447
- id: "entry-active-tool",
1448
- kind: "work",
1449
- createdAt: MESSAGE_CREATED_AT,
1450
- entry: {
1451
- id: "work-active-tool",
1452
- createdAt: MESSAGE_CREATED_AT,
1453
- runId,
1454
- label: "Run command",
1455
- tone: "tool",
1456
- itemType: "command_execution",
1457
- command: "git status",
1458
- toolLifecycleStatus: "inProgress",
1459
- },
1460
- },
1461
- ]}
1462
- />,
1463
- );
1464
-
1465
- expect(markup).toContain('data-anchor-index="0"');
1466
- expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
1467
- });
1468
-
1469
- it("hands end-following back to the list once the send anchor is released", () => {
1470
- const firstEntry = buildUserTimelineEntry("First prompt.");
1471
- const secondEntry = {
1472
- ...buildUserTimelineEntry("Newest prompt."),
1473
- id: "entry-2",
1474
- message: {
1475
- ...buildUserTimelineEntry("Newest prompt.").message,
1476
- id: MessageId.make("message-2"),
1477
- },
1478
- };
1479
- const timelineEntries = [firstEntry, secondEntry];
1480
-
1481
- expect(
1482
- renderToStaticMarkup(
1483
- <MessagesTimeline
1484
- {...buildProps()}
1485
- anchorMessageId={firstEntry.message.id}
1486
- timelineEntries={timelineEntries}
1487
- />,
1488
- ),
1489
- ).not.toContain('data-maintain-scroll-at-end="enabled"');
1490
-
1491
- expect(
1492
- renderToStaticMarkup(
1493
- <MessagesTimeline
1494
- {...buildProps()}
1495
- anchorMessageId={null}
1496
- timelineEntries={timelineEntries}
1497
- />,
1498
- ),
1499
- ).toContain('data-maintain-scroll-at-end="enabled"');
1500
-
1501
- expect(
1502
- renderToStaticMarkup(
1503
- <MessagesTimeline
1504
- {...buildProps()}
1505
- anchorMessageId={null}
1506
- liveFollowEnabled={false}
1507
- timelineEntries={timelineEntries}
1508
- />,
1509
- ),
1510
- ).not.toContain('data-maintain-scroll-at-end="enabled"');
1511
- });
1512
-
1513
- it("renders collapse controls for long user messages", () => {
1514
- const markup = renderToStaticMarkup(
1515
- <MessagesTimeline
1516
- {...buildProps()}
1517
- timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
1518
- />,
1519
- );
1520
-
1521
- expect(markup).toContain("Show full message");
1522
- expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
1523
- expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
1524
- expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
1525
- expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
1526
- expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
1527
- expect(markup).toContain('data-user-message-collapsed="true"');
1528
- expect(markup).toContain('data-user-message-fade="true"');
1529
- expect(markup).toContain('data-user-message-footer="true"');
1530
- });
1531
-
1532
- it("does not render collapse controls for short user messages", () => {
1533
- const markup = renderToStaticMarkup(
1534
- <MessagesTimeline
1535
- {...buildProps()}
1536
- timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
1537
- />,
1538
- );
1539
-
1540
- expect(markup).not.toContain("Show full message");
1541
- expect(markup).toContain('data-user-message-collapsible="false"');
1542
- expect(markup).toContain("rounded-2xl bg-message p-3");
1543
- });
1544
-
1545
- it("identifies user-role messages sent by another agent", async () => {
1546
- const { MessagesTimeline } = await import("./MessagesTimeline");
1547
- const entry = buildUserTimelineEntry("Review this area");
1548
- const agentMarkup = renderToStaticMarkup(
1549
- <MessagesTimeline
1550
- {...buildProps()}
1551
- timelineEntries={[
1552
- {
1553
- ...entry,
1554
- message: { ...entry.message, createdBy: "agent", creationSource: "provider" },
1555
- },
1556
- ]}
1557
- />,
1558
- );
1559
- const userMarkup = renderToStaticMarkup(
1560
- <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
1561
- );
1562
-
1563
- expect(agentMarkup).toContain('data-user-message-attribution="agent"');
1564
- expect(agentMarkup).toContain("Sent by another agent");
1565
- expect(userMarkup).not.toContain("Sent by another agent");
1566
- });
1567
-
1568
- it("keeps a subagent parent-thread link at the top of an empty timeline", async () => {
1569
- const { MessagesTimeline } = await import("./MessagesTimeline");
1570
- const markup = renderToStaticMarkup(
1571
- <MessagesTimeline
1572
- {...buildProps()}
1573
- timelineEntries={[]}
1574
- parentThreadLink={{
1575
- threadId: ThreadId.make("thread-parent"),
1576
- title: "Architecture audit",
1577
- }}
1578
- />,
1579
- );
1580
-
1581
- expect(markup).toContain('aria-label="Open parent thread"');
1582
- expect(markup).toContain("Subagent of");
1583
- expect(markup).toContain("Architecture audit");
1584
- expect(markup).not.toContain("Send a message to start the conversation");
1585
- });
1586
-
1587
- it("keeps steer intent visible on committed user messages", async () => {
1588
- const { MessagesTimeline } = await import("./MessagesTimeline");
1589
- const entry = buildUserTimelineEntry("Adjust the current turn");
1590
- const markup = renderToStaticMarkup(
1591
- <MessagesTimeline
1592
- {...buildProps()}
1593
- timelineEntries={[
1594
- { ...entry, message: { ...entry.message, inputIntent: "steer" as const } },
1595
- ]}
1596
- />,
1597
- );
1598
-
1599
- expect(markup).toContain("data-base-ui-tooltip-trigger");
1600
- expect(markup).toContain("lucide-redo-2");
1601
- expect(markup).toContain('data-user-message-intent="steer"');
1602
- expect(markup).toContain("items-center justify-end gap-1");
1603
- expect(markup).toContain("gap-1 text-xs leading-none text-muted-foreground");
1604
- expect(markup.indexOf("Steer")).toBeLessThan(markup.indexOf("Adjust the current turn"));
1605
- });
1606
-
1607
- it("keeps compact spacing below a collapsed turn divider", () => {
1608
- const runId = RunId.make("run-collapsed-spacing");
1609
- const markup = renderToStaticMarkup(
1610
- <MessagesTimeline
1611
- {...buildProps()}
1612
- timelineEntries={[
1613
- buildUserTimelineEntry("Investigate spacing"),
1614
- {
1615
- id: "assistant-commentary-spacing",
1616
- kind: "message",
1617
- createdAt: "2026-03-17T19:12:30.000Z",
1618
- message: {
1619
- id: MessageId.make("assistant-commentary-spacing"),
1620
- role: "assistant",
1621
- text: "Checking the layout.",
1622
- runId,
1623
- createdAt: "2026-03-17T19:12:30.000Z",
1624
- updatedAt: "2026-03-17T19:12:31.000Z",
1625
- streaming: false,
1626
- },
1627
- },
1628
- {
1629
- id: "assistant-final-spacing",
1630
- kind: "message",
1631
- createdAt: "2026-03-17T19:12:32.000Z",
1632
- message: {
1633
- id: MessageId.make("assistant-final-spacing"),
1634
- role: "assistant",
1635
- text: "Spacing fixed.",
1636
- runId,
1637
- createdAt: "2026-03-17T19:12:32.000Z",
1638
- updatedAt: "2026-03-17T19:12:33.000Z",
1639
- streaming: false,
1640
- },
1641
- },
1642
- ]}
1643
- />,
1644
- );
1645
-
1646
- expect(markup).toContain('class="pb-1.5" data-timeline-row-id="turn-fold:');
1647
- expect(markup).toContain('data-timeline-row-kind="turn-fold"');
1648
- });
1649
-
1650
- it("shows a collapsed disclosure for superseded attempt output", async () => {
1651
- const { MessagesTimeline } = await import("./MessagesTimeline");
1652
- const runId = RunId.make("run-steered");
1653
- const supersededAttempt = {
1654
- id: "attempt-1" as never,
1655
- runId,
1656
- attemptOrdinal: 1,
1657
- rootNodeId: "node-attempt-1" as never,
1658
- status: "superseded" as const,
1659
- completedAt: null,
1660
- };
1661
- const activeAttempt = {
1662
- id: "attempt-2" as never,
1663
- runId,
1664
- attemptOrdinal: 2,
1665
- rootNodeId: "node-attempt-2" as never,
1666
- status: "running" as const,
1667
- completedAt: null,
1668
- };
1669
- const markup = renderToStaticMarkup(
1670
- <MessagesTimeline
1671
- {...buildProps()}
1672
- latestRun={{
1673
- runId,
1674
- status: "running",
1675
- startedAt: MESSAGE_CREATED_AT,
1676
- completedAt: null,
1677
- }}
1678
- timelineEntries={[
1679
- {
1680
- id: "superseded-response-entry",
1681
- kind: "message",
1682
- createdAt: MESSAGE_CREATED_AT,
1683
- attempt: supersededAttempt,
1684
- message: {
1685
- id: MessageId.make("superseded-response"),
1686
- role: "assistant",
1687
- text: "Partial response from the old attempt",
1688
- runId,
1689
- createdAt: MESSAGE_CREATED_AT,
1690
- updatedAt: MESSAGE_CREATED_AT,
1691
- streaming: false,
1692
- },
1693
- },
1694
- {
1695
- id: "active-response-entry",
1696
- kind: "message",
1697
- createdAt: "2026-03-17T19:12:29.000Z",
1698
- attempt: activeAttempt,
1699
- message: {
1700
- id: MessageId.make("active-response"),
1701
- role: "assistant",
1702
- text: "Current response remains visible",
1703
- runId,
1704
- createdAt: "2026-03-17T19:12:29.000Z",
1705
- updatedAt: "2026-03-17T19:12:29.000Z",
1706
- streaming: true,
1707
- },
1708
- },
1709
- ]}
1710
- />,
1711
- );
1712
-
1713
- expect(markup).toContain('data-superseded-attempt-id="attempt-1"');
1714
- expect(markup).toContain('aria-expanded="false"');
1715
- expect(markup).toContain("Superseded attempt");
1716
- expect(markup).toContain("Cut off by a steer");
1717
- expect(markup).toContain("Current response remains visible");
1718
- expect(markup).not.toContain("Partial response from the old attempt");
1719
- });
1720
-
1721
- it("exposes a per-response fork action for completed assistant items", async () => {
1722
- const { MessagesTimeline } = await import("./MessagesTimeline");
1723
- const projectedItem = {
1724
- position: 0,
1725
- visibility: "local",
1726
- sourceThreadId: "thread-1",
1727
- sourceItemId: "assistant-item-1",
1728
- item: {
1729
- id: "assistant-item-1",
1730
- threadId: "thread-1",
1731
- runId: "run-1",
1732
- nodeId: null,
1733
- providerThreadId: null,
1734
- providerTurnId: null,
1735
- nativeItemRef: null,
1736
- parentItemId: null,
1737
- ordinal: 0,
1738
- status: "completed",
1739
- title: null,
1740
- startedAt: null,
1741
- completedAt: null,
1742
- updatedAt: {},
1743
- type: "assistant_message",
1744
- messageId: "assistant-message-1",
1745
- text: "Done",
1746
- streaming: false,
1747
- },
1748
- } as never;
1749
- const markup = renderToStaticMarkup(
1750
- <MessagesTimeline
1751
- {...buildProps()}
1752
- timelineEntries={[
1753
- {
1754
- id: "assistant-message-1",
1755
- kind: "message",
1756
- createdAt: MESSAGE_CREATED_AT,
1757
- projectedItem,
1758
- message: {
1759
- id: MessageId.make("assistant-message-1"),
1760
- role: "assistant",
1761
- text: "Done",
1762
- runId: RunId.make("run-1"),
1763
- createdAt: MESSAGE_CREATED_AT,
1764
- updatedAt: MESSAGE_CREATED_AT,
1765
- streaming: false,
1766
- },
1767
- },
1768
- ]}
1769
- />,
1770
- );
1771
-
1772
- expect(markup).toContain('aria-label="Fork from this response"');
1773
- });
1774
-
1775
- it("renders inline terminal labels with the composer chip UI", async () => {
1776
- const { MessagesTimeline } = await import("./MessagesTimeline");
1777
- const markup = renderToStaticMarkup(
1778
- <MessagesTimeline
1779
- {...buildProps()}
1780
- timelineEntries={[
1781
- buildUserTimelineEntry(
1782
- [
1783
- buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
1784
- "",
1785
- "<terminal_context>",
1786
- "- Terminal 1 lines 1-5:",
1787
- " 1 | julius@mac effect-http-ws-cli % bun i",
1788
- " 2 | bun install v1.3.9 (cf6cdbbb)",
1789
- "</terminal_context>",
1790
- ].join("\n"),
1791
- ),
1792
- ]}
1793
- />,
1794
- );
1795
-
1796
- expect(markup).toContain("Terminal 1 lines 1-5");
1797
- expect(markup).toContain("lucide-terminal");
1798
- expect(markup).toContain("yoo what's");
1799
- expect(markup).not.toContain("terminal_context");
1800
- expect(markup).toContain("Show full message");
1801
- }, 20_000);
1802
-
1803
- it("renders chips for standalone element-pick context messages", () => {
1804
- const markup = renderToStaticMarkup(
1805
- <MessagesTimeline
1806
- {...buildProps()}
1807
- timelineEntries={[
1808
- buildUserTimelineEntry(
1809
- [
1810
- "<element_context>",
1811
- "- <SubmitButton> (Button.tsx:12):",
1812
- " url: https://example.com/dashboard",
1813
- " selector: button.submit",
1814
- " source: /repo/src/Button.tsx:12:5",
1815
- " html:",
1816
- ' <button class="submit">Save</button>',
1817
- "</element_context>",
1818
- ].join("\n"),
1819
- ),
1820
- ]}
1821
- />,
1822
- );
1823
-
1824
- expect(markup).toContain("SubmitButton");
1825
- expect(markup).not.toContain("<element_context");
1826
- expect(markup).not.toContain("<element_context");
1827
- });
1828
-
1829
- it("keeps the copy button for collapsed long user messages", () => {
1830
- const markup = renderToStaticMarkup(
1831
- <MessagesTimeline
1832
- {...buildProps()}
1833
- timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
1834
- />,
1835
- );
1836
-
1837
- expect(markup).toContain('aria-label="Copy message"');
1838
- expect(markup).toContain('data-user-message-collapsed="true"');
1839
- expect(markup).toContain('data-user-message-footer="true"');
1840
- });
1841
-
1842
- it("renders context compaction entries in the normal work log", () => {
1843
- const markup = renderToStaticMarkup(
1844
- <MessagesTimeline
1845
- {...buildProps()}
1846
- timelineEntries={[
1847
- {
1848
- id: "entry-1",
1849
- kind: "work",
1850
- createdAt: "2026-03-17T19:12:28.000Z",
1851
- entry: {
1852
- id: "work-1",
1853
- createdAt: "2026-03-17T19:12:28.000Z",
1854
- label: "Context compacted",
1855
- tone: "info",
1856
- },
1857
- },
1858
- ]}
1859
- />,
1860
- );
1861
-
1862
- expect(markup).toContain("Context compacted");
1863
- });
1864
-
1865
- it("does not render the transient V2 interruption request", async () => {
1866
- const { MessagesTimeline } = await import("./MessagesTimeline");
1867
- const markup = renderToStaticMarkup(
1868
- <MessagesTimeline
1869
- {...buildProps()}
1870
- timelineEntries={[
1871
- {
1872
- id: "interrupt-request",
1873
- kind: "event",
1874
- createdAt: MESSAGE_CREATED_AT,
1875
- projectedItem: {
1876
- position: 0,
1877
- visibility: "local",
1878
- sourceThreadId: "thread-1",
1879
- sourceItemId: "interrupt-request",
1880
- item: {
1881
- id: "interrupt-request",
1882
- threadId: "thread-1",
1883
- runId: "run-1",
1884
- nodeId: null,
1885
- providerThreadId: null,
1886
- providerTurnId: null,
1887
- nativeItemRef: null,
1888
- parentItemId: null,
1889
- ordinal: 0,
1890
- status: "completed",
1891
- title: null,
1892
- startedAt: null,
1893
- completedAt: null,
1894
- updatedAt: {},
1895
- type: "run_interrupt_request",
1896
- message: "Waiting for the provider to stop.",
1897
- },
1898
- } as never,
1899
- },
1900
- ]}
1901
- />,
1902
- );
1903
-
1904
- expect(markup).not.toContain('data-v2-item-type="run_interrupt_request"');
1905
- expect(markup).not.toContain("Interrupt requested");
1906
- expect(markup).not.toContain("Waiting for the provider to stop.");
1907
- expect(markup).not.toContain("Structured details");
1908
- });
1909
-
1910
- it("renders context handoffs as from → to model endpoints instead of the summary", async () => {
1911
- const { MessagesTimeline } = await import("./MessagesTimeline");
1912
- const providerStatuses = [
1913
- {
1914
- instanceId: "codex_personal",
1915
- driver: "codex",
1916
- enabled: true,
1917
- installed: true,
1918
- version: null,
1919
- status: "ready",
1920
- auth: {},
1921
- checkedAt: MESSAGE_CREATED_AT,
1922
- models: [{ slug: "gpt-5.6-sol", name: "GPT 5.6 Sol", isCustom: false, capabilities: null }],
1923
- slashCommands: [],
1924
- skills: [],
1925
- },
1926
- {
1927
- instanceId: "claudeAgent",
1928
- driver: "claudeAgent",
1929
- enabled: true,
1930
- installed: true,
1931
- version: null,
1932
- status: "ready",
1933
- auth: {},
1934
- checkedAt: MESSAGE_CREATED_AT,
1935
- models: [
1936
- { slug: "claude-fable-5", name: "Claude Fable 5", isCustom: false, capabilities: null },
1937
- ],
1938
- slashCommands: [],
1939
- skills: [],
1940
- },
1941
- ] as never;
1942
- const buildHandoffEntry = (item: Record<string, unknown>) => ({
1943
- id: "handoff-1",
1944
- kind: "event" as const,
1945
- createdAt: MESSAGE_CREATED_AT,
1946
- projectedItem: {
1947
- position: 0,
1948
- visibility: "local",
1949
- sourceThreadId: "thread-1",
1950
- sourceItemId: "handoff-1",
1951
- item: {
1952
- id: "handoff-1",
1953
- threadId: "thread-1",
1954
- runId: "run-2",
1955
- nodeId: null,
1956
- providerThreadId: null,
1957
- providerTurnId: null,
1958
- nativeItemRef: null,
1959
- parentItemId: null,
1960
- ordinal: 0,
1961
- status: "completed",
1962
- title: "Provider handoff",
1963
- startedAt: null,
1964
- completedAt: null,
1965
- updatedAt: {},
1966
- type: "handoff",
1967
- contextHandoffId: "handoff-1",
1968
- fromProviderThreadIds: ["provider-thread-1"],
1969
- toProviderThreadId: "provider-thread-2",
1970
- strategy: "full_thread_summary",
1971
- summary: "Full conversation context for provider handoff.",
1972
- ...item,
1973
- },
1974
- } as never,
1975
- });
1976
-
1977
- const { RegistryProvider } = await import("@effect/atom-react");
1978
- const { serverEnvironment } = await import("../../state/server");
1979
- const renderWithProviders = (element: ReactElement) =>
1980
- renderToStaticMarkup(
1981
- <RegistryProvider
1982
- initialValues={[
1983
- [serverEnvironment.providersValueAtom(ACTIVE_THREAD_ENVIRONMENT_ID), providerStatuses],
1984
- ]}
1985
- >
1986
- {element}
1987
- </RegistryProvider>,
1988
- );
1989
- const markup = renderWithProviders(
1990
- <MessagesTimeline
1991
- {...buildProps()}
1992
- timelineEntries={[
1993
- buildHandoffEntry({
1994
- fromProviderInstanceIds: ["codex_personal"],
1995
- toProviderInstanceId: "claudeAgent",
1996
- fromModelSelections: [{ instanceId: "codex_personal", model: "gpt-5.6-sol" }],
1997
- toModel: "claude-fable-5",
1998
- }),
1999
- ]}
2000
- />,
2001
- );
2002
-
2003
- expect(markup).toContain("Context handoff");
2004
- expect(markup).toContain("GPT 5.6 Sol");
2005
- expect(markup).toContain("Claude Fable 5");
2006
- expect(markup).not.toContain("Full conversation context");
2007
- expect(markup).not.toContain("·");
2008
-
2009
- const legacyRuns = [
2010
- {
2011
- id: "run-1",
2012
- ordinal: 1,
2013
- providerInstanceId: "codex_personal",
2014
- modelSelection: { instanceId: "codex_personal", model: "gpt-5.6-sol" },
2015
- },
2016
- {
2017
- id: "run-2",
2018
- ordinal: 2,
2019
- providerInstanceId: "claudeAgent",
2020
- modelSelection: { instanceId: "claudeAgent", model: "claude-fable-5" },
2021
- },
2022
- ] as never;
2023
- const legacyMarkup = renderWithProviders(
2024
- <MessagesTimeline
2025
- {...buildProps()}
2026
- runs={legacyRuns}
2027
- timelineEntries={[
2028
- buildHandoffEntry({
2029
- fromProviderInstanceIds: ["codex_personal"],
2030
- toProviderInstanceId: "claudeAgent",
2031
- }),
2032
- ]}
2033
- />,
2034
- );
2035
-
2036
- expect(legacyMarkup).toContain("GPT 5.6 Sol");
2037
- expect(legacyMarkup).toContain("Claude Fable 5");
2038
- expect(legacyMarkup).not.toContain("Full conversation context");
2039
-
2040
- const bareMarkup = renderWithProviders(
2041
- <MessagesTimeline
2042
- {...buildProps()}
2043
- timelineEntries={[
2044
- buildHandoffEntry({
2045
- fromProviderInstanceIds: ["codex_personal"],
2046
- toProviderInstanceId: "claudeAgent",
2047
- }),
2048
- ]}
2049
- />,
2050
- );
2051
-
2052
- expect(bareMarkup).toContain("Codex Personal");
2053
- expect(bareMarkup).not.toContain("Full conversation context");
2054
- });
2055
-
2056
- it("renders created threads as lean rows with inline chat links", async () => {
2057
- const { MessagesTimeline } = await import("./MessagesTimeline");
2058
- const markup = renderToStaticMarkup(
2059
- <MessagesTimeline
2060
- {...buildProps()}
2061
- timelineEntries={[
2062
- {
2063
- id: "thread-created",
2064
- kind: "event",
2065
- createdAt: MESSAGE_CREATED_AT,
2066
- projectedItem: {
2067
- position: 0,
2068
- visibility: "local",
2069
- sourceThreadId: "thread-1",
2070
- sourceItemId: "thread-created",
2071
- item: {
2072
- id: "thread-created",
2073
- threadId: "thread-1",
2074
- runId: "run-1",
2075
- nodeId: "node-1",
2076
- providerThreadId: null,
2077
- providerTurnId: null,
2078
- nativeItemRef: null,
2079
- parentItemId: null,
2080
- ordinal: 1,
2081
- status: "completed",
2082
- title: "Claude research thread",
2083
- startedAt: null,
2084
- completedAt: null,
2085
- updatedAt: {},
2086
- type: "thread_created",
2087
- targetThreadId: "thread-2",
2088
- targetRunId: "run-2",
2089
- targetProviderInstanceId: "claude-default",
2090
- targetModel: "claude-sonnet-4-6",
2091
- },
2092
- } as never,
2093
- },
2094
- ]}
2095
- />,
2096
- );
2097
-
2098
- expect(markup).toContain('data-v2-item-type="thread_created"');
2099
- expect(markup).toContain('aria-label="Open Claude research thread"');
2100
- expect(markup).toContain("Claude research thread");
2101
- expect(markup).toContain("Open chat");
2102
- expect(markup).not.toContain("Work Log");
2103
- });
2104
-
2105
- it("keeps the collapsed summary icon neutral when the group ends in a failure", () => {
2106
- const markup = renderToStaticMarkup(
2107
- <MessagesTimeline
2108
- {...buildProps()}
2109
- timelineEntries={[
2110
- {
2111
- id: "entry-completed",
2112
- kind: "work",
2113
- createdAt: "2026-03-17T19:12:28.000Z",
2114
- entry: {
2115
- id: "work-completed",
2116
- createdAt: "2026-03-17T19:12:28.000Z",
2117
- label: "Run tests",
2118
- tone: "tool",
2119
- itemType: "command_execution",
2120
- toolLifecycleStatus: "completed",
2121
- },
2122
- },
2123
- {
2124
- id: "entry-failed",
2125
- kind: "work",
2126
- createdAt: "2026-03-17T19:12:29.000Z",
2127
- entry: {
2128
- id: "work-failed",
2129
- createdAt: "2026-03-17T19:12:29.000Z",
2130
- label: "Run lint",
2131
- tone: "tool",
2132
- itemType: "command_execution",
2133
- toolLifecycleStatus: "failed",
2134
- },
2135
- },
2136
- ]}
2137
- />,
2138
- );
2139
-
2140
- expect(markup).toContain("Ran 2 commands");
2141
- expect(markup).toContain("lucide-terminal");
2142
- expect(markup).not.toContain("lucide-x");
2143
- expect(markup).not.toContain("text-destructive");
2144
- expect(markup).toContain("tool call failed");
2145
- });
2146
-
2147
- it("keeps mixed work logs neutral after a later tool call succeeds", () => {
2148
- const markup = renderToStaticMarkup(
2149
- <MessagesTimeline
2150
- {...buildProps()}
2151
- timelineEntries={[
2152
- {
2153
- id: "entry-failed",
2154
- kind: "work",
2155
- createdAt: "2026-03-17T19:12:28.000Z",
2156
- entry: {
2157
- id: "work-failed",
2158
- createdAt: "2026-03-17T19:12:28.000Z",
2159
- label: "Run search",
2160
- tone: "tool",
2161
- itemType: "command_execution",
2162
- toolLifecycleStatus: "failed",
2163
- },
2164
- },
2165
- {
2166
- id: "entry-info",
2167
- kind: "work",
2168
- createdAt: "2026-03-17T19:12:29.000Z",
2169
- entry: {
2170
- id: "work-info",
2171
- createdAt: "2026-03-17T19:12:29.000Z",
2172
- label: "Status updated",
2173
- tone: "info",
2174
- },
2175
- },
2176
- {
2177
- id: "entry-completed",
2178
- kind: "work",
2179
- createdAt: "2026-03-17T19:12:30.000Z",
2180
- entry: {
2181
- id: "work-completed",
2182
- createdAt: "2026-03-17T19:12:30.000Z",
2183
- label: "Run tests",
2184
- tone: "tool",
2185
- itemType: "command_execution",
2186
- toolLifecycleStatus: "completed",
2187
- },
2188
- },
2189
- ]}
2190
- />,
2191
- );
2192
-
2193
- expect(markup).toContain("Ran 2 commands and received 1 update");
2194
- expect(markup).not.toContain('aria-label="Hidden work includes a failure"');
2195
- });
2196
-
2197
- it.each(
2198
- (
2199
- [
2200
- {
2201
- status: "running",
2202
- progress: "Reading src/index.ts",
2203
- result: null,
2204
- preview: "Reading src/index.ts",
2205
- },
2206
- {
2207
- status: "completed",
2208
- progress: "Reading src/index.ts",
2209
- result: "Tests should be isolated.",
2210
- preview: "Tests should be isolated.",
2211
- },
2212
- {
2213
- status: "running",
2214
- progress: "Reading src/index.ts",
2215
- result: "Partial streamed answer",
2216
- preview: "Reading src/index.ts",
2217
- },
2218
- {
2219
- status: "running",
2220
- progress: undefined,
2221
- result: "Streaming answer so far",
2222
- preview: "Streaming answer so far",
2223
- },
2224
- {
2225
- status: "cancelled",
2226
- progress: "Reading src/index.ts",
2227
- result: "Partial output before cancel",
2228
- preview: "Partial output before cancel",
2229
- },
2230
- {
2231
- status: "completed",
2232
- progress: "Audited 12 packages",
2233
- result: " \n\t ",
2234
- preview: "Audited 12 packages",
2235
- },
2236
- ] as const
2237
- ).flatMap((scenario) => [1, 2].map((count) => ({ ...scenario, count }))),
2238
- )(
2239
- "shows $count $status subagents with '$preview', grouping only multiple agents",
2240
- async ({ status, progress, result, preview, count }) => {
2241
- activityTestState.expandedRuns = true;
2242
- activityTestState.subagentTooltips = true;
2243
- vi.stubGlobal("HTMLElement", ElementStub);
2244
- window.HTMLElement = ElementStub as unknown as typeof HTMLElement;
2245
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
2246
- vi.stubGlobal("requestAnimationFrame", () => 0);
2247
- vi.stubGlobal("cancelAnimationFrame", () => {});
2248
- const onOpenThread = vi.fn();
2249
- let renderer: ReactTestRenderer | undefined;
2250
- try {
2251
- await act(() => {
2252
- renderer = create(
2253
- <MessagesTimeline
2254
- {...buildProps()}
2255
- onOpenThread={onOpenThread}
2256
- timelineEntries={Array.from({ length: count }, (_, index) => ({
2257
- id: `subagent-progress-${index}`,
2258
- kind: "event",
2259
- createdAt: MESSAGE_CREATED_AT,
2260
- projectedItem: {
2261
- position: 0,
2262
- visibility: "local",
2263
- sourceThreadId: "thread-1",
2264
- sourceItemId: "subagent-progress",
2265
- item: {
2266
- id: `subagent-progress-${index}`,
2267
- threadId: "thread-1",
2268
- runId: "run-1",
2269
- nodeId: `node-subagent-${index}`,
2270
- providerThreadId: "provider-thread-1",
2271
- providerTurnId: "provider-turn-1",
2272
- nativeItemRef: null,
2273
- parentItemId: null,
2274
- ordinal: 1,
2275
- status,
2276
- title: "Package audit",
2277
- startedAt: null,
2278
- completedAt: null,
2279
- updatedAt: {},
2280
- type: "subagent",
2281
- subagentId: `node-subagent-${index}`,
2282
- origin: "provider_native",
2283
- driver: "claudeAgent",
2284
- providerInstanceId: "claudeAgent",
2285
- childThreadId: "thread-subagent-1",
2286
- prompt: "Inspect the package",
2287
- progress,
2288
- result,
2289
- },
2290
- } as never,
2291
- }))}
2292
- />,
2293
- );
2294
- });
2295
- const groupLabel = `${count} subagents`;
2296
- const group = () =>
2297
- renderer!.root.findAll(
2298
- (node) => node.type === "button" && node.props["aria-label"] === groupLabel,
2299
- )[0]!;
2300
- const child = () =>
2301
- renderer!.root.findAll(
2302
- (node) => node.type === "button" && node.props["aria-label"] === "Open Package audit",
2303
- );
2304
- if (count > 1) {
2305
- expect(child()).toHaveLength(0);
2306
- await act(() => group().props.onClick({ nativeEvent: new Event("click") }));
2307
- } else {
2308
- expect(group()).toBeUndefined();
2309
- }
2310
- expect(child()).toHaveLength(count);
2311
- const content = renderer!.root
2312
- .findAll((node) => typeof node.type === "string")
2313
- .flatMap((node) => node.children.filter((child) => typeof child === "string"))
2314
- .join("");
2315
- expect(content).toContain(preview);
2316
- expect(content).not.toContain("Inspect the package");
2317
- if (result?.trim() && result !== preview) expect(content).not.toContain(result);
2318
- if (progress && progress !== preview) expect(content).not.toContain(progress);
2319
- await act(() => child()[0]!.props.onClick());
2320
- expect(onOpenThread).toHaveBeenCalledWith("thread-subagent-1");
2321
- if (count > 1) {
2322
- await act(() => group().props.onClick({ nativeEvent: new Event("click") }));
2323
- expect(child()).toHaveLength(0);
2324
- }
2325
- } finally {
2326
- await act(() => renderer?.unmount());
2327
- vi.stubGlobal("HTMLElement", undefined);
2328
- }
2329
- },
2330
- );
2331
-
2332
- it("renders V2 provider retries in the normal work log", () => {
2333
- activityTestState.expanded = true;
2334
- const retryItem = {
2335
- id: "provider-error",
2336
- threadId: "thread-1",
2337
- runId: "run-1",
2338
- nodeId: null,
2339
- providerThreadId: "provider-thread-1",
2340
- providerTurnId: "provider-turn-1",
2341
- nativeItemRef: null,
2342
- parentItemId: null,
2343
- ordinal: 99,
2344
- status: "running",
2345
- title: "Provider retry",
2346
- startedAt: {},
2347
- completedAt: null,
2348
- updatedAt: {},
2349
- type: "error",
2350
- failure: {
2351
- class: "transport_error",
2352
- message: "The response stream disconnected.",
2353
- code: "responseStreamDisconnected",
2354
- retryable: true,
2355
- },
2356
- retry: {
2357
- attempt: 2,
2358
- maxAttempts: 5,
2359
- retryDelayMs: null,
2360
- },
2361
- } as const;
2362
- const projectedItem = {
2363
- position: 0,
2364
- visibility: "local",
2365
- sourceThreadId: "thread-1",
2366
- sourceItemId: retryItem.id,
2367
- item: retryItem,
2368
- } as const;
2369
- const markup = renderToStaticMarkup(
2370
- <MessagesTimeline
2371
- {...buildProps()}
2372
- isWorking
2373
- activeTurnInProgress
2374
- latestRun={{
2375
- runId: RunId.make("run-1"),
2376
- status: "running",
2377
- startedAt: MESSAGE_CREATED_AT,
2378
- completedAt: null,
2379
- }}
2380
- timelineEntries={
2381
- [
2382
- {
2383
- id: "provider-error",
2384
- kind: "work",
2385
- createdAt: MESSAGE_CREATED_AT,
2386
- entry: {
2387
- id: retryItem.id,
2388
- createdAt: MESSAGE_CREATED_AT,
2389
- runId: "run-1",
2390
- label: "Retrying provider (2/5)",
2391
- detail: retryItem.failure.message,
2392
- tone: "info",
2393
- itemType: "error",
2394
- toolLifecycleStatus: "inProgress",
2395
- structuredPayload: retryItem,
2396
- projectedItem,
2397
- },
2398
- },
2399
- ] as never
2400
- }
2401
- />,
2402
- );
2403
-
2404
- expect(markup).toContain('data-v2-item-type="error"');
2405
- expect(markup).toContain("Retrying provider (2/5)");
2406
- expect(markup).toContain('aria-expanded="false"');
2407
- expect(markup).not.toContain('data-v2-event-disclosure="true"');
2408
- });
2409
-
2410
- it("keeps inherited V2 work provenance on the rendered row", async () => {
2411
- activityTestState.expanded = true;
2412
- const { MessagesTimeline } = await import("./MessagesTimeline");
2413
- const item = {
2414
- id: "command-inherited",
2415
- threadId: "thread-source",
2416
- runId: null,
2417
- nodeId: null,
2418
- providerThreadId: null,
2419
- providerTurnId: null,
2420
- nativeItemRef: null,
2421
- parentItemId: null,
2422
- ordinal: 0,
2423
- status: "completed",
2424
- title: null,
2425
- startedAt: null,
2426
- completedAt: null,
2427
- updatedAt: {},
2428
- type: "command_execution",
2429
- input: "pwd",
2430
- output: "/workspace",
2431
- exitCode: 0,
2432
- } as const;
2433
- const projectedItem = {
2434
- position: 0,
2435
- visibility: "inherited",
2436
- sourceThreadId: "thread-source",
2437
- sourceItemId: item.id,
2438
- item,
2439
- } as const;
2440
- const markup = renderToStaticMarkup(
2441
- <MessagesTimeline
2442
- {...buildProps()}
2443
- timelineEntries={
2444
- [
2445
- {
2446
- id: "context-info-entry",
2447
- kind: "work",
2448
- createdAt: MESSAGE_CREATED_AT,
2449
- entry: {
2450
- id: "context-info",
2451
- createdAt: MESSAGE_CREATED_AT,
2452
- label: "Session started",
2453
- tone: "info",
2454
- },
2455
- },
2456
- {
2457
- id: item.id,
2458
- kind: "work",
2459
- createdAt: MESSAGE_CREATED_AT,
2460
- entry: {
2461
- id: item.id,
2462
- createdAt: MESSAGE_CREATED_AT,
2463
- runId: null,
2464
- label: "Ran command",
2465
- command: item.input,
2466
- tone: "tool",
2467
- itemType: item.type,
2468
- toolLifecycleStatus: "completed",
2469
- structuredPayload: item,
2470
- projectedItem,
2471
- },
2472
- },
2473
- ] as never
2474
- }
2475
- />,
2476
- );
2477
-
2478
- expect(markup).toContain('data-v2-item-type="command_execution"');
2479
- expect(markup).toContain('data-v2-item-visibility="inherited"');
2480
- expect(markup).toContain("Received 1 update and ran 1 command");
2481
- });
2482
-
2483
- it("renders T3 MCP dynamic tools with the product logo and pretty name", async () => {
2484
- activityTestState.expanded = true;
2485
- const { MessagesTimeline } = await import("./MessagesTimeline");
2486
- const item = {
2487
- id: "tool-t3-thread-read",
2488
- threadId: "thread-source",
2489
- runId: null,
2490
- nodeId: null,
2491
- providerThreadId: null,
2492
- providerTurnId: null,
2493
- nativeItemRef: null,
2494
- parentItemId: null,
2495
- ordinal: 0,
2496
- status: "completed",
2497
- title: null,
2498
- startedAt: null,
2499
- completedAt: null,
2500
- updatedAt: {},
2501
- type: "dynamic_tool",
2502
- toolName: "mcp__t3-code__t3_thread_read",
2503
- input: { threadId: "thread-child" },
2504
- output: { messages: [] },
2505
- } as const;
2506
- const projectedItem = {
2507
- position: 0,
2508
- visibility: "local",
2509
- sourceThreadId: "thread-source",
2510
- sourceItemId: item.id,
2511
- item,
2512
- } as const;
2513
- const markup = renderToStaticMarkup(
2514
- <MessagesTimeline
2515
- {...buildProps()}
2516
- timelineEntries={
2517
- [
2518
- {
2519
- id: "context-info-entry",
2520
- kind: "work",
2521
- createdAt: MESSAGE_CREATED_AT,
2522
- entry: {
2523
- id: "context-info",
2524
- createdAt: MESSAGE_CREATED_AT,
2525
- label: "Session started",
2526
- tone: "info",
2527
- },
2528
- },
2529
- {
2530
- id: item.id,
2531
- kind: "work",
2532
- createdAt: MESSAGE_CREATED_AT,
2533
- entry: {
2534
- id: item.id,
2535
- createdAt: MESSAGE_CREATED_AT,
2536
- runId: null,
2537
- label: item.toolName,
2538
- tone: "tool",
2539
- itemType: item.type,
2540
- toolTitle: item.toolName,
2541
- toolLifecycleStatus: "completed",
2542
- toolData: { input: item.input, output: item.output },
2543
- structuredPayload: item,
2544
- projectedItem,
2545
- },
2546
- },
2547
- ] as never
2548
- }
2549
- />,
2550
- );
2551
-
2552
- expect(markup).toContain('viewBox="15.5309 37 94.3941 56.96"');
2553
- expect(markup).toContain("Read a T3 thread");
2554
- expect(markup).not.toContain("mcp__t3-code__t3_thread_read");
2555
- });
2556
-
2557
- it("formats changed file paths from the workspace root", async () => {
2558
- activityTestState.expanded = true;
2559
- const { MessagesTimeline } = await import("./MessagesTimeline");
2560
- const markup = renderToStaticMarkup(
2561
- <MessagesTimeline
2562
- {...buildProps()}
2563
- timelineEntries={[
2564
- {
2565
- id: "context-info-entry",
2566
- kind: "work",
2567
- createdAt: "2026-03-17T19:12:28.000Z",
2568
- entry: {
2569
- id: "context-info",
2570
- createdAt: "2026-03-17T19:12:28.000Z",
2571
- label: "Session started",
2572
- tone: "info",
2573
- },
2574
- },
2575
- {
2576
- id: "entry-1",
2577
- kind: "work",
2578
- createdAt: "2026-03-17T19:12:28.000Z",
2579
- entry: {
2580
- id: "work-1",
2581
- createdAt: "2026-03-17T19:12:28.000Z",
2582
- label: "Updated files",
2583
- tone: "tool",
2584
- itemType: "file_change",
2585
- toolLifecycleStatus: "completed",
2586
- changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
2587
- },
2588
- },
2589
- ]}
2590
- workspaceRoot="C:/Users/mike/dev-stuff/t3code"
2591
- />,
2592
- );
2593
-
2594
- expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
2595
- expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
2596
- });
2597
-
2598
- it("renders review comment contexts as structured cards instead of raw tags", () => {
2599
- const markup = renderToStaticMarkup(
2600
- <MessagesTimeline
2601
- {...buildProps()}
2602
- timelineEntries={[
2603
- {
2604
- id: "entry-1",
2605
- kind: "message",
2606
- createdAt: "2026-03-17T19:12:28.000Z",
2607
- message: {
2608
- id: MessageId.make("message-2"),
2609
- role: "user",
2610
- text: [
2611
- '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
2612
- "Wadduo",
2613
- "```diff",
2614
- "@@ -0,0 +47,2 @@",
2615
- '+ it("keeps valid zero-usage snapshots", () => {',
2616
- "+ expect(snapshot).not.toBeNull();",
2617
- "```",
2618
- "</review_comment>",
2619
- ].join("\n"),
2620
- runId: null,
2621
- createdAt: "2026-03-17T19:12:28.000Z",
2622
- updatedAt: "2026-03-17T19:12:28.000Z",
2623
- streaming: false,
2624
- },
2625
- },
2626
- ]}
2627
- />,
2628
- );
2629
-
2630
- expect(markup).toContain("contextWindow.test.ts +47 to +58");
2631
- expect(markup).toContain("lucide-message-circle");
2632
- expect(markup).not.toContain(">Review comment<");
2633
- expect(markup).not.toContain("<review_comment");
2634
- expect(markup).not.toContain("</review_comment>");
2635
- });
2636
-
2637
- it("renders file review comments as source code instead of diffs", () => {
2638
- const markup = renderToStaticMarkup(
2639
- <MessagesTimeline
2640
- {...buildProps()}
2641
- timelineEntries={[
2642
- {
2643
- id: "entry-1",
2644
- kind: "message",
2645
- createdAt: "2026-03-17T19:12:28.000Z",
2646
- message: {
2647
- id: MessageId.make("message-source-comment"),
2648
- role: "user",
2649
- text: [
2650
- '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
2651
- "Clarify this.",
2652
- "```md",
2653
- "# Plan",
2654
- "- Step one",
2655
- "```",
2656
- "</review_comment>",
2657
- ].join("\n"),
2658
- runId: null,
2659
- createdAt: "2026-03-17T19:12:28.000Z",
2660
- updatedAt: "2026-03-17T19:12:28.000Z",
2661
- streaming: false,
2662
- },
2663
- },
2664
- ]}
2665
- />,
2666
- );
2667
-
2668
- expect(markup).toContain("plan.md L1 to L2");
2669
- expect(markup).not.toContain("review_comment");
2670
- expect(markup).not.toContain('data-testid="file-diff"');
2671
- });
2672
-
2673
- it("collapses settled tool runs behind a generated summary toggle", () => {
2674
- const markup = renderToStaticMarkup(
2675
- <MessagesTimeline
2676
- {...buildProps()}
2677
- timelineEntries={[
2678
- {
2679
- id: "entry-1",
2680
- kind: "work",
2681
- createdAt: "2026-03-17T19:12:28.000Z",
2682
- entry: {
2683
- id: "work-1",
2684
- createdAt: "2026-03-17T19:12:28.000Z",
2685
- label: "Ran command",
2686
- command: "vp lint",
2687
- tone: "tool",
2688
- itemType: "command_execution",
2689
- toolLifecycleStatus: "completed",
2690
- },
2691
- },
2692
- {
2693
- id: "entry-2",
2694
- kind: "work",
2695
- createdAt: "2026-03-17T19:12:29.000Z",
2696
- entry: {
2697
- id: "work-2",
2698
- createdAt: "2026-03-17T19:12:29.000Z",
2699
- label: "Ran command",
2700
- command: "vp test run",
2701
- tone: "tool",
2702
- itemType: "command_execution",
2703
- toolLifecycleStatus: "completed",
2704
- },
2705
- },
2706
- ]}
2707
- />,
2708
- );
2709
-
2710
- expect(markup).toContain("Ran 2 commands");
2711
- expect(markup).toContain('aria-expanded="false"');
2712
- expect(markup).not.toContain("vp lint");
2713
- });
2714
-
2715
- it("renders a muted failure marker for failed tool lifecycle entries", () => {
2716
- activityTestState.expanded = true;
2717
- const markup = renderToStaticMarkup(
2718
- <MessagesTimeline
2719
- {...buildProps()}
2720
- timelineEntries={[
2721
- {
2722
- id: "entry-info",
2723
- kind: "work",
2724
- createdAt: "2026-03-17T19:12:27.000Z",
2725
- entry: {
2726
- id: "work-info",
2727
- createdAt: "2026-03-17T19:12:27.000Z",
2728
- label: "Status updated",
2729
- tone: "info",
2730
- },
2731
- },
2732
- {
2733
- id: "entry-1",
2734
- kind: "work",
2735
- createdAt: "2026-03-17T19:12:28.000Z",
2736
- entry: {
2737
- id: "work-1",
2738
- createdAt: "2026-03-17T19:12:28.000Z",
2739
- label: "Glob",
2740
- tone: "tool",
2741
- toolLifecycleStatus: "failed",
2742
- detail: "No files found",
2743
- },
2744
- },
2745
- ]}
2746
- />,
2747
- );
2748
-
2749
- expect(markup).toContain("lucide-zap");
2750
- expect(markup).toContain('aria-label="Tool call failed"');
2751
- expect(markup).not.toContain("text-destructive");
2752
- });
2753
-
2754
- it("keeps the red treatment for severe orchestration failures", () => {
2755
- const markup = renderToStaticMarkup(
2756
- <MessagesTimeline
2757
- {...buildProps()}
2758
- timelineEntries={[
2759
- {
2760
- id: "entry-info",
2761
- kind: "work",
2762
- createdAt: "2026-03-17T19:12:27.000Z",
2763
- entry: {
2764
- id: "work-info",
2765
- createdAt: "2026-03-17T19:12:27.000Z",
2766
- label: "Status updated",
2767
- tone: "info",
2768
- },
2769
- },
2770
- {
2771
- id: "entry-turn-failed",
2772
- kind: "work",
2773
- createdAt: "2026-03-17T19:12:28.000Z",
2774
- entry: {
2775
- id: "work-turn-failed",
2776
- createdAt: "2026-03-17T19:12:28.000Z",
2777
- label: "Provider turn start failed",
2778
- tone: "error",
2779
- itemType: "error",
2780
- toolLifecycleStatus: "failed",
2781
- },
2782
- },
2783
- ]}
2784
- />,
2785
- );
2786
-
2787
- expect(markup).toContain("lucide-circle-alert");
2788
- expect(markup).toContain("text-destructive");
2789
- });
2790
-
2791
- it.each([
2792
- [
2793
- "**Viewing image first** with *care*, ~~old~~ `code` and [context](https://example.com)",
2794
- "Viewing image first with care, old code and context",
2795
- 1,
2796
- ],
2797
- ["first paragraph\n\nsecond paragraph", "first paragraph second paragraph", 0],
2798
- ["- first\n- second", "first second", 0],
2799
- ["first \nsecond", "first second", 0],
2800
- ["", "image description", 0],
2801
- ["", "Thought", 0],
2802
- ["---", "Thought", 0],
2803
- ] as const)(
2804
- "shows plain text for a V2 reasoning preview: %s",
2805
- async (markdown, expected, strongCount) => {
2806
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
2807
- vi.stubGlobal("requestAnimationFrame", () => 0);
2808
- vi.stubGlobal("cancelAnimationFrame", () => {});
2809
- activityTestState.expanded = true;
2810
- let renderer: ReactTestRenderer | undefined;
2811
- try {
2812
- await act(() => {
2813
- renderer = create(
2814
- <MessagesTimeline
2815
- {...buildProps()}
2816
- timelineEntries={[
2817
- {
2818
- id: "reasoning-preview",
2819
- kind: "work",
2820
- createdAt: MESSAGE_CREATED_AT,
2821
- entry: {
2822
- id: "reasoning-preview",
2823
- createdAt: MESSAGE_CREATED_AT,
2824
- label: markdown,
2825
- detail: markdown,
2826
- tone: "thinking",
2827
- itemType: "reasoning",
2828
- toolLifecycleStatus: "completed",
2829
- },
2830
- },
2831
- ]}
2832
- />,
2833
- );
2834
- });
2835
- const previewText = () =>
2836
- renderer!.root
2837
- .findAllByType("span")
2838
- .flatMap((node) => node.findAll(() => true))
2839
- .flatMap((node) => node.children)
2840
- .filter((child) => typeof child === "string")
2841
- .join(" ");
2842
- expect(previewText()).toContain(expected);
2843
- expect(renderer!.root.findAllByType("strong")).toHaveLength(0);
2844
- const row = () =>
2845
- renderer!.root.findAll(
2846
- (node) =>
2847
- node.type === "div" &&
2848
- node.props.role === "button" &&
2849
- typeof node.props["aria-expanded"] === "boolean",
2850
- )[0]!;
2851
- await act(() => row().props.onClick());
2852
- expect(renderer!.root.findAllByType("strong")).toHaveLength(strongCount);
2853
- await act(() => row().props.onClick());
2854
- expect(previewText()).toContain(expected);
2855
- expect(renderer!.root.findAllByType("strong")).toHaveLength(0);
2856
- } finally {
2857
- await act(() => renderer?.unmount());
2858
- }
2859
- },
2860
- );
2861
-
2862
- it("expands and collapses a tool call through its header", async () => {
2863
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
2864
- vi.stubGlobal("requestAnimationFrame", () => 0);
2865
- vi.stubGlobal("cancelAnimationFrame", () => {});
2866
- let renderer: ReactTestRenderer | undefined;
2867
- try {
2868
- await act(() => {
2869
- renderer = create(
2870
- <MessagesTimeline
2871
- {...buildProps()}
2872
- timelineEntries={[
2873
- {
2874
- id: "entry-standalone",
2875
- kind: "work",
2876
- createdAt: MESSAGE_CREATED_AT,
2877
- entry: {
2878
- id: "work-standalone",
2879
- createdAt: MESSAGE_CREATED_AT,
2880
- toolCallId: "call-standalone",
2881
- label: "Run lint",
2882
- tone: "tool",
2883
- itemType: "command_execution",
2884
- command: "pnpm lint",
2885
- toolLifecycleStatus: "completed",
2886
- },
2887
- },
2888
- ]}
2889
- />,
2890
- );
2891
- });
2892
- await act(() => renderer!.root.findByProps({ "aria-expanded": false }).props.onClick());
2893
- const expanded = renderer!.root.findAll(
2894
- (node) => node.type === "div" && node.props["aria-expanded"] === true,
2895
- )[0]!;
2896
- expect(expanded).toBeDefined();
2897
- await act(() => expanded.props.onClick());
2898
- expect(
2899
- renderer!.root.findAll(
2900
- (node) => node.type === "div" && node.props["aria-expanded"] === true,
2901
- ),
2902
- ).toHaveLength(0);
2903
- } finally {
2904
- await act(() => renderer?.unmount());
2905
- }
2906
- });
2907
-});
apps/web/src/components/chat/MessagesTimeline.tsx
+1
-1
@@ -2443,7 +2443,7 @@ function UserMessageIntentMarker({
2443
);
2444
}
2445
2446
-export function resolvePreviewAnnotationImage(input: {
2446
+function resolvePreviewAnnotationImage(input: {
2447
record: Extract<KnownComposerContextRecord, { kind: "preview-annotation" }>;
2448
recordsById: ReadonlyMap<string, ComposerContextRecord>;
2449
userImages: ReadonlyArray<ChatImageAttachment>;