TypeScript
fix(server): queued preview actions no longer start after their deadline, except recording stop (#16941)
Jesse van Dijk8f947a313b29
diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.tsindex 961ea352c7c..a119327bf16 100644--- a/apps/server/src/preview/ServerBrowser.test.ts+++ b/apps/server/src/preview/ServerBrowser.test.ts@@ -23,6 +23,7 @@ import * as PubSub from "effect/PubSub";import * as Queue from "effect/Queue";import * as Scope from "effect/Scope";import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";import type { BrowserContext, Page } from "playwright-core";import { beforeEach, expect, vi } from "vite-plus/test";@@ -32,6 +33,7 @@ import * as Broker from "../mcp/PreviewAutomationBroker.ts";import * as DesktopChannel from "./DesktopBrowserChannel.ts";import * as Manager from "./Manager.ts";import * as ServerBrowser from "./ServerBrowser.ts";+import * as ServerBrowserContexts from "./ServerBrowserContexts.ts";import * as PreviewBrowser from "./PreviewBrowser.ts";vi.mock("./ServerBrowserContexts.ts", () => ({@@ -152,6 +154,9 @@ function makeContext(onClose?: (context: BrowserContext) => void) {goto: vi.fn(async (next: string) => {url = next;events.emit("load");+ const pending = initialNavigation;+ initialNavigation = null;+ await pending?.();}),goBack: vi.fn(async () => {}),goForward: vi.fn(async () => {}),@@ -206,6 +211,7 @@ let pageCopy = "";let keyCopy = "";let focusedFrame: ReturnType<typeof makeFrame> | null = null;let contextFailure: Error | null = null;+let initialNavigation: (() => Promise<void>) | null = null;let desktopRendersNext = false;const desktopDetaches = new NodeEvents.EventEmitter();const desktopTabs = new Set<string>();@@ -316,6 +322,7 @@ beforeEach(() => {contextRequests.length = 0;contextGate = null;contextFailure = null;+ initialNavigation = null;pageCopy = "";keyCopy = "";focusedFrame = null;@@ -325,6 +332,71 @@ beforeEach(() => {desktopConnections.length = 0;});+it.live("an expired open still drains its initial navigation before human input", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const browser = yield* ServerBrowser.ServerBrowser;+ const broker = yield* Broker.PreviewAutomationBroker;+ const manager = yield* Manager.PreviewManager;+ yield* Effect.yieldNow;+ const committed = Promise.withResolvers<void>();+ const events: string[] = [];+ const clock = vi.spyOn(performance, "now").mockReturnValue(0);+ yield* Effect.addFinalizer(() => Effect.sync(() => clock.mockRestore()));+ yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));+ const original = ServerBrowserContexts.ServerBrowserContexts.prototype.contextFor;+ const create = vi+ .spyOn(ServerBrowserContexts.ServerBrowserContexts.prototype, "contextFor")+ .mockImplementation(async function (+ this: ServerBrowserContexts.ServerBrowserContexts,+ profileId,+ isolationKey,+ ) {+ const context = await original.call(this, profileId, isolationKey);+ contexts.at(-1)!.page.goto.mockImplementationOnce(async () => {+ clock.mockReturnValue(1000);+ await committed.promise;+ events.push("navigation committed");+ });+ return context;+ });+ yield* Effect.addFinalizer(() => Effect.sync(() => create.mockRestore()));+ const expired = yield* broker+ .invoke<PreviewAutomationStatus>({+ scope,+ operation: "open",+ input: { url: "http://localhost:5173/slow", reuseExistingTab: false, show: false },+ timeoutMs: 1000,+ })+ .pipe(Effect.flip);+ expect(expired).toMatchObject({ _tag: "PreviewAutomationTimeoutError" });+ const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });+ expect(sessions).toHaveLength(1);+ const tabId = PreviewTabId.make(sessions[0]!.tabId);+ const viewer = yield* browser.attachViewer(viewerInput(tabId, true));+ yield* Queue.clear(viewer.output);+ const takeover = yield* viewer.input({ type: "takeControl" }).pipe(Effect.forkScoped);+ let control = yield* Queue.take(viewer.output);+ while (control._tag !== "control" || control.controller !== "you") {+ control = yield* Queue.take(viewer.output);+ }+ const cdp = contexts[0]!.sessions.at(-1)!;+ const send = cdp.send.getMockImplementation()!;+ cdp.send.mockImplementation(async (operation, input) => {+ if (operation === "Input.insertText") events.push("human typed");+ return send(operation, input);+ });+ const typing = yield* viewer.input({ type: "text", text: "hello" }).pipe(Effect.forkScoped);+ yield* broker.invoke({ scope, tabId, operation: "status", input: {} });+ expect(events).toEqual([]);+ committed.resolve();+ yield* Fiber.join(takeover);+ yield* Fiber.join(typing);+ expect(events).toEqual(["navigation committed", "human typed"]);+ }),+ ).pipe(Effect.provide(layer)),+);+it.live.each(["desktop" as const, undefined])("explicit desktop targets ($0 runtime) fail without creating a server tab",(runtime) =>@@ -595,6 +667,193 @@ it.live.each([).pipe(Effect.provide(layer)),);+it.live("a user-opened tab allows a corrected URL before its initial navigation commits", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const { browser } = yield* ready;+ const manager = yield* Manager.PreviewManager;+ yield* Effect.yieldNow;+ const started = Promise.withResolvers<void>();+ const committed = Promise.withResolvers<void>();+ yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));+ initialNavigation = () => {+ started.resolve();+ return committed.promise;+ };+ const opened = yield* manager.open({+ threadId: scope.thread.threadId,+ url: "http://localhost:5173/stalled",+ runtime: "server",+ });+ yield* Effect.promise(() => started.promise);+ const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, true));+ const correction = yield* viewer+ .input({ type: "navigate", url: "http://localhost:5173/fixed" })+ .pipe(Effect.forkScoped);+ yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));+ const lastNavigationBeforeCommit = contexts[1]!.page.goto.mock.calls.at(-1);+ committed.resolve();+ yield* Fiber.join(correction);+ expect(lastNavigationBeforeCommit).toEqual([+ "http://localhost:5173/fixed",+ expect.objectContaining({ waitUntil: "commit" }),+ ]);+ }),+ ).pipe(Effect.provide(layer)),+);++it.live("an expired queued click never reaches the page", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const { broker, tabId } = yield* ready;+ const page = contexts[0]!.page;+ const started = Promise.withResolvers<void>();+ const release = Promise.withResolvers<Awaited<ReturnType<typeof page.evaluate>>>();+ const metadata = {+ url: "about:blank",+ title: "test page",+ loading: false,+ visibleText: "",+ interactiveElements: [],+ };+ yield* Effect.addFinalizer(() => Effect.sync(() => release.resolve(metadata)));+ page.evaluate.mockImplementationOnce(async () => {+ started.resolve();+ return release.promise;+ });+ const click = vi.fn(async () => {});+ page.locator.mockReturnValue({+ scrollIntoViewIfNeeded: async () => {},+ boundingBox: async () => ({ x: 0, y: 0, width: 10, height: 10 }),+ click,+ } as never);+ let now = performance.now();+ const clock = vi.spyOn(performance, "now").mockImplementation(() => now);+ yield* Effect.addFinalizer(() => Effect.sync(() => clock.mockRestore()));+ const snapshot = yield* broker+ .invoke<PreviewAutomationSnapshot>({+ scope,+ tabId,+ operation: "snapshot",+ input: {},+ timeoutMs: 5000,+ })+ .pipe(Effect.forkScoped);+ yield* Effect.promise(() => started.promise);+ const action = yield* broker+ .invoke<void>({+ scope,+ tabId,+ operation: "click",+ input: { selector: "button" },+ timeoutMs: 1000,+ })+ .pipe(Effect.exit, Effect.forkScoped);+ // The later status reply marks delivery through the same request stream.+ yield* broker.invoke({ scope, tabId, operation: "status", input: {} });+ now += 1000;+ release.resolve(metadata);+ yield* Fiber.join(snapshot);+ const result = yield* Fiber.join(action);+ expect(click).not.toHaveBeenCalled();+ const error = yield* Effect.flip(result);+ expect(error).toMatchObject({+ _tag: "PreviewAutomationTimeoutError",+ remoteTag: "PreviewAutomationTimeoutError",+ });+ }),+ ).pipe(Effect.provide(layer)),+);++it.effect(+ "a queued recording stop still runs after its deadline when a snapshot caller times out",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ const { broker, tabId } = yield* ready;+ const page = contexts[0]!.page;+ const encoder = {+ evaluate: vi+ .fn()+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce({ mimeType: "video/webm", count: 1, bytes: 5 })+ .mockResolvedValueOnce("ZnJhbWU="),+ close: vi.fn(async () => {}),+ };+ const scratchPage = vi+ .spyOn(ServerBrowserContexts.ServerBrowserContexts.prototype, "scratchPage")+ .mockResolvedValue(encoder as unknown as Page);+ yield* Effect.addFinalizer(() => Effect.sync(() => scratchPage.mockRestore()));+ const recording = yield* broker.invoke({+ scope,+ tabId,+ operation: "recordingStart",+ input: {},+ });+ expect(recording).toMatchObject({ recording: true });+ const session = contexts[0]!.sessions.at(-1)!;+ expect(session.send).toHaveBeenCalledWith("Page.startScreencast", expect.anything());++ const started = Promise.withResolvers<void>();+ const release = Promise.withResolvers<Awaited<ReturnType<typeof page.evaluate>>>();+ const metadata = {+ url: "about:blank",+ title: "test page",+ loading: false,+ visibleText: "",+ interactiveElements: [],+ };+ yield* Effect.addFinalizer(() => Effect.sync(() => release.resolve(metadata)));+ page.evaluate.mockImplementationOnce(async () => {+ started.resolve();+ return release.promise;+ });+ let now = performance.now();+ const clock = vi.spyOn(performance, "now").mockImplementation(() => now);+ yield* Effect.addFinalizer(() => Effect.sync(() => clock.mockRestore()));+ const snapshot = yield* broker+ .invoke<PreviewAutomationSnapshot>({+ scope,+ tabId,+ operation: "snapshot",+ input: {},+ timeoutMs: 150,+ updateCurrentTab: false,+ })+ .pipe(Effect.flip, Effect.forkScoped);+ yield* Effect.promise(() => started.promise);+ const stop = yield* broker+ .invoke<void>({+ scope,+ tabId,+ operation: "recordingStop",+ input: {},+ timeoutMs: 1000,+ })+ .pipe(Effect.exit, Effect.forkScoped);+ // The status reply marks delivery while the snapshot still holds the tab queue.+ yield* broker.invoke({ scope, tabId, operation: "status", input: {} });+ yield* TestClock.adjust(150);+ expect(yield* Fiber.join(snapshot)).toMatchObject({+ _tag: "PreviewAutomationTimeoutError",+ });+ now += 1000;+ expect(session.detach).not.toHaveBeenCalled();+ release.resolve(metadata);+ yield* yield* Fiber.join(stop);+ expect(session.detach).toHaveBeenCalledOnce();+ const stopped = yield* broker+ .invoke<void>({ scope, tabId, operation: "recordingStop", input: {} })+ .pipe(Effect.flip);+ expect(stopped).toMatchObject({+ _tag: "PreviewAutomationExecutionError",+ cause: { _tag: "PreviewAutomationRecordingNotActiveError" },+ });+ }),+ ).pipe(Effect.provide(layer)),+);+it.live("enforces provider ownership and explicit targets when a session has multiple tabs", () =>Effect.scoped(Effect.gen(function* () {diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.tsindex d9626784c32..3537f201b25 100644--- a/apps/server/src/preview/ServerBrowser.ts+++ b/apps/server/src/preview/ServerBrowser.ts@@ -899,7 +899,8 @@ const make = Effect.gen(function* () {: page.goto(snapshot.navStatus.url, options)).then(constVoid);- void tab.initialNavigation.catch(constVoid);+ if (tab.control.agentId !== null) tab.control.track(tab.initialNavigation);+ else void tab.initialNavigation.catch(constVoid);}return tab;};@@ -1704,7 +1705,10 @@ const make = Effect.gen(function* () {}};- const runOperation = async (request: PreviewAutomationRequest): Promise<unknown> => {+ const runOperation = async (+ request: PreviewAutomationRequest,+ deadlineMs: number,+ ): Promise<unknown> => {const input = request.input;switch (request.operation) {case "status":@@ -1790,34 +1794,38 @@ const make = Effect.gen(function* () {"A browser dialog is pending. Read preview_status and use preview_dialog first.","dialogPending",);- return tab.control.agent(request.agentSessionId, async () => {- if (tab.dialog)- throw new BrowserControlInterrupted(- "A browser dialog is pending. Read preview_status and use preview_dialog first.",- "dialogPending",- );- if (existing) {- if (url) await navigate(tab, url, "load", navigationTimeout);- } else {- await tab.initialNavigation;- }- const reveal = open.open ?? open.show;- if (reveal !== false) {- await Effect.runPromise(- manager.requestReveal({- threadId: tab.threadId,- tabId: tab.tabId,- force: reveal === true,- }),- );- }- if (!existing && url) {- await tab.page- .waitForLoadState("load", { timeout: navigationTimeout })- .catch(constVoid);- }- return statusWithTitle(tab, request.agentSessionId);- });+ return tab.control.agent(+ request.agentSessionId,+ async () => {+ if (tab.dialog)+ throw new BrowserControlInterrupted(+ "A browser dialog is pending. Read preview_status and use preview_dialog first.",+ "dialogPending",+ );+ if (existing) {+ if (url) await navigate(tab, url, "load", navigationTimeout);+ } else {+ await tab.initialNavigation;+ }+ const reveal = open.open ?? open.show;+ if (reveal !== false) {+ await Effect.runPromise(+ manager.requestReveal({+ threadId: tab.threadId,+ tabId: tab.tabId,+ force: reveal === true,+ }),+ );+ }+ if (!existing && url) {+ await tab.page+ .waitForLoadState("load", { timeout: navigationTimeout })+ .catch(constVoid);+ }+ return statusWithTitle(tab, request.agentSessionId);+ },+ deadlineMs,+ );}case "recordingStop": {if (@@ -1849,6 +1857,8 @@ const make = Effect.gen(function* () {"No recording is active for this thread.",);}+ // A stop cannot act twice (a retry finds no recording);+ // dropping a late one would leave capture running.return tab.control.agent(request.agentSessionId ?? "", () => stopRecording(tab));}}@@ -1891,23 +1901,27 @@ const make = Effect.gen(function* () {return executeTabOperation(tab, request);});}- return tab.control.agent(agentSessionId, async () => {- if (tab.dialog)- throw new BrowserControlInterrupted(- "A browser dialog is pending. Read preview_status and use preview_dialog first.",- "dialogPending",- );- const generation = tab.control.generation;- tab.agentOperating = !READ_OPERATIONS.has(request.operation);- updateFileChooserInterception(tab);- try {- return await executeTabOperation(tab, request);- } finally {- tab.agentOperating = false;+ return tab.control.agent(+ agentSessionId,+ async () => {+ if (tab.dialog)+ throw new BrowserControlInterrupted(+ "A browser dialog is pending. Read preview_status and use preview_dialog first.",+ "dialogPending",+ );+ const generation = tab.control.generation;+ tab.agentOperating = !READ_OPERATIONS.has(request.operation);updateFileChooserInterception(tab);- if (generation !== tab.control.generation) ServerBrowserPage.invalidateRefs(tab.page);- }- });+ try {+ return await executeTabOperation(tab, request);+ } finally {+ tab.agentOperating = false;+ updateFileChooserInterception(tab);+ if (generation !== tab.control.generation) ServerBrowserPage.invalidateRefs(tab.page);+ }+ },+ deadlineMs,+ );};const executeTabOperation = async (tab: ServerTab, request: PreviewAutomationRequest) => {@@ -2002,7 +2016,10 @@ const make = Effect.gen(function* () {const handleRequest = (connectionId: string, request: PreviewAutomationRequest) =>Effect.tryPromise({- try: () => runOperation(request).finally(() => markUsed(request)),+ try: () =>+ runOperation(request, performance.now() + request.timeoutMs).finally(() =>+ markUsed(request),+ ),catch: ServerBrowserPage.toOperationError,}).pipe(Effect.match({diff --git a/apps/server/src/preview/SessionControl.test.ts b/apps/server/src/preview/SessionControl.test.tsindex 42eabc212ac..b9cd7f66710 100644--- a/apps/server/src/preview/SessionControl.test.ts+++ b/apps/server/src/preview/SessionControl.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vite-plus/test";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";@@ -179,3 +179,37 @@ describe("SessionControl", () => {await expect(control.agent("agent-b", async () => "acted")).resolves.toBe("acted");});});++describe("request deadlines at dispatch", () => {+ afterEach(() => vi.restoreAllMocks());++ it("finishes running work, skips expired queued actions, and accepts fresh work", async () => {+ let now = 0;+ vi.spyOn(performance, "now").mockImplementation(() => now);+ const control = new SessionControl("agent");+ const started = Promise.withResolvers<void>();+ const finish = Promise.withResolvers<void>();+ const events: string[] = [];+ const running = control.agent(+ "agent",+ async () => {+ events.push("started");+ started.resolve();+ await finish.promise;+ events.push("finished");+ },+ 100,+ );+ await started.promise;+ const expired = expect(+ control.agent("agent", async () => events.push("expired"), 100),+ ).rejects.toMatchObject({ name: "TimeoutError" });+ const next = control.agent("agent", async () => events.push("next"), 200);+ // No timer fires: expiry must be checked when the queue resumes.+ now = 100;+ expect(events).toEqual(["started"]);+ finish.resolve();+ await Promise.all([running, expired, next]);+ expect(events).toEqual(["started", "finished", "next"]);+ });+});diff --git a/apps/server/src/preview/SessionControl.ts b/apps/server/src/preview/SessionControl.tsindex 690d42166ab..cee60e2f953 100644--- a/apps/server/src/preview/SessionControl.ts+++ b/apps/server/src/preview/SessionControl.ts@@ -73,13 +73,19 @@ export class SessionControl {this.onGenerationChange();}- private async action<A>(allowed: () => boolean, run: () => Promise<A>) {+ private async action<A>(allowed: () => boolean, run: () => Promise<A>, deadlineMs?: number) {this.assertOpen();if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab.");const epoch = this.epoch;return this.enqueue(async () => {this.assertOpen();if (epoch !== this.epoch || !allowed()) throw new BrowserControlInterrupted();+ if (deadlineMs !== undefined && performance.now() >= deadlineMs) {+ throw new DOMException(+ "This browser request expired before it could start.",+ "TimeoutError",+ );+ }return run();});}@@ -88,7 +94,7 @@ export class SessionControl {return this.agentId === null || this.agentId === agentId;}- agent<A>(agentId: string, run: () => Promise<A>) {+ agent<A>(agentId: string, run: () => Promise<A>, deadlineMs?: number) {if (!this.agentMayAct(agentId))return Promise.reject(new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),@@ -97,7 +103,7 @@ export class SessionControl {return Promise.reject(new BrowserControlInterrupted("A human controls this tab.", "humanControl"),);- return this.action(() => this.agentMayAct(agentId) && this.owner === null, run);+ return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs);}agentCanActNow(agentId: string) {