The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { it as effectIt } from "@effect/vitest"; |
| 2 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 3 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 4 | import type { |
| 5 | DesktopPreviewFindResultEvent, |
| 6 | DesktopPreviewRecordingInputEvent, |
| 7 | PreviewAnnotationPayload, |
| 8 | PreviewAnnotationRect, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 11 | import { parseKeybindingShortcut } from "@t3tools/shared/keybindings"; |
| 12 | import { app, shell } from "electron"; |
| 13 | import * as Cause from "effect/Cause"; |
| 14 | import * as Deferred from "effect/Deferred"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as Exit from "effect/Exit"; |
| 17 | import * as FileSystem from "effect/FileSystem"; |
| 18 | import * as Fiber from "effect/Fiber"; |
| 19 | import * as Queue from "effect/Queue"; |
| 20 | import * as Stream from "effect/Stream"; |
| 21 | import * as Layer from "effect/Layer"; |
| 22 | import * as Logger from "effect/Logger"; |
| 23 | import * as Option from "effect/Option"; |
| 24 | import * as Path from "effect/Path"; |
| 25 | import type * as Scope from "effect/Scope"; |
| 26 | import { TestClock } from "effect/testing"; |
| 27 | import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; |
| 28 | |
| 29 | import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; |
| 30 | import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; |
| 31 | import * as ElectronWindow from "../electron/ElectronWindow.ts"; |
| 32 | import * as BrowserSession from "./BrowserSession.ts"; |
| 33 | import * as DesktopBrowserHost from "./DesktopBrowserHost.ts"; |
| 34 | import * as PreviewManager from "./Manager.ts"; |
| 35 | import * as PreviewPasskeys from "./Passkeys.ts"; |
| 36 | |
| 37 | describe("fitPictureInPictureContentSize", () => { |
| 38 | it("does not collapse toward the minimum size when orientation changes repeatedly", () => { |
| 39 | const portrait = PreviewManager.fitPictureInPictureContentSize([523, 294], 9 / 16); |
| 40 | const landscape = PreviewManager.fitPictureInPictureContentSize(portrait, 16 / 9); |
| 41 | |
| 42 | expect(portrait).toEqual([294, 523]); |
| 43 | expect(landscape).toEqual([523, 294]); |
| 44 | }); |
| 45 | }); |
| 46 | |
| 47 | describe("isPreviewEditingShortcut", () => { |
| 48 | const input = (platform: NodeJS.Platform, key: string, overrides: Partial<Electron.Input> = {}) => |
| 49 | ({ |
| 50 | type: "keyDown", |
| 51 | key, |
| 52 | meta: platform === "darwin", |
| 53 | control: platform !== "darwin", |
| 54 | shift: false, |
| 55 | alt: false, |
| 56 | ...overrides, |
| 57 | }) as Electron.Input; |
| 58 | |
| 59 | it("recognizes macOS Paste and Match Style when Option changes the key to a symbol", () => { |
| 60 | const pasteAndMatchStyle = input("darwin", "◊", { code: "KeyV", alt: true, shift: true }); |
| 61 | expect(PreviewManager.isPreviewEditingShortcut(pasteAndMatchStyle, "darwin")).toBe(true); |
| 62 | for (const modifiers of [ |
| 63 | { code: "KeyC" }, |
| 64 | { alt: false }, |
| 65 | { shift: false }, |
| 66 | { control: true }, |
| 67 | ]) { |
| 68 | expect( |
| 69 | PreviewManager.isPreviewEditingShortcut({ ...pasteAndMatchStyle, ...modifiers }, "darwin"), |
| 70 | ).toBe(false); |
| 71 | } |
| 72 | }); |
| 73 | }); |
| 74 | |
| 75 | describe("previewWindowOpenAction", () => { |
| 76 | const details = (overrides: { |
| 77 | readonly url?: string; |
| 78 | readonly disposition?: Electron.HandlerDetails["disposition"]; |
| 79 | }) => ({ |
| 80 | url: "https://accounts.google.com/o/oauth2/auth", |
| 81 | disposition: "new-window" as Electron.HandlerDetails["disposition"], |
| 82 | ...overrides, |
| 83 | }); |
| 84 | |
| 85 | it("opens a real window for scripted popups so the opener survives", () => { |
| 86 | expect(PreviewManager.previewWindowOpenAction(details({}))).toBe("popup"); |
| 87 | expect( |
| 88 | PreviewManager.previewWindowOpenAction(details({ url: "http://localhost:5173/auth" })), |
| 89 | ).toBe("popup"); |
| 90 | }); |
| 91 | |
| 92 | it("opens HTTP links in preview tabs", () => { |
| 93 | for (const disposition of ["foreground-tab", "background-tab"] as const) { |
| 94 | expect(PreviewManager.previewWindowOpenAction(details({ disposition }))).toBe("new-tab"); |
| 95 | } |
| 96 | }); |
| 97 | |
| 98 | it("keeps a form POST with a body on the in-place path", () => { |
| 99 | const postBody = { data: [], contentType: "application/x-www-form-urlencoded" }; |
| 100 | expect( |
| 101 | PreviewManager.previewWindowOpenAction({ |
| 102 | ...details({ disposition: "foreground-tab" }), |
| 103 | postBody, |
| 104 | }), |
| 105 | ).toBe("navigate"); |
| 106 | }); |
| 107 | |
| 108 | it("does not hand a window to schemes that cannot be hardened", () => { |
| 109 | for (const url of [ |
| 110 | "vscode://vscode-remote/ssh-remote+box/tmp", |
| 111 | "blob:https://example.com/0b6c6a5e-55d4-4b4c-9d47-8f1b0c1d2e3f", |
| 112 | ]) { |
| 113 | expect(PreviewManager.previewWindowOpenAction(details({ url }))).toBe("navigate"); |
| 114 | } |
| 115 | }); |
| 116 | |
| 117 | it("denies local and inline schemes that no page could open in place itself", () => { |
| 118 | for (const url of [ |
| 119 | "data:text/html,<h1>hi</h1>", |
| 120 | "DaTa:text/html,<h1>hi</h1>", |
| 121 | "file:///etc/passwd", |
| 122 | "javascript:alert(1)", |
| 123 | "view-source:https://example.com", |
| 124 | "chrome://gpu", |
| 125 | "about:srcdoc", |
| 126 | "devtools://devtools/bundled/inspector.html", |
| 127 | "filesystem:https://example.com/temporary/page.html", |
| 128 | "not a url", |
| 129 | ]) { |
| 130 | for (const disposition of ["new-window", "foreground-tab", "background-tab"] as const) { |
| 131 | expect(PreviewManager.previewWindowOpenAction(details({ url, disposition }))).toBe("deny"); |
| 132 | } |
| 133 | } |
| 134 | }); |
| 135 | |
| 136 | it("denies a blank window instead of blanking the opener", () => { |
| 137 | for (const url of ["about:blank", ""]) { |
| 138 | for (const disposition of ["new-window", "foreground-tab"] as const) { |
| 139 | expect(PreviewManager.previewWindowOpenAction(details({ url, disposition }))).toBe("deny"); |
| 140 | } |
| 141 | } |
| 142 | }); |
| 143 | }); |
| 144 | |
| 145 | const { |
| 146 | browserWindowConstructor, |
| 147 | clipboardItemConstructor, |
| 148 | createFromPath, |
| 149 | fromId, |
| 150 | getFocusedWebContents, |
| 151 | mkdir, |
| 152 | previewSession, |
| 153 | showItemInFolder, |
| 154 | webviewSend, |
| 155 | writeFile, |
| 156 | writeClipboard, |
| 157 | } = vi.hoisted(() => ({ |
| 158 | browserWindowConstructor: vi.fn(), |
| 159 | clipboardItemConstructor: vi.fn(), |
| 160 | createFromPath: vi.fn((): { readonly isEmpty: () => boolean; readonly toPNG: () => Buffer } => ({ |
| 161 | isEmpty: () => false, |
| 162 | toPNG: () => Buffer.from("png"), |
| 163 | })), |
| 164 | fromId: vi.fn<(_id?: number) => Electron.WebContents | null>((_id?: number) => null), |
| 165 | getFocusedWebContents: vi.fn(() => null), |
| 166 | mkdir: vi.fn((_path: string) => undefined), |
| 167 | previewSession: { on: vi.fn() }, |
| 168 | showItemInFolder: vi.fn(), |
| 169 | webviewSend: vi.fn(), |
| 170 | writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined), |
| 171 | writeClipboard: vi.fn(async () => undefined), |
| 172 | })); |
| 173 | |
| 174 | vi.mock("electron", () => ({ |
| 175 | app: { getPath: vi.fn() }, |
| 176 | BrowserWindow: browserWindowConstructor, |
| 177 | // oxlint-disable-next-line typescript/no-extraneous-class -- This constructor-only mock implements the browser ClipboardItem API. |
| 178 | ClipboardItem: class { |
| 179 | constructor(data: Record<string, unknown>) { |
| 180 | clipboardItemConstructor(data); |
| 181 | } |
| 182 | }, |
| 183 | clipboard: { |
| 184 | write: writeClipboard, |
| 185 | }, |
| 186 | nativeImage: { |
| 187 | createFromPath, |
| 188 | }, |
| 189 | shell: { |
| 190 | showItemInFolder, |
| 191 | }, |
| 192 | session: { |
| 193 | fromPartition: vi.fn(), |
| 194 | }, |
| 195 | webContents: { |
| 196 | fromId, |
| 197 | getFocusedWebContents, |
| 198 | }, |
| 199 | })); |
| 200 | |
| 201 | const layerBrowserSession = Layer.succeed( |
| 202 | BrowserSession.BrowserSession, |
| 203 | BrowserSession.BrowserSession.of({ |
| 204 | getPartition: () => Effect.succeed("persist:t3code-preview-test"), |
| 205 | isPartition: (partition) => partition.startsWith("persist:t3code-preview-"), |
| 206 | getSession: () => Effect.succeed(previewSession as unknown as Electron.Session), |
| 207 | clearCookies: () => Effect.void, |
| 208 | cookiesCleared: () => Effect.void, |
| 209 | clearCache: () => Effect.void, |
| 210 | }), |
| 211 | ); |
| 212 | |
| 213 | const layerEnvironment = Layer.succeed( |
| 214 | DesktopEnvironment.DesktopEnvironment, |
| 215 | DesktopEnvironment.DesktopEnvironment.of({ |
| 216 | browserArtifactsDir: "/tmp/t3/dev/browser-artifacts", |
| 217 | dirname: "/tmp/t3/desktop", |
| 218 | path: { |
| 219 | join: (...parts: ReadonlyArray<string>) => parts.join("/"), |
| 220 | }, |
| 221 | } as DesktopEnvironment.DesktopEnvironment["Service"]), |
| 222 | ); |
| 223 | |
| 224 | const layerFileSystem = FileSystem.layerNoop({ |
| 225 | makeDirectory: (path) => |
| 226 | Effect.sync(() => { |
| 227 | mkdir(path); |
| 228 | }), |
| 229 | writeFile: (path, data) => |
| 230 | Effect.sync(() => { |
| 231 | writeFile(path, data); |
| 232 | }), |
| 233 | }); |
| 234 | |
| 235 | const managerLayer = (platform: NodeJS.Platform = "darwin") => |
| 236 | PreviewManager.layer.pipe( |
| 237 | Layer.provideMerge( |
| 238 | Layer.succeed(DesktopRendererHistory.DesktopRendererHistory, { |
| 239 | register: () => Effect.void, |
| 240 | recordMetrics: () => Effect.void, |
| 241 | shutdown: Effect.void, |
| 242 | }), |
| 243 | ), |
| 244 | Layer.provideMerge(DesktopBrowserHost.layer), |
| 245 | Layer.provideMerge(layerBrowserSession), |
| 246 | Layer.provideMerge( |
| 247 | Layer.mock(PreviewPasskeys.PreviewPasskeys)({ |
| 248 | bridgeEnabled: false, |
| 249 | installSessionHandlers: () => {}, |
| 250 | attachGuest: () => () => {}, |
| 251 | }), |
| 252 | ), |
| 253 | Layer.provideMerge(layerEnvironment), |
| 254 | Layer.provideMerge(layerFileSystem), |
| 255 | Layer.provideMerge(Path.layer), |
| 256 | Layer.provideMerge(NodeCrypto.layer), |
| 257 | Layer.provideMerge(Layer.succeed(HostProcess.Platform, platform)), |
| 258 | ); |
| 259 | |
| 260 | const withManager = <A>( |
| 261 | use: ( |
| 262 | manager: PreviewManager.PreviewManager["Service"], |
| 263 | ) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>, |
| 264 | platform: NodeJS.Platform = "darwin", |
| 265 | ) => |
| 266 | Effect.gen(function* () { |
| 267 | const manager = yield* PreviewManager.PreviewManager; |
| 268 | return yield* use(manager); |
| 269 | }).pipe(Effect.provide(managerLayer(platform)), Effect.scoped); |
| 270 | |
| 271 | interface TestCapturedPreviewImage { |
| 272 | readonly toJPEG: () => Buffer; |
| 273 | readonly toBitmap?: () => Buffer; |
| 274 | readonly getSize: () => { readonly width: number; readonly height: number }; |
| 275 | } |
| 276 | |
| 277 | type TestDisplayMediaHandler = ( |
| 278 | request: { readonly frame: { readonly frameTreeNodeId: number } | null }, |
| 279 | callback: (streams: { video?: unknown }) => void, |
| 280 | ) => void; |
| 281 | |
| 282 | interface TestHostWebContents { |
| 283 | readonly id: number; |
| 284 | readonly mainFrame: { readonly frameTreeNodeId: number }; |
| 285 | readonly executeJavaScript: ReturnType<typeof vi.fn>; |
| 286 | readonly isDestroyed: () => boolean; |
| 287 | readonly session: { |
| 288 | readonly setDisplayMediaRequestHandler: ReturnType<typeof vi.fn>; |
| 289 | }; |
| 290 | readonly displayMediaHandler: () => TestDisplayMediaHandler | undefined; |
| 291 | } |
| 292 | |
| 293 | type TestPreviewWebContents = Electron.WebContents & { |
| 294 | readonly setBackgroundThrottling: ReturnType<typeof vi.fn<(enabled: boolean) => void>>; |
| 295 | }; |
| 296 | |
| 297 | const makeTestHostWebContents = (): TestHostWebContents => { |
| 298 | let handler: TestDisplayMediaHandler | undefined; |
| 299 | return { |
| 300 | id: 7, |
| 301 | mainFrame: { frameTreeNodeId: 7 }, |
| 302 | executeJavaScript: vi.fn(async () => true), |
| 303 | isDestroyed: () => false, |
| 304 | session: { |
| 305 | setDisplayMediaRequestHandler: vi.fn((next: TestDisplayMediaHandler) => { |
| 306 | handler = next; |
| 307 | }), |
| 308 | }, |
| 309 | displayMediaHandler: () => handler, |
| 310 | }; |
| 311 | }; |
| 312 | |
| 313 | const makeTestPreviewWebContents = ( |
| 314 | capturePage: () => Promise<TestCapturedPreviewImage>, |
| 315 | id = 42, |
| 316 | hostWebContents: TestHostWebContents = makeTestHostWebContents(), |
| 317 | ) => { |
| 318 | const setBackgroundThrottling = vi.fn<(enabled: boolean) => void>(); |
| 319 | return { |
| 320 | id, |
| 321 | mainFrame: { routingId: id }, |
| 322 | hostWebContents, |
| 323 | executeJavaScript: vi.fn(async () => ({ width: 1280, height: 720 })), |
| 324 | isDestroyed: () => false, |
| 325 | getType: () => "webview", |
| 326 | getURL: () => "https://example.com", |
| 327 | getTitle: () => "Example", |
| 328 | isLoadingMainFrame: () => false, |
| 329 | getZoomFactor: () => 1, |
| 330 | setZoomFactor: vi.fn(), |
| 331 | setAudioMuted: vi.fn(), |
| 332 | setBackgroundThrottling, |
| 333 | isCurrentlyAudible: () => false, |
| 334 | on: vi.fn(), |
| 335 | off: vi.fn(), |
| 336 | ipc: { on: vi.fn(), off: vi.fn() }, |
| 337 | send: webviewSend, |
| 338 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 339 | setIgnoreMenuShortcuts: vi.fn(), |
| 340 | setWindowOpenHandler: vi.fn(), |
| 341 | debugger: { |
| 342 | isAttached: () => false, |
| 343 | attach: vi.fn(), |
| 344 | sendCommand: vi.fn(async () => undefined), |
| 345 | on: vi.fn(), |
| 346 | off: vi.fn(), |
| 347 | }, |
| 348 | capturePage, |
| 349 | } as unknown as TestPreviewWebContents; |
| 350 | }; |
| 351 | |
| 352 | const makeStillImage = (pixels = "fresh-png") => ({ |
| 353 | toPNG: () => Buffer.from(pixels), |
| 354 | toJPEG: () => Buffer.from(pixels), |
| 355 | getSize: () => ({ width: 100, height: 80 }), |
| 356 | }); |
| 357 | |
| 358 | const makeTestStillImageWebContents = (...args: Parameters<typeof makeTestPreviewWebContents>) => { |
| 359 | const wc = makeTestPreviewWebContents(...args); |
| 360 | Object.assign(wc, { isDevToolsOpened: () => false }); |
| 361 | holdStillImagePaint(wc, Promise.resolve()); |
| 362 | return wc; |
| 363 | }; |
| 364 | |
| 365 | const holdStillImagePaint = ( |
| 366 | wc: TestPreviewWebContents, |
| 367 | paint: Promise<void> | Array<Promise<void>>, |
| 368 | ) => { |
| 369 | vi.mocked(wc.debugger.sendCommand).mockImplementation(async (method) => { |
| 370 | if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } }; |
| 371 | if (method === "Page.createIsolatedWorld") return { executionContextId: 7 }; |
| 372 | if (method === "Runtime.evaluate") { |
| 373 | await (Array.isArray(paint) ? paint.shift() : paint); |
| 374 | return { result: { value: true } }; |
| 375 | } |
| 376 | return undefined; |
| 377 | }); |
| 378 | }; |
| 379 | |
| 380 | const setupStill = (manager: PreviewManager.PreviewManager["Service"], paint = Promise.resolve()) => |
| 381 | Effect.gen(function* () { |
| 382 | const image = makeStillImage(); |
| 383 | const capturePage = vi.fn<() => Promise<typeof image>>().mockResolvedValue(image); |
| 384 | const wc = makeTestStillImageWebContents(capturePage); |
| 385 | holdStillImagePaint(wc, paint); |
| 386 | fromId.mockReturnValue(wc); |
| 387 | yield* manager.createTab("tab_still"); |
| 388 | yield* manager.registerWebview("tab_still", wc.id); |
| 389 | yield* manager.setColorScheme("tab_still", "system"); |
| 390 | return { image, capturePage, wc, capture: manager.captureScreenshot("tab_still") }; |
| 391 | }); |
| 392 | |
| 393 | const setupRecordingRaceTabs = (manager: PreviewManager.PreviewManager["Service"]) => |
| 394 | Effect.gen(function* () { |
| 395 | const capturePage = vi.fn(async () => ({ |
| 396 | toJPEG: () => Buffer.from("unused-recording-frame"), |
| 397 | getSize: () => ({ width: 1280, height: 720 }), |
| 398 | })); |
| 399 | const host = makeTestHostWebContents(); |
| 400 | const destroyedIds = new Set<number>(); |
| 401 | const makeWebContents = (id: number) => |
| 402 | Object.assign(makeTestPreviewWebContents(capturePage, id, host), { |
| 403 | executeJavaScript: vi.fn(async () => ({ width: 1280, height: 720 })), |
| 404 | isDestroyed: () => destroyedIds.has(id), |
| 405 | }); |
| 406 | const webContentsById = new Map([ |
| 407 | [41, makeWebContents(41)], |
| 408 | [42, makeWebContents(42)], |
| 409 | ]); |
| 410 | fromId.mockImplementation((id) => |
| 411 | id === undefined ? null : (webContentsById.get(id) ?? null), |
| 412 | ); |
| 413 | yield* manager.createTab("tab_race_a"); |
| 414 | yield* manager.createTab("tab_race_b"); |
| 415 | yield* manager.registerWebview("tab_race_a", 41); |
| 416 | yield* manager.registerWebview("tab_race_b", 42); |
| 417 | const grants: Array<{ video?: unknown }> = []; |
| 418 | return { |
| 419 | host, |
| 420 | grants, |
| 421 | destroy: (id: number) => destroyedIds.add(id), |
| 422 | takeGrant: (frame = host.mainFrame) => |
| 423 | host.displayMediaHandler()?.({ frame }, (value) => { |
| 424 | grants.push(value); |
| 425 | }), |
| 426 | }; |
| 427 | }); |
| 428 | |
| 429 | const TEST_FAVICON = "data:image/png;base64,cG5n"; |
| 430 | |
| 431 | const makeSourcePng = (width = 1, height = 1): Buffer => { |
| 432 | const buffer = Buffer.alloc(24); |
| 433 | Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(buffer); |
| 434 | buffer.writeUInt32BE(width, 16); |
| 435 | buffer.writeUInt32BE(height, 20); |
| 436 | return buffer; |
| 437 | }; |
| 438 | |
| 439 | const makeFaviconWebContents = (options?: { |
| 440 | readonly changes?: ChangeSignal; |
| 441 | readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>; |
| 442 | readonly id?: number; |
| 443 | readonly rasterize?: (code: string) => Promise<unknown>; |
| 444 | readonly url?: string; |
| 445 | }) => { |
| 446 | const sourcePng = makeSourcePng(); |
| 447 | const listeners = new Map<string, (...args: never[]) => void>(); |
| 448 | let currentUrl = options?.url ?? "http://localhost:3200/"; |
| 449 | let destroyed = false; |
| 450 | let loading = false; |
| 451 | const fetchImpl = |
| 452 | options?.fetch ?? |
| 453 | (async () => |
| 454 | new Response(new Uint8Array(sourcePng), { |
| 455 | headers: { "content-type": "image/png" }, |
| 456 | })); |
| 457 | const fetch = vi.fn((url: string, init?: RequestInit) => { |
| 458 | const response = fetchImpl(url, init); |
| 459 | options?.changes?.notify(); |
| 460 | return response; |
| 461 | }); |
| 462 | const executeJavaScriptInIsolatedWorld = vi.fn( |
| 463 | (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) => { |
| 464 | const result = options?.rasterize |
| 465 | ? options.rasterize(scripts[0]?.code ?? "") |
| 466 | : Promise.resolve(TEST_FAVICON); |
| 467 | options?.changes?.notify(); |
| 468 | return result; |
| 469 | }, |
| 470 | ); |
| 471 | const reload = vi.fn(); |
| 472 | const loadURL = vi.fn(async (url: string) => { |
| 473 | currentUrl = url; |
| 474 | }); |
| 475 | const off = vi.fn(); |
| 476 | const debuggerOff = vi.fn(); |
| 477 | const webContents = { |
| 478 | id: options?.id ?? 42, |
| 479 | isDestroyed: () => destroyed, |
| 480 | getType: () => "webview", |
| 481 | getURL: () => currentUrl, |
| 482 | getTitle: () => "Preview", |
| 483 | isLoadingMainFrame: () => loading, |
| 484 | isDevToolsOpened: () => false, |
| 485 | getZoomFactor: () => 1, |
| 486 | setZoomFactor: vi.fn(), |
| 487 | setAudioMuted: vi.fn(), |
| 488 | isCurrentlyAudible: () => false, |
| 489 | reload, |
| 490 | reloadIgnoringCache: vi.fn(), |
| 491 | loadURL, |
| 492 | on: vi.fn((event: string, listener: (...args: never[]) => void) => { |
| 493 | listeners.set(event, listener); |
| 494 | }), |
| 495 | off, |
| 496 | ipc: { on: vi.fn(), off: vi.fn() }, |
| 497 | send: webviewSend, |
| 498 | session: { fetch }, |
| 499 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 500 | isFocused: vi.fn(() => true), |
| 501 | focusedFrame: {} as object | null, |
| 502 | setIgnoreMenuShortcuts: vi.fn(), |
| 503 | setWindowOpenHandler: vi.fn(), |
| 504 | executeJavaScriptInIsolatedWorld, |
| 505 | debugger: { |
| 506 | isAttached: () => false, |
| 507 | attach: vi.fn(), |
| 508 | sendCommand: vi.fn(async () => undefined), |
| 509 | on: vi.fn(), |
| 510 | off: debuggerOff, |
| 511 | }, |
| 512 | }; |
| 513 | return { |
| 514 | executeJavaScriptInIsolatedWorld, |
| 515 | fetch, |
| 516 | debuggerOff, |
| 517 | listeners, |
| 518 | loadURL, |
| 519 | off, |
| 520 | reload, |
| 521 | setDestroyed: (value: boolean) => { |
| 522 | destroyed = value; |
| 523 | }, |
| 524 | setLoading: (value: boolean) => { |
| 525 | loading = value; |
| 526 | }, |
| 527 | setUrl: (url: string) => { |
| 528 | currentUrl = url; |
| 529 | }, |
| 530 | webContents: webContents as never, |
| 531 | }; |
| 532 | }; |
| 533 | |
| 534 | // Electron mocks and state subscribers call `notify`, so a wait re-checks its |
| 535 | // predicate exactly when the state it reads changes. |
| 536 | const makeChangeSignal = () => { |
| 537 | const waiters = new Set<() => void>(); |
| 538 | return { |
| 539 | notify: () => { |
| 540 | for (const wake of waiters) wake(); |
| 541 | }, |
| 542 | until: (predicate: () => boolean) => |
| 543 | Effect.callback<void>((resume) => { |
| 544 | if (predicate()) return resume(Effect.void); |
| 545 | const wake = () => { |
| 546 | if (!predicate()) return; |
| 547 | waiters.delete(wake); |
| 548 | resume(Effect.void); |
| 549 | }; |
| 550 | waiters.add(wake); |
| 551 | return Effect.sync(() => void waiters.delete(wake)); |
| 552 | }), |
| 553 | }; |
| 554 | }; |
| 555 | type ChangeSignal = ReturnType<typeof makeChangeSignal>; |
| 556 | |
| 557 | // Favicon captures run detached from the Electron listener, so asserting that |
| 558 | // one published nothing can only give its promise chain a fixed number of turns. |
| 559 | const flushMicrotasks = function* () { |
| 560 | for (let turn = 0; turn < 30; turn++) yield* Effect.promise(() => Promise.resolve()); |
| 561 | }; |
| 562 | |
| 563 | const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => { |
| 564 | const listeners = new Map<string, () => void>(); |
| 565 | const webContentsListeners = new Map<string, () => void>(); |
| 566 | const send = vi.fn(); |
| 567 | let destroyed = false; |
| 568 | const webContents = { |
| 569 | on: vi.fn((event: string, listener: () => void) => { |
| 570 | webContentsListeners.set(event, listener); |
| 571 | }), |
| 572 | off: vi.fn((event: string) => { |
| 573 | webContentsListeners.delete(event); |
| 574 | }), |
| 575 | send, |
| 576 | }; |
| 577 | const pictureInPictureWindow = { |
| 578 | isDestroyed: vi.fn(() => destroyed), |
| 579 | once: vi.fn((event: string, listener: () => void) => { |
| 580 | listeners.set(event, listener); |
| 581 | }), |
| 582 | setAlwaysOnTop: vi.fn(), |
| 583 | setVisibleOnAllWorkspaces: vi.fn(), |
| 584 | setAspectRatio: vi.fn(), |
| 585 | getContentSize: vi.fn(() => [480, 320]), |
| 586 | setContentSize: vi.fn(), |
| 587 | loadURL: vi.fn(loadURL), |
| 588 | showInactive: vi.fn(() => { |
| 589 | if (destroyed) throw new Error("Picture-in-picture window is closed."); |
| 590 | }), |
| 591 | close: vi.fn(() => { |
| 592 | if (destroyed) return; |
| 593 | destroyed = true; |
| 594 | listeners.get("closed")?.(); |
| 595 | }), |
| 596 | get webContents() { |
| 597 | if (destroyed) throw new Error("Picture-in-picture window is closed."); |
| 598 | return webContents; |
| 599 | }, |
| 600 | }; |
| 601 | return { pictureInPictureWindow, send, webContentsListeners }; |
| 602 | }; |
| 603 | |
| 604 | describe("PreviewManager", () => { |
| 605 | beforeEach(() => { |
| 606 | browserWindowConstructor.mockReset(); |
| 607 | fromId.mockClear(); |
| 608 | getFocusedWebContents.mockReset(); |
| 609 | getFocusedWebContents.mockReturnValue(null); |
| 610 | mkdir.mockClear(); |
| 611 | previewSession.on.mockClear(); |
| 612 | writeFile.mockClear(); |
| 613 | showItemInFolder.mockClear(); |
| 614 | clipboardItemConstructor.mockClear(); |
| 615 | writeClipboard.mockClear(); |
| 616 | createFromPath.mockClear(); |
| 617 | webviewSend.mockClear(); |
| 618 | }); |
| 619 | |
| 620 | effectIt.effect("preserves recording artifacts saved in the same millisecond", () => |
| 621 | withManager((manager) => |
| 622 | Effect.gen(function* () { |
| 623 | const stored = new Map<string, Uint8Array>(); |
| 624 | const save = (path: string, bytes: Uint8Array) => { |
| 625 | stored.set(path, Uint8Array.from(bytes)); |
| 626 | return undefined; |
| 627 | }; |
| 628 | writeFile.mockImplementationOnce(save).mockImplementationOnce(save); |
| 629 | const firstBytes = new Uint8Array([1, 2, 3]); |
| 630 | const secondBytes = new Uint8Array([4, 5, 6]); |
| 631 | const [first, second] = yield* Effect.all( |
| 632 | [ |
| 633 | manager.saveRecording("tab_first", "video/webm", firstBytes), |
| 634 | manager.saveRecording("tab_second", "video/webm", secondBytes), |
| 635 | ], |
| 636 | { concurrency: "unbounded" }, |
| 637 | ); |
| 638 | |
| 639 | expect(first.path).not.toBe(second.path); |
| 640 | expect(stored.get(first.path)).toEqual(firstBytes); |
| 641 | expect(stored.get(second.path)).toEqual(secondBytes); |
| 642 | }), |
| 643 | ), |
| 644 | ); |
| 645 | |
| 646 | effectIt.effect.each([false, true])( |
| 647 | "preserves simultaneous same-name downloads with an existing destination: %s", |
| 648 | (existing) => |
| 649 | Effect.gen(function* () { |
| 650 | const fs = yield* FileSystem.FileSystem; |
| 651 | const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-test-" }); |
| 652 | const downloads = `${dir}/downloads`; |
| 653 | yield* fs.makeDirectory(downloads); |
| 654 | using _downloads = vi.spyOn(app, "getPath").mockReturnValue(downloads); |
| 655 | if (existing) yield* fs.writeFileString(`${downloads}/report.txt`, "existing download"); |
| 656 | const sources = [`${dir}/first`, `${dir}/second`]; |
| 657 | yield* fs.writeFileString(sources[0]!, "first download"); |
| 658 | yield* fs.writeFileString(sources[1]!, "second download"); |
| 659 | const checked = yield* Deferred.make<void>(); |
| 660 | const finished = makeChangeSignal(); |
| 661 | let probes = 0; |
| 662 | let completions = 0; |
| 663 | using _reveal = vi.spyOn(shell, "showItemInFolder").mockImplementation(() => { |
| 664 | completions += 1; |
| 665 | finished.notify(); |
| 666 | }); |
| 667 | const raceTarget = `${downloads}/${existing ? "report (1).txt" : "report.txt"}`; |
| 668 | const exists = (target: string) => |
| 669 | Effect.gen(function* () { |
| 670 | const found = yield* fs.exists(target); |
| 671 | if (target === raceTarget) { |
| 672 | if (++probes === 2) yield* Deferred.succeed(checked, undefined); |
| 673 | yield* Deferred.await(checked); |
| 674 | } |
| 675 | return found; |
| 676 | }); |
| 677 | const manager = yield* PreviewManager.make.pipe( |
| 678 | Effect.provideService(FileSystem.FileSystem, { ...fs, exists }), |
| 679 | Effect.provide( |
| 680 | Layer.mergeAll( |
| 681 | layerEnvironment, |
| 682 | layerBrowserSession, |
| 683 | Layer.mock(DesktopBrowserHost.DesktopBrowserHost)({ |
| 684 | attach: () => {}, |
| 685 | detach: () => {}, |
| 686 | setShown: () => {}, |
| 687 | setCaptureDrawn: () => {}, |
| 688 | loadFailed: () => {}, |
| 689 | humanStartedDownload: () => true, |
| 690 | agentLedPage: () => false, |
| 691 | placeDownload: () => true, |
| 692 | }), |
| 693 | Layer.mock(PreviewPasskeys.PreviewPasskeys)({ |
| 694 | bridgeEnabled: false, |
| 695 | installSessionHandlers: () => {}, |
| 696 | attachGuest: () => () => {}, |
| 697 | }), |
| 698 | Layer.mock(DesktopRendererHistory.DesktopRendererHistory)({}), |
| 699 | Layer.succeed(HostProcess.Platform, "linux"), |
| 700 | ), |
| 701 | ), |
| 702 | ); |
| 703 | yield* manager.getBrowserSession("downloads"); |
| 704 | const listener = previewSession.on.mock.calls[0]![1] as ( |
| 705 | event: unknown, |
| 706 | item: { |
| 707 | once: (event: string, done: (event: unknown, state: string) => void) => void; |
| 708 | getFilename: () => string; |
| 709 | getSavePath: () => string; |
| 710 | }, |
| 711 | source: unknown, |
| 712 | ) => void; |
| 713 | for (const source of sources) { |
| 714 | listener( |
| 715 | {}, |
| 716 | { |
| 717 | once: (_event, done) => done({}, "completed"), |
| 718 | getFilename: () => "report.txt", |
| 719 | getSavePath: () => source, |
| 720 | }, |
| 721 | {}, |
| 722 | ); |
| 723 | } |
| 724 | yield* finished.until(() => completions === 2); |
| 725 | const names = yield* fs.readDirectory(downloads); |
| 726 | expect(names.toSorted()).toEqual( |
| 727 | existing |
| 728 | ? ["report (1).txt", "report (2).txt", "report.txt"] |
| 729 | : ["report (1).txt", "report.txt"], |
| 730 | ); |
| 731 | const contents = yield* Effect.forEach(names, (name) => |
| 732 | fs.readFileString(`${downloads}/${name}`), |
| 733 | ); |
| 734 | expect(contents.toSorted()).toEqual( |
| 735 | (existing |
| 736 | ? ["existing download", "first download", "second download"] |
| 737 | : ["first download", "second download"] |
| 738 | ).toSorted(), |
| 739 | ); |
| 740 | if (existing) { |
| 741 | expect(yield* fs.readFileString(`${downloads}/report.txt`)).toBe("existing download"); |
| 742 | } |
| 743 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 744 | ); |
| 745 | |
| 746 | effectIt.effect.each([ |
| 747 | ["linux", "ctrl+alt+[", "[", "BracketLeft", false], |
| 748 | ["win32", "ctrl+alt+8", "[", "Digit8", false], |
| 749 | ["win32", "ctrl+alt+k", "K", "KeyK", false], |
| 750 | ["linux", "ctrl+alt+`", "Dead", "Backquote", false], |
| 751 | ["darwin", "ctrl+alt+[", "[", "BracketLeft", true], |
| 752 | ["linux", "ctrl+alt+f7", "F7", "F7", true], |
| 753 | ] as const)( |
| 754 | "handles ambiguous preview chords on %s: %s", |
| 755 | ([platform, chord, key, code, expected]) => |
| 756 | withManager( |
| 757 | (manager) => |
| 758 | Effect.gen(function* () { |
| 759 | const preview = makeFaviconWebContents(); |
| 760 | const send = vi.fn(); |
| 761 | Object.assign(preview.webContents, { |
| 762 | hostWebContents: { isDestroyed: () => false, send }, |
| 763 | }); |
| 764 | fromId.mockReturnValue(preview.webContents); |
| 765 | yield* manager.createTab("tab_alt_graph"); |
| 766 | yield* manager.registerWebview("tab_alt_graph", 42); |
| 767 | yield* manager.setForwardedShortcuts([ |
| 768 | { command: "view.reopenClosed", shortcut: parseKeybindingShortcut(chord)! }, |
| 769 | ]); |
| 770 | const preventDefault = vi.fn(); |
| 771 | preview.listeners.get("before-input-event")!( |
| 772 | { preventDefault } as never, |
| 773 | { |
| 774 | type: "keyDown", |
| 775 | key, |
| 776 | code, |
| 777 | meta: false, |
| 778 | control: true, |
| 779 | shift: false, |
| 780 | alt: true, |
| 781 | } as never, |
| 782 | ); |
| 783 | expect(preventDefault).toHaveBeenCalledTimes(expected ? 1 : 0); |
| 784 | expect(send).toHaveBeenCalledTimes(expected ? 1 : 0); |
| 785 | }), |
| 786 | platform, |
| 787 | ), |
| 788 | ); |
| 789 | |
| 790 | effectIt.effect.each([ |
| 791 | ["darwin", true, false, true], |
| 792 | ["darwin", false, true, false], |
| 793 | ["linux", false, true, true], |
| 794 | ["win32", true, false, false], |
| 795 | ] as const)( |
| 796 | "reloads the preview only on the platform refresh chord: %s meta=%s ctrl=%s", |
| 797 | ([platform, meta, control, expected]) => |
| 798 | withManager( |
| 799 | (manager) => |
| 800 | Effect.gen(function* () { |
| 801 | const preview = makeFaviconWebContents(); |
| 802 | fromId.mockReturnValue(preview.webContents); |
| 803 | yield* manager.createTab("tab_refresh"); |
| 804 | yield* manager.registerWebview("tab_refresh", 42); |
| 805 | const preventDefault = vi.fn(); |
| 806 | preview.listeners.get("before-input-event")!( |
| 807 | { preventDefault } as never, |
| 808 | { type: "keyDown", key: "r", meta, control, shift: false, alt: false } as never, |
| 809 | ); |
| 810 | expect(preventDefault).toHaveBeenCalledTimes(expected ? 1 : 0); |
| 811 | expect(preview.reload).toHaveBeenCalledTimes(expected ? 1 : 0); |
| 812 | }), |
| 813 | platform, |
| 814 | ), |
| 815 | ); |
| 816 | |
| 817 | effectIt.effect.each([ |
| 818 | "navigate", |
| 819 | "reload", |
| 820 | "goBack", |
| 821 | "goForward", |
| 822 | "refresh", |
| 823 | "hardReload", |
| 824 | ] as const)("%s stops a page script that never yields before it navigates", (operation) => |
| 825 | withManager((manager) => |
| 826 | Effect.gen(function* () { |
| 827 | const preview = makeFaviconWebContents(); |
| 828 | // As in Chromium: the hung renderer answers nothing, and a terminate reaches it only |
| 829 | // while no navigation is pending. |
| 830 | let stopped = false; |
| 831 | const probed = yield* Deferred.make<void>(); |
| 832 | const navigatedAfterStop: Array<boolean> = []; |
| 833 | const navigated = () => { |
| 834 | navigatedAfterStop.push(stopped); |
| 835 | }; |
| 836 | const sendCommand = async (method: string) => { |
| 837 | if (method === "Runtime.evaluate") { |
| 838 | Deferred.doneUnsafe(probed, Effect.void); |
| 839 | await new Promise(() => {}); |
| 840 | } |
| 841 | if (method === "Runtime.terminateExecution") stopped = true; |
| 842 | }; |
| 843 | Object.assign(preview.webContents, { |
| 844 | getURL: () => "http://localhost:5173/busy", |
| 845 | reload: navigated, |
| 846 | reloadIgnoringCache: navigated, |
| 847 | loadURL: async () => navigated(), |
| 848 | navigationHistory: { |
| 849 | canGoBack: () => true, |
| 850 | canGoForward: () => true, |
| 851 | goBack: navigated, |
| 852 | goForward: navigated, |
| 853 | }, |
| 854 | debugger: { |
| 855 | isAttached: () => false, |
| 856 | attach: vi.fn(), |
| 857 | sendCommand, |
| 858 | on: vi.fn(), |
| 859 | off: vi.fn(), |
| 860 | }, |
| 861 | }); |
| 862 | fromId.mockReturnValue(preview.webContents); |
| 863 | yield* manager.createTab("tab_busy"); |
| 864 | yield* manager.registerWebview("tab_busy", 42); |
| 865 | |
| 866 | const leaving = yield* ( |
| 867 | operation === "navigate" |
| 868 | ? manager.navigate("tab_busy", "http://localhost:5173/next") |
| 869 | : operation === "reload" |
| 870 | ? manager.navigate("tab_busy", "http://localhost:5173/busy") |
| 871 | : manager[operation]("tab_busy") |
| 872 | ).pipe(Effect.forkChild); |
| 873 | const probing = yield* Effect.raceFirst( |
| 874 | Deferred.await(probed).pipe(Effect.as(true)), |
| 875 | Fiber.await(leaving).pipe(Effect.as(false)), |
| 876 | ); |
| 877 | if (probing) yield* TestClock.adjust(1_000); |
| 878 | yield* Fiber.join(leaving); |
| 879 | |
| 880 | expect(navigatedAfterStop).toEqual([true]); |
| 881 | }), |
| 882 | ), |
| 883 | ); |
| 884 | |
| 885 | effectIt.effect("keeps mouse back and forward buttons inside the preview tab", () => |
| 886 | withManager((manager) => |
| 887 | Effect.gen(function* () { |
| 888 | const preview = makeFaviconWebContents(); |
| 889 | const goBack = vi.fn(); |
| 890 | const goForward = vi.fn(); |
| 891 | const send = vi.fn(); |
| 892 | let canGoBack = false; |
| 893 | Object.assign(preview.webContents, { |
| 894 | navigationHistory: { |
| 895 | canGoBack: () => canGoBack, |
| 896 | canGoForward: () => true, |
| 897 | goBack, |
| 898 | goForward, |
| 899 | }, |
| 900 | getZoomFactor: () => 2, |
| 901 | send, |
| 902 | }); |
| 903 | fromId.mockReturnValue(preview.webContents); |
| 904 | yield* manager.createTab("tab_mouse_navigation"); |
| 905 | yield* manager.registerWebview("tab_mouse_navigation", 42); |
| 906 | |
| 907 | // Electron reports thumb buttons as "back"/"forward" for every frame of the guest, iframes included. |
| 908 | const beforeMouse = preview.listeners.get("before-mouse-event"); |
| 909 | expect(beforeMouse, "guest has no before-mouse-event listener").toBeDefined(); |
| 910 | const press = (type: "mouseDown" | "mouseUp", button: string) => { |
| 911 | const preventDefault = vi.fn(); |
| 912 | beforeMouse!({ preventDefault } as never, { type, button, x: 10, y: 10 } as never); |
| 913 | return preventDefault; |
| 914 | }; |
| 915 | |
| 916 | // At the start of tab history the press is still swallowed, or the host app goes back instead. |
| 917 | expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); |
| 918 | expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); |
| 919 | expect(goBack).not.toHaveBeenCalled(); |
| 920 | |
| 921 | canGoBack = true; |
| 922 | expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); |
| 923 | expect(goBack).not.toHaveBeenCalled(); |
| 924 | expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); |
| 925 | expect(goBack).toHaveBeenCalledOnce(); |
| 926 | expect(press("mouseDown", "forward")).toHaveBeenCalledOnce(); |
| 927 | expect(press("mouseUp", "forward")).toHaveBeenCalledOnce(); |
| 928 | expect(goForward).toHaveBeenCalledOnce(); |
| 929 | for (const button of ["left", "right"]) { |
| 930 | expect(press("mouseDown", button)).not.toHaveBeenCalled(); |
| 931 | expect(press("mouseUp", button)).not.toHaveBeenCalled(); |
| 932 | } |
| 933 | expect(goBack).toHaveBeenCalledOnce(); |
| 934 | expect(goForward).toHaveBeenCalledOnce(); |
| 935 | // The guest replays dropped presses for human input and recordings, in CSS px. |
| 936 | expect(send.mock.calls.filter(([channel]) => channel === "preview:thumb-press")).toEqual([ |
| 937 | ["preview:thumb-press", "down", 5, 5, 3], |
| 938 | ["preview:thumb-press", "up", 5, 5, 3], |
| 939 | ["preview:thumb-press", "down", 5, 5, 3], |
| 940 | ["preview:thumb-press", "up", 5, 5, 3], |
| 941 | ["preview:thumb-press", "down", 5, 5, 4], |
| 942 | ["preview:thumb-press", "up", 5, 5, 4], |
| 943 | ]); |
| 944 | }), |
| 945 | ), |
| 946 | ); |
| 947 | |
| 948 | effectIt.effect("keeps editing and forwarded shortcuts in whichever tab holds focus", () => |
| 949 | withManager((manager) => |
| 950 | Effect.gen(function* () { |
| 951 | const send = vi.fn(); |
| 952 | const focus = vi.fn(); |
| 953 | const host = { isDestroyed: () => false, send, focus }; |
| 954 | const older = makeFaviconWebContents({ id: 42 }); |
| 955 | const newer = makeFaviconWebContents({ id: 43 }); |
| 956 | for (const tab of [older, newer]) Object.assign(tab.webContents, { hostWebContents: host }); |
| 957 | getFocusedWebContents.mockReturnValue(newer.webContents as never); |
| 958 | fromId.mockReturnValue(older.webContents); |
| 959 | yield* manager.createTab("tab_older"); |
| 960 | yield* manager.registerWebview("tab_older", 42); |
| 961 | fromId.mockReturnValue(newer.webContents); |
| 962 | yield* manager.createTab("tab_newer"); |
| 963 | yield* manager.registerWebview("tab_newer", 43); |
| 964 | const shortcut = parseKeybindingShortcut("mod+shift+t")!; |
| 965 | yield* manager.setForwardedShortcuts([{ command: "view.reopenClosed", shortcut }]); |
| 966 | |
| 967 | const beforeInput = older.listeners.get("before-input-event")!; |
| 968 | const key = { type: "keyDown", meta: true, control: false, alt: false }; |
| 969 | beforeInput( |
| 970 | { preventDefault: vi.fn() } as never, |
| 971 | { ...key, key: "v", shift: false } as never, |
| 972 | ); |
| 973 | expect( |
| 974 | (older.webContents as Electron.WebContents).setIgnoreMenuShortcuts, |
| 975 | ).toHaveBeenLastCalledWith(false); |
| 976 | |
| 977 | const preventDefault = vi.fn(); |
| 978 | beforeInput({ preventDefault } as never, { ...key, key: "T", shift: true } as never); |
| 979 | expect(preventDefault).toHaveBeenCalledOnce(); |
| 980 | expect(send).toHaveBeenCalledExactlyOnceWith("desktop:menu-action", "view.reopenClosed"); |
| 981 | |
| 982 | yield* manager.setForwardedShortcuts([ |
| 983 | { command: "preview.focusUrl", shortcut: parseKeybindingShortcut("mod+l")! }, |
| 984 | ]); |
| 985 | beforeInput({ preventDefault } as never, { ...key, key: "l", shift: false } as never); |
| 986 | expect(focus).toHaveBeenCalledOnce(); |
| 987 | expect(send).toHaveBeenLastCalledWith("desktop:menu-action", "preview.focusUrl"); |
| 988 | expect(focus.mock.invocationCallOrder[0]).toBeLessThan(send.mock.invocationCallOrder[1]!); |
| 989 | beforeInput( |
| 990 | { preventDefault } as never, |
| 991 | { ...key, key: "l", shift: false, isAutoRepeat: true } as never, |
| 992 | ); |
| 993 | expect(focus).toHaveBeenCalledOnce(); |
| 994 | expect(send).toHaveBeenCalledTimes(2); |
| 995 | send.mockClear(); |
| 996 | yield* manager.setForwardedShortcuts([{ command: "view.reopenClosed", shortcut }]); |
| 997 | |
| 998 | Object.assign(newer.webContents, { focusedFrame: null }); |
| 999 | const agentInput = newer.listeners.get("before-input-event")!; |
| 1000 | const agentPreventDefault = vi.fn(); |
| 1001 | agentInput( |
| 1002 | { preventDefault: agentPreventDefault } as never, |
| 1003 | { ...key, key: "v", shift: false } as never, |
| 1004 | ); |
| 1005 | expect( |
| 1006 | (newer.webContents as Electron.WebContents).setIgnoreMenuShortcuts, |
| 1007 | ).toHaveBeenLastCalledWith(true); |
| 1008 | agentInput( |
| 1009 | { preventDefault: agentPreventDefault } as never, |
| 1010 | { ...key, key: "T", shift: true } as never, |
| 1011 | ); |
| 1012 | expect(agentPreventDefault).not.toHaveBeenCalled(); |
| 1013 | expect(send).not.toHaveBeenCalled(); |
| 1014 | }), |
| 1015 | ), |
| 1016 | ); |
| 1017 | |
| 1018 | effectIt.effect.each([ |
| 1019 | ["darwin", true], |
| 1020 | ["linux", false], |
| 1021 | ["win32", false], |
| 1022 | ] as const)( |
| 1023 | "lets the page and its iframes claim the find and zoom shortcuts before the host acts on %s", |
| 1024 | ([platform, usesMeta]) => |
| 1025 | withManager( |
| 1026 | (manager) => |
| 1027 | Effect.gen(function* () { |
| 1028 | const preview = makeFaviconWebContents(); |
| 1029 | const send = vi.fn(); |
| 1030 | const mainFrame = { processId: 1, routingId: 1 }; |
| 1031 | Object.assign(preview.webContents, { |
| 1032 | hostWebContents: { isDestroyed: () => false, send }, |
| 1033 | mainFrame, |
| 1034 | focusedFrame: mainFrame, |
| 1035 | }); |
| 1036 | fromId.mockReturnValue(preview.webContents); |
| 1037 | yield* manager.createTab("tab_page_find"); |
| 1038 | yield* manager.registerWebview("tab_page_find", 42); |
| 1039 | yield* manager.setForwardedShortcuts([ |
| 1040 | { command: "preview.find", shortcut: parseKeybindingShortcut("mod+f")! }, |
| 1041 | { command: "preview.zoomIn", shortcut: parseKeybindingShortcut("mod+=")! }, |
| 1042 | ]); |
| 1043 | const beforeInput = preview.listeners.get("before-input-event")!; |
| 1044 | const keepsZoom = vi.fn(); |
| 1045 | beforeInput( |
| 1046 | { preventDefault: keepsZoom } as never, |
| 1047 | { |
| 1048 | type: "keyDown", |
| 1049 | key: "=", |
| 1050 | code: "Equal", |
| 1051 | meta: usesMeta, |
| 1052 | control: !usesMeta, |
| 1053 | shift: false, |
| 1054 | alt: false, |
| 1055 | } as never, |
| 1056 | ); |
| 1057 | expect(keepsZoom).not.toHaveBeenCalled(); |
| 1058 | const findKey = { |
| 1059 | type: "keyDown", |
| 1060 | key: "f", |
| 1061 | code: "KeyF", |
| 1062 | meta: usesMeta, |
| 1063 | control: !usesMeta, |
| 1064 | }; |
| 1065 | const preventDefault = vi.fn(); |
| 1066 | |
| 1067 | beforeInput( |
| 1068 | { preventDefault } as never, |
| 1069 | { ...findKey, shift: false, alt: false } as never, |
| 1070 | ); |
| 1071 | expect(preventDefault).not.toHaveBeenCalled(); |
| 1072 | expect(send).not.toHaveBeenCalled(); |
| 1073 | |
| 1074 | const ipcOn = (preview.webContents as Electron.WebContents).ipc.on as ReturnType< |
| 1075 | typeof vi.fn |
| 1076 | >; |
| 1077 | const pageUnhandledShortcut = ipcOn.mock.calls.find( |
| 1078 | ([channel]) => channel === "preview:page-unhandled-shortcut", |
| 1079 | )![1]; |
| 1080 | pageUnhandledShortcut( |
| 1081 | {}, |
| 1082 | { |
| 1083 | key: "f", |
| 1084 | code: "KeyF", |
| 1085 | metaKey: usesMeta, |
| 1086 | ctrlKey: !usesMeta, |
| 1087 | shiftKey: false, |
| 1088 | altKey: false, |
| 1089 | }, |
| 1090 | ); |
| 1091 | expect(send).toHaveBeenCalledExactlyOnceWith("desktop:menu-action", "preview.find"); |
| 1092 | |
| 1093 | Object.assign(preview.webContents, { focusedFrame: { processId: 1, routingId: 2 } }); |
| 1094 | beforeInput( |
| 1095 | { preventDefault } as never, |
| 1096 | { ...findKey, shift: false, alt: false } as never, |
| 1097 | ); |
| 1098 | expect(preventDefault).not.toHaveBeenCalled(); |
| 1099 | expect(send).toHaveBeenCalledOnce(); |
| 1100 | |
| 1101 | Object.assign(preview.webContents, { focusedFrame: mainFrame }); |
| 1102 | yield* manager.setForwardedShortcuts([ |
| 1103 | { command: "preview.find", shortcut: parseKeybindingShortcut("ctrl+alt+8")! }, |
| 1104 | ]); |
| 1105 | pageUnhandledShortcut( |
| 1106 | {}, |
| 1107 | { |
| 1108 | key: "[", |
| 1109 | code: "Digit8", |
| 1110 | metaKey: false, |
| 1111 | ctrlKey: true, |
| 1112 | shiftKey: false, |
| 1113 | altKey: true, |
| 1114 | }, |
| 1115 | ); |
| 1116 | expect(send).toHaveBeenCalledTimes(usesMeta ? 2 : 1); |
| 1117 | }), |
| 1118 | platform, |
| 1119 | ), |
| 1120 | ); |
| 1121 | |
| 1122 | effectIt.effect("searches the guest page and reports its match counts", () => |
| 1123 | withManager((manager) => |
| 1124 | Effect.gen(function* () { |
| 1125 | const preview = makeFaviconWebContents(); |
| 1126 | const findInPage = vi.fn(); |
| 1127 | const stopFindInPage = vi.fn(); |
| 1128 | Object.assign(preview.webContents, { findInPage, stopFindInPage }); |
| 1129 | fromId.mockReturnValue(preview.webContents); |
| 1130 | yield* manager.createTab("tab_find"); |
| 1131 | yield* manager.registerWebview("tab_find", 42); |
| 1132 | const reported = yield* Deferred.make<DesktopPreviewFindResultEvent>(); |
| 1133 | yield* manager.subscribeFindResults((event) => Deferred.succeed(reported, event)); |
| 1134 | |
| 1135 | yield* manager.findInPage("tab_find", "needle", { forward: true, newSession: true }); |
| 1136 | expect(findInPage).toHaveBeenCalledExactlyOnceWith("needle", { |
| 1137 | forward: true, |
| 1138 | findNext: true, |
| 1139 | }); |
| 1140 | |
| 1141 | preview.listeners.get("found-in-page")!( |
| 1142 | {} as never, |
| 1143 | { |
| 1144 | requestId: 1, |
| 1145 | activeMatchOrdinal: 2, |
| 1146 | matches: 5, |
| 1147 | finalUpdate: true, |
| 1148 | } as never, |
| 1149 | ); |
| 1150 | expect(yield* Deferred.await(reported)).toEqual({ |
| 1151 | tabId: "tab_find", |
| 1152 | activeMatchOrdinal: 2, |
| 1153 | matches: 5, |
| 1154 | }); |
| 1155 | |
| 1156 | yield* manager.stopFindInPage("tab_find"); |
| 1157 | expect(stopFindInPage).toHaveBeenCalledExactlyOnceWith("clearSelection"); |
| 1158 | }), |
| 1159 | ), |
| 1160 | ); |
| 1161 | |
| 1162 | effectIt.effect("isolates failed state listeners and continues delivery", () => { |
| 1163 | const loggedErrors: Array<unknown> = []; |
| 1164 | const logger = Logger.make(({ message }) => { |
| 1165 | for (const value of Array.isArray(message) ? message : [message]) { |
| 1166 | if (typeof value === "object" && value !== null && "cause" in value) { |
| 1167 | loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>)); |
| 1168 | } |
| 1169 | } |
| 1170 | }); |
| 1171 | const deliveryError = new ElectronWindow.ElectronWindowOperationError({ |
| 1172 | operation: "send-window-message", |
| 1173 | platform: "darwin", |
| 1174 | windowId: 42, |
| 1175 | channel: "preview:state-change", |
| 1176 | cause: new Error("renderer unavailable"), |
| 1177 | }); |
| 1178 | const delivered = vi.fn(); |
| 1179 | |
| 1180 | return withManager((manager) => |
| 1181 | Effect.gen(function* () { |
| 1182 | yield* manager.subscribeStateChanges(() => Effect.die(deliveryError)); |
| 1183 | yield* manager.subscribeStateChanges((tabId, state) => |
| 1184 | Effect.sync(() => { |
| 1185 | delivered(tabId, state); |
| 1186 | }), |
| 1187 | ); |
| 1188 | |
| 1189 | const state = yield* manager.createTab("tab_listener_failure"); |
| 1190 | |
| 1191 | expect(delivered).toHaveBeenCalledOnce(); |
| 1192 | expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state); |
| 1193 | expect(loggedErrors).toHaveLength(1); |
| 1194 | expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError); |
| 1195 | expect(loggedErrors[0]).toMatchObject({ |
| 1196 | operation: "send-window-message", |
| 1197 | windowId: 42, |
| 1198 | channel: "preview:state-change", |
| 1199 | }); |
| 1200 | }), |
| 1201 | ).pipe( |
| 1202 | Effect.provide( |
| 1203 | Logger.layer([logger], { |
| 1204 | mergeWithExisting: false, |
| 1205 | }), |
| 1206 | ), |
| 1207 | ); |
| 1208 | }); |
| 1209 | |
| 1210 | effectIt.effect("does not swallow state listener interruption", () => |
| 1211 | withManager((manager) => |
| 1212 | Effect.gen(function* () { |
| 1213 | const exit = yield* Effect.scoped( |
| 1214 | Effect.gen(function* () { |
| 1215 | yield* manager.subscribeStateChanges(() => Effect.interrupt); |
| 1216 | return yield* Effect.exit(manager.createTab("tab_interrupted_listener")); |
| 1217 | }), |
| 1218 | ); |
| 1219 | |
| 1220 | expect(Exit.isFailure(exit)).toBe(true); |
| 1221 | if (Exit.isFailure(exit)) { |
| 1222 | expect(Cause.hasInterrupts(exit.cause)).toBe(true); |
| 1223 | } |
| 1224 | }), |
| 1225 | ), |
| 1226 | ); |
| 1227 | |
| 1228 | effectIt.effect("queues navigation until the webview registers", () => |
| 1229 | withManager((manager) => |
| 1230 | Effect.gen(function* () { |
| 1231 | const loadURL = vi.fn(async () => undefined); |
| 1232 | const listeners = new Map<string, (...args: never[]) => void>(); |
| 1233 | fromId.mockReturnValue({ |
| 1234 | id: 42, |
| 1235 | isDestroyed: () => false, |
| 1236 | getType: () => "webview", |
| 1237 | getURL: () => "about:blank", |
| 1238 | getTitle: () => "", |
| 1239 | isLoadingMainFrame: () => false, |
| 1240 | getZoomFactor: () => 1, |
| 1241 | setZoomFactor: vi.fn(), |
| 1242 | setAudioMuted: vi.fn(), |
| 1243 | isCurrentlyAudible: () => false, |
| 1244 | loadURL, |
| 1245 | on: vi.fn((event: string, listener: (...args: never[]) => void) => { |
| 1246 | listeners.set(event, listener); |
| 1247 | }), |
| 1248 | off: vi.fn(), |
| 1249 | ipc: { on: vi.fn(), off: vi.fn() }, |
| 1250 | send: webviewSend, |
| 1251 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 1252 | setIgnoreMenuShortcuts: vi.fn(), |
| 1253 | setWindowOpenHandler: vi.fn(), |
| 1254 | debugger: { |
| 1255 | isAttached: () => false, |
| 1256 | attach: vi.fn(), |
| 1257 | sendCommand: vi.fn(async () => undefined), |
| 1258 | on: vi.fn(), |
| 1259 | off: vi.fn(), |
| 1260 | }, |
| 1261 | } as never); |
| 1262 | |
| 1263 | yield* manager.navigate("tab_pending", "localhost:3200"); |
| 1264 | |
| 1265 | yield* manager.registerWebview("tab_pending", 42); |
| 1266 | yield* Effect.yieldNow; |
| 1267 | |
| 1268 | expect(loadURL).toHaveBeenCalledOnce(); |
| 1269 | expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/"); |
| 1270 | }), |
| 1271 | ), |
| 1272 | ); |
| 1273 | |
| 1274 | effectIt.effect("treats a load superseded by a page redirect as a successful navigation", () => |
| 1275 | withManager((manager) => |
| 1276 | Effect.gen(function* () { |
| 1277 | // Same shape Electron's loadURL rejects with in lib/browser/api/web-contents.ts. |
| 1278 | const loadError = (errno: number, code: string, url: string) => |
| 1279 | Object.assign(new Error(`${code} (${errno}) loading '${url}'`), { errno, code, url }); |
| 1280 | const preview = makeFaviconWebContents(); |
| 1281 | fromId.mockReturnValue(preview.webContents); |
| 1282 | yield* manager.createTab("tab_redirect"); |
| 1283 | yield* manager.registerWebview("tab_redirect", 42); |
| 1284 | |
| 1285 | preview.loadURL.mockRejectedValueOnce( |
| 1286 | loadError(-3, "ERR_ABORTED", "https://example.com/target"), |
| 1287 | ); |
| 1288 | yield* manager.navigate("tab_redirect", "https://example.com/"); |
| 1289 | |
| 1290 | preview.loadURL.mockRejectedValueOnce( |
| 1291 | loadError(-3, "ERR_ABORTED", "https://example.com/reload"), |
| 1292 | ); |
| 1293 | yield* manager.navigate("tab_redirect", "https://example.com/reload"); |
| 1294 | |
| 1295 | preview.loadURL.mockImplementationOnce(async () => { |
| 1296 | preview.listeners.get("will-prevent-unload")?.(); |
| 1297 | throw loadError(-3, "ERR_ABORTED", "https://example.com/blocked"); |
| 1298 | }); |
| 1299 | const blocked = yield* Effect.exit( |
| 1300 | manager.navigate("tab_redirect", "https://example.com/blocked"), |
| 1301 | ); |
| 1302 | expect(Exit.isFailure(blocked)).toBe(true); |
| 1303 | |
| 1304 | preview.loadURL.mockRejectedValueOnce( |
| 1305 | loadError(-105, "ERR_NAME_NOT_RESOLVED", "https://missing.invalid/"), |
| 1306 | ); |
| 1307 | const failed = yield* Effect.exit( |
| 1308 | manager.navigate("tab_redirect", "https://missing.invalid/"), |
| 1309 | ); |
| 1310 | expect(Exit.isFailure(failed)).toBe(true); |
| 1311 | if (Exit.isSuccess(failed)) return; |
| 1312 | expect(Option.getOrThrow(Cause.findErrorOption(failed.cause))).toMatchObject({ |
| 1313 | _tag: "PreviewOperationError", |
| 1314 | operation: "navigate.loadURL", |
| 1315 | cause: { errno: -105 }, |
| 1316 | }); |
| 1317 | }), |
| 1318 | ), |
| 1319 | ); |
| 1320 | |
| 1321 | effectIt.effect("detaches through the pinned debugger after the webview is destroyed", () => |
| 1322 | withManager((manager) => |
| 1323 | Effect.gen(function* () { |
| 1324 | let destroyed = false; |
| 1325 | let attached = false; |
| 1326 | const debuggerOff = vi.fn(); |
| 1327 | const debuggerDetach = vi.fn(() => { |
| 1328 | attached = false; |
| 1329 | }); |
| 1330 | const wcDebugger = { |
| 1331 | isAttached: () => attached, |
| 1332 | attach: vi.fn(() => { |
| 1333 | attached = true; |
| 1334 | }), |
| 1335 | detach: debuggerDetach, |
| 1336 | sendCommand: vi.fn(async () => undefined), |
| 1337 | on: vi.fn(), |
| 1338 | off: debuggerOff, |
| 1339 | }; |
| 1340 | fromId.mockReturnValue({ |
| 1341 | id: 42, |
| 1342 | isDestroyed: () => destroyed, |
| 1343 | getType: () => "webview", |
| 1344 | getURL: () => "http://localhost:3200/", |
| 1345 | getTitle: () => "Preview", |
| 1346 | isLoadingMainFrame: () => false, |
| 1347 | isDevToolsOpened: () => false, |
| 1348 | getZoomFactor: () => 1, |
| 1349 | setZoomFactor: vi.fn(), |
| 1350 | setAudioMuted: vi.fn(), |
| 1351 | isCurrentlyAudible: () => false, |
| 1352 | reload: vi.fn(), |
| 1353 | loadURL: vi.fn(async () => undefined), |
| 1354 | on: vi.fn(), |
| 1355 | off: vi.fn(), |
| 1356 | ipc: { on: vi.fn(), off: vi.fn() }, |
| 1357 | send: webviewSend, |
| 1358 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 1359 | setIgnoreMenuShortcuts: vi.fn(), |
| 1360 | setWindowOpenHandler: vi.fn(), |
| 1361 | get debugger() { |
| 1362 | if (destroyed) throw new Error("Object has been destroyed"); |
| 1363 | return wcDebugger; |
| 1364 | }, |
| 1365 | } as never); |
| 1366 | yield* manager.createTab("tab_pinned_debugger"); |
| 1367 | yield* manager.registerWebview("tab_pinned_debugger", 42); |
| 1368 | yield* manager.setColorScheme("tab_pinned_debugger", "dark"); |
| 1369 | expect(attached).toBe(true); |
| 1370 | destroyed = true; |
| 1371 | |
| 1372 | yield* manager.navigate("tab_pinned_debugger", "https://example.com/"); |
| 1373 | |
| 1374 | expect(debuggerOff).toHaveBeenCalledWith("message", expect.any(Function)); |
| 1375 | expect(debuggerDetach).toHaveBeenCalledOnce(); |
| 1376 | }), |
| 1377 | ), |
| 1378 | ); |
| 1379 | |
| 1380 | effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () => |
| 1381 | withManager((manager) => |
| 1382 | Effect.gen(function* () { |
| 1383 | const previous = makeFaviconWebContents(); |
| 1384 | const replacement = makeFaviconWebContents({ url: "https://example.com/" }); |
| 1385 | let current = previous.webContents; |
| 1386 | let startReplacementRegistration: () => void = () => void 0; |
| 1387 | const replacementReady = new Promise<void>((resolve) => { |
| 1388 | startReplacementRegistration = resolve; |
| 1389 | }); |
| 1390 | fromId.mockImplementation(() => current); |
| 1391 | yield* manager.createTab("tab_destroyed_replacement_race"); |
| 1392 | yield* manager.registerWebview("tab_destroyed_replacement_race", 42); |
| 1393 | yield* manager.setColorScheme("tab_destroyed_replacement_race", "dark"); |
| 1394 | const replacementRegistration = yield* Effect.promise(() => replacementReady).pipe( |
| 1395 | Effect.flatMap(() => manager.registerWebview("tab_destroyed_replacement_race", 42)), |
| 1396 | Effect.forkChild({ startImmediately: true }), |
| 1397 | ); |
| 1398 | previous.setDestroyed(true); |
| 1399 | previous.debuggerOff.mockImplementationOnce(() => { |
| 1400 | current = replacement.webContents; |
| 1401 | startReplacementRegistration(); |
| 1402 | }); |
| 1403 | const states: PreviewManager.PreviewTabState[] = []; |
| 1404 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1405 | Effect.sync(() => { |
| 1406 | states.push(state); |
| 1407 | }), |
| 1408 | ); |
| 1409 | |
| 1410 | yield* manager.navigate("tab_destroyed_replacement_race", "https://example.com/"); |
| 1411 | const registrationExit = yield* Fiber.await(replacementRegistration); |
| 1412 | |
| 1413 | expect(Exit.isSuccess(registrationExit)).toBe(true); |
| 1414 | expect(previous.off).toHaveBeenCalled(); |
| 1415 | expect(replacement.off).not.toHaveBeenCalled(); |
| 1416 | expect(states.at(-1)).toMatchObject({ |
| 1417 | webContentsId: 42, |
| 1418 | navStatus: { kind: "Loading", url: "https://example.com/" }, |
| 1419 | }); |
| 1420 | }), |
| 1421 | ), |
| 1422 | ); |
| 1423 | |
| 1424 | effectIt.effect("shares an identical in-flight event and lets a changed event win", () => |
| 1425 | withManager((manager) => |
| 1426 | Effect.gen(function* () { |
| 1427 | const changes = makeChangeSignal(); |
| 1428 | let resolveFirst!: (response: Response) => void; |
| 1429 | const firstResponse = new Promise<Response>((resolve) => { |
| 1430 | resolveFirst = resolve; |
| 1431 | }); |
| 1432 | const preview = makeFaviconWebContents({ |
| 1433 | changes, |
| 1434 | fetch: (url) => |
| 1435 | url.endsWith("first.png") |
| 1436 | ? firstResponse |
| 1437 | : Promise.resolve( |
| 1438 | new Response(new Uint8Array(makeSourcePng()), { |
| 1439 | headers: { "content-type": "image/png" }, |
| 1440 | }), |
| 1441 | ), |
| 1442 | }); |
| 1443 | fromId.mockReturnValue(preview.webContents); |
| 1444 | const states: PreviewManager.PreviewTabState[] = []; |
| 1445 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1446 | Effect.sync(() => { |
| 1447 | states.push(state); |
| 1448 | changes.notify(); |
| 1449 | }), |
| 1450 | ); |
| 1451 | yield* manager.createTab("tab_favicon_latest"); |
| 1452 | yield* manager.registerWebview("tab_favicon_latest", 42); |
| 1453 | |
| 1454 | const faviconUpdated = preview.listeners.get("page-favicon-updated")!; |
| 1455 | faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never); |
| 1456 | faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never); |
| 1457 | yield* changes.until(() => preview.fetch.mock.calls.length === 1); |
| 1458 | faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never); |
| 1459 | yield* changes.until(() => states.at(-1)?.favicon !== undefined); |
| 1460 | resolveFirst( |
| 1461 | new Response(new Uint8Array(makeSourcePng()), { |
| 1462 | headers: { "content-type": "image/png" }, |
| 1463 | }), |
| 1464 | ); |
| 1465 | yield* flushMicrotasks(); |
| 1466 | |
| 1467 | expect(preview.fetch).toHaveBeenCalledTimes(2); |
| 1468 | expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1); |
| 1469 | }), |
| 1470 | ), |
| 1471 | ); |
| 1472 | |
| 1473 | effectIt.effect("does not publish a capture invalidated by navigation", () => |
| 1474 | withManager((manager) => |
| 1475 | Effect.gen(function* () { |
| 1476 | const changes = makeChangeSignal(); |
| 1477 | let resolveFetch!: (response: Response) => void; |
| 1478 | const preview = makeFaviconWebContents({ |
| 1479 | changes, |
| 1480 | fetch: () => |
| 1481 | new Promise<Response>((resolve) => { |
| 1482 | resolveFetch = resolve; |
| 1483 | }), |
| 1484 | }); |
| 1485 | fromId.mockReturnValue(preview.webContents); |
| 1486 | const states: PreviewManager.PreviewTabState[] = []; |
| 1487 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1488 | Effect.sync(() => { |
| 1489 | states.push(state); |
| 1490 | changes.notify(); |
| 1491 | }), |
| 1492 | ); |
| 1493 | yield* manager.createTab("tab_favicon_navigation"); |
| 1494 | yield* manager.registerWebview("tab_favicon_navigation", 42); |
| 1495 | preview.listeners.get("page-favicon-updated")?.( |
| 1496 | {} as never, |
| 1497 | ["http://localhost:3200/favicon.png"] as never, |
| 1498 | ); |
| 1499 | yield* changes.until(() => preview.fetch.mock.calls.length === 1); |
| 1500 | preview.listeners.get("did-start-navigation")?.({ |
| 1501 | isMainFrame: true, |
| 1502 | isSameDocument: false, |
| 1503 | } as never); |
| 1504 | preview.setUrl("https://example.com/"); |
| 1505 | resolveFetch( |
| 1506 | new Response(new Uint8Array(makeSourcePng()), { |
| 1507 | headers: { "content-type": "image/png" }, |
| 1508 | }), |
| 1509 | ); |
| 1510 | yield* flushMicrotasks(); |
| 1511 | |
| 1512 | expect(states.some((state) => state.favicon !== undefined)).toBe(false); |
| 1513 | }), |
| 1514 | ), |
| 1515 | ); |
| 1516 | |
| 1517 | effectIt.effect("ignores an old capture that completes after webview replacement", () => |
| 1518 | withManager((manager) => |
| 1519 | Effect.gen(function* () { |
| 1520 | const changes = makeChangeSignal(); |
| 1521 | let resolveFetch!: (response: Response) => void; |
| 1522 | const initial = makeFaviconWebContents({ |
| 1523 | changes, |
| 1524 | id: 42, |
| 1525 | fetch: () => |
| 1526 | new Promise<Response>((resolve) => { |
| 1527 | resolveFetch = resolve; |
| 1528 | }), |
| 1529 | }); |
| 1530 | const replacement = makeFaviconWebContents({ changes, id: 43 }); |
| 1531 | fromId.mockImplementation((id?: number) => |
| 1532 | id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null, |
| 1533 | ); |
| 1534 | const states: PreviewManager.PreviewTabState[] = []; |
| 1535 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1536 | Effect.sync(() => { |
| 1537 | states.push(state); |
| 1538 | changes.notify(); |
| 1539 | }), |
| 1540 | ); |
| 1541 | yield* manager.createTab("tab_favicon_late_replace"); |
| 1542 | yield* manager.registerWebview("tab_favicon_late_replace", 42); |
| 1543 | initial.listeners.get("page-favicon-updated")?.( |
| 1544 | {} as never, |
| 1545 | ["http://localhost:3200/favicon.png"] as never, |
| 1546 | ); |
| 1547 | yield* changes.until(() => initial.fetch.mock.calls.length === 1); |
| 1548 | |
| 1549 | yield* manager.registerWebview("tab_favicon_late_replace", 43); |
| 1550 | resolveFetch( |
| 1551 | new Response(new Uint8Array(makeSourcePng()), { |
| 1552 | headers: { "content-type": "image/png" }, |
| 1553 | }), |
| 1554 | ); |
| 1555 | yield* flushMicrotasks(); |
| 1556 | |
| 1557 | expect(states.at(-1)?.webContentsId).toBe(43); |
| 1558 | expect( |
| 1559 | states.some((state) => state.webContentsId === 43 && state.favicon !== undefined), |
| 1560 | ).toBe(false); |
| 1561 | }), |
| 1562 | ), |
| 1563 | ); |
| 1564 | |
| 1565 | effectIt.effect("treats a reused WebContents id as a new attachment", () => |
| 1566 | withManager((manager) => |
| 1567 | Effect.gen(function* () { |
| 1568 | const changes = makeChangeSignal(); |
| 1569 | const initial = makeFaviconWebContents({ changes, id: 42 }); |
| 1570 | const replacement = makeFaviconWebContents({ changes, id: 42 }); |
| 1571 | let active = initial.webContents; |
| 1572 | fromId.mockImplementation(() => active); |
| 1573 | const states: PreviewManager.PreviewTabState[] = []; |
| 1574 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1575 | Effect.sync(() => { |
| 1576 | states.push(state); |
| 1577 | changes.notify(); |
| 1578 | }), |
| 1579 | ); |
| 1580 | yield* manager.createTab("tab_favicon_reused_id"); |
| 1581 | yield* manager.registerWebview("tab_favicon_reused_id", 42); |
| 1582 | initial.listeners.get("page-favicon-updated")?.( |
| 1583 | {} as never, |
| 1584 | ["http://localhost:3200/favicon.png"] as never, |
| 1585 | ); |
| 1586 | yield* changes.until(() => states.at(-1)?.favicon !== undefined); |
| 1587 | |
| 1588 | active = replacement.webContents; |
| 1589 | yield* manager.registerWebview("tab_favicon_reused_id", 42); |
| 1590 | |
| 1591 | expect(states.at(-1)?.favicon).toBeUndefined(); |
| 1592 | expect(initial.off).toHaveBeenCalled(); |
| 1593 | expect(replacement.listeners.has("page-favicon-updated")).toBe(true); |
| 1594 | }), |
| 1595 | ), |
| 1596 | ); |
| 1597 | |
| 1598 | const makeAttachingGuest = (id: number) => { |
| 1599 | const listeners = new Map<string, () => void>(); |
| 1600 | const attach = vi.fn(); |
| 1601 | const detach = vi.fn(); |
| 1602 | const sendCommand = vi.fn<(method: string, params?: unknown) => Promise<unknown>>( |
| 1603 | async () => undefined, |
| 1604 | ); |
| 1605 | const detachListeners = new Set<() => void>(); |
| 1606 | let chromiumDetaches = 0; |
| 1607 | let destroyed = false; |
| 1608 | const wc = { |
| 1609 | id, |
| 1610 | isDestroyed: () => destroyed, |
| 1611 | isDevToolsOpened: () => { |
| 1612 | if (destroyed) throw new TypeError("Object has been destroyed"); |
| 1613 | return false; |
| 1614 | }, |
| 1615 | getType: () => "webview", |
| 1616 | getURL: () => "http://localhost:5173/README.md", |
| 1617 | getTitle: () => "README.md", |
| 1618 | isLoadingMainFrame: () => true, |
| 1619 | getZoomFactor: () => 1, |
| 1620 | setZoomFactor: vi.fn(), |
| 1621 | setAudioMuted: vi.fn(), |
| 1622 | isCurrentlyAudible: () => false, |
| 1623 | on: vi.fn(), |
| 1624 | off: vi.fn(), |
| 1625 | once: (event: string, listener: () => void) => { |
| 1626 | listeners.set(event, listener); |
| 1627 | }, |
| 1628 | ipc: { on: vi.fn(), off: vi.fn() }, |
| 1629 | send: webviewSend, |
| 1630 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 1631 | setIgnoreMenuShortcuts: vi.fn(), |
| 1632 | setWindowOpenHandler: vi.fn(), |
| 1633 | debugger: { |
| 1634 | isAttached: () => attach.mock.calls.length > detach.mock.calls.length + chromiumDetaches, |
| 1635 | attach, |
| 1636 | detach, |
| 1637 | sendCommand, |
| 1638 | on: (event: string, listener: () => void) => { |
| 1639 | if (event === "detach") detachListeners.add(listener); |
| 1640 | }, |
| 1641 | off: (event: string, listener: () => void) => { |
| 1642 | if (event === "detach") detachListeners.delete(listener); |
| 1643 | }, |
| 1644 | }, |
| 1645 | }; |
| 1646 | /** Chromium dropping the debugger without a detach() call. */ |
| 1647 | const chromiumDetach = () => { |
| 1648 | chromiumDetaches += 1; |
| 1649 | // Snapshot like an EventEmitter, so a listener added during emit waits for the next one. |
| 1650 | for (const listener of Array.from(detachListeners)) listener(); |
| 1651 | }; |
| 1652 | return { |
| 1653 | wc: wc as unknown as Electron.WebContents, |
| 1654 | attach, |
| 1655 | detach, |
| 1656 | sendCommand, |
| 1657 | chromiumDetach, |
| 1658 | destroy: () => { |
| 1659 | destroyed = true; |
| 1660 | listeners.get("destroyed")?.(); |
| 1661 | }, |
| 1662 | }; |
| 1663 | }; |
| 1664 | |
| 1665 | effectIt.effect("reattaches a debugger that Chromium dropped on its own", () => |
| 1666 | withManager((manager) => |
| 1667 | Effect.gen(function* () { |
| 1668 | const guest = makeAttachingGuest(48); |
| 1669 | fromId.mockReturnValue(guest.wc); |
| 1670 | yield* manager.createTab("tab_detached"); |
| 1671 | yield* manager.registerWebview("tab_detached", 48); |
| 1672 | yield* Effect.yieldNow; |
| 1673 | expect(guest.attach).toHaveBeenCalledTimes(1); |
| 1674 | |
| 1675 | guest.chromiumDetach(); |
| 1676 | yield* Effect.yieldNow; |
| 1677 | yield* Effect.yieldNow; |
| 1678 | expect(guest.attach).toHaveBeenCalledTimes(2); |
| 1679 | }), |
| 1680 | ), |
| 1681 | ); |
| 1682 | |
| 1683 | effectIt.effect("skips a guest destroyed while another guest's session opens", () => |
| 1684 | withManager((manager) => |
| 1685 | Effect.gen(function* () { |
| 1686 | const slow = makeAttachingGuest(46); |
| 1687 | let releaseSlow = () => {}; |
| 1688 | const slowCommand = new Promise<void>((resolve) => { |
| 1689 | releaseSlow = resolve; |
| 1690 | }); |
| 1691 | slow.sendCommand.mockImplementation(() => slowCommand); |
| 1692 | const queued = makeAttachingGuest(47); |
| 1693 | |
| 1694 | const slowFiber = yield* manager |
| 1695 | .prepareWebview(slow.wc) |
| 1696 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1697 | const queuedFiber = yield* manager |
| 1698 | .prepareWebview(queued.wc) |
| 1699 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1700 | queued.destroy(); |
| 1701 | releaseSlow(); |
| 1702 | |
| 1703 | expect(Exit.isSuccess(yield* Fiber.await(slowFiber))).toBe(true); |
| 1704 | expect(Exit.isSuccess(yield* Fiber.await(queuedFiber))).toBe(true); |
| 1705 | expect(slow.attach).toHaveBeenCalledTimes(1); |
| 1706 | expect(queued.attach).not.toHaveBeenCalled(); |
| 1707 | }), |
| 1708 | ), |
| 1709 | ); |
| 1710 | |
| 1711 | const makeAudioWebContents = (id: number) => { |
| 1712 | const listeners = new Map<string, (...args: never[]) => void>(); |
| 1713 | const setAudioMuted = vi.fn(); |
| 1714 | let audible = false; |
| 1715 | let audibleAfterFirstRead = false; |
| 1716 | let audibleReads = 0; |
| 1717 | return { |
| 1718 | setAudioMuted, |
| 1719 | emitAudioState: (next: boolean) => { |
| 1720 | audible = next; |
| 1721 | listeners.get("audio-state-changed")?.({ audible: next } as never); |
| 1722 | }, |
| 1723 | /** Simulate playback starting during attach before the tab owns the guest and can receive its events. */ |
| 1724 | startPlayingAfterFirstRead: () => { |
| 1725 | audibleAfterFirstRead = true; |
| 1726 | }, |
| 1727 | wc: { |
| 1728 | id, |
| 1729 | isDestroyed: () => false, |
| 1730 | isDevToolsOpened: () => false, |
| 1731 | getType: () => "webview", |
| 1732 | getURL: () => "https://example.com", |
| 1733 | getTitle: () => "Example", |
| 1734 | isLoadingMainFrame: () => false, |
| 1735 | getZoomFactor: () => 1, |
| 1736 | setZoomFactor: vi.fn(), |
| 1737 | setAudioMuted, |
| 1738 | isCurrentlyAudible: () => { |
| 1739 | audibleReads += 1; |
| 1740 | if (audibleAfterFirstRead && audibleReads > 1) return true; |
| 1741 | return audible; |
| 1742 | }, |
| 1743 | loadURL: vi.fn(async () => undefined), |
| 1744 | on: vi.fn((event: string, listener: (...args: never[]) => void) => { |
| 1745 | listeners.set(event, listener); |
| 1746 | }), |
| 1747 | off: vi.fn((event: string) => { |
| 1748 | listeners.delete(event); |
| 1749 | }), |
| 1750 | ipc: { on: vi.fn(), off: vi.fn() }, |
| 1751 | send: webviewSend, |
| 1752 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 1753 | setIgnoreMenuShortcuts: vi.fn(), |
| 1754 | setWindowOpenHandler: vi.fn(), |
| 1755 | debugger: { |
| 1756 | isAttached: () => false, |
| 1757 | attach: vi.fn(), |
| 1758 | sendCommand: vi.fn(async () => undefined), |
| 1759 | on: vi.fn(), |
| 1760 | off: vi.fn(), |
| 1761 | }, |
| 1762 | } as never, |
| 1763 | }; |
| 1764 | }; |
| 1765 | |
| 1766 | effectIt.effect("reconciles audibility that changed while the guest attached", () => |
| 1767 | withManager((manager) => |
| 1768 | Effect.gen(function* () { |
| 1769 | const guest = makeAudioWebContents(42); |
| 1770 | guest.startPlayingAfterFirstRead(); |
| 1771 | fromId.mockReturnValue(guest.wc); |
| 1772 | const states: PreviewManager.PreviewTabState[] = []; |
| 1773 | |
| 1774 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1775 | Effect.sync(() => { |
| 1776 | states.push(state); |
| 1777 | }), |
| 1778 | ); |
| 1779 | yield* manager.createTab("tab_audio_window"); |
| 1780 | yield* manager.registerWebview("tab_audio_window", 42); |
| 1781 | yield* Effect.yieldNow; |
| 1782 | |
| 1783 | expect(states.at(-1)?.audible).toBe(true); |
| 1784 | }), |
| 1785 | ), |
| 1786 | ); |
| 1787 | |
| 1788 | effectIt.effect("ignores audio state from a replaced guest", () => |
| 1789 | withManager((manager) => |
| 1790 | Effect.gen(function* () { |
| 1791 | const first = makeAudioWebContents(42); |
| 1792 | fromId.mockReturnValue(first.wc); |
| 1793 | const states: PreviewManager.PreviewTabState[] = []; |
| 1794 | |
| 1795 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1796 | Effect.sync(() => { |
| 1797 | states.push(state); |
| 1798 | }), |
| 1799 | ); |
| 1800 | yield* manager.createTab("tab_audio_stale"); |
| 1801 | yield* manager.registerWebview("tab_audio_stale", 42); |
| 1802 | yield* Effect.yieldNow; |
| 1803 | |
| 1804 | const replacement = makeAudioWebContents(43); |
| 1805 | fromId.mockReturnValue(replacement.wc); |
| 1806 | yield* manager.registerWebview("tab_audio_stale", 43); |
| 1807 | yield* Effect.yieldNow; |
| 1808 | |
| 1809 | const publishedBefore = states.length; |
| 1810 | first.emitAudioState(true); |
| 1811 | yield* Effect.yieldNow; |
| 1812 | |
| 1813 | expect(states.length).toBe(publishedBefore); |
| 1814 | expect(states.at(-1)?.audible).toBe(false); |
| 1815 | }), |
| 1816 | ), |
| 1817 | ); |
| 1818 | |
| 1819 | effectIt.effect("blocks late webview and capture starts during tab close", () => |
| 1820 | withManager((manager) => |
| 1821 | Effect.gen(function* () { |
| 1822 | const capturePage = vi.fn(async () => ({ |
| 1823 | toJPEG: () => Buffer.from("close-race-frame"), |
| 1824 | getSize: () => ({ width: 1280, height: 720 }), |
| 1825 | })); |
| 1826 | const firstWebContents = makeTestPreviewWebContents(capturePage, 42); |
| 1827 | const replacementWebContents = makeTestPreviewWebContents(capturePage, 43); |
| 1828 | const replacementListenerSpies = replacementWebContents as unknown as { |
| 1829 | readonly on: ReturnType<typeof vi.fn>; |
| 1830 | readonly off: ReturnType<typeof vi.fn>; |
| 1831 | readonly ipc: { readonly off: ReturnType<typeof vi.fn> }; |
| 1832 | }; |
| 1833 | fromId.mockImplementation((id) => { |
| 1834 | if (id === 42) return firstWebContents; |
| 1835 | if (id === 43) return replacementWebContents; |
| 1836 | return null; |
| 1837 | }); |
| 1838 | const { pictureInPictureWindow } = makeTestPictureInPictureWindow(); |
| 1839 | browserWindowConstructor.mockImplementation(function () { |
| 1840 | return pictureInPictureWindow; |
| 1841 | }); |
| 1842 | |
| 1843 | yield* manager.createTab("tab_close_register_race"); |
| 1844 | yield* manager.registerWebview("tab_close_register_race", 42); |
| 1845 | yield* manager.openPictureInPicture("tab_close_register_race"); |
| 1846 | |
| 1847 | const closeCleanupPaused = yield* Deferred.make<void>(); |
| 1848 | const continueCloseCleanup = yield* Deferred.make<void>(); |
| 1849 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 1850 | !state.pictureInPicture && state.webContentsId === 42 |
| 1851 | ? Deferred.succeed(closeCleanupPaused, undefined).pipe( |
| 1852 | Effect.andThen(Deferred.await(continueCloseCleanup)), |
| 1853 | ) |
| 1854 | : Effect.void, |
| 1855 | ); |
| 1856 | |
| 1857 | const closeFiber = yield* manager |
| 1858 | .closeTab("tab_close_register_race") |
| 1859 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1860 | yield* Deferred.await(closeCleanupPaused); |
| 1861 | const recreateFiber = yield* manager |
| 1862 | .createTab("tab_close_register_race") |
| 1863 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1864 | const registrationFiber = yield* manager |
| 1865 | .registerWebview("tab_close_register_race", 43) |
| 1866 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1867 | yield* Effect.yieldNow; |
| 1868 | expect(replacementListenerSpies.on).not.toHaveBeenCalled(); |
| 1869 | yield* manager.closeTab("tab_close_register_race"); |
| 1870 | const recordingExit = yield* Effect.exit(manager.startRecording("tab_close_register_race")); |
| 1871 | yield* Deferred.succeed(continueCloseCleanup, undefined); |
| 1872 | yield* Fiber.join(closeFiber); |
| 1873 | const recreated = yield* Fiber.join(recreateFiber); |
| 1874 | const registrationExit = yield* Fiber.await(registrationFiber); |
| 1875 | |
| 1876 | for (const exit of [registrationExit, recordingExit] as ReadonlyArray< |
| 1877 | Exit.Exit<unknown, PreviewManager.PreviewManagerError> |
| 1878 | >) { |
| 1879 | expect(Exit.isFailure(exit)).toBe(true); |
| 1880 | if (Exit.isSuccess(exit)) continue; |
| 1881 | expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({ |
| 1882 | _tag: "PreviewTabNotFoundError", |
| 1883 | tabId: "tab_close_register_race", |
| 1884 | }); |
| 1885 | } |
| 1886 | expect(replacementListenerSpies.on).not.toHaveBeenCalled(); |
| 1887 | expect(replacementListenerSpies.off).not.toHaveBeenCalled(); |
| 1888 | expect(replacementListenerSpies.ipc.off).not.toHaveBeenCalled(); |
| 1889 | expect(capturePage).toHaveBeenCalledOnce(); |
| 1890 | expect(recreated.webContentsId).toBeNull(); |
| 1891 | }), |
| 1892 | ), |
| 1893 | ); |
| 1894 | |
| 1895 | effectIt.effect("captures final pixels after warmup fails and paint readiness settles", () => |
| 1896 | withManager((manager) => |
| 1897 | Effect.gen(function* () { |
| 1898 | const paint = Promise.withResolvers<void>(); |
| 1899 | const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise); |
| 1900 | capturePage |
| 1901 | .mockRejectedValueOnce(new Error("UnknownVizError")) |
| 1902 | .mockRejectedValueOnce(new Error("UnknownVizError")) |
| 1903 | .mockRejectedValueOnce(new Error("UnknownVizError")) |
| 1904 | .mockResolvedValue(makeStillImage("final-png")); |
| 1905 | const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); |
| 1906 | yield* TestClock.adjust(300); |
| 1907 | expect(capturePage).toHaveBeenCalledTimes(3); |
| 1908 | expect(writeFile).not.toHaveBeenCalled(); |
| 1909 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 1910 | paint.resolve(); |
| 1911 | const artifact = yield* Fiber.join(fiber); |
| 1912 | expect(capturePage).toHaveBeenCalledTimes(4); |
| 1913 | expect(writeFile.mock.calls).toEqual([[artifact.path, Buffer.from("final-png")]]); |
| 1914 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 1915 | }), |
| 1916 | ), |
| 1917 | ); |
| 1918 | |
| 1919 | effectIt.effect("preserves both screenshots of the same site in the same millisecond", () => |
| 1920 | withManager((manager) => |
| 1921 | Effect.gen(function* () { |
| 1922 | const firstPng = Buffer.from("first-preview-png"); |
| 1923 | const secondPng = Buffer.from("second-preview-png"); |
| 1924 | const pngImage = (png: Buffer) => ({ |
| 1925 | toPNG: () => png, |
| 1926 | toJPEG: () => png, |
| 1927 | getSize: () => ({ width: 1280, height: 720 }), |
| 1928 | }); |
| 1929 | const capturePage = vi |
| 1930 | .fn<() => Promise<ReturnType<typeof pngImage>>>() |
| 1931 | .mockResolvedValueOnce(pngImage(firstPng)) |
| 1932 | .mockResolvedValueOnce(pngImage(firstPng)) |
| 1933 | .mockResolvedValueOnce(pngImage(secondPng)) |
| 1934 | .mockResolvedValueOnce(pngImage(secondPng)); |
| 1935 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); |
| 1936 | yield* manager.createTab("tab_1"); |
| 1937 | yield* manager.registerWebview("tab_1", 42); |
| 1938 | const first = yield* manager.captureScreenshot("tab_1"); |
| 1939 | const second = yield* manager.captureScreenshot("tab_1"); |
| 1940 | |
| 1941 | expect(first.createdAt).toBe(second.createdAt); |
| 1942 | expect(first.id).not.toBe(second.id); |
| 1943 | expect(first.path).not.toBe(second.path); |
| 1944 | expect(first.id).toMatch(/^browser-screenshot-example-com-[a-z0-9]+-[0-9a-f]{8}$/); |
| 1945 | expect(second.id).toMatch(/^browser-screenshot-example-com-[a-z0-9]+-[0-9a-f]{8}$/); |
| 1946 | expect(writeFile.mock.calls).toEqual([ |
| 1947 | [first.path, firstPng], |
| 1948 | [second.path, secondPng], |
| 1949 | ]); |
| 1950 | }), |
| 1951 | ), |
| 1952 | ); |
| 1953 | |
| 1954 | effectIt.effect( |
| 1955 | "waits for paint before capturing and restores rendering after overlapping requests", |
| 1956 | () => |
| 1957 | withManager((manager) => |
| 1958 | Effect.gen(function* () { |
| 1959 | const paints = [Promise.withResolvers<void>(), Promise.withResolvers<void>()]; |
| 1960 | const pendingPaints = paints.map((paint) => paint.promise); |
| 1961 | const { image, capturePage, wc, capture } = yield* setupStill(manager); |
| 1962 | holdStillImagePaint(wc, pendingPaints); |
| 1963 | const first = Promise.withResolvers<typeof image>(); |
| 1964 | const second = Promise.withResolvers<typeof image>(); |
| 1965 | capturePage |
| 1966 | .mockResolvedValueOnce(makeStillImage("discarded-warmup")) |
| 1967 | .mockResolvedValueOnce(makeStillImage("discarded-warmup")) |
| 1968 | .mockReturnValueOnce(first.promise) |
| 1969 | .mockReturnValueOnce(second.promise); |
| 1970 | const hostThrottling = vi.fn(); |
| 1971 | yield* manager.setMainWindow({ |
| 1972 | isDestroyed: () => false, |
| 1973 | once: vi.fn(), |
| 1974 | webContents: { setBackgroundThrottling: hostThrottling }, |
| 1975 | } as never); |
| 1976 | const one = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); |
| 1977 | const two = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); |
| 1978 | yield* TestClock.adjust(0); |
| 1979 | expect(capturePage).toHaveBeenCalledTimes(2); |
| 1980 | expect(pendingPaints).toHaveLength(0); |
| 1981 | expect(writeFile).not.toHaveBeenCalled(); |
| 1982 | expect(hostThrottling.mock.calls).toEqual([[false]]); |
| 1983 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 1984 | paints.forEach((paint) => paint.resolve()); |
| 1985 | yield* TestClock.adjust(0); |
| 1986 | expect(capturePage).toHaveBeenCalledTimes(4); |
| 1987 | first.resolve(image); |
| 1988 | yield* Fiber.join(one); |
| 1989 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 1990 | second.resolve(image); |
| 1991 | yield* Fiber.join(two); |
| 1992 | const saved = writeFile.mock.calls.map(([, bytes]) => bytes); |
| 1993 | expect(saved).toEqual([image.toPNG(), image.toPNG()]); |
| 1994 | expect(hostThrottling.mock.calls).toEqual([[false], [true]]); |
| 1995 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 1996 | }), |
| 1997 | ), |
| 1998 | ); |
| 1999 | |
| 2000 | effectIt.effect("keeps picture-in-picture rendering after a still image completes", () => |
| 2001 | withManager((manager) => |
| 2002 | Effect.gen(function* () { |
| 2003 | const { image, capturePage, wc, capture } = yield* setupStill(manager); |
| 2004 | const pending = Promise.withResolvers<typeof image>(); |
| 2005 | capturePage |
| 2006 | .mockResolvedValueOnce(image) |
| 2007 | .mockResolvedValueOnce(makeStillImage("discarded-warmup")) |
| 2008 | .mockReturnValueOnce(pending.promise); |
| 2009 | const { pictureInPictureWindow } = makeTestPictureInPictureWindow(); |
| 2010 | browserWindowConstructor.mockImplementation(function () { |
| 2011 | return pictureInPictureWindow; |
| 2012 | }); |
| 2013 | yield* manager.openPictureInPicture("tab_still"); |
| 2014 | const still = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); |
| 2015 | yield* TestClock.adjust(0); |
| 2016 | expect(capturePage).toHaveBeenCalledTimes(3); |
| 2017 | expect(writeFile).not.toHaveBeenCalled(); |
| 2018 | pending.resolve(image); |
| 2019 | yield* Fiber.join(still); |
| 2020 | expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]); |
| 2021 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2022 | yield* manager.closePictureInPicture("tab_still"); |
| 2023 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2024 | }), |
| 2025 | ), |
| 2026 | ); |
| 2027 | |
| 2028 | effectIt.effect("keeps a pending still image rendering when recording ends", () => |
| 2029 | withManager((manager) => |
| 2030 | Effect.gen(function* () { |
| 2031 | const { image, capturePage, wc, capture } = yield* setupStill(manager); |
| 2032 | const pending = Promise.withResolvers<typeof image>(); |
| 2033 | capturePage.mockResolvedValueOnce(image).mockReturnValue(pending.promise); |
| 2034 | yield* manager.startRecording("tab_still"); |
| 2035 | const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); |
| 2036 | yield* TestClock.adjust(0); |
| 2037 | yield* manager.stopRecording("tab_still"); |
| 2038 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2039 | pending.resolve(image); |
| 2040 | yield* Fiber.join(fiber); |
| 2041 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2042 | }), |
| 2043 | ), |
| 2044 | ); |
| 2045 | |
| 2046 | effectIt.effect("saves available pixels when paint readiness never settles", () => |
| 2047 | withManager((manager) => |
| 2048 | Effect.gen(function* () { |
| 2049 | const paint = Promise.withResolvers<void>(); |
| 2050 | const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise); |
| 2051 | const first = yield* Effect.exit(capture).pipe( |
| 2052 | Effect.forkChild({ startImmediately: true }), |
| 2053 | ); |
| 2054 | yield* TestClock.adjust(1_001); |
| 2055 | expect(Exit.isSuccess(yield* Fiber.join(first))).toBe(true); |
| 2056 | expect(capturePage).toHaveBeenCalledTimes(2); |
| 2057 | expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]); |
| 2058 | expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2059 | }), |
| 2060 | ), |
| 2061 | ); |
| 2062 | |
| 2063 | effectIt.effect("keeps every recorded guest unthrottled until its frame capture stops", () => |
| 2064 | withManager((manager) => |
| 2065 | Effect.gen(function* () { |
| 2066 | const setBackgroundThrottling = vi.fn(); |
| 2067 | const capturePage = vi.fn(async () => ({ |
| 2068 | toJPEG: () => Buffer.from("recording-frame"), |
| 2069 | getSize: () => ({ width: 1280, height: 720 }), |
| 2070 | })); |
| 2071 | const host = makeTestHostWebContents(); |
| 2072 | const firstWebContents = makeTestPreviewWebContents(capturePage, 41, host); |
| 2073 | const secondWebContents = makeTestPreviewWebContents(capturePage, 42, host); |
| 2074 | const webContentsById = new Map([ |
| 2075 | [41, firstWebContents], |
| 2076 | [42, secondWebContents], |
| 2077 | ]); |
| 2078 | fromId.mockImplementation((id) => |
| 2079 | id === undefined ? null : (webContentsById.get(id) ?? null), |
| 2080 | ); |
| 2081 | |
| 2082 | yield* manager.createTab("tab_capture_throttling_1"); |
| 2083 | yield* manager.createTab("tab_capture_throttling_2"); |
| 2084 | yield* manager.registerWebview("tab_capture_throttling_1", 41); |
| 2085 | yield* manager.registerWebview("tab_capture_throttling_2", 42); |
| 2086 | yield* manager.setMainWindow({ |
| 2087 | isDestroyed: () => false, |
| 2088 | once: vi.fn(), |
| 2089 | webContents: { setBackgroundThrottling }, |
| 2090 | } as never); |
| 2091 | |
| 2092 | yield* manager.startRecording("tab_capture_throttling_1"); |
| 2093 | host.displayMediaHandler()?.({ frame: host.mainFrame }, () => {}); |
| 2094 | yield* manager.startRecording("tab_capture_throttling_2"); |
| 2095 | expect(setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2096 | expect(firstWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2097 | expect(secondWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2098 | |
| 2099 | yield* manager.stopRecording("tab_capture_throttling_1"); |
| 2100 | expect(setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2101 | expect(firstWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2102 | expect(secondWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2103 | |
| 2104 | yield* manager.stopRecording("tab_capture_throttling_2"); |
| 2105 | expect(setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2106 | expect(secondWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2107 | }), |
| 2108 | ), |
| 2109 | ); |
| 2110 | |
| 2111 | effectIt.effect("does not commit failed starts and retries throttle restoration", () => |
| 2112 | withManager((manager) => |
| 2113 | Effect.gen(function* () { |
| 2114 | const setBackgroundThrottling = vi.fn<(enabled: boolean) => void>(); |
| 2115 | const capturePage = vi.fn(async () => ({ |
| 2116 | toJPEG: () => Buffer.from("recording-frame"), |
| 2117 | getSize: () => ({ width: 1280, height: 720 }), |
| 2118 | })); |
| 2119 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); |
| 2120 | |
| 2121 | yield* manager.createTab("tab_capture_throttling_failure"); |
| 2122 | yield* manager.registerWebview("tab_capture_throttling_failure", 42); |
| 2123 | yield* manager.setMainWindow({ |
| 2124 | isDestroyed: () => false, |
| 2125 | once: vi.fn(), |
| 2126 | webContents: { setBackgroundThrottling }, |
| 2127 | } as never); |
| 2128 | |
| 2129 | setBackgroundThrottling.mockImplementationOnce(() => { |
| 2130 | throw new Error("start throttling update failed"); |
| 2131 | }); |
| 2132 | const failedStart = yield* Effect.exit( |
| 2133 | manager.startRecording("tab_capture_throttling_failure"), |
| 2134 | ); |
| 2135 | expect(Exit.isFailure(failedStart)).toBe(true); |
| 2136 | |
| 2137 | yield* manager.startRecording("tab_capture_throttling_failure"); |
| 2138 | expect(setBackgroundThrottling.mock.calls).toEqual([[false], [false]]); |
| 2139 | |
| 2140 | setBackgroundThrottling.mockImplementationOnce(() => { |
| 2141 | throw new Error("stop throttling update failed"); |
| 2142 | }); |
| 2143 | yield* manager.stopRecording("tab_capture_throttling_failure"); |
| 2144 | expect(setBackgroundThrottling.mock.calls).toEqual([[false], [false], [true], [true]]); |
| 2145 | |
| 2146 | yield* manager.startRecording("tab_capture_throttling_failure"); |
| 2147 | yield* manager.stopRecording("tab_capture_throttling_failure"); |
| 2148 | expect(setBackgroundThrottling.mock.calls).toEqual([ |
| 2149 | [false], |
| 2150 | [false], |
| 2151 | [true], |
| 2152 | [true], |
| 2153 | [false], |
| 2154 | [true], |
| 2155 | ]); |
| 2156 | }), |
| 2157 | ), |
| 2158 | ); |
| 2159 | |
| 2160 | effectIt.effect("keeps frame capture closed when a replacement is destroyed during cleanup", () => |
| 2161 | withManager((manager) => |
| 2162 | Effect.gen(function* () { |
| 2163 | const windowEvents = new Map<string, () => void>(); |
| 2164 | const host = makeTestHostWebContents(); |
| 2165 | const capturePage = vi.fn(async () => ({ |
| 2166 | toJPEG: () => Buffer.from("recording-frame"), |
| 2167 | getSize: () => ({ width: 1280, height: 720 }), |
| 2168 | })); |
| 2169 | const guest = makeTestPreviewWebContents(capturePage, 42, host); |
| 2170 | fromId.mockReturnValue(guest); |
| 2171 | yield* manager.createTab("tab_shutdown"); |
| 2172 | yield* manager.registerWebview("tab_shutdown", 42); |
| 2173 | yield* manager.setMainWindow({ |
| 2174 | isDestroyed: () => false, |
| 2175 | once: (event: string, listener: () => void) => windowEvents.set(event, listener), |
| 2176 | webContents: { setBackgroundThrottling: vi.fn() }, |
| 2177 | } as never); |
| 2178 | yield* manager.startRecording("tab_shutdown"); |
| 2179 | const pip = makeTestPictureInPictureWindow(); |
| 2180 | browserWindowConstructor.mockImplementation(function () { |
| 2181 | return pip.pictureInPictureWindow; |
| 2182 | }); |
| 2183 | yield* manager.openPictureInPicture("tab_shutdown"); |
| 2184 | const capturesBeforeClose = capturePage.mock.calls.length; |
| 2185 | const cleanupStarted = yield* Deferred.make<void>(); |
| 2186 | const releaseCleanup = yield* Deferred.make<void>(); |
| 2187 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 2188 | state.pictureInPicture |
| 2189 | ? Effect.void |
| 2190 | : Deferred.succeed(cleanupStarted, undefined).pipe( |
| 2191 | Effect.andThen(Deferred.await(releaseCleanup)), |
| 2192 | ), |
| 2193 | ); |
| 2194 | |
| 2195 | windowEvents.get("closed")!(); |
| 2196 | yield* Deferred.await(cleanupStarted); |
| 2197 | let destroyed = false; |
| 2198 | const replacement = yield* manager |
| 2199 | .setMainWindow({ |
| 2200 | isDestroyed: () => destroyed, |
| 2201 | once: vi.fn(), |
| 2202 | webContents: { setBackgroundThrottling: vi.fn() }, |
| 2203 | } as never) |
| 2204 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 2205 | try { |
| 2206 | expect(replacement.pollUnsafe()).toBeUndefined(); |
| 2207 | destroyed = true; |
| 2208 | } finally { |
| 2209 | yield* Deferred.succeed(releaseCleanup, undefined); |
| 2210 | } |
| 2211 | yield* Fiber.join(replacement); |
| 2212 | |
| 2213 | const restart = yield* Effect.exit(manager.startRecording("tab_shutdown")); |
| 2214 | expect(Exit.isFailure(restart)).toBe(true); |
| 2215 | if (Exit.isFailure(restart)) { |
| 2216 | expect(Option.getOrThrow(Cause.findErrorOption(restart.cause))).toMatchObject({ |
| 2217 | _tag: "PreviewMainWindowClosedError", |
| 2218 | tabId: "tab_shutdown", |
| 2219 | }); |
| 2220 | } |
| 2221 | expect(capturePage).toHaveBeenCalledTimes(capturesBeforeClose); |
| 2222 | expect(pip.pictureInPictureWindow.isDestroyed()).toBe(true); |
| 2223 | expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2224 | const grants: Array<{ video?: unknown }> = []; |
| 2225 | host.displayMediaHandler()?.({ frame: host.mainFrame }, (value) => grants.push(value)); |
| 2226 | expect(grants).toEqual([{}]); |
| 2227 | }), |
| 2228 | ), |
| 2229 | ); |
| 2230 | |
| 2231 | effectIt.effect("ignores close events from replaced main windows", () => |
| 2232 | withManager((manager) => |
| 2233 | Effect.gen(function* () { |
| 2234 | let closeFirstWindow: (() => void) | undefined; |
| 2235 | const firstWindowThrottling = vi.fn(); |
| 2236 | const replacementWindowThrottling = vi.fn(); |
| 2237 | const capturePage = vi.fn(async () => ({ |
| 2238 | toJPEG: () => Buffer.from("recording-frame"), |
| 2239 | getSize: () => ({ width: 1280, height: 720 }), |
| 2240 | })); |
| 2241 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); |
| 2242 | |
| 2243 | yield* manager.createTab("tab_replaced_window_close"); |
| 2244 | yield* manager.registerWebview("tab_replaced_window_close", 42); |
| 2245 | yield* manager.setMainWindow({ |
| 2246 | isDestroyed: () => false, |
| 2247 | once: vi.fn((event: string, listener: () => void) => { |
| 2248 | if (event === "closed") closeFirstWindow = listener; |
| 2249 | }), |
| 2250 | webContents: { setBackgroundThrottling: firstWindowThrottling }, |
| 2251 | } as never); |
| 2252 | yield* manager.setMainWindow({ |
| 2253 | isDestroyed: () => false, |
| 2254 | once: vi.fn(), |
| 2255 | webContents: { setBackgroundThrottling: replacementWindowThrottling }, |
| 2256 | } as never); |
| 2257 | |
| 2258 | closeFirstWindow?.(); |
| 2259 | yield* manager.startRecording("tab_replaced_window_close"); |
| 2260 | expect(firstWindowThrottling).not.toHaveBeenCalled(); |
| 2261 | expect(replacementWindowThrottling.mock.calls).toEqual([[false]]); |
| 2262 | yield* manager.stopRecording("tab_replaced_window_close"); |
| 2263 | expect(replacementWindowThrottling.mock.calls).toEqual([[false], [true]]); |
| 2264 | }), |
| 2265 | ), |
| 2266 | ); |
| 2267 | |
| 2268 | effectIt.effect("releases frame capture when the main window closes", () => |
| 2269 | withManager((manager) => |
| 2270 | Effect.gen(function* () { |
| 2271 | let closeMainWindow: (() => void) | undefined; |
| 2272 | const firstWindowThrottling = vi.fn(); |
| 2273 | const replacementWindowThrottling = vi.fn(); |
| 2274 | const capturePage = vi.fn(async () => ({ |
| 2275 | toJPEG: () => Buffer.from("recording-frame"), |
| 2276 | getSize: () => ({ width: 1280, height: 720 }), |
| 2277 | })); |
| 2278 | const host = makeTestHostWebContents(); |
| 2279 | const webContentsById = new Map([ |
| 2280 | [42, makeTestPreviewWebContents(capturePage, 42, host)], |
| 2281 | [43, makeTestPreviewWebContents(capturePage, 43, host)], |
| 2282 | ]); |
| 2283 | fromId.mockImplementation((id) => |
| 2284 | id === undefined ? null : (webContentsById.get(id) ?? null), |
| 2285 | ); |
| 2286 | |
| 2287 | yield* manager.createTab("tab_window_close_recording"); |
| 2288 | yield* manager.createTab("tab_window_close_race"); |
| 2289 | yield* manager.registerWebview("tab_window_close_recording", 42); |
| 2290 | yield* manager.registerWebview("tab_window_close_race", 43); |
| 2291 | yield* manager.setMainWindow({ |
| 2292 | isDestroyed: () => false, |
| 2293 | once: vi.fn((event: string, listener: () => void) => { |
| 2294 | if (event === "closed") closeMainWindow = listener; |
| 2295 | }), |
| 2296 | webContents: { setBackgroundThrottling: firstWindowThrottling }, |
| 2297 | } as never); |
| 2298 | yield* manager.startRecording("tab_window_close_recording"); |
| 2299 | expect(firstWindowThrottling.mock.calls).toEqual([[false]]); |
| 2300 | |
| 2301 | closeMainWindow?.(); |
| 2302 | const racedStart = yield* Effect.exit(manager.startRecording("tab_window_close_race")); |
| 2303 | expect(Exit.isFailure(racedStart)).toBe(true); |
| 2304 | if (Exit.isFailure(racedStart)) { |
| 2305 | expect(Option.getOrThrow(Cause.findErrorOption(racedStart.cause))).toMatchObject({ |
| 2306 | _tag: "PreviewMainWindowClosedError", |
| 2307 | tabId: "tab_window_close_race", |
| 2308 | }); |
| 2309 | } |
| 2310 | yield* Effect.yieldNow; |
| 2311 | yield* Effect.yieldNow; |
| 2312 | |
| 2313 | const grants: Array<{ video?: unknown }> = []; |
| 2314 | host.displayMediaHandler()?.({ frame: host.mainFrame }, (value) => grants.push(value)); |
| 2315 | expect(grants).toEqual([{}]); |
| 2316 | |
| 2317 | yield* manager.setMainWindow({ |
| 2318 | isDestroyed: () => false, |
| 2319 | once: vi.fn(), |
| 2320 | webContents: { setBackgroundThrottling: replacementWindowThrottling }, |
| 2321 | } as never); |
| 2322 | expect(replacementWindowThrottling).not.toHaveBeenCalled(); |
| 2323 | }), |
| 2324 | ), |
| 2325 | ); |
| 2326 | |
| 2327 | effectIt.effect("does not arm recording after the main window closes during warmup", () => |
| 2328 | withManager((manager) => |
| 2329 | Effect.gen(function* () { |
| 2330 | let closeMainWindow: (() => void) | undefined; |
| 2331 | let finishWarmup!: (image: TestCapturedPreviewImage) => void; |
| 2332 | let markWarmupStarted!: () => void; |
| 2333 | const warmupStarted = new Promise<void>((resolve) => { |
| 2334 | markWarmupStarted = resolve; |
| 2335 | }); |
| 2336 | const capturedImage = { |
| 2337 | toJPEG: () => Buffer.from("recording-frame"), |
| 2338 | getSize: () => ({ width: 1280, height: 720 }), |
| 2339 | }; |
| 2340 | const capturePage = vi.fn( |
| 2341 | () => |
| 2342 | new Promise<TestCapturedPreviewImage>((resolve) => { |
| 2343 | markWarmupStarted(); |
| 2344 | finishWarmup = resolve; |
| 2345 | }), |
| 2346 | ); |
| 2347 | const host = makeTestHostWebContents(); |
| 2348 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42, host)); |
| 2349 | |
| 2350 | yield* manager.createTab("tab_window_close_warmup"); |
| 2351 | yield* manager.registerWebview("tab_window_close_warmup", 42); |
| 2352 | yield* manager.setMainWindow({ |
| 2353 | isDestroyed: () => false, |
| 2354 | once: vi.fn((event: string, listener: () => void) => { |
| 2355 | if (event === "closed") closeMainWindow = listener; |
| 2356 | }), |
| 2357 | webContents: { setBackgroundThrottling: vi.fn() }, |
| 2358 | } as never); |
| 2359 | |
| 2360 | const start = yield* manager |
| 2361 | .startRecording("tab_window_close_warmup") |
| 2362 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 2363 | yield* Effect.promise(() => warmupStarted); |
| 2364 | closeMainWindow?.(); |
| 2365 | finishWarmup(capturedImage); |
| 2366 | |
| 2367 | const exit = yield* Fiber.await(start); |
| 2368 | expect(Exit.isFailure(exit)).toBe(true); |
| 2369 | if (Exit.isFailure(exit)) { |
| 2370 | expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({ |
| 2371 | _tag: "PreviewMainWindowClosedError", |
| 2372 | tabId: "tab_window_close_warmup", |
| 2373 | }); |
| 2374 | } |
| 2375 | expect(host.session.setDisplayMediaRequestHandler).not.toHaveBeenCalled(); |
| 2376 | }), |
| 2377 | ), |
| 2378 | ); |
| 2379 | |
| 2380 | effectIt.effect("tells the server when a tab it renders natively closes", () => |
| 2381 | Effect.gen(function* () { |
| 2382 | const host = yield* DesktopBrowserHost.DesktopBrowserHost; |
| 2383 | const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; |
| 2384 | const lines = yield* Queue.unbounded<string>(); |
| 2385 | yield* host.events.pipe( |
| 2386 | Stream.runForEach((line) => Queue.offer(lines, new TextDecoder().decode(line))), |
| 2387 | Effect.forkScoped, |
| 2388 | ); |
| 2389 | const nextType = Queue.take(lines).pipe( |
| 2390 | Effect.map((line) => /"type":"(\w+)"/.exec(line)?.[1]), |
| 2391 | ); |
| 2392 | const capturePage = vi.fn(async () => ({ |
| 2393 | toPNG: () => Buffer.from("png"), |
| 2394 | toJPEG: () => Buffer.from("jpeg"), |
| 2395 | getSize: () => ({ width: 100, height: 80 }), |
| 2396 | })); |
| 2397 | fromId.mockReturnValue( |
| 2398 | Object.assign(makeTestPreviewWebContents(capturePage, 42), { |
| 2399 | isDevToolsOpened: () => false, |
| 2400 | getUserAgent: () => "Electron", |
| 2401 | }), |
| 2402 | ); |
| 2403 | const manager = yield* PreviewManager.PreviewManager; |
| 2404 | yield* manager.createTab("tab_1", { serverTab }); |
| 2405 | yield* manager.registerWebview("tab_1", 42); |
| 2406 | expect(yield* nextType).toBe("attached"); |
| 2407 | yield* manager.closeTab("tab_1"); |
| 2408 | expect(yield* nextType).toBe("detached"); |
| 2409 | }).pipe(Effect.provide(managerLayer())), |
| 2410 | ); |
| 2411 | |
| 2412 | effectIt.effect( |
| 2413 | "asks the client to paint a navigated server tab while the agent captures it", |
| 2414 | () => |
| 2415 | Effect.gen(function* () { |
| 2416 | const host = yield* DesktopBrowserHost.DesktopBrowserHost; |
| 2417 | const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; |
| 2418 | const windowThrottling = vi.fn<(enabled: boolean) => void>(); |
| 2419 | const mainWebContents = Object.assign(makeTestHostWebContents(), { |
| 2420 | setBackgroundThrottling: windowThrottling, |
| 2421 | }); |
| 2422 | const contents = Object.assign( |
| 2423 | makeTestPreviewWebContents( |
| 2424 | async () => { |
| 2425 | throw new Error("unused"); |
| 2426 | }, |
| 2427 | 42, |
| 2428 | mainWebContents, |
| 2429 | ), |
| 2430 | { |
| 2431 | isDevToolsOpened: () => false, |
| 2432 | getUserAgent: () => "Electron", |
| 2433 | loadURL: vi.fn(async () => undefined), |
| 2434 | }, |
| 2435 | ); |
| 2436 | const screenshot = Promise.withResolvers<unknown>(); |
| 2437 | contents.debugger.sendCommand = vi.fn((method: string) => |
| 2438 | method === "Page.captureScreenshot" ? screenshot.promise : Promise.resolve(undefined), |
| 2439 | ) as unknown as typeof contents.debugger.sendCommand; |
| 2440 | fromId.mockReturnValue(contents); |
| 2441 | const manager = yield* PreviewManager.PreviewManager; |
| 2442 | yield* manager.setMainWindow({ |
| 2443 | isDestroyed: () => false, |
| 2444 | once: vi.fn(), |
| 2445 | webContents: mainWebContents, |
| 2446 | } as never); |
| 2447 | const capturing = yield* Queue.unbounded<boolean>(); |
| 2448 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 2449 | Queue.offer(capturing, state.capturing).pipe(Effect.asVoid), |
| 2450 | ); |
| 2451 | const attached = yield* Deferred.make<void>(); |
| 2452 | yield* host.events.pipe( |
| 2453 | Stream.runForEach((line) => |
| 2454 | new TextDecoder().decode(line).includes('"type":"attached"') |
| 2455 | ? Deferred.succeed(attached, undefined) |
| 2456 | : Effect.void, |
| 2457 | ), |
| 2458 | Effect.forkScoped, |
| 2459 | ); |
| 2460 | yield* manager.createTab("tab_1", { serverTab }); |
| 2461 | yield* manager.registerWebview("tab_1", 42); |
| 2462 | yield* Deferred.await(attached); |
| 2463 | // Navigating rebuilds the tab's state, which must keep the server tab it answers for. |
| 2464 | yield* manager.navigate("tab_1", "https://example.com/next"); |
| 2465 | yield* Queue.clear(capturing); |
| 2466 | |
| 2467 | yield* host.handleCommandLine( |
| 2468 | JSON.stringify({ |
| 2469 | type: "cdp", |
| 2470 | ...serverTab, |
| 2471 | message: JSON.stringify({ |
| 2472 | id: 1, |
| 2473 | method: "Page.captureScreenshot", |
| 2474 | sessionId: "t3-preview-page", |
| 2475 | }), |
| 2476 | }), |
| 2477 | ); |
| 2478 | expect(yield* Queue.take(capturing)).toBe(true); |
| 2479 | // A locked or covered window paints a guest it had hidden only while unthrottled. |
| 2480 | expect(windowThrottling.mock.calls).toEqual([[false]]); |
| 2481 | expect(contents.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 2482 | yield* manager.setCaptureDrawn("tab_1", true); |
| 2483 | screenshot.resolve({ data: "" }); |
| 2484 | expect(yield* Queue.take(capturing)).toBe(false); |
| 2485 | expect(windowThrottling.mock.calls).toEqual([[false], [true]]); |
| 2486 | expect(contents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 2487 | }).pipe(Effect.provide(managerLayer())), |
| 2488 | ); |
| 2489 | |
| 2490 | effectIt.effect( |
| 2491 | "opens a new-tab link in the background only when the agent's input led to it", |
| 2492 | () => |
| 2493 | Effect.gen(function* () { |
| 2494 | const host = yield* DesktopBrowserHost.DesktopBrowserHost; |
| 2495 | const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; |
| 2496 | const contents = Object.assign( |
| 2497 | makeTestPreviewWebContents(async () => { |
| 2498 | throw new Error("unused"); |
| 2499 | }, 42), |
| 2500 | { |
| 2501 | isDevToolsOpened: () => false, |
| 2502 | getUserAgent: () => "Electron", |
| 2503 | focusedFrame: null, |
| 2504 | }, |
| 2505 | ); |
| 2506 | fromId.mockReturnValue(contents); |
| 2507 | const manager = yield* PreviewManager.PreviewManager; |
| 2508 | const openLinks = yield* Queue.unbounded<boolean>(); |
| 2509 | yield* manager.subscribeOpenLinks(({ background }) => |
| 2510 | Queue.offer(openLinks, background).pipe(Effect.asVoid), |
| 2511 | ); |
| 2512 | const attached = yield* Deferred.make<void>(); |
| 2513 | yield* host.events.pipe( |
| 2514 | Stream.runForEach((line) => |
| 2515 | new TextDecoder().decode(line).includes('"type":"attached"') |
| 2516 | ? Deferred.succeed(attached, undefined) |
| 2517 | : Effect.void, |
| 2518 | ), |
| 2519 | Effect.forkScoped, |
| 2520 | ); |
| 2521 | yield* manager.createTab("tab_1", { serverTab }); |
| 2522 | yield* manager.registerWebview("tab_1", 42); |
| 2523 | yield* Deferred.await(attached); |
| 2524 | const openWindow = vi.mocked(contents.setWindowOpenHandler).mock.calls[0]![0]; |
| 2525 | const openBlankLink = Effect.suspend(() => { |
| 2526 | openWindow({ |
| 2527 | url: "https://example.com/next", |
| 2528 | disposition: "foreground-tab", |
| 2529 | } as Electron.HandlerDetails); |
| 2530 | return Queue.take(openLinks); |
| 2531 | }); |
| 2532 | |
| 2533 | expect(yield* openBlankLink).toBe(false); |
| 2534 | |
| 2535 | yield* host.handleCommandLine( |
| 2536 | JSON.stringify({ |
| 2537 | type: "cdp", |
| 2538 | ...serverTab, |
| 2539 | message: JSON.stringify({ |
| 2540 | id: 1, |
| 2541 | method: "Runtime.evaluate", |
| 2542 | params: { expression: "document.querySelector('a').click()" }, |
| 2543 | sessionId: "t3-preview-page", |
| 2544 | }), |
| 2545 | }), |
| 2546 | ); |
| 2547 | expect(yield* openBlankLink).toBe(true); |
| 2548 | |
| 2549 | // A person clicking in the guest itself gives it a focused frame. |
| 2550 | Object.assign(contents, { focusedFrame: {} }); |
| 2551 | expect(yield* openBlankLink).toBe(false); |
| 2552 | }).pipe(Effect.provide(managerLayer()), Effect.scoped), |
| 2553 | ); |
| 2554 | |
| 2555 | effectIt.effect("reports early and subsequent load failures for the current guest", () => |
| 2556 | Effect.gen(function* () { |
| 2557 | const host = yield* DesktopBrowserHost.DesktopBrowserHost; |
| 2558 | const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; |
| 2559 | const lines = yield* Queue.unbounded<string>(); |
| 2560 | yield* host.events.pipe( |
| 2561 | Stream.runForEach((line) => Queue.offer(lines, new TextDecoder().decode(line))), |
| 2562 | Effect.forkScoped({ startImmediately: true }), |
| 2563 | ); |
| 2564 | const makeGuest = (id: number) => { |
| 2565 | const listeners = new Map<string, Array<(...args: unknown[]) => void>>(); |
| 2566 | const wc = Object.assign( |
| 2567 | makeTestPreviewWebContents( |
| 2568 | async () => ({ |
| 2569 | toJPEG: () => Buffer.from("jpeg"), |
| 2570 | getSize: () => ({ width: 100, height: 80 }), |
| 2571 | }), |
| 2572 | id, |
| 2573 | ), |
| 2574 | { |
| 2575 | isDevToolsOpened: () => false, |
| 2576 | getUserAgent: () => "Electron", |
| 2577 | once: vi.fn(), |
| 2578 | on: (event: string, listener: (...args: unknown[]) => void) => { |
| 2579 | listeners.set(event, [...(listeners.get(event) ?? []), listener]); |
| 2580 | }, |
| 2581 | }, |
| 2582 | ); |
| 2583 | const emit = (event: string, ...args: unknown[]) => { |
| 2584 | for (const listener of listeners.get(event) ?? []) listener(...args); |
| 2585 | }; |
| 2586 | return { |
| 2587 | wc, |
| 2588 | emit, |
| 2589 | fail: (url: string) => |
| 2590 | emit("did-fail-load", {}, -202, "ERR_CERT_AUTHORITY_INVALID", url, true), |
| 2591 | }; |
| 2592 | }; |
| 2593 | const initial = makeGuest(42); |
| 2594 | const replacement = makeGuest(43); |
| 2595 | const manager = yield* PreviewManager.PreviewManager; |
| 2596 | const statuses: PreviewManager.PreviewNavStatus[] = []; |
| 2597 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 2598 | Effect.sync(() => { |
| 2599 | statuses.push(state.navStatus); |
| 2600 | }), |
| 2601 | ); |
| 2602 | yield* manager.createTab("tab_1", { serverTab }); |
| 2603 | yield* manager.prepareWebview(initial.wc); |
| 2604 | yield* manager.prepareWebview(replacement.wc); |
| 2605 | initial.fail("https://first.local/"); |
| 2606 | initial.emit("did-start-navigation", { isMainFrame: false, isSameDocument: false }); |
| 2607 | initial.emit("did-start-loading"); |
| 2608 | replacement.fail("https://second.local/"); |
| 2609 | const failure = (url: string) => ({ |
| 2610 | type: "loadFailed", |
| 2611 | ...serverTab, |
| 2612 | url, |
| 2613 | code: -202, |
| 2614 | description: "ERR_CERT_AUTHORITY_INVALID", |
| 2615 | }); |
| 2616 | |
| 2617 | fromId.mockReturnValue(initial.wc); |
| 2618 | yield* manager.registerWebview("tab_1", 42); |
| 2619 | expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab }); |
| 2620 | expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://first.local/")); |
| 2621 | |
| 2622 | fromId.mockReturnValue(replacement.wc); |
| 2623 | yield* manager.registerWebview("tab_1", 43); |
| 2624 | expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab }); |
| 2625 | expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab }); |
| 2626 | expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://second.local/")); |
| 2627 | |
| 2628 | // A callback queued by the old guest must not report a failure for its replacement. |
| 2629 | initial.fail("https://stale.local/"); |
| 2630 | replacement.fail("https://current.local/"); |
| 2631 | expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://current.local/")); |
| 2632 | expect(statuses).not.toContainEqual(expect.objectContaining({ url: "https://stale.local/" })); |
| 2633 | |
| 2634 | const retried = makeGuest(44); |
| 2635 | yield* manager.prepareWebview(retried.wc); |
| 2636 | retried.fail("https://retry.local/"); |
| 2637 | retried.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }); |
| 2638 | fromId.mockReturnValue(retried.wc); |
| 2639 | yield* manager.registerWebview("tab_1", 44); |
| 2640 | expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab }); |
| 2641 | expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab }); |
| 2642 | expect(statuses.at(-1)?.kind).toBe("Success"); |
| 2643 | }).pipe(Effect.provide(managerLayer())), |
| 2644 | ); |
| 2645 | |
| 2646 | effectIt.effect("discards a screenshot that resolves after its guest is replaced", () => |
| 2647 | withManager((manager) => |
| 2648 | Effect.gen(function* () { |
| 2649 | const image = { |
| 2650 | toPNG: () => Buffer.from("stale-png"), |
| 2651 | toJPEG: () => Buffer.from("stale-jpeg"), |
| 2652 | getSize: () => ({ width: 100, height: 80 }), |
| 2653 | }; |
| 2654 | const pending = Promise.withResolvers<typeof image>(); |
| 2655 | const capturePage = vi.fn(() => pending.promise); |
| 2656 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42)); |
| 2657 | yield* manager.createTab("tab_1"); |
| 2658 | yield* manager.registerWebview("tab_1", 42); |
| 2659 | |
| 2660 | const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe( |
| 2661 | Effect.forkChild({ startImmediately: true }), |
| 2662 | ); |
| 2663 | yield* TestClock.adjust(0); |
| 2664 | expect(capturePage).toHaveBeenCalledOnce(); |
| 2665 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43)); |
| 2666 | yield* manager.registerWebview("tab_1", 43); |
| 2667 | pending.resolve(image); |
| 2668 | const exit = yield* Fiber.join(fiber); |
| 2669 | |
| 2670 | expect(Exit.isFailure(exit)).toBe(true); |
| 2671 | expect(capturePage).toHaveBeenCalledOnce(); |
| 2672 | expect(writeFile).not.toHaveBeenCalled(); |
| 2673 | }), |
| 2674 | ), |
| 2675 | ); |
| 2676 | |
| 2677 | effectIt.effect("grants each concurrent preview recording its own tab frame", () => |
| 2678 | withManager((manager) => |
| 2679 | Effect.gen(function* () { |
| 2680 | const firstJpeg = Buffer.from("first-recording-frame"); |
| 2681 | const secondJpeg = Buffer.from("second-recording-frame"); |
| 2682 | const firstCapturePage = vi.fn(async () => ({ |
| 2683 | toJPEG: () => firstJpeg, |
| 2684 | getSize: () => ({ width: 800, height: 600 }), |
| 2685 | })); |
| 2686 | const secondCapturePage = vi.fn(async () => ({ |
| 2687 | toJPEG: () => secondJpeg, |
| 2688 | getSize: () => ({ width: 390, height: 844 }), |
| 2689 | })); |
| 2690 | const firstSendCommand = vi.fn(async () => undefined); |
| 2691 | const secondSendCommand = vi.fn(async () => undefined); |
| 2692 | const host = makeTestHostWebContents(); |
| 2693 | const makeWebContents = ( |
| 2694 | id: number, |
| 2695 | capturePage: typeof firstCapturePage, |
| 2696 | sendCommand: typeof firstSendCommand, |
| 2697 | ) => |
| 2698 | ({ |
| 2699 | id, |
| 2700 | mainFrame: { routingId: id }, |
| 2701 | hostWebContents: host, |
| 2702 | executeJavaScript: vi.fn(async () => |
| 2703 | id === 41 ? { width: 800, height: 600 } : { width: 390, height: 844 }, |
| 2704 | ), |
| 2705 | isDestroyed: () => false, |
| 2706 | getType: () => "webview", |
| 2707 | getURL: () => `https://example.com/${id}`, |
| 2708 | getTitle: () => `Example ${id}`, |
| 2709 | isLoadingMainFrame: () => false, |
| 2710 | getZoomFactor: () => 1, |
| 2711 | setZoomFactor: vi.fn(), |
| 2712 | setAudioMuted: vi.fn(), |
| 2713 | setBackgroundThrottling: vi.fn(), |
| 2714 | isCurrentlyAudible: () => false, |
| 2715 | on: vi.fn(), |
| 2716 | off: vi.fn(), |
| 2717 | ipc: { on: vi.fn(), off: vi.fn() }, |
| 2718 | send: webviewSend, |
| 2719 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 2720 | setIgnoreMenuShortcuts: vi.fn(), |
| 2721 | setWindowOpenHandler: vi.fn(), |
| 2722 | debugger: { |
| 2723 | isAttached: () => false, |
| 2724 | attach: vi.fn(), |
| 2725 | sendCommand, |
| 2726 | on: vi.fn(), |
| 2727 | off: vi.fn(), |
| 2728 | }, |
| 2729 | capturePage, |
| 2730 | }) as never; |
| 2731 | const webContentsById = new Map([ |
| 2732 | [41, makeWebContents(41, firstCapturePage, firstSendCommand)], |
| 2733 | [42, makeWebContents(42, secondCapturePage, secondSendCommand)], |
| 2734 | ]); |
| 2735 | fromId.mockImplementation((id) => |
| 2736 | id === undefined ? null : (webContentsById.get(id) ?? null), |
| 2737 | ); |
| 2738 | yield* manager.createTab("tab_1"); |
| 2739 | yield* manager.createTab("tab_2"); |
| 2740 | yield* manager.registerWebview("tab_1", 41); |
| 2741 | yield* manager.registerWebview("tab_2", 42); |
| 2742 | |
| 2743 | const grants: Array<{ video?: unknown }> = []; |
| 2744 | const takeGrant = () => |
| 2745 | host.displayMediaHandler()?.({ frame: host.mainFrame }, (value) => { |
| 2746 | grants.push(value); |
| 2747 | }); |
| 2748 | |
| 2749 | yield* manager.startRecording("tab_1"); |
| 2750 | takeGrant(); |
| 2751 | yield* manager.startRecording("tab_2"); |
| 2752 | takeGrant(); |
| 2753 | expect(grants).toEqual([{ video: { routingId: 41 } }, { video: { routingId: 42 } }]); |
| 2754 | |
| 2755 | expect(firstCapturePage).toHaveBeenCalledOnce(); |
| 2756 | expect(secondCapturePage).toHaveBeenCalledOnce(); |
| 2757 | expect(firstSendCommand).not.toHaveBeenCalledWith( |
| 2758 | "Page.startScreencast", |
| 2759 | expect.anything(), |
| 2760 | ); |
| 2761 | expect(secondSendCommand).not.toHaveBeenCalledWith( |
| 2762 | "Page.startScreencast", |
| 2763 | expect.anything(), |
| 2764 | ); |
| 2765 | |
| 2766 | yield* Effect.all([manager.stopRecording("tab_1"), manager.stopRecording("tab_2")], { |
| 2767 | concurrency: 2, |
| 2768 | discard: true, |
| 2769 | }); |
| 2770 | }), |
| 2771 | ), |
| 2772 | ); |
| 2773 | |
| 2774 | effectIt.effect("only lets the host frame that armed a recording claim its stream", () => |
| 2775 | withManager((manager) => |
| 2776 | Effect.gen(function* () { |
| 2777 | const { grants, takeGrant } = yield* setupRecordingRaceTabs(manager); |
| 2778 | |
| 2779 | yield* manager.startRecording("tab_race_a"); |
| 2780 | takeGrant({ frameTreeNodeId: 999 }); |
| 2781 | takeGrant(); |
| 2782 | |
| 2783 | expect(grants).toEqual([{}, { video: { routingId: 41 } }]); |
| 2784 | yield* manager.stopRecording("tab_race_a"); |
| 2785 | }), |
| 2786 | ), |
| 2787 | ); |
| 2788 | |
| 2789 | effectIt.effect("reclaims the arm slot from a destroyed webContents", () => |
| 2790 | withManager((manager) => |
| 2791 | Effect.gen(function* () { |
| 2792 | const { grants, takeGrant, destroy } = yield* setupRecordingRaceTabs(manager); |
| 2793 | |
| 2794 | yield* manager.startRecording("tab_race_a"); |
| 2795 | destroy(41); |
| 2796 | yield* manager.startRecording("tab_race_b"); |
| 2797 | takeGrant(); |
| 2798 | expect(grants).toEqual([{ video: { routingId: 42 } }]); |
| 2799 | |
| 2800 | yield* manager.stopRecording("tab_race_b"); |
| 2801 | }), |
| 2802 | ), |
| 2803 | ); |
| 2804 | |
| 2805 | effectIt.effect( |
| 2806 | "publishes human ownership only on transitions while retaining every recording press", |
| 2807 | () => |
| 2808 | withManager((manager) => |
| 2809 | Effect.gen(function* () { |
| 2810 | let humanInput: ((input: unknown) => void) | undefined; |
| 2811 | const contents = makeTestPreviewWebContents(async () => ({ |
| 2812 | toJPEG: () => Buffer.from("frame"), |
| 2813 | getSize: () => ({ width: 800, height: 600 }), |
| 2814 | })); |
| 2815 | contents.ipc.on = (channel, callback) => { |
| 2816 | if (channel === "preview:human-input") |
| 2817 | humanInput = (input) => callback({} as Electron.IpcMainEvent, input); |
| 2818 | return contents.ipc; |
| 2819 | }; |
| 2820 | fromId.mockReturnValue(contents); |
| 2821 | yield* manager.createTab("tab_human"); |
| 2822 | yield* manager.registerWebview("tab_human", 42); |
| 2823 | yield* manager.startRecording("tab_human", { |
| 2824 | showKeyPresses: true, |
| 2825 | showMousePresses: true, |
| 2826 | }); |
| 2827 | const controllers: string[] = []; |
| 2828 | const feedback = yield* Queue.unbounded<void>(); |
| 2829 | webviewSend.mockImplementation((channel) => { |
| 2830 | if (channel === "preview:recording-controller") Queue.offerUnsafe(feedback, undefined); |
| 2831 | }); |
| 2832 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 2833 | Effect.sync(() => { |
| 2834 | controllers.push(state.controller); |
| 2835 | }), |
| 2836 | ); |
| 2837 | for (const press of [ |
| 2838 | { kind: "pointer", x: 10, y: 20, button: 0 }, |
| 2839 | { kind: "pointer", x: 30, y: 40, button: 0 }, |
| 2840 | { kind: "key", key: "a", code: "KeyA" }, |
| 2841 | ]) { |
| 2842 | humanInput?.(press); |
| 2843 | yield* Queue.take(feedback); |
| 2844 | } |
| 2845 | expect(controllers).toEqual(["human"]); |
| 2846 | expect( |
| 2847 | webviewSend.mock.calls.filter( |
| 2848 | ([channel]) => channel === "preview:recording-controller", |
| 2849 | ), |
| 2850 | ).toEqual([ |
| 2851 | ["preview:recording-controller", "human", { x: 10, y: 20 }], |
| 2852 | ["preview:recording-controller", "human", { x: 30, y: 40 }], |
| 2853 | ["preview:recording-controller", "human", undefined], |
| 2854 | ]); |
| 2855 | yield* TestClock.adjust(750); |
| 2856 | expect(controllers).toEqual(["human", "none"]); |
| 2857 | }), |
| 2858 | ), |
| 2859 | ); |
| 2860 | |
| 2861 | effectIt.effect("keeps human ownership until the last input's idle deadline", () => |
| 2862 | withManager((manager) => |
| 2863 | Effect.gen(function* () { |
| 2864 | let humanInput: ((input: unknown) => void) | undefined; |
| 2865 | const contents = makeTestPreviewWebContents(async () => ({ |
| 2866 | toJPEG: () => Buffer.from("frame"), |
| 2867 | getSize: () => ({ width: 800, height: 600 }), |
| 2868 | })); |
| 2869 | contents.ipc.on = (channel, callback) => { |
| 2870 | if (channel === "preview:human-input") |
| 2871 | humanInput = (input) => callback({} as Electron.IpcMainEvent, input); |
| 2872 | return contents.ipc; |
| 2873 | }; |
| 2874 | fromId.mockReturnValue(contents); |
| 2875 | yield* manager.createTab("tab_idle"); |
| 2876 | yield* manager.registerWebview("tab_idle", 42); |
| 2877 | const controllers: string[] = []; |
| 2878 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 2879 | Effect.sync(() => { |
| 2880 | controllers.push(state.controller); |
| 2881 | }), |
| 2882 | ); |
| 2883 | const press = () => humanInput?.({ kind: "key", key: "a", code: "KeyA" }); |
| 2884 | press(); |
| 2885 | yield* TestClock.adjust(500); |
| 2886 | press(); |
| 2887 | yield* TestClock.adjust(749); |
| 2888 | expect(controllers).toEqual(["human"]); |
| 2889 | yield* TestClock.adjust(1); |
| 2890 | expect(controllers).toEqual(["human", "none"]); |
| 2891 | |
| 2892 | press(); |
| 2893 | yield* TestClock.adjust(500); |
| 2894 | const staleInput = humanInput; |
| 2895 | const replacement = makeTestPreviewWebContents( |
| 2896 | async () => ({ |
| 2897 | toJPEG: () => Buffer.from("frame"), |
| 2898 | getSize: () => ({ width: 800, height: 600 }), |
| 2899 | }), |
| 2900 | 43, |
| 2901 | ); |
| 2902 | replacement.ipc.on = contents.ipc.on; |
| 2903 | contents.isDestroyed = () => true; |
| 2904 | fromId.mockImplementation((id) => (id === 43 ? replacement : null)); |
| 2905 | yield* manager.registerWebview("tab_idle", 43); |
| 2906 | expect(controllers.at(-1)).toBe("none"); |
| 2907 | const count = controllers.length; |
| 2908 | staleInput?.({ kind: "key", key: "b", code: "KeyB" }); |
| 2909 | yield* TestClock.adjust(750); |
| 2910 | expect(controllers).toHaveLength(count); |
| 2911 | }), |
| 2912 | ), |
| 2913 | ); |
| 2914 | |
| 2915 | effectIt.effect("gates recording decorations and isolates failed subscribers", () => |
| 2916 | withManager((manager) => |
| 2917 | Effect.gen(function* () { |
| 2918 | const callbacks = new Map< |
| 2919 | string, |
| 2920 | (event: unknown, input: unknown) => Fiber.Fiber<void, never> | undefined |
| 2921 | >(); |
| 2922 | const contents = Object.assign( |
| 2923 | makeTestPreviewWebContents(async () => ({ |
| 2924 | toJPEG: () => Buffer.from("frame"), |
| 2925 | getSize: () => ({ width: 800, height: 600 }), |
| 2926 | })), |
| 2927 | { |
| 2928 | ipc: { |
| 2929 | on: ( |
| 2930 | channel: string, |
| 2931 | callback: (event: unknown, input: unknown) => Fiber.Fiber<void, never> | undefined, |
| 2932 | ) => callbacks.set(channel, callback), |
| 2933 | off: vi.fn(), |
| 2934 | }, |
| 2935 | }, |
| 2936 | ); |
| 2937 | fromId.mockReturnValue(contents as never); |
| 2938 | yield* manager.createTab("tab_recording_input"); |
| 2939 | yield* manager.registerWebview("tab_recording_input", 42); |
| 2940 | const received: DesktopPreviewRecordingInputEvent[] = []; |
| 2941 | yield* manager.subscribeRecordingInputs(() => Effect.die("renderer unavailable")); |
| 2942 | yield* manager.subscribeRecordingInputs((event) => |
| 2943 | Effect.sync(() => { |
| 2944 | received.push(event); |
| 2945 | }), |
| 2946 | ); |
| 2947 | const send = (input: unknown) => |
| 2948 | Effect.gen(function* () { |
| 2949 | const fiber = callbacks.get("preview:recording-input")?.(null, input); |
| 2950 | if (fiber) yield* Fiber.join(fiber); |
| 2951 | }); |
| 2952 | const key = { type: "key", label: "⌘C", held: true, width: 800 }; |
| 2953 | const pointer = { |
| 2954 | type: "pointer", |
| 2955 | phase: "down", |
| 2956 | x: 120, |
| 2957 | y: 80, |
| 2958 | width: 800, |
| 2959 | height: 600, |
| 2960 | }; |
| 2961 | yield* send(key); |
| 2962 | expect(received).toEqual([]); |
| 2963 | yield* manager.startRecording("tab_recording_input", { |
| 2964 | showKeyPresses: true, |
| 2965 | showMousePresses: false, |
| 2966 | }); |
| 2967 | yield* send(key); |
| 2968 | yield* send(pointer); |
| 2969 | yield* send({ ...key, width: 0 }); |
| 2970 | expect(received).toEqual([{ tabId: "tab_recording_input", input: key }]); |
| 2971 | yield* manager.stopRecording("tab_recording_input"); |
| 2972 | yield* send(key); |
| 2973 | expect(received).toHaveLength(1); |
| 2974 | yield* manager.startRecording("tab_recording_input", { |
| 2975 | showKeyPresses: false, |
| 2976 | showMousePresses: true, |
| 2977 | }); |
| 2978 | yield* send(key); |
| 2979 | yield* send(pointer); |
| 2980 | expect(received.at(-1)).toEqual({ tabId: "tab_recording_input", input: pointer }); |
| 2981 | expect(received).toHaveLength(2); |
| 2982 | }), |
| 2983 | ), |
| 2984 | ); |
| 2985 | |
| 2986 | effectIt.effect("continues native recording when the source warmup fails", () => |
| 2987 | withManager((manager) => |
| 2988 | Effect.gen(function* () { |
| 2989 | const capturePage = vi.fn(async () => { |
| 2990 | throw new Error("source is not ready"); |
| 2991 | }); |
| 2992 | const host = makeTestHostWebContents(); |
| 2993 | const webContents = Object.assign(makeTestPreviewWebContents(capturePage, 42, host), { |
| 2994 | executeJavaScript: vi.fn(async () => ({ width: 1280, height: 720 })), |
| 2995 | }); |
| 2996 | fromId.mockReturnValue(webContents); |
| 2997 | |
| 2998 | yield* manager.createTab("tab_recording_warmup_failure"); |
| 2999 | yield* manager.registerWebview("tab_recording_warmup_failure", 42); |
| 3000 | |
| 3001 | yield* manager.startRecording("tab_recording_warmup_failure"); |
| 3002 | expect(capturePage).toHaveBeenCalledTimes(2); |
| 3003 | |
| 3004 | const handler = host.displayMediaHandler(); |
| 3005 | const streams: Array<{ video?: unknown }> = []; |
| 3006 | handler?.({ frame: host.mainFrame }, (value) => streams.push(value)); |
| 3007 | handler?.({ frame: host.mainFrame }, (value) => streams.push(value)); |
| 3008 | expect(streams).toEqual([{ video: { routingId: 42 } }, {}]); |
| 3009 | |
| 3010 | yield* manager.stopRecording("tab_recording_warmup_failure"); |
| 3011 | }), |
| 3012 | ), |
| 3013 | ); |
| 3014 | |
| 3015 | effectIt.effect("serializes recording source acquisition with webview replacement", () => |
| 3016 | withManager((manager) => |
| 3017 | Effect.gen(function* () { |
| 3018 | const capturedImage = { |
| 3019 | toJPEG: () => Buffer.from("unused-recording-frame"), |
| 3020 | getSize: () => ({ width: 1280, height: 720 }), |
| 3021 | }; |
| 3022 | let markWarmupStarted!: () => void; |
| 3023 | const warmupStarted = new Promise<void>((resolve) => { |
| 3024 | markWarmupStarted = resolve; |
| 3025 | }); |
| 3026 | let finishWarmup!: (image: TestCapturedPreviewImage) => void; |
| 3027 | const capturePage = vi |
| 3028 | .fn<() => Promise<TestCapturedPreviewImage>>() |
| 3029 | .mockImplementationOnce( |
| 3030 | () => |
| 3031 | new Promise<TestCapturedPreviewImage>((resolve) => { |
| 3032 | markWarmupStarted(); |
| 3033 | finishWarmup = resolve; |
| 3034 | }), |
| 3035 | ) |
| 3036 | .mockResolvedValue(capturedImage); |
| 3037 | const initialWebContents = makeTestPreviewWebContents(capturePage, 42); |
| 3038 | const replacementOn = vi.fn(); |
| 3039 | const replacementWebContents = Object.assign(makeTestPreviewWebContents(capturePage, 43), { |
| 3040 | on: replacementOn, |
| 3041 | }); |
| 3042 | fromId.mockImplementation((id) => { |
| 3043 | if (id === 42) return initialWebContents; |
| 3044 | if (id === 43) return replacementWebContents; |
| 3045 | return null; |
| 3046 | }); |
| 3047 | |
| 3048 | yield* manager.createTab("tab_recording_replacement_race"); |
| 3049 | yield* manager.registerWebview("tab_recording_replacement_race", 42); |
| 3050 | const start = yield* manager |
| 3051 | .startRecording("tab_recording_replacement_race") |
| 3052 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 3053 | yield* Effect.promise(() => warmupStarted); |
| 3054 | const replacement = yield* manager |
| 3055 | .registerWebview("tab_recording_replacement_race", 43) |
| 3056 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 3057 | yield* Effect.yieldNow; |
| 3058 | expect(replacementOn).not.toHaveBeenCalled(); |
| 3059 | |
| 3060 | finishWarmup(capturedImage); |
| 3061 | yield* Fiber.join(start); |
| 3062 | yield* Fiber.join(replacement); |
| 3063 | expect(replacementOn).toHaveBeenCalled(); |
| 3064 | expect(initialWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 3065 | expect(replacementWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); |
| 3066 | yield* manager.stopRecording("tab_recording_replacement_race"); |
| 3067 | expect(initialWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); |
| 3068 | expect(replacementWebContents.setBackgroundThrottling.mock.calls).toEqual([ |
| 3069 | [false], |
| 3070 | [true], |
| 3071 | ]); |
| 3072 | }), |
| 3073 | ), |
| 3074 | ); |
| 3075 | |
| 3076 | effectIt.effect("does not publish picture-in-picture readiness after window teardown", () => |
| 3077 | withManager((manager) => |
| 3078 | Effect.gen(function* () { |
| 3079 | const capturePage = vi.fn(async () => ({ |
| 3080 | toJPEG: () => Buffer.from("closing-preview-frame"), |
| 3081 | getSize: () => ({ width: 1280, height: 720 }), |
| 3082 | })); |
| 3083 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); |
| 3084 | const { pictureInPictureWindow } = makeTestPictureInPictureWindow(); |
| 3085 | pictureInPictureWindow.showInactive.mockImplementationOnce(() => { |
| 3086 | pictureInPictureWindow.close(); |
| 3087 | }); |
| 3088 | browserWindowConstructor.mockImplementation(function () { |
| 3089 | return pictureInPictureWindow; |
| 3090 | }); |
| 3091 | const states: PreviewManager.PreviewTabState[] = []; |
| 3092 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 3093 | Effect.sync(() => { |
| 3094 | states.push(state); |
| 3095 | }), |
| 3096 | ); |
| 3097 | |
| 3098 | yield* manager.createTab("tab_pip_teardown"); |
| 3099 | yield* manager.registerWebview("tab_pip_teardown", 42); |
| 3100 | const openExit = yield* Effect.exit(manager.openPictureInPicture("tab_pip_teardown")); |
| 3101 | |
| 3102 | expect(Exit.hasInterrupts(openExit)).toBe(true); |
| 3103 | expect(pictureInPictureWindow.close).toHaveBeenCalledOnce(); |
| 3104 | expect(states.some((state) => state.pictureInPicture)).toBe(false); |
| 3105 | expect(states.at(-1)?.pictureInPicture).toBe(false); |
| 3106 | }), |
| 3107 | ), |
| 3108 | ); |
| 3109 | |
| 3110 | effectIt.effect("closes an initializing picture-in-picture without blocking later opens", () => |
| 3111 | withManager((manager) => |
| 3112 | Effect.gen(function* () { |
| 3113 | const capturePage = vi.fn(async () => ({ |
| 3114 | toJPEG: () => Buffer.from("serialized-preview-frame"), |
| 3115 | getSize: () => ({ width: 1280, height: 720 }), |
| 3116 | })); |
| 3117 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); |
| 3118 | const { pictureInPictureWindow: initializingWindow } = makeTestPictureInPictureWindow( |
| 3119 | () => new Promise<void>(() => {}), |
| 3120 | ); |
| 3121 | const { pictureInPictureWindow: reopenedWindow } = makeTestPictureInPictureWindow(); |
| 3122 | browserWindowConstructor |
| 3123 | .mockImplementationOnce(function () { |
| 3124 | return initializingWindow; |
| 3125 | }) |
| 3126 | .mockImplementationOnce(function () { |
| 3127 | return reopenedWindow; |
| 3128 | }); |
| 3129 | const states: PreviewManager.PreviewTabState[] = []; |
| 3130 | yield* manager.subscribeStateChanges((_tabId, state) => |
| 3131 | Effect.sync(() => { |
| 3132 | states.push(state); |
| 3133 | }), |
| 3134 | ); |
| 3135 | yield* manager.createTab("tab_concurrent_pip"); |
| 3136 | yield* manager.registerWebview("tab_concurrent_pip", 42); |
| 3137 | |
| 3138 | const firstOpen = yield* manager |
| 3139 | .openPictureInPicture("tab_concurrent_pip") |
| 3140 | .pipe(Effect.forkChild); |
| 3141 | yield* Effect.yieldNow; |
| 3142 | const secondOpen = yield* manager |
| 3143 | .openPictureInPicture("tab_concurrent_pip") |
| 3144 | .pipe(Effect.forkChild); |
| 3145 | yield* Effect.yieldNow; |
| 3146 | const close = yield* manager |
| 3147 | .closePictureInPicture("tab_concurrent_pip") |
| 3148 | .pipe(Effect.forkChild); |
| 3149 | yield* Effect.yieldNow; |
| 3150 | |
| 3151 | expect(browserWindowConstructor).toHaveBeenCalledOnce(); |
| 3152 | expect(initializingWindow.loadURL).toHaveBeenCalledOnce(); |
| 3153 | expect(initializingWindow.close).toHaveBeenCalledOnce(); |
| 3154 | const [firstOpenExit, secondOpenExit] = yield* Effect.all([ |
| 3155 | Fiber.await(firstOpen), |
| 3156 | Fiber.await(secondOpen), |
| 3157 | ]); |
| 3158 | yield* Fiber.join(close); |
| 3159 | |
| 3160 | expect(Exit.hasInterrupts(firstOpenExit)).toBe(true); |
| 3161 | expect(Exit.hasInterrupts(secondOpenExit)).toBe(true); |
| 3162 | expect(initializingWindow.showInactive).not.toHaveBeenCalled(); |
| 3163 | expect(capturePage).not.toHaveBeenCalled(); |
| 3164 | expect(states.at(-1)?.pictureInPicture).toBe(false); |
| 3165 | |
| 3166 | yield* manager.openPictureInPicture("tab_concurrent_pip"); |
| 3167 | |
| 3168 | expect(browserWindowConstructor).toHaveBeenCalledTimes(2); |
| 3169 | expect(reopenedWindow.showInactive).toHaveBeenCalledOnce(); |
| 3170 | expect(capturePage).toHaveBeenCalledOnce(); |
| 3171 | expect(states.at(-1)?.pictureInPicture).toBe(true); |
| 3172 | |
| 3173 | yield* manager.closePictureInPicture("tab_concurrent_pip"); |
| 3174 | |
| 3175 | expect(browserWindowConstructor).toHaveBeenCalledTimes(2); |
| 3176 | expect(reopenedWindow.close).toHaveBeenCalledOnce(); |
| 3177 | expect(states.at(-1)?.pictureInPicture).toBe(false); |
| 3178 | const capturesAfterClose = capturePage.mock.calls.length; |
| 3179 | yield* TestClock.adjust(200); |
| 3180 | expect(capturePage).toHaveBeenCalledTimes(capturesAfterClose); |
| 3181 | }), |
| 3182 | ), |
| 3183 | ); |
| 3184 | |
| 3185 | effectIt.effect("shows picture-in-picture and keeps capturing after stalled captures", () => |
| 3186 | withManager((manager) => |
| 3187 | Effect.gen(function* () { |
| 3188 | const image = { |
| 3189 | toJPEG: () => Buffer.from("preview-frame"), |
| 3190 | getSize: () => ({ width: 1280, height: 720 }), |
| 3191 | }; |
| 3192 | const stalledInitial = Promise.withResolvers<typeof image>(); |
| 3193 | const stalledLoop = Promise.withResolvers<typeof image>(); |
| 3194 | const capturePage = vi |
| 3195 | .fn<() => Promise<typeof image>>() |
| 3196 | .mockImplementationOnce(() => stalledInitial.promise) |
| 3197 | .mockImplementationOnce(() => stalledLoop.promise) |
| 3198 | .mockResolvedValue(image); |
| 3199 | fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); |
| 3200 | const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow(); |
| 3201 | browserWindowConstructor.mockImplementation(function () { |
| 3202 | return pictureInPictureWindow; |
| 3203 | }); |
| 3204 | yield* manager.createTab("tab_pip_stalled_capture"); |
| 3205 | yield* manager.registerWebview("tab_pip_stalled_capture", 42); |
| 3206 | |
| 3207 | try { |
| 3208 | const open = yield* manager |
| 3209 | .openPictureInPicture("tab_pip_stalled_capture") |
| 3210 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 3211 | yield* TestClock.adjust(1_000); |
| 3212 | expect(pictureInPictureWindow.showInactive).toHaveBeenCalledOnce(); |
| 3213 | yield* Fiber.join(open); |
| 3214 | |
| 3215 | expect(send).not.toHaveBeenCalled(); |
| 3216 | yield* TestClock.adjust(500); |
| 3217 | expect(send).toHaveBeenCalled(); |
| 3218 | } finally { |
| 3219 | // Release stalled native calls after a failing assertion against unchanged base. |
| 3220 | stalledInitial.resolve(image); |
| 3221 | stalledLoop.resolve(image); |
| 3222 | } |
| 3223 | }), |
| 3224 | ), |
| 3225 | ); |
| 3226 | |
| 3227 | effectIt.effect("rejects picture-in-picture when its webview changes during initialization", () => |
| 3228 | withManager((manager) => |
| 3229 | Effect.gen(function* () { |
| 3230 | const initialCapturePage = vi.fn(async () => ({ |
| 3231 | toJPEG: () => Buffer.from("stale-preview-frame"), |
| 3232 | getSize: () => ({ width: 1280, height: 720 }), |
| 3233 | })); |
| 3234 | const replacementCapturePage = vi.fn(async () => ({ |
| 3235 | toJPEG: () => Buffer.from("replacement-preview-frame"), |
| 3236 | getSize: () => ({ width: 1280, height: 720 }), |
| 3237 | })); |
| 3238 | const initialWebContents = makeTestPreviewWebContents(initialCapturePage, 42); |
| 3239 | const replacementWebContents = makeTestPreviewWebContents(replacementCapturePage, 43); |
| 3240 | fromId.mockImplementation((webContentsId?: number) => { |
| 3241 | if (webContentsId === 42) return initialWebContents; |
| 3242 | if (webContentsId === 43) return replacementWebContents; |
| 3243 | return null; |
| 3244 | }); |
| 3245 | let resolveLoad: (() => void) | undefined; |
| 3246 | const { pictureInPictureWindow } = makeTestPictureInPictureWindow( |
| 3247 | () => |
| 3248 | new Promise<void>((resolve) => { |
| 3249 | resolveLoad = resolve; |
| 3250 | }), |
| 3251 | ); |
| 3252 | browserWindowConstructor.mockImplementation(function () { |
| 3253 | return pictureInPictureWindow; |
| 3254 | }); |
| 3255 | |
| 3256 | yield* manager.createTab("tab_replaced_webview"); |
| 3257 | yield* manager.registerWebview("tab_replaced_webview", 42); |
| 3258 | const open = yield* manager |
| 3259 | .openPictureInPicture("tab_replaced_webview") |
| 3260 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 3261 | yield* Effect.yieldNow; |
| 3262 | expect(pictureInPictureWindow.loadURL).toHaveBeenCalledOnce(); |
| 3263 | expect(resolveLoad).toBeDefined(); |
| 3264 | const concurrentOpen = yield* manager |
| 3265 | .openPictureInPicture("tab_replaced_webview") |
| 3266 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 3267 | yield* Effect.yieldNow; |
| 3268 | |
| 3269 | yield* manager.registerWebview("tab_replaced_webview", 43); |
| 3270 | resolveLoad?.(); |
| 3271 | |
| 3272 | const openExits = yield* Effect.all([Fiber.await(open), Fiber.await(concurrentOpen)]); |
| 3273 | for (const openExit of openExits) { |
| 3274 | expect(Exit.isFailure(openExit)).toBe(true); |
| 3275 | if (Exit.isSuccess(openExit)) continue; |
| 3276 | const error = Option.getOrThrow(Cause.findErrorOption(openExit.cause)); |
| 3277 | expect(error).toMatchObject({ |
| 3278 | _tag: "PreviewOperationError", |
| 3279 | operation: "pictureInPicture.validateWebContents", |
| 3280 | tabId: "tab_replaced_webview", |
| 3281 | webContentsId: 42, |
| 3282 | }); |
| 3283 | } |
| 3284 | expect(browserWindowConstructor).toHaveBeenCalledOnce(); |
| 3285 | expect(pictureInPictureWindow.close).toHaveBeenCalledOnce(); |
| 3286 | expect(pictureInPictureWindow.showInactive).not.toHaveBeenCalled(); |
| 3287 | expect(initialCapturePage).not.toHaveBeenCalled(); |
| 3288 | expect(replacementCapturePage).not.toHaveBeenCalled(); |
| 3289 | }), |
| 3290 | ), |
| 3291 | ); |
| 3292 | |
| 3293 | effectIt.effect("keeps element picking active during subframe navigation", () => |
| 3294 | withManager((manager) => |
| 3295 | Effect.gen(function* () { |
| 3296 | const listeners = new Map<string, (...args: unknown[]) => void>(); |
| 3297 | fromId.mockReturnValue({ |
| 3298 | id: 42, |
| 3299 | isDestroyed: () => false, |
| 3300 | getType: () => "webview", |
| 3301 | getURL: () => "https://example.com", |
| 3302 | getTitle: () => "Example", |
| 3303 | isLoadingMainFrame: () => false, |
| 3304 | isFocused: () => true, |
| 3305 | getZoomFactor: () => 1, |
| 3306 | setZoomFactor: vi.fn(), |
| 3307 | setAudioMuted: vi.fn(), |
| 3308 | isCurrentlyAudible: () => false, |
| 3309 | on: vi.fn((event: string, listener: (...args: unknown[]) => void) => { |
| 3310 | listeners.set(event, listener); |
| 3311 | }), |
| 3312 | once: vi.fn((event: string, listener: (...args: unknown[]) => void) => { |
| 3313 | listeners.set(event, (...args) => { |
| 3314 | listeners.delete(event); |
| 3315 | listener(...args); |
| 3316 | }); |
| 3317 | }), |
| 3318 | off: vi.fn(), |
| 3319 | ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, |
| 3320 | send: webviewSend, |
| 3321 | navigationHistory: { canGoBack: () => false, canGoForward: () => false }, |
| 3322 | setIgnoreMenuShortcuts: vi.fn(), |
| 3323 | setWindowOpenHandler: vi.fn(), |
| 3324 | debugger: { |
| 3325 | isAttached: () => false, |
| 3326 | attach: vi.fn(), |
| 3327 | sendCommand: vi.fn(async () => undefined), |
| 3328 | on: vi.fn(), |
| 3329 | off: vi.fn(), |
| 3330 | }, |
| 3331 | } as never); |
| 3332 | |
| 3333 | yield* manager.createTab("tab_1"); |
| 3334 | yield* manager.registerWebview("tab_1", 42); |
| 3335 | const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); |
| 3336 | yield* Effect.yieldNow; |
| 3337 | |
| 3338 | listeners.get("did-start-navigation")?.({ |
| 3339 | url: "about:blank", |
| 3340 | isSameDocument: false, |
| 3341 | isMainFrame: false, |
| 3342 | frame: null, |
| 3343 | }); |
| 3344 | yield* Effect.yieldNow; |
| 3345 | expect(pick.pollUnsafe()).toBeUndefined(); |
| 3346 | |
| 3347 | listeners.get("did-start-navigation")?.({ |
| 3348 | url: "https://example.com/next", |
| 3349 | isSameDocument: false, |
| 3350 | isMainFrame: true, |
| 3351 | frame: null, |
| 3352 | }); |
| 3353 | yield* Effect.yieldNow; |
| 3354 | expect(pick.pollUnsafe()).toBeDefined(); |
| 3355 | expect(yield* Fiber.join(pick)).toBeNull(); |
| 3356 | }), |
| 3357 | ), |
| 3358 | ); |
| 3359 | |
| 3360 | effectIt.effect("delivers annotation voice state only to the pick session that owns it", () => |
| 3361 | withManager((manager) => |
| 3362 | Effect.gen(function* () { |
| 3363 | const firstReady = yield* Deferred.make<void>(); |
| 3364 | const secondReady = yield* Deferred.make<void>(); |
| 3365 | let registrations = 0; |
| 3366 | const guest = { |
| 3367 | ...makeTestPreviewWebContents(async () => ({ |
| 3368 | toPNG: () => Buffer.from("unused"), |
| 3369 | toJPEG: () => Buffer.from("unused"), |
| 3370 | getSize: () => ({ width: 1, height: 1 }), |
| 3371 | })), |
| 3372 | isFocused: () => true, |
| 3373 | focus: vi.fn(), |
| 3374 | send: (channel: string, ...args: unknown[]) => { |
| 3375 | webviewSend(channel, ...args); |
| 3376 | if (channel === "preview:start-pick") |
| 3377 | Deferred.doneUnsafe(registrations++ === 0 ? firstReady : secondReady, Effect.void); |
| 3378 | }, |
| 3379 | once: vi.fn(), |
| 3380 | ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, |
| 3381 | }; |
| 3382 | fromId.mockReturnValue(guest as never); |
| 3383 | yield* manager.createTab("tab_1"); |
| 3384 | yield* manager.registerWebview("tab_1", 42); |
| 3385 | const first = yield* manager |
| 3386 | .pickElement("tab_1", { sessionId: "first", shortcuts: [] }) |
| 3387 | .pipe(Effect.forkChild); |
| 3388 | yield* Deferred.await(firstReady); |
| 3389 | const state = { |
| 3390 | tabId: "tab_1", |
| 3391 | sessionId: "first", |
| 3392 | available: true, |
| 3393 | phase: "recording" as const, |
| 3394 | status: "Recording", |
| 3395 | errorAction: null, |
| 3396 | preview: null, |
| 3397 | freezesEditor: true, |
| 3398 | blocksSubmission: true, |
| 3399 | level: 0, |
| 3400 | shortcutLabel: "Ctrl+D", |
| 3401 | draft: { text: "Tighten spacing", cursor: 15 }, |
| 3402 | }; |
| 3403 | yield* manager.updateAnnotationVoice(state); |
| 3404 | expect(webviewSend).toHaveBeenCalledWith("preview:annotation-voice-state", state); |
| 3405 | const second = yield* manager |
| 3406 | .pickElement("tab_1", { sessionId: "second", shortcuts: [] }) |
| 3407 | .pipe(Effect.forkChild); |
| 3408 | yield* Deferred.await(secondReady); |
| 3409 | expect(yield* Fiber.join(first)).toBeNull(); |
| 3410 | webviewSend.mockClear(); |
| 3411 | yield* manager.updateAnnotationVoice(state); |
| 3412 | expect(webviewSend).not.toHaveBeenCalled(); |
| 3413 | yield* manager.updateAnnotationVoice({ ...state, sessionId: "second" }); |
| 3414 | expect(webviewSend).toHaveBeenCalledOnce(); |
| 3415 | yield* manager.cancelPickElement("tab_1"); |
| 3416 | expect(yield* Fiber.join(second)).toBeNull(); |
| 3417 | webviewSend.mockClear(); |
| 3418 | yield* manager.updateAnnotationVoice({ ...state, sessionId: "second" }); |
| 3419 | expect(webviewSend).not.toHaveBeenCalled(); |
| 3420 | }), |
| 3421 | ), |
| 3422 | ); |
| 3423 | |
| 3424 | effectIt.effect("keeps annotation send grants isolated and updates an active pick", () => |
| 3425 | withManager((manager) => |
| 3426 | Effect.gen(function* () { |
| 3427 | const picked = new Map<number, (event: unknown, ...args: unknown[]) => void>(); |
| 3428 | const capturePage = vi.fn(async () => ({ |
| 3429 | toJPEG: () => Buffer.from("annotation"), |
| 3430 | toDataURL: () => "data:image/png;base64,YW5ub3RhdGlvbg==", |
| 3431 | getSize: () => ({ width: 10, height: 10 }), |
| 3432 | })); |
| 3433 | const guests = new Map( |
| 3434 | [42, 43, 44].map( |
| 3435 | (id) => |
| 3436 | [ |
| 3437 | id, |
| 3438 | Object.assign(makeTestPreviewWebContents(capturePage, id), { |
| 3439 | isFocused: () => true, |
| 3440 | once: vi.fn(), |
| 3441 | ipc: { |
| 3442 | on: vi.fn( |
| 3443 | (channel: string, listener: (event: unknown, ...args: unknown[]) => void) => { |
| 3444 | if (channel === "preview:element-picked") picked.set(id, listener); |
| 3445 | }, |
| 3446 | ), |
| 3447 | off: vi.fn(), |
| 3448 | removeListener: vi.fn(), |
| 3449 | }, |
| 3450 | }), |
| 3451 | ] as const, |
| 3452 | ), |
| 3453 | ); |
| 3454 | fromId.mockImplementation((id) => (id === undefined ? null : (guests.get(id) ?? null))); |
| 3455 | yield* manager.createTab("tab_a"); |
| 3456 | yield* manager.createTab("tab_b"); |
| 3457 | yield* manager.registerWebview("tab_a", 42); |
| 3458 | yield* manager.registerWebview("tab_b", 43); |
| 3459 | yield* manager.setAnnotationSendEnabled("tab_a", true); |
| 3460 | const annotation = { |
| 3461 | id: "annotation-scopes", |
| 3462 | pageUrl: "https://example.com", |
| 3463 | pageTitle: "Example", |
| 3464 | comment: "Tighten this spacing", |
| 3465 | elements: [], |
| 3466 | regions: [], |
| 3467 | strokes: [], |
| 3468 | styleChanges: [], |
| 3469 | screenshot: null, |
| 3470 | createdAt: "2026-09-05T00:00:00.000Z", |
| 3471 | }; |
| 3472 | for (const [tabId, id, nextGrant, expected] of [ |
| 3473 | ["tab_b", 43, undefined, "attach"], |
| 3474 | ["tab_a", 42, false, "attach"], |
| 3475 | ["tab_a", 42, true, "send"], |
| 3476 | ] as const) { |
| 3477 | const pick = yield* manager.pickElement(tabId).pipe(Effect.forkChild); |
| 3478 | yield* Effect.yieldNow; |
| 3479 | if (nextGrant !== undefined) { |
| 3480 | yield* manager.setAnnotationSendEnabled(tabId, nextGrant); |
| 3481 | } |
| 3482 | picked.get(id)?.({}, annotation, null, "send"); |
| 3483 | const result = yield* Fiber.join(pick); |
| 3484 | expect(result?.annotation.id).toBe(annotation.id); |
| 3485 | expect(result?.submission).toBe(expected); |
| 3486 | } |
| 3487 | yield* manager.registerWebview("tab_a", 44); |
| 3488 | const replacementPick = yield* manager.pickElement("tab_a").pipe(Effect.forkChild); |
| 3489 | yield* Effect.yieldNow; |
| 3490 | picked.get(44)?.({}, annotation, null, "send"); |
| 3491 | expect((yield* Fiber.join(replacementPick))?.submission).toBe("send"); |
| 3492 | yield* manager.closeTab("tab_a"); |
| 3493 | yield* manager.createTab("tab_a"); |
| 3494 | yield* manager.registerWebview("tab_a", 44); |
| 3495 | const reopenedPick = yield* manager.pickElement("tab_a").pipe(Effect.forkChild); |
| 3496 | yield* Effect.yieldNow; |
| 3497 | picked.get(44)?.({}, annotation, null, "send"); |
| 3498 | expect((yield* Fiber.join(reopenedPick))?.submission).toBe("attach"); |
| 3499 | }), |
| 3500 | ), |
| 3501 | ); |
| 3502 | |
| 3503 | describe("annotation screenshots", () => { |
| 3504 | const captureAnnotation = ( |
| 3505 | cropRect: PreviewAnnotationRect | null, |
| 3506 | targets: Partial<Pick<PreviewAnnotationPayload, "elements" | "regions" | "strokes">> = {}, |
| 3507 | emptyImage?: "viewport" | "crop", |
| 3508 | ) => |
| 3509 | withManager((manager) => |
| 3510 | Effect.gen(function* () { |
| 3511 | let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined; |
| 3512 | const crop = vi.fn((rect: Electron.Rectangle) => ({ |
| 3513 | isEmpty: () => emptyImage === "crop", |
| 3514 | getSize: () => |
| 3515 | emptyImage === "crop" |
| 3516 | ? { width: 0, height: 0 } |
| 3517 | : { width: rect.width, height: rect.height }, |
| 3518 | toDataURL: () => (emptyImage === "crop" ? "data:," : "data:image/png;base64,cropped"), |
| 3519 | })); |
| 3520 | const capturePage = vi.fn(async () => ({ |
| 3521 | isEmpty: () => emptyImage === "viewport", |
| 3522 | getSize: () => |
| 3523 | emptyImage === "viewport" ? { width: 0, height: 0 } : { width: 2000, height: 1200 }, |
| 3524 | toJPEG: () => Buffer.from("unused"), |
| 3525 | toDataURL: () => (emptyImage === "viewport" ? "data:," : "data:image/png;base64,full"), |
| 3526 | crop, |
| 3527 | })); |
| 3528 | fromId.mockReturnValue( |
| 3529 | Object.assign(makeTestPreviewWebContents(capturePage), { |
| 3530 | isFocused: () => true, |
| 3531 | once: vi.fn(), |
| 3532 | ipc: { |
| 3533 | on: vi.fn((channel: string, listener: typeof onPicked) => { |
| 3534 | if (channel === "preview:element-picked") onPicked = listener; |
| 3535 | }), |
| 3536 | off: vi.fn(), |
| 3537 | removeListener: vi.fn(), |
| 3538 | }, |
| 3539 | }), |
| 3540 | ); |
| 3541 | |
| 3542 | yield* manager.createTab("tab_1"); |
| 3543 | yield* manager.registerWebview("tab_1", 42); |
| 3544 | const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); |
| 3545 | yield* Effect.yieldNow; |
| 3546 | onPicked?.( |
| 3547 | {}, |
| 3548 | { |
| 3549 | id: "annotation_1", |
| 3550 | pageUrl: "https://example.com", |
| 3551 | pageTitle: "Example", |
| 3552 | comment: "Tighten this spacing", |
| 3553 | elements: [], |
| 3554 | regions: [], |
| 3555 | strokes: [], |
| 3556 | ...targets, |
| 3557 | styleChanges: [], |
| 3558 | screenshot: null, |
| 3559 | createdAt: "2026-06-11T00:00:00.000Z", |
| 3560 | }, |
| 3561 | cropRect, |
| 3562 | "attach", |
| 3563 | 2, |
| 3564 | ); |
| 3565 | |
| 3566 | const result = yield* Fiber.join(pick); |
| 3567 | expect(capturePage).toHaveBeenCalledExactlyOnceWith(); |
| 3568 | expect(result?.annotation.comment).toBe("Tighten this spacing"); |
| 3569 | expect(result?.submission).toBe("attach"); |
| 3570 | return { result, crop }; |
| 3571 | }), |
| 3572 | ); |
| 3573 | |
| 3574 | effectIt.effect("clips a partially visible selection to the captured viewport", () => |
| 3575 | Effect.gen(function* () { |
| 3576 | const { result, crop } = yield* captureAnnotation( |
| 3577 | { x: -40, y: 570, width: 240, height: 110 }, |
| 3578 | { regions: [{ id: "region_1", rect: { x: -20, y: 590, width: 200, height: 70 } }] }, |
| 3579 | ); |
| 3580 | expect(crop).toHaveBeenCalledExactlyOnceWith({ x: 0, y: 1140, width: 400, height: 60 }); |
| 3581 | expect(result?.screenshotFailed).toBeUndefined(); |
| 3582 | expect(result?.annotation.screenshot).toMatchObject({ |
| 3583 | dataUrl: "data:image/png;base64,cropped", |
| 3584 | width: 400, |
| 3585 | height: 60, |
| 3586 | }); |
| 3587 | }), |
| 3588 | ); |
| 3589 | |
| 3590 | effectIt.effect.each([ |
| 3591 | { |
| 3592 | name: "an offscreen crop without individual target bounds", |
| 3593 | cropRect: { x: 1010, y: 40, width: 100, height: 70 }, |
| 3594 | regions: [], |
| 3595 | }, |
| 3596 | { |
| 3597 | name: "padding overlapping the viewport while its target is offscreen", |
| 3598 | cropRect: { x: 40, y: -100, width: 240, height: 110 }, |
| 3599 | regions: [{ id: "region_1", rect: { x: 60, y: -80, width: 200, height: 70 } }], |
| 3600 | }, |
| 3601 | { |
| 3602 | name: "a union spanning the viewport with both targets offscreen", |
| 3603 | cropRect: { x: -230, y: 40, width: 1460, height: 110 }, |
| 3604 | regions: [ |
| 3605 | { id: "region_1", rect: { x: -210, y: 60, width: 200, height: 70 } }, |
| 3606 | { id: "region_2", rect: { x: 1010, y: 60, width: 200, height: 70 } }, |
| 3607 | ], |
| 3608 | }, |
| 3609 | { |
| 3610 | name: "an offscreen target when crop bounds are missing", |
| 3611 | cropRect: null, |
| 3612 | regions: [{ id: "region_1", rect: { x: 60, y: -80, width: 200, height: 70 } }], |
| 3613 | }, |
| 3614 | ])("does not attach $name", ({ cropRect, regions }) => |
| 3615 | Effect.gen(function* () { |
| 3616 | const { result, crop } = yield* captureAnnotation(cropRect, { regions }); |
| 3617 | expect(crop).not.toHaveBeenCalled(); |
| 3618 | expect(result?.annotation.screenshot).toBeNull(); |
| 3619 | expect(result?.screenshotFailed).toBe(true); |
| 3620 | }), |
| 3621 | ); |
| 3622 | |
| 3623 | // regression: #18441 zero-area strokes on the viewport edge must still get a screenshot crop |
| 3624 | effectIt.effect.each([ |
| 3625 | { |
| 3626 | name: "zero-width SVG line on the left edge", |
| 3627 | rect: { x: 0, y: 60, width: 0, height: 70 }, |
| 3628 | cropRect: { x: -20, y: 40, width: 40, height: 110 }, |
| 3629 | expectedCrop: { x: 0, y: 80, width: 40, height: 220 }, |
| 3630 | }, |
| 3631 | { |
| 3632 | name: "zero-height SVG line on the top edge", |
| 3633 | rect: { x: 60, y: 0, width: 70, height: 0 }, |
| 3634 | cropRect: { x: 40, y: -20, width: 110, height: 40 }, |
| 3635 | expectedCrop: { x: 80, y: 0, width: 220, height: 40 }, |
| 3636 | }, |
| 3637 | ])("captures a stroked $name", ({ rect, cropRect, expectedCrop }) => |
| 3638 | Effect.gen(function* () { |
| 3639 | const { result, crop } = yield* captureAnnotation(cropRect, { |
| 3640 | elements: [ |
| 3641 | { |
| 3642 | id: "element_1", |
| 3643 | rect, |
| 3644 | element: { |
| 3645 | pageUrl: "https://example.com", |
| 3646 | pageTitle: "Example", |
| 3647 | tagName: "line", |
| 3648 | selector: "svg > line", |
| 3649 | htmlPreview: '<line stroke="black" stroke-width="2" />', |
| 3650 | componentName: null, |
| 3651 | source: null, |
| 3652 | stack: [], |
| 3653 | styles: "stroke: black; stroke-width: 2px;", |
| 3654 | pickedAt: "2026-06-11T00:00:00.000Z", |
| 3655 | }, |
| 3656 | }, |
| 3657 | ], |
| 3658 | }); |
| 3659 | expect(crop).toHaveBeenCalledExactlyOnceWith(expectedCrop); |
| 3660 | expect(result?.screenshotFailed).toBeUndefined(); |
| 3661 | expect(result?.annotation.screenshot).toMatchObject({ |
| 3662 | dataUrl: "data:image/png;base64,cropped", |
| 3663 | width: expectedCrop.width, |
| 3664 | height: expectedCrop.height, |
| 3665 | }); |
| 3666 | }), |
| 3667 | ); |
| 3668 | }); |
| 3669 | |
| 3670 | effectIt.effect("reveals only files inside the configured browser artifact directory", () => |
| 3671 | withManager((manager) => |
| 3672 | Effect.gen(function* () { |
| 3673 | yield* manager.revealArtifact("/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png"); |
| 3674 | |
| 3675 | expect(showItemInFolder).toHaveBeenCalledWith( |
| 3676 | "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png", |
| 3677 | ); |
| 3678 | const exit = yield* Effect.exit(manager.revealArtifact("/tmp/t3/dev/settings.json")); |
| 3679 | expect(Exit.isFailure(exit)).toBe(true); |
| 3680 | if (Exit.isSuccess(exit)) return; |
| 3681 | const error = Option.getOrThrow(Cause.findErrorOption(exit.cause)); |
| 3682 | expect(error).toMatchObject({ |
| 3683 | _tag: "PreviewArtifactPathOutsideDirectoryError", |
| 3684 | artifactPath: "/tmp/t3/dev/settings.json", |
| 3685 | artifactDirectory: "/tmp/t3/dev/browser-artifacts", |
| 3686 | }); |
| 3687 | expect("cause" in error).toBe(false); |
| 3688 | }), |
| 3689 | ), |
| 3690 | ); |
| 3691 | }); |