Add preview annotation capture tooling

- Add structured annotation payload validation and tests
- Update preview preload to capture selected elements, regions, and strokes
- Wire new preview annotation UI into the web app

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and Theo Browne committed 2026-06-13 22:18:37 -07:00
1 parent 50bc18b208
commit 07c6d70b91
13 files changed
+1481 -351

No files matched your search

@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { isPickedElementPayload } from "./picked-element-payload.ts";
import { isPickedElementPayload, isPreviewAnnotationPayload } from "./picked-element-payload.ts";
function validPayload(overrides?: Record<string, unknown>): Record<string, unknown> {
return {
@@ -133,3 +133,69 @@ describe("isPickedElementPayload", () => {
expect(isPickedElementPayload(validPayload({ stack: [{ bogus: true }] }))).toBe(false);
});
});
function validAnnotation(overrides?: Record<string, unknown>): Record<string, unknown> {
return {
id: "annotation_1",
pageUrl: "https://example.com/",
pageTitle: "Example",
comment: "Make this clearer",
elements: [
{
id: "element_1",
element: validPayload(),
rect: { x: 10, y: 20, width: 100, height: 40 },
},
],
regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
strokes: [
{
id: "stroke_1",
color: "#7c3aed",
width: 4,
points: [
{ x: 10, y: 10 },
{ x: 20, y: 20 },
],
bounds: { x: 6, y: 6, width: 18, height: 18 },
},
],
styleChanges: [
{
targetId: "element_1",
selector: "button.submit",
property: "opacity",
previousValue: "1",
value: "0.5",
},
],
screenshot: null,
createdAt: "2026-06-11T00:00:00.000Z",
...overrides,
};
}
describe("isPreviewAnnotationPayload", () => {
it("accepts a structured annotation draft before screenshot capture", () => {
expect(isPreviewAnnotationPayload(validAnnotation())).toBe(true);
});
it("rejects screenshots supplied by the guest preload", () => {
expect(isPreviewAnnotationPayload(validAnnotation({ screenshot: { dataUrl: "bad" } }))).toBe(
false,
);
});
it("rejects malformed geometry and nested element payloads", () => {
expect(
isPreviewAnnotationPayload(
validAnnotation({ regions: [{ id: "region_1", rect: { x: 0, y: 0, width: "wide" } }] }),
),
).toBe(false);
expect(
isPreviewAnnotationPayload(
validAnnotation({ elements: [{ id: "element_1", element: {}, rect: {} }] }),
),
).toBe(false);
});
});
+98 -1
View File
@@ -10,7 +10,7 @@
* channel via prototype pollution) would otherwise throw deep in the
* renderer and the chip silently never appears.
*/
import type { PickedElementPayload } from "@t3tools/contracts";
import type { PickedElementPayload, PreviewAnnotationPayload } from "@t3tools/contracts";
function isStringOrNull(value: unknown): value is string | null {
return value === null || typeof value === "string";
@@ -47,3 +47,100 @@ export function isPickedElementPayload(value: unknown): value is PickedElementPa
if (!c["stack"].every(isPickedStackFrame)) return false;
return true;
}
function isRect(value: unknown): boolean {
if (typeof value !== "object" || value === null) return false;
const rect = value as Record<string, unknown>;
return ["x", "y", "width", "height"].every(
(key) => typeof rect[key] === "number" && Number.isFinite(rect[key]),
);
}
function isPoint(value: unknown): boolean {
if (typeof value !== "object" || value === null) return false;
const point = value as Record<string, unknown>;
return (
typeof point["x"] === "number" &&
Number.isFinite(point["x"]) &&
typeof point["y"] === "number" &&
Number.isFinite(point["y"])
);
}
export function isPreviewAnnotationPayload(value: unknown): value is PreviewAnnotationPayload {
if (typeof value !== "object" || value === null) return false;
const annotation = value as Record<string, unknown>;
if (typeof annotation["id"] !== "string") return false;
if (typeof annotation["pageUrl"] !== "string") return false;
if (!isStringOrNull(annotation["pageTitle"])) return false;
if (typeof annotation["comment"] !== "string") return false;
if (typeof annotation["createdAt"] !== "string") return false;
if (annotation["screenshot"] !== null) return false;
const elements = annotation["elements"];
if (!Array.isArray(elements)) return false;
if (
!elements.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const target = entry as Record<string, unknown>;
return (
typeof target["id"] === "string" &&
isPickedElementPayload(target["element"]) &&
isRect(target["rect"])
);
})
) {
return false;
}
const regions = annotation["regions"];
if (!Array.isArray(regions)) return false;
if (
!regions.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const target = entry as Record<string, unknown>;
return typeof target["id"] === "string" && isRect(target["rect"]);
})
) {
return false;
}
const strokes = annotation["strokes"];
if (!Array.isArray(strokes)) return false;
if (
!strokes.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const target = entry as Record<string, unknown>;
return (
typeof target["id"] === "string" &&
typeof target["color"] === "string" &&
typeof target["width"] === "number" &&
Number.isFinite(target["width"]) &&
Array.isArray(target["points"]) &&
target["points"].every(isPoint) &&
isRect(target["bounds"])
);
})
) {
return false;
}
const styleChanges = annotation["styleChanges"];
if (!Array.isArray(styleChanges)) return false;
if (
!styleChanges.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const change = entry as Record<string, unknown>;
return (
typeof change["targetId"] === "string" &&
isStringOrNull(change["selector"]) &&
typeof change["property"] === "string" &&
typeof change["previousValue"] === "string" &&
typeof change["value"] === "string"
);
})
) {
return false;
}
return true;
}
File diff suppressed because it is too large. Load diff
+76 -12
View File
@@ -6,16 +6,17 @@
* elements live in the renderer; we only attach listeners and forward state
* here). Single layer-scoped browser session partition.
*/
import type { PickedElementPayload } from "@t3tools/contracts";
import type { PreviewAnnotationPayload, PreviewAnnotationRect } from "@t3tools/contracts";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import { type BrowserWindow, type Session, session, webContents } from "electron";
import { isPickedElementPayload } from "./picked-element-payload.ts";
import { isPreviewAnnotationPayload } from "./picked-element-payload.ts";
const PREVIEW_PARTITION = "persist:t3code-preview";
const START_PICK_CHANNEL = "preview:start-pick";
const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
// Re-export the guest webview security posture from its dedicated module so
// the constant is unit-testable in isolation. See
@@ -53,6 +54,58 @@ const ZOOM_LEVELS: ReadonlyArray<number> = [
const DEFAULT_ZOOM_FACTOR = 1.0;
const ZOOM_EPSILON = 0.001;
const normalizeCaptureRect = (value: unknown): PreviewAnnotationRect | null => {
if (typeof value !== "object" || value === null) return null;
const rect = value as Record<string, unknown>;
const x = rect["x"];
const y = rect["y"];
const width = rect["width"];
const height = rect["height"];
if (
typeof x !== "number" ||
!Number.isFinite(x) ||
typeof y !== "number" ||
!Number.isFinite(y) ||
typeof width !== "number" ||
!Number.isFinite(width) ||
typeof height !== "number" ||
!Number.isFinite(height) ||
width <= 0 ||
height <= 0
) {
return null;
}
return {
x: Math.max(0, Math.floor(x)),
y: Math.max(0, Math.floor(y)),
width: Math.max(1, Math.ceil(width)),
height: Math.max(1, Math.ceil(height)),
};
};
const captureAnnotationScreenshot = async (
wc: Electron.WebContents,
cropRect: PreviewAnnotationRect | null,
) => {
const image = await wc.capturePage(
cropRect
? {
x: cropRect.x,
y: cropRect.y,
width: cropRect.width,
height: cropRect.height,
}
: undefined,
);
const size = image.getSize();
return {
dataUrl: image.toDataURL(),
width: size.width,
height: size.height,
cropRect: cropRect ?? { x: 0, y: 0, width: size.width, height: size.height },
};
};
const findZoomStep = (current: number): number => {
for (let index = 0; index < ZOOM_LEVELS.length; index += 1) {
if (Math.abs(ZOOM_LEVELS[index]! - current) < ZOOM_EPSILON) return index;
@@ -77,7 +130,7 @@ interface ManagedListeners {
}
interface PickSession {
readonly resolve: (payload: PickedElementPayload | null) => void;
readonly resolve: (payload: PreviewAnnotationPayload | null) => void;
readonly cleanup: () => void;
}
@@ -103,7 +156,7 @@ export class PreviewViewManager {
private readonly attached = new Map<number, ManagedListeners>();
private browserSession: Session | null = null;
private readonly listeners = new Set<Listener>();
/** In-flight element-pick sessions, keyed by tabId (one pick per tab). */
/** In-flight preview annotation sessions, keyed by tabId. */
private readonly pickSessions = new Map<string, PickSession>();
setMainWindow(window: BrowserWindow): void {
@@ -290,17 +343,17 @@ export class PreviewViewManager {
}
/**
* Activate the in-page element picker for `tabId`. Resolves with the
* `PickedElementPayload` the preload script bubbles back via `ipc-message`,
* or `null` when the user cancels (Escape, navigation, manual cancel).
* Activate annotation mode for `tabId`. Resolves after the guest submits a
* multi-target annotation and the desktop process captures its screenshot,
* or with `null` when the user cancels.
*
* Exactly one pick session may be active per tab — re-invoking while a
* pick is in flight cleanly resolves the old session with `null` first.
*/
async pickElement(tabId: string): Promise<PickedElementPayload | null> {
async pickElement(tabId: string): Promise<PreviewAnnotationPayload | null> {
const wc = this.requireWebContents(tabId);
this.cancelPickElement(tabId);
return new Promise<PickedElementPayload | null>((resolve) => {
return new Promise<PreviewAnnotationPayload | null>((resolve) => {
// `wc.ipc` is the per-WebContents IpcMain that receives messages the
// webview's preload sends with `ipcRenderer.send(...)`. We use that
// (not the global `wc.on("ipc-message", ...)`, which is for
@@ -313,7 +366,7 @@ export class PreviewViewManager {
this.pickSessions.delete(tabId);
};
const session: PickSession = { resolve, cleanup };
const settle = (payload: PickedElementPayload | null) => {
const settle = (payload: PreviewAnnotationPayload | null) => {
if (this.pickSessions.get(tabId) !== session) return;
cleanup();
resolve(payload);
@@ -324,11 +377,22 @@ export class PreviewViewManager {
settle(null);
return;
}
if (!isPickedElementPayload(payload)) {
if (!isPreviewAnnotationPayload(payload)) {
settle(null);
return;
}
settle(payload);
const cropRect = normalizeCaptureRect(args[1]);
void captureAnnotationScreenshot(wc, cropRect)
.then((screenshot) => settle({ ...payload, screenshot }))
.catch(() => settle(payload))
.finally(() => {
if (wc.isDestroyed()) return;
try {
wc.send(ANNOTATION_CAPTURED_CHANNEL);
} catch {
// The guest may have navigated while capture was in flight.
}
});
};
const onDestroyed = () => settle(null);
const onNavigated = () => settle(null);
-1
View File
@@ -64,7 +64,6 @@
"babel-plugin-react-compiler": "1.0.0",
"msw": "2.12.11",
"playwright": "^1.58.2",
"react-grab": "^0.1.32",
"tailwindcss": "^4.0.0",
"vite": "catalog:",
"vite-plus": "catalog:",
@@ -37,8 +37,8 @@ interface Props {
/** When provided, renders an "Open in browser" affordance to the right. */
onOpenInBrowser?: (() => void) | undefined;
/**
* When provided, renders a "Select element" toggle button to the right of
* the URL input. Pressed while a pick is active (button shows in `pressed`
* When provided, renders an annotation-mode toggle button to the right of
* the URL input. Pressed while annotation mode is active (button shows in `pressed`
* state). Disabled in `pickDisabled` mode.
*/
onPickElement?: (() => void) | undefined;
@@ -192,7 +192,7 @@ export function PreviewChromeRow({
size="icon-xs"
onClick={onPickElement}
disabled={pickDisabled}
aria-label={pickActive ? "Cancel element pick" : "Select element from page"}
aria-label={pickActive ? "Cancel annotation" : "Annotate preview"}
aria-pressed={pickActive ? "true" : "false"}
type="button"
/>
@@ -204,8 +204,8 @@ export function PreviewChromeRow({
{pickDisabled && pickDisabledReason
? pickDisabledReason
: pickActive
? "Cancel pick (Esc)"
: "Select element to attach"}
? "Cancel annotation (Esc)"
: "Annotate elements, regions, and drawings"}
</TooltipPopup>
</Tooltip>
) : null}
@@ -7,6 +7,10 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useComposerDraftStore } from "~/composerDraftStore";
import { ensureEnvironmentApi } from "~/environmentApi";
import { normalizeElementContextSelection } from "~/lib/elementContext";
import {
appendPreviewAnnotationPrompt,
previewAnnotationScreenshotFile,
} from "~/lib/previewAnnotation";
import { ensureLocalApi } from "~/localApi";
import { selectThreadPreviewState, usePreviewStateStore } from "~/previewStateStore";
@@ -45,6 +49,9 @@ export function PreviewView({ threadRef, configuredUrls, visible }: Props) {
const applyServerSnapshot = usePreviewStateStore((state) => state.applyServerSnapshot);
const rememberUrl = usePreviewStateStore((state) => state.rememberUrl);
const addElementContext = useComposerDraftStore((store) => store.addElementContext);
const addImage = useComposerDraftStore((store) => store.addImage);
const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
const setPrompt = useComposerDraftStore((store) => store.setPrompt);
usePreviewSession(threadRef);
@@ -137,11 +144,26 @@ export function PreviewView({ threadRef, configuredUrls, visible }: Props) {
setPickActive(true);
void (async () => {
try {
const payload = await previewBridge.pickElement(tabId);
if (!payload) return;
const selection = normalizeElementContextSelection(payload);
if (!selection) return;
addElementContext(threadRef, selection);
const annotation = await previewBridge.pickElement(tabId);
if (!annotation) return;
for (const target of annotation.elements) {
const selection = normalizeElementContextSelection(target.element);
if (selection) addElementContext(threadRef, selection);
}
const currentPrompt = getComposerDraft(threadRef)?.prompt ?? "";
setPrompt(threadRef, appendPreviewAnnotationPrompt(currentPrompt, annotation));
const screenshotFile = await previewAnnotationScreenshotFile(annotation);
if (screenshotFile && annotation.screenshot) {
addImage(threadRef, {
type: "image",
id: annotation.id,
name: screenshotFile.name,
mimeType: screenshotFile.type,
sizeBytes: screenshotFile.size,
previewUrl: annotation.screenshot.dataUrl,
file: screenshotFile,
});
}
} catch {
// Picker failed (e.g. webview navigated). Treat as silent cancel.
} finally {
@@ -165,7 +187,7 @@ export function PreviewView({ threadRef, configuredUrls, visible }: Props) {
}
}
})();
}, [addElementContext, tabId, threadRef]);
}, [addElementContext, addImage, getComposerDraft, setPrompt, tabId, threadRef]);
// If the active tab changes mid-pick (close, thread switch, hot restart),
// tell main to tear down the in-flight session AND reset our local toggle
@@ -0,0 +1,60 @@
import type { PreviewAnnotationPayload } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { appendPreviewAnnotationPrompt, buildPreviewAnnotationPrompt } from "./previewAnnotation";
const annotation: PreviewAnnotationPayload = {
id: "annotation_1",
pageUrl: "http://localhost:3000",
pageTitle: "Example",
comment: "Make these cards feel related.",
elements: [],
regions: [{ id: "region_1", rect: { x: 10, y: 20, width: 100, height: 80 } }],
strokes: [
{
id: "stroke_1",
color: "#7c3aed",
width: 4,
points: [
{ x: 10, y: 10 },
{ x: 20, y: 20 },
],
bounds: { x: 6, y: 6, width: 18, height: 18 },
},
],
styleChanges: [
{
targetId: "element_1",
selector: ".card",
property: "border-radius",
previousValue: "4px",
value: "16px",
},
],
screenshot: {
dataUrl: "data:image/png;base64,AA==",
width: 100,
height: 80,
cropRect: { x: 10, y: 20, width: 100, height: 80 },
},
createdAt: "2026-06-11T00:00:00.000Z",
};
describe("preview annotations", () => {
it("describes regions, drawings, styles, and screenshot context", () => {
const result = buildPreviewAnnotationPrompt(annotation);
expect(result).toContain("Make these cards feel related.");
expect(result).toContain("1 marked region");
expect(result).toContain("1 drawing");
expect(result).toContain("border-radius: 4px → 16px");
expect(result).toContain("attached screenshot");
});
it("appends to an existing composer prompt", () => {
expect(
appendPreviewAnnotationPrompt("Fix this", annotation).startsWith(
"Fix this\n\nPreview annotation:",
),
).toBe(true);
});
});
+53
View File
@@ -0,0 +1,53 @@
import type { PreviewAnnotationPayload } from "@t3tools/contracts";
export function buildPreviewAnnotationPrompt(annotation: PreviewAnnotationPayload): string {
const lines = ["Preview annotation:"];
if (annotation.comment.trim()) lines.push(annotation.comment.trim());
const targets: string[] = [];
if (annotation.elements.length > 0) {
targets.push(
`${annotation.elements.length} selected element${annotation.elements.length === 1 ? "" : "s"}`,
);
}
if (annotation.regions.length > 0) {
targets.push(
`${annotation.regions.length} marked region${annotation.regions.length === 1 ? "" : "s"}`,
);
}
if (annotation.strokes.length > 0) {
targets.push(
`${annotation.strokes.length} drawing${annotation.strokes.length === 1 ? "" : "s"}`,
);
}
if (targets.length > 0) lines.push(`Targets: ${targets.join(", ")}.`);
if (annotation.styleChanges.length > 0) {
lines.push("Requested visual changes:");
for (const change of annotation.styleChanges) {
lines.push(`- ${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`);
}
}
if (annotation.screenshot) {
lines.push("The attached screenshot is the annotated preview crop.");
}
return lines.join("\n");
}
export function appendPreviewAnnotationPrompt(
prompt: string,
annotation: PreviewAnnotationPayload,
): string {
const annotationText = buildPreviewAnnotationPrompt(annotation);
const trimmed = prompt.trim();
return trimmed ? `${trimmed}\n\n${annotationText}` : annotationText;
}
export async function previewAnnotationScreenshotFile(
annotation: PreviewAnnotationPayload,
): Promise<File | null> {
if (!annotation.screenshot) return null;
const response = await fetch(annotation.screenshot.dataUrl);
const blob = await response.blob();
return new File([blob], `preview-annotation-${annotation.id}.png`, {
type: blob.type || "image/png",
});
}
-4
View File
@@ -18,10 +18,6 @@ import { getRouter } from "./router";
import { APP_DISPLAY_NAME } from "./branding";
import { syncDocumentWindowControlsOverlayClass } from "./lib/windowControlsOverlay";
if (import.meta.env.DEV) {
void import("react-grab");
}
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
const history = isElectron ? createHashHistory() : createBrowserHistory();
+15
View File
@@ -0,0 +1,15 @@
// @effect-diagnostics nodeBuiltinImport:off
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vite-plus/test";
import packageJson from "../package.json" with { type: "json" };
describe("React Grab runtime boundary", () => {
it("keeps the host renderer free of the React Grab overlay", () => {
const mainSource = readFileSync(new URL("./main.tsx", import.meta.url), "utf8");
expect(mainSource).not.toMatch(/import\(["']react-grab["']\)/);
expect(packageJson.dependencies).not.toHaveProperty("react-grab");
expect(packageJson.devDependencies).not.toHaveProperty("react-grab");
});
});
+66 -2
View File
@@ -505,6 +505,70 @@ export interface PickedElementPayload {
pickedAt: string;
}
export interface PreviewAnnotationRect {
x: number;
y: number;
width: number;
height: number;
}
export interface PreviewAnnotationPoint {
x: number;
y: number;
}
export interface PreviewAnnotationElementTarget {
id: string;
element: PickedElementPayload;
rect: PreviewAnnotationRect;
}
export interface PreviewAnnotationRegionTarget {
id: string;
rect: PreviewAnnotationRect;
}
export interface PreviewAnnotationStrokeTarget {
id: string;
color: string;
width: number;
points: ReadonlyArray<PreviewAnnotationPoint>;
bounds: PreviewAnnotationRect;
}
export interface PreviewAnnotationStyleChange {
targetId: string;
selector: string | null;
property: string;
previousValue: string;
value: string;
}
export interface PreviewAnnotationScreenshot {
dataUrl: string;
width: number;
height: number;
cropRect: PreviewAnnotationRect;
}
/**
* A submitted preview annotation. One annotation may reference multiple DOM
* elements, freeform regions, and ink strokes. The desktop main process adds
* the screenshot after the guest preload submits the structured draft.
*/
export interface PreviewAnnotationPayload {
id: string;
pageUrl: string;
pageTitle: string | null;
comment: string;
elements: ReadonlyArray<PreviewAnnotationElementTarget>;
regions: ReadonlyArray<PreviewAnnotationRegionTarget>;
strokes: ReadonlyArray<PreviewAnnotationStrokeTarget>;
styleChanges: ReadonlyArray<PreviewAnnotationStyleChange>;
screenshot: PreviewAnnotationScreenshot | null;
createdAt: string;
}
export interface DesktopBridge {
getAppBranding: () => DesktopAppBranding | null;
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
@@ -601,8 +665,8 @@ export interface DesktopPreviewBridge {
* the picked payload, or `null` when the user cancels (Escape / nav). The
* promise rejects if the picker can't be activated (no webview, etc.).
*/
pickElement: (tabId: string) => Promise<PickedElementPayload | null>;
/** Cancel an in-flight `pickElement(tabId)` (renderer-side teardown). */
pickElement: (tabId: string) => Promise<PreviewAnnotationPayload | null>;
/** Cancel an in-flight preview annotation session. */
cancelPickElement: (tabId: string) => Promise<void>;
onStateChange: (listener: (tabId: string, state: DesktopPreviewTabState) => void) => () => void;
}
-3
View File
@@ -583,9 +583,6 @@ importers:
playwright:
specifier: ^1.58.2
version: 1.60.0
react-grab:
specifier: ^0.1.32
version: 0.1.44([email protected])
tailwindcss:
specifier: ^4.0.0
version: 4.3.0