Skip to content

Commit 2d31acb

Browse files
t3dotggclaude
andauthored
fix(web): the sidebar no longer keeps old renders alive (pingdotgg#19852)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 339179f commit 2d31acb

3 files changed

Lines changed: 83 additions & 63 deletions

File tree

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

Lines changed: 20 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@ import {
268268
type ProviderInstanceEntry,
269269
} from "../providerInstances";
270270
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
271+
import { useStableCallback } from "../hooks/useStableCallback";
271272
import { stackedThreadToast, toastManager } from "./ui/toast";
272273
import { Button, InlineButton } from "./ui/button";
273274
import {
@@ -2628,20 +2629,19 @@ export default function Sidebar() {
26282629
() => projectGroupsSpanEnvironments(projectGroups),
26292630
[projectGroups],
26302631
);
2631-
const scratchMachineLabelFor = useCallback(
2632-
(thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">) => {
2633-
if (!showProjectEnvironments) return null;
2634-
const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`);
2635-
if (
2636-
!project ||
2637-
!isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot)
2638-
) {
2639-
return null;
2640-
}
2641-
return environmentLabelById.get(thread.environmentId) ?? null;
2642-
},
2643-
[environmentLabelById, projectByKey, serverConfigs, showProjectEnvironments],
2644-
);
2632+
const scratchMachineLabelFor = (
2633+
thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">,
2634+
) => {
2635+
if (!showProjectEnvironments) return null;
2636+
const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`);
2637+
if (
2638+
!project ||
2639+
!isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot)
2640+
) {
2641+
return null;
2642+
}
2643+
return environmentLabelById.get(thread.environmentId) ?? null;
2644+
};
26452645
const projectGroupByScopeKey = useMemo(
26462646
() => new Map(projectGroups.map((project) => [project.projectKey, project] as const)),
26472647
[projectGroups],
@@ -2745,7 +2745,7 @@ export default function Sidebar() {
27452745
clearSelection();
27462746
}, [clearSelection, projectScopeKey]);
27472747

2748-
const openProjectSettings = useCallback(
2748+
const openProjectSettings = useStableCallback(
27492749
(projectGroup: SidebarProjectSnapshot, projectRef?: ScopedProjectRef) => {
27502750
if (isMobile) {
27512751
setOpenMobile(false);
@@ -2762,15 +2762,14 @@ export default function Sidebar() {
27622762
},
27632763
});
27642764
},
2765-
[isMobile, projectGroupingSettings, projects, router, setOpenMobile],
27662765
);
27672766
// Anchor for the scope popup: the header search field, not its icon trigger.
27682767
const headerSearchRef = useRef<HTMLDivElement | null>(null);
27692768
// Safari can send a click after Ctrl+click opens settings. Ignore that one
27702769
// selection, then clear the guard when the picker opens again.
27712770
const suppressNextScopeChangeRef = useRef(false);
27722771
const highlightedProjectScopeKeyRef = useRef<string | null>(null);
2773-
const handleProjectSettings = useCallback(
2772+
const handleProjectSettings = useStableCallback(
27742773
(
27752774
event: ReactMouseEvent<HTMLElement> | ReactKeyboardEvent<HTMLInputElement>,
27762775
projectGroup: SidebarProjectSnapshot,
@@ -2781,7 +2780,6 @@ export default function Sidebar() {
27812780
dispatchProjectScopeMenu({ type: "project-settings-opened" });
27822781
openProjectSettings(projectGroup);
27832782
},
2784-
[openProjectSettings],
27852783
);
27862784

27872785
// Keep a dropped row at its destination while its server applies the
@@ -3602,7 +3600,7 @@ export default function Sidebar() {
36023600
action: SidebarSweepAction;
36033601
keys: ReadonlySet<string>;
36043602
} | null>(null);
3605-
const startActionSweep = useCallback(
3603+
const startActionSweep = useStableCallback(
36063604
(threadRef: ScopedThreadRef, action: SidebarSweepAction, event: PointerEvent) => {
36073605
const originKey = scopedThreadKey(threadRef);
36083606
const originSection = sectionByThreadKeyRef.current.get(originKey);
@@ -3661,7 +3659,6 @@ export default function Sidebar() {
36613659
onAbort: () => {},
36623660
});
36633661
},
3664-
[attemptUnsettle, attemptUnsnooze, serverConfigs, settleThreads],
36653662
);
36663663
const pinnedKeys = useMemo(
36673664
() =>
@@ -4280,7 +4277,7 @@ export default function Sidebar() {
42804277
);
42814278

42824279
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
4283-
const handleMultiSelectContextMenu = useCallback(
4280+
const handleMultiSelectContextMenu = useStableCallback(
42844281
async (position: { x: number; y: number }) => {
42854282
const api = readLocalApi();
42864283
if (!api) return;
@@ -4540,22 +4537,9 @@ export default function Sidebar() {
45404537
}),
45414538
);
45424539
},
4543-
[
4544-
attemptUnpin,
4545-
clearSelection,
4546-
confirmThreadDelete,
4547-
deleteThread,
4548-
markThreadUnread,
4549-
performSnooze,
4550-
removeFromSelection,
4551-
serverConfigs,
4552-
settleThreads,
4553-
updateThreadMetadata,
4554-
timestampFormat,
4555-
],
45564540
);
45574541

4558-
const handleDraftContextMenu = useCallback(
4542+
const handleDraftContextMenu = useStableCallback(
45594543
(draftId: DraftId, position: { x: number; y: number }) => {
45604544
void (async () => {
45614545
const api = readLocalApi();
@@ -4605,10 +4589,9 @@ export default function Sidebar() {
46054589
}
46064590
})();
46074591
},
4608-
[copyBranchToClipboard, copyPathToClipboard, openProjectSettings, projectByKey],
46094592
);
46104593

4611-
const handleThreadContextMenu = useCallback(
4594+
const handleThreadContextMenu = useStableCallback(
46124595
(threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
46134596
void (async () => {
46144597
const api = readLocalApi();
@@ -4878,32 +4861,6 @@ export default function Sidebar() {
48784861
}
48794862
})();
48804863
},
4881-
[
4882-
archiveThread,
4883-
attemptPin,
4884-
attemptSettle,
4885-
attemptSnooze,
4886-
attemptUnpin,
4887-
attemptUnsettle,
4888-
attemptUnsnooze,
4889-
confirmThreadArchive,
4890-
confirmThreadDelete,
4891-
copyBranchToClipboard,
4892-
copyPathToClipboard,
4893-
copyThreadIdToClipboard,
4894-
deleteThread,
4895-
handleMultiSelectContextMenu,
4896-
markThreadUnread,
4897-
openProjectSettings,
4898-
projectScopeKey,
4899-
projectByKey,
4900-
serverConfigs,
4901-
setProjectScopeKey,
4902-
setThreadAutoSettle,
4903-
startThreadRename,
4904-
updateThreadMetadata,
4905-
timestampFormat,
4906-
],
49074864
);
49084865

49094866
// Thread jump (cmd+1..9) and prev/next traversal reuse the same commands as
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { act } from "react";
2+
import { create, type ReactTestRenderer } from "react-test-renderer";
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4+
5+
import { useStableCallback } from "./useStableCallback";
6+
7+
let renderer: ReactTestRenderer | null = null;
8+
let handlers: Array<() => string> = [];
9+
10+
function Probe({ label }: { label: string }) {
11+
handlers.push(useStableCallback(() => label));
12+
return null;
13+
}
14+
15+
async function render(label: string) {
16+
await act(() => {
17+
if (renderer) renderer.update(<Probe label={label} />);
18+
else renderer = create(<Probe label={label} />);
19+
});
20+
}
21+
22+
beforeEach(() => {
23+
handlers = [];
24+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
25+
});
26+
27+
afterEach(async () => {
28+
await act(() => renderer?.unmount());
29+
renderer = null;
30+
vi.unstubAllGlobals();
31+
});
32+
33+
describe("useStableCallback", () => {
34+
it("keeps one identity and calls the latest committed function", async () => {
35+
await render("first");
36+
await render("second");
37+
38+
expect(new Set(handlers).size).toBe(1);
39+
expect(handlers[0]!()).toBe("second");
40+
});
41+
});
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { useCallback, useLayoutEffect, useRef } from "react";
2+
3+
/**
4+
* Returns a function with a fixed identity that always calls the latest `fn`.
5+
* Only call it from event handlers and effects; during render it would see the
6+
* previous commit's `fn`.
7+
*
8+
* Use it for event handlers in large, long-lived components. A `useCallback`
9+
* result keeps the render scope it was created in, and V8 shares one scope
10+
* between all closures of a render. When several memoized handlers change at
11+
* different times, each keeps an older scope holding older copies of the
12+
* others, and old renders pile up for as long as the component is mounted.
13+
*/
14+
export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
15+
fn: (...args: Args) => Result,
16+
): (...args: Args) => Result {
17+
const latest = useRef(fn);
18+
useLayoutEffect(() => {
19+
latest.current = fn;
20+
});
21+
return useCallback((...args: Args) => latest.current(...args), []);
22+
}

0 commit comments

Comments
 (0)