Open History to see the last commit
1import type { PreviewAnnotationPayload } from "@t3tools/contracts";
2import { dataUrlToFile } from "./imageCompression";
3import { buildElementContextBlock, normalizeElementContextSelection } from "./elementContext";
4
5const TRAILING_PREVIEW_ANNOTATION_BLOCK_PATTERN =
6 /\n*<preview_annotation>\n((?:(?!<preview_annotation>)[\s\S])*)\n<\/preview_annotation>\s*$/;
7
8export interface ParsedPreviewAnnotation {
9 id: string;
10 title: string;
11 comment: string;
12 targetSummary: string;
13 styleChanges: string[];
14 hasScreenshot: boolean;
15}
16
17export interface ExtractedPreviewAnnotation {
18 promptText: string;
19 annotation: ParsedPreviewAnnotation | null;
20}
21
22export function buildPreviewAnnotationPrompt(annotation: PreviewAnnotationPayload): string {
23 const lines = ["Preview annotation:"];
24 lines.push(`Id: ${annotation.id}`);
25 const title = annotation.pageTitle?.trim() || annotation.pageUrl.trim() || "Preview";
26 lines.push(`Page: ${title}`);
27 if (annotation.comment.trim()) lines.push(`Comment: ${annotation.comment.trim()}`);
28 const targets: string[] = [];
29 if (annotation.elements.length > 0) {
30 targets.push(
31 `${annotation.elements.length} selected element${annotation.elements.length === 1 ? "" : "s"}`,
32 );
33 }
34 if (annotation.regions.length > 0) {
35 targets.push(
36 `${annotation.regions.length} marked region${annotation.regions.length === 1 ? "" : "s"}`,
37 );
38 }
39 if (annotation.strokes.length > 0) {
40 targets.push(
41 `${annotation.strokes.length} drawing${annotation.strokes.length === 1 ? "" : "s"}`,
42 );
43 }
44 if (targets.length > 0) lines.push(`Targets: ${targets.join(", ")}.`);
45 if (annotation.styleChanges.length > 0) {
46 lines.push("Requested visual changes:");
47 for (const change of annotation.styleChanges) {
48 lines.push(`- ${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`);
49 }
50 }
51 if (annotation.screenshot) {
52 lines.push("The attached screenshot is the annotated preview crop.");
53 }
54 const elementContexts = annotation.elements
55 .map((target) => normalizeElementContextSelection(target.element))
56 .filter((context) => context !== null);
57 const elementBlock = buildElementContextBlock(elementContexts);
58 if (elementBlock) lines.push(elementBlock);
59 return ["<preview_annotation>", ...lines, "</preview_annotation>"].join("\n");
60}
61
62export function appendPreviewAnnotationPrompt(
63 prompt: string,
64 annotation: PreviewAnnotationPayload,
65): string {
66 const annotationText = buildPreviewAnnotationPrompt(annotation);
67 const trimmed = prompt.trim();
68 return trimmed ? `${trimmed}\n\n${annotationText}` : annotationText;
69}
70
71export function extractTrailingPreviewAnnotation(prompt: string): ExtractedPreviewAnnotation {
72 const match = TRAILING_PREVIEW_ANNOTATION_BLOCK_PATTERN.exec(prompt);
73 if (!match) return { promptText: prompt, annotation: null };
74 const body = match[1] ?? "";
75 const lines = body.split("\n");
76 const pageLine = lines.find((line) => line.startsWith("Page: "));
77 const idLine = lines.find((line) => line.startsWith("Id: "));
78 const commentLine = lines.find((line) => line.startsWith("Comment: "));
79 const targetsLine = lines.find((line) => line.startsWith("Targets: "));
80 const styleHeadingIndex = lines.indexOf("Requested visual changes:");
81 const linesAfterStyleHeading = lines.slice(styleHeadingIndex + 1);
82 const elementContextIndex = linesAfterStyleHeading.indexOf("<element_context>");
83 const styleChanges =
84 styleHeadingIndex < 0
85 ? []
86 : linesAfterStyleHeading
87 .slice(0, elementContextIndex < 0 ? undefined : elementContextIndex)
88 .filter((line) => line.startsWith("- "))
89 .map((line) => line.slice(2));
90 return {
91 promptText: prompt.slice(0, match.index).replace(/\n+$/, ""),
92 annotation: {
93 id: idLine?.slice("Id: ".length).trim() || `${match.index}`,
94 title: pageLine?.slice("Page: ".length).trim() || "Preview annotation",
95 comment: commentLine?.slice("Comment: ".length).trim() || "",
96 targetSummary: targetsLine?.slice("Targets: ".length).trim() || "",
97 styleChanges,
98 hasScreenshot: body.includes("The attached screenshot is the annotated preview crop."),
99 },
100 };
101}
102
103export type PreviewAnnotationCapture =
104 /** The crop is ready to attach. */
105 | { readonly status: "captured"; readonly file: File }
106 /** The pick carried no crop, which is normal for comment-only annotations. */
107 | { readonly status: "none" }
108 /** The crop could not be decoded. Send the annotation without it. */
109 | { readonly status: "failed" };
110
111/** Decode locally because the desktop CSP does not allow fetching data URLs. */
112export function capturePreviewAnnotationScreenshot(
113 annotation: PreviewAnnotationPayload,
114): PreviewAnnotationCapture {
115 if (!annotation.screenshot) return { status: "none" };
116 const { dataUrl } = annotation.screenshot;
117 const match = /^data:(image\/[^;,]+);base64,.+$/s.exec(dataUrl);
118 if (!match?.[1]) return { status: "failed" };
119 try {
120 return {
121 status: "captured",
122 file: dataUrlToFile(dataUrl, `preview-annotation-${annotation.id}.png`, match[1]),
123 };
124 } catch {
125 return { status: "failed" };
126 }
127}