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

presentation.ts

503 lines18.3 KB

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