Skip to content

Commit 9dd7c68

Browse files
committed
fix(server): serialize recording restarts after late screencast stops
Keep recording pause, resume and final stop on one promise chain. A timed-out snapshot can release its capture lock without sending a recording restart ahead of the unanswered stop. Extend the TestClock regression to cover viewer detach with an unanswered stop, attached viewer recovery, and recording recovery. The recording case fails before the queue is added; all 58 browser service tests, changed-file lint and formatting, and server typecheck pass.
1 parent d8a2b43 commit 9dd7c68

2 files changed

Lines changed: 107 additions & 51 deletions

File tree

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

Lines changed: 87 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -848,54 +848,93 @@ it.live("streams to a read-only viewer without allowing takeover, input, or view
848848
).pipe(Effect.provide(layer)),
849849
);
850850

851-
it.effect("a viewer whose screencast never stops delays a snapshot boundedly, not forever", () =>
852-
Effect.scoped(
853-
Effect.gen(function* () {
854-
const { browser, broker, tabId } = yield* ready;
855-
const viewerScope = yield* Scope.fork(yield* Effect.scope);
856-
yield* browser.attachViewer(viewerInput(tabId, false)).pipe(Scope.provide(viewerScope));
857-
const session = contexts[0]!.sessions.at(-1)!;
858-
// The viewer's next screencast stop answers only when the test ends, after
859-
// the viewer detaches.
860-
const stalled = Promise.withResolvers<Record<string, unknown>>();
861-
yield* Effect.addFinalizer(() => Effect.sync(() => stalled.resolve({})));
862-
const stops = yield* Queue.unbounded<void>();
863-
const send = session.send.getMockImplementation()!;
864-
let stalling = true;
865-
session.send.mockImplementation((method, input) => {
866-
if (method !== "Page.stopScreencast" || !stalling) return send(method, input);
867-
stalling = false;
868-
Queue.offerUnsafe(stops, undefined);
869-
return stalled.promise;
870-
});
871-
const captures = () =>
872-
contexts[0]!.sessions.flatMap((item) =>
873-
item.send.mock.calls.filter(
874-
([method, input]) =>
875-
method === "Page.captureScreenshot" && (input as { format: string }).format === "png",
876-
),
877-
).length;
878-
const snapshot = broker.invoke<PreviewAutomationSnapshot>({
879-
scope,
880-
tabId,
881-
operation: "snapshot",
882-
input: {},
883-
});
884-
const first = yield* snapshot.pipe(Effect.forkScoped);
885-
yield* Queue.take(stops);
886-
expect(captures()).toBe(0);
887-
// The pause gives up on the stalled viewer and the snapshot captures without it.
888-
yield* TestClock.adjust("2 seconds");
889-
expect(captures()).toBe(1);
890-
// Its resume waits behind the stalled stop and gives up too, releasing the tab.
891-
yield* TestClock.adjust("2 seconds");
892-
expect((yield* Fiber.join(first)).accessibilityTree).toEqual(expect.any(String));
893-
// Once the stalled viewer detaches, the next snapshot no longer waits for it.
894-
yield* Scope.close(viewerScope, Exit.void);
895-
expect((yield* snapshot).accessibilityTree).toEqual(expect.any(String));
896-
expect(captures()).toBe(2);
897-
}),
898-
).pipe(Effect.provide(layer)),
851+
it.effect.each([
852+
{ kind: "viewer", lateAnswer: false },
853+
{ kind: "viewer", lateAnswer: true },
854+
{ kind: "recording", lateAnswer: true },
855+
] as const)(
856+
"a $kind does not block snapshots after a stalled stop, with late answer: $lateAnswer",
857+
({ kind, lateAnswer }) =>
858+
Effect.scoped(
859+
Effect.gen(function* () {
860+
const { browser, broker, tabId } = yield* ready;
861+
const viewerScope = yield* Scope.fork(yield* Effect.scope);
862+
if (kind === "viewer") {
863+
yield* browser.attachViewer(viewerInput(tabId, false)).pipe(Scope.provide(viewerScope));
864+
} else {
865+
yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} });
866+
}
867+
const session = contexts[0]!.sessions.at(-1)!;
868+
// Keep the stop unanswered through both handoff deadlines. It either
869+
// answers while still attached or stays stalled until after detach.
870+
const stalled = Promise.withResolvers<Record<string, unknown>>();
871+
yield* Effect.addFinalizer(() => Effect.sync(() => stalled.resolve({})));
872+
const stops = yield* Queue.unbounded<void>();
873+
const resumes = yield* Queue.unbounded<void>();
874+
const send = session.send.getMockImplementation()!;
875+
let stalling = true;
876+
let stopPending = false;
877+
let startsBeforeStop = 0;
878+
session.send.mockImplementation((method, input) => {
879+
if (method === "Page.stopScreencast" && stalling) {
880+
stalling = false;
881+
stopPending = true;
882+
Queue.offerUnsafe(stops, undefined);
883+
return stalled.promise.finally(() => {
884+
stopPending = false;
885+
});
886+
}
887+
if (method === "Page.startScreencast") {
888+
if (stopPending) startsBeforeStop++;
889+
Queue.offerUnsafe(resumes, undefined);
890+
}
891+
return send(method, input);
892+
});
893+
const captures = () =>
894+
contexts[0]!.sessions.flatMap((item) =>
895+
item.send.mock.calls.filter(
896+
([method, input]) =>
897+
method === "Page.captureScreenshot" &&
898+
(input as { format: string }).format === "png",
899+
),
900+
).length;
901+
const snapshot = broker.invoke<PreviewAutomationSnapshot>({
902+
scope,
903+
tabId,
904+
operation: "snapshot",
905+
input: {},
906+
});
907+
const first = yield* snapshot.pipe(Effect.forkScoped);
908+
yield* Queue.take(stops);
909+
expect(captures()).toBe(0);
910+
// The pause gives up on the stalled session and the snapshot captures without it.
911+
yield* TestClock.adjust("2 seconds");
912+
expect(captures()).toBe(1);
913+
// Its resume waits behind the stalled stop and gives up too, releasing the tab.
914+
yield* TestClock.adjust("2 seconds");
915+
expect((yield* Fiber.join(first)).accessibilityTree).toEqual(expect.any(String));
916+
expect(startsBeforeStop).toBe(0);
917+
expect(yield* Queue.size(resumes)).toBe(0);
918+
if (lateAnswer) {
919+
stalled.resolve({});
920+
yield* Queue.take(resumes);
921+
// Recovery needs no additional clock advance, and the next snapshot
922+
// leaves the same session streaming again.
923+
expect((yield* snapshot).accessibilityTree).toEqual(expect.any(String));
924+
expect(
925+
session.send.mock.calls
926+
.filter(
927+
([method]) => method === "Page.stopScreencast" || method === "Page.startScreencast",
928+
)
929+
.at(-1)?.[0],
930+
).toBe("Page.startScreencast");
931+
expect(startsBeforeStop).toBe(0);
932+
}
933+
yield* Scope.close(viewerScope, Exit.void);
934+
expect((yield* snapshot).accessibilityTree).toEqual(expect.any(String));
935+
expect(captures()).toBe(lateAnswer ? 3 : 2);
936+
}),
937+
).pipe(Effect.provide(layer)),
899938
);
900939

901940
it.live(

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

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,7 @@ interface Recording {
292292
readonly session: CDPSession;
293293
readonly startedAt: string;
294294
readonly framesInFlight: Set<Promise<void>>;
295+
screencastParams: Promise<void>;
295296
}
296297

297298
interface ServerTab {
@@ -1770,6 +1771,7 @@ const make = Effect.gen(function* () {
17701771
session: opened,
17711772
startedAt: new Date().toISOString(),
17721773
framesInFlight,
1774+
screencastParams: Promise.resolve(),
17731775
};
17741776
tab.recording = recording;
17751777
return recording;
@@ -1785,6 +1787,21 @@ const make = Effect.gen(function* () {
17851787
return started;
17861788
};
17871789

1790+
// Like viewers, recordings queue a restart behind any unanswered stop even
1791+
// after the snapshot stops waiting for that session.
1792+
const setRecordingScreencast = (tab: ServerTab, recording: Recording, paused: boolean) => {
1793+
recording.screencastParams = recording.screencastParams.then(async () => {
1794+
if (tab.recording !== recording || (!paused && tab.capturing > 0)) return;
1795+
await recording.session
1796+
.send(
1797+
paused ? "Page.stopScreencast" : "Page.startScreencast",
1798+
paused ? undefined : RECORDING_SCREENCAST,
1799+
)
1800+
.catch(constVoid);
1801+
});
1802+
return recording.screencastParams;
1803+
};
1804+
17881805
// A stalled viewer or recording keeps its own late answer; the capture goes on without it.
17891806
const settleScreencasts = (pending: ReadonlyArray<Promise<unknown> | undefined>) =>
17901807
runPromise(
@@ -1800,7 +1817,7 @@ const make = Effect.gen(function* () {
18001817
try {
18011818
await settleScreencasts([
18021819
...[...tab.viewers].map((viewer) => viewer.pause()),
1803-
recording?.session.send("Page.stopScreencast").catch(constVoid),
1820+
recording ? setRecordingScreencast(tab, recording, true) : undefined,
18041821
]);
18051822
return await capture();
18061823
} finally {
@@ -1809,7 +1826,7 @@ const make = Effect.gen(function* () {
18091826
await settleScreencasts([
18101827
...[...tab.viewers].map((viewer) => viewer.resume()),
18111828
recording && tab.recording === recording
1812-
? recording.session.send("Page.startScreencast", RECORDING_SCREENCAST).catch(constVoid)
1829+
? setRecordingScreencast(tab, recording, false)
18131830
: undefined,
18141831
]);
18151832
}
@@ -1827,7 +1844,7 @@ const make = Effect.gen(function* () {
18271844
let mimeType: string | null;
18281845
const chunks: Array<Buffer> = [];
18291846
try {
1830-
await recording.session.send("Page.stopScreencast").catch(constVoid);
1847+
await setRecordingScreencast(tab, recording, true);
18311848
await Promise.all(recording.framesInFlight);
18321849
await recording.session.detach().catch(constVoid);
18331850
const stopped = await recording.encoder.evaluate(() =>

0 commit comments

Comments
 (0)