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

presentation.ts

531 lines19.3 KB

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";
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;
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();
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 };
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";
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 );
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;
165​
166function nonEmptyString(value: unknown): string | null {
167 return typeof value === "string" && value.trim().length > 0 ? value : null;
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;
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;
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 });
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 );
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);
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 );
314​
315export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
316 if (
317 entry.sourceActivityKind === "approval.requested" ||
318 entry.sourceActivityKind === "approval.resolved" ||
319 entry.sourceActivityKind === "provider.approval.respond.failed"
320 ) {
321 return "update";
322 }
323 if (resolveWorkEntryToolPresentation(entry)?.icon === "browser") return "browser";
324 if (
325 entry.requestKind === "file-read" ||
326 entry.itemType === "image_view" ||
327 entry.viewedImagePath !== undefined ||
328 (entry.itemType === "dynamic_tool_call" &&
329 entry.toolTitle?.trim().toLowerCase() === "read file")
330 ) {
331 return "read";
332 }
333 if (
334 entry.requestKind === "file-change" ||
335 entry.itemType === "file_change" ||
336 (entry.changedFiles?.length ?? 0) > 0
337 ) {
338 return "edit";
339 }
340 if (entry.requestKind === "command" || entry.itemType === "command_execution" || entry.command) {
341 return "command";
342 }
343 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
344 if (entry.itemType === "web_search") return "search";
345 return workLogEntryIsToolLike(entry) ? "other" : "update";
347​
348export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
349 const viewedImagePath = entry.viewedImagePath?.trim();
350 if (
351 viewedImagePath !== undefined &&
352 !/[\r\n]/.test(viewedImagePath) &&
353 isWorkspaceImagePreviewPath(viewedImagePath)
354 ) {
355 return viewedImagePath;
356 }
357 const detail = entry.detail?.trim();
358 return toolGroupAction(entry) === "read" &&
359 detail !== undefined &&
360 !/[\r\n]/.test(detail) &&
361 isWorkspaceImagePreviewPath(detail)
362 ? detail
363 : null;
365​
366export interface ViewedImageAsset {
367 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
368 readonly alt: string;
369 readonly srcFragment: string;
371​
372export function resolveViewedImageAsset(
373 source: string,
374 input: {
375 readonly threadId: ThreadId;
376 readonly workspaceRoot?: string | null | undefined;
377 },
378): ViewedImageAsset | null {
379 // A relative path with no known workspace still names a media-file relative
380 // to the thread's workspace, so classify against "." and drop the prefix.
381 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
382 if (imageSource._tag !== "WorkspaceFile") return null;
383 const resolvedFilePath =
384 input.workspaceRoot == null && imageSource.path.startsWith("./")
385 ? imageSource.path.slice(2)
386 : imageSource.path;
387​
388 const media = resolveMediaSource(source, {
389 threadId: input.threadId,
390 workspaceRoot: input.workspaceRoot,
391 resolvedFilePath,
392 });
393 if (media === null || media.access !== "environment") return null;
394 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
396​
397function toolGroupActionCount(
398 action: ToolGroupAction,
399 entries: ReadonlyArray<WorkLogPresentationEntry>,
400): number {
401 if (action !== "edit") return entries.length;
402​
403 const changedFiles = new Set<string>();
404 let editsWithoutFileDetails = 0;
405 for (const entry of entries) {
406 if (!entry.changedFiles || entry.changedFiles.length === 0) {
407 editsWithoutFileDetails += 1;
408 continue;
409 }
410 for (const file of entry.changedFiles) changedFiles.add(file);
411 }
412 return changedFiles.size + editsWithoutFileDetails;
414​
415function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
416 switch (action) {
417 case "read":
418 return `Read ${count} ${count === 1 ? "file" : "files"}`;
419 case "edit":
420 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
421 case "command":
422 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
423 case "browser":
424 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
425 case "search":
426 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
427 case "code-search":
428 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
429 case "other":
430 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
431 case "update":
432 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
433 }
435​
436export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): string {
437 const summaryEntries = omitSupersededLifecycleMarkers(entries, (entry) => entry);
438 const sources = new Map<string, ToolActivitySource>();
439 const groupedEntries = new Map<ToolGroupAction, WorkLogPresentationEntry[]>();
440 for (const entry of summaryEntries) {
441 if (entry.toolSource) {
442 sources.set(entry.toolSource.key, entry.toolSource);
443 continue;
444 }
445 const action = toolGroupAction(entry);
446 const group = groupedEntries.get(action);
447 if (group) group.push(entry);
448 else groupedEntries.set(action, [entry]);
449 }
450 const labels = [...groupedEntries].map(([action, actionEntries]) =>
451 toolGroupActionLabel(action, toolGroupActionCount(action, actionEntries)),
452 );
453 if (sources.size > 0) {
454 const sourceValues = [...sources.values()];
455 const sourceNames = sourceValues.map((source) => source.name);
456 const formattedNames =
457 sourceNames.length < 2
458 ? sourceNames[0]!
459 : sourceNames.length === 2
460 ? sourceNames.join(" and ")
461 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
462 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
463 labels.unshift(
464 `Used ${formattedNames}${allIntegrations ? ` ${sources.size === 1 ? "integration" : "integrations"}` : ""}`,
465 );
466 }
467 const sentenceLabels = labels.map((label, index) =>
468 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
469 );
470 if (sentenceLabels.length < 2) return sentenceLabels[0] ?? "";
471 if (sentenceLabels.length === 2) return sentenceLabels.join(" and ");
472 return `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
474​
475export function omitSupersededLifecycleMarkers<T>(
476 entries: readonly T[],
477 workEntryFor: (entry: T) => WorkLogPresentationEntry,
478): T[] {
479 const laterTerminalIdentities = new Set<string>();
480 const reversedEntries: T[] = [];
481​
482 for (let index = entries.length - 1; index >= 0; index -= 1) {
483 const entry = entries[index]!;
484 const workEntry = workEntryFor(entry);
485 const normalizedLabel = normalizeCompactToolLabel(workEntry.toolTitle ?? workEntry.label);
486 const identity = [
487 workEntry.turnId ?? "no-turn",
488 workEntry.itemType ?? "",
489 normalizedLabel,
490 ].join("\u001f");
491 const activityKind = workEntry.sourceActivityKind;
492 const isStatuslessIdlessMarker =
493 workEntry.toolCallId === undefined &&
494 workEntry.toolLifecycleStatus === undefined &&
495 (activityKind === "tool.started" || activityKind === "tool.updated");
496 if (isStatuslessIdlessMarker && laterTerminalIdentities.has(identity)) continue;
497​
498 reversedEntries.push(entry);
499 if (
500 activityKind === "tool.completed" ||
501 (workEntry.toolLifecycleStatus !== undefined &&
502 workEntry.toolLifecycleStatus !== "inProgress")
503 ) {
504 laterTerminalIdentities.add(identity);
505 }
506 }
507​
508 return reversedEntries.toReversed();
510​
511export function toolGroupSummaryKind(
512 entries: ReadonlyArray<WorkLogPresentationEntry>,
513): ToolGroupSummaryKind {
514 const actions = new Set(entries.map(toolGroupAction));
515 if (actions.size !== 1) return "mixed";
516​
517 const action = actions.values().next().value!;
518 if (action !== "other") return action;
519​
520 const fallbackKinds = new Set(
521 entries.map((entry): ToolGroupSummaryKind => {
522 if (entry.itemType === "mcp_tool_call") return "other";
523 if (entry.itemType === "dynamic_tool_call") return "dynamic-tool";
524 if (entry.itemType === "collab_agent_tool_call" || entry.taskId) return "agent-tool";
525 if (entry.tone === "thinking") return "agent-tool";
526 if (entry.tone === "tool") return "tone-tool";
527 return "other";
528 }),
529 );
530 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";