Open History to see the last commit
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";
15}
16
17export interface WorkLogPresentationEntry {
18 readonly label: string;
19 readonly toolTitle?: string;
20 readonly tone: "thinking" | "tool" | "info" | "error";
21 readonly command?: string;
22 readonly detail?: 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;
31}
32
33export type ToolGroupAction =
34 | "read"
35 | "edit"
36 | "command"
37 | "code-search"
38 | "search"
39 | "other"
40 | "update";
41
42export type ToolGroupSummaryKind =
43 | ToolGroupAction
44 | "dynamic-tool"
45 | "agent-tool"
46 | "tone-tool"
47 | "mixed";
48
49export function normalizeCompactToolLabel(value: string): string {
50 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
51}
52
53function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
54 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
55 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
56 if (entry.requestKind !== undefined) return true;
57 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
58}
59
60export function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
61 return (
62 entry.itemType === "web_search" &&
63 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
64 );
65}
66
67export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
68 if (
69 entry.requestKind === "file-read" ||
70 entry.itemType === "image_view" ||
71 (entry.itemType === "dynamic_tool_call" &&
72 entry.toolTitle?.trim().toLowerCase() === "read file")
73 ) {
74 return "read";
75 }
76 if (
77 entry.requestKind === "file-change" ||
78 entry.itemType === "file_change" ||
79 (entry.changedFiles?.length ?? 0) > 0
80 ) {
81 return "edit";
82 }
83 if (entry.requestKind === "command" || entry.itemType === "command_execution" || entry.command) {
84 return "command";
85 }
86 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
87 if (entry.itemType === "web_search") return "search";
88 return workLogEntryIsToolLike(entry) ? "other" : "update";
89}
90
91export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
92 const detail = entry.detail?.trim();
93 return toolGroupAction(entry) === "read" &&
94 detail !== undefined &&
95 !/[\r\n]/.test(detail) &&
96 isWorkspaceImagePreviewPath(detail)
97 ? detail
98 : null;
99}
100
101export interface ViewedImageAsset {
102 readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "workspace-file" }>;
103 readonly alt: string;
104 readonly srcFragment: string;
105}
106
107const ABSOLUTE_IMAGE_SOURCE_PATTERN = /^(?:file:|[\\/]|[a-z]:[\\/])/i;
108const T3_ATTACHMENT_IMAGE_PATH_PATTERN =
109 /(?:^|[\\/])(?:dev|userdata)[\\/]attachments[\\/]([a-z0-9_-]{1,128})\.[a-z0-9]{1,10}$/i;
110
111export function resolveViewedImageAsset(
112 source: string,
113 input: {
114 readonly threadId: ThreadId;
115 readonly workspaceRoot?: string | null | undefined;
116 },
117): ViewedImageAsset | null {
118 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
119 if (imageSource._tag !== "WorkspaceFile") return null;
120
121 const path =
122 input.workspaceRoot == null && imageSource.path.startsWith("./")
123 ? imageSource.path.slice(2)
124 : imageSource.path;
125 const attachmentId = ABSOLUTE_IMAGE_SOURCE_PATTERN.test(source)
126 ? (T3_ATTACHMENT_IMAGE_PATH_PATTERN.exec(path)?.[1] ?? null)
127 : null;
128
129 return {
130 resource: attachmentId
131 ? { _tag: "attachment", attachmentId }
132 : { _tag: "workspace-file", threadId: input.threadId, path },
133 alt: path.split(/[\\/]/).at(-1) ?? "image",
134 srcFragment: markdownImageSourceFragment(source),
135 };
136}
137
138function toolGroupActionCount(
139 action: ToolGroupAction,
140 entries: ReadonlyArray<WorkLogPresentationEntry>,
141): number {
142 if (action !== "edit") return entries.length;
143
144 const changedFiles = new Set<string>();
145 let editsWithoutFileDetails = 0;
146 for (const entry of entries) {
147 if (!entry.changedFiles || entry.changedFiles.length === 0) {
148 editsWithoutFileDetails += 1;
149 continue;
150 }
151 for (const file of entry.changedFiles) changedFiles.add(file);
152 }
153 return changedFiles.size + editsWithoutFileDetails;
154}
155
156function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
157 switch (action) {
158 case "read":
159 return `Read ${count} ${count === 1 ? "file" : "files"}`;
160 case "edit":
161 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
162 case "command":
163 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
164 case "search":
165 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
166 case "code-search":
167 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
168 case "other":
169 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
170 case "update":
171 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
172 }
173}
174
175export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): string {
176 const summaryEntries = omitSupersededLifecycleMarkers(entries, (entry) => entry);
177 const groupedEntries = new Map<ToolGroupAction, WorkLogPresentationEntry[]>();
178 for (const entry of summaryEntries) {
179 const action = toolGroupAction(entry);
180 const group = groupedEntries.get(action);
181 if (group) group.push(entry);
182 else groupedEntries.set(action, [entry]);
183 }
184 const labels = [...groupedEntries].map(([action, actionEntries]) =>
185 toolGroupActionLabel(action, toolGroupActionCount(action, actionEntries)),
186 );
187 const sentenceLabels = labels.map((label, index) =>
188 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
189 );
190 if (sentenceLabels.length < 2) return sentenceLabels[0] ?? "";
191 if (sentenceLabels.length === 2) return sentenceLabels.join(" and ");
192 return `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
193}
194
195export function omitSupersededLifecycleMarkers<T>(
196 entries: readonly T[],
197 workEntryFor: (entry: T) => WorkLogPresentationEntry,
198): T[] {
199 const laterTerminalIdentities = new Set<string>();
200 const reversedEntries: T[] = [];
201
202 for (let index = entries.length - 1; index >= 0; index -= 1) {
203 const entry = entries[index]!;
204 const workEntry = workEntryFor(entry);
205 const normalizedLabel = normalizeCompactToolLabel(workEntry.toolTitle ?? workEntry.label);
206 const identity = [
207 workEntry.turnId ?? "no-turn",
208 workEntry.itemType ?? "",
209 normalizedLabel,
210 ].join("\u001f");
211 const activityKind = workEntry.sourceActivityKind;
212 const isStatuslessIdlessMarker =
213 workEntry.toolCallId === undefined &&
214 workEntry.toolLifecycleStatus === undefined &&
215 (activityKind === "tool.started" || activityKind === "tool.updated");
216 if (isStatuslessIdlessMarker && laterTerminalIdentities.has(identity)) continue;
217
218 reversedEntries.push(entry);
219 if (
220 activityKind === "tool.completed" ||
221 (workEntry.toolLifecycleStatus !== undefined &&
222 workEntry.toolLifecycleStatus !== "inProgress")
223 ) {
224 laterTerminalIdentities.add(identity);
225 }
226 }
227
228 return reversedEntries.toReversed();
229}
230
231export function toolGroupSummaryKind(
232 entries: ReadonlyArray<WorkLogPresentationEntry>,
233): ToolGroupSummaryKind {
234 const actions = new Set(entries.map(toolGroupAction));
235 if (actions.size !== 1) return "mixed";
236
237 const action = actions.values().next().value!;
238 if (action !== "other") return action;
239
240 const fallbackKinds = new Set(
241 entries.map((entry): ToolGroupSummaryKind => {
242 if (entry.itemType === "mcp_tool_call") return "other";
243 if (entry.itemType === "dynamic_tool_call") return "dynamic-tool";
244 if (entry.itemType === "collab_agent_tool_call" || entry.taskId) return "agent-tool";
245 if (entry.tone === "thinking") return "agent-tool";
246 if (entry.tone === "tool") return "tone-tool";
247 return "other";
248 }),
249 );
250 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
251}