Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
246 changes: 194 additions & 52 deletions apps/desktop/src/preview/Manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts";
import type {
DesktopPreviewRecordingFrame,
DesktopPreviewRecordingInputEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
} from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { parseKeybindingShortcut } from "@t3tools/shared/keybindings";
Expand Down Expand Up @@ -4328,68 +4330,208 @@ describe("PreviewManager", () => {
),
);

effectIt.effect("crops the picked area out of a full-page capture at device scale", () =>
withManager((manager) =>
Effect.gen(function* () {
let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined;
const crop = vi.fn((rect: Electron.Rectangle) => ({
getSize: () => ({ width: rect.width, height: rect.height }),
toDataURL: () => "data:image/png;base64,cropped",
}));
const capturePage = vi.fn(async () => ({
getSize: () => ({ width: 2000, height: 1200 }),
crop,
}));
fromId.mockReturnValue(
Object.assign(makeTestPreviewWebContents(capturePage as never), {
isFocused: () => true,
once: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof onPicked) => {
if (channel === "preview:element-picked") onPicked = listener;
}),
off: vi.fn(),
removeListener: vi.fn(),
describe("annotation screenshots", () => {
const captureAnnotation = (
cropRect: PreviewAnnotationRect | null,
targets: Partial<Pick<PreviewAnnotationPayload, "elements" | "regions" | "strokes">> = {},
emptyImage?: "viewport" | "crop",
) =>
withManager((manager) =>
Effect.gen(function* () {
let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined;
const crop = vi.fn((rect: Electron.Rectangle) => ({
isEmpty: () => emptyImage === "crop",
getSize: () =>
emptyImage === "crop"
? { width: 0, height: 0 }
: { width: rect.width, height: rect.height },
toDataURL: () => (emptyImage === "crop" ? "data:," : "data:image/png;base64,cropped"),
}));
const capturePage = vi.fn(async () => ({
isEmpty: () => emptyImage === "viewport",
getSize: () =>
emptyImage === "viewport" ? { width: 0, height: 0 } : { width: 2000, height: 1200 },
toJPEG: () => Buffer.from("unused"),
toDataURL: () => (emptyImage === "viewport" ? "data:," : "data:image/png;base64,full"),
crop,
}));
fromId.mockReturnValue(
Object.assign(makeTestPreviewWebContents(capturePage), {
isFocused: () => true,
once: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof onPicked) => {
if (channel === "preview:element-picked") onPicked = listener;
}),
off: vi.fn(),
removeListener: vi.fn(),
},
}),
);

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: [],
strokes: [],
...targets,
styleChanges: [],
screenshot: null,
createdAt: "2026-06-11T00:00:00.000Z",
},
}),
);
cropRect,
"attach",
2,
);

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",
},
{ x: 5, y: 6, width: 20, height: 30 },
"attach",
2,
);
const result = yield* Fiber.join(pick);
expect(capturePage).toHaveBeenCalledExactlyOnceWith();
expect(result?.annotation.comment).toBe("Tighten this spacing");
expect(result?.submission).toBe("attach");
return { result, crop };
}),
);

const result = yield* Fiber.join(pick);
expect(capturePage).toHaveBeenCalledWith();
expect(crop).toHaveBeenCalledWith({ x: 10, y: 12, width: 40, height: 60 });
effectIt.effect("crops an on-screen region at device scale", () =>
Effect.gen(function* () {
const rect = { x: 5, y: 6, width: 20, height: 30 };
const { result, crop } = yield* captureAnnotation(rect, {
regions: [{ id: "region_1", rect }],
});
expect(crop).toHaveBeenCalledExactlyOnceWith({ x: 10, y: 12, width: 40, height: 60 });
expect(result?.screenshotFailed).toBeUndefined();
expect(result?.annotation.screenshot).toEqual({
dataUrl: "data:image/png;base64,cropped",
width: 40,
height: 60,
cropRect: { x: 5, y: 6, width: 20, height: 30 },
cropRect: rect,
});
}),
),
);
);

effectIt.effect("clips a partially visible selection to the captured viewport", () =>
Effect.gen(function* () {
const { result, crop } = yield* captureAnnotation(
{ x: -40, y: 570, width: 240, height: 110 },
{ regions: [{ id: "region_1", rect: { x: -20, y: 590, width: 200, height: 70 } }] },
);
expect(crop).toHaveBeenCalledExactlyOnceWith({ x: 0, y: 1140, width: 400, height: 60 });
expect(result?.screenshotFailed).toBeUndefined();
expect(result?.annotation.screenshot).toMatchObject({
dataUrl: "data:image/png;base64,cropped",
width: 400,
height: 60,
});
}),
);

effectIt.effect.each([
{
name: "an offscreen crop without individual target bounds",
cropRect: { x: 1010, y: 40, width: 100, height: 70 },
regions: [],
},
{
name: "padding overlapping the viewport while its target is offscreen",
cropRect: { x: 40, y: -100, width: 240, height: 110 },
regions: [{ id: "region_1", rect: { x: 60, y: -80, width: 200, height: 70 } }],
},
{
name: "a union spanning the viewport with both targets offscreen",
cropRect: { x: -230, y: 40, width: 1460, height: 110 },
regions: [
{ id: "region_1", rect: { x: -210, y: 60, width: 200, height: 70 } },
{ id: "region_2", rect: { x: 1010, y: 60, width: 200, height: 70 } },
],
},
{
name: "an offscreen target when crop bounds are missing",
cropRect: null,
regions: [{ id: "region_1", rect: { x: 60, y: -80, width: 200, height: 70 } }],
},
])("does not attach $name", ({ cropRect, regions }) =>
Effect.gen(function* () {
const { result, crop } = yield* captureAnnotation(cropRect, { regions });
expect(crop).not.toHaveBeenCalled();
expect(result?.annotation.screenshot).toBeNull();
expect(result?.screenshotFailed).toBe(true);
}),
);

effectIt.effect.each([
{
name: "zero-width SVG line on the left edge",
rect: { x: 0, y: 60, width: 0, height: 70 },
cropRect: { x: -20, y: 40, width: 40, height: 110 },
expectedCrop: { x: 0, y: 80, width: 40, height: 220 },
},
{
name: "zero-height SVG line on the top edge",
rect: { x: 60, y: 0, width: 70, height: 0 },
cropRect: { x: 40, y: -20, width: 110, height: 40 },
expectedCrop: { x: 80, y: 0, width: 220, height: 40 },
},
])("captures a stroked $name", ({ rect, cropRect, expectedCrop }) =>
Effect.gen(function* () {
const { result, crop } = yield* captureAnnotation(cropRect, {
elements: [
{
id: "element_1",
rect,
element: {
pageUrl: "https://example.com",
pageTitle: "Example",
tagName: "line",
selector: "svg > line",
htmlPreview: '<line stroke="black" stroke-width="2" />',
componentName: null,
source: null,
stack: [],
styles: "stroke: black; stroke-width: 2px;",
pickedAt: "2026-06-11T00:00:00.000Z",
},
},
],
});
expect(crop).toHaveBeenCalledExactlyOnceWith(expectedCrop);
expect(result?.screenshotFailed).toBeUndefined();
expect(result?.annotation.screenshot).toMatchObject({
dataUrl: "data:image/png;base64,cropped",
width: expectedCrop.width,
height: expectedCrop.height,
});
}),
);

effectIt.effect.each(["viewport", "crop"] as const)(
"reports an empty native %s image as a failed screenshot",
(emptyImage) =>
Effect.gen(function* () {
const rect = { x: 5, y: 6, width: 20, height: 30 };
const { result, crop } = yield* captureAnnotation(
rect,
{
regions: [{ id: "region_1", rect }],
},
emptyImage,
);
if (emptyImage === "viewport") expect(crop).not.toHaveBeenCalled();
else
expect(crop).toHaveBeenCalledExactlyOnceWith({ x: 10, y: 12, width: 40, height: 60 });
expect(result?.annotation.screenshot).toBeNull();
expect(result?.screenshotFailed).toBe(true);
}),
);
});

effectIt.effect("a stale capture from a replaced pick never touches the next pick", () =>
withManager((manager) =>
Expand Down
55 changes: 39 additions & 16 deletions apps/desktop/src/preview/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,24 +270,35 @@ const normalizeCaptureRect = (value: unknown): PreviewAnnotationRect | null => {
) {
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)),
};
return { x, y, width, height };
};

/**
* Crops a full-page capture to a picked annotation. `cropRect` is in CSS px;
* the capture's pixels are CSS px × the guest's `devicePixelRatio`.
*/
// capturePage returns a 1x NativeImage containing device pixels, so crop() uses
// CSS coordinates scaled by the guest's devicePixelRatio (including page zoom).
const cropAnnotationScreenshot = (
image: Electron.NativeImage,
cropRect: PreviewAnnotationRect | null,
devicePixelRatio: number,
targetRects: ReadonlyArray<PreviewAnnotationRect>,
): PreviewAnnotationPayload["screenshot"] => {
const full = image.getSize();
if (full.width <= 0 || full.height <= 0) return null;
const scale = Number.isFinite(devicePixelRatio) && devicePixelRatio > 0 ? devicePixelRatio : 1;
// Padding or a union of offscreen targets can overlap an empty viewport area.
// A zero-width/height SVG line can still paint at the top or left edge.
if (
targetRects.length > 0 &&
!targetRects.some(
(rect) =>
(rect.width > 0 || rect.height > 0) &&
rect.x * scale < full.width &&
rect.y * scale < full.height &&
(rect.width === 0 ? rect.x >= 0 : rect.x + rect.width > 0) &&
(rect.height === 0 ? rect.y >= 0 : rect.y + rect.height > 0),
)
) {
return null;
}
if (!cropRect) {
return {
dataUrl: image.toDataURL(),
Expand All @@ -296,16 +307,21 @@ const cropAnnotationScreenshot = (
cropRect: { x: 0, y: 0, width: full.width, height: full.height },
};
}
const scale = Number.isFinite(devicePixelRatio) && devicePixelRatio > 0 ? devicePixelRatio : 1;
const x = Math.min(full.width - 1, Math.max(0, Math.floor(cropRect.x * scale)));
const y = Math.min(full.height - 1, Math.max(0, Math.floor(cropRect.y * scale)));
const x = Math.max(0, Math.floor(cropRect.x * scale));
const y = Math.max(0, Math.floor(cropRect.y * scale));
const right = Math.min(full.width, Math.ceil((cropRect.x + cropRect.width) * scale));
const bottom = Math.min(full.height, Math.ceil((cropRect.y + cropRect.height) * scale));
// A target scrolled out of view has no pixels in this capture. Clamping its
// origin onto the edge would attach an unrelated strip as a successful crop.
if (right <= x || bottom <= y) return null;
const cropped = image.crop({
x,
y,
width: Math.max(1, Math.min(full.width - x, Math.ceil(cropRect.width * scale))),
height: Math.max(1, Math.min(full.height - y, Math.ceil(cropRect.height * scale))),
width: right - x,
height: bottom - y,
});
const size = cropped.getSize();
if (size.width <= 0 || size.height <= 0) return null;
return { dataUrl: cropped.toDataURL(), width: size.width, height: size.height, cropRect };
};

Expand Down Expand Up @@ -2198,13 +2214,20 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const submission =
args[2] === "send" && annotationSendEnabled.get(tabId) === true ? "send" : "attach";
const devicePixelRatio = typeof args[3] === "number" ? args[3] : 1;
const targetRects = [
...payload.elements.map((target) => target.rect),
...payload.regions.map((target) => target.rect),
...payload.strokes.map((target) => target.bounds),
];
runFork(
capturePageWithRetry(
{ operation: "captureAnnotationScreenshot", tabId, webContentsId: wc.id },
tabId,
wc,
).pipe(
Effect.map((image) => cropAnnotationScreenshot(image, cropRect, devicePixelRatio)),
Effect.map((image) =>
cropAnnotationScreenshot(image, cropRect, devicePixelRatio, targetRects),
),
Effect.tapError((error) =>
Effect.logWarning("preview annotation screenshot failed").pipe(
Effect.annotateLogs({ tabId, webContentsId: wc.id, error: error.message }),
Expand Down
15 changes: 6 additions & 9 deletions apps/desktop/src/preview/PickPreload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,12 @@ function unionRects(
const top = Math.min(...rects.map((rect) => rect.y));
const right = Math.max(...rects.map((rect) => rect.x + rect.width));
const bottom = Math.max(...rects.map((rect) => rect.y + rect.height));
const x = Math.max(0, left - padding);
const y = Math.max(0, top - padding);
const maxWidth = Math.max(1, window.innerWidth - x);
const maxHeight = Math.max(1, window.innerHeight - y);
// Main clips to the captured viewport; clipping here would lose offscreen bounds.
return {
x,
y,
width: Math.min(maxWidth, right - left + padding * 2),
height: Math.min(maxHeight, bottom - top + padding * 2),
x: left - padding,
y: top - padding,
width: right - left + padding * 2,
height: bottom - top + padding * 2,
};
}

Expand Down Expand Up @@ -1439,7 +1436,7 @@ function startAnnotation(sendEnabled: boolean): void {
annotation,
screenshotRect,
submission === "send" && !sendEnabled ? "attach" : submission,
// Main crops a full-page capture, whose pixels are CSS px × this.
// Main crops a viewport capture, whose pixels are CSS px × this.
window.devicePixelRatio,
);
})
Expand Down
Loading