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