Skip to content
TypeScript

fix(server): streamed clicks no longer wait behind stale hovers (#22739)

Rookmatee94c3a72ca25
diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts
index 3cf6d253832..1051514a053 100644
--- a/apps/server/src/preview/ServerBrowser.test.ts
+++ b/apps/server/src/preview/ServerBrowser.test.ts
@@ -977,6 +977,133 @@ it.live(
).pipe(Effect.provide(layer)),
);
+it.effect.each([
+ {
+ name: "hover burst before a click",
+ inputs: [
+ ...Array.from({ length: 120 }, (_, x) => ({
+ type: "mouse",
+ action: "move",
+ x,
+ buttons: 0,
+ button: "none",
+ })),
+ { type: "mouse", action: "down", x: 119, buttons: 1, button: "left" },
+ { type: "mouse", action: "up", x: 119, buttons: 0, button: "left" },
+ ],
+ expected: [
+ { type: "mouseMoved", x: -1 },
+ { type: "mouseMoved", x: 119 },
+ { type: "mousePressed", x: 119 },
+ { type: "mouseReleased", x: 119 },
+ ],
+ },
+ {
+ name: "modifier changes and drag points",
+ inputs: [
+ { type: "mouse", action: "move", x: 1, buttons: 0, button: "none" },
+ { type: "mouse", action: "move", x: 2, buttons: 0, button: "none", modifiers: 2 },
+ { type: "mouse", action: "move", x: 3, buttons: 0, button: "none", modifiers: 2 },
+ { type: "mouse", action: "down", x: 3, buttons: 1, button: "left" },
+ { type: "mouse", action: "move", x: 4, buttons: 1, button: "left" },
+ { type: "mouse", action: "move", x: 5, buttons: 1, button: "left" },
+ { type: "mouse", action: "up", x: 5, buttons: 0, button: "left" },
+ ],
+ expected: [
+ { type: "mouseMoved", x: -1 },
+ { type: "mouseMoved", x: 1, modifiers: 0 },
+ { type: "mouseMoved", x: 3, modifiers: 2 },
+ { type: "mousePressed", x: 3 },
+ { type: "mouseMoved", x: 4 },
+ { type: "mouseMoved", x: 5 },
+ { type: "mouseReleased", x: 5 },
+ ],
+ },
+ {
+ name: "wheel and keyboard boundaries",
+ inputs: [
+ { type: "mouse", action: "move", x: 1, buttons: 0, button: "none" },
+ { type: "wheel", x: 1, deltaY: 20 },
+ { type: "wheel", x: 1, deltaY: 30 },
+ { type: "mouse", action: "move", x: 2, buttons: 0, button: "none" },
+ { type: "key", action: "down", key: "a", code: "KeyA", text: "a" },
+ { type: "mouse", action: "move", x: 3, buttons: 0, button: "none" },
+ ],
+ expected: [
+ { type: "mouseMoved", x: -1 },
+ { type: "mouseMoved", x: 1 },
+ { type: "mouseWheel", deltaY: 20 },
+ { type: "mouseWheel", deltaY: 30 },
+ { type: "mouseMoved", x: 2 },
+ { type: "keyDown", key: "a" },
+ { type: "mouseMoved", x: 3 },
+ ],
+ },
+ {
+ name: "text, navigation and resize boundaries",
+ inputs: [
+ { type: "mouse", action: "move", x: 1, buttons: 0, button: "none" },
+ { type: "text", text: "typed" },
+ { type: "mouse", action: "move", x: 2, buttons: 0, button: "none" },
+ { type: "navigate", url: "http://localhost:5173/next" },
+ { type: "mouse", action: "move", x: 3, buttons: 0, button: "none" },
+ { type: "resize", width: 640, height: 480 },
+ { type: "mouse", action: "move", x: 4, buttons: 0, button: "none" },
+ ],
+ expected: [
+ { type: "mouseMoved", x: -1 },
+ { type: "mouseMoved", x: 1 },
+ { text: "typed" },
+ { type: "mouseMoved", x: 2 },
+ { type: "mouseMoved", x: 3 },
+ { type: "mouseMoved", x: 4 },
+ ],
+ },
+ {
+ name: "ambiguous button fields",
+ inputs: [
+ { type: "mouse", action: "move", x: 1, button: "none" },
+ { type: "mouse", action: "move", x: 2, button: "none" },
+ { type: "mouse", action: "move", x: 3, buttons: 0 },
+ { type: "mouse", action: "move", x: 4, buttons: 0 },
+ ],
+ expected: [-1, 1, 2, 3, 4].map((x) => ({ type: "mouseMoved", x })),
+ },
+])("orders streamed input correctly for $name", (testCase) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { browser, tabId } = yield* ready;
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
+ yield* viewer.input({ type: "takeControl" });
+ const session = contexts[0]!.sessions.at(-1)!;
+ const send = session.send.getMockImplementation()!;
+ const started = Promise.withResolvers<void>();
+ const finish = Promise.withResolvers<void>();
+ yield* Effect.addFinalizer(() => Effect.sync(() => finish.resolve()));
+ session.send.mockClear();
+ session.send.mockImplementationOnce(async (method, input) => {
+ started.resolve();
+ await finish.promise;
+ return send(method, input);
+ });
+ const running = yield* viewer
+ .input({ type: "mouse", action: "move", x: -1, button: "none", buttons: 0 })
+ .pipe(Effect.forkScoped({ startImmediately: true }));
+ yield* Effect.promise(() => started.promise);
+ const waiting = yield* Effect.forEach(testCase.inputs, (input) =>
+ viewer.input(input).pipe(Effect.forkScoped({ startImmediately: true })),
+ );
+ finish.resolve();
+ yield* Effect.forEach([running, ...waiting], Fiber.join);
+ const dispatched = session.send.mock.calls.flatMap(([method, input]) =>
+ method.startsWith("Input.") ? [input] : [],
+ );
+ expect(dispatched).toHaveLength(testCase.expected.length);
+ expect(dispatched).toMatchObject(testCase.expected);
+ }),
+ ).pipe(Effect.provide(layer)),
+);
+
it.live("only the controlling viewer's copy and cut keys reach its clipboard", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts
index 0e52b5066c0..61caa1069bb 100644
--- a/apps/server/src/preview/ServerBrowser.ts
+++ b/apps/server/src/preview/ServerBrowser.ts
@@ -2550,9 +2550,17 @@ const make = Effect.gen(function* () {
: {}),
});
} else {
- await tab.control.human(viewer.id, () =>
- dispatchViewerInput(tab, session, viewer, message),
- );
+ const dispatch = () => dispatchViewerInput(tab, session, viewer, message);
+ if (
+ message.type === "mouse" &&
+ message.action === "move" &&
+ message.button === "none" &&
+ message.buttons === 0
+ ) {
+ await tab.control.humanLatest(viewer.id, `hover:${modifiersOf(message)}`, dispatch);
+ } else {
+ await tab.control.human(viewer.id, dispatch);
+ }
}
} catch {
broadcastControl(tab);
diff --git a/apps/server/src/preview/SessionControl.test.ts b/apps/server/src/preview/SessionControl.test.ts
index a5971f010a5..e086ad854b3 100644
--- a/apps/server/src/preview/SessionControl.test.ts
+++ b/apps/server/src/preview/SessionControl.test.ts
@@ -3,6 +3,193 @@ import { describe, expect, it } from "vite-plus/test";
import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";
describe("SessionControl", () => {
+ it("replaces waiting hover work without changing the running action or delaying the following click", async () => {
+ const control = new SessionControl("agent");
+ await control.take("viewer");
+ const started = Promise.withResolvers<void>();
+ const finish = Promise.withResolvers<void>();
+ const events: Array<number | string> = [];
+ const running = control.humanLatest("viewer", "hover:0", async () => {
+ events.push("running");
+ started.resolve();
+ await finish.promise;
+ });
+ await started.promise;
+ const moves = Array.from({ length: 120 }, (_, position) =>
+ control.humanLatest("viewer", "hover:0", async () => {
+ events.push(position);
+ }),
+ );
+ const click = control.human("viewer", async () => {
+ events.push("click");
+ });
+ finish.resolve();
+ await Promise.all([running, ...moves, click]);
+ expect(events).toEqual(["running", 119, "click"]);
+ });
+
+ it.each(["human", "system", "modifiers"] as const)(
+ "does not merge waiting hover work across a %s action",
+ async (barrier) => {
+ const control = new SessionControl("agent");
+ await control.take("viewer");
+ const finish = Promise.withResolvers<void>();
+ const events: string[] = [];
+ const running = control.human("viewer", () => finish.promise);
+ const before = control.humanLatest("viewer", "hover:0", async () => {
+ events.push("before");
+ });
+ const recordBarrier = async () => {
+ events.push("barrier");
+ };
+ const between =
+ barrier === "modifiers"
+ ? control.humanLatest("viewer", "hover:2", recordBarrier)
+ : barrier === "system"
+ ? control.system(recordBarrier)
+ : control.human("viewer", recordBarrier);
+ const after = control.humanLatest("viewer", "hover:0", async () => {
+ events.push("after");
+ });
+ finish.resolve();
+ await Promise.all([running, before, between, after]);
+ expect(events).toEqual(["before", "barrier", "after"]);
+ },
+ );
+
+ it("does not let another viewer replace or split the owner's waiting hover", async () => {
+ const control = new SessionControl("agent");
+ await control.take("viewer");
+ const finish = Promise.withResolvers<void>();
+ const events: string[] = [];
+ const running = control.human("viewer", () => finish.promise);
+ const stale = control.humanLatest("viewer", "hover", async () => {
+ events.push("stale");
+ });
+ await expect(
+ control.humanLatest("other", "hover", async () => {
+ events.push("other");
+ }),
+ ).rejects.toThrow(BrowserControlInterrupted);
+ const latest = control.humanLatest("viewer", "hover", async () => {
+ events.push("latest");
+ });
+ finish.resolve();
+ await Promise.all([running, stale, latest]);
+ expect(events).toEqual(["latest"]);
+ });
+
+ it.each(["release", "disconnect"] as const)(
+ "does not revive waiting hover work after %s and retaking control",
+ async (handoff) => {
+ const control = new SessionControl("agent");
+ await control.take("viewer");
+ const started = Promise.withResolvers<void>();
+ const finish = Promise.withResolvers<void>();
+ const events: string[] = [];
+ const running = control.human("viewer", () => {
+ started.resolve();
+ return finish.promise;
+ });
+ await started.promise;
+ const stale = expect(
+ control.humanLatest("viewer", "hover", async () => {
+ events.push("stale");
+ }),
+ ).rejects.toThrow(BrowserControlInterrupted);
+ const released = control[handoff]("viewer");
+ const retaken = control.take("viewer");
+ const fresh = control.humanLatest("viewer", "hover", async () => {
+ events.push("fresh");
+ });
+ const latest = control.humanLatest("viewer", "hover", async () => {
+ events.push("latest");
+ });
+ finish.resolve();
+ await Promise.all([running, stale, released, retaken, fresh, latest]);
+ expect(events).toEqual(["latest"]);
+ },
+ );
+
+ it("rejects every caller of a merged hover when the tab closes", async () => {
+ const control = new SessionControl("agent");
+ await control.take("viewer");
+ const started = Promise.withResolvers<void>();
+ const finish = Promise.withResolvers<void>();
+ const events: string[] = [];
+ const running = control.human("viewer", () => {
+ started.resolve();
+ return finish.promise;
+ });
+ await started.promise;
+ const waiting = [1, 2].map((position) =>
+ expect(
+ control.humanLatest("viewer", "hover", async () => {
+ events.push(`hover ${position}`);
+ }),
+ ).rejects.toThrow("closed"),
+ );
+ const closed = control.close();
+ await expect(
+ control.humanLatest("viewer", "hover", async () => {
+ events.push("after close");
+ }),
+ ).rejects.toThrow("closed");
+ finish.resolve();
+ await Promise.all([running, ...waiting, closed]);
+ expect(events).toEqual([]);
+ });
+
+ it("shares a merged dispatch failure and accepts fresh hover work afterwards", async () => {
+ const control = new SessionControl("agent");
+ await control.take("viewer");
+ const finish = Promise.withResolvers<void>();
+ const events: string[] = [];
+ const running = control.human("viewer", () => finish.promise);
+ const first = expect(
+ control.humanLatest("viewer", "hover", async () => {
+ events.push("superseded");
+ }),
+ ).rejects.toThrow("dispatch failed");
+ const last = expect(
+ control.humanLatest("viewer", "hover", async () => {
+ throw new Error("dispatch failed");
+ }),
+ ).rejects.toThrow("dispatch failed");
+ finish.resolve();
+ await Promise.all([running, first, last]);
+ await control.humanLatest("viewer", "hover", async () => {
+ events.push("recovered");
+ });
+ expect(events).toEqual(["recovered"]);
+ });
+
+ it("waits for tracked navigation before dispatching the latest human hover", async () => {
+ const control = new SessionControl("agent");
+ await control.take("viewer");
+ const committed = Promise.withResolvers<void>();
+ const events: string[] = [];
+ const navigation = control.human("viewer", async () => {
+ control.track(
+ committed.promise.then(() => {
+ events.push("navigation committed");
+ }),
+ );
+ return "started";
+ });
+ const first = control.humanLatest("viewer", "hover", async () => {
+ events.push("superseded");
+ });
+ const latest = control.humanLatest("viewer", "hover", async () => {
+ events.push("latest");
+ });
+ await expect(navigation).resolves.toBe("started");
+ expect(events).toEqual([]);
+ committed.resolve();
+ await Promise.all([first, latest]);
+ expect(events).toEqual(["navigation committed", "latest"]);
+ });
+
it("returns an action result before tracked navigation but drains it before already queued actions", async () => {
const control = new SessionControl("agent");
const committed = Promise.withResolvers<void>();
diff --git a/apps/server/src/preview/SessionControl.ts b/apps/server/src/preview/SessionControl.ts
index de02f32a1f7..cff65d3379a 100644
--- a/apps/server/src/preview/SessionControl.ts
+++ b/apps/server/src/preview/SessionControl.ts
@@ -22,6 +22,10 @@ export class SessionControl {
readonly agentId: string | null;
private readonly onGenerationChange: () => void;
private tail: Promise<unknown> = Promise.resolve();
+ private latestHuman: {
+ entry: { viewerId: string; key: string; run: () => Promise<void> };
+ result: Promise<void>;
+ } | null = null;
private pending: Promise<void> = Promise.resolve();
private readonly handoff = new Set<Promise<void>>();
private owner: string | null = null;
@@ -42,6 +46,7 @@ export class SessionControl {
}
private enqueue<A>(run: () => Promise<A>): Promise<A> {
+ this.latestHuman = null;
const result = this.tail.then(run);
this.tail = result.then(
() => this.pending,
@@ -68,6 +73,7 @@ export class SessionControl {
}
private changeOwner(owner: string | null) {
+ this.latestHuman = null;
this.owner = owner;
this.epoch++;
this.onGenerationChange();
@@ -128,6 +134,23 @@ export class SessionControl {
return this.action(() => this.owner === viewerId, run);
}
+ /** Replace only adjacent waiting work; the running action and intervening actions keep their order. */
+ humanLatest(viewerId: string, key: string, run: () => Promise<void>): Promise<void> {
+ if (this.closed || this.owner !== viewerId) return this.human(viewerId, run);
+ const latest = this.latestHuman;
+ if (latest?.entry.viewerId === viewerId && latest.entry.key === key) {
+ latest.entry.run = run;
+ return latest.result;
+ }
+ const entry = { viewerId, key, run };
+ const result = this.human(viewerId, async () => {
+ if (this.latestHuman?.entry === entry) this.latestHuman = null;
+ await entry.run();
+ });
+ this.latestHuman = { entry, result };
+ return result;
+ }
+
async take(viewerId: string) {
this.assertOpen();
if (this.owner !== null && this.owner !== viewerId) {