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