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

presentation.ts

504 lines18.0 KB

1import {
2 isToolLifecycleItemType,
3 type AssetResource,
4 type ThreadId,
5 type ToolLifecycleItemType,
6} from "@t3tools/contracts";
7import {
8 classifyMarkdownImageSource,
9 markdownImageSourceFragment,
10} from "@t3tools/client-runtime/markdown-images";
11import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
12​
13export function isWorktreeSetupActivity(kind: string): boolean {
14 return kind === "setup-script.requested" || kind === "setup-script.started";
16​
17export interface WorkLogPresentationEntry {
18 readonly label: string;
19 readonly toolTitle?: string;
20 readonly toolData?: unknown;
21 readonly tone: "thinking" | "tool" | "info" | "error";
22 readonly command?: string;
23 readonly detail?: string;
24 readonly viewedImagePath?: string;
25 readonly changedFiles?: ReadonlyArray<string>;
26 readonly itemType?: ToolLifecycleItemType;
27 readonly requestKind?: string;
28 readonly turnId?: string | null;
29 readonly toolCallId?: string;
30 readonly toolLifecycleStatus?: string;
31 readonly sourceActivityKind?: string;
32 readonly taskId?: string;
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 : action;
119​
120 return {
121 displayName: `${verb} ${detail}`,
122 icon: name.startsWith("preview_") ? ("browser" as const) : ("t3-code" as const),
123 };
125​
126/** Resolves tool identity before choosing labels or icons in either client. */
127export function resolveWorkEntryToolPresentation(
128 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "toolLifecycleStatus">,
129 fallbackStatus?: "inProgress" | "completed",
130) {
131 const status = entry.toolLifecycleStatus ?? fallbackStatus;
132 const data = entry.toolData;
133 if (data !== null && typeof data === "object") {
134 if (
135 "server" in data &&
136 typeof data.server === "string" &&
137 "tool" in data &&
138 typeof data.tool === "string"
139 ) {
140 return resolveT3McpToolPresentation(`${data.server}.${data.tool}`, status);
141 }
142 if ("toolName" in data && typeof data.toolName === "string") {
143 return resolveT3McpToolPresentation(data.toolName, status);
144 }
145 }
146​
147 return (
148 resolveT3McpToolPresentation(entry.toolTitle, status) ??
149 resolveT3McpToolPresentation(entry.label, status)
150 );
152​
153function asRecord(value: unknown): Record<string, unknown> | null {
154 return value !== null && typeof value === "object" && !Array.isArray(value)
155 ? (value as Record<string, unknown>)
156 : null;
158​
159function nonEmptyString(value: unknown): string | null {
160 return typeof value === "string" && value.trim().length > 0 ? value : null;
162​
163function commandResultContent(value: unknown): string | null {
164 const direct = nonEmptyString(value);
165 if (direct) return direct;
166​
167 const directContent = Array.isArray(value) ? value : null;
168 const record = asRecord(value);
169 const content = record?.content;
170 const contentText = nonEmptyString(content);
171 if (contentText) return contentText;
172 const blocks = directContent ?? (Array.isArray(content) ? content : null);
173 if (!blocks) return null;
174​
175 const chunks = blocks.flatMap((entry) => {
176 const text = nonEmptyString(entry) ?? nonEmptyString(asRecord(entry)?.text);
177 return text ? [text] : [];
178 });
179 return chunks.length > 0 ? chunks.join("\n") : null;
181​
182/** Returns provider command output before it is formatted for a work-log row. */
183export function extractCommandOutputText(dataValue: unknown): string | null {
184 const data = asRecord(dataValue);
185 const item = asRecord(data?.item);
186 const itemResult = asRecord(item?.result);
187 const rawOutput = asRecord(data?.rawOutput);
188 const outputStreams = [
189 nonEmptyString(rawOutput?.stdout),
190 nonEmptyString(rawOutput?.stderr),
191 ].filter((value): value is string => value !== null);
192 const acpContent = Array.isArray(data?.content)
193 ? data.content
194 .flatMap((entryValue) => {
195 const entry = asRecord(entryValue);
196 const content = asRecord(entry?.content);
197 const text = entry?.type === "content" ? nonEmptyString(content?.text) : null;
198 return text ? [text] : [];
199 })
200 .join("\n")
201 : null;
202​
203 const candidates = [
204 item?.aggregatedOutput,
205 itemResult?.content,
206 data?.rawOutput,
207 rawOutput?.content,
208 outputStreams.length > 0 ? outputStreams.join("\n") : null,
209 rawOutput?.output,
210 acpContent,
211 data?.result,
212 ];
213 for (const candidate of candidates) {
214 const text = commandResultContent(candidate);
215 if (text) return text;
216 }
217 return null;
219​
220/**
221 * Ingestion caps tool details at 180 chars and appends "...", so a long command
222 * echo no longer equals the command it repeats. Treat a truncated prefix of the
223 * command as the same echo.
224 */
225function textRepeatsCommand(text: string, commands: ReadonlyArray<string | null>): boolean {
226 const truncated = text.endsWith("...")
227 ? text.slice(0, -3)
228 : text.endsWith("\u2026")
229 ? text.slice(0, -1)
230 : null;
231 return commands.some((candidate) => {
232 const command = candidate?.trim();
233 if (!command) return false;
234 if (command === text) return true;
235 return (
236 truncated !== null &&
237 truncated.length > 0 &&
238 command.length > truncated.length &&
239 command.startsWith(truncated)
240 );
241 });
243​
244/**
245 * Decides whether a command row's `detail` is a synthetic echo of the command
246 * rather than real output. OpenCode stores completed output in `detail` with no
247 * other output channel, so plain equality is only treated as synthetic when the
248 * payload shape shows the detail came from the command: Codex item metadata,
249 * an ACP tool call (`data.toolCallId`, `kind: "execute"`), a Claude tool-name
250 * prefix, or no structured command at all.
251 */
252export function commandDetailRepeatsCommand(input: {
253 readonly detail: string;
254 readonly command: string | null;
255 readonly rawCommand: string | null;
256 readonly toolName: unknown;
257 readonly data: unknown;
258}): boolean {
259 const toolName = nonEmptyString(input.toolName)?.trim();
260 const detail = input.detail.trim();
261 const commands = [input.command, input.rawCommand];
262 if (toolName) {
263 const prefix = `${toolName}:`;
264 if (detail.toLowerCase().startsWith(prefix.toLowerCase())) {
265 const unprefixed = detail.slice(prefix.length).trim();
266 if (textRepeatsCommand(unprefixed, commands)) return true;
267 }
268 }
269​
270 if (!textRepeatsCommand(detail, commands)) return false;
271​
272 const data = asRecord(input.data);
273 const item = asRecord(data?.item);
274 const itemInput = asRecord(item?.input);
275 const itemResult = asRecord(item?.result);
276 const hasStructuredCommand = [
277 item?.command,
278 itemInput?.command,
279 itemResult?.command,
280 data?.command,
281 ].some((value) =>
282 Array.isArray(value)
283 ? value.some((part) => nonEmptyString(part) !== null)
284 : nonEmptyString(value) !== null,
285 );
286 return (
287 !hasStructuredCommand ||
288 item !== null ||
289 data?.toolCallId !== undefined ||
290 nonEmptyString(data?.kind)?.toLowerCase() === "execute"
291 );
293​
294function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
295 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
296 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
297 if (entry.requestKind !== undefined) return true;
298 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
300​
301export function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
302 return (
303 entry.itemType === "web_search" &&
304 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
305 );
307​
308export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
309 if (resolveWorkEntryToolPresentation(entry)?.icon === "browser") return "browser";
310 if (
311 entry.requestKind === "file-read" ||
312 entry.itemType === "image_view" ||
313 entry.viewedImagePath !== undefined ||
314 (entry.itemType === "dynamic_tool_call" &&
315 entry.toolTitle?.trim().toLowerCase() === "read file")
316 ) {
317 return "read";
318 }
319 if (
320 entry.requestKind === "file-change" ||
321 entry.itemType === "file_change" ||
322 (entry.changedFiles?.length ?? 0) > 0
323 ) {
324 return "edit";
325 }
326 if (entry.requestKind === "command" || entry.itemType === "command_execution" || entry.command) {
327 return "command";
328 }
329 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
330 if (entry.itemType === "web_search") return "search";
331 return workLogEntryIsToolLike(entry) ? "other" : "update";
333​
334export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
335 const viewedImagePath = entry.viewedImagePath?.trim();
336 if (
337 viewedImagePath !== undefined &&
338 !/[\r\n]/.test(viewedImagePath) &&
339 isWorkspaceImagePreviewPath(viewedImagePath)
340 ) {
341 return viewedImagePath;
342 }
343 const detail = entry.detail?.trim();
344 return toolGroupAction(entry) === "read" &&
345 detail !== undefined &&
346 !/[\r\n]/.test(detail) &&
347 isWorkspaceImagePreviewPath(detail)
348 ? detail
349 : null;
351​
352export interface ViewedImageAsset {
353 readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "media-file" }>;
354 readonly alt: string;
355 readonly srcFragment: string;
357​
358const ABSOLUTE_IMAGE_SOURCE_PATTERN = /^(?:file:|[\\/]|[a-z]:[\\/])/i;
359const T3_ATTACHMENT_IMAGE_PATH_PATTERN =
360 /(?:^|[\\/])(?:dev|userdata)[\\/]attachments[\\/]([a-z0-9_-]{1,128})\.[a-z0-9]{1,10}$/i;
361​
362export function resolveViewedImageAsset(
363 source: string,
364 input: {
365 readonly threadId: ThreadId;
366 readonly workspaceRoot?: string | null | undefined;
367 },
368): ViewedImageAsset | null {
369 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
370 if (imageSource._tag !== "WorkspaceFile") return null;
371​
372 const path =
373 input.workspaceRoot == null && imageSource.path.startsWith("./")
374 ? imageSource.path.slice(2)
375 : imageSource.path;
376 const attachmentId = ABSOLUTE_IMAGE_SOURCE_PATTERN.test(source)
377 ? (T3_ATTACHMENT_IMAGE_PATH_PATTERN.exec(path)?.[1] ?? null)
378 : null;
379​
380 return {
381 resource: attachmentId
382 ? { _tag: "attachment", attachmentId }
383 : { _tag: "media-file", threadId: input.threadId, path },
384 alt: path.split(/[\\/]/).at(-1) ?? "image",
385 srcFragment: markdownImageSourceFragment(source),
386 };
388​
389function toolGroupActionCount(
390 action: ToolGroupAction,
391 entries: ReadonlyArray<WorkLogPresentationEntry>,
392): number {
393 if (action !== "edit") return entries.length;
394​
395 const changedFiles = new Set<string>();
396 let editsWithoutFileDetails = 0;
397 for (const entry of entries) {
398 if (!entry.changedFiles || entry.changedFiles.length === 0) {
399 editsWithoutFileDetails += 1;
400 continue;
401 }
402 for (const file of entry.changedFiles) changedFiles.add(file);
403 }
404 return changedFiles.size + editsWithoutFileDetails;
406​
407function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
408 switch (action) {
409 case "read":
410 return `Read ${count} ${count === 1 ? "file" : "files"}`;
411 case "edit":
412 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
413 case "command":
414 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
415 case "browser":
416 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
417 case "search":
418 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
419 case "code-search":
420 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
421 case "other":
422 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
423 case "update":
424 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
425 }
427​
428export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): string {
429 const summaryEntries = omitSupersededLifecycleMarkers(entries, (entry) => entry);
430 const groupedEntries = new Map<ToolGroupAction, WorkLogPresentationEntry[]>();
431 for (const entry of summaryEntries) {
432 const action = toolGroupAction(entry);
433 const group = groupedEntries.get(action);
434 if (group) group.push(entry);
435 else groupedEntries.set(action, [entry]);
436 }
437 const labels = [...groupedEntries].map(([action, actionEntries]) =>
438 toolGroupActionLabel(action, toolGroupActionCount(action, actionEntries)),
439 );
440 const sentenceLabels = labels.map((label, index) =>
441 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
442 );
443 if (sentenceLabels.length < 2) return sentenceLabels[0] ?? "";
444 if (sentenceLabels.length === 2) return sentenceLabels.join(" and ");
445 return `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
447​
448export function omitSupersededLifecycleMarkers<T>(
449 entries: readonly T[],
450 workEntryFor: (entry: T) => WorkLogPresentationEntry,
451): T[] {
452 const laterTerminalIdentities = new Set<string>();
453 const reversedEntries: T[] = [];
454​
455 for (let index = entries.length - 1; index >= 0; index -= 1) {
456 const entry = entries[index]!;
457 const workEntry = workEntryFor(entry);
458 const normalizedLabel = normalizeCompactToolLabel(workEntry.toolTitle ?? workEntry.label);
459 const identity = [
460 workEntry.turnId ?? "no-turn",
461 workEntry.itemType ?? "",
462 normalizedLabel,
463 ].join("\u001f");
464 const activityKind = workEntry.sourceActivityKind;
465 const isStatuslessIdlessMarker =
466 workEntry.toolCallId === undefined &&
467 workEntry.toolLifecycleStatus === undefined &&
468 (activityKind === "tool.started" || activityKind === "tool.updated");
469 if (isStatuslessIdlessMarker && laterTerminalIdentities.has(identity)) continue;
470​
471 reversedEntries.push(entry);
472 if (
473 activityKind === "tool.completed" ||
474 (workEntry.toolLifecycleStatus !== undefined &&
475 workEntry.toolLifecycleStatus !== "inProgress")
476 ) {
477 laterTerminalIdentities.add(identity);
478 }
479 }
480​
481 return reversedEntries.toReversed();
483​
484export function toolGroupSummaryKind(
485 entries: ReadonlyArray<WorkLogPresentationEntry>,
486): ToolGroupSummaryKind {
487 const actions = new Set(entries.map(toolGroupAction));
488 if (actions.size !== 1) return "mixed";
489​
490 const action = actions.values().next().value!;
491 if (action !== "other") return action;
492​
493 const fallbackKinds = new Set(
494 entries.map((entry): ToolGroupSummaryKind => {
495 if (entry.itemType === "mcp_tool_call") return "other";
496 if (entry.itemType === "dynamic_tool_call") return "dynamic-tool";
497 if (entry.itemType === "collab_agent_tool_call" || entry.taskId) return "agent-tool";
498 if (entry.tone === "thinking") return "agent-tool";
499 if (entry.tone === "tool") return "tone-tool";
500 return "other";
501 }),
502 );
503 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";