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

presentation.ts

610 lines21.9 KB

1import {
2 isToolLifecycleItemType,
3 type AssetResource,
4 type ToolActivitySource,
5 type ToolActivitySurface,
6 type ToolActivityIcon,
7 type OrchestrationV2TurnItem,
8 type ThreadId,
9} from "@t3tools/contracts";
10import {
11 resolveT3McpToolSummaryAction,
12 type T3McpToolSummaryAction,
13} from "@t3tools/shared/t3McpToolPresentation";
14import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
15​
16import { classifyMarkdownImageSource } from "../markdownImages.ts";
17import { resolveMediaSource } from "../mediaSource.ts";
18​
19import {
20 summarizeT3ToolCalls,
21 type T3ToolSummaryCall,
22} from "@t3tools/client-runtime/t3ToolSummary";
23​
24export type WorkLogToolLifecycleStatus =
25 | "inProgress"
26 | "completed"
27 | "failed"
28 | "declined"
29 | "stopped"
30 | "idle";
31​
32export interface WorkLogPresentationEntry {
33 readonly id: string;
34 readonly createdAt: string;
35 readonly label: string;
36 readonly tone: "thinking" | "tool" | "info" | "error";
37 readonly command?: string;
38 readonly rawCommand?: string;
39 readonly detail?: string;
40 readonly viewedImagePath?: string;
41 readonly changedFiles?: ReadonlyArray<string>;
42 readonly toolTitle?: string;
43 readonly toolData?: unknown;
44 readonly requestKind?: string;
45 readonly itemType?: OrchestrationV2TurnItem["type"];
46 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
47 readonly structuredPayload?: OrchestrationV2TurnItem;
48 readonly toolSource?: ToolActivitySource;
49 readonly toolSurface?: ToolActivitySurface;
50 readonly toolIcon?: ToolActivityIcon;
52​
53export type ToolGroupAction =
54 | "read"
55 | "edit"
56 | "command"
57 | "browser"
58 | "code-search"
59 | "search"
60 | "other"
61 | "update";
62​
63export type ToolGroupSummaryKind =
64 | ToolGroupAction
65 | "dynamic-tool"
66 | "agent-tool"
67 | "tone-tool"
68 | "mixed";
69​
70export function normalizeCompactToolLabel(value: string): string {
71 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
73​
74const T3_MCP_TOOL_LABELS: Record<
75 string,
76 readonly [action: string, running: string, completed: string, detail: string]
77> = {
78 orchestrator_capabilities: ["Get", "Getting", "Got", "orchestration capabilities"],
79 delegate_task: ["Delegate", "Delegating", "Delegated", "a child task"],
80 task_status: ["Get", "Getting", "Got", "delegated task status"],
81 task_cancel: ["Cancel", "Canceling", "Canceled", "delegated task"],
82 schedule_task: ["Schedule", "Scheduling", "Scheduled", "a recurring task"],
83 list_scheduled_tasks: ["List", "Listing", "Listed", "scheduled tasks"],
84 update_scheduled_task: ["Update", "Updating", "Updated", "a scheduled task"],
85 delete_scheduled_task: ["Delete", "Deleting", "Deleted", "a scheduled task"],
86 create_threads: ["Create", "Creating", "Created", "T3 threads"],
87 t3_thread_start: ["Start", "Starting", "Started", "a T3 thread"],
88 t3_thread_list: ["List", "Listing", "Listed", "T3 threads"],
89 t3_thread_read: ["Read", "Reading", "Read", "a T3 thread"],
90 t3_thread_send: ["Send", "Sending", "Sent", "to a T3 thread"],
91 t3_thread_wait: ["Wait", "Waiting", "Waited", "for a T3 thread"],
92 t3_thread_interrupt: ["Interrupt", "Interrupting", "Interrupted", "a T3 thread"],
93 t3_worktree_handoff: ["Hand off", "Handing off", "Handed off", "thread to a git worktree"],
94 t3_worktree_status: ["Get", "Getting", "Got", "thread worktree status"],
95 preview_status: ["Get", "Getting", "Got", "preview browser status"],
96 preview_open: ["Open", "Opening", "Opened", "a page in the preview browser"],
97 preview_navigate: ["Navigate", "Navigating", "Navigated", "the preview browser"],
98 preview_snapshot: [
99 "Take a snapshot of",
100 "Taking a snapshot of",
101 "Took a snapshot of",
102 "the preview page",
103 ],
104 preview_click: ["Click", "Clicking", "Clicked", "in the preview browser"],
105 preview_press: ["Press", "Pressing", "Pressed", "a key in the preview browser"],
106 preview_type: ["Type", "Typing", "Typed", "in the preview browser"],
107 preview_scroll: ["Scroll", "Scrolling", "Scrolled", "the preview browser"],
108 preview_resize: ["Resize", "Resizing", "Resized", "the preview browser"],
109 preview_evaluate: ["Evaluate", "Evaluating", "Evaluated", "script in the preview browser"],
110 preview_wait_for: ["Wait", "Waiting", "Waited", "for the preview page"],
111 preview_set_appearance: ["Set", "Setting", "Set", "preview browser appearance"],
112 preview_recording_start: ["Start", "Starting", "Started", "recording the preview browser"],
113 preview_recording_stop: ["Stop", "Stopping", "Stopped", "recording the preview browser"],
114};
115​
116function resolveT3McpToolPresentation(value: string | undefined, status: string | undefined) {
117 if (!value) return null;
118 const name = normalizeCompactToolLabel(value).replace(
119 /^(?:mcp__(?:t3-code|t3_code|t3code)__|(?:t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*))/i,
120 "",
121 );
122 if (!Object.hasOwn(T3_MCP_TOOL_LABELS, name)) return null;
123​
124 const [action, running, completed, detail] = T3_MCP_TOOL_LABELS[name]!;
125 const verb =
126 status === "inProgress"
127 ? running
128 : status === "completed"
129 ? completed
130 : status === "failed"
131 ? `Failed to ${action.toLowerCase()}`
132 : status === "declined"
133 ? `Declined to ${action.toLowerCase()}`
134 : status === "stopped"
135 ? `Stopped ${running.toLowerCase()}`
136 : running;
137​
138 return {
139 displayName: `${verb} ${detail}`,
140 icon: name.startsWith("preview_") ? ("browser" as const) : ("t3-code" as const),
141 };
143​
144/** Only active or completed calls can inherit the live group’s present tense. */
145export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
146 if (status === "failed" || status === "declined" || status === "stopped" || status === "idle") {
147 return status;
148 }
149 if (presentTense || status === "inProgress") return "inProgress";
150 return "completed";
152​
153/** Resolves tool identity before choosing labels or icons in either client. */
154export function resolveWorkEntryToolPresentation(
155 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "toolLifecycleStatus">,
156 fallbackStatus?: "inProgress" | "completed",
157) {
158 const status = entry.toolLifecycleStatus ?? fallbackStatus;
159 const data = entry.toolData;
160 if (data !== null && typeof data === "object") {
161 if (
162 "server" in data &&
163 typeof data.server === "string" &&
164 "tool" in data &&
165 typeof data.tool === "string"
166 ) {
167 return resolveT3McpToolPresentation(`${data.server}.${data.tool}`, status);
168 }
169 if ("toolName" in data && typeof data.toolName === "string") {
170 return resolveT3McpToolPresentation(data.toolName, status);
171 }
172 }
173​
174 return (
175 resolveT3McpToolPresentation(entry.toolTitle, status) ??
176 resolveT3McpToolPresentation(entry.label, status)
177 );
179​
180function asRecord(value: unknown): Record<string, unknown> | null {
181 return value !== null && typeof value === "object" && !Array.isArray(value)
182 ? (value as Record<string, unknown>)
183 : null;
185​
186function nonEmptyString(value: unknown): string | null {
187 return typeof value === "string" && value.trim().length > 0 ? value : null;
189​
190function commandResultContent(value: unknown): string | null {
191 const direct = nonEmptyString(value);
192 if (direct) return direct;
193​
194 const directContent = Array.isArray(value) ? value : null;
195 const record = asRecord(value);
196 const content = record?.content;
197 const contentText = nonEmptyString(content);
198 if (contentText) return contentText;
199 const blocks = directContent ?? (Array.isArray(content) ? content : null);
200 if (!blocks) return null;
201​
202 const chunks = blocks.flatMap((entry) => {
203 const text = nonEmptyString(entry) ?? nonEmptyString(asRecord(entry)?.text);
204 return text ? [text] : [];
205 });
206 return chunks.length > 0 ? chunks.join("\n") : null;
208​
209/** Returns provider command output before it is formatted for a work-log row. */
210export function extractCommandOutputText(dataValue: unknown): string | null {
211 const data = asRecord(dataValue);
212 const item = asRecord(data?.item);
213 const itemResult = asRecord(item?.result);
214 const rawOutput = asRecord(data?.rawOutput);
215 const outputStreams = [
216 nonEmptyString(rawOutput?.stdout),
217 nonEmptyString(rawOutput?.stderr),
218 ].filter((value): value is string => value !== null);
219 const acpContent = Array.isArray(data?.content)
220 ? data.content
221 .flatMap((entryValue) => {
222 const entry = asRecord(entryValue);
223 const content = asRecord(entry?.content);
224 const text = entry?.type === "content" ? nonEmptyString(content?.text) : null;
225 return text ? [text] : [];
226 })
227 .join("\n")
228 : null;
229​
230 const candidates = [
231 item?.aggregatedOutput,
232 itemResult?.content,
233 data?.rawOutput,
234 rawOutput?.content,
235 outputStreams.length > 0 ? outputStreams.join("\n") : null,
236 rawOutput?.output,
237 acpContent,
238 data?.result,
239 ];
240 for (const candidate of candidates) {
241 const text = commandResultContent(candidate);
242 if (text) return text;
243 }
244 return null;
246​
247/**
248 * Ingestion caps tool details at 180 chars and appends "...", so a long command
249 * echo no longer equals the command it repeats. Treat a truncated prefix of the
250 * command as the same echo.
251 */
252function textRepeatsCommand(text: string, commands: ReadonlyArray<string | null>): boolean {
253 const truncated = text.endsWith("...")
254 ? text.slice(0, -3)
255 : text.endsWith("\u2026")
256 ? text.slice(0, -1)
257 : null;
258 return commands.some((candidate) => {
259 const command = candidate?.trim();
260 if (!command) return false;
261 if (command === text) return true;
262 return (
263 truncated !== null &&
264 truncated.length > 0 &&
265 command.length > truncated.length &&
266 command.startsWith(truncated)
267 );
268 });
270​
271/**
272 * Decides whether a command row's `detail` is a synthetic echo of the command
273 * rather than real output. OpenCode stores completed output in `detail` with no
274 * other output channel, so plain equality is only treated as synthetic when the
275 * payload shape shows the detail came from the command: Codex item metadata,
276 * an ACP tool call (`data.toolCallId`, `kind: "execute"`), a Claude tool-name
277 * prefix, or no structured command at all.
278 */
279export function commandDetailRepeatsCommand(input: {
280 readonly detail: string;
281 readonly command: string | null;
282 readonly rawCommand: string | null;
283 readonly toolName: unknown;
284 readonly data: unknown;
285}): boolean {
286 const toolName = nonEmptyString(input.toolName)?.trim();
287 const detail = input.detail.trim();
288 const commands = [input.command, input.rawCommand];
289 if (toolName) {
290 const prefix = `${toolName}:`;
291 if (detail.toLowerCase().startsWith(prefix.toLowerCase())) {
292 const unprefixed = detail.slice(prefix.length).trim();
293 if (textRepeatsCommand(unprefixed, commands)) return true;
294 }
295 }
296​
297 if (!textRepeatsCommand(detail, commands)) return false;
298​
299 const data = asRecord(input.data);
300 const item = asRecord(data?.item);
301 const itemInput = asRecord(item?.input);
302 const itemResult = asRecord(item?.result);
303 const hasStructuredCommand = [
304 item?.command,
305 itemInput?.command,
306 itemResult?.command,
307 data?.command,
308 ].some((value) =>
309 Array.isArray(value)
310 ? value.some((part) => nonEmptyString(part) !== null)
311 : nonEmptyString(value) !== null,
312 );
313 return (
314 !hasStructuredCommand ||
315 item !== null ||
316 data?.toolCallId !== undefined ||
317 nonEmptyString(data?.kind)?.toLowerCase() === "execute"
318 );
320​
321export function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
322 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
323 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
324 if (entry.requestKind !== undefined) return true;
325 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
327​
328function toolDetailTextLooksLikeFailure(text: string): boolean {
329 const normalized = text.toLowerCase();
330 return (
331 normalized.includes("file not found") ||
332 normalized.includes("no files found") ||
333 normalized.includes("enoent") ||
334 normalized.includes("no such file or directory") ||
335 normalized.includes("no such file") ||
336 (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
337 normalized.includes("commandnotfoundexception") ||
338 normalized.includes("is not recognized as the name of a cmdlet") ||
339 (normalized.includes("is not recognized") && normalized.includes("the term '")) ||
340 normalized.includes("a parameter cannot be found that matches parameter name") ||
341 normalized.includes("command not found") ||
342 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
343 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
344 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
345 );
347​
348export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
349 if (
350 entry.tone === "error" ||
351 entry.toolLifecycleStatus === "failed" ||
352 entry.toolLifecycleStatus === "declined"
353 ) {
354 return true;
355 }
356 return (
357 workLogEntryIsToolLike(entry) &&
358 entry.detail !== undefined &&
359 toolDetailTextLooksLikeFailure(entry.detail)
360 );
362​
363export function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
364 return (
365 entry.itemType === "file_search" ||
366 (entry.itemType === "web_search" &&
367 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
368 );
370​
371export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
372 if (resolveWorkEntryToolPresentation(entry)?.icon === "browser") return "browser";
373 if (entry.requestKind === "file-read" || entry.viewedImagePath !== undefined) return "read";
374 if (
375 entry.itemType === "dynamic_tool" &&
376 /^read(?:\s+file)?$/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
377 ) {
378 return "read";
379 }
380 if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
381 if (entry.itemType === "command_execution" || entry.command) return "command";
382 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
383 if (entry.itemType === "web_search") return "search";
384 return workLogEntryIsToolLike(entry) ? "other" : "update";
386​
387export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
388 const viewedImagePath = entry.viewedImagePath?.trim();
389 if (
390 viewedImagePath !== undefined &&
391 !/[\r\n]/.test(viewedImagePath) &&
392 isWorkspaceImagePreviewPath(viewedImagePath)
393 ) {
394 return viewedImagePath;
395 }
396 const detail = entry.detail?.trim();
397 return toolGroupAction(entry) === "read" &&
398 detail !== undefined &&
399 !/[\r\n]/.test(detail) &&
400 isWorkspaceImagePreviewPath(detail)
401 ? detail
402 : null;
404​
405export interface ViewedImageAsset {
406 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
407 readonly alt: string;
408 readonly srcFragment: string;
410​
411export function resolveViewedImageAsset(
412 source: string,
413 input: {
414 readonly threadId: ThreadId;
415 readonly workspaceRoot?: string | null | undefined;
416 },
417): ViewedImageAsset | null {
418 // A relative path with no known workspace still names a media-file relative
419 // to the thread's workspace, so classify against "." and drop the prefix.
420 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
421 if (imageSource._tag !== "WorkspaceFile") return null;
422 const resolvedFilePath =
423 input.workspaceRoot == null && imageSource.path.startsWith("./")
424 ? imageSource.path.slice(2)
425 : imageSource.path;
426​
427 const media = resolveMediaSource(source, {
428 threadId: input.threadId,
429 workspaceRoot: input.workspaceRoot,
430 resolvedFilePath,
431 });
432 if (media === null || media.access !== "environment") return null;
433 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
435​
436function toolGroupActionCount(
437 action: ToolGroupAction,
438 entries: ReadonlyArray<WorkLogPresentationEntry>,
439): number {
440 if (action !== "edit") return entries.length;
441 const changedFiles = new Set<string>();
442 let editsWithoutFileDetails = 0;
443 for (const entry of entries) {
444 if (!entry.changedFiles || entry.changedFiles.length === 0) {
445 editsWithoutFileDetails += 1;
446 } else {
447 for (const file of entry.changedFiles) changedFiles.add(file);
448 }
449 }
450 return changedFiles.size + editsWithoutFileDetails;
452​
453function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
454 switch (action) {
455 case "read":
456 return `Read ${count} ${count === 1 ? "file" : "files"}`;
457 case "edit":
458 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
459 case "command":
460 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
461 case "browser":
462 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
463 case "search":
464 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
465 case "code-search":
466 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
467 case "other":
468 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
469 case "update":
470 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
471 }
473​
474function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
475 const item = entry.structuredPayload;
476 const data =
477 entry.toolData !== null && typeof entry.toolData === "object"
478 ? (entry.toolData as Record<string, unknown>)
479 : undefined;
480 return {
481 input: item?.type === "dynamic_tool" ? item.input : data?.input,
482 output: item?.type === "dynamic_tool" ? item.output : data?.output,
483 outcome:
484 entry.toolLifecycleStatus === "failed" ||
485 entry.toolLifecycleStatus === "declined" ||
486 entry.tone === "error"
487 ? "failed"
488 : entry.toolLifecycleStatus === "completed"
489 ? "completed"
490 : "unfinished",
491 };
493​
494function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
495 switch (action) {
496 case "command":
497 case "edit":
498 case "delegate":
499 case "task-cancel":
500 case "thread-create":
501 case "thread-send":
502 case "thread-interrupt":
503 case "schedule-create":
504 case "schedule-update":
505 case "schedule-delete":
506 return 0;
507 case "other":
508 case "update":
509 return 2;
510 default:
511 return 1;
512 }
514​
515/** Summarizes at most two action categories; every omitted call still counts in the remainder. */
516export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): {
517 summary: string;
518 hasFailure: boolean;
519} {
520 const groups = new Map<
521 ToolGroupAction | T3McpToolSummaryAction,
522 {
523 action: ToolGroupAction;
524 t3Action: T3McpToolSummaryAction | null;
525 entries: WorkLogPresentationEntry[];
526 }
527 >();
528 const sources = new Map<string, ToolActivitySource>();
529 for (const entry of entries) {
530 if (entry.toolSource) {
531 sources.set(entry.toolSource.key, entry.toolSource);
532 continue;
533 }
534 const item = entry.structuredPayload;
535 const t3Action = resolveT3McpToolSummaryAction(
536 (item?.type === "dynamic_tool" ? item.toolName : null) ?? entry.toolTitle ?? entry.label,
537 );
538 const action = toolGroupAction(entry);
539 const key = t3Action ?? action;
540 const group = groups.get(key);
541 if (group) group.entries.push(entry);
542 else groups.set(key, { action, t3Action, entries: [entry] });
543 }
544 const summaries = [...groups].map(([action, group], index) => ({
545 index,
546 count: group.entries.length,
547 priority: summaryActionPriority(action),
548 ...(group.t3Action
549 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall))
550 : {
551 label: toolGroupActionLabel(
552 group.action,
553 toolGroupActionCount(group.action, group.entries),
554 ),
555 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
556 }),
557 }));
558 const selected = [...summaries]
559 .sort((a, b) => a.priority - b.priority || a.index - b.index)
560 .slice(0, 2)
561 .sort((a, b) => a.index - b.index);
562 const labels = selected.map(({ label }) => label);
563 if (sources.size > 0) {
564 const sourceValues = [...sources.values()];
565 const sourceNames = sourceValues.map((source) => source.name);
566 const formattedNames =
567 sourceNames.length < 2
568 ? sourceNames[0]!
569 : sourceNames.length === 2
570 ? sourceNames.join(" and ")
571 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
572 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
573 labels.unshift(
574 `Used ${formattedNames}${allIntegrations ? ` ${sources.size === 1 ? "integration" : "integrations"}` : ""}`,
575 );
576 }
577 const sourcedCount = entries.filter((entry) => entry.toolSource !== undefined).length;
578 const remainingCount =
579 entries.length - sourcedCount - selected.reduce((count, group) => count + group.count, 0);
580 if (remainingCount > 0) {
581 labels.push(`Performed ${remainingCount} other ${remainingCount === 1 ? "action" : "actions"}`);
582 }
583 const sentenceLabels = labels.map((label, index) =>
584 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
585 );
586 const summary =
587 sentenceLabels.length < 3
588 ? sentenceLabels.join(" and ")
589 : `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
590 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
592​
593export function toolGroupSummaryKind(
594 entries: ReadonlyArray<WorkLogPresentationEntry>,
595): ToolGroupSummaryKind {
596 const actions = new Set(entries.map(toolGroupAction));
597 if (actions.size !== 1) return "mixed";
598 const action = actions.values().next().value!;
599 if (action !== "other") return action;
600 const fallbackKinds = new Set(
601 entries.map((entry): ToolGroupSummaryKind => {
602 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
603 if (entry.itemType === "subagent") return "agent-tool";
604 if (entry.tone === "thinking") return "agent-tool";
605 if (entry.tone === "tool") return "tone-tool";
606 return "other";
607 }),
608 );
609 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";