Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions apps/server/src/preview/ServerBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3086,7 +3086,7 @@ it.effect.each([
).pipe(Effect.provide(layer)),
);

it.effect("a queued recording stop drains after its caller expires during navigation", () =>
it.effect("queued input expires but recording stop drains after navigation", () =>
Effect.scoped(
Effect.gen(function* () {
const { broker, tabId } = yield* ready;
Expand All @@ -3112,6 +3112,8 @@ it.effect("a queued recording stop drains after its caller expires during naviga
const session = contexts[0]!.sessions.at(-1)!;
expect(session.send).toHaveBeenCalledWith("Page.startScreencast", expect.anything());

// Keep the dispatch deadline live: interruption must also be checked at the native seam.
using _dispatchClock = vi.spyOn(performance, "now").mockReturnValue(0);
const started = Promise.withResolvers<void>();
const release = Promise.withResolvers<void>();
yield* Effect.addFinalizer(() => Effect.sync(() => release.resolve()));
Expand All @@ -3129,6 +3131,15 @@ it.effect("a queued recording stop drains after its caller expires during naviga
})
.pipe(Effect.forkScoped);
yield* Effect.promise(() => started.promise);
const expiredInput = yield* broker
.invoke<void>({
scope,
tabId,
operation: "press",
input: { key: "Enter" },
timeoutMs: 1000,
})
.pipe(Effect.flip, Effect.forkScoped);
const stop = yield* broker
.invoke<void>({
scope,
Expand All @@ -3142,13 +3153,19 @@ it.effect("a queued recording stop drains after its caller expires during naviga
yield* broker.invoke({ scope, tabId, operation: "status", input: {} });
yield* TestClock.adjust(1000);
expect(yield* Fiber.join(stop)).toMatchObject({ _tag: "PreviewAutomationTimeoutError" });
expect(yield* Fiber.join(expiredInput)).toMatchObject({
_tag: "PreviewAutomationTimeoutError",
});
expect(session.detach).not.toHaveBeenCalled();
expect(encoder.close).not.toHaveBeenCalled();
release.resolve();
yield* Fiber.join(navigation);
yield* Effect.promise(() => closed.promise);
expect(session.detach).toHaveBeenCalled();
expect(encoder.close).toHaveBeenCalledOnce();
expect(page.keyboard.press).not.toHaveBeenCalled();
yield* broker.invoke({ scope, tabId, operation: "press", input: { key: "Enter" } });
expect(page.keyboard.press).toHaveBeenCalledExactlyOnceWith("Enter");
const stopped = yield* broker
.invoke<void>({ scope, tabId, operation: "recordingStop", input: {} })
.pipe(Effect.flip);
Expand Down Expand Up @@ -3899,7 +3916,12 @@ it.effect.each(["agent", "viewer"] as const)(
const session = contexts[0]!.sessions[0]!;
const send = session.send.getMockImplementation()!;
session.send.mockImplementation(async (method, input) => {
if (method !== "Runtime.evaluate") return send(method, input);
// Title watches also evaluate scripts; only the dialog expression is blocked.
if (
method !== "Runtime.evaluate" ||
(input as { expression?: string }).expression !== 'confirm("Delete row?")'
)
return send(method, input);
started.resolve();
return resolvedEvaluation.promise;
});
Expand Down
2 changes: 0 additions & 2 deletions apps/server/src/preview/ServerBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4403,7 +4403,6 @@ const make = Effect.gen(function* () {
);
return statusWithTitle(tab, request.agentSessionId);
}),
signal,
deadlineMs,
);
}
Expand Down Expand Up @@ -4578,7 +4577,6 @@ const make = Effect.gen(function* () {
if (generation !== tab.control.generation) ServerBrowserPage.invalidateRefs(tab.page);
}
}),
signal,
deadlineMs,
);
};
Expand Down
62 changes: 24 additions & 38 deletions apps/server/src/preview/SessionControl.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it, vi } from "vite-plus/test";

import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";

Expand Down Expand Up @@ -190,43 +190,34 @@ describe("SessionControl", () => {
expect(events).toEqual(["navigation committed", "latest"]);
});

it("discards an expired queued action without replaying it after the active action drains", async () => {
it("finishes running work, skips expired queued actions, and accepts fresh work", async () => {
let now = 0;
using _clock = 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 () => {
started.resolve();
await finish.promise;
events.push("finished");
});
const running = control.agent(
"agent",
async () => {
events.push("started");
started.resolve();
await finish.promise;
events.push("finished");
},
100,
);
await started.promise;
const expired = new AbortController();
const queued = expect(
control.agent("agent", async () => events.push("late click"), expired.signal),
).rejects.toThrow("request expired");
expired.abort(new Error("request expired"));
const next = control.agent("agent", async () => events.push("fresh action"));
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, queued, next]);
expect(events).toEqual(["finished", "fresh action"]);
});

it("rejects an already cancelled action before it reaches the queue", async () => {
const control = new SessionControl("agent");
const cancelled = AbortSignal.abort(new Error("request cancelled"));
let executed = false;
await expect(
control.agent(
"agent",
async () => {
executed = true;
},
cancelled,
),
).rejects.toThrow("request cancelled");
expect(executed).toBe(false);
await expect(control.agent("agent", async () => "ready")).resolves.toBe("ready");
await Promise.all([running, expired, next]);
expect(events).toEqual(["started", "finished", "next"]);
});

it("returns an action result before tracked navigation but drains it before already queued actions", async () => {
Expand Down Expand Up @@ -267,17 +258,12 @@ describe("SessionControl", () => {
const handingOff = control[handoff]("viewer", async () => {
events.push("input released");
});
const cancelled = new AbortController();
const expired = expect(
control.agent("agent", async () => events.push("expired action"), cancelled.signal),
).rejects.toThrow("request expired");
cancelled.abort(new Error("request expired"));
const resumed = control.agent("agent", async () => events.push("agent resumed"));
replacement.resolve();
await replacement.promise;
expect(events).toEqual(["human typed"]);
slow.reject(new Error("navigation replaced"));
await Promise.all([handingOff, expired, resumed]);
await Promise.all([handingOff, resumed]);
expect(events).toEqual(["human typed", "input released", "agent resumed"]);
},
);
Expand Down
25 changes: 3 additions & 22 deletions apps/server/src/preview/SessionControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,21 +94,12 @@ export class SessionControl {
this.onGenerationChange();
}

private async action<A>(
allowed: () => boolean,
run: () => Promise<A>,
deadlineOrSignal?: number | AbortSignal,
dispatchDeadlineMs?: number,
) {
const signal = typeof deadlineOrSignal === "number" ? undefined : deadlineOrSignal;
const deadlineMs = typeof deadlineOrSignal === "number" ? deadlineOrSignal : dispatchDeadlineMs;
signal?.throwIfAborted();
private async action<A>(allowed: () => boolean, run: () => Promise<A>, deadlineMs?: number) {
this.assertOpen();
if (!allowed())
throw new BrowserControlInterrupted({ message: "You do not control this browser tab." });
const epoch = this.epoch;
return this.enqueue(async () => {
signal?.throwIfAborted();
this.assertOpen();
if (epoch !== this.epoch || !allowed()) throw new BrowserControlInterrupted();
if (deadlineMs !== undefined && performance.now() >= deadlineMs) {
Expand All @@ -125,12 +116,7 @@ export class SessionControl {
return this.agentId === null || this.agentId === agentId;
}

agent<A>(
agentId: string,
run: () => Promise<A>,
deadlineOrSignal?: number | AbortSignal,
dispatchDeadlineMs?: number,
) {
agent<A>(agentId: string, run: () => Promise<A>, deadlineMs?: number) {
if (!this.agentMayAct(agentId))
return Promise.reject(
new BrowserControlInterrupted({
Expand All @@ -145,12 +131,7 @@ export class SessionControl {
reason: "humanControl",
}),
);
return this.action(
() => this.agentMayAct(agentId) && this.owner === null,
run,
deadlineOrSignal,
dispatchDeadlineMs,
);
return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs);
}

agentCanActNow(agentId: string) {
Expand Down
14 changes: 12 additions & 2 deletions scripts/dev-runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ it.live.each(["SIGTERM", "SIGHUP"] as const)(
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "dev-runner-shutdown-"));
const bin = NodePath.join(root, "bin");
NodeFS.mkdirSync(bin);
// Cold checkouts must not compile the resource monitor before testing shutdown.
NodeFS.writeFileSync(NodePath.join(bin, "cargo"), `#!${process.execPath}\n`, { mode: 0o755 });
// A stubborn descendant keeps inherited output open until group cleanup finishes.
const descendant = `process.on("SIGTERM", () => {}); process.send("ready"); setInterval(() => {}, 1000);`;
NodeFS.writeFileSync(
Expand Down Expand Up @@ -117,14 +119,22 @@ it.live.each(["SIGTERM", "SIGHUP"] as const)(
// oxlint-disable t3code/no-real-time-wait-in-tests -- A failure deadline bounds the real subprocess; readiness itself comes from its stdout event.
// @effect-diagnostics-next-line globalTimers:off -- Real child process deadlines must use native time.
const timeout = setTimeout(
() => reject(new Error("Process fixture did not start")),
() =>
reject(
new Error(`Process fixture did not start\nstdout:\n${output}\nstderr:\n${errors}`),
),
8000,
);
// oxlint-enable t3code/no-real-time-wait-in-tests
runner.once("error", reject);
runner.once("exit", () => {
clearTimeout(timeout);
if (!tree) reject(new Error(`Runner exited before the fixture started: ${errors}`));
if (!tree)
reject(
new Error(
`Runner exited before the fixture started\nstdout:\n${output}\nstderr:\n${errors}`,
),
);
});
runner.stdout.on("data", (chunk: Buffer) => {
output += chunk.toString();
Expand Down