The best way to control Claude Code, Codex and more from any computer or phone
fix(server): keep browser input responsive during slow navigation (#16691)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Joseph Vidal committed
Oct 19, 2026 at 00:52 UTC
a946febd6781e175005dd97f41f48848afaf7741
3 files changed
+130
-47
apps/server/src/preview/ServerBrowser.test.ts
+102
-36
@@ -12,12 +12,14 @@ import {
12
} from "@t3tools/contracts";
13
import * as Clock from "effect/Clock";
14
import * as Effect from "effect/Effect";
15
+import * as Exit from "effect/Exit";
16
import * as Fiber from "effect/Fiber";
17
import * as FileSystem from "effect/FileSystem";
18
import * as Layer from "effect/Layer";
19
import * as Option from "effect/Option";
20
import * as PubSub from "effect/PubSub";
21
import * as Queue from "effect/Queue";
22
+import * as Scope from "effect/Scope";
23
import * as Stream from "effect/Stream";
24
import type { BrowserContext, Page } from "playwright-core";
25
import { beforeEach, expect, vi } from "vite-plus/test";
@@ -473,56 +475,120 @@ it.live("readiness none responds immediately but takeover input waits for naviga
475
);
476
477
it.live.each([
476
- { method: "goto" as const, message: { type: "navigate", url: "http://localhost:5173/next" } },
478
+ {
479
+ method: "goto" as const,
480
+ message: { type: "navigate", url: "http://localhost:5173/next" },
481
+ handoff: "release",
482
+ },
483
+ { method: "goBack" as const, message: { type: "history", delta: -1 }, handoff: "release" },
484
+ { method: "goForward" as const, message: { type: "history", delta: 1 }, handoff: "release" },
485
+ { method: "reload" as const, message: { type: "reload" }, handoff: "release" },
486
+ {
487
+ method: "goto" as const,
488
+ message: { type: "navigate", url: "http://localhost:5173/next" },
489
+ handoff: "disconnect",
490
+ },
491
+])(
492
+ "$handoff waits for viewer $method to commit before agent actions",
493
+ ({ method, message, handoff }) =>
494
+ Effect.scoped(
495
+ Effect.gen(function* () {
496
+ const { browser, broker, tabId } = yield* ready;
497
+ const viewerScope = yield* Scope.make();
498
+ yield* Effect.addFinalizer(() => Scope.close(viewerScope, Exit.void));
499
+ const viewer = yield* browser
500
+ .attachViewer(viewerInput(tabId, true))
501
+ .pipe(Effect.provideService(Scope.Scope, viewerScope));
502
+ yield* viewer.input({ type: "takeControl" });
503
+ const started = Promise.withResolvers<void>();
504
+ const committed = Promise.withResolvers<void>();
505
+ const events: string[] = [];
506
+ contexts[0]!.page[method].mockImplementationOnce(async () => {
507
+ started.resolve();
508
+ await committed.promise;
509
+ events.push("navigation committed");
510
+ });
511
+ const navigate = yield* viewer.input(message).pipe(Effect.forkScoped);
512
+ yield* Effect.promise(() => started.promise);
513
+ const releasing = yield* (
514
+ handoff === "disconnect"
515
+ ? Scope.close(viewerScope, Exit.void)
516
+ : viewer.input({ type: "releaseControl" })
517
+ ).pipe(Effect.forkScoped);
518
+ yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
519
+ // Drain runnable promise work while the navigation gate remains closed.
520
+ yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
521
+ const status = yield* broker.invoke<PreviewAutomationStatus>({
522
+ scope,
523
+ tabId,
524
+ operation: "status",
525
+ input: {},
526
+ });
527
+ expect(status.control?.owner).toBe("agent");
528
+ const cdp = contexts[0]!.sessions[0]!;
529
+ const send = cdp.send.getMockImplementation()!;
530
+ cdp.send.mockImplementation(async (operation, input) => {
531
+ if (operation === "Runtime.evaluate") events.push("agent acted");
532
+ return send(operation, input);
533
+ });
534
+ const resumed = yield* broker
535
+ .invoke({
536
+ scope,
537
+ tabId,
538
+ operation: "evaluate",
539
+ input: { expression: "resumed()" },
540
+ })
541
+ .pipe(Effect.forkScoped);
542
+ yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
543
+ expect(events).toEqual([]);
544
+ committed.resolve();
545
+ yield* Fiber.join(navigate);
546
+ yield* Fiber.join(releasing);
547
+ yield* Fiber.join(resumed);
548
+ expect(events).toEqual(["navigation committed", "agent acted"]);
549
+ const calls = contexts[0]!.page[method].mock.calls;
550
+ expect(calls[0]?.at(-1)).toMatchObject({ waitUntil: "commit", timeout: 15_000 });
551
+ }),
552
+ ).pipe(Effect.provide(layer)),
553
+);
554
+
555
+it.live.each([
556
+ { method: "goto" as const, message: { type: "navigate", url: "http://10.255.255.1/" } },
557
{ method: "goBack" as const, message: { type: "history", delta: -1 } },
558
{ method: "goForward" as const, message: { type: "history", delta: 1 } },
559
{ method: "reload" as const, message: { type: "reload" } },
480
-])("release waits for viewer $method to commit before agent actions", ({ method, message }) =>
560
+])("a pending viewer $method allows a corrected URL and text input", ({ method, message }) =>
561
Effect.scoped(
562
Effect.gen(function* () {
483
- const { browser, broker, tabId } = yield* ready;
563
+ const { browser, tabId } = yield* ready;
564
const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
565
yield* viewer.input({ type: "takeControl" });
486
- yield* Queue.clear(viewer.output);
566
const started = Promise.withResolvers<void>();
567
const committed = Promise.withResolvers<void>();
489
- const events: string[] = [];
490
- contexts[0]!.page[method].mockImplementationOnce(async () => {
568
+ const page = contexts[0]!.page;
569
+ page[method].mockImplementationOnce(() => {
570
started.resolve();
492
- await committed.promise;
493
- events.push("navigation committed");
571
+ return committed.promise;
572
});
495
- const navigate = yield* viewer.input(message).pipe(Effect.forkScoped);
496
- yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
573
+ const navigation = yield* viewer.input(message).pipe(Effect.forkScoped);
574
yield* Effect.promise(() => started.promise);
498
- const releasing = yield* viewer.input({ type: "releaseControl" }).pipe(Effect.forkScoped);
499
- let control = yield* Queue.take(viewer.output);
500
- while (control._tag !== "control" || control.controller !== "agent") {
501
- control = yield* Queue.take(viewer.output);
502
- }
503
- const cdp = contexts[0]!.sessions[0]!;
504
- const send = cdp.send.getMockImplementation()!;
505
- cdp.send.mockImplementation(async (operation, input) => {
506
- if (operation === "Runtime.evaluate") events.push("agent acted");
507
- return send(operation, input);
575
+ const correction = yield* Effect.gen(function* () {
576
+ yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" });
577
+ yield* viewer.input({ type: "text", text: "hello" });
578
+ }).pipe(Effect.forkScoped);
579
+ yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
580
+ // Check after runnable promises drain, without waiting for navigation or a timeout.
581
+ yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
582
+ expect(page.goto).toHaveBeenLastCalledWith(
583
+ "http://localhost:5173/fixed",
584
+ expect.objectContaining({ waitUntil: "commit" }),
585
+ );
586
+ expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
587
+ text: "hello",
588
});
509
- const resumed = yield* broker
510
- .invoke({
511
- scope,
512
- tabId,
513
- operation: "evaluate",
514
- input: { expression: "resumed()" },
515
- })
516
- .pipe(Effect.forkScoped);
517
- yield* broker.invoke({ scope, tabId, operation: "status", input: {} });
518
- expect(events).toEqual([]);
589
committed.resolve();
520
- yield* Fiber.join(navigate);
521
- yield* Fiber.join(releasing);
522
- yield* Fiber.join(resumed);
523
- expect(events).toEqual(["navigation committed", "agent acted"]);
524
- const calls = contexts[0]!.page[method].mock.calls;
525
- expect(calls[0]?.at(-1)).toMatchObject({ waitUntil: "commit", timeout: 15_000 });
590
+ yield* Fiber.join(navigation);
591
+ yield* Fiber.join(correction);
592
}),
593
).pipe(Effect.provide(layer)),
594
);
apps/server/src/preview/ServerBrowser.ts
+8
-5
@@ -2177,23 +2177,26 @@ const make = Effect.gen(function* () {
2177
await applySetting(tab, setting);
2178
return;
2179
}
2180
+ // A stalled navigation must not block a corrected URL or further viewer input.
2181
case "navigate":
2182
if (typeof message.url === "string") {
2183
const url = normalizePreviewUrl(message.url);
2183
- await tab.page.goto(url, VIEWER_NAVIGATION_OPTIONS);
2184
+ tab.control.trackUntilHandoff(tab.page.goto(url, VIEWER_NAVIGATION_OPTIONS));
2185
}
2186
return;
2187
case "history":
2187
- await (num(message.delta) < 0
2188
- ? tab.page.goBack(VIEWER_NAVIGATION_OPTIONS)
2189
- : tab.page.goForward(VIEWER_NAVIGATION_OPTIONS));
2188
+ tab.control.trackUntilHandoff(
2189
+ num(message.delta) < 0
2190
+ ? tab.page.goBack(VIEWER_NAVIGATION_OPTIONS)
2191
+ : tab.page.goForward(VIEWER_NAVIGATION_OPTIONS),
2192
+ );
2193
return;
2194
case "reload":
2195
if (message.ignoreCache === true) {
2196
await session.send("Page.reload", { ignoreCache: true });
2197
return;
2198
}
2196
- await tab.page.reload(VIEWER_NAVIGATION_OPTIONS);
2199
+ tab.control.trackUntilHandoff(tab.page.reload(VIEWER_NAVIGATION_OPTIONS));
2200
return;
2201
case "probe": {
2202
const x = num(message.x);
apps/server/src/preview/SessionControl.ts
+20
-6
@@ -11,12 +11,19 @@ export class BrowserControlInterrupted extends Error {
11
}
12
}
13
14
+const settle = (work: Promise<unknown>) =>
15
+ work.then(
16
+ () => undefined,
17
+ () => undefined,
18
+ );
19
+
20
/** Reserves control immediately, but drains running work before the new owner can act. */
21
export class SessionControl {
22
readonly agentId: string | null;
23
private readonly onGenerationChange: () => void;
24
private tail: Promise<unknown> = Promise.resolve();
25
private pending: Promise<void> = Promise.resolve();
26
+ private readonly handoff = new Set<Promise<void>>();
27
private owner: string | null = null;
28
private epoch = 0;
29
private closed = false;
@@ -45,11 +52,15 @@ export class SessionControl {
52
53
/** An action can respond before its navigation commits, while later actions still wait. */
54
track(work: Promise<unknown>) {
48
- const settled = work.then(
49
- () => undefined,
50
- () => undefined,
51
- );
52
- this.pending = Promise.all([this.pending, settled]).then(() => undefined);
55
+ this.pending = Promise.all([this.pending, settle(work)]).then(() => undefined);
56
+ }
57
+
58
+ /** Viewer input stays responsive, but control handoffs still drain its navigations. */
59
+ trackUntilHandoff(work: Promise<unknown>) {
60
+ const settled = settle(work).finally(() => {
61
+ this.handoff.delete(settled);
62
+ });
63
+ this.handoff.add(settled);
64
}
65
66
private assertOpen() {
@@ -131,7 +142,10 @@ export class SessionControl {
142
);
143
}
144
this.changeOwner(null);
134
- await this.enqueue(afterDrain);
145
+ await this.enqueue(async () => {
146
+ await Promise.all(this.handoff);
147
+ await afterDrain();
148
+ });
149
}
150
151
async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {