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