fix(preview): resize hidden browser tabs reliably #8469
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 20 commits into
main fromfix/preview-hidden-viewport-v2opened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/desktop/src/preview/Manager.ts line 2553OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2448,0 +2533,21 @@2533+ });2534+ yield* applyInitial(intent.input).pipe(Effect.ensuring(reconcileLatest.pipe(Effect.ignore)));2535+ });2536+2537+ // Human/toolbar path. Must not take agent control or write a resize action.2538+ const setViewport = Effect.fn("PreviewManager.setViewport")(function* (2539+ tabId: string,2540+ input: PreviewViewportOverride,2541+ ) {2542+ const wc = yield* requireWebContents(tabId);2543+ const intent = yield* rememberViewportOverride(tabId, input);2544+ yield* settleViewportIntent(tabId, wc, intent, (latest) =>2545+ applyViewportOverride(tabId, wc, latest),2546+ );2547+ });2548+2549+ const automationSetViewport = Effect.fn("PreviewManager.automationSetViewport")(function* (2550+ tabId: string,2551+ input: PreviewViewportOverride,2552+ ) {2553+ const wc = yield* requireWebContents(tabId);apps/web/src/components/preview/PreviewAutomationHosts.tsx line 603OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -522,5 +598,6 @@522598 previousSetting,523599 serverEpoch: operationState.serverEpoch,524600 };525- });526- let viewport: PreviewRenderedViewportSize;601+ };602+ const mutationDeadline = { deadlineAt, timeoutError };603+ const applied = await runBrowserViewportMutation(
- @@ -2446,3 +2467,11 @@24462467 );24472468 });244824692470+ const deviceMetricsOverride = Effect.fnUntraced(function* (2471+ tabId: string,2472+ input: { readonly width: number; readonly height: number },2473+ ) {2474+ const zoomFactor = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.zoomFactor ?? 1;2475+ return {2476+ width: Math.max(1, Math.round(input.width * zoomFactor)),2477+ height: Math.max(1, Math.round(input.height * zoomFactor)),@@ -2448,0 +2545,21 @@2545+ applyViewportOverride(tabId, wc, latest),2546+ );2547+ });2548+2549+ const automationSetViewport = Effect.fn("PreviewManager.automationSetViewport")(function* (2550+ tabId: string,2551+ input: PreviewViewportOverride,2552+ ) {2553+ const wc = yield* requireWebContents(tabId);2554+ const intent = yield* rememberViewportOverride(tabId, input);2555+ yield* withControlSession(tabId, wc, "resize", (send) =>2556+ settleViewportIntent(tabId, wc, intent, (latest) => {2557+ if ("clear" in latest) {2558+ return send("Emulation.clearDeviceMetricsOverride").pipe(Effect.asVoid);2559+ }2560+ return deviceMetricsOverride(tabId, latest).pipe(2561+ Effect.flatMap((metrics) => send("Emulation.setDeviceMetricsOverride", metrics)),2562+ Effect.asVoid,2563+ );2564+ }),2565+ );apps/web/src/components/preview/previewViewportRollback.ts line 18OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2,3 +2,17 @@2233 import { browserViewportSettingKey } from "~/browser/browserViewportLayout";445+export async function applyPreviewViewportRollback(options: {6+ readonly previous: PreviewViewportSetting;7+ readonly requested: PreviewViewportSetting;8+ readonly applyGuest: (setting: PreviewViewportSetting) => Promise<void>;9+ readonly rollbackServer: () => Promise<boolean>;10+}): Promise<void> {11+ void options.applyGuest(options.previous).catch(() => undefined);12+ let serverRolledBack = false;13+ try {14+ serverRolledBack = await options.rollbackServer();15+ } finally {16+ if (!serverRolledBack) {17+ void options.applyGuest(options.requested).catch(() => undefined);18+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -2448,0 +2571,21 @@2571+ applied = latest;2572+ appliedWebContents = currentWebContents;2573+ }2574+ }),2575+ );2576+ if (Exit.isFailure(initialExit)) return yield* Effect.failCause(initialExit.cause);2577+ if (Exit.isFailure(reconcileExit)) return yield* Effect.failCause(reconcileExit.cause);2578+ });2579+2580+ // Human/toolbar path. Must not take agent control or write a resize action.2581+ const setViewport = Effect.fn("PreviewManager.setViewport")(function* (2582+ tabId: string,2583+ input: PreviewViewportOverride,2584+ ) {2585+ const prepared = yield* prepareViewportIntent(tabId, input);2586+ yield* settleViewportIntent(2587+ tabId,2588+ prepared.wc,2589+ prepared.intent,2590+ prepared.generation,2591+ (latest) => applyViewportOverride(tabId, prepared.wc, latest),
- apps/web/src/browser/browserViewportActions.ts lines 58 to 64Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -26,7 +48,17 @@2648 const started = previous2749 .catch(() => undefined)2850 .then(() => ({29- operation: Promise.resolve().then(start),51+ operation:52+ deadline && Date.now() >= deadline.deadlineAt53+ ? Promise.reject<A>(deadline.timeoutError())54+ : Promise.resolve().then(start),3055 }));31- const execution = started.then(({ operation }) => operation);32- const tail = execution.then(() => undefined);56+ const operation = started.then(({ operation: startedOperation }) => startedOperation);57+ const execution = deadline ? runOperationBeforeDeadline(operation, deadline) : operation;58+ // If this mutation reached the front, its deadline releases the queue even59+ // when the underlying request never settles. A mutation that expires while60+ // waiting still follows the prior tail and cannot overtake it.61+ const tail = started62+ .then(({ operation: startedOperation }) =>63+ deadline ? runOperationBeforeDeadline(startedOperation, deadline) : startedOperation,64+ )apps/desktop/src/preview/Manager.ts line 2705Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2448,0 +2492,21 @@2492+2493+ const rememberViewportOverride = (tabId: string, input: PreviewViewportOverride) =>2494+ SynchronizedRef.modify(viewportOverridesRef, (overrides) => {2495+ const intent: PreviewViewportIntent = { input };2496+ return [2497+ intent,2498+ replaceMap(overrides, (copy) => {2499+ copy.set(tabId, intent);2500+ }),2501+ ] as const;2502+ });2503+2504+ const prepareViewportIntent = (tabId: string, input: PreviewViewportOverride) =>2505+ withTabLifecycleLock(2506+ tabId,2507+ Effect.gen(function* () {2508+ if ((yield* Ref.get(closingTabIdsRef)).has(tabId)) {2509+ return yield* new PreviewTabNotFoundError({ tabId });2510+ }2511+ const wc = yield* requireWebContents(tabId);2512+ const intent = yield* rememberViewportOverride(tabId, input);apps/web/src/previewStateStore.ts lines 409 to 415OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -353,3 +406,10 @@353406 snapshots.some((snapshot) => snapshot.tabId === tabId),354407 ),355408 );409+ const knownTabIds = sameServer410+ ? new Set([411+ ...Object.keys(current.serverRevisionByTabId),412+ ...Object.keys(current.sessions),413+ ...Object.keys(sessions),414+ ])415+ : new Set(Object.keys(sessions));apps/desktop/src/preview/Manager.ts line 2548OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2448,0 +2528,21 @@2528+ yield* attemptPromise(2529+ { operation: "applyViewportOverride", tabId, webContentsId: wc.id },2530+ () => wc.debugger.sendCommand("Emulation.clearDeviceMetricsOverride"),2531+ );2532+ return;2533+ }2534+ const metrics = yield* deviceMetricsOverride(tabId, input);2535+ yield* attemptPromise({ operation: "applyViewportOverride", tabId, webContentsId: wc.id }, () =>2536+ wc.debugger.sendCommand("Emulation.setDeviceMetricsOverride", metrics),2537+ );2538+ });2539+2540+ const settleViewportIntent = Effect.fnUntraced(function* (2541+ tabId: string,2542+ wc: Electron.WebContents,2543+ intent: PreviewViewportIntent,2544+ generation: number | undefined,2545+ applyInitial: (input: PreviewViewportOverride) => Effect.Effect<void, PreviewManagerError>,2546+ ) {2547+ const initialExit = yield* Effect.exit(applyInitial(intent.input));2548+ const reconcileExit = yield* Effect.exit(
- apps/desktop/src/preview/Manager.ts line 2577OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2448,0 +2557,21 @@2557+ const current = (yield* SynchronizedRef.get(tabsRef)).get(tabId);2558+ if (!current) return yield* new PreviewTabNotFoundError({ tabId });2559+ if (current.webContentsId == null) {2560+ return yield* new PreviewWebviewNotInitializedError({ tabId });2561+ }2562+ const currentWebContents = webContents.fromId(current.webContentsId);2563+ if (!currentWebContents || currentWebContents.isDestroyed()) {2564+ return yield* new PreviewWebContentsNotFoundError({2565+ tabId,2566+ webContentsId: current.webContentsId,2567+ });2568+ }2569+ if (latest === applied && currentWebContents === appliedWebContents) return;2570+ yield* applyViewportOverride(tabId, currentWebContents, latest.input);2571+ applied = latest;2572+ appliedWebContents = currentWebContents;2573+ }2574+ }),2575+ );2576+ if (Exit.isFailure(initialExit)) return yield* Effect.failCause(initialExit.cause);2577+ if (Exit.isFailure(reconcileExit)) return yield* Effect.failCause(reconcileExit.cause);
- apps/web/src/previewStateStore.ts line 328OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -297,5 +312,17 @@297312 updateThreadPreviewState(ref, (current) => {298- if (current.suppressedTabIds.has(snapshot.tabId)) return current;299- const existing = current.sessions[snapshot.tabId];300- if (existing && existing.updatedAt > snapshot.updatedAt) return current;301- const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };313+ const stateVersion = snapshot.stateVersion;314+ if (stateVersion) {315+ if (current.serverEpoch !== null && stateVersion.serverEpoch !== current.serverEpoch) {316+ return current;317+ }318+ const tabRevision = current.serverRevisionByTabId[snapshot.tabId] ?? 0;319+ if (stateVersion.revision < tabRevision) return current;320+ }321+ const {322+ stateVersion: _stateVersion,323+ previousViewport: _previousViewport,324+ ...sessionSnapshot325+ } = snapshot;326+ if (current.suppressedTabIds.has(sessionSnapshot.tabId)) return current;327+ const existing = current.sessions[sessionSnapshot.tabId];328+ if (existing && existing.updatedAt > sessionSnapshot.updatedAt) return current;
- apps/web/src/previewStateStore.ts line 261Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -243,2 +241,21 @@241+ sessions,242+ snapshot: current.activeTabId === event.tabId ? failedSnapshot : current.snapshot,243+ };244+ }245+ case "closed": {246+ const closed = removeSession(current, event.tabId);247+ if (!closed.suppressedTabIds.has(event.tabId)) return closed;248+ const suppressedTabIds = new Set(closed.suppressedTabIds);249+ suppressedTabIds.delete(event.tabId);250+ return { ...closed, suppressedTabIds };251+ }252+ }253+ })();254+ const serverRevisionByTabId = (() => {255+ if (!next.sessions[event.tabId]) {256+ if (current.serverRevisionByTabId[event.tabId] === undefined) {257+ return current.serverRevisionByTabId;243258 }259+ const { [event.tabId]: _removed, ...remaining } = current.serverRevisionByTabId;260+ return remaining;244261 }
- apps/web/src/components/preview/PreviewAutomationHosts.tsx line 472OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -438,3 +469,4 @@438469 },439470 });440471 },472+ { deadlineAt: requestDeadlineAt, timeoutError },
- @@ -2613,0 +2818,21 @@2818+ prepared.generation,2819+ (latest) => applyViewportOverride(tabId, prepared.wc, latest),2820+ ).pipe(2821+ Effect.tap(() => acceptViewportOverride(prepared.intent)),2822+ Effect.onError(() => rollbackViewportOverride(tabId, prepared.intent, prepared.generation)),2823+ );2824+ });2825+2826+ const automationSetViewport = Effect.fn("PreviewManager.automationSetViewport")(function* (2827+ tabId: string,2828+ input: PreviewViewportOverride,2829+ ) {2830+ const prepared = yield* prepareViewportIntent(tabId, input);2831+ yield* withControlSession(tabId, prepared.wc, "resize", (send) =>2832+ settleViewportIntent(tabId, prepared.wc, prepared.intent, prepared.generation, (latest) => {2833+ if ("clear" in latest) {2834+ return send("Emulation.clearDeviceMetricsOverride").pipe(Effect.asVoid);2835+ }2836+ return deviceMetricsOverride(tabId, latest).pipe(2837+ Effect.flatMap((metrics) => send("Emulation.setDeviceMetricsOverride", metrics)),2838+ Effect.asVoid,apps/desktop/src/preview/Manager.ts line 2784OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2613,0 +2764,21 @@2764+ const restored = yield* restorePreviousViewportOverride(tabId, intent);2765+ if (restored) yield* reconcileViewportRollback(tabId, generation);2766+ }).pipe(Effect.ignore);2767+2768+ const settleViewportIntent = Effect.fnUntraced(function* (2769+ tabId: string,2770+ wc: Electron.WebContents,2771+ intent: PreviewViewportIntent,2772+ generation: number | undefined,2773+ applyInitial: (input: PreviewViewportOverride) => Effect.Effect<void, PreviewManagerError>,2774+ ) {2775+ const initialExit = yield* Effect.exit(applyInitial(intent.input));2776+ if (Exit.isFailure(initialExit)) return yield* Effect.failCause(initialExit.cause);2777+ const reconcileExit = yield* Effect.exit(2778+ Effect.gen(function* () {2779+ let applied = intent;2780+ let appliedWebContents = wc;2781+ while (true) {2782+ const latest = (yield* SynchronizedRef.get(viewportOverridesRef)).get(tabId);2783+ if (!latest || tabLifecycleGenerations.get(tabId) !== generation) {2784+ return yield* new PreviewTabNotFoundError({ tabId });
- @@ -197,3 +211,10 @@197211 deviceToolbarVisible,198212 aspectRatio: lockedAspectRatio,199213 });214+ const guestViewportKey = browserViewportSettingKey(effectiveViewport);215+ guestViewportRef.current = effectiveViewport;216+ useEffect(() => {217+ const setViewport = previewBridge?.setViewport;218+ if (!setViewport || !hasWebContents) return;219+ const frame = window.requestAnimationFrame(() => {220+ void applyPreviewGuestViewport(setViewport, runtimeTabId, guestViewportRef.current).catch(
- @@ -2613,0 +2824,21 @@2824+ applied = current.intent;2825+ appliedWebContents = current.wc;2826+ }2827+ });2828+2829+ // Human/toolbar path. Must not take agent control or write a resize action.2830+ const setViewport = Effect.fn("PreviewManager.setViewport")(function* (2831+ tabId: string,2832+ input: PreviewViewportOverride,2833+ ) {2834+ const prepared = yield* prepareViewportIntent(tabId, input);2835+ yield* settleViewportIntent(2836+ tabId,2837+ prepared.wc,2838+ prepared.intent,2839+ prepared.generation,2840+ (latest) => applyViewportOverride(tabId, prepared.wc, latest),2841+ ).pipe(2842+ Effect.tap(() => acceptViewportOverride(prepared.intent)),2843+ Effect.onError(() => rollbackViewportOverride(tabId, prepared.intent, prepared.generation)),2844+ );
juliusmarminge added labelsmacroscope-review
juliusmarminge requested changes
tanstack-source added labelsbug
t3dotgg(GitHub profile, opens in a new tab) linked this to fix #3712
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
2f92fdcd-4721-4ce1-93bf-cc0f3b60e19dYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Comment `@coderabbitai help` to get the list of available commands.