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

presentation.ts

691 lines25.3 KB

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