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

presentation.ts

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