Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import {
3 EnvironmentId,
4 ProviderDriverKind,
5 ThreadId,
6 TurnItemId,
7 type OrchestrationV2TurnItem,
8} from "@t3tools/contracts";
9import * as DateTime from "effect/DateTime";
10
11import {
12 isJsonToolText,
13 threadReadTarget,
14 toolArgumentLanguage,
15 toolCallLines,
16 turnItemOutputImages,
17 turnItemOutputText,
18} from "./itemDetail.ts";
19
20describe("isJsonToolText", () => {
21 it.each([
22 ['{"screenshot":{"mimeType":"image/png"}}', true],
23 ['[{"threadId":"thread-1"}]', true],
24 ['{\n\n "status": "completed"\n}', true],
25 ['{\n "count": 1\n}\n\n{\n "count": 2\n}', true],
26 ['{"id":1}\n{"id":2}', true],
27 ['{"id":1}\n{"id":-9007199254740993}', true],
28 ["false", true],
29 ["null", true],
30 ["42", true],
31 ['"completed"', true],
32 ['{"partial":', false],
33 ['{"count":1}\n\nFinished.', false],
34 ['{"count":1}\nFinished.', false],
35 ['{"id":1}\n{"id":', false],
36 ["1\n2\n3", false],
37 ["No output.", false],
38 ["", false],
39 ] as const)("classifies %j as JSON: %s", (text, expected) => {
40 expect(isJsonToolText(text)).toBe(expected);
41 });
42});
43
44it("highlights the code argument of OpenCode's execute tool", () => {
45 const code = "const answer: number = 42;";
46 const codeArgument = { key: "code", text: code, inlineJson: false };
47 const tool = {
48 toolName: "execute",
49 nativeItemRef: {
50 driver: ProviderDriverKind.make("opencode"),
51 nativeId: "call-execute",
52 strength: "strong" as const,
53 },
54 };
55 expect(toolArgumentLanguage(codeArgument, tool)).toBe("typescript");
56 expect(toolArgumentLanguage(codeArgument, { ...tool, nativeItemRef: null })).toBeNull();
57 expect(toolArgumentLanguage({ ...codeArgument, key: "description" }, tool)).toBeNull();
58});
59
60it("highlights JSON scalars inline and keeps structured JSON in blocks", () => {
61 const { args } = toolCallLines({
62 args: {
63 limit: 100,
64 includeSubagents: true,
65 dryRun: false,
66 cursor: null,
67 query: "100",
68 label: "",
69 options: { dryRun: false },
70 paths: ["README.md"],
71 },
72 });
73 expect(
74 args?.map((arg) => [arg.key, arg.text, arg.inlineJson, toolArgumentLanguage(arg)]),
75 ).toEqual([
76 ["limit", "100", true, "json"],
77 ["includeSubagents", "true", true, "json"],
78 ["dryRun", "false", true, "json"],
79 ["cursor", "null", true, "json"],
80 ["query", "100", false, null],
81 ["label", '""', false, null],
82 ["options", '{"dryRun":false}', false, "json"],
83 ["paths", '["README.md"]', false, "json"],
84 ]);
85});
86
87function toolItem(output: unknown): OrchestrationV2TurnItem {
88 return {
89 id: TurnItemId.make("images"),
90 threadId: ThreadId.make("thread"),
91 runId: null,
92 nodeId: null,
93 providerThreadId: null,
94 providerTurnId: null,
95 nativeItemRef: null,
96 parentItemId: null,
97 ordinal: 1,
98 status: "completed",
99 title: null,
100 startedAt: null,
101 completedAt: null,
102 updatedAt: DateTime.makeUnsafe("2026-10-01T00:00:00Z"),
103 type: "dynamic_tool",
104 toolName: "screenshots",
105 input: {},
106 output,
107 };
108}
109
110it("uses a thread read's saved link and keeps unfinished calls in their requested environment", () => {
111 const source = EnvironmentId.make("source");
112 const remote = EnvironmentId.make("remote");
113 const threadId = ThreadId.make("task(1)");
114 const read = {
115 ...toolItem(undefined),
116 type: "dynamic_tool",
117 toolName: "mcp__t3-code__t3_thread_read",
118 input: { args: { threadId, environmentId: remote } },
119 } as Extract<OrchestrationV2TurnItem, { type: "dynamic_tool" }>;
120 expect(threadReadTarget(read, source)).toEqual({
121 ref: { threadId, environmentId: remote },
122 title: null,
123 });
124 expect(
125 threadReadTarget(
126 {
127 ...read,
128 input: { threadId },
129 output: {
130 thread: {
131 threadId,
132 title: "Saved title",
133 link: "[Saved title](<t3-thread://v2/remote/task(1)>)",
134 },
135 },
136 },
137 source,
138 ),
139 ).toEqual({ ref: { threadId, environmentId: remote }, title: "Saved title" });
140});
141
142describe("tool image output parsing", () => {
143 it.each(["image-only", "summary", "json"] as const)(
144 "keeps structured fields beside %s content",
145 (shape) => {
146 const content = [
147 { type: "image", mimeType: "image/png" },
148 ...(shape === "image-only"
149 ? []
150 : [{ type: "text", text: shape === "summary" ? "Sunny" : '{"temp":21}' }]),
151 ];
152 for (const structuredContent of [
153 { temp: 21 },
154 { type: "text", text: "Sunny", temp: 21 },
155 { content: [{ type: "text", text: "Sunny" }], temp: 21 },
156 ]) {
157 const item = toolItem({ structuredContent, content });
158 expect(turnItemOutputText(item)).toBe(JSON.stringify(structuredContent, null, 2));
159 expect(turnItemOutputImages(item)).toHaveLength(1);
160 }
161 for (const structuredContent of [null, {}, [], "", undefined]) {
162 expect(turnItemOutputText(toolItem({ structuredContent, content }))).toBe(
163 shape === "image-only" ? null : shape === "summary" ? "Sunny" : '{\n "temp": 21\n}',
164 );
165 expect(
166 turnItemOutputText(
167 toolItem({ structuredContent, content: [{ type: "text", text: " " }] }),
168 ),
169 ).toBeNull();
170 }
171 const unrecognized = {
172 structuredContent: null,
173 content: [{ type: "audio", data: "abc" }],
174 };
175 expect(turnItemOutputText(toolItem(unrecognized))).toBe(
176 JSON.stringify(unrecognized, null, 2),
177 );
178 expect(
179 turnItemOutputText(
180 toolItem({
181 content: [{ type: "text", text: "File contents" }],
182 structuredContent: { path: "read.ts", ready: true },
183 }),
184 ),
185 ).toBe("File contents");
186 },
187 );
188 it.each(["array", "content", "structured"] as const)(
189 "keeps markers for images beyond the served positions in %s output",
190 (shape) => {
191 // Detail responses retain image metadata after the server strips image bytes.
192 const image = { type: "image", mimeType: "image/png" };
193 const blocks = Array.from({ length: 8 }, () => ({ ...image }));
194 const wrap = (content: unknown[]) =>
195 shape === "array"
196 ? content
197 : shape === "structured"
198 ? { content, structuredContent: { temp: 21 } }
199 : { content };
200 const withinLimit = toolItem(wrap(blocks));
201 expect(turnItemOutputText(withinLimit)).toBe(
202 shape === "structured" ? '{\n "temp": 21\n}' : null,
203 );
204 expect(turnItemOutputImages(withinLimit)).toHaveLength(8);
205
206 const overflow = toolItem(
207 wrap([
208 ...blocks,
209 { type: "text", text: "Two additional screenshots:" },
210 { ...image, sizeBytes: 100 },
211 { type: "image", source: { type: "base64", media_type: "image/jpeg" } },
212 ]),
213 );
214 expect(turnItemOutputImages(overflow)).toHaveLength(8);
215 expect(turnItemOutputText(overflow)).toBe(
216 (shape === "structured" ? '{\n "temp": 21\n}' : "Two additional screenshots:") +
217 "\n[image]\n[image]",
218 );
219 },
220 );
221});
222
223describe("tool text output formatting", () => {
224 it("shows a Claude MCP result's JSON text once when the envelope includes metadata", () => {
225 const payload = { projects: [{ id: "project-1", title: "Example" }], nextCursor: 20 };
226 const output = {
227 content: JSON.stringify(payload),
228 _meta: { "io.modelcontextprotocol/serverInfo": { name: "T3 Code", version: "0.1.14" } },
229 structuredContent: payload,
230 };
231 expect(turnItemOutputText(toolItem(output))).toBe(JSON.stringify(payload, null, 2));
232 });
233
234 it.each([
235 '{"id":1234567890123456789,"name":"x"}',
236 '{"id":1}\n{"id":-9007199254740993}',
237 '{"id":9.007199254740993e15}',
238 '{"id":1e309}',
239 '{"ratio":1e-400}',
240 '{"price":123456789012345.6789}',
241 '{"ratio":0.1234567890123456789}',
242 ])("keeps %j as returned when parsing would change a number", (text) => {
243 expect(turnItemOutputText(toolItem({ content: [{ type: "text", text }] }))).toBe(text);
244 });
245
246 it.each([
247 '{"port":80,"port":443}',
248 '{"server":{"port":80,"p\\u006frt":443}}',
249 '{"id":1}\n{"id":2,"id":3}',
250 ])("keeps %j as returned when an object repeats a key", (text) => {
251 expect(turnItemOutputText(toolItem({ content: [{ type: "text", text }] }))).toBe(text);
252 });
253
254 it.each(['{"total":2,"1":"a","0":"b"}', '{"10":1,"9":2}'])(
255 "keeps %j as returned when stringifying would reorder its keys",
256 (text) => {
257 expect(turnItemOutputText(toolItem({ content: [{ type: "text", text }] }))).toBe(text);
258 },
259 );
260
261 it.each([
262 '{"id":42,"note":"12345678901234567890"}',
263 '[{"port":80},{"port":443,"note":"port"}]',
264 '{"price":1.50,"rate":25e-1}',
265 '{"ratio":0.00e-400}',
266 '{"2":1,"10":2,"a":3}',
267 ])("still pretty-prints %j", (text) => {
268 expect(turnItemOutputText(toolItem({ content: [{ type: "text", text }] }))).toBe(
269 JSON.stringify(JSON.parse(text), null, 2),
270 );
271 });
272});
273
274describe("ACP tool call content output", () => {
275 it("shows the text of ACP content entries, not their JSON", () => {
276 // ACP agents report a tool's result as content entries; the adapter stores them when no rawOutput is sent.
277 const output = [
278 { type: "content", content: { type: "text", text: "Cloud config is up to date." } },
279 { type: "content", content: { type: "text", text: "2 profiles loaded." } },
280 ];
281 expect(turnItemOutputText(toolItem(output))).toBe(
282 "Cloud config is up to date.\n2 profiles loaded.",
283 );
284 });
285});
286
287describe("MCP app tool output", () => {
288 it("shows the tool result, not the app wrapper", () => {
289 const text = "Notice\nview\tcount\n/home\t42";
290 const item = toolItem({
291 t3McpApp: {
292 attachmentId: "app-html",
293 server: "repro",
294 tool: "aggregate_rum_events",
295 resourceUri: "ui://repro/dataviz",
296 },
297 result: { content: [{ type: "text", text }] },
298 });
299 expect(turnItemOutputText(item)).toBe(text);
300 });
301
302 it("reads a result with metadata and marks images it cannot preview", () => {
303 const item = toolItem({
304 t3McpApp: {
305 attachmentId: "app-html",
306 server: "repro",
307 tool: "chart",
308 resourceUri: "ui://repro/chart",
309 },
310 result: {
311 content: [
312 { type: "text", text: "chart" },
313 { type: "image", mimeType: "image/png", data: "iVBORw0KGgo=" },
314 ],
315 _meta: { "ui/resourceUri": "ui://repro/chart" },
316 },
317 });
318 expect(turnItemOutputText(item)).toBe("chart\n[image]");
319
320 const bounded = toolItem({
321 t3McpApp: {
322 attachmentId: "app-html",
323 server: "repro",
324 tool: "chart",
325 resourceUri: "ui://repro/chart",
326 },
327 result: [
328 { type: "text", text: "chart" },
329 { type: "image", mimeType: "image/png" },
330 ],
331 });
332 expect(turnItemOutputText(bounded)).toBe("chart\n[image]");
333 });
334});
335
336describe("file search output text", () => {
337 function searchItem(
338 results: Extract<OrchestrationV2TurnItem, { type: "file_search" }>["results"],
339 status: OrchestrationV2TurnItem["status"] = "completed",
340 ): OrchestrationV2TurnItem {
341 const {
342 toolName: _toolName,
343 input: _input,
344 output: _output,
345 ...base
346 } = toolItem(null) as Extract<OrchestrationV2TurnItem, { type: "dynamic_tool" }>;
347 return { ...base, type: "file_search", pattern: "needle", status, results };
348 }
349
350 it("prints matches under one heading per file", () => {
351 expect(
352 turnItemOutputText(
353 searchItem([
354 { fileName: "src/one.ts", line: 2, preview: " const needle = 1;" },
355 { fileName: "src/two.ts", line: 7, column: 3, preview: "needle()" },
356 { fileName: "src/one.ts", line: 9, preview: "return needle;" },
357 ]),
358 ),
359 ).toBe("src/one.ts\n2: const needle = 1;\n9: return needle;\n\nsrc/two.ts\n7:3: needle()");
360 });
361
362 it("keeps a plain file list one path per line", () => {
363 expect(turnItemOutputText(searchItem([{ fileName: "a.ts" }, { fileName: "b.ts" }]))).toBe(
364 "a.ts\nb.ts",
365 );
366 });
367
368 const ripgrepError =
369 "rg: src/cycle: Too many levels of symbolic links (os error 62)\nrg: src/missing: No such file or directory (os error 2)";
370 it.each([
371 [JSON.stringify({ message: ripgrepError }), ripgrepError],
372 [JSON.stringify({ message: "Timed out after 25s" }), "Timed out after 25s"],
373 [ripgrepError, ripgrepError],
374 ['{"message":"Search failed","code":"EACCES"}', '{"message":"Search failed","code":"EACCES"}'],
375 ])("renders a failed search diagnostic as text", (preview, expected) => {
376 expect(turnItemOutputText(searchItem([{ fileName: "src", preview }], "failed"))).toBe(expected);
377 });
378
379 it("keeps a numbered match from a failed search", () => {
380 expect(
381 turnItemOutputText(
382 searchItem([{ fileName: "src/a.ts", line: 3, preview: "needle" }], "failed"),
383 ),
384 ).toBe("src/a.ts\n3: needle");
385 });
386});