Open History to see the last commit
1import { type ThreadId } from "@t3tools/contracts";
2import type { PickedElementPayload, PickedElementStackFrame } from "@t3tools/contracts";
3
4const ELEMENT_CONTEXT_HTML_PREVIEW_LIMIT = 4000;
5const ELEMENT_CONTEXT_STYLES_LIMIT = 4000;
6const ELEMENT_CONTEXT_LABEL_TAG_MAX = 24;
7
8const TRAILING_ELEMENT_CONTEXT_BLOCK_PATTERN =
9 /\n*<element_context>\n([\s\S]*?)\n<\/element_context>\s*$/;
10
11/**
12 * Stable, persistable element selection captured from the in-app preview
13 * browser. We deliberately keep the shape JSON-serializable so it can ride
14 * through `localStorage` persistence, draft restoration, and transcript
15 * snapshots without bespoke marshalling.
16 */
17export interface ElementContextSelection {
18 /** Page URL where the element was picked. */
19 pageUrl: string;
20 /** Best-effort `<title>`. */
21 pageTitle: string | null;
22 /** Lowercase tag, e.g. `"button"`. */
23 tagName: string;
24 /** CSS selector — may be null when react-grab can't compute one. */
25 selector: string | null;
26 /** Truncated outer-HTML preview. */
27 htmlPreview: string;
28 /** Nearest React component display name, or null. */
29 componentName: string | null;
30 /** Source frame (file + line) — null when unavailable. */
31 source: PickedElementStackFrame | null;
32 /** Author CSS (no UA defaults). May be empty. */
33 styles: string;
34}
35
36export interface ElementContextDraft extends ElementContextSelection {
37 /** Stable composer-side id used for keyed rendering + dedupe. */
38 id: string;
39 threadId: ThreadId;
40 /** ISO-8601 wall clock pick time. */
41 pickedAt: string;
42}
43
44export interface ParsedElementContextEntry {
45 header: string;
46 body: string;
47}
48
49export interface ExtractedElementContexts {
50 promptText: string;
51 contextCount: number;
52 contexts: ParsedElementContextEntry[];
53}
54
55function truncateString(value: string, limit: number): string {
56 if (value.length <= limit) return value;
57 return `${value.slice(0, Math.max(0, limit - 1))}…`;
58}
59
60function normalizeText(value: string): string {
61 return value.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
62}
63
64/**
65 * Sanitize a payload coming back from the desktop bridge before it lands in
66 * the composer draft. Trims/clamps every string field so we never persist a
67 * 5MB outerHTML blob and silently break `localStorage`.
68 */
69export function normalizeElementContextSelection(
70 raw: PickedElementPayload,
71): ElementContextSelection | null {
72 const pageUrl = raw.pageUrl.trim();
73 const tagName = raw.tagName.trim().toLowerCase();
74 if (pageUrl.length === 0 || tagName.length === 0) {
75 return null;
76 }
77 const stackFrame = raw.source ?? raw.stack[0] ?? null;
78 return {
79 pageUrl,
80 pageTitle: raw.pageTitle?.trim() ?? null,
81 tagName,
82 selector: raw.selector?.trim() || null,
83 htmlPreview: truncateString(normalizeText(raw.htmlPreview), ELEMENT_CONTEXT_HTML_PREVIEW_LIMIT),
84 componentName: raw.componentName?.trim() || null,
85 source: stackFrame
86 ? {
87 functionName: stackFrame.functionName?.trim() || null,
88 fileName: stackFrame.fileName?.trim() || null,
89 lineNumber: stackFrame.lineNumber ?? null,
90 columnNumber: stackFrame.columnNumber ?? null,
91 }
92 : null,
93 styles: truncateString(normalizeText(raw.styles), ELEMENT_CONTEXT_STYLES_LIMIT),
94 };
95}
96
97/**
98 * Stable dedupe key. Two picks of the same element on the same page produce
99 * the same key, so we don't end up with a runaway chip row from spam-clicks.
100 */
101export function elementContextDedupKey(context: ElementContextSelection): string {
102 return [context.pageUrl, context.selector ?? "", context.tagName, context.componentName ?? ""]
103 .join("|")
104 .toLowerCase();
105}
106
107function shortenTagLabel(tagName: string): string {
108 if (tagName.length <= ELEMENT_CONTEXT_LABEL_TAG_MAX) return tagName;
109 return `${tagName.slice(0, ELEMENT_CONTEXT_LABEL_TAG_MAX - 1)}…`;
110}
111
112/**
113 * Compact chip label — `<Button>` for component picks, `<button>` otherwise.
114 * Component name takes priority because it's higher-signal for the agent.
115 */
116export function formatElementContextLabel(context: ElementContextSelection): string {
117 if (context.componentName) return `<${context.componentName}>`;
118 return `<${shortenTagLabel(context.tagName)}>`;
119}
120
121function basenameFromPath(filePath: string): string {
122 const parts = filePath.split(/[\\/]/);
123 return parts[parts.length - 1] ?? filePath;
124}
125
126export function formatElementContextSourceLabel(context: ElementContextSelection): string | null {
127 const source = context.source;
128 if (!source?.fileName) return null;
129 const base = basenameFromPath(source.fileName);
130 if (source.lineNumber == null) return base;
131 return `${base}:${source.lineNumber}`;
132}
133
134function buildContextHeader(context: ElementContextSelection): string {
135 const label = formatElementContextLabel(context);
136 const source = formatElementContextSourceLabel(context);
137 return source ? `${label} (${source})` : label;
138}
139
140function indentLines(value: string): string[] {
141 return value.split("\n").map((line) => ` ${line}`);
142}
143
144function buildSingleContextLines(context: ElementContextSelection): string[] {
145 const lines: string[] = [];
146 lines.push(`- ${buildContextHeader(context)}:`);
147 if (context.pageUrl.length > 0) {
148 lines.push(` url: ${context.pageUrl}`);
149 }
150 if (context.selector) {
151 lines.push(` selector: ${context.selector}`);
152 }
153 if (context.source?.fileName) {
154 const { fileName, lineNumber, columnNumber } = context.source;
155 const location =
156 lineNumber != null
157 ? `${fileName}:${lineNumber}${columnNumber != null ? `:${columnNumber}` : ""}`
158 : fileName;
159 lines.push(` source: ${location}`);
160 }
161 const html = context.htmlPreview.trim();
162 if (html.length > 0) {
163 lines.push(" html:");
164 lines.push(...indentLines(html));
165 }
166 const styles = context.styles.trim();
167 if (styles.length > 0) {
168 lines.push(" styles:");
169 lines.push(...indentLines(styles));
170 }
171 return lines;
172}
173
174/**
175 * Serialize element-context drafts into the `<element_context>` block we
176 * append to the user's outgoing message text. Mirrors the `<terminal_context>`
177 * block format so it composes cleanly when both are present.
178 */
179export function buildElementContextBlock(contexts: ReadonlyArray<ElementContextSelection>): string {
180 if (contexts.length === 0) return "";
181 const lines: string[] = [];
182 for (let index = 0; index < contexts.length; index += 1) {
183 const context = contexts[index]!;
184 lines.push(...buildSingleContextLines(context));
185 if (index < contexts.length - 1) lines.push("");
186 }
187 return ["<element_context>", ...lines, "</element_context>"].join("\n");
188}
189
190export function appendElementContextsToPrompt(
191 prompt: string,
192 contexts: ReadonlyArray<ElementContextSelection>,
193): string {
194 const block = buildElementContextBlock(contexts);
195 if (block.length === 0) return prompt;
196 const trimmed = prompt.trim();
197 return trimmed.length > 0 ? `${trimmed}\n\n${block}` : block;
198}
199
200const ELEMENT_CONTEXT_ID_PREFIX = "el_";
201let nextElementContextSequence = 0;
202
203export function newElementContextId(): string {
204 nextElementContextSequence += 1;
205 return `${ELEMENT_CONTEXT_ID_PREFIX}${nextElementContextSequence.toString(36)}`;
206}
207
208/**
209 * Mirror image of `appendElementContextsToPrompt` for transcript display:
210 * detects (and strips) a trailing `<element_context>` block so we can render
211 * the original prompt body and chips separately in user-message bubbles.
212 */
213export function extractTrailingElementContexts(prompt: string): ExtractedElementContexts {
214 const match = TRAILING_ELEMENT_CONTEXT_BLOCK_PATTERN.exec(prompt);
215 if (!match) {
216 return { promptText: prompt, contextCount: 0, contexts: [] };
217 }
218 const promptText = prompt.slice(0, match.index).replace(/\n+$/, "");
219 const contexts = parseElementContextEntries(match[1] ?? "");
220 return { promptText, contextCount: contexts.length, contexts };
221}
222
223function parseElementContextEntries(block: string): ParsedElementContextEntry[] {
224 const entries: ParsedElementContextEntry[] = [];
225 let current: { header: string; bodyLines: string[] } | null = null;
226 const commit = () => {
227 if (!current) return;
228 entries.push({ header: current.header, body: current.bodyLines.join("\n").trimEnd() });
229 current = null;
230 };
231 for (const line of block.split("\n")) {
232 const headerMatch = /^- (.+):$/.exec(line);
233 if (headerMatch) {
234 commit();
235 current = { header: headerMatch[1]!, bodyLines: [] };
236 continue;
237 }
238 if (!current) continue;
239 if (line.startsWith(" ")) current.bodyLines.push(line.slice(2));
240 else if (line.length === 0) current.bodyLines.push("");
241 }
242 commit();
243 return entries;
244}