Open History to see the last commit
1import {
2 isToolLifecycleItemType,
3 type AssetResource,
4 type ThreadId,
5 type ToolActivitySource,
6 type ToolLifecycleItemType,
7} from "@t3tools/contracts";
8import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
9import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
10import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
11
12export function isWorktreeSetupActivity(kind: string): boolean {
13 return kind === "setup-script.requested" || kind === "setup-script.started";
14}
15
16export interface WorkLogPresentationEntry {
17 readonly label: string;
18 readonly toolTitle?: string;
19 readonly toolData?: unknown;
20 readonly tone: "thinking" | "tool" | "info" | "error";
21 readonly command?: string;
22 readonly detail?: string;
23 readonly viewedImagePath?: string;
24 readonly changedFiles?: ReadonlyArray<string>;
25 readonly itemType?: ToolLifecycleItemType;
26 readonly requestKind?: string;
27 readonly turnId?: string | null;
28 readonly toolCallId?: string;
29 readonly toolLifecycleStatus?: string;
30 readonly sourceActivityKind?: string;
31 readonly taskId?: string;
32 readonly toolSource?: ToolActivitySource;
33}
34
35export type ToolGroupAction =
36 | "read"
37 | "edit"
38 | "command"
39 | "browser"
40 | "code-search"
41 | "search"
42 | "other"
43 | "update";
44
45export type ToolGroupSummaryKind =
46 | ToolGroupAction
47 | "dynamic-tool"
48 | "agent-tool"
49 | "tone-tool"
50 | "mixed";
51
52export function normalizeCompactToolLabel(value: string): string {
53 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
54}
55
56const T3_MCP_TOOL_LABELS: Record<
57 string,
58 readonly [action: string, running: string, completed: string, detail: string]
59> = {
60 orchestrator_capabilities: ["Get", "Getting", "Got", "orchestration capabilities"],
61 delegate_task: ["Delegate", "Delegating", "Delegated", "a child task"],
62 task_status: ["Get", "Getting", "Got", "delegated task status"],
63 task_cancel: ["Cancel", "Canceling", "Canceled", "delegated task"],
64 schedule_task: ["Schedule", "Scheduling", "Scheduled", "a recurring task"],
65 list_scheduled_tasks: ["List", "Listing", "Listed", "scheduled tasks"],
66 update_scheduled_task: ["Update", "Updating", "Updated", "a scheduled task"],
67 delete_scheduled_task: ["Delete", "Deleting", "Deleted", "a scheduled task"],
68 create_threads: ["Create", "Creating", "Created", "T3 threads"],
69 t3_thread_start: ["Start", "Starting", "Started", "a T3 thread"],
70 t3_thread_list: ["List", "Listing", "Listed", "T3 threads"],
71 t3_thread_read: ["Read", "Reading", "Read", "a T3 thread"],
72 t3_thread_send: ["Send", "Sending", "Sent", "to a T3 thread"],
73 t3_thread_wait: ["Wait", "Waiting", "Waited", "for a T3 thread"],
74 t3_thread_interrupt: ["Interrupt", "Interrupting", "Interrupted", "a T3 thread"],
75 t3_worktree_handoff: ["Hand off", "Handing off", "Handed off", "thread to a git worktree"],
76 t3_worktree_status: ["Get", "Getting", "Got", "thread worktree status"],
77 preview_status: ["Get", "Getting", "Got", "preview browser status"],
78 preview_open: ["Open", "Opening", "Opened", "a page in the preview browser"],
79 preview_navigate: ["Navigate", "Navigating", "Navigated", "the preview browser"],
80 preview_snapshot: [
81 "Take a snapshot of",
82 "Taking a snapshot of",
83 "Took a snapshot of",
84 "the preview page",
85 ],
86 preview_click: ["Click", "Clicking", "Clicked", "in the preview browser"],
87 preview_press: ["Press", "Pressing", "Pressed", "a key in the preview browser"],
88 preview_type: ["Type", "Typing", "Typed", "in the preview browser"],
89 preview_scroll: ["Scroll", "Scrolling", "Scrolled", "the preview browser"],
90 preview_resize: ["Resize", "Resizing", "Resized", "the preview browser"],
91 preview_evaluate: ["Evaluate", "Evaluating", "Evaluated", "script in the preview browser"],
92 preview_wait_for: ["Wait", "Waiting", "Waited", "for the preview page"],
93 preview_set_appearance: ["Set", "Setting", "Set", "preview browser appearance"],
94 preview_recording_start: ["Start", "Starting", "Started", "recording the preview browser"],
95 preview_recording_stop: ["Stop", "Stopping", "Stopped", "recording the preview browser"],
96};
97
98function resolveT3McpToolPresentation(value: string | undefined, status: string | undefined) {
99 if (!value) return null;
100 const name = normalizeCompactToolLabel(value).replace(
101 /^(?:mcp__(?:t3-code|t3_code|t3code)__|(?:t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*))/i,
102 "",
103 );
104 if (!Object.hasOwn(T3_MCP_TOOL_LABELS, name)) return null;
105
106 const [action, running, completed, detail] = T3_MCP_TOOL_LABELS[name]!;
107 const verb =
108 status === "inProgress"
109 ? running
110 : status === "completed"
111 ? completed
112 : status === "failed"
113 ? `Failed to ${action.toLowerCase()}`
114 : status === "declined"
115 ? `Declined to ${action.toLowerCase()}`
116 : status === "stopped"
117 ? `Stopped ${running.toLowerCase()}`
118 : running;
119
120 return {
121 displayName: `${verb} ${detail}`,
122 icon: name.startsWith("preview_") ? ("browser" as const) : ("t3-code" as const),
123 };
124}
125
126/** Latest live activity stays present-tense unless the call itself failed, declined, or stopped. */
127export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
128 if (status === "failed" || status === "declined" || status === "stopped") return status;
129 if (presentTense || status === "inProgress") return "inProgress";
130 return "completed";
131}
132
133/** Resolves tool identity before choosing labels or icons in either client. */
134export function resolveWorkEntryToolPresentation(
135 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "toolLifecycleStatus">,
136 fallbackStatus?: "inProgress" | "completed",
137) {
138 const status = entry.toolLifecycleStatus ?? fallbackStatus;
139 const data = entry.toolData;
140 if (data !== null && typeof data === "object") {
141 if (
142 "server" in data &&
143 typeof data.server === "string" &&
144 "tool" in data &&
145 typeof data.tool === "string"
146 ) {
147 return resolveT3McpToolPresentation(`${data.server}.${data.tool}`, status);
148 }
149 if ("toolName" in data && typeof data.toolName === "string") {
150 return resolveT3McpToolPresentation(data.toolName, status);
151 }
152 }
153
154 return (
155 resolveT3McpToolPresentation(entry.toolTitle, status) ??
156 resolveT3McpToolPresentation(entry.label, status)
157 );
158}
159
160function asRecord(value: unknown): Record<string, unknown> | null {
161 return value !== null && typeof value === "object" && !Array.isArray(value)
162 ? (value as Record<string, unknown>)
163 : null;
164}
165
166function nonEmptyString(value: unknown): string | null {
167 return typeof value === "string" && value.trim().length > 0 ? value : null;
168}
169
170function commandResultContent(value: unknown): string | null {
171 const direct = nonEmptyString(value);
172 if (direct) return direct;
173
174 const directContent = Array.isArray(value) ? value : null;
175 const record = asRecord(value);
176 const content = record?.content;
177 const contentText = nonEmptyString(content);
178 if (contentText) return contentText;
179 const blocks = directContent ?? (Array.isArray(content) ? content : null);
180 if (!blocks) return null;
181
182 const chunks = blocks.flatMap((entry) => {
183 const text = nonEmptyString(entry) ?? nonEmptyString(asRecord(entry)?.text);
184 return text ? [text] : [];
185 });
186 return chunks.length > 0 ? chunks.join("\n") : null;
187}
188
189/** Returns provider command output before it is formatted for a work-log row. */
190export function extractCommandOutputText(dataValue: unknown): string | null {
191 const data = asRecord(dataValue);
192 const item = asRecord(data?.item);
193 const itemResult = asRecord(item?.result);
194 const rawOutput = asRecord(data?.rawOutput);
195 const outputStreams = [
196 nonEmptyString(rawOutput?.stdout),
197 nonEmptyString(rawOutput?.stderr),
198 ].filter((value): value is string => value !== null);
199 const acpContent = Array.isArray(data?.content)
200 ? data.content
201 .flatMap((entryValue) => {
202 const entry = asRecord(entryValue);
203 const content = asRecord(entry?.content);
204 const text = entry?.type === "content" ? nonEmptyString(content?.text) : null;
205 return text ? [text] : [];
206 })
207 .join("\n")
208 : null;
209
210 const candidates = [
211 item?.aggregatedOutput,
212 itemResult?.content,
213 data?.rawOutput,
214 rawOutput?.content,
215 outputStreams.length > 0 ? outputStreams.join("\n") : null,
216 rawOutput?.output,
217 acpContent,
218 data?.result,
219 ];
220 for (const candidate of candidates) {
221 const text = commandResultContent(candidate);
222 if (text) return text;
223 }
224 return null;
225}
226
227/**
228 * Ingestion caps tool details at 180 chars and appends "...", so a long command
229 * echo no longer equals the command it repeats. Treat a truncated prefix of the
230 * command as the same echo.
231 */
232function textRepeatsCommand(text: string, commands: ReadonlyArray<string | null>): boolean {
233 const truncated = text.endsWith("...")
234 ? text.slice(0, -3)
235 : text.endsWith("\u2026")
236 ? text.slice(0, -1)
237 : null;
238 return commands.some((candidate) => {
239 const command = candidate?.trim();
240 if (!command) return false;
241 if (command === text) return true;
242 return (
243 truncated !== null &&
244 truncated.length > 0 &&
245 command.length > truncated.length &&
246 command.startsWith(truncated)
247 );
248 });
249}
250
251/**
252 * Decides whether a command row's `detail` is a synthetic echo of the command
253 * rather than real output. OpenCode stores completed output in `detail` with no
254 * other output channel, so plain equality is only treated as synthetic when the
255 * payload shape shows the detail came from the command: Codex item metadata,
256 * an ACP tool call (`data.toolCallId`, `kind: "execute"`), a Claude tool-name
257 * prefix, or no structured command at all.
258 */
259export function commandDetailRepeatsCommand(input: {
260 readonly detail: string;
261 readonly command: string | null;
262 readonly rawCommand: string | null;
263 readonly toolName: unknown;
264 readonly data: unknown;
265}): boolean {
266 const toolName = nonEmptyString(input.toolName)?.trim();
267 const detail = input.detail.trim();
268 const commands = [input.command, input.rawCommand];
269 if (toolName) {
270 const prefix = `${toolName}:`;
271 if (detail.toLowerCase().startsWith(prefix.toLowerCase())) {
272 const unprefixed = detail.slice(prefix.length).trim();
273 if (textRepeatsCommand(unprefixed, commands)) return true;
274 }
275 }
276
277 if (!textRepeatsCommand(detail, commands)) return false;
278
279 const data = asRecord(input.data);
280 const item = asRecord(data?.item);
281 const itemInput = asRecord(item?.input);
282 const itemResult = asRecord(item?.result);
283 const hasStructuredCommand = [
284 item?.command,
285 itemInput?.command,
286 itemResult?.command,
287 data?.command,
288 ].some((value) =>
289 Array.isArray(value)
290 ? value.some((part) => nonEmptyString(part) !== null)
291 : nonEmptyString(value) !== null,
292 );
293 return (
294 !hasStructuredCommand ||
295 item !== null ||
296 data?.toolCallId !== undefined ||
297 nonEmptyString(data?.kind)?.toLowerCase() === "execute"
298 );
299}
300
301function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
302 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
303 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
304 if (entry.requestKind !== undefined) return true;
305 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
306}
307
308export function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
309 return (
310 entry.itemType === "web_search" &&
311 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
312 );
313}
314
315export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
316 if (resolveWorkEntryToolPresentation(entry)?.icon === "browser") return "browser";
317 if (
318 entry.requestKind === "file-read" ||
319 entry.itemType === "image_view" ||
320 entry.viewedImagePath !== undefined ||
321 (entry.itemType === "dynamic_tool_call" &&
322 entry.toolTitle?.trim().toLowerCase() === "read file")
323 ) {
324 return "read";
325 }
326 if (
327 entry.requestKind === "file-change" ||
328 entry.itemType === "file_change" ||
329 (entry.changedFiles?.length ?? 0) > 0
330 ) {
331 return "edit";
332 }
333 if (entry.requestKind === "command" || entry.itemType === "command_execution" || entry.command) {
334 return "command";
335 }
336 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
337 if (entry.itemType === "web_search") return "search";
338 return workLogEntryIsToolLike(entry) ? "other" : "update";
339}
340
341export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
342 const viewedImagePath = entry.viewedImagePath?.trim();
343 if (
344 viewedImagePath !== undefined &&
345 !/[\r\n]/.test(viewedImagePath) &&
346 isWorkspaceImagePreviewPath(viewedImagePath)
347 ) {
348 return viewedImagePath;
349 }
350 const detail = entry.detail?.trim();
351 return toolGroupAction(entry) === "read" &&
352 detail !== undefined &&
353 !/[\r\n]/.test(detail) &&
354 isWorkspaceImagePreviewPath(detail)
355 ? detail
356 : null;
357}
358
359export interface ViewedImageAsset {
360 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
361 readonly alt: string;
362 readonly srcFragment: string;
363}
364
365export function resolveViewedImageAsset(
366 source: string,
367 input: {
368 readonly threadId: ThreadId;
369 readonly workspaceRoot?: string | null | undefined;
370 },
371): ViewedImageAsset | null {
372 // A relative path with no known workspace still names a media-file relative
373 // to the thread's workspace, so classify against "." and drop the prefix.
374 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
375 if (imageSource._tag !== "WorkspaceFile") return null;
376 const resolvedFilePath =
377 input.workspaceRoot == null && imageSource.path.startsWith("./")
378 ? imageSource.path.slice(2)
379 : imageSource.path;
380
381 const media = resolveMediaSource(source, {
382 threadId: input.threadId,
383 workspaceRoot: input.workspaceRoot,
384 resolvedFilePath,
385 });
386 if (media === null || media.access !== "environment") return null;
387 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
388}
389
390function toolGroupActionCount(
391 action: ToolGroupAction,
392 entries: ReadonlyArray<WorkLogPresentationEntry>,
393): number {
394 if (action !== "edit") return entries.length;
395
396 const changedFiles = new Set<string>();
397 let editsWithoutFileDetails = 0;
398 for (const entry of entries) {
399 if (!entry.changedFiles || entry.changedFiles.length === 0) {
400 editsWithoutFileDetails += 1;
401 continue;
402 }
403 for (const file of entry.changedFiles) changedFiles.add(file);
404 }
405 return changedFiles.size + editsWithoutFileDetails;
406}
407
408function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
409 switch (action) {
410 case "read":
411 return `Read ${count} ${count === 1 ? "file" : "files"}`;
412 case "edit":
413 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
414 case "command":
415 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
416 case "browser":
417 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
418 case "search":
419 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
420 case "code-search":
421 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
422 case "other":
423 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
424 case "update":
425 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
426 }
427}
428
429export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): string {
430 const summaryEntries = omitSupersededLifecycleMarkers(entries, (entry) => entry);
431 const sources = new Map<string, ToolActivitySource>();
432 const groupedEntries = new Map<ToolGroupAction, WorkLogPresentationEntry[]>();
433 for (const entry of summaryEntries) {
434 if (entry.toolSource) {
435 sources.set(entry.toolSource.key, entry.toolSource);
436 continue;
437 }
438 const action = toolGroupAction(entry);
439 const group = groupedEntries.get(action);
440 if (group) group.push(entry);
441 else groupedEntries.set(action, [entry]);
442 }
443 const labels = [...groupedEntries].map(([action, actionEntries]) =>
444 toolGroupActionLabel(action, toolGroupActionCount(action, actionEntries)),
445 );
446 if (sources.size > 0) {
447 const sourceValues = [...sources.values()];
448 const sourceNames = sourceValues.map((source) => source.name);
449 const formattedNames =
450 sourceNames.length < 2
451 ? sourceNames[0]!
452 : sourceNames.length === 2
453 ? sourceNames.join(" and ")
454 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
455 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
456 labels.unshift(
457 `Used ${formattedNames}${allIntegrations ? ` ${sources.size === 1 ? "integration" : "integrations"}` : ""}`,
458 );
459 }
460 const sentenceLabels = labels.map((label, index) =>
461 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
462 );
463 if (sentenceLabels.length < 2) return sentenceLabels[0] ?? "";
464 if (sentenceLabels.length === 2) return sentenceLabels.join(" and ");
465 return `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
466}
467
468export function omitSupersededLifecycleMarkers<T>(
469 entries: readonly T[],
470 workEntryFor: (entry: T) => WorkLogPresentationEntry,
471): T[] {
472 const laterTerminalIdentities = new Set<string>();
473 const reversedEntries: T[] = [];
474
475 for (let index = entries.length - 1; index >= 0; index -= 1) {
476 const entry = entries[index]!;
477 const workEntry = workEntryFor(entry);
478 const normalizedLabel = normalizeCompactToolLabel(workEntry.toolTitle ?? workEntry.label);
479 const identity = [
480 workEntry.turnId ?? "no-turn",
481 workEntry.itemType ?? "",
482 normalizedLabel,
483 ].join("\u001f");
484 const activityKind = workEntry.sourceActivityKind;
485 const isStatuslessIdlessMarker =
486 workEntry.toolCallId === undefined &&
487 workEntry.toolLifecycleStatus === undefined &&
488 (activityKind === "tool.started" || activityKind === "tool.updated");
489 if (isStatuslessIdlessMarker && laterTerminalIdentities.has(identity)) continue;
490
491 reversedEntries.push(entry);
492 if (
493 activityKind === "tool.completed" ||
494 (workEntry.toolLifecycleStatus !== undefined &&
495 workEntry.toolLifecycleStatus !== "inProgress")
496 ) {
497 laterTerminalIdentities.add(identity);
498 }
499 }
500
501 return reversedEntries.toReversed();
502}
503
504export function toolGroupSummaryKind(
505 entries: ReadonlyArray<WorkLogPresentationEntry>,
506): ToolGroupSummaryKind {
507 const actions = new Set(entries.map(toolGroupAction));
508 if (actions.size !== 1) return "mixed";
509
510 const action = actions.values().next().value!;
511 if (action !== "other") return action;
512
513 const fallbackKinds = new Set(
514 entries.map((entry): ToolGroupSummaryKind => {
515 if (entry.itemType === "mcp_tool_call") return "other";
516 if (entry.itemType === "dynamic_tool_call") return "dynamic-tool";
517 if (entry.itemType === "collab_agent_tool_call" || entry.taskId) return "agent-tool";
518 if (entry.tone === "thinking") return "agent-tool";
519 if (entry.tone === "tool") return "tone-tool";
520 return "other";
521 }),
522 );
523 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
524}