Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

presentation.test.ts

467 lines15.6 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import { ThreadId, TurnItemId, type OrchestrationV2TurnItem } from "@t3tools/contracts";
4import * as DateTime from "effect/DateTime";
5import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput";
6​
7import {
8 liveThoughtLine,
9 resolveViewedImageAsset,
10 resolveWorkEntryToolPresentation,
11 summarizeToolGroup,
12 toolGroupSummaryKind,
13 toolItemForDisplay,
14 type WorkLogPresentationEntry,
15 workEntryIndicatesToolFailure,
16 workEntryDisplayIndicatesToolFailure,
17 workEntriesViewedImagePaths,
18 workEntriesViewedImages,
19 workEntryViewedImagePath,
20} from "./presentation.js";
21​
22describe("liveThoughtLine", () => {
23 it.each(["The area is 3 * 4 * 5 cubic units.", "Matching glob * and the * literal."])(
24 "preserves literal markers in %s",
25 (thought) => {
26 expect(liveThoughtLine(thought)).toBe(thought);
27 },
28 );
29​
30 it("strips emphasis without removing spaced underscores", () => {
31 expect(liveThoughtLine("*em* and _a b_ leave _ these _ alone.")).toBe(
32 "em and a b leave _ these _ alone.",
33 );
34 });
35});
36​
37function commandItem(
38 fields: Partial<Extract<OrchestrationV2TurnItem, { type: "command_execution" }>> = {},
39): Extract<OrchestrationV2TurnItem, { type: "command_execution" }> {
40 return {
41 id: TurnItemId.make("command"),
42 threadId: ThreadId.make("thread"),
43 runId: null,
44 nodeId: null,
45 providerThreadId: null,
46 providerTurnId: null,
47 nativeItemRef: null,
48 parentItemId: null,
49 ordinal: 1,
50 status: "completed",
51 title: null,
52 startedAt: null,
53 completedAt: null,
54 updatedAt: DateTime.makeUnsafe("2026-09-08T00:00:00.000Z"),
55 type: "command_execution",
56 input: 'rg "command not found"',
57 ...fields,
58 };
60​
61describe("workEntryIndicatesToolFailure", () => {
62 const base = {
63 id: "w1",
64 createdAt: "2026-01-01T00:00:00.000Z",
65 label: "Read",
66 };
67​
68 it.each([
69 [{ exitCode: 2 }, true],
70 [{ output: "sh: missing-command: command not found" }, true],
71 [{ output: `${"x".repeat(32_768)} command not found` }, false],
72 ] as const)(
73 "preserves command failure state after removing displayed output: %j",
74 (fields, failed) => {
75 const structuredPayload = commandItem(fields);
76 const entry: WorkLogPresentationEntry = {
77 ...base,
78 tone: "tool",
79 itemType: "command_execution",
80 toolLifecycleStatus: "completed",
81 structuredPayload,
82 };
83 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(failed);
84 expect(JSON.stringify(toolItemForDisplay(structuredPayload))).not.toContain('"output":');
85 },
86 );
87​
88 it.each([
89 "logs/app.log:12: Error: ENOENT: no such file or directory",
90 "fixtures/ci.txt:3: Process exited with exit code 2",
91 ])("trusts a zero exit code over failure text in the output and command: %s", (output) => {
92 const entry: WorkLogPresentationEntry = {
93 ...base,
94 tone: "tool",
95 itemType: "command_execution",
96 toolLifecycleStatus: "completed",
97 command: 'rg -n "ENOENT|exit code" logs fixtures',
98 structuredPayload: commandItem({ output, exitCode: 0, outputIndicatesFailure: true }),
99 };
100 expect(workEntryIndicatesToolFailure(entry)).toBe(false);
101 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
102 });
103​
104 it("ignores failure phrases in reasoning text", () => {
105 const entry: WorkLogPresentationEntry = {
106 ...base,
107 label: "Thinking",
108 tone: "thinking",
109 itemType: "reasoning",
110 toolLifecycleStatus: "completed",
111 detail: "That exit code 2 is just from listing the deleted directory, which is expected.",
112 };
113 expect(workEntryIndicatesToolFailure(entry)).toBe(false);
114 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
115 });
116​
117 it("does not treat error text in a command as rendered failure", () => {
118 const entry = {
119 ...base,
120 label: "Ran command",
121 tone: "tool",
122 toolLifecycleStatus: "completed",
123 command: 'rg "file not found"',
124 detail: "Found 3 matches",
125 } satisfies WorkLogPresentationEntry;
126​
127 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
128​
129 expect(workEntryIndicatesToolFailure(entry)).toBe(true);
130 expect(workEntryDisplayIndicatesToolFailure({ ...entry, detail: "File not found" })).toBe(true);
131 });
132});
133​
134describe("resolveWorkEntryToolPresentation", () => {
135 it("shows returned MCP errors as failures even in the live activity row", () => {
136 const entry: WorkLogPresentationEntry = {
137 id: "clone",
138 createdAt: "2026-09-19T00:00:00.000Z",
139 tone: "tool",
140 label: "T3-code.t3_project_clone",
141 toolLifecycleStatus: "inProgress",
142 itemType: "dynamic_tool",
143 toolData: { output: { isError: true } },
144 };
145 expect(resolveWorkEntryToolPresentation(entry)?.displayName).toBe(
146 "Failed to clone a repository",
147 );
148 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(true);
149 const childFailure = {
150 ...entry,
151 label: "T3-code.task_status",
152 toolLifecycleStatus: "completed" as const,
153 toolData: { output: { taskId: "child", status: "failed", summary: "command not found" } },
154 };
155 expect(workEntryDisplayIndicatesToolFailure(childFailure)).toBe(false);
156 });
157 it.each([
158 "mcp__t3-code__preview_click",
159 "mcp__t3_code__preview_click",
160 "mcp__t3code__preview_click",
161 "T3-code.preview_click",
162 "t3-code · preview_click completed",
163 "t3_code/preview_click",
164 "preview_click",
165 ])("recognizes browser tool names across providers: %s", (label) => {
166 expect(resolveWorkEntryToolPresentation({ label })).toEqual({
167 displayName: "Clicking in the preview browser",
168 icon: "browser",
169 });
170 });
171​
172 it("uses structured MCP identity when the provider supplies a custom title", () => {
173 expect(
174 resolveWorkEntryToolPresentation({
175 label: "Tool call complete",
176 toolTitle: "Inspect the current page",
177 toolData: { server: "t3-code", tool: "preview_snapshot", result: { title: "Example" } },
178 }),
179 ).toEqual({ displayName: "Taking a snapshot of the preview page", icon: "browser" });
180 });
181​
182 it("names the reported outcome when it contradicts the row's verb", () => {
183 const row = (tool: string, output: unknown) =>
184 resolveWorkEntryToolPresentation({
185 label: `T3-code.${tool}`,
186 toolLifecycleStatus: "completed",
187 toolData: { output: compactT3McpToolOutput(`t3-code.${tool}`, output) },
188 })?.displayName;
189 expect(row("pull_request_create", { number: 470, created: false })).toBe(
190 "Found 1 open pull request",
191 );
192 expect(row("pull_request_create", { number: 470, created: true })).toBe(
193 "Opened a pull request",
194 );
195 expect(row("ci_rerun", { number: 883, checks: [] })).toBe("Found no failed checks to re-run");
196 expect(row("ci_rerun", { number: 883, checks: [{ name: "ci", rerun: true }] })).toBe(
197 "Re-ran CI",
198 );
199 expect(row("pull_request_merge", { number: 1, state: "open" })).toBe(
200 "Queued 1 pull request to merge",
201 );
202 });
203​
204 it("distinguishes pull request searches from unqueried lists in rows and groups", () => {
205 const list: WorkLogPresentationEntry = {
206 id: "pull-request-list",
207 createdAt: "2026-01-01T00:00:00.000Z",
208 label: "T3-code.pull_request_list",
209 tone: "tool",
210 itemType: "dynamic_tool",
211 toolLifecycleStatus: "completed",
212 toolData: { input: { state: "open" } },
213 };
214 const search = {
215 ...list,
216 id: "pull-request-search",
217 toolData: { input: { query: "is:pr is:open gitlab" }, output: { pullRequests: [] } },
218 };
219 expect(resolveWorkEntryToolPresentation(list)?.displayName).toBe("Listed pull requests");
220 expect(resolveWorkEntryToolPresentation(search)?.displayName).toBe("Searched pull requests");
221 expect(
222 resolveWorkEntryToolPresentation({
223 ...search,
224 toolData: { input: { args: search.toolData.input } },
225 })?.displayName,
226 ).toBe("Searched pull requests");
227 expect(
228 resolveWorkEntryToolPresentation({
229 ...search,
230 toolLifecycleStatus: "failed",
231 })?.displayName,
232 ).toBe("Failed to search pull requests");
233 expect(summarizeToolGroup([search, { ...search, id: "second-query" }]).summary).toBe(
234 "Searched pull requests 2 times",
235 );
236 });
237​
238 it("uses the summary's state only when the provider omitted a lifecycle status", () => {
239 const entry = { label: "T3-code.preview_click" };
240 expect(resolveWorkEntryToolPresentation(entry, "inProgress")?.displayName).toBe(
241 "Clicking in the preview browser",
242 );
243 expect(resolveWorkEntryToolPresentation(entry, "completed")?.displayName).toBe(
244 "Clicked in the preview browser",
245 );
246 expect(
247 resolveWorkEntryToolPresentation({ ...entry, toolLifecycleStatus: "completed" }, "inProgress")
248 ?.displayName,
249 ).toBe("Clicked in the preview browser");
250 expect(
251 resolveWorkEntryToolPresentation({ ...entry, toolLifecycleStatus: "failed" }, "completed")
252 ?.displayName,
253 ).toBe("Failed to click in the preview browser");
254 });
255​
256 it.each([
257 ["https://github.com/acme/web/pull/7", "PR #7"],
258 ["https://gitlab.com/acme/web/-/merge_requests/7", "MR #7"],
259 ])("names a linked change request with its host's term (%s)", (url, target) => {
260 expect(
261 resolveWorkEntryToolPresentation({
262 label: "T3-code.link_pull_request",
263 toolLifecycleStatus: "completed",
264 toolData: { arguments: { url } },
265 })?.displayName,
266 ).toMatch(new RegExp(` ${target}$`));
267 });
268​
269 it("does not brand unknown tools or another server's matching tool name", () => {
270 for (const label of [
271 "mcp__github__preview_click",
272 "t3-code.unknown_tool",
273 "t3-code.toString",
274 "Search files",
275 ]) {
276 expect(resolveWorkEntryToolPresentation({ label })).toBeNull();
277 }
278 expect(
279 resolveWorkEntryToolPresentation({
280 label: "preview_click",
281 toolData: { server: "another-server", tool: "preview_click" },
282 }),
283 ).toBeNull();
284 });
285});
286​
287describe("resolveViewedImageAsset", () => {
288 it("requests the file the agent read when its name holds %, # or ?", () => {
289 const path = "/Users/me/.grok/sessions/%2FUsers%2Fme%2Fproject/shot #1?/1.jpg";
290 expect(
291 resolveViewedImageAsset(path, { threadId: ThreadId.make("thread"), workspaceRoot: "/repo" }),
292 ).toEqual({
293 resource: { _tag: "media-file", threadId: ThreadId.make("thread"), path },
294 alt: "1.jpg",
295 srcFragment: "",
296 });
297 });
298​
299 it("still decodes a file URL", () => {
300 expect(
301 resolveViewedImageAsset("file:///repo/my%20shot.png", { threadId: ThreadId.make("thread") })
302 ?.resource.path,
303 ).toBe("/repo/my shot.png");
304 });
305});
306​
307describe("workEntryViewedImagePath", () => {
308 it("withholds a Read's image preview until the Read has finished", () => {
309 const read: WorkLogPresentationEntry = {
310 id: "read",
311 createdAt: "2026-01-01T00:00:00.000Z",
312 label: "Read",
313 tone: "tool",
314 itemType: "dynamic_tool",
315 viewedImagePath: "/repo/out/later3.png",
316 };
317​
318 expect(workEntryViewedImagePath({ ...read, toolLifecycleStatus: "inProgress" })).toBeNull();
319 expect(workEntryViewedImagePath({ ...read, toolLifecycleStatus: "completed" })).toBe(
320 "/repo/out/later3.png",
321 );
322 });
323});
324​
325describe("workEntriesViewedImages", () => {
326 const read = (
327 id: string,
328 path: string,
329 toolLifecycleStatus: NonNullable<WorkLogPresentationEntry["toolLifecycleStatus"]>,
330 ): WorkLogPresentationEntry => ({
331 id,
332 createdAt: "2026-01-01T00:00:00.000Z",
333 label: "Read",
334 tone: "tool",
335 itemType: "dynamic_tool",
336 viewedImagePath: path,
337 toolLifecycleStatus,
338 });
339​
340 it("marks an image pending until a Read of it finishes", () => {
341 expect(
342 workEntriesViewedImages([
343 read("done", "/repo/a.png", "completed"),
344 read("running", "/repo/b.png", "inProgress"),
345 read("missing", "/repo/c.png", "failed"),
346 read("again", "/repo/a.png", "inProgress"),
347 ]),
348 ).toEqual([
349 { path: "/repo/a.png", pending: false },
350 { path: "/repo/b.png", pending: true },
351 ]);
352 expect(
353 workEntriesViewedImages([
354 read("running", "/repo/b.png", "inProgress"),
355 read("done", "/repo/b.png", "completed"),
356 ]),
357 ).toEqual([{ path: "/repo/b.png", pending: false }]);
358 });
359​
360 it("orders the finished images like the strip shows them", () => {
361 expect(
362 workEntriesViewedImagePaths([
363 read("first", "/repo/a.png", "inProgress"),
364 read("other", "/repo/b.png", "completed"),
365 read("again", "/repo/a.png", "completed"),
366 ]),
367 ).toEqual(["/repo/a.png", "/repo/b.png"]);
368 });
369});
370​
371it("distinguishes saved file globs from content searches in a tool group", () => {
372 const search = (pattern: string, title: string): WorkLogPresentationEntry => ({
373 id: pattern,
374 createdAt: "2026-09-08T00:00:00.000Z",
375 label: title,
376 tone: "tool",
377 itemType: "file_search",
378 structuredPayload: { ...commandItem(), type: "file_search", pattern, title },
379 });
380 const glob = search("**/*.ts", "Searched files **/*.ts in src");
381 const grep = search("files TODO", "Searched files TODO");
382​
383 expect(toolGroupSummaryKind([glob])).toBe("file-search");
384 expect(toolGroupSummaryKind([grep])).toBe("code-search");
385 expect(summarizeToolGroup([glob, grep]).summary).toBe("Searched files and searched code 1 time");
386});
387​
388describe("summarizeToolGroup read counts", () => {
389 const read = (id: string, filePath: string, offset?: number): WorkLogPresentationEntry => ({
390 id,
391 createdAt: "2026-11-27T00:00:00.000Z",
392 label: "Read",
393 tone: "tool",
394 itemType: "dynamic_tool",
395 toolTitle: "Read",
396 toolLifecycleStatus: "completed",
397 structuredPayload: {
398 id: TurnItemId.make(id),
399 threadId: ThreadId.make("thread"),
400 runId: null,
401 nodeId: null,
402 providerThreadId: null,
403 providerTurnId: null,
404 nativeItemRef: null,
405 parentItemId: null,
406 ordinal: 0,
407 status: "completed",
408 title: null,
409 startedAt: null,
410 completedAt: null,
411 updatedAt: DateTime.makeUnsafe("2026-11-27T00:00:00.000Z"),
412 type: "dynamic_tool",
413 toolName: "Read",
414 input: offset === undefined ? { file_path: filePath } : { file_path: filePath, offset },
415 },
416 });
417​
418 it("counts a file read in several chunks once, as edits do", () => {
419 expect(
420 summarizeToolGroup([
421 read("a1", "/repo/src/a.ts"),
422 read("a2", "/repo/src/a.ts", 200),
423 read("b", "/repo/src/b.ts"),
424 ]).summary,
425 ).toBe("Read 2 files");
426 });
427​
428 it("counts filenames that differ only by trailing whitespace as separate files", () => {
429 expect(
430 summarizeToolGroup([
431 read("a", "report.txt"),
432 read("b", "report.txt "),
433 read("c", "report.txt "),
434 ]).summary,
435 ).toBe("Read 2 files");
436 });
437});
438​
439describe("summarizeToolGroup approvals", () => {
440 const command: WorkLogPresentationEntry = {
441 id: "command",
442 createdAt: "2026-11-27T00:00:00.000Z",
443 label: "pwd",
444 tone: "tool",
445 itemType: "command_execution",
446 command: "pwd",
447 toolLifecycleStatus: "completed",
448 };
449 const approval: WorkLogPresentationEntry = {
450 id: "approval",
451 createdAt: "2026-11-27T00:00:00.000Z",
452 label: "Approval requested",
453 tone: "tool",
454 itemType: "approval_request",
455 requestKind: "command",
456 toolLifecycleStatus: "completed",
457 };
458​
459 it("does not count the approval for a step as a tool of its own", () => {
460 expect(summarizeToolGroup([command, approval]).summary).toBe("Ran 1 command");
461 expect(toolGroupSummaryKind([command, approval])).toBe("command");
462 });
463​
464 it("still summarizes a group that only holds an approval", () => {
465 expect(summarizeToolGroup([approval]).summary).toBe("Used 1 tool");
466 });
467});