Skip to content

Commit 45ae805

Browse files
fix(desktop): background agent tabs keep their host so the page is never reloaded
Moving a tab from its hidden window into a panel webview replaces the page, losing whatever the agent had built up in it. A tab's host is now fixed when it first appears, and the panel streams a background tab like a server tab. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4d5013a commit 45ae805

6 files changed

Lines changed: 24 additions & 107 deletions

File tree

‎apps/desktop/src/preview/Manager.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -722,7 +722,7 @@ describe("PreviewManager", () => {
722722
);
723723

724724
effectIt.effect(
725-
"hosts an agent tab in a never-shown window until a panel webview takes it over",
725+
"hosts an agent tab in a never-shown window until a panel webview replaces it",
726726
() =>
727727
withManager((manager) =>
728728
Effect.gen(function* () {
@@ -767,7 +767,6 @@ describe("PreviewManager", () => {
767767
});
768768
expect(state.webContentsId).toBe(55);
769769
expect(loadURL).toHaveBeenCalledWith("https://example.com/agent");
770-
// Back on screen, the renderer moves the tab into a panel webview.
771770
fromId.mockReturnValue(
772771
makeTestPreviewWebContents(async () => ({
773772
toJPEG: () => Buffer.from(""),

‎apps/desktop/src/preview/Manager.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2086,7 +2086,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
20862086
return yield* withTabLifecycleLock(
20872087
tabId,
20882088
registerWebviewUnlocked(tabId, webContentsId, expectedGeneration).pipe(
2089-
// The renderer moved a background tab into the panel once T3 was on screen again.
2089+
// A reloaded renderer may host a background tab in a panel webview instead.
20902090
Effect.tap(() => Effect.sync(() => closeBackgroundWindow(tabId))),
20912091
),
20922092
);

‎apps/web/src/browser/ElectronBrowserHost.browser.test.tsx‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ import {
6767
import { reconcilePreviewServerSessions, resetPreviewStateForTests } from "~/previewStateStore";
6868
import { AppAtomRegistryProvider } from "~/rpc/atomRegistry";
6969
import { ElectronBrowserHost } from "./ElectronBrowserHost";
70-
import { useRendersServerTabNatively } from "./previewRuntime";
70+
import { rendersServerTabNatively } from "./previewRuntime";
7171

7272
const threadRef = scopeThreadRef(
7373
EnvironmentId.make("host-webview-order"),
@@ -218,20 +218,15 @@ describe("ElectronBrowserHost", () => {
218218
url: `https://example.com/${tabId}`,
219219
});
220220
expect(screen.container.querySelectorAll("webview")).toHaveLength(0);
221-
// Back on screen, a tab nobody views keeps its live page; the viewed one moves into the panel.
222-
await act(() => window.dispatchEvent(new Event("focus")));
221+
// Moving hosts would reload the agent's page, so it stays streamed once T3 is back.
222+
window.desktopBridge = {
223+
getWindowShown: () => true,
224+
getWindowZoomFactor: () => 1,
225+
} as never;
226+
expect(
227+
rendersServerTabNatively(threadRef.environmentId, threadRef.environmentId, agentTab),
228+
).toBe(false);
223229
expect(screen.container.querySelectorAll("webview")).toHaveLength(0);
224-
function Viewer() {
225-
useRendersServerTabNatively(threadRef.environmentId, agentTab);
226-
return null;
227-
}
228-
await using _viewer = await render(
229-
<AppAtomRegistryProvider>
230-
<Viewer />
231-
</AppAtomRegistryProvider>,
232-
);
233-
await act(() => window.dispatchEvent(new Event("focus")));
234-
expect(screen.container.querySelectorAll("webview")).toHaveLength(1);
235230
}
236231
},
237232
);

‎apps/web/src/browser/ElectronBrowserHost.tsx‎

Lines changed: 4 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -31,20 +31,13 @@ import { useBrowserPointerStore } from "./browserPointerStore";
3131
import { HostedBrowserWebview } from "./HostedBrowserWebview";
3232
import { openUrlInPreview } from "./openFileInPreview";
3333
import { acquireDesktopTab } from "./desktopTabLifetime";
34-
import {
35-
type BackgroundHosting,
36-
hostsServerTabInBackground,
37-
readBackgroundHosting,
38-
rendersServerTabNatively,
39-
useBackgroundHosting,
40-
} from "./previewRuntime";
34+
import { hostsServerTabInBackground, rendersServerTabNatively } from "./previewRuntime";
4135
import { previewRuntimeTabId } from "./previewRuntimeTabId";
4236

4337
/** Every session this window renders as a hosted webview, in a fixed (non-display) order. */
4438
function hostedBrowserSessions(
4539
previewByThreadKey: Record<string, ThreadPreviewState>,
4640
primaryEnvironmentId: EnvironmentId | null,
47-
hosting: BackgroundHosting,
4841
) {
4942
const activeSessions = Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
5043
const threadRef = parseScopedThreadKey(threadKey);
@@ -53,18 +46,8 @@ function hostedBrowserSessions(
5346
.filter(
5447
(snapshot) =>
5548
snapshot.runtime !== "server" ||
56-
rendersServerTabNatively(
57-
threadRef.environmentId,
58-
primaryEnvironmentId,
59-
snapshot,
60-
hosting,
61-
) ||
62-
hostsServerTabInBackground(
63-
threadRef.environmentId,
64-
primaryEnvironmentId,
65-
snapshot,
66-
hosting,
67-
),
49+
rendersServerTabNatively(threadRef.environmentId, primaryEnvironmentId, snapshot) ||
50+
hostsServerTabInBackground(threadRef.environmentId, primaryEnvironmentId, snapshot),
6851
)
6952
.map((snapshot) => ({
7053
threadRef,
@@ -73,7 +56,6 @@ function hostedBrowserSessions(
7356
threadRef.environmentId,
7457
primaryEnvironmentId,
7558
snapshot,
76-
hosting,
7759
),
7860
runtimeTabId: previewRuntimeTabId(threadRef, previewState.serverEpoch, snapshot.tabId),
7961
pictureInPicture:
@@ -124,7 +106,6 @@ function openLinkInPreview({ tabId, url, background }: DesktopPreviewOpenLinkEve
124106
const source = hostedBrowserSessions(
125107
readActivePreviewSessions(),
126108
appAtomRegistry.get(primaryEnvironmentIdAtom),
127-
readBackgroundHosting(),
128109
).find((session) => session.runtimeTabId === tabId);
129110
if (!source) return;
130111
void openUrlInPreview({
@@ -156,11 +137,7 @@ export function ElectronBrowserHost() {
156137
const previewByThreadKey = useActivePreviewSessions();
157138
const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
158139
useDesktopHostedPreviewSessions(primaryEnvironmentId);
159-
const sessions = hostedBrowserSessions(
160-
previewByThreadKey,
161-
primaryEnvironmentId,
162-
useBackgroundHosting(),
163-
);
140+
const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId);
164141

165142
if (!isElectron) return null;
166143
return (

‎apps/web/src/browser/previewRuntime.ts‎

Lines changed: 7 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { useAtomValue } from "@effect/atom-react";
2-
import { useEffect, useSyncExternalStore } from "react";
32
import type { EnvironmentId, PreviewRuntime, PreviewSessionSnapshot } from "@t3tools/contracts";
43

54
import { isElectron } from "~/env";
@@ -62,46 +61,18 @@ function desktopHostsServerTab(
6261
);
6362
}
6463

65-
// Fixed when a tab first appears, until someone views it with T3 on screen: moving a page between
66-
// hosts replaces it, so a tab nobody looks at keeps its live page in the background window.
67-
let backgroundHostedTabs = new Map<string, boolean>();
68-
const hostingListeners = new Set<() => void>();
69-
70-
const hostingKey = (environmentId: EnvironmentId, snapshot: RuntimeSnapshot) =>
71-
`${environmentId}\u0000${snapshot.threadId}\u0000${snapshot.tabId}`;
72-
73-
// A new map makes memoized callers look again.
74-
const returnTabToPanel = (key: string) => {
75-
if (backgroundHostedTabs.get(key) !== true) return;
76-
backgroundHostedTabs = new Map(backgroundHostedTabs).set(key, false);
77-
for (const listener of hostingListeners) listener();
78-
};
79-
80-
const subscribeBackgroundHosting = (listener: () => void) => {
81-
hostingListeners.add(listener);
82-
return () => {
83-
hostingListeners.delete(listener);
84-
};
85-
};
86-
87-
export type BackgroundHosting = ReadonlyMap<string, boolean>;
88-
89-
export const readBackgroundHosting = (): BackgroundHosting => backgroundHostedTabs;
90-
91-
export function useBackgroundHosting(): BackgroundHosting {
92-
return useSyncExternalStore(subscribeBackgroundHosting, readBackgroundHosting);
93-
}
64+
// Fixed when a tab first appears: Electron cannot move a page between a window and a
65+
// `<webview>`, so changing hosts later would reload it and lose the agent's live page.
66+
const backgroundHostedTabs = new Map<string, boolean>();
9467

9568
/**
9669
* A panel `<webview>` created while the app window is hidden or minimized never paints, so an
9770
* agent tab that appears then runs in a never-shown desktop window and the panel streams it.
98-
* `hosting` is the map from `useBackgroundHosting`, passed so memoized callers recompute.
9971
*/
10072
export function hostsServerTabInBackground(
10173
environmentId: EnvironmentId,
10274
primaryEnvironmentId: EnvironmentId | null,
10375
snapshot: RuntimeSnapshot | null | undefined,
104-
hosting: BackgroundHosting,
10576
): boolean {
10677
if (
10778
!snapshot ||
@@ -110,8 +81,8 @@ export function hostsServerTabInBackground(
11081
) {
11182
return false;
11283
}
113-
const key = hostingKey(environmentId, snapshot);
114-
const decided = backgroundHostedTabs.get(key) ?? hosting.get(key);
84+
const key = `${environmentId}\u0000${snapshot.threadId}\u0000${snapshot.tabId}`;
85+
const decided = backgroundHostedTabs.get(key);
11586
if (decided !== undefined) return decided;
11687
const background = window.desktopBridge?.getWindowShown?.() === false;
11788
backgroundHostedTabs.set(key, background);
@@ -122,35 +93,16 @@ export function rendersServerTabNatively(
12293
environmentId: EnvironmentId,
12394
primaryEnvironmentId: EnvironmentId | null,
12495
snapshot: RuntimeSnapshot | null | undefined,
125-
hosting: BackgroundHosting,
12696
): boolean {
12797
return (
12898
desktopHostsServerTab(environmentId, primaryEnvironmentId, snapshot) &&
129-
!hostsServerTabInBackground(environmentId, primaryEnvironmentId, snapshot, hosting)
99+
!hostsServerTabInBackground(environmentId, primaryEnvironmentId, snapshot)
130100
);
131101
}
132102

133-
/** For the tab the panel shows: a background tab moves into the panel once T3 has focus. */
134103
export function useRendersServerTabNatively(
135104
environmentId: EnvironmentId,
136105
snapshot: RuntimeSnapshot | null | undefined,
137106
): boolean {
138-
const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
139-
const hosting = useBackgroundHosting();
140-
const background = hostsServerTabInBackground(
141-
environmentId,
142-
primaryEnvironmentId,
143-
snapshot,
144-
hosting,
145-
);
146-
const backgroundKey = background && snapshot ? hostingKey(environmentId, snapshot) : null;
147-
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves the viewed tab into the panel when the app window has focus, which React does not track
148-
useEffect(() => {
149-
if (backgroundKey === null) return;
150-
const moveToPanel = () => returnTabToPanel(backgroundKey);
151-
if (document.hasFocus()) moveToPanel();
152-
window.addEventListener("focus", moveToPanel);
153-
return () => window.removeEventListener("focus", moveToPanel);
154-
}, [backgroundKey]);
155-
return desktopHostsServerTab(environmentId, primaryEnvironmentId, snapshot) && !background;
107+
return rendersServerTabNatively(environmentId, useAtomValue(primaryEnvironmentIdAtom), snapshot);
156108
}

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

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
2525
import type { BrowserViewportResizeDirection } from "~/browser/browserViewportLayout";
2626
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
27-
import { rendersServerTabNatively, useBackgroundHosting } from "~/browser/previewRuntime";
27+
import { rendersServerTabNatively } from "~/browser/previewRuntime";
2828
import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
2929
import { type ServerBrowserHandle, ServerBrowserSurface } from "~/browser/ServerBrowserSurface";
3030
import {
@@ -138,16 +138,10 @@ function useBrowserMiniPlayerSource(threadRef: ScopedThreadRef | null, tabId: st
138138
runtimeTabId === null ? null : (state.byTabId[runtimeTabId]?.fittedSourceContent ?? null),
139139
);
140140
const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
141-
const backgroundHosting = useBackgroundHosting();
142141
const serverTab =
143142
threadRef !== null &&
144143
snapshot?.runtime === "server" &&
145-
!rendersServerTabNatively(
146-
threadRef.environmentId,
147-
primaryEnvironmentId,
148-
snapshot,
149-
backgroundHosting,
150-
);
144+
!rendersServerTabNatively(threadRef.environmentId, primaryEnvironmentId, snapshot);
151145
const streamViewport = useStreamedSourceSize((state) =>
152146
threadRef &&
153147
tabId !== null &&

0 commit comments

Comments
 (0)