Skip to content

Commit c014e36

Browse files
refactor(web): resize drags, panel shells and the browser host own their listeners
The right panel, sidebar rail and Electron browser host kept DOM listeners, leases and drag state alive through effects that re-read "latest" refs, and the panel shell re-rendered two frames after every resize to restore its width transition. - useResizeDrag: one drag object per handle; blur is listened to only during a drag, the handle's ref abandons a drag on unmount, and bounds travel with the session instead of a latest-options ref. - useResizableWidth: a drag commits to the storage key and width it started from; only the mid-drag bounds refresh stays a layout effect. - usePreviewPanelInlineSize / PreviewPanelShell: the shell's ref callback measures the row; the width transition is disabled in the commit that changes width and re-enabled by the next open/close, so no rAF effect or extra render. Focus/inert effects are unchanged. - sidebar: open state lives in a per-provider store, so collapsing moves focus out and cancels a rail drag from the handler; inert is a prop. The rail's width-restore effect is dropped (AppSidebarLayout already restores). - RightPanelTabs: the tab strip's scroll, resize and wheel listeners are owned by its ref callback. - BrowserSurfaceSlot: the surface lease is owned by the slot's ref callback. - ElectronBrowserHost: annotation theme sync, agent pointer and open-link listeners start with the app services. Effects in touched files: 21 -> 7. Kept: tab scrollIntoView, the two keyboard listeners in RightPanelTabs, the panel shell focus/inert pair, the slot's presentation update, and the resizable width bounds refresh. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0712398 commit c014e36

12 files changed

Lines changed: 435 additions & 314 deletions

‎apps/web/src/appInit.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createBrowserHistory, createHashHistory } from "@tanstack/react-router"
44

55
import { applyAppearanceContrast } from "./appearanceContrast";
66
import { applyAppearanceFontVariables } from "./appearanceFonts";
7+
import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
78
import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
89
import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
910
import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
@@ -141,6 +142,7 @@ export function startAppServices(): AppRouter {
141142
startDefaultThemeAdoption();
142143
startModelPreferencesMigration();
143144
startAgentOpenedPreviews();
145+
if (isElectron) startElectronBrowserHost();
144146
startThreadOverlayRetention(router);
145147
startMainAppLocationTracking(router);
146148
startBackgroundThreadAnnouncements(appAtomRegistry, router);

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,11 @@ export function BrowserSurfaceSlot(props: {
2121
className,
2222
fitSourceContent = false,
2323
} = props;
24-
const elementRef = useRef<HTMLDivElement | null>(null);
2524
const presentationRef = useRef({ visible, cornerRadius, zIndex });
2625
const updateRef = useRef<(() => void) | null>(null);
2726

28-
useLayoutEffect(() => {
29-
const element = elementRef.current;
30-
if (!element) return;
27+
// The lease lives as long as this element for one tab, so the ref callback owns it.
28+
const attachSurface = (element: HTMLDivElement) => {
3129
let lease = acquireBrowserSurface(tabId, fitSourceContent);
3230
const update = () => {
3331
const rect = element.getBoundingClientRect();
@@ -77,7 +75,7 @@ export function BrowserSurfaceSlot(props: {
7775
if (updateRef.current === update) updateRef.current = null;
7876
lease.release();
7977
};
80-
}, [fitSourceContent, tabId]);
78+
};
8179

8280
useLayoutEffect(() => {
8381
presentationRef.current = { visible, cornerRadius, zIndex };
@@ -90,5 +88,5 @@ export function BrowserSurfaceSlot(props: {
9088
zIndex,
9189
]);
9290

93-
return <div ref={elementRef} className={className} data-browser-surface-slot={tabId} />;
91+
return <div ref={attachSurface} className={className} data-browser-surface-slot={tabId} />;
9492
}

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

Lines changed: 80 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
11
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
22
import {
33
AuthPreviewOperateScope,
4+
type DesktopPreviewBridge,
45
type DesktopPreviewOpenLinkEvent,
6+
type EnvironmentId,
57
FILL_PREVIEW_VIEWPORT,
68
} from "@t3tools/contracts";
79
import { useAtomValue } from "@effect/atom-react";
8-
import { type ComponentProps, useEffect, useEffectEvent, useState } from "react";
10+
import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
11+
import { type ComponentProps, useState } from "react";
912

1013
import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
1114

1215
import { isElectron } from "~/env";
1316
import { useClientSettingsHydrated } from "~/hooks/useSettings";
1417
import { useDesktopHostedPreviewSessions } from "~/components/preview/usePreviewSession";
15-
import { useActivePreviewSessions } from "~/previewStateStore";
18+
import {
19+
readActivePreviewSessions,
20+
type ThreadPreviewState,
21+
useActivePreviewSessions,
22+
} from "~/previewStateStore";
23+
import { appAtomRegistry } from "~/rpc/atomRegistry";
1624
import { previewEnvironment } from "~/state/preview";
1725
import { useEnvironmentScope } from "~/state/session";
18-
import { useAtomCommand } from "~/state/use-atom-command";
1926

2027
import { readPreviewAnnotationTheme } from "./annotationTheme";
2128
import { useBrowserDefaults } from "./browserDefaults";
@@ -25,10 +32,11 @@ import { openUrlInPreview } from "./openFileInPreview";
2532
import { rendersServerTabNatively } from "./previewRuntime";
2633
import { previewRuntimeTabId } from "./previewRuntimeTabId";
2734

28-
export function ElectronBrowserHost() {
29-
const previewByThreadKey = useActivePreviewSessions();
30-
const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
31-
useDesktopHostedPreviewSessions(primaryEnvironmentId);
35+
/** Every session this window renders as a hosted webview, in a fixed (non-display) order. */
36+
function hostedBrowserSessions(
37+
previewByThreadKey: Record<string, ThreadPreviewState>,
38+
primaryEnvironmentId: EnvironmentId | null,
39+
) {
3240
const activeSessions = Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
3341
const threadRef = parseScopedThreadKey(threadKey);
3442
return threadRef
@@ -50,68 +58,78 @@ export function ElectronBrowserHost() {
5058
});
5159
// Electron destroys a moved webview's guest, so the render order must not follow the server's
5260
// updatedAt order. Any fixed order works; this one is not a display order.
53-
const sessions = activeSessions.toSorted((left, right) =>
61+
return activeSessions.toSorted((left, right) =>
5462
left.runtimeTabId < right.runtimeTabId ? -1 : left.runtimeTabId > right.runtimeTabId ? 1 : 0,
5563
);
64+
}
5665

57-
useEffect(() => {
58-
const preview = window.desktopBridge?.preview;
59-
if (!preview) return;
60-
61-
let lastSerializedTheme = "";
62-
const syncTheme = () => {
63-
const theme = readPreviewAnnotationTheme();
64-
const serializedTheme = JSON.stringify(theme);
65-
if (serializedTheme === lastSerializedTheme) return;
66-
lastSerializedTheme = serializedTheme;
67-
void preview.setAnnotationTheme(theme).catch(() => {
68-
lastSerializedTheme = "";
69-
});
70-
};
71-
const frameId = window.requestAnimationFrame(syncTheme);
72-
const observer = new MutationObserver(syncTheme);
73-
observer.observe(document.documentElement, {
74-
attributes: true,
75-
attributeFilter: ["class", "style"],
76-
});
77-
const headObserver = new MutationObserver(syncTheme);
78-
headObserver.observe(document.head, {
79-
childList: true,
80-
subtree: true,
81-
characterData: true,
66+
function startAnnotationThemeSync(preview: DesktopPreviewBridge): () => void {
67+
let lastSerializedTheme = "";
68+
const syncTheme = () => {
69+
const theme = readPreviewAnnotationTheme();
70+
const serializedTheme = JSON.stringify(theme);
71+
if (serializedTheme === lastSerializedTheme) return;
72+
lastSerializedTheme = serializedTheme;
73+
void preview.setAnnotationTheme(theme).catch(() => {
74+
lastSerializedTheme = "";
8275
});
83-
return () => {
84-
window.cancelAnimationFrame(frameId);
85-
observer.disconnect();
86-
headObserver.disconnect();
87-
};
88-
}, []);
76+
};
77+
// App services start before the first paint, when the theme styles may not be applied yet.
78+
const frameId = window.requestAnimationFrame(syncTheme);
79+
const observer = new MutationObserver(syncTheme);
80+
observer.observe(document.documentElement, {
81+
attributes: true,
82+
attributeFilter: ["class", "style"],
83+
});
84+
const headObserver = new MutationObserver(syncTheme);
85+
headObserver.observe(document.head, {
86+
childList: true,
87+
subtree: true,
88+
characterData: true,
89+
});
90+
return () => {
91+
window.cancelAnimationFrame(frameId);
92+
observer.disconnect();
93+
headObserver.disconnect();
94+
};
95+
}
8996

90-
useEffect(() => {
91-
const preview = window.desktopBridge?.preview;
92-
if (!preview) return;
93-
return preview.onPointerEvent((event) => {
97+
function openLinkInPreview({ tabId, url, background }: DesktopPreviewOpenLinkEvent): void {
98+
const source = hostedBrowserSessions(
99+
readActivePreviewSessions(),
100+
appAtomRegistry.get(primaryEnvironmentIdAtom),
101+
).find((session) => session.runtimeTabId === tabId);
102+
if (!source) return;
103+
void openUrlInPreview({
104+
threadRef: source.threadRef,
105+
url,
106+
openPreview: (input) => runAtomCommand(appAtomRegistry, previewEnvironment.open, input),
107+
profileId: source.snapshot.profileId,
108+
background,
109+
});
110+
}
111+
112+
/** App-lifetime listeners for the desktop preview bridge: annotation theme, agent pointer, links. */
113+
export function startElectronBrowserHost(): () => void {
114+
const preview = window.desktopBridge?.preview;
115+
if (!preview) return () => {};
116+
const disposers = [
117+
startAnnotationThemeSync(preview),
118+
preview.onPointerEvent((event) => {
94119
useBrowserPointerStore.getState().apply(event);
95-
});
96-
}, []);
120+
}),
121+
preview.onOpenLink(openLinkInPreview),
122+
];
123+
return () => {
124+
for (const dispose of disposers) dispose();
125+
};
126+
}
97127

98-
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: true });
99-
const onOpenLink = useEffectEvent(({ tabId, url, background }: DesktopPreviewOpenLinkEvent) => {
100-
const source = sessions.find((session) => session.runtimeTabId === tabId);
101-
if (!source) return;
102-
void openUrlInPreview({
103-
threadRef: source.threadRef,
104-
url,
105-
openPreview,
106-
profileId: source.snapshot.profileId,
107-
background,
108-
});
109-
});
110-
useEffect(() => {
111-
const preview = window.desktopBridge?.preview;
112-
if (!preview) return;
113-
return preview.onOpenLink(onOpenLink);
114-
}, []);
128+
export function ElectronBrowserHost() {
129+
const previewByThreadKey = useActivePreviewSessions();
130+
const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
131+
useDesktopHostedPreviewSessions(primaryEnvironmentId);
132+
const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId);
115133

116134
if (!isElectron) return null;
117135
return (

‎apps/web/src/components/RightPanelTabs.tsx‎

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -981,10 +981,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
981981
return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true);
982982
}, [props.open]);
983983

984-
const updateTabScrollState = () => {
985-
const viewport = tabScrollViewport(tabListRef.current);
986-
if (!viewport) return;
987-
984+
const updateTabScrollState = (viewport: HTMLDivElement) => {
988985
const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
989986
const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
990987
const canScrollRight =
@@ -1183,34 +1180,19 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
11831180
setRenamingDevice(null);
11841181
});
11851182

1183+
// A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip.
11861184
useEffect(() => {
11871185
if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
11881186
const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
11891187
activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
11901188
}, [props.activeSurfaceId, tabScrollState.hasOverflow]);
11911189

1192-
useEffect(() => {
1193-
const viewport = tabScrollViewport(tabListRef.current);
1194-
if (!viewport) return;
1195-
1196-
const content = viewport.firstElementChild;
1197-
const stopObserving = observeResize(
1198-
content ? [viewport, content] : viewport,
1199-
updateTabScrollState,
1200-
);
1201-
viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
1202-
updateTabScrollState();
1203-
1204-
return () => {
1205-
stopObserving();
1206-
viewport.removeEventListener("scroll", updateTabScrollState);
1207-
};
1208-
}, [updateTabScrollState]);
1209-
1210-
useEffect(() => {
1211-
const viewport = tabScrollViewport(tabListRef.current);
1190+
const attachTabList = (root: HTMLDivElement | null) => {
1191+
tabListRef.current = root;
1192+
const viewport = tabScrollViewport(root);
12121193
if (!viewport) return;
12131194

1195+
const update = () => updateTabScrollState(viewport);
12141196
const handleWheel = (event: WheelEvent) => {
12151197
if (event.ctrlKey) return;
12161198
let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
@@ -1222,12 +1204,22 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
12221204
viewport.scrollLeft += delta;
12231205
if (viewport.scrollLeft === previousScrollLeft) return;
12241206
event.preventDefault();
1225-
updateTabScrollState();
1207+
update();
12261208
};
12271209

1210+
const content = viewport.firstElementChild;
1211+
const stopObserving = observeResize(content ? [viewport, content] : viewport, update);
1212+
viewport.addEventListener("scroll", update, { passive: true });
12281213
viewport.addEventListener("wheel", handleWheel, { passive: false });
1229-
return () => viewport.removeEventListener("wheel", handleWheel);
1230-
}, [updateTabScrollState]);
1214+
update();
1215+
1216+
return () => {
1217+
tabListRef.current = null;
1218+
stopObserving();
1219+
viewport.removeEventListener("scroll", update);
1220+
viewport.removeEventListener("wheel", handleWheel);
1221+
};
1222+
};
12311223

12321224
return (
12331225
<PreviewPanelShell
@@ -1250,7 +1242,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
12501242
>
12511243
<ScrollArea
12521244
radius="none"
1253-
ref={tabListRef}
1245+
ref={attachTabList}
12541246
hideScrollbars
12551247
scrollFade
12561248
className="min-w-0 flex-1"

‎apps/web/src/components/chat/ChatRightPanel.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export function ChatRightPanel(props: ChatRightPanelProps) {
2727
layoutControls,
2828
...tabs
2929
} = props;
30-
const inlineSize = usePreviewPanelInlineSize(undefined, {
30+
const inlineSize = usePreviewPanelInlineSize({
3131
container: workspaceLayoutElement,
3232
widthStorageKey,
3333
});

0 commit comments

Comments
 (0)