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, 04:45 UTC
| 1 | import * as NodeEvents from "node:events"; |
| 2 | import * as NodeVM from "node:vm"; |
| 3 | // @effect-diagnostics-next-line nodeBuiltinImport:off - Playwright download mocks perform real file operations outside the Effect runtime. |
| 4 | import * as NodeFSP from "node:fs/promises"; |
| 5 | |
| 6 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 7 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 8 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 9 | import { it } from "@effect/vitest"; |
| 10 | import { |
| 11 | type BrowserRecordingFrameRate, |
| 12 | EnvironmentId, |
| 13 | PreviewTabId, |
| 14 | ProviderInstanceId, |
| 15 | ThreadId, |
| 16 | type PreviewAutomationLoadError, |
| 17 | type PreviewAutomationResizeResult, |
| 18 | type PreviewAutomationSnapshot, |
| 19 | type PreviewAutomationStatus, |
| 20 | } from "@t3tools/contracts"; |
| 21 | import * as Deferred from "effect/Deferred"; |
| 22 | import * as Effect from "effect/Effect"; |
| 23 | import * as Exit from "effect/Exit"; |
| 24 | import * as Scope from "effect/Scope"; |
| 25 | import * as Fiber from "effect/Fiber"; |
| 26 | import * as FileSystem from "effect/FileSystem"; |
| 27 | import * as Layer from "effect/Layer"; |
| 28 | import * as Logger from "effect/Logger"; |
| 29 | import * as Option from "effect/Option"; |
| 30 | import * as Path from "effect/Path"; |
| 31 | import * as PubSub from "effect/PubSub"; |
| 32 | import * as Queue from "effect/Queue"; |
| 33 | import * as Stream from "effect/Stream"; |
| 34 | import * as TestClock from "effect/testing/TestClock"; |
| 35 | import { chromium, type BrowserContext, type Page } from "playwright-core"; |
| 36 | import { beforeEach, expect, vi } from "vite-plus/test"; |
| 37 | |
| 38 | import * as ServerConfig from "../config.ts"; |
| 39 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 40 | import * as Broker from "../mcp/PreviewAutomationBroker.ts"; |
| 41 | import * as DesktopChannel from "./DesktopBrowserChannel.ts"; |
| 42 | import * as Manager from "./Manager.ts"; |
| 43 | import * as PreviewAgentActivity from "./PreviewAgentActivity.ts"; |
| 44 | import * as ServerBrowser from "./ServerBrowser.ts"; |
| 45 | import * as PreviewBrowser from "./PreviewBrowser.ts"; |
| 46 | |
| 47 | vi.mock("./ServerBrowserContexts.ts", () => ({ |
| 48 | presentAsChrome: async () => {}, |
| 49 | ServerBrowserContexts: class { |
| 50 | private readonly onClose: ((context: BrowserContext) => void) | undefined; |
| 51 | constructor(options: { onContextClose?: (context: BrowserContext) => void }) { |
| 52 | this.onClose = options.onContextClose; |
| 53 | } |
| 54 | async contextFor(profileId: string, isolationKey?: string) { |
| 55 | if (realContextOverride) return realContextOverride; |
| 56 | contextRequests.push({ profileId, isolated: isolationKey !== undefined }); |
| 57 | if (contextFailure) throw contextFailure; |
| 58 | await contextGate?.promise; |
| 59 | const context = makeContext(this.onClose); |
| 60 | const setupFailure = pageSetupFailure; |
| 61 | if (setupFailure) { |
| 62 | context.newCDPSession = async () => { |
| 63 | throw setupFailure; |
| 64 | }; |
| 65 | } |
| 66 | contexts.push(context); |
| 67 | return context as unknown as BrowserContext; |
| 68 | } |
| 69 | async scratchPage() { |
| 70 | return encoderPageOverride ?? (makeEncoderPage() as unknown as Page); |
| 71 | } |
| 72 | async connectDesktopPage(endpoint: string) { |
| 73 | const context = makeContext(undefined, desktopPageUrl); |
| 74 | context.page.viewportSize.mockReturnValue(null); |
| 75 | const browser = { close: vi.fn(async () => {}) }; |
| 76 | desktopConnections.push({ endpoint, context, browser }); |
| 77 | desktopConnectionStarted?.resolve(); |
| 78 | await desktopConnectionGate?.promise; |
| 79 | return { browser, page: context.page as unknown as Page }; |
| 80 | } |
| 81 | async close() { |
| 82 | for (const context of contexts) await context.close(); |
| 83 | } |
| 84 | }, |
| 85 | })); |
| 86 | |
| 87 | function makeFrame() { |
| 88 | const frame = { |
| 89 | copy: "", |
| 90 | detached: false, |
| 91 | isDetached: () => frame.detached, |
| 92 | recording: Promise.withResolvers<void>(), |
| 93 | }; |
| 94 | return frame; |
| 95 | } |
| 96 | |
| 97 | const PNG_HEADER = (() => { |
| 98 | const header = Buffer.alloc(24); |
| 99 | header.write("IHDR", 12); |
| 100 | header.writeUInt32BE(1280, 16); |
| 101 | header.writeUInt32BE(800, 20); |
| 102 | return header.toString("base64"); |
| 103 | })(); |
| 104 | |
| 105 | function makeSession( |
| 106 | frame: ReturnType<typeof makeFrame> | undefined, |
| 107 | viewport: { width: number; height: number }, |
| 108 | ) { |
| 109 | const events = new NodeEvents.EventEmitter(); |
| 110 | return { |
| 111 | on: vi.fn((name: string, callback: (...args: unknown[]) => void) => events.on(name, callback)), |
| 112 | emit: (name: string, ...args: unknown[]) => events.emit(name, ...args), |
| 113 | emitAsync: (name: string, ...args: unknown[]) => |
| 114 | Promise.all(events.listeners(name).map((listener) => listener(...args))), |
| 115 | detach: vi.fn(async () => {}), |
| 116 | send: vi.fn(async (method: string, input?: unknown): Promise<Record<string, unknown>> => { |
| 117 | if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] }; |
| 118 | if (method === "Page.getLayoutMetrics") return { cssVisualViewport: { pageX: 0, pageY: 0 } }; |
| 119 | if (method === "Page.captureScreenshot") { |
| 120 | if ((input as { format: string }).format === "jpeg" && heldStill) await heldStill(); |
| 121 | // A snapshot sizes its screenshot from the PNG header; viewers get JPEG frames as-is. |
| 122 | return { data: (input as { format: string }).format === "png" ? PNG_HEADER : "ZnJhbWU=" }; |
| 123 | } |
| 124 | // Snapshots shrink their screenshot in the page; the header stands in for the result. |
| 125 | if (method === "Runtime.callFunctionOn") return { result: { value: PNG_HEADER } }; |
| 126 | if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } }; |
| 127 | if (method === "Page.createIsolatedWorld") { |
| 128 | const worldContexts: Record<string, number> = { |
| 129 | "t3-preview-viewport": 9, |
| 130 | "t3-preview-title": 11, |
| 131 | "t3-preview": 1, |
| 132 | }; |
| 133 | return { |
| 134 | executionContextId: worldContexts[(input as { worldName: string }).worldName] ?? 7, |
| 135 | }; |
| 136 | } |
| 137 | // A title watch settles only when the document's title changes. |
| 138 | if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 11) |
| 139 | return new Promise(() => {}); |
| 140 | if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 1) { |
| 141 | return { result: { value: [] } }; |
| 142 | } |
| 143 | if (method === "Page.addScriptToEvaluateOnNewDocument") frame?.recording.resolve(); |
| 144 | // The recorder drops its last copy on every copy or cut key it sees. |
| 145 | if ( |
| 146 | method === "Input.dispatchKeyEvent" && |
| 147 | ["copy", "cut"].includes((input as { commands?: Array<string> }).commands?.[0] ?? "") |
| 148 | ) { |
| 149 | if (focusedFrame) focusedFrame.copy = keyCopy; |
| 150 | else pageCopy = keyCopy; |
| 151 | } |
| 152 | if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) { |
| 153 | const value = frame ? frame.copy : pageCopy; |
| 154 | if (frame) frame.copy = ""; |
| 155 | else pageCopy = ""; |
| 156 | return { result: { value } }; |
| 157 | } |
| 158 | if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 9) |
| 159 | return desktopSizeAnswer?.() ?? { result: { value: { ...viewport } } }; |
| 160 | return { result: { value: "evaluated" } }; |
| 161 | }), |
| 162 | }; |
| 163 | } |
| 164 | |
| 165 | function fileChooserElement(accept: string) { |
| 166 | return { |
| 167 | getAttribute: async () => accept, |
| 168 | evaluate: (probe: (element: { ownerDocument: unknown }) => boolean) => |
| 169 | Promise.resolve( |
| 170 | probe({ |
| 171 | ownerDocument: (globalThis as typeof globalThis & { document?: unknown }).document, |
| 172 | }), |
| 173 | ), |
| 174 | }; |
| 175 | } |
| 176 | |
| 177 | function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = "about:blank") { |
| 178 | const events = new NodeEvents.EventEmitter(); |
| 179 | const nativeFileChooser = vi.fn(); |
| 180 | const setChooserFiles = vi.fn(async (_files: unknown) => {}); |
| 181 | const sessions: ReturnType<typeof makeSession>[] = []; |
| 182 | let url = initialUrl; |
| 183 | let viewport: ReturnType<Page["viewportSize"]> = { width: 1280, height: 800 }; |
| 184 | const cssViewport = { width: 1920, height: 1080 }; |
| 185 | let closed = false; |
| 186 | let contextClosed = false; |
| 187 | const page = { |
| 188 | on: (name: string, callback: (...args: unknown[]) => void) => events.on(name, callback), |
| 189 | once: (name: string, callback: (...args: unknown[]) => void) => events.once(name, callback), |
| 190 | off: (name: string, callback: (...args: unknown[]) => void) => events.off(name, callback), |
| 191 | emit: (name: string, ...args: unknown[]) => events.emit(name, ...args), |
| 192 | nativeFileChooser, |
| 193 | setChooserFiles, |
| 194 | openFileChooser: () => { |
| 195 | if ( |
| 196 | !events.emit("filechooser", { |
| 197 | isMultiple: () => false, |
| 198 | element: () => fileChooserElement(".csv"), |
| 199 | setFiles: setChooserFiles, |
| 200 | }) |
| 201 | ) { |
| 202 | nativeFileChooser(); |
| 203 | } |
| 204 | }, |
| 205 | emitAsync: (name: string, ...args: unknown[]) => |
| 206 | Promise.all(events.listeners(name).map((listener) => listener(...args))), |
| 207 | setDefaultTimeout: vi.fn(), |
| 208 | setDefaultNavigationTimeout: vi.fn(), |
| 209 | context: () => context, |
| 210 | mainFrame: () => page, |
| 211 | frames: () => [page], |
| 212 | url: () => url, |
| 213 | commit: (next: string) => { |
| 214 | url = next; |
| 215 | }, |
| 216 | title: vi.fn(async () => "test page"), |
| 217 | viewportSize: vi.fn(() => viewport), |
| 218 | setViewportSize: vi.fn(async (size: typeof viewport) => { |
| 219 | viewport = size; |
| 220 | }), |
| 221 | goto: vi.fn(async (next: string, _options?: { timeout?: number; waitUntil?: string }) => { |
| 222 | const pending = initialNavigation; |
| 223 | initialNavigation = null; |
| 224 | await pending?.(); |
| 225 | url = next; |
| 226 | events.emit("load"); |
| 227 | }), |
| 228 | goBack: vi.fn(async () => {}), |
| 229 | goForward: vi.fn(async () => {}), |
| 230 | reload: vi.fn(async () => {}), |
| 231 | emulateMedia: vi.fn(async () => {}), |
| 232 | waitForLoadState: vi.fn(async (_state?: string, _options?: { timeout?: number }) => {}), |
| 233 | evaluate: vi.fn(async () => ({ |
| 234 | url, |
| 235 | title: "test page", |
| 236 | loading: false, |
| 237 | visibleText: "delete", |
| 238 | interactiveElements: [], |
| 239 | })), |
| 240 | ariaSnapshot: vi.fn(async () => '- button "delete" [ref=e1]'), |
| 241 | locator: vi.fn((): unknown => { |
| 242 | throw new Error("Unexpected locator action"); |
| 243 | }), |
| 244 | isClosed: () => closed, |
| 245 | // Models Playwright: unload handlers always run, but `beforeunload` only with |
| 246 | // `runBeforeUnload`, and a guarding page stays open behind a `beforeunload` dialog. |
| 247 | beforeUnload: "none" as "none" | "listen" | "guard", |
| 248 | unloadEvents: [] as string[], |
| 249 | beforeUnloadDialog: null as null | { |
| 250 | accept: ReturnType<typeof vi.fn>; |
| 251 | dismiss: ReturnType<typeof vi.fn>; |
| 252 | }, |
| 253 | // Set to hold the page open after `beforeunload` until resolved, as Playwright's |
| 254 | // `runBeforeUnload` close resolves before the page actually closes. |
| 255 | unloadGate: null as PromiseWithResolvers<void> | null, |
| 256 | removed: false, |
| 257 | pagehideBinding: null as (() => void) | null, |
| 258 | pagehideWatched: Promise.withResolvers<void>(), |
| 259 | exposeFunction: vi.fn(async (_name: string, callback: () => void) => { |
| 260 | page.pagehideBinding = callback; |
| 261 | page.pagehideWatched.resolve(); |
| 262 | }), |
| 263 | close: vi.fn(async (options?: { runBeforeUnload?: boolean }) => { |
| 264 | if (closed) return; |
| 265 | const finish = () => { |
| 266 | if (closed || page.removed) return; |
| 267 | page.unloadEvents.push("pagehide"); |
| 268 | page.pagehideBinding?.(); |
| 269 | page.unloadEvents.push("visibilitychange"); |
| 270 | closed = true; |
| 271 | events.emit("close"); |
| 272 | }; |
| 273 | if (!options?.runBeforeUnload || page.beforeUnload === "none") return finish(); |
| 274 | page.unloadEvents.push("beforeunload"); |
| 275 | if (page.beforeUnload === "listen" && page.unloadGate) { |
| 276 | void page.unloadGate.promise.then(finish); |
| 277 | return; |
| 278 | } |
| 279 | if (page.beforeUnload === "listen") return finish(); |
| 280 | const dialog = { |
| 281 | type: () => "beforeunload", |
| 282 | message: () => "", |
| 283 | defaultValue: () => "", |
| 284 | accept: vi.fn(async () => finish()), |
| 285 | dismiss: vi.fn(async () => {}), |
| 286 | }; |
| 287 | page.beforeUnloadDialog = dialog; |
| 288 | events.emit("dialog", dialog); |
| 289 | }), |
| 290 | }; |
| 291 | const context = { |
| 292 | page, |
| 293 | sessions, |
| 294 | cssViewport, |
| 295 | newPage: async () => page as unknown as Page, |
| 296 | grantPermissions: vi.fn(async () => {}), |
| 297 | newCDPSession: async (target: unknown) => { |
| 298 | const session = makeSession( |
| 299 | target === page ? undefined : (target as ReturnType<typeof makeFrame>), |
| 300 | cssViewport, |
| 301 | ); |
| 302 | sessions.push(session); |
| 303 | return session; |
| 304 | }, |
| 305 | closing: Promise.withResolvers<void>(), |
| 306 | close: vi.fn(async () => { |
| 307 | if (contextClosed) return; |
| 308 | contextClosed = true; |
| 309 | context.closing.resolve(); |
| 310 | await page.close(); |
| 311 | onClose?.(context as unknown as BrowserContext); |
| 312 | }), |
| 313 | }; |
| 314 | return context; |
| 315 | } |
| 316 | |
| 317 | // Runs the real encoder script against fake canvas and MediaRecorder globals. |
| 318 | function makeEncoderPage() { |
| 319 | let paintedFrame = ""; |
| 320 | const canvas = { |
| 321 | width: 0, |
| 322 | height: 0, |
| 323 | getContext: () => ({ |
| 324 | drawImage(bitmap: { pixels: string }) { |
| 325 | paintedFrame = bitmap.pixels; |
| 326 | }, |
| 327 | fillRect() {}, |
| 328 | }), |
| 329 | captureStream: (frameRate?: number) => ({ |
| 330 | frameRate, |
| 331 | getTracks: () => [], |
| 332 | getVideoTracks: () => [{ requestFrame() {} }], |
| 333 | }), |
| 334 | }; |
| 335 | const video = { |
| 336 | play: async () => {}, |
| 337 | pause() {}, |
| 338 | requestVideoFrameCallback: (callback: () => void) => queueMicrotask(callback), |
| 339 | }; |
| 340 | class FakeMediaRecorder { |
| 341 | static isTypeSupported = (type: string) => type === "video/webm"; |
| 342 | mimeType = "video/webm"; |
| 343 | state = "inactive"; |
| 344 | onstart: (() => void) | null = null; |
| 345 | onstop: (() => void) | null = null; |
| 346 | ondataavailable: ((event: { data: Blob }) => void) | null = null; |
| 347 | readonly stream: { frameRate?: number }; |
| 348 | constructor(stream: { frameRate?: number }, options: { videoBitsPerSecond: number }) { |
| 349 | this.stream = stream; |
| 350 | encoderStreams.push({ |
| 351 | frameRate: stream.frameRate, |
| 352 | bitsPerSecond: options.videoBitsPerSecond, |
| 353 | }); |
| 354 | } |
| 355 | start() { |
| 356 | this.state = "recording"; |
| 357 | this.onstart?.(); |
| 358 | } |
| 359 | stop() { |
| 360 | this.state = "inactive"; |
| 361 | this.ondataavailable?.({ data: new Blob([paintedFrame]) }); |
| 362 | this.onstop?.(); |
| 363 | } |
| 364 | } |
| 365 | const sandbox: Record<string, unknown> = { |
| 366 | document: { createElement: (tag: string) => (tag === "video" ? video : canvas) }, |
| 367 | Path2D: function Path2D() {}, |
| 368 | MediaRecorder: FakeMediaRecorder, |
| 369 | createImageBitmap: async (blob: Blob) => { |
| 370 | await decodeGate?.promise; |
| 371 | return { width: 1280, height: 800, pixels: await blob.text(), close() {} }; |
| 372 | }, |
| 373 | atob, |
| 374 | btoa, |
| 375 | Blob, |
| 376 | performance, |
| 377 | }; |
| 378 | sandbox.window = sandbox; |
| 379 | const context = NodeVM.createContext(sandbox); |
| 380 | return { |
| 381 | ...makeContext().page, |
| 382 | evaluate: vi.fn(async (script: string | ((arg: unknown) => unknown), arg?: unknown) => |
| 383 | typeof script === "string" |
| 384 | ? NodeVM.runInContext(script, context) |
| 385 | : NodeVM.runInContext(`(${script.toString()})`, context)(arg), |
| 386 | ), |
| 387 | }; |
| 388 | } |
| 389 | |
| 390 | const contexts: ReturnType<typeof makeContext>[] = []; |
| 391 | let encoderPageOverride: Page | undefined; |
| 392 | let realContextOverride: BrowserContext | undefined; |
| 393 | const encoderStreams: Array<{ frameRate: number | undefined; bitsPerSecond: number }> = []; |
| 394 | let decodeGate: PromiseWithResolvers<void> | null = null; |
| 395 | const contextRequests: Array<{ profileId: string; isolated: boolean }> = []; |
| 396 | let contextGate: PromiseWithResolvers<void> | null = null; |
| 397 | let heldStill: (() => Promise<void>) | null = null; |
| 398 | let pageCopy = ""; |
| 399 | let keyCopy = ""; |
| 400 | let focusedFrame: ReturnType<typeof makeFrame> | null = null; |
| 401 | let contextFailure: Error | null = null; |
| 402 | let pageSetupFailure: Error | null = null; |
| 403 | let initialNavigation: (() => Promise<void>) | null = null; |
| 404 | let desktopRendersNext = false; |
| 405 | let desktopPageUrl = "about:blank"; |
| 406 | let desktopConnectionGate: PromiseWithResolvers<void> | null = null; |
| 407 | let desktopConnectionStarted: PromiseWithResolvers<void> | null = null; |
| 408 | /** Replaces the answer to the desktop page's size reads. */ |
| 409 | let desktopSizeAnswer: (() => Promise<Record<string, unknown>>) | null = null; |
| 410 | const desktopDetaches = new NodeEvents.EventEmitter(); |
| 411 | let desktopDetachReady = Promise.withResolvers<void>(); |
| 412 | let desktopReleased = Promise.withResolvers<void>(); |
| 413 | const desktopTabs = new Set<string>(); |
| 414 | const desktopRenders = (tabId: string) => { |
| 415 | if (desktopRendersNext) { |
| 416 | desktopRendersNext = false; |
| 417 | desktopTabs.add(tabId); |
| 418 | } |
| 419 | return desktopTabs.has(tabId); |
| 420 | }; |
| 421 | /** When set, a desktop that has not attached a tab waits for it the way the real channel does. */ |
| 422 | let desktopAttachesLate = false; |
| 423 | let desktopAttachWaiting = Promise.withResolvers<void>(); |
| 424 | const shownDesktopTabs = new (class extends Set<string> { |
| 425 | override add(tabId: string) { |
| 426 | super.add(tabId); |
| 427 | desktopDetaches.emit("shown", tabId); |
| 428 | return this; |
| 429 | } |
| 430 | })(); |
| 431 | const releasedDesktopTabs: Array<string> = []; |
| 432 | const desktopLoadFailures = new Map<string, PreviewAutomationLoadError>(); |
| 433 | const desktopTurns = new NodeEvents.EventEmitter(); |
| 434 | const desktopConnections: Array<{ |
| 435 | endpoint: string; |
| 436 | context: ReturnType<typeof makeContext>; |
| 437 | browser: { close: ReturnType<typeof vi.fn> }; |
| 438 | }> = []; |
| 439 | const testThread = { |
| 440 | threadId: ThreadId.make("browser-test-thread"), |
| 441 | providerSessionId: "agent-a", |
| 442 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 443 | }; |
| 444 | const scope = { |
| 445 | environmentId: EnvironmentId.make("browser-test-environment"), |
| 446 | thread: testThread, |
| 447 | client: undefined, |
| 448 | requestNamespace: "browser-test", |
| 449 | capabilities: new Set(["preview"] as const), |
| 450 | issuedAt: 1, |
| 451 | }; |
| 452 | const asSession = (providerSessionId: string) => ({ |
| 453 | ...scope, |
| 454 | thread: { ...testThread, providerSessionId }, |
| 455 | }); |
| 456 | const dependencies = Layer.mergeAll( |
| 457 | Broker.layer, |
| 458 | Manager.layer, |
| 459 | Layer.succeed(ServerEnvironment.ServerEnvironment, { |
| 460 | getEnvironmentId: Effect.succeed(scope.environmentId), |
| 461 | getDescriptor: Effect.die("unused descriptor"), |
| 462 | }), |
| 463 | Layer.succeed(PreviewBrowser.PreviewBrowser, { |
| 464 | executable: Effect.die("mock Chromium does not need an executable"), |
| 465 | installed: Effect.die("mock Chromium does not need an executable"), |
| 466 | }), |
| 467 | Layer.succeed(DesktopChannel.DesktopBrowserChannel, { |
| 468 | available: true, |
| 469 | awaitAttached: (key, timeout) => |
| 470 | !desktopAttachesLate || desktopRenders(key.tabId) |
| 471 | ? Effect.sync(() => desktopRenders(key.tabId)) |
| 472 | : Effect.raceFirst( |
| 473 | Stream.callback<string>((queue) => |
| 474 | Effect.acquireRelease( |
| 475 | Effect.sync(() => { |
| 476 | const onAttach = (attached: { tabId: string }) => |
| 477 | Queue.offerUnsafe(queue, attached.tabId); |
| 478 | desktopDetaches.on("attach", onAttach); |
| 479 | return onAttach; |
| 480 | }), |
| 481 | (onAttach) => Effect.sync(() => desktopDetaches.off("attach", onAttach)), |
| 482 | ), |
| 483 | ).pipe( |
| 484 | Stream.filter((tabId) => tabId === key.tabId), |
| 485 | Stream.runHead, |
| 486 | Effect.as(true), |
| 487 | ), |
| 488 | Effect.sync(() => desktopAttachWaiting.resolve()).pipe( |
| 489 | Effect.andThen(Effect.sleep(timeout)), |
| 490 | Effect.as(false), |
| 491 | ), |
| 492 | ), |
| 493 | detached: Stream.callback<{ threadId: string; tabId: string }>((queue) => |
| 494 | Effect.acquireRelease( |
| 495 | Effect.sync(() => { |
| 496 | const onDetach = (key: { threadId: string; tabId: string }) => |
| 497 | Queue.offerUnsafe(queue, key); |
| 498 | desktopDetaches.on("detach", onDetach); |
| 499 | desktopDetachReady.resolve(); |
| 500 | return onDetach; |
| 501 | }), |
| 502 | (onDetach) => Effect.sync(() => desktopDetaches.off("detach", onDetach)), |
| 503 | ), |
| 504 | ), |
| 505 | attached: Stream.callback<{ threadId: string; tabId: string }>((queue) => |
| 506 | Effect.acquireRelease( |
| 507 | Effect.sync(() => { |
| 508 | const onAttach = (key: { threadId: string; tabId: string }) => |
| 509 | Queue.offerUnsafe(queue, key); |
| 510 | desktopDetaches.on("attach", onAttach); |
| 511 | return onAttach; |
| 512 | }), |
| 513 | (onAttach) => Effect.sync(() => desktopDetaches.off("attach", onAttach)), |
| 514 | ), |
| 515 | ), |
| 516 | isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)), |
| 517 | isShown: (key) => shownDesktopTabs.has(key.tabId), |
| 518 | awaitShown: (key, timeout) => |
| 519 | shownDesktopTabs.has(key.tabId) |
| 520 | ? Effect.succeed(true) |
| 521 | : Effect.callback<boolean>((resume) => { |
| 522 | const onShown = (tabId: string) => { |
| 523 | if (tabId === key.tabId) resume(Effect.succeed(true)); |
| 524 | }; |
| 525 | desktopDetaches.on("shown", onShown); |
| 526 | return Effect.sync(() => desktopDetaches.off("shown", onShown)); |
| 527 | }).pipe(Effect.timeoutOrElse({ duration: timeout, orElse: () => Effect.succeed(false) })), |
| 528 | loadFailure: (key) => desktopLoadFailures.get(key.tabId), |
| 529 | endpoint: (key) => |
| 530 | Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () => |
| 531 | Effect.sync(() => { |
| 532 | releasedDesktopTabs.push(key.tabId); |
| 533 | desktopDetaches.emit("release", key.tabId); |
| 534 | desktopReleased.resolve(); |
| 535 | }), |
| 536 | ), |
| 537 | pointer: () => Effect.void, |
| 538 | turn: (threadId, active) => Effect.sync(() => desktopTurns.emit("turn", threadId, active)), |
| 539 | }), |
| 540 | PreviewAgentActivity.layer, |
| 541 | ).pipe( |
| 542 | Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-server-browser-" })), |
| 543 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 544 | ); |
| 545 | const layer = ServerBrowser.layer.pipe(Layer.provideMerge(dependencies)); |
| 546 | const ready = Effect.gen(function* () { |
| 547 | const browser = yield* ServerBrowser.ServerBrowser; |
| 548 | const broker = yield* Broker.PreviewAutomationBroker; |
| 549 | yield* Effect.yieldNow; |
| 550 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 551 | scope, |
| 552 | operation: "open", |
| 553 | input: { reuseExistingTab: false, show: false }, |
| 554 | }); |
| 555 | const tabId = PreviewTabId.make(opened.tabId!); |
| 556 | return { browser, broker, tabId }; |
| 557 | }); |
| 558 | const viewerInput = (tabId: string, canOperate: boolean) => ({ |
| 559 | threadId: scope.thread.threadId, |
| 560 | tabId, |
| 561 | canOperate, |
| 562 | maxWidth: 1280, |
| 563 | maxHeight: 800, |
| 564 | quality: 70, |
| 565 | }); |
| 566 | /** Fills a viewer's output with frames; resolves once every one of them is acknowledged. */ |
| 567 | const stallViewer = (viewer: ServerBrowser.ServerBrowserViewer) => { |
| 568 | const output = viewer.output as unknown as Queue.Queue<ServerBrowser.ServerBrowserViewerOutput>; |
| 569 | const acked = Promise.withResolvers<void>(); |
| 570 | let unacked = 0; |
| 571 | const ack = Effect.sync(() => { |
| 572 | if (--unacked === 0) acked.resolve(); |
| 573 | }); |
| 574 | while (Queue.offerUnsafe(output, { _tag: "frame", data: Buffer.alloc(0), ack })) unacked++; |
| 575 | return Effect.promise(() => acked.promise); |
| 576 | }; |
| 577 | const viewportSizes = (items: ReadonlyArray<ServerBrowser.ServerBrowserViewerOutput>) => |
| 578 | items.flatMap((item) => (item._tag === "viewport" ? [`${item.width}x${item.height}`] : [])); |
| 579 | const openDesktopViewer = Effect.gen(function* () { |
| 580 | const browser = yield* ServerBrowser.ServerBrowser; |
| 581 | const manager = yield* Manager.PreviewManager; |
| 582 | desktopRendersNext = true; |
| 583 | const { tabId } = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" }); |
| 584 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 585 | const context = desktopConnections[0]!.context; |
| 586 | const cdp = context.sessions[0]!; |
| 587 | const resize = (width: number, height: number) => { |
| 588 | Object.assign(context.cssViewport, { width, height }); |
| 589 | return Effect.promise(() => cdp.emitAsync("Page.frameResized")); |
| 590 | }; |
| 591 | return { tabId, viewer, context, cdp, resize }; |
| 592 | }); |
| 593 | |
| 594 | beforeEach(() => { |
| 595 | contexts.length = 0; |
| 596 | encoderPageOverride = undefined; |
| 597 | realContextOverride = undefined; |
| 598 | encoderStreams.length = 0; |
| 599 | decodeGate = null; |
| 600 | contextRequests.length = 0; |
| 601 | contextGate = null; |
| 602 | heldStill = null; |
| 603 | contextFailure = null; |
| 604 | pageSetupFailure = null; |
| 605 | initialNavigation = null; |
| 606 | pageCopy = ""; |
| 607 | keyCopy = ""; |
| 608 | focusedFrame = null; |
| 609 | desktopTabs.clear(); |
| 610 | shownDesktopTabs.clear(); |
| 611 | desktopLoadFailures.clear(); |
| 612 | desktopRendersNext = false; |
| 613 | desktopAttachesLate = false; |
| 614 | desktopAttachWaiting = Promise.withResolvers<void>(); |
| 615 | desktopPageUrl = "about:blank"; |
| 616 | desktopConnectionGate = null; |
| 617 | desktopConnectionStarted = null; |
| 618 | desktopSizeAnswer = null; |
| 619 | desktopDetachReady = Promise.withResolvers<void>(); |
| 620 | desktopReleased = Promise.withResolvers<void>(); |
| 621 | releasedDesktopTabs.length = 0; |
| 622 | desktopConnections.length = 0; |
| 623 | }); |
| 624 | |
| 625 | it.effect("tells the desktop once per thread when its agent turns start and end", () => |
| 626 | Effect.gen(function* () { |
| 627 | yield* ServerBrowser.ServerBrowser; |
| 628 | const activity = yield* PreviewAgentActivity.PreviewAgentActivity; |
| 629 | const threadId = scope.thread.threadId; |
| 630 | const turns = yield* Queue.unbounded<readonly [string, boolean]>(); |
| 631 | const record = (id: string, active: boolean) => Queue.offerUnsafe(turns, [id, active]); |
| 632 | desktopTurns.on("turn", record); |
| 633 | yield* Effect.addFinalizer(() => Effect.sync(() => desktopTurns.off("turn", record))); |
| 634 | const endFirst = yield* activity.begin(threadId); |
| 635 | // An overlapping turn on the same thread neither starts nor ends focus on its own. |
| 636 | const endSecond = yield* activity.begin(threadId); |
| 637 | expect(yield* Queue.take(turns)).toEqual([threadId, true]); |
| 638 | yield* endFirst; |
| 639 | yield* endFirst; |
| 640 | expect(yield* activity.active(threadId)).toBe(true); |
| 641 | yield* endSecond; |
| 642 | expect(yield* Queue.take(turns)).toEqual([threadId, false]); |
| 643 | expect(yield* Queue.size(turns)).toBe(0); |
| 644 | }).pipe(Effect.scoped, Effect.provide(layer)), |
| 645 | ); |
| 646 | |
| 647 | it.effect("preview_open reports its navigation timeout instead of the request budget", () => |
| 648 | Effect.scoped( |
| 649 | Effect.gen(function* () { |
| 650 | const { broker, tabId } = yield* ready; |
| 651 | const manager = yield* Manager.PreviewManager; |
| 652 | initialNavigation = async () => { |
| 653 | throw Object.assign(new Error("page.goto: Timeout 15000ms exceeded."), { |
| 654 | name: "TimeoutError", |
| 655 | }); |
| 656 | }; |
| 657 | |
| 658 | const error = yield* broker |
| 659 | .invoke<PreviewAutomationStatus>({ |
| 660 | scope, |
| 661 | operation: "open", |
| 662 | input: { |
| 663 | url: "http://localhost:1337/", |
| 664 | reuseExistingTab: false, |
| 665 | show: false, |
| 666 | }, |
| 667 | }) |
| 668 | .pipe(Effect.flip); |
| 669 | |
| 670 | expect(error).toMatchObject({ |
| 671 | _tag: "PreviewAutomationTimeoutError", |
| 672 | timeoutMs: 15_000, |
| 673 | }); |
| 674 | expect(error.message).toBe("Preview automation open timed out after 15000ms."); |
| 675 | // The failed open returned no tabId, so its tab must not linger and block later opens. |
| 676 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 677 | expect(sessions.map((session) => session.tabId)).toEqual([tabId]); |
| 678 | expect(contexts[1]!.page.close).toHaveBeenCalled(); |
| 679 | }), |
| 680 | ).pipe(Effect.provide(layer)), |
| 681 | ); |
| 682 | |
| 683 | it.effect( |
| 684 | "an initial download stays available after preview_open reports the navigation error", |
| 685 | () => |
| 686 | Effect.scoped( |
| 687 | Effect.gen(function* () { |
| 688 | const { broker, tabId } = yield* ready; |
| 689 | const manager = yield* Manager.PreviewManager; |
| 690 | const released = Promise.withResolvers<void>(); |
| 691 | initialNavigation = async () => { |
| 692 | contexts[1]!.page.emit("download", { |
| 693 | failure: async () => null, |
| 694 | delete: async () => released.resolve(), |
| 695 | saveAs: (path: string) => NodeFSP.writeFile(path, "a,b"), |
| 696 | suggestedFilename: () => "report.csv", |
| 697 | url: () => "http://localhost:1337/report.csv", |
| 698 | }); |
| 699 | throw new Error("page.goto: Download is starting"); |
| 700 | }; |
| 701 | const error = yield* broker |
| 702 | .invoke<PreviewAutomationStatus>({ |
| 703 | scope, |
| 704 | operation: "open", |
| 705 | input: { |
| 706 | url: "http://localhost:1337/report.csv", |
| 707 | reuseExistingTab: false, |
| 708 | open: false, |
| 709 | }, |
| 710 | }) |
| 711 | .pipe(Effect.flip); |
| 712 | expect(error.message).toContain("Download is starting"); |
| 713 | yield* Effect.promise(() => released.promise); |
| 714 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 715 | expect(sessions).toHaveLength(2); |
| 716 | const downloadTabId = PreviewTabId.make(sessions.find((tab) => tab.tabId !== tabId)!.tabId); |
| 717 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 718 | scope, |
| 719 | tabId: downloadTabId, |
| 720 | operation: "status", |
| 721 | input: {}, |
| 722 | }); |
| 723 | expect(status.downloads).toEqual([ |
| 724 | expect.objectContaining({ fileName: "report.csv", sizeBytes: 3 }), |
| 725 | ]); |
| 726 | expect( |
| 727 | yield* (yield* FileSystem.FileSystem).readFileString(status.downloads![0]!.path), |
| 728 | ).toBe("a,b"); |
| 729 | }), |
| 730 | ).pipe(Effect.provide(layer)), |
| 731 | ); |
| 732 | |
| 733 | it.effect.each([ |
| 734 | { renderer: "idle", title: "Heavy page" }, |
| 735 | { renderer: "busy", title: null }, |
| 736 | ])( |
| 737 | "navigate returns the committed page while its load event is still pending ($renderer renderer)", |
| 738 | ({ renderer, title }) => |
| 739 | Effect.scoped( |
| 740 | Effect.gen(function* () { |
| 741 | const { broker, tabId } = yield* ready; |
| 742 | const page = contexts[0]!.page; |
| 743 | const titleRequested = Promise.withResolvers<void>(); |
| 744 | // A busy main thread never answers title(); drive its native deadline explicitly. |
| 745 | page.title.mockImplementation(() => { |
| 746 | titleRequested.resolve(); |
| 747 | return renderer === "busy" |
| 748 | ? new Promise<string>(() => {}) |
| 749 | : Promise.resolve("Heavy page"); |
| 750 | }); |
| 751 | const heavy = "http://localhost:5173/heavy"; |
| 752 | const timedOut = (method: string, timeout: number | undefined) => |
| 753 | Object.assign(new Error(`${method}: Timeout ${timeout}ms exceeded.`), { |
| 754 | name: "TimeoutError", |
| 755 | }); |
| 756 | // The document commits and parses, but a stalled subresource holds back `load`. |
| 757 | page.goto.mockImplementation(async (next, options) => { |
| 758 | page.commit(next); |
| 759 | page.emit("request", { |
| 760 | url: () => next, |
| 761 | isNavigationRequest: () => true, |
| 762 | frame: () => page, |
| 763 | }); |
| 764 | if (options?.waitUntil === "load") throw timedOut("page.goto", options.timeout); |
| 765 | }); |
| 766 | page.waitForLoadState.mockImplementation(async (state, options) => { |
| 767 | if (state === undefined || state === "load") { |
| 768 | throw timedOut("page.waitForLoadState", options?.timeout); |
| 769 | } |
| 770 | }); |
| 771 | |
| 772 | vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); |
| 773 | const result = yield* broker |
| 774 | .invoke<PreviewAutomationStatus>({ |
| 775 | scope, |
| 776 | tabId, |
| 777 | operation: "navigate", |
| 778 | input: { url: heavy, timeoutMs: 4_000 }, |
| 779 | }) |
| 780 | .pipe(Effect.forkScoped); |
| 781 | const titleRead = yield* Effect.raceFirst( |
| 782 | Effect.promise(() => titleRequested.promise).pipe(Effect.as(true)), |
| 783 | Fiber.await(result).pipe(Effect.as(false)), |
| 784 | ); |
| 785 | if (titleRead && renderer === "busy") { |
| 786 | yield* Effect.promise(() => vi.advanceTimersByTimeAsync(250)); |
| 787 | } |
| 788 | const status = yield* Fiber.join(result); |
| 789 | |
| 790 | expect(status).toMatchObject({ url: heavy, title, loading: true }); |
| 791 | }), |
| 792 | ).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers())), Effect.provide(layer)), |
| 793 | ); |
| 794 | |
| 795 | it.effect("a desktop status answers with the last viewport while the renderer cannot measure", () => |
| 796 | Effect.scoped( |
| 797 | Effect.gen(function* () { |
| 798 | const { broker } = yield* ready; |
| 799 | desktopRendersNext = true; |
| 800 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 801 | scope, |
| 802 | operation: "open", |
| 803 | input: { url: "https://example.com/", reuseExistingTab: false, show: false }, |
| 804 | }); |
| 805 | const measuring = Promise.withResolvers<void>(); |
| 806 | desktopSizeAnswer = () => { |
| 807 | measuring.resolve(); |
| 808 | return new Promise(() => {}); |
| 809 | }; |
| 810 | // A resize makes the next status measure again. |
| 811 | yield* Effect.promise(() => |
| 812 | desktopConnections[0]!.context.sessions[0]!.emitAsync("Page.frameResized"), |
| 813 | ); |
| 814 | |
| 815 | vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); |
| 816 | const result = yield* broker |
| 817 | .invoke<PreviewAutomationStatus>({ |
| 818 | scope, |
| 819 | tabId: opened.tabId!, |
| 820 | operation: "status", |
| 821 | input: {}, |
| 822 | }) |
| 823 | .pipe(Effect.forkScoped); |
| 824 | yield* Effect.promise(() => measuring.promise); |
| 825 | yield* Effect.promise(() => vi.advanceTimersByTimeAsync(250)); |
| 826 | const status = yield* Fiber.join(result); |
| 827 | |
| 828 | expect(status.viewport).toEqual({ width: 1920, height: 1080 }); |
| 829 | }), |
| 830 | ).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers())), Effect.provide(layer)), |
| 831 | ); |
| 832 | |
| 833 | it.effect.each([ |
| 834 | { name: "an agent navigate", message: null }, |
| 835 | { name: "a viewer navigate", message: { type: "navigate", url: "http://localhost:5173/next" } }, |
| 836 | { name: "a viewer Back", message: { type: "history", delta: -1 } }, |
| 837 | { name: "a viewer Forward", message: { type: "history", delta: 1 } }, |
| 838 | { name: "a viewer Reload", message: { type: "reload" } }, |
| 839 | { name: "a viewer hard reload", message: { type: "reload", ignoreCache: true } }, |
| 840 | ])("$name stops a page script that never yields before it navigates", ({ message }) => |
| 841 | Effect.scoped( |
| 842 | Effect.gen(function* () { |
| 843 | const { browser, broker, tabId } = yield* ready; |
| 844 | const viewer = message ? yield* browser.attachViewer(viewerInput(tabId, true)) : null; |
| 845 | if (viewer) yield* viewer.input({ type: "takeControl" }); |
| 846 | const { page, sessions } = contexts[0]!; |
| 847 | // As in Chrome: the hung renderer answers nothing, and a terminate reaches it only while |
| 848 | // no navigation is pending. |
| 849 | let stopped = false; |
| 850 | const probed = Promise.withResolvers<void>(); |
| 851 | const navigatedAfterStop: Array<boolean> = []; |
| 852 | for (const cdp of sessions) { |
| 853 | const send = cdp.send.getMockImplementation()!; |
| 854 | cdp.send.mockImplementation((method, input) => { |
| 855 | if ( |
| 856 | method === "Runtime.evaluate" && |
| 857 | (input as { expression: string }).expression === "0" |
| 858 | ) { |
| 859 | probed.resolve(); |
| 860 | return new Promise(() => {}); |
| 861 | } |
| 862 | if (method === "Runtime.terminateExecution") stopped = true; |
| 863 | if (method === "Page.reload") navigatedAfterStop.push(stopped); |
| 864 | return send(method, input); |
| 865 | }); |
| 866 | } |
| 867 | const goto = page.goto.getMockImplementation()!; |
| 868 | page.goto.mockImplementation(async (next, options) => { |
| 869 | navigatedAfterStop.push(stopped); |
| 870 | return goto(next, options); |
| 871 | }); |
| 872 | for (const method of ["goBack", "goForward", "reload"] as const) { |
| 873 | page[method].mockImplementation(async () => { |
| 874 | navigatedAfterStop.push(stopped); |
| 875 | }); |
| 876 | } |
| 877 | |
| 878 | vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); |
| 879 | const result = yield* ( |
| 880 | viewer |
| 881 | ? viewer.input(message) |
| 882 | : broker.invoke<PreviewAutomationStatus>({ |
| 883 | scope, |
| 884 | tabId, |
| 885 | operation: "navigate", |
| 886 | input: { url: "http://localhost:5173/next", timeoutMs: 5_000 }, |
| 887 | }) |
| 888 | ).pipe(Effect.forkScoped); |
| 889 | const probing = yield* Effect.raceFirst( |
| 890 | Effect.promise(() => probed.promise).pipe(Effect.as(true)), |
| 891 | Fiber.await(result).pipe(Effect.as(false)), |
| 892 | ); |
| 893 | if (probing) yield* Effect.promise(() => vi.advanceTimersByTimeAsync(1_000)); |
| 894 | yield* Fiber.join(result); |
| 895 | |
| 896 | expect(navigatedAfterStop).toEqual([true]); |
| 897 | }), |
| 898 | ).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers())), Effect.provide(layer)), |
| 899 | ); |
| 900 | |
| 901 | it.live("navigate fails when the page never commits within its timeout", () => |
| 902 | Effect.scoped( |
| 903 | Effect.gen(function* () { |
| 904 | const { broker, tabId } = yield* ready; |
| 905 | contexts[0]!.page.goto.mockImplementation(async () => { |
| 906 | throw Object.assign(new Error("page.goto: Timeout 4000ms exceeded."), { |
| 907 | name: "TimeoutError", |
| 908 | }); |
| 909 | }); |
| 910 | |
| 911 | const error = yield* broker |
| 912 | .invoke<PreviewAutomationStatus>({ |
| 913 | scope, |
| 914 | tabId, |
| 915 | operation: "navigate", |
| 916 | input: { url: "http://10.255.255.1/", timeoutMs: 4_000 }, |
| 917 | }) |
| 918 | .pipe(Effect.flip); |
| 919 | |
| 920 | expect(error).toMatchObject({ _tag: "PreviewAutomationTimeoutError", timeoutMs: 4_000 }); |
| 921 | }), |
| 922 | ).pipe(Effect.provide(layer)), |
| 923 | ); |
| 924 | |
| 925 | it.effect.each(["desktop" as const, undefined])( |
| 926 | "explicit desktop targets ($0 runtime) fail without creating a server tab", |
| 927 | (runtime) => |
| 928 | Effect.scoped( |
| 929 | Effect.gen(function* () { |
| 930 | const { broker, tabId } = yield* ready; |
| 931 | const manager = yield* Manager.PreviewManager; |
| 932 | const desktop = yield* manager.open({ |
| 933 | threadId: scope.thread.threadId, |
| 934 | url: "https://example.com/original", |
| 935 | ...(runtime === undefined ? {} : { runtime }), |
| 936 | }); |
| 937 | const before = yield* manager.list({ threadId: scope.thread.threadId }); |
| 938 | const error = yield* broker |
| 939 | .invoke<PreviewAutomationStatus>({ |
| 940 | scope, |
| 941 | tabId: PreviewTabId.make(desktop.tabId), |
| 942 | operation: "open", |
| 943 | input: { url: "https://example.com/replacement", open: true }, |
| 944 | }) |
| 945 | .pipe(Effect.flip); |
| 946 | expect(error).toMatchObject({ _tag: "PreviewAutomationExecutionError" }); |
| 947 | expect(error.message).toContain("desktop runtime"); |
| 948 | expect(error.message).toContain("cannot control"); |
| 949 | expect(yield* manager.list({ threadId: scope.thread.threadId })).toEqual(before); |
| 950 | expect(contexts).toHaveLength(1); |
| 951 | const reused = yield* broker.invoke<PreviewAutomationStatus>({ |
| 952 | scope, |
| 953 | operation: "open", |
| 954 | input: { open: false }, |
| 955 | }); |
| 956 | expect(reused.tabId).toBe(tabId); |
| 957 | }), |
| 958 | ).pipe(Effect.provide(layer)), |
| 959 | ); |
| 960 | |
| 961 | it.effect("a tab the desktop does not draw is marked headless, so the desktop streams it", () => |
| 962 | Effect.scoped( |
| 963 | Effect.gen(function* () { |
| 964 | const { broker, tabId } = yield* ready; |
| 965 | const manager = yield* Manager.PreviewManager; |
| 966 | desktopRendersNext = true; |
| 967 | const desktopTab = yield* broker.invoke<PreviewAutomationStatus>({ |
| 968 | scope, |
| 969 | operation: "open", |
| 970 | input: { reuseExistingTab: false, show: false }, |
| 971 | }); |
| 972 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 973 | const headlessOf = (id: string | null) => |
| 974 | sessions.find((session) => session.tabId === id)?.headless; |
| 975 | |
| 976 | expect(headlessOf(tabId)).toBe(true); |
| 977 | expect(headlessOf(desktopTab.tabId)).toBeUndefined(); |
| 978 | }), |
| 979 | ).pipe(Effect.provide(layer)), |
| 980 | ); |
| 981 | |
| 982 | it.effect("a server started without the desktop browser channel marks its tabs headless", () => |
| 983 | Effect.scoped( |
| 984 | Effect.gen(function* () { |
| 985 | const { tabId } = yield* ready; |
| 986 | const manager = yield* Manager.PreviewManager; |
| 987 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 988 | |
| 989 | expect(sessions.find((session) => session.tabId === tabId)?.headless).toBe(true); |
| 990 | }), |
| 991 | ).pipe( |
| 992 | // A WSL-only desktop starts its backend without the browser fds. |
| 993 | Effect.provide( |
| 994 | ServerBrowser.layer.pipe( |
| 995 | Layer.provide(DesktopChannel.layer), |
| 996 | Layer.provideMerge(dependencies), |
| 997 | ), |
| 998 | ), |
| 999 | ), |
| 1000 | ); |
| 1001 | |
| 1002 | it.effect("an agent's tab the reloaded desktop dropped goes back to the desktop", () => |
| 1003 | Effect.scoped( |
| 1004 | Effect.gen(function* () { |
| 1005 | const { broker } = yield* ready; |
| 1006 | const manager = yield* Manager.PreviewManager; |
| 1007 | const threadId = scope.thread.threadId; |
| 1008 | desktopRendersNext = true; |
| 1009 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1010 | scope, |
| 1011 | operation: "open", |
| 1012 | input: { url: "https://example.com/?t=1", reuseExistingTab: false, open: false }, |
| 1013 | }); |
| 1014 | const tabId = PreviewTabId.make(opened.tabId!); |
| 1015 | // The renderer reloads on another thread: its webview goes, and it only mounts this |
| 1016 | // thread's tabs again once a preview event for the thread reaches it. |
| 1017 | yield* Effect.promise(() => desktopDetachReady.promise); |
| 1018 | desktopAttachesLate = true; |
| 1019 | desktopTabs.delete(tabId); |
| 1020 | desktopDetaches.emit("detach", { threadId, tabId }); |
| 1021 | yield* Effect.promise(() => desktopReleased.promise); |
| 1022 | // It is still reloading when the agent's call arrives, so it misses the first event. |
| 1023 | yield* Effect.gen(function* () { |
| 1024 | yield* Effect.promise(() => desktopAttachWaiting.promise); |
| 1025 | const events = yield* manager.subscribeEvents; |
| 1026 | const nextForThread = Effect.gen(function* () { |
| 1027 | let event = yield* PubSub.take(events); |
| 1028 | while (event.threadId !== threadId) event = yield* PubSub.take(events); |
| 1029 | }); |
| 1030 | yield* nextForThread; |
| 1031 | yield* nextForThread; |
| 1032 | desktopTabs.add(tabId); |
| 1033 | desktopDetaches.emit("attach", { threadId, tabId }); |
| 1034 | }).pipe(Effect.forkScoped); |
| 1035 | |
| 1036 | const evaluating = yield* broker |
| 1037 | .invoke({ |
| 1038 | scope, |
| 1039 | tabId, |
| 1040 | operation: "evaluate", |
| 1041 | input: { expression: "navigator.userAgent" }, |
| 1042 | }) |
| 1043 | .pipe(Effect.forkScoped); |
| 1044 | yield* Effect.raceFirst( |
| 1045 | Fiber.join(evaluating), |
| 1046 | Effect.promise(() => desktopAttachWaiting.promise).pipe( |
| 1047 | Effect.andThen(TestClock.adjust("10 seconds")), |
| 1048 | Effect.andThen(Fiber.join(evaluating)), |
| 1049 | ), |
| 1050 | ); |
| 1051 | const { sessions } = yield* manager.list({ threadId }); |
| 1052 | |
| 1053 | expect(sessions.find((session) => session.tabId === tabId)?.headless).toBeUndefined(); |
| 1054 | expect(desktopConnections).toHaveLength(2); |
| 1055 | }), |
| 1056 | ).pipe(Effect.provide(layer)), |
| 1057 | ); |
| 1058 | |
| 1059 | // Playwright emulates a light color scheme on every page it attaches to. |
| 1060 | it.effect("a desktop tab left on the system appearance clears Playwright's light emulation", () => |
| 1061 | Effect.scoped( |
| 1062 | Effect.gen(function* () { |
| 1063 | const { context } = yield* openDesktopViewer; |
| 1064 | |
| 1065 | expect(context.page.emulateMedia).toHaveBeenCalledWith({ colorScheme: null }); |
| 1066 | }), |
| 1067 | ).pipe(Effect.provide(layer)), |
| 1068 | ); |
| 1069 | |
| 1070 | it.effect("a desktop page that loaded before the server attached reports its loaded title", () => |
| 1071 | Effect.scoped( |
| 1072 | Effect.gen(function* () { |
| 1073 | const { broker } = yield* ready; |
| 1074 | const manager = yield* Manager.PreviewManager; |
| 1075 | const events = yield* manager.subscribeEvents; |
| 1076 | desktopRendersNext = true; |
| 1077 | desktopPageUrl = "https://example.com/loaded"; |
| 1078 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1079 | scope, |
| 1080 | operation: "open", |
| 1081 | input: { url: desktopPageUrl, reuseExistingTab: false, show: false }, |
| 1082 | }); |
| 1083 | let event = yield* PubSub.take(events); |
| 1084 | while (event.type !== "navigated" || event.tabId !== opened.tabId) { |
| 1085 | event = yield* PubSub.take(events); |
| 1086 | } |
| 1087 | |
| 1088 | expect(event.snapshot.navStatus).toEqual({ |
| 1089 | _tag: "Success", |
| 1090 | url: "https://example.com/loaded", |
| 1091 | title: "test page", |
| 1092 | }); |
| 1093 | }), |
| 1094 | ).pipe(Effect.provide(layer)), |
| 1095 | ); |
| 1096 | |
| 1097 | it.effect.each(["none", "during", "after-fragment", "same-url"])( |
| 1098 | "Stop settles an initial navigation with its request event $0", |
| 1099 | (requestTiming) => |
| 1100 | Effect.scoped( |
| 1101 | Effect.gen(function* () { |
| 1102 | const { browser, broker } = yield* ready; |
| 1103 | const manager = yield* Manager.PreviewManager; |
| 1104 | const events = yield* manager.subscribeEvents; |
| 1105 | const started = Promise.withResolvers<void>(); |
| 1106 | const committed = Promise.withResolvers<void>(); |
| 1107 | initialNavigation = () => { |
| 1108 | started.resolve(); |
| 1109 | return committed.promise; |
| 1110 | }; |
| 1111 | yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve())); |
| 1112 | const { tabId } = yield* manager.open({ |
| 1113 | threadId: scope.thread.threadId, |
| 1114 | runtime: "server", |
| 1115 | url: |
| 1116 | requestTiming === "after-fragment" |
| 1117 | ? "https://example.com/pending#section" |
| 1118 | : "https://example.com/pending", |
| 1119 | }); |
| 1120 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 1121 | yield* Effect.promise(() => started.promise); |
| 1122 | const page = contexts.at(-1)!.page; |
| 1123 | const request = { |
| 1124 | url: () => "https://example.com/pending", |
| 1125 | method: () => "GET", |
| 1126 | isNavigationRequest: () => true, |
| 1127 | frame: () => page, |
| 1128 | failure: () => ({ errorText: "net::ERR_ABORTED" }), |
| 1129 | }; |
| 1130 | const cdp = contexts.at(-1)!.sessions.at(-1)!; |
| 1131 | const send = cdp.send.getMockImplementation()!; |
| 1132 | cdp.send.mockImplementation(async (operation, input) => { |
| 1133 | if (operation === "Page.stopLoading") { |
| 1134 | committed.reject(new Error("net::ERR_ABORTED")); |
| 1135 | if (requestTiming === "during") page.emit("request", request); |
| 1136 | } |
| 1137 | return send(operation, input); |
| 1138 | }); |
| 1139 | yield* viewer.input({ type: "stopLoading" }); |
| 1140 | const stopped = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1141 | scope, |
| 1142 | tabId, |
| 1143 | operation: "status", |
| 1144 | input: {}, |
| 1145 | }); |
| 1146 | expect(stopped.loading).toBe(false); |
| 1147 | let settled = yield* PubSub.take(events); |
| 1148 | while ( |
| 1149 | settled.type !== "navigated" || |
| 1150 | settled.tabId !== tabId || |
| 1151 | settled.snapshot.navStatus._tag !== "Idle" |
| 1152 | ) { |
| 1153 | settled = yield* PubSub.take(events); |
| 1154 | } |
| 1155 | const corrected = requestTiming === "same-url"; |
| 1156 | using timeout = vi.spyOn(globalThis, "setTimeout"); |
| 1157 | if (corrected) { |
| 1158 | page.goto.mockImplementationOnce(async () => { |
| 1159 | page.emit("request", request); |
| 1160 | }); |
| 1161 | yield* viewer.input({ type: "navigate", url: request.url() }); |
| 1162 | } else if (requestTiming !== "none") { |
| 1163 | if (requestTiming === "after-fragment") page.emit("request", request); |
| 1164 | page.emit("requestfailed", request); |
| 1165 | } |
| 1166 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1167 | scope, |
| 1168 | tabId, |
| 1169 | operation: "status", |
| 1170 | input: {}, |
| 1171 | }); |
| 1172 | expect(status.loading).toBe(corrected); |
| 1173 | expect(timeout).not.toHaveBeenCalledWith(expect.any(Function), 5_000); |
| 1174 | if (!corrected) { |
| 1175 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 1176 | expect(sessions.find((session) => session.tabId === tabId)?.navStatus).toEqual({ |
| 1177 | _tag: "Idle", |
| 1178 | }); |
| 1179 | } |
| 1180 | }), |
| 1181 | ).pipe(Effect.provide(layer)), |
| 1182 | ); |
| 1183 | |
| 1184 | it.effect.each([ |
| 1185 | { |
| 1186 | method: "goto" as const, |
| 1187 | message: { type: "navigate", url: "http://10.255.255.1/" }, |
| 1188 | abortEvent: "before", |
| 1189 | }, |
| 1190 | { method: "goBack" as const, message: { type: "history", delta: -1 }, abortEvent: "before" }, |
| 1191 | { method: "goForward" as const, message: { type: "history", delta: 1 }, abortEvent: "before" }, |
| 1192 | { method: "reload" as const, message: { type: "reload" }, abortEvent: "after" }, |
| 1193 | { method: "reload" as const, message: { type: "reload" }, abortEvent: "none" }, |
| 1194 | ...["before", "after", "none"].map((abortEvent) => ({ |
| 1195 | method: "goto" as const, |
| 1196 | message: { type: "navigate", url: "http://10.255.255.1/" }, |
| 1197 | abortEvent, |
| 1198 | blank: true, |
| 1199 | })), |
| 1200 | ])("viewer $method Stop settles ($abortEvent, blank=$blank)", (testCase) => |
| 1201 | Effect.scoped( |
| 1202 | Effect.gen(function* () { |
| 1203 | const { method, message, abortEvent } = testCase; |
| 1204 | const blank = "blank" in testCase; |
| 1205 | const { browser, broker, tabId } = yield* ready; |
| 1206 | const manager = yield* Manager.PreviewManager; |
| 1207 | const events = yield* manager.subscribeEvents; |
| 1208 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 1209 | yield* viewer.input({ type: "takeControl" }); |
| 1210 | const started = Promise.withResolvers<void>(); |
| 1211 | const committed = Promise.withResolvers<void>(); |
| 1212 | const page = contexts[0]!.page; |
| 1213 | page[method].mockImplementationOnce(() => { |
| 1214 | started.resolve(); |
| 1215 | return committed.promise; |
| 1216 | }); |
| 1217 | const navigation = yield* viewer.input(message).pipe(Effect.forkScoped); |
| 1218 | yield* Effect.promise(() => started.promise); |
| 1219 | const cdp = contexts[0]!.sessions.at(-1)!; |
| 1220 | const send = cdp.send.getMockImplementation()!; |
| 1221 | const request = { |
| 1222 | url: () => "https://example.com/pending", |
| 1223 | method: () => "GET", |
| 1224 | isNavigationRequest: () => true, |
| 1225 | frame: () => page, |
| 1226 | failure: () => ({ errorText: "net::ERR_ABORTED" }), |
| 1227 | }; |
| 1228 | const typed = Promise.withResolvers<void>(); |
| 1229 | let cancelled = false; |
| 1230 | cdp.send.mockImplementation(async (operation, input) => { |
| 1231 | if (operation === "Input.insertText") typed.resolve(); |
| 1232 | if (operation === "Page.stopLoading") { |
| 1233 | cancelled = true; |
| 1234 | committed.reject(new Error("net::ERR_ABORTED")); |
| 1235 | if (abortEvent === "before") page.emit("requestfailed", request); |
| 1236 | } |
| 1237 | return send(operation, input); |
| 1238 | }); |
| 1239 | const correction = yield* Effect.gen(function* () { |
| 1240 | if (!blank) yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" }); |
| 1241 | yield* viewer.input({ type: "text", text: "hello" }); |
| 1242 | }).pipe(Effect.forkScoped); |
| 1243 | yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve())); |
| 1244 | // The text reaches the page while the first navigation is still uncommitted. |
| 1245 | yield* Effect.promise(() => typed.promise); |
| 1246 | expect(page.goto).toHaveBeenLastCalledWith( |
| 1247 | blank ? "http://10.255.255.1/" : "http://localhost:5173/fixed", |
| 1248 | expect.objectContaining({ waitUntil: "commit" }), |
| 1249 | ); |
| 1250 | expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", { |
| 1251 | text: "hello", |
| 1252 | }); |
| 1253 | page.emit("request", request); |
| 1254 | let loadingEvent = yield* PubSub.take(events); |
| 1255 | while ( |
| 1256 | loadingEvent.type !== "navigated" || |
| 1257 | loadingEvent.snapshot.navStatus._tag !== "Loading" |
| 1258 | ) { |
| 1259 | loadingEvent = yield* PubSub.take(events); |
| 1260 | } |
| 1261 | const reader = yield* browser.attachViewer(viewerInput(tabId, false)); |
| 1262 | yield* reader.input({ type: "stopLoading" }); |
| 1263 | expect(cancelled).toBe(false); |
| 1264 | if (abortEvent === "none" && !blank) committed.resolve(); |
| 1265 | yield* viewer.input({ type: "stopLoading" }); |
| 1266 | expect(cancelled).toBe(true); |
| 1267 | using timeout = vi.spyOn(globalThis, "setTimeout"); |
| 1268 | if (abortEvent === "after") page.emit("requestfailed", request); |
| 1269 | expect(timeout).not.toHaveBeenCalledWith(expect.any(Function), 5_000); |
| 1270 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1271 | scope, |
| 1272 | tabId, |
| 1273 | operation: "status", |
| 1274 | input: {}, |
| 1275 | }); |
| 1276 | expect(status.loading).toBe(false); |
| 1277 | const expectedStatus = blank ? "Idle" : "Success"; |
| 1278 | let settled = yield* PubSub.take(events); |
| 1279 | while (settled.type !== "navigated" || settled.snapshot.navStatus._tag !== expectedStatus) { |
| 1280 | settled = yield* PubSub.take(events); |
| 1281 | } |
| 1282 | if (blank) { |
| 1283 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 1284 | expect(sessions.find((session) => session.tabId === tabId)?.navStatus).toEqual({ |
| 1285 | _tag: "Idle", |
| 1286 | }); |
| 1287 | } |
| 1288 | if (settled.snapshot.navStatus._tag === "Success") |
| 1289 | expect(settled.snapshot.navStatus.url).toBe("http://localhost:5173/fixed"); |
| 1290 | expect(page[method]).toHaveBeenCalledTimes(method === "goto" && !blank ? 2 : 1); |
| 1291 | yield* viewer.input({ type: "releaseControl" }); |
| 1292 | yield* Fiber.join(navigation); |
| 1293 | yield* Fiber.join(correction); |
| 1294 | }), |
| 1295 | ).pipe(Effect.provide(layer)), |
| 1296 | ); |
| 1297 | |
| 1298 | // The fake encoder decodes every frame at 1280x800, so 30 fps hits the bitrate floor. |
| 1299 | it.effect.each([ |
| 1300 | { reports: [], frameRate: 30, bitsPerSecond: 2.5e6 }, |
| 1301 | { reports: [30], frameRate: 30, bitsPerSecond: 2.5e6 }, |
| 1302 | { reports: [60], frameRate: 60, bitsPerSecond: 1280 * 800 * 60 * 0.05 }, |
| 1303 | { reports: [60, undefined], frameRate: 60, bitsPerSecond: 1280 * 800 * 60 * 0.05 }, |
| 1304 | { reports: [60, 30], frameRate: 30, bitsPerSecond: 2.5e6 }, |
| 1305 | ] satisfies ReadonlyArray<{ |
| 1306 | reports: ReadonlyArray<BrowserRecordingFrameRate | undefined>; |
| 1307 | frameRate: number; |
| 1308 | bitsPerSecond: number; |
| 1309 | }>)( |
| 1310 | "agent recordings encode at the last reported frame rate ($reports)", |
| 1311 | ({ reports, frameRate, bitsPerSecond }) => |
| 1312 | Effect.scoped( |
| 1313 | Effect.gen(function* () { |
| 1314 | const { browser, broker, tabId } = yield* ready; |
| 1315 | const reportProfiles = yield* browser.profileReporter; |
| 1316 | for (const recordingFrameRate of reports) { |
| 1317 | yield* reportProfiles({ |
| 1318 | profiles: [], |
| 1319 | defaultProfileId: "default", |
| 1320 | ...(recordingFrameRate === undefined ? {} : { recordingFrameRate }), |
| 1321 | }); |
| 1322 | } |
| 1323 | yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} }); |
| 1324 | expect(encoderStreams).toEqual([{ frameRate, bitsPerSecond }]); |
| 1325 | }), |
| 1326 | ).pipe(Effect.provide(layer)), |
| 1327 | ); |
| 1328 | |
| 1329 | // Chrome stops sending screencast frames while too many are unacked. |
| 1330 | it.effect("recordings ack screencast frames without waiting for the encoder to decode them", () => |
| 1331 | Effect.scoped( |
| 1332 | Effect.gen(function* () { |
| 1333 | const { broker, tabId } = yield* ready; |
| 1334 | yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} }); |
| 1335 | const session = contexts[0]!.sessions.find((candidate) => |
| 1336 | candidate.send.mock.calls.some(([method]) => method === "Page.startScreencast"), |
| 1337 | )!; |
| 1338 | const gate = Promise.withResolvers<void>(); |
| 1339 | decodeGate = gate; |
| 1340 | yield* Effect.addFinalizer(() => Effect.sync(() => gate.resolve())); |
| 1341 | for (const sessionId of [1, 2, 3]) { |
| 1342 | session.emit("Page.screencastFrame", { |
| 1343 | data: Buffer.from(`frame ${sessionId}`).toString("base64"), |
| 1344 | sessionId, |
| 1345 | metadata: { deviceWidth: 1280 }, |
| 1346 | }); |
| 1347 | } |
| 1348 | expect( |
| 1349 | session.send.mock.calls.filter(([method]) => method === "Page.screencastFrameAck"), |
| 1350 | ).toHaveLength(3); |
| 1351 | }), |
| 1352 | ).pipe(Effect.provide(layer)), |
| 1353 | ); |
| 1354 | |
| 1355 | it.effect.each([{ truncated: false }, { truncated: true }])( |
| 1356 | "saves a large recording as a binary download and removes its staged file (truncated: $truncated)", |
| 1357 | ({ truncated }) => |
| 1358 | Effect.scoped( |
| 1359 | Effect.gen(function* () { |
| 1360 | const { broker, tabId } = yield* ready; |
| 1361 | const fs = yield* FileSystem.FileSystem; |
| 1362 | const bytes = 8 * 1024 * 1024; |
| 1363 | const payload = Buffer.alloc(bytes, 0x5a); |
| 1364 | let stagedPath: string | undefined; |
| 1365 | const download = Promise.withResolvers<{ saveAs: (path: string) => Promise<void> }>(); |
| 1366 | const sandbox = NodeVM.createContext({ |
| 1367 | __t3Recorder: { |
| 1368 | frame: async () => true, |
| 1369 | stop: async () => ({ mimeType: "video/webm", count: 1, bytes }), |
| 1370 | chunk: async () => { |
| 1371 | throw new Error("Large recording used Base64 export"); |
| 1372 | }, |
| 1373 | download: () => |
| 1374 | download.resolve({ |
| 1375 | saveAs: async (path) => { |
| 1376 | stagedPath = path; |
| 1377 | await NodeFSP.writeFile(path, truncated ? payload.subarray(1) : payload); |
| 1378 | }, |
| 1379 | }), |
| 1380 | }, |
| 1381 | }); |
| 1382 | encoderPageOverride = { |
| 1383 | ...makeContext().page, |
| 1384 | evaluate: async (script: string | ((arg: unknown) => unknown), arg?: unknown) => |
| 1385 | typeof script === "function" |
| 1386 | ? NodeVM.runInContext(`(${script.toString()})`, sandbox)(arg) |
| 1387 | : undefined, |
| 1388 | waitForEvent: () => download.promise, |
| 1389 | } as unknown as Page; |
| 1390 | |
| 1391 | yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} }); |
| 1392 | const stop = broker.invoke<{ path: string; sizeBytes: number }>({ |
| 1393 | scope, |
| 1394 | tabId, |
| 1395 | operation: "recordingStop", |
| 1396 | input: {}, |
| 1397 | }); |
| 1398 | if (truncated) { |
| 1399 | expect(yield* stop.pipe(Effect.flip)).toMatchObject({ |
| 1400 | _tag: "PreviewAutomationExecutionError", |
| 1401 | }); |
| 1402 | } else { |
| 1403 | const artifact = yield* stop; |
| 1404 | expect(artifact.sizeBytes).toBe(bytes); |
| 1405 | expect(Buffer.from(yield* fs.readFile(artifact.path)).equals(payload)).toBe(true); |
| 1406 | } |
| 1407 | expect(stagedPath).toBeDefined(); |
| 1408 | expect(yield* fs.exists(stagedPath!)).toBe(false); |
| 1409 | }), |
| 1410 | ).pipe(Effect.provide(layer)), |
| 1411 | ); |
| 1412 | |
| 1413 | it.effect.each([ |
| 1414 | { refreshFails: false, expected: "final frame" }, |
| 1415 | { refreshFails: true, expected: "frame" }, |
| 1416 | ])( |
| 1417 | "saves the last page state when stopping a recording ($refreshFails)", |
| 1418 | ({ refreshFails, expected }) => |
| 1419 | Effect.scoped( |
| 1420 | Effect.gen(function* () { |
| 1421 | const { broker, tabId } = yield* ready; |
| 1422 | const fs = yield* FileSystem.FileSystem; |
| 1423 | yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} }); |
| 1424 | |
| 1425 | const cdp = contexts[0]!.sessions[0]!; |
| 1426 | const send = cdp.send.getMockImplementation()!; |
| 1427 | cdp.send.mockImplementation((method, input) => { |
| 1428 | if (method !== "Page.captureScreenshot") return send(method, input); |
| 1429 | return refreshFails |
| 1430 | ? Promise.reject(new Error("Page cannot capture a frame")) |
| 1431 | : Promise.resolve({ data: Buffer.from("final frame").toString("base64") }); |
| 1432 | }); |
| 1433 | const artifact = yield* broker.invoke<{ path: string }>({ |
| 1434 | scope, |
| 1435 | tabId, |
| 1436 | operation: "recordingStop", |
| 1437 | input: {}, |
| 1438 | }); |
| 1439 | expect(yield* fs.readFileString(artifact.path)).toBe(expected); |
| 1440 | }), |
| 1441 | ).pipe(Effect.provide(layer)), |
| 1442 | ); |
| 1443 | |
| 1444 | it.effect("enforces provider ownership and explicit targets when a session has multiple tabs", () => |
| 1445 | Effect.scoped( |
| 1446 | Effect.gen(function* () { |
| 1447 | const { broker, tabId } = yield* ready; |
| 1448 | const foreign = yield* broker |
| 1449 | .invoke<void>({ |
| 1450 | scope: asSession("agent-b"), |
| 1451 | tabId, |
| 1452 | operation: "navigate", |
| 1453 | input: { url: "http://localhost:5173/foreign" }, |
| 1454 | }) |
| 1455 | .pipe(Effect.flip); |
| 1456 | expect(foreign).toMatchObject({ |
| 1457 | _tag: "PreviewAutomationControlInterruptedError", |
| 1458 | reason: "agentMismatch", |
| 1459 | }); |
| 1460 | expect(contexts[0]!.page.goto).not.toHaveBeenCalledWith( |
| 1461 | "http://localhost:5173/foreign", |
| 1462 | expect.anything(), |
| 1463 | ); |
| 1464 | yield* broker.invoke<PreviewAutomationSnapshot>({ |
| 1465 | scope: asSession("agent-b"), |
| 1466 | tabId, |
| 1467 | operation: "snapshot", |
| 1468 | input: {}, |
| 1469 | }); |
| 1470 | const foreignEvaluate = yield* broker |
| 1471 | .invoke<void>({ |
| 1472 | scope: asSession("agent-b"), |
| 1473 | tabId, |
| 1474 | operation: "evaluate", |
| 1475 | input: { expression: "read()" }, |
| 1476 | }) |
| 1477 | .pipe(Effect.flip); |
| 1478 | expect(foreignEvaluate).toMatchObject({ |
| 1479 | _tag: "PreviewAutomationControlInterruptedError", |
| 1480 | reason: "agentMismatch", |
| 1481 | }); |
| 1482 | yield* broker.invoke({ |
| 1483 | scope, |
| 1484 | operation: "open", |
| 1485 | input: { reuseExistingTab: false, show: false }, |
| 1486 | }); |
| 1487 | const ambiguous = yield* broker |
| 1488 | .invoke<void>({ scope, operation: "evaluate", input: { expression: "ambiguous()" } }) |
| 1489 | .pipe(Effect.flip); |
| 1490 | expect(ambiguous).toMatchObject({ |
| 1491 | _tag: "PreviewAutomationControlInterruptedError", |
| 1492 | reason: "tabRequired", |
| 1493 | }); |
| 1494 | const ambiguousStop = yield* broker |
| 1495 | .invoke<void>({ scope, operation: "recordingStop", input: {} }) |
| 1496 | .pipe(Effect.flip); |
| 1497 | expect(ambiguousStop).toMatchObject({ |
| 1498 | _tag: "PreviewAutomationControlInterruptedError", |
| 1499 | reason: "tabRequired", |
| 1500 | }); |
| 1501 | const explicitStop = yield* broker |
| 1502 | .invoke<void>({ scope, tabId, operation: "recordingStop", input: {} }) |
| 1503 | .pipe(Effect.flip); |
| 1504 | expect(explicitStop).toMatchObject({ |
| 1505 | _tag: "PreviewAutomationExecutionError", |
| 1506 | cause: { _tag: "PreviewAutomationRecordingNotActiveError" }, |
| 1507 | }); |
| 1508 | const result = yield* broker.invoke({ |
| 1509 | scope, |
| 1510 | tabId, |
| 1511 | operation: "evaluate", |
| 1512 | input: { expression: "owned()" }, |
| 1513 | }); |
| 1514 | expect(result).toBe("evaluated"); |
| 1515 | expect(contexts).toHaveLength(2); |
| 1516 | |
| 1517 | const manager = yield* Manager.PreviewManager; |
| 1518 | const unclaimed = yield* manager.open({ |
| 1519 | threadId: scope.thread.threadId, |
| 1520 | runtime: "server", |
| 1521 | }); |
| 1522 | const closeUnclaimed = yield* broker |
| 1523 | .invoke<void>({ |
| 1524 | scope, |
| 1525 | tabId: PreviewTabId.make(unclaimed.tabId), |
| 1526 | operation: "close", |
| 1527 | input: {}, |
| 1528 | }) |
| 1529 | .pipe(Effect.flip); |
| 1530 | expect(closeUnclaimed).toMatchObject({ |
| 1531 | _tag: "PreviewAutomationControlInterruptedError", |
| 1532 | reason: "unclaimedTab", |
| 1533 | }); |
| 1534 | expect(closeUnclaimed.message).toBe( |
| 1535 | "This tab has no agent owner. Ask the user to close it in the browser panel.", |
| 1536 | ); |
| 1537 | expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toContainEqual( |
| 1538 | expect.objectContaining({ tabId: unclaimed.tabId }), |
| 1539 | ); |
| 1540 | }), |
| 1541 | ).pipe(Effect.provide(layer)), |
| 1542 | ); |
| 1543 | |
| 1544 | it.effect("a first still that never returns does not stall the tab's later captures", () => |
| 1545 | Effect.scoped( |
| 1546 | Effect.gen(function* () { |
| 1547 | const { browser, broker, tabId } = yield* ready; |
| 1548 | vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); |
| 1549 | yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers())); |
| 1550 | const capturing = Promise.withResolvers<void>(); |
| 1551 | const stuck = Promise.withResolvers<void>(); |
| 1552 | heldStill = () => { |
| 1553 | heldStill = null; |
| 1554 | capturing.resolve(); |
| 1555 | return stuck.promise; |
| 1556 | }; |
| 1557 | yield* Effect.addFinalizer(() => Effect.sync(() => stuck.resolve())); |
| 1558 | yield* browser.attachViewer(viewerInput(tabId, true)); |
| 1559 | yield* Effect.promise(() => capturing.promise); |
| 1560 | const snapshotting = yield* broker |
| 1561 | .invoke<PreviewAutomationSnapshot>({ scope, tabId, operation: "snapshot", input: {} }) |
| 1562 | .pipe(Effect.forkScoped); |
| 1563 | yield* Effect.promise(() => vi.advanceTimersByTimeAsync(2_000)); |
| 1564 | const snapshot = yield* Fiber.join(snapshotting); |
| 1565 | expect(snapshot.accessibilityTree).toContain("delete"); |
| 1566 | const second = yield* browser.attachViewer(viewerInput(tabId, false)); |
| 1567 | const frame = yield* Stream.fromQueue(second.output).pipe( |
| 1568 | Stream.filter((output) => output._tag === "frame"), |
| 1569 | Stream.runHead, |
| 1570 | ); |
| 1571 | expect(Option.isSome(frame)).toBe(true); |
| 1572 | }), |
| 1573 | ).pipe(Effect.provide(layer)), |
| 1574 | ); |
| 1575 | |
| 1576 | it.effect("keeps a tab's zoom when its viewer resizes", () => |
| 1577 | Effect.scoped( |
| 1578 | Effect.gen(function* () { |
| 1579 | const browser = yield* ServerBrowser.ServerBrowser; |
| 1580 | const manager = yield* Manager.PreviewManager; |
| 1581 | const { tabId } = yield* manager.open({ |
| 1582 | threadId: scope.thread.threadId, |
| 1583 | runtime: "server", |
| 1584 | zoomFactor: 1.5, |
| 1585 | }); |
| 1586 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 1587 | yield* viewer.input({ type: "takeControl" }); |
| 1588 | const cdp = contexts[0]!.sessions[0]!; |
| 1589 | cdp.send.mockClear(); |
| 1590 | // Resizing the page resets Chromium's device metrics, so zoom must be applied again. |
| 1591 | yield* viewer.input({ type: "resize", width: 390, height: 844 }); |
| 1592 | expect(cdp.send).toHaveBeenCalledWith( |
| 1593 | "Emulation.setDeviceMetricsOverride", |
| 1594 | expect.objectContaining({ deviceScaleFactor: 3 }), |
| 1595 | ); |
| 1596 | }), |
| 1597 | ).pipe(Effect.provide(layer)), |
| 1598 | ); |
| 1599 | |
| 1600 | it.effect( |
| 1601 | "streams to a read-only viewer without allowing takeover, input, or viewport changes", |
| 1602 | () => |
| 1603 | Effect.scoped( |
| 1604 | Effect.gen(function* () { |
| 1605 | const { browser, tabId } = yield* ready; |
| 1606 | const viewer = yield* browser.attachViewer(viewerInput(tabId, false)); |
| 1607 | const page = contexts[0]!.page; |
| 1608 | page.setViewportSize.mockClear(); |
| 1609 | const session = contexts[0]!.sessions.at(-1)!; |
| 1610 | session.send.mockClear(); |
| 1611 | for (const message of [ |
| 1612 | { type: "takeControl" }, |
| 1613 | { type: "key", action: "down", key: "a", text: "a" }, |
| 1614 | { type: "resize", width: 390, height: 844 }, |
| 1615 | { type: "viewport", setting: { _tag: "freeform", width: 390, height: 844 } }, |
| 1616 | ]) |
| 1617 | yield* viewer.input(message); |
| 1618 | expect(page.setViewportSize).not.toHaveBeenCalled(); |
| 1619 | expect(session.send.mock.calls.some(([method]) => method.startsWith("Input."))).toBe(false); |
| 1620 | const outputs = yield* Stream.fromQueue(viewer.output).pipe( |
| 1621 | Stream.takeUntil((output) => output._tag === "frame"), |
| 1622 | Stream.runCollect, |
| 1623 | ); |
| 1624 | expect(outputs).toContainEqual( |
| 1625 | expect.objectContaining({ _tag: "frame", data: Buffer.from("frame") }), |
| 1626 | ); |
| 1627 | expect(outputs).toContainEqual(expect.objectContaining({ _tag: "viewport" })); |
| 1628 | expect(outputs).toContainEqual( |
| 1629 | expect.objectContaining({ _tag: "control", canOperate: false, controller: "agent" }), |
| 1630 | ); |
| 1631 | const operator = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 1632 | yield* operator.input({ type: "takeControl" }); |
| 1633 | yield* operator.input({ type: "text", text: "typed" }); |
| 1634 | yield* operator.input({ type: "resize", width: 390, height: 844 }); |
| 1635 | expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", { |
| 1636 | text: "typed", |
| 1637 | }); |
| 1638 | expect(page.setViewportSize).toHaveBeenCalledWith({ width: 390, height: 844 }); |
| 1639 | yield* operator.input({ type: "releaseControl" }); |
| 1640 | }), |
| 1641 | ).pipe(Effect.provide(layer)), |
| 1642 | ); |
| 1643 | |
| 1644 | it.effect( |
| 1645 | "takeover waits for the running agent and revokes snapshot refs before returning control", |
| 1646 | () => |
| 1647 | Effect.scoped( |
| 1648 | Effect.gen(function* () { |
| 1649 | const { browser, broker, tabId } = yield* ready; |
| 1650 | const snapshot = yield* broker.invoke<PreviewAutomationSnapshot>({ |
| 1651 | scope, |
| 1652 | tabId, |
| 1653 | operation: "snapshot", |
| 1654 | input: {}, |
| 1655 | }); |
| 1656 | const ref = /\[ref=([^\]]+)\]/.exec(String(snapshot.accessibilityTree))![1]!; |
| 1657 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 1658 | const started = Promise.withResolvers<void>(); |
| 1659 | const finish = Promise.withResolvers<Record<string, unknown>>(); |
| 1660 | const session = contexts[0]!.sessions[0]!; |
| 1661 | session.send.mockImplementationOnce(async () => { |
| 1662 | started.resolve(); |
| 1663 | return finish.promise; |
| 1664 | }); |
| 1665 | const running = yield* broker |
| 1666 | .invoke({ scope, tabId, operation: "evaluate", input: { expression: "pending()" } }) |
| 1667 | .pipe(Effect.forkScoped); |
| 1668 | yield* Effect.addFinalizer(() => |
| 1669 | Effect.sync(() => finish.resolve({ result: { value: "finished" } })), |
| 1670 | ); |
| 1671 | yield* Effect.promise(() => started.promise); |
| 1672 | const takeover = yield* viewer.input({ type: "takeControl" }).pipe(Effect.forkScoped); |
| 1673 | let control = yield* Queue.take(viewer.output); |
| 1674 | while (control._tag !== "control" || control.controller !== "you") { |
| 1675 | control = yield* Queue.take(viewer.output); |
| 1676 | } |
| 1677 | const rejected = yield* broker |
| 1678 | .invoke<void>({ scope, tabId, operation: "evaluate", input: { expression: "racing()" } }) |
| 1679 | .pipe(Effect.flip); |
| 1680 | expect(rejected).toMatchObject({ |
| 1681 | _tag: "PreviewAutomationControlInterruptedError", |
| 1682 | reason: "humanControl", |
| 1683 | }); |
| 1684 | finish.resolve({ result: { value: "finished" } }); |
| 1685 | expect(yield* Fiber.join(running)).toBe("finished"); |
| 1686 | yield* Fiber.join(takeover); |
| 1687 | yield* viewer.input({ type: "releaseControl" }); |
| 1688 | const stale = yield* broker |
| 1689 | .invoke<void>({ scope, tabId, operation: "click", input: { locator: `aria-ref=${ref}` } }) |
| 1690 | .pipe(Effect.flip); |
| 1691 | expect(stale._tag).toBe("PreviewAutomationInvalidSelectorError"); |
| 1692 | expect(contexts[0]!.page.locator).not.toHaveBeenCalled(); |
| 1693 | expect( |
| 1694 | yield* broker.invoke({ |
| 1695 | scope, |
| 1696 | tabId, |
| 1697 | operation: "evaluate", |
| 1698 | input: { expression: "resumed()" }, |
| 1699 | }), |
| 1700 | ).toBe("evaluated"); |
| 1701 | }), |
| 1702 | ).pipe(Effect.provide(layer)), |
| 1703 | ); |
| 1704 | |
| 1705 | it.effect( |
| 1706 | "reports a valid CSS selector that matches several elements as ambiguous, not invalid", |
| 1707 | () => |
| 1708 | Effect.scoped( |
| 1709 | Effect.gen(function* () { |
| 1710 | const { broker, tabId } = yield* ready; |
| 1711 | const strict = new Error( |
| 1712 | "locator.scrollIntoViewIfNeeded: Error: strict mode violation: locator('button[aria-label=\\'Permissions: Full access\\']') resolved to 2 elements:", |
| 1713 | ); |
| 1714 | contexts[0]!.page.locator.mockImplementation( |
| 1715 | () => |
| 1716 | new Proxy( |
| 1717 | {}, |
| 1718 | { |
| 1719 | get: () => async () => { |
| 1720 | throw strict; |
| 1721 | }, |
| 1722 | }, |
| 1723 | ), |
| 1724 | ); |
| 1725 | const failure = yield* broker |
| 1726 | .invoke<void>({ |
| 1727 | scope, |
| 1728 | tabId, |
| 1729 | operation: "click", |
| 1730 | input: { selector: "button[aria-label='Permissions: Full access']", timeoutMs: 1_000 }, |
| 1731 | }) |
| 1732 | .pipe(Effect.flip); |
| 1733 | expect(failure.message).not.toMatch(/invalid selector/); |
| 1734 | expect(failure.message).toMatch(/2 elements/); |
| 1735 | }), |
| 1736 | ).pipe(Effect.provide(layer)), |
| 1737 | ); |
| 1738 | |
| 1739 | it.effect("reports a pending dialog without evaluating the page and resolves it explicitly", () => |
| 1740 | Effect.scoped( |
| 1741 | Effect.gen(function* () { |
| 1742 | const { broker, tabId } = yield* ready; |
| 1743 | const page = contexts[0]!.page; |
| 1744 | yield* broker.invoke({ |
| 1745 | scope, |
| 1746 | tabId, |
| 1747 | operation: "navigate", |
| 1748 | input: { url: "http://localhost:5173" }, |
| 1749 | }); |
| 1750 | const started = Promise.withResolvers<void>(); |
| 1751 | const resolvedEvaluation = Promise.withResolvers<Record<string, unknown>>(); |
| 1752 | const session = contexts[0]!.sessions[0]!; |
| 1753 | const send = session.send.getMockImplementation()!; |
| 1754 | session.send.mockImplementation(async (method, input) => { |
| 1755 | if (method !== "Runtime.evaluate") return send(method, input); |
| 1756 | started.resolve(); |
| 1757 | return resolvedEvaluation.promise; |
| 1758 | }); |
| 1759 | const blockedAction = yield* broker |
| 1760 | .invoke({ |
| 1761 | scope, |
| 1762 | tabId, |
| 1763 | operation: "evaluate", |
| 1764 | input: { expression: 'confirm("Delete row?")' }, |
| 1765 | }) |
| 1766 | .pipe(Effect.forkScoped); |
| 1767 | yield* Effect.addFinalizer(() => |
| 1768 | Effect.sync(() => resolvedEvaluation.resolve({ result: { value: true } })), |
| 1769 | ); |
| 1770 | yield* Effect.promise(() => started.promise); |
| 1771 | const dialog = { |
| 1772 | type: () => "confirm", |
| 1773 | message: () => "Delete row?", |
| 1774 | defaultValue: () => "", |
| 1775 | accept: vi.fn(async () => { |
| 1776 | resolvedEvaluation.resolve({ result: { value: true } }); |
| 1777 | }), |
| 1778 | dismiss: vi.fn(async () => {}), |
| 1779 | }; |
| 1780 | page.emit("dialog", dialog); |
| 1781 | page.title.mockClear(); |
| 1782 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1783 | scope, |
| 1784 | tabId, |
| 1785 | operation: "status", |
| 1786 | input: {}, |
| 1787 | }); |
| 1788 | expect(status.dialog).toMatchObject({ type: "confirm", message: "Delete row?" }); |
| 1789 | expect(page.title).not.toHaveBeenCalled(); |
| 1790 | expect(dialog.dismiss).not.toHaveBeenCalled(); |
| 1791 | const reuse = yield* broker |
| 1792 | .invoke<void>({ |
| 1793 | scope, |
| 1794 | tabId, |
| 1795 | operation: "open", |
| 1796 | input: { url: "http://localhost:5173/other" }, |
| 1797 | }) |
| 1798 | .pipe(Effect.flip); |
| 1799 | expect(reuse).toMatchObject({ |
| 1800 | _tag: "PreviewAutomationControlInterruptedError", |
| 1801 | reason: "dialogPending", |
| 1802 | }); |
| 1803 | expect(page.goto).toHaveBeenCalledTimes(1); |
| 1804 | yield* broker.invoke({ scope, tabId, operation: "dialog", input: { accept: true } }); |
| 1805 | expect(yield* Fiber.join(blockedAction)).toBe(true); |
| 1806 | expect(dialog.accept).toHaveBeenCalledTimes(1); |
| 1807 | const resolved = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1808 | scope, |
| 1809 | tabId, |
| 1810 | operation: "status", |
| 1811 | input: {}, |
| 1812 | }); |
| 1813 | expect(resolved.dialog).toBeNull(); |
| 1814 | }), |
| 1815 | ).pipe(Effect.provide(layer)), |
| 1816 | ); |
| 1817 | |
| 1818 | it.effect("closing an isolated tab closes its context only after the page closes", () => |
| 1819 | Effect.scoped( |
| 1820 | Effect.gen(function* () { |
| 1821 | const { broker, tabId } = yield* ready; |
| 1822 | const context = contexts[0]!; |
| 1823 | const page = context.page; |
| 1824 | page.beforeUnload = "listen"; |
| 1825 | page.unloadGate = Promise.withResolvers<void>(); |
| 1826 | yield* broker.invoke({ scope, tabId, operation: "close", input: {} }); |
| 1827 | expect(context.close).not.toHaveBeenCalled(); |
| 1828 | expect(page.isClosed()).toBe(false); |
| 1829 | page.unloadGate.resolve(); |
| 1830 | yield* Effect.promise(() => context.closing.promise); |
| 1831 | expect(page.isClosed()).toBe(true); |
| 1832 | expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]); |
| 1833 | }), |
| 1834 | ).pipe(Effect.provide(layer)), |
| 1835 | ); |
| 1836 | |
| 1837 | it.effect("closing a tab force-closes a page that never finishes unloading", () => |
| 1838 | Effect.scoped( |
| 1839 | Effect.gen(function* () { |
| 1840 | const { broker, tabId } = yield* ready; |
| 1841 | const context = contexts[0]!; |
| 1842 | const page = context.page; |
| 1843 | page.beforeUnload = "listen"; |
| 1844 | page.unloadGate = Promise.withResolvers<void>(); |
| 1845 | vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); |
| 1846 | yield* broker.invoke({ scope, tabId, operation: "close", input: {} }); |
| 1847 | vi.advanceTimersByTime(4_999); |
| 1848 | expect(page.isClosed()).toBe(false); |
| 1849 | expect(context.close).not.toHaveBeenCalled(); |
| 1850 | vi.advanceTimersByTime(1); |
| 1851 | expect(page.isClosed()).toBe(true); |
| 1852 | yield* Effect.promise(() => context.closing.promise); |
| 1853 | expect(vi.getTimerCount()).toBe(0); |
| 1854 | }).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers()))), |
| 1855 | ).pipe(Effect.provide(layer)), |
| 1856 | ); |
| 1857 | |
| 1858 | it.effect("closing a desktop tab during setup unloads its page before disconnecting", () => |
| 1859 | Effect.scoped( |
| 1860 | Effect.gen(function* () { |
| 1861 | const { broker } = yield* ready; |
| 1862 | const manager = yield* Manager.PreviewManager; |
| 1863 | desktopRendersNext = true; |
| 1864 | const gate = (desktopConnectionGate = Promise.withResolvers<void>()); |
| 1865 | const started = (desktopConnectionStarted = Promise.withResolvers<void>()); |
| 1866 | yield* Effect.addFinalizer(() => Effect.sync(() => gate.resolve())); |
| 1867 | const opening = yield* broker |
| 1868 | .invoke<PreviewAutomationStatus>({ |
| 1869 | scope, |
| 1870 | operation: "open", |
| 1871 | input: { reuseExistingTab: false, open: false }, |
| 1872 | }) |
| 1873 | .pipe(Effect.result, Effect.forkScoped); |
| 1874 | yield* Effect.promise(() => started.promise); |
| 1875 | const { context, browser } = desktopConnections[0]!; |
| 1876 | const page = context.page; |
| 1877 | page.beforeUnload = "listen"; |
| 1878 | page.unloadGate = Promise.withResolvers<void>(); |
| 1879 | const { sessions } = yield* manager.list({ threadId: testThread.threadId }); |
| 1880 | const session = sessions.find((candidate) => !candidate.headless)!; |
| 1881 | const closing = yield* manager |
| 1882 | .close({ threadId: testThread.threadId, tabId: session.tabId }) |
| 1883 | .pipe(Effect.forkScoped({ startImmediately: true })); |
| 1884 | expect(page.isClosed()).toBe(false); |
| 1885 | gate.resolve(); |
| 1886 | yield* Effect.promise(() => |
| 1887 | Promise.race([page.pagehideWatched.promise, desktopReleased.promise]), |
| 1888 | ); |
| 1889 | expect((yield* manager.list({ threadId: testThread.threadId })).sessions).toEqual( |
| 1890 | expect.arrayContaining([expect.objectContaining({ tabId: session.tabId })]), |
| 1891 | ); |
| 1892 | page.unloadGate.resolve(); |
| 1893 | yield* Fiber.join(closing); |
| 1894 | expect(yield* Fiber.join(opening)).toMatchObject({ _tag: "Failure" }); |
| 1895 | yield* Effect.promise(() => desktopReleased.promise); |
| 1896 | expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]); |
| 1897 | expect(page.isClosed()).toBe(true); |
| 1898 | expect(browser.close).toHaveBeenCalled(); |
| 1899 | }), |
| 1900 | ).pipe(Effect.provide(layer)), |
| 1901 | ); |
| 1902 | |
| 1903 | it.effect.each(["agent", "client", "all", "concurrent"] as const)( |
| 1904 | "closing a desktop tab waits for unload before removal (%s)", |
| 1905 | (source) => |
| 1906 | Effect.scoped( |
| 1907 | Effect.gen(function* () { |
| 1908 | const { broker } = yield* ready; |
| 1909 | const manager = yield* Manager.PreviewManager; |
| 1910 | desktopRendersNext = true; |
| 1911 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1912 | scope, |
| 1913 | operation: "open", |
| 1914 | input: { reuseExistingTab: false, open: false }, |
| 1915 | }); |
| 1916 | const tabId = PreviewTabId.make(opened.tabId!); |
| 1917 | const { context, browser } = desktopConnections[0]!; |
| 1918 | const page = context.page; |
| 1919 | // The desktop removes the webview once the session closes, dropping an unload in progress. |
| 1920 | const events = yield* manager.subscribeEvents; |
| 1921 | const sessionClosed = Promise.withResolvers<void>(); |
| 1922 | yield* Effect.gen(function* () { |
| 1923 | while ((yield* PubSub.take(events)).type !== "closed"); |
| 1924 | page.removed = true; |
| 1925 | sessionClosed.resolve(); |
| 1926 | }).pipe(Effect.forkScoped); |
| 1927 | page.beforeUnload = "listen"; |
| 1928 | page.unloadGate = Promise.withResolvers<void>(); |
| 1929 | const close = () => manager.close({ threadId: testThread.threadId, tabId }); |
| 1930 | const closing = yield* ( |
| 1931 | source === "agent" |
| 1932 | ? broker.invoke({ scope, tabId, operation: "close", input: {} }) |
| 1933 | : source === "all" |
| 1934 | ? manager.close({ threadId: testThread.threadId }) |
| 1935 | : source === "concurrent" |
| 1936 | ? Effect.all([close(), close()], { concurrency: "unbounded", discard: true }) |
| 1937 | : close() |
| 1938 | ).pipe(Effect.forkScoped); |
| 1939 | // The page finishes unloading once the server listens for it, or too late if it never does. |
| 1940 | yield* Effect.promise(() => |
| 1941 | Promise.race([page.pagehideWatched.promise, sessionClosed.promise]), |
| 1942 | ); |
| 1943 | expect(browser.close).not.toHaveBeenCalled(); |
| 1944 | const openedDuringClose = |
| 1945 | source === "all" |
| 1946 | ? yield* manager.open({ threadId: testThread.threadId, runtime: "server" }) |
| 1947 | : undefined; |
| 1948 | page.unloadGate.resolve(); |
| 1949 | yield* Fiber.join(closing); |
| 1950 | yield* Effect.promise(() => desktopReleased.promise); |
| 1951 | expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]); |
| 1952 | expect(browser.close).toHaveBeenCalledTimes(1); |
| 1953 | if (openedDuringClose) { |
| 1954 | const remaining = yield* manager.list({ threadId: testThread.threadId }); |
| 1955 | expect(remaining.sessions.map((session) => session.tabId)).toContain( |
| 1956 | openedDuringClose.tabId, |
| 1957 | ); |
| 1958 | } |
| 1959 | }), |
| 1960 | ).pipe(Effect.provide(layer)), |
| 1961 | ); |
| 1962 | |
| 1963 | it.effect("closing a tab with an unsaved-changes guard still closes it", () => |
| 1964 | Effect.scoped( |
| 1965 | Effect.gen(function* () { |
| 1966 | const browser = yield* ServerBrowser.ServerBrowser; |
| 1967 | const broker = yield* Broker.PreviewAutomationBroker; |
| 1968 | yield* Effect.yieldNow; |
| 1969 | // A profile context is shared, so closing the tab cannot fall back to closing its context. |
| 1970 | const reportProfiles = yield* browser.profileReporter; |
| 1971 | yield* reportProfiles({ |
| 1972 | profiles: [{ id: "profile-work", name: "Work", kind: "persistent" }], |
| 1973 | defaultProfileId: "profile-work", |
| 1974 | }); |
| 1975 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 1976 | scope, |
| 1977 | operation: "open", |
| 1978 | input: { reuseExistingTab: false, show: false, profileId: "profile-work" }, |
| 1979 | }); |
| 1980 | const tabId = PreviewTabId.make(opened.tabId!); |
| 1981 | expect(contextRequests).toEqual([{ profileId: "profile-work", isolated: false }]); |
| 1982 | const page = contexts[0]!.page; |
| 1983 | page.beforeUnload = "guard"; |
| 1984 | yield* broker.invoke({ scope, tabId, operation: "close", input: {} }); |
| 1985 | // The mock raises the dialog inside `close`, so an unanswered guard leaves the page open here. |
| 1986 | expect(page.beforeUnloadDialog).not.toBeNull(); |
| 1987 | expect(page.beforeUnloadDialog!.accept).toHaveBeenCalledTimes(1); |
| 1988 | expect(page.isClosed()).toBe(true); |
| 1989 | expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]); |
| 1990 | }), |
| 1991 | ).pipe(Effect.provide(layer)), |
| 1992 | ); |
| 1993 | |
| 1994 | it.effect("a tab whose renderer crashes stays open instead of vanishing", () => |
| 1995 | Effect.scoped( |
| 1996 | Effect.gen(function* () { |
| 1997 | const { browser, broker, tabId } = yield* ready; |
| 1998 | const url = `https://example.com/app?${"a".repeat(3000)}`; |
| 1999 | contexts[0]!.page.commit(url); |
| 2000 | yield* Effect.promise(() => contexts[0]!.page.emitAsync("crash")); |
| 2001 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2002 | scope, |
| 2003 | tabId, |
| 2004 | operation: "status", |
| 2005 | input: {}, |
| 2006 | }); |
| 2007 | expect(status.tabId).toBe(tabId); |
| 2008 | expect(status.loadError).toEqual({ |
| 2009 | url: url.slice(0, 2048), |
| 2010 | code: -2, |
| 2011 | description: "Page crashed", |
| 2012 | }); |
| 2013 | // The crashed page cannot load anything again, so Reload goes to the page that replaced it. |
| 2014 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2015 | yield* viewer.input({ type: "takeControl" }); |
| 2016 | yield* viewer.input({ type: "reload" }); |
| 2017 | expect(contexts[1]!.page.goto).toHaveBeenCalledWith(url, expect.anything()); |
| 2018 | }), |
| 2019 | ).pipe(Effect.provide(layer)), |
| 2020 | ); |
| 2021 | |
| 2022 | it.effect("a tab opened to a file the browser cannot show reports the file to download", () => |
| 2023 | Effect.scoped( |
| 2024 | Effect.gen(function* () { |
| 2025 | const browser = yield* ServerBrowser.ServerBrowser; |
| 2026 | const manager = yield* Manager.PreviewManager; |
| 2027 | const events = yield* manager.subscribeEvents; |
| 2028 | yield* Effect.yieldNow; |
| 2029 | const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" }); |
| 2030 | const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, true)); |
| 2031 | const page = contexts[0]!.page; |
| 2032 | const pdf = "https://example.com/paper.pdf"; |
| 2033 | const request = { url: () => pdf, method: () => "GET", isNavigationRequest: () => true }; |
| 2034 | page.emit("requestfailed", { |
| 2035 | ...request, |
| 2036 | frame: () => page, |
| 2037 | failure: () => ({ errorText: "net::ERR_ABORTED" }), |
| 2038 | }); |
| 2039 | const saved = yield* Queue.unbounded<string>(); |
| 2040 | const written = Promise.withResolvers<void>(); |
| 2041 | page.emit("download", { |
| 2042 | failure: async () => null, |
| 2043 | delete: async () => { |
| 2044 | // A new navigation during cleanup must not erase the settled download status. |
| 2045 | page.emit("request", { |
| 2046 | url: () => "https://example.com/next", |
| 2047 | method: () => "GET", |
| 2048 | isNavigationRequest: () => true, |
| 2049 | frame: () => page, |
| 2050 | }); |
| 2051 | }, |
| 2052 | saveAs: (path: string) => { |
| 2053 | Queue.offerUnsafe(saved, path); |
| 2054 | return written.promise; |
| 2055 | }, |
| 2056 | suggestedFilename: () => "paper.pdf", |
| 2057 | url: () => pdf, |
| 2058 | }); |
| 2059 | const fs = yield* FileSystem.FileSystem; |
| 2060 | yield* fs.writeFileString(yield* Queue.take(saved), "%PDF"); |
| 2061 | written.resolve(); |
| 2062 | const received = []; |
| 2063 | let status; |
| 2064 | do { |
| 2065 | status = yield* PubSub.take(events); |
| 2066 | received.push(status); |
| 2067 | } while ( |
| 2068 | status.type !== "navigated" || |
| 2069 | status.snapshot.navStatus._tag !== "Loading" || |
| 2070 | status.snapshot.navStatus.url !== "https://example.com/next" |
| 2071 | ); |
| 2072 | expect(received).toContainEqual( |
| 2073 | expect.objectContaining({ |
| 2074 | type: "failed", |
| 2075 | url: pdf, |
| 2076 | download: { id: expect.any(String), fileName: "paper.pdf" }, |
| 2077 | }), |
| 2078 | ); |
| 2079 | expect((yield* Queue.clear(viewer.output)).some((item) => item._tag === "download")).toBe( |
| 2080 | false, |
| 2081 | ); |
| 2082 | }), |
| 2083 | ).pipe(Effect.provide(layer)), |
| 2084 | ); |
| 2085 | |
| 2086 | it.effect( |
| 2087 | "a late failure from a request that predates tracking leaves a newer navigation loading", |
| 2088 | () => |
| 2089 | Effect.scoped( |
| 2090 | Effect.gen(function* () { |
| 2091 | const { broker, tabId } = yield* ready; |
| 2092 | const page = contexts[0]!.page; |
| 2093 | const navigation = (url: string) => ({ |
| 2094 | url: () => url, |
| 2095 | method: () => "GET", |
| 2096 | isNavigationRequest: () => true, |
| 2097 | frame: () => page, |
| 2098 | failure: () => ({ errorText: "net::ERR_CONNECTION_REFUSED" }), |
| 2099 | }); |
| 2100 | page.emit("request", navigation("https://example.com/next")); |
| 2101 | // A popup's first request can start before the tab listens for requests. |
| 2102 | page.emit("requestfailed", navigation("https://example.com/first")); |
| 2103 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2104 | scope, |
| 2105 | tabId, |
| 2106 | operation: "status", |
| 2107 | input: {}, |
| 2108 | }); |
| 2109 | expect(status.loading).toBe(true); |
| 2110 | }), |
| 2111 | ).pipe(Effect.provide(layer)), |
| 2112 | ); |
| 2113 | |
| 2114 | it.effect("a request whose frame is not available yet is not a main navigation", () => |
| 2115 | Effect.scoped( |
| 2116 | Effect.gen(function* () { |
| 2117 | const { broker, tabId } = yield* ready; |
| 2118 | const page = contexts[0]!.page; |
| 2119 | const frameless = { |
| 2120 | url: () => "https://example.com/early", |
| 2121 | method: () => "GET", |
| 2122 | isNavigationRequest: () => true, |
| 2123 | frame: () => { |
| 2124 | throw new Error("Frame for this navigation request is not available"); |
| 2125 | }, |
| 2126 | failure: () => ({ errorText: "net::ERR_CONNECTION_REFUSED" }), |
| 2127 | }; |
| 2128 | expect(() => page.emit("request", frameless)).not.toThrow(); |
| 2129 | const statusAfterRequest = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2130 | scope, |
| 2131 | tabId, |
| 2132 | operation: "status", |
| 2133 | input: {}, |
| 2134 | }); |
| 2135 | expect(statusAfterRequest.loading).toBe(false); |
| 2136 | expect(() => page.emit("requestfailed", frameless)).not.toThrow(); |
| 2137 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2138 | scope, |
| 2139 | tabId, |
| 2140 | operation: "status", |
| 2141 | input: {}, |
| 2142 | }); |
| 2143 | expect(status.loading).toBe(false); |
| 2144 | }), |
| 2145 | ).pipe(Effect.provide(layer)), |
| 2146 | ); |
| 2147 | |
| 2148 | it.effect.each(["before", "during"] as const)( |
| 2149 | "a navigation that fails while a load reads its title keeps its failure (request %s read)", |
| 2150 | (requestTiming) => |
| 2151 | Effect.scoped( |
| 2152 | Effect.gen(function* () { |
| 2153 | const { tabId } = yield* ready; |
| 2154 | const manager = yield* Manager.PreviewManager; |
| 2155 | const events = yield* manager.subscribeEvents; |
| 2156 | const page = contexts[0]!.page; |
| 2157 | const heldTitle = Promise.withResolvers<string>(); |
| 2158 | page.title.mockImplementationOnce(() => heldTitle.promise); |
| 2159 | const failing = { |
| 2160 | url: () => "https://example.com/missing", |
| 2161 | method: () => "GET", |
| 2162 | isNavigationRequest: () => true, |
| 2163 | frame: () => page, |
| 2164 | failure: () => ({ errorText: "net::ERR_NAME_NOT_RESOLVED" }), |
| 2165 | }; |
| 2166 | if (requestTiming === "before") page.emit("request", failing); |
| 2167 | yield* Effect.promise(() => page.goto("https://example.com/first")); |
| 2168 | if (requestTiming === "during") page.emit("request", failing); |
| 2169 | page.emit("requestfailed", failing); |
| 2170 | heldTitle.resolve("Held"); |
| 2171 | // A load at the same await depth reports after the held one, so its Success marks the end. |
| 2172 | page.emit("load"); |
| 2173 | |
| 2174 | const statuses: Array<string> = []; |
| 2175 | while (!statuses.at(-1)?.startsWith("Success")) { |
| 2176 | const event = yield* PubSub.take(events); |
| 2177 | if (event.type === "failed" && event.tabId === tabId) { |
| 2178 | statuses.push(`LoadFailed ${event.url}`); |
| 2179 | } else if (event.type === "navigated" && event.tabId === tabId) { |
| 2180 | const status = event.snapshot.navStatus; |
| 2181 | if (status._tag === "Success") statuses.push(`Success ${status.title}`); |
| 2182 | else if (status._tag === "Loading") statuses.push(`Loading ${status.url}`); |
| 2183 | } |
| 2184 | } |
| 2185 | expect(statuses).toEqual([ |
| 2186 | "Loading https://example.com/missing", |
| 2187 | "LoadFailed https://example.com/missing", |
| 2188 | "Success test page", |
| 2189 | ]); |
| 2190 | }), |
| 2191 | ).pipe(Effect.provide(layer)), |
| 2192 | ); |
| 2193 | |
| 2194 | it.effect.each([ |
| 2195 | { |
| 2196 | name: "hover burst before a click", |
| 2197 | inputs: [ |
| 2198 | ...Array.from({ length: 120 }, (_, x) => ({ |
| 2199 | type: "mouse", |
| 2200 | action: "move", |
| 2201 | x, |
| 2202 | buttons: 0, |
| 2203 | button: "none", |
| 2204 | })), |
| 2205 | { type: "mouse", action: "down", x: 119, buttons: 1, button: "left" }, |
| 2206 | { type: "mouse", action: "up", x: 119, buttons: 0, button: "left" }, |
| 2207 | ], |
| 2208 | expected: [ |
| 2209 | { type: "mouseMoved", x: -1 }, |
| 2210 | { type: "mouseMoved", x: 119 }, |
| 2211 | { type: "mousePressed", x: 119 }, |
| 2212 | { type: "mouseReleased", x: 119 }, |
| 2213 | ], |
| 2214 | }, |
| 2215 | { |
| 2216 | name: "wheel burst before a click", |
| 2217 | inputs: [ |
| 2218 | ...Array.from({ length: 120 }, () => ({ |
| 2219 | type: "wheel", |
| 2220 | x: 100, |
| 2221 | y: 200, |
| 2222 | deltaX: 0, |
| 2223 | deltaY: 12, |
| 2224 | })), |
| 2225 | { type: "mouse", action: "down", x: 100, buttons: 1, button: "left" }, |
| 2226 | { type: "mouse", action: "up", x: 100, buttons: 0, button: "left" }, |
| 2227 | ], |
| 2228 | expected: [ |
| 2229 | { type: "mouseMoved", x: -1 }, |
| 2230 | { type: "mouseWheel", x: 100, y: 200, deltaX: 0, deltaY: 1440 }, |
| 2231 | { type: "mousePressed", x: 100 }, |
| 2232 | { type: "mouseReleased", x: 100 }, |
| 2233 | ], |
| 2234 | }, |
| 2235 | { |
| 2236 | name: "modifier changes and drag points", |
| 2237 | inputs: [ |
| 2238 | { type: "mouse", action: "move", x: 1, buttons: 0, button: "none" }, |
| 2239 | { type: "mouse", action: "move", x: 2, buttons: 0, button: "none", modifiers: 2 }, |
| 2240 | { type: "mouse", action: "move", x: 3, buttons: 0, button: "none", modifiers: 2 }, |
| 2241 | { type: "mouse", action: "down", x: 3, buttons: 1, button: "left" }, |
| 2242 | { type: "mouse", action: "move", x: 4, buttons: 1, button: "left" }, |
| 2243 | { type: "mouse", action: "move", x: 5, buttons: 1, button: "left" }, |
| 2244 | { type: "mouse", action: "up", x: 5, buttons: 0, button: "left" }, |
| 2245 | ], |
| 2246 | expected: [ |
| 2247 | { type: "mouseMoved", x: -1 }, |
| 2248 | { type: "mouseMoved", x: 1, modifiers: 0 }, |
| 2249 | { type: "mouseMoved", x: 3, modifiers: 2 }, |
| 2250 | { type: "mousePressed", x: 3 }, |
| 2251 | { type: "mouseMoved", x: 4 }, |
| 2252 | { type: "mouseMoved", x: 5 }, |
| 2253 | { type: "mouseReleased", x: 5 }, |
| 2254 | ], |
| 2255 | }, |
| 2256 | { |
| 2257 | name: "wheel and keyboard boundaries", |
| 2258 | inputs: [ |
| 2259 | { type: "mouse", action: "move", x: 1, buttons: 0, button: "none" }, |
| 2260 | { type: "wheel", x: 1, deltaY: 20 }, |
| 2261 | { type: "wheel", x: 1, deltaY: 30 }, |
| 2262 | { type: "mouse", action: "move", x: 2, buttons: 0, button: "none" }, |
| 2263 | { type: "key", action: "down", key: "a", code: "KeyA", text: "a" }, |
| 2264 | { type: "mouse", action: "move", x: 3, buttons: 0, button: "none" }, |
| 2265 | ], |
| 2266 | expected: [ |
| 2267 | { type: "mouseMoved", x: -1 }, |
| 2268 | { type: "mouseMoved", x: 1 }, |
| 2269 | { type: "mouseWheel", deltaY: 50 }, |
| 2270 | { type: "mouseMoved", x: 2 }, |
| 2271 | { type: "keyDown", key: "a" }, |
| 2272 | { type: "mouseMoved", x: 3 }, |
| 2273 | ], |
| 2274 | }, |
| 2275 | { |
| 2276 | name: "wheel position, modifier and direction boundaries", |
| 2277 | inputs: [ |
| 2278 | { type: "wheel", x: 1, deltaX: 5, deltaY: 10 }, |
| 2279 | { type: "wheel", x: 1, deltaX: 5, deltaY: 10 }, |
| 2280 | { type: "wheel", x: 2, deltaY: 10 }, |
| 2281 | { type: "wheel", x: 2, deltaY: 10, modifiers: 2 }, |
| 2282 | { type: "wheel", x: 2, deltaY: -10, modifiers: 2 }, |
| 2283 | { type: "wheel", x: 2, deltaY: -10, modifiers: 2 }, |
| 2284 | ], |
| 2285 | expected: [ |
| 2286 | { type: "mouseMoved", x: -1 }, |
| 2287 | { type: "mouseWheel", x: 1, deltaX: 10, deltaY: 20, modifiers: 0 }, |
| 2288 | { type: "mouseWheel", x: 2, deltaX: 0, deltaY: 10, modifiers: 0 }, |
| 2289 | { type: "mouseWheel", x: 2, deltaY: 10, modifiers: 2 }, |
| 2290 | { type: "mouseWheel", x: 2, deltaY: -20, modifiers: 2 }, |
| 2291 | ], |
| 2292 | }, |
| 2293 | { |
| 2294 | name: "text, navigation and resize boundaries", |
| 2295 | inputs: [ |
| 2296 | { type: "mouse", action: "move", x: 1, buttons: 0, button: "none" }, |
| 2297 | { type: "text", text: "typed" }, |
| 2298 | { type: "mouse", action: "move", x: 2, buttons: 0, button: "none" }, |
| 2299 | { type: "navigate", url: "http://localhost:5173/next" }, |
| 2300 | { type: "mouse", action: "move", x: 3, buttons: 0, button: "none" }, |
| 2301 | { type: "resize", width: 640, height: 480 }, |
| 2302 | { type: "mouse", action: "move", x: 4, buttons: 0, button: "none" }, |
| 2303 | ], |
| 2304 | expected: [ |
| 2305 | { type: "mouseMoved", x: -1 }, |
| 2306 | { type: "mouseMoved", x: 1 }, |
| 2307 | { text: "typed" }, |
| 2308 | { type: "mouseMoved", x: 2 }, |
| 2309 | { type: "mouseMoved", x: 3 }, |
| 2310 | { type: "mouseMoved", x: 4 }, |
| 2311 | ], |
| 2312 | }, |
| 2313 | { |
| 2314 | name: "ambiguous button fields", |
| 2315 | inputs: [ |
| 2316 | { type: "mouse", action: "move", x: 1, button: "none" }, |
| 2317 | { type: "mouse", action: "move", x: 2, button: "none" }, |
| 2318 | { type: "mouse", action: "move", x: 3, buttons: 0 }, |
| 2319 | { type: "mouse", action: "move", x: 4, buttons: 0 }, |
| 2320 | ], |
| 2321 | expected: [-1, 1, 2, 3, 4].map((x) => ({ type: "mouseMoved", x })), |
| 2322 | }, |
| 2323 | ])("orders streamed input correctly for $name", (testCase) => |
| 2324 | Effect.scoped( |
| 2325 | Effect.gen(function* () { |
| 2326 | const { browser, tabId } = yield* ready; |
| 2327 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2328 | yield* viewer.input({ type: "takeControl" }); |
| 2329 | const session = contexts[0]!.sessions.at(-1)!; |
| 2330 | const send = session.send.getMockImplementation()!; |
| 2331 | const started = Promise.withResolvers<void>(); |
| 2332 | const finish = Promise.withResolvers<void>(); |
| 2333 | yield* Effect.addFinalizer(() => Effect.sync(() => finish.resolve())); |
| 2334 | session.send.mockClear(); |
| 2335 | session.send.mockImplementationOnce(async (method, input) => { |
| 2336 | started.resolve(); |
| 2337 | await finish.promise; |
| 2338 | return send(method, input); |
| 2339 | }); |
| 2340 | const running = yield* viewer |
| 2341 | .input({ type: "mouse", action: "move", x: -1, button: "none", buttons: 0 }) |
| 2342 | .pipe(Effect.forkScoped({ startImmediately: true })); |
| 2343 | yield* Effect.promise(() => started.promise); |
| 2344 | const waiting = yield* Effect.forEach(testCase.inputs, (input) => |
| 2345 | viewer.input(input).pipe(Effect.forkScoped({ startImmediately: true })), |
| 2346 | ); |
| 2347 | finish.resolve(); |
| 2348 | yield* Effect.forEach([running, ...waiting], Fiber.join); |
| 2349 | const dispatched = session.send.mock.calls.flatMap(([method, input]) => |
| 2350 | method.startsWith("Input.") ? [input] : [], |
| 2351 | ); |
| 2352 | expect(dispatched).toHaveLength(testCase.expected.length); |
| 2353 | expect(dispatched).toMatchObject(testCase.expected); |
| 2354 | }), |
| 2355 | ).pipe(Effect.provide(layer)), |
| 2356 | ); |
| 2357 | |
| 2358 | it.effect("only the controlling viewer's copy and cut keys reach its clipboard", () => |
| 2359 | Effect.scoped( |
| 2360 | Effect.gen(function* () { |
| 2361 | const { browser, tabId } = yield* ready; |
| 2362 | const watcher = yield* browser.attachViewer(viewerInput(tabId, false)); |
| 2363 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2364 | yield* viewer.input({ type: "takeControl" }); |
| 2365 | const clipboard = (queue: typeof viewer.output) => |
| 2366 | Queue.clear(queue).pipe( |
| 2367 | Effect.map((items) => items.filter((item) => item._tag === "clipboard")), |
| 2368 | ); |
| 2369 | pageCopy = "unprompted"; |
| 2370 | yield* viewer.input({ type: "mouse", action: "move", x: 10, y: 10 }); |
| 2371 | yield* viewer.input({ type: "wheel", x: 10, y: 10, deltaY: 40 }); |
| 2372 | yield* viewer.input({ type: "key", action: "down", key: "v", code: "KeyV", modifiers: 4 }); |
| 2373 | yield* viewer.input({ type: "unknown" }); |
| 2374 | expect(yield* clipboard(viewer.output)).toEqual([]); |
| 2375 | keyCopy = "copied"; |
| 2376 | yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 }); |
| 2377 | const cdp = contexts[0]!.sessions.at(-1)!; |
| 2378 | expect(cdp.send).toHaveBeenCalledWith( |
| 2379 | "Input.dispatchKeyEvent", |
| 2380 | expect.objectContaining({ key: "c", commands: ["copy"] }), |
| 2381 | ); |
| 2382 | expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "copied" }]); |
| 2383 | keyCopy = "cut"; |
| 2384 | yield* viewer.input({ type: "key", action: "down", key: "x", code: "KeyX", modifiers: 2 }); |
| 2385 | expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "cut" }]); |
| 2386 | pageCopy = "left over"; |
| 2387 | keyCopy = ""; |
| 2388 | yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 }); |
| 2389 | expect(yield* clipboard(viewer.output)).toEqual([]); |
| 2390 | expect(yield* clipboard(watcher.output)).toEqual([]); |
| 2391 | }), |
| 2392 | ).pipe(Effect.provide(layer)), |
| 2393 | ); |
| 2394 | |
| 2395 | it.effect("a busy embedded frame does not hold a copy key back from the page", () => |
| 2396 | Effect.scoped( |
| 2397 | Effect.gen(function* () { |
| 2398 | const { browser, tabId } = yield* ready; |
| 2399 | const context = contexts[0]!; |
| 2400 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2401 | yield* viewer.input({ type: "takeControl" }); |
| 2402 | const pageSession = context.sessions.at(-1)!; |
| 2403 | const frame = makeFrame(); |
| 2404 | context.page.emit("framenavigated", frame); |
| 2405 | yield* Effect.promise(() => frame.recording.promise); |
| 2406 | |
| 2407 | // The frame answers its copy read only once the page has the key and the |
| 2408 | // input after it, like a frame busy for longer than the user waits. |
| 2409 | const keyReached = Promise.withResolvers<void>(); |
| 2410 | const pageSend = pageSession.send.getMockImplementation()!; |
| 2411 | pageSession.send.mockImplementation(async (method, input) => { |
| 2412 | if (method === "Input.dispatchKeyEvent" && (input as { type?: string }).type === "keyUp") |
| 2413 | keyReached.resolve(); |
| 2414 | return pageSend(method, input); |
| 2415 | }); |
| 2416 | const frameSession = context.sessions.at(-1)!; |
| 2417 | const frameSend = frameSession.send.getMockImplementation()!; |
| 2418 | frameSession.send.mockImplementation(async (method, input) => { |
| 2419 | if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) { |
| 2420 | await keyReached.promise; |
| 2421 | } |
| 2422 | return frameSend(method, input); |
| 2423 | }); |
| 2424 | |
| 2425 | keyCopy = "copied"; |
| 2426 | const copying = yield* viewer |
| 2427 | .input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 }) |
| 2428 | .pipe(Effect.forkScoped({ startImmediately: true })); |
| 2429 | yield* viewer.input({ type: "key", action: "up", key: "c", code: "KeyC", modifiers: 4 }); |
| 2430 | yield* Fiber.join(copying); |
| 2431 | expect(pageSession.send).toHaveBeenCalledWith( |
| 2432 | "Input.dispatchKeyEvent", |
| 2433 | expect.objectContaining({ key: "c", commands: ["copy"] }), |
| 2434 | ); |
| 2435 | const clipboard = yield* Queue.clear(viewer.output); |
| 2436 | expect(clipboard.filter((item) => item._tag === "clipboard")).toEqual([ |
| 2437 | { _tag: "clipboard", text: "copied" }, |
| 2438 | ]); |
| 2439 | }), |
| 2440 | ).pipe(Effect.provide(layer)), |
| 2441 | ); |
| 2442 | |
| 2443 | it.effect.each([false, true])( |
| 2444 | "a page download is saved, offered to the controller, and listed for the agent (delete fails: %s)", |
| 2445 | (deleteFails) => |
| 2446 | Effect.scoped( |
| 2447 | Effect.gen(function* () { |
| 2448 | const { browser, broker, tabId } = yield* ready; |
| 2449 | const page = contexts[0]!.page; |
| 2450 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2451 | yield* viewer.input({ type: "takeControl" }); |
| 2452 | yield* Queue.clear(viewer.output); |
| 2453 | const fs = yield* FileSystem.FileSystem; |
| 2454 | const original = `${yield* fs.makeTempDirectoryScoped()}/chromium-download`; |
| 2455 | yield* fs.writeFileString(original, "a,b"); |
| 2456 | const released = Promise.withResolvers<void>(); |
| 2457 | page.emit("download", { |
| 2458 | failure: async () => null, |
| 2459 | delete: async () => { |
| 2460 | try { |
| 2461 | if (deleteFails) throw new Error("context closed"); |
| 2462 | await NodeFSP.rm(original); |
| 2463 | } finally { |
| 2464 | released.resolve(); |
| 2465 | } |
| 2466 | }, |
| 2467 | saveAs: (path: string) => NodeFSP.copyFile(original, path), |
| 2468 | suggestedFilename: () => "report.csv", |
| 2469 | url: () => 'data:text/csv;charset="a,b",a b\'c', |
| 2470 | }); |
| 2471 | let offered = yield* Queue.take(viewer.output); |
| 2472 | while (offered._tag !== "download") offered = yield* Queue.take(viewer.output); |
| 2473 | expect(offered).toMatchObject({ _tag: "download", fileName: "report.csv", sizeBytes: 3 }); |
| 2474 | yield* Effect.promise(() => released.promise); |
| 2475 | expect(yield* fs.exists(original)).toBe(deleteFails); |
| 2476 | const file = yield* browser.openDownload({ |
| 2477 | threadId: scope.thread.threadId, |
| 2478 | tabId, |
| 2479 | downloadId: offered.id, |
| 2480 | }); |
| 2481 | expect(Option.isSome(file) && file.value.fileName).toBe("report.csv"); |
| 2482 | expect(yield* fs.readFileString(Option.getOrThrow(file).path)).toBe("a,b"); |
| 2483 | if ((yield* HostProcess.Platform) !== "win32") { |
| 2484 | expect((yield* fs.stat(Option.getOrThrow(file).path)).mode & 0o777).toBe(0o600); |
| 2485 | } |
| 2486 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2487 | scope, |
| 2488 | tabId, |
| 2489 | operation: "status", |
| 2490 | input: {}, |
| 2491 | }); |
| 2492 | expect(status.downloads).toEqual([ |
| 2493 | expect.objectContaining({ |
| 2494 | fileName: "report.csv", |
| 2495 | sizeBytes: 3, |
| 2496 | url: "data:text/csv,…", |
| 2497 | }), |
| 2498 | ]); |
| 2499 | expect( |
| 2500 | Option.isNone( |
| 2501 | yield* browser.openDownload({ |
| 2502 | threadId: scope.thread.threadId, |
| 2503 | tabId, |
| 2504 | downloadId: "guess", |
| 2505 | }), |
| 2506 | ), |
| 2507 | ).toBe(true); |
| 2508 | if ((yield* HostProcess.Platform) !== "win32") { |
| 2509 | const folder = (yield* Path.Path).dirname(Option.getOrThrow(file).path); |
| 2510 | yield* fs.chmod(folder, 0o755); |
| 2511 | page.emit("download", { |
| 2512 | failure: async () => null, |
| 2513 | delete: async () => {}, |
| 2514 | saveAs: (path: string) => NodeFSP.writeFile(path, "c"), |
| 2515 | suggestedFilename: () => "again.csv", |
| 2516 | url: () => "https://example.test/again.csv", |
| 2517 | }); |
| 2518 | let again = yield* Queue.take(viewer.output); |
| 2519 | while (again._tag !== "download") again = yield* Queue.take(viewer.output); |
| 2520 | expect((yield* fs.stat(folder)).mode & 0o777).toBe(0o700); |
| 2521 | } |
| 2522 | }), |
| 2523 | ).pipe(Effect.provide(layer)), |
| 2524 | ); |
| 2525 | |
| 2526 | it.effect("a tab showing a data: page reports its URL without the content", () => |
| 2527 | Effect.scoped( |
| 2528 | Effect.gen(function* () { |
| 2529 | const { broker, tabId } = yield* ready; |
| 2530 | const sibling = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2531 | scope: asSession("agent-b"), |
| 2532 | operation: "open", |
| 2533 | input: { reuseExistingTab: false, show: false }, |
| 2534 | }); |
| 2535 | yield* Effect.promise(() => contexts[1]!.page.goto("data:text/html,<p>SIBLING-SECRET</p>")); |
| 2536 | const manager = yield* Manager.PreviewManager; |
| 2537 | const events = yield* manager.subscribeEvents; |
| 2538 | yield* Effect.promise(() => contexts[0]!.page.goto("data:text/html,<p>SECRET-KEY</p>")); |
| 2539 | let event = yield* PubSub.take(events); |
| 2540 | while ( |
| 2541 | event.type !== "navigated" || |
| 2542 | event.tabId !== tabId || |
| 2543 | event.snapshot.navStatus._tag !== "Success" |
| 2544 | ) { |
| 2545 | event = yield* PubSub.take(events); |
| 2546 | } |
| 2547 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2548 | scope, |
| 2549 | tabId, |
| 2550 | operation: "status", |
| 2551 | input: {}, |
| 2552 | }); |
| 2553 | expect(event.snapshot.navStatus).toMatchObject({ url: "data:text/html,…" }); |
| 2554 | expect(status.url).toBe("data:text/html,…"); |
| 2555 | expect(status.tabs?.find((entry) => entry.tabId === tabId)?.url).toBe("data:text/html,…"); |
| 2556 | expect(status.tabs?.find((entry) => entry.tabId === sibling.tabId)?.url).toBe( |
| 2557 | "data:text/html,…", |
| 2558 | ); |
| 2559 | expect(JSON.stringify([event, status])).not.toContain("SECRET-KEY"); |
| 2560 | expect(JSON.stringify([event, status])).not.toContain("SIBLING-SECRET"); |
| 2561 | }), |
| 2562 | ).pipe(Effect.provide(layer)), |
| 2563 | ); |
| 2564 | |
| 2565 | it.effect.each(["save failed", "oversized"])( |
| 2566 | "a rejected download releases the original and keeps no saved copy (%s)", |
| 2567 | (outcome) => |
| 2568 | Effect.scoped( |
| 2569 | Effect.gen(function* () { |
| 2570 | const { broker, tabId } = yield* ready; |
| 2571 | const fs = yield* FileSystem.FileSystem; |
| 2572 | const original = `${yield* fs.makeTempDirectoryScoped()}/chromium-download`; |
| 2573 | yield* fs.writeFileString(original, "a,b"); |
| 2574 | let savedPath: string | undefined; |
| 2575 | const released = Promise.withResolvers<void>(); |
| 2576 | contexts[0]!.page.emit("download", { |
| 2577 | failure: async () => null, |
| 2578 | delete: async () => { |
| 2579 | await NodeFSP.rm(original); |
| 2580 | released.resolve(); |
| 2581 | }, |
| 2582 | saveAs: async (path: string) => { |
| 2583 | savedPath = path; |
| 2584 | await NodeFSP.copyFile(original, path); |
| 2585 | if (outcome === "save failed") throw new Error("save interrupted"); |
| 2586 | // A sparse file exercises the size limit without writing a GiB of data. |
| 2587 | await NodeFSP.truncate(path, 1024 ** 3 + 1); |
| 2588 | }, |
| 2589 | suggestedFilename: () => "report.csv", |
| 2590 | url: () => "blob:http://localhost:5173/1", |
| 2591 | }); |
| 2592 | yield* Effect.promise(() => released.promise); |
| 2593 | expect(yield* fs.exists(original)).toBe(false); |
| 2594 | if (savedPath !== undefined) expect(yield* fs.exists(savedPath)).toBe(false); |
| 2595 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2596 | scope, |
| 2597 | tabId, |
| 2598 | operation: "status", |
| 2599 | input: {}, |
| 2600 | }); |
| 2601 | expect(status.downloads).toEqual([]); |
| 2602 | }), |
| 2603 | ).pipe(Effect.provide(layer)), |
| 2604 | ); |
| 2605 | |
| 2606 | it.effect("a restarted server removes the previous run's downloads and keeps its profiles", () => |
| 2607 | Effect.scoped( |
| 2608 | Effect.gen(function* () { |
| 2609 | const { stateDir } = yield* ServerConfig.ServerConfig; |
| 2610 | const fs = yield* FileSystem.FileSystem; |
| 2611 | const path = yield* Path.Path; |
| 2612 | const previousTab = path.join(stateDir, "server-browser", "downloads", "previous-tab"); |
| 2613 | const profile = path.join(stateDir, "server-browser", "profiles", "default"); |
| 2614 | yield* fs.makeDirectory(previousTab, { recursive: true }); |
| 2615 | yield* fs.makeDirectory(profile, { recursive: true }); |
| 2616 | yield* fs.writeFileString(path.join(previousTab, "report.csv"), "a,b"); |
| 2617 | yield* fs.writeFileString(path.join(profile, "Preferences"), "{}"); |
| 2618 | |
| 2619 | yield* Layer.build(ServerBrowser.layer); |
| 2620 | |
| 2621 | expect(yield* fs.exists(previousTab)).toBe(false); |
| 2622 | expect(yield* fs.readFileString(path.join(profile, "Preferences"))).toBe("{}"); |
| 2623 | }), |
| 2624 | ).pipe(Effect.provide(dependencies)), |
| 2625 | ); |
| 2626 | |
| 2627 | it.effect("a page's file picker goes to the controller and takes its uploaded files", () => |
| 2628 | Effect.scoped( |
| 2629 | Effect.gen(function* () { |
| 2630 | const { browser, tabId } = yield* ready; |
| 2631 | const page = contexts[0]!.page; |
| 2632 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2633 | yield* viewer.input({ type: "takeControl" }); |
| 2634 | const setFiles = vi.fn(async (_files: unknown) => {}); |
| 2635 | page.emit("filechooser", { |
| 2636 | isMultiple: () => false, |
| 2637 | element: () => fileChooserElement(".csv"), |
| 2638 | setFiles, |
| 2639 | }); |
| 2640 | let offered = yield* Queue.take(viewer.output); |
| 2641 | while (offered._tag !== "fileChooser") offered = yield* Queue.take(viewer.output); |
| 2642 | expect(offered).toMatchObject({ multiple: false, accept: ".csv" }); |
| 2643 | const file = (name: string) => ({ name, mimeType: "text/csv", buffer: Buffer.from(name) }); |
| 2644 | const answer = (chooserId: string) => |
| 2645 | browser.answerFileChooser({ |
| 2646 | threadId: scope.thread.threadId, |
| 2647 | tabId, |
| 2648 | chooserId, |
| 2649 | files: [file("a.csv"), file("b.csv")], |
| 2650 | }); |
| 2651 | expect(yield* answer("other")).toBe(false); |
| 2652 | expect(yield* answer(offered.id)).toBe(true); |
| 2653 | expect(setFiles).toHaveBeenCalledExactlyOnceWith([file("a.csv")]); |
| 2654 | let closed = yield* Queue.take(viewer.output); |
| 2655 | while (closed._tag !== "fileChooserClosed") closed = yield* Queue.take(viewer.output); |
| 2656 | expect(closed.id).toBe(offered.id); |
| 2657 | expect(yield* answer(offered.id)).toBe(false); |
| 2658 | }), |
| 2659 | ).pipe(Effect.provide(layer)), |
| 2660 | ); |
| 2661 | |
| 2662 | it.effect("overlapping file pickers keep the newer offer answerable", () => |
| 2663 | Effect.scoped( |
| 2664 | Effect.gen(function* () { |
| 2665 | const { browser, tabId } = yield* ready; |
| 2666 | const page = contexts[0]!.page; |
| 2667 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2668 | yield* viewer.input({ type: "takeControl" }); |
| 2669 | const accept = Promise.withResolvers<string | null>(); |
| 2670 | const firstFiles = vi.fn(async (_files: unknown) => {}); |
| 2671 | const secondFiles = vi.fn(async (_files: unknown) => {}); |
| 2672 | page.emit("filechooser", { |
| 2673 | isMultiple: () => false, |
| 2674 | element: () => ({ ...fileChooserElement(""), getAttribute: () => accept.promise }), |
| 2675 | setFiles: firstFiles, |
| 2676 | }); |
| 2677 | page.emit("filechooser", { |
| 2678 | isMultiple: () => false, |
| 2679 | element: () => fileChooserElement(".csv"), |
| 2680 | setFiles: secondFiles, |
| 2681 | }); |
| 2682 | accept.resolve(".txt"); |
| 2683 | let first = yield* Queue.take(viewer.output); |
| 2684 | while (first._tag !== "fileChooser") first = yield* Queue.take(viewer.output); |
| 2685 | let second = yield* Queue.take(viewer.output); |
| 2686 | while (second._tag !== "fileChooser") second = yield* Queue.take(viewer.output); |
| 2687 | expect(second.accept).toBe(".csv"); |
| 2688 | expect( |
| 2689 | yield* browser.answerFileChooser({ |
| 2690 | threadId: scope.thread.threadId, |
| 2691 | tabId, |
| 2692 | chooserId: second.id, |
| 2693 | files: [{ name: "a.csv", mimeType: "text/csv", buffer: Buffer.from("a") }], |
| 2694 | }), |
| 2695 | ).toBe(true); |
| 2696 | expect(firstFiles).not.toHaveBeenCalled(); |
| 2697 | expect(secondFiles).toHaveBeenCalledOnce(); |
| 2698 | }), |
| 2699 | ).pipe(Effect.provide(layer)), |
| 2700 | ); |
| 2701 | |
| 2702 | it.effect("a detached file picker stays open across same-document navigation", () => |
| 2703 | Effect.scoped( |
| 2704 | Effect.gen(function* () { |
| 2705 | const { browser, tabId } = yield* ready; |
| 2706 | const page = contexts[0]!.page; |
| 2707 | const pageDocument = {}; |
| 2708 | vi.stubGlobal("document", pageDocument); |
| 2709 | yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllGlobals())); |
| 2710 | const detachedInput = { isConnected: false, ownerDocument: pageDocument }; |
| 2711 | const navigationProbe = Promise.withResolvers<boolean>(); |
| 2712 | const navigationProbeStarted = Promise.withResolvers<void>(); |
| 2713 | const navigationProbeFinished = Promise.withResolvers<void>(); |
| 2714 | let probeCount = 0; |
| 2715 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2716 | yield* viewer.input({ type: "takeControl" }); |
| 2717 | page.emit("filechooser", { |
| 2718 | isMultiple: () => false, |
| 2719 | element: () => ({ |
| 2720 | getAttribute: async () => "", |
| 2721 | evaluate: (probe: (element: typeof detachedInput) => boolean) => { |
| 2722 | probeCount++; |
| 2723 | if (probeCount === 1) return Promise.resolve(probe(detachedInput)); |
| 2724 | navigationProbeStarted.resolve(); |
| 2725 | return navigationProbe.promise.then((current) => { |
| 2726 | const result = probe(detachedInput); |
| 2727 | navigationProbeFinished.resolve(); |
| 2728 | return current && result; |
| 2729 | }); |
| 2730 | }, |
| 2731 | }), |
| 2732 | setFiles: vi.fn(async (_files: unknown) => {}), |
| 2733 | }); |
| 2734 | let offered = yield* Queue.take(viewer.output); |
| 2735 | while (offered._tag !== "fileChooser") offered = yield* Queue.take(viewer.output); |
| 2736 | |
| 2737 | page.emit("framenavigated", page); |
| 2738 | yield* Effect.promise(() => navigationProbeStarted.promise); |
| 2739 | navigationProbe.resolve(true); |
| 2740 | yield* Effect.promise(() => navigationProbeFinished.promise); |
| 2741 | yield* viewer.input({ type: "releaseControl" }); |
| 2742 | let closedAfterNavigation = false; |
| 2743 | let control = yield* Queue.take(viewer.output); |
| 2744 | while (control._tag !== "control" || control.controller === "you") { |
| 2745 | if (control._tag === "fileChooserClosed") closedAfterNavigation = true; |
| 2746 | control = yield* Queue.take(viewer.output); |
| 2747 | } |
| 2748 | expect(closedAfterNavigation).toBe(false); |
| 2749 | yield* viewer.input({ type: "takeControl" }); |
| 2750 | let restoredControl = yield* Queue.take(viewer.output); |
| 2751 | while (restoredControl._tag !== "control" || restoredControl.controller !== "you") { |
| 2752 | restoredControl = yield* Queue.take(viewer.output); |
| 2753 | } |
| 2754 | |
| 2755 | expect( |
| 2756 | yield* browser.answerFileChooser({ |
| 2757 | threadId: scope.thread.threadId, |
| 2758 | tabId, |
| 2759 | chooserId: offered.id, |
| 2760 | files: [{ name: "a.csv", mimeType: "text/csv", buffer: Buffer.from("a") }], |
| 2761 | }), |
| 2762 | ).toBe(true); |
| 2763 | }), |
| 2764 | ).pipe(Effect.provide(layer)), |
| 2765 | ); |
| 2766 | |
| 2767 | it.effect.each(["main", "iframe"])( |
| 2768 | "a file picker closes at %s document commit before DOMContentLoaded", |
| 2769 | (frame) => |
| 2770 | Effect.scoped( |
| 2771 | Effect.gen(function* () { |
| 2772 | const { browser, tabId } = yield* ready; |
| 2773 | const page = contexts[0]!.page; |
| 2774 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2775 | yield* viewer.input({ type: "takeControl" }); |
| 2776 | const setFiles = vi.fn(async (_files: unknown) => {}); |
| 2777 | const probeStarted = Promise.withResolvers<void>(); |
| 2778 | const probeSettled = Promise.withResolvers<void>(); |
| 2779 | let probeCount = 0; |
| 2780 | page.emit("filechooser", { |
| 2781 | isMultiple: () => false, |
| 2782 | element: () => ({ |
| 2783 | getAttribute: async () => "", |
| 2784 | evaluate: () => { |
| 2785 | probeCount++; |
| 2786 | if (probeCount === 1) return Promise.resolve(true); |
| 2787 | probeStarted.resolve(); |
| 2788 | return Promise.reject(new Error("Execution context was destroyed")).finally(() => |
| 2789 | probeSettled.resolve(), |
| 2790 | ); |
| 2791 | }, |
| 2792 | }), |
| 2793 | setFiles, |
| 2794 | }); |
| 2795 | let offered = yield* Queue.take(viewer.output); |
| 2796 | while (offered._tag !== "fileChooser") offered = yield* Queue.take(viewer.output); |
| 2797 | |
| 2798 | page.emit("framenavigated", frame === "main" ? page : makeFrame()); |
| 2799 | yield* Effect.promise(() => probeStarted.promise); |
| 2800 | yield* Effect.promise(() => probeSettled.promise); |
| 2801 | let closed = yield* Queue.take(viewer.output); |
| 2802 | while (closed._tag !== "fileChooserClosed") closed = yield* Queue.take(viewer.output); |
| 2803 | expect(closed.id).toBe(offered.id); |
| 2804 | expect( |
| 2805 | yield* browser.answerFileChooser({ |
| 2806 | threadId: scope.thread.threadId, |
| 2807 | tabId, |
| 2808 | chooserId: offered.id, |
| 2809 | files: [{ name: "a.csv", mimeType: "text/csv", buffer: Buffer.from("a") }], |
| 2810 | }), |
| 2811 | ).toBe(false); |
| 2812 | expect(setFiles).not.toHaveBeenCalled(); |
| 2813 | }), |
| 2814 | ).pipe(Effect.provide(layer)), |
| 2815 | ); |
| 2816 | |
| 2817 | it.effect("a file picker closes when its page is replaced while control changes hands", () => |
| 2818 | Effect.scoped( |
| 2819 | Effect.gen(function* () { |
| 2820 | const { broker, browser, tabId } = yield* ready; |
| 2821 | const page = contexts[0]!.page; |
| 2822 | const first = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2823 | yield* first.input({ type: "takeControl" }); |
| 2824 | const current = Promise.withResolvers<boolean>(); |
| 2825 | const probeStarted = Promise.withResolvers<void>(); |
| 2826 | let probeCount = 0; |
| 2827 | page.emit("filechooser", { |
| 2828 | isMultiple: () => false, |
| 2829 | element: () => ({ |
| 2830 | getAttribute: async () => "", |
| 2831 | evaluate: () => { |
| 2832 | probeCount++; |
| 2833 | if (probeCount === 1) return Promise.resolve(true); |
| 2834 | probeStarted.resolve(); |
| 2835 | return current.promise; |
| 2836 | }, |
| 2837 | }), |
| 2838 | setFiles: vi.fn(async (_files: unknown) => {}), |
| 2839 | }); |
| 2840 | let offered = yield* Queue.take(first.output); |
| 2841 | while (offered._tag !== "fileChooser") offered = yield* Queue.take(first.output); |
| 2842 | |
| 2843 | page.emit("framenavigated", page); |
| 2844 | yield* Effect.promise(() => probeStarted.promise); |
| 2845 | const second = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2846 | yield* first.input({ type: "releaseControl" }); |
| 2847 | yield* second.input({ type: "takeControl" }); |
| 2848 | let reoffered = yield* Queue.take(second.output); |
| 2849 | while (reoffered._tag !== "fileChooser") reoffered = yield* Queue.take(second.output); |
| 2850 | current.resolve(false); |
| 2851 | let closed = yield* Queue.take(second.output); |
| 2852 | while (closed._tag !== "fileChooserClosed") closed = yield* Queue.take(second.output); |
| 2853 | expect(closed.id).toBe(reoffered.id); |
| 2854 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2855 | scope, |
| 2856 | tabId, |
| 2857 | operation: "status", |
| 2858 | input: {}, |
| 2859 | }); |
| 2860 | expect(status.fileChooser).toBeNull(); |
| 2861 | }), |
| 2862 | ).pipe(Effect.provide(layer)), |
| 2863 | ); |
| 2864 | |
| 2865 | it.effect("a file picker is not offered after its document changes while reading accept", () => |
| 2866 | Effect.scoped( |
| 2867 | Effect.gen(function* () { |
| 2868 | const { broker, browser, tabId } = yield* ready; |
| 2869 | const page = contexts[0]!.page; |
| 2870 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2871 | yield* viewer.input({ type: "takeControl" }); |
| 2872 | const accept = Promise.withResolvers<string | null>(); |
| 2873 | const acceptRead = Promise.withResolvers<void>(); |
| 2874 | const current = Promise.withResolvers<boolean>(); |
| 2875 | const probeStarted = Promise.withResolvers<void>(); |
| 2876 | page.emit("filechooser", { |
| 2877 | isMultiple: () => false, |
| 2878 | element: () => ({ |
| 2879 | getAttribute: () => { |
| 2880 | acceptRead.resolve(); |
| 2881 | return accept.promise; |
| 2882 | }, |
| 2883 | evaluate: () => { |
| 2884 | probeStarted.resolve(); |
| 2885 | return current.promise; |
| 2886 | }, |
| 2887 | }), |
| 2888 | setFiles: vi.fn(async (_files: unknown) => {}), |
| 2889 | }); |
| 2890 | |
| 2891 | yield* Effect.promise(() => acceptRead.promise); |
| 2892 | page.emit("framenavigated", page); |
| 2893 | accept.resolve(""); |
| 2894 | yield* Effect.promise(() => accept.promise); |
| 2895 | yield* Effect.promise(() => probeStarted.promise); |
| 2896 | current.resolve(false); |
| 2897 | yield* Effect.promise(() => current.promise); |
| 2898 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 2899 | scope, |
| 2900 | tabId, |
| 2901 | operation: "status", |
| 2902 | input: {}, |
| 2903 | }); |
| 2904 | expect(status.fileChooser).toBeNull(); |
| 2905 | }), |
| 2906 | ).pipe(Effect.provide(layer)), |
| 2907 | ); |
| 2908 | |
| 2909 | it.effect("only the current controller can answer a file picker", () => |
| 2910 | Effect.scoped( |
| 2911 | Effect.gen(function* () { |
| 2912 | const { browser, tabId } = yield* ready; |
| 2913 | const first = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2914 | yield* first.input({ type: "takeControl" }); |
| 2915 | const setFiles = vi.fn(async (_files: unknown) => {}); |
| 2916 | contexts[0]!.page.emit("filechooser", { |
| 2917 | isMultiple: () => false, |
| 2918 | element: () => fileChooserElement(""), |
| 2919 | setFiles, |
| 2920 | }); |
| 2921 | let offered = yield* Queue.take(first.output); |
| 2922 | while (offered._tag !== "fileChooser") offered = yield* Queue.take(first.output); |
| 2923 | const second = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 2924 | yield* first.input({ type: "releaseControl" }); |
| 2925 | yield* second.input({ type: "takeControl" }); |
| 2926 | const answered = yield* browser.answerFileChooser({ |
| 2927 | threadId: scope.thread.threadId, |
| 2928 | tabId, |
| 2929 | chooserId: offered.id, |
| 2930 | files: [{ name: "a.txt", mimeType: "text/plain", buffer: Buffer.from("a") }], |
| 2931 | }); |
| 2932 | expect(answered).toBe(false); |
| 2933 | expect(setFiles).not.toHaveBeenCalled(); |
| 2934 | }), |
| 2935 | ).pipe(Effect.provide(layer)), |
| 2936 | ); |
| 2937 | |
| 2938 | it.effect( |
| 2939 | "desktop viewers get the page's CSS size and keep the last one a read cannot measure", |
| 2940 | () => |
| 2941 | Effect.scoped( |
| 2942 | Effect.gen(function* () { |
| 2943 | // Each page size read waits here for its answer. |
| 2944 | const reads = yield* Queue.unbounded<PromiseWithResolvers<Record<string, unknown>>>(); |
| 2945 | const deferReads = () => { |
| 2946 | desktopSizeAnswer = () => { |
| 2947 | const read = Promise.withResolvers<Record<string, unknown>>(); |
| 2948 | Queue.offerUnsafe(reads, read); |
| 2949 | return read.promise; |
| 2950 | }; |
| 2951 | }; |
| 2952 | deferReads(); |
| 2953 | const { viewer, cdp, context } = yield* openDesktopViewer; |
| 2954 | const answer = (width: number, height: number) => ({ |
| 2955 | result: { value: { width, height } }, |
| 2956 | }); |
| 2957 | const resized = () => cdp.emitAsync("Page.frameResized"); |
| 2958 | // The read on attach never answers and gives up with no size to send. |
| 2959 | const blocked = yield* Queue.take(reads); |
| 2960 | yield* TestClock.adjust("1 second"); |
| 2961 | // The next page load measures again. |
| 2962 | desktopSizeAnswer = null; |
| 2963 | yield* Effect.promise(() => cdp.emitAsync("Page.loadEventFired")); |
| 2964 | expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual(["1920x1080"]); |
| 2965 | // While a dialog is open nothing reads. The host closing it clears it, and since |
| 2966 | // closing resizes nothing, the close itself remeasures. |
| 2967 | deferReads(); |
| 2968 | context.page.emit("dialog", { |
| 2969 | type: () => "alert", |
| 2970 | message: () => "", |
| 2971 | defaultValue: () => "", |
| 2972 | }); |
| 2973 | yield* Effect.promise(resized); |
| 2974 | expect(yield* Queue.size(reads)).toBe(0); |
| 2975 | desktopSizeAnswer = null; |
| 2976 | yield* Effect.promise(() => cdp.emitAsync("Page.javascriptDialogClosed")); |
| 2977 | expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ |
| 2978 | "1920x1080", |
| 2979 | "1920x1080", |
| 2980 | ]); |
| 2981 | // The late answer, a read a navigation breaks and a hidden webview keep the last size. |
| 2982 | blocked.resolve(answer(100, 100)); |
| 2983 | deferReads(); |
| 2984 | const navigated = resized(); |
| 2985 | (yield* Queue.take(reads)).reject(new Error("Cannot find context with specified id")); |
| 2986 | yield* Effect.promise(() => navigated); |
| 2987 | const hidden = resized(); |
| 2988 | (yield* Queue.take(reads)).resolve(answer(0, 0)); |
| 2989 | yield* Effect.promise(() => hidden); |
| 2990 | expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ |
| 2991 | "1920x1080", |
| 2992 | "1920x1080", |
| 2993 | ]); |
| 2994 | // Resizes during a read share one more read, so the newest size arrives last. |
| 2995 | const first = resized(); |
| 2996 | const firstRead = yield* Queue.take(reads); |
| 2997 | const burst = Promise.all([resized(), resized()]); |
| 2998 | firstRead.resolve(answer(800, 500)); |
| 2999 | (yield* Queue.take(reads)).resolve(answer(1000, 600)); |
| 3000 | expect(yield* Queue.size(reads)).toBe(0); |
| 3001 | yield* Effect.promise(() => Promise.all([first, burst])); |
| 3002 | expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ |
| 3003 | "800x500", |
| 3004 | "1000x600", |
| 3005 | "1000x600", |
| 3006 | ]); |
| 3007 | }), |
| 3008 | ).pipe(Effect.provide(layer)), |
| 3009 | ); |
| 3010 | |
| 3011 | it.effect("a desktop tab reports the size the desktop draws after a resize", () => |
| 3012 | Effect.scoped( |
| 3013 | Effect.gen(function* () { |
| 3014 | const { broker } = yield* ready; |
| 3015 | const manager = yield* Manager.PreviewManager; |
| 3016 | const failReads = () => Promise.reject(new Error("Cannot find context with specified id")); |
| 3017 | desktopSizeAnswer = failReads; |
| 3018 | desktopRendersNext = true; |
| 3019 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3020 | scope, |
| 3021 | operation: "open", |
| 3022 | input: { reuseExistingTab: false, show: false }, |
| 3023 | }); |
| 3024 | const tabId = PreviewTabId.make(opened.tabId!); |
| 3025 | const { context } = desktopConnections.at(-1)!; |
| 3026 | const cdp = context.sessions[0]!; |
| 3027 | const events = yield* manager.subscribeEvents; |
| 3028 | const status = broker |
| 3029 | .invoke<PreviewAutomationStatus>({ scope, tabId, operation: "status", input: {} }) |
| 3030 | .pipe(Effect.map((result) => result.viewport)); |
| 3031 | // The desktop draws the new size once the session update reaches it. |
| 3032 | const resize = (input: Record<string, unknown>, width: number, height: number) => |
| 3033 | Effect.gen(function* () { |
| 3034 | const result = yield* broker |
| 3035 | .invoke<PreviewAutomationResizeResult>({ scope, tabId, operation: "resize", input }) |
| 3036 | .pipe(Effect.forkScoped); |
| 3037 | let event = yield* PubSub.take(events); |
| 3038 | while (event.type !== "resized" || event.tabId !== tabId) { |
| 3039 | event = yield* PubSub.take(events); |
| 3040 | } |
| 3041 | Object.assign(context.cssViewport, { width, height }); |
| 3042 | yield* Effect.promise(() => cdp.emitAsync("Page.frameResized")); |
| 3043 | return (yield* Fiber.join(result)).viewport; |
| 3044 | }); |
| 3045 | |
| 3046 | // A size no read measured after the resize is unknown, never a default or the last one. |
| 3047 | expect( |
| 3048 | yield* resize({ mode: "freeform", width: 900, height: 600 }, 900, 600), |
| 3049 | ).toBeUndefined(); |
| 3050 | // A hidden guest takes the new size only while the desktop paints it, which a capture asks for. |
| 3051 | expect(cdp.send).toHaveBeenCalledWith( |
| 3052 | "Page.captureScreenshot", |
| 3053 | expect.objectContaining({ clip: expect.anything() }), |
| 3054 | ); |
| 3055 | desktopSizeAnswer = null; |
| 3056 | expect(yield* resize({ mode: "freeform", width: 1280, height: 760 }, 1280, 760)).toEqual({ |
| 3057 | width: 1280, |
| 3058 | height: 760, |
| 3059 | }); |
| 3060 | desktopSizeAnswer = failReads; |
| 3061 | expect(yield* status).toEqual({ width: 1280, height: 760 }); |
| 3062 | expect( |
| 3063 | yield* resize({ mode: "freeform", width: 1000, height: 700 }, 1000, 700), |
| 3064 | ).toBeUndefined(); |
| 3065 | desktopSizeAnswer = null; |
| 3066 | // A page can keep another size than the fixed one asked for; both report the page's. |
| 3067 | expect(yield* resize({ mode: "freeform", width: 844, height: 390 }, 560, 760)).toEqual({ |
| 3068 | width: 560, |
| 3069 | height: 760, |
| 3070 | }); |
| 3071 | expect(yield* status).toEqual({ width: 560, height: 760 }); |
| 3072 | expect(yield* resize({ mode: "fill" }, 1234, 700)).toEqual({ width: 1234, height: 700 }); |
| 3073 | // No page resize or load since that read, so status answers without reading again. |
| 3074 | let reads = 0; |
| 3075 | desktopSizeAnswer = async () => { |
| 3076 | reads += 1; |
| 3077 | return { result: { value: { width: 1, height: 1 } } }; |
| 3078 | }; |
| 3079 | expect(yield* status).toEqual({ width: 1234, height: 700 }); |
| 3080 | expect(reads).toBe(0); |
| 3081 | // A status during a read waits for it rather than answer the size before it. |
| 3082 | const pending = yield* Queue.unbounded<PromiseWithResolvers<Record<string, unknown>>>(); |
| 3083 | const heldAnswer = () => { |
| 3084 | const read = Promise.withResolvers<Record<string, unknown>>(); |
| 3085 | Queue.offerUnsafe(pending, read); |
| 3086 | return read.promise; |
| 3087 | }; |
| 3088 | desktopSizeAnswer = heldAnswer; |
| 3089 | const answer = (width: number, height: number) => ({ result: { value: { width, height } } }); |
| 3090 | const refill = broker |
| 3091 | .invoke<PreviewAutomationResizeResult>({ |
| 3092 | scope, |
| 3093 | tabId, |
| 3094 | operation: "resize", |
| 3095 | input: { mode: "fill" }, |
| 3096 | }) |
| 3097 | .pipe( |
| 3098 | Effect.map((result) => result.viewport), |
| 3099 | Effect.forkScoped, |
| 3100 | ); |
| 3101 | // Status reads the URL just before it picks the size. |
| 3102 | const url = context.page.url(); |
| 3103 | using urlRead = vi.spyOn(context.page, "url"); |
| 3104 | const startStatus = Effect.gen(function* () { |
| 3105 | const started = Promise.withResolvers<void>(); |
| 3106 | urlRead.mockImplementationOnce(() => { |
| 3107 | started.resolve(); |
| 3108 | return url; |
| 3109 | }); |
| 3110 | const fiber = yield* Effect.forkScoped(status); |
| 3111 | yield* Effect.promise(() => started.promise); |
| 3112 | return fiber; |
| 3113 | }); |
| 3114 | const filled = yield* refill; |
| 3115 | const read = yield* Queue.take(pending); |
| 3116 | const during = yield* startStatus; |
| 3117 | read.resolve(answer(1100, 650)); |
| 3118 | expect(yield* Fiber.join(during)).toEqual({ width: 1100, height: 650 }); |
| 3119 | expect(yield* Fiber.join(filled)).toEqual({ width: 1100, height: 650 }); |
| 3120 | // A page resize during that read makes its answer old: status reads again, and the |
| 3121 | // resize result has no size. |
| 3122 | const outdated = yield* refill; |
| 3123 | const oldRead = yield* Queue.take(pending); |
| 3124 | const later = yield* startStatus; |
| 3125 | yield* Effect.promise(() => cdp.emitAsync("Page.frameResized")); |
| 3126 | desktopSizeAnswer = async () => answer(1000, 600); |
| 3127 | oldRead.resolve(answer(1100, 650)); |
| 3128 | expect(yield* Fiber.join(later)).toEqual({ width: 1000, height: 600 }); |
| 3129 | expect(yield* Fiber.join(outdated)).toBeUndefined(); |
| 3130 | // So does a load during that read, which may have measured the page before it. |
| 3131 | desktopSizeAnswer = heldAnswer; |
| 3132 | const reloaded = yield* refill; |
| 3133 | const pageRead = yield* Queue.take(pending); |
| 3134 | const navigated = yield* startStatus; |
| 3135 | yield* Effect.promise(() => cdp.emitAsync("Page.loadEventFired")); |
| 3136 | desktopSizeAnswer = async () => answer(900, 560); |
| 3137 | pageRead.resolve(answer(1000, 600)); |
| 3138 | expect(yield* Fiber.join(navigated)).toEqual({ width: 900, height: 560 }); |
| 3139 | expect(yield* Fiber.join(reloaded)).toBeUndefined(); |
| 3140 | }), |
| 3141 | ).pipe(Effect.provide(layer)), |
| 3142 | ); |
| 3143 | |
| 3144 | it.effect("a stalled desktop viewer still gets its size, control and reconnect", () => |
| 3145 | Effect.scoped( |
| 3146 | Effect.gen(function* () { |
| 3147 | const { tabId, viewer, context, resize } = yield* openDesktopViewer; |
| 3148 | const output = |
| 3149 | viewer.output as unknown as Queue.Queue<ServerBrowser.ServerBrowserViewerOutput>; |
| 3150 | // Ready once the sizes measured on attach and on a first resize both arrived. |
| 3151 | yield* resize(1920, 1080); |
| 3152 | expect(viewportSizes(yield* Queue.takeAll(viewer.output))).toEqual([ |
| 3153 | "1920x1080", |
| 3154 | "1920x1080", |
| 3155 | ]); |
| 3156 | yield* Effect.promise(() => desktopDetachReady.promise); |
| 3157 | yield* viewer.input({ type: "takeControl" }); |
| 3158 | context.page.emit("filechooser", { |
| 3159 | isMultiple: () => false, |
| 3160 | element: () => fileChooserElement(".csv"), |
| 3161 | setFiles: vi.fn(async () => {}), |
| 3162 | }); |
| 3163 | let chooser = yield* Queue.take(viewer.output); |
| 3164 | while (chooser._tag !== "fileChooser") chooser = yield* Queue.take(viewer.output); |
| 3165 | yield* Queue.clear(viewer.output); |
| 3166 | // A resize compacts a full backlog but keeps control, the open picker and |
| 3167 | // one-time notifications in order. |
| 3168 | yield* viewer.input({ type: "takeControl" }); |
| 3169 | const notifications: Array<ServerBrowser.ServerBrowserViewerOutput> = [ |
| 3170 | { _tag: "fileChooserClosed", id: "chooser-0" }, |
| 3171 | { _tag: "popup", tabId: "popup-1" }, |
| 3172 | { _tag: "download", id: "download-1", fileName: "report.csv", sizeBytes: 3 }, |
| 3173 | { _tag: "clipboard", text: "copied" }, |
| 3174 | ]; |
| 3175 | for (const item of notifications) Queue.offerUnsafe(output, item); |
| 3176 | let acked = stallViewer(viewer); |
| 3177 | yield* resize(1000, 600); |
| 3178 | expect(yield* Queue.takeAll(viewer.output)).toEqual([ |
| 3179 | chooser, |
| 3180 | ...notifications, |
| 3181 | expect.objectContaining({ _tag: "control", controller: "you" }), |
| 3182 | { _tag: "viewport", width: 1000, height: 600 }, |
| 3183 | ]); |
| 3184 | yield* acked; |
| 3185 | // A control change keeps only the newest size. |
| 3186 | yield* resize(900, 500); |
| 3187 | yield* resize(1200, 700); |
| 3188 | acked = stallViewer(viewer); |
| 3189 | yield* viewer.input({ type: "releaseControl" }); |
| 3190 | expect(yield* Queue.takeAll(viewer.output)).toEqual([ |
| 3191 | expect.objectContaining({ _tag: "control", controller: "unclaimed" }), |
| 3192 | { _tag: "viewport", width: 1200, height: 700 }, |
| 3193 | ]); |
| 3194 | yield* acked; |
| 3195 | // Notifications that no longer fit go oldest first, never the size. |
| 3196 | let copies = 0; |
| 3197 | while (Queue.offerUnsafe(output, { _tag: "clipboard", text: `copy ${copies}` })) copies++; |
| 3198 | yield* resize(1000, 600); |
| 3199 | const compacted = yield* Queue.takeAll(viewer.output); |
| 3200 | expect(compacted.at(0)).toEqual({ _tag: "clipboard", text: "copy 1" }); |
| 3201 | expect(compacted.at(-1)).toEqual({ _tag: "viewport", width: 1000, height: 600 }); |
| 3202 | // The desktop takes the page back; a resize after it cannot bury the reconnect. |
| 3203 | acked = stallViewer(viewer); |
| 3204 | desktopDetaches.emit("detach", { threadId: scope.thread.threadId, tabId }); |
| 3205 | yield* Effect.promise(() => desktopReleased.promise); |
| 3206 | yield* resize(1000, 600); |
| 3207 | expect(yield* Queue.takeAll(viewer.output)).toEqual([{ _tag: "reconnect" }]); |
| 3208 | yield* acked; |
| 3209 | }), |
| 3210 | ).pipe(Effect.provide(layer)), |
| 3211 | ); |
| 3212 | |
| 3213 | it.effect("the tab the desktop shows is visible and picked for agents without a tab", () => |
| 3214 | Effect.scoped( |
| 3215 | Effect.gen(function* () { |
| 3216 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3217 | const manager = yield* Manager.PreviewManager; |
| 3218 | yield* ServerBrowser.ServerBrowser; |
| 3219 | yield* Effect.yieldNow; |
| 3220 | const openDesktopTab = Effect.fn("openDesktopTab")(function* (url: string) { |
| 3221 | desktopRendersNext = true; |
| 3222 | const opened = yield* manager.open({ |
| 3223 | threadId: scope.thread.threadId, |
| 3224 | url, |
| 3225 | runtime: "server", |
| 3226 | }); |
| 3227 | const tabId = PreviewTabId.make(opened.tabId); |
| 3228 | yield* broker.invoke({ scope, tabId, operation: "status", input: {} }); |
| 3229 | return tabId; |
| 3230 | }); |
| 3231 | const recentTab = yield* openDesktopTab("http://localhost:5173/recent"); |
| 3232 | const shownTab = yield* openDesktopTab("http://localhost:5173/shown"); |
| 3233 | // Opened first and used last, so recency or insertion order alone picks it. |
| 3234 | yield* broker.invoke({ scope, tabId: recentTab, operation: "status", input: {} }); |
| 3235 | |
| 3236 | shownDesktopTabs.add(shownTab); |
| 3237 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3238 | scope: asSession("agent-b"), |
| 3239 | operation: "status", |
| 3240 | input: {}, |
| 3241 | }); |
| 3242 | expect(status).toMatchObject({ |
| 3243 | tabId: shownTab, |
| 3244 | visible: true, |
| 3245 | tabs: [ |
| 3246 | expect.objectContaining({ tabId: recentTab, visible: false }), |
| 3247 | expect.objectContaining({ tabId: shownTab, visible: true }), |
| 3248 | ], |
| 3249 | }); |
| 3250 | }), |
| 3251 | ).pipe(Effect.provide(layer)), |
| 3252 | ); |
| 3253 | |
| 3254 | it.effect( |
| 3255 | "agents read a human's tab with no arguments and act on it only while nobody drives", |
| 3256 | () => |
| 3257 | Effect.scoped( |
| 3258 | Effect.gen(function* () { |
| 3259 | const browser = yield* ServerBrowser.ServerBrowser; |
| 3260 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3261 | const manager = yield* Manager.PreviewManager; |
| 3262 | yield* Effect.yieldNow; |
| 3263 | const opened = yield* manager.open({ |
| 3264 | threadId: scope.thread.threadId, |
| 3265 | url: "http://localhost:5173/mine", |
| 3266 | runtime: "server", |
| 3267 | }); |
| 3268 | const tabId = PreviewTabId.make(opened.tabId); |
| 3269 | const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); |
| 3270 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3271 | scope, |
| 3272 | operation: "status", |
| 3273 | input: {}, |
| 3274 | }); |
| 3275 | expect(status).toMatchObject({ |
| 3276 | tabId, |
| 3277 | control: { owner: "human", ownedByCaller: false }, |
| 3278 | }); |
| 3279 | expect(status.tabs).toEqual([ |
| 3280 | expect.objectContaining({ tabId, owner: "human", ownedByCaller: false, visible: true }), |
| 3281 | ]); |
| 3282 | const evaluated = yield* broker |
| 3283 | .invoke<void>({ scope, operation: "evaluate", input: { expression: "read()" } }) |
| 3284 | .pipe(Effect.flip); |
| 3285 | expect(evaluated).toMatchObject({ |
| 3286 | _tag: "PreviewAutomationControlInterruptedError", |
| 3287 | reason: "humanControl", |
| 3288 | }); |
| 3289 | yield* broker.invoke<PreviewAutomationSnapshot>({ |
| 3290 | scope, |
| 3291 | tabId, |
| 3292 | operation: "snapshot", |
| 3293 | input: {}, |
| 3294 | }); |
| 3295 | const refused = yield* broker |
| 3296 | .invoke<void>({ |
| 3297 | scope, |
| 3298 | tabId, |
| 3299 | operation: "navigate", |
| 3300 | input: { url: "http://localhost:5173/agent" }, |
| 3301 | }) |
| 3302 | .pipe(Effect.flip); |
| 3303 | expect(refused).toMatchObject({ |
| 3304 | _tag: "PreviewAutomationControlInterruptedError", |
| 3305 | reason: "humanControl", |
| 3306 | }); |
| 3307 | yield* viewer.input({ type: "releaseControl" }); |
| 3308 | const released = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3309 | scope, |
| 3310 | tabId, |
| 3311 | operation: "status", |
| 3312 | input: {}, |
| 3313 | }); |
| 3314 | expect(released.control).toMatchObject({ owner: "unclaimed", ownedByCaller: false }); |
| 3315 | yield* broker.invoke({ |
| 3316 | scope, |
| 3317 | tabId, |
| 3318 | operation: "navigate", |
| 3319 | input: { url: "http://localhost:5173/agent" }, |
| 3320 | }); |
| 3321 | expect(contexts[0]!.page.goto).toHaveBeenCalledWith( |
| 3322 | "http://localhost:5173/agent", |
| 3323 | expect.anything(), |
| 3324 | ); |
| 3325 | yield* viewer.input({ type: "takeControl" }); |
| 3326 | const retaken = yield* broker |
| 3327 | .invoke<void>({ scope, tabId, operation: "press", input: { key: "Enter" } }) |
| 3328 | .pipe(Effect.flip); |
| 3329 | expect(retaken).toMatchObject({ reason: "humanControl" }); |
| 3330 | }), |
| 3331 | ).pipe(Effect.provide(layer)), |
| 3332 | ); |
| 3333 | |
| 3334 | it.effect("preview_open reports a tab it shows as visible once the client attaches", () => |
| 3335 | Effect.scoped( |
| 3336 | Effect.gen(function* () { |
| 3337 | const browser = yield* ServerBrowser.ServerBrowser; |
| 3338 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3339 | const manager = yield* Manager.PreviewManager; |
| 3340 | const events = yield* manager.subscribeEvents; |
| 3341 | yield* Effect.yieldNow; |
| 3342 | // Like a real client, the stream attaches asynchronously after the reveal request arrives. |
| 3343 | yield* Effect.gen(function* () { |
| 3344 | let event; |
| 3345 | do event = yield* PubSub.take(events); |
| 3346 | while (event.type !== "navigated" || !event.snapshot.revealRequest); |
| 3347 | yield* browser.attachViewer(viewerInput(event.tabId, false)).pipe(Effect.forkScoped); |
| 3348 | }).pipe(Effect.forkScoped); |
| 3349 | |
| 3350 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3351 | scope, |
| 3352 | operation: "open", |
| 3353 | input: { reuseExistingTab: false, open: true }, |
| 3354 | }); |
| 3355 | |
| 3356 | expect(opened.visible).toBe(true); |
| 3357 | }), |
| 3358 | ).pipe(Effect.provide(layer)), |
| 3359 | ); |
| 3360 | |
| 3361 | it.effect("preview_open reports a hidden desktop tab it reveals as visible", () => |
| 3362 | Effect.scoped( |
| 3363 | Effect.gen(function* () { |
| 3364 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3365 | const manager = yield* Manager.PreviewManager; |
| 3366 | yield* ServerBrowser.ServerBrowser; |
| 3367 | const events = yield* manager.subscribeEvents; |
| 3368 | yield* Effect.yieldNow; |
| 3369 | desktopRendersNext = true; |
| 3370 | const created = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3371 | scope, |
| 3372 | operation: "open", |
| 3373 | input: { reuseExistingTab: false, open: false }, |
| 3374 | }); |
| 3375 | const tabId = PreviewTabId.make(created.tabId!); |
| 3376 | expect(created.visible).toBe(false); |
| 3377 | // Like the desktop renderer, the docked panel reports the tab shown after the reveal arrives. |
| 3378 | yield* Effect.gen(function* () { |
| 3379 | let event; |
| 3380 | do event = yield* PubSub.take(events); |
| 3381 | while (event.type !== "navigated" || !event.snapshot.revealRequest); |
| 3382 | // The report crosses the client, the desktop main process and its pipe, so it lands a task later. |
| 3383 | yield* Effect.yieldNow; |
| 3384 | yield* Effect.sync(() => shownDesktopTabs.add(tabId)); |
| 3385 | }).pipe(Effect.forkScoped); |
| 3386 | |
| 3387 | const opened = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3388 | scope, |
| 3389 | tabId, |
| 3390 | operation: "open", |
| 3391 | input: { open: true }, |
| 3392 | }); |
| 3393 | |
| 3394 | expect(opened.visible).toBe(true); |
| 3395 | expect(opened.tabs).toEqual([expect.objectContaining({ tabId, visible: true })]); |
| 3396 | }), |
| 3397 | ).pipe(Effect.provide(layer)), |
| 3398 | ); |
| 3399 | |
| 3400 | it.effect("a session's own tab stays its default while other sessions' tabs are listed", () => |
| 3401 | Effect.scoped( |
| 3402 | Effect.gen(function* () { |
| 3403 | const { broker, tabId } = yield* ready; |
| 3404 | const other = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3405 | scope: asSession("agent-b"), |
| 3406 | operation: "open", |
| 3407 | input: { reuseExistingTab: false, show: false }, |
| 3408 | }); |
| 3409 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3410 | scope, |
| 3411 | operation: "status", |
| 3412 | input: {}, |
| 3413 | }); |
| 3414 | expect(status.tabId).toBe(tabId); |
| 3415 | expect(status.tabs).toEqual( |
| 3416 | expect.arrayContaining([ |
| 3417 | expect.objectContaining({ tabId, owner: "agent", ownedByCaller: true }), |
| 3418 | expect.objectContaining({ tabId: other.tabId, owner: "agent", ownedByCaller: false }), |
| 3419 | ]), |
| 3420 | ); |
| 3421 | }), |
| 3422 | ).pipe(Effect.provide(layer)), |
| 3423 | ); |
| 3424 | |
| 3425 | it.effect( |
| 3426 | "preview_open picks a reported profile by id or name and defaults to the reported one", |
| 3427 | () => |
| 3428 | Effect.scoped( |
| 3429 | Effect.gen(function* () { |
| 3430 | const browser = yield* ServerBrowser.ServerBrowser; |
| 3431 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3432 | const manager = yield* Manager.PreviewManager; |
| 3433 | yield* Effect.yieldNow; |
| 3434 | const reportProfiles = yield* browser.profileReporter; |
| 3435 | yield* reportProfiles({ |
| 3436 | profiles: [{ id: "profile-work", name: "Work", kind: "persistent" }], |
| 3437 | defaultProfileId: "profile-work", |
| 3438 | }); |
| 3439 | const openWith = (profileId?: string) => |
| 3440 | broker.invoke<PreviewAutomationStatus>({ |
| 3441 | scope, |
| 3442 | operation: "open", |
| 3443 | input: { |
| 3444 | reuseExistingTab: false, |
| 3445 | show: false, |
| 3446 | ...(profileId === undefined ? {} : { profileId }), |
| 3447 | }, |
| 3448 | }); |
| 3449 | const byDefault = yield* openWith(); |
| 3450 | const byName = yield* openWith("WORK"); |
| 3451 | const byId = yield* openWith("incognito"); |
| 3452 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 3453 | const profileOf = (tabId: string | null) => |
| 3454 | sessions.find((session) => session.tabId === tabId)?.profileId; |
| 3455 | expect(profileOf(byDefault.tabId)).toBe("profile-work"); |
| 3456 | expect(profileOf(byName.tabId)).toBe("profile-work"); |
| 3457 | expect(profileOf(byId.tabId)).toBe("incognito"); |
| 3458 | expect(contextRequests).toEqual([ |
| 3459 | { profileId: "profile-work", isolated: false }, |
| 3460 | { profileId: "profile-work", isolated: false }, |
| 3461 | { profileId: "incognito", isolated: true }, |
| 3462 | ]); |
| 3463 | expect(byDefault).toMatchObject({ |
| 3464 | defaultProfileId: "profile-work", |
| 3465 | profiles: [ |
| 3466 | { id: "default", name: "Default" }, |
| 3467 | { id: "incognito", name: "Incognito", incognito: true }, |
| 3468 | { id: "profile-work", name: "Work" }, |
| 3469 | ], |
| 3470 | }); |
| 3471 | const unknown = yield* openWith("Personal").pipe(Effect.flip); |
| 3472 | expect(unknown).toMatchObject({ |
| 3473 | _tag: "PreviewAutomationExecutionError", |
| 3474 | reason: |
| 3475 | 'No browser profile is named "Personal". Use one of: Default (id default), Incognito (id incognito), Work (id profile-work).', |
| 3476 | }); |
| 3477 | }), |
| 3478 | ).pipe(Effect.provide(layer)), |
| 3479 | ); |
| 3480 | |
| 3481 | // Holds the next profile save at its temp-file cleanup, after the rename, until released. |
| 3482 | const gateSaveCleanup = Effect.gen(function* () { |
| 3483 | const fs = yield* FileSystem.FileSystem; |
| 3484 | const cleanupStarted = yield* Deferred.make<void>(); |
| 3485 | const releaseCleanup = yield* Deferred.make<void>(); |
| 3486 | let paused = false; |
| 3487 | return { |
| 3488 | cleanupStarted, |
| 3489 | releaseCleanup, |
| 3490 | pauseNext: () => { |
| 3491 | paused = true; |
| 3492 | }, |
| 3493 | fs: FileSystem.FileSystem.of({ |
| 3494 | ...fs, |
| 3495 | remove: (target, options) => |
| 3496 | fs.remove(target, options).pipe( |
| 3497 | Effect.tap(() => { |
| 3498 | if (!paused) return Effect.void; |
| 3499 | paused = false; |
| 3500 | return Deferred.succeed(cleanupStarted, undefined).pipe( |
| 3501 | Effect.andThen(Deferred.await(releaseCleanup)), |
| 3502 | ); |
| 3503 | }), |
| 3504 | ), |
| 3505 | }), |
| 3506 | }; |
| 3507 | }); |
| 3508 | |
| 3509 | it.effect( |
| 3510 | "an agent opens a reported profile after a restart, before any client reports again", |
| 3511 | () => |
| 3512 | Effect.gen(function* () { |
| 3513 | const gate = yield* gateSaveCleanup; |
| 3514 | const persistent = (name: string) => |
| 3515 | ({ id: `profile-${name.toLowerCase()}`, name, kind: "persistent" }) as const; |
| 3516 | // Together the two clients report more profiles than one report may hold. |
| 3517 | const fromA = [ |
| 3518 | persistent("Work"), |
| 3519 | ...Array.from({ length: 12 }, (_, n) => persistent(`A${n}`)), |
| 3520 | ]; |
| 3521 | const fromB = [ |
| 3522 | persistent("Shared"), |
| 3523 | ...Array.from({ length: 12 }, (_, n) => persistent(`B${n}`)), |
| 3524 | ]; |
| 3525 | yield* Effect.gen(function* () { |
| 3526 | const browser = yield* ServerBrowser.ServerBrowser; |
| 3527 | const clientA = yield* Scope.make(); |
| 3528 | const reportFromA = yield* browser.profileReporter.pipe( |
| 3529 | Effect.provideService(Scope.Scope, clientA), |
| 3530 | ); |
| 3531 | const reportFromB = yield* browser.profileReporter; |
| 3532 | const reportFromC = yield* browser.profileReporter; |
| 3533 | yield* reportFromA({ profiles: fromA, defaultProfileId: "profile-work" }); |
| 3534 | gate.pauseNext(); |
| 3535 | const savingB = yield* reportFromB({ |
| 3536 | profiles: fromB, |
| 3537 | defaultProfileId: "profile-shared", |
| 3538 | }).pipe(Effect.forkScoped({ startImmediately: true })); |
| 3539 | // A save that ends without reaching the gate fails the test instead of hanging it. |
| 3540 | yield* Effect.raceFirst( |
| 3541 | Deferred.await(gate.cleanupStarted), |
| 3542 | Fiber.join(savingB).pipe( |
| 3543 | Effect.andThen(Effect.die("save finished before the cleanup gate")), |
| 3544 | ), |
| 3545 | ); |
| 3546 | // C's save waits behind B's while the client that reported Work disconnects, as at shutdown. |
| 3547 | const savingC = yield* reportFromC({ |
| 3548 | profiles: [], |
| 3549 | defaultProfileId: "profile-shared", |
| 3550 | }).pipe(Effect.forkScoped({ startImmediately: true })); |
| 3551 | yield* Scope.close(clientA, Exit.void); |
| 3552 | yield* Deferred.succeed(gate.releaseCleanup, undefined); |
| 3553 | yield* Fiber.join(savingB); |
| 3554 | yield* Fiber.join(savingC); |
| 3555 | }).pipe( |
| 3556 | Effect.scoped, |
| 3557 | Effect.provide( |
| 3558 | Layer.fresh(ServerBrowser.layer).pipe( |
| 3559 | Layer.provide(Layer.succeed(FileSystem.FileSystem, gate.fs)), |
| 3560 | ), |
| 3561 | ), |
| 3562 | ); |
| 3563 | |
| 3564 | const restarted = yield* Effect.gen(function* () { |
| 3565 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3566 | yield* ServerBrowser.ServerBrowser; |
| 3567 | yield* Effect.yieldNow; |
| 3568 | return yield* broker.invoke<PreviewAutomationStatus>({ |
| 3569 | scope, |
| 3570 | operation: "open", |
| 3571 | input: { reuseExistingTab: false, show: false, profileId: "Work" }, |
| 3572 | }); |
| 3573 | }).pipe(Effect.provide(Layer.fresh(ServerBrowser.layer))); |
| 3574 | |
| 3575 | expect(contextRequests).toEqual([{ profileId: "profile-work", isolated: false }]); |
| 3576 | expect(restarted.tabs).toMatchObject([{ profileId: "profile-work" }]); |
| 3577 | expect(restarted).toMatchObject({ |
| 3578 | defaultProfileId: "profile-shared", |
| 3579 | profiles: [ |
| 3580 | { id: "default", name: "Default" }, |
| 3581 | { id: "incognito", name: "Incognito", incognito: true }, |
| 3582 | ...[...fromA, ...fromB].map(({ id, name }) => ({ id, name })), |
| 3583 | ], |
| 3584 | }); |
| 3585 | }).pipe(Effect.provide(dependencies)), |
| 3586 | ); |
| 3587 | |
| 3588 | it.effect("warns at startup about a saved profile catalog it cannot read or decode", () => |
| 3589 | Effect.gen(function* () { |
| 3590 | const fs = yield* FileSystem.FileSystem; |
| 3591 | const path = yield* Path.Path; |
| 3592 | const { stateDir } = yield* ServerConfig.ServerConfig; |
| 3593 | const savedPath = path.join(stateDir, "server-browser", "reported-profiles.json"); |
| 3594 | const startupWarnings = (saved: "missing" | "empty" | "invalid" | "unreadable") => |
| 3595 | Effect.gen(function* () { |
| 3596 | const messages: string[] = []; |
| 3597 | yield* fs.remove(savedPath, { recursive: true, force: true }); |
| 3598 | yield* fs.makeDirectory(path.dirname(savedPath), { recursive: true }); |
| 3599 | if (saved === "empty") yield* fs.writeFileString(savedPath, ""); |
| 3600 | if (saved === "invalid") yield* fs.writeFileString(savedPath, "{"); |
| 3601 | if (saved === "unreadable") yield* fs.makeDirectory(savedPath); |
| 3602 | const logger = Logger.make(({ message }) => { |
| 3603 | messages.push(String(message)); |
| 3604 | }); |
| 3605 | yield* ServerBrowser.ServerBrowser.pipe( |
| 3606 | Effect.provide( |
| 3607 | Layer.fresh(ServerBrowser.layer).pipe( |
| 3608 | Layer.provide(Logger.layer([logger], { mergeWithExisting: false })), |
| 3609 | ), |
| 3610 | ), |
| 3611 | ); |
| 3612 | return messages.filter((message) => message.includes("saved browser profiles")); |
| 3613 | }); |
| 3614 | |
| 3615 | expect(yield* startupWarnings("missing")).toEqual([]); |
| 3616 | expect(yield* startupWarnings("empty")).toEqual([]); |
| 3617 | expect(yield* startupWarnings("invalid")).toEqual([ |
| 3618 | expect.stringContaining("ignoring invalid saved browser profiles"), |
| 3619 | ]); |
| 3620 | expect(yield* startupWarnings("unreadable")).toEqual([ |
| 3621 | expect.stringContaining("failed to read saved browser profiles"), |
| 3622 | ]); |
| 3623 | }).pipe(Effect.provide(dependencies)), |
| 3624 | ); |
| 3625 | |
| 3626 | it.effect("a report interrupted while an earlier save holds the lock is still saved", () => |
| 3627 | Effect.gen(function* () { |
| 3628 | const gate = yield* gateSaveCleanup; |
| 3629 | const work = { id: "profile-work", name: "Work", kind: "persistent" } as const; |
| 3630 | const late = { id: "profile-late", name: "Late", kind: "persistent" } as const; |
| 3631 | yield* Effect.gen(function* () { |
| 3632 | const report = yield* (yield* ServerBrowser.ServerBrowser).profileReporter; |
| 3633 | gate.pauseNext(); |
| 3634 | const saving = yield* report({ profiles: [work], defaultProfileId: "profile-work" }).pipe( |
| 3635 | Effect.forkScoped({ startImmediately: true }), |
| 3636 | ); |
| 3637 | yield* Effect.raceFirst( |
| 3638 | Deferred.await(gate.cleanupStarted), |
| 3639 | Fiber.join(saving).pipe( |
| 3640 | Effect.andThen(Effect.die("save finished before the cleanup gate")), |
| 3641 | ), |
| 3642 | ); |
| 3643 | // The client disconnects while its report waits for the save in progress. |
| 3644 | const waiting = yield* report({ |
| 3645 | profiles: [work, late], |
| 3646 | defaultProfileId: "profile-late", |
| 3647 | }).pipe(Effect.forkScoped({ startImmediately: true })); |
| 3648 | waiting.interruptUnsafe(); |
| 3649 | yield* Deferred.succeed(gate.releaseCleanup, undefined); |
| 3650 | yield* Fiber.join(saving); |
| 3651 | yield* Fiber.await(waiting); |
| 3652 | }).pipe( |
| 3653 | Effect.scoped, |
| 3654 | Effect.provide( |
| 3655 | Layer.fresh(ServerBrowser.layer).pipe( |
| 3656 | Layer.provide(Layer.succeed(FileSystem.FileSystem, gate.fs)), |
| 3657 | ), |
| 3658 | ), |
| 3659 | ); |
| 3660 | |
| 3661 | const restarted = yield* Effect.gen(function* () { |
| 3662 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3663 | yield* ServerBrowser.ServerBrowser; |
| 3664 | yield* Effect.yieldNow; |
| 3665 | return yield* broker.invoke<PreviewAutomationStatus>({ |
| 3666 | scope, |
| 3667 | operation: "open", |
| 3668 | input: { reuseExistingTab: false, show: false, profileId: "Late" }, |
| 3669 | }); |
| 3670 | }).pipe(Effect.provide(Layer.fresh(ServerBrowser.layer))); |
| 3671 | |
| 3672 | expect(restarted).toMatchObject({ |
| 3673 | defaultProfileId: "profile-late", |
| 3674 | tabs: [{ profileId: "profile-late" }], |
| 3675 | }); |
| 3676 | }).pipe(Effect.provide(dependencies)), |
| 3677 | ); |
| 3678 | |
| 3679 | it.effect("profiles reported by one client survive another client's report", () => |
| 3680 | Effect.scoped( |
| 3681 | Effect.gen(function* () { |
| 3682 | const { browser, broker } = yield* ready; |
| 3683 | contextRequests.length = 0; |
| 3684 | const work = { id: "profile-work", name: "Work", kind: "persistent" } as const; |
| 3685 | const shared = { id: "profile-shared", name: "Shared", kind: "persistent" } as const; |
| 3686 | const openWork = () => |
| 3687 | broker.invoke<PreviewAutomationStatus>({ |
| 3688 | scope, |
| 3689 | operation: "open", |
| 3690 | input: { reuseExistingTab: false, show: false, profileId: work.id }, |
| 3691 | }); |
| 3692 | const reportFromA = yield* browser.profileReporter; |
| 3693 | const clientB = yield* Scope.make(); |
| 3694 | const reportFromB = yield* browser.profileReporter.pipe( |
| 3695 | Effect.provideService(Scope.Scope, clientB), |
| 3696 | ); |
| 3697 | yield* reportFromA({ profiles: [work, shared], defaultProfileId: work.id }); |
| 3698 | yield* reportFromB({ profiles: [shared], defaultProfileId: shared.id }); |
| 3699 | expect(yield* openWork()).toMatchObject({ |
| 3700 | defaultProfileId: shared.id, |
| 3701 | profiles: [ |
| 3702 | { id: "default", name: "Default" }, |
| 3703 | { id: "incognito", name: "Incognito", incognito: true }, |
| 3704 | { id: work.id, name: work.name }, |
| 3705 | { id: shared.id, name: shared.name }, |
| 3706 | ], |
| 3707 | }); |
| 3708 | expect(contextRequests).toEqual([{ profileId: work.id, isolated: false }]); |
| 3709 | yield* Scope.close(clientB, Exit.void); |
| 3710 | expect(yield* openWork()).toMatchObject({ defaultProfileId: work.id }); |
| 3711 | yield* reportFromA({ profiles: [shared], defaultProfileId: shared.id }); |
| 3712 | const removed = yield* openWork().pipe(Effect.flip); |
| 3713 | expect(removed).toMatchObject({ |
| 3714 | _tag: "PreviewAutomationExecutionError", |
| 3715 | reason: |
| 3716 | 'No browser profile is named "profile-work". Use one of: Default (id default), Incognito (id incognito), Shared (id profile-shared).', |
| 3717 | }); |
| 3718 | }), |
| 3719 | ).pipe(Effect.provide(layer)), |
| 3720 | ); |
| 3721 | |
| 3722 | it.effect.each([ |
| 3723 | { budget: "agent", limit: 8 }, |
| 3724 | { budget: "server", limit: 32 }, |
| 3725 | ])("opens and popups reserve the $budget budget before session creation", ({ budget, limit }) => |
| 3726 | Effect.scoped( |
| 3727 | Effect.gen(function* () { |
| 3728 | const { broker, browser, tabId } = yield* ready; |
| 3729 | const manager = yield* Manager.PreviewManager; |
| 3730 | const open = (target = scope) => |
| 3731 | broker.invoke<PreviewAutomationStatus>({ |
| 3732 | scope: target, |
| 3733 | operation: "open", |
| 3734 | input: { reuseExistingTab: false, show: false }, |
| 3735 | }); |
| 3736 | for (let index = 1; index < limit - 3; index++) { |
| 3737 | yield* open(budget === "agent" ? scope : asSession(`other-${Math.floor(index / 8)}`)); |
| 3738 | } |
| 3739 | |
| 3740 | const sessionGate = Promise.withResolvers<void>(); |
| 3741 | const launchGate = (contextGate = Promise.withResolvers<void>()); |
| 3742 | const sessionStarted = Promise.withResolvers<void>(); |
| 3743 | const realOpen = manager.open; |
| 3744 | const delayedOpen = vi.spyOn(manager, "open").mockImplementation((input) => |
| 3745 | Effect.promise(() => { |
| 3746 | sessionStarted.resolve(); |
| 3747 | return sessionGate.promise; |
| 3748 | }).pipe(Effect.andThen(realOpen(input))), |
| 3749 | ); |
| 3750 | yield* Effect.addFinalizer(() => |
| 3751 | Effect.sync(() => { |
| 3752 | sessionGate.resolve(); |
| 3753 | launchGate.resolve(); |
| 3754 | delayedOpen.mockRestore(); |
| 3755 | }), |
| 3756 | ); |
| 3757 | const events = yield* manager.subscribeEvents; |
| 3758 | const first = yield* open().pipe(Effect.result, Effect.forkScoped); |
| 3759 | yield* Effect.promise(() => sessionStarted.promise); |
| 3760 | const popup = makeContext(); |
| 3761 | const resized = Promise.withResolvers<void>(); |
| 3762 | const setViewportSize = popup.page.setViewportSize; |
| 3763 | popup.page.setViewportSize = vi.fn(async (size) => { |
| 3764 | await setViewportSize(size); |
| 3765 | if (size?.width === 900) resized.resolve(); |
| 3766 | }); |
| 3767 | const newCDPSession = popup.newCDPSession; |
| 3768 | popup.newCDPSession = async (target) => { |
| 3769 | await launchGate.promise; |
| 3770 | return newCDPSession(target); |
| 3771 | }; |
| 3772 | contexts[0]!.page.emit("popup", popup.page); |
| 3773 | const last = yield* open().pipe(Effect.result, Effect.forkScoped); |
| 3774 | const overflow = yield* open().pipe(Effect.result, Effect.forkScoped); |
| 3775 | // The host processes this after the opens, while manager creation is blocked. |
| 3776 | const reused = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3777 | scope, |
| 3778 | tabId, |
| 3779 | operation: "open", |
| 3780 | input: { show: false }, |
| 3781 | }); |
| 3782 | expect(reused.tabId).toBe(tabId); |
| 3783 | expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength( |
| 3784 | limit - 3, |
| 3785 | ); |
| 3786 | |
| 3787 | sessionGate.resolve(); |
| 3788 | for (let count = 0; count < 3; count++) { |
| 3789 | let event = yield* PubSub.take(events); |
| 3790 | while (event.type !== "opened") event = yield* PubSub.take(events); |
| 3791 | yield* manager.resize({ |
| 3792 | threadId: scope.thread.threadId, |
| 3793 | tabId: event.tabId, |
| 3794 | viewport: { _tag: "freeform", width: 900, height: 700 }, |
| 3795 | }); |
| 3796 | } |
| 3797 | // The same slots must stay reserved after publication, while pages are still opening. |
| 3798 | const duringLaunch = yield* open().pipe(Effect.result, Effect.forkScoped); |
| 3799 | const rejectedPopup = makeContext(); |
| 3800 | contexts[0]!.page.emit("popup", rejectedPopup.page); |
| 3801 | yield* broker.invoke({ scope, tabId, operation: "status", input: {} }); |
| 3802 | launchGate.resolve(); |
| 3803 | |
| 3804 | expect((yield* Fiber.join(first))._tag).toBe("Success"); |
| 3805 | expect((yield* Fiber.join(last))._tag).toBe("Success"); |
| 3806 | for (const fiber of [overflow, duringLaunch]) { |
| 3807 | expect(yield* Fiber.join(fiber)).toMatchObject({ |
| 3808 | _tag: "Failure", |
| 3809 | failure: { _tag: "PreviewAutomationControlInterruptedError", reason: "tabLimit" }, |
| 3810 | }); |
| 3811 | } |
| 3812 | yield* Effect.promise(() => resized.promise); |
| 3813 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 3814 | for (const session of sessions) |
| 3815 | yield* browser.attachViewer(viewerInput(session.tabId, false)); |
| 3816 | expect(sessions).toHaveLength(limit); |
| 3817 | expect(popup.page.isClosed()).toBe(false); |
| 3818 | expect(rejectedPopup.page.isClosed()).toBe(true); |
| 3819 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3820 | scope, |
| 3821 | tabId, |
| 3822 | operation: "status", |
| 3823 | input: {}, |
| 3824 | }); |
| 3825 | expect(status.tabs).toHaveLength(limit); |
| 3826 | }), |
| 3827 | ).pipe(Effect.provide(layer)), |
| 3828 | ); |
| 3829 | |
| 3830 | it.effect("failed session and browser launches release capacity, as does closing a tab", () => |
| 3831 | Effect.scoped( |
| 3832 | Effect.gen(function* () { |
| 3833 | const { broker, tabId } = yield* ready; |
| 3834 | const manager = yield* Manager.PreviewManager; |
| 3835 | const open = broker.invoke<PreviewAutomationStatus>({ |
| 3836 | scope, |
| 3837 | operation: "open", |
| 3838 | input: { reuseExistingTab: false, show: false }, |
| 3839 | }); |
| 3840 | for (let count = 1; count < 7; count++) yield* open; |
| 3841 | const failSession = vi |
| 3842 | .spyOn(manager, "open") |
| 3843 | .mockImplementationOnce(() => Effect.die(new Error("session creation failed"))); |
| 3844 | yield* Effect.addFinalizer(() => Effect.sync(() => failSession.mockRestore())); |
| 3845 | expect(yield* open.pipe(Effect.result)).toMatchObject({ _tag: "Failure" }); |
| 3846 | failSession.mockRestore(); |
| 3847 | const events = yield* manager.subscribeEvents; |
| 3848 | contextFailure = new Error("Chromium launch failed"); |
| 3849 | expect(yield* open.pipe(Effect.result)).toMatchObject({ _tag: "Failure" }); |
| 3850 | let failedSession = yield* PubSub.take(events); |
| 3851 | while (failedSession.type !== "opened") failedSession = yield* PubSub.take(events); |
| 3852 | // A failed launch must not leave a session a viewer can relaunch past the budget. |
| 3853 | expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(7); |
| 3854 | contextFailure = null; |
| 3855 | pageSetupFailure = new Error("Target page, context or browser has been closed"); |
| 3856 | expect(yield* open.pipe(Effect.result)).toMatchObject({ _tag: "Failure" }); |
| 3857 | pageSetupFailure = null; |
| 3858 | // Setup that fails after the page exists must not leave the page or its context open. |
| 3859 | expect(contexts.at(-1)!.close).toHaveBeenCalled(); |
| 3860 | expect(contexts.at(-1)!.page.isClosed()).toBe(true); |
| 3861 | expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(7); |
| 3862 | expect((yield* open).available).toBe(true); |
| 3863 | expect(yield* open.pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" }); |
| 3864 | expect( |
| 3865 | yield* broker |
| 3866 | .invoke<PreviewAutomationStatus>({ |
| 3867 | scope, |
| 3868 | tabId: PreviewTabId.make(failedSession.tabId), |
| 3869 | operation: "open", |
| 3870 | input: { show: false }, |
| 3871 | }) |
| 3872 | .pipe(Effect.flip), |
| 3873 | ).toMatchObject({ _tag: "PreviewAutomationTabNotFoundError" }); |
| 3874 | const browser = yield* ServerBrowser.ServerBrowser; |
| 3875 | expect( |
| 3876 | yield* browser.attachViewer(viewerInput(failedSession.tabId, false)).pipe(Effect.flip), |
| 3877 | ).toMatchObject({ _tag: "ServerBrowserTabNotFoundError" }); |
| 3878 | yield* broker.invoke({ scope, tabId, operation: "close", input: {} }); |
| 3879 | expect((yield* open).available).toBe(true); |
| 3880 | const status = yield* broker.invoke<PreviewAutomationStatus>({ |
| 3881 | scope, |
| 3882 | operation: "status", |
| 3883 | input: {}, |
| 3884 | }); |
| 3885 | expect(status.tabs).toHaveLength(8); |
| 3886 | }), |
| 3887 | ).pipe(Effect.provide(layer)), |
| 3888 | ); |
| 3889 | |
| 3890 | it.effect("a full server takes back the slot of the longest idle agent tab nobody views", () => |
| 3891 | Effect.scoped( |
| 3892 | Effect.gen(function* () { |
| 3893 | const broker = yield* Broker.PreviewAutomationBroker; |
| 3894 | const manager = yield* Manager.PreviewManager; |
| 3895 | yield* ServerBrowser.ServerBrowser; |
| 3896 | yield* Effect.yieldNow; |
| 3897 | const now = vi.spyOn(Date, "now").mockReturnValue(0); |
| 3898 | yield* Effect.addFinalizer(() => Effect.sync(() => now.mockRestore())); |
| 3899 | const open = (providerSessionId: string) => { |
| 3900 | desktopRendersNext = true; |
| 3901 | return broker.invoke<PreviewAutomationStatus>({ |
| 3902 | scope: asSession(providerSessionId), |
| 3903 | operation: "open", |
| 3904 | input: { reuseExistingTab: false, open: false }, |
| 3905 | }); |
| 3906 | }; |
| 3907 | const opened: Array<string> = []; |
| 3908 | for (let index = 0; index < 32; index++) { |
| 3909 | now.mockReturnValue(index); |
| 3910 | opened.push((yield* open(`agent-${Math.floor(index / 8)}`)).tabId!); |
| 3911 | } |
| 3912 | |
| 3913 | now.mockReturnValue(100); |
| 3914 | yield* broker.invoke<PreviewAutomationStatus>({ |
| 3915 | scope: asSession("agent-observer"), |
| 3916 | operation: "status", |
| 3917 | tabId: PreviewTabId.make(opened[0]!), |
| 3918 | input: {}, |
| 3919 | }); |
| 3920 | |
| 3921 | // Inside the idle window every desktop tab keeps its slot. |
| 3922 | now.mockReturnValue(29 * 60 * 1000); |
| 3923 | expect(yield* open("agent-new").pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" }); |
| 3924 | expect(releasedDesktopTabs).toEqual([]); |
| 3925 | |
| 3926 | now.mockReturnValue(31 * 60 * 1000); |
| 3927 | // A session at its own limit couldn't use a freed slot, so nothing closes for it. |
| 3928 | expect(yield* open("agent-3").pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" }); |
| 3929 | expect(releasedDesktopTabs).toEqual([]); |
| 3930 | // Tabs a desktop window shows keep their slots however long they sit idle. |
| 3931 | for (const tabId of opened) shownDesktopTabs.add(tabId); |
| 3932 | expect(yield* open("agent-new").pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" }); |
| 3933 | expect(releasedDesktopTabs).toEqual([]); |
| 3934 | shownDesktopTabs.clear(); |
| 3935 | shownDesktopTabs.add(opened[1]!); |
| 3936 | desktopConnections[2]!.context.page.beforeUnload = "listen"; |
| 3937 | const events = yield* manager.subscribeEvents; |
| 3938 | const releases = yield* Queue.unbounded<string>(); |
| 3939 | const recordRelease = (tabId: string) => Queue.offerUnsafe(releases, tabId); |
| 3940 | desktopDetaches.on("release", recordRelease); |
| 3941 | yield* Effect.addFinalizer(() => |
| 3942 | Effect.sync(() => desktopDetaches.off("release", recordRelease)), |
| 3943 | ); |
| 3944 | const fresh = yield* open("agent-new"); |
| 3945 | expect(fresh.tabId).toBeDefined(); |
| 3946 | expect(yield* Queue.take(releases)).toBe(opened[2]); |
| 3947 | expect(desktopConnections[2]!.context.page.unloadEvents).toEqual([ |
| 3948 | "beforeunload", |
| 3949 | "pagehide", |
| 3950 | "visibilitychange", |
| 3951 | ]); |
| 3952 | yield* Stream.fromSubscription(events).pipe( |
| 3953 | Stream.filter((event) => event.type === "closed" && event.tabId === opened[2]), |
| 3954 | Stream.runHead, |
| 3955 | ); |
| 3956 | expect(releasedDesktopTabs).toEqual([opened[2]]); |
| 3957 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 3958 | expect(sessions.map((session) => session.tabId).toSorted()).toEqual( |
| 3959 | [...opened.filter((tabId) => tabId !== opened[2]), fresh.tabId!].toSorted(), |
| 3960 | ); |
| 3961 | |
| 3962 | // A second open must reclaim a different tab while the first page is unloading. |
| 3963 | const closingPage = desktopConnections[3]!.context.page; |
| 3964 | closingPage.beforeUnload = "listen"; |
| 3965 | closingPage.unloadGate = Promise.withResolvers<void>(); |
| 3966 | const closeRequests = yield* Queue.unbounded<void>(); |
| 3967 | const close = manager.close; |
| 3968 | const closeSpy = vi |
| 3969 | .spyOn(manager, "close") |
| 3970 | .mockImplementation((input) => |
| 3971 | Queue.offer(closeRequests, undefined).pipe(Effect.andThen(close(input))), |
| 3972 | ); |
| 3973 | yield* Effect.addFinalizer(() => Effect.sync(() => closeSpy.mockRestore())); |
| 3974 | const firstOpen = yield* open("agent-concurrent").pipe(Effect.forkScoped); |
| 3975 | yield* Queue.take(closeRequests); |
| 3976 | yield* Effect.promise(() => closingPage.pagehideWatched.promise); |
| 3977 | const secondOpen = yield* open("agent-concurrent").pipe(Effect.forkScoped); |
| 3978 | yield* Queue.take(closeRequests); |
| 3979 | closingPage.unloadGate.resolve(); |
| 3980 | const concurrent = yield* Effect.all([Fiber.join(firstOpen), Fiber.join(secondOpen)]); |
| 3981 | expect(concurrent.every((status) => status.available)).toBe(true); |
| 3982 | const remaining = (yield* manager.list({ threadId: scope.thread.threadId })).sessions; |
| 3983 | expect(remaining).toHaveLength(32); |
| 3984 | const closedBeforeReturn = yield* Deferred.make<void>(); |
| 3985 | const finishClose = yield* Deferred.make<void>(); |
| 3986 | let heldClose = false; |
| 3987 | closeSpy.mockImplementation((input) => { |
| 3988 | const hold = !heldClose; |
| 3989 | heldClose = true; |
| 3990 | return close(input).pipe( |
| 3991 | Effect.andThen( |
| 3992 | hold |
| 3993 | ? Deferred.succeed(closedBeforeReturn, undefined).pipe( |
| 3994 | Effect.andThen(Deferred.await(finishClose)), |
| 3995 | ) |
| 3996 | : Effect.void, |
| 3997 | ), |
| 3998 | ); |
| 3999 | }); |
| 4000 | const reclaimingOpen = yield* open("agent-reclaiming").pipe(Effect.forkScoped); |
| 4001 | yield* Deferred.await(closedBeforeReturn); |
| 4002 | const takingFreedSlot = yield* open("agent-taking-free-slot"); |
| 4003 | expect(takingFreedSlot.available).toBe(true); |
| 4004 | yield* Deferred.succeed(finishClose, undefined); |
| 4005 | expect((yield* Fiber.join(reclaimingOpen)).available).toBe(true); |
| 4006 | expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(32); |
| 4007 | expect(remaining.some((session) => session.tabId === opened[3])).toBe(false); |
| 4008 | expect(remaining.some((session) => session.tabId === opened[4])).toBe(false); |
| 4009 | }), |
| 4010 | ).pipe(Effect.provide(layer)), |
| 4011 | ); |
| 4012 | |
| 4013 | const certificateError = { |
| 4014 | url: "https://device.local/", |
| 4015 | code: -202, |
| 4016 | description: "ERR_CERT_AUTHORITY_INVALID", |
| 4017 | }; |
| 4018 | const dataUrl = `data:text/html,${"PAYLOAD".repeat(300)}`; |
| 4019 | |
| 4020 | it.effect("reports why a page failed to load while the tab shows the error page", () => |
| 4021 | Effect.scoped( |
| 4022 | Effect.gen(function* () { |
| 4023 | const { broker, tabId } = yield* ready; |
| 4024 | const page = contexts[0]!.page; |
| 4025 | const request = { |
| 4026 | url: () => certificateError.url, |
| 4027 | method: () => "GET", |
| 4028 | isNavigationRequest: () => true, |
| 4029 | frame: () => page, |
| 4030 | failure: () => ({ errorText: "net::ERR_CERT_AUTHORITY_INVALID" }), |
| 4031 | }; |
| 4032 | const status = () => |
| 4033 | broker.invoke<PreviewAutomationStatus>({ scope, tabId, operation: "status", input: {} }); |
| 4034 | const snapshot = () => |
| 4035 | broker.invoke<PreviewAutomationSnapshot>({ |
| 4036 | scope, |
| 4037 | tabId, |
| 4038 | operation: "snapshot", |
| 4039 | input: {}, |
| 4040 | }); |
| 4041 | expect(yield* status()).not.toHaveProperty("loadError"); |
| 4042 | expect(yield* snapshot()).not.toHaveProperty("loadError"); |
| 4043 | page.emit("request", request); |
| 4044 | page.emit("requestfailed", request); |
| 4045 | page.url = () => "chrome-error://chromewebdata/"; |
| 4046 | expect(yield* status()).toMatchObject({ |
| 4047 | url: certificateError.url, |
| 4048 | loadError: certificateError, |
| 4049 | }); |
| 4050 | expect(yield* snapshot()).toMatchObject({ |
| 4051 | url: certificateError.url, |
| 4052 | loadError: certificateError, |
| 4053 | }); |
| 4054 | |
| 4055 | const subframeRequest = { |
| 4056 | ...request, |
| 4057 | url: () => "https://frame.local/", |
| 4058 | frame: () => ({}), |
| 4059 | }; |
| 4060 | page.emit("request", subframeRequest); |
| 4061 | page.emit("requestfailed", subframeRequest); |
| 4062 | expect(yield* status()).toMatchObject({ |
| 4063 | url: certificateError.url, |
| 4064 | loadError: certificateError, |
| 4065 | }); |
| 4066 | |
| 4067 | // Clearing must happen before the next navigation replaces the error page. |
| 4068 | page.emit("request", { ...request, url: () => "https://device.local/login" }); |
| 4069 | expect(yield* status()).not.toHaveProperty("loadError"); |
| 4070 | expect(yield* snapshot()).not.toHaveProperty("loadError"); |
| 4071 | |
| 4072 | const dataRequest = { ...request, url: () => dataUrl }; |
| 4073 | page.emit("request", dataRequest); |
| 4074 | page.emit("requestfailed", dataRequest); |
| 4075 | expect((yield* status()).loadError?.url).toBe("data:text/html,…"); |
| 4076 | initialNavigation = async () => { |
| 4077 | page.emit("request", request); |
| 4078 | page.emit("requestfailed", request); |
| 4079 | }; |
| 4080 | const error = yield* broker |
| 4081 | .invoke<PreviewAutomationStatus>({ |
| 4082 | scope, |
| 4083 | tabId, |
| 4084 | operation: "navigate", |
| 4085 | input: { url: certificateError.url }, |
| 4086 | }) |
| 4087 | .pipe(Effect.flip); |
| 4088 | expect(error).toMatchObject({ |
| 4089 | _tag: "PreviewAutomationExecutionError", |
| 4090 | reason: `Navigation to ${certificateError.url} failed: ${certificateError.description}`, |
| 4091 | }); |
| 4092 | }), |
| 4093 | ).pipe(Effect.provide(layer)), |
| 4094 | ); |
| 4095 | |
| 4096 | it.effect("preview_open rejects a desktop navigation that failed before automation attached", () => |
| 4097 | Effect.scoped( |
| 4098 | Effect.gen(function* () { |
| 4099 | const { broker, tabId } = yield* ready; |
| 4100 | const manager = yield* Manager.PreviewManager; |
| 4101 | const channel = yield* DesktopChannel.DesktopBrowserChannel; |
| 4102 | desktopRendersNext = true; |
| 4103 | desktopPageUrl = "chrome-error://chromewebdata/"; |
| 4104 | const failure = { |
| 4105 | ...certificateError, |
| 4106 | url: "https://user:secret@device.local/?token=private#fragment", |
| 4107 | }; |
| 4108 | using _failure = vi.spyOn(channel, "loadFailure").mockReturnValue(failure); |
| 4109 | const error = yield* broker |
| 4110 | .invoke<PreviewAutomationStatus>({ |
| 4111 | scope, |
| 4112 | operation: "open", |
| 4113 | input: { url: failure.url, reuseExistingTab: false, open: false }, |
| 4114 | }) |
| 4115 | .pipe(Effect.flip); |
| 4116 | expect(error).toMatchObject({ |
| 4117 | _tag: "PreviewAutomationExecutionError", |
| 4118 | reason: `Navigation to ${certificateError.url} failed: ${certificateError.description}`, |
| 4119 | }); |
| 4120 | expect(JSON.stringify(error)).not.toMatch(/secret|private|fragment/); |
| 4121 | const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); |
| 4122 | expect(sessions.map((session) => session.tabId)).toEqual([tabId]); |
| 4123 | }), |
| 4124 | ).pipe(Effect.provide(layer)), |
| 4125 | ); |
| 4126 | |
| 4127 | it.effect("reports a desktop tab's load failure from before the server connected", () => |
| 4128 | Effect.scoped( |
| 4129 | Effect.gen(function* () { |
| 4130 | const browser = yield* ServerBrowser.ServerBrowser; |
| 4131 | const broker = yield* Broker.PreviewAutomationBroker; |
| 4132 | const manager = yield* Manager.PreviewManager; |
| 4133 | yield* Effect.yieldNow; |
| 4134 | desktopRendersNext = true; |
| 4135 | const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" }); |
| 4136 | desktopLoadFailures.set(opened.tabId, certificateError); |
| 4137 | yield* browser.attachViewer(viewerInput(opened.tabId, false)); |
| 4138 | const page = desktopConnections[0]!.context.page; |
| 4139 | page.url = () => "chrome-error://chromewebdata/"; |
| 4140 | const status = () => |
| 4141 | broker.invoke<PreviewAutomationStatus>({ |
| 4142 | scope, |
| 4143 | operation: "status", |
| 4144 | input: {}, |
| 4145 | tabId: PreviewTabId.make(opened.tabId), |
| 4146 | }); |
| 4147 | const snapshot = () => |
| 4148 | broker.invoke<PreviewAutomationSnapshot>({ |
| 4149 | scope, |
| 4150 | operation: "snapshot", |
| 4151 | input: {}, |
| 4152 | tabId: PreviewTabId.make(opened.tabId), |
| 4153 | }); |
| 4154 | expect(yield* status()).toMatchObject({ |
| 4155 | url: certificateError.url, |
| 4156 | loadError: certificateError, |
| 4157 | }); |
| 4158 | expect(yield* snapshot()).toMatchObject({ |
| 4159 | url: certificateError.url, |
| 4160 | loadError: certificateError, |
| 4161 | }); |
| 4162 | desktopLoadFailures.set(opened.tabId, { ...certificateError, url: dataUrl }); |
| 4163 | expect((yield* status()).loadError?.url).toBe("data:text/html,…"); |
| 4164 | // A navigation the server sees supersedes it, even before the error page goes. |
| 4165 | page.emit("request", { |
| 4166 | url: () => "https://device.local/retry", |
| 4167 | isNavigationRequest: () => true, |
| 4168 | frame: () => page, |
| 4169 | }); |
| 4170 | expect(yield* status()).not.toHaveProperty("loadError"); |
| 4171 | expect(yield* snapshot()).not.toHaveProperty("loadError"); |
| 4172 | }), |
| 4173 | ).pipe(Effect.provide(layer)), |
| 4174 | ); |
| 4175 | |
| 4176 | it.effect("a popup opens in its opener's appearance", () => |
| 4177 | Effect.scoped( |
| 4178 | Effect.gen(function* () { |
| 4179 | const browser = yield* ServerBrowser.ServerBrowser; |
| 4180 | const manager = yield* Manager.PreviewManager; |
| 4181 | yield* Effect.yieldNow; |
| 4182 | const opened = yield* manager.open({ |
| 4183 | threadId: scope.thread.threadId, |
| 4184 | runtime: "server", |
| 4185 | colorScheme: "dark", |
| 4186 | }); |
| 4187 | yield* browser.attachViewer(viewerInput(opened.tabId, true)); |
| 4188 | const events = yield* manager.subscribeEvents; |
| 4189 | contexts[0]!.page.emit("popup", makeContext().page); |
| 4190 | let event = yield* PubSub.take(events); |
| 4191 | while (event.type !== "opened") event = yield* PubSub.take(events); |
| 4192 | expect(event.snapshot.colorScheme).toBe("dark"); |
| 4193 | }), |
| 4194 | ).pipe(Effect.provide(layer)), |
| 4195 | ); |
| 4196 | |
| 4197 | it.live("a page's title change without navigation reaches its session", () => |
| 4198 | Effect.gen(function* () { |
| 4199 | const native = yield* Effect.acquireRelease( |
| 4200 | Effect.promise(() => chromium.launch({ headless: true })), |
| 4201 | (browser) => Effect.promise(() => browser.close()), |
| 4202 | ); |
| 4203 | const context = yield* Effect.promise(() => native.newContext()); |
| 4204 | yield* Effect.promise(() => |
| 4205 | context.route("**/*", (route) => |
| 4206 | route.fulfill({ contentType: "text/html", body: "<title>Original</title>" }), |
| 4207 | ), |
| 4208 | ); |
| 4209 | let watched = Promise.withResolvers<void>(); |
| 4210 | const newSession = context.newCDPSession.bind(context); |
| 4211 | vi.spyOn(context, "newCDPSession").mockImplementation(async (page) => { |
| 4212 | const cdp = await newSession(page); |
| 4213 | const send = cdp.send.bind(cdp); |
| 4214 | vi.spyOn(cdp, "send").mockImplementation((...args) => { |
| 4215 | const result = send(...args); |
| 4216 | if ( |
| 4217 | args[0] === "Runtime.evaluate" && |
| 4218 | args[1] && |
| 4219 | "awaitPromise" in args[1] && |
| 4220 | args[1].awaitPromise |
| 4221 | ) { |
| 4222 | void send("Runtime.evaluate", { expression: "0" }).then( |
| 4223 | () => watched.resolve(), |
| 4224 | // The browser can close while the last probe is pending. |
| 4225 | () => undefined, |
| 4226 | ); |
| 4227 | } |
| 4228 | return result; |
| 4229 | }); |
| 4230 | return cdp; |
| 4231 | }); |
| 4232 | realContextOverride = context; |
| 4233 | yield* Effect.gen(function* () { |
| 4234 | yield* ServerBrowser.ServerBrowser; |
| 4235 | const manager = yield* Manager.PreviewManager; |
| 4236 | const events = yield* manager.subscribeEvents; |
| 4237 | yield* manager.open({ |
| 4238 | threadId: testThread.threadId, |
| 4239 | runtime: "server", |
| 4240 | url: "https://fixture.test/", |
| 4241 | }); |
| 4242 | const successes: Array<{ title: string; url: string; back: boolean; forward: boolean }> = []; |
| 4243 | const navigatedTo = Effect.fn(function* (title: string) { |
| 4244 | for (;;) { |
| 4245 | const event = yield* PubSub.take(events); |
| 4246 | if (event.type !== "navigated") continue; |
| 4247 | const { navStatus } = event.snapshot; |
| 4248 | if (navStatus._tag === "Success") { |
| 4249 | successes.push({ |
| 4250 | title: navStatus.title, |
| 4251 | url: navStatus.url, |
| 4252 | back: event.snapshot.canGoBack, |
| 4253 | forward: event.snapshot.canGoForward, |
| 4254 | }); |
| 4255 | if (navStatus.title === title) return navStatus; |
| 4256 | } |
| 4257 | } |
| 4258 | }); |
| 4259 | expect((yield* navigatedTo("Original"))._tag).toBe("Success"); |
| 4260 | const page = context.pages()[0]!; |
| 4261 | yield* Effect.promise(() => watched.promise); |
| 4262 | watched = Promise.withResolvers<void>(); |
| 4263 | yield* Effect.promise(() => |
| 4264 | page.evaluate("document.head.replaceWith(document.head.cloneNode(true))"), |
| 4265 | ); |
| 4266 | for (const title of ["Replaced", "Updated", "Final"]) { |
| 4267 | if (title === "Final") |
| 4268 | yield* Effect.promise(() => |
| 4269 | page.evaluate( |
| 4270 | "document.documentElement.replaceWith(document.documentElement.cloneNode(true))", |
| 4271 | ), |
| 4272 | ); |
| 4273 | yield* Effect.promise(() => |
| 4274 | page.evaluate( |
| 4275 | `document.title = ${JSON.stringify(title)}; ${title === "Updated" ? "history.pushState({}, '', '/next')" : ""}`, |
| 4276 | ), |
| 4277 | ); |
| 4278 | expect(yield* navigatedTo(title)).toEqual({ |
| 4279 | _tag: "Success", |
| 4280 | url: title === "Replaced" ? "https://fixture.test/" : "https://fixture.test/next", |
| 4281 | title, |
| 4282 | }); |
| 4283 | yield* Effect.promise(() => watched.promise); |
| 4284 | watched = Promise.withResolvers<void>(); |
| 4285 | } |
| 4286 | expect(successes.filter(({ title }) => title === "Updated")).toEqual([ |
| 4287 | { title: "Updated", url: "https://fixture.test/next", back: true, forward: false }, |
| 4288 | ]); |
| 4289 | yield* Effect.promise(() => |
| 4290 | context.route("**/drawing.svg", (route) => |
| 4291 | route.fulfill({ |
| 4292 | contentType: "image/svg+xml", |
| 4293 | body: '<svg xmlns="http://www.w3.org/2000/svg"><title>Drawing</title></svg>', |
| 4294 | }), |
| 4295 | ), |
| 4296 | ); |
| 4297 | yield* Effect.promise(() => page.goto("https://fixture.test/drawing.svg")); |
| 4298 | yield* navigatedTo("Drawing"); |
| 4299 | yield* Effect.promise(() => watched.promise); |
| 4300 | yield* Effect.promise(() => |
| 4301 | page.evaluate("document.querySelector('title').textContent = 'Renamed drawing'"), |
| 4302 | ); |
| 4303 | expect(yield* navigatedTo("Renamed drawing")).toEqual({ |
| 4304 | _tag: "Success", |
| 4305 | url: "https://fixture.test/drawing.svg", |
| 4306 | title: "Renamed drawing", |
| 4307 | }); |
| 4308 | }).pipe(Effect.provide(layer)); |
| 4309 | }).pipe(Effect.scoped), |
| 4310 | ); |