Open History to see the last commit
1import {
2 isToolLifecycleItemType,
3 type AssetResource,
4 type RuntimeItemStatus,
5 type ThreadId,
6 type ToolActivitySource,
7 type ToolLifecycleItemType,
8} from "@t3tools/contracts";
9import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
10import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
11import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
12import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
13
14export function isWorktreeSetupActivity(kind: string): boolean {
15 return kind === "setup-script.requested" || kind === "setup-script.started";
16}
17
18export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped";
19
20export interface WorkLogPresentationEntry {
21 readonly label: string;
22 readonly toolTitle?: string;
23 readonly toolData?: unknown;
24 readonly tone: "thinking" | "tool" | "info" | "error";
25 readonly command?: string;
26 readonly detail?: string;
27 readonly viewedImagePath?: string;
28 readonly changedFiles?: ReadonlyArray<string>;
29 readonly itemType?: ToolLifecycleItemType;
30 readonly requestKind?: string;
31 readonly turnId?: string | null;
32 readonly toolCallId?: string;
33 readonly toolLifecycleStatus?: string;
34 readonly sourceActivityKind?: string;
35 readonly taskId?: string;
36 readonly toolSource?: ToolActivitySource;
37}
38
39export type ToolGroupAction =
40 | "link-pr"
41 | "unlink-pr"
42 | "list-prs"
43 | "read"
44 | "edit"
45 | "command"
46 | "browser"
47 | "code-search"
48 | "search"
49 | "other"
50 | "update";
51
52export type ToolGroupSummaryKind =
53 | "pull-request"
54 | ToolGroupAction
55 | "dynamic-tool"
56 | "agent-tool"
57 | "tone-tool"
58 | "mixed";
59
60export function normalizeCompactToolLabel(value: string): string {
61 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
62}
63
64const T3_MCP_TOOL_LABELS: Record<
65 string,
66 readonly [action: string, running: string, completed: string, detail: string]
67> = {
68 link_pull_request: ["Link", "Linking", "Linked", "a pull request"],
69 unlink_pull_request: ["Unlink", "Unlinking", "Unlinked", "a pull request"],
70 list_thread_pull_requests: ["Check", "Checking", "Checked", "linked pull requests"],
71 orchestrator_capabilities: ["Get", "Getting", "Got", "orchestration capabilities"],
72 delegate_task: ["Delegate", "Delegating", "Delegated", "a child task"],
73 task_status: ["Get", "Getting", "Got", "delegated task status"],
74 task_cancel: ["Cancel", "Canceling", "Canceled", "delegated task"],
75 schedule_task: ["Schedule", "Scheduling", "Scheduled", "a recurring task"],
76 list_scheduled_tasks: ["List", "Listing", "Listed", "scheduled tasks"],
77 update_scheduled_task: ["Update", "Updating", "Updated", "a scheduled task"],
78 delete_scheduled_task: ["Delete", "Deleting", "Deleted", "a scheduled task"],
79 create_threads: ["Create", "Creating", "Created", "T3 threads"],
80 t3_thread_start: ["Start", "Starting", "Started", "a T3 thread"],
81 t3_thread_list: ["List", "Listing", "Listed", "T3 threads"],
82 t3_thread_read: ["Read", "Reading", "Read", "a T3 thread"],
83 t3_thread_send: ["Send", "Sending", "Sent", "to a T3 thread"],
84 t3_thread_wait: ["Wait", "Waiting", "Waited", "for a T3 thread"],
85 t3_thread_interrupt: ["Interrupt", "Interrupting", "Interrupted", "a T3 thread"],
86 t3_worktree_handoff: ["Hand off", "Handing off", "Handed off", "thread to a git worktree"],
87 t3_worktree_status: ["Get", "Getting", "Got", "thread worktree status"],
88 preview_status: ["Get", "Getting", "Got", "preview browser status"],
89 preview_open: ["Open", "Opening", "Opened", "a page in the preview browser"],
90 preview_navigate: ["Navigate", "Navigating", "Navigated", "the preview browser"],
91 preview_snapshot: [
92 "Take a snapshot of",
93 "Taking a snapshot of",
94 "Took a snapshot of",
95 "the preview page",
96 ],
97 preview_click: ["Click", "Clicking", "Clicked", "in the preview browser"],
98 preview_press: ["Press", "Pressing", "Pressed", "a key in the preview browser"],
99 preview_type: ["Type", "Typing", "Typed", "in the preview browser"],
100 preview_scroll: ["Scroll", "Scrolling", "Scrolled", "the preview browser"],
101 preview_resize: ["Resize", "Resizing", "Resized", "the preview browser"],
102 preview_evaluate: ["Evaluate", "Evaluating", "Evaluated", "script in the preview browser"],
103 preview_wait_for: ["Wait", "Waiting", "Waited", "for the preview page"],
104 preview_set_appearance: ["Set", "Setting", "Set", "preview browser appearance"],
105 preview_recording_start: ["Start", "Starting", "Started", "recording the preview browser"],
106 preview_recording_stop: ["Stop", "Stopping", "Stopped", "recording the preview browser"],
107};
108
109const PR_TOOL_ACTIONS: Readonly<Record<string, ToolGroupAction>> = {
110 link_pull_request: "link-pr",
111 unlink_pull_request: "unlink-pr",
112 list_thread_pull_requests: "list-prs",
113};
114
115function resolveT3McpToolPresentation(
116 value: string | undefined,
117 status: string | undefined,
118 data?: unknown,
119) {
120 if (!value) return null;
121 const name = normalizeCompactToolLabel(value).replace(
122 /^(?:mcp__(?:t3-code|t3_code|t3code)__|(?:t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*))/i,
123 "",
124 );
125 if (!Object.hasOwn(T3_MCP_TOOL_LABELS, name)) return null;
126
127 const [action, running, completed, detail] = T3_MCP_TOOL_LABELS[name]!;
128 const verb =
129 status === "inProgress"
130 ? running
131 : status === "completed"
132 ? completed
133 : status === "failed"
134 ? `Failed to ${action.toLowerCase()}`
135 : status === "declined"
136 ? `Declined to ${action.toLowerCase()}`
137 : status === "stopped"
138 ? `Stopped ${running.toLowerCase()}`
139 : running;
140
141 const actionKind = Object.hasOwn(PR_TOOL_ACTIONS, name) ? PR_TOOL_ACTIONS[name] : undefined;
142 const payload = asRecord(data);
143 const input =
144 asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
145 const urlTarget = typeof input?.url === "string" ? parseChangeRequestUrl(input.url) : null;
146 const number = urlTarget?.number ?? input?.number;
147 const target =
148 actionKind !== undefined &&
149 actionKind !== "list-prs" &&
150 typeof number === "number" &&
151 Number.isSafeInteger(number) &&
152 number > 0
153 ? `PR #${number}`
154 : detail;
155 return {
156 displayName: `${verb} ${target}`,
157 icon:
158 actionKind !== undefined
159 ? ("pull-request" as const)
160 : name.startsWith("preview_")
161 ? ("browser" as const)
162 : ("t3-code" as const),
163 ...(actionKind === undefined ? {} : { action: actionKind }),
164 };
165}
166
167/** Latest live activity stays present-tense unless the call itself failed, declined, or stopped. */
168export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
169 if (status === "failed" || status === "declined" || status === "stopped") return status;
170 if (presentTense || status === "inProgress") return "inProgress";
171 return "completed";
172}
173
174/** Resolves tool identity before choosing labels or icons in either client. */
175export function resolveWorkEntryToolPresentation(
176 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "toolLifecycleStatus">,
177 fallbackStatus?: "inProgress" | "completed",
178) {
179 const status = entry.toolLifecycleStatus ?? fallbackStatus;
180 const data = entry.toolData;
181 if (data !== null && typeof data === "object") {
182 if (
183 "server" in data &&
184 typeof data.server === "string" &&
185 "tool" in data &&
186 typeof data.tool === "string"
187 ) {
188 return resolveT3McpToolPresentation(`${data.server}.${data.tool}`, status, data);
189 }
190 if ("toolName" in data && typeof data.toolName === "string") {
191 return resolveT3McpToolPresentation(data.toolName, status, data);
192 }
193 }
194
195 return (
196 resolveT3McpToolPresentation(entry.toolTitle, status, data) ??
197 resolveT3McpToolPresentation(entry.label, status, data)
198 );
199}
200
201function asRecord(value: unknown): Record<string, unknown> | null {
202 return value !== null && typeof value === "object" && !Array.isArray(value)
203 ? (value as Record<string, unknown>)
204 : null;
205}
206
207function nonEmptyString(value: unknown): string | null {
208 return typeof value === "string" && value.trim().length > 0 ? value : null;
209}
210
211function commandResultContent(value: unknown): string | null {
212 const direct = nonEmptyString(value);
213 if (direct) return direct;
214
215 const directContent = Array.isArray(value) ? value : null;
216 const record = asRecord(value);
217 const content = record?.content;
218 const contentText = nonEmptyString(content);
219 if (contentText) return contentText;
220 const blocks = directContent ?? (Array.isArray(content) ? content : null);
221 if (!blocks) return null;
222
223 const chunks = blocks.flatMap((entry) => {
224 const text = nonEmptyString(entry) ?? nonEmptyString(asRecord(entry)?.text);
225 return text ? [text] : [];
226 });
227 return chunks.length > 0 ? chunks.join("\n") : null;
228}
229
230/** Returns provider command output before it is formatted for a work-log row. */
231export function extractCommandOutputText(dataValue: unknown): string | null {
232 const data = asRecord(dataValue);
233 const item = asRecord(data?.item);
234 const itemResult = asRecord(item?.result);
235 const rawOutput = asRecord(data?.rawOutput);
236 const outputStreams = [
237 nonEmptyString(rawOutput?.stdout),
238 nonEmptyString(rawOutput?.stderr),
239 ].filter((value): value is string => value !== null);
240 const acpContent = Array.isArray(data?.content)
241 ? data.content
242 .flatMap((entryValue) => {
243 const entry = asRecord(entryValue);
244 const content = asRecord(entry?.content);
245 const text = entry?.type === "content" ? nonEmptyString(content?.text) : null;
246 return text ? [text] : [];
247 })
248 .join("\n")
249 : null;
250
251 const candidates = [
252 item?.aggregatedOutput,
253 itemResult?.content,
254 data?.rawOutput,
255 rawOutput?.content,
256 outputStreams.length > 0 ? outputStreams.join("\n") : null,
257 rawOutput?.output,
258 acpContent,
259 data?.result,
260 ];
261 for (const candidate of candidates) {
262 const text = commandResultContent(candidate);
263 if (text) return text;
264 }
265 return null;
266}
267
268/**
269 * Ingestion caps tool details at 180 chars and appends "...", so a long command
270 * echo no longer equals the command it repeats. Treat a truncated prefix of the
271 * command as the same echo.
272 */
273function textRepeatsCommand(text: string, commands: ReadonlyArray<string | null>): boolean {
274 const truncated = text.endsWith("...")
275 ? text.slice(0, -3)
276 : text.endsWith("\u2026")
277 ? text.slice(0, -1)
278 : null;
279 return commands.some((candidate) => {
280 const command = candidate?.trim();
281 if (!command) return false;
282 if (command === text) return true;
283 return (
284 truncated !== null &&
285 truncated.length > 0 &&
286 command.length > truncated.length &&
287 command.startsWith(truncated)
288 );
289 });
290}
291
292/**
293 * Decides whether a command row's `detail` is a synthetic echo of the command
294 * rather than real output. OpenCode stores completed output in `detail` with no
295 * other output channel, so plain equality is only treated as synthetic when the
296 * payload shape shows the detail came from the command: Codex item metadata,
297 * an ACP tool call (`data.toolCallId`, `kind: "execute"`), a Claude tool-name
298 * prefix, or no structured command at all.
299 */
300export function commandDetailRepeatsCommand(input: {
301 readonly detail: string;
302 readonly command: string | null;
303 readonly rawCommand: string | null;
304 readonly toolName: unknown;
305 readonly data: unknown;
306}): boolean {
307 const toolName = nonEmptyString(input.toolName)?.trim();
308 const detail = input.detail.trim();
309 const commands = [input.command, input.rawCommand];
310 if (toolName) {
311 const prefix = `${toolName}:`;
312 if (detail.toLowerCase().startsWith(prefix.toLowerCase())) {
313 const unprefixed = detail.slice(prefix.length).trim();
314 if (textRepeatsCommand(unprefixed, commands)) return true;
315 }
316 }
317
318 if (!textRepeatsCommand(detail, commands)) return false;
319
320 const data = asRecord(input.data);
321 const item = asRecord(data?.item);
322 const itemInput = asRecord(item?.input);
323 const itemResult = asRecord(item?.result);
324 const hasStructuredCommand = [
325 item?.command,
326 itemInput?.command,
327 itemResult?.command,
328 data?.command,
329 ].some((value) =>
330 Array.isArray(value)
331 ? value.some((part) => nonEmptyString(part) !== null)
332 : nonEmptyString(value) !== null,
333 );
334 return (
335 !hasStructuredCommand ||
336 item !== null ||
337 data?.toolCallId !== undefined ||
338 nonEmptyString(data?.kind)?.toLowerCase() === "execute"
339 );
340}
341
342export function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
343 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
344 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
345 if (entry.requestKind !== undefined) return true;
346 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
347}
348
349/** Maps item and task status to the status shown on a work-log row. */
350export function extractWorkLogToolLifecycleStatus(
351 payloadValue: unknown,
352): WorkLogToolLifecycleStatus | undefined {
353 const payload = asRecord(payloadValue);
354 switch (payload?.status) {
355 case "pending":
356 case "running":
357 case "waiting":
358 return "inProgress";
359 case "cancelled":
360 case "interrupted":
361 return "stopped";
362 case "idle":
363 // A batch becomes idle when its parent turn ends. Other idle tasks can resume.
364 return payload.taskType === "subagent_batch" ? "stopped" : undefined;
365 case "inProgress":
366 case "completed":
367 case "failed":
368 case "declined":
369 case "stopped":
370 return payload.status;
371 default:
372 return undefined;
373 }
374}
375
376// Some providers report completion even when the output describes a failure.
377function toolDetailTextLooksLikeFailure(text: string): boolean {
378 const normalized = text.toLowerCase();
379 return (
380 normalized.includes("file not found") ||
381 normalized.includes("no files found") ||
382 normalized.includes("enoent") ||
383 normalized.includes("no such file or directory") ||
384 normalized.includes("no such file") ||
385 normalized.includes("commandnotfoundexception") ||
386 normalized.includes("command not found") ||
387 (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
388 (normalized.includes("is not recognized") && normalized.includes("the term '")) ||
389 normalized.includes("is not recognized as the name of a cmdlet") ||
390 normalized.includes("a parameter cannot be found that matches parameter name") ||
391 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
392 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
393 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
394 );
395}
396
397function workEntryIndicatesToolFailureFromOutput(
398 entry: WorkLogPresentationEntry,
399 includeCommand: boolean,
400): boolean {
401 if (
402 entry.tone === "error" ||
403 entry.toolLifecycleStatus === "failed" ||
404 entry.toolLifecycleStatus === "declined"
405 ) {
406 return true;
407 }
408 if (!workLogEntryIsToolLike(entry)) return false;
409 const output = includeCommand
410 ? [entry.detail, entry.command].filter(Boolean).join("\n")
411 : (entry.detail ?? "");
412 return output.length > 0 && toolDetailTextLooksLikeFailure(output);
413}
414
415/** Includes legacy activities that stored error output in the command field. */
416export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
417 return workEntryIndicatesToolFailureFromOutput(entry, true);
418}
419
420/** Checks rendered output without treating the user's command as an error. */
421export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
422 return workEntryIndicatesToolFailureFromOutput(entry, false);
423}
424
425/** Decides whether the row can show a success marker. */
426export function workEntryIndicatesToolSuccess(entry: WorkLogPresentationEntry): boolean {
427 return (
428 workLogEntryIsToolLike(entry) &&
429 !workEntryIndicatesToolFailure(entry) &&
430 entry.tone !== "thinking" &&
431 entry.toolLifecycleStatus !== "inProgress" &&
432 entry.toolLifecycleStatus !== "stopped"
433 );
434}
435
436function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
437 return (
438 entry.itemType === "web_search" &&
439 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
440 );
441}
442
443export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
444 if (
445 entry.sourceActivityKind === "approval.requested" ||
446 entry.sourceActivityKind === "approval.resolved" ||
447 entry.sourceActivityKind === "provider.approval.respond.failed"
448 ) {
449 return "update";
450 }
451 const presentation = resolveWorkEntryToolPresentation(entry);
452 if (presentation?.action !== undefined) return presentation.action;
453 if (presentation?.icon === "browser") return "browser";
454 if (
455 entry.requestKind === "file-read" ||
456 entry.itemType === "image_view" ||
457 entry.viewedImagePath !== undefined ||
458 (entry.itemType === "dynamic_tool_call" &&
459 entry.toolTitle?.trim().toLowerCase() === "read file")
460 ) {
461 return "read";
462 }
463 if (
464 entry.requestKind === "file-change" ||
465 entry.itemType === "file_change" ||
466 (entry.changedFiles?.length ?? 0) > 0
467 ) {
468 return "edit";
469 }
470 if (entry.requestKind === "command" || entry.itemType === "command_execution" || entry.command) {
471 return "command";
472 }
473 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
474 if (entry.itemType === "web_search") return "search";
475 return workLogEntryIsToolLike(entry) ? "other" : "update";
476}
477
478export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
479 const viewedImagePath = entry.viewedImagePath?.trim();
480 if (
481 viewedImagePath !== undefined &&
482 !/[\r\n]/.test(viewedImagePath) &&
483 isWorkspaceImagePreviewPath(viewedImagePath)
484 ) {
485 return viewedImagePath;
486 }
487 const detail = entry.detail?.trim();
488 return toolGroupAction(entry) === "read" &&
489 detail !== undefined &&
490 !/[\r\n]/.test(detail) &&
491 isWorkspaceImagePreviewPath(detail)
492 ? detail
493 : null;
494}
495
496export interface ViewedImageAsset {
497 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
498 readonly alt: string;
499 readonly srcFragment: string;
500}
501
502export function resolveViewedImageAsset(
503 source: string,
504 input: {
505 readonly threadId: ThreadId;
506 readonly workspaceRoot?: string | null | undefined;
507 },
508): ViewedImageAsset | null {
509 // A relative path with no known workspace still names a media-file relative
510 // to the thread's workspace, so classify against "." and drop the prefix.
511 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
512 if (imageSource._tag !== "WorkspaceFile") return null;
513 const resolvedFilePath =
514 input.workspaceRoot == null && imageSource.path.startsWith("./")
515 ? imageSource.path.slice(2)
516 : imageSource.path;
517
518 const media = resolveMediaSource(source, {
519 threadId: input.threadId,
520 workspaceRoot: input.workspaceRoot,
521 resolvedFilePath,
522 });
523 if (media === null || media.access !== "environment") return null;
524 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
525}
526
527function toolGroupActionCount(
528 action: ToolGroupAction,
529 entries: ReadonlyArray<WorkLogPresentationEntry>,
530): number {
531 if (action !== "edit") return entries.length;
532
533 const changedFiles = new Set<string>();
534 let editsWithoutFileDetails = 0;
535 for (const entry of entries) {
536 if (!entry.changedFiles || entry.changedFiles.length === 0) {
537 editsWithoutFileDetails += 1;
538 continue;
539 }
540 for (const file of entry.changedFiles) changedFiles.add(file);
541 }
542 return changedFiles.size + editsWithoutFileDetails;
543}
544
545function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
546 switch (action) {
547 case "link-pr":
548 return `Linked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
549 case "unlink-pr":
550 return `Unlinked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
551 case "list-prs":
552 return count === 1
553 ? "Checked linked pull requests"
554 : `Checked linked pull requests ${count} times`;
555 case "read":
556 return `Read ${count} ${count === 1 ? "file" : "files"}`;
557 case "edit":
558 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
559 case "command":
560 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
561 case "browser":
562 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
563 case "search":
564 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
565 case "code-search":
566 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
567 case "other":
568 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
569 case "update":
570 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
571 }
572}
573
574export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): string {
575 const summaryEntries = omitSupersededLifecycleMarkers(entries, (entry) => entry);
576 const sources = new Map<string, ToolActivitySource>();
577 const groupedEntries = new Map<ToolGroupAction, WorkLogPresentationEntry[]>();
578 for (const entry of summaryEntries) {
579 if (entry.toolSource && resolveWorkEntryToolPresentation(entry)?.icon !== "pull-request") {
580 sources.set(entry.toolSource.key, entry.toolSource);
581 continue;
582 }
583 const action = toolGroupAction(entry);
584 const group = groupedEntries.get(action);
585 if (group) group.push(entry);
586 else groupedEntries.set(action, [entry]);
587 }
588 const labels = [...groupedEntries].map(([action, actionEntries]) =>
589 toolGroupActionLabel(action, toolGroupActionCount(action, actionEntries)),
590 );
591 if (sources.size > 0) {
592 const sourceValues = [...sources.values()];
593 const sourceNames = sourceValues.map((source) => source.name);
594 const formattedNames =
595 sourceNames.length < 2
596 ? sourceNames[0]!
597 : sourceNames.length === 2
598 ? sourceNames.join(" and ")
599 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
600 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
601 labels.unshift(
602 `Used ${formattedNames}${allIntegrations ? ` ${sources.size === 1 ? "integration" : "integrations"}` : ""}`,
603 );
604 }
605 const sentenceLabels = labels.map((label, index) =>
606 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
607 );
608 if (sentenceLabels.length < 2) return sentenceLabels[0] ?? "";
609 if (sentenceLabels.length === 2) return sentenceLabels.join(" and ");
610 return `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
611}
612
613export function omitSupersededLifecycleMarkers<T>(
614 entries: readonly T[],
615 workEntryFor: (entry: T) => WorkLogPresentationEntry,
616): T[] {
617 const laterTerminalIdentities = new Set<string>();
618 const reversedEntries: T[] = [];
619
620 for (let index = entries.length - 1; index >= 0; index -= 1) {
621 const entry = entries[index]!;
622 const workEntry = workEntryFor(entry);
623 const normalizedLabel = normalizeCompactToolLabel(workEntry.toolTitle ?? workEntry.label);
624 const identity = [
625 workEntry.turnId ?? "no-turn",
626 workEntry.itemType ?? "",
627 normalizedLabel,
628 ].join("\u001f");
629 const activityKind = workEntry.sourceActivityKind;
630 const isStatuslessIdlessMarker =
631 workEntry.toolCallId === undefined &&
632 workEntry.toolLifecycleStatus === undefined &&
633 (activityKind === "tool.started" || activityKind === "tool.updated");
634 if (isStatuslessIdlessMarker && laterTerminalIdentities.has(identity)) continue;
635
636 reversedEntries.push(entry);
637 if (
638 activityKind === "tool.completed" ||
639 (workEntry.toolLifecycleStatus !== undefined &&
640 workEntry.toolLifecycleStatus !== "inProgress")
641 ) {
642 laterTerminalIdentities.add(identity);
643 }
644 }
645
646 return reversedEntries.toReversed();
647}
648
649export function toolGroupSummaryKind(
650 entries: ReadonlyArray<WorkLogPresentationEntry>,
651): ToolGroupSummaryKind {
652 if (
653 entries.length > 0 &&
654 entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
655 )
656 return "pull-request";
657 const actions = new Set(entries.map(toolGroupAction));
658 if (actions.size !== 1) return "mixed";
659
660 const action = actions.values().next().value!;
661 if (action !== "other") return action;
662
663 const fallbackKinds = new Set(
664 entries.map((entry): ToolGroupSummaryKind => {
665 if (entry.itemType === "mcp_tool_call") return "other";
666 if (entry.itemType === "dynamic_tool_call") return "dynamic-tool";
667 if (entry.itemType === "collab_agent_tool_call" || entry.taskId) return "agent-tool";
668 if (entry.tone === "thinking") return "agent-tool";
669 if (entry.tone === "tool") return "tone-tool";
670 return "other";
671 }),
672 );
673 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
674}