Skip to content
TypeScript

fix(web): unlock the composer when preview capture fails (#9127)

Theo Browne19c97ea56d30
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index 75271d76386..d334b363508 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -3137,6 +3137,164 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect("settles the pick when the annotation screenshot never arrives", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined;
+ fromId.mockReturnValue({
+ id: 42,
+ isDestroyed: () => false,
+ getType: () => "webview",
+ getURL: () => "https://example.com",
+ getTitle: () => "Example",
+ isLoading: () => false,
+ isFocused: () => true,
+ getZoomFactor: () => 1,
+ setZoomFactor: vi.fn(),
+ setAudioMuted: vi.fn(),
+ isCurrentlyAudible: () => false,
+ on: vi.fn(),
+ once: vi.fn(),
+ off: vi.fn(),
+ // A wedged compositor leaves `capturePage` pending forever.
+ capturePage: vi.fn(() => new Promise(() => {})),
+ ipc: {
+ on: vi.fn((channel: string, listener: typeof onPicked) => {
+ if (channel === "preview:element-picked") onPicked = listener;
+ }),
+ off: vi.fn(),
+ removeListener: vi.fn(),
+ },
+ send: webviewSend,
+ navigationHistory: { canGoBack: () => false, canGoForward: () => false },
+ setWindowOpenHandler: vi.fn(),
+ debugger: {
+ isAttached: () => false,
+ attach: vi.fn(),
+ sendCommand: vi.fn(async () => undefined),
+ on: vi.fn(),
+ off: vi.fn(),
+ },
+ } as never);
+
+ yield* manager.createTab("tab_1");
+ yield* manager.registerWebview("tab_1", 42);
+ const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
+ yield* Effect.yieldNow;
+
+ onPicked?.(
+ {},
+ {
+ id: "annotation_1",
+ pageUrl: "https://example.com",
+ pageTitle: "Example",
+ comment: "Tighten this spacing",
+ elements: [],
+ regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
+ strokes: [],
+ styleChanges: [],
+ screenshot: null,
+ createdAt: "2026-06-11T00:00:00.000Z",
+ },
+ null,
+ "send",
+ );
+ yield* Effect.yieldNow;
+ expect(pick.pollUnsafe()).toBeUndefined();
+
+ yield* TestClock.adjust("6 seconds");
+ // The pick has to give up on the crop rather than strand the renderer,
+ // which would leave the composer stuck on "Capturing…".
+ const result = yield* Fiber.join(pick);
+ expect(result?.annotation.screenshot).toBeNull();
+ expect(result?.screenshotFailed).toBe(true);
+ expect(result?.submission).toBe("send");
+ expect(webviewSend).toHaveBeenCalledWith("preview:annotation-captured");
+ }),
+ ),
+ );
+
+ effectIt.effect("a stale capture from a replaced pick never touches the next pick", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined;
+ fromId.mockReturnValue({
+ id: 42,
+ isDestroyed: () => false,
+ getType: () => "webview",
+ getURL: () => "https://example.com",
+ getTitle: () => "Example",
+ isLoading: () => false,
+ isFocused: () => true,
+ getZoomFactor: () => 1,
+ setZoomFactor: vi.fn(),
+ setAudioMuted: vi.fn(),
+ isCurrentlyAudible: () => false,
+ on: vi.fn(),
+ once: vi.fn(),
+ off: vi.fn(),
+ capturePage: vi.fn(() => new Promise(() => {})),
+ ipc: {
+ on: vi.fn((channel: string, listener: typeof onPicked) => {
+ if (channel === "preview:element-picked") onPicked = listener;
+ }),
+ off: vi.fn(),
+ removeListener: vi.fn(),
+ },
+ send: webviewSend,
+ navigationHistory: { canGoBack: () => false, canGoForward: () => false },
+ setWindowOpenHandler: vi.fn(),
+ debugger: {
+ isAttached: () => false,
+ attach: vi.fn(),
+ sendCommand: vi.fn(async () => undefined),
+ on: vi.fn(),
+ off: vi.fn(),
+ },
+ } as never);
+ const annotation = {
+ id: "annotation_1",
+ pageUrl: "https://example.com",
+ pageTitle: "Example",
+ comment: "Tighten this spacing",
+ elements: [],
+ regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
+ strokes: [],
+ styleChanges: [],
+ screenshot: null,
+ createdAt: "2026-06-11T00:00:00.000Z",
+ };
+
+ yield* manager.createTab("tab_1");
+ yield* manager.registerWebview("tab_1", 42);
+ const firstPick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
+ yield* Effect.yieldNow;
+ // The first pick submits and its crop hangs.
+ onPicked?.({}, annotation, null, "send");
+ yield* Effect.yieldNow;
+
+ // A second pick on the same tab replaces the first, which resumes null.
+ const secondPick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
+ yield* Effect.yieldNow;
+ expect(yield* Fiber.join(firstPick)).toBeNull();
+ webviewSend.mockClear();
+
+ // The first pick's crop times out while the second pick is live. It
+ // must not signal the overlay, which would tear down the second pick.
+ yield* TestClock.adjust("6 seconds");
+ yield* Effect.yieldNow;
+ expect(webviewSend).not.toHaveBeenCalledWith("preview:annotation-captured");
+ expect(secondPick.pollUnsafe()).toBeUndefined();
+
+ onPicked?.({}, { ...annotation, id: "annotation_2" }, null, "attach");
+ yield* TestClock.adjust("6 seconds");
+ const result = yield* Fiber.join(secondPick);
+ expect(result?.annotation.id).toBe("annotation_2");
+ expect(result?.submission).toBe("attach");
+ }),
+ ),
+ );
+
effectIt.effect("navigates the guest history when the thumb-button ipc fires", () =>
withManager((manager) =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 01398721dd5..8af2a460fb3 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -306,13 +306,24 @@ const normalizeCaptureRect = (value: unknown): PreviewAnnotationRect | null => {
};
};
+/** `capturePage` never settles when the guest's compositor is wedged. */
+const ANNOTATION_SCREENSHOT_TIMEOUT = "5 seconds";
+
+/**
+ * Crops the guest for a picked annotation. A stalled `capturePage` resolves to
+ * `null` after the timeout: the annotation is still sendable without its
+ * screenshot, and the pick session must settle either way.
+ */
const captureAnnotationScreenshot = (
tabId: string,
wc: Electron.WebContents,
cropRect: PreviewAnnotationRect | null,
): Effect.Effect<PreviewAnnotationPayload["screenshot"], PreviewManagerError> =>
Effect.tryPromise({
- try: () =>
+ // The unused abort signal is what makes this interruptible, and therefore
+ // what lets the timeout below fire. Drop the parameter and a stalled
+ // capture strands the pick session again.
+ try: (_signal) =>
wc.capturePage(
cropRect
? {
@@ -331,7 +342,7 @@ const captureAnnotationScreenshot = (
cause,
}),
}).pipe(
- Effect.map((image) => {
+ Effect.map((image): PreviewAnnotationPayload["screenshot"] => {
const size = image.getSize();
return {
dataUrl: image.toDataURL(),
@@ -340,6 +351,15 @@ const captureAnnotationScreenshot = (
cropRect: cropRect ?? { x: 0, y: 0, width: size.width, height: size.height },
};
}),
+ Effect.timeoutOption(ANNOTATION_SCREENSHOT_TIMEOUT),
+ Effect.flatMap((screenshot) =>
+ Option.isSome(screenshot)
+ ? Effect.succeed(screenshot.value)
+ : Effect.logWarning("preview annotation screenshot timed out").pipe(
+ Effect.annotateLogs({ tabId, webContentsId: wc.id }),
+ Effect.as(null),
+ ),
+ ),
);
const findZoomStep = (current: number): number => {
@@ -2370,30 +2390,52 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const annotationTheme = yield* Ref.get(annotationThemeRef);
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
(resume) => {
+ // Declared first so cleanup can check slot ownership by identity
+ // without a type cycle through the cancel effect it builds.
+ const session: PickSession = { cancel: Effect.suspend(() => cancelPickSession()) };
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
wc.ipc.removeListener(ELEMENT_PICKED_CHANNEL, onMessage);
wc.off("destroyed", onDestroyed);
wc.off("did-start-navigation", onNavigated);
}).pipe(Effect.ignore);
+ // Only drop the slot while it is still ours. A newer session may
+ // already have swapped itself in before cancelling this one.
yield* Ref.update(pickSessionsRef, (sessions) =>
- replaceMap(sessions, (copy) => {
- copy.delete(tabId);
- }),
+ sessions.get(tabId) === session
+ ? replaceMap(sessions, (copy) => {
+ copy.delete(tabId);
+ })
+ : sessions,
);
});
- const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
+ // Every exit from this session runs through `claimSettle`, so the
+ // renderer's `pickElement` promise resolves exactly once. The previous
+ // identity check let a cancelled or replaced session return without
+ // resuming, which left the composer waiting forever.
+ let settled = false;
+ const claimSettle = (): boolean => {
+ if (settled) return false;
+ settled = true;
+ return true;
+ };
+ const finishPick = Effect.fn("PreviewManager.finishPickElement")(function* (
payload: PreviewAnnotationSubmissionResult | null,
) {
- const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
- if (!active || active.cancel !== cancel) return;
yield* cleanup();
resume(Effect.succeed(payload));
});
+ const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
+ payload: PreviewAnnotationSubmissionResult | null,
+ ) {
+ if (!claimSettle()) return;
+ yield* finishPick(payload);
+ });
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
runFork(settlePick(payload));
};
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
+ if (!claimSettle()) return;
yield* cleanup();
const tabs = yield* SynchronizedRef.get(tabsRef);
const activeTab = tabs.get(tabId);
@@ -2412,7 +2454,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
resume(Effect.succeed(null));
});
- const cancel = cancelPickSession();
const onMessage = (_event: Electron.IpcMainEvent, ...args: unknown[]): void => {
const payload = args[0];
if (!isPreviewAnnotationPayload(payload)) {
@@ -2423,19 +2464,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const submission = args[2] === "send" ? "send" : "attach";
runFork(
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
- Effect.matchEffect({
- onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
- onSuccess: (screenshot) =>
- Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
+ // The renderer cannot tell a dropped crop from a comment-only
+ // pick by the null alone, so a failed or timed-out capture is
+ // flagged on the result.
+ Effect.match({
+ onFailure: (): PreviewAnnotationSubmissionResult => ({
+ annotation: payload,
+ submission,
+ screenshotFailed: true,
+ }),
+ onSuccess: (screenshot): PreviewAnnotationSubmissionResult =>
+ screenshot === null
+ ? { annotation: payload, submission, screenshotFailed: true }
+ : { annotation: { ...payload, screenshot }, submission },
}),
- Effect.ensuring(
- attempt(
+ Effect.flatMap((result) => {
+ // A capture that outlives its session must not touch the
+ // overlay: the preload tears down on the captured signal, and
+ // by now it may be running a newer pick.
+ if (!claimSettle()) return Effect.void;
+ return attempt(
{ operation: "pickElement.captureComplete", tabId, webContentsId: wc.id },
() => {
if (!wc.isDestroyed()) wc.send(ANNOTATION_CAPTURED_CHANNEL);
},
- ).pipe(Effect.ignore),
- ),
+ ).pipe(Effect.ignore, Effect.andThen(finishPick(result)));
+ }),
),
);
};
@@ -2449,6 +2503,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
if (isMainFrame) settle(null);
};
const registerPickElement = Effect.fn("PreviewManager.registerPickElement")(function* () {
+ // Two picks on one tab can overlap. Swap this session in and cancel
+ // the previous holder in one step, so no third pick can slip into an
+ // empty slot in between and the session we push out still resumes
+ // its renderer.
+ const replaced = yield* Ref.modify(pickSessionsRef, (sessions) => [
+ sessions.get(tabId) ?? null,
+ replaceMap(sessions, (copy) => {
+ copy.set(tabId, session);
+ }),
+ ]);
+ if (replaced) yield* replaced.cancel;
+ // A newer pick may have cancelled this session while the previous
+ // one was torn down. Cleanup already ran, so attaching listeners now
+ // would leak them and start an overlay nobody is waiting on.
+ if (settled) return;
yield* attempt({ operation: "pickElement.register", tabId, webContentsId: wc.id }, () => {
wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage);
wc.once("destroyed", onDestroyed);
@@ -2456,21 +2525,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
if (!wc.isFocused()) wc.focus();
wc.send(START_PICK_CHANNEL, annotationTheme);
});
- yield* Ref.update(pickSessionsRef, (sessions) =>
- replaceMap(sessions, (copy) => {
- copy.set(tabId, { cancel });
- }),
- );
});
runFork(
registerPickElement().pipe(
Effect.catch((error: PreviewManagerError) => {
+ if (!claimSettle()) return Effect.void;
resume(Effect.fail(error));
return cleanup();
}),
),
);
- return cancel;
+ return session.cancel;
},
);
});
diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts
index f315bdcec73..6155c4119ec 100644
--- a/apps/desktop/src/preview/PickPreload.ts
+++ b/apps/desktop/src/preview/PickPreload.ts
@@ -1,4 +1,4 @@
-// @effect-diagnostics globalDate:off - This isolated Electron preload does not run inside an Effect runtime.
+// @effect-diagnostics globalDate:off globalTimers:off - This isolated Electron preload does not run inside an Effect runtime.
import { ipcRenderer } from "electron";
import { getElementContext } from "react-grab/primitives";
import type {
@@ -30,6 +30,8 @@ const Z_INDEX_OVERLAY = 2147483646;
const PRIMARY = "var(--t3-primary)";
const PRIMARY_FILL = "color-mix(in srgb, var(--t3-primary) 10%, transparent)";
const MAX_MARQUEE_ELEMENTS = 20;
+/** Upper bound on one element's React context lookup during submit. */
+const ELEMENT_CONTEXT_TIMEOUT_MS = 5_000;
const CONTENT_LAYER_Z_INDEX = 1;
const CHROME_LAYER_Z_INDEX = 10;
@@ -279,25 +281,67 @@ function toStackFrame(frame: {
};
}
-async function captureElement(element: Element): Promise<PickedElementPayload | null> {
+/**
+ * Resolves to `null` instead of hanging when `promise` outlives `millis`.
+ * `getElementContext` walks the inspected page's React internals, and some
+ * pages leave it pending forever. Without a bound, the whole submit chain
+ * stalls and the overlay sits on "Capturing…".
+ */
+function withCaptureTimeout<A>(promise: Promise<A>, millis: number): Promise<A | null> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ return Promise.race([
+ promise,
+ new Promise<null>((resolve) => {
+ timer = setTimeout(() => resolve(null), millis);
+ }),
+ ]).finally(() => clearTimeout(timer));
+}
+
+/** Truncation for the DOM-only preview used when React context is unavailable. */
+const HTML_PREVIEW_MAX_CHARS = 500;
+
+/**
+ * Describes a picked element. The React context lookup can stall or throw on
+ * some pages, so the element is never dropped: without context it still
+ * carries its tag, a short HTML preview, and its rect so the crop stays on the
+ * pick instead of falling back to the whole viewport.
+ */
+async function captureElement(element: Element): Promise<PickedElementPayload> {
+ const base = {
+ pageUrl: location.href,
+ pageTitle: document.title?.trim() || null,
+ tagName: element.tagName.toLowerCase(),
+ pickedAt: new Date().toISOString(),
+ };
try {
- const context = await getElementContext(element);
- const stack = (context.stack ?? []).map(toStackFrame);
- return {
- pageUrl: location.href,
- pageTitle: document.title?.trim() || null,
- tagName: element.tagName.toLowerCase(),
- selector: context.selector,
- htmlPreview: context.htmlPreview ?? "",
- componentName: context.componentName,
- source: stack[0] ?? null,
- stack,
- styles: context.styles ?? "",
- pickedAt: new Date().toISOString(),
- };
+ const context = await withCaptureTimeout(
+ Promise.resolve(getElementContext(element)),
+ ELEMENT_CONTEXT_TIMEOUT_MS,
+ );
+ if (context) {
+ const stack = (context.stack ?? []).map(toStackFrame);
+ return {
+ ...base,
+ selector: context.selector,
+ htmlPreview: context.htmlPreview ?? "",
+ componentName: context.componentName,
+ source: stack[0] ?? null,
+ stack,
+ styles: context.styles ?? "",
+ };
+ }
} catch {
- return null;
+ // Fall through to the DOM-only payload.
}
+ return {
+ ...base,
+ selector: null,
+ htmlPreview: element.outerHTML.slice(0, HTML_PREVIEW_MAX_CHARS),
+ componentName: null,
+ source: null,
+ stack: [],
+ styles: "",
+ };
}
function createButton(label: string, title: string): HTMLButtonElement {
@@ -1225,12 +1269,20 @@ function startAnnotation(): void {
pendingCapture = true;
submit.disabled = true;
submit.textContent = "Capturing…";
+ // Snapshot everything the annotation will carry before the capture runs.
+ // The element context lookup can take up to its timeout, and the user can
+ // keep editing meanwhile; the annotation must describe what they submitted.
+ const submittedComment = comment.value.trim();
+ const submittedRegions = [...regions];
+ const submittedStrokes = [...strokes];
+ const submittedStyleChanges = Array.from(styleChanges.values(), (change) => ({ ...change }));
void Promise.all(
Array.from(selected.values()).map(async (target) => {
const element = await captureElement(target.element);
- if (!element) return null;
- for (const change of styleChanges.values()) {
- if (change.targetId === target.id) change.selector = element.selector;
+ for (const change of submittedStyleChanges) {
+ if (change.targetId === target.id && element.selector !== null) {
+ change.selector = element.selector;
+ }
}
return {
id: target.id,
@@ -1238,30 +1290,39 @@ function startAnnotation(): void {
rect: rectFromDomRect(target.element.getBoundingClientRect()),
};
}),
- ).then((captured) => {
- const elements = captured.filter((target) => target !== null);
- const annotation: PreviewAnnotationPayload = {
- id: nextId("annotation"),
- pageUrl: location.href,
- pageTitle: document.title?.trim() || null,
- comment: comment.value.trim(),
- elements,
- regions: [...regions],
- strokes: [...strokes],
- styleChanges: Array.from(styleChanges.values()),
- screenshot: null,
- createdAt: new Date().toISOString(),
- };
- editor.style.display = "none";
- toolbar.style.display = "none";
- hoverOutline.style.display = "none";
- const screenshotRect = unionRects([
- ...elements.map((target) => target.rect),
- ...regions.map((region) => region.rect),
- ...strokes.map((stroke) => stroke.bounds),
- ]);
- ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
- });
+ )
+ .then((elements) => {
+ // The overlay may have been cancelled or replaced while the capture
+ // ran. A late submit must not deliver into the next pick's listener.
+ if (finished) return;
+ const annotation: PreviewAnnotationPayload = {
+ id: nextId("annotation"),
+ pageUrl: location.href,
+ pageTitle: document.title?.trim() || null,
+ comment: submittedComment,
+ elements,
+ regions: submittedRegions,
+ strokes: submittedStrokes,
+ styleChanges: submittedStyleChanges,
+ screenshot: null,
+ createdAt: new Date().toISOString(),
+ };
+ editor.style.display = "none";
+ toolbar.style.display = "none";
+ hoverOutline.style.display = "none";
+ const screenshotRect = unionRects([
+ ...elements.map((target) => target.rect),
+ ...submittedRegions.map((region) => region.rect),
+ ...submittedStrokes.map((stroke) => stroke.bounds),
+ ]);
+ ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
+ })
+ .catch(() => {
+ // Last resort. Main is waiting on this message, so hand it an empty
+ // pick rather than leaving the button stuck on "Capturing…" and the
+ // renderer's pick promise pending. teardown is a no-op once finished.
+ teardown(true);
+ });
};
submit.addEventListener("click", () => submitAnnotation("attach"));
root.addEventListener("keydown", (event) => {
diff --git a/apps/web/src/components/preview/PreviewView.test.tsx b/apps/web/src/components/preview/PreviewView.test.tsx
index 808842044e9..bb20ee36237 100644
--- a/apps/web/src/components/preview/PreviewView.test.tsx
+++ b/apps/web/src/components/preview/PreviewView.test.tsx
@@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({
openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
pickElement: vi.fn(),
- previewAnnotationScreenshotFile: vi.fn(),
+ capturePreviewAnnotationScreenshot: vi.fn(),
addPreviewAnnotation: vi.fn(),
addImage: vi.fn(),
toggleAnnotation: null as (() => void) | null,
@@ -90,7 +90,7 @@ vi.mock("~/composerDraftStore", () => ({
}));
vi.mock("~/lib/previewAnnotation", () => ({
- previewAnnotationScreenshotFile: mocks.previewAnnotationScreenshotFile,
+ capturePreviewAnnotationScreenshot: mocks.capturePreviewAnnotationScreenshot,
}));
vi.mock("~/localApi", () => ({
@@ -252,6 +252,7 @@ vi.mock("~/browser/BrowserSurfaceSlot", () => ({ BrowserSurfaceSlot: () => null
vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
import { PreviewView, previewProfileName } from "./PreviewView";
+import { toastManager } from "~/components/ui/toast";
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
const TEST_THREAD_REF = {
@@ -339,8 +340,10 @@ describe("PreviewView navigation", () => {
mocks.openPictureInPicture.mockClear();
mocks.closePictureInPicture.mockClear();
mocks.pickElement.mockReset();
- mocks.previewAnnotationScreenshotFile.mockReset();
+ mocks.capturePreviewAnnotationScreenshot.mockReset();
+ mocks.capturePreviewAnnotationScreenshot.mockResolvedValue({ status: "none" });
mocks.addPreviewAnnotation.mockClear();
+ vi.mocked(toastManager.add).mockClear();
mocks.addImage.mockClear();
mocks.toggleAnnotation = null;
mocks.pictureInPicture = false;
@@ -551,7 +554,39 @@ describe("PreviewView navigation", () => {
expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
});
- it("still sends when screenshot attachment conversion fails", async () => {
+ it("warns when main dropped the crop before handing over the pick", async () => {
+ const annotation = {
+ id: "annotation-3",
+ pageUrl: "https://example.com/dashboard",
+ pageTitle: "Dashboard",
+ comment: "Tighten this spacing",
+ elements: [],
+ regions: [],
+ strokes: [],
+ styleChanges: [],
+ screenshot: null,
+ createdAt: "2026-07-27T00:00:00.000Z",
+ };
+ const onSendAnnotation = vi.fn();
+ mocks.pickElement.mockResolvedValue({ annotation, submission: "send", screenshotFailed: true });
+
+ renderToStaticMarkup(
+ <PreviewView
+ threadRef={TEST_THREAD_REF}
+ tabId="tab-1"
+ visible
+ onSendAnnotation={onSendAnnotation}
+ />,
+ );
+ mocks.toggleAnnotation?.();
+
+ await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
+ // A null screenshot alone looks like a comment-only pick; the flag is what
+ // separates "no crop requested" from "crop lost to a timeout".
+ expect(toastManager.add).toHaveBeenCalledTimes(1);
+ });
+
+ it("still sends when the picked element's crop cannot be captured", async () => {
const annotation = {
id: "annotation-2",
pageUrl: "https://example.com/dashboard",
@@ -571,7 +606,7 @@ describe("PreviewView navigation", () => {
};
const onSendAnnotation = vi.fn();
mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
- mocks.previewAnnotationScreenshotFile.mockRejectedValue(new Error("conversion failed"));
+ mocks.capturePreviewAnnotationScreenshot.mockResolvedValue({ status: "failed" });
renderToStaticMarkup(
<PreviewView
@@ -583,7 +618,11 @@ describe("PreviewView navigation", () => {
);
mocks.toggleAnnotation?.();
- await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null));
+ // The forwarded and stored annotation both drop the screenshot, so the
+ // prompt does not claim a crop that was never attached.
+ const sent = { ...annotation, screenshot: null };
+ await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
+ expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
expect(mocks.addImage).not.toHaveBeenCalled();
});
});
diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx
index 6d431a48e3d..640690854e5 100644
--- a/apps/web/src/components/preview/PreviewView.tsx
+++ b/apps/web/src/components/preview/PreviewView.tsx
@@ -20,7 +20,7 @@ import {
useThreadRecentHistory,
} from "~/browserHistoryStore";
import { type ComposerImageAttachment, useComposerDraftStore } from "~/composerDraftStore";
-import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
+import { capturePreviewAnnotationScreenshot } from "~/lib/previewAnnotation";
import { ensureLocalApi } from "~/localApi";
import {
rememberPreviewUrl,
@@ -579,15 +579,30 @@ export function PreviewView({
try {
const result = await previewBridge.pickElement(runtimeTabId);
if (!result) return;
- const { annotation, submission } = result;
+ const { annotation: picked, submission, screenshotFailed = false } = result;
+ // The structured annotation is still sendable when its optional crop
+ // stalls or fails, so tell the user what they lost and keep going
+ // instead of holding the composer for an attachment that never lands.
+ // The stored copy drops the screenshot on failure, otherwise the prompt
+ // would tell the agent a crop is attached when none was sent.
+ const capture = await capturePreviewAnnotationScreenshot(picked);
+ // Main reports a crop that failed or timed out on its side; the local
+ // conversion can fail too. Either way the user should hear about it.
+ const cropDropped = screenshotFailed || capture.status === "failed";
+ const annotation = capture.status === "failed" ? { ...picked, screenshot: null } : picked;
addPreviewAnnotation(threadRef, annotation);
- let screenshotFile: File | null = null;
- try {
- screenshotFile = await previewAnnotationScreenshotFile(annotation);
- } catch {
- // The structured annotation is still sendable when converting its
- // optional screenshot into a composer attachment fails.
+ if (cropDropped) {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Could not capture the picked element",
+ // The send path reports its own outcome, so only say what this
+ // handler knows: the crop was dropped.
+ description: "The annotation was kept without the screenshot.",
+ }),
+ );
}
+ const screenshotFile = capture.status === "captured" ? capture.file : null;
const image =
screenshotFile && annotation.screenshot
? ({
diff --git a/apps/web/src/lib/previewAnnotation.test.ts b/apps/web/src/lib/previewAnnotation.test.ts
index 05f4b8d6273..a449de5ae84 100644
--- a/apps/web/src/lib/previewAnnotation.test.ts
+++ b/apps/web/src/lib/previewAnnotation.test.ts
@@ -1,9 +1,10 @@
import type { PreviewAnnotationPayload } from "@t3tools/contracts";
-import { describe, expect, it } from "vite-plus/test";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
appendPreviewAnnotationPrompt,
buildPreviewAnnotationPrompt,
+ capturePreviewAnnotationScreenshot,
extractTrailingPreviewAnnotation,
} from "./previewAnnotation";
@@ -85,3 +86,36 @@ describe("preview annotations", () => {
expect(extractedFirst.promptText).toBe("Fix this");
});
});
+
+describe("preview annotation capture", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it("returns the crop when the fetch resolves", async () => {
+ vi.stubGlobal("fetch", async () => new Response(new Blob(["png"], { type: "image/png" })));
+ const capture = await capturePreviewAnnotationScreenshot(annotation);
+ expect(capture.status).toBe("captured");
+ });
+
+ it("reports none when the annotation carries no crop", async () => {
+ const capture = await capturePreviewAnnotationScreenshot({ ...annotation, screenshot: null });
+ expect(capture).toEqual({ status: "none" });
+ });
+
+ it("fails instead of hanging when the crop never arrives", async () => {
+ vi.useFakeTimers();
+ vi.stubGlobal("fetch", () => new Promise<Response>(() => {}));
+ const capturePromise = capturePreviewAnnotationScreenshot(annotation, 1_000);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(await capturePromise).toEqual({ status: "failed" });
+ });
+
+ it("fails when the crop fetch throws", async () => {
+ vi.stubGlobal("fetch", async () => {
+ throw new Error("data url unreadable");
+ });
+ expect(await capturePreviewAnnotationScreenshot(annotation)).toEqual({ status: "failed" });
+ });
+});
diff --git a/apps/web/src/lib/previewAnnotation.ts b/apps/web/src/lib/previewAnnotation.ts
index f1723dd93aa..464c8c8a94d 100644
--- a/apps/web/src/lib/previewAnnotation.ts
+++ b/apps/web/src/lib/previewAnnotation.ts
@@ -99,7 +99,7 @@ export function extractTrailingPreviewAnnotation(prompt: string): ExtractedPrevi
};
}
-export async function previewAnnotationScreenshotFile(
+async function previewAnnotationScreenshotFile(
annotation: PreviewAnnotationPayload,
): Promise<File | null> {
if (!annotation.screenshot) return null;
@@ -109,3 +109,40 @@ export async function previewAnnotationScreenshotFile(
type: blob.type || "image/png",
});
}
+
+/** Upper bound on turning a picked element's crop into a composer attachment. */
+export const PREVIEW_ANNOTATION_CAPTURE_TIMEOUT_MS = 5_000;
+
+export type PreviewAnnotationCapture =
+ /** The crop is ready to attach. */
+ | { readonly status: "captured"; readonly file: File }
+ /** The pick carried no crop, which is normal for comment-only annotations. */
+ | { readonly status: "none" }
+ /** The crop stalled or threw. Send the annotation without it. */
+ | { readonly status: "failed" };
+
+/**
+ * Bounded wrapper around `previewAnnotationScreenshotFile`. The picker holds the
+ * composer while this runs, so it must always settle: a stalled crop resolves as
+ * `failed` instead of leaving the caller waiting.
+ */
+export async function capturePreviewAnnotationScreenshot(
+ annotation: PreviewAnnotationPayload,
+ timeoutMs: number = PREVIEW_ANNOTATION_CAPTURE_TIMEOUT_MS,
+): Promise<PreviewAnnotationCapture> {
+ if (!annotation.screenshot) return { status: "none" };
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const file = await Promise.race([
+ previewAnnotationScreenshotFile(annotation),
+ new Promise<null>((resolve) => {
+ timer = setTimeout(() => resolve(null), timeoutMs);
+ }),
+ ]);
+ return file ? { status: "captured", file } : { status: "failed" };
+ } catch {
+ return { status: "failed" };
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index ea276f4ff92..4c124b45623 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -934,11 +934,14 @@ export const PreviewAnnotationSubmissionSchema: Schema.Codec<PreviewAnnotationSu
export interface PreviewAnnotationSubmissionResult {
annotation: PreviewAnnotationPayload;
submission: PreviewAnnotationSubmission;
+ /** The crop was requested but failed or timed out, so `annotation.screenshot` is null. */
+ screenshotFailed?: boolean;
}
export const PreviewAnnotationSubmissionResultSchema: Schema.Codec<PreviewAnnotationSubmissionResult> =
Schema.Struct({
annotation: PreviewAnnotationPayloadSchema,
submission: PreviewAnnotationSubmissionSchema,
+ screenshotFailed: Schema.optionalKey(Schema.Boolean),
});
export const DesktopPreviewTabInputSchema = Schema.Struct({