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