Skip to content

Commit e4dc45d

Browse files
committed
fix(preview): reclaim hidden tabs after automation timeouts
1 parent d15210c commit e4dc45d

4 files changed

Lines changed: 323 additions & 4 deletions

File tree

‎apps/web/src/components/preview/PreviewAutomationHosts.test.tsx‎

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const mocks = vi.hoisted(() => ({
3636
),
3737
list: vi.fn(async () => AsyncResult.success(emptyList)),
3838
resize: vi.fn(),
39+
close: vi.fn(async () => AsyncResult.success(undefined)),
3940
respond:
4041
vi.fn<
4142
(target: { environmentId: EnvironmentId; input: PreviewAutomationResponse }) => Promise<void>
@@ -56,6 +57,7 @@ vi.mock("~/state/preview", () => ({
5657
list: () => listAtom,
5758
open: mocks.open,
5859
resize: mocks.resize,
60+
close: mocks.close,
5961
respondToAutomation: mocks.respond,
6062
focusAutomationHost: mocks.focus,
6163
},
@@ -211,6 +213,158 @@ describe("PreviewAutomationHosts open", () => {
211213
});
212214
});
213215

216+
describe("PreviewAutomationHosts timeout cleanup", () => {
217+
it("closes a hidden tab created after its open request already timed out", async () => {
218+
const opened = deferred<Awaited<ReturnType<typeof mocks.open>>>();
219+
mocks.open.mockImplementationOnce(() => opened.promise);
220+
vi.useFakeTimers();
221+
try {
222+
await act(async () => {
223+
appAtomRegistry.set(
224+
requestsAtom,
225+
AsyncResult.success({
226+
...requestEvent,
227+
request: { ...requestEvent.request, timeoutMs: 100 },
228+
}),
229+
);
230+
await vi.advanceTimersByTimeAsync(0);
231+
});
232+
expect(mocks.open).toHaveBeenCalledTimes(1);
233+
await act(async () => vi.advanceTimersByTimeAsync(100));
234+
expect(mocks.close).not.toHaveBeenCalled();
235+
236+
await act(async () => {
237+
opened.resolve(AsyncResult.success(snapshot));
238+
await opened.promise;
239+
});
240+
expect(mocks.close).toHaveBeenCalledTimes(1);
241+
expect(readThreadPreviewState(threadRef).sessions[snapshot.tabId]).toBeUndefined();
242+
} finally {
243+
vi.useRealTimers();
244+
}
245+
});
246+
247+
it("preserves an agent tab after it has been explicitly presented", async () => {
248+
await act(async () => {
249+
appAtomRegistry.set(requestsAtom, AsyncResult.success(requestEvent));
250+
await vi.waitFor(() => expect(mocks.respond).toHaveBeenCalledTimes(1));
251+
});
252+
const runtimeTabId = previewRuntimeTabId(
253+
threadRef,
254+
readThreadPreviewState(threadRef).serverEpoch,
255+
snapshot.tabId,
256+
);
257+
const owner = Symbol();
258+
await act(() => {
259+
useBrowserSurfaceStore.getState().claim(runtimeTabId, owner, false);
260+
useBrowserSurfaceStore
261+
.getState()
262+
.present(runtimeTabId, owner, { x: 0, y: 0, width: 800, height: 600 }, true, 0, 1);
263+
});
264+
await act(async () => {
265+
appAtomRegistry.set(
266+
requestsAtom,
267+
AsyncResult.success({
268+
...requestEvent,
269+
request: {
270+
...requestEvent.request,
271+
requestId: "present-existing",
272+
tabId: snapshot.tabId,
273+
input: { open: true },
274+
},
275+
}),
276+
);
277+
await vi.waitFor(() => expect(mocks.respond).toHaveBeenCalledTimes(2));
278+
});
279+
await act(() => useBrowserSurfaceStore.getState().release(runtimeTabId, owner));
280+
281+
const pendingResponse = deferred<void>();
282+
mocks.respond.mockImplementationOnce(() => pendingResponse.promise);
283+
vi.useFakeTimers();
284+
try {
285+
await act(async () => {
286+
appAtomRegistry.set(
287+
requestsAtom,
288+
AsyncResult.success({
289+
...requestEvent,
290+
request: {
291+
...requestEvent.request,
292+
requestId: "stalled-status",
293+
operation: "status",
294+
tabId: snapshot.tabId,
295+
input: {},
296+
},
297+
}),
298+
);
299+
});
300+
await act(async () => vi.advanceTimersByTimeAsync(15_000));
301+
expect(mocks.close).not.toHaveBeenCalled();
302+
expect(readThreadPreviewState(threadRef).sessions[snapshot.tabId]).toEqual(snapshot);
303+
} finally {
304+
pendingResponse.resolve();
305+
await act(async () => pendingResponse.promise);
306+
vi.useRealTimers();
307+
}
308+
});
309+
310+
it.each([false, true])(
311+
"closes only a hidden agent tab that was never presented (presented: %s)",
312+
async (wasPresented) => {
313+
await act(async () => {
314+
appAtomRegistry.set(requestsAtom, AsyncResult.success(requestEvent));
315+
await vi.waitFor(() => expect(mocks.respond).toHaveBeenCalledTimes(1));
316+
});
317+
const runtimeTabId = previewRuntimeTabId(
318+
threadRef,
319+
readThreadPreviewState(threadRef).serverEpoch,
320+
snapshot.tabId,
321+
);
322+
if (wasPresented) {
323+
const owner = Symbol();
324+
await act(() => {
325+
useBrowserSurfaceStore.getState().claim(runtimeTabId, owner, false);
326+
useBrowserSurfaceStore
327+
.getState()
328+
.present(runtimeTabId, owner, { x: 0, y: 0, width: 800, height: 600 }, true, 0, 1);
329+
});
330+
await act(() => useBrowserSurfaceStore.getState().release(runtimeTabId, owner));
331+
}
332+
expect(useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible ?? false).toBe(false);
333+
expect(mocks.close).not.toHaveBeenCalled();
334+
335+
const pendingResponse = deferred<void>();
336+
mocks.respond.mockImplementationOnce(() => pendingResponse.promise);
337+
vi.useFakeTimers();
338+
try {
339+
await act(async () => {
340+
appAtomRegistry.set(
341+
requestsAtom,
342+
AsyncResult.success({
343+
...requestEvent,
344+
request: {
345+
...requestEvent.request,
346+
requestId: "stalled-status",
347+
operation: "status",
348+
tabId: snapshot.tabId,
349+
input: {},
350+
},
351+
}),
352+
);
353+
});
354+
await act(async () => vi.advanceTimersByTimeAsync(15_000));
355+
expect(mocks.close).toHaveBeenCalledTimes(wasPresented ? 0 : 1);
356+
expect(readThreadPreviewState(threadRef).sessions[snapshot.tabId]).toBe(
357+
wasPresented ? snapshot : undefined,
358+
);
359+
} finally {
360+
pendingResponse.resolve();
361+
await act(async () => pendingResponse.promise);
362+
vi.useRealTimers();
363+
}
364+
},
365+
);
366+
});
367+
214368
describe("PreviewAutomationHosts ownership", () => {
215369
it("reports only local live tabs and removes ownership when their web contents close", async () => {
216370
await act(() => {
@@ -360,4 +514,50 @@ describe("PreviewAutomationHosts ownership", () => {
360514
result: { available: false, tabId: snapshot.tabId },
361515
});
362516
});
517+
518+
it("preserves an existing user tab reused by a hidden automation request", async () => {
519+
const pendingResponse = deferred<void>();
520+
applyPreviewServerSnapshot(threadRef, snapshot);
521+
await act(async () => {
522+
appAtomRegistry.set(
523+
requestsAtom,
524+
AsyncResult.success({
525+
...requestEvent,
526+
request: {
527+
...requestEvent.request,
528+
tabId: snapshot.tabId,
529+
input: { open: false },
530+
},
531+
}),
532+
);
533+
await vi.waitFor(() => expect(mocks.respond).toHaveBeenCalledTimes(1));
534+
});
535+
expect(mocks.open).not.toHaveBeenCalled();
536+
mocks.respond.mockImplementationOnce(() => pendingResponse.promise);
537+
vi.useFakeTimers();
538+
try {
539+
await act(async () => {
540+
appAtomRegistry.set(
541+
requestsAtom,
542+
AsyncResult.success({
543+
...requestEvent,
544+
request: {
545+
...requestEvent.request,
546+
requestId: "stalled-status",
547+
operation: "status",
548+
tabId: snapshot.tabId,
549+
input: {},
550+
},
551+
}),
552+
);
553+
});
554+
await act(async () => vi.advanceTimersByTimeAsync(15_000));
555+
expect(mocks.close).not.toHaveBeenCalled();
556+
expect(readThreadPreviewState(threadRef).sessions[snapshot.tabId]).toEqual(snapshot);
557+
} finally {
558+
pendingResponse.resolve();
559+
await act(async () => pendingResponse.promise);
560+
vi.useRealTimers();
561+
}
562+
});
363563
});

‎apps/web/src/components/preview/PreviewAutomationHosts.tsx‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ import {
8484
} from "./previewNavigationReadiness";
8585
import { createPreviewAutomationRequestConsumerAtom } from "./previewAutomationRequestConsumer";
8686
import { createPreviewAutomationClientId } from "./previewAutomationClientId";
87+
import { closePreviewSession } from "./closePreviewSession";
8788
import {
8889
needsPreviewAutomationSessionSync,
8990
resolvePreviewAutomationOpenTab,
@@ -342,6 +343,9 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
342343
const resize = useAtomCommand(previewEnvironment.resize, {
343344
reportFailure: false,
344345
});
346+
const close = useAtomCommand(previewEnvironment.close, {
347+
reportFailure: false,
348+
});
345349
const respondToAutomation = useAtomCommand(
346350
previewEnvironment.respondToAutomation,
347351
"preview automation response",
@@ -353,11 +357,51 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
353357
const [automationConnectionAtom] = useState(() => Atom.make<string | null>(null));
354358
const automationConnectionId = useAtomValue(automationConnectionAtom);
355359
const presentationSuppressedRuntimeTabsRef = useRef(new Map<string, Set<string>>());
360+
const hiddenAutomationTabsRef = useRef(new Map<string, ScopedThreadRef>());
361+
362+
useEffect(() => {
363+
for (const runtimeTabId of visibleRuntimeTabIds) {
364+
hiddenAutomationTabsRef.current.delete(runtimeTabId);
365+
}
366+
}, [visibleRuntimeTabIds]);
367+
368+
const reclaimTimedOutHiddenTabs = useCallback(() => {
369+
if (!hiddenAutomationTabsRef.current.size) return;
370+
for (const [runtimeTabId, threadRef] of hiddenAutomationTabsRef.current) {
371+
const state = readThreadPreviewState(threadRef);
372+
const snapshot = Object.values(state.sessions).find(
373+
(session) =>
374+
previewRuntimeTabId(threadRef, state.serverEpoch, session.tabId) === runtimeTabId,
375+
);
376+
if (!snapshot) continue;
377+
if (
378+
useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible ||
379+
state.desktopByTabId[snapshot.tabId]?.pictureInPicture ||
380+
readActiveBrowserRecordingTargets(threadRef).some(
381+
(recording) => recording.runtimeTabId === runtimeTabId,
382+
)
383+
) {
384+
continue;
385+
}
386+
// The broker is about to evict this host. Unmount the hidden guest now
387+
// so an animated page cannot keep allocating GPU surfaces offscreen.
388+
void closePreviewSession({
389+
closePreview: close,
390+
snapshot,
391+
tabId: snapshot.tabId,
392+
threadRef,
393+
}).then((result) => {
394+
if (result._tag === "Success") hiddenAutomationTabsRef.current.delete(runtimeTabId);
395+
});
396+
}
397+
}, [close]);
356398

357399
const handleRequest = useCallback(
358400
async (request: PreviewAutomationRequest): Promise<unknown> => {
359401
// Session sync and tab creation consume the same budget as overlay registration.
360-
const hostDeadlineMs = Date.now() + resolveHostWaitBudgetMs(request.timeoutMs);
402+
const startedAt = Date.now();
403+
const hostDeadlineMs = startedAt + resolveHostWaitBudgetMs(request.timeoutMs);
404+
const requestDeadlineMs = startedAt + request.timeoutMs;
361405
const threadRef: ScopedThreadRef = {
362406
environmentId,
363407
threadId: request.threadId,
@@ -477,6 +521,10 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
477521
readThreadPreviewState(threadRef).serverEpoch,
478522
activeTabId,
479523
);
524+
if (!reusedExistingTab && explicitlySuppressesPreviewMiniPlayer(input)) {
525+
hiddenAutomationTabsRef.current.set(activeRuntimeTabId, threadRef);
526+
if (Date.now() >= requestDeadlineMs) reclaimTimedOutHiddenTabs();
527+
}
480528
if (activeSnapshot) {
481529
const defaultViewport = previewAutomationDefaultViewport(
482530
reusedExistingTab,
@@ -540,6 +588,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
540588
}
541589
}
542590
if (shouldPresentPreview) {
591+
hiddenAutomationTabsRef.current.delete(activeRuntimeTabId);
543592
usePreviewMiniPlayerStore
544593
.getState()
545594
.open(threadRef, browserMiniPlayerSource(activeTabId));
@@ -794,7 +843,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
794843
browserActivity.release?.();
795844
}
796845
},
797-
[environmentId, listPreviews, open, registry, resize],
846+
[environmentId, listPreviews, open, reclaimTimedOutHiddenTabs, registry, resize],
798847
);
799848
const [requestHandlerAtom] = useState(() => Atom.make({ handle: handleRequest }));
800849
const setRequestHandler = useAtomSet(requestHandlerAtom);
@@ -815,6 +864,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
815864
environmentId,
816865
input: response,
817866
}),
867+
onTimeout: reclaimTimedOutHiddenTabs,
818868
label: `preview:automation-host:${environmentId}:${automationClientId}`,
819869
}),
820870
[
@@ -823,6 +873,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
823873
automationRequestsAtom,
824874
requestHandlerAtom,
825875
respondToAutomation,
876+
reclaimTimedOutHiddenTabs,
826877
environmentId,
827878
],
828879
);

0 commit comments

Comments
 (0)