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
This commit is contained in:
1 parent
f7c422d581
commit
3d9e8dea7d
33 files changed
+2618
-1845
No files matched your search
@@ -7,9 +7,9 @@ import { compile } from "tailwindcss";
|
||||
|
||||
const directory = dirname(fileURLToPath(import.meta.url));
|
||||
const appRoot = join(directory, "..");
|
||||
const sourcePath = join(appRoot, "src", "preview-annotation.css");
|
||||
const preloadPath = join(appRoot, "src", "preview-pick-preload.ts");
|
||||
const outputPath = join(appRoot, "src", "preview-annotation-styles.generated.ts");
|
||||
const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
|
||||
const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
|
||||
const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
|
||||
const require = createRequire(import.meta.url);
|
||||
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ const bootstrap = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
yield* installDesktopIpcHandlers;
|
||||
yield* installDesktopIpcHandlers();
|
||||
yield* logBootstrapInfo("bootstrap ipc handlers registered");
|
||||
|
||||
if (!(yield* Ref.get(state.quitting))) {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { previewViewManager } from "../preview-view-manager.ts";
|
||||
import * as DesktopIpc from "./DesktopIpc.ts";
|
||||
import {
|
||||
clearCloudAuthToken,
|
||||
@@ -50,12 +48,11 @@ import {
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import { previewMethods } from "./methods/preview.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
previewViewManager.configureArtifactDirectory(environment.browserArtifactsDir);
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
@@ -97,7 +94,7 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
yield* ipc.handle(downloadUpdate);
|
||||
yield* ipc.handle(installUpdate);
|
||||
yield* ipc.handle(checkForUpdate);
|
||||
for (const previewMethod of previewMethods) {
|
||||
for (const previewMethod of PreviewIpc.methods) {
|
||||
yield* ipc.handle(previewMethod);
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
|
||||
});
|
||||
@@ -1,8 +1,19 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const fromPartition = vi.fn(() => {
|
||||
throw new Error("Session can only be received when app is ready");
|
||||
});
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import * as PreviewIpc from "./preview.ts";
|
||||
|
||||
const { fromPartition } = vi.hoisted(() => ({
|
||||
fromPartition: vi.fn(() => {
|
||||
throw new Error("Session can only be received when app is ready");
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
BrowserWindow: {
|
||||
@@ -25,4 +36,19 @@ describe("preview IPC methods", () => {
|
||||
await expect(import("./preview.ts")).resolves.toBeDefined();
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
|
||||
Effect.map(
|
||||
PreviewIpc.registerWebview
|
||||
.handler({ tabId: "tab-1", webContentsId: 0 })
|
||||
.pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
|
||||
(exit) => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Cause.findErrorOption(exit.cause);
|
||||
expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,251 +1,378 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { DesktopPreviewAnnotationTheme } from "@t3tools/contracts";
|
||||
import {
|
||||
DesktopPreviewAnnotationThemeInputSchema,
|
||||
DesktopPreviewArtifactInputSchema,
|
||||
DesktopPreviewAutomationClickInputSchema,
|
||||
DesktopPreviewAutomationEvaluateInputSchema,
|
||||
DesktopPreviewAutomationPressInputSchema,
|
||||
DesktopPreviewAutomationScrollInputSchema,
|
||||
DesktopPreviewAutomationTypeInputSchema,
|
||||
DesktopPreviewAutomationWaitForInputSchema,
|
||||
DesktopPreviewConfigInputSchema,
|
||||
DesktopPreviewNavigateInputSchema,
|
||||
DesktopPreviewRecordingArtifactSchema,
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { BrowserWindow } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { previewViewManager } from "../../preview-view-manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview-webview-preferences.ts";
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import type { DesktopIpcMethod } from "../DesktopIpc.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
previewViewManager.onStateChange((tabId, state) => {
|
||||
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
|
||||
window.webContents.send(channel, ...args);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
previewViewManager.onRecordingFrame((frame) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
previewViewManager.onPointerEvent((event) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const tabIdFrom = (raw: unknown): string => {
|
||||
if (typeof raw !== "object" || raw === null || !("tabId" in raw)) {
|
||||
throw new Error("preview tab id is required");
|
||||
}
|
||||
const tabId = raw.tabId;
|
||||
if (typeof tabId !== "string" || tabId.trim().length === 0) {
|
||||
throw new Error("preview tab id must be a non-empty string");
|
||||
}
|
||||
return tabId;
|
||||
};
|
||||
|
||||
const inputFrom = (raw: unknown): unknown => {
|
||||
if (typeof raw !== "object" || raw === null || !("input" in raw)) {
|
||||
throw new Error("preview automation input is required");
|
||||
}
|
||||
return raw.input;
|
||||
};
|
||||
export const installPreviewEventForwarding = Effect.fn(
|
||||
"desktop.ipc.preview.installEventForwarding",
|
||||
)(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.subscribeStateChanges((tabId, state) => {
|
||||
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
|
||||
});
|
||||
yield* manager.subscribeRecordingFrames((frame) => {
|
||||
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
|
||||
});
|
||||
yield* manager.subscribePointerEvents((event) => {
|
||||
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
|
||||
});
|
||||
});
|
||||
|
||||
const annotationThemeFrom = (raw: unknown): DesktopPreviewAnnotationTheme => {
|
||||
if (typeof raw !== "object" || raw === null || !("theme" in raw)) {
|
||||
throw new Error("preview annotation theme is required");
|
||||
}
|
||||
const theme = raw.theme;
|
||||
if (typeof theme !== "object" || theme === null) {
|
||||
throw new Error("preview annotation theme must be an object");
|
||||
}
|
||||
const record = theme as Record<string, unknown>;
|
||||
const stringKeys = [
|
||||
"radius",
|
||||
"background",
|
||||
"foreground",
|
||||
"popover",
|
||||
"popoverForeground",
|
||||
"primary",
|
||||
"primaryForeground",
|
||||
"muted",
|
||||
"mutedForeground",
|
||||
"accent",
|
||||
"accentForeground",
|
||||
"border",
|
||||
"input",
|
||||
"ring",
|
||||
"fontSans",
|
||||
"fontMono",
|
||||
] as const;
|
||||
for (const key of stringKeys) {
|
||||
if (typeof record[key] !== "string" || record[key].length === 0) {
|
||||
throw new Error(`preview annotation theme ${key} must be a non-empty string`);
|
||||
}
|
||||
}
|
||||
if (record["colorScheme"] !== "light" && record["colorScheme"] !== "dark") {
|
||||
throw new Error("preview annotation theme colorScheme must be light or dark");
|
||||
}
|
||||
return record as unknown as DesktopPreviewAnnotationTheme;
|
||||
};
|
||||
export const createTab = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.createTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
class PreviewIpcError extends Data.TaggedError("PreviewIpcError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export const closeTab = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.closeTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
const method = (
|
||||
export const registerWebview = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
|
||||
payload: DesktopPreviewRegisterWebviewInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.registerWebview(tabId, webContentsId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const navigate = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
|
||||
payload: DesktopPreviewNavigateInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.navigate(tabId, url);
|
||||
}),
|
||||
});
|
||||
|
||||
const tabMethod = (
|
||||
channel: string,
|
||||
handler: (raw: unknown) => unknown | Promise<unknown>,
|
||||
): DesktopIpcMethod<PreviewIpcError, never> => ({
|
||||
channel,
|
||||
handler: (raw) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Promise.resolve(handler(raw)),
|
||||
catch: (cause) => new PreviewIpcError({ cause }),
|
||||
name: string,
|
||||
invoke: (
|
||||
manager: PreviewManager.PreviewManagerShape,
|
||||
tabId: string,
|
||||
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
|
||||
) =>
|
||||
makeIpcMethod({
|
||||
channel,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn(name)(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* invoke(manager, tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const goBack = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_BACK_CHANNEL,
|
||||
"desktop.ipc.preview.goBack",
|
||||
(manager, tabId) => manager.goBack(tabId),
|
||||
);
|
||||
export const goForward = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
|
||||
"desktop.ipc.preview.goForward",
|
||||
(manager, tabId) => manager.goForward(tabId),
|
||||
);
|
||||
export const refresh = tabMethod(
|
||||
IpcChannels.PREVIEW_REFRESH_CHANNEL,
|
||||
"desktop.ipc.preview.refresh",
|
||||
(manager, tabId) => manager.refresh(tabId),
|
||||
);
|
||||
export const zoomIn = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
|
||||
"desktop.ipc.preview.zoomIn",
|
||||
(manager, tabId) => manager.zoomIn(tabId),
|
||||
);
|
||||
export const zoomOut = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
|
||||
"desktop.ipc.preview.zoomOut",
|
||||
(manager, tabId) => manager.zoomOut(tabId),
|
||||
);
|
||||
export const resetZoom = tabMethod(
|
||||
IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
|
||||
"desktop.ipc.preview.resetZoom",
|
||||
(manager, tabId) => manager.resetZoom(tabId),
|
||||
);
|
||||
export const hardReload = tabMethod(
|
||||
IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
(manager, tabId) => manager.openDevTools(tabId),
|
||||
);
|
||||
export const cancelPickElement = tabMethod(
|
||||
IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
|
||||
"desktop.ipc.preview.cancelPickElement",
|
||||
(manager, tabId) => manager.cancelPickElement(tabId),
|
||||
);
|
||||
export const startRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
|
||||
"desktop.ipc.preview.startRecording",
|
||||
(manager, tabId) => manager.startRecording(tabId),
|
||||
);
|
||||
export const stopRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
|
||||
"desktop.ipc.preview.stopRecording",
|
||||
(manager, tabId) => manager.stopRecording(tabId),
|
||||
);
|
||||
|
||||
export const clearCookies = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCookies();
|
||||
}),
|
||||
});
|
||||
|
||||
export const previewMethods = [
|
||||
method(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, (raw) =>
|
||||
previewViewManager.createTab(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, (raw) =>
|
||||
previewViewManager.closeTab(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, (raw) => {
|
||||
const tabId = tabIdFrom(raw);
|
||||
const webContentsId =
|
||||
typeof raw === "object" && raw !== null && "webContentsId" in raw ? raw.webContentsId : null;
|
||||
if (
|
||||
typeof webContentsId !== "number" ||
|
||||
!Number.isInteger(webContentsId) ||
|
||||
webContentsId <= 0
|
||||
) {
|
||||
throw new Error("preview webContentsId must be a positive integer");
|
||||
}
|
||||
return previewViewManager.registerWebview(tabId, webContentsId);
|
||||
export const clearCache = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCache();
|
||||
}),
|
||||
method(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, (raw) => {
|
||||
const tabId = tabIdFrom(raw);
|
||||
const url = typeof raw === "object" && raw !== null && "url" in raw ? raw.url : null;
|
||||
if (typeof url !== "string") throw new Error("preview url must be a string");
|
||||
return previewViewManager.navigate(tabId, url);
|
||||
}),
|
||||
method(IpcChannels.PREVIEW_GO_BACK_CHANNEL, (raw) => previewViewManager.goBack(tabIdFrom(raw))),
|
||||
method(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, (raw) =>
|
||||
previewViewManager.goForward(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_REFRESH_CHANNEL, (raw) => previewViewManager.refresh(tabIdFrom(raw))),
|
||||
method(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, (raw) => previewViewManager.zoomIn(tabIdFrom(raw))),
|
||||
method(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, (raw) => previewViewManager.zoomOut(tabIdFrom(raw))),
|
||||
method(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, (raw) =>
|
||||
previewViewManager.resetZoom(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, (raw) =>
|
||||
previewViewManager.hardReload(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, (raw) =>
|
||||
previewViewManager.openDevTools(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, () => previewViewManager.clearCookies()),
|
||||
method(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL, () => previewViewManager.clearCache()),
|
||||
method(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, (raw) => {
|
||||
const environmentId =
|
||||
typeof raw === "object" && raw !== null && "environmentId" in raw ? raw.environmentId : null;
|
||||
if (typeof environmentId !== "string" || environmentId.length === 0) {
|
||||
throw new Error("preview environment id is required");
|
||||
}
|
||||
previewViewManager.getBrowserSession(environmentId);
|
||||
const preloadPath = `${__dirname}/preview-pick-preload.cjs`;
|
||||
});
|
||||
|
||||
export const getPreviewConfig = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
|
||||
payload: DesktopPreviewConfigInputSchema,
|
||||
result: DesktopPreviewWebviewConfigSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.getBrowserSession(environmentId);
|
||||
return {
|
||||
partition: previewViewManager.getBrowserPartition(environmentId),
|
||||
partition: manager.getBrowserPartition(environmentId),
|
||||
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
|
||||
preloadUrl: pathToFileURL(preloadPath).href,
|
||||
preloadUrl: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
|
||||
};
|
||||
}),
|
||||
method(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, (raw) =>
|
||||
previewViewManager.setAnnotationTheme(annotationThemeFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, (raw) =>
|
||||
previewViewManager.pickElement(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, (raw) =>
|
||||
previewViewManager.cancelPickElement(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, (raw) =>
|
||||
previewViewManager.captureScreenshot(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, (raw) => {
|
||||
const path = typeof raw === "object" && raw !== null && "path" in raw ? raw.path : null;
|
||||
if (typeof path !== "string" || path.trim().length === 0) {
|
||||
throw new Error("preview artifact path is required");
|
||||
}
|
||||
return previewViewManager.revealArtifact(path);
|
||||
});
|
||||
|
||||
export const setAnnotationTheme = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
|
||||
payload: DesktopPreviewAnnotationThemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setAnnotationTheme(theme);
|
||||
}),
|
||||
method(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, (raw) => {
|
||||
const path = typeof raw === "object" && raw !== null && "path" in raw ? raw.path : null;
|
||||
if (typeof path !== "string" || path.trim().length === 0) {
|
||||
throw new Error("preview artifact path is required");
|
||||
}
|
||||
return previewViewManager.copyArtifactToClipboard(path);
|
||||
});
|
||||
|
||||
export const pickElement = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
}),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, (raw) =>
|
||||
previewViewManager.automationStatus(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL, (raw) =>
|
||||
previewViewManager.automationSnapshot(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL, (raw) =>
|
||||
previewViewManager.automationClick(
|
||||
tabIdFrom(raw),
|
||||
inputFrom(raw) as Parameters<typeof previewViewManager.automationClick>[1],
|
||||
),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL, (raw) =>
|
||||
previewViewManager.automationType(
|
||||
tabIdFrom(raw),
|
||||
inputFrom(raw) as Parameters<typeof previewViewManager.automationType>[1],
|
||||
),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL, (raw) =>
|
||||
previewViewManager.automationPress(
|
||||
tabIdFrom(raw),
|
||||
inputFrom(raw) as Parameters<typeof previewViewManager.automationPress>[1],
|
||||
),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL, (raw) =>
|
||||
previewViewManager.automationScroll(
|
||||
tabIdFrom(raw),
|
||||
inputFrom(raw) as Parameters<typeof previewViewManager.automationScroll>[1],
|
||||
),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL, (raw) =>
|
||||
previewViewManager.automationEvaluate(
|
||||
tabIdFrom(raw),
|
||||
inputFrom(raw) as Parameters<typeof previewViewManager.automationEvaluate>[1],
|
||||
),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL, (raw) =>
|
||||
previewViewManager.automationWaitFor(
|
||||
tabIdFrom(raw),
|
||||
inputFrom(raw) as Parameters<typeof previewViewManager.automationWaitFor>[1],
|
||||
),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_RECORDING_START_CHANNEL, (raw) =>
|
||||
previewViewManager.startRecording(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL, (raw) =>
|
||||
previewViewManager.stopRecording(tabIdFrom(raw)),
|
||||
),
|
||||
method(IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, (raw) => {
|
||||
const tabId = tabIdFrom(raw);
|
||||
if (typeof raw !== "object" || raw === null) throw new Error("recording payload is required");
|
||||
const mimeType = "mimeType" in raw ? raw.mimeType : null;
|
||||
const data = "data" in raw ? raw.data : null;
|
||||
if (typeof mimeType !== "string" || !(data instanceof Uint8Array)) {
|
||||
throw new Error("recording mimeType and bytes are required");
|
||||
}
|
||||
return previewViewManager.saveRecording(tabId, mimeType, data);
|
||||
});
|
||||
|
||||
export const captureScreenshot = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: DesktopPreviewScreenshotArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.captureScreenshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const revealArtifact = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.revealArtifact(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const copyArtifactToClipboard = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.copyArtifactToClipboard(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationStatus = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationStatus,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationStatus(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationSnapshot = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationSnapshot,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationSnapshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationClick = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
|
||||
payload: DesktopPreviewAutomationClickInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationClick(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationType = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationTypeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationType(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationPress = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
|
||||
payload: DesktopPreviewAutomationPressInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationPress(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationScroll = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
|
||||
payload: DesktopPreviewAutomationScrollInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationScroll(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationEvaluate = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationEvaluateInputSchema,
|
||||
result: Schema.Unknown,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationEvaluate(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationWaitFor = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
|
||||
payload: DesktopPreviewAutomationWaitForInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationWaitFor(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const saveRecording = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
|
||||
payload: DesktopPreviewRecordingSaveInputSchema,
|
||||
result: DesktopPreviewRecordingArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.saveRecording(tabId, mimeType, data);
|
||||
}),
|
||||
});
|
||||
|
||||
export const methods = [
|
||||
createTab,
|
||||
closeTab,
|
||||
registerWebview,
|
||||
navigate,
|
||||
goBack,
|
||||
goForward,
|
||||
refresh,
|
||||
zoomIn,
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
getPreviewConfig,
|
||||
setAnnotationTheme,
|
||||
pickElement,
|
||||
cancelPickElement,
|
||||
captureScreenshot,
|
||||
revealArtifact,
|
||||
copyArtifactToClipboard,
|
||||
automationStatus,
|
||||
automationSnapshot,
|
||||
automationClick,
|
||||
automationType,
|
||||
automationPress,
|
||||
automationScroll,
|
||||
automationEvaluate,
|
||||
automationWaitFor,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
saveRecording,
|
||||
] as const;
|
||||
@@ -44,6 +44,8 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
@@ -127,7 +129,15 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
|
||||
const desktopPreviewLayer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(PreviewBrowserSession.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
Layer.provideMerge(desktopServerExposureLayer),
|
||||
Layer.provideMerge(desktopPreviewLayer),
|
||||
);
|
||||
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,93 @@
|
||||
import type { Session } from "electron";
|
||||
import { session } from "electron";
|
||||
import { createHash } from "node:crypto";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface BrowserSessionShape {
|
||||
readonly getPartition: (scope?: string) => string;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
}
|
||||
|
||||
export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
|
||||
"@t3tools/desktop/preview/BrowserSession",
|
||||
) {}
|
||||
|
||||
const make = Effect.fn("BrowserSession.make")(() =>
|
||||
Effect.sync(() => {
|
||||
const sessions = new Map<string, Session>();
|
||||
const getPartition = (scope = "shared"): string => {
|
||||
const digest = createHash("sha256").update(scope).digest("hex").slice(0, 20);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${digest}`;
|
||||
};
|
||||
|
||||
const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
|
||||
const partition = getPartition(scope);
|
||||
const existing = sessions.get(partition);
|
||||
if (existing) return existing;
|
||||
return yield* Effect.try({
|
||||
try: () => {
|
||||
const browserSession = session.fromPartition(partition);
|
||||
const userAgent = browserSession
|
||||
.getUserAgent()
|
||||
.replace(/Electron\/[\d.]+ /, "")
|
||||
.replace(/\s*t3code\/[\d.]+/, "");
|
||||
browserSession.setUserAgent(userAgent);
|
||||
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
|
||||
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
|
||||
callback(allowed.includes(permission));
|
||||
});
|
||||
sessions.set(partition, browserSession);
|
||||
return browserSession;
|
||||
},
|
||||
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
|
||||
});
|
||||
});
|
||||
|
||||
return BrowserSession.of({
|
||||
getPartition,
|
||||
isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
|
||||
getSession,
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Promise.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
browserSession.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
),
|
||||
),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
|
||||
});
|
||||
}),
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Promise.all(
|
||||
[...sessions.values()].map((browserSession) => browserSession.clearCache()),
|
||||
),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
|
||||
});
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(BrowserSession, make());
|
||||
@@ -0,0 +1,6 @@
|
||||
export const START_PICK_CHANNEL = "preview:start-pick";
|
||||
export const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
|
||||
export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
|
||||
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
|
||||
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
|
||||
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
|
||||
+6
-6
@@ -40,7 +40,7 @@ describe("PreviewViewManager automation status", () => {
|
||||
});
|
||||
|
||||
it("reports an unregistered webview as temporarily unavailable", async () => {
|
||||
const { PreviewViewManager } = await import("./preview-view-manager.ts");
|
||||
const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
|
||||
const manager = new PreviewViewManager();
|
||||
|
||||
expect(manager.automationStatus("tab_1")).toEqual({
|
||||
@@ -95,7 +95,7 @@ describe("PreviewViewManager automation status", () => {
|
||||
},
|
||||
capturePage,
|
||||
} as never);
|
||||
const { PreviewViewManager } = await import("./preview-view-manager.ts");
|
||||
const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
|
||||
const manager = new PreviewViewManager();
|
||||
manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
|
||||
manager.createTab("tab_1");
|
||||
@@ -127,7 +127,7 @@ describe("PreviewViewManager automation status", () => {
|
||||
});
|
||||
|
||||
it("reveals only files inside the configured browser artifact directory", async () => {
|
||||
const { PreviewViewManager } = await import("./preview-view-manager.ts");
|
||||
const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
|
||||
const manager = new PreviewViewManager();
|
||||
manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
|
||||
|
||||
@@ -142,7 +142,7 @@ describe("PreviewViewManager automation status", () => {
|
||||
});
|
||||
|
||||
it("copies screenshot artifacts to the system clipboard", async () => {
|
||||
const { PreviewViewManager } = await import("./preview-view-manager.ts");
|
||||
const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
|
||||
const manager = new PreviewViewManager();
|
||||
manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
|
||||
const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
|
||||
@@ -202,7 +202,7 @@ describe("PreviewViewManager automation status", () => {
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const { PreviewViewManager } = await import("./preview-view-manager.ts");
|
||||
const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
|
||||
const manager = new PreviewViewManager();
|
||||
manager.onPointerEvent((event) => activity.push(event.phase));
|
||||
manager.createTab("tab_1");
|
||||
@@ -271,7 +271,7 @@ describe("PreviewViewManager automation status", () => {
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const { PreviewViewManager } = await import("./preview-view-manager.ts");
|
||||
const { PreviewViewManager } = (await import("./Manager.ts")).__testing;
|
||||
const manager = new PreviewViewManager();
|
||||
manager.createTab("tab_1");
|
||||
manager.registerWebview("tab_1", 42);
|
||||
@@ -33,31 +33,30 @@ import {
|
||||
type Session,
|
||||
clipboard,
|
||||
nativeImage,
|
||||
session,
|
||||
shell,
|
||||
webContents,
|
||||
} from "electron";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
import { isPreviewAnnotationPayload } from "./picked-element-payload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./playwright-injected-runtime.ts";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
const START_PICK_CHANNEL = "preview:start-pick";
|
||||
const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
|
||||
const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
|
||||
const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
|
||||
const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
|
||||
const HUMAN_INPUT_CHANNEL = "preview:human-input";
|
||||
|
||||
// Re-export the guest webview security posture from its dedicated module so
|
||||
// the constant is unit-testable in isolation. See
|
||||
// `preview-webview-preferences.ts` for the full security rationale.
|
||||
export { PREVIEW_WEBVIEW_PREFERENCES } from "./preview-webview-preferences.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "./preview-webview-preferences.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import {
|
||||
ANNOTATION_CAPTURED_CHANNEL,
|
||||
ANNOTATION_THEME_CHANNEL,
|
||||
CANCEL_PICK_CHANNEL,
|
||||
ELEMENT_PICKED_CHANNEL,
|
||||
HUMAN_INPUT_CHANNEL,
|
||||
START_PICK_CHANNEL,
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -238,6 +237,7 @@ interface ManagedListeners {
|
||||
navigate: () => void;
|
||||
failed: (event: Event, code: number, description: string) => void;
|
||||
humanInput: (_event: unknown, signal?: unknown) => void;
|
||||
beforeInput: (event: Electron.Event, input: Electron.Input) => void;
|
||||
}
|
||||
|
||||
interface PickSession {
|
||||
@@ -249,6 +249,11 @@ interface BrowserControlSession {
|
||||
readonly webContentsId: number;
|
||||
tail: Promise<void>;
|
||||
initialized: Promise<void>;
|
||||
readonly onMessage: (
|
||||
event: Electron.Event,
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
) => void;
|
||||
}
|
||||
|
||||
interface BrowserDiagnostics {
|
||||
@@ -318,13 +323,12 @@ const inputSignalsMatch = (left: PreviewInputSignal, right: PreviewInputSignal):
|
||||
);
|
||||
};
|
||||
|
||||
export class PreviewViewManager {
|
||||
class PreviewViewManager {
|
||||
private annotationTheme = DEFAULT_ANNOTATION_THEME;
|
||||
private artifactDirectory: string | null = null;
|
||||
private mainWindow: BrowserWindow | null = null;
|
||||
private readonly tabs = new Map<string, PreviewTabState>();
|
||||
private readonly attached = new Map<number, ManagedListeners>();
|
||||
private readonly browserSessions = new Map<string, Session>();
|
||||
private readonly listeners = new Set<Listener>();
|
||||
private readonly pointerEventListeners = new Set<PointerEventListener>();
|
||||
private readonly recordingFrameListeners = new Set<RecordingFrameListener>();
|
||||
@@ -394,43 +398,6 @@ export class PreviewViewManager {
|
||||
this.mainWindow = window;
|
||||
}
|
||||
|
||||
getBrowserPartition(scope = "shared"): string {
|
||||
const digest = createHash("sha256").update(scope).digest("hex").slice(0, 20);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${digest}`;
|
||||
}
|
||||
|
||||
isBrowserPartition(partition: string): boolean {
|
||||
return partition.startsWith(PREVIEW_PARTITION_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the canonical `<webview webpreferences="...">` string. Renderer
|
||||
* fetches this via the desktop bridge so the security posture for guest
|
||||
* surfaces lives in exactly one place (here) and any future guest webview
|
||||
* (docs panel, OAuth popup, etc.) can opt in by calling the same getter.
|
||||
*/
|
||||
getWebviewPreferences(): string {
|
||||
return PREVIEW_WEBVIEW_PREFERENCES;
|
||||
}
|
||||
|
||||
getBrowserSession(scope = "shared"): Session {
|
||||
const partition = this.getBrowserPartition(scope);
|
||||
const existing = this.browserSessions.get(partition);
|
||||
if (existing) return existing;
|
||||
const sess = session.fromPartition(partition);
|
||||
const ua = sess
|
||||
.getUserAgent()
|
||||
.replace(/Electron\/[\d.]+ /, "")
|
||||
.replace(/\s*t3code\/[\d.]+/, "");
|
||||
sess.setUserAgent(ua);
|
||||
sess.setPermissionRequestHandler((_wc, perm, callback) => {
|
||||
const allow = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
|
||||
callback(allow.includes(perm));
|
||||
});
|
||||
this.browserSessions.set(partition, sess);
|
||||
return sess;
|
||||
}
|
||||
|
||||
createTab(tabId: string): PreviewTabState {
|
||||
const existing = this.tabs.get(tabId);
|
||||
if (existing) return existing;
|
||||
@@ -574,25 +541,6 @@ export class PreviewViewManager {
|
||||
wc.openDevTools({ mode: "detach" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop cookies/localStorage/etc. for the preview partition. Affects every
|
||||
* preview tab since they all share `persist:t3code-preview`.
|
||||
*/
|
||||
async clearCookies(): Promise<void> {
|
||||
await Promise.all(
|
||||
[...this.browserSessions.values()].map((sess) =>
|
||||
sess.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Drop the HTTP cache for the preview partition. */
|
||||
async clearCache(): Promise<void> {
|
||||
await Promise.all([...this.browserSessions.values()].map((sess) => sess.clearCache()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Activate annotation mode for `tabId`. Resolves after the guest submits a
|
||||
* multi-target annotation and the desktop process captures its screenshot,
|
||||
@@ -1289,20 +1237,15 @@ export class PreviewViewManager {
|
||||
"Preview control cannot attach because another debugger owns this page.",
|
||||
);
|
||||
}
|
||||
const control: BrowserControlSession = {
|
||||
webContentsId: wc.id,
|
||||
tail: Promise.resolve(),
|
||||
initialized: Promise.resolve(),
|
||||
};
|
||||
const diagnostics: BrowserDiagnostics = {
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
requests: new Map(),
|
||||
};
|
||||
this.diagnostics.set(wc.id, diagnostics);
|
||||
wc.debugger.on("message", (_event, method, params) => {
|
||||
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const frame = params as Record<string, unknown>;
|
||||
const frame = params;
|
||||
const sessionId = frame["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
void wc.debugger
|
||||
@@ -1325,8 +1268,15 @@ export class PreviewViewManager {
|
||||
for (const listener of this.recordingFrameListeners) listener(payload);
|
||||
}
|
||||
}
|
||||
this.captureDiagnosticMessage(diagnostics, method, params as Record<string, unknown>);
|
||||
});
|
||||
this.captureDiagnosticMessage(diagnostics, method, params);
|
||||
};
|
||||
const control: BrowserControlSession = {
|
||||
webContentsId: wc.id,
|
||||
tail: Promise.resolve(),
|
||||
initialized: Promise.resolve(),
|
||||
onMessage,
|
||||
};
|
||||
wc.debugger.on("message", onMessage);
|
||||
control.initialized = (async () => {
|
||||
wc.debugger.attach("1.3");
|
||||
await Promise.all([
|
||||
@@ -1347,10 +1297,15 @@ export class PreviewViewManager {
|
||||
}
|
||||
|
||||
private detachControlSession(webContentsId: number): void {
|
||||
const control = this.controlSessions.get(webContentsId);
|
||||
this.controlSessions.delete(webContentsId);
|
||||
this.diagnostics.delete(webContentsId);
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed() || !wc.debugger.isAttached()) return;
|
||||
if (!wc || wc.isDestroyed()) return;
|
||||
if (control) {
|
||||
wc.debugger.off("message", control.onMessage);
|
||||
}
|
||||
if (!wc.debugger.isAttached()) return;
|
||||
try {
|
||||
wc.debugger.detach();
|
||||
} catch {
|
||||
@@ -1617,7 +1572,7 @@ export class PreviewViewManager {
|
||||
|
||||
// Forward app-level shortcuts to the main window so mod+shift+J etc.
|
||||
// still toggles the preview panel even when the webview has focus.
|
||||
wc.on("before-input-event", (event, input) => {
|
||||
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
|
||||
if (this.isAppShortcut(input) && this.mainWindow && !this.mainWindow.isDestroyed()) {
|
||||
event.preventDefault();
|
||||
this.mainWindow.webContents.sendInputEvent({
|
||||
@@ -1631,9 +1586,10 @@ export class PreviewViewManager {
|
||||
],
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
wc.on("before-input-event", beforeInput);
|
||||
|
||||
this.attached.set(wc.id, { navigate: sync, failed, humanInput });
|
||||
this.attached.set(wc.id, { navigate: sync, failed, humanInput, beforeInput });
|
||||
}
|
||||
|
||||
private detachListeners(webContentsId: number): void {
|
||||
@@ -1648,6 +1604,7 @@ export class PreviewViewManager {
|
||||
wc.off("did-start-loading", handlers.navigate);
|
||||
wc.off("did-stop-loading", handlers.navigate);
|
||||
wc.off("did-fail-load", handlers.failed as never);
|
||||
wc.off("before-input-event", handlers.beforeInput);
|
||||
wc.ipc.off(HUMAN_INPUT_CHANNEL, handlers.humanInput);
|
||||
}
|
||||
|
||||
@@ -1738,4 +1695,255 @@ export class PreviewWebviewNotInitializedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export const previewViewManager = new PreviewViewManager();
|
||||
export class PreviewManagerError extends Data.TaggedError("PreviewManagerError")<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Desktop preview operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface PreviewManagerShape {
|
||||
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly isBrowserPartition: (partition: string) => boolean;
|
||||
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
|
||||
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly registerWebview: (
|
||||
tabId: string,
|
||||
webContentsId: number,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserPartition: (scope?: string) => string;
|
||||
readonly setAnnotationTheme: (
|
||||
theme: DesktopPreviewAnnotationTheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
|
||||
readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly saveRecording: (
|
||||
tabId: string,
|
||||
mimeType: string,
|
||||
data: Uint8Array,
|
||||
) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
|
||||
readonly automationStatus: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
|
||||
readonly automationSnapshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
|
||||
readonly automationClick: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationClickInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationType: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationTypeInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationPress: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationPressInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationScroll: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationScrollInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationEvaluate: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationEvaluateInput,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
readonly automationWaitFor: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationWaitForInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribePointerEvents: (
|
||||
listener: PointerEventListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribeRecordingFrames: (
|
||||
listener: RecordingFrameListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
|
||||
"@t3tools/desktop/preview/Manager/PreviewManager",
|
||||
) {}
|
||||
|
||||
const make = Effect.fn("PreviewManager.make")(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const browserSession = yield* BrowserSession.BrowserSession;
|
||||
const manager = new PreviewViewManager();
|
||||
manager.configureArtifactDirectory(environment.browserArtifactsDir);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => manager.destroy()));
|
||||
|
||||
const attempt = <A>(
|
||||
operation: string,
|
||||
evaluate: () => A,
|
||||
): Effect.Effect<A, PreviewManagerError> =>
|
||||
Effect.try({
|
||||
try: evaluate,
|
||||
catch: (cause) => new PreviewManagerError({ operation, cause }),
|
||||
});
|
||||
const attemptPromise = <A>(
|
||||
operation: string,
|
||||
evaluate: () => Promise<A>,
|
||||
): Effect.Effect<A, PreviewManagerError> =>
|
||||
Effect.tryPromise({
|
||||
try: evaluate,
|
||||
catch: (cause) => new PreviewManagerError({ operation, cause }),
|
||||
});
|
||||
const browserSessionEffect = <A>(
|
||||
operation: string,
|
||||
effect: Effect.Effect<A, BrowserSession.BrowserSessionError>,
|
||||
): Effect.Effect<A, PreviewManagerError> =>
|
||||
effect.pipe(Effect.mapError((cause) => new PreviewManagerError({ operation, cause })));
|
||||
|
||||
return PreviewManager.of({
|
||||
setMainWindow: Effect.fn("PreviewManager.setMainWindow")(function* (window) {
|
||||
yield* attempt("setMainWindow", () => manager.setMainWindow(window));
|
||||
}),
|
||||
getBrowserSession: Effect.fn("PreviewManager.getBrowserSession")(function* (scope) {
|
||||
return yield* browserSessionEffect("getBrowserSession", browserSession.getSession(scope));
|
||||
}),
|
||||
isBrowserPartition: browserSession.isPartition,
|
||||
createTab: Effect.fn("PreviewManager.createTab")(function* (tabId) {
|
||||
return yield* attempt("createTab", () => manager.createTab(tabId));
|
||||
}),
|
||||
closeTab: Effect.fn("PreviewManager.closeTab")(function* (tabId) {
|
||||
yield* attempt("closeTab", () => manager.closeTab(tabId));
|
||||
}),
|
||||
registerWebview: Effect.fn("PreviewManager.registerWebview")(function* (tabId, webContentsId) {
|
||||
yield* attempt("registerWebview", () => manager.registerWebview(tabId, webContentsId));
|
||||
}),
|
||||
navigate: Effect.fn("PreviewManager.navigate")(function* (tabId, url) {
|
||||
yield* attemptPromise("navigate", () => manager.navigate(tabId, url));
|
||||
}),
|
||||
goBack: Effect.fn("PreviewManager.goBack")(function* (tabId) {
|
||||
yield* attempt("goBack", () => manager.goBack(tabId));
|
||||
}),
|
||||
goForward: Effect.fn("PreviewManager.goForward")(function* (tabId) {
|
||||
yield* attempt("goForward", () => manager.goForward(tabId));
|
||||
}),
|
||||
refresh: Effect.fn("PreviewManager.refresh")(function* (tabId) {
|
||||
yield* attempt("refresh", () => manager.refresh(tabId));
|
||||
}),
|
||||
zoomIn: Effect.fn("PreviewManager.zoomIn")(function* (tabId) {
|
||||
yield* attempt("zoomIn", () => manager.zoomIn(tabId));
|
||||
}),
|
||||
zoomOut: Effect.fn("PreviewManager.zoomOut")(function* (tabId) {
|
||||
yield* attempt("zoomOut", () => manager.zoomOut(tabId));
|
||||
}),
|
||||
resetZoom: Effect.fn("PreviewManager.resetZoom")(function* (tabId) {
|
||||
yield* attempt("resetZoom", () => manager.resetZoom(tabId));
|
||||
}),
|
||||
hardReload: Effect.fn("PreviewManager.hardReload")(function* (tabId) {
|
||||
yield* attempt("hardReload", () => manager.hardReload(tabId));
|
||||
}),
|
||||
openDevTools: Effect.fn("PreviewManager.openDevTools")(function* (tabId) {
|
||||
yield* attempt("openDevTools", () => manager.openDevTools(tabId));
|
||||
}),
|
||||
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* () {
|
||||
yield* browserSessionEffect("clearCookies", browserSession.clearCookies());
|
||||
}),
|
||||
clearCache: Effect.fn("PreviewManager.clearCache")(function* () {
|
||||
yield* browserSessionEffect("clearCache", browserSession.clearCache());
|
||||
}),
|
||||
getBrowserPartition: browserSession.getPartition,
|
||||
setAnnotationTheme: Effect.fn("PreviewManager.setAnnotationTheme")(function* (theme) {
|
||||
yield* attempt("setAnnotationTheme", () => manager.setAnnotationTheme(theme));
|
||||
}),
|
||||
pickElement: Effect.fn("PreviewManager.pickElement")(function* (tabId) {
|
||||
return yield* attemptPromise("pickElement", () => manager.pickElement(tabId));
|
||||
}),
|
||||
cancelPickElement: Effect.fn("PreviewManager.cancelPickElement")(function* (tabId) {
|
||||
yield* attempt("cancelPickElement", () => manager.cancelPickElement(tabId));
|
||||
}),
|
||||
captureScreenshot: Effect.fn("PreviewManager.captureScreenshot")(function* (tabId) {
|
||||
return yield* attemptPromise("captureScreenshot", () => manager.captureScreenshot(tabId));
|
||||
}),
|
||||
revealArtifact: Effect.fn("PreviewManager.revealArtifact")(function* (path) {
|
||||
yield* attempt("revealArtifact", () => manager.revealArtifact(path));
|
||||
}),
|
||||
copyArtifactToClipboard: Effect.fn("PreviewManager.copyArtifactToClipboard")(function* (path) {
|
||||
yield* attempt("copyArtifactToClipboard", () => manager.copyArtifactToClipboard(path));
|
||||
}),
|
||||
startRecording: Effect.fn("PreviewManager.startRecording")(function* (tabId) {
|
||||
yield* attemptPromise("startRecording", () => manager.startRecording(tabId));
|
||||
}),
|
||||
stopRecording: Effect.fn("PreviewManager.stopRecording")(function* (tabId) {
|
||||
yield* attemptPromise("stopRecording", () => manager.stopRecording(tabId));
|
||||
}),
|
||||
saveRecording: Effect.fn("PreviewManager.saveRecording")(function* (tabId, mimeType, data) {
|
||||
return yield* attemptPromise("saveRecording", () =>
|
||||
manager.saveRecording(tabId, mimeType, data),
|
||||
);
|
||||
}),
|
||||
automationStatus: Effect.fn("PreviewManager.automationStatus")(function* (tabId) {
|
||||
return yield* attempt("automationStatus", () => manager.automationStatus(tabId));
|
||||
}),
|
||||
automationSnapshot: Effect.fn("PreviewManager.automationSnapshot")(function* (tabId) {
|
||||
return yield* attemptPromise("automationSnapshot", () => manager.automationSnapshot(tabId));
|
||||
}),
|
||||
automationClick: Effect.fn("PreviewManager.automationClick")(function* (tabId, input) {
|
||||
yield* attemptPromise("automationClick", () => manager.automationClick(tabId, input));
|
||||
}),
|
||||
automationType: Effect.fn("PreviewManager.automationType")(function* (tabId, input) {
|
||||
yield* attemptPromise("automationType", () => manager.automationType(tabId, input));
|
||||
}),
|
||||
automationPress: Effect.fn("PreviewManager.automationPress")(function* (tabId, input) {
|
||||
yield* attemptPromise("automationPress", () => manager.automationPress(tabId, input));
|
||||
}),
|
||||
automationScroll: Effect.fn("PreviewManager.automationScroll")(function* (tabId, input) {
|
||||
yield* attemptPromise("automationScroll", () => manager.automationScroll(tabId, input));
|
||||
}),
|
||||
automationEvaluate: Effect.fn("PreviewManager.automationEvaluate")(function* (tabId, input) {
|
||||
return yield* attemptPromise("automationEvaluate", () =>
|
||||
manager.automationEvaluate(tabId, input),
|
||||
);
|
||||
}),
|
||||
automationWaitFor: Effect.fn("PreviewManager.automationWaitFor")(function* (tabId, input) {
|
||||
yield* attemptPromise("automationWaitFor", () => manager.automationWaitFor(tabId, input));
|
||||
}),
|
||||
subscribeStateChanges: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => manager.onStateChange(listener)),
|
||||
(unsubscribe) => Effect.sync(unsubscribe),
|
||||
).pipe(Effect.asVoid),
|
||||
subscribePointerEvents: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => manager.onPointerEvent(listener)),
|
||||
(unsubscribe) => Effect.sync(unsubscribe),
|
||||
).pipe(Effect.asVoid),
|
||||
subscribeRecordingFrames: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => manager.onRecordingFrame(listener)),
|
||||
(unsubscribe) => Effect.sync(unsubscribe),
|
||||
).pipe(Effect.asVoid),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(PreviewManager, make());
|
||||
|
||||
/** Exposed for tests. */
|
||||
export const __testing = {
|
||||
PreviewViewManager,
|
||||
};
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Pure clamp/flip math for the floating label that follows the cursor while
|
||||
* the user is picking an element in the in-app browser. Lives in its own
|
||||
* electron-free module so the geometry can be unit-tested without spinning
|
||||
* up an Electron preload context (`preview-pick-preload.ts` itself imports
|
||||
* up an Electron preload context (`PickPreload.ts` itself imports
|
||||
* `electron` and `react-grab/primitives`, which can't load under vitest).
|
||||
*
|
||||
* - Horizontally pins the label to `targetLeft`, clamped into
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { computeLabelPosition } from "./preview-pick-label-position.ts";
|
||||
import { computeLabelPosition } from "./PickLabelPosition.ts";
|
||||
|
||||
const VIEWPORT = { viewportWidth: 1280, viewportHeight: 800 };
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isPickedElementPayload, isPreviewAnnotationPayload } from "./picked-element-payload.ts";
|
||||
import { isPickedElementPayload, isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
|
||||
function validPayload(overrides?: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Strict structural validator for `PickedElementPayload` messages received
|
||||
* from the in-page picker preload (`apps/desktop/src/preview-pick-preload.ts`)
|
||||
* from the in-page picker preload (`apps/desktop/src/preview/PickPreload.ts`)
|
||||
* via `wc.ipc`. Lives in its own electron-free module so the validator is
|
||||
* trivially unit-testable.
|
||||
*
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
playwrightInjectedRuntimeInstallExpression,
|
||||
playwrightInjectedRuntimeSource,
|
||||
} from "./playwright-injected-runtime.ts";
|
||||
} from "./PlaywrightInjectedRuntime.ts";
|
||||
|
||||
describe("playwright injected runtime", () => {
|
||||
it("extracts the pinned runtime from playwright-core", async () => {
|
||||
File renamed without changes.
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "./preview-webview-preferences.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "./WebviewPreferences.ts";
|
||||
|
||||
/**
|
||||
* Mirrors Electron's webview attribute parser closely enough to catch the
|
||||
+2
-2
@@ -4,7 +4,7 @@
|
||||
* surfaces inherit the same security posture.
|
||||
*
|
||||
* Lives in its own electron-free module so the value is unit-testable
|
||||
* without importing `preview-view-manager.ts` (which transitively imports
|
||||
* without importing `Manager.ts` (which transitively imports
|
||||
* `electron` and blows up under vitest).
|
||||
*
|
||||
* - `contextIsolation=false`: the picker preload needs to share `globalThis`
|
||||
@@ -22,7 +22,7 @@
|
||||
* - `nodeIntegration=false`: pinned for clarity (the page itself never gets
|
||||
* Node access).
|
||||
*
|
||||
* Format notes (locked down by `preview-webview-preferences.test.ts`):
|
||||
* Format notes (locked down by `WebviewPreferences.test.ts`):
|
||||
* - Whitespace-free. Electron's webpreferences parser splits on `,` and
|
||||
* does not trim, so a leading space would turn a key into an unknown one
|
||||
* and silently drop it.
|
||||
@@ -29,6 +29,7 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
|
||||
const environmentInput = {
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
@@ -166,6 +167,12 @@ function makeTestLayer(input: {
|
||||
} satisfies ElectronShell.ElectronShellShape),
|
||||
electronThemeLayer,
|
||||
electronWindowLayer,
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
getBrowserSession: () => Effect.succeed({} as Electron.Session),
|
||||
setMainWindow: () => Effect.void,
|
||||
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getBrowserPartition: () => "persist:t3code-preview-test",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import { previewViewManager } from "../preview-view-manager.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
@@ -37,7 +37,8 @@ type DesktopWindowRuntimeServices =
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
| ElectronWindow.ElectronWindow;
|
||||
| ElectronWindow.ElectronWindow
|
||||
| PreviewManager.PreviewManager;
|
||||
|
||||
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
|
||||
"DesktopWindowDevServerUrlMissingError",
|
||||
@@ -49,7 +50,8 @@ export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
|
||||
|
||||
export type DesktopWindowError =
|
||||
| DesktopWindowDevServerUrlMissingError
|
||||
| ElectronWindow.ElectronWindowCreateError;
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
export interface DesktopWindowShape {
|
||||
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
@@ -163,6 +165,7 @@ const make = Effect.gen(function* () {
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
@@ -171,7 +174,7 @@ const make = Effect.gen(function* () {
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
|
||||
backendHttpUrl: URL,
|
||||
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
|
||||
previewViewManager.getBrowserSession();
|
||||
yield* previewManager.getBrowserSession();
|
||||
const applicationUrl = environment.isDevelopment
|
||||
? yield* resolveDesktopDevServerUrl(environment)
|
||||
: backendHttpUrl.href;
|
||||
@@ -198,11 +201,11 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
});
|
||||
|
||||
previewViewManager.setMainWindow(window);
|
||||
yield* previewManager.setMainWindow(window);
|
||||
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
|
||||
if (
|
||||
typeof params.partition !== "string" ||
|
||||
!previewViewManager.isBrowserPartition(params.partition)
|
||||
!previewManager.isBrowserPartition(params.partition)
|
||||
) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type * as Types from "effect/Types";
|
||||
import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
@@ -29,6 +30,20 @@ const unauthorized = HttpServerResponse.jsonUnsafe(
|
||||
},
|
||||
);
|
||||
|
||||
type AuthenticatedHttpEffect = Effect.Effect<
|
||||
HttpServerResponse.HttpServerResponse,
|
||||
Types.unhandled,
|
||||
McpInvocationContext.McpInvocationContext
|
||||
>;
|
||||
|
||||
type McpAuthMiddleware = (
|
||||
httpEffect: AuthenticatedHttpEffect,
|
||||
) => Effect.Effect<
|
||||
HttpServerResponse.HttpServerResponse,
|
||||
Types.unhandled,
|
||||
HttpServerRequest.HttpServerRequest
|
||||
>;
|
||||
|
||||
export const normalizeMcpHttpResponse = (
|
||||
response: HttpServerResponse.HttpServerResponse,
|
||||
): HttpServerResponse.HttpServerResponse => {
|
||||
@@ -41,27 +56,123 @@ export const normalizeMcpHttpResponse = (
|
||||
: response;
|
||||
};
|
||||
|
||||
const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
|
||||
Effect.map(
|
||||
(registry): McpAuthMiddleware =>
|
||||
Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const authorization = request.headers.authorization;
|
||||
const token =
|
||||
authorization?.startsWith("Bearer ") === true
|
||||
? authorization.slice("Bearer ".length).trim()
|
||||
: "";
|
||||
const invocation = yield* registry.resolve(token);
|
||||
if (!invocation) return unauthorized;
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.map(normalizeMcpHttpResponse),
|
||||
);
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
|
||||
);
|
||||
|
||||
const McpAuthMiddlewareLive = HttpRouter.middleware<{
|
||||
provides: McpInvocationContext.McpInvocationContext;
|
||||
}>()(
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* McpSessionRegistry.McpSessionRegistry;
|
||||
return Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const authorization = request.headers.authorization;
|
||||
const token =
|
||||
authorization?.startsWith("Bearer ") === true
|
||||
? authorization.slice("Bearer ".length).trim()
|
||||
: "";
|
||||
const invocation = yield* registry.resolve(token);
|
||||
if (!invocation) return unauthorized;
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.map(normalizeMcpHttpResponse),
|
||||
);
|
||||
}>()(makeMcpAuthMiddleware).layer;
|
||||
|
||||
const registerPreviewToolkit = Effect.fn("McpHttpServer.registerPreviewToolkit")(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const built = yield* PreviewToolkit;
|
||||
const handleTool = built.handle as unknown as (
|
||||
name: keyof typeof built.tools,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<
|
||||
Stream.Stream<{ readonly encodedResult: unknown }, Error>,
|
||||
Error,
|
||||
McpInvocationContext.McpInvocationContext
|
||||
>;
|
||||
for (const tool of Object.values(built.tools)) {
|
||||
yield* server.addTool({
|
||||
tool: new McpSchema.Tool({
|
||||
name: tool.name,
|
||||
description: Tool.getDescription(tool),
|
||||
inputSchema: Tool.getJsonSchema(tool),
|
||||
annotations: {
|
||||
...Context.getOption(tool.annotations, Tool.Title).pipe(
|
||||
Option.map((title) => ({ title })),
|
||||
Option.getOrUndefined,
|
||||
),
|
||||
readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
|
||||
destructiveHint: Context.get(tool.annotations, Tool.Destructive),
|
||||
idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
|
||||
openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
|
||||
},
|
||||
}),
|
||||
annotations: tool.annotations,
|
||||
handle: (payload) =>
|
||||
handleTool(tool.name as keyof typeof built.tools, payload).pipe(
|
||||
Stream.unwrap,
|
||||
Stream.run(Sink.last()),
|
||||
Effect.flatMap(Effect.fromOption),
|
||||
Effect.matchCause({
|
||||
onFailure: (cause) =>
|
||||
new McpSchema.CallToolResult({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: Cause.pretty(cause) }],
|
||||
}),
|
||||
onSuccess: (result) => {
|
||||
if (tool.name === "preview_snapshot") {
|
||||
const snapshot = result.encodedResult as {
|
||||
readonly screenshot: {
|
||||
readonly mimeType: "image/png";
|
||||
readonly data: string;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
};
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
const { screenshot, ...page } = snapshot;
|
||||
const metadata = {
|
||||
...page,
|
||||
screenshot: {
|
||||
mimeType: screenshot.mimeType,
|
||||
width: screenshot.width,
|
||||
height: screenshot.height,
|
||||
},
|
||||
};
|
||||
return new McpSchema.CallToolResult({
|
||||
isError: false,
|
||||
structuredContent: metadata,
|
||||
content: [
|
||||
{ type: "text", text: JSON.stringify(metadata) },
|
||||
{
|
||||
type: "image",
|
||||
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
|
||||
mimeType: screenshot.mimeType,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
const encodedResultText = JSON.stringify(result.encodedResult) ?? "null";
|
||||
return new McpSchema.CallToolResult({
|
||||
isError: false,
|
||||
structuredContent:
|
||||
result.encodedResult !== null && typeof result.encodedResult === "object"
|
||||
? result.encodedResult
|
||||
: undefined,
|
||||
content: [{ type: "text", text: encodedResultText }],
|
||||
});
|
||||
},
|
||||
}),
|
||||
) as unknown as Effect.Effect<McpSchema.CallToolResult, never, McpSchema.McpServerClient>,
|
||||
});
|
||||
}),
|
||||
).layer;
|
||||
}
|
||||
});
|
||||
|
||||
export const PreviewToolkitRegistrationLive = Layer.effectDiscard(registerPreviewToolkit()).pipe(
|
||||
Layer.provide(PreviewToolkitHandlersLive),
|
||||
);
|
||||
|
||||
const McpTransportLive = McpServer.layerHttp({
|
||||
name: "T3 Code",
|
||||
@@ -69,98 +180,7 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const PreviewToolkitRegistrationLive = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const built = yield* PreviewToolkit;
|
||||
const handleTool = built.handle as unknown as (
|
||||
name: keyof typeof built.tools,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<
|
||||
Stream.Stream<{ readonly encodedResult: unknown }, Error>,
|
||||
Error,
|
||||
McpInvocationContext.McpInvocationContext
|
||||
>;
|
||||
for (const tool of Object.values(built.tools)) {
|
||||
yield* server.addTool({
|
||||
tool: new McpSchema.Tool({
|
||||
name: tool.name,
|
||||
description: Tool.getDescription(tool),
|
||||
inputSchema: Tool.getJsonSchema(tool),
|
||||
annotations: {
|
||||
...Context.getOption(tool.annotations, Tool.Title).pipe(
|
||||
Option.map((title) => ({ title })),
|
||||
Option.getOrUndefined,
|
||||
),
|
||||
readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
|
||||
destructiveHint: Context.get(tool.annotations, Tool.Destructive),
|
||||
idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
|
||||
openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
|
||||
},
|
||||
}),
|
||||
annotations: tool.annotations,
|
||||
handle: (payload) =>
|
||||
handleTool(tool.name as keyof typeof built.tools, payload).pipe(
|
||||
Stream.unwrap,
|
||||
Stream.run(Sink.last()),
|
||||
Effect.flatMap(Effect.fromOption),
|
||||
Effect.matchCause({
|
||||
onFailure: (cause) =>
|
||||
new McpSchema.CallToolResult({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: Cause.pretty(cause) }],
|
||||
}),
|
||||
onSuccess: (result) => {
|
||||
if (tool.name === "preview_snapshot") {
|
||||
const snapshot = result.encodedResult as {
|
||||
readonly screenshot: {
|
||||
readonly mimeType: "image/png";
|
||||
readonly data: string;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
};
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
const { screenshot, ...page } = snapshot;
|
||||
const metadata = {
|
||||
...page,
|
||||
screenshot: {
|
||||
mimeType: screenshot.mimeType,
|
||||
width: screenshot.width,
|
||||
height: screenshot.height,
|
||||
},
|
||||
};
|
||||
return new McpSchema.CallToolResult({
|
||||
isError: false,
|
||||
structuredContent: metadata,
|
||||
content: [
|
||||
{ type: "text", text: JSON.stringify(metadata) },
|
||||
{
|
||||
type: "image",
|
||||
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
|
||||
mimeType: screenshot.mimeType,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
const encodedResultText = JSON.stringify(result.encodedResult) ?? "null";
|
||||
return new McpSchema.CallToolResult({
|
||||
isError: false,
|
||||
structuredContent:
|
||||
result.encodedResult !== null && typeof result.encodedResult === "object"
|
||||
? result.encodedResult
|
||||
: undefined,
|
||||
content: [{ type: "text", text: encodedResultText }],
|
||||
});
|
||||
},
|
||||
}),
|
||||
) as unknown as Effect.Effect<McpSchema.CallToolResult, never, McpSchema.McpServerClient>,
|
||||
});
|
||||
}
|
||||
}),
|
||||
).pipe(Layer.provide(PreviewToolkitHandlersLive));
|
||||
|
||||
export const layer = Layer.mergeAll(PreviewToolkitRegistrationLive).pipe(
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
@@ -18,15 +18,17 @@ const fakeEnvironment = ServerEnvironment.of({
|
||||
});
|
||||
|
||||
const makeRegistry = (now: () => number) =>
|
||||
McpSessionRegistry.makeForTest({
|
||||
now,
|
||||
idleTimeoutMs: 100,
|
||||
maximumLifetimeMs: 1_000,
|
||||
}).pipe(
|
||||
Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
|
||||
Effect.provideService(ServerEnvironment, fakeEnvironment),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
McpSessionRegistry.__testing
|
||||
.make({
|
||||
now,
|
||||
idleTimeoutMs: 100,
|
||||
maximumLifetimeMs: 1_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
|
||||
Effect.provideService(ServerEnvironment, fakeEnvironment),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.effect("stores only a token hash, resolves the bearer token, and revokes by thread", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -184,8 +184,6 @@ export const layer: Layer.Layer<
|
||||
),
|
||||
);
|
||||
|
||||
export const makeForTest = make;
|
||||
|
||||
export const issueActiveMcpCredential = (
|
||||
request: McpCredentialRequest,
|
||||
): Effect.Effect<McpIssuedCredential | undefined> =>
|
||||
@@ -200,3 +198,8 @@ export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =
|
||||
|
||||
export const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
|
||||
activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
|
||||
|
||||
/** Exposed for tests. */
|
||||
export const __testing = {
|
||||
make,
|
||||
};
|
||||
@@ -23,7 +23,7 @@ const scope = {
|
||||
it.effect("routes a request to the focused owner and correlates its response", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.makeForTest;
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make();
|
||||
const requests = yield* broker.connect("client-1");
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
@@ -56,7 +56,7 @@ it.effect("routes a request to the focused owner and correlates its response", (
|
||||
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.makeForTest;
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make();
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
@@ -67,7 +67,7 @@ it.effect("rejects calls when no focused owner exists", () =>
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.makeForTest;
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make();
|
||||
const requests = yield* broker.connect("client-hidden");
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
|
||||
@@ -119,14 +119,12 @@ const makeResponseError = (
|
||||
}
|
||||
};
|
||||
|
||||
const makeService = (): PreviewAutomationBrokerShape => {
|
||||
const state = Effect.runSync(
|
||||
Ref.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
owners: new Map(),
|
||||
pending: new Map(),
|
||||
}),
|
||||
);
|
||||
const make = Effect.fn("PreviewAutomationBroker.make")(function* () {
|
||||
const state = yield* Ref.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
owners: new Map(),
|
||||
pending: new Map(),
|
||||
});
|
||||
let requestSequence = 0;
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
@@ -297,10 +295,11 @@ const makeService = (): PreviewAutomationBrokerShape => {
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make());
|
||||
|
||||
/** Exposed for tests. */
|
||||
export const __testing = {
|
||||
make,
|
||||
};
|
||||
|
||||
const service = makeService();
|
||||
const make = Effect.succeed(service);
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
|
||||
export const makeForTest = Effect.sync(makeService);
|
||||
@@ -127,7 +127,7 @@ const buildIdleSnapshot = (input: {
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const make = Effect.fn("PreviewManager.make")(function* () {
|
||||
const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
|
||||
// Unbounded PubSub is fine here — events are tiny and we don't want to
|
||||
// block publishers if a subscriber is slow. WS clients backpressure on
|
||||
@@ -359,4 +359,4 @@ const make = Effect.gen(function* () {
|
||||
} satisfies PreviewManagerShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(PreviewManager, make);
|
||||
export const layer = Layer.effect(PreviewManager, make());
|
||||
@@ -2,8 +2,9 @@ import * as net from "node:net";
|
||||
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as Net from "@t3tools/shared/Net";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProcessRunner } from "../processRunner.ts";
|
||||
import * as PortScanner from "./PortScanner.ts";
|
||||
@@ -13,7 +14,60 @@ const { parseLsofOutput, parsePortFromLsofName, parseWindowsListenerOutput, serv
|
||||
const TestProcessRunner = Layer.succeed(ProcessRunner, {
|
||||
run: () => Effect.die("ProcessRunner should not be used by Windows TCP probe tests"),
|
||||
});
|
||||
const TestPortDiscoveryLive = PortScanner.layer.pipe(Layer.provide(TestProcessRunner));
|
||||
const TestPortDiscoveryLive = PortScanner.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(TestProcessRunner, Net.layer)),
|
||||
);
|
||||
|
||||
const openServer = (port: number): Effect.Effect<net.Server | null> =>
|
||||
Effect.callback((resume) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", () => {
|
||||
resume(Effect.succeed(null));
|
||||
});
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
resume(Effect.succeed(server));
|
||||
});
|
||||
return Effect.sync(() => {
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
|
||||
const closeServer = (server: net.Server): Effect.Effect<void> =>
|
||||
Effect.callback((resume) => {
|
||||
server.close(() => resume(Effect.void));
|
||||
});
|
||||
|
||||
const windowsPlatform = Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const originalPlatform = process.platform;
|
||||
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
|
||||
return originalPlatform;
|
||||
}),
|
||||
(originalPlatform) =>
|
||||
Effect.sync(() => {
|
||||
Object.defineProperty(process, "platform", {
|
||||
value: originalPlatform,
|
||||
configurable: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
|
||||
ports: ReadonlyArray<number>,
|
||||
) {
|
||||
for (const port of ports) {
|
||||
const server = yield* openServer(port);
|
||||
if (server !== null) return { port, server };
|
||||
}
|
||||
return yield* Effect.die(
|
||||
new Error("No common development port was available for the preview scanner test"),
|
||||
);
|
||||
});
|
||||
|
||||
const commonDevServer = Effect.acquireRelease(
|
||||
openCommonDevServer(PortScanner.COMMON_DEV_PORTS),
|
||||
({ server }) => closeServer(server),
|
||||
);
|
||||
|
||||
describe("parsePortFromLsofName", () => {
|
||||
it("parses *:port", () => {
|
||||
@@ -180,51 +234,26 @@ describe("parseWindowsListenerOutput", () => {
|
||||
* path (TCP-probe fallback) by monkey-patching `process.platform` for the
|
||||
* duration of the test so we don't depend on `lsof` being installed.
|
||||
*/
|
||||
describe("PortDiscovery integration (TCP probe fallback)", () => {
|
||||
let originalPlatform: NodeJS.Platform;
|
||||
let server: net.Server;
|
||||
let port: number;
|
||||
|
||||
beforeEach(async () => {
|
||||
originalPlatform = process.platform;
|
||||
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
|
||||
for (const candidate of PortScanner.COMMON_DEV_PORTS) {
|
||||
const candidateServer = net.createServer();
|
||||
const listening = await new Promise<boolean>((resolve) => {
|
||||
candidateServer.once("error", () => resolve(false));
|
||||
candidateServer.listen(candidate, "127.0.0.1", () => resolve(true));
|
||||
});
|
||||
if (listening) {
|
||||
server = candidateServer;
|
||||
port = candidate;
|
||||
return;
|
||||
}
|
||||
candidateServer.close();
|
||||
}
|
||||
throw new Error("No common development port was available for the preview scanner test");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
Object.defineProperty(process, "platform", {
|
||||
value: originalPlatform,
|
||||
configurable: true,
|
||||
});
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
effectIt.effect("scan() returns a server we just opened on a curated dev port", () =>
|
||||
Effect.gen(function* () {
|
||||
effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fallback)", (it) => {
|
||||
it.effect(
|
||||
"scan() returns a server we just opened on a curated dev port",
|
||||
Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
|
||||
yield* windowsPlatform;
|
||||
const { port } = yield* commonDevServer;
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const result = yield* scanner.scan();
|
||||
const found = result.find((server) => server.port === port);
|
||||
expect(found).toBeDefined();
|
||||
expect(found?.host).toBe("localhost");
|
||||
}).pipe(Effect.provide(TestPortDiscoveryLive)),
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("retain() drives an immediate broadcast to subscribers", () => {
|
||||
const received: number[] = [];
|
||||
return Effect.gen(function* () {
|
||||
it.effect(
|
||||
"retain() drives an immediate broadcast to subscribers",
|
||||
Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
|
||||
yield* windowsPlatform;
|
||||
const { port } = yield* commonDevServer;
|
||||
const received: number[] = [];
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const unsubscribe = yield* scanner.subscribe((servers) =>
|
||||
Effect.sync(() => {
|
||||
@@ -235,6 +264,6 @@ describe("PortDiscovery integration (TCP probe fallback)", () => {
|
||||
unsubscribe();
|
||||
release();
|
||||
expect(received).toContain(port);
|
||||
}).pipe(Effect.provide(TestPortDiscoveryLive));
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -5,15 +5,14 @@
|
||||
* stable line-prefixed field format; this is the only `lsof` flag set we rely
|
||||
* on).
|
||||
*
|
||||
* Windows / lsof missing: TCP-connects to a curated list of common dev ports
|
||||
* on 127.0.0.1.
|
||||
* Windows / lsof missing: checks a curated list of common dev ports through
|
||||
* the shared Net service.
|
||||
*
|
||||
* Polling is reference-counted via `retain()`. A single layer-scoped fiber
|
||||
* polls forever, but each tick is a no-op when the retain count is zero.
|
||||
*/
|
||||
import * as net from "node:net";
|
||||
|
||||
import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
|
||||
import * as Net from "@t3tools/shared/Net";
|
||||
import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
|
||||
import { Cause, Context, Duration, Effect, Layer, Ref, Schedule } from "effect";
|
||||
|
||||
@@ -45,7 +44,6 @@ export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
|
||||
]);
|
||||
|
||||
const POLL_INTERVAL = Duration.seconds(3);
|
||||
const TCP_PROBE_TIMEOUT_MS = 200;
|
||||
const LSOF_TIMEOUT_MS = 5_000;
|
||||
const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
|
||||
|
||||
@@ -148,40 +146,6 @@ const parseWindowsListenerOutput = (
|
||||
return [...seen.values()].toSorted((left, right) => left.port - right.port);
|
||||
};
|
||||
|
||||
const probeTcpPort = (port: number): Promise<boolean> =>
|
||||
new Promise((resolve) => {
|
||||
const socket = new net.Socket();
|
||||
let settled = false;
|
||||
const finish = (ok: boolean) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
resolve(ok);
|
||||
};
|
||||
socket.setTimeout(TCP_PROBE_TIMEOUT_MS);
|
||||
socket.once("timeout", () => finish(false));
|
||||
socket.once("error", () => finish(false));
|
||||
socket.once("connect", () => finish(true));
|
||||
socket.connect({ host: "127.0.0.1", port });
|
||||
});
|
||||
|
||||
const probeCommonPorts = (): Effect.Effect<ReadonlyArray<DiscoveredLocalServer>> =>
|
||||
Effect.promise(async () => {
|
||||
const results = await Promise.all(
|
||||
COMMON_DEV_PORTS.map(async (port) => ({ port, listening: await probeTcpPort(port) })),
|
||||
);
|
||||
return results
|
||||
.filter((r) => r.listening)
|
||||
.map<DiscoveredLocalServer>((r) => ({
|
||||
host: "localhost",
|
||||
port: r.port,
|
||||
url: `http://localhost:${r.port}`,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
}));
|
||||
});
|
||||
|
||||
const serversEqual = (
|
||||
left: ReadonlyArray<DiscoveredLocalServer>,
|
||||
right: ReadonlyArray<DiscoveredLocalServer>,
|
||||
@@ -206,7 +170,8 @@ const serversEqual = (
|
||||
return true;
|
||||
};
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const make = Effect.fn("PortDiscovery.make")(function* () {
|
||||
const net = yield* Net.NetService;
|
||||
const processRunner = yield* ProcessRunner;
|
||||
const stateRef = yield* Ref.make<ScannerState>({
|
||||
lastSnapshot: [],
|
||||
@@ -224,6 +189,30 @@ const make = Effect.gen(function* () {
|
||||
// be a synchronous side-effect-only function.
|
||||
let retainCount = 0;
|
||||
|
||||
const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
|
||||
const results = yield* Effect.forEach(
|
||||
COMMON_DEV_PORTS,
|
||||
(port) =>
|
||||
net.isPortAvailableOnLoopback(port).pipe(
|
||||
Effect.map((available) => ({
|
||||
port,
|
||||
listening: !available,
|
||||
})),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return results
|
||||
.filter((result) => result.listening)
|
||||
.map<DiscoveredLocalServer>((result) => ({
|
||||
host: "localhost",
|
||||
port: result.port,
|
||||
url: `http://localhost:${result.port}`,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
}));
|
||||
});
|
||||
|
||||
const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
|
||||
const terminalByProcessId = new Map<number, TerminalProcessOwner>();
|
||||
for (const registration of terminalProcesses.values()) {
|
||||
@@ -268,14 +257,15 @@ const make = Effect.gen(function* () {
|
||||
const broadcast = (servers: ReadonlyArray<DiscoveredLocalServer>): Effect.Effect<void> =>
|
||||
Effect.forEach(Array.from(listeners), (listener) => listener(servers), { discard: true });
|
||||
|
||||
const pollTick = Effect.gen(function* () {
|
||||
if (retainCount <= 0) return;
|
||||
const next = yield* scanOnce();
|
||||
const state = yield* Ref.get(stateRef);
|
||||
if (serversEqual(state.lastSnapshot, next)) return;
|
||||
yield* Ref.update(stateRef, (s) => ({ ...s, lastSnapshot: next }));
|
||||
yield* broadcast(next);
|
||||
}).pipe(
|
||||
const pollTick = Effect.fn("PortDiscovery.pollTick")(
|
||||
function* () {
|
||||
if (retainCount <= 0) return;
|
||||
const next = yield* scanOnce();
|
||||
const state = yield* Ref.get(stateRef);
|
||||
if (serversEqual(state.lastSnapshot, next)) return;
|
||||
yield* Ref.update(stateRef, (s) => ({ ...s, lastSnapshot: next }));
|
||||
yield* broadcast(next);
|
||||
},
|
||||
Effect.catchCause((cause: Cause.Cause<never>) =>
|
||||
Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
|
||||
),
|
||||
@@ -283,7 +273,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
// Single layer-scoped polling fiber. Ticks are no-ops when no client is
|
||||
// currently retained, so the cost is one Ref.get every POLL_INTERVAL.
|
||||
yield* Effect.forkScoped(pollTick.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
|
||||
yield* Effect.forkScoped(pollTick().pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
|
||||
|
||||
const retain: PortDiscoveryShape["retain"] = Effect.fn("PortDiscovery.retain")(function* () {
|
||||
const wasIdle = retainCount === 0;
|
||||
@@ -291,7 +281,7 @@ const make = Effect.gen(function* () {
|
||||
if (wasIdle) {
|
||||
// Run an immediate scan + broadcast so the new retainer doesn't have
|
||||
// to wait up to POLL_INTERVAL for the first emission.
|
||||
yield* pollTick;
|
||||
yield* pollTick();
|
||||
}
|
||||
let released = false;
|
||||
return () => {
|
||||
@@ -349,7 +339,7 @@ const make = Effect.gen(function* () {
|
||||
} satisfies PortDiscoveryShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(PortDiscovery, make);
|
||||
export const layer = Layer.effect(PortDiscovery, make());
|
||||
|
||||
/** Exposed for tests. */
|
||||
export const __testing = {
|
||||
|
||||
@@ -66,7 +66,7 @@ import type {
|
||||
PreviewReportStatusInput,
|
||||
PreviewSessionSnapshot,
|
||||
} from "./preview.ts";
|
||||
import type {
|
||||
import {
|
||||
PreviewAutomationClickInput,
|
||||
PreviewAutomationEvaluateInput,
|
||||
PreviewAutomationOwner,
|
||||
@@ -455,6 +455,42 @@ export interface DesktopPreviewTabState {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export const DesktopPreviewTabIdSchema = Schema.String.check(Schema.isTrimmed()).check(
|
||||
Schema.isNonEmpty(),
|
||||
);
|
||||
|
||||
export const DesktopPreviewNavStatusSchema = Schema.Union([
|
||||
Schema.Struct({ kind: Schema.Literal("Idle") }),
|
||||
Schema.Struct({
|
||||
kind: Schema.Literal("Loading"),
|
||||
url: Schema.String,
|
||||
title: Schema.String,
|
||||
}),
|
||||
Schema.Struct({
|
||||
kind: Schema.Literal("Success"),
|
||||
url: Schema.String,
|
||||
title: Schema.String,
|
||||
}),
|
||||
Schema.Struct({
|
||||
kind: Schema.Literal("LoadFailed"),
|
||||
url: Schema.String,
|
||||
title: Schema.String,
|
||||
code: Schema.Number,
|
||||
description: Schema.String,
|
||||
}),
|
||||
]);
|
||||
|
||||
export const DesktopPreviewTabStateSchema: Schema.Codec<DesktopPreviewTabState> = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
webContentsId: Schema.NullOr(Schema.Int),
|
||||
navStatus: DesktopPreviewNavStatusSchema,
|
||||
canGoBack: Schema.Boolean,
|
||||
canGoForward: Schema.Boolean,
|
||||
zoomFactor: Schema.Number,
|
||||
controller: Schema.Literals(["human", "agent", "none"]),
|
||||
updatedAt: Schema.String,
|
||||
});
|
||||
|
||||
export interface DesktopPreviewPointerEvent {
|
||||
tabId: string;
|
||||
phase: "move" | "click";
|
||||
@@ -464,6 +500,16 @@ export interface DesktopPreviewPointerEvent {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export const DesktopPreviewPointerEventSchema: Schema.Codec<DesktopPreviewPointerEvent> =
|
||||
Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
phase: Schema.Literals(["move", "click"]),
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
sequence: Schema.Int,
|
||||
createdAt: Schema.String,
|
||||
});
|
||||
|
||||
/**
|
||||
* Static config a renderer needs to mount a preview `<webview>`. Returned
|
||||
* atomically by `DesktopPreviewBridge.getPreviewConfig()` so the renderer
|
||||
@@ -487,6 +533,13 @@ export interface DesktopPreviewWebviewConfig {
|
||||
preloadUrl: string | null;
|
||||
}
|
||||
|
||||
export const DesktopPreviewWebviewConfigSchema: Schema.Codec<DesktopPreviewWebviewConfig> =
|
||||
Schema.Struct({
|
||||
partition: Schema.String,
|
||||
webPreferences: Schema.String,
|
||||
preloadUrl: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
export interface DesktopPreviewAnnotationTheme {
|
||||
colorScheme: "light" | "dark";
|
||||
radius: string;
|
||||
@@ -507,6 +560,27 @@ export interface DesktopPreviewAnnotationTheme {
|
||||
fontMono: string;
|
||||
}
|
||||
|
||||
export const DesktopPreviewAnnotationThemeSchema: Schema.Codec<DesktopPreviewAnnotationTheme> =
|
||||
Schema.Struct({
|
||||
colorScheme: Schema.Literals(["light", "dark"]),
|
||||
radius: Schema.String,
|
||||
background: Schema.String,
|
||||
foreground: Schema.String,
|
||||
popover: Schema.String,
|
||||
popoverForeground: Schema.String,
|
||||
primary: Schema.String,
|
||||
primaryForeground: Schema.String,
|
||||
muted: Schema.String,
|
||||
mutedForeground: Schema.String,
|
||||
accent: Schema.String,
|
||||
accentForeground: Schema.String,
|
||||
border: Schema.String,
|
||||
input: Schema.String,
|
||||
ring: Schema.String,
|
||||
fontSans: Schema.String,
|
||||
fontMono: Schema.String,
|
||||
});
|
||||
|
||||
export interface DesktopPreviewRecordingFrame {
|
||||
tabId: string;
|
||||
data: string;
|
||||
@@ -515,6 +589,15 @@ export interface DesktopPreviewRecordingFrame {
|
||||
receivedAt: string;
|
||||
}
|
||||
|
||||
export const DesktopPreviewRecordingFrameSchema: Schema.Codec<DesktopPreviewRecordingFrame> =
|
||||
Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
data: Schema.String,
|
||||
width: Schema.Number,
|
||||
height: Schema.Number,
|
||||
receivedAt: Schema.String,
|
||||
});
|
||||
|
||||
export interface DesktopPreviewRecordingArtifact {
|
||||
id: string;
|
||||
tabId: string;
|
||||
@@ -524,6 +607,16 @@ export interface DesktopPreviewRecordingArtifact {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export const DesktopPreviewRecordingArtifactSchema: Schema.Codec<DesktopPreviewRecordingArtifact> =
|
||||
Schema.Struct({
|
||||
id: Schema.String,
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
path: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Int,
|
||||
createdAt: Schema.String,
|
||||
});
|
||||
|
||||
export interface DesktopPreviewScreenshotArtifact {
|
||||
id: string;
|
||||
tabId: string;
|
||||
@@ -533,6 +626,16 @@ export interface DesktopPreviewScreenshotArtifact {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export const DesktopPreviewScreenshotArtifactSchema: Schema.Codec<DesktopPreviewScreenshotArtifact> =
|
||||
Schema.Struct({
|
||||
id: Schema.String,
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
path: Schema.String,
|
||||
mimeType: Schema.Literal("image/png"),
|
||||
sizeBytes: Schema.Int,
|
||||
createdAt: Schema.String,
|
||||
});
|
||||
|
||||
/**
|
||||
* Single stack frame captured by react-grab's `getElementContext`. We surface
|
||||
* the source file/line so coding agents can jump straight to the JSX that
|
||||
@@ -545,6 +648,13 @@ export interface PickedElementStackFrame {
|
||||
columnNumber: number | null;
|
||||
}
|
||||
|
||||
export const PickedElementStackFrameSchema: Schema.Codec<PickedElementStackFrame> = Schema.Struct({
|
||||
functionName: Schema.NullOr(Schema.String),
|
||||
fileName: Schema.NullOr(Schema.String),
|
||||
lineNumber: Schema.NullOr(Schema.Number),
|
||||
columnNumber: Schema.NullOr(Schema.Number),
|
||||
});
|
||||
|
||||
/**
|
||||
* A successful element pick from the preview webview. All fields are
|
||||
* best-effort — pages that don't ship a React fiber tree (or aren't running
|
||||
@@ -574,6 +684,19 @@ export interface PickedElementPayload {
|
||||
pickedAt: string;
|
||||
}
|
||||
|
||||
export const PickedElementPayloadSchema: Schema.Codec<PickedElementPayload> = Schema.Struct({
|
||||
pageUrl: Schema.String,
|
||||
pageTitle: Schema.NullOr(Schema.String),
|
||||
tagName: Schema.String,
|
||||
selector: Schema.NullOr(Schema.String),
|
||||
htmlPreview: Schema.String,
|
||||
componentName: Schema.NullOr(Schema.String),
|
||||
source: Schema.NullOr(PickedElementStackFrameSchema),
|
||||
stack: Schema.Array(PickedElementStackFrameSchema),
|
||||
styles: Schema.String,
|
||||
pickedAt: Schema.String,
|
||||
});
|
||||
|
||||
export interface PreviewAnnotationRect {
|
||||
x: number;
|
||||
y: number;
|
||||
@@ -581,22 +704,47 @@ export interface PreviewAnnotationRect {
|
||||
height: number;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationRectSchema: Schema.Codec<PreviewAnnotationRect> = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
width: Schema.Number,
|
||||
height: Schema.Number,
|
||||
});
|
||||
|
||||
export interface PreviewAnnotationPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationPointSchema: Schema.Codec<PreviewAnnotationPoint> = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
});
|
||||
|
||||
export interface PreviewAnnotationElementTarget {
|
||||
id: string;
|
||||
element: PickedElementPayload;
|
||||
rect: PreviewAnnotationRect;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationElementTargetSchema: Schema.Codec<PreviewAnnotationElementTarget> =
|
||||
Schema.Struct({
|
||||
id: Schema.String,
|
||||
element: PickedElementPayloadSchema,
|
||||
rect: PreviewAnnotationRectSchema,
|
||||
});
|
||||
|
||||
export interface PreviewAnnotationRegionTarget {
|
||||
id: string;
|
||||
rect: PreviewAnnotationRect;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationRegionTargetSchema: Schema.Codec<PreviewAnnotationRegionTarget> =
|
||||
Schema.Struct({
|
||||
id: Schema.String,
|
||||
rect: PreviewAnnotationRectSchema,
|
||||
});
|
||||
|
||||
export interface PreviewAnnotationStrokeTarget {
|
||||
id: string;
|
||||
color: string;
|
||||
@@ -605,6 +753,15 @@ export interface PreviewAnnotationStrokeTarget {
|
||||
bounds: PreviewAnnotationRect;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationStrokeTargetSchema: Schema.Codec<PreviewAnnotationStrokeTarget> =
|
||||
Schema.Struct({
|
||||
id: Schema.String,
|
||||
color: Schema.String,
|
||||
width: Schema.Number,
|
||||
points: Schema.Array(PreviewAnnotationPointSchema),
|
||||
bounds: PreviewAnnotationRectSchema,
|
||||
});
|
||||
|
||||
export interface PreviewAnnotationStyleChange {
|
||||
targetId: string;
|
||||
selector: string | null;
|
||||
@@ -613,6 +770,15 @@ export interface PreviewAnnotationStyleChange {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationStyleChangeSchema: Schema.Codec<PreviewAnnotationStyleChange> =
|
||||
Schema.Struct({
|
||||
targetId: Schema.String,
|
||||
selector: Schema.NullOr(Schema.String),
|
||||
property: Schema.String,
|
||||
previousValue: Schema.String,
|
||||
value: Schema.String,
|
||||
});
|
||||
|
||||
export interface PreviewAnnotationScreenshot {
|
||||
dataUrl: string;
|
||||
width: number;
|
||||
@@ -620,6 +786,14 @@ export interface PreviewAnnotationScreenshot {
|
||||
cropRect: PreviewAnnotationRect;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationScreenshotSchema: Schema.Codec<PreviewAnnotationScreenshot> =
|
||||
Schema.Struct({
|
||||
dataUrl: Schema.String,
|
||||
width: Schema.Number,
|
||||
height: Schema.Number,
|
||||
cropRect: PreviewAnnotationRectSchema,
|
||||
});
|
||||
|
||||
/**
|
||||
* A submitted preview annotation. One annotation may reference multiple DOM
|
||||
* elements, freeform regions, and ink strokes. The desktop main process adds
|
||||
@@ -638,6 +812,83 @@ export interface PreviewAnnotationPayload {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export const PreviewAnnotationPayloadSchema: Schema.Codec<PreviewAnnotationPayload> = Schema.Struct(
|
||||
{
|
||||
id: Schema.String,
|
||||
pageUrl: Schema.String,
|
||||
pageTitle: Schema.NullOr(Schema.String),
|
||||
comment: Schema.String,
|
||||
elements: Schema.Array(PreviewAnnotationElementTargetSchema),
|
||||
regions: Schema.Array(PreviewAnnotationRegionTargetSchema),
|
||||
strokes: Schema.Array(PreviewAnnotationStrokeTargetSchema),
|
||||
styleChanges: Schema.Array(PreviewAnnotationStyleChangeSchema),
|
||||
screenshot: Schema.NullOr(PreviewAnnotationScreenshotSchema),
|
||||
createdAt: Schema.String,
|
||||
},
|
||||
);
|
||||
|
||||
export const DesktopPreviewTabInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
});
|
||||
|
||||
export const DesktopPreviewRegisterWebviewInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
webContentsId: Schema.Int.check(Schema.isGreaterThan(0)),
|
||||
});
|
||||
|
||||
export const DesktopPreviewNavigateInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
url: Schema.String,
|
||||
});
|
||||
|
||||
export const DesktopPreviewConfigInputSchema = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
});
|
||||
|
||||
export const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({
|
||||
theme: DesktopPreviewAnnotationThemeSchema,
|
||||
});
|
||||
|
||||
export const DesktopPreviewArtifactInputSchema = Schema.Struct({
|
||||
path: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),
|
||||
});
|
||||
|
||||
export const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
mimeType: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),
|
||||
data: Schema.Uint8Array,
|
||||
});
|
||||
|
||||
export const DesktopPreviewAutomationClickInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
input: PreviewAutomationClickInput,
|
||||
});
|
||||
|
||||
export const DesktopPreviewAutomationTypeInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
input: PreviewAutomationTypeInput,
|
||||
});
|
||||
|
||||
export const DesktopPreviewAutomationPressInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
input: PreviewAutomationPressInput,
|
||||
});
|
||||
|
||||
export const DesktopPreviewAutomationScrollInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
input: PreviewAutomationScrollInput,
|
||||
});
|
||||
|
||||
export const DesktopPreviewAutomationEvaluateInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
input: PreviewAutomationEvaluateInput,
|
||||
});
|
||||
|
||||
export const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({
|
||||
tabId: DesktopPreviewTabIdSchema,
|
||||
input: PreviewAutomationWaitForInput,
|
||||
});
|
||||
|
||||
export interface DesktopBridge {
|
||||
getAppBranding: () => DesktopAppBranding | null;
|
||||
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
|
||||
|
||||
Reference in new issue
Block a user