Open History to see the last commit
1import {
2 isOrchestrationV2WorkActive,
3 isToolLifecycleItemType,
4 type AssetResource,
5 type RuntimeItemStatus,
6 type ToolActivitySource,
7 type ToolActivitySurface,
8 type ToolActivityIcon,
9 type OrchestrationV2TurnItem,
10 type ThreadId,
11} from "@t3tools/contracts";
12import type { ToolCallVisibility } from "@t3tools/contracts/settings";
13import {
14 resolveT3McpSummaryAction,
15 resolveT3McpToolDefinition,
16 type T3McpToolDefinition,
17 type T3McpToolSummaryAction,
18} from "@t3tools/shared/t3McpToolPresentation";
19import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
20import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
21import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
22import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview";
23import { formatTokens } from "@t3tools/shared/usageFormat";
24import { classifyToolActivity } from "@t3tools/shared/toolActivity";
25import { toolOutputIndicatesFailure } from "@t3tools/shared/toolOutput";
26
27import {
28 summarizeT3ToolCalls,
29 t3ToolOutcomeLabel,
30 t3ToolResultIndicatesFailure,
31 type T3ToolSummaryCall,
32} from "@t3tools/client-runtime/t3ToolSummary";
33import { mFallback, msg } from "gt-i18n";
34import { t3ToolSentence } from "./t3ToolSentences.ts";
35import type { MFunctionType } from "gt-i18n/types";
36
37export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped" | "idle";
38
39export function toolItemForDisplay(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
40 switch (item.type) {
41 case "command_execution":
42 case "dynamic_tool": {
43 const { output: _output, ...displayItem } = item;
44 return displayItem;
45 }
46 case "file_change": {
47 const { diffStr, oldStr: _oldStr, newStr: _newStr, ...displayItem } = item;
48 // A failed edit's diffStr holds the provider's error, not a diff.
49 return item.status === "failed" && diffStr?.trim()
50 ? { ...displayItem, diffStr }
51 : displayItem;
52 }
53 default:
54 return item;
55 }
56}
57
58type CompactionLabelItem = Pick<
59 Extract<OrchestrationV2TurnItem, { type: "compaction" }>,
60 "status" | "beforeTokenCount" | "afterTokenCount"
61>;
62
63export function contextCompactionTokenCounts(
64 item: CompactionLabelItem,
65): { readonly before: string; readonly after: string } | null {
66 if (
67 item.status === "running" ||
68 item.beforeTokenCount === undefined ||
69 item.afterTokenCount === undefined
70 ) {
71 return null;
72 }
73 return { before: formatTokens(item.beforeTokenCount), after: formatTokens(item.afterTokenCount) };
74}
75
76export function contextCompactionLabel(
77 item: CompactionLabelItem,
78 resolve: MFunctionType = mFallback,
79): string {
80 if (item.status === "failed") return resolve(msg("Context compaction failed"));
81 if (item.status === "cancelled" || item.status === "interrupted")
82 return resolve(msg("Context compaction stopped"));
83 if (isOrchestrationV2WorkActive(item.status)) return resolve(msg("Compacting context"));
84 const tokens = contextCompactionTokenCounts(item);
85 return tokens
86 ? resolve(msg("Context compacted {before} → {after} tokens", tokens))
87 : resolve(msg("Context compacted"));
88}
89
90export interface WorkLogPresentationEntry {
91 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
92 readonly id: string;
93 readonly createdAt: string;
94 readonly label: string;
95 readonly tone: "thinking" | "tool" | "info" | "error";
96 readonly command?: string;
97 readonly rawCommand?: string;
98 readonly detail?: string;
99 readonly viewedImagePath?: string;
100 readonly changedFiles?: ReadonlyArray<string>;
101 readonly toolTitle?: string;
102 readonly toolData?: unknown;
103 readonly requestKind?: string;
104 readonly itemType?: OrchestrationV2TurnItem["type"];
105 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
106 readonly structuredPayload?: OrchestrationV2TurnItem;
107 readonly toolSource?: ToolActivitySource;
108 readonly toolSurface?: ToolActivitySurface;
109 readonly toolIcon?: ToolActivityIcon;
110}
111
112export type ToolGroupAction =
113 | "link-pr"
114 | "unlink-pr"
115 | "list-prs"
116 | "watch-pr"
117 | "unwatch-pr"
118 | "read"
119 | "edit"
120 | "command"
121 | "thread-create"
122 | "browser"
123 | "device"
124 | "code-search"
125 | "search"
126 | "other"
127 | "update";
128
129export type ToolGroupSummaryKind =
130 | "pull-request"
131 | ToolGroupAction
132 | "dynamic-tool"
133 | "reasoning"
134 | "agent-tool"
135 | "tone-tool"
136 | "mixed";
137
138export function normalizeCompactToolLabel(value: string): string {
139 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
140}
141
142function workEntryToolName(
143 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "structuredPayload">,
144): string | undefined {
145 const item = entry.structuredPayload;
146 if (item?.type === "dynamic_tool" && item.toolName) return item.toolName;
147 const data = asRecord(entry.toolData);
148 if (typeof data?.server === "string" && typeof data.tool === "string") {
149 return `${data.server}.${data.tool}`;
150 }
151 if (typeof data?.toolName === "string") return data.toolName;
152 return resolveT3McpToolDefinition(entry.toolTitle) ? entry.toolTitle : entry.label;
153}
154
155function workEntryToolInput(
156 entry: Pick<WorkLogPresentationEntry, "toolData" | "structuredPayload">,
157): unknown {
158 const item = entry.structuredPayload;
159 const data = asRecord(entry.toolData);
160 return item?.type === "dynamic_tool"
161 ? item.input
162 : (data?.arguments ?? data?.input ?? data?.rawInput);
163}
164
165function workEntryToolOutput(
166 entry: Pick<WorkLogPresentationEntry, "toolData" | "structuredPayload">,
167): unknown {
168 const item = entry.structuredPayload;
169 const data = asRecord(entry.toolData);
170 return item?.type === "dynamic_tool"
171 ? item.output
172 : (data?.output ?? data?.result ?? data?.rawOutput ?? data?.content);
173}
174
175function t3ToolStatusKey(status: string | undefined) {
176 return status === "inProgress" ||
177 status === "completed" ||
178 status === "failed" ||
179 status === "declined" ||
180 status === "stopped"
181 ? status
182 : "other";
183}
184
185function resolveT3McpToolPresentation(
186 definition: T3McpToolDefinition | null,
187 status: string | undefined,
188 data: unknown,
189 resolve: MFunctionType,
190) {
191 if (!definition) return null;
192 const detail = definition.labels[3];
193
194 const actionKind =
195 definition.summaryAction === "link-pr" ||
196 definition.summaryAction === "unlink-pr" ||
197 definition.summaryAction === "list-prs" ||
198 definition.summaryAction === "watch-pr" ||
199 definition.summaryAction === "unwatch-pr"
200 ? definition.summaryAction
201 : undefined;
202 const payload = asRecord(data);
203 const input =
204 asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
205 const urlTarget =
206 typeof input?.url === "string" ? sourceControlClients.parseChangeRequestUrl(input.url) : null;
207 const number = urlTarget?.link.number ?? input?.number;
208 const { shortLabel } = (urlTarget?.definition ?? sourceControlClients.get(undefined))
209 .changeRequest;
210 const pullRequestNumber =
211 actionKind !== undefined &&
212 actionKind !== "list-prs" &&
213 typeof number === "number" &&
214 Number.isSafeInteger(number) &&
215 number > 0
216 ? number
217 : null;
218 const sentence = t3ToolSentence(definition.labels);
219 const statusKey = t3ToolStatusKey(status);
220 // A tool added to the shared table after `t3ToolSentences.ts` was generated.
221 const [action, running, completed] = definition.labels;
222 const fallbackVerb =
223 status === "inProgress"
224 ? running
225 : status === "completed"
226 ? completed
227 : status === "failed"
228 ? `Failed to ${action.toLowerCase()}`
229 : status === "declined"
230 ? `Declined to ${action.toLowerCase()}`
231 : status === "stopped"
232 ? `Stopped ${running.toLowerCase()}`
233 : running;
234 const displayName =
235 sentence === undefined
236 ? `${fallbackVerb} ${pullRequestNumber === null ? detail : `${shortLabel} #${pullRequestNumber}`}`
237 : pullRequestNumber !== null && sentence.changeRequest !== undefined
238 ? resolve(sentence.changeRequest, {
239 status: statusKey,
240 changeRequest: shortLabel,
241 number: String(pullRequestNumber),
242 })
243 : resolve(sentence.detail, { status: statusKey });
244 return {
245 displayName,
246 icon: definition.icon,
247 ...(actionKind === undefined ? {} : { action: actionKind }),
248 };
249}
250
251export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
252 if (status === "failed" || status === "declined" || status === "stopped" || status === "idle") {
253 return status;
254 }
255 if (presentTense || status === "inProgress") return "inProgress";
256 return "completed";
257}
258
259export function genericCommandStatusLabel(
260 status: ReturnType<typeof liveActivityToolStatus>,
261 resolve: MFunctionType = mFallback,
262) {
263 return resolve(
264 status === "inProgress"
265 ? msg("Running command")
266 : status === "failed"
267 ? msg("Failed command")
268 : status === "declined"
269 ? msg("Declined command")
270 : status === "stopped"
271 ? msg("Stopped command")
272 : msg("Ran command"),
273 );
274}
275
276const GENERIC_COMMAND_TITLES = new Set(["Ran command", "Run command", "Command"]);
277
278export function commandlessCommandLabel(
279 entry: Pick<
280 WorkLogPresentationEntry,
281 "itemType" | "command" | "toolTitle" | "label" | "structuredPayload"
282 >,
283 status: ReturnType<typeof liveActivityToolStatus>,
284 resolve: MFunctionType = mFallback,
285): string | null {
286 if (entry.itemType !== "command_execution" || entry.command?.trim()) return null;
287 // The provider's own title, before a client substitutes its translated fallback.
288 const title = (
289 entry.structuredPayload ? entry.structuredPayload.title : entry.toolTitle || entry.label
290 )?.trim();
291 return !title || GENERIC_COMMAND_TITLES.has(normalizeCompactToolLabel(title))
292 ? genericCommandStatusLabel(status, resolve)
293 : null;
294}
295
296export function resolveWorkEntryToolPresentation(
297 entry: Pick<
298 WorkLogPresentationEntry,
299 "label" | "toolTitle" | "toolData" | "toolLifecycleStatus" | "structuredPayload"
300 >,
301 fallbackStatus?: "inProgress" | "completed",
302 resolve: MFunctionType = mFallback,
303) {
304 const definition = resolveT3McpToolDefinition(
305 workEntryToolName(entry),
306 workEntryToolInput(entry),
307 );
308 const output = workEntryToolOutput(entry);
309 const failed = definition !== null && t3ToolResultIndicatesFailure(output);
310 const status = entry.toolLifecycleStatus ?? fallbackStatus;
311 const presentation = resolveT3McpToolPresentation(
312 definition,
313 failed ? "failed" : status,
314 entry.toolData,
315 resolve,
316 );
317 if (definition === null || presentation === null || failed || status !== "completed") {
318 return presentation;
319 }
320 const outcomeLabel = t3ToolOutcomeLabel(
321 definition.summaryAction,
322 { input: workEntryToolInput(entry), output, outcome: "completed" },
323 resolve,
324 );
325 return outcomeLabel === undefined ? presentation : { ...presentation, displayName: outcomeLabel };
326}
327
328function asRecord(value: unknown): Record<string, unknown> | null {
329 return value !== null && typeof value === "object" && !Array.isArray(value)
330 ? (value as Record<string, unknown>)
331 : null;
332}
333
334function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
335 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
336 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
337 if (entry.requestKind !== undefined) return true;
338 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
339}
340
341function workEntryIndicatesToolFailureFromOutput(
342 entry: WorkLogPresentationEntry,
343 includeCommand: boolean,
344): boolean {
345 if (
346 entry.tone === "error" ||
347 entry.toolLifecycleStatus === "failed" ||
348 entry.toolLifecycleStatus === "declined"
349 ) {
350 return true;
351 }
352 // Reasoning detail is the model's own prose (often tens of KB), not tool
353 // output: scanning it is slow on long threads and misreads phrases like
354 // "that exit code 2 is expected" as a failed tool.
355 if (!workLogEntryIsToolLike(entry) || entry.itemType === "reasoning") return false;
356 if (
357 resolveT3McpToolDefinition(workEntryToolName(entry)) &&
358 t3ToolResultIndicatesFailure(workEntryToolOutput(entry))
359 ) {
360 return true;
361 }
362 const item = entry.structuredPayload;
363 if (item?.type === "command_execution") {
364 // The exit code outranks text in the output or the command itself.
365 if (item.exitCode !== undefined) return item.exitCode !== 0;
366 if (item.outputIndicatesFailure) return true;
367 if (item.output && toolOutputIndicatesFailure(item.output.slice(0, 32_768))) {
368 return true;
369 }
370 }
371 const output = includeCommand
372 ? [entry.detail, entry.command].filter(Boolean).join("\n")
373 : (entry.detail ?? "");
374 return output.length > 0 && toolOutputIndicatesFailure(output);
375}
376
377// Rows are re-derived on every timeline update but entries are reused while
378// their item is unchanged, so these per-entry checks are computed once.
379const entryChecks = new WeakMap<
380 WorkLogPresentationEntry,
381 { failure?: boolean; displayFailure?: boolean; action?: ToolGroupAction }
382>();
383
384function checksFor(entry: WorkLogPresentationEntry) {
385 let checks = entryChecks.get(entry);
386 if (!checks) {
387 checks = {};
388 entryChecks.set(entry, checks);
389 }
390 return checks;
391}
392
393export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
394 return (checksFor(entry).failure ??= workEntryIndicatesToolFailureFromOutput(entry, true));
395}
396
397export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
398 return (checksFor(entry).displayFailure ??= workEntryIndicatesToolFailureFromOutput(
399 entry,
400 false,
401 ));
402}
403
404const HIDEABLE_TOOL_CALL_ITEM_TYPES: ReadonlySet<WorkLogPresentationEntry["itemType"]> = new Set([
405 "command_execution",
406 "file_change",
407 "file_search",
408 "web_search",
409 "dynamic_tool",
410]);
411
412export function workEntryHiddenByToolCallVisibility(
413 entry: WorkLogPresentationEntry,
414 visibility: ToolCallVisibility,
415): boolean {
416 if (visibility === "showAll" || !HIDEABLE_TOOL_CALL_ITEM_TYPES.has(entry.itemType)) return false;
417 if (visibility !== "hideSuccessful") return true;
418 return entry.toolLifecycleStatus === "completed" && !workEntryDisplayIndicatesToolFailure(entry);
419}
420
421function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
422 return (
423 entry.itemType === "file_search" ||
424 (entry.itemType === "web_search" &&
425 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
426 );
427}
428
429export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
430 return (checksFor(entry).action ??= computeToolGroupAction(entry));
431}
432
433function computeToolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
434 if (entry.itemType === "thread_created") return "thread-create";
435 const presentation = resolveWorkEntryToolPresentation(entry);
436 if (presentation?.action !== undefined) return presentation.action;
437 if (presentation?.icon === "browser") return "browser";
438 if (presentation?.icon === "device") return "device";
439 if (entry.requestKind === "file-read" || entry.viewedImagePath !== undefined) return "read";
440 if (entry.itemType === "approval_request" || entry.itemType === "user_input_request") {
441 return workLogEntryIsToolLike(entry) ? "other" : "update";
442 }
443 const data = asRecord(entry.toolData) ?? {};
444 const toolName =
445 entry.structuredPayload?.type === "dynamic_tool"
446 ? entry.structuredPayload.toolName
447 : typeof data.toolName === "string"
448 ? data.toolName
449 : entry.toolTitle;
450 const classified = classifyToolActivity({
451 itemType:
452 entry.itemType === "command_execution" ||
453 entry.itemType === "file_change" ||
454 entry.itemType === "web_search"
455 ? entry.itemType
456 : entry.itemType === "dynamic_tool"
457 ? "dynamic_tool_call"
458 : undefined,
459 title: entry.toolTitle ?? entry.label,
460 data: {
461 ...data,
462 ...(toolName ? { toolName } : {}),
463 },
464 });
465 if (classified === "read") return "read";
466 if (classified === "file_change" || entry.itemType === "file_change") return "edit";
467 if (classified === "command" || entry.itemType === "command_execution" || entry.command) {
468 return "command";
469 }
470 if (classified === "search") {
471 return entry.itemType === "web_search" && !workLogEntryIsLocalCodeSearch(entry)
472 ? "search"
473 : "code-search";
474 }
475 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
476 if (entry.itemType === "web_search") return "search";
477 if ((entry.changedFiles?.length ?? 0) > 0) return "edit";
478 return workLogEntryIsToolLike(entry) ? "other" : "update";
479}
480
481export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
482 // The file may not exist until the call runs, and an open row never retries a failed asset URL.
483 return entry.toolLifecycleStatus === "failed" || entry.toolLifecycleStatus === "inProgress"
484 ? null
485 : viewedImagePathOf(entry);
486}
487
488function viewedImagePathOf(entry: WorkLogPresentationEntry): string | null {
489 const viewedImagePath = entry.viewedImagePath?.trim();
490 if (
491 viewedImagePath !== undefined &&
492 !/[\r\n]/.test(viewedImagePath) &&
493 isWorkspaceImagePreviewPath(viewedImagePath)
494 ) {
495 return viewedImagePath;
496 }
497 const detail = entry.detail?.trim();
498 return toolGroupAction(entry) === "read" &&
499 detail !== undefined &&
500 !/[\r\n]/.test(detail) &&
501 isWorkspaceImagePreviewPath(detail)
502 ? detail
503 : null;
504}
505
506/** Distinct images the agent opened across a tool group, in viewing order. */
507export function workEntriesViewedImagePaths(
508 entries: ReadonlyArray<WorkLogPresentationEntry>,
509): string[] {
510 return workEntriesViewedImages(entries).flatMap(({ path, pending }) => (pending ? [] : path));
511}
512
513export interface ViewedImage {
514 readonly path: string;
515 /** Only running Reads opened it, so its file may not exist yet; show a placeholder, not a request. */
516 readonly pending: boolean;
517}
518
519/** {@link workEntriesViewedImagePaths}, plus the images a running Read is opening. */
520export function workEntriesViewedImages(
521 entries: ReadonlyArray<WorkLogPresentationEntry>,
522): ViewedImage[] {
523 const pendingByPath = new Map<string, boolean>();
524 for (const entry of entries) {
525 if (entry.toolLifecycleStatus === "failed") continue;
526 const path = viewedImagePathOf(entry);
527 if (path === null) continue;
528 const pending = entry.toolLifecycleStatus === "inProgress";
529 pendingByPath.set(path, (pendingByPath.get(path) ?? true) && pending);
530 }
531 return [...pendingByPath].map(([path, pending]) => ({ path, pending }));
532}
533
534export interface ViewedImageAsset {
535 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
536 readonly alt: string;
537 readonly srcFragment: string;
538}
539
540/**
541 * A tool reports the literal path it read, not a markdown destination. Escape what markdown
542 * resolution would decode or split off, so a name like Grok's `sessions/%2FUsers...` survives.
543 */
544export function viewedImageMarkdownSource(path: string): string {
545 return /^file:/i.test(path) ? path : path.replace(/[%#?]/g, encodeURIComponent);
546}
547
548export function resolveViewedImageAsset(
549 path: string,
550 input: {
551 readonly threadId: ThreadId;
552 readonly workspaceRoot?: string | null | undefined;
553 },
554): ViewedImageAsset | null {
555 const source = viewedImageMarkdownSource(path);
556 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
557 if (imageSource._tag !== "WorkspaceFile") return null;
558 const resolvedFilePath =
559 input.workspaceRoot == null && imageSource.path.startsWith("./")
560 ? imageSource.path.slice(2)
561 : imageSource.path;
562
563 const media = resolveMediaSource(source, {
564 threadId: input.threadId,
565 workspaceRoot: input.workspaceRoot,
566 resolvedFilePath,
567 });
568 if (media === null || media.access !== "environment") return null;
569 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
570}
571
572function toolGroupActionCount(
573 action: ToolGroupAction,
574 entries: ReadonlyArray<WorkLogPresentationEntry>,
575): number {
576 if (action !== "edit") return entries.length;
577 const changedFiles = new Set<string>();
578 let editsWithoutFileDetails = 0;
579 for (const entry of entries) {
580 if (!entry.changedFiles || entry.changedFiles.length === 0) {
581 editsWithoutFileDetails += 1;
582 } else {
583 for (const file of entry.changedFiles) changedFiles.add(file);
584 }
585 }
586 return changedFiles.size + editsWithoutFileDetails;
587}
588
589function toolGroupActionLabel(
590 action: ToolGroupAction,
591 count: number,
592 resolve: MFunctionType,
593): string {
594 switch (action) {
595 case "link-pr":
596 return resolve(
597 msg(
598 "{count, plural, one {Linked {count} pull request} other {Linked {count} pull requests}}",
599 {
600 count,
601 },
602 ),
603 );
604 case "unlink-pr":
605 return resolve(
606 msg(
607 "{count, plural, one {Unlinked {count} pull request} other {Unlinked {count} pull requests}}",
608 { count },
609 ),
610 );
611 case "watch-pr":
612 return resolve(
613 msg(
614 "{count, plural, one {Watching {count} pull request} other {Watching {count} pull requests}}",
615 { count },
616 ),
617 );
618 case "unwatch-pr":
619 return resolve(
620 msg(
621 "{count, plural, one {Stopped watching {count} pull request} other {Stopped watching {count} pull requests}}",
622 { count },
623 ),
624 );
625 case "list-prs":
626 return resolve(
627 msg(
628 "{count, plural, =1 {Checked linked pull requests} other {Checked linked pull requests {count} times}}",
629 { count },
630 ),
631 );
632 case "read":
633 return resolve(
634 msg("{count, plural, one {Read {count} file} other {Read {count} files}}", { count }),
635 );
636 case "edit":
637 return resolve(
638 msg("{count, plural, one {Changed {count} file} other {Changed {count} files}}", { count }),
639 );
640 case "command":
641 return resolve(
642 msg("{count, plural, one {Ran {count} command} other {Ran {count} commands}}", { count }),
643 );
644 case "thread-create":
645 return resolve(
646 msg("{count, plural, one {Created {count} thread} other {Created {count} threads}}", {
647 count,
648 }),
649 );
650 case "device":
651 return resolve(
652 msg(
653 "{count, plural, one {Used device controls {count} time} other {Used device controls {count} times}}",
654 { count },
655 ),
656 );
657 case "browser":
658 return resolve(
659 msg("{count, plural, one {Used browser {count} time} other {Used browser {count} times}}", {
660 count,
661 }),
662 );
663 case "search":
664 return resolve(
665 msg(
666 "{count, plural, one {Searched the web {count} time} other {Searched the web {count} times}}",
667 { count },
668 ),
669 );
670 case "code-search":
671 return resolve(
672 msg(
673 "{count, plural, one {Searched code {count} time} other {Searched code {count} times}}",
674 { count },
675 ),
676 );
677 case "other":
678 return resolve(
679 msg("{count, plural, one {Used {count} tool} other {Used {count} tools}}", { count }),
680 );
681 case "update":
682 return resolve(
683 msg("{count, plural, one {Received {count} update} other {Received {count} updates}}", {
684 count,
685 }),
686 );
687 }
688}
689
690function joinClauses(items: ReadonlyArray<string>, resolve: MFunctionType): string {
691 if (items.length < 2) return items[0] ?? "";
692 if (items.length === 2) {
693 return resolve(msg("{first} and {second}", { first: items[0]!, second: items[1]! }));
694 }
695 return resolve(
696 msg("{items}, and {last}", { items: items.slice(0, -1).join(", "), last: items.at(-1)! }),
697 );
698}
699
700function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
701 return {
702 input: workEntryToolInput(entry),
703 output: workEntryToolOutput(entry),
704 outcome:
705 entry.toolLifecycleStatus === "failed" ||
706 entry.toolLifecycleStatus === "declined" ||
707 entry.tone === "error"
708 ? "failed"
709 : entry.toolLifecycleStatus === "completed"
710 ? "completed"
711 : "unfinished",
712 };
713}
714
715function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
716 switch (action) {
717 case "command":
718 case "edit":
719 case "delegate":
720 case "task-cancel":
721 case "thread-create":
722 case "thread-send":
723 case "thread-interrupt":
724 case "workflow-stop":
725 case "background-wait":
726 case "schedule-create":
727 case "schedule-update":
728 case "schedule-delete":
729 case "schedule-run":
730 case "thread-configure":
731 case "thread-fork":
732 case "thread-merge":
733 case "thread-organize":
734 case "thread-update":
735 case "queue-edit":
736 case "queue-cancel":
737 case "queue-reorder":
738 case "queue-steer":
739 case "question-respond":
740 case "worktree-handoff":
741 case "project-create":
742 case "project-update":
743 case "project-delete":
744 case "project-clone":
745 case "environment-update":
746 case "theme-set":
747 case "attachment-prepare":
748 case "attachment-discard":
749 case "attachment-send":
750 return 0;
751 case "other":
752 case "update":
753 return 2;
754 default:
755 return 1;
756 }
757}
758
759export function summarizeToolGroup(
760 entries: ReadonlyArray<WorkLogPresentationEntry>,
761 resolve: MFunctionType = mFallback,
762): {
763 summary: string;
764 hasFailure: boolean;
765} {
766 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
767 if (entries.length > 0 && toolEntries.length === 0) {
768 return {
769 summary:
770 entries.length === 1
771 ? resolve(msg("Thought", { $context: "noun, a reasoning step" }))
772 : resolve(msg("Thought (×{count})", { count: entries.length })),
773 hasFailure: false,
774 };
775 }
776 entries = toolEntries;
777 const groups = new Map<
778 ToolGroupAction | T3McpToolSummaryAction,
779 {
780 action: ToolGroupAction;
781 t3Action: T3McpToolSummaryAction | null;
782 entries: WorkLogPresentationEntry[];
783 }
784 >();
785 const sources = new Map<string, ToolActivitySource>();
786 for (const entry of entries) {
787 const t3Action = resolveT3McpSummaryAction(
788 workEntryToolName(entry),
789 t3ToolSummaryCall(entry).input,
790 );
791 if (entry.toolSource && t3Action === null) {
792 sources.set(entry.toolSource.key, entry.toolSource);
793 continue;
794 }
795 const action = toolGroupAction(entry);
796 const key = t3Action ?? action;
797 const group = groups.get(key);
798 if (group) group.entries.push(entry);
799 else groups.set(key, { action, t3Action, entries: [entry] });
800 }
801 const summaries = [...groups].map(([action, group], index) => ({
802 index,
803 count: group.entries.length,
804 priority: summaryActionPriority(action),
805 ...(group.t3Action
806 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall), resolve)
807 : {
808 label: toolGroupActionLabel(
809 group.action,
810 toolGroupActionCount(group.action, group.entries),
811 resolve,
812 ),
813 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
814 }),
815 }));
816 const selected = [...summaries]
817 .sort((a, b) => a.priority - b.priority || a.index - b.index)
818 .slice(0, 2)
819 .sort((a, b) => a.index - b.index);
820 const labels = selected.map(({ label }) => label);
821 if (sources.size > 0) {
822 const sourceValues = [...sources.values()];
823 const sourceNames = [...new Set(sourceValues.map((source) => source.name))];
824 const names = joinClauses(sourceNames, resolve);
825 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
826 labels.unshift(
827 allIntegrations
828 ? resolve(
829 msg(
830 "{count, plural, =1 {Used {names} integration} other {Used {names} integrations}}",
831 { count: sourceNames.length, names },
832 ),
833 )
834 : resolve(msg("Used {names}", { names })),
835 );
836 }
837 const sourcedCount = entries.filter(
838 (entry) =>
839 entry.toolSource !== undefined &&
840 resolveT3McpToolDefinition(workEntryToolName(entry)) === null,
841 ).length;
842 const remainingCount =
843 entries.length - sourcedCount - selected.reduce((count, group) => count + group.count, 0);
844 if (remainingCount > 0) {
845 labels.push(
846 resolve(
847 msg(
848 "{count, plural, one {Performed {count} other action} other {Performed {count} other actions}}",
849 { count: remainingCount },
850 ),
851 ),
852 );
853 }
854 const sentenceLabels = labels.map((label, index) =>
855 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
856 );
857 const summary = joinClauses(sentenceLabels, resolve);
858 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
859}
860
861export function toolGroupSummaryKind(
862 entries: ReadonlyArray<WorkLogPresentationEntry>,
863): ToolGroupSummaryKind {
864 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
865 if (entries.length > 0 && toolEntries.length === 0) return "reasoning";
866 entries = toolEntries;
867 if (
868 entries.length > 0 &&
869 entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
870 )
871 return "pull-request";
872 const actions = new Set(entries.map(toolGroupAction));
873 if (actions.size !== 1) return "mixed";
874 const action = actions.values().next().value!;
875 if (action !== "other") return action;
876 const fallbackKinds = new Set(
877 entries.map((entry): ToolGroupSummaryKind => {
878 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
879 if (entry.itemType === "subagent") return "agent-tool";
880 if (entry.tone === "thinking") return "agent-tool";
881 if (entry.tone === "tool") return "tone-tool";
882 return "other";
883 }),
884 );
885 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
886}
887
888export function liveThoughtLine(markdown: string): string {
889 const heading = /^\s*\*\*([^*\r\n]+)\*\*[ \t]*\r?(?:\n|$)/.exec(markdown)?.[1];
890 const text = (heading ?? markdown)
891 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
892 .replace(/^[ \t]*(?:#{1,6}|[-*+]|\d+\.)[ \t]+/gm, "")
893 .replace(/`+|\*\*|~~/g, "")
894 .replace(/(^|[^\w*])[*_]([^*_\n]+)[*_](?![\w*])/g, "$1$2")
895 .replace(/\s+/g, " ")
896 .trim();
897 if (heading !== undefined) return text;
898 // CJK sentences end in full-width marks with no space after them.
899 const end = /[.?!]["'”’)]?(?=\s)|[。!?]["'”’)」』]?/.exec(text);
900 return end ? text.slice(0, end.index + end[0].length) : text;
901}