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

presentation.ts

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