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

presentation.ts

741 lines26.9 KB

1import {
2 isToolLifecycleItemType,
3 type AssetResource,
4 type RuntimeItemStatus,
5 type ToolActivitySource,
6 type ToolActivitySurface,
7 type ToolActivityIcon,
8 type OrchestrationV2TurnItem,
9 type ThreadId,
10} from "@t3tools/contracts";
11import {
12 resolveT3McpToolSummaryAction,
13 type T3McpToolSummaryAction,
14} from "@t3tools/shared/t3McpToolPresentation";
15import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
16import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
17import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
18import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
19import { formatTokens } from "@t3tools/shared/usageFormat";
20import { toolOutputIndicatesFailure } from "@t3tools/shared/toolOutput";
21​
22import {
23 summarizeT3ToolCalls,
24 type T3ToolSummaryCall,
25} from "@t3tools/client-runtime/t3ToolSummary";
26​
27export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped" | "idle";
28​
29/** Inspection and copying omit raw outputs, including values from older caches. */
30export function toolItemForDisplay(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
31 switch (item.type) {
32 case "command_execution":
33 case "dynamic_tool": {
34 const { output: _output, ...displayItem } = item;
35 return displayItem;
36 }
37 case "file_change": {
38 const { diffStr: _diffStr, oldStr: _oldStr, newStr: _newStr, ...displayItem } = item;
39 return displayItem;
40 }
41 default:
42 return item;
43 }
45​
46export function contextCompactionLabel(
47 item: Pick<
48 Extract<OrchestrationV2TurnItem, { type: "compaction" }>,
49 "status" | "beforeTokenCount" | "afterTokenCount"
50 >,
51): string {
52 if (item.status === "running") return "Compacting context";
53 if (item.beforeTokenCount !== undefined && item.afterTokenCount !== undefined) {
54 return `Context compacted ${formatTokens(item.beforeTokenCount)} → ${formatTokens(item.afterTokenCount)} tokens`;
55 }
56 return "Context compacted";
58​
59export interface WorkLogPresentationEntry {
60 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
61 readonly id: string;
62 readonly createdAt: string;
63 readonly label: string;
64 readonly tone: "thinking" | "tool" | "info" | "error";
65 readonly command?: string;
66 readonly rawCommand?: string;
67 readonly detail?: string;
68 readonly viewedImagePath?: string;
69 readonly changedFiles?: ReadonlyArray<string>;
70 readonly toolTitle?: string;
71 readonly toolData?: unknown;
72 readonly requestKind?: string;
73 readonly itemType?: OrchestrationV2TurnItem["type"];
74 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
75 readonly structuredPayload?: OrchestrationV2TurnItem;
76 readonly toolSource?: ToolActivitySource;
77 readonly toolSurface?: ToolActivitySurface;
78 readonly toolIcon?: ToolActivityIcon;
80​
81export type ToolGroupAction =
82 | "link-pr"
83 | "unlink-pr"
84 | "list-prs"
85 | "read"
86 | "edit"
87 | "command"
88 | "thread-create"
89 | "browser"
90 | "device"
91 | "code-search"
92 | "search"
93 | "other"
94 | "update";
95​
96export type ToolGroupSummaryKind =
97 | "pull-request"
98 | ToolGroupAction
99 | "dynamic-tool"
100 | "reasoning"
101 | "agent-tool"
102 | "tone-tool"
103 | "mixed";
104​
105export function normalizeCompactToolLabel(value: string): string {
106 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
108​
109const T3_MCP_TOOL_LABELS: Record<
110 string,
111 readonly [action: string, running: string, completed: string, detail: string]
112> = {
113 link_pull_request: ["Link", "Linking", "Linked", "a pull request"],
114 unlink_pull_request: ["Unlink", "Unlinking", "Unlinked", "a pull request"],
115 list_thread_pull_requests: ["Check", "Checking", "Checked", "linked pull requests"],
116 orchestrator_capabilities: ["Get", "Getting", "Got", "orchestration capabilities"],
117 delegate_task: ["Delegate", "Delegating", "Delegated", "a child task"],
118 task_status: ["Get", "Getting", "Got", "delegated task status"],
119 task_cancel: ["Cancel", "Canceling", "Canceled", "delegated task"],
120 schedule_task: ["Schedule", "Scheduling", "Scheduled", "a recurring task"],
121 list_scheduled_tasks: ["List", "Listing", "Listed", "scheduled tasks"],
122 update_scheduled_task: ["Update", "Updating", "Updated", "a scheduled task"],
123 delete_scheduled_task: ["Delete", "Deleting", "Deleted", "a scheduled task"],
124 create_threads: ["Create", "Creating", "Created", "T3 threads"],
125 t3_thread_start: ["Start", "Starting", "Started", "a T3 thread"],
126 t3_thread_list: ["List", "Listing", "Listed", "T3 threads"],
127 t3_thread_read: ["Read", "Reading", "Read", "a T3 thread"],
128 t3_thread_send: ["Send", "Sending", "Sent", "to a T3 thread"],
129 t3_thread_wait: ["Wait", "Waiting", "Waited", "for a T3 thread"],
130 t3_thread_interrupt: ["Interrupt", "Interrupting", "Interrupted", "a T3 thread"],
131 t3_worktree_handoff: ["Hand off", "Handing off", "Handed off", "thread to a git worktree"],
132 t3_worktree_status: ["Get", "Getting", "Got", "thread worktree status"],
133 preview_status: ["Get", "Getting", "Got", "preview browser status"],
134 preview_open: ["Open", "Opening", "Opened", "a page in the preview browser"],
135 preview_navigate: ["Navigate", "Navigating", "Navigated", "the preview browser"],
136 preview_snapshot: [
137 "Take a snapshot of",
138 "Taking a snapshot of",
139 "Took a snapshot of",
140 "the preview page",
141 ],
142 preview_click: ["Click", "Clicking", "Clicked", "in the preview browser"],
143 preview_press: ["Press", "Pressing", "Pressed", "a key in the preview browser"],
144 preview_type: ["Type", "Typing", "Typed", "in the preview browser"],
145 preview_scroll: ["Scroll", "Scrolling", "Scrolled", "the preview browser"],
146 preview_resize: ["Resize", "Resizing", "Resized", "the preview browser"],
147 preview_evaluate: ["Evaluate", "Evaluating", "Evaluated", "script in the preview browser"],
148 preview_wait_for: ["Wait", "Waiting", "Waited", "for the preview page"],
149 preview_set_appearance: ["Set", "Setting", "Set", "preview browser appearance"],
150 preview_recording_start: ["Start", "Starting", "Started", "recording the preview browser"],
151 preview_recording_stop: ["Stop", "Stopping", "Stopped", "recording the preview browser"],
152 device_list: ["List", "Listing", "Listed", "simulators and emulators"],
153 device_open: ["Open", "Opening", "Opened", "a device in the Device panel"],
154 device_screenshot: [
155 "Take a screenshot of",
156 "Taking a screenshot of",
157 "Took a screenshot of",
158 "the device",
159 ],
160 device_close: ["Close", "Closing", "Closed", "a device"],
161};
162​
163const PR_TOOL_ACTIONS: Readonly<Record<string, ToolGroupAction>> = {
164 link_pull_request: "link-pr",
165 unlink_pull_request: "unlink-pr",
166 list_thread_pull_requests: "list-prs",
167};
168​
169function resolveT3McpToolPresentation(
170 value: string | undefined,
171 status: string | undefined,
172 data?: unknown,
173) {
174 if (!value) return null;
175 const name = normalizeCompactToolLabel(value).replace(
176 /^(?:mcp__(?:t3-code|t3_code|t3code)__|(?:t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*))/i,
177 "",
178 );
179 if (!Object.hasOwn(T3_MCP_TOOL_LABELS, name)) return null;
180​
181 const [action, running, completed, detail] = T3_MCP_TOOL_LABELS[name]!;
182 const verb =
183 status === "inProgress"
184 ? running
185 : status === "completed"
186 ? completed
187 : status === "failed"
188 ? `Failed to ${action.toLowerCase()}`
189 : status === "declined"
190 ? `Declined to ${action.toLowerCase()}`
191 : status === "stopped"
192 ? `Stopped ${running.toLowerCase()}`
193 : running;
194​
195 const actionKind = Object.hasOwn(PR_TOOL_ACTIONS, name) ? PR_TOOL_ACTIONS[name] : undefined;
196 const payload = asRecord(data);
197 const input =
198 asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
199 const urlTarget = typeof input?.url === "string" ? parseChangeRequestUrl(input.url) : null;
200 const number = urlTarget?.number ?? input?.number;
201 const target =
202 actionKind !== undefined &&
203 actionKind !== "list-prs" &&
204 typeof number === "number" &&
205 Number.isSafeInteger(number) &&
206 number > 0
207 ? `PR #${number}`
208 : detail;
209 return {
210 displayName: `${verb} ${target}`,
211 icon:
212 actionKind !== undefined
213 ? ("pull-request" as const)
214 : name.startsWith("preview_")
215 ? ("browser" as const)
216 : name.startsWith("device_")
217 ? ("device" as const)
218 : ("t3-code" as const),
219 ...(actionKind === undefined ? {} : { action: actionKind }),
220 };
222​
223/** Only active or completed calls can inherit the live group’s present tense. */
224export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
225 if (status === "failed" || status === "declined" || status === "stopped" || status === "idle") {
226 return status;
227 }
228 if (presentTense || status === "inProgress") return "inProgress";
229 return "completed";
231​
232/** Resolves tool identity before choosing labels or icons in either client. */
233export function resolveWorkEntryToolPresentation(
234 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "toolLifecycleStatus">,
235 fallbackStatus?: "inProgress" | "completed",
236) {
237 const status = entry.toolLifecycleStatus ?? fallbackStatus;
238 const data = entry.toolData;
239 if (data !== null && typeof data === "object") {
240 if (
241 "server" in data &&
242 typeof data.server === "string" &&
243 "tool" in data &&
244 typeof data.tool === "string"
245 ) {
246 return resolveT3McpToolPresentation(`${data.server}.${data.tool}`, status, data);
247 }
248 if ("toolName" in data && typeof data.toolName === "string") {
249 return resolveT3McpToolPresentation(data.toolName, status, data);
250 }
251 }
252​
253 return (
254 resolveT3McpToolPresentation(entry.toolTitle, status, data) ??
255 resolveT3McpToolPresentation(entry.label, status, data)
256 );
258​
259function asRecord(value: unknown): Record<string, unknown> | null {
260 return value !== null && typeof value === "object" && !Array.isArray(value)
261 ? (value as Record<string, unknown>)
262 : null;
264​
265function nonEmptyString(value: unknown): string | null {
266 return typeof value === "string" && value.trim().length > 0 ? value : null;
268​
269function commandResultContent(value: unknown): string | null {
270 const direct = nonEmptyString(value);
271 if (direct) return direct;
272​
273 const directContent = Array.isArray(value) ? value : null;
274 const record = asRecord(value);
275 const content = record?.content;
276 const contentText = nonEmptyString(content);
277 if (contentText) return contentText;
278 const blocks = directContent ?? (Array.isArray(content) ? content : null);
279 if (!blocks) return null;
280​
281 const chunks = blocks.flatMap((entry) => {
282 const text = nonEmptyString(entry) ?? nonEmptyString(asRecord(entry)?.text);
283 return text ? [text] : [];
284 });
285 return chunks.length > 0 ? chunks.join("\n") : null;
287​
288/** Returns provider command output before it is formatted for a work-log row. */
289export function extractCommandOutputText(dataValue: unknown): string | null {
290 const data = asRecord(dataValue);
291 const item = asRecord(data?.item);
292 const itemResult = asRecord(item?.result);
293 const rawOutput = asRecord(data?.rawOutput);
294 const outputStreams = [
295 nonEmptyString(rawOutput?.stdout),
296 nonEmptyString(rawOutput?.stderr),
297 ].filter((value): value is string => value !== null);
298 const acpContent = Array.isArray(data?.content)
299 ? data.content
300 .flatMap((entryValue) => {
301 const entry = asRecord(entryValue);
302 const content = asRecord(entry?.content);
303 const text = entry?.type === "content" ? nonEmptyString(content?.text) : null;
304 return text ? [text] : [];
305 })
306 .join("\n")
307 : null;
308​
309 const candidates = [
310 item?.aggregatedOutput,
311 itemResult?.content,
312 data?.rawOutput,
313 rawOutput?.content,
314 outputStreams.length > 0 ? outputStreams.join("\n") : null,
315 rawOutput?.output,
316 acpContent,
317 data?.result,
318 ];
319 for (const candidate of candidates) {
320 const text = commandResultContent(candidate);
321 if (text) return text;
322 }
323 return null;
325​
326/**
327 * Ingestion caps tool details at 180 chars and appends "...", so a long command
328 * echo no longer equals the command it repeats. Treat a truncated prefix of the
329 * command as the same echo.
330 */
331function textRepeatsCommand(text: string, commands: ReadonlyArray<string | null>): boolean {
332 const truncated = text.endsWith("...")
333 ? text.slice(0, -3)
334 : text.endsWith("\u2026")
335 ? text.slice(0, -1)
336 : null;
337 return commands.some((candidate) => {
338 const command = candidate?.trim();
339 if (!command) return false;
340 if (command === text) return true;
341 return (
342 truncated !== null &&
343 truncated.length > 0 &&
344 command.length > truncated.length &&
345 command.startsWith(truncated)
346 );
347 });
349​
350/**
351 * Decides whether a command row's `detail` is a synthetic echo of the command
352 * rather than real output. OpenCode stores completed output in `detail` with no
353 * other output channel, so plain equality is only treated as synthetic when the
354 * payload shape shows the detail came from the command: Codex item metadata,
355 * an ACP tool call (`data.toolCallId`, `kind: "execute"`), a Claude tool-name
356 * prefix, or no structured command at all.
357 */
358export function commandDetailRepeatsCommand(input: {
359 readonly detail: string;
360 readonly command: string | null;
361 readonly rawCommand: string | null;
362 readonly toolName: unknown;
363 readonly data: unknown;
364}): boolean {
365 const toolName = nonEmptyString(input.toolName)?.trim();
366 const detail = input.detail.trim();
367 const commands = [input.command, input.rawCommand];
368 if (toolName) {
369 const prefix = `${toolName}:`;
370 if (detail.toLowerCase().startsWith(prefix.toLowerCase())) {
371 const unprefixed = detail.slice(prefix.length).trim();
372 if (textRepeatsCommand(unprefixed, commands)) return true;
373 }
374 }
375​
376 if (!textRepeatsCommand(detail, commands)) return false;
377​
378 const data = asRecord(input.data);
379 const item = asRecord(data?.item);
380 const itemInput = asRecord(item?.input);
381 const itemResult = asRecord(item?.result);
382 const hasStructuredCommand = [
383 item?.command,
384 itemInput?.command,
385 itemResult?.command,
386 data?.command,
387 ].some((value) =>
388 Array.isArray(value)
389 ? value.some((part) => nonEmptyString(part) !== null)
390 : nonEmptyString(value) !== null,
391 );
392 return (
393 !hasStructuredCommand ||
394 item !== null ||
395 data?.toolCallId !== undefined ||
396 nonEmptyString(data?.kind)?.toLowerCase() === "execute"
397 );
399​
400function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
401 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
402 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
403 if (entry.requestKind !== undefined) return true;
404 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
406​
407function workEntryIndicatesToolFailureFromOutput(
408 entry: WorkLogPresentationEntry,
409 includeCommand: boolean,
410): boolean {
411 if (
412 entry.tone === "error" ||
413 entry.toolLifecycleStatus === "failed" ||
414 entry.toolLifecycleStatus === "declined"
415 ) {
416 return true;
417 }
418 if (!workLogEntryIsToolLike(entry)) return false;
419 const item = entry.structuredPayload;
420 if (item?.type === "command_execution") {
421 if (item.outputIndicatesFailure || (item.exitCode !== undefined && item.exitCode !== 0)) {
422 return true;
423 }
424 // Older servers/caches can still carry output. Read only the previous
425 // preview-sized prefix for status, without exposing it in the row detail.
426 if (item.output && toolOutputIndicatesFailure(item.output.slice(0, 32_768))) {
427 return true;
428 }
429 }
430 const output = includeCommand
431 ? [entry.detail, entry.command].filter(Boolean).join("\n")
432 : (entry.detail ?? "");
433 return output.length > 0 && toolOutputIndicatesFailure(output);
435​
436/** Includes legacy activities that stored error output in the command field. */
437export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
438 return workEntryIndicatesToolFailureFromOutput(entry, true);
440​
441/** Checks rendered output without treating the user's command as an error. */
442export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
443 return workEntryIndicatesToolFailureFromOutput(entry, false);
445​
446/** Decides whether the row can show a success marker. */
447export function workEntryIndicatesToolSuccess(entry: WorkLogPresentationEntry): boolean {
448 return (
449 workLogEntryIsToolLike(entry) &&
450 !workEntryIndicatesToolFailure(entry) &&
451 entry.tone !== "thinking" &&
452 entry.toolLifecycleStatus !== "idle" &&
453 entry.toolLifecycleStatus !== "inProgress" &&
454 entry.toolLifecycleStatus !== "stopped"
455 );
457​
458function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
459 return (
460 entry.itemType === "file_search" ||
461 (entry.itemType === "web_search" &&
462 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
463 );
465​
466export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
467 if (entry.itemType === "thread_created") return "thread-create";
468 const presentation = resolveWorkEntryToolPresentation(entry);
469 if (presentation?.action !== undefined) return presentation.action;
470 if (presentation?.icon === "browser") return "browser";
471 if (presentation?.icon === "device") return "device";
472 if (entry.requestKind === "file-read" || entry.viewedImagePath !== undefined) return "read";
473 if (
474 entry.itemType === "dynamic_tool" &&
475 /^read(?:\s+file)?$/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
476 ) {
477 return "read";
478 }
479 if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
480 if (entry.itemType === "command_execution" || entry.command) return "command";
481 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
482 if (entry.itemType === "web_search") return "search";
483 return workLogEntryIsToolLike(entry) ? "other" : "update";
485​
486export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
487 const viewedImagePath = entry.viewedImagePath?.trim();
488 if (
489 viewedImagePath !== undefined &&
490 !/[\r\n]/.test(viewedImagePath) &&
491 isWorkspaceImagePreviewPath(viewedImagePath)
492 ) {
493 return viewedImagePath;
494 }
495 const detail = entry.detail?.trim();
496 return toolGroupAction(entry) === "read" &&
497 detail !== undefined &&
498 !/[\r\n]/.test(detail) &&
499 isWorkspaceImagePreviewPath(detail)
500 ? detail
501 : null;
503​
504export interface ViewedImageAsset {
505 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
506 readonly alt: string;
507 readonly srcFragment: string;
509​
510export function resolveViewedImageAsset(
511 source: string,
512 input: {
513 readonly threadId: ThreadId;
514 readonly workspaceRoot?: string | null | undefined;
515 },
516): ViewedImageAsset | null {
517 // A relative path with no known workspace still names a media-file relative
518 // to the thread's workspace, so classify against "." and drop the prefix.
519 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
520 if (imageSource._tag !== "WorkspaceFile") return null;
521 const resolvedFilePath =
522 input.workspaceRoot == null && imageSource.path.startsWith("./")
523 ? imageSource.path.slice(2)
524 : imageSource.path;
525​
526 const media = resolveMediaSource(source, {
527 threadId: input.threadId,
528 workspaceRoot: input.workspaceRoot,
529 resolvedFilePath,
530 });
531 if (media === null || media.access !== "environment") return null;
532 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
534​
535function toolGroupActionCount(
536 action: ToolGroupAction,
537 entries: ReadonlyArray<WorkLogPresentationEntry>,
538): number {
539 if (action !== "edit") return entries.length;
540 const changedFiles = new Set<string>();
541 let editsWithoutFileDetails = 0;
542 for (const entry of entries) {
543 if (!entry.changedFiles || entry.changedFiles.length === 0) {
544 editsWithoutFileDetails += 1;
545 } else {
546 for (const file of entry.changedFiles) changedFiles.add(file);
547 }
548 }
549 return changedFiles.size + editsWithoutFileDetails;
551​
552function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
553 switch (action) {
554 case "link-pr":
555 return `Linked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
556 case "unlink-pr":
557 return `Unlinked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
558 case "list-prs":
559 return count === 1
560 ? "Checked linked pull requests"
561 : `Checked linked pull requests ${count} times`;
562 case "read":
563 return `Read ${count} ${count === 1 ? "file" : "files"}`;
564 case "edit":
565 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
566 case "command":
567 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
568 case "thread-create":
569 return `Created ${count} ${count === 1 ? "thread" : "threads"}`;
570 case "device":
571 return `Used device controls ${count} ${count === 1 ? "time" : "times"}`;
572 case "browser":
573 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
574 case "search":
575 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
576 case "code-search":
577 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
578 case "other":
579 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
580 case "update":
581 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
582 }
584​
585function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
586 const item = entry.structuredPayload;
587 const data =
588 entry.toolData !== null && typeof entry.toolData === "object"
589 ? (entry.toolData as Record<string, unknown>)
590 : undefined;
591 return {
592 input: item?.type === "dynamic_tool" ? item.input : data?.input,
593 output: item?.type === "dynamic_tool" ? item.output : data?.output,
594 outcome:
595 entry.toolLifecycleStatus === "failed" ||
596 entry.toolLifecycleStatus === "declined" ||
597 entry.tone === "error"
598 ? "failed"
599 : entry.toolLifecycleStatus === "completed"
600 ? "completed"
601 : "unfinished",
602 };
604​
605function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
606 switch (action) {
607 case "command":
608 case "edit":
609 case "delegate":
610 case "task-cancel":
611 case "thread-create":
612 case "thread-send":
613 case "thread-interrupt":
614 case "schedule-create":
615 case "schedule-update":
616 case "schedule-delete":
617 return 0;
618 case "other":
619 case "update":
620 return 2;
621 default:
622 return 1;
623 }
625​
626/** Summarizes at most two action categories; every omitted call still counts in the remainder. */
627export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): {
628 summary: string;
629 hasFailure: boolean;
630} {
631 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
632 if (entries.length > 0 && toolEntries.length === 0) {
633 return {
634 summary: entries.length === 1 ? "Thought" : `Thought (×${entries.length})`,
635 hasFailure: false,
636 };
637 }
638 entries = toolEntries;
639 const groups = new Map<
640 ToolGroupAction | T3McpToolSummaryAction,
641 {
642 action: ToolGroupAction;
643 t3Action: T3McpToolSummaryAction | null;
644 entries: WorkLogPresentationEntry[];
645 }
646 >();
647 const sources = new Map<string, ToolActivitySource>();
648 for (const entry of entries) {
649 if (entry.toolSource && resolveWorkEntryToolPresentation(entry)?.icon !== "pull-request") {
650 sources.set(entry.toolSource.key, entry.toolSource);
651 continue;
652 }
653 const item = entry.structuredPayload;
654 const t3Action = resolveT3McpToolSummaryAction(
655 (item?.type === "dynamic_tool" ? item.toolName : null) ?? entry.toolTitle ?? entry.label,
656 );
657 const action = toolGroupAction(entry);
658 const key = t3Action ?? action;
659 const group = groups.get(key);
660 if (group) group.entries.push(entry);
661 else groups.set(key, { action, t3Action, entries: [entry] });
662 }
663 const summaries = [...groups].map(([action, group], index) => ({
664 index,
665 count: group.entries.length,
666 priority: summaryActionPriority(action),
667 ...(group.t3Action
668 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall))
669 : {
670 label: toolGroupActionLabel(
671 group.action,
672 toolGroupActionCount(group.action, group.entries),
673 ),
674 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
675 }),
676 }));
677 const selected = [...summaries]
678 .sort((a, b) => a.priority - b.priority || a.index - b.index)
679 .slice(0, 2)
680 .sort((a, b) => a.index - b.index);
681 const labels = selected.map(({ label }) => label);
682 if (sources.size > 0) {
683 const sourceValues = [...sources.values()];
684 const sourceNames = sourceValues.map((source) => source.name);
685 const formattedNames =
686 sourceNames.length < 2
687 ? sourceNames[0]!
688 : sourceNames.length === 2
689 ? sourceNames.join(" and ")
690 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
691 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
692 labels.unshift(
693 `Used ${formattedNames}${allIntegrations ? ` ${sources.size === 1 ? "integration" : "integrations"}` : ""}`,
694 );
695 }
696 const sourcedCount = entries.filter(
697 (entry) =>
698 entry.toolSource !== undefined &&
699 resolveWorkEntryToolPresentation(entry)?.icon !== "pull-request",
700 ).length;
701 const remainingCount =
702 entries.length - sourcedCount - selected.reduce((count, group) => count + group.count, 0);
703 if (remainingCount > 0) {
704 labels.push(`Performed ${remainingCount} other ${remainingCount === 1 ? "action" : "actions"}`);
705 }
706 const sentenceLabels = labels.map((label, index) =>
707 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
708 );
709 const summary =
710 sentenceLabels.length < 3
711 ? sentenceLabels.join(" and ")
712 : `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
713 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
715​
716export function toolGroupSummaryKind(
717 entries: ReadonlyArray<WorkLogPresentationEntry>,
718): ToolGroupSummaryKind {
719 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
720 if (entries.length > 0 && toolEntries.length === 0) return "reasoning";
721 entries = toolEntries;
722 if (
723 entries.length > 0 &&
724 entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
725 )
726 return "pull-request";
727 const actions = new Set(entries.map(toolGroupAction));
728 if (actions.size !== 1) return "mixed";
729 const action = actions.values().next().value!;
730 if (action !== "other") return action;
731 const fallbackKinds = new Set(
732 entries.map((entry): ToolGroupSummaryKind => {
733 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
734 if (entry.itemType === "subagent") return "agent-tool";
735 if (entry.tone === "thinking") return "agent-tool";
736 if (entry.tone === "tool") return "tone-tool";
737 return "other";
738 }),
739 );
740 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";