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

presentation.ts

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