Skip to content

Commit b60a7bd

Browse files
committed
fix(server): bound final cleanup of stalled preview recordings
A recording stop queued behind an unanswered screencast command could hold the capture lock indefinitely. Bound final screencast settling to two seconds. Retire the recording before attempting detach and encoder close, with a shared two-second cleanup bound, so late queued commands cannot restart it. Extend the existing TestClock table with an unanswered recording stop followed by recordingStop. Stall detach and close too, verify a queued snapshot completes, and ensure late responses cannot restart the retired session. The case fails on the previous commit; all 59 browser-service tests, changed-file lint and formatting, and server typecheck pass.
1 parent 9dd7c68 commit b60a7bd

2 files changed

Lines changed: 85 additions & 4 deletions

File tree

‎apps/server/src/preview/ServerBrowser.test.ts‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import * as Manager from "./Manager.ts";
3939
import * as PreviewAgentActivity from "./PreviewAgentActivity.ts";
4040
import * as ServerBrowser from "./ServerBrowser.ts";
4141
import * as PreviewBrowser from "./PreviewBrowser.ts";
42+
import { SessionControl } from "./SessionControl.ts";
4243

4344
vi.mock("./ServerBrowserContexts.ts", () => ({
4445
presentAsChrome: async () => {},
@@ -62,7 +63,9 @@ vi.mock("./ServerBrowserContexts.ts", () => ({
6263
return context as unknown as BrowserContext;
6364
}
6465
async scratchPage() {
65-
return makeEncoderPage() as unknown as Page;
66+
const encoder = makeEncoderPage();
67+
encoderPages.push(encoder);
68+
return encoder as unknown as Page;
6669
}
6770
async connectDesktopPage(endpoint: string) {
6871
const context = makeContext(undefined, desktopPageUrl);
@@ -297,6 +300,7 @@ function makeEncoderPage() {
297300
}
298301

299302
const contexts: ReturnType<typeof makeContext>[] = [];
303+
const encoderPages: ReturnType<typeof makeEncoderPage>[] = [];
300304
const encoderStreams: Array<{ frameRate: number | undefined; bitsPerSecond: number }> = [];
301305
const contextRequests: Array<{ profileId: string; isolated: boolean }> = [];
302306
let contextGate: PromiseWithResolvers<void> | null = null;
@@ -449,6 +453,7 @@ const openDesktopViewer = Effect.gen(function* () {
449453
beforeEach(() => {
450454
contexts.length = 0;
451455
encoderStreams.length = 0;
456+
encoderPages.length = 0;
452457
contextRequests.length = 0;
453458
contextGate = null;
454459
contextFailure = null;
@@ -852,6 +857,7 @@ it.effect.each([
852857
{ kind: "viewer", lateAnswer: false },
853858
{ kind: "viewer", lateAnswer: true },
854859
{ kind: "recording", lateAnswer: true },
860+
{ kind: "recording", lateAnswer: false },
855861
] as const)(
856862
"a $kind does not block snapshots after a stalled stop, with late answer: $lateAnswer",
857863
({ kind, lateAnswer }) =>
@@ -929,6 +935,70 @@ it.effect.each([
929935
.at(-1)?.[0],
930936
).toBe("Page.startScreencast");
931937
expect(startsBeforeStop).toBe(0);
938+
} else if (kind === "recording") {
939+
// Even cleanup acknowledgements may stall. Retiring the recording
940+
// must release the capture lock before any of these promises answer.
941+
const encoder = encoderPages.at(-1)!;
942+
// Let the pre-fix path finish cleanly if a failed assertion releases the stop.
943+
encoder.evaluate.mockResolvedValue({ mimeType: null, count: 0, bytes: 0 });
944+
session.detach.mockImplementation(() => stalled.promise.then(() => {}));
945+
encoder.close.mockImplementation(() => stalled.promise.then(() => {}));
946+
const started = yield* Queue.unbounded<void>();
947+
const agent = SessionControl.prototype.agent;
948+
using _started = vi.spyOn(SessionControl.prototype, "agent").mockImplementation(function <
949+
A,
950+
>(this: SessionControl, agentId: string, run: () => Promise<A>, deadlineMs?: number) {
951+
const invoke = agent.bind(this);
952+
return invoke(
953+
agentId,
954+
() => {
955+
const result = run();
956+
Queue.offerUnsafe(started, undefined);
957+
return result;
958+
},
959+
deadlineMs,
960+
);
961+
});
962+
const stopping = yield* broker
963+
.invoke<void>({
964+
scope,
965+
tabId,
966+
operation: "recordingStop",
967+
input: {},
968+
})
969+
.pipe(Effect.flip, Effect.forkScoped);
970+
yield* Queue.take(started);
971+
yield* TestClock.adjust("2 seconds");
972+
expect(session.detach).toHaveBeenCalledTimes(1);
973+
expect(encoder.close).toHaveBeenCalledTimes(1);
974+
const queued = yield* snapshot.pipe(Effect.forkScoped);
975+
yield* TestClock.adjust("2 seconds");
976+
expect(yield* Fiber.join(stopping)).toMatchObject({
977+
_tag: "PreviewAutomationExecutionError",
978+
cause: {
979+
_tag: "PreviewAutomationExecutionError",
980+
message: "The recording's screencast stop timed out; the recording was discarded.",
981+
},
982+
});
983+
expect((yield* Fiber.join(queued)).accessibilityTree).toEqual(expect.any(String));
984+
expect(captures()).toBe(2);
985+
const retry = yield* broker
986+
.invoke<void>({
987+
scope,
988+
tabId,
989+
operation: "recordingStop",
990+
input: {},
991+
})
992+
.pipe(Effect.flip);
993+
expect(retry).toMatchObject({
994+
_tag: "PreviewAutomationExecutionError",
995+
cause: { _tag: "PreviewAutomationRecordingNotActiveError" },
996+
});
997+
stalled.resolve({});
998+
yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} });
999+
// Late answers from the retired recording cannot restart its session.
1000+
expect(yield* Queue.size(resumes)).toBe(0);
1001+
return;
9321002
}
9331003
yield* Scope.close(viewerScope, Exit.void);
9341004
expect((yield* snapshot).accessibilityTree).toEqual(expect.any(String));

‎apps/server/src/preview/ServerBrowser.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,9 +1844,15 @@ const make = Effect.gen(function* () {
18441844
let mimeType: string | null;
18451845
const chunks: Array<Buffer> = [];
18461846
try {
1847-
await setRecordingScreencast(tab, recording, true);
1847+
if (
1848+
Option.isNone(await settleScreencasts([setRecordingScreencast(tab, recording, true)]))
1849+
) {
1850+
throw new ServerBrowserPage.ServerBrowserOperationError({
1851+
tag: "PreviewAutomationExecutionError",
1852+
message: "The recording's screencast stop timed out; the recording was discarded.",
1853+
});
1854+
}
18481855
await Promise.all(recording.framesInFlight);
1849-
await recording.session.detach().catch(constVoid);
18501856
const stopped = await recording.encoder.evaluate(() =>
18511857
(globalThis as unknown as EncoderWindow).__t3Recorder.stop(),
18521858
);
@@ -1866,8 +1872,13 @@ const make = Effect.gen(function* () {
18661872
chunks.push(Buffer.from(chunk, "base64"));
18671873
}
18681874
} finally {
1869-
await recording.encoder.close().catch(constVoid);
1875+
// Retire before cleanup so a late queued restart cannot revive this
1876+
// recording. Cleanup acknowledgements must not keep the capture lock.
18701877
tab.recording = null;
1878+
await settleScreencasts([
1879+
recording.session.detach().catch(constVoid),
1880+
recording.encoder.close().catch(constVoid),
1881+
]);
18711882
}
18721883
const data = Buffer.concat(chunks);
18731884
if (!mimeType || data.byteLength === 0) {

0 commit comments

Comments
 (0)