Skip to content
TypeScript

fix(web): the sidebar no longer keeps old renders alive (#19852)

Theo Browne2d31acb9751d
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 246a075bf93..65c00d70e3a 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -268,6 +268,7 @@ import {
type ProviderInstanceEntry,
} from "../providerInstances";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
+import { useStableCallback } from "../hooks/useStableCallback";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { Button, InlineButton } from "./ui/button";
import {
@@ -2628,20 +2629,19 @@ export default function Sidebar() {
() => projectGroupsSpanEnvironments(projectGroups),
[projectGroups],
);
- const scratchMachineLabelFor = useCallback(
- (thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">) => {
- if (!showProjectEnvironments) return null;
- const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`);
- if (
- !project ||
- !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot)
- ) {
- return null;
- }
- return environmentLabelById.get(thread.environmentId) ?? null;
- },
- [environmentLabelById, projectByKey, serverConfigs, showProjectEnvironments],
- );
+ const scratchMachineLabelFor = (
+ thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">,
+ ) => {
+ if (!showProjectEnvironments) return null;
+ const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`);
+ if (
+ !project ||
+ !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot)
+ ) {
+ return null;
+ }
+ return environmentLabelById.get(thread.environmentId) ?? null;
+ };
const projectGroupByScopeKey = useMemo(
() => new Map(projectGroups.map((project) => [project.projectKey, project] as const)),
[projectGroups],
@@ -2745,7 +2745,7 @@ export default function Sidebar() {
clearSelection();
}, [clearSelection, projectScopeKey]);
- const openProjectSettings = useCallback(
+ const openProjectSettings = useStableCallback(
(projectGroup: SidebarProjectSnapshot, projectRef?: ScopedProjectRef) => {
if (isMobile) {
setOpenMobile(false);
@@ -2762,7 +2762,6 @@ export default function Sidebar() {
},
});
},
- [isMobile, projectGroupingSettings, projects, router, setOpenMobile],
);
// Anchor for the scope popup: the header search field, not its icon trigger.
const headerSearchRef = useRef<HTMLDivElement | null>(null);
@@ -2770,7 +2769,7 @@ export default function Sidebar() {
// selection, then clear the guard when the picker opens again.
const suppressNextScopeChangeRef = useRef(false);
const highlightedProjectScopeKeyRef = useRef<string | null>(null);
- const handleProjectSettings = useCallback(
+ const handleProjectSettings = useStableCallback(
(
event: ReactMouseEvent<HTMLElement> | ReactKeyboardEvent<HTMLInputElement>,
projectGroup: SidebarProjectSnapshot,
@@ -2781,7 +2780,6 @@ export default function Sidebar() {
dispatchProjectScopeMenu({ type: "project-settings-opened" });
openProjectSettings(projectGroup);
},
- [openProjectSettings],
);
// Keep a dropped row at its destination while its server applies the
@@ -3602,7 +3600,7 @@ export default function Sidebar() {
action: SidebarSweepAction;
keys: ReadonlySet<string>;
} | null>(null);
- const startActionSweep = useCallback(
+ const startActionSweep = useStableCallback(
(threadRef: ScopedThreadRef, action: SidebarSweepAction, event: PointerEvent) => {
const originKey = scopedThreadKey(threadRef);
const originSection = sectionByThreadKeyRef.current.get(originKey);
@@ -3661,7 +3659,6 @@ export default function Sidebar() {
onAbort: () => {},
});
},
- [attemptUnsettle, attemptUnsnooze, serverConfigs, settleThreads],
);
const pinnedKeys = useMemo(
() =>
@@ -4280,7 +4277,7 @@ export default function Sidebar() {
);
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
- const handleMultiSelectContextMenu = useCallback(
+ const handleMultiSelectContextMenu = useStableCallback(
async (position: { x: number; y: number }) => {
const api = readLocalApi();
if (!api) return;
@@ -4540,22 +4537,9 @@ export default function Sidebar() {
}),
);
},
- [
- attemptUnpin,
- clearSelection,
- confirmThreadDelete,
- deleteThread,
- markThreadUnread,
- performSnooze,
- removeFromSelection,
- serverConfigs,
- settleThreads,
- updateThreadMetadata,
- timestampFormat,
- ],
);
- const handleDraftContextMenu = useCallback(
+ const handleDraftContextMenu = useStableCallback(
(draftId: DraftId, position: { x: number; y: number }) => {
void (async () => {
const api = readLocalApi();
@@ -4605,10 +4589,9 @@ export default function Sidebar() {
}
})();
},
- [copyBranchToClipboard, copyPathToClipboard, openProjectSettings, projectByKey],
);
- const handleThreadContextMenu = useCallback(
+ const handleThreadContextMenu = useStableCallback(
(threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
void (async () => {
const api = readLocalApi();
@@ -4878,32 +4861,6 @@ export default function Sidebar() {
}
})();
},
- [
- archiveThread,
- attemptPin,
- attemptSettle,
- attemptSnooze,
- attemptUnpin,
- attemptUnsettle,
- attemptUnsnooze,
- confirmThreadArchive,
- confirmThreadDelete,
- copyBranchToClipboard,
- copyPathToClipboard,
- copyThreadIdToClipboard,
- deleteThread,
- handleMultiSelectContextMenu,
- markThreadUnread,
- openProjectSettings,
- projectScopeKey,
- projectByKey,
- serverConfigs,
- setProjectScopeKey,
- setThreadAutoSettle,
- startThreadRename,
- updateThreadMetadata,
- timestampFormat,
- ],
);
// Thread jump (cmd+1..9) and prev/next traversal reuse the same commands as
diff --git a/apps/web/src/hooks/useStableCallback.test.tsx b/apps/web/src/hooks/useStableCallback.test.tsx
new file mode 100644
index 00000000000..ddd7fde3520
--- /dev/null
+++ b/apps/web/src/hooks/useStableCallback.test.tsx
@@ -0,0 +1,41 @@
+import { act } from "react";
+import { create, type ReactTestRenderer } from "react-test-renderer";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { useStableCallback } from "./useStableCallback";
+
+let renderer: ReactTestRenderer | null = null;
+let handlers: Array<() => string> = [];
+
+function Probe({ label }: { label: string }) {
+ handlers.push(useStableCallback(() => label));
+ return null;
+}
+
+async function render(label: string) {
+ await act(() => {
+ if (renderer) renderer.update(<Probe label={label} />);
+ else renderer = create(<Probe label={label} />);
+ });
+}
+
+beforeEach(() => {
+ handlers = [];
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+});
+
+afterEach(async () => {
+ await act(() => renderer?.unmount());
+ renderer = null;
+ vi.unstubAllGlobals();
+});
+
+describe("useStableCallback", () => {
+ it("keeps one identity and calls the latest committed function", async () => {
+ await render("first");
+ await render("second");
+
+ expect(new Set(handlers).size).toBe(1);
+ expect(handlers[0]!()).toBe("second");
+ });
+});
diff --git a/apps/web/src/hooks/useStableCallback.ts b/apps/web/src/hooks/useStableCallback.ts
new file mode 100644
index 00000000000..329414253a8
--- /dev/null
+++ b/apps/web/src/hooks/useStableCallback.ts
@@ -0,0 +1,22 @@
+import { useCallback, useLayoutEffect, useRef } from "react";
+
+/**
+ * Returns a function with a fixed identity that always calls the latest `fn`.
+ * Only call it from event handlers and effects; during render it would see the
+ * previous commit's `fn`.
+ *
+ * Use it for event handlers in large, long-lived components. A `useCallback`
+ * result keeps the render scope it was created in, and V8 shares one scope
+ * between all closures of a render. When several memoized handlers change at
+ * different times, each keeps an older scope holding older copies of the
+ * others, and old renders pile up for as long as the component is mounted.
+ */
+export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
+ fn: (...args: Args) => Result,
+): (...args: Args) => Result {
+ const latest = useRef(fn);
+ useLayoutEffect(() => {
+ latest.current = fn;
+ });
+ return useCallback((...args: Args) => latest.current(...args), []);
+}