@devries-cameron20 / t3code-1 / commits / 3d9e8dea7d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Refactor desktop preview IPC onto shared manager

- Move preview session and IPC wiring into the new preview module - Tighten IPC validation with schema-based handlers - Update preview asset paths and tests for the browser preview port

Julius Marminge committed Jun 12, 2026 at 17:17 UTC 3d9e8dea7d0d7d775bfc617929d7bb2c5d3e651e
33 files changed +2617 -1844
apps/desktop/scripts/build-preview-annotation-css.mjs
+3 -3
@@ -7,9 +7,9 @@ import { compile } from "tailwindcss";
7
8 const directory = dirname(fileURLToPath(import.meta.url));
9 const appRoot = join(directory, "..");
10 -const sourcePath = join(appRoot, "src", "preview-annotation.css");
11 -const preloadPath = join(appRoot, "src", "preview-pick-preload.ts");
12 -const outputPath = join(appRoot, "src", "preview-annotation-styles.generated.ts");
10 +const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
11 +const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
12 +const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
13 const require = createRequire(import.meta.url);
14 const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
15
apps/desktop/src/app/DesktopApp.ts
+1 -1
@@ -176,7 +176,7 @@ const bootstrap = Effect.gen(function* () {
176 );
177 }
178
179 - yield* installDesktopIpcHandlers;
179 + yield* installDesktopIpcHandlers();
180 yield* logBootstrapInfo("bootstrap ipc handlers registered");
181
182 if (!(yield* Ref.get(state.quitting))) {
apps/desktop/src/ipc/DesktopIpcHandlers.ts
+5 -8
@@ -1,7 +1,5 @@
1 import * as Effect from "effect/Effect";
2
3 -import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
4 -import { previewViewManager } from "../preview-view-manager.ts";
3 import * as DesktopIpc from "./DesktopIpc.ts";
4 import {
5 clearCloudAuthToken,
@@ -50,12 +48,11 @@ import {
48 setTheme,
49 showContextMenu,
50 } from "./methods/window.ts";
53 -import { previewMethods } from "./methods/preview.ts";
51 +import * as PreviewIpc from "./methods/preview.ts";
52
55 -export const installDesktopIpcHandlers = Effect.gen(function* () {
53 +export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
54 const ipc = yield* DesktopIpc.DesktopIpc;
57 - const environment = yield* DesktopEnvironment.DesktopEnvironment;
58 - previewViewManager.configureArtifactDirectory(environment.browserArtifactsDir);
55 + yield* PreviewIpc.installPreviewEventForwarding();
56
57 yield* ipc.handleSync(getAppBranding);
58 yield* ipc.handleSync(getLocalEnvironmentBootstrap);
@@ -97,7 +94,7 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
94 yield* ipc.handle(downloadUpdate);
95 yield* ipc.handle(installUpdate);
96 yield* ipc.handle(checkForUpdate);
100 - for (const previewMethod of previewMethods) {
97 + for (const previewMethod of PreviewIpc.methods) {
98 yield* ipc.handle(previewMethod);
99 }
103 -}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
100 +});
apps/desktop/src/ipc/methods/preview.test.ts
+29 -3
@@ -1,8 +1,19 @@
1 +import { it as effectIt } from "@effect/vitest";
2 +import * as Cause from "effect/Cause";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 +import * as Option from "effect/Option";
6 +import * as Schema from "effect/Schema";
7 import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
8
3 -const fromPartition = vi.fn(() => {
4 - throw new Error("Session can only be received when app is ready");
5 -});
9 +import * as PreviewManager from "../../preview/Manager.ts";
10 +import * as PreviewIpc from "./preview.ts";
11 +
12 +const { fromPartition } = vi.hoisted(() => ({
13 + fromPartition: vi.fn(() => {
14 + throw new Error("Session can only be received when app is ready");
15 + }),
16 +}));
17
18 vi.mock("electron", () => ({
19 BrowserWindow: {
@@ -25,4 +36,19 @@ describe("preview IPC methods", () => {
36 await expect(import("./preview.ts")).resolves.toBeDefined();
37 expect(fromPartition).not.toHaveBeenCalled();
38 });
39 +
40 + effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
41 + Effect.map(
42 + PreviewIpc.registerWebview
43 + .handler({ tabId: "tab-1", webContentsId: 0 })
44 + .pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
45 + (exit) => {
46 + expect(Exit.isFailure(exit)).toBe(true);
47 + if (Exit.isSuccess(exit)) return;
48 + const error = Cause.findErrorOption(exit.cause);
49 + expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
50 + expect(fromPartition).not.toHaveBeenCalled();
51 + },
52 + ),
53 + );
54 });
apps/desktop/src/ipc/methods/preview.ts
+349 -222
@@ -1,251 +1,378 @@
1 // @effect-diagnostics nodeBuiltinImport:off
2 -import * as Data from "effect/Data";
3 -import * as Effect from "effect/Effect";
4 -import type { DesktopPreviewAnnotationTheme } from "@t3tools/contracts";
2 +import {
3 + DesktopPreviewAnnotationThemeInputSchema,
4 + DesktopPreviewArtifactInputSchema,
5 + DesktopPreviewAutomationClickInputSchema,
6 + DesktopPreviewAutomationEvaluateInputSchema,
7 + DesktopPreviewAutomationPressInputSchema,
8 + DesktopPreviewAutomationScrollInputSchema,
9 + DesktopPreviewAutomationTypeInputSchema,
10 + DesktopPreviewAutomationWaitForInputSchema,
11 + DesktopPreviewConfigInputSchema,
12 + DesktopPreviewNavigateInputSchema,
13 + DesktopPreviewRecordingArtifactSchema,
14 + DesktopPreviewRecordingSaveInputSchema,
15 + DesktopPreviewRegisterWebviewInputSchema,
16 + DesktopPreviewScreenshotArtifactSchema,
17 + DesktopPreviewTabInputSchema,
18 + DesktopPreviewWebviewConfigSchema,
19 + PreviewAnnotationPayloadSchema,
20 + PreviewAutomationSnapshot,
21 + PreviewAutomationStatus,
22 +} from "@t3tools/contracts";
23 import { BrowserWindow } from "electron";
24 +import * as Effect from "effect/Effect";
25 +import * as Schema from "effect/Schema";
26 import { pathToFileURL } from "node:url";
27
8 -import { previewViewManager } from "../../preview-view-manager.ts";
9 -import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview-webview-preferences.ts";
28 +import * as PreviewManager from "../../preview/Manager.ts";
29 +import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
30 import * as IpcChannels from "../channels.ts";
11 -import type { DesktopIpcMethod } from "../DesktopIpc.ts";
31 +import { makeIpcMethod } from "../DesktopIpc.ts";
32
13 -previewViewManager.onStateChange((tabId, state) => {
33 +const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
34 for (const window of BrowserWindow.getAllWindows()) {
35 if (!window.isDestroyed()) {
16 - window.webContents.send(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
36 + window.webContents.send(channel, ...args);
37 }
38 }
19 -});
39 +};
40
21 -previewViewManager.onRecordingFrame((frame) => {
22 - for (const window of BrowserWindow.getAllWindows()) {
23 - if (!window.isDestroyed()) {
24 - window.webContents.send(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
25 - }
26 - }
41 +export const installPreviewEventForwarding = Effect.fn(
42 + "desktop.ipc.preview.installEventForwarding",
43 +)(function* () {
44 + const manager = yield* PreviewManager.PreviewManager;
45 + yield* manager.subscribeStateChanges((tabId, state) => {
46 + broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
47 + });
48 + yield* manager.subscribeRecordingFrames((frame) => {
49 + broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
50 + });
51 + yield* manager.subscribePointerEvents((event) => {
52 + broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
53 + });
54 });
55
29 -previewViewManager.onPointerEvent((event) => {
30 - for (const window of BrowserWindow.getAllWindows()) {
31 - if (!window.isDestroyed()) {
32 - window.webContents.send(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
33 - }
34 - }
56 +export const createTab = makeIpcMethod({
57 + channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
58 + payload: DesktopPreviewTabInputSchema,
59 + result: Schema.Void,
60 + handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
61 + const manager = yield* PreviewManager.PreviewManager;
62 + yield* manager.createTab(tabId);
63 + }),
64 });
65
37 -const tabIdFrom = (raw: unknown): string => {
38 - if (typeof raw !== "object" || raw === null || !("tabId" in raw)) {
39 - throw new Error("preview tab id is required");
40 - }
41 - const tabId = raw.tabId;
42 - if (typeof tabId !== "string" || tabId.trim().length === 0) {
43 - throw new Error("preview tab id must be a non-empty string");
44 - }
45 - return tabId;
46 -};
47 -
48 -const inputFrom = (raw: unknown): unknown => {
49 - if (typeof raw !== "object" || raw === null || !("input" in raw)) {
50 - throw new Error("preview automation input is required");
51 - }
52 - return raw.input;
53 -};
66 +export const closeTab = makeIpcMethod({
67 + channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
68 + payload: DesktopPreviewTabInputSchema,
69 + result: Schema.Void,
70 + handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
71 + const manager = yield* PreviewManager.PreviewManager;
72 + yield* manager.closeTab(tabId);
73 + }),
74 +});
75
55 -const annotationThemeFrom = (raw: unknown): DesktopPreviewAnnotationTheme => {
56 - if (typeof raw !== "object" || raw === null || !("theme" in raw)) {
57 - throw new Error("preview annotation theme is required");
58 - }
59 - const theme = raw.theme;
60 - if (typeof theme !== "object" || theme === null) {
61 - throw new Error("preview annotation theme must be an object");
62 - }
63 - const record = theme as Record<string, unknown>;
64 - const stringKeys = [
65 - "radius",
66 - "background",
67 - "foreground",
68 - "popover",
69 - "popoverForeground",
70 - "primary",
71 - "primaryForeground",
72 - "muted",
73 - "mutedForeground",
74 - "accent",
75 - "accentForeground",
76 - "border",
77 - "input",
78 - "ring",
79 - "fontSans",
80 - "fontMono",
81 - ] as const;
82 - for (const key of stringKeys) {
83 - if (typeof record[key] !== "string" || record[key].length === 0) {
84 - throw new Error(`preview annotation theme ${key} must be a non-empty string`);
85 - }
86 - }
87 - if (record["colorScheme"] !== "light" && record["colorScheme"] !== "dark") {
88 - throw new Error("preview annotation theme colorScheme must be light or dark");
89 - }
90 - return record as unknown as DesktopPreviewAnnotationTheme;
91 -};
76 +export const registerWebview = makeIpcMethod({
77 + channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
78 + payload: DesktopPreviewRegisterWebviewInputSchema,
79 + result: Schema.Void,
80 + handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
81 + const manager = yield* PreviewManager.PreviewManager;
82 + yield* manager.registerWebview(tabId, webContentsId);
83 + }),
84 +});
85
93 -class PreviewIpcError extends Data.TaggedError("PreviewIpcError")<{
94 - readonly cause: unknown;
95 -}> {}
86 +export const navigate = makeIpcMethod({
87 + channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
88 + payload: DesktopPreviewNavigateInputSchema,
89 + result: Schema.Void,
90 + handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
91 + const manager = yield* PreviewManager.PreviewManager;
92 + yield* manager.navigate(tabId, url);
93 + }),
94 +});
95
97 -const method = (
96 +const tabMethod = (
97 channel: string,
99 - handler: (raw: unknown) => unknown | Promise<unknown>,
100 -): DesktopIpcMethod<PreviewIpcError, never> => ({
101 - channel,
102 - handler: (raw) =>
103 - Effect.tryPromise({
104 - try: () => Promise.resolve(handler(raw)),
105 - catch: (cause) => new PreviewIpcError({ cause }),
98 + name: string,
99 + invoke: (
100 + manager: PreviewManager.PreviewManagerShape,
101 + tabId: string,
102 + ) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
103 +) =>
104 + makeIpcMethod({
105 + channel,
106 + payload: DesktopPreviewTabInputSchema,
107 + result: Schema.Void,
108 + handler: Effect.fn(name)(function* ({ tabId }) {
109 + const manager = yield* PreviewManager.PreviewManager;
110 + yield* invoke(manager, tabId);
111 }),
112 + });
113 +
114 +export const goBack = tabMethod(
115 + IpcChannels.PREVIEW_GO_BACK_CHANNEL,
116 + "desktop.ipc.preview.goBack",
117 + (manager, tabId) => manager.goBack(tabId),
118 +);
119 +export const goForward = tabMethod(
120 + IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
121 + "desktop.ipc.preview.goForward",
122 + (manager, tabId) => manager.goForward(tabId),
123 +);
124 +export const refresh = tabMethod(
125 + IpcChannels.PREVIEW_REFRESH_CHANNEL,
126 + "desktop.ipc.preview.refresh",
127 + (manager, tabId) => manager.refresh(tabId),
128 +);
129 +export const zoomIn = tabMethod(
130 + IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
131 + "desktop.ipc.preview.zoomIn",
132 + (manager, tabId) => manager.zoomIn(tabId),
133 +);
134 +export const zoomOut = tabMethod(
135 + IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
136 + "desktop.ipc.preview.zoomOut",
137 + (manager, tabId) => manager.zoomOut(tabId),
138 +);
139 +export const resetZoom = tabMethod(
140 + IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
141 + "desktop.ipc.preview.resetZoom",
142 + (manager, tabId) => manager.resetZoom(tabId),
143 +);
144 +export const hardReload = tabMethod(
145 + IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
146 + "desktop.ipc.preview.hardReload",
147 + (manager, tabId) => manager.hardReload(tabId),
148 +);
149 +export const openDevTools = tabMethod(
150 + IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
151 + "desktop.ipc.preview.openDevTools",
152 + (manager, tabId) => manager.openDevTools(tabId),
153 +);
154 +export const cancelPickElement = tabMethod(
155 + IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
156 + "desktop.ipc.preview.cancelPickElement",
157 + (manager, tabId) => manager.cancelPickElement(tabId),
158 +);
159 +export const startRecording = tabMethod(
160 + IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
161 + "desktop.ipc.preview.startRecording",
162 + (manager, tabId) => manager.startRecording(tabId),
163 +);
164 +export const stopRecording = tabMethod(
165 + IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
166 + "desktop.ipc.preview.stopRecording",
167 + (manager, tabId) => manager.stopRecording(tabId),
168 +);
169 +
170 +export const clearCookies = makeIpcMethod({
171 + channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
172 + payload: Schema.Void,
173 + result: Schema.Void,
174 + handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
175 + const manager = yield* PreviewManager.PreviewManager;
176 + yield* manager.clearCookies();
177 + }),
178 });
179
109 -export const previewMethods = [
110 - method(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, (raw) =>
111 - previewViewManager.createTab(tabIdFrom(raw)),
112 - ),
113 - method(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, (raw) =>
114 - previewViewManager.closeTab(tabIdFrom(raw)),
115 - ),
116 - method(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, (raw) => {
117 - const tabId = tabIdFrom(raw);
118 - const webContentsId =
119 - typeof raw === "object" && raw !== null && "webContentsId" in raw ? raw.webContentsId : null;
120 - if (
121 - typeof webContentsId !== "number" ||
122 - !Number.isInteger(webContentsId) ||
123 - webContentsId <= 0
124 - ) {
125 - throw new Error("preview webContentsId must be a positive integer");
126 - }
127 - return previewViewManager.registerWebview(tabId, webContentsId);
128 - }),
129 - method(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, (raw) => {
130 - const tabId = tabIdFrom(raw);
131 - const url = typeof raw === "object" && raw !== null && "url" in raw ? raw.url : null;
132 - if (typeof url !== "string") throw new Error("preview url must be a string");
133 - return previewViewManager.navigate(tabId, url);
134 - }),
135 - method(IpcChannels.PREVIEW_GO_BACK_CHANNEL, (raw) => previewViewManager.goBack(tabIdFrom(raw))),
136 - method(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, (raw) =>
137 - previewViewManager.goForward(tabIdFrom(raw)),
138 - ),
139 - method(IpcChannels.PREVIEW_REFRESH_CHANNEL, (raw) => previewViewManager.refresh(tabIdFrom(raw))),
140 - method(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, (raw) => previewViewManager.zoomIn(tabIdFrom(raw))),
141 - method(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, (raw) => previewViewManager.zoomOut(tabIdFrom(raw))),
142 - method(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, (raw) =>
143 - previewViewManager.resetZoom(tabIdFrom(raw)),
144 - ),
145 - method(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, (raw) =>
146 - previewViewManager.hardReload(tabIdFrom(raw)),
147 - ),
148 - method(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, (raw) =>
149 - previewViewManager.openDevTools(tabIdFrom(raw)),
150 - ),
151 - method(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, () => previewViewManager.clearCookies()),
152 - method(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL, () => previewViewManager.clearCache()),
153 - method(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, (raw) => {
154 - const environmentId =
155 - typeof raw === "object" && raw !== null && "environmentId" in raw ? raw.environmentId : null;
156 - if (typeof environmentId !== "string" || environmentId.length === 0) {
157 - throw new Error("preview environment id is required");
158 - }
159 - previewViewManager.getBrowserSession(environmentId);
160 - const preloadPath = `${__dirname}/preview-pick-preload.cjs`;
180 +export const clearCache = makeIpcMethod({
181 + channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
182 + payload: Schema.Void,
183 + result: Schema.Void,
184 + handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
185 + const manager = yield* PreviewManager.PreviewManager;
186 + yield* manager.clearCache();
187 + }),
188 +});
189 +
190 +export const getPreviewConfig = makeIpcMethod({
191 + channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
192 + payload: DesktopPreviewConfigInputSchema,
193 + result: DesktopPreviewWebviewConfigSchema,
194 + handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
195 + const manager = yield* PreviewManager.PreviewManager;
196 + yield* manager.getBrowserSession(environmentId);
197 return {
162 - partition: previewViewManager.getBrowserPartition(environmentId),
198 + partition: manager.getBrowserPartition(environmentId),
199 webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
164 - preloadUrl: pathToFileURL(preloadPath).href,
200 + preloadUrl: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
201 };
202 }),
167 - method(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, (raw) =>
168 - previewViewManager.setAnnotationTheme(annotationThemeFrom(raw)),
169 - ),
170 - method(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, (raw) =>
171 - previewViewManager.pickElement(tabIdFrom(raw)),
172 - ),
173 - method(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, (raw) =>
174 - previewViewManager.cancelPickElement(tabIdFrom(raw)),
175 - ),
176 - method(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, (raw) =>
177 - previewViewManager.captureScreenshot(tabIdFrom(raw)),
178 - ),
179 - method(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, (raw) => {
180 - const path = typeof raw === "object" && raw !== null && "path" in raw ? raw.path : null;
181 - if (typeof path !== "string" || path.trim().length === 0) {
182 - throw new Error("preview artifact path is required");
183 - }
184 - return previewViewManager.revealArtifact(path);
203 +});
204 +
205 +export const setAnnotationTheme = makeIpcMethod({
206 + channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
207 + payload: DesktopPreviewAnnotationThemeInputSchema,
208 + result: Schema.Void,
209 + handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
210 + const manager = yield* PreviewManager.PreviewManager;
211 + yield* manager.setAnnotationTheme(theme);
212 }),
186 - method(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, (raw) => {
187 - const path = typeof raw === "object" && raw !== null && "path" in raw ? raw.path : null;
188 - if (typeof path !== "string" || path.trim().length === 0) {
189 - throw new Error("preview artifact path is required");
190 - }
191 - return previewViewManager.copyArtifactToClipboard(path);
192 - }),
193 - method(IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, (raw) =>
194 - previewViewManager.automationStatus(tabIdFrom(raw)),
195 - ),
196 - method(IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL, (raw) =>
197 - previewViewManager.automationSnapshot(tabIdFrom(raw)),
198 - ),
199 - method(IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL, (raw) =>
200 - previewViewManager.automationClick(
201 - tabIdFrom(raw),
202 - inputFrom(raw) as Parameters<typeof previewViewManager.automationClick>[1],
203 - ),
204 - ),
205 - method(IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL, (raw) =>
206 - previewViewManager.automationType(
207 - tabIdFrom(raw),
208 - inputFrom(raw) as Parameters<typeof previewViewManager.automationType>[1],
209 - ),
210 - ),
211 - method(IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL, (raw) =>
212 - previewViewManager.automationPress(
213 - tabIdFrom(raw),
214 - inputFrom(raw) as Parameters<typeof previewViewManager.automationPress>[1],
215 - ),
216 - ),
217 - method(IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL, (raw) =>
218 - previewViewManager.automationScroll(
219 - tabIdFrom(raw),
220 - inputFrom(raw) as Parameters<typeof previewViewManager.automationScroll>[1],
221 - ),
222 - ),
223 - method(IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL, (raw) =>
224 - previewViewManager.automationEvaluate(
225 - tabIdFrom(raw),
226 - inputFrom(raw) as Parameters<typeof previewViewManager.automationEvaluate>[1],
227 - ),
228 - ),
229 - method(IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL, (raw) =>
230 - previewViewManager.automationWaitFor(
231 - tabIdFrom(raw),
232 - inputFrom(raw) as Parameters<typeof previewViewManager.automationWaitFor>[1],
233 - ),
234 - ),
235 - method(IpcChannels.PREVIEW_RECORDING_START_CHANNEL, (raw) =>
236 - previewViewManager.startRecording(tabIdFrom(raw)),
237 - ),
238 - method(IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL, (raw) =>
239 - previewViewManager.stopRecording(tabIdFrom(raw)),
240 - ),
241 - method(IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, (raw) => {
242 - const tabId = tabIdFrom(raw);
243 - if (typeof raw !== "object" || raw === null) throw new Error("recording payload is required");
244 - const mimeType = "mimeType" in raw ? raw.mimeType : null;
245 - const data = "data" in raw ? raw.data : null;
246 - if (typeof mimeType !== "string" || !(data instanceof Uint8Array)) {
247 - throw new Error("recording mimeType and bytes are required");
248 - }
249 - return previewViewManager.saveRecording(tabId, mimeType, data);
213 +});
214 +
215 +export const pickElement = makeIpcMethod({
216 + channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
217 + payload: DesktopPreviewTabInputSchema,
218 + result: Schema.NullOr(PreviewAnnotationPayloadSchema),
219 + handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
220 + const manager = yield* PreviewManager.PreviewManager;
221 + return yield* manager.pickElement(tabId);
222 + }),
223 +});
224 +
225 +export const captureScreenshot = makeIpcMethod({
226 + channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
227 + payload: DesktopPreviewTabInputSchema,
228 + result: DesktopPreviewScreenshotArtifactSchema,
229 + handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
230 + const manager = yield* PreviewManager.PreviewManager;
231 + return yield* manager.captureScreenshot(tabId);
232 + }),
233 +});
234 +
235 +export const revealArtifact = makeIpcMethod({
236 + channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
237 + payload: DesktopPreviewArtifactInputSchema,
238 + result: Schema.Void,
239 + handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
240 + const manager = yield* PreviewManager.PreviewManager;
241 + yield* manager.revealArtifact(path);
242 + }),
243 +});
244 +
245 +export const copyArtifactToClipboard = makeIpcMethod({
246 + channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
247 + payload: DesktopPreviewArtifactInputSchema,
248 + result: Schema.Void,
249 + handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
250 + const manager = yield* PreviewManager.PreviewManager;
251 + yield* manager.copyArtifactToClipboard(path);
252 + }),
253 +});
254 +
255 +export const automationStatus = makeIpcMethod({
256 + channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
257 + payload: DesktopPreviewTabInputSchema,
258 + result: PreviewAutomationStatus,
259 + handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
260 + const manager = yield* PreviewManager.PreviewManager;
261 + return yield* manager.automationStatus(tabId);
262 + }),
263 +});
264 +
265 +export const automationSnapshot = makeIpcMethod({
266 + channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
267 + payload: DesktopPreviewTabInputSchema,
268 + result: PreviewAutomationSnapshot,
269 + handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
270 + const manager = yield* PreviewManager.PreviewManager;
271 + return yield* manager.automationSnapshot(tabId);
272 + }),
273 +});
274 +
275 +export const automationClick = makeIpcMethod({
276 + channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
277 + payload: DesktopPreviewAutomationClickInputSchema,
278 + result: Schema.Void,
279 + handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
280 + const manager = yield* PreviewManager.PreviewManager;
281 + yield* manager.automationClick(tabId, input);
282 + }),
283 +});
284 +
285 +export const automationType = makeIpcMethod({
286 + channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
287 + payload: DesktopPreviewAutomationTypeInputSchema,
288 + result: Schema.Void,
289 + handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
290 + const manager = yield* PreviewManager.PreviewManager;
291 + yield* manager.automationType(tabId, input);
292 }),
293 +});
294 +
295 +export const automationPress = makeIpcMethod({
296 + channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
297 + payload: DesktopPreviewAutomationPressInputSchema,
298 + result: Schema.Void,
299 + handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
300 + const manager = yield* PreviewManager.PreviewManager;
301 + yield* manager.automationPress(tabId, input);
302 + }),
303 +});
304 +
305 +export const automationScroll = makeIpcMethod({
306 + channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
307 + payload: DesktopPreviewAutomationScrollInputSchema,
308 + result: Schema.Void,
309 + handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
310 + const manager = yield* PreviewManager.PreviewManager;
311 + yield* manager.automationScroll(tabId, input);
312 + }),
313 +});
314 +
315 +export const automationEvaluate = makeIpcMethod({
316 + channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
317 + payload: DesktopPreviewAutomationEvaluateInputSchema,
318 + result: Schema.Unknown,
319 + handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
320 + const manager = yield* PreviewManager.PreviewManager;
321 + return yield* manager.automationEvaluate(tabId, input);
322 + }),
323 +});
324 +
325 +export const automationWaitFor = makeIpcMethod({
326 + channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
327 + payload: DesktopPreviewAutomationWaitForInputSchema,
328 + result: Schema.Void,
329 + handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
330 + const manager = yield* PreviewManager.PreviewManager;
331 + yield* manager.automationWaitFor(tabId, input);
332 + }),
333 +});
334 +
335 +export const saveRecording = makeIpcMethod({
336 + channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
337 + payload: DesktopPreviewRecordingSaveInputSchema,
338 + result: DesktopPreviewRecordingArtifactSchema,
339 + handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
340 + const manager = yield* PreviewManager.PreviewManager;
341 + return yield* manager.saveRecording(tabId, mimeType, data);
342 + }),
343 +});
344 +
345 +export const methods = [
346 + createTab,
347 + closeTab,
348 + registerWebview,
349 + navigate,
350 + goBack,
351 + goForward,
352 + refresh,
353 + zoomIn,
354 + zoomOut,
355 + resetZoom,
356 + hardReload,
357 + openDevTools,
358 + clearCookies,
359 + clearCache,
360 + getPreviewConfig,
361 + setAnnotationTheme,
362 + pickElement,
363 + cancelPickElement,
364 + captureScreenshot,
365 + revealArtifact,
366 + copyArtifactToClipboard,
367 + automationStatus,
368 + automationSnapshot,
369 + automationClick,
370 + automationType,
371 + automationPress,
372 + automationScroll,
373 + automationEvaluate,
374 + automationWaitFor,
375 + startRecording,
376 + stopRecording,
377 + saveRecording,
378 ] as const;
apps/desktop/src/main.ts
+11 -1
@@ -44,6 +44,8 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
44 import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
45 import * as DesktopState from "./app/DesktopState.ts";
46 import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
47 +import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
48 +import * as PreviewManager from "./preview/Manager.ts";
49 import * as DesktopWindow from "./window/DesktopWindow.ts";
50
51 const desktopEnvironmentLayer = Layer.unwrap(
@@ -127,7 +129,15 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
129 Layer.provideMerge(desktopFoundationLayer),
130 );
131
130 -const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
132 +const desktopPreviewLayer = PreviewManager.layer.pipe(
133 + Layer.provideMerge(PreviewBrowserSession.layer),
134 + Layer.provideMerge(desktopFoundationLayer),
135 +);
136 +
137 +const desktopWindowLayer = DesktopWindow.layer.pipe(
138 + Layer.provideMerge(desktopServerExposureLayer),
139 + Layer.provideMerge(desktopPreviewLayer),
140 +);
141
142 const desktopBackendLayer = DesktopBackendManager.layer.pipe(
143 Layer.provideMerge(DesktopAppIdentity.layer),
apps/desktop/src/preview-pick-preload.ts
+1 -1262
@@ -1,1262 +1 @@
1 -// @effect-diagnostics globalDate:off
2 -import { ipcRenderer } from "electron";
3 -import { getElementContext } from "react-grab/primitives";
4 -import type {
5 - DesktopPreviewAnnotationTheme,
6 - PickedElementPayload,
7 - PickedElementStackFrame,
8 - PreviewAnnotationPayload,
9 - PreviewAnnotationPoint,
10 - PreviewAnnotationRect,
11 - PreviewAnnotationRegionTarget,
12 - PreviewAnnotationStrokeTarget,
13 - PreviewAnnotationStyleChange,
14 -} from "@t3tools/contracts";
15 -
16 -import { previewAnnotationStyles } from "./preview-annotation-styles.generated.ts";
17 -
18 -const START_PICK_CHANNEL = "preview:start-pick";
19 -const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
20 -const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
21 -const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
22 -const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
23 -const HUMAN_INPUT_CHANNEL = "preview:human-input";
24 -const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui";
25 -const Z_INDEX_OVERLAY = 2147483646;
26 -const PRIMARY = "var(--t3-primary)";
27 -const PRIMARY_FILL = "color-mix(in srgb, var(--t3-primary) 10%, transparent)";
28 -const MAX_MARQUEE_ELEMENTS = 20;
29 -const CONTENT_LAYER_Z_INDEX = 1;
30 -const CHROME_LAYER_Z_INDEX = 10;
31 -
32 -type AnnotationTool = "select" | "marquee" | "draw" | "erase";
33 -
34 -interface SelectedElement {
35 - id: string;
36 - element: Element;
37 - outline: HTMLDivElement;
38 - label: HTMLDivElement;
39 - baselineStyles: Map<string, string>;
40 -}
41 -
42 -interface AnnotationSession {
43 - teardown: (notifyMain: boolean) => void;
44 - applyTheme: (theme: DesktopPreviewAnnotationTheme) => void;
45 -}
46 -
47 -let activeSession: AnnotationSession | null = null;
48 -let idSequence = 0;
49 -let annotationTheme: DesktopPreviewAnnotationTheme | null = null;
50 -
51 -const applyAnnotationTheme = (
52 - host: HTMLElement,
53 - theme: DesktopPreviewAnnotationTheme | null,
54 -): void => {
55 - if (!theme) return;
56 - host.style.colorScheme = theme.colorScheme;
57 - const variables = {
58 - "--t3-radius": theme.radius,
59 - "--t3-background": theme.background,
60 - "--t3-foreground": theme.foreground,
61 - "--t3-popover": theme.popover,
62 - "--t3-popover-foreground": theme.popoverForeground,
63 - "--t3-primary": theme.primary,
64 - "--t3-primary-foreground": theme.primaryForeground,
65 - "--t3-muted": theme.muted,
66 - "--t3-muted-foreground": theme.mutedForeground,
67 - "--t3-accent": theme.accent,
68 - "--t3-accent-foreground": theme.accentForeground,
69 - "--t3-border": theme.border,
70 - "--t3-input": theme.input,
71 - "--t3-ring": theme.ring,
72 - "--t3-font-sans": theme.fontSans,
73 - "--t3-font-mono": theme.fontMono,
74 - };
75 - for (const [name, value] of Object.entries(variables)) {
76 - host.style.setProperty(name, value);
77 - }
78 -};
79 -
80 -const reportHumanPointerInput = (event: PointerEvent): void => {
81 - if (!event.isTrusted) return;
82 - ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
83 - kind: "pointer",
84 - x: event.clientX,
85 - y: event.clientY,
86 - button: event.button,
87 - });
88 -};
89 -
90 -const reportHumanKeyInput = (event: KeyboardEvent): void => {
91 - if (!event.isTrusted) return;
92 - ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
93 - kind: "key",
94 - key: event.key,
95 - code: event.code,
96 - });
97 -};
98 -
99 -window.addEventListener("pointerdown", reportHumanPointerInput, true);
100 -window.addEventListener("keydown", reportHumanKeyInput, true);
101 -
102 -const nextId = (prefix: string): string => {
103 - idSequence += 1;
104 - return `${prefix}_${idSequence.toString(36)}`;
105 -};
106 -
107 -const rectFromDomRect = (rect: DOMRect): PreviewAnnotationRect => ({
108 - x: rect.left,
109 - y: rect.top,
110 - width: rect.width,
111 - height: rect.height,
112 -});
113 -
114 -const normalizeRect = (
115 - startX: number,
116 - startY: number,
117 - endX: number,
118 - endY: number,
119 -): PreviewAnnotationRect => ({
120 - x: Math.min(startX, endX),
121 - y: Math.min(startY, endY),
122 - width: Math.abs(endX - startX),
123 - height: Math.abs(endY - startY),
124 -});
125 -
126 -const isUsableRect = (rect: PreviewAnnotationRect): boolean => rect.width >= 3 && rect.height >= 3;
127 -
128 -function unionRects(
129 - rects: ReadonlyArray<PreviewAnnotationRect>,
130 - padding = 20,
131 -): PreviewAnnotationRect | null {
132 - if (rects.length === 0) return null;
133 - const left = Math.min(...rects.map((rect) => rect.x));
134 - const top = Math.min(...rects.map((rect) => rect.y));
135 - const right = Math.max(...rects.map((rect) => rect.x + rect.width));
136 - const bottom = Math.max(...rects.map((rect) => rect.y + rect.height));
137 - const x = Math.max(0, left - padding);
138 - const y = Math.max(0, top - padding);
139 - const maxWidth = Math.max(1, window.innerWidth - x);
140 - const maxHeight = Math.max(1, window.innerHeight - y);
141 - return {
142 - x,
143 - y,
144 - width: Math.min(maxWidth, right - left + padding * 2),
145 - height: Math.min(maxHeight, bottom - top + padding * 2),
146 - };
147 -}
148 -
149 -function isAnnotationNode(element: Element): boolean {
150 - return element instanceof Element && element.closest(`[${OVERLAY_ATTRIBUTE}]`) !== null;
151 -}
152 -
153 -function pickFromPoint(clientX: number, clientY: number): Element | null {
154 - for (const candidate of document.elementsFromPoint(clientX, clientY)) {
155 - if (!(candidate instanceof Element)) continue;
156 - if (isAnnotationNode(candidate)) continue;
157 - if (candidate === document.documentElement || candidate === document.body) continue;
158 - return candidate;
159 - }
160 - return null;
161 -}
162 -
163 -function describeRawElement(element: Element): string {
164 - const tag = element.tagName.toLowerCase();
165 - const id = element.id ? `#${element.id}` : "";
166 - const classes =
167 - element instanceof HTMLElement && typeof element.className === "string"
168 - ? element.className
169 - .trim()
170 - .split(/\s+/)
171 - .filter(Boolean)
172 - .slice(0, 2)
173 - .map((name) => `.${name}`)
174 - .join("")
175 - : "";
176 - return `${tag}${id}${classes}`;
177 -}
178 -
179 -function createBox(color: string, fill: string): HTMLDivElement {
180 - const node = document.createElement("div");
181 - node.setAttribute(OVERLAY_ATTRIBUTE, "");
182 - node.style.cssText = [
183 - "position:fixed",
184 - "pointer-events:none",
185 - `border:2px solid ${color}`,
186 - `background:${fill}`,
187 - "border-radius:3px",
188 - "box-sizing:border-box",
189 - "display:none",
190 - `z-index:${CONTENT_LAYER_Z_INDEX}`,
191 - ].join(";");
192 - return node;
193 -}
194 -
195 -function positionBox(node: HTMLElement, rect: PreviewAnnotationRect): void {
196 - node.style.display = "block";
197 - node.style.transform = `translate(${rect.x}px, ${rect.y}px)`;
198 - node.style.width = `${rect.width}px`;
199 - node.style.height = `${rect.height}px`;
200 -}
201 -
202 -function createLabel(): HTMLDivElement {
203 - const label = document.createElement("div");
204 - label.setAttribute(OVERLAY_ATTRIBUTE, "");
205 - label.className =
206 - "fixed z-1 max-w-70 overflow-hidden rounded-md bg-primary px-2 py-1 font-sans text-xs font-semibold text-primary-foreground shadow-md";
207 - label.style.cssText = [
208 - "position:fixed",
209 - "pointer-events:none",
210 - "white-space:nowrap",
211 - "text-overflow:ellipsis",
212 - `z-index:${CONTENT_LAYER_Z_INDEX}`,
213 - ].join(";");
214 - return label;
215 -}
216 -
217 -function updateSelectedVisual(target: SelectedElement): void {
218 - if (!target.element.isConnected) {
219 - target.outline.style.display = "none";
220 - target.label.style.display = "none";
221 - return;
222 - }
223 - const rect = target.element.getBoundingClientRect();
224 - positionBox(target.outline, rectFromDomRect(rect));
225 - target.label.textContent = describeRawElement(target.element);
226 - target.label.style.display = "block";
227 - target.label.style.transform = `translate(${Math.max(4, rect.left)}px, ${Math.max(4, rect.top - 22)}px)`;
228 -}
229 -
230 -function toStackFrame(frame: {
231 - functionName?: string;
232 - fileName?: string;
233 - lineNumber?: number;
234 - columnNumber?: number;
235 -}): PickedElementStackFrame {
236 - return {
237 - functionName: frame.functionName ?? null,
238 - fileName: frame.fileName ?? null,
239 - lineNumber: frame.lineNumber ?? null,
240 - columnNumber: frame.columnNumber ?? null,
241 - };
242 -}
243 -
244 -async function captureElement(element: Element): Promise<PickedElementPayload | null> {
245 - try {
246 - const context = await getElementContext(element);
247 - const stack = (context.stack ?? []).map(toStackFrame);
248 - return {
249 - pageUrl: location.href,
250 - pageTitle: document.title?.trim() || null,
251 - tagName: element.tagName.toLowerCase(),
252 - selector: context.selector,
253 - htmlPreview: context.htmlPreview ?? "",
254 - componentName: context.componentName,
255 - source: stack[0] ?? null,
256 - stack,
257 - styles: context.styles ?? "",
258 - pickedAt: new Date().toISOString(),
259 - };
260 - } catch {
261 - return null;
262 - }
263 -}
264 -
265 -function createButton(label: string, title: string): HTMLButtonElement {
266 - const button = document.createElement("button");
267 - button.type = "button";
268 - button.textContent = label;
269 - button.title = title;
270 - button.className =
271 - "inline-flex h-7 cursor-pointer items-center justify-center rounded-md border border-transparent px-2 font-sans text-xs font-medium text-foreground outline-none hover:bg-accent disabled:pointer-events-none disabled:opacity-60";
272 - return button;
273 -}
274 -
275 -function styleControl(input: HTMLInputElement | HTMLSelectElement): void {
276 - input.setAttribute("aria-label", input.getAttribute("aria-label") ?? "Style value");
277 - input.className =
278 - "h-7 min-w-0 w-full appearance-none rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground shadow-xs outline-none";
279 -}
280 -
281 -function createUnitControl(input: HTMLInputElement): HTMLElement {
282 - const wrapper = document.createElement("div");
283 - wrapper.style.cssText = "position:relative;min-width:0";
284 - const unit = document.createElement("span");
285 - unit.textContent = input.dataset.unit ?? "";
286 - unit.className =
287 - "pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 font-mono text-xs text-muted-foreground";
288 - wrapper.append(input, unit);
289 - return wrapper;
290 -}
291 -
292 -function createField(
293 - labelText: string,
294 - input: HTMLInputElement | HTMLSelectElement,
295 -): HTMLLabelElement {
296 - const label = document.createElement("label");
297 - label.className =
298 - "grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
299 - const text = document.createElement("span");
300 - text.textContent = labelText;
301 - styleControl(input);
302 - label.append(
303 - text,
304 - input instanceof HTMLInputElement && input.dataset.unit ? createUnitControl(input) : input,
305 - );
306 - return label;
307 -}
308 -
309 -function createStyleSection(): HTMLElement {
310 - const section = document.createElement("section");
311 - section.className = "grid gap-1 border-t border-border py-2";
312 - return section;
313 -}
314 -
315 -function createUnitInput(unit: string, placeholder = "0"): HTMLInputElement {
316 - const input = document.createElement("input");
317 - input.type = "number";
318 - input.placeholder = placeholder;
319 - input.style.paddingRight = "30px";
320 - input.dataset.unit = unit;
321 - return input;
322 -}
323 -
324 -function pathFromPoints(points: ReadonlyArray<PreviewAnnotationPoint>): string {
325 - if (points.length === 0) return "";
326 - if (points.length === 1) return `M ${points[0]!.x} ${points[0]!.y} l 0.01 0.01`;
327 - let path = `M ${points[0]!.x} ${points[0]!.y}`;
328 - for (let index = 1; index < points.length - 1; index += 1) {
329 - const current = points[index]!;
330 - const next = points[index + 1]!;
331 - path += ` Q ${current.x} ${current.y} ${(current.x + next.x) / 2} ${(current.y + next.y) / 2}`;
332 - }
333 - const last = points[points.length - 1]!;
334 - path += ` L ${last.x} ${last.y}`;
335 - return path;
336 -}
337 -
338 -function strokeBounds(
339 - points: ReadonlyArray<PreviewAnnotationPoint>,
340 - width: number,
341 -): PreviewAnnotationRect {
342 - const xs = points.map((point) => point.x);
343 - const ys = points.map((point) => point.y);
344 - const padding = width + 3;
345 - const left = Math.min(...xs) - padding;
346 - const top = Math.min(...ys) - padding;
347 - const right = Math.max(...xs) + padding;
348 - const bottom = Math.max(...ys) + padding;
349 - return { x: left, y: top, width: right - left, height: bottom - top };
350 -}
351 -
352 -function startAnnotation(): void {
353 - activeSession?.teardown(false);
354 - let finished = false;
355 - const host = document.createElement("div");
356 - host.setAttribute(OVERLAY_ATTRIBUTE, "");
357 - host.style.cssText = `position:fixed;inset:0;z-index:${Z_INDEX_OVERLAY};pointer-events:none`;
358 - applyAnnotationTheme(host, annotationTheme);
359 - const shadowRoot = host.attachShadow({ mode: "closed" });
360 - const themeStyle = document.createElement("style");
361 - themeStyle.textContent = previewAnnotationStyles;
362 - shadowRoot.appendChild(themeStyle);
363 -
364 - const root = document.createElement("div");
365 - root.setAttribute(OVERLAY_ATTRIBUTE, "");
366 - root.className = "fixed inset-0 font-sans text-foreground";
367 - root.style.cssText = "pointer-events:none";
368 - const cursorStyle = document.createElement("style");
369 - cursorStyle.setAttribute(OVERLAY_ATTRIBUTE, "");
370 - cursorStyle.textContent = `html[data-t3code-annotation-tool] body, html[data-t3code-annotation-tool] body * { cursor: crosshair !important; } [${OVERLAY_ATTRIBUTE}], [${OVERLAY_ATTRIBUTE}] * { cursor: default !important; } [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-inner-spin-button, [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-outer-spin-button { appearance:none; margin:0; }`;
371 - document.documentElement.appendChild(cursorStyle);
372 - shadowRoot.appendChild(root);
373 -
374 - const hoverOutline = createBox(PRIMARY, PRIMARY_FILL);
375 - const marqueeBox = createBox(PRIMARY, PRIMARY_FILL);
376 - root.append(hoverOutline, marqueeBox);
377 -
378 - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
379 - svg.setAttribute(OVERLAY_ATTRIBUTE, "");
380 - svg.setAttribute("width", "100%");
381 - svg.setAttribute("height", "100%");
382 - svg.setAttribute("viewBox", `0 0 ${window.innerWidth} ${window.innerHeight}`);
383 - svg.style.cssText = "position:fixed;inset:0;overflow:visible;pointer-events:none";
384 - svg.style.zIndex = String(CONTENT_LAYER_Z_INDEX);
385 - root.appendChild(svg);
386 -
387 - const toolbar = document.createElement("div");
388 - toolbar.setAttribute(OVERLAY_ATTRIBUTE, "");
389 - toolbar.className =
390 - "pointer-events-auto fixed top-2.5 left-1/2 flex -translate-x-1/2 gap-0.5 rounded-lg border border-border bg-popover/95 p-1 text-popover-foreground shadow-lg backdrop-blur-xl";
391 - toolbar.style.zIndex = String(CHROME_LAYER_Z_INDEX);
392 - root.appendChild(toolbar);
393 -
394 - const editor = document.createElement("div");
395 - editor.setAttribute(OVERLAY_ATTRIBUTE, "");
396 - editor.className =
397 - "pointer-events-auto fixed hidden max-h-[calc(100vh-16px)] w-[min(360px,calc(100vw-16px))] flex-col overflow-hidden rounded-xl border border-border bg-popover/96 text-popover-foreground shadow-2xl backdrop-blur-xl";
398 - editor.style.zIndex = String(CHROME_LAYER_Z_INDEX);
399 - root.appendChild(editor);
400 -
401 - const composerRow = document.createElement("div");
402 - composerRow.className = "flex items-start gap-2 p-2";
403 -
404 - const adjust = createButton("", "Expand annotation editor");
405 - adjust.setAttribute("aria-label", "Expand annotation editor");
406 - adjust.setAttribute("aria-expanded", "false");
407 - adjust.className +=
408 - " h-8 w-8 shrink-0 bg-muted p-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground";
409 - adjust.innerHTML =
410 - '<svg viewBox="0 0 20 20" width="15" height="15" aria-hidden="true"><path d="M4 5h12M4 10h12M4 15h12M7 3v4M13 8v4M9 13v4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>';
411 - composerRow.appendChild(adjust);
412 -
413 - const comment = document.createElement("textarea");
414 - comment.placeholder = "Describe the change…";
415 - comment.rows = 1;
416 - comment.className =
417 - "min-h-8 max-h-24 min-w-0 flex-1 resize-none overflow-y-hidden border-0 border-b border-b-transparent bg-transparent px-0 py-1.5 font-sans text-sm leading-5 text-foreground outline-none ring-0 placeholder:text-muted-foreground focus:border-b-primary focus:outline-none focus:ring-0";
418 - composerRow.appendChild(comment);
419 -
420 - const dragHandle = document.createElement("button");
421 - dragHandle.type = "button";
422 - dragHandle.textContent = "⠿";
423 - dragHandle.title = "Drag annotation editor";
424 - dragHandle.className =
425 - "hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
426 - composerRow.appendChild(dragHandle);
427 -
428 - const submit = createButton("Attach", "Attach annotation and screenshot");
429 - submit.className +=
430 - " h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
431 - composerRow.appendChild(submit);
432 - editor.appendChild(composerRow);
433 -
434 - const stylePanel = document.createElement("div");
435 - stylePanel.className =
436 - "hidden max-h-[min(176px,calc(100vh-180px))] overflow-auto border-t border-border bg-muted/40 px-3";
437 - editor.appendChild(stylePanel);
438 -
439 - const selected = new Map<Element, SelectedElement>();
440 - const regions: PreviewAnnotationRegionTarget[] = [];
441 - const strokes: PreviewAnnotationStrokeTarget[] = [];
442 - const styleChanges = new Map<string, PreviewAnnotationStyleChange>();
443 - const toolButtons = new Map<AnnotationTool, HTMLButtonElement>();
444 - let tool: AnnotationTool = "select";
445 - let dragStart: PreviewAnnotationPoint | null = null;
446 - let activeStroke: { target: PreviewAnnotationStrokeTarget; path: SVGPathElement } | null = null;
447 - let pendingCapture = false;
448 - let editorExpanded = false;
449 - let editorWasShown = false;
450 - let editorPosition: { left: number; top: number } | null = null;
451 - let editorDrag: { pointerId: number; offsetX: number; offsetY: number } | null = null;
452 - let editorLayoutFrame: number | null = null;
453 -
454 - const resizeComment = (): void => {
455 - const maxHeight = 96;
456 - comment.style.height = "auto";
457 - const nextHeight = Math.min(comment.scrollHeight, maxHeight);
458 - comment.style.height = `${nextHeight}px`;
459 - comment.style.overflowY = comment.scrollHeight > maxHeight ? "auto" : "hidden";
460 - queueEditorLayout();
461 - };
462 - comment.addEventListener("input", resizeComment);
463 -
464 - const updateStatus = (): void => {
465 - const hasTargets = selected.size > 0 || regions.length > 0 || strokes.length > 0;
466 - editor.style.display = hasTargets ? "flex" : "none";
467 - submit.disabled = !hasTargets;
468 - submit.style.opacity = hasTargets ? "1" : "0.45";
469 - adjust.disabled = !hasTargets;
470 - stylePanel.style.display = editorExpanded && selected.size > 0 ? "grid" : "none";
471 - queueEditorLayout();
472 - if (hasTargets && !editorWasShown) {
473 - editorWasShown = true;
474 - window.setTimeout(() => comment.focus({ preventScroll: true }), 0);
475 - }
476 - };
477 -
478 - const refreshToolButtons = (): void => {
479 - for (const [candidate, button] of toolButtons) {
480 - const active = candidate === tool;
481 - button.classList.toggle("bg-primary/10", active);
482 - button.classList.toggle("text-primary", active);
483 - button.classList.toggle("text-foreground", !active);
484 - }
485 - if (tool !== "select") hoverOutline.style.display = "none";
486 - if (tool !== "marquee") marqueeBox.style.display = "none";
487 - document.documentElement.setAttribute("data-t3code-annotation-tool", tool);
488 - };
489 -
490 - const removeSelected = (target: SelectedElement): void => {
491 - if (target.element instanceof HTMLElement || target.element instanceof SVGElement) {
492 - for (const [property, baseline] of target.baselineStyles) {
493 - if (baseline) target.element.style.setProperty(property, baseline);
494 - else target.element.style.removeProperty(property);
495 - }
496 - }
497 - selected.delete(target.element);
498 - target.outline.remove();
499 - target.label.remove();
500 - for (const [key, change] of styleChanges) {
501 - if (change.targetId === target.id) styleChanges.delete(key);
502 - }
503 - updateStatus();
504 - };
505 -
506 - const addSelected = (element: Element): void => {
507 - if (selected.has(element)) return;
508 - const target: SelectedElement = {
509 - id: nextId("element"),
510 - element,
511 - outline: createBox(PRIMARY, PRIMARY_FILL),
512 - label: createLabel(),
513 - baselineStyles: new Map(),
514 - };
515 - selected.set(element, target);
516 - root.append(target.outline, target.label);
517 - updateSelectedVisual(target);
518 - updateStatus();
519 - if (editorExpanded) {
520 - stylePanel.style.display = "grid";
521 - syncStyleControls();
522 - }
523 - };
524 -
525 - const toggleSelected = (element: Element, additive: boolean): void => {
526 - const existing = selected.get(element);
527 - if (existing) {
528 - removeSelected(existing);
529 - return;
530 - }
531 - if (!additive) {
532 - for (const target of Array.from(selected.values())) removeSelected(target);
533 - }
534 - addSelected(element);
535 - };
536 -
537 - const setStyleForSelected = (property: string, value: string): void => {
538 - for (const target of selected.values()) {
539 - if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement))
540 - continue;
541 - if (!target.baselineStyles.has(property)) {
542 - target.baselineStyles.set(property, target.element.style.getPropertyValue(property));
543 - }
544 - const key = `${target.id}:${property}`;
545 - const previousValue =
546 - styleChanges.get(key)?.previousValue ??
547 - getComputedStyle(target.element).getPropertyValue(property).trim();
548 - target.element.style.setProperty(property, value, "important");
549 - styleChanges.set(key, {
550 - targetId: target.id,
551 - selector: null,
552 - property,
553 - previousValue,
554 - value,
555 - });
556 - updateSelectedVisual(target);
557 - }
558 - };
559 -
560 - const textSection = createStyleSection();
561 - const colorsSection = createStyleSection();
562 - const bordersSection = createStyleSection();
563 - const sizingSection = createStyleSection();
564 - stylePanel.append(textSection, colorsSection, bordersSection, sizingSection);
565 -
566 - const fontFamily = document.createElement("select");
567 - for (const value of ["inherit", "system-ui", "sans-serif", "serif", "monospace"]) {
568 - const option = document.createElement("option");
569 - option.value = value;
570 - option.textContent = value;
571 - fontFamily.appendChild(option);
572 - }
573 - fontFamily.addEventListener("change", () => setStyleForSelected("font-family", fontFamily.value));
574 - textSection.appendChild(createField("Font", fontFamily));
575 -
576 - const fontSize = createUnitInput("px", "16");
577 - fontSize.min = "1";
578 - fontSize.max = "300";
579 - fontSize.addEventListener("input", () => {
580 - if (fontSize.value) setStyleForSelected("font-size", `${fontSize.value}px`);
581 - });
582 - textSection.appendChild(createField("Font size", fontSize));
583 -
584 - const fontWeight = document.createElement("select");
585 - for (const value of ["300", "400", "500", "600", "700", "800", "900"]) {
586 - const option = document.createElement("option");
587 - option.value = value;
588 - option.textContent = value;
589 - fontWeight.appendChild(option);
590 - }
591 - fontWeight.addEventListener("change", () => setStyleForSelected("font-weight", fontWeight.value));
592 - textSection.appendChild(createField("Font weight", fontWeight));
593 -
594 - const lineHeight = document.createElement("input");
595 - lineHeight.type = "text";
596 - lineHeight.placeholder = "normal / 1.4";
597 - lineHeight.addEventListener("change", () => {
598 - if (lineHeight.value.trim()) setStyleForSelected("line-height", lineHeight.value.trim());
599 - });
600 - textSection.appendChild(createField("Line height", lineHeight));
601 -
602 - const createColorRow = (
603 - labelText: string,
604 - property: string,
605 - section: HTMLElement,
606 - ): { row: HTMLLabelElement; color: HTMLInputElement; text: HTMLInputElement } => {
607 - const row = document.createElement("label");
608 - row.className =
609 - "grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
610 - const label = document.createElement("span");
611 - label.textContent = labelText;
612 - const control = document.createElement("div");
613 - control.className =
614 - "grid h-7 grid-cols-[22px_minmax(0,1fr)] items-center gap-1 rounded-md border border-input bg-background px-1 shadow-xs";
615 - const color = document.createElement("input");
616 - color.type = "color";
617 - color.setAttribute("aria-label", labelText);
618 - color.style.cssText =
619 - "width:20px;height:20px;padding:0;border:0;border-radius:5px;overflow:hidden;background:transparent;cursor:pointer";
620 - const text = document.createElement("input");
621 - text.type = "text";
622 - text.setAttribute("aria-label", `${labelText} value`);
623 - text.className =
624 - "min-w-0 w-full border-0 bg-transparent font-mono text-xs text-foreground outline-none";
625 - color.addEventListener("input", () => {
626 - text.value = color.value;
627 - setStyleForSelected(property, color.value);
628 - });
629 - text.addEventListener("change", () => {
630 - const value = text.value.trim();
631 - if (!value) return;
632 - setStyleForSelected(property, value);
633 - if (/^#[0-9a-f]{6}$/i.test(value)) color.value = value;
634 - });
635 - control.append(color, text);
636 - row.append(label, control);
637 - section.appendChild(row);
638 - return { row, color, text };
639 - };
640 -
641 - const textColor = createColorRow("Text color", "color", colorsSection);
642 - const backgroundColor = createColorRow("Background", "background-color", colorsSection);
643 -
644 - const opacity = document.createElement("input");
645 - opacity.type = "range";
646 - opacity.min = "0";
647 - opacity.max = "1";
648 - opacity.step = "0.05";
649 - opacity.value = "1";
650 - opacity.style.accentColor = PRIMARY;
651 - opacity.addEventListener("input", () => setStyleForSelected("opacity", opacity.value));
652 - colorsSection.appendChild(createField("Opacity", opacity));
653 -
654 - const radius = createUnitInput("px", "0");
655 - radius.min = "0";
656 - radius.max = "300";
657 - radius.addEventListener("input", () => {
658 - if (radius.value) setStyleForSelected("border-radius", `${radius.value}px`);
659 - });
660 - bordersSection.appendChild(createField("Radius", radius));
661 -
662 - const borderColor = createColorRow("Border color", "border-color", bordersSection);
663 -
664 - const borderWidth = createUnitInput("px", "0");
665 - borderWidth.min = "0";
666 - borderWidth.max = "100";
667 - borderWidth.addEventListener("input", () => {
668 - if (borderWidth.value) {
669 - setStyleForSelected("border-style", "solid");
670 - setStyleForSelected("border-width", `${borderWidth.value}px`);
671 - }
672 - });
673 - bordersSection.appendChild(createField("Border width", borderWidth));
674 -
675 - const dimensions = document.createElement("div");
676 - dimensions.style.cssText =
677 - "display:grid;grid-template-columns:82px minmax(0,1fr);gap:8px;align-items:center";
678 - const dimensionLabel = document.createElement("div");
679 - dimensionLabel.className = "grid gap-2 font-sans text-xs font-medium text-muted-foreground";
680 - dimensionLabel.innerHTML = "<span>Width</span><span>Height</span>";
681 - const dimensionControls = document.createElement("div");
682 - dimensionControls.style.cssText = "position:relative;display:grid;gap:3px;padding-left:22px";
683 - const widthInput = createUnitInput("px", "auto");
684 - const heightInput = createUnitInput("px", "auto");
685 - styleControl(widthInput);
686 - styleControl(heightInput);
687 - const aspectLock = createButton("", "Lock aspect ratio");
688 - aspectLock.setAttribute("aria-pressed", "true");
689 - aspectLock.style.cssText +=
690 - ";position:absolute;left:0;top:50%;transform:translateY(-50%);width:18px;height:38px;padding:0";
691 - aspectLock.className += " bg-primary/10 text-primary";
692 - dimensionControls.append(
693 - createUnitControl(widthInput),
694 - createUnitControl(heightInput),
695 - aspectLock,
696 - );
697 - dimensions.append(dimensionLabel, dimensionControls);
698 - sizingSection.appendChild(dimensions);
699 -
700 - let aspectLocked = true;
701 - let aspectRatio = 1;
702 - const refreshAspectButton = (): void => {
703 - aspectLock.innerHTML = aspectLocked
704 - ? '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="M8 6.5 9.5 5A3.5 3.5 0 0 1 14.5 10l-1.5 1.5M12 13.5 10.5 15A3.5 3.5 0 0 1 5.5 10L7 8.5M7.5 12.5l5-5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>'
705 - : '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="m6 6 8 8M8 6.5 9.5 5A3.5 3.5 0 0 1 14 9M12 13.5 10.5 15A3.5 3.5 0 0 1 6 11" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>';
706 - aspectLock.setAttribute("aria-pressed", String(aspectLocked));
707 - aspectLock.classList.toggle("bg-primary/10", aspectLocked);
708 - aspectLock.classList.toggle("text-primary", aspectLocked);
709 - aspectLock.classList.toggle("bg-muted", !aspectLocked);
710 - aspectLock.classList.toggle("text-muted-foreground", !aspectLocked);
711 - };
712 - aspectLock.addEventListener("click", () => {
713 - aspectLocked = !aspectLocked;
714 - refreshAspectButton();
715 - });
716 - widthInput.addEventListener("input", () => {
717 - const width = Number(widthInput.value);
718 - if (!Number.isFinite(width) || width <= 0) return;
719 - setStyleForSelected("width", `${width}px`);
720 - if (aspectLocked && aspectRatio > 0) {
721 - const height = Math.max(1, Math.round(width / aspectRatio));
722 - heightInput.value = String(height);
723 - setStyleForSelected("height", `${height}px`);
724 - }
725 - });
726 - heightInput.addEventListener("input", () => {
727 - const height = Number(heightInput.value);
728 - if (!Number.isFinite(height) || height <= 0) return;
729 - setStyleForSelected("height", `${height}px`);
730 - if (aspectLocked && aspectRatio > 0) {
731 - const width = Math.max(1, Math.round(height * aspectRatio));
732 - widthInput.value = String(width);
733 - setStyleForSelected("width", `${width}px`);
734 - }
735 - });
736 - refreshAspectButton();
737 -
738 - const addSpacingField = (
739 - label: string,
740 - property: string,
741 - placeholder: string,
742 - ): HTMLInputElement => {
743 - const input = document.createElement("input");
744 - input.type = "text";
745 - input.placeholder = placeholder;
746 - input.addEventListener("change", () => {
747 - if (input.value.trim()) setStyleForSelected(property, input.value.trim());
748 - });
749 - sizingSection.appendChild(createField(label, input));
750 - return input;
751 - };
752 - const padding = addSpacingField("Padding", "padding", "0 0 0 0");
753 - const margin = addSpacingField("Margin", "margin", "0 0 0 0");
754 - const gap = addSpacingField("Gap", "gap", "0px");
755 -
756 - const syncStyleControls = (): void => {
757 - const first = selected.values().next().value as SelectedElement | undefined;
758 - if (!first) return;
759 - const computed = getComputedStyle(first.element);
760 - const rect = first.element.getBoundingClientRect();
761 - aspectRatio = rect.height > 0 ? rect.width / rect.height : 1;
762 - widthInput.value = String(Math.round(rect.width));
763 - heightInput.value = String(Math.round(rect.height));
764 - fontSize.value = String(Math.round(Number.parseFloat(computed.fontSize) || 16));
765 - fontWeight.value = computed.fontWeight.match(/^[0-9]+$/) ? computed.fontWeight : "400";
766 - lineHeight.value = computed.lineHeight;
767 - fontFamily.value = Array.from(fontFamily.options).some(
768 - (option) => option.value === computed.fontFamily,
769 - )
770 - ? computed.fontFamily
771 - : "inherit";
772 - textColor.text.value = computed.color;
773 - backgroundColor.text.value = computed.backgroundColor;
774 - borderColor.text.value = computed.borderColor;
775 - opacity.value = computed.opacity;
776 - radius.value = String(Math.round(Number.parseFloat(computed.borderRadius) || 0));
777 - borderWidth.value = String(Math.round(Number.parseFloat(computed.borderWidth) || 0));
778 - padding.value = computed.padding;
779 - margin.value = computed.margin;
780 - gap.value = computed.gap === "normal" ? "0px" : computed.gap;
781 - };
782 -
783 - const tools: ReadonlyArray<[AnnotationTool, string, string]> = [
784 - ["select", "Select", "Select elements (V)"],
785 - ["marquee", "Region", "Draw a region or marquee-select elements (R)"],
786 - ["draw", "Draw", "Draw freehand (D)"],
787 - ["erase", "Erase", "Remove an annotation target (E)"],
788 - ];
789 - for (const [candidate, label, title] of tools) {
790 - const button = createButton(label, title);
791 - button.className += " h-8 px-2.5 text-sm";
792 - button.addEventListener("click", () => {
793 - tool = candidate;
794 - refreshToolButtons();
795 - });
796 - toolButtons.set(candidate, button);
797 - toolbar.appendChild(button);
798 - }
799 -
800 - const clampEditorPosition = (left: number, top: number): { left: number; top: number } => {
801 - const margin = 8;
802 - const rect = editor.getBoundingClientRect();
803 - return {
804 - left: Math.min(
805 - Math.max(margin, left),
806 - Math.max(margin, window.innerWidth - rect.width - margin),
807 - ),
808 - top: Math.min(
809 - Math.max(margin, top),
810 - Math.max(margin, window.innerHeight - rect.height - margin),
811 - ),
812 - };
813 - };
814 -
815 - const applyEditorPosition = (position: { left: number; top: number }): void => {
816 - const clamped = clampEditorPosition(position.left, position.top);
817 - editor.style.left = `${clamped.left}px`;
818 - editor.style.top = `${clamped.top}px`;
819 - editor.style.right = "auto";
820 - editor.style.bottom = "auto";
821 - if (editorExpanded) editorPosition = clamped;
822 - };
823 -
824 - const getAnnotationBounds = (): PreviewAnnotationRect | null =>
825 - unionRects(
826 - [
827 - ...Array.from(selected.values(), (target) =>
828 - rectFromDomRect(target.element.getBoundingClientRect()),
829 - ),
830 - ...regions.map((region) => region.rect),
831 - ...strokes.map((stroke) => stroke.bounds),
832 - ],
833 - 0,
834 - );
835 -
836 - const positionCompactEditor = (): void => {
837 - const bounds = getAnnotationBounds();
838 - if (!bounds) return;
839 - const editorRect = editor.getBoundingClientRect();
840 - const gap = 8;
841 - const candidates = [
842 - { left: bounds.x + bounds.width + gap, top: bounds.y },
843 - { left: bounds.x - editorRect.width - gap, top: bounds.y },
844 - {
845 - left: bounds.x + bounds.width - editorRect.width,
846 - top: bounds.y + bounds.height + gap,
847 - },
848 - {
849 - left: bounds.x + bounds.width - editorRect.width,
850 - top: bounds.y - editorRect.height - gap,
851 - },
852 - ];
853 - const overflow = (position: { left: number; top: number }): number =>
854 - Math.max(0, -position.left) +
855 - Math.max(0, -position.top) +
856 - Math.max(0, position.left + editorRect.width - window.innerWidth) +
857 - Math.max(0, position.top + editorRect.height - window.innerHeight);
858 - const best = candidates.reduce((current, candidate) =>
859 - overflow(candidate) < overflow(current) ? candidate : current,
860 - );
861 - applyEditorPosition(best);
862 - };
863 -
864 - function queueEditorLayout(): void {
865 - if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
866 - editorLayoutFrame = window.requestAnimationFrame(() => {
867 - editorLayoutFrame = null;
868 - if (editor.style.display === "none") return;
869 - if (editorExpanded && editorPosition) applyEditorPosition(editorPosition);
870 - else positionCompactEditor();
871 - });
872 - }
873 -
874 - adjust.addEventListener("click", () => {
875 - if (selected.size === 0) return;
876 - if (!editorExpanded) {
877 - const rect = editor.getBoundingClientRect();
878 - editorExpanded = true;
879 - editorPosition = { left: rect.left, top: rect.top };
880 - stylePanel.style.display = selected.size > 0 ? "grid" : "none";
881 - dragHandle.style.display = "block";
882 - adjust.setAttribute("aria-expanded", "true");
883 - adjust.title = "Collapse annotation editor";
884 - adjust.setAttribute("aria-label", "Collapse annotation editor");
885 - if (selected.size > 0) syncStyleControls();
886 - } else {
887 - editorExpanded = false;
888 - editorPosition = null;
889 - stylePanel.style.display = "none";
890 - dragHandle.style.display = "none";
891 - adjust.setAttribute("aria-expanded", "false");
892 - adjust.title = "Expand annotation editor";
893 - adjust.setAttribute("aria-label", "Expand annotation editor");
894 - }
895 - queueEditorLayout();
896 - });
897 -
898 - const onEditorPointerDown = (event: PointerEvent): void => {
899 - if (event.button !== 0 || !editorExpanded) return;
900 - const rect = editor.getBoundingClientRect();
901 - editorDrag = {
902 - pointerId: event.pointerId,
903 - offsetX: event.clientX - rect.left,
904 - offsetY: event.clientY - rect.top,
905 - };
906 - dragHandle.setPointerCapture(event.pointerId);
907 - dragHandle.style.cursor = "grabbing";
908 - event.preventDefault();
909 - event.stopPropagation();
910 - };
911 -
912 - const onEditorPointerMove = (event: PointerEvent): void => {
913 - if (!editorDrag || editorDrag.pointerId !== event.pointerId) return;
914 - applyEditorPosition({
915 - left: event.clientX - editorDrag.offsetX,
916 - top: event.clientY - editorDrag.offsetY,
917 - });
918 - event.preventDefault();
919 - event.stopPropagation();
920 - };
921 -
922 - const onEditorPointerUp = (event: PointerEvent): void => {
923 - if (!editorDrag || editorDrag.pointerId !== event.pointerId) return;
924 - editorDrag = null;
925 - dragHandle.style.cursor = "grab";
926 - if (dragHandle.hasPointerCapture(event.pointerId))
927 - dragHandle.releasePointerCapture(event.pointerId);
928 - event.preventDefault();
929 - event.stopPropagation();
930 - };
931 - dragHandle.addEventListener("pointerdown", onEditorPointerDown);
932 - dragHandle.addEventListener("pointermove", onEditorPointerMove);
933 - dragHandle.addEventListener("pointerup", onEditorPointerUp);
934 - dragHandle.addEventListener("pointercancel", onEditorPointerUp);
935 -
936 - const repaint = (): void => {
937 - for (const target of selected.values()) updateSelectedVisual(target);
938 - queueEditorLayout();
939 - };
940 -
941 - const removeTargetAtPoint = (x: number, y: number): boolean => {
942 - for (const target of Array.from(selected.values()).toReversed()) {
943 - const rect = target.element.getBoundingClientRect();
944 - if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
945 - removeSelected(target);
946 - return true;
947 - }
948 - }
949 - const regionIndex = regions.findIndex(
950 - (region) =>
951 - x >= region.rect.x &&
952 - x <= region.rect.x + region.rect.width &&
953 - y >= region.rect.y &&
954 - y <= region.rect.y + region.rect.height,
955 - );
956 - if (regionIndex >= 0) {
957 - const [removed] = regions.splice(regionIndex, 1);
958 - root.querySelector(`[data-region-id="${removed?.id}"]`)?.remove();
959 - updateStatus();
960 - return true;
961 - }
962 - const strokeIndex = strokes.findIndex(
963 - (stroke) =>
964 - x >= stroke.bounds.x &&
965 - x <= stroke.bounds.x + stroke.bounds.width &&
966 - y >= stroke.bounds.y &&
967 - y <= stroke.bounds.y + stroke.bounds.height,
968 - );
969 - if (strokeIndex >= 0) {
970 - const [removed] = strokes.splice(strokeIndex, 1);
971 - svg.querySelector(`[data-stroke-id="${removed?.id}"]`)?.remove();
972 - updateStatus();
973 - return true;
974 - }
975 - return false;
976 - };
977 -
978 - const selectElementsInRect = (rect: PreviewAnnotationRect): number => {
979 - const candidates = Array.from(document.querySelectorAll("body *"))
980 - .filter((element) => !isAnnotationNode(element))
981 - .map((element) => ({ element, rect: element.getBoundingClientRect() }))
982 - .filter(({ rect: candidate }) => {
983 - if (candidate.width < 2 || candidate.height < 2) return false;
984 - return !(
985 - candidate.right < rect.x ||
986 - candidate.left > rect.x + rect.width ||
987 - candidate.bottom < rect.y ||
988 - candidate.top > rect.y + rect.height
989 - );
990 - })
991 - .filter(({ element, rect: candidate }) => {
992 - const centerX = candidate.left + candidate.width / 2;
993 - const centerY = candidate.top + candidate.height / 2;
994 - return (
995 - centerX >= rect.x &&
996 - centerX <= rect.x + rect.width &&
997 - centerY >= rect.y &&
998 - centerY <= rect.y + rect.height &&
999 - (element.children.length === 0 ||
1000 - element instanceof HTMLButtonElement ||
1001 - element instanceof HTMLAnchorElement ||
1002 - element.getAttribute("role") === "button")
1003 - );
1004 - })
1005 - .sort(
1006 - (left, right) => left.rect.width * left.rect.height - right.rect.width * right.rect.height,
1007 - )
1008 - .slice(0, MAX_MARQUEE_ELEMENTS);
1009 - for (const candidate of candidates) addSelected(candidate.element);
1010 - return candidates.length;
1011 - };
1012 -
1013 - const clearHoverOutline = (): void => {
1014 - hoverOutline.style.display = "none";
1015 - };
1016 -
1017 - const onPointerMove = (event: PointerEvent): void => {
1018 - if (isAnnotationNode(event.target as Element)) {
1019 - clearHoverOutline();
1020 - return;
1021 - }
1022 - if (tool === "select" && dragStart === null) {
1023 - const target = pickFromPoint(event.clientX, event.clientY);
1024 - if (target) positionBox(hoverOutline, rectFromDomRect(target.getBoundingClientRect()));
1025 - else clearHoverOutline();
1026 - return;
1027 - }
1028 - clearHoverOutline();
1029 - if (tool === "marquee" && dragStart) {
1030 - positionBox(
1031 - marqueeBox,
1032 - normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY),
1033 - );
1034 - return;
1035 - }
1036 - if (tool === "draw" && activeStroke) {
1037 - activeStroke.target.points = [
1038 - ...activeStroke.target.points,
1039 - { x: event.clientX, y: event.clientY },
1040 - ];
1041 - activeStroke.target.bounds = strokeBounds(
1042 - activeStroke.target.points,
1043 - activeStroke.target.width,
1044 - );
1045 - activeStroke.path.setAttribute("d", pathFromPoints(activeStroke.target.points));
1046 - }
1047 - };
1048 -
1049 - const onPointerDown = (event: PointerEvent): void => {
1050 - if (event.button !== 0 || isAnnotationNode(event.target as Element)) return;
1051 - event.preventDefault();
1052 - event.stopPropagation();
1053 - if (tool === "select") {
1054 - const target = pickFromPoint(event.clientX, event.clientY);
1055 - if (target) toggleSelected(target, event.shiftKey);
1056 - return;
1057 - }
1058 - if (tool === "erase") {
1059 - removeTargetAtPoint(event.clientX, event.clientY);
1060 - return;
1061 - }
1062 - dragStart = { x: event.clientX, y: event.clientY };
1063 - if (tool === "draw") {
1064 - const stroke: PreviewAnnotationStrokeTarget = {
1065 - id: nextId("stroke"),
1066 - color: annotationTheme?.primary ?? "#2563eb",
1067 - width: 4,
1068 - points: [dragStart],
1069 - bounds: { x: dragStart.x, y: dragStart.y, width: 1, height: 1 },
1070 - };
1071 - const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
1072 - path.setAttribute(OVERLAY_ATTRIBUTE, "");
1073 - path.setAttribute("data-stroke-id", stroke.id);
1074 - path.setAttribute("fill", "none");
1075 - path.setAttribute("stroke", stroke.color);
1076 - path.setAttribute("stroke-width", String(stroke.width));
1077 - path.setAttribute("stroke-linecap", "round");
1078 - path.setAttribute("stroke-linejoin", "round");
1079 - svg.appendChild(path);
1080 - activeStroke = { target: stroke, path };
1081 - }
1082 - };
1083 -
1084 - const onPointerUp = (event: PointerEvent): void => {
1085 - if (!dragStart) return;
1086 - event.preventDefault();
1087 - event.stopPropagation();
1088 - if (tool === "marquee") {
1089 - const rect = normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY);
1090 - marqueeBox.style.display = "none";
1091 - if (isUsableRect(rect)) {
1092 - const found = selectElementsInRect(rect);
1093 - if (found === 0) {
1094 - const region: PreviewAnnotationRegionTarget = { id: nextId("region"), rect };
1095 - regions.push(region);
1096 - const regionBox = createBox(
1097 - PRIMARY,
1098 - "color-mix(in srgb, var(--t3-primary) 6%, transparent)",
1099 - );
1100 - regionBox.setAttribute("data-region-id", region.id);
1101 - positionBox(regionBox, rect);
1102 - root.appendChild(regionBox);
1103 - }
1104 - }
1105 - } else if (tool === "draw" && activeStroke) {
1106 - if (activeStroke.target.points.length > 1) strokes.push(activeStroke.target);
1107 - else activeStroke.path.remove();
1108 - activeStroke = null;
1109 - }
1110 - dragStart = null;
1111 - updateStatus();
1112 - };
1113 -
1114 - const onClick = (event: MouseEvent): void => {
1115 - if (isAnnotationNode(event.target as Element)) return;
1116 - event.preventDefault();
1117 - event.stopPropagation();
1118 - };
1119 -
1120 - const onPointerOut = (event: PointerEvent): void => {
1121 - if (event.relatedTarget === null) clearHoverOutline();
1122 - };
1123 -
1124 - const onWindowBlur = (): void => {
1125 - clearHoverOutline();
1126 - };
1127 -
1128 - const restoreStyles = (): void => {
1129 - for (const target of selected.values()) {
1130 - if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement))
1131 - continue;
1132 - for (const [property, baseline] of target.baselineStyles) {
1133 - if (baseline) target.element.style.setProperty(property, baseline);
1134 - else target.element.style.removeProperty(property);
1135 - }
1136 - }
1137 - };
1138 -
1139 - const teardown = (notifyMain: boolean): void => {
1140 - if (finished) return;
1141 - finished = true;
1142 - restoreStyles();
1143 - window.removeEventListener("pointermove", onPointerMove, true);
1144 - window.removeEventListener("pointerdown", onPointerDown, true);
1145 - window.removeEventListener("pointerup", onPointerUp, true);
1146 - window.removeEventListener("pointerout", onPointerOut, true);
1147 - window.removeEventListener("click", onClick, true);
1148 - window.removeEventListener("blur", onWindowBlur);
1149 - window.removeEventListener("keydown", onKeyDown, true);
1150 - window.removeEventListener("scroll", repaint, true);
1151 - window.removeEventListener("resize", repaint);
1152 - dragHandle.removeEventListener("pointerdown", onEditorPointerDown);
1153 - dragHandle.removeEventListener("pointermove", onEditorPointerMove);
1154 - dragHandle.removeEventListener("pointerup", onEditorPointerUp);
1155 - dragHandle.removeEventListener("pointercancel", onEditorPointerUp);
1156 - if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
1157 - ipcRenderer.off(CANCEL_PICK_CHANNEL, onCancel);
1158 - ipcRenderer.off(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
1159 - document.documentElement.removeAttribute("data-t3code-annotation-tool");
1160 - cursorStyle.remove();
1161 - host.remove();
1162 - activeSession = null;
1163 - if (notifyMain) ipcRenderer.send(ELEMENT_PICKED_CHANNEL, null);
1164 - };
1165 -
1166 - const onCancel = (): void => teardown(false);
1167 - const onCaptured = (): void => teardown(false);
1168 - const onKeyDown = (event: KeyboardEvent): void => {
1169 - if (isAnnotationNode(event.target as Element) && event.key !== "Escape") return;
1170 - if (event.key === "Escape") {
1171 - event.preventDefault();
1172 - event.stopPropagation();
1173 - teardown(true);
1174 - return;
1175 - }
1176 - if (event.key === "v") tool = "select";
1177 - else if (event.key === "r") tool = "marquee";
1178 - else if (event.key === "d") tool = "draw";
1179 - else if (event.key === "e") tool = "erase";
1180 - else return;
1181 - refreshToolButtons();
1182 - };
1183 -
1184 - submit.addEventListener("click", () => {
1185 - if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
1186 - return;
1187 - pendingCapture = true;
1188 - submit.disabled = true;
1189 - submit.textContent = "Capturing…";
1190 - void Promise.all(
1191 - Array.from(selected.values()).map(async (target) => {
1192 - const element = await captureElement(target.element);
1193 - if (!element) return null;
1194 - for (const change of styleChanges.values()) {
1195 - if (change.targetId === target.id) change.selector = element.selector;
1196 - }
1197 - return {
1198 - id: target.id,
1199 - element,
1200 - rect: rectFromDomRect(target.element.getBoundingClientRect()),
1201 - };
1202 - }),
1203 - ).then((captured) => {
1204 - const elements = captured.filter((target) => target !== null);
1205 - const annotation: PreviewAnnotationPayload = {
1206 - id: nextId("annotation"),
1207 - pageUrl: location.href,
1208 - pageTitle: document.title?.trim() || null,
1209 - comment: comment.value.trim(),
1210 - elements,
1211 - regions: [...regions],
1212 - strokes: [...strokes],
1213 - styleChanges: Array.from(styleChanges.values()),
1214 - screenshot: null,
1215 - createdAt: new Date().toISOString(),
1216 - };
1217 - editor.style.display = "none";
1218 - toolbar.style.display = "none";
1219 - hoverOutline.style.display = "none";
1220 - const screenshotRect = unionRects([
1221 - ...elements.map((target) => target.rect),
1222 - ...regions.map((region) => region.rect),
1223 - ...strokes.map((stroke) => stroke.bounds),
1224 - ]);
1225 - ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
1226 - });
1227 - });
1228 - comment.addEventListener("keydown", (event) => {
1229 - if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
1230 - event.preventDefault();
1231 - submit.click();
1232 - });
1233 -
1234 - window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
1235 - window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false });
1236 - window.addEventListener("pointerup", onPointerUp, { capture: true, passive: false });
1237 - window.addEventListener("pointerout", onPointerOut, { capture: true, passive: true });
1238 - window.addEventListener("click", onClick, { capture: true, passive: false });
1239 - window.addEventListener("blur", onWindowBlur);
1240 - window.addEventListener("keydown", onKeyDown, { capture: true });
1241 - window.addEventListener("scroll", repaint, { capture: true, passive: true });
1242 - window.addEventListener("resize", repaint, { passive: true });
1243 - ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel);
1244 - ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
1245 - document.documentElement.appendChild(host);
1246 - refreshToolButtons();
1247 - updateStatus();
1248 - activeSession = {
1249 - teardown,
1250 - applyTheme: (theme) => applyAnnotationTheme(host, theme),
1251 - };
1252 -}
1253 -
1254 -ipcRenderer.on(START_PICK_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme | undefined) => {
1255 - if (theme) annotationTheme = theme;
1256 - startAnnotation();
1257 -});
1258 -ipcRenderer.on(ANNOTATION_THEME_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme) => {
1259 - annotationTheme = theme;
1260 - activeSession?.applyTheme(theme);
1261 -});
1262 -ipcRenderer.on(CANCEL_PICK_CHANNEL, () => activeSession?.teardown(false));
1 +import "./preview/PickPreload.ts";
apps/desktop/src/preview/Annotation.css renamed
apps/desktop/src/preview/AnnotationStyles.generated.ts renamed
apps/desktop/src/preview/BrowserSession.ts new
+93
@@ -0,0 +1,93 @@
1 +import type { Session } from "electron";
2 +import { session } from "electron";
3 +import { createHash } from "node:crypto";
4 +import * as Context from "effect/Context";
5 +import * as Data from "effect/Data";
6 +import * as Effect from "effect/Effect";
7 +import * as Layer from "effect/Layer";
8 +
9 +const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
10 +
11 +export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
12 + readonly operation: string;
13 + readonly cause: unknown;
14 +}> {
15 + override get message() {
16 + return `Desktop preview browser session operation failed: ${this.operation}`;
17 + }
18 +}
19 +
20 +export interface BrowserSessionShape {
21 + readonly getPartition: (scope?: string) => string;
22 + readonly isPartition: (partition: string) => boolean;
23 + readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
24 + readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
25 + readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
26 +}
27 +
28 +export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
29 + "@t3tools/desktop/preview/BrowserSession",
30 +) {}
31 +
32 +const make = Effect.fn("BrowserSession.make")(() =>
33 + Effect.sync(() => {
34 + const sessions = new Map<string, Session>();
35 + const getPartition = (scope = "shared"): string => {
36 + const digest = createHash("sha256").update(scope).digest("hex").slice(0, 20);
37 + return `${PREVIEW_PARTITION_PREFIX}${digest}`;
38 + };
39 +
40 + const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
41 + const partition = getPartition(scope);
42 + const existing = sessions.get(partition);
43 + if (existing) return existing;
44 + return yield* Effect.try({
45 + try: () => {
46 + const browserSession = session.fromPartition(partition);
47 + const userAgent = browserSession
48 + .getUserAgent()
49 + .replace(/Electron\/[\d.]+ /, "")
50 + .replace(/\s*t3code\/[\d.]+/, "");
51 + browserSession.setUserAgent(userAgent);
52 + browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
53 + const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
54 + callback(allowed.includes(permission));
55 + });
56 + sessions.set(partition, browserSession);
57 + return browserSession;
58 + },
59 + catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
60 + });
61 + });
62 +
63 + return BrowserSession.of({
64 + getPartition,
65 + isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
66 + getSession,
67 + clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
68 + yield* Effect.tryPromise({
69 + try: () =>
70 + Promise.all(
71 + [...sessions.values()].map((browserSession) =>
72 + browserSession.clearStorageData({
73 + storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
74 + }),
75 + ),
76 + ),
77 + catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
78 + });
79 + }),
80 + clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
81 + yield* Effect.tryPromise({
82 + try: () =>
83 + Promise.all(
84 + [...sessions.values()].map((browserSession) => browserSession.clearCache()),
85 + ),
86 + catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
87 + });
88 + }),
89 + });
90 + }),
91 +);
92 +
93 +export const layer = Layer.effect(BrowserSession, make());
apps/desktop/src/preview/GuestProtocol.ts new
+6
@@ -0,0 +1,6 @@
1 +export const START_PICK_CHANNEL = "preview:start-pick";
2 +export const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
3 +export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
4 +export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
5 +export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
6 +export const HUMAN_INPUT_CHANNEL = "preview:human-input";
apps/desktop/src/preview/Manager.test.ts renamed
+6 -6
@@ -40,7 +40,7 @@ describe("PreviewViewManager automation status", () => {
40 });
41
42 it("reports an unregistered webview as temporarily unavailable", async () => {
43 - const { PreviewViewManager } = await import("./preview-view-manager.ts");
43 + const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
44 const manager = new PreviewViewManager();
45
46 expect(manager.automationStatus("tab_1")).toEqual({
@@ -95,7 +95,7 @@ describe("PreviewViewManager automation status", () => {
95 },
96 capturePage,
97 } as never);
98 - const { PreviewViewManager } = await import("./preview-view-manager.ts");
98 + const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
99 const manager = new PreviewViewManager();
100 manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
101 manager.createTab("tab_1");
@@ -127,7 +127,7 @@ describe("PreviewViewManager automation status", () => {
127 });
128
129 it("reveals only files inside the configured browser artifact directory", async () => {
130 - const { PreviewViewManager } = await import("./preview-view-manager.ts");
130 + const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
131 const manager = new PreviewViewManager();
132 manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
133
@@ -142,7 +142,7 @@ describe("PreviewViewManager automation status", () => {
142 });
143
144 it("copies screenshot artifacts to the system clipboard", async () => {
145 - const { PreviewViewManager } = await import("./preview-view-manager.ts");
145 + const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
146 const manager = new PreviewViewManager();
147 manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
148 const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
@@ -202,7 +202,7 @@ describe("PreviewViewManager automation status", () => {
202 off: vi.fn(),
203 },
204 } as never);
205 - const { PreviewViewManager } = await import("./preview-view-manager.ts");
205 + const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
206 const manager = new PreviewViewManager();
207 manager.onPointerEvent((event) => activity.push(event.phase));
208 manager.createTab("tab_1");
@@ -271,7 +271,7 @@ describe("PreviewViewManager automation status", () => {
271 off: vi.fn(),
272 },
273 } as never);
274 - const { PreviewViewManager } = await import("./preview-view-manager.ts");
274 + const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
275 const manager = new PreviewViewManager();
276 manager.createTab("tab_1");
277 manager.registerWebview("tab_1", 42);
apps/desktop/src/preview/Manager.ts renamed
+299 -91
@@ -33,31 +33,30 @@ import {
33 type Session,
34 clipboard,
35 nativeImage,
36 - session,
36 shell,
37 webContents,
38 } from "electron";
39 import { mkdir, writeFile } from "node:fs/promises";
40 import { isAbsolute, join, relative, resolve, sep } from "node:path";
42 -import { createHash } from "node:crypto";
41 import { setTimeout as sleep } from "node:timers/promises";
44 -
45 -import { isPreviewAnnotationPayload } from "./picked-element-payload.ts";
46 -import { playwrightInjectedRuntimeInstallExpression } from "./playwright-injected-runtime.ts";
47 -
48 -const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
49 -const START_PICK_CHANNEL = "preview:start-pick";
50 -const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
51 -const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
52 -const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
53 -const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
54 -const HUMAN_INPUT_CHANNEL = "preview:human-input";
55 -
56 -// Re-export the guest webview security posture from its dedicated module so
57 -// the constant is unit-testable in isolation. See
58 -// `preview-webview-preferences.ts` for the full security rationale.
59 -export { PREVIEW_WEBVIEW_PREFERENCES } from "./preview-webview-preferences.ts";
60 -import { PREVIEW_WEBVIEW_PREFERENCES } from "./preview-webview-preferences.ts";
42 +import * as Context from "effect/Context";
43 +import * as Data from "effect/Data";
44 +import * as Effect from "effect/Effect";
45 +import * as Layer from "effect/Layer";
46 +import type * as Scope from "effect/Scope";
47 +
48 +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
49 +import * as BrowserSession from "./BrowserSession.ts";
50 +import {
51 + ANNOTATION_CAPTURED_CHANNEL,
52 + ANNOTATION_THEME_CHANNEL,
53 + CANCEL_PICK_CHANNEL,
54 + ELEMENT_PICKED_CHANNEL,
55 + HUMAN_INPUT_CHANNEL,
56 + START_PICK_CHANNEL,
57 +} from "./GuestProtocol.ts";
58 +import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
59 +import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
60
61 export type PreviewNavStatus =
62 | { kind: "Idle" }
@@ -238,6 +237,7 @@ interface ManagedListeners {
237 navigate: () => void;
238 failed: (event: Event, code: number, description: string) => void;
239 humanInput: (_event: unknown, signal?: unknown) => void;
240 + beforeInput: (event: Electron.Event, input: Electron.Input) => void;
241 }
242
243 interface PickSession {
@@ -249,6 +249,11 @@ interface BrowserControlSession {
249 readonly webContentsId: number;
250 tail: Promise<void>;
251 initialized: Promise<void>;
252 + readonly onMessage: (
253 + event: Electron.Event,
254 + method: string,
255 + params: Record<string, unknown>,
256 + ) => void;
257 }
258
259 interface BrowserDiagnostics {
@@ -318,13 +323,12 @@ const inputSignalsMatch = (left: PreviewInputSignal, right: PreviewInputSignal):
323 );
324 };
325
321 -export class PreviewViewManager {
326 +class PreviewViewManager {
327 private annotationTheme = DEFAULT_ANNOTATION_THEME;
328 private artifactDirectory: string | null = null;
329 private mainWindow: BrowserWindow | null = null;
330 private readonly tabs = new Map<string, PreviewTabState>();
331 private readonly attached = new Map<number, ManagedListeners>();
327 - private readonly browserSessions = new Map<string, Session>();
332 private readonly listeners = new Set<Listener>();
333 private readonly pointerEventListeners = new Set<PointerEventListener>();
334 private readonly recordingFrameListeners = new Set<RecordingFrameListener>();
@@ -394,43 +398,6 @@ export class PreviewViewManager {
398 this.mainWindow = window;
399 }
400
397 - getBrowserPartition(scope = "shared"): string {
398 - const digest = createHash("sha256").update(scope).digest("hex").slice(0, 20);
399 - return `${PREVIEW_PARTITION_PREFIX}${digest}`;
400 - }
401 -
402 - isBrowserPartition(partition: string): boolean {
403 - return partition.startsWith(PREVIEW_PARTITION_PREFIX);
404 - }
405 -
406 - /**
407 - * Returns the canonical `<webview webpreferences="...">` string. Renderer
408 - * fetches this via the desktop bridge so the security posture for guest
409 - * surfaces lives in exactly one place (here) and any future guest webview
410 - * (docs panel, OAuth popup, etc.) can opt in by calling the same getter.
411 - */
412 - getWebviewPreferences(): string {
413 - return PREVIEW_WEBVIEW_PREFERENCES;
414 - }
415 -
416 - getBrowserSession(scope = "shared"): Session {
417 - const partition = this.getBrowserPartition(scope);
418 - const existing = this.browserSessions.get(partition);
419 - if (existing) return existing;
420 - const sess = session.fromPartition(partition);
421 - const ua = sess
422 - .getUserAgent()
423 - .replace(/Electron\/[\d.]+ /, "")
424 - .replace(/\s*t3code\/[\d.]+/, "");
425 - sess.setUserAgent(ua);
426 - sess.setPermissionRequestHandler((_wc, perm, callback) => {
427 - const allow = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
428 - callback(allow.includes(perm));
429 - });
430 - this.browserSessions.set(partition, sess);
431 - return sess;
432 - }
433 -
401 createTab(tabId: string): PreviewTabState {
402 const existing = this.tabs.get(tabId);
403 if (existing) return existing;
@@ -574,25 +541,6 @@ export class PreviewViewManager {
541 wc.openDevTools({ mode: "detach" });
542 }
543
577 - /**
578 - * Drop cookies/localStorage/etc. for the preview partition. Affects every
579 - * preview tab since they all share `persist:t3code-preview`.
580 - */
581 - async clearCookies(): Promise<void> {
582 - await Promise.all(
583 - [...this.browserSessions.values()].map((sess) =>
584 - sess.clearStorageData({
585 - storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
586 - }),
587 - ),
588 - );
589 - }
590 -
591 - /** Drop the HTTP cache for the preview partition. */
592 - async clearCache(): Promise<void> {
593 - await Promise.all([...this.browserSessions.values()].map((sess) => sess.clearCache()));
594 - }
595 -
544 /**
545 * Activate annotation mode for `tabId`. Resolves after the guest submits a
546 * multi-target annotation and the desktop process captures its screenshot,
@@ -1289,20 +1237,15 @@ export class PreviewViewManager {
1237 "Preview control cannot attach because another debugger owns this page.",
1238 );
1239 }
1292 - const control: BrowserControlSession = {
1293 - webContentsId: wc.id,
1294 - tail: Promise.resolve(),
1295 - initialized: Promise.resolve(),
1296 - };
1240 const diagnostics: BrowserDiagnostics = {
1241 consoleEntries: [],
1242 networkEntries: [],
1243 requests: new Map(),
1244 };
1245 this.diagnostics.set(wc.id, diagnostics);
1303 - wc.debugger.on("message", (_event, method, params) => {
1246 + const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
1247 if (method === "Page.screencastFrame") {
1305 - const frame = params as Record<string, unknown>;
1248 + const frame = params;
1249 const sessionId = frame["sessionId"];
1250 if (typeof sessionId === "number") {
1251 void wc.debugger
@@ -1325,8 +1268,15 @@ export class PreviewViewManager {
1268 for (const listener of this.recordingFrameListeners) listener(payload);
1269 }
1270 }
1328 - this.captureDiagnosticMessage(diagnostics, method, params as Record<string, unknown>);
1329 - });
1271 + this.captureDiagnosticMessage(diagnostics, method, params);
1272 + };
1273 + const control: BrowserControlSession = {
1274 + webContentsId: wc.id,
1275 + tail: Promise.resolve(),
1276 + initialized: Promise.resolve(),
1277 + onMessage,
1278 + };
1279 + wc.debugger.on("message", onMessage);
1280 control.initialized = (async () => {
1281 wc.debugger.attach("1.3");
1282 await Promise.all([
@@ -1347,10 +1297,15 @@ export class PreviewViewManager {
1297 }
1298
1299 private detachControlSession(webContentsId: number): void {
1300 + const control = this.controlSessions.get(webContentsId);
1301 this.controlSessions.delete(webContentsId);
1302 this.diagnostics.delete(webContentsId);
1303 const wc = webContents.fromId(webContentsId);
1353 - if (!wc || wc.isDestroyed() || !wc.debugger.isAttached()) return;
1304 + if (!wc || wc.isDestroyed()) return;
1305 + if (control) {
1306 + wc.debugger.off("message", control.onMessage);
1307 + }
1308 + if (!wc.debugger.isAttached()) return;
1309 try {
1310 wc.debugger.detach();
1311 } catch {
@@ -1617,7 +1572,7 @@ export class PreviewViewManager {
1572
1573 // Forward app-level shortcuts to the main window so mod+shift+J etc.
1574 // still toggles the preview panel even when the webview has focus.
1620 - wc.on("before-input-event", (event, input) => {
1575 + const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
1576 if (this.isAppShortcut(input) && this.mainWindow && !this.mainWindow.isDestroyed()) {
1577 event.preventDefault();
1578 this.mainWindow.webContents.sendInputEvent({
@@ -1631,9 +1586,10 @@ export class PreviewViewManager {
1586 ],
1587 });
1588 }
1634 - });
1589 + };
1590 + wc.on("before-input-event", beforeInput);
1591
1636 - this.attached.set(wc.id, { navigate: sync, failed, humanInput });
1592 + this.attached.set(wc.id, { navigate: sync, failed, humanInput, beforeInput });
1593 }
1594
1595 private detachListeners(webContentsId: number): void {
@@ -1648,6 +1604,7 @@ export class PreviewViewManager {
1604 wc.off("did-start-loading", handlers.navigate);
1605 wc.off("did-stop-loading", handlers.navigate);
1606 wc.off("did-fail-load", handlers.failed as never);
1607 + wc.off("before-input-event", handlers.beforeInput);
1608 wc.ipc.off(HUMAN_INPUT_CHANNEL, handlers.humanInput);
1609 }
1610
@@ -1738,4 +1695,255 @@ export class PreviewWebviewNotInitializedError extends Error {
1695 }
1696 }
1697
1741 -export const previewViewManager = new PreviewViewManager();
1698 +export class PreviewManagerError extends Data.TaggedError("PreviewManagerError")<{
1699 + readonly operation: string;
1700 + readonly cause: unknown;
1701 +}> {
1702 + override get message() {
1703 + return `Desktop preview operation failed: ${this.operation}`;
1704 + }
1705 +}
1706 +
1707 +export interface PreviewManagerShape {
1708 + readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
1709 + readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
1710 + readonly isBrowserPartition: (partition: string) => boolean;
1711 + readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
1712 + readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1713 + readonly registerWebview: (
1714 + tabId: string,
1715 + webContentsId: number,
1716 + ) => Effect.Effect<void, PreviewManagerError>;
1717 + readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
1718 + readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1719 + readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1720 + readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1721 + readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1722 + readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1723 + readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1724 + readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1725 + readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1726 + readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
1727 + readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
1728 + readonly getBrowserPartition: (scope?: string) => string;
1729 + readonly setAnnotationTheme: (
1730 + theme: DesktopPreviewAnnotationTheme,
1731 + ) => Effect.Effect<void, PreviewManagerError>;
1732 + readonly pickElement: (
1733 + tabId: string,
1734 + ) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
1735 + readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1736 + readonly captureScreenshot: (
1737 + tabId: string,
1738 + ) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
1739 + readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
1740 + readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
1741 + readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1742 + readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
1743 + readonly saveRecording: (
1744 + tabId: string,
1745 + mimeType: string,
1746 + data: Uint8Array,
1747 + ) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
1748 + readonly automationStatus: (
1749 + tabId: string,
1750 + ) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
1751 + readonly automationSnapshot: (
1752 + tabId: string,
1753 + ) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
1754 + readonly automationClick: (
1755 + tabId: string,
1756 + input: PreviewAutomationClickInput,
1757 + ) => Effect.Effect<void, PreviewManagerError>;
1758 + readonly automationType: (
1759 + tabId: string,
1760 + input: PreviewAutomationTypeInput,
1761 + ) => Effect.Effect<void, PreviewManagerError>;
1762 + readonly automationPress: (
1763 + tabId: string,
1764 + input: PreviewAutomationPressInput,
1765 + ) => Effect.Effect<void, PreviewManagerError>;
1766 + readonly automationScroll: (
1767 + tabId: string,
1768 + input: PreviewAutomationScrollInput,
1769 + ) => Effect.Effect<void, PreviewManagerError>;
1770 + readonly automationEvaluate: (
1771 + tabId: string,
1772 + input: PreviewAutomationEvaluateInput,
1773 + ) => Effect.Effect<unknown, PreviewManagerError>;
1774 + readonly automationWaitFor: (
1775 + tabId: string,
1776 + input: PreviewAutomationWaitForInput,
1777 + ) => Effect.Effect<void, PreviewManagerError>;
1778 + readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
1779 + readonly subscribePointerEvents: (
1780 + listener: PointerEventListener,
1781 + ) => Effect.Effect<void, never, Scope.Scope>;
1782 + readonly subscribeRecordingFrames: (
1783 + listener: RecordingFrameListener,
1784 + ) => Effect.Effect<void, never, Scope.Scope>;
1785 +}
1786 +
1787 +export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
1788 + "@t3tools/desktop/preview/Manager/PreviewManager",
1789 +) {}
1790 +
1791 +const make = Effect.fn("PreviewManager.make")(function* () {
1792 + const environment = yield* DesktopEnvironment.DesktopEnvironment;
1793 + const browserSession = yield* BrowserSession.BrowserSession;
1794 + const manager = new PreviewViewManager();
1795 + manager.configureArtifactDirectory(environment.browserArtifactsDir);
1796 + yield* Effect.addFinalizer(() => Effect.sync(() => manager.destroy()));
1797 +
1798 + const attempt = <A>(
1799 + operation: string,
1800 + evaluate: () => A,
1801 + ): Effect.Effect<A, PreviewManagerError> =>
1802 + Effect.try({
1803 + try: evaluate,
1804 + catch: (cause) => new PreviewManagerError({ operation, cause }),
1805 + });
1806 + const attemptPromise = <A>(
1807 + operation: string,
1808 + evaluate: () => Promise<A>,
1809 + ): Effect.Effect<A, PreviewManagerError> =>
1810 + Effect.tryPromise({
1811 + try: evaluate,
1812 + catch: (cause) => new PreviewManagerError({ operation, cause }),
1813 + });
1814 + const browserSessionEffect = <A>(
1815 + operation: string,
1816 + effect: Effect.Effect<A, BrowserSession.BrowserSessionError>,
1817 + ): Effect.Effect<A, PreviewManagerError> =>
1818 + effect.pipe(Effect.mapError((cause) => new PreviewManagerError({ operation, cause })));
1819 +
1820 + return PreviewManager.of({
1821 + setMainWindow: Effect.fn("PreviewManager.setMainWindow")(function* (window) {
1822 + yield* attempt("setMainWindow", () => manager.setMainWindow(window));
1823 + }),
1824 + getBrowserSession: Effect.fn("PreviewManager.getBrowserSession")(function* (scope) {
1825 + return yield* browserSessionEffect("getBrowserSession", browserSession.getSession(scope));
1826 + }),
1827 + isBrowserPartition: browserSession.isPartition,
1828 + createTab: Effect.fn("PreviewManager.createTab")(function* (tabId) {
1829 + return yield* attempt("createTab", () => manager.createTab(tabId));
1830 + }),
1831 + closeTab: Effect.fn("PreviewManager.closeTab")(function* (tabId) {
1832 + yield* attempt("closeTab", () => manager.closeTab(tabId));
1833 + }),
1834 + registerWebview: Effect.fn("PreviewManager.registerWebview")(function* (tabId, webContentsId) {
1835 + yield* attempt("registerWebview", () => manager.registerWebview(tabId, webContentsId));
1836 + }),
1837 + navigate: Effect.fn("PreviewManager.navigate")(function* (tabId, url) {
1838 + yield* attemptPromise("navigate", () => manager.navigate(tabId, url));
1839 + }),
1840 + goBack: Effect.fn("PreviewManager.goBack")(function* (tabId) {
1841 + yield* attempt("goBack", () => manager.goBack(tabId));
1842 + }),
1843 + goForward: Effect.fn("PreviewManager.goForward")(function* (tabId) {
1844 + yield* attempt("goForward", () => manager.goForward(tabId));
1845 + }),
1846 + refresh: Effect.fn("PreviewManager.refresh")(function* (tabId) {
1847 + yield* attempt("refresh", () => manager.refresh(tabId));
1848 + }),
1849 + zoomIn: Effect.fn("PreviewManager.zoomIn")(function* (tabId) {
1850 + yield* attempt("zoomIn", () => manager.zoomIn(tabId));
1851 + }),
1852 + zoomOut: Effect.fn("PreviewManager.zoomOut")(function* (tabId) {
1853 + yield* attempt("zoomOut", () => manager.zoomOut(tabId));
1854 + }),
1855 + resetZoom: Effect.fn("PreviewManager.resetZoom")(function* (tabId) {
1856 + yield* attempt("resetZoom", () => manager.resetZoom(tabId));
1857 + }),
1858 + hardReload: Effect.fn("PreviewManager.hardReload")(function* (tabId) {
1859 + yield* attempt("hardReload", () => manager.hardReload(tabId));
1860 + }),
1861 + openDevTools: Effect.fn("PreviewManager.openDevTools")(function* (tabId) {
1862 + yield* attempt("openDevTools", () => manager.openDevTools(tabId));
1863 + }),
1864 + clearCookies: Effect.fn("PreviewManager.clearCookies")(function* () {
1865 + yield* browserSessionEffect("clearCookies", browserSession.clearCookies());
1866 + }),
1867 + clearCache: Effect.fn("PreviewManager.clearCache")(function* () {
1868 + yield* browserSessionEffect("clearCache", browserSession.clearCache());
1869 + }),
1870 + getBrowserPartition: browserSession.getPartition,
1871 + setAnnotationTheme: Effect.fn("PreviewManager.setAnnotationTheme")(function* (theme) {
1872 + yield* attempt("setAnnotationTheme", () => manager.setAnnotationTheme(theme));
1873 + }),
1874 + pickElement: Effect.fn("PreviewManager.pickElement")(function* (tabId) {
1875 + return yield* attemptPromise("pickElement", () => manager.pickElement(tabId));
1876 + }),
1877 + cancelPickElement: Effect.fn("PreviewManager.cancelPickElement")(function* (tabId) {
1878 + yield* attempt("cancelPickElement", () => manager.cancelPickElement(tabId));
1879 + }),
1880 + captureScreenshot: Effect.fn("PreviewManager.captureScreenshot")(function* (tabId) {
1881 + return yield* attemptPromise("captureScreenshot", () => manager.captureScreenshot(tabId));
1882 + }),
1883 + revealArtifact: Effect.fn("PreviewManager.revealArtifact")(function* (path) {
1884 + yield* attempt("revealArtifact", () => manager.revealArtifact(path));
1885 + }),
1886 + copyArtifactToClipboard: Effect.fn("PreviewManager.copyArtifactToClipboard")(function* (path) {
1887 + yield* attempt("copyArtifactToClipboard", () => manager.copyArtifactToClipboard(path));
1888 + }),
1889 + startRecording: Effect.fn("PreviewManager.startRecording")(function* (tabId) {
1890 + yield* attemptPromise("startRecording", () => manager.startRecording(tabId));
1891 + }),
1892 + stopRecording: Effect.fn("PreviewManager.stopRecording")(function* (tabId) {
1893 + yield* attemptPromise("stopRecording", () => manager.stopRecording(tabId));
1894 + }),
1895 + saveRecording: Effect.fn("PreviewManager.saveRecording")(function* (tabId, mimeType, data) {
1896 + return yield* attemptPromise("saveRecording", () =>
1897 + manager.saveRecording(tabId, mimeType, data),
1898 + );
1899 + }),
1900 + automationStatus: Effect.fn("PreviewManager.automationStatus")(function* (tabId) {
1901 + return yield* attempt("automationStatus", () => manager.automationStatus(tabId));
1902 + }),
1903 + automationSnapshot: Effect.fn("PreviewManager.automationSnapshot")(function* (tabId) {
1904 + return yield* attemptPromise("automationSnapshot", () => manager.automationSnapshot(tabId));
1905 + }),
1906 + automationClick: Effect.fn("PreviewManager.automationClick")(function* (tabId, input) {
1907 + yield* attemptPromise("automationClick", () => manager.automationClick(tabId, input));
1908 + }),
1909 + automationType: Effect.fn("PreviewManager.automationType")(function* (tabId, input) {
1910 + yield* attemptPromise("automationType", () => manager.automationType(tabId, input));
1911 + }),
1912 + automationPress: Effect.fn("PreviewManager.automationPress")(function* (tabId, input) {
1913 + yield* attemptPromise("automationPress", () => manager.automationPress(tabId, input));
1914 + }),
1915 + automationScroll: Effect.fn("PreviewManager.automationScroll")(function* (tabId, input) {
1916 + yield* attemptPromise("automationScroll", () => manager.automationScroll(tabId, input));
1917 + }),
1918 + automationEvaluate: Effect.fn("PreviewManager.automationEvaluate")(function* (tabId, input) {
1919 + return yield* attemptPromise("automationEvaluate", () =>
1920 + manager.automationEvaluate(tabId, input),
1921 + );
1922 + }),
1923 + automationWaitFor: Effect.fn("PreviewManager.automationWaitFor")(function* (tabId, input) {
1924 + yield* attemptPromise("automationWaitFor", () => manager.automationWaitFor(tabId, input));
1925 + }),
1926 + subscribeStateChanges: (listener) =>
1927 + Effect.acquireRelease(
1928 + Effect.sync(() => manager.onStateChange(listener)),
1929 + (unsubscribe) => Effect.sync(unsubscribe),
1930 + ).pipe(Effect.asVoid),
1931 + subscribePointerEvents: (listener) =>
1932 + Effect.acquireRelease(
1933 + Effect.sync(() => manager.onPointerEvent(listener)),
1934 + (unsubscribe) => Effect.sync(unsubscribe),
1935 + ).pipe(Effect.asVoid),
1936 + subscribeRecordingFrames: (listener) =>
1937 + Effect.acquireRelease(
1938 + Effect.sync(() => manager.onRecordingFrame(listener)),
1939 + (unsubscribe) => Effect.sync(unsubscribe),
1940 + ).pipe(Effect.asVoid),
1941 + });
1942 +});
1943 +
1944 +export const layer = Layer.effect(PreviewManager, make());
1945 +
1946 +/** Exposed for tests. */
1947 +export const __testing = {
1948 + PreviewViewManager,
1949 +};
apps/desktop/src/preview/PickLabelPosition.ts renamed
+1 -1
@@ -2,7 +2,7 @@
2 * Pure clamp/flip math for the floating label that follows the cursor while
3 * the user is picking an element in the in-app browser. Lives in its own
4 * electron-free module so the geometry can be unit-tested without spinning
5 - * up an Electron preload context (`preview-pick-preload.ts` itself imports
5 + * up an Electron preload context (`PickPreload.ts` itself imports
6 * `electron` and `react-grab/primitives`, which can't load under vitest).
7 *
8 * - Horizontally pins the label to `targetLeft`, clamped into
apps/desktop/src/preview/PickPreload.test.ts renamed
+1 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { computeLabelPosition } from "./preview-pick-label-position.ts";
3 +import { computeLabelPosition } from "./PickLabelPosition.ts";
4
5 const VIEWPORT = { viewportWidth: 1280, viewportHeight: 800 };
6
apps/desktop/src/preview/PickPreload.ts new
+1263
@@ -0,0 +1,1263 @@
1 +// @effect-diagnostics globalDate:off
2 +import { ipcRenderer } from "electron";
3 +import { getElementContext } from "react-grab/primitives";
4 +import type {
5 + DesktopPreviewAnnotationTheme,
6 + PickedElementPayload,
7 + PickedElementStackFrame,
8 + PreviewAnnotationPayload,
9 + PreviewAnnotationPoint,
10 + PreviewAnnotationRect,
11 + PreviewAnnotationRegionTarget,
12 + PreviewAnnotationStrokeTarget,
13 + PreviewAnnotationStyleChange,
14 +} from "@t3tools/contracts";
15 +
16 +import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
17 +import {
18 + ANNOTATION_CAPTURED_CHANNEL,
19 + ANNOTATION_THEME_CHANNEL,
20 + CANCEL_PICK_CHANNEL,
21 + ELEMENT_PICKED_CHANNEL,
22 + HUMAN_INPUT_CHANNEL,
23 + START_PICK_CHANNEL,
24 +} from "./GuestProtocol.ts";
25 +const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui";
26 +const Z_INDEX_OVERLAY = 2147483646;
27 +const PRIMARY = "var(--t3-primary)";
28 +const PRIMARY_FILL = "color-mix(in srgb, var(--t3-primary) 10%, transparent)";
29 +const MAX_MARQUEE_ELEMENTS = 20;
30 +const CONTENT_LAYER_Z_INDEX = 1;
31 +const CHROME_LAYER_Z_INDEX = 10;
32 +
33 +type AnnotationTool = "select" | "marquee" | "draw" | "erase";
34 +
35 +interface SelectedElement {
36 + id: string;
37 + element: Element;
38 + outline: HTMLDivElement;
39 + label: HTMLDivElement;
40 + baselineStyles: Map<string, string>;
41 +}
42 +
43 +interface AnnotationSession {
44 + teardown: (notifyMain: boolean) => void;
45 + applyTheme: (theme: DesktopPreviewAnnotationTheme) => void;
46 +}
47 +
48 +let activeSession: AnnotationSession | null = null;
49 +let idSequence = 0;
50 +let annotationTheme: DesktopPreviewAnnotationTheme | null = null;
51 +
52 +const applyAnnotationTheme = (
53 + host: HTMLElement,
54 + theme: DesktopPreviewAnnotationTheme | null,
55 +): void => {
56 + if (!theme) return;
57 + host.style.colorScheme = theme.colorScheme;
58 + const variables = {
59 + "--t3-radius": theme.radius,
60 + "--t3-background": theme.background,
61 + "--t3-foreground": theme.foreground,
62 + "--t3-popover": theme.popover,
63 + "--t3-popover-foreground": theme.popoverForeground,
64 + "--t3-primary": theme.primary,
65 + "--t3-primary-foreground": theme.primaryForeground,
66 + "--t3-muted": theme.muted,
67 + "--t3-muted-foreground": theme.mutedForeground,
68 + "--t3-accent": theme.accent,
69 + "--t3-accent-foreground": theme.accentForeground,
70 + "--t3-border": theme.border,
71 + "--t3-input": theme.input,
72 + "--t3-ring": theme.ring,
73 + "--t3-font-sans": theme.fontSans,
74 + "--t3-font-mono": theme.fontMono,
75 + };
76 + for (const [name, value] of Object.entries(variables)) {
77 + host.style.setProperty(name, value);
78 + }
79 +};
80 +
81 +const reportHumanPointerInput = (event: PointerEvent): void => {
82 + if (!event.isTrusted) return;
83 + ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
84 + kind: "pointer",
85 + x: event.clientX,
86 + y: event.clientY,
87 + button: event.button,
88 + });
89 +};
90 +
91 +const reportHumanKeyInput = (event: KeyboardEvent): void => {
92 + if (!event.isTrusted) return;
93 + ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
94 + kind: "key",
95 + key: event.key,
96 + code: event.code,
97 + });
98 +};
99 +
100 +window.addEventListener("pointerdown", reportHumanPointerInput, true);
101 +window.addEventListener("keydown", reportHumanKeyInput, true);
102 +
103 +const nextId = (prefix: string): string => {
104 + idSequence += 1;
105 + return `${prefix}_${idSequence.toString(36)}`;
106 +};
107 +
108 +const rectFromDomRect = (rect: DOMRect): PreviewAnnotationRect => ({
109 + x: rect.left,
110 + y: rect.top,
111 + width: rect.width,
112 + height: rect.height,
113 +});
114 +
115 +const normalizeRect = (
116 + startX: number,
117 + startY: number,
118 + endX: number,
119 + endY: number,
120 +): PreviewAnnotationRect => ({
121 + x: Math.min(startX, endX),
122 + y: Math.min(startY, endY),
123 + width: Math.abs(endX - startX),
124 + height: Math.abs(endY - startY),
125 +});
126 +
127 +const isUsableRect = (rect: PreviewAnnotationRect): boolean => rect.width >= 3 && rect.height >= 3;
128 +
129 +function unionRects(
130 + rects: ReadonlyArray<PreviewAnnotationRect>,
131 + padding = 20,
132 +): PreviewAnnotationRect | null {
133 + if (rects.length === 0) return null;
134 + const left = Math.min(...rects.map((rect) => rect.x));
135 + const top = Math.min(...rects.map((rect) => rect.y));
136 + const right = Math.max(...rects.map((rect) => rect.x + rect.width));
137 + const bottom = Math.max(...rects.map((rect) => rect.y + rect.height));
138 + const x = Math.max(0, left - padding);
139 + const y = Math.max(0, top - padding);
140 + const maxWidth = Math.max(1, window.innerWidth - x);
141 + const maxHeight = Math.max(1, window.innerHeight - y);
142 + return {
143 + x,
144 + y,
145 + width: Math.min(maxWidth, right - left + padding * 2),
146 + height: Math.min(maxHeight, bottom - top + padding * 2),
147 + };
148 +}
149 +
150 +function isAnnotationNode(element: Element): boolean {
151 + return element instanceof Element && element.closest(`[${OVERLAY_ATTRIBUTE}]`) !== null;
152 +}
153 +
154 +function pickFromPoint(clientX: number, clientY: number): Element | null {
155 + for (const candidate of document.elementsFromPoint(clientX, clientY)) {
156 + if (!(candidate instanceof Element)) continue;
157 + if (isAnnotationNode(candidate)) continue;
158 + if (candidate === document.documentElement || candidate === document.body) continue;
159 + return candidate;
160 + }
161 + return null;
162 +}
163 +
164 +function describeRawElement(element: Element): string {
165 + const tag = element.tagName.toLowerCase();
166 + const id = element.id ? `#${element.id}` : "";
167 + const classes =
168 + element instanceof HTMLElement && typeof element.className === "string"
169 + ? element.className
170 + .trim()
171 + .split(/\s+/)
172 + .filter(Boolean)
173 + .slice(0, 2)
174 + .map((name) => `.${name}`)
175 + .join("")
176 + : "";
177 + return `${tag}${id}${classes}`;
178 +}
179 +
180 +function createBox(color: string, fill: string): HTMLDivElement {
181 + const node = document.createElement("div");
182 + node.setAttribute(OVERLAY_ATTRIBUTE, "");
183 + node.style.cssText = [
184 + "position:fixed",
185 + "pointer-events:none",
186 + `border:2px solid ${color}`,
187 + `background:${fill}`,
188 + "border-radius:3px",
189 + "box-sizing:border-box",
190 + "display:none",
191 + `z-index:${CONTENT_LAYER_Z_INDEX}`,
192 + ].join(";");
193 + return node;
194 +}
195 +
196 +function positionBox(node: HTMLElement, rect: PreviewAnnotationRect): void {
197 + node.style.display = "block";
198 + node.style.transform = `translate(${rect.x}px, ${rect.y}px)`;
199 + node.style.width = `${rect.width}px`;
200 + node.style.height = `${rect.height}px`;
201 +}
202 +
203 +function createLabel(): HTMLDivElement {
204 + const label = document.createElement("div");
205 + label.setAttribute(OVERLAY_ATTRIBUTE, "");
206 + label.className =
207 + "fixed z-1 max-w-70 overflow-hidden rounded-md bg-primary px-2 py-1 font-sans text-xs font-semibold text-primary-foreground shadow-md";
208 + label.style.cssText = [
209 + "position:fixed",
210 + "pointer-events:none",
211 + "white-space:nowrap",
212 + "text-overflow:ellipsis",
213 + `z-index:${CONTENT_LAYER_Z_INDEX}`,
214 + ].join(";");
215 + return label;
216 +}
217 +
218 +function updateSelectedVisual(target: SelectedElement): void {
219 + if (!target.element.isConnected) {
220 + target.outline.style.display = "none";
221 + target.label.style.display = "none";
222 + return;
223 + }
224 + const rect = target.element.getBoundingClientRect();
225 + positionBox(target.outline, rectFromDomRect(rect));
226 + target.label.textContent = describeRawElement(target.element);
227 + target.label.style.display = "block";
228 + target.label.style.transform = `translate(${Math.max(4, rect.left)}px, ${Math.max(4, rect.top - 22)}px)`;
229 +}
230 +
231 +function toStackFrame(frame: {
232 + functionName?: string;
233 + fileName?: string;
234 + lineNumber?: number;
235 + columnNumber?: number;
236 +}): PickedElementStackFrame {
237 + return {
238 + functionName: frame.functionName ?? null,
239 + fileName: frame.fileName ?? null,
240 + lineNumber: frame.lineNumber ?? null,
241 + columnNumber: frame.columnNumber ?? null,
242 + };
243 +}
244 +
245 +async function captureElement(element: Element): Promise<PickedElementPayload | null> {
246 + try {
247 + const context = await getElementContext(element);
248 + const stack = (context.stack ?? []).map(toStackFrame);
249 + return {
250 + pageUrl: location.href,
251 + pageTitle: document.title?.trim() || null,
252 + tagName: element.tagName.toLowerCase(),
253 + selector: context.selector,
254 + htmlPreview: context.htmlPreview ?? "",
255 + componentName: context.componentName,
256 + source: stack[0] ?? null,
257 + stack,
258 + styles: context.styles ?? "",
259 + pickedAt: new Date().toISOString(),
260 + };
261 + } catch {
262 + return null;
263 + }
264 +}
265 +
266 +function createButton(label: string, title: string): HTMLButtonElement {
267 + const button = document.createElement("button");
268 + button.type = "button";
269 + button.textContent = label;
270 + button.title = title;
271 + button.className =
272 + "inline-flex h-7 cursor-pointer items-center justify-center rounded-md border border-transparent px-2 font-sans text-xs font-medium text-foreground outline-none hover:bg-accent disabled:pointer-events-none disabled:opacity-60";
273 + return button;
274 +}
275 +
276 +function styleControl(input: HTMLInputElement | HTMLSelectElement): void {
277 + input.setAttribute("aria-label", input.getAttribute("aria-label") ?? "Style value");
278 + input.className =
279 + "h-7 min-w-0 w-full appearance-none rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground shadow-xs outline-none";
280 +}
281 +
282 +function createUnitControl(input: HTMLInputElement): HTMLElement {
283 + const wrapper = document.createElement("div");
284 + wrapper.style.cssText = "position:relative;min-width:0";
285 + const unit = document.createElement("span");
286 + unit.textContent = input.dataset.unit ?? "";
287 + unit.className =
288 + "pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 font-mono text-xs text-muted-foreground";
289 + wrapper.append(input, unit);
290 + return wrapper;
291 +}
292 +
293 +function createField(
294 + labelText: string,
295 + input: HTMLInputElement | HTMLSelectElement,
296 +): HTMLLabelElement {
297 + const label = document.createElement("label");
298 + label.className =
299 + "grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
300 + const text = document.createElement("span");
301 + text.textContent = labelText;
302 + styleControl(input);
303 + label.append(
304 + text,
305 + input instanceof HTMLInputElement && input.dataset.unit ? createUnitControl(input) : input,
306 + );
307 + return label;
308 +}
309 +
310 +function createStyleSection(): HTMLElement {
311 + const section = document.createElement("section");
312 + section.className = "grid gap-1 border-t border-border py-2";
313 + return section;
314 +}
315 +
316 +function createUnitInput(unit: string, placeholder = "0"): HTMLInputElement {
317 + const input = document.createElement("input");
318 + input.type = "number";
319 + input.placeholder = placeholder;
320 + input.style.paddingRight = "30px";
321 + input.dataset.unit = unit;
322 + return input;
323 +}
324 +
325 +function pathFromPoints(points: ReadonlyArray<PreviewAnnotationPoint>): string {
326 + if (points.length === 0) return "";
327 + if (points.length === 1) return `M ${points[0]!.x} ${points[0]!.y} l 0.01 0.01`;
328 + let path = `M ${points[0]!.x} ${points[0]!.y}`;
329 + for (let index = 1; index < points.length - 1; index += 1) {
330 + const current = points[index]!;
331 + const next = points[index + 1]!;
332 + path += ` Q ${current.x} ${current.y} ${(current.x + next.x) / 2} ${(current.y + next.y) / 2}`;
333 + }
334 + const last = points[points.length - 1]!;
335 + path += ` L ${last.x} ${last.y}`;
336 + return path;
337 +}
338 +
339 +function strokeBounds(
340 + points: ReadonlyArray<PreviewAnnotationPoint>,
341 + width: number,
342 +): PreviewAnnotationRect {
343 + const xs = points.map((point) => point.x);
344 + const ys = points.map((point) => point.y);
345 + const padding = width + 3;
346 + const left = Math.min(...xs) - padding;
347 + const top = Math.min(...ys) - padding;
348 + const right = Math.max(...xs) + padding;
349 + const bottom = Math.max(...ys) + padding;
350 + return { x: left, y: top, width: right - left, height: bottom - top };
351 +}
352 +
353 +function startAnnotation(): void {
354 + activeSession?.teardown(false);
355 + let finished = false;
356 + const host = document.createElement("div");
357 + host.setAttribute(OVERLAY_ATTRIBUTE, "");
358 + host.style.cssText = `position:fixed;inset:0;z-index:${Z_INDEX_OVERLAY};pointer-events:none`;
359 + applyAnnotationTheme(host, annotationTheme);
360 + const shadowRoot = host.attachShadow({ mode: "closed" });
361 + const themeStyle = document.createElement("style");
362 + themeStyle.textContent = previewAnnotationStyles;
363 + shadowRoot.appendChild(themeStyle);
364 +
365 + const root = document.createElement("div");
366 + root.setAttribute(OVERLAY_ATTRIBUTE, "");
367 + root.className = "fixed inset-0 font-sans text-foreground";
368 + root.style.cssText = "pointer-events:none";
369 + const cursorStyle = document.createElement("style");
370 + cursorStyle.setAttribute(OVERLAY_ATTRIBUTE, "");
371 + cursorStyle.textContent = `html[data-t3code-annotation-tool] body, html[data-t3code-annotation-tool] body * { cursor: crosshair !important; } [${OVERLAY_ATTRIBUTE}], [${OVERLAY_ATTRIBUTE}] * { cursor: default !important; } [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-inner-spin-button, [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-outer-spin-button { appearance:none; margin:0; }`;
372 + document.documentElement.appendChild(cursorStyle);
373 + shadowRoot.appendChild(root);
374 +
375 + const hoverOutline = createBox(PRIMARY, PRIMARY_FILL);
376 + const marqueeBox = createBox(PRIMARY, PRIMARY_FILL);
377 + root.append(hoverOutline, marqueeBox);
378 +
379 + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
380 + svg.setAttribute(OVERLAY_ATTRIBUTE, "");
381 + svg.setAttribute("width", "100%");
382 + svg.setAttribute("height", "100%");
383 + svg.setAttribute("viewBox", `0 0 ${window.innerWidth} ${window.innerHeight}`);
384 + svg.style.cssText = "position:fixed;inset:0;overflow:visible;pointer-events:none";
385 + svg.style.zIndex = String(CONTENT_LAYER_Z_INDEX);
386 + root.appendChild(svg);
387 +
388 + const toolbar = document.createElement("div");
389 + toolbar.setAttribute(OVERLAY_ATTRIBUTE, "");
390 + toolbar.className =
391 + "pointer-events-auto fixed top-2.5 left-1/2 flex -translate-x-1/2 gap-0.5 rounded-lg border border-border bg-popover/95 p-1 text-popover-foreground shadow-lg backdrop-blur-xl";
392 + toolbar.style.zIndex = String(CHROME_LAYER_Z_INDEX);
393 + root.appendChild(toolbar);
394 +
395 + const editor = document.createElement("div");
396 + editor.setAttribute(OVERLAY_ATTRIBUTE, "");
397 + editor.className =
398 + "pointer-events-auto fixed hidden max-h-[calc(100vh-16px)] w-[min(360px,calc(100vw-16px))] flex-col overflow-hidden rounded-xl border border-border bg-popover/96 text-popover-foreground shadow-2xl backdrop-blur-xl";
399 + editor.style.zIndex = String(CHROME_LAYER_Z_INDEX);
400 + root.appendChild(editor);
401 +
402 + const composerRow = document.createElement("div");
403 + composerRow.className = "flex items-start gap-2 p-2";
404 +
405 + const adjust = createButton("", "Expand annotation editor");
406 + adjust.setAttribute("aria-label", "Expand annotation editor");
407 + adjust.setAttribute("aria-expanded", "false");
408 + adjust.className +=
409 + " h-8 w-8 shrink-0 bg-muted p-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground";
410 + adjust.innerHTML =
411 + '<svg viewBox="0 0 20 20" width="15" height="15" aria-hidden="true"><path d="M4 5h12M4 10h12M4 15h12M7 3v4M13 8v4M9 13v4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>';
412 + composerRow.appendChild(adjust);
413 +
414 + const comment = document.createElement("textarea");
415 + comment.placeholder = "Describe the change…";
416 + comment.rows = 1;
417 + comment.className =
418 + "min-h-8 max-h-24 min-w-0 flex-1 resize-none overflow-y-hidden border-0 border-b border-b-transparent bg-transparent px-0 py-1.5 font-sans text-sm leading-5 text-foreground outline-none ring-0 placeholder:text-muted-foreground focus:border-b-primary focus:outline-none focus:ring-0";
419 + composerRow.appendChild(comment);
420 +
421 + const dragHandle = document.createElement("button");
422 + dragHandle.type = "button";
423 + dragHandle.textContent = "⠿";
424 + dragHandle.title = "Drag annotation editor";
425 + dragHandle.className =
426 + "hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
427 + composerRow.appendChild(dragHandle);
428 +
429 + const submit = createButton("Attach", "Attach annotation and screenshot");
430 + submit.className +=
431 + " h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
432 + composerRow.appendChild(submit);
433 + editor.appendChild(composerRow);
434 +
435 + const stylePanel = document.createElement("div");
436 + stylePanel.className =
437 + "hidden max-h-[min(176px,calc(100vh-180px))] overflow-auto border-t border-border bg-muted/40 px-3";
438 + editor.appendChild(stylePanel);
439 +
440 + const selected = new Map<Element, SelectedElement>();
441 + const regions: PreviewAnnotationRegionTarget[] = [];
442 + const strokes: PreviewAnnotationStrokeTarget[] = [];
443 + const styleChanges = new Map<string, PreviewAnnotationStyleChange>();
444 + const toolButtons = new Map<AnnotationTool, HTMLButtonElement>();
445 + let tool: AnnotationTool = "select";
446 + let dragStart: PreviewAnnotationPoint | null = null;
447 + let activeStroke: { target: PreviewAnnotationStrokeTarget; path: SVGPathElement } | null = null;
448 + let pendingCapture = false;
449 + let editorExpanded = false;
450 + let editorWasShown = false;
451 + let editorPosition: { left: number; top: number } | null = null;
452 + let editorDrag: { pointerId: number; offsetX: number; offsetY: number } | null = null;
453 + let editorLayoutFrame: number | null = null;
454 +
455 + const resizeComment = (): void => {
456 + const maxHeight = 96;
457 + comment.style.height = "auto";
458 + const nextHeight = Math.min(comment.scrollHeight, maxHeight);
459 + comment.style.height = `${nextHeight}px`;
460 + comment.style.overflowY = comment.scrollHeight > maxHeight ? "auto" : "hidden";
461 + queueEditorLayout();
462 + };
463 + comment.addEventListener("input", resizeComment);
464 +
465 + const updateStatus = (): void => {
466 + const hasTargets = selected.size > 0 || regions.length > 0 || strokes.length > 0;
467 + editor.style.display = hasTargets ? "flex" : "none";
468 + submit.disabled = !hasTargets;
469 + submit.style.opacity = hasTargets ? "1" : "0.45";
470 + adjust.disabled = !hasTargets;
471 + stylePanel.style.display = editorExpanded && selected.size > 0 ? "grid" : "none";
472 + queueEditorLayout();
473 + if (hasTargets && !editorWasShown) {
474 + editorWasShown = true;
475 + window.setTimeout(() => comment.focus({ preventScroll: true }), 0);
476 + }
477 + };
478 +
479 + const refreshToolButtons = (): void => {
480 + for (const [candidate, button] of toolButtons) {
481 + const active = candidate === tool;
482 + button.classList.toggle("bg-primary/10", active);
483 + button.classList.toggle("text-primary", active);
484 + button.classList.toggle("text-foreground", !active);
485 + }
486 + if (tool !== "select") hoverOutline.style.display = "none";
487 + if (tool !== "marquee") marqueeBox.style.display = "none";
488 + document.documentElement.setAttribute("data-t3code-annotation-tool", tool);
489 + };
490 +
491 + const removeSelected = (target: SelectedElement): void => {
492 + if (target.element instanceof HTMLElement || target.element instanceof SVGElement) {
493 + for (const [property, baseline] of target.baselineStyles) {
494 + if (baseline) target.element.style.setProperty(property, baseline);
495 + else target.element.style.removeProperty(property);
496 + }
497 + }
498 + selected.delete(target.element);
499 + target.outline.remove();
500 + target.label.remove();
501 + for (const [key, change] of styleChanges) {
502 + if (change.targetId === target.id) styleChanges.delete(key);
503 + }
504 + updateStatus();
505 + };
506 +
507 + const addSelected = (element: Element): void => {
508 + if (selected.has(element)) return;
509 + const target: SelectedElement = {
510 + id: nextId("element"),
511 + element,
512 + outline: createBox(PRIMARY, PRIMARY_FILL),
513 + label: createLabel(),
514 + baselineStyles: new Map(),
515 + };
516 + selected.set(element, target);
517 + root.append(target.outline, target.label);
518 + updateSelectedVisual(target);
519 + updateStatus();
520 + if (editorExpanded) {
521 + stylePanel.style.display = "grid";
522 + syncStyleControls();
523 + }
524 + };
525 +
526 + const toggleSelected = (element: Element, additive: boolean): void => {
527 + const existing = selected.get(element);
528 + if (existing) {
529 + removeSelected(existing);
530 + return;
531 + }
532 + if (!additive) {
533 + for (const target of Array.from(selected.values())) removeSelected(target);
534 + }
535 + addSelected(element);
536 + };
537 +
538 + const setStyleForSelected = (property: string, value: string): void => {
539 + for (const target of selected.values()) {
540 + if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement))
541 + continue;
542 + if (!target.baselineStyles.has(property)) {
543 + target.baselineStyles.set(property, target.element.style.getPropertyValue(property));
544 + }
545 + const key = `${target.id}:${property}`;
546 + const previousValue =
547 + styleChanges.get(key)?.previousValue ??
548 + getComputedStyle(target.element).getPropertyValue(property).trim();
549 + target.element.style.setProperty(property, value, "important");
550 + styleChanges.set(key, {
551 + targetId: target.id,
552 + selector: null,
553 + property,
554 + previousValue,
555 + value,
556 + });
557 + updateSelectedVisual(target);
558 + }
559 + };
560 +
561 + const textSection = createStyleSection();
562 + const colorsSection = createStyleSection();
563 + const bordersSection = createStyleSection();
564 + const sizingSection = createStyleSection();
565 + stylePanel.append(textSection, colorsSection, bordersSection, sizingSection);
566 +
567 + const fontFamily = document.createElement("select");
568 + for (const value of ["inherit", "system-ui", "sans-serif", "serif", "monospace"]) {
569 + const option = document.createElement("option");
570 + option.value = value;
571 + option.textContent = value;
572 + fontFamily.appendChild(option);
573 + }
574 + fontFamily.addEventListener("change", () => setStyleForSelected("font-family", fontFamily.value));
575 + textSection.appendChild(createField("Font", fontFamily));
576 +
577 + const fontSize = createUnitInput("px", "16");
578 + fontSize.min = "1";
579 + fontSize.max = "300";
580 + fontSize.addEventListener("input", () => {
581 + if (fontSize.value) setStyleForSelected("font-size", `${fontSize.value}px`);
582 + });
583 + textSection.appendChild(createField("Font size", fontSize));
584 +
585 + const fontWeight = document.createElement("select");
586 + for (const value of ["300", "400", "500", "600", "700", "800", "900"]) {
587 + const option = document.createElement("option");
588 + option.value = value;
589 + option.textContent = value;
590 + fontWeight.appendChild(option);
591 + }
592 + fontWeight.addEventListener("change", () => setStyleForSelected("font-weight", fontWeight.value));
593 + textSection.appendChild(createField("Font weight", fontWeight));
594 +
595 + const lineHeight = document.createElement("input");
596 + lineHeight.type = "text";
597 + lineHeight.placeholder = "normal / 1.4";
598 + lineHeight.addEventListener("change", () => {
599 + if (lineHeight.value.trim()) setStyleForSelected("line-height", lineHeight.value.trim());
600 + });
601 + textSection.appendChild(createField("Line height", lineHeight));
602 +
603 + const createColorRow = (
604 + labelText: string,
605 + property: string,
606 + section: HTMLElement,
607 + ): { row: HTMLLabelElement; color: HTMLInputElement; text: HTMLInputElement } => {
608 + const row = document.createElement("label");
609 + row.className =
610 + "grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
611 + const label = document.createElement("span");
612 + label.textContent = labelText;
613 + const control = document.createElement("div");
614 + control.className =
615 + "grid h-7 grid-cols-[22px_minmax(0,1fr)] items-center gap-1 rounded-md border border-input bg-background px-1 shadow-xs";
616 + const color = document.createElement("input");
617 + color.type = "color";
618 + color.setAttribute("aria-label", labelText);
619 + color.style.cssText =
620 + "width:20px;height:20px;padding:0;border:0;border-radius:5px;overflow:hidden;background:transparent;cursor:pointer";
621 + const text = document.createElement("input");
622 + text.type = "text";
623 + text.setAttribute("aria-label", `${labelText} value`);
624 + text.className =
625 + "min-w-0 w-full border-0 bg-transparent font-mono text-xs text-foreground outline-none";
626 + color.addEventListener("input", () => {
627 + text.value = color.value;
628 + setStyleForSelected(property, color.value);
629 + });
630 + text.addEventListener("change", () => {
631 + const value = text.value.trim();
632 + if (!value) return;
633 + setStyleForSelected(property, value);
634 + if (/^#[0-9a-f]{6}$/i.test(value)) color.value = value;
635 + });
636 + control.append(color, text);
637 + row.append(label, control);
638 + section.appendChild(row);
639 + return { row, color, text };
640 + };
641 +
642 + const textColor = createColorRow("Text color", "color", colorsSection);
643 + const backgroundColor = createColorRow("Background", "background-color", colorsSection);
644 +
645 + const opacity = document.createElement("input");
646 + opacity.type = "range";
647 + opacity.min = "0";
648 + opacity.max = "1";
649 + opacity.step = "0.05";
650 + opacity.value = "1";
651 + opacity.style.accentColor = PRIMARY;
652 + opacity.addEventListener("input", () => setStyleForSelected("opacity", opacity.value));
653 + colorsSection.appendChild(createField("Opacity", opacity));
654 +
655 + const radius = createUnitInput("px", "0");
656 + radius.min = "0";
657 + radius.max = "300";
658 + radius.addEventListener("input", () => {
659 + if (radius.value) setStyleForSelected("border-radius", `${radius.value}px`);
660 + });
661 + bordersSection.appendChild(createField("Radius", radius));
662 +
663 + const borderColor = createColorRow("Border color", "border-color", bordersSection);
664 +
665 + const borderWidth = createUnitInput("px", "0");
666 + borderWidth.min = "0";
667 + borderWidth.max = "100";
668 + borderWidth.addEventListener("input", () => {
669 + if (borderWidth.value) {
670 + setStyleForSelected("border-style", "solid");
671 + setStyleForSelected("border-width", `${borderWidth.value}px`);
672 + }
673 + });
674 + bordersSection.appendChild(createField("Border width", borderWidth));
675 +
676 + const dimensions = document.createElement("div");
677 + dimensions.style.cssText =
678 + "display:grid;grid-template-columns:82px minmax(0,1fr);gap:8px;align-items:center";
679 + const dimensionLabel = document.createElement("div");
680 + dimensionLabel.className = "grid gap-2 font-sans text-xs font-medium text-muted-foreground";
681 + dimensionLabel.innerHTML = "<span>Width</span><span>Height</span>";
682 + const dimensionControls = document.createElement("div");
683 + dimensionControls.style.cssText = "position:relative;display:grid;gap:3px;padding-left:22px";
684 + const widthInput = createUnitInput("px", "auto");
685 + const heightInput = createUnitInput("px", "auto");
686 + styleControl(widthInput);
687 + styleControl(heightInput);
688 + const aspectLock = createButton("", "Lock aspect ratio");
689 + aspectLock.setAttribute("aria-pressed", "true");
690 + aspectLock.style.cssText +=
691 + ";position:absolute;left:0;top:50%;transform:translateY(-50%);width:18px;height:38px;padding:0";
692 + aspectLock.className += " bg-primary/10 text-primary";
693 + dimensionControls.append(
694 + createUnitControl(widthInput),
695 + createUnitControl(heightInput),
696 + aspectLock,
697 + );
698 + dimensions.append(dimensionLabel, dimensionControls);
699 + sizingSection.appendChild(dimensions);
700 +
701 + let aspectLocked = true;
702 + let aspectRatio = 1;
703 + const refreshAspectButton = (): void => {
704 + aspectLock.innerHTML = aspectLocked
705 + ? '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="M8 6.5 9.5 5A3.5 3.5 0 0 1 14.5 10l-1.5 1.5M12 13.5 10.5 15A3.5 3.5 0 0 1 5.5 10L7 8.5M7.5 12.5l5-5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>'
706 + : '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="m6 6 8 8M8 6.5 9.5 5A3.5 3.5 0 0 1 14 9M12 13.5 10.5 15A3.5 3.5 0 0 1 6 11" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>';
707 + aspectLock.setAttribute("aria-pressed", String(aspectLocked));
708 + aspectLock.classList.toggle("bg-primary/10", aspectLocked);
709 + aspectLock.classList.toggle("text-primary", aspectLocked);
710 + aspectLock.classList.toggle("bg-muted", !aspectLocked);
711 + aspectLock.classList.toggle("text-muted-foreground", !aspectLocked);
712 + };
713 + aspectLock.addEventListener("click", () => {
714 + aspectLocked = !aspectLocked;
715 + refreshAspectButton();
716 + });
717 + widthInput.addEventListener("input", () => {
718 + const width = Number(widthInput.value);
719 + if (!Number.isFinite(width) || width <= 0) return;
720 + setStyleForSelected("width", `${width}px`);
721 + if (aspectLocked && aspectRatio > 0) {
722 + const height = Math.max(1, Math.round(width / aspectRatio));
723 + heightInput.value = String(height);
724 + setStyleForSelected("height", `${height}px`);
725 + }
726 + });
727 + heightInput.addEventListener("input", () => {
728 + const height = Number(heightInput.value);
729 + if (!Number.isFinite(height) || height <= 0) return;
730 + setStyleForSelected("height", `${height}px`);
731 + if (aspectLocked && aspectRatio > 0) {
732 + const width = Math.max(1, Math.round(height * aspectRatio));
733 + widthInput.value = String(width);
734 + setStyleForSelected("width", `${width}px`);
735 + }
736 + });
737 + refreshAspectButton();
738 +
739 + const addSpacingField = (
740 + label: string,
741 + property: string,
742 + placeholder: string,
743 + ): HTMLInputElement => {
744 + const input = document.createElement("input");
745 + input.type = "text";
746 + input.placeholder = placeholder;
747 + input.addEventListener("change", () => {
748 + if (input.value.trim()) setStyleForSelected(property, input.value.trim());
749 + });
750 + sizingSection.appendChild(createField(label, input));
751 + return input;
752 + };
753 + const padding = addSpacingField("Padding", "padding", "0 0 0 0");
754 + const margin = addSpacingField("Margin", "margin", "0 0 0 0");
755 + const gap = addSpacingField("Gap", "gap", "0px");
756 +
757 + const syncStyleControls = (): void => {
758 + const first = selected.values().next().value as SelectedElement | undefined;
759 + if (!first) return;
760 + const computed = getComputedStyle(first.element);
761 + const rect = first.element.getBoundingClientRect();
762 + aspectRatio = rect.height > 0 ? rect.width / rect.height : 1;
763 + widthInput.value = String(Math.round(rect.width));
764 + heightInput.value = String(Math.round(rect.height));
765 + fontSize.value = String(Math.round(Number.parseFloat(computed.fontSize) || 16));
766 + fontWeight.value = computed.fontWeight.match(/^[0-9]+$/) ? computed.fontWeight : "400";
767 + lineHeight.value = computed.lineHeight;
768 + fontFamily.value = Array.from(fontFamily.options).some(
769 + (option) => option.value === computed.fontFamily,
770 + )
771 + ? computed.fontFamily
772 + : "inherit";
773 + textColor.text.value = computed.color;
774 + backgroundColor.text.value = computed.backgroundColor;
775 + borderColor.text.value = computed.borderColor;
776 + opacity.value = computed.opacity;
777 + radius.value = String(Math.round(Number.parseFloat(computed.borderRadius) || 0));
778 + borderWidth.value = String(Math.round(Number.parseFloat(computed.borderWidth) || 0));
779 + padding.value = computed.padding;
780 + margin.value = computed.margin;
781 + gap.value = computed.gap === "normal" ? "0px" : computed.gap;
782 + };
783 +
784 + const tools: ReadonlyArray<[AnnotationTool, string, string]> = [
785 + ["select", "Select", "Select elements (V)"],
786 + ["marquee", "Region", "Draw a region or marquee-select elements (R)"],
787 + ["draw", "Draw", "Draw freehand (D)"],
788 + ["erase", "Erase", "Remove an annotation target (E)"],
789 + ];
790 + for (const [candidate, label, title] of tools) {
791 + const button = createButton(label, title);
792 + button.className += " h-8 px-2.5 text-sm";
793 + button.addEventListener("click", () => {
794 + tool = candidate;
795 + refreshToolButtons();
796 + });
797 + toolButtons.set(candidate, button);
798 + toolbar.appendChild(button);
799 + }
800 +
801 + const clampEditorPosition = (left: number, top: number): { left: number; top: number } => {
802 + const margin = 8;
803 + const rect = editor.getBoundingClientRect();
804 + return {
805 + left: Math.min(
806 + Math.max(margin, left),
807 + Math.max(margin, window.innerWidth - rect.width - margin),
808 + ),
809 + top: Math.min(
810 + Math.max(margin, top),
811 + Math.max(margin, window.innerHeight - rect.height - margin),
812 + ),
813 + };
814 + };
815 +
816 + const applyEditorPosition = (position: { left: number; top: number }): void => {
817 + const clamped = clampEditorPosition(position.left, position.top);
818 + editor.style.left = `${clamped.left}px`;
819 + editor.style.top = `${clamped.top}px`;
820 + editor.style.right = "auto";
821 + editor.style.bottom = "auto";
822 + if (editorExpanded) editorPosition = clamped;
823 + };
824 +
825 + const getAnnotationBounds = (): PreviewAnnotationRect | null =>
826 + unionRects(
827 + [
828 + ...Array.from(selected.values(), (target) =>
829 + rectFromDomRect(target.element.getBoundingClientRect()),
830 + ),
831 + ...regions.map((region) => region.rect),
832 + ...strokes.map((stroke) => stroke.bounds),
833 + ],
834 + 0,
835 + );
836 +
837 + const positionCompactEditor = (): void => {
838 + const bounds = getAnnotationBounds();
839 + if (!bounds) return;
840 + const editorRect = editor.getBoundingClientRect();
841 + const gap = 8;
842 + const candidates = [
843 + { left: bounds.x + bounds.width + gap, top: bounds.y },
844 + { left: bounds.x - editorRect.width - gap, top: bounds.y },
845 + {
846 + left: bounds.x + bounds.width - editorRect.width,
847 + top: bounds.y + bounds.height + gap,
848 + },
849 + {
850 + left: bounds.x + bounds.width - editorRect.width,
851 + top: bounds.y - editorRect.height - gap,
852 + },
853 + ];
854 + const overflow = (position: { left: number; top: number }): number =>
855 + Math.max(0, -position.left) +
856 + Math.max(0, -position.top) +
857 + Math.max(0, position.left + editorRect.width - window.innerWidth) +
858 + Math.max(0, position.top + editorRect.height - window.innerHeight);
859 + const best = candidates.reduce((current, candidate) =>
860 + overflow(candidate) < overflow(current) ? candidate : current,
861 + );
862 + applyEditorPosition(best);
863 + };
864 +
865 + function queueEditorLayout(): void {
866 + if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
867 + editorLayoutFrame = window.requestAnimationFrame(() => {
868 + editorLayoutFrame = null;
869 + if (editor.style.display === "none") return;
870 + if (editorExpanded && editorPosition) applyEditorPosition(editorPosition);
871 + else positionCompactEditor();
872 + });
873 + }
874 +
875 + adjust.addEventListener("click", () => {
876 + if (selected.size === 0) return;
877 + if (!editorExpanded) {
878 + const rect = editor.getBoundingClientRect();
879 + editorExpanded = true;
880 + editorPosition = { left: rect.left, top: rect.top };
881 + stylePanel.style.display = selected.size > 0 ? "grid" : "none";
882 + dragHandle.style.display = "block";
883 + adjust.setAttribute("aria-expanded", "true");
884 + adjust.title = "Collapse annotation editor";
885 + adjust.setAttribute("aria-label", "Collapse annotation editor");
886 + if (selected.size > 0) syncStyleControls();
887 + } else {
888 + editorExpanded = false;
889 + editorPosition = null;
890 + stylePanel.style.display = "none";
891 + dragHandle.style.display = "none";
892 + adjust.setAttribute("aria-expanded", "false");
893 + adjust.title = "Expand annotation editor";
894 + adjust.setAttribute("aria-label", "Expand annotation editor");
895 + }
896 + queueEditorLayout();
897 + });
898 +
899 + const onEditorPointerDown = (event: PointerEvent): void => {
900 + if (event.button !== 0 || !editorExpanded) return;
901 + const rect = editor.getBoundingClientRect();
902 + editorDrag = {
903 + pointerId: event.pointerId,
904 + offsetX: event.clientX - rect.left,
905 + offsetY: event.clientY - rect.top,
906 + };
907 + dragHandle.setPointerCapture(event.pointerId);
908 + dragHandle.style.cursor = "grabbing";
909 + event.preventDefault();
910 + event.stopPropagation();
911 + };
912 +
913 + const onEditorPointerMove = (event: PointerEvent): void => {
914 + if (!editorDrag || editorDrag.pointerId !== event.pointerId) return;
915 + applyEditorPosition({
916 + left: event.clientX - editorDrag.offsetX,
917 + top: event.clientY - editorDrag.offsetY,
918 + });
919 + event.preventDefault();
920 + event.stopPropagation();
921 + };
922 +
923 + const onEditorPointerUp = (event: PointerEvent): void => {
924 + if (!editorDrag || editorDrag.pointerId !== event.pointerId) return;
925 + editorDrag = null;
926 + dragHandle.style.cursor = "grab";
927 + if (dragHandle.hasPointerCapture(event.pointerId))
928 + dragHandle.releasePointerCapture(event.pointerId);
929 + event.preventDefault();
930 + event.stopPropagation();
931 + };
932 + dragHandle.addEventListener("pointerdown", onEditorPointerDown);
933 + dragHandle.addEventListener("pointermove", onEditorPointerMove);
934 + dragHandle.addEventListener("pointerup", onEditorPointerUp);
935 + dragHandle.addEventListener("pointercancel", onEditorPointerUp);
936 +
937 + const repaint = (): void => {
938 + for (const target of selected.values()) updateSelectedVisual(target);
939 + queueEditorLayout();
940 + };
941 +
942 + const removeTargetAtPoint = (x: number, y: number): boolean => {
943 + for (const target of Array.from(selected.values()).toReversed()) {
944 + const rect = target.element.getBoundingClientRect();
945 + if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
946 + removeSelected(target);
947 + return true;
948 + }
949 + }
950 + const regionIndex = regions.findIndex(
951 + (region) =>
952 + x >= region.rect.x &&
953 + x <= region.rect.x + region.rect.width &&
954 + y >= region.rect.y &&
955 + y <= region.rect.y + region.rect.height,
956 + );
957 + if (regionIndex >= 0) {
958 + const [removed] = regions.splice(regionIndex, 1);
959 + root.querySelector(`[data-region-id="${removed?.id}"]`)?.remove();
960 + updateStatus();
961 + return true;
962 + }
963 + const strokeIndex = strokes.findIndex(
964 + (stroke) =>
965 + x >= stroke.bounds.x &&
966 + x <= stroke.bounds.x + stroke.bounds.width &&
967 + y >= stroke.bounds.y &&
968 + y <= stroke.bounds.y + stroke.bounds.height,
969 + );
970 + if (strokeIndex >= 0) {
971 + const [removed] = strokes.splice(strokeIndex, 1);
972 + svg.querySelector(`[data-stroke-id="${removed?.id}"]`)?.remove();
973 + updateStatus();
974 + return true;
975 + }
976 + return false;
977 + };
978 +
979 + const selectElementsInRect = (rect: PreviewAnnotationRect): number => {
980 + const candidates = Array.from(document.querySelectorAll("body *"))
981 + .filter((element) => !isAnnotationNode(element))
982 + .map((element) => ({ element, rect: element.getBoundingClientRect() }))
983 + .filter(({ rect: candidate }) => {
984 + if (candidate.width < 2 || candidate.height < 2) return false;
985 + return !(
986 + candidate.right < rect.x ||
987 + candidate.left > rect.x + rect.width ||
988 + candidate.bottom < rect.y ||
989 + candidate.top > rect.y + rect.height
990 + );
991 + })
992 + .filter(({ element, rect: candidate }) => {
993 + const centerX = candidate.left + candidate.width / 2;
994 + const centerY = candidate.top + candidate.height / 2;
995 + return (
996 + centerX >= rect.x &&
997 + centerX <= rect.x + rect.width &&
998 + centerY >= rect.y &&
999 + centerY <= rect.y + rect.height &&
1000 + (element.children.length === 0 ||
1001 + element instanceof HTMLButtonElement ||
1002 + element instanceof HTMLAnchorElement ||
1003 + element.getAttribute("role") === "button")
1004 + );
1005 + })
1006 + .sort(
1007 + (left, right) => left.rect.width * left.rect.height - right.rect.width * right.rect.height,
1008 + )
1009 + .slice(0, MAX_MARQUEE_ELEMENTS);
1010 + for (const candidate of candidates) addSelected(candidate.element);
1011 + return candidates.length;
1012 + };
1013 +
1014 + const clearHoverOutline = (): void => {
1015 + hoverOutline.style.display = "none";
1016 + };
1017 +
1018 + const onPointerMove = (event: PointerEvent): void => {
1019 + if (isAnnotationNode(event.target as Element)) {
1020 + clearHoverOutline();
1021 + return;
1022 + }
1023 + if (tool === "select" && dragStart === null) {
1024 + const target = pickFromPoint(event.clientX, event.clientY);
1025 + if (target) positionBox(hoverOutline, rectFromDomRect(target.getBoundingClientRect()));
1026 + else clearHoverOutline();
1027 + return;
1028 + }
1029 + clearHoverOutline();
1030 + if (tool === "marquee" && dragStart) {
1031 + positionBox(
1032 + marqueeBox,
1033 + normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY),
1034 + );
1035 + return;
1036 + }
1037 + if (tool === "draw" && activeStroke) {
1038 + activeStroke.target.points = [
1039 + ...activeStroke.target.points,
1040 + { x: event.clientX, y: event.clientY },
1041 + ];
1042 + activeStroke.target.bounds = strokeBounds(
1043 + activeStroke.target.points,
1044 + activeStroke.target.width,
1045 + );
1046 + activeStroke.path.setAttribute("d", pathFromPoints(activeStroke.target.points));
1047 + }
1048 + };
1049 +
1050 + const onPointerDown = (event: PointerEvent): void => {
1051 + if (event.button !== 0 || isAnnotationNode(event.target as Element)) return;
1052 + event.preventDefault();
1053 + event.stopPropagation();
1054 + if (tool === "select") {
1055 + const target = pickFromPoint(event.clientX, event.clientY);
1056 + if (target) toggleSelected(target, event.shiftKey);
1057 + return;
1058 + }
1059 + if (tool === "erase") {
1060 + removeTargetAtPoint(event.clientX, event.clientY);
1061 + return;
1062 + }
1063 + dragStart = { x: event.clientX, y: event.clientY };
1064 + if (tool === "draw") {
1065 + const stroke: PreviewAnnotationStrokeTarget = {
1066 + id: nextId("stroke"),
1067 + color: annotationTheme?.primary ?? "#2563eb",
1068 + width: 4,
1069 + points: [dragStart],
1070 + bounds: { x: dragStart.x, y: dragStart.y, width: 1, height: 1 },
1071 + };
1072 + const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
1073 + path.setAttribute(OVERLAY_ATTRIBUTE, "");
1074 + path.setAttribute("data-stroke-id", stroke.id);
1075 + path.setAttribute("fill", "none");
1076 + path.setAttribute("stroke", stroke.color);
1077 + path.setAttribute("stroke-width", String(stroke.width));
1078 + path.setAttribute("stroke-linecap", "round");
1079 + path.setAttribute("stroke-linejoin", "round");
1080 + svg.appendChild(path);
1081 + activeStroke = { target: stroke, path };
1082 + }
1083 + };
1084 +
1085 + const onPointerUp = (event: PointerEvent): void => {
1086 + if (!dragStart) return;
1087 + event.preventDefault();
1088 + event.stopPropagation();
1089 + if (tool === "marquee") {
1090 + const rect = normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY);
1091 + marqueeBox.style.display = "none";
1092 + if (isUsableRect(rect)) {
1093 + const found = selectElementsInRect(rect);
1094 + if (found === 0) {
1095 + const region: PreviewAnnotationRegionTarget = { id: nextId("region"), rect };
1096 + regions.push(region);
1097 + const regionBox = createBox(
1098 + PRIMARY,
1099 + "color-mix(in srgb, var(--t3-primary) 6%, transparent)",
1100 + );
1101 + regionBox.setAttribute("data-region-id", region.id);
1102 + positionBox(regionBox, rect);
1103 + root.appendChild(regionBox);
1104 + }
1105 + }
1106 + } else if (tool === "draw" && activeStroke) {
1107 + if (activeStroke.target.points.length > 1) strokes.push(activeStroke.target);
1108 + else activeStroke.path.remove();
1109 + activeStroke = null;
1110 + }
1111 + dragStart = null;
1112 + updateStatus();
1113 + };
1114 +
1115 + const onClick = (event: MouseEvent): void => {
1116 + if (isAnnotationNode(event.target as Element)) return;
1117 + event.preventDefault();
1118 + event.stopPropagation();
1119 + };
1120 +
1121 + const onPointerOut = (event: PointerEvent): void => {
1122 + if (event.relatedTarget === null) clearHoverOutline();
1123 + };
1124 +
1125 + const onWindowBlur = (): void => {
1126 + clearHoverOutline();
1127 + };
1128 +
1129 + const restoreStyles = (): void => {
1130 + for (const target of selected.values()) {
1131 + if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement))
1132 + continue;
1133 + for (const [property, baseline] of target.baselineStyles) {
1134 + if (baseline) target.element.style.setProperty(property, baseline);
1135 + else target.element.style.removeProperty(property);
1136 + }
1137 + }
1138 + };
1139 +
1140 + const teardown = (notifyMain: boolean): void => {
1141 + if (finished) return;
1142 + finished = true;
1143 + restoreStyles();
1144 + window.removeEventListener("pointermove", onPointerMove, true);
1145 + window.removeEventListener("pointerdown", onPointerDown, true);
1146 + window.removeEventListener("pointerup", onPointerUp, true);
1147 + window.removeEventListener("pointerout", onPointerOut, true);
1148 + window.removeEventListener("click", onClick, true);
1149 + window.removeEventListener("blur", onWindowBlur);
1150 + window.removeEventListener("keydown", onKeyDown, true);
1151 + window.removeEventListener("scroll", repaint, true);
1152 + window.removeEventListener("resize", repaint);
1153 + dragHandle.removeEventListener("pointerdown", onEditorPointerDown);
1154 + dragHandle.removeEventListener("pointermove", onEditorPointerMove);
1155 + dragHandle.removeEventListener("pointerup", onEditorPointerUp);
1156 + dragHandle.removeEventListener("pointercancel", onEditorPointerUp);
1157 + if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
1158 + ipcRenderer.off(CANCEL_PICK_CHANNEL, onCancel);
1159 + ipcRenderer.off(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
1160 + document.documentElement.removeAttribute("data-t3code-annotation-tool");
1161 + cursorStyle.remove();
1162 + host.remove();
1163 + activeSession = null;
1164 + if (notifyMain) ipcRenderer.send(ELEMENT_PICKED_CHANNEL, null);
1165 + };
1166 +
1167 + const onCancel = (): void => teardown(false);
1168 + const onCaptured = (): void => teardown(false);
1169 + const onKeyDown = (event: KeyboardEvent): void => {
1170 + if (isAnnotationNode(event.target as Element) && event.key !== "Escape") return;
1171 + if (event.key === "Escape") {
1172 + event.preventDefault();
1173 + event.stopPropagation();
1174 + teardown(true);
1175 + return;
1176 + }
1177 + if (event.key === "v") tool = "select";
1178 + else if (event.key === "r") tool = "marquee";
1179 + else if (event.key === "d") tool = "draw";
1180 + else if (event.key === "e") tool = "erase";
1181 + else return;
1182 + refreshToolButtons();
1183 + };
1184 +
1185 + submit.addEventListener("click", () => {
1186 + if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
1187 + return;
1188 + pendingCapture = true;
1189 + submit.disabled = true;
1190 + submit.textContent = "Capturing…";
1191 + void Promise.all(
1192 + Array.from(selected.values()).map(async (target) => {
1193 + const element = await captureElement(target.element);
1194 + if (!element) return null;
1195 + for (const change of styleChanges.values()) {
1196 + if (change.targetId === target.id) change.selector = element.selector;
1197 + }
1198 + return {
1199 + id: target.id,
1200 + element,
1201 + rect: rectFromDomRect(target.element.getBoundingClientRect()),
1202 + };
1203 + }),
1204 + ).then((captured) => {
1205 + const elements = captured.filter((target) => target !== null);
1206 + const annotation: PreviewAnnotationPayload = {
1207 + id: nextId("annotation"),
1208 + pageUrl: location.href,
1209 + pageTitle: document.title?.trim() || null,
1210 + comment: comment.value.trim(),
1211 + elements,
1212 + regions: [...regions],
1213 + strokes: [...strokes],
1214 + styleChanges: Array.from(styleChanges.values()),
1215 + screenshot: null,
1216 + createdAt: new Date().toISOString(),
1217 + };
1218 + editor.style.display = "none";
1219 + toolbar.style.display = "none";
1220 + hoverOutline.style.display = "none";
1221 + const screenshotRect = unionRects([
1222 + ...elements.map((target) => target.rect),
1223 + ...regions.map((region) => region.rect),
1224 + ...strokes.map((stroke) => stroke.bounds),
1225 + ]);
1226 + ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
1227 + });
1228 + });
1229 + comment.addEventListener("keydown", (event) => {
1230 + if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
1231 + event.preventDefault();
1232 + submit.click();
1233 + });
1234 +
1235 + window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
1236 + window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false });
1237 + window.addEventListener("pointerup", onPointerUp, { capture: true, passive: false });
1238 + window.addEventListener("pointerout", onPointerOut, { capture: true, passive: true });
1239 + window.addEventListener("click", onClick, { capture: true, passive: false });
1240 + window.addEventListener("blur", onWindowBlur);
1241 + window.addEventListener("keydown", onKeyDown, { capture: true });
1242 + window.addEventListener("scroll", repaint, { capture: true, passive: true });
1243 + window.addEventListener("resize", repaint, { passive: true });
1244 + ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel);
1245 + ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
1246 + document.documentElement.appendChild(host);
1247 + refreshToolButtons();
1248 + updateStatus();
1249 + activeSession = {
1250 + teardown,
1251 + applyTheme: (theme) => applyAnnotationTheme(host, theme),
1252 + };
1253 +}
1254 +
1255 +ipcRenderer.on(START_PICK_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme | undefined) => {
1256 + if (theme) annotationTheme = theme;
1257 + startAnnotation();
1258 +});
1259 +ipcRenderer.on(ANNOTATION_THEME_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme) => {
1260 + annotationTheme = theme;
1261 + activeSession?.applyTheme(theme);
1262 +});
1263 +ipcRenderer.on(CANCEL_PICK_CHANNEL, () => activeSession?.teardown(false));
apps/desktop/src/preview/PickedElementPayload.test.ts renamed
+1 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { isPickedElementPayload, isPreviewAnnotationPayload } from "./picked-element-payload.ts";
3 +import { isPickedElementPayload, isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
4
5 function validPayload(overrides?: Record<string, unknown>): Record<string, unknown> {
6 return {
apps/desktop/src/preview/PickedElementPayload.ts renamed
+1 -1
@@ -1,6 +1,6 @@
1 /**
2 * Strict structural validator for `PickedElementPayload` messages received
3 - * from the in-page picker preload (`apps/desktop/src/preview-pick-preload.ts`)
3 + * from the in-page picker preload (`apps/desktop/src/preview/PickPreload.ts`)
4 * via `wc.ipc`. Lives in its own electron-free module so the validator is
5 * trivially unit-testable.
6 *
apps/desktop/src/preview/PlaywrightInjectedRuntime.test.ts renamed
+1 -1
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
3 import {
4 playwrightInjectedRuntimeInstallExpression,
5 playwrightInjectedRuntimeSource,
6 -} from "./playwright-injected-runtime.ts";
6 +} from "./PlaywrightInjectedRuntime.ts";
7
8 describe("playwright injected runtime", () => {
9 it("extracts the pinned runtime from playwright-core", async () => {
apps/desktop/src/preview/PlaywrightInjectedRuntime.ts renamed
apps/desktop/src/preview/WebviewPreferences.test.ts renamed
+1 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { PREVIEW_WEBVIEW_PREFERENCES } from "./preview-webview-preferences.ts";
3 +import { PREVIEW_WEBVIEW_PREFERENCES } from "./WebviewPreferences.ts";
4
5 /**
6 * Mirrors Electron's webview attribute parser closely enough to catch the
apps/desktop/src/preview/WebviewPreferences.ts renamed
+2 -2
@@ -4,7 +4,7 @@
4 * surfaces inherit the same security posture.
5 *
6 * Lives in its own electron-free module so the value is unit-testable
7 - * without importing `preview-view-manager.ts` (which transitively imports
7 + * without importing `Manager.ts` (which transitively imports
8 * `electron` and blows up under vitest).
9 *
10 * - `contextIsolation=false`: the picker preload needs to share `globalThis`
@@ -22,7 +22,7 @@
22 * - `nodeIntegration=false`: pinned for clarity (the page itself never gets
23 * Node access).
24 *
25 - * Format notes (locked down by `preview-webview-preferences.test.ts`):
25 + * Format notes (locked down by `WebviewPreferences.test.ts`):
26 * - Whitespace-free. Electron's webpreferences parser splits on `,` and
27 * does not trim, so a leading space would turn a key into an unknown one
28 * and silently drop it.
apps/desktop/src/window/DesktopWindow.test.ts
+7
@@ -29,6 +29,7 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
29 import * as ElectronWindow from "../electron/ElectronWindow.ts";
30 import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
31 import * as DesktopWindow from "./DesktopWindow.ts";
32 +import * as PreviewManager from "../preview/Manager.ts";
33
34 const environmentInput = {
35 dirname: "/repo/apps/desktop/dist-electron",
@@ -166,6 +167,12 @@ function makeTestLayer(input: {
167 } satisfies ElectronShell.ElectronShellShape),
168 electronThemeLayer,
169 electronWindowLayer,
170 + Layer.mock(PreviewManager.PreviewManager)({
171 + getBrowserSession: () => Effect.succeed({} as Electron.Session),
172 + setMainWindow: () => Effect.void,
173 + isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
174 + getBrowserPartition: () => "persist:t3code-preview-test",
175 + }),
176 ),
177 ),
178 );
apps/desktop/src/window/DesktopWindow.ts
+9 -6
@@ -11,7 +11,7 @@ import * as DesktopAssets from "../app/DesktopAssets.ts";
11 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12 import * as DesktopObservability from "../app/DesktopObservability.ts";
13 import * as DesktopState from "../app/DesktopState.ts";
14 -import { previewViewManager } from "../preview-view-manager.ts";
14 +import * as PreviewManager from "../preview/Manager.ts";
15 import * as ElectronMenu from "../electron/ElectronMenu.ts";
16 import * as ElectronShell from "../electron/ElectronShell.ts";
17 import * as ElectronTheme from "../electron/ElectronTheme.ts";
@@ -37,7 +37,8 @@ type DesktopWindowRuntimeServices =
37 | ElectronMenu.ElectronMenu
38 | ElectronShell.ElectronShell
39 | ElectronTheme.ElectronTheme
40 - | ElectronWindow.ElectronWindow;
40 + | ElectronWindow.ElectronWindow
41 + | PreviewManager.PreviewManager;
42
43 export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
44 "DesktopWindowDevServerUrlMissingError",
@@ -49,7 +50,8 @@ export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
50
51 export type DesktopWindowError =
52 | DesktopWindowDevServerUrlMissingError
52 - | ElectronWindow.ElectronWindowCreateError;
53 + | ElectronWindow.ElectronWindowCreateError
54 + | PreviewManager.PreviewManagerError;
55
56 export interface DesktopWindowShape {
57 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
@@ -163,6 +165,7 @@ const make = Effect.gen(function* () {
165 const electronShell = yield* ElectronShell.ElectronShell;
166 const electronTheme = yield* ElectronTheme.ElectronTheme;
167 const electronWindow = yield* ElectronWindow.ElectronWindow;
168 + const previewManager = yield* PreviewManager.PreviewManager;
169 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
170 const state = yield* DesktopState.DesktopState;
171 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
@@ -171,7 +174,7 @@ const make = Effect.gen(function* () {
174 const createWindow = Effect.fn("desktop.window.createWindow")(function* (
175 backendHttpUrl: URL,
176 ): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
174 - previewViewManager.getBrowserSession();
177 + yield* previewManager.getBrowserSession();
178 const applicationUrl = environment.isDevelopment
179 ? yield* resolveDesktopDevServerUrl(environment)
180 : backendHttpUrl.href;
@@ -198,11 +201,11 @@ const make = Effect.gen(function* () {
201 },
202 });
203
201 - previewViewManager.setMainWindow(window);
204 + yield* previewManager.setMainWindow(window);
205 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
206 if (
207 typeof params.partition !== "string" ||
205 - !previewViewManager.isBrowserPartition(params.partition)
208 + !previewManager.isBrowserPartition(params.partition)
209 ) {
210 event.preventDefault();
211 return;
apps/server/src/mcp/McpHttpServer.ts
+130 -110
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
5 import * as Option from "effect/Option";
6 import * as Sink from "effect/Sink";
7 import * as Stream from "effect/Stream";
8 +import type * as Types from "effect/Types";
9 import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
10 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
11
@@ -29,6 +30,20 @@ const unauthorized = HttpServerResponse.jsonUnsafe(
30 },
31 );
32
33 +type AuthenticatedHttpEffect = Effect.Effect<
34 + HttpServerResponse.HttpServerResponse,
35 + Types.unhandled,
36 + McpInvocationContext.McpInvocationContext
37 +>;
38 +
39 +type McpAuthMiddleware = (
40 + httpEffect: AuthenticatedHttpEffect,
41 +) => Effect.Effect<
42 + HttpServerResponse.HttpServerResponse,
43 + Types.unhandled,
44 + HttpServerRequest.HttpServerRequest
45 +>;
46 +
47 export const normalizeMcpHttpResponse = (
48 response: HttpServerResponse.HttpServerResponse,
49 ): HttpServerResponse.HttpServerResponse => {
@@ -41,27 +56,123 @@ export const normalizeMcpHttpResponse = (
56 : response;
57 };
58
59 +const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
60 + Effect.map(
61 + (registry): McpAuthMiddleware =>
62 + Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
63 + const request = yield* HttpServerRequest.HttpServerRequest;
64 + const authorization = request.headers.authorization;
65 + const token =
66 + authorization?.startsWith("Bearer ") === true
67 + ? authorization.slice("Bearer ".length).trim()
68 + : "";
69 + const invocation = yield* registry.resolve(token);
70 + if (!invocation) return unauthorized;
71 + return yield* httpEffect.pipe(
72 + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
73 + Effect.map(normalizeMcpHttpResponse),
74 + );
75 + }),
76 + ),
77 + Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
78 +);
79 +
80 const McpAuthMiddlewareLive = HttpRouter.middleware<{
81 provides: McpInvocationContext.McpInvocationContext;
46 -}>()(
47 - Effect.gen(function* () {
48 - const registry = yield* McpSessionRegistry.McpSessionRegistry;
49 - return Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
50 - const request = yield* HttpServerRequest.HttpServerRequest;
51 - const authorization = request.headers.authorization;
52 - const token =
53 - authorization?.startsWith("Bearer ") === true
54 - ? authorization.slice("Bearer ".length).trim()
55 - : "";
56 - const invocation = yield* registry.resolve(token);
57 - if (!invocation) return unauthorized;
58 - return yield* httpEffect.pipe(
59 - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
60 - Effect.map(normalizeMcpHttpResponse),
61 - );
82 +}>()(makeMcpAuthMiddleware).layer;
83 +
84 +const registerPreviewToolkit = Effect.fn("McpHttpServer.registerPreviewToolkit")(function* () {
85 + const server = yield* McpServer.McpServer;
86 + const built = yield* PreviewToolkit;
87 + const handleTool = built.handle as unknown as (
88 + name: keyof typeof built.tools,
89 + payload: unknown,
90 + ) => Effect.Effect<
91 + Stream.Stream<{ readonly encodedResult: unknown }, Error>,
92 + Error,
93 + McpInvocationContext.McpInvocationContext
94 + >;
95 + for (const tool of Object.values(built.tools)) {
96 + yield* server.addTool({
97 + tool: new McpSchema.Tool({
98 + name: tool.name,
99 + description: Tool.getDescription(tool),
100 + inputSchema: Tool.getJsonSchema(tool),
101 + annotations: {
102 + ...Context.getOption(tool.annotations, Tool.Title).pipe(
103 + Option.map((title) => ({ title })),
104 + Option.getOrUndefined,
105 + ),
106 + readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
107 + destructiveHint: Context.get(tool.annotations, Tool.Destructive),
108 + idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
109 + openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
110 + },
111 + }),
112 + annotations: tool.annotations,
113 + handle: (payload) =>
114 + handleTool(tool.name as keyof typeof built.tools, payload).pipe(
115 + Stream.unwrap,
116 + Stream.run(Sink.last()),
117 + Effect.flatMap(Effect.fromOption),
118 + Effect.matchCause({
119 + onFailure: (cause) =>
120 + new McpSchema.CallToolResult({
121 + isError: true,
122 + content: [{ type: "text", text: Cause.pretty(cause) }],
123 + }),
124 + onSuccess: (result) => {
125 + if (tool.name === "preview_snapshot") {
126 + const snapshot = result.encodedResult as {
127 + readonly screenshot: {
128 + readonly mimeType: "image/png";
129 + readonly data: string;
130 + readonly width: number;
131 + readonly height: number;
132 + };
133 + readonly [key: string]: unknown;
134 + };
135 + const { screenshot, ...page } = snapshot;
136 + const metadata = {
137 + ...page,
138 + screenshot: {
139 + mimeType: screenshot.mimeType,
140 + width: screenshot.width,
141 + height: screenshot.height,
142 + },
143 + };
144 + return new McpSchema.CallToolResult({
145 + isError: false,
146 + structuredContent: metadata,
147 + content: [
148 + { type: "text", text: JSON.stringify(metadata) },
149 + {
150 + type: "image",
151 + data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
152 + mimeType: screenshot.mimeType,
153 + },
154 + ],
155 + });
156 + }
157 + const encodedResultText = JSON.stringify(result.encodedResult) ?? "null";
158 + return new McpSchema.CallToolResult({
159 + isError: false,
160 + structuredContent:
161 + result.encodedResult !== null && typeof result.encodedResult === "object"
162 + ? result.encodedResult
163 + : undefined,
164 + content: [{ type: "text", text: encodedResultText }],
165 + });
166 + },
167 + }),
168 + ) as unknown as Effect.Effect<McpSchema.CallToolResult, never, McpSchema.McpServerClient>,
169 });
63 - }),
64 -).layer;
170 + }
171 +});
172 +
173 +export const PreviewToolkitRegistrationLive = Layer.effectDiscard(registerPreviewToolkit()).pipe(
174 + Layer.provide(PreviewToolkitHandlersLive),
175 +);
176
177 const McpTransportLive = McpServer.layerHttp({
178 name: "T3 Code",
@@ -69,98 +180,7 @@ const McpTransportLive = McpServer.layerHttp({
180 path: "/mcp",
181 }).pipe(Layer.provide(McpAuthMiddlewareLive));
182
72 -export const PreviewToolkitRegistrationLive = Layer.effectDiscard(
73 - Effect.gen(function* () {
74 - const server = yield* McpServer.McpServer;
75 - const built = yield* PreviewToolkit;
76 - const handleTool = built.handle as unknown as (
77 - name: keyof typeof built.tools,
78 - payload: unknown,
79 - ) => Effect.Effect<
80 - Stream.Stream<{ readonly encodedResult: unknown }, Error>,
81 - Error,
82 - McpInvocationContext.McpInvocationContext
83 - >;
84 - for (const tool of Object.values(built.tools)) {
85 - yield* server.addTool({
86 - tool: new McpSchema.Tool({
87 - name: tool.name,
88 - description: Tool.getDescription(tool),
89 - inputSchema: Tool.getJsonSchema(tool),
90 - annotations: {
91 - ...Context.getOption(tool.annotations, Tool.Title).pipe(
92 - Option.map((title) => ({ title })),
93 - Option.getOrUndefined,
94 - ),
95 - readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
96 - destructiveHint: Context.get(tool.annotations, Tool.Destructive),
97 - idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
98 - openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
99 - },
100 - }),
101 - annotations: tool.annotations,
102 - handle: (payload) =>
103 - handleTool(tool.name as keyof typeof built.tools, payload).pipe(
104 - Stream.unwrap,
105 - Stream.run(Sink.last()),
106 - Effect.flatMap(Effect.fromOption),
107 - Effect.matchCause({
108 - onFailure: (cause) =>
109 - new McpSchema.CallToolResult({
110 - isError: true,
111 - content: [{ type: "text", text: Cause.pretty(cause) }],
112 - }),
113 - onSuccess: (result) => {
114 - if (tool.name === "preview_snapshot") {
115 - const snapshot = result.encodedResult as {
116 - readonly screenshot: {
117 - readonly mimeType: "image/png";
118 - readonly data: string;
119 - readonly width: number;
120 - readonly height: number;
121 - };
122 - readonly [key: string]: unknown;
123 - };
124 - const { screenshot, ...page } = snapshot;
125 - const metadata = {
126 - ...page,
127 - screenshot: {
128 - mimeType: screenshot.mimeType,
129 - width: screenshot.width,
130 - height: screenshot.height,
131 - },
132 - };
133 - return new McpSchema.CallToolResult({
134 - isError: false,
135 - structuredContent: metadata,
136 - content: [
137 - { type: "text", text: JSON.stringify(metadata) },
138 - {
139 - type: "image",
140 - data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
141 - mimeType: screenshot.mimeType,
142 - },
143 - ],
144 - });
145 - }
146 - const encodedResultText = JSON.stringify(result.encodedResult) ?? "null";
147 - return new McpSchema.CallToolResult({
148 - isError: false,
149 - structuredContent:
150 - result.encodedResult !== null && typeof result.encodedResult === "object"
151 - ? result.encodedResult
152 - : undefined,
153 - content: [{ type: "text", text: encodedResultText }],
154 - });
155 - },
156 - }),
157 - ) as unknown as Effect.Effect<McpSchema.CallToolResult, never, McpSchema.McpServerClient>,
158 - });
159 - }
160 - }),
161 -).pipe(Layer.provide(PreviewToolkitHandlersLive));
162 -
163 -export const layer = Layer.mergeAll(PreviewToolkitRegistrationLive).pipe(
183 +export const layer = PreviewToolkitRegistrationLive.pipe(
184 Layer.provideMerge(McpTransportLive),
185 Layer.provide(PreviewAutomationBroker.layer),
186 );
apps/server/src/mcp/McpSessionRegistry.test.ts
+11 -9
@@ -18,15 +18,17 @@ const fakeEnvironment = ServerEnvironment.of({
18 });
19
20 const makeRegistry = (now: () => number) =>
21 - McpSessionRegistry.makeForTest({
22 - now,
23 - idleTimeoutMs: 100,
24 - maximumLifetimeMs: 1_000,
25 - }).pipe(
26 - Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
27 - Effect.provideService(ServerEnvironment, fakeEnvironment),
28 - Effect.provide(NodeServices.layer),
29 - );
21 + McpSessionRegistry.__testing
22 + .make({
23 + now,
24 + idleTimeoutMs: 100,
25 + maximumLifetimeMs: 1_000,
26 + })
27 + .pipe(
28 + Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
29 + Effect.provideService(ServerEnvironment, fakeEnvironment),
30 + Effect.provide(NodeServices.layer),
31 + );
32
33 it.effect("stores only a token hash, resolves the bearer token, and revokes by thread", () =>
34 Effect.gen(function* () {
apps/server/src/mcp/McpSessionRegistry.ts
+5 -2
@@ -184,8 +184,6 @@ export const layer: Layer.Layer<
184 ),
185 );
186
187 -export const makeForTest = make;
188 -
187 export const issueActiveMcpCredential = (
188 request: McpCredentialRequest,
189 ): Effect.Effect<McpIssuedCredential | undefined> =>
@@ -200,3 +198,8 @@ export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =
198
199 export const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
200 activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
201 +
202 +/** Exposed for tests. */
203 +export const __testing = {
204 + make,
205 +};
apps/server/src/mcp/PreviewAutomationBroker.test.ts
+3 -3
@@ -23,7 +23,7 @@ const scope = {
23 it.effect("routes a request to the focused owner and correlates its response", () =>
24 Effect.scoped(
25 Effect.gen(function* () {
26 - const broker = yield* PreviewAutomationBroker.makeForTest;
26 + const broker = yield* PreviewAutomationBroker.__testing.make();
27 const requests = yield* broker.connect("client-1");
28 yield* Stream.runForEach(requests, (request) =>
29 broker.respond({
@@ -56,7 +56,7 @@ it.effect("routes a request to the focused owner and correlates its response", (
56
57 it.effect("rejects calls when no focused owner exists", () =>
58 Effect.gen(function* () {
59 - const broker = yield* PreviewAutomationBroker.makeForTest;
59 + const broker = yield* PreviewAutomationBroker.__testing.make();
60 const error = yield* broker
61 .invoke<void>({ scope, operation: "status", input: {} })
62 .pipe(Effect.flip);
@@ -67,7 +67,7 @@ it.effect("rejects calls when no focused owner exists", () =>
67 it.effect("routes interactive commands to a hidden durable browser host", () =>
68 Effect.scoped(
69 Effect.gen(function* () {
70 - const broker = yield* PreviewAutomationBroker.makeForTest;
70 + const broker = yield* PreviewAutomationBroker.__testing.make();
71 const requests = yield* broker.connect("client-hidden");
72 yield* Stream.runForEach(requests, (request) =>
73 broker.respond({ requestId: request.requestId, ok: true }),
apps/server/src/mcp/PreviewAutomationBroker.ts
+12 -13
@@ -119,14 +119,12 @@ const makeResponseError = (
119 }
120 };
121
122 -const makeService = (): PreviewAutomationBrokerShape => {
123 - const state = Effect.runSync(
124 - Ref.make<BrokerState>({
125 - clients: new Map(),
126 - owners: new Map(),
127 - pending: new Map(),
128 - }),
129 - );
122 +const make = Effect.fn("PreviewAutomationBroker.make")(function* () {
123 + const state = yield* Ref.make<BrokerState>({
124 + clients: new Map(),
125 + owners: new Map(),
126 + pending: new Map(),
127 + });
128 let requestSequence = 0;
129
130 const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
@@ -297,10 +295,11 @@ const makeService = (): PreviewAutomationBrokerShape => {
295 });
296
297 return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
300 -};
298 +});
299
302 -const service = makeService();
303 -const make = Effect.succeed(service);
304 -export const layer = Layer.effect(PreviewAutomationBroker, make);
300 +export const layer = Layer.effect(PreviewAutomationBroker, make());
301
306 -export const makeForTest = Effect.sync(makeService);
302 +/** Exposed for tests. */
303 +export const __testing = {
304 + make,
305 +};
apps/server/src/preview/Manager.ts
+2 -2
@@ -127,7 +127,7 @@ const buildIdleSnapshot = (input: {
127 updatedAt: input.updatedAt,
128 });
129
130 -const make = Effect.gen(function* () {
130 +const make = Effect.fn("PreviewManager.make")(function* () {
131 const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
132 // Unbounded PubSub is fine here — events are tiny and we don't want to
133 // block publishers if a subscriber is slow. WS clients backpressure on
@@ -359,4 +359,4 @@ const make = Effect.gen(function* () {
359 } satisfies PreviewManagerShape;
360 });
361
362 -export const layer = Layer.effect(PreviewManager, make);
362 +export const layer = Layer.effect(PreviewManager, make());
apps/server/src/preview/PortScanner.test.ts
+71 -42
@@ -2,8 +2,9 @@ import * as net from "node:net";
2
3 import { it as effectIt } from "@effect/vitest";
4 import { ThreadId } from "@t3tools/contracts";
5 +import * as Net from "@t3tools/shared/Net";
6 import { Effect, Layer } from "effect";
6 -import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
7 +import { describe, expect, it } from "vite-plus/test";
8
9 import { ProcessRunner } from "../processRunner.ts";
10 import * as PortScanner from "./PortScanner.ts";
@@ -13,7 +14,60 @@ const { parseLsofOutput, parsePortFromLsofName, parseWindowsListenerOutput, serv
14 const TestProcessRunner = Layer.succeed(ProcessRunner, {
15 run: () => Effect.die("ProcessRunner should not be used by Windows TCP probe tests"),
16 });
16 -const TestPortDiscoveryLive = PortScanner.layer.pipe(Layer.provide(TestProcessRunner));
17 +const TestPortDiscoveryLive = PortScanner.layer.pipe(
18 + Layer.provide(Layer.mergeAll(TestProcessRunner, Net.layer)),
19 +);
20 +
21 +const openServer = (port: number): Effect.Effect<net.Server | null> =>
22 + Effect.callback((resume) => {
23 + const server = net.createServer();
24 + server.once("error", () => {
25 + resume(Effect.succeed(null));
26 + });
27 + server.listen(port, "127.0.0.1", () => {
28 + resume(Effect.succeed(server));
29 + });
30 + return Effect.sync(() => {
31 + server.close();
32 + });
33 + });
34 +
35 +const closeServer = (server: net.Server): Effect.Effect<void> =>
36 + Effect.callback((resume) => {
37 + server.close(() => resume(Effect.void));
38 + });
39 +
40 +const windowsPlatform = Effect.acquireRelease(
41 + Effect.sync(() => {
42 + const originalPlatform = process.platform;
43 + Object.defineProperty(process, "platform", { value: "win32", configurable: true });
44 + return originalPlatform;
45 + }),
46 + (originalPlatform) =>
47 + Effect.sync(() => {
48 + Object.defineProperty(process, "platform", {
49 + value: originalPlatform,
50 + configurable: true,
51 + });
52 + }),
53 +);
54 +
55 +const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
56 + ports: ReadonlyArray<number>,
57 +) {
58 + for (const port of ports) {
59 + const server = yield* openServer(port);
60 + if (server !== null) return { port, server };
61 + }
62 + return yield* Effect.die(
63 + new Error("No common development port was available for the preview scanner test"),
64 + );
65 +});
66 +
67 +const commonDevServer = Effect.acquireRelease(
68 + openCommonDevServer(PortScanner.COMMON_DEV_PORTS),
69 + ({ server }) => closeServer(server),
70 +);
71
72 describe("parsePortFromLsofName", () => {
73 it("parses *:port", () => {
@@ -180,51 +234,26 @@ describe("parseWindowsListenerOutput", () => {
234 * path (TCP-probe fallback) by monkey-patching `process.platform` for the
235 * duration of the test so we don't depend on `lsof` being installed.
236 */
183 -describe("PortDiscovery integration (TCP probe fallback)", () => {
184 - let originalPlatform: NodeJS.Platform;
185 - let server: net.Server;
186 - let port: number;
187 -
188 - beforeEach(async () => {
189 - originalPlatform = process.platform;
190 - Object.defineProperty(process, "platform", { value: "win32", configurable: true });
191 - for (const candidate of PortScanner.COMMON_DEV_PORTS) {
192 - const candidateServer = net.createServer();
193 - const listening = await new Promise<boolean>((resolve) => {
194 - candidateServer.once("error", () => resolve(false));
195 - candidateServer.listen(candidate, "127.0.0.1", () => resolve(true));
196 - });
197 - if (listening) {
198 - server = candidateServer;
199 - port = candidate;
200 - return;
201 - }
202 - candidateServer.close();
203 - }
204 - throw new Error("No common development port was available for the preview scanner test");
205 - });
206 -
207 - afterEach(async () => {
208 - Object.defineProperty(process, "platform", {
209 - value: originalPlatform,
210 - configurable: true,
211 - });
212 - await new Promise<void>((resolve) => server.close(() => resolve()));
213 - });
214 -
215 - effectIt.effect("scan() returns a server we just opened on a curated dev port", () =>
216 - Effect.gen(function* () {
237 +effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fallback)", (it) => {
238 + it.effect(
239 + "scan() returns a server we just opened on a curated dev port",
240 + Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
241 + yield* windowsPlatform;
242 + const { port } = yield* commonDevServer;
243 const scanner = yield* PortScanner.PortDiscovery;
244 const result = yield* scanner.scan();
245 const found = result.find((server) => server.port === port);
246 expect(found).toBeDefined();
247 expect(found?.host).toBe("localhost");
222 - }).pipe(Effect.provide(TestPortDiscoveryLive)),
248 + }),
249 );
250
225 - effectIt.effect("retain() drives an immediate broadcast to subscribers", () => {
226 - const received: number[] = [];
227 - return Effect.gen(function* () {
251 + it.effect(
252 + "retain() drives an immediate broadcast to subscribers",
253 + Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
254 + yield* windowsPlatform;
255 + const { port } = yield* commonDevServer;
256 + const received: number[] = [];
257 const scanner = yield* PortScanner.PortDiscovery;
258 const unsubscribe = yield* scanner.subscribe((servers) =>
259 Effect.sync(() => {
@@ -235,6 +264,6 @@ describe("PortDiscovery integration (TCP probe fallback)", () => {
264 unsubscribe();
265 release();
266 expect(received).toContain(port);
238 - }).pipe(Effect.provide(TestPortDiscoveryLive));
239 - });
267 + }),
268 + );
269 });
apps/server/src/preview/PortScanner.ts
+41 -51
@@ -5,15 +5,14 @@
5 * stable line-prefixed field format; this is the only `lsof` flag set we rely
6 * on).
7 *
8 - * Windows / lsof missing: TCP-connects to a curated list of common dev ports
9 - * on 127.0.0.1.
8 + * Windows / lsof missing: checks a curated list of common dev ports through
9 + * the shared Net service.
10 *
11 * Polling is reference-counted via `retain()`. A single layer-scoped fiber
12 * polls forever, but each tick is a no-op when the retain count is zero.
13 */
14 -import * as net from "node:net";
15 -
14 import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
15 +import * as Net from "@t3tools/shared/Net";
16 import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
17 import { Cause, Context, Duration, Effect, Layer, Ref, Schedule } from "effect";
18
@@ -45,7 +44,6 @@ export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
44 ]);
45
46 const POLL_INTERVAL = Duration.seconds(3);
48 -const TCP_PROBE_TIMEOUT_MS = 200;
47 const LSOF_TIMEOUT_MS = 5_000;
48 const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
49
@@ -148,40 +146,6 @@ const parseWindowsListenerOutput = (
146 return [...seen.values()].toSorted((left, right) => left.port - right.port);
147 };
148
151 -const probeTcpPort = (port: number): Promise<boolean> =>
152 - new Promise((resolve) => {
153 - const socket = new net.Socket();
154 - let settled = false;
155 - const finish = (ok: boolean) => {
156 - if (settled) return;
157 - settled = true;
158 - socket.destroy();
159 - resolve(ok);
160 - };
161 - socket.setTimeout(TCP_PROBE_TIMEOUT_MS);
162 - socket.once("timeout", () => finish(false));
163 - socket.once("error", () => finish(false));
164 - socket.once("connect", () => finish(true));
165 - socket.connect({ host: "127.0.0.1", port });
166 - });
167 -
168 -const probeCommonPorts = (): Effect.Effect<ReadonlyArray<DiscoveredLocalServer>> =>
169 - Effect.promise(async () => {
170 - const results = await Promise.all(
171 - COMMON_DEV_PORTS.map(async (port) => ({ port, listening: await probeTcpPort(port) })),
172 - );
173 - return results
174 - .filter((r) => r.listening)
175 - .map<DiscoveredLocalServer>((r) => ({
176 - host: "localhost",
177 - port: r.port,
178 - url: `http://localhost:${r.port}`,
179 - processName: null,
180 - pid: null,
181 - terminal: null,
182 - }));
183 - });
184 -
149 const serversEqual = (
150 left: ReadonlyArray<DiscoveredLocalServer>,
151 right: ReadonlyArray<DiscoveredLocalServer>,
@@ -206,7 +170,8 @@ const serversEqual = (
170 return true;
171 };
172
209 -const make = Effect.gen(function* () {
173 +const make = Effect.fn("PortDiscovery.make")(function* () {
174 + const net = yield* Net.NetService;
175 const processRunner = yield* ProcessRunner;
176 const stateRef = yield* Ref.make<ScannerState>({
177 lastSnapshot: [],
@@ -224,6 +189,30 @@ const make = Effect.gen(function* () {
189 // be a synchronous side-effect-only function.
190 let retainCount = 0;
191
192 + const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
193 + const results = yield* Effect.forEach(
194 + COMMON_DEV_PORTS,
195 + (port) =>
196 + net.isPortAvailableOnLoopback(port).pipe(
197 + Effect.map((available) => ({
198 + port,
199 + listening: !available,
200 + })),
201 + ),
202 + { concurrency: "unbounded" },
203 + );
204 + return results
205 + .filter((result) => result.listening)
206 + .map<DiscoveredLocalServer>((result) => ({
207 + host: "localhost",
208 + port: result.port,
209 + url: `http://localhost:${result.port}`,
210 + processName: null,
211 + pid: null,
212 + terminal: null,
213 + }));
214 + });
215 +
216 const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
217 const terminalByProcessId = new Map<number, TerminalProcessOwner>();
218 for (const registration of terminalProcesses.values()) {
@@ -268,14 +257,15 @@ const make = Effect.gen(function* () {
257 const broadcast = (servers: ReadonlyArray<DiscoveredLocalServer>): Effect.Effect<void> =>
258 Effect.forEach(Array.from(listeners), (listener) => listener(servers), { discard: true });
259
271 - const pollTick = Effect.gen(function* () {
272 - if (retainCount <= 0) return;
273 - const next = yield* scanOnce();
274 - const state = yield* Ref.get(stateRef);
275 - if (serversEqual(state.lastSnapshot, next)) return;
276 - yield* Ref.update(stateRef, (s) => ({ ...s, lastSnapshot: next }));
277 - yield* broadcast(next);
278 - }).pipe(
260 + const pollTick = Effect.fn("PortDiscovery.pollTick")(
261 + function* () {
262 + if (retainCount <= 0) return;
263 + const next = yield* scanOnce();
264 + const state = yield* Ref.get(stateRef);
265 + if (serversEqual(state.lastSnapshot, next)) return;
266 + yield* Ref.update(stateRef, (s) => ({ ...s, lastSnapshot: next }));
267 + yield* broadcast(next);
268 + },
269 Effect.catchCause((cause: Cause.Cause<never>) =>
270 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
271 ),
@@ -283,7 +273,7 @@ const make = Effect.gen(function* () {
273
274 // Single layer-scoped polling fiber. Ticks are no-ops when no client is
275 // currently retained, so the cost is one Ref.get every POLL_INTERVAL.
286 - yield* Effect.forkScoped(pollTick.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
276 + yield* Effect.forkScoped(pollTick().pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
277
278 const retain: PortDiscoveryShape["retain"] = Effect.fn("PortDiscovery.retain")(function* () {
279 const wasIdle = retainCount === 0;
@@ -291,7 +281,7 @@ const make = Effect.gen(function* () {
281 if (wasIdle) {
282 // Run an immediate scan + broadcast so the new retainer doesn't have
283 // to wait up to POLL_INTERVAL for the first emission.
294 - yield* pollTick;
284 + yield* pollTick();
285 }
286 let released = false;
287 return () => {
@@ -349,7 +339,7 @@ const make = Effect.gen(function* () {
339 } satisfies PortDiscoveryShape;
340 });
341
352 -export const layer = Layer.effect(PortDiscovery, make);
342 +export const layer = Layer.effect(PortDiscovery, make());
343
344 /** Exposed for tests. */
345 export const __testing = {
packages/contracts/src/ipc.ts
+252 -1
@@ -66,7 +66,7 @@ import type {
66 PreviewReportStatusInput,
67 PreviewSessionSnapshot,
68 } from "./preview.ts";
69 -import type {
69 +import {
70 PreviewAutomationClickInput,
71 PreviewAutomationEvaluateInput,
72 PreviewAutomationOwner,
@@ -455,6 +455,42 @@ export interface DesktopPreviewTabState {
455 updatedAt: string;
456 }
457
458 +export const DesktopPreviewTabIdSchema = Schema.String.check(Schema.isTrimmed()).check(
459 + Schema.isNonEmpty(),
460 +);
461 +
462 +export const DesktopPreviewNavStatusSchema = Schema.Union([
463 + Schema.Struct({ kind: Schema.Literal("Idle") }),
464 + Schema.Struct({
465 + kind: Schema.Literal("Loading"),
466 + url: Schema.String,
467 + title: Schema.String,
468 + }),
469 + Schema.Struct({
470 + kind: Schema.Literal("Success"),
471 + url: Schema.String,
472 + title: Schema.String,
473 + }),
474 + Schema.Struct({
475 + kind: Schema.Literal("LoadFailed"),
476 + url: Schema.String,
477 + title: Schema.String,
478 + code: Schema.Number,
479 + description: Schema.String,
480 + }),
481 +]);
482 +
483 +export const DesktopPreviewTabStateSchema: Schema.Codec<DesktopPreviewTabState> = Schema.Struct({
484 + tabId: DesktopPreviewTabIdSchema,
485 + webContentsId: Schema.NullOr(Schema.Int),
486 + navStatus: DesktopPreviewNavStatusSchema,
487 + canGoBack: Schema.Boolean,
488 + canGoForward: Schema.Boolean,
489 + zoomFactor: Schema.Number,
490 + controller: Schema.Literals(["human", "agent", "none"]),
491 + updatedAt: Schema.String,
492 +});
493 +
494 export interface DesktopPreviewPointerEvent {
495 tabId: string;
496 phase: "move" | "click";
@@ -464,6 +500,16 @@ export interface DesktopPreviewPointerEvent {
500 createdAt: string;
501 }
502
503 +export const DesktopPreviewPointerEventSchema: Schema.Codec<DesktopPreviewPointerEvent> =
504 + Schema.Struct({
505 + tabId: DesktopPreviewTabIdSchema,
506 + phase: Schema.Literals(["move", "click"]),
507 + x: Schema.Number,
508 + y: Schema.Number,
509 + sequence: Schema.Int,
510 + createdAt: Schema.String,
511 + });
512 +
513 /**
514 * Static config a renderer needs to mount a preview `<webview>`. Returned
515 * atomically by `DesktopPreviewBridge.getPreviewConfig()` so the renderer
@@ -487,6 +533,13 @@ export interface DesktopPreviewWebviewConfig {
533 preloadUrl: string | null;
534 }
535
536 +export const DesktopPreviewWebviewConfigSchema: Schema.Codec<DesktopPreviewWebviewConfig> =
537 + Schema.Struct({
538 + partition: Schema.String,
539 + webPreferences: Schema.String,
540 + preloadUrl: Schema.NullOr(Schema.String),
541 + });
542 +
543 export interface DesktopPreviewAnnotationTheme {
544 colorScheme: "light" | "dark";
545 radius: string;
@@ -507,6 +560,27 @@ export interface DesktopPreviewAnnotationTheme {
560 fontMono: string;
561 }
562
563 +export const DesktopPreviewAnnotationThemeSchema: Schema.Codec<DesktopPreviewAnnotationTheme> =
564 + Schema.Struct({
565 + colorScheme: Schema.Literals(["light", "dark"]),
566 + radius: Schema.String,
567 + background: Schema.String,
568 + foreground: Schema.String,
569 + popover: Schema.String,
570 + popoverForeground: Schema.String,
571 + primary: Schema.String,
572 + primaryForeground: Schema.String,
573 + muted: Schema.String,
574 + mutedForeground: Schema.String,
575 + accent: Schema.String,
576 + accentForeground: Schema.String,
577 + border: Schema.String,
578 + input: Schema.String,
579 + ring: Schema.String,
580 + fontSans: Schema.String,
581 + fontMono: Schema.String,
582 + });
583 +
584 export interface DesktopPreviewRecordingFrame {
585 tabId: string;
586 data: string;
@@ -515,6 +589,15 @@ export interface DesktopPreviewRecordingFrame {
589 receivedAt: string;
590 }
591
592 +export const DesktopPreviewRecordingFrameSchema: Schema.Codec<DesktopPreviewRecordingFrame> =
593 + Schema.Struct({
594 + tabId: DesktopPreviewTabIdSchema,
595 + data: Schema.String,
596 + width: Schema.Number,
597 + height: Schema.Number,
598 + receivedAt: Schema.String,
599 + });
600 +
601 export interface DesktopPreviewRecordingArtifact {
602 id: string;
603 tabId: string;
@@ -524,6 +607,16 @@ export interface DesktopPreviewRecordingArtifact {
607 createdAt: string;
608 }
609
610 +export const DesktopPreviewRecordingArtifactSchema: Schema.Codec<DesktopPreviewRecordingArtifact> =
611 + Schema.Struct({
612 + id: Schema.String,
613 + tabId: DesktopPreviewTabIdSchema,
614 + path: Schema.String,
615 + mimeType: Schema.String,
616 + sizeBytes: Schema.Int,
617 + createdAt: Schema.String,
618 + });
619 +
620 export interface DesktopPreviewScreenshotArtifact {
621 id: string;
622 tabId: string;
@@ -533,6 +626,16 @@ export interface DesktopPreviewScreenshotArtifact {
626 createdAt: string;
627 }
628
629 +export const DesktopPreviewScreenshotArtifactSchema: Schema.Codec<DesktopPreviewScreenshotArtifact> =
630 + Schema.Struct({
631 + id: Schema.String,
632 + tabId: DesktopPreviewTabIdSchema,
633 + path: Schema.String,
634 + mimeType: Schema.Literal("image/png"),
635 + sizeBytes: Schema.Int,
636 + createdAt: Schema.String,
637 + });
638 +
639 /**
640 * Single stack frame captured by react-grab's `getElementContext`. We surface
641 * the source file/line so coding agents can jump straight to the JSX that
@@ -545,6 +648,13 @@ export interface PickedElementStackFrame {
648 columnNumber: number | null;
649 }
650
651 +export const PickedElementStackFrameSchema: Schema.Codec<PickedElementStackFrame> = Schema.Struct({
652 + functionName: Schema.NullOr(Schema.String),
653 + fileName: Schema.NullOr(Schema.String),
654 + lineNumber: Schema.NullOr(Schema.Number),
655 + columnNumber: Schema.NullOr(Schema.Number),
656 +});
657 +
658 /**
659 * A successful element pick from the preview webview. All fields are
660 * best-effort — pages that don't ship a React fiber tree (or aren't running
@@ -574,6 +684,19 @@ export interface PickedElementPayload {
684 pickedAt: string;
685 }
686
687 +export const PickedElementPayloadSchema: Schema.Codec<PickedElementPayload> = Schema.Struct({
688 + pageUrl: Schema.String,
689 + pageTitle: Schema.NullOr(Schema.String),
690 + tagName: Schema.String,
691 + selector: Schema.NullOr(Schema.String),
692 + htmlPreview: Schema.String,
693 + componentName: Schema.NullOr(Schema.String),
694 + source: Schema.NullOr(PickedElementStackFrameSchema),
695 + stack: Schema.Array(PickedElementStackFrameSchema),
696 + styles: Schema.String,
697 + pickedAt: Schema.String,
698 +});
699 +
700 export interface PreviewAnnotationRect {
701 x: number;
702 y: number;
@@ -581,22 +704,47 @@ export interface PreviewAnnotationRect {
704 height: number;
705 }
706
707 +export const PreviewAnnotationRectSchema: Schema.Codec<PreviewAnnotationRect> = Schema.Struct({
708 + x: Schema.Number,
709 + y: Schema.Number,
710 + width: Schema.Number,
711 + height: Schema.Number,
712 +});
713 +
714 export interface PreviewAnnotationPoint {
715 x: number;
716 y: number;
717 }
718
719 +export const PreviewAnnotationPointSchema: Schema.Codec<PreviewAnnotationPoint> = Schema.Struct({
720 + x: Schema.Number,
721 + y: Schema.Number,
722 +});
723 +
724 export interface PreviewAnnotationElementTarget {
725 id: string;
726 element: PickedElementPayload;
727 rect: PreviewAnnotationRect;
728 }
729
730 +export const PreviewAnnotationElementTargetSchema: Schema.Codec<PreviewAnnotationElementTarget> =
731 + Schema.Struct({
732 + id: Schema.String,
733 + element: PickedElementPayloadSchema,
734 + rect: PreviewAnnotationRectSchema,
735 + });
736 +
737 export interface PreviewAnnotationRegionTarget {
738 id: string;
739 rect: PreviewAnnotationRect;
740 }
741
742 +export const PreviewAnnotationRegionTargetSchema: Schema.Codec<PreviewAnnotationRegionTarget> =
743 + Schema.Struct({
744 + id: Schema.String,
745 + rect: PreviewAnnotationRectSchema,
746 + });
747 +
748 export interface PreviewAnnotationStrokeTarget {
749 id: string;
750 color: string;
@@ -605,6 +753,15 @@ export interface PreviewAnnotationStrokeTarget {
753 bounds: PreviewAnnotationRect;
754 }
755
756 +export const PreviewAnnotationStrokeTargetSchema: Schema.Codec<PreviewAnnotationStrokeTarget> =
757 + Schema.Struct({
758 + id: Schema.String,
759 + color: Schema.String,
760 + width: Schema.Number,
761 + points: Schema.Array(PreviewAnnotationPointSchema),
762 + bounds: PreviewAnnotationRectSchema,
763 + });
764 +
765 export interface PreviewAnnotationStyleChange {
766 targetId: string;
767 selector: string | null;
@@ -613,6 +770,15 @@ export interface PreviewAnnotationStyleChange {
770 value: string;
771 }
772
773 +export const PreviewAnnotationStyleChangeSchema: Schema.Codec<PreviewAnnotationStyleChange> =
774 + Schema.Struct({
775 + targetId: Schema.String,
776 + selector: Schema.NullOr(Schema.String),
777 + property: Schema.String,
778 + previousValue: Schema.String,
779 + value: Schema.String,
780 + });
781 +
782 export interface PreviewAnnotationScreenshot {
783 dataUrl: string;
784 width: number;
@@ -620,6 +786,14 @@ export interface PreviewAnnotationScreenshot {
786 cropRect: PreviewAnnotationRect;
787 }
788
789 +export const PreviewAnnotationScreenshotSchema: Schema.Codec<PreviewAnnotationScreenshot> =
790 + Schema.Struct({
791 + dataUrl: Schema.String,
792 + width: Schema.Number,
793 + height: Schema.Number,
794 + cropRect: PreviewAnnotationRectSchema,
795 + });
796 +
797 /**
798 * A submitted preview annotation. One annotation may reference multiple DOM
799 * elements, freeform regions, and ink strokes. The desktop main process adds
@@ -638,6 +812,83 @@ export interface PreviewAnnotationPayload {
812 createdAt: string;
813 }
814
815 +export const PreviewAnnotationPayloadSchema: Schema.Codec<PreviewAnnotationPayload> = Schema.Struct(
816 + {
817 + id: Schema.String,
818 + pageUrl: Schema.String,
819 + pageTitle: Schema.NullOr(Schema.String),
820 + comment: Schema.String,
821 + elements: Schema.Array(PreviewAnnotationElementTargetSchema),
822 + regions: Schema.Array(PreviewAnnotationRegionTargetSchema),
823 + strokes: Schema.Array(PreviewAnnotationStrokeTargetSchema),
824 + styleChanges: Schema.Array(PreviewAnnotationStyleChangeSchema),
825 + screenshot: Schema.NullOr(PreviewAnnotationScreenshotSchema),
826 + createdAt: Schema.String,
827 + },
828 +);
829 +
830 +export const DesktopPreviewTabInputSchema = Schema.Struct({
831 + tabId: DesktopPreviewTabIdSchema,
832 +});
833 +
834 +export const DesktopPreviewRegisterWebviewInputSchema = Schema.Struct({
835 + tabId: DesktopPreviewTabIdSchema,
836 + webContentsId: Schema.Int.check(Schema.isGreaterThan(0)),
837 +});
838 +
839 +export const DesktopPreviewNavigateInputSchema = Schema.Struct({
840 + tabId: DesktopPreviewTabIdSchema,
841 + url: Schema.String,
842 +});
843 +
844 +export const DesktopPreviewConfigInputSchema = Schema.Struct({
845 + environmentId: EnvironmentId,
846 +});
847 +
848 +export const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({
849 + theme: DesktopPreviewAnnotationThemeSchema,
850 +});
851 +
852 +export const DesktopPreviewArtifactInputSchema = Schema.Struct({
853 + path: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),
854 +});
855 +
856 +export const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({
857 + tabId: DesktopPreviewTabIdSchema,
858 + mimeType: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),
859 + data: Schema.Uint8Array,
860 +});
861 +
862 +export const DesktopPreviewAutomationClickInputSchema = Schema.Struct({
863 + tabId: DesktopPreviewTabIdSchema,
864 + input: PreviewAutomationClickInput,
865 +});
866 +
867 +export const DesktopPreviewAutomationTypeInputSchema = Schema.Struct({
868 + tabId: DesktopPreviewTabIdSchema,
869 + input: PreviewAutomationTypeInput,
870 +});
871 +
872 +export const DesktopPreviewAutomationPressInputSchema = Schema.Struct({
873 + tabId: DesktopPreviewTabIdSchema,
874 + input: PreviewAutomationPressInput,
875 +});
876 +
877 +export const DesktopPreviewAutomationScrollInputSchema = Schema.Struct({
878 + tabId: DesktopPreviewTabIdSchema,
879 + input: PreviewAutomationScrollInput,
880 +});
881 +
882 +export const DesktopPreviewAutomationEvaluateInputSchema = Schema.Struct({
883 + tabId: DesktopPreviewTabIdSchema,
884 + input: PreviewAutomationEvaluateInput,
885 +});
886 +
887 +export const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({
888 + tabId: DesktopPreviewTabIdSchema,
889 + input: PreviewAutomationWaitForInput,
890 +});
891 +
892 export interface DesktopBridge {
893 getAppBranding: () => DesktopAppBranding | null;
894 getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;