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

presentation.ts

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