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

presentation.ts

995 lines32.3 KB

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