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

presentation.ts

776 lines27.1 KB

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