Open History to see the last commit
1import {
2 type ComposerContextId,
3 ComposerContextRecord,
4 type ElementContextRecord,
5 type PreviewAnnotationContextRecord,
6 ReviewCommentContextRecord,
7 type TerminalContextRecord,
8} from "@t3tools/contracts";
9import * as Schema from "effect/Schema";
10
11import { formatComposerContextReference } from "./composerContextReferences.ts";
12
13/**
14 * Upgrades a message written before inline context references: trailing
15 * `<terminal_context>`, `<element_context>` and `<preview_annotation>` blocks, inline or
16 * trailing `<review_comment>` blocks, and U+FFFC terminal placeholders. Produces canonical
17 * reference links plus records so old messages render and copy through the new path.
18 * Event history is never rewritten; this runs in memory on read.
19 */
20
21export interface UpgradedLegacyContext {
22 text: string;
23 records: ComposerContextRecord[];
24}
25
26const PLACEHOLDER = "";
27const TRAILING_TERMINAL = /\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;
28const TRAILING_ELEMENT = /\n*<element_context>\n([\s\S]*?)\n<\/element_context>\s*$/;
29const TRAILING_PREVIEW =
30 /\n*<preview_annotation>\n((?:(?!\n<\/preview_annotation>)[\s\S])*)\n<\/preview_annotation>\s*$/;
31const REVIEW_OR_CONTEXT_BLOCK =
32 /<review_comment\b([^>]*)>|^<(terminal_context|element_context|preview_annotation)>\n[\s\S]*?\n<\/\2>/gm;
33const REVIEW_ATTRIBUTE = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
34const REVIEW_FENCE = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
35const REVIEW_TOKEN = "\uE000";
36const LEGACY_MARKERS =
37 /<(?:terminal_context|element_context|preview_annotation|review_comment)\b|/;
38const isReviewCommentContextRecord = Schema.is(ReviewCommentContextRecord);
39const isLegacyContextRecords = Schema.is(
40 Schema.Array(ComposerContextRecord).check(Schema.isMaxLength(200)),
41);
42
43interface ParsedEntry {
44 header: string;
45 body: string;
46}
47
48function parseEntries(block: string): ParsedEntry[] | null {
49 const entries: ParsedEntry[] = [];
50 let current: { header: string; bodyLines: string[] } | null = null;
51 const commit = () => {
52 if (!current) return;
53 entries.push({ header: current.header, body: current.bodyLines.join("\n").trimEnd() });
54 current = null;
55 };
56 for (const line of block.split("\n")) {
57 const headerMatch = /^- (.+):$/.exec(line);
58 if (headerMatch) {
59 commit();
60 current = { header: headerMatch[1]!, bodyLines: [] };
61 continue;
62 }
63 if (current && line.startsWith(" ")) current.bodyLines.push(line.slice(2));
64 else if (line.trim().length > 0) return null;
65 else if (current) current.bodyLines.push("");
66 }
67 commit();
68 return entries;
69}
70
71/** The inline label the old send path wrote for a terminal excerpt: `@terminal-1:509-514`. */
72function inlineTerminalLabel(record: TerminalContextRecord): string {
73 const slug = record.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
74 const range =
75 record.lineStart === record.lineEnd
76 ? `${record.lineStart}`
77 : `${record.lineStart}-${record.lineEnd}`;
78 return `@${slug}:${range}`;
79}
80
81function legacyId(kind: string, index: number): ComposerContextId {
82 return `legacy_${kind}_${index}` as ComposerContextId;
83}
84
85function terminalRecord(entry: ParsedEntry, index: number): TerminalContextRecord | null {
86 const header = /^(.*?) (?:line (\d+)|lines (\d+)-(\d+))$/.exec(entry.header);
87 if (!header) return null;
88 const terminalLabel = header[1]!.trim();
89 if (!terminalLabel) return null;
90 const lineStart = Number(header[2] ?? header[3]);
91 const lineEnd = Number(header[2] ?? header[4]);
92 const text = entry.body
93 .split("\n")
94 .map((line) => line.replace(/^\d+ \| ?/, ""))
95 .join("\n");
96 return {
97 version: 1,
98 contextId: legacyId("terminal", index),
99 kind: "terminal",
100 label: entry.header,
101 terminalId: terminalLabel.toLowerCase().replace(/\s+/g, "-"),
102 terminalLabel,
103 lineStart,
104 lineEnd,
105 text,
106 };
107}
108
109function parseSource(location: string): ElementContextRecord["source"] {
110 const match = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(location);
111 if (!match || !match[1]) return null;
112 return {
113 functionName: null,
114 fileName: match[1],
115 lineNumber: match[2] === undefined ? null : Number(match[2]),
116 columnNumber: match[3] === undefined ? null : Number(match[3]),
117 };
118}
119
120function elementRecord(entry: ParsedEntry, index: number): ElementContextRecord | null {
121 const header = /^<([^>]+)>/.exec(entry.header);
122 if (!header) return null;
123 const inner = header[1]!;
124 const fields: Record<string, string> = {};
125 const sections: Record<string, string[]> = {};
126 let section: string | null = null;
127 for (const line of entry.body.split("\n")) {
128 if (section && (line.startsWith(" ") || line.length === 0)) {
129 sections[section]!.push(line.slice(2));
130 continue;
131 }
132 section = null;
133 const field = /^([a-z]+): (.*)$/.exec(line);
134 if (field) {
135 fields[field[1]!] = field[2]!;
136 continue;
137 }
138 const sectionStart = /^(html|styles):$/.exec(line);
139 if (sectionStart) {
140 section = sectionStart[1]!;
141 sections[section] = [];
142 }
143 }
144 return {
145 version: 1,
146 contextId: legacyId("element", index),
147 kind: "element",
148 label: `<${inner}>`,
149 pageUrl: fields.url ?? "",
150 pageTitle: null,
151 tagName: inner.toLowerCase(),
152 selector: fields.selector ?? null,
153 htmlPreview: (sections.html ?? []).join("\n").trimEnd(),
154 componentName: /[A-Z]/.test(inner) ? inner : null,
155 source: fields.source ? parseSource(fields.source) : null,
156 styles: (sections.styles ?? []).join("\n").trimEnd(),
157 };
158}
159
160function previewRecord(body: string, index: number): PreviewAnnotationContextRecord | null {
161 const lines = body.split("\n");
162 // A legacy comment was written verbatim, so it can run over several lines and hold blank
163 // lines and markup of its own. Its value is every line up to the next field or the block that
164 // follows it — anything else is text the author typed, and dropping it loses instructions the
165 // chip that replaces this block cannot show.
166 const FIELD_PREFIXES = ["Preview annotation:", "Id: ", "Page: ", "Comment: ", "Targets: "];
167 const BLOCK_DELIMITER =
168 /^<\/?(?:terminal_context|element_context|preview_annotation|review_comment)\b/;
169 const isFieldStart = (line: string) =>
170 FIELD_PREFIXES.some((candidate) => line.startsWith(candidate)) ||
171 line === "Requested visual changes:" ||
172 BLOCK_DELIMITER.test(line) ||
173 line === "The attached screenshot is the annotated preview crop.";
174 const read = (prefix: string) => {
175 const start = lines.findIndex((line) => line.startsWith(prefix));
176 if (start < 0) return "";
177 let end = start + 1;
178 while (end < lines.length && !isFieldStart(lines[end]!)) end += 1;
179 return [lines[start]!.slice(prefix.length), ...lines.slice(start + 1, end)].join("\n").trim();
180 };
181 const styleHeading = lines.indexOf("Requested visual changes:");
182 const styleChanges: string[] = [];
183 if (styleHeading >= 0) {
184 for (const line of lines.slice(styleHeading + 1)) {
185 if (!line.startsWith("- ")) break;
186 styleChanges.push(line.slice(2));
187 }
188 }
189 const page = read("Page: ");
190 const pageIsUrl = /^https?:\/\//i.test(page);
191 const elements: NonNullable<PreviewAnnotationContextRecord["elements"]>[number][] = [];
192 for (const match of body.matchAll(/<element_context>\n([\s\S]*?)\n<\/element_context>/g)) {
193 const entries = parseEntries(match[1] ?? "");
194 if (entries === null) return null;
195 for (const entry of entries) {
196 const record = elementRecord(entry, elements.length + 1);
197 if (record === null) return null;
198 const {
199 version: _version,
200 contextId: _contextId,
201 kind: _kind,
202 label: _label,
203 ...details
204 } = record;
205 elements.push(details);
206 }
207 }
208 return {
209 version: 1,
210 contextId: legacyId("preview-annotation", index),
211 kind: "preview-annotation",
212 label: page || "Preview annotation",
213 annotationId: read("Id: "),
214 pageUrl: pageIsUrl ? page : (elements[0]?.pageUrl ?? ""),
215 pageTitle: pageIsUrl ? null : page || null,
216 comment: read("Comment: "),
217 targetSummary: read("Targets: "),
218 styleChanges,
219 ...(elements.length > 0 ? { elements } : {}),
220 };
221}
222
223function unescapeAttribute(value: string): string {
224 return value
225 .replace(/</g, "<")
226 .replace(/>/g, ">")
227 .replace(/"/g, '"')
228 .replace(/&/g, "&");
229}
230
231function reviewRecord(
232 rawAttributes: string,
233 rawBody: string,
234 index: number,
235): ReviewCommentContextRecord | null {
236 const attributes: Record<string, string> = {};
237 for (const match of rawAttributes.matchAll(REVIEW_ATTRIBUTE)) {
238 attributes[match[1]!] = unescapeAttribute(match[2] ?? "");
239 }
240 const filePath = attributes.filePath?.trim();
241 const sectionId = attributes.sectionId?.trim();
242 const startIndex = attributes.startIndex;
243 const endIndex = attributes.endIndex;
244 if (!filePath || !sectionId || !/^\d+$/.test(startIndex ?? "") || !/^\d+$/.test(endIndex ?? "")) {
245 return null;
246 }
247 const fences = Array.from(rawBody.matchAll(REVIEW_FENCE));
248 const fence = fences.at(-1);
249 const rangeLabel = attributes.rangeLabel?.trim() || "line";
250 const basename = filePath.split(/[\\/]/).at(-1) ?? filePath;
251 return {
252 version: 1,
253 contextId: legacyId("review-comment", index),
254 kind: "review-comment",
255 label: `${basename} ${rangeLabel}`,
256 sectionId,
257 sectionTitle: attributes.sectionTitle?.trim() || "Review",
258 filePath,
259 startIndex: Math.min(Number(startIndex), Number(endIndex)),
260 endIndex: Math.max(Number(startIndex), Number(endIndex)),
261 rangeLabel,
262 text: rawBody.slice(0, fence?.index ?? rawBody.length).trim(),
263 diff: fence?.[3] ?? "",
264 fenceLanguage: fence?.[2]?.trim() || "diff",
265 };
266}
267
268function stripTrailing(
269 text: string,
270 pattern: RegExp,
271): { text: string; match: RegExpExecArray } | null {
272 const match = pattern.exec(text);
273 if (!match) return null;
274 return { text: text.slice(0, match.index).replace(/\n+$/, ""), match };
275}
276
277/** Review source can contain literal closing tags inside its dynamically sized code fence. */
278function replaceReviewBlocks(
279 text: string,
280 replace: (whole: string, attributes: string, body: string) => string,
281): string {
282 const parts: string[] = [];
283 const openings = new RegExp(REVIEW_OR_CONTEXT_BLOCK);
284 let consumed = 0;
285 for (let opening = openings.exec(text); opening; opening = openings.exec(text)) {
286 // Other context blocks own their payload, including any review-shaped source text.
287 if (opening[2]) continue;
288 const bodyStart = openings.lastIndex;
289 const boundaries = /^(`{3,})([^\n]*)$|<\/review_comment>/gm;
290 boundaries.lastIndex = bodyStart;
291 let fenceLength = 0;
292 for (let boundary = boundaries.exec(text); boundary; boundary = boundaries.exec(text)) {
293 if (boundary[1]) {
294 if (fenceLength === 0) fenceLength = boundary[1].length;
295 else if (boundary[1].length >= fenceLength && !boundary[2]?.trim()) fenceLength = 0;
296 } else if (fenceLength === 0) {
297 parts.push(text.slice(consumed, opening.index));
298 consumed = boundaries.lastIndex;
299 parts.push(
300 replace(
301 text.slice(opening.index, consumed),
302 opening[1]!,
303 text.slice(bodyStart, boundary.index),
304 ),
305 );
306 openings.lastIndex = consumed;
307 break;
308 }
309 }
310 if (consumed < bodyStart) break;
311 }
312 parts.push(text.slice(consumed));
313 return parts.join("");
314}
315
316export function upgradeLegacyContextMessage(text: string): UpgradedLegacyContext {
317 if (!LEGACY_MARKERS.test(text)) return { text, records: [] };
318
319 const terminalEntries: ParsedEntry[] = [];
320 const elementEntries: ParsedEntry[] = [];
321 const previewBodies: string[] = [];
322 const reviews: ReviewCommentContextRecord[] = [];
323
324 // A literal private-use token in the message must never be mistaken for our placeholder.
325 let reviewToken = REVIEW_TOKEN;
326 while (text.includes(reviewToken)) reviewToken += reviewToken;
327 const reviewTokenPattern = new RegExp(`${reviewToken}(\\d+)${reviewToken}`, "g");
328 const trailingReviewTokenPattern = new RegExp(`(?:\\s*${reviewToken}\\d+${reviewToken})+\\s*$`);
329
330 // Review blocks become tokens in place first so they neither hide the trailing blocks
331 // behind them nor lose their position. Unparseable blocks stay as text.
332 let rest = replaceReviewBlocks(text, (whole, attributes, rawBody) => {
333 const record = reviewRecord(attributes, rawBody, reviews.length + 1);
334 // Keep the original prose if converting it would produce a record the wire drops.
335 if (!record || !isReviewCommentContextRecord(record)) return whole;
336 reviews.push(record);
337 return `${reviewToken}${reviews.length - 1}${reviewToken}`;
338 });
339
340 // Blocks were appended in send order (terminal, element, preview, review), so they peel
341 // off the end in reverse. Each peel exposes the next block as trailing.
342 // Peel reviews only when they hide another trailing context block. A review at the end
343 // of ordinary prose can still be inline; keep its original spacing and line breaks.
344 const trailingReviewTokens: number[] = [];
345 const tokens = trailingReviewTokenPattern.exec(rest);
346 if (tokens && tokens[0].length > 0) {
347 const preceding = rest.slice(0, tokens.index);
348 if (
349 TRAILING_PREVIEW.test(preceding) ||
350 TRAILING_ELEMENT.test(preceding) ||
351 TRAILING_TERMINAL.test(preceding)
352 ) {
353 trailingReviewTokens.push(
354 ...Array.from(tokens[0].matchAll(reviewTokenPattern), (m) => Number(m[1])),
355 );
356 rest = preceding;
357 }
358 }
359 for (;;) {
360 const preview = stripTrailing(rest, TRAILING_PREVIEW);
361 if (preview) {
362 rest = preview.text;
363 previewBodies.unshift(preview.match[1] ?? "");
364 continue;
365 }
366 const element = stripTrailing(rest, TRAILING_ELEMENT);
367 if (element) {
368 const entries = parseEntries(element.match[1] ?? "");
369 if (!entries?.length || entries.some((entry) => elementRecord(entry, 1) === null))
370 return { text, records: [] };
371 rest = element.text;
372 elementEntries.unshift(...entries);
373 continue;
374 }
375 const terminal = stripTrailing(rest, TRAILING_TERMINAL);
376 if (terminal) {
377 const entries = parseEntries(terminal.match[1] ?? "");
378 if (!entries?.length || entries.some((entry) => terminalRecord(entry, 1) === null))
379 return { text, records: [] };
380 rest = terminal.text;
381 terminalEntries.unshift(...entries);
382 continue;
383 }
384 break;
385 }
386
387 const terminals = terminalEntries
388 .map((entry, index) => terminalRecord(entry, index + 1))
389 .filter((record) => record !== null);
390 const elements = elementEntries
391 .map((entry, index) => elementRecord(entry, index + 1))
392 .filter((record) => record !== null);
393 const previews: PreviewAnnotationContextRecord[] = [];
394 for (const [index, previewBody] of previewBodies.entries()) {
395 const record = previewRecord(previewBody, index + 1);
396 if (record === null) return { text, records: [] };
397 previews.push(record);
398 }
399 const appendedReviews = trailingReviewTokens.map((index) => reviews[index]!);
400
401 let body = rest.replace(reviewTokenPattern, (_whole, index: string) =>
402 formatComposerContextReference(reviews[Number(index)]!),
403 );
404
405 // Placeholders bind to terminal entries in order, like the old materialize step did.
406 let placeholderIndex = 0;
407 body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {
408 const record = terminals[placeholderIndex];
409 placeholderIndex += 1;
410 return record ? formatComposerContextReference(record) : "";
411 });
412 // Sent messages carry the materialized `@terminal-1:509-514` label instead of the
413 // placeholder; each such label becomes the chip in place.
414 const placedTerminals = new Set(terminals.slice(0, placeholderIndex));
415 for (const record of terminals) {
416 if (placedTerminals.has(record)) continue;
417 const label = inlineTerminalLabel(record);
418 let at = body.indexOf(label);
419 while (
420 at !== -1 &&
421 (/[\p{L}\p{N}\p{M}_@.-]$/u.test(body.slice(0, at)) ||
422 /^(?:[\p{L}\p{N}\p{M}_-]|[.@]+[\p{L}\p{N}\p{M}_-])/u.test(body.slice(at + label.length)))
423 ) {
424 at = body.indexOf(label, at + 1);
425 }
426 if (at === -1) continue;
427 body = `${body.slice(0, at)}${formatComposerContextReference(record)}${body.slice(at + label.length)}`;
428 placedTerminals.add(record);
429 }
430 body = body.trimEnd();
431
432 const appended = [
433 ...terminals.filter((record) => !placedTerminals.has(record)),
434 ...elements,
435 ...previews,
436 ...appendedReviews,
437 ].map((record) => formatComposerContextReference(record));
438 const upgradedText =
439 appended.length === 0
440 ? body
441 : body.length > 0
442 ? `${body}\n\n${appended.join(" ")}`
443 : appended.join(" ");
444
445 const records = [...terminals, ...elements, ...previews, ...reviews];
446 // Conversion is atomic: keep the source if any record would be dropped on the wire.
447 if (!isLegacyContextRecords(records)) return { text, records: [] };
448 return {
449 text: upgradedText,
450 records,
451 };
452}