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

presentation.ts

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