The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 15:45 UTC
refactor(web): sidebar thread lists derive state instead of syncing it in effects (#25234)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 21:23 UTC
6a3a460b09e70f06eebfd46ad304c74b96afa179
17 files changed
+825
-509
apps/web/src/components/LegacySidebar.tsx
+35
-53
@@ -24,7 +24,15 @@ import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
24
import { ProjectFavicon } from "./ProjectFavicon";
25
import { useAtomValue } from "@effect/atom-react";
26
import { autoAnimate } from "@formkit/auto-animate";
27
-import React, { useEffect, useEffectEvent, memo, useRef, useState } from "react";
27
+import React, {
28
+ createContext,
29
+ useEffect,
30
+ useEffectEvent,
31
+ memo,
32
+ useContext,
33
+ useRef,
34
+ useState,
35
+} from "react";
36
import { cn } from "~/lib/utils";
37
import { useShallow } from "zustand/react/shallow";
38
import {
@@ -199,7 +207,8 @@ import {
207
shouldClearThreadSelectionOnMouseDown,
208
sortProjectsForSidebar,
209
useSidebarRowSubscriptionLease,
202
- useThreadJumpHintVisibility,
210
+ setFileDragActive,
211
+ useThreadJumpHintsVisible,
212
ThreadStatusPill,
213
} from "./Sidebar.logic";
214
import { sortThreads } from "../lib/threadSort";
@@ -227,11 +236,7 @@ import {
236
} from "../sidebarProjectGrouping";
237
import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
238
import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
230
-import {
231
- completeSidebarRouteReveal,
232
- pendingSidebarRouteReveal,
233
- type SidebarRouteReveal,
234
-} from "./sidebar/routeReveal";
239
+import { type SidebarRouteReveal, useActiveRowReveal } from "./sidebar/routeReveal";
240
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
241
updated_at: "Last user message",
242
created_at: "Created at",
@@ -383,6 +388,11 @@ function checkTaskPermission(environmentId: EnvironmentId): boolean {
388
return false;
389
}
390
391
+// The active row reports itself, so a route change scrolls to it once it mounts.
392
+const RevealActiveRowContext = createContext<(row: HTMLElement | null, threadKey: string) => void>(
393
+ () => {},
394
+);
395
+
396
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
397
const {
398
orderedProjectThreadKeys,
@@ -415,12 +425,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
425
const canOperatePreview = useEnvironmentScope(thread.environmentId, AuthPreviewOperateScope);
426
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
427
const [isFileDragOver, setIsFileDragOver] = useState(false);
418
- useEffect(() => {
419
- if (!isFileDragOver) return;
420
- const clearFileDrag = () => setIsFileDragOver(false);
421
- window.addEventListener("dragend", clearFileDrag);
422
- return () => window.removeEventListener("dragend", clearFileDrag);
423
- }, [isFileDragOver]);
428
+ const revealActiveRow = useContext(RevealActiveRowContext);
429
const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(isActive);
430
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
431
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
@@ -466,7 +471,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
471
// Hooks must precede this ref's plain uses for the compiler to cache it.
472
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
473
const fileDropHandlers = makeWorkspaceFileDropHandlers({
469
- setDragActive: setIsFileDragOver,
474
+ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active),
475
addFiles: (files) => {
476
onFileDropThreads(threadRef, files);
477
},
@@ -669,6 +674,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
674
onBlurCapture={handleBlurCapture}
675
>
676
<div
677
+ ref={isActive ? (node) => revealActiveRow(node, threadKey) : undefined}
678
role="button"
679
tabIndex={0}
680
data-active={isActive}
@@ -3259,6 +3265,13 @@ function useLegacySidebarThreads(input: {
3265
};
3266
}
3267
3268
+function clearThreadSelectionOnOutsideMouseDown(event: globalThis.MouseEvent) {
3269
+ const selection = useThreadSelectionStore.getState();
3270
+ if (!selection.hasSelection()) return;
3271
+ const target = event.target instanceof HTMLElement ? event.target : null;
3272
+ if (shouldClearThreadSelectionOnMouseDown(target)) selection.clearSelection();
3273
+}
3274
+
3275
export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) {
3276
const reorderProjects = useUiStateStore((store) => store.reorderProjects);
3277
const navigate = useNavigate();
@@ -3283,7 +3296,6 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
3296
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
3297
ReadonlySet<string>
3298
>(() => new Set());
3286
- const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility();
3299
const dragInProgressRef = useRef(false);
3300
const suppressProjectClickAfterDragRef = useRef(false);
3301
const suppressProjectClickForContextMenuRef = useRef(false);
@@ -3323,25 +3335,7 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
3335
sidebarThreadPreviewCount,
3336
expandedThreadListsByProject,
3337
});
3326
- // History and the command palette can open a thread scrolled out of view,
3327
- // and a remount starts the list at the top, so each route change and each
3328
- // mount scroll to the open thread once. Its row can mount after the route
3329
- // does, once its environment's shells arrive, so the reveal waits for it.
3330
- const mountRevealOwed = useRef(true);
3331
- const routeRowRendered =
3332
- routeThreadKey !== null && visibleSidebarThreadKeys.includes(routeThreadKey);
3333
- const revealRouteRow = useStableCallback(() => {
3334
- const pendingKey = pendingSidebarRouteReveal(routeReveal, routeThreadKey);
3335
- if (pendingKey === null && (!mountRevealOwed.current || routeThreadKey === null)) return;
3336
- const activeRow = document.querySelector(
3337
- '[data-sidebar="content"] [data-thread-item] [data-active="true"]',
3338
- );
3339
- if (!activeRow) return;
3340
- completeSidebarRouteReveal(routeReveal);
3341
- mountRevealOwed.current = false;
3342
- activeRow.scrollIntoView({ block: "nearest" });
3343
- });
3344
- useEffect(revealRouteRow, [revealRouteRow, routeThreadKey, routeRowRendered]);
3338
+ const revealActiveRow = useActiveRowReveal(routeReveal, routeThreadKey);
3339
const newThreadShortcutLabelOptions = {
3340
platform,
3341
context: {
@@ -3438,15 +3432,12 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
3432
context: sidebarShortcutContext,
3433
},
3434
);
3435
+ const showThreadJumpHints = useThreadJumpHintsVisible(shouldShowThreadJumpHintsNow);
3436
const visibleThreadJumpLabelByKey = showThreadJumpHints
3437
? threadJumpLabelByKey
3438
: EMPTY_THREAD_JUMP_LABELS;
3439
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
3440
3446
- useEffect(() => {
3447
- updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
3448
- }, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]);
3449
-
3441
const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => {
3442
const shortcutContext = {
3443
terminalFocus: isTerminalFocused(),
@@ -3508,20 +3499,11 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
3499
window.removeEventListener("keydown", handleWindowKeyDown);
3500
};
3501
}, []);
3511
-
3502
+ // A window listener whose lifetime is the sidebar's: no element owns outside clicks.
3503
useEffect(() => {
3513
- const onMouseDown = (event: globalThis.MouseEvent) => {
3514
- if (!useThreadSelectionStore.getState().hasSelection()) return;
3515
- const target = event.target instanceof HTMLElement ? event.target : null;
3516
- if (!shouldClearThreadSelectionOnMouseDown(target)) return;
3517
- clearSelection();
3518
- };
3519
-
3520
- window.addEventListener("mousedown", onMouseDown);
3521
- return () => {
3522
- window.removeEventListener("mousedown", onMouseDown);
3523
- };
3524
- }, [clearSelection]);
3504
+ window.addEventListener("mousedown", clearThreadSelectionOnOutsideMouseDown);
3505
+ return () => window.removeEventListener("mousedown", clearThreadSelectionOnOutsideMouseDown);
3506
+ }, []);
3507
3508
const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState);
3509
const desktopUpdateButtonAction = desktopUpdateState
@@ -3647,7 +3629,7 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
3629
};
3630
3631
return (
3650
- <>
3632
+ <RevealActiveRowContext value={revealActiveRow}>
3633
{prewarmedSidebarThreadRefs.map((threadRef) => (
3634
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
3635
))}
@@ -3693,6 +3675,6 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
3675
projectsLength={projectsLength}
3676
/>
3677
<SidebarChromeFooter />
3696
- </>
3678
+ </RevealActiveRowContext>
3679
);
3680
}
apps/web/src/components/Sidebar.logic.browser.test.tsx
new
+33
@@ -0,0 +1,33 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+
3
+import { render } from "../../test/render";
4
+import { useSnoozeWakeClock } from "./Sidebar.logic";
5
+
6
+const MOUNTED_AT_MS = Date.parse("2026-10-24T08:00:00.000Z");
7
+
8
+function WakeClock(props: { readonly threads: ReadonlyArray<{ readonly snoozedUntil: string }> }) {
9
+ return <output>{useSnoozeWakeClock(props.threads)}</output>;
10
+}
11
+
12
+describe("useSnoozeWakeClock", () => {
13
+ it("settles in one step when many distinct wakes passed during a sleep", async () => {
14
+ using now = vi.spyOn(Date, "now").mockReturnValue(MOUNTED_AT_MS);
15
+ // More distinct wakes than React's 25 render-phase re-render limit.
16
+ const threads = Array.from({ length: 40 }, (_, index) => ({
17
+ snoozedUntil: new Date(MOUNTED_AT_MS + 1 + index * 60_000).toISOString(),
18
+ }));
19
+ await using screen = await render(<WakeClock threads={threads} />, {
20
+ // A bare hook host; nothing here links or navigates.
21
+ router: false,
22
+ });
23
+ await expect.element(screen.getByRole("status")).toHaveTextContent(String(MOUNTED_AT_MS));
24
+
25
+ // The machine resumes after every wake has passed; the first wake's timer fires late.
26
+ const resumedAtMs = MOUNTED_AT_MS + 24 * 60 * 60_000;
27
+ now.mockReturnValue(resumedAtMs);
28
+
29
+ // The clock lands on the last elapsed wake, so every woken thread has left the shelf.
30
+ const lastWakeMs = MOUNTED_AT_MS + 1 + 39 * 60_000;
31
+ await expect.element(screen.getByRole("status")).toHaveTextContent(String(lastWakeMs));
32
+ });
33
+});
apps/web/src/components/Sidebar.logic.test.ts
+65
-1
@@ -44,7 +44,11 @@ import {
44
type Thread,
45
} from "../types";
46
import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures";
47
-import { completeSidebarRouteReveal, pendingSidebarRouteReveal } from "./sidebar/routeReveal";
47
+import {
48
+ completeSidebarRouteReveal,
49
+ pendingSidebarRouteReveal,
50
+ resolveSidebarRouteReveal,
51
+} from "./sidebar/routeReveal";
52
53
const localEnvironmentId = EnvironmentId.make("environment-local");
54
@@ -1288,3 +1292,63 @@ describe("pendingSidebarRouteReveal", () => {
1292
expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBe("env:a1");
1293
});
1294
});
1295
+
1296
+describe("resolveSidebarRouteReveal", () => {
1297
+ const scopedProjectKeys = new Set(["environment-test:project-scoped"]);
1298
+ const hidden = makeThreadFixture({ projectId: ProjectId.make("project-other") });
1299
+ const hiddenKey = "environment-test:thread-test";
1300
+ const findThread = (key: string) => (key === hiddenKey ? hidden : undefined);
1301
+
1302
+ it("widens the scope for a newly opened thread the scope hides", () => {
1303
+ expect(
1304
+ resolveSidebarRouteReveal({
1305
+ reveal: { observedKey: "environment-test:other", pendingKey: null },
1306
+ routeKey: hiddenKey,
1307
+ isSearching: false,
1308
+ scopedProjectKeys,
1309
+ findThread,
1310
+ }),
1311
+ ).toEqual({ pendingKey: hiddenKey, widensScope: true });
1312
+ });
1313
+
1314
+ it("never widens for a thread whose reveal already completed", () => {
1315
+ // A remount's once-per-mount scroll must keep the scope the user chose.
1316
+ expect(
1317
+ resolveSidebarRouteReveal({
1318
+ reveal: { observedKey: hiddenKey, pendingKey: null },
1319
+ routeKey: hiddenKey,
1320
+ isSearching: false,
1321
+ scopedProjectKeys,
1322
+ findThread,
1323
+ }),
1324
+ ).toEqual({ pendingKey: null, widensScope: false });
1325
+ });
1326
+
1327
+ it("widens again for a thread reopened before the thread between them listed its row", () => {
1328
+ // The user scoped away from the open thread, then went to a thread whose row
1329
+ // never mounted, then came back.
1330
+ const reveal = { observedKey: hiddenKey, pendingKey: null };
1331
+ const resolve = (routeKey: string) =>
1332
+ resolveSidebarRouteReveal({
1333
+ reveal,
1334
+ routeKey,
1335
+ isSearching: false,
1336
+ scopedProjectKeys,
1337
+ findThread,
1338
+ });
1339
+ resolve("environment-test:unlisted");
1340
+ expect(resolve(hiddenKey)).toEqual({ pendingKey: hiddenKey, widensScope: true });
1341
+ });
1342
+
1343
+ it("holds a pending reveal without widening while searching", () => {
1344
+ expect(
1345
+ resolveSidebarRouteReveal({
1346
+ reveal: { observedKey: hiddenKey, pendingKey: hiddenKey },
1347
+ routeKey: hiddenKey,
1348
+ isSearching: true,
1349
+ scopedProjectKeys,
1350
+ findThread,
1351
+ }),
1352
+ ).toEqual({ pendingKey: hiddenKey, widensScope: false });
1353
+ });
1354
+});
apps/web/src/components/Sidebar.logic.ts
+67
-83
@@ -31,6 +31,8 @@ import type { SidebarThreadSummary, Thread } from "../types";
31
import { normalizeSearchText } from "../lib/utils";
32
import { isLatestRunSettled } from "../session-logic";
33
import { observeIntersection } from "../lib/observeIntersection";
34
+import { deadlineAfter, deadlineStore } from "@t3tools/client-runtime/clock";
35
+import { useDeadlinePassed } from "../hooks/useDeadline";
36
37
export function shouldNavigateAfterThreadPark(input: {
38
readonly threadKey: string;
@@ -89,6 +91,61 @@ export function useSidebarRowSubscriptionLease(isActive: boolean): {
91
};
92
}
93
94
+const fileDragClears = new Set<(active: false) => void>();
95
+function clearFileDrags() {
96
+ const clears = [...fileDragClears];
97
+ fileDragClears.clear();
98
+ for (const clear of clears) clear(false);
99
+}
100
+
101
+/**
102
+ * A file drag that ends outside every drop target (Escape, or a drop elsewhere)
103
+ * sends no dragleave to the row it last entered, so the window's dragend clears it.
104
+ */
105
+export function setFileDragActive(setActive: (active: boolean) => void, active: boolean) {
106
+ setActive(active);
107
+ if (typeof window === "undefined") return;
108
+ if (!active) {
109
+ if (fileDragClears.delete(setActive) && fileDragClears.size === 0) {
110
+ window.removeEventListener("dragend", clearFileDrags);
111
+ }
112
+ return;
113
+ }
114
+ if (fileDragClears.size === 0) window.addEventListener("dragend", clearFileDrags, { once: true });
115
+ fileDragClears.add(setActive);
116
+}
117
+
118
+/**
119
+ * A clock that advances exactly when a snooze wake time passes, so a woken
120
+ * thread leaves the shelf on time without a per-second clock.
121
+ */
122
+export function useSnoozeWakeClock(
123
+ threads: ReadonlyArray<{ readonly snoozedUntil?: string | null | undefined }>,
124
+): number {
125
+ const [clockMs, setClockMs] = React.useState(() => Date.now());
126
+ const wakeTimes: number[] = [];
127
+ let nextWakeAt: number | null = null;
128
+ for (const thread of threads) {
129
+ const wakeAt = thread.snoozedUntil == null ? Number.NaN : Date.parse(thread.snoozedUntil);
130
+ if (!(wakeAt > clockMs)) continue;
131
+ wakeTimes.push(wakeAt);
132
+ if (nextWakeAt === null || wakeAt < nextWakeAt) nextWakeAt = wakeAt;
133
+ }
134
+ const woke = useDeadlinePassed(nextWakeAt);
135
+ // Advancing to the latest wake that has passed skips every wake that elapsed
136
+ // meanwhile, e.g. across a laptop sleep. Stepping one wake at a time would
137
+ // re-render once per elapsed wake and hit React's limit.
138
+ if (woke && nextWakeAt !== null) {
139
+ let nextClockMs = nextWakeAt;
140
+ for (const wakeAt of wakeTimes) {
141
+ if (wakeAt > nextClockMs && deadlineStore(wakeAt).getSnapshot()) nextClockMs = wakeAt;
142
+ }
143
+ setClockMs(nextClockMs);
144
+ return nextClockMs;
145
+ }
146
+ return clockMs;
147
+}
148
+
149
export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
150
const [retained, setRetained] = React.useState<{
151
readonly key: string;
@@ -607,89 +664,16 @@ type ThreadStatusInput = Pick<
664
blockedOnThreadWait?: boolean | undefined;
665
};
666
610
-export interface ThreadJumpHintVisibilityController {
611
- sync: (shouldShow: boolean) => void;
612
- dispose: () => void;
613
-}
614
-
615
-function createThreadJumpHintVisibilityController(input: {
616
- delayMs: number;
617
- onVisibilityChange: (visible: boolean) => void;
618
- setTimeoutFn?: typeof globalThis.setTimeout;
619
- clearTimeoutFn?: typeof globalThis.clearTimeout;
620
-}): ThreadJumpHintVisibilityController {
621
- const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
622
- const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
623
- let isVisible = false;
624
- let timeoutId: NodeJS.Timeout | null = null;
625
-
626
- const clearPendingShow = () => {
627
- if (timeoutId === null) {
628
- return;
629
- }
630
- clearTimeoutFn(timeoutId);
631
- timeoutId = null;
632
- };
633
-
634
- return {
635
- sync: (shouldShow) => {
636
- if (!shouldShow) {
637
- clearPendingShow();
638
- if (isVisible) {
639
- isVisible = false;
640
- input.onVisibilityChange(false);
641
- }
642
- return;
643
- }
644
-
645
- if (isVisible || timeoutId !== null) {
646
- return;
647
- }
648
-
649
- timeoutId = setTimeoutFn(() => {
650
- timeoutId = null;
651
- isVisible = true;
652
- input.onVisibilityChange(true);
653
- }, input.delayMs);
654
- },
655
- dispose: () => {
656
- clearPendingShow();
657
- },
658
- };
659
-}
660
-
661
-export function useThreadJumpHintVisibility(): {
662
- showThreadJumpHints: boolean;
663
- updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
664
-} {
665
- const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
666
- const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
667
-
668
- React.useEffect(() => {
669
- const controller = createThreadJumpHintVisibilityController({
670
- delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
671
- onVisibilityChange: (visible) => {
672
- setShowThreadJumpHints(visible);
673
- },
674
- setTimeoutFn: window.setTimeout.bind(window),
675
- clearTimeoutFn: window.clearTimeout.bind(window),
676
- });
677
- controllerRef.current = controller;
678
-
679
- return () => {
680
- controller.dispose();
681
- controllerRef.current = null;
682
- };
683
- }, []);
684
-
685
- const updateThreadJumpHintsVisibility = (shouldShow: boolean) => {
686
- controllerRef.current?.sync(shouldShow);
687
- };
688
-
689
- return {
690
- showThreadJumpHints,
691
- updateThreadJumpHintsVisibility,
692
- };
667
+/**
668
+ * Thread jump hints appear once the jump modifier has been held for a moment,
669
+ * so a quick shortcut never flashes them, and hide as soon as it is released.
670
+ */
671
+export function useThreadJumpHintsVisible(shouldShow: boolean): boolean {
672
+ const [showAt, setShowAt] = React.useState<number | null>(null);
673
+ let nextShowAt = shouldShow ? showAt : null;
674
+ if (shouldShow && showAt === null) nextShowAt = deadlineAfter(THREAD_JUMP_HINT_SHOW_DELAY_MS);
675
+ if (nextShowAt !== showAt) setShowAt(nextShowAt);
676
+ return useDeadlinePassed(nextShowAt);
677
}
678
679
export function resolveThreadLastVisitedAt(
apps/web/src/components/Sidebar.pointer.ts
+1
-7
@@ -1,13 +1,7 @@
1
-import { useLayoutEffect, type PointerEvent as ReactPointerEvent } from "react";
1
+import { type PointerEvent as ReactPointerEvent } from "react";
2
import { type SensorProps } from "@dnd-kit/core";
3
import { getOwnerDocument, getWindow } from "@dnd-kit/utilities";
4
5
-// Search unmounts the drag context while its owning Sidebar remains mounted.
6
-export function SidebarDragLifecycle({ onUnmount }: { onUnmount: () => void }) {
7
- useLayoutEffect(() => onUnmount, [onUnmount]);
8
- return null;
9
-}
10
-
5
type Options = {
6
distance: number;
7
onAttach: (sensor: SidebarPointerSensor) => void;
apps/web/src/components/Sidebar.tsx
+143
-158
@@ -71,7 +71,7 @@ import {
71
type MouseEvent as ReactMouseEvent,
72
type ReactNode,
73
} from "react";
74
-import { useRouter } from "@tanstack/react-router";
74
+import { type AnyRouter, useRouter } from "@tanstack/react-router";
75
76
import {
77
isAtomCommandInterrupted,
@@ -138,11 +138,15 @@ import { threadEnvironment } from "../state/threads";
138
import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../state/olderSettledShelf";
139
import { useThreadSearch } from "../state/queries";
140
import { useOrchestrationCommand } from "../state/use-orchestration-command";
141
-import { readEnvironmentScope } from "../state/session";
141
+import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
142
import { appAtomRegistry } from "../rpc/atomRegistry";
143
import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
144
import { openGuestShareDialog } from "./chat/guestShareDialogState";
145
-import { buildThreadRouteParams, resolveActiveThreadRouteRef } from "../threadRoutes";
145
+import {
146
+ buildThreadRouteParams,
147
+ resolveActiveThreadRouteRef,
148
+ resolveThreadRouteTarget,
149
+} from "../threadRoutes";
150
import type { SidebarThreadSummary } from "../types";
151
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
152
import { cn } from "~/lib/utils";
@@ -179,7 +183,8 @@ import {
183
sortPinnedThreadsForSidebar,
184
sortThreadsForSidebar,
185
sortWorkingThreadsBySend,
182
- useThreadJumpHintVisibility,
186
+ useSnoozeWakeClock,
187
+ useThreadJumpHintsVisible,
188
type SidebarListItem,
189
type SidebarSection,
190
resolveSidebarRowThreadId,
@@ -189,16 +194,16 @@ import {
194
createSidebarSortingStrategy,
195
restrictBelowSidebarLabel,
196
} from "./Sidebar.drag";
192
-import { SidebarDragLifecycle, SidebarPointerSensor } from "./Sidebar.pointer";
197
+import { SidebarPointerSensor } from "./Sidebar.pointer";
198
import { createSidebarListMotion } from "./Sidebar.motion";
199
import { resolveSnoozePresets, snoozeWakeLabel, type SnoozePreset } from "./Sidebar.snooze";
200
import { ProjectFavicon } from "./ProjectFavicon";
201
import { deriveProviderEntriesByEnvironment } from "../providerInstances";
202
import { useStableCallback } from "../hooks/useStableCallback";
203
import {
199
- completeSidebarRouteReveal,
200
- pendingSidebarRouteReveal,
204
+ resolveSidebarRouteReveal,
205
type SidebarRouteReveal,
206
+ useActiveRowReveal,
207
} from "./sidebar/routeReveal";
208
import { stackedThreadToast, toastManager } from "./ui/toast";
209
import { Button } from "./ui/button";
@@ -365,24 +370,17 @@ function useSidebarThreads(input: {
370
readonly scopedProjectKeys: ReadonlySet<string> | null;
371
readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
372
readonly optimisticDrop: SidebarOptimisticDrop | null;
368
- readonly routeThreadRef: ScopedThreadRef | null;
373
+ readonly threads: readonly EnvironmentThreadShell[];
374
+ readonly routeRowThreadKey: string | null;
375
}) {
370
- const { projectScopeKey, scopedProjectKeys, serverConfigs, optimisticDrop, routeThreadRef } =
371
- input;
372
- const threads = useQuietThreadShells();
373
- const routeRowThreadKey =
374
- routeThreadRef === null
375
- ? null
376
- : scopedThreadKey(
377
- scopeThreadRef(
378
- routeThreadRef.environmentId,
379
- resolveSidebarRowThreadId(
380
- routeThreadRef.threadId,
381
- routeThreadRef.environmentId,
382
- threads,
383
- ),
384
- ),
385
- );
376
+ const {
377
+ projectScopeKey,
378
+ scopedProjectKeys,
379
+ serverConfigs,
380
+ optimisticDrop,
381
+ threads,
382
+ routeRowThreadKey,
383
+ } = input;
384
const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled);
385
const inboxReturnsVersion = useSyncExternalStore(
386
inboxReturns.subscribe,
@@ -390,12 +388,7 @@ function useSidebarThreads(input: {
388
);
389
const nowMinute = useNowMinute();
390
// Minute-quantized clocks would delay second-precise snooze wakes by up to a minute.
393
- const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
394
- const [nextSnoozeWakeAt, setNextSnoozeWakeAt] = useState<string | null>(null);
395
- useEffect(
396
- () => scheduleSnoozeWake(nextSnoozeWakeAt, () => bumpSnoozeWakeTick((tick) => tick + 1)),
397
- [nextSnoozeWakeAt],
398
- );
391
+ const snoozeWakeClock = useSnoozeWakeClock(threads);
392
const [settledShelfExpanded, setSettledShelfExpanded] = useLocalStorage(
393
SETTLED_SHELF_EXPANDED_KEY,
394
false,
@@ -427,10 +420,8 @@ function useSidebarThreads(input: {
420
serverConfigs,
421
optimisticDrop,
422
workingShelfEnabled,
430
- clockKey: `${nowMinute}:${snoozeWakeTick}:${inboxReturnsVersion}`,
423
+ clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`,
424
});
432
- const partitionNextWakeAt = partition.snoozedThreads[0]?.snoozedUntil ?? null;
433
- if (partitionNextWakeAt !== nextSnoozeWakeAt) setNextSnoozeWakeAt(partitionNextWakeAt);
425
426
const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } =
427
partition;
@@ -484,7 +475,6 @@ function useSidebarThreads(input: {
475
for (const thread of list) sectionByThreadKey.set(threadShellKey(thread), section);
476
}
477
return {
487
- routeRowThreadKey,
478
...partition,
479
threads,
480
workingShelfEnabled,
@@ -752,15 +742,6 @@ function useSidebarLookups() {
742
};
743
}
744
755
-function scheduleSnoozeWake(wakeAt: string | null, onWake: () => void): (() => void) | undefined {
756
- const wakeAtMs = wakeAt === null ? Number.NaN : Date.parse(wakeAt);
757
- if (Number.isNaN(wakeAtMs)) return undefined;
758
- // Delays beyond signed 32-bit range fire immediately and loop for far-future snoozes.
759
- const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
760
- const id = window.setTimeout(onWake, delayMs);
761
- return () => window.clearTimeout(id);
762
-}
763
-
745
function canOperateThreads(
746
threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,
747
): boolean {
@@ -785,6 +766,19 @@ const SIDEBAR_DRAG_DISTANCE = 6;
766
767
const SIDEBAR_DRAG_LABEL_HEIGHT = 24;
768
769
+const threadSearchResultId = (index: number) => `sidebar-thread-search-result-${index}`;
770
+
771
+// Continuations that outlive a render read the open thread from the router.
772
+function readRouteThreadKey(router: AnyRouter): string | null {
773
+ const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
774
+ const draft =
775
+ target?.kind === "draft"
776
+ ? useComposerDraftStore.getState().getDraftSession(target.draftId)
777
+ : null;
778
+ const ref = resolveActiveThreadRouteRef(target, draft);
779
+ return ref === null ? null : scopedThreadKey(ref);
780
+}
781
+
782
export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) {
783
const {
784
projects,
@@ -878,6 +872,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
872
},
873
});
874
const newThreadContext = useHandleNewThread();
875
+ // Row callbacks capture only the handler; the rest of the context changes with the route.
876
+ const { handleNewThread } = newThreadContext;
877
const primaryEnvironmentId = usePrimaryEnvironmentId();
878
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
879
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
@@ -909,10 +905,20 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
905
const [threadSearchQuery, setThreadSearchQuery] = useState("");
906
const [searchHighlightKey, setSearchHighlightKey] = useState<string | null>(null);
907
const searchEnvironmentIds = useConnectedEnvironmentIds();
912
- const handleNewThreadRef = useRef(newThreadContext.handleNewThread);
908
const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
909
const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
915
- const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
910
+ const [renamingThreadRef, setRenamingThreadRef] = useState<ScopedThreadRef | null>(null);
911
+ const canOperateRenamingThread = useEnvironmentScope(
912
+ renamingThreadRef?.environmentId ?? null,
913
+ AuthOrchestrationOperateScope,
914
+ );
915
+ // Losing operate access cancels the rename without committing the title, so
916
+ // the editor does not return and take focus when access comes back.
917
+ if (renamingThreadRef !== null && !canOperateRenamingThread) setRenamingThreadRef(null);
918
+ const renamingThreadKey =
919
+ renamingThreadRef !== null && canOperateRenamingThread
920
+ ? scopedThreadKey(renamingThreadRef)
921
+ : null;
922
const [renamingTitle, setRenamingTitle] = useState("");
923
const settlingThreadKeysRef = useRef(new Set<string>());
924
const threadListRef = useRef<HTMLUListElement | null>(null);
@@ -939,18 +945,70 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
945
const openAddProjectCommandPalette = () => openCommandPalette({ open: "add-project" });
946
const routeThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);
947
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
942
- const routeThreadKeyRef = useRef(routeThreadKey);
948
949
// A selection made under one scope can hold threads the next scope hides.
950
const setProjectScopeKey = (key: string | null) => {
951
clearSelection();
952
setPersistedProjectScopeKey(key);
953
};
949
- const projectScopeKey = resolveSidebarProjectScopeKey({
954
+ // A scope whose project is gone reads as all projects once every snapshot has
955
+ // loaded. The stored key is left alone, so the scope returns with its project.
956
+ const chosenProjectScopeKey = resolveSidebarProjectScopeKey({
957
groups: projectGroups,
958
key: persistedProjectScopeKey,
959
settings: projectGroupingSettings,
960
+ canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,
961
+ });
962
+ const chosenProjectGroup =
963
+ chosenProjectScopeKey === null
964
+ ? null
965
+ : (projectGroups.find((project) => project.projectKey === chosenProjectScopeKey) ?? null);
966
+ const chosenScopeProjectKeys =
967
+ chosenProjectGroup === null
968
+ ? null
969
+ : new Set(
970
+ chosenProjectGroup.memberProjectRefs.map(
971
+ (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
972
+ ),
973
+ );
974
+ const threads = useQuietThreadShells();
975
+ const routeRowThreadKey =
976
+ routeThreadRef === null
977
+ ? null
978
+ : scopedThreadKey(
979
+ scopeThreadRef(
980
+ routeThreadRef.environmentId,
981
+ resolveSidebarRowThreadId(
982
+ routeThreadRef.threadId,
983
+ routeThreadRef.environmentId,
984
+ threads,
985
+ ),
986
+ ),
987
+ );
988
+ const isSearchingThreads = threadSearchQuery.trim().length > 0;
989
+
990
+ // History, the palette and links can open a thread the scope hides or the list
991
+ // scrolled away; a remount starts at the top, so each mount scrolls to the open
992
+ // thread once. Render decides the widening, so the first frame of the new route
993
+ // already lists the row; the active row's ref callback scrolls to it.
994
+ const { widensScope: revealWidensScope } = resolveSidebarRouteReveal({
995
+ reveal: routeReveal,
996
+ routeKey: routeRowThreadKey,
997
+ isSearching: isSearchingThreads,
998
+ scopedProjectKeys: chosenScopeProjectKeys,
999
+ findThread: (key) => threads.find((candidate) => threadShellKey(candidate) === key),
1000
});
1001
+ const projectScopeKey = revealWidensScope ? null : chosenProjectScopeKey;
1002
+ // The widened scope outlives the reveal, so it is written back to the persisted
1003
+ // scope. Route changes arrive from history, links and the palette, and only this
1004
+ // component holds the project groups that decide a widening, so no single
1005
+ // navigation handler can make the write.
1006
+ useEffect(() => {
1007
+ if (!revealWidensScope) return;
1008
+ clearSelection();
1009
+ setPersistedProjectScopeKey(null);
1010
+ }, [clearSelection, revealWidensScope, setPersistedProjectScopeKey]);
1011
+ const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey);
1012
const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups);
1013
const scratchMachineLabelFor = (
1014
thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">,
@@ -974,18 +1032,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1032
matches: (item, query) =>
1033
projectScopeFilter.contains(item, query, (candidate) => candidate.label),
1034
});
977
- const scopedProjectGroup =
978
- projectScopeKey === null
979
- ? null
980
- : (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null);
981
- const scopedProjectKeys =
982
- scopedProjectGroup === null
983
- ? null
984
- : new Set(
985
- scopedProjectGroup.memberProjectRefs.map(
986
- (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
987
- ),
988
- );
1035
+ const scopedProjectGroup = revealWidensScope ? null : chosenProjectGroup;
1036
+ const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys;
1037
const threadSearch = useThreadSearch(
1038
searchEnvironmentIds,
1039
threadSearchQuery,
@@ -997,26 +1045,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1045
),
1046
},
1047
);
1000
- useEffect(() => {
1001
- const nextKey = resolveSidebarProjectScopeKey({
1002
- groups: projectGroups,
1003
- key: persistedProjectScopeKey,
1004
- settings: projectGroupingSettings,
1005
- canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,
1006
- });
1007
- if (nextKey !== persistedProjectScopeKey) {
1008
- clearSelection();
1009
- setPersistedProjectScopeKey(nextKey);
1010
- }
1011
- }, [
1012
- allProjectConfigsReady,
1013
- allProjectSnapshotsReady,
1014
- clearSelection,
1015
- persistedProjectScopeKey,
1016
- projectGroups,
1017
- projectGroupingSettings,
1018
- setPersistedProjectScopeKey,
1019
- ]);
1048
const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
1049
const visibleDraftSessionCount = useComposerDraftStore((store) => {
1050
let count = 0;
@@ -1070,7 +1098,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1098
);
1099
1100
const {
1073
- threads,
1101
workingShelfEnabled,
1102
pinnedThreads,
1103
draggableThreadKeys,
@@ -1104,53 +1131,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1131
activeKeys,
1132
pinnedKeysById,
1133
activeKeysById,
1107
- routeRowThreadKey,
1134
} = useSidebarThreads({
1135
projectScopeKey,
1136
scopedProjectKeys,
1137
serverConfigs,
1138
optimisticDrop,
1113
- routeThreadRef,
1114
- });
1115
-
1116
- const isSearchingThreads = threadSearchQuery.trim().length > 0;
1117
-
1118
- // History, the command palette, and links can open a thread the project
1119
- // scope hides or the list has scrolled away. A remount starts the list at
1120
- // the top, so each mount also scrolls to the open thread once, without
1121
- // widening the scope.
1122
- const mountRevealOwed = useRef(true);
1123
- const revealRouteRow = useStableCallback(() => {
1124
- const pendingKey = pendingSidebarRouteReveal(routeReveal, routeRowThreadKey);
1125
- // Search results replace the thread list; reveal once the list returns.
1126
- if (isSearchingThreads) return;
1127
- const revealKey = pendingKey ?? (mountRevealOwed.current ? routeRowThreadKey : null);
1128
- if (revealKey === null) return;
1129
- const thread = threads.find((candidate) => threadShellKey(candidate) === revealKey);
1130
- if (thread === undefined) return;
1131
- if (
1132
- pendingKey !== null &&
1133
- scopedProjectKeys !== null &&
1134
- filterSidebarV2VisibleThreads([thread], scopedProjectKeys).length === 0 &&
1135
- filterSidebarV2VisibleThreads([thread], null).length === 1
1136
- ) {
1137
- // The row renders under the widened scope; scroll on that pass.
1138
- setProjectScopeKey(null);
1139
- return;
1140
- }
1141
- const activeRow = document.querySelector('[data-sidebar="content"] [aria-current="page"]');
1142
- if (!activeRow) return;
1143
- completeSidebarRouteReveal(routeReveal);
1144
- mountRevealOwed.current = false;
1145
- activeRow.scrollIntoView({ block: "nearest" });
1146
- });
1147
- useEffect(revealRouteRow, [
1148
- revealRouteRow,
1149
- routeRowThreadKey,
1139
threads,
1151
- projectScopeKey,
1152
- isSearchingThreads,
1153
- ]);
1140
+ routeRowThreadKey,
1141
+ });
1142
1143
// Ranked across environments as the palette ranks them, so one
1144
// environment's list does not sit above another's better matches; rows
@@ -1220,15 +1208,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1208
typeof index === "function" ? index(activeSearchResultIndex) : index
1209
] ?? null,
1210
);
1223
- const activeSearchResultKey = isSearchingThreads
1224
- ? (threadSearchResultKeys[activeSearchResultIndex] ?? null)
1225
- : null;
1226
- useEffect(() => {
1227
- if (activeSearchResultKey === null) return;
1228
- document
1229
- .querySelector(`[data-search-result-key="${globalThis.CSS.escape(activeSearchResultKey)}"]`)
1230
- ?.scrollIntoView({ block: "nearest" });
1231
- }, [activeSearchResultKey]);
1211
+ const moveSearchHighlight = (step: 1 | -1) => {
1212
+ const count = threadSearchResults.length;
1213
+ setActiveSearchResultIndex((activeSearchResultIndex + step + count) % count);
1214
+ };
1215
1216
const orderedThreadKeysRef = useRef(orderedThreadKeys);
1217
// Read changing maps/sets through refs so streamed events preserve row callbacks.
@@ -1246,8 +1229,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1229
}
1230
return mapping;
1231
})();
1249
- const { showThreadJumpHints: showJumpHints, updateThreadJumpHintsVisibility } =
1250
- useThreadJumpHintVisibility();
1232
1233
const navigateToThread = (threadRef: ScopedThreadRef) => {
1234
if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
@@ -1319,14 +1300,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1300
if (threadSearchResults.length === 0) return;
1301
if (event.key === "ArrowDown") {
1302
event.preventDefault();
1322
- setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length);
1303
+ moveSearchHighlight(1);
1304
return;
1305
}
1306
if (event.key === "ArrowUp") {
1307
event.preventDefault();
1327
- setActiveSearchResultIndex(
1328
- (index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length,
1329
- );
1308
+ moveSearchHighlight(-1);
1309
return;
1310
}
1311
if (event.key === "Enter") {
@@ -1338,15 +1317,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1317
1318
const startThreadRename = (threadRef: ScopedThreadRef, title: string) => {
1319
if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
1341
- setRenamingThreadKey(scopedThreadKey(threadRef));
1320
+ setRenamingThreadRef(threadRef);
1321
setRenamingTitle(title);
1322
};
1344
- const cancelThreadRename = () => setRenamingThreadKey(null);
1323
+ const cancelThreadRename = () => setRenamingThreadRef(null);
1324
const commitThreadRename = (threadRef: ScopedThreadRef, title: string, originalTitle: string) => {
1325
void (async () => {
1326
if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
1327
const trimmed = title.trim();
1349
- setRenamingThreadKey(null);
1328
+ setRenamingThreadRef(null);
1329
if (trimmed.length === 0) {
1330
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
1331
return;
@@ -1395,7 +1374,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1374
threadKey: string,
1375
coParkingKeys?: ReadonlySet<string>,
1376
): (() => void) | null => {
1398
- if (routeThreadKeyRef.current !== threadKey) return null;
1377
+ if (readRouteThreadKey(router) !== threadKey) return null;
1378
const shell = threadByKeyRef.current.get(threadKey);
1379
const orderedKeys = orderedThreadKeysRef.current;
1380
const settledKeys = settledThreadKeysRef.current;
@@ -1411,8 +1390,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1390
return nextThread
1391
? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id))
1392
: shell
1414
- ? () =>
1415
- void handleNewThreadRef.current(scopeProjectRef(shell.environmentId, shell.projectId))
1393
+ ? () => void handleNewThread(scopeProjectRef(shell.environmentId, shell.projectId))
1394
: () => void router.navigate({ to: "/" });
1395
};
1396
@@ -1443,7 +1421,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1421
if (
1422
shouldNavigateAfterThreadPark({
1423
threadKey,
1446
- currentThreadKey: routeThreadKeyRef.current,
1424
+ currentThreadKey: readRouteThreadKey(router),
1425
action: "settle",
1426
now: new Date().toISOString(),
1427
thread: readThreadShell(threadRef),
@@ -1499,11 +1477,20 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1477
restrictBelowPins,
1478
restrictToFirstScrollableAncestor,
1479
];
1502
- const attachListMotionRef = (node: HTMLUListElement | null) => {
1480
+ const attachListMotionRef = (node: HTMLUListElement) => {
1481
threadListRef.current = node;
1504
- listMotionRef.current?.dispose();
1505
- listMotionRef.current = node === null ? null : createSidebarListMotion(node);
1506
- listMotionRef.current?.update(false);
1482
+ const motion = createSidebarListMotion(node);
1483
+ listMotionRef.current = motion;
1484
+ motion.update(false);
1485
+ return () => {
1486
+ // Search replaces this list while the Sidebar stays mounted, and a drag
1487
+ // whose rows are gone can never drop. The compiler memoizes this callback
1488
+ // with no deps (it reads only refs), so the cleanup runs only on unmount.
1489
+ dragSensorRef.current?.cancel();
1490
+ motion.dispose();
1491
+ if (listMotionRef.current === motion) listMotionRef.current = null;
1492
+ if (threadListRef.current === node) threadListRef.current = null;
1493
+ };
1494
};
1495
1496
const isContextDrag = dragState?.contextDrag === true || dragState?.activeSection === "working";
@@ -1570,11 +1557,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1557
const dndSensors = useSensors(useSensor(SidebarPointerSensor, pointerSensorOptions));
1558
const sectionByThreadKeyRef = useRef(sectionByThreadKey);
1559
useLayoutEffect(() => {
1573
- routeThreadKeyRef.current = routeThreadKey;
1560
projectGroupsRef.current = projectGroups;
1561
orderedThreadKeysRef.current = orderedThreadKeys;
1562
threadByKeyRef.current = threadByKey;
1577
- handleNewThreadRef.current = newThreadContext.handleNewThread;
1563
settledThreadKeysRef.current = settledThreadKeys;
1564
snoozedThreadKeysRef.current = snoozedThreadKeys;
1565
sectionByThreadKeyRef.current = sectionByThreadKey;
@@ -1943,7 +1928,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1928
settled &&
1929
shouldNavigateAfterThreadPark({
1930
threadKey: activeKey,
1946
- currentThreadKey: routeThreadKeyRef.current,
1931
+ currentThreadKey: readRouteThreadKey(router),
1932
action: "settle",
1933
now: new Date().toISOString(),
1934
thread: readThreadShell(threadRef),
@@ -2014,7 +1999,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1999
if (
2000
shouldNavigateAfterThreadPark({
2001
threadKey,
2017
- currentThreadKey: routeThreadKeyRef.current,
2002
+ currentThreadKey: readRouteThreadKey(router),
2003
action: "snooze",
2004
now: new Date().toISOString(),
2005
thread: readThreadShell(threadRef),
@@ -2454,7 +2439,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2439
return;
2440
case "new-thread-on-branch": {
2441
const result = await settlePromise(() =>
2457
- handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId), {
2442
+ handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
2443
branch: thread.branch,
2444
worktreePath: thread.worktreePath,
2445
envMode: thread.worktreePath ? "worktree" : "local",
@@ -2685,9 +2670,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2670
},
2671
},
2672
);
2688
- useEffect(() => {
2689
- updateThreadJumpHintsVisibility(shouldShowJumpHintsNow);
2690
- }, [shouldShowJumpHintsNow, updateThreadJumpHintsVisibility]);
2673
+ const showJumpHints = useThreadJumpHintsVisible(shouldShowJumpHintsNow);
2674
2675
const handleNewThreadClick = (event?: ReactMouseEvent) => {
2676
if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) {
@@ -2696,7 +2679,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2679
activeDraftThread: newThreadContext.activeDraftThread,
2680
activeThread: newThreadContext.activeThread ?? undefined,
2681
defaultProjectRef: newThreadContext.defaultProjectRef,
2699
- handleNewThread: newThreadContext.handleNewThread,
2682
+ handleNewThread,
2683
});
2684
return;
2685
}
@@ -2906,7 +2889,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2889
}
2890
isHighlighted={activeSearchResultIndex === index}
2891
isRouteActive={routeRowThreadKey === threadKey}
2909
- resultId={`sidebar-thread-search-result-${index}`}
2892
+ resultId={threadSearchResultId(index)}
2893
searchMatch={
2894
threadSearchMatchByKey.get(
2895
threadSearchMatchKey({
@@ -2950,7 +2933,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2933
onDragOver={handleThreadDragOver}
2934
onDragEnd={handleThreadDragEnd}
2935
>
2953
- <SidebarDragLifecycle onUnmount={cancelThreadDrag} />
2936
<SortableContext items={sortableIds} strategy={sidebarSortingStrategy}>
2937
<ul
2938
ref={attachListMotionRef}
@@ -3026,6 +3008,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3008
}
3009
wokeAt={threadWokeAt(thread, { now: snoozeNow })}
3010
isActive={routeRowThreadKey === threadKey}
3011
+ revealRef={
3012
+ routeRowThreadKey === threadKey ? revealActiveRow : undefined
3013
+ }
3014
isRouteThread={routeThreadKey === threadKey}
3015
openPullRequestsInRightPanel={routeThreadRef !== null}
3016
jumpLabel={
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+117
-104
@@ -3,6 +3,7 @@ import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators";
3
import { discardComposerDraft } from "../../lib/discardComposerDraft";
4
import { requestCustomSnooze } from "../CustomSnoozeDialog";
5
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
6
+import { useDeadlinePassed } from "~/hooks/useDeadline";
7
import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests";
8
import { useSortable } from "@dnd-kit/sortable";
9
import { CSS } from "@dnd-kit/utilities";
@@ -49,7 +50,6 @@ import {
50
} from "lucide-react";
51
import {
52
memo,
52
- useEffect,
53
useRef,
54
useState,
55
type KeyboardEvent as ReactKeyboardEvent,
@@ -84,6 +84,7 @@ import {
84
resolveWorkingStartedAt,
85
useRetainedValue,
86
useSidebarRowSubscriptionLease,
87
+ setFileDragActive,
88
} from "../Sidebar.logic";
89
import { resolveLocalCheckoutBranchMismatch } from "../BranchToolbar.logic";
90
import {
@@ -524,6 +525,8 @@ type SidebarThreadRowProps = {
525
snoozeWakeLabelText: string | null;
526
wokeAt: string | null;
527
isActive: boolean;
528
+ // Set on the active row only; scrolls it into view when a reveal is owed.
529
+ revealRef?: ((row: HTMLElement, threadKey: string) => void) | undefined;
530
// Unlike isActive, never true for the ancestor standing in for an open
531
// subagent: drafts and PR clicks care about which composer is on screen.
532
isRouteThread: boolean;
@@ -560,6 +563,47 @@ type SidebarThreadRowProps = {
563
onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined;
564
};
565
566
+// Mounted only while renaming, so each rename starts uncommitted.
567
+function ThreadRenameInput(props: {
568
+ title: string;
569
+ onTitleChange: (title: string) => void;
570
+ onCommit: () => void;
571
+ onCancel: () => void;
572
+}) {
573
+ // Enter and Escape blur the input as it unmounts; that blur must not commit again.
574
+ const settledRef = useRef(false);
575
+ const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
576
+ event.stopPropagation();
577
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
578
+ if (event.key === "Enter") {
579
+ event.preventDefault();
580
+ settledRef.current = true;
581
+ props.onCommit();
582
+ } else if (event.key === "Escape") {
583
+ event.preventDefault();
584
+ settledRef.current = true;
585
+ props.onCancel();
586
+ }
587
+ };
588
+ return (
589
+ <input
590
+ autoFocus
591
+ value={props.title}
592
+ dir="auto"
593
+ aria-label="Thread title"
594
+ onChange={(event) => props.onTitleChange(event.target.value)}
595
+ onFocus={(event) => event.currentTarget.select()}
596
+ onKeyDown={handleKeyDown}
597
+ onBlur={() => {
598
+ if (!settledRef.current) props.onCommit();
599
+ }}
600
+ onClick={(event) => event.stopPropagation()}
601
+ onDoubleClick={(event) => event.stopPropagation()}
602
+ className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground"
603
+ />
604
+ );
605
+}
606
+
607
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
608
const {
609
isRenaming,
@@ -587,10 +631,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
631
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
632
const threadKey = scopedThreadKey(threadRef);
633
const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
590
- useEffect(() => {
591
- if (!canOperateThread && isRenaming) onCancelRename();
592
- }, [canOperateThread, isRenaming, onCancelRename]);
593
- const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(props.isActive);
634
+ const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease(props.isActive);
635
+ const { revealRef } = props;
636
+ const rowRef = (row: HTMLElement | null) => {
637
+ if (row !== null) revealRef?.(row, threadKey);
638
+ return leaseRowRef(row);
639
+ };
640
const isRegeneratingTitle = thread.titleRegeneration != null;
641
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
642
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
@@ -786,41 +832,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
832
const [isFileDragOver, setIsFileDragOver] = useState(false);
833
const fileDropHandlers = onFileDropThreads
834
? makeWorkspaceFileDropHandlers({
789
- setDragActive: setIsFileDragOver,
835
+ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active),
836
addFiles: (files) => {
837
onFileDropThreads(threadRef, files);
838
},
839
addFolders: () => {},
840
})
841
: null;
796
- useEffect(() => {
797
- if (!isFileDragOver) return;
798
- const clearFileDrag = () => setIsFileDragOver(false);
799
- window.addEventListener("dragend", clearFileDrag);
800
- return () => window.removeEventListener("dragend", clearFileDrag);
801
- }, [isFileDragOver]);
802
- const renameCommittedRef = useRef(false);
803
- useEffect(() => {
804
- if (isRenaming) renameCommittedRef.current = false;
805
- }, [isRenaming]);
806
- const handleRenameKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
807
- event.stopPropagation();
808
- if (event.nativeEvent.isComposing || event.keyCode === 229) return;
809
- if (event.key === "Enter") {
810
- event.preventDefault();
811
- renameCommittedRef.current = true;
812
- onCommitRename(threadRef, renamingTitle, thread.title);
813
- } else if (event.key === "Escape") {
814
- event.preventDefault();
815
- renameCommittedRef.current = true;
816
- onCancelRename();
817
- }
818
- };
819
- const handleRenameBlur = () => {
820
- if (!renameCommittedRef.current) {
821
- onCommitRename(threadRef, renamingTitle, thread.title);
822
- }
823
- };
842
const handleSettleClick = (event: ReactMouseEvent) => {
843
event.preventDefault();
844
event.stopPropagation();
@@ -865,18 +883,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
883
const snoozeGateExpiryMs = hasQueuedTurnStart(thread, { now: snoozeGateNow })
884
? Date.parse(thread.latestUserMessageAt ?? "") + QUEUED_TURN_START_GRACE_MS
885
: Number.NaN;
868
- useEffect(() => {
869
- // A gate still closed past its expiry is held by runtime status, not time,
870
- // so no clock tick can open it.
871
- if (!Number.isFinite(snoozeGateExpiryMs) || snoozeGateExpiryMs <= Date.parse(snoozeGateNow)) {
872
- return;
873
- }
874
- const id = window.setTimeout(
875
- () => setSnoozeGateClock({ thread, now: new Date().toISOString() }),
876
- Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647),
877
- );
878
- return () => window.clearTimeout(id);
879
- }, [snoozeGateExpiryMs, snoozeGateNow, thread]);
886
+ // A gate still closed past its expiry is held by runtime status, not time,
887
+ // so no clock tick can open it.
888
+ const snoozeGateOpensAt =
889
+ Number.isFinite(snoozeGateExpiryMs) && snoozeGateExpiryMs > Date.parse(snoozeGateNow)
890
+ ? snoozeGateExpiryMs + 50
891
+ : null;
892
+ const snoozeGateOpened = useDeadlinePassed(snoozeGateOpensAt);
893
+ if (snoozeGateOpened && snoozeGateOpensAt !== null) {
894
+ setSnoozeGateClock({ thread, now: new Date(snoozeGateOpensAt).toISOString() });
895
+ }
896
const showSnoozeButton =
897
canOperateThread && props.snoozeSupported && canSnooze(thread, { now: snoozeGateNow });
898
// Closing here, not just masking, keeps the menu from reopening when the button returns.
@@ -953,55 +969,47 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
969
isActive: props.isActive,
970
});
971
956
- const title =
957
- isRenaming && canOperateThread ? (
958
- <input
959
- autoFocus
960
- value={renamingTitle}
961
- dir="auto"
962
- aria-label="Thread title"
963
- onChange={(event) => onRenameTitleChange(event.target.value)}
964
- onFocus={(event) => event.currentTarget.select()}
965
- onKeyDown={handleRenameKeyDown}
966
- onBlur={handleRenameBlur}
967
- onClick={(event) => event.stopPropagation()}
968
- onDoubleClick={(event) => event.stopPropagation()}
969
- className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground"
970
- />
971
- ) : (
972
- <span
973
- aria-hidden
974
- className={cn(
975
- "min-w-0 flex-1 text-start text-sm transition-opacity motion-reduce:transition-none",
976
- shouldRecede ? "font-normal" : "font-medium",
977
- variant === "card"
978
- ? cn(
979
- "truncate",
980
- shouldRecede
981
- ? "text-secondary-label redesign:text-foreground/75 redesign:group-hover/sidebar-row:text-foreground redesign:group-focus-visible/sidebar-row:text-foreground"
982
- : isUnread || isWoke || status === "input" || status === "request"
983
- ? "text-foreground"
984
- : status === "failed"
985
- ? "text-foreground/95"
986
- : "text-foreground/90 redesign:text-foreground",
987
- )
988
- : cn(
989
- "truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",
990
- shouldRecede
991
- ? "text-secondary-label/70 redesign:text-secondary-label"
992
- : props.isActive || isWoke || status === "input" || status === "request"
993
- ? "text-foreground"
994
- : isUnread
995
- ? "text-muted-foreground"
996
- : "text-secondary-label/70",
997
- ),
998
- isRegeneratingTitle && "opacity-55",
999
- )}
1000
- dir={textDirection(thread.title)}
1001
- >
1002
- {thread.title}
1003
- </span>
1004
- );
972
+ const title = isRenaming ? (
973
+ <ThreadRenameInput
974
+ title={renamingTitle}
975
+ onTitleChange={onRenameTitleChange}
976
+ onCommit={() => onCommitRename(threadRef, renamingTitle, thread.title)}
977
+ onCancel={onCancelRename}
978
+ />
979
+ ) : (
980
+ <span
981
+ aria-hidden
982
+ className={cn(
983
+ "min-w-0 flex-1 text-start text-sm transition-opacity motion-reduce:transition-none",
984
+ shouldRecede ? "font-normal" : "font-medium",
985
+ variant === "card"
986
+ ? cn(
987
+ "truncate",
988
+ shouldRecede
989
+ ? "text-secondary-label redesign:text-foreground/75 redesign:group-hover/sidebar-row:text-foreground redesign:group-focus-visible/sidebar-row:text-foreground"
990
+ : isUnread || isWoke || status === "input" || status === "request"
991
+ ? "text-foreground"
992
+ : status === "failed"
993
+ ? "text-foreground/95"
994
+ : "text-foreground/90 redesign:text-foreground",
995
+ )
996
+ : cn(
997
+ "truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",
998
+ shouldRecede
999
+ ? "text-secondary-label/70 redesign:text-secondary-label"
1000
+ : props.isActive || isWoke || status === "input" || status === "request"
1001
+ ? "text-foreground"
1002
+ : isUnread
1003
+ ? "text-muted-foreground"
1004
+ : "text-secondary-label/70",
1005
+ ),
1006
+ isRegeneratingTitle && "opacity-55",
1007
+ )}
1008
+ dir={textDirection(thread.title)}
1009
+ >
1010
+ {thread.title}
1011
+ </span>
1012
+ );
1013
const accessibleTitle = isRenaming ? null : <span className="sr-only">{thread.title}</span>;
1014
1015
const prBadgeShape = supportsMultiplePullRequests
@@ -1540,6 +1548,13 @@ function latestRunDiff(
1548
return null;
1549
}
1550
1551
+// Attached only to the highlighted result, so React calls it each time the
1552
+// highlight lands on a different row: a new query, late rows replacing the first
1553
+// result, or arrow keys moving past the scrolled edge.
1554
+const scrollHighlightedResultIntoView = (node: HTMLLIElement | null) => {
1555
+ node?.scrollIntoView({ block: "nearest" });
1556
+};
1557
+
1558
export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
1559
isSettled: boolean;
1560
thread: SidebarThreadSummary;
@@ -1609,27 +1624,25 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props
1624
const [isFileDragOver, setIsFileDragOver] = useState(false);
1625
const onFileDropThreads = props.onFileDropThreads;
1626
const fileDropHandlers = makeWorkspaceFileDropHandlers({
1612
- setDragActive: setIsFileDragOver,
1627
+ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active),
1628
addFiles: (files) => {
1629
onFileDropThreads(threadRef, files);
1630
},
1631
addFolders: () => {},
1632
});
1618
- useEffect(() => {
1619
- if (!isFileDragOver) return;
1620
- const clearFileDrag = () => setIsFileDragOver(false);
1621
- window.addEventListener("dragend", clearFileDrag);
1622
- return () => window.removeEventListener("dragend", clearFileDrag);
1623
- }, [isFileDragOver]);
1633
return (
1625
- <li role="presentation" className="list-none" {...fileDropHandlers}>
1634
+ <li
1635
+ ref={props.isHighlighted ? scrollHighlightedResultIntoView : undefined}
1636
+ role="presentation"
1637
+ className="list-none"
1638
+ {...fileDropHandlers}
1639
+ >
1640
<Tooltip>
1641
<TooltipTrigger
1642
render={
1643
<button
1644
ref={rowRef}
1645
id={props.resultId}
1632
- data-search-result-key={scopedThreadKey(threadRef)}
1646
type="button"
1647
role="option"
1648
tabIndex={-1}
apps/web/src/components/sidebar/SidebarThreadUndoNotice.browser.test.tsx
deleted
-37
@@ -1,37 +0,0 @@
1
-import { describe, expect, it, vi } from "vite-plus/test";
2
-
3
-import { act, fakeTimers, render } from "../../../test/render";
4
-import { useThreadUndoNotice } from "../../hooks/showThreadUndoNotice";
5
-import { SidebarThreadUndoNotice } from "./SidebarThreadUndoNotice";
6
-
7
-const spoken = () =>
8
- [...document.querySelectorAll('body > [aria-live="polite"]')]
9
- .map((region) => region.textContent)
10
- .join("");
11
-
12
-describe("SidebarThreadUndoNotice", () => {
13
- it("speaks the notice, and drops it when the notice clears before it is spoken", async () => {
14
- using _notice = { [Symbol.dispose]: () => useThreadUndoNotice.setState({ notice: null }) };
15
- await using _screen = await render(<SidebarThreadUndoNotice />);
16
- using _timers = fakeTimers();
17
- const showSettled = () =>
18
- act(async () =>
19
- useThreadUndoNotice.setState({
20
- notice: { action: "Settled", count: 1, undo: async () => {} },
21
- }),
22
- );
23
-
24
- await showSettled();
25
- await act(async () => vi.advanceTimersByTime(300));
26
- expect(spoken()).toMatch(/^Settled 1 thread, /);
27
-
28
- await act(async () => useThreadUndoNotice.setState({ notice: null }));
29
- for (const region of document.querySelectorAll('body > [aria-live="polite"]')) {
30
- region.textContent = "";
31
- }
32
- await showSettled();
33
- await act(async () => useThreadUndoNotice.setState({ notice: null }));
34
- await act(async () => vi.advanceTimersByTime(300));
35
- expect(spoken()).toBe("");
36
- });
37
-});
apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx
+9
-19
@@ -1,9 +1,11 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import { useEffect } from "react";
2
4
-import { undoLatestThreadAction, useThreadUndoNotice } from "../../hooks/showThreadUndoNotice";
5
-import { shortcutLabelForCommand } from "../../keybindings";
6
-import { announce, cancelAnnouncement } from "../../lib/announce";
3
+import {
4
+ threadUndoLabel,
5
+ threadUndoNoticeSummary,
6
+ undoLatestThreadAction,
7
+ useThreadUndoNotice,
8
+} from "../../hooks/showThreadUndoNotice";
9
import { primaryServerKeybindingsAtom } from "../../state/server";
10
import { Alert, AlertDescription } from "../ui/alert";
11
import { InlineButton } from "../ui/button";
@@ -12,25 +14,13 @@ export function SidebarThreadUndoNotice() {
14
const notice = useThreadUndoNotice((state) => state.notice);
15
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
16
15
- const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
16
- const undoLabel = shortcut ? `${shortcut} to undo` : "Undo";
17
- const summary = notice
18
- ? `${notice.action} ${notice.count} ${notice.action === "Discarded" ? "draft" : "thread"}${notice.count === 1 ? "" : "s"}`
19
- : null;
20
-
21
- // A live region that mounts already filled is skipped by screen readers, and settling
22
- // usually moves focus to the next thread at the same moment.
23
- useEffect(() => {
24
- if (summary) announce(`${summary}, ${undoLabel}`, "thread-undo-notice");
25
- else cancelAnnouncement("thread-undo-notice");
26
- }, [summary, undoLabel]);
27
-
28
- if (!summary) return null;
17
+ if (!notice) return null;
18
19
return (
20
<Alert role="group" variant="sidebar">
21
<AlertDescription>
33
- {summary}, <InlineButton onClick={undoLatestThreadAction}>{undoLabel}</InlineButton>
22
+ {threadUndoNoticeSummary(notice)},{" "}
23
+ <InlineButton onClick={undoLatestThreadAction}>{threadUndoLabel(keybindings)}</InlineButton>
24
</AlertDescription>
25
</Alert>
26
);
apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx
new
+96
@@ -0,0 +1,96 @@
1
+import type { DesktopUpdateState } from "@t3tools/contracts";
2
+import { describe, expect, it, vi } from "vite-plus/test";
3
+import { userEvent } from "vite-plus/test/browser";
4
+
5
+import { act, render } from "../../../test/render";
6
+import { SidebarUpdatePill } from "./SidebarUpdatePill";
7
+
8
+const mocks = vi.hoisted(() => {
9
+ const listeners = new Set<() => void>();
10
+ return {
11
+ update: null as DesktopUpdateState | null,
12
+ subscribe: (listener: () => void) => {
13
+ listeners.add(listener);
14
+ return () => listeners.delete(listener);
15
+ },
16
+ notify: () => {
17
+ for (const listener of listeners) listener();
18
+ },
19
+ };
20
+});
21
+vi.mock("../../state/desktopUpdate", async (importOriginal) => ({
22
+ ...(await importOriginal<typeof import("../../state/desktopUpdate")>()),
23
+ useDesktopUpdateState: (await import("react")).useSyncExternalStore.bind(
24
+ null,
25
+ mocks.subscribe,
26
+ () => mocks.update,
27
+ ),
28
+}));
29
+// The pill only renders in the desktop app.
30
+vi.mock("../../env", async (importOriginal) => ({
31
+ ...(await importOriginal<typeof import("../../env")>()),
32
+ isElectron: true,
33
+}));
34
+vi.mock("./useUpdateEverything", () => ({
35
+ useUpdateEverything: () => ({ hasUpdates: false, summary: "", lines: [], restarts: [] }),
36
+}));
37
+
38
+function nightlyUpdate(releaseNotes: DesktopUpdateState["releaseNotes"]): DesktopUpdateState {
39
+ return {
40
+ enabled: true,
41
+ status: "available",
42
+ channel: "nightly",
43
+ currentVersion: "0.0.50-nightly.1",
44
+ hostArch: "arm64",
45
+ appArch: "arm64",
46
+ runningUnderArm64Translation: false,
47
+ availableVersion: "0.0.50-nightly.2",
48
+ downloadedVersion: null,
49
+ releaseNotes,
50
+ omittedReleaseCount: 0,
51
+ downloadPercent: null,
52
+ checkedAt: null,
53
+ message: null,
54
+ errorContext: null,
55
+ canRetry: false,
56
+ };
57
+}
58
+
59
+const RELEASE_NOTES: DesktopUpdateState["releaseNotes"] = [
60
+ { version: "0.0.50-nightly.2", items: ["Faster sidebar."], totalItems: 1 },
61
+];
62
+
63
+function setup(update: DesktopUpdateState | null) {
64
+ mocks.update = update;
65
+}
66
+
67
+function publish(update: DesktopUpdateState | null) {
68
+ return act(() => {
69
+ mocks.update = update;
70
+ mocks.notify();
71
+ });
72
+}
73
+
74
+const releaseNotes = () => document.querySelector('[aria-label="Nightly update release notes"]');
75
+
76
+describe("SidebarUpdatePill release notes", () => {
77
+ it("closes when the release notes stop applying", async () => {
78
+ setup(nightlyUpdate(RELEASE_NOTES));
79
+ await using _screen = await render(<SidebarUpdatePill />);
80
+ await userEvent.tab();
81
+ await vi.waitFor(() => expect(releaseNotes()).not.toBeNull());
82
+
83
+ await publish(nightlyUpdate([]));
84
+ await vi.waitFor(() => expect(releaseNotes()).toBeNull());
85
+ });
86
+
87
+ it("opens when release notes arrive while the trigger has keyboard focus", async () => {
88
+ setup(nightlyUpdate([]));
89
+ await using _screen = await render(<SidebarUpdatePill />);
90
+ await userEvent.tab();
91
+ expect(releaseNotes()).toBeNull();
92
+
93
+ await publish(nightlyUpdate(RELEASE_NOTES));
94
+ await vi.waitFor(() => expect(releaseNotes()).not.toBeNull());
95
+ });
96
+});
apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+17
-13
@@ -1,6 +1,6 @@
1
import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
2
import { TriangleAlertIcon } from "lucide-react";
3
-import { type ComponentProps, useEffect, useId, useRef, useState } from "react";
3
+import { type ComponentProps, useId, useRef, useState } from "react";
4
import { flushSync } from "react-dom";
5
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6
import { isElectron } from "../../env";
@@ -259,17 +259,15 @@ function SidebarUpdateControl() {
259
const showReleaseNotesPopover =
260
!isRunningEverything && shouldUseSidebarUpdateReleaseNotesPopover(showUpdateDetails, state);
261
262
- useEffect(() => {
263
- if (!showReleaseNotesPopover) {
264
- releaseNotesPopoverHandle.close();
265
- return;
266
- }
267
-
268
- const trigger = document.getElementById(releaseNotesTriggerId);
269
- if (trigger?.matches(":focus-visible")) {
270
- releaseNotesPopoverHandle.open(releaseNotesTriggerId);
271
- }
272
- }, [releaseNotesPopoverHandle, releaseNotesTriggerId, showReleaseNotesPopover]);
262
+ const [releaseNotesOpen, setReleaseNotesOpen] = useState(false);
263
+ const [releaseNotesTriggerFocusVisible, setReleaseNotesTriggerFocusVisible] = useState(false);
264
+ // Release notes close when they stop applying, and open when they start
265
+ // applying while the trigger already holds keyboard focus.
266
+ const [releaseNotesShownBefore, setReleaseNotesShownBefore] = useState(showReleaseNotesPopover);
267
+ if (releaseNotesShownBefore !== showReleaseNotesPopover) {
268
+ setReleaseNotesShownBefore(showReleaseNotesPopover);
269
+ setReleaseNotesOpen(showReleaseNotesPopover && releaseNotesTriggerFocusVisible);
270
+ }
271
272
const handleAction = async () => {
273
const bridge = window.desktopBridge;
@@ -463,9 +461,12 @@ function SidebarUpdateControl() {
461
onClick={handleAction}
462
onBlur={() => {
463
suppressReleaseNotesFocusOpen.current = false;
464
+ setReleaseNotesTriggerFocusVisible(false);
465
}}
466
onFocus={(event) => {
468
- if (!showReleaseNotesPopover || !event.currentTarget.matches(":focus-visible")) return;
467
+ const focusVisible = event.currentTarget.matches(":focus-visible");
468
+ setReleaseNotesTriggerFocusVisible(focusVisible);
469
+ if (!showReleaseNotesPopover || !focusVisible) return;
470
if (suppressReleaseNotesFocusOpen.current) {
471
suppressReleaseNotesFocusOpen.current = false;
472
return;
@@ -489,12 +490,15 @@ function SidebarUpdateControl() {
490
<SidebarMenuItem className="ml-auto shrink-0">
491
<Popover
492
handle={releaseNotesPopoverHandle}
493
+ open={releaseNotesOpen && showReleaseNotesPopover}
494
+ triggerId={releaseNotesTriggerId}
495
onOpenChange={(open, details) => {
496
if (open && !showReleaseNotesPopover) {
497
details.cancel();
498
return;
499
}
500
handleSidebarUpdateReleaseNotesPopoverOpenChange(open, details);
501
+ if (!details.isCanceled) setReleaseNotesOpen(open);
502
}}
503
>
504
<Tooltip disabled={showReleaseNotesPopover}>
apps/web/src/components/sidebar/routeReveal.browser.test.tsx
new
+107
@@ -0,0 +1,107 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { render } from "../../../test/render";
4
+import { type SidebarRouteReveal, useActiveRowReveal } from "./routeReveal";
5
+
6
+const ROW_HEIGHT_PX = 24;
7
+
8
+function RevealList(props: {
9
+ readonly reveal: SidebarRouteReveal;
10
+ readonly rowKeys: ReadonlyArray<string>;
11
+ readonly activeKey: string | null;
12
+}) {
13
+ const revealActiveRow = useActiveRowReveal(props.reveal, props.activeKey);
14
+ return (
15
+ <ul aria-label="Threads" style={{ height: ROW_HEIGHT_PX * 4, overflowY: "auto", margin: 0 }}>
16
+ {props.rowKeys.map((key) => (
17
+ <li
18
+ key={key}
19
+ ref={key === props.activeKey ? (row) => revealActiveRow(row, key) : undefined}
20
+ style={{ height: ROW_HEIGHT_PX }}
21
+ >
22
+ {key}
23
+ </li>
24
+ ))}
25
+ </ul>
26
+ );
27
+}
28
+
29
+const rowKeys = (count: number) => Array.from({ length: count }, (_, index) => `thread-${index}`);
30
+const newReveal = (): SidebarRouteReveal => ({ observedKey: null, pendingKey: null });
31
+
32
+describe("useActiveRowReveal", () => {
33
+ it("scrolls an off-screen row into view when the route opens its thread", async () => {
34
+ const reveal = newReveal();
35
+ const keys = rowKeys(50);
36
+ await using screen = await render(
37
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-0" />,
38
+ // No router: the route arrives as the activeKey prop.
39
+ { router: false },
40
+ );
41
+ const target = screen.getByText("thread-40", { exact: true });
42
+ await expect.element(target).not.toBeInViewport();
43
+
44
+ await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />);
45
+
46
+ await expect.element(target).toBeInViewport();
47
+ });
48
+
49
+ it("reveals the active row when it mounts after the shells arrive", async () => {
50
+ const reveal = newReveal();
51
+ // The route already names the thread, but its environment's shells have not
52
+ // listed it yet.
53
+ await using screen = await render(
54
+ <RevealList reveal={reveal} rowKeys={rowKeys(5)} activeKey="thread-40" />,
55
+ // No router: the route arrives as the activeKey prop.
56
+ { router: false },
57
+ );
58
+ await expect.element(screen.getByText("thread-4", { exact: true })).toBeInTheDocument();
59
+
60
+ await screen.rerender(
61
+ <RevealList reveal={reveal} rowKeys={rowKeys(50)} activeKey="thread-40" />,
62
+ );
63
+
64
+ await expect.element(screen.getByText("thread-40", { exact: true })).toBeInViewport();
65
+ });
66
+
67
+ it("reveals a thread reopened after a thread whose row never mounted", async () => {
68
+ const reveal = newReveal();
69
+ const keys = rowKeys(50);
70
+ await using screen = await render(
71
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />,
72
+ // No router: the route arrives as the activeKey prop.
73
+ { router: false },
74
+ );
75
+ const target = screen.getByText("thread-40", { exact: true });
76
+ await expect.element(target).toBeInViewport();
77
+ screen.getByRole("list", { name: "Threads" }).element().scrollTop = 0;
78
+ await expect.element(target).not.toBeInViewport();
79
+
80
+ // The route moves to a thread the list does not hold yet, then back.
81
+ await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-99" />);
82
+ await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />);
83
+
84
+ await expect.element(target).toBeInViewport();
85
+ });
86
+
87
+ it("reveals the open thread again when the sidebar remounts on the same route", async () => {
88
+ const reveal = newReveal();
89
+ const keys = rowKeys(50);
90
+ {
91
+ await using screen = await render(
92
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />,
93
+ // No router: the route arrives as the activeKey prop.
94
+ { router: false },
95
+ );
96
+ await expect.element(screen.getByText("thread-40", { exact: true })).toBeInViewport();
97
+ }
98
+
99
+ // A remount starts the list at the top; the record outlives it with no reveal pending.
100
+ await using screen = await render(
101
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />,
102
+ // No router: the route arrives as the activeKey prop.
103
+ { router: false },
104
+ );
105
+ await expect.element(screen.getByText("thread-40", { exact: true })).toBeInViewport();
106
+ });
107
+});
apps/web/src/components/sidebar/routeReveal.ts
+43
@@ -1,3 +1,7 @@
1
+import { useRef } from "react";
2
+
3
+import { filterSidebarV2VisibleThreads } from "../Sidebar.logic";
4
+
5
// AppSidebarLayout owns this so drawer and Settings remounts preserve the chosen project scope.
6
// Only route changes may widen that scope; scroll position is lost on remount.
7
// Leaving Settings commits the router's location before its matches, briefly hiding thread params.
@@ -22,3 +26,42 @@ export function pendingSidebarRouteReveal(
26
export function completeSidebarRouteReveal(reveal: SidebarRouteReveal): void {
27
reveal.pendingKey = null;
28
}
29
+
30
+// Each route change and each mount scroll to the open thread once. Render records
31
+// the route, so a thread left before its row mounted still counts as a change.
32
+// The row can mount after the route, once its shells arrive, so its ref scrolls.
33
+export function useActiveRowReveal(reveal: SidebarRouteReveal, routeKey: string | null) {
34
+ const mountRevealOwed = useRef(true);
35
+ pendingSidebarRouteReveal(reveal, routeKey);
36
+ return (row: HTMLElement | null, rowKey: string) => {
37
+ if (row === null) return;
38
+ if (reveal.pendingKey !== rowKey && !mountRevealOwed.current) return;
39
+ completeSidebarRouteReveal(reveal);
40
+ mountRevealOwed.current = false;
41
+ row.scrollIntoView({ block: "nearest" });
42
+ };
43
+}
44
+
45
+type RevealableThread = Parameters<typeof filterSidebarV2VisibleThreads>[0][number];
46
+
47
+// Render records the route before deciding, so the first render of a new route
48
+// already widens the scope. Only a route reveal widens: the once-per-mount
49
+// scroll never changes a scope the user chose.
50
+export function resolveSidebarRouteReveal<T extends RevealableThread>(input: {
51
+ readonly reveal: SidebarRouteReveal;
52
+ readonly routeKey: string | null;
53
+ readonly isSearching: boolean;
54
+ readonly scopedProjectKeys: ReadonlySet<string> | null;
55
+ readonly findThread: (key: string) => T | undefined;
56
+}): { readonly pendingKey: string | null; readonly widensScope: boolean } {
57
+ const { reveal, routeKey, isSearching, scopedProjectKeys, findThread } = input;
58
+ const pendingKey = pendingSidebarRouteReveal(reveal, routeKey);
59
+ // Search results replace the thread list; the reveal waits for it to return.
60
+ const thread = pendingKey === null || isSearching ? undefined : findThread(pendingKey);
61
+ const widensScope =
62
+ thread !== undefined &&
63
+ scopedProjectKeys !== null &&
64
+ filterSidebarV2VisibleThreads([thread], scopedProjectKeys).length === 0 &&
65
+ filterSidebarV2VisibleThreads([thread], null).length === 1;
66
+ return { pendingKey, widensScope };
67
+}
apps/web/src/hooks/showThreadUndoNotice.test.ts
+23
@@ -2,6 +2,7 @@ import { AsyncResult } from "effect/reactivity";
2
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3
4
import { toastManager } from "../components/ui/toast";
5
+import { announce, cancelAnnouncement } from "../lib/announce";
6
import {
7
releaseThreadUndoShortcut,
8
showThreadUndoNotice,
@@ -10,6 +11,8 @@ import {
11
} from "./showThreadUndoNotice";
12
import * as ThreadUndo from "./threadUndo";
13
14
+vi.mock("../lib/announce", () => ({ announce: vi.fn(), cancelAnnouncement: vi.fn() }));
15
+
16
beforeEach(() => vi.useFakeTimers());
17
afterEach(() => {
18
vi.runAllTimers();
@@ -65,4 +68,24 @@ describe("thread undo notice", () => {
68
vi.advanceTimersByTime(5_000);
69
expect(threadUndoClaimsShortcut()).toBe(false);
70
});
71
+
72
+ it("announces each new summary once, and cancels it when the notice clears", async () => {
73
+ const { options } = setup();
74
+ vi.mocked(announce).mockClear();
75
+ vi.mocked(cancelAnnouncement).mockClear();
76
+ showThreadUndoNotice(options);
77
+ expect(announce).toHaveBeenCalledExactlyOnceWith(
78
+ expect.stringMatching(/^Unpinned 1 thread, /),
79
+ "thread-undo-notice",
80
+ );
81
+ ThreadUndo.invalidate("pin", "env/other");
82
+ expect(announce).toHaveBeenCalledOnce();
83
+ showThreadUndoNotice({ ...options, claim: ThreadUndo.begin("pin", "env/second") });
84
+ expect(announce).toHaveBeenLastCalledWith(
85
+ expect.stringMatching(/^Unpinned 2 threads, /),
86
+ "thread-undo-notice",
87
+ );
88
+ await notice().undo();
89
+ expect(cancelAnnouncement).toHaveBeenCalledWith("thread-undo-notice");
90
+ });
91
});
apps/web/src/hooks/showThreadUndoNotice.ts
+62
-34
@@ -6,6 +6,10 @@ import {
6
import { create } from "zustand";
7
8
import { stackedThreadToast, toastManager } from "../components/ui/toast";
9
+import { shortcutLabelForCommand } from "../keybindings";
10
+import { announce, cancelAnnouncement } from "../lib/announce";
11
+import { appAtomRegistry } from "../rpc/atomRegistry";
12
+import { primaryServerKeybindingsAtom } from "../state/server";
13
import * as ThreadUndo from "./threadUndo";
14
15
type UndoOptions = {
@@ -24,6 +28,34 @@ type UndoNotice = {
28
29
export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null }));
30
31
+export function threadUndoNoticeSummary(notice: Pick<UndoNotice, "action" | "count">): string {
32
+ const noun = notice.action === "Discarded" ? "draft" : "thread";
33
+ return `${notice.action} ${notice.count} ${noun}${notice.count === 1 ? "" : "s"}`;
34
+}
35
+
36
+export function threadUndoLabel(keybindings: Parameters<typeof shortcutLabelForCommand>[0]) {
37
+ const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
38
+ return shortcut ? `${shortcut} to undo` : "Undo";
39
+}
40
+
41
+let announcedSummary: string | null = null;
42
+
43
+// A live region that mounts already filled is skipped by screen readers, and settling
44
+// usually moves focus to the next thread at the same moment, so the notice is announced
45
+// separately from the alert that shows it.
46
+function setNotice(notice: UndoNotice | null) {
47
+ useThreadUndoNotice.setState({ notice });
48
+ const summary = notice ? threadUndoNoticeSummary(notice) : null;
49
+ if (summary === announcedSummary) return;
50
+ announcedSummary = summary;
51
+ if (summary) {
52
+ const label = threadUndoLabel(appAtomRegistry.get(primaryServerKeybindingsAtom));
53
+ announce(`${summary}, ${label}`, "thread-undo-notice");
54
+ } else {
55
+ cancelAnnouncement("thread-undo-notice");
56
+ }
57
+}
58
+
59
let liveUndos: UndoOptions[] = [];
60
let expiry: ReturnType<typeof setTimeout> | undefined;
61
// A new notice owns mod+z even inside a text field, until the user presses
@@ -37,7 +69,7 @@ function refreshNotice() {
69
const latest = liveUndos.at(-1);
70
if (!latest) {
71
clearTimeout(expiry);
40
- useThreadUndoNotice.setState({ notice: null });
72
+ setNotice(null);
73
return;
74
}
75
const group: UndoOptions[] = [];
@@ -46,40 +78,36 @@ function refreshNotice() {
78
if (entry.action !== latest.action) break;
79
group.push(entry);
80
}
49
- useThreadUndoNotice.setState({
50
- notice: {
51
- action: latest.action,
52
- count: group.length,
53
- undo: async () => {
54
- const current = group.filter(
55
- (entry) => liveUndos.includes(entry) && entry.claim.isCurrent(),
56
- );
57
- liveUndos = liveUndos.filter((entry) => !group.includes(entry));
58
- // Claim before awaiting to prevent repeated actions restoring a group twice.
59
- for (const entry of current) entry.claim.finish();
60
- refreshNotice();
61
- await Promise.all(
62
- current.map(async ({ undo, failureTitle }) => {
63
- const reportFailure = (error: unknown) => {
64
- toastManager.add(
65
- stackedThreadToast({
66
- type: "error",
67
- title: failureTitle,
68
- description: error instanceof Error ? error.message : "An error occurred.",
69
- }),
70
- );
71
- };
72
- try {
73
- const result = await undo();
74
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
75
- reportFailure(squashAtomCommandFailure(result));
76
- }
77
- } catch (error) {
78
- reportFailure(error);
81
+ setNotice({
82
+ action: latest.action,
83
+ count: group.length,
84
+ undo: async () => {
85
+ const current = group.filter((entry) => liveUndos.includes(entry) && entry.claim.isCurrent());
86
+ liveUndos = liveUndos.filter((entry) => !group.includes(entry));
87
+ // Claim before awaiting to prevent repeated actions restoring a group twice.
88
+ for (const entry of current) entry.claim.finish();
89
+ refreshNotice();
90
+ await Promise.all(
91
+ current.map(async ({ undo, failureTitle }) => {
92
+ const reportFailure = (error: unknown) => {
93
+ toastManager.add(
94
+ stackedThreadToast({
95
+ type: "error",
96
+ title: failureTitle,
97
+ description: error instanceof Error ? error.message : "An error occurred.",
98
+ }),
99
+ );
100
+ };
101
+ try {
102
+ const result = await undo();
103
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
104
+ reportFailure(squashAtomCommandFailure(result));
105
}
80
- }),
81
- );
82
- },
106
+ } catch (error) {
107
+ reportFailure(error);
108
+ }
109
+ }),
110
+ );
111
},
112
});
113
}
apps/web/src/lib/announce.ts
+2
@@ -37,6 +37,8 @@ function createRegion() {
37
* replaces one still waiting from the same `source`, so a superseded status isn't read out.
38
*/
39
export function announce(message: string, source?: string) {
40
+ // Stores announce without a mounted owner, so they also run where no DOM exists (unit tests).
41
+ if (typeof document === "undefined") return;
42
if (!regions) {
43
regions = [createRegion(), createRegion()];
44
document.addEventListener("focusin", () => {
packages/client-runtime/src/clock.ts
+5
@@ -112,6 +112,11 @@ function armDeadline(entry: DeadlineEntry, deadlineMs: number) {
112
entry.timer = setTimeout(() => armDeadline(entry, deadlineMs), Math.min(delay, MAX_TIMEOUT_MS));
113
}
114
115
+/** The epoch-ms deadline `delayMs` from now, for `deadlineStore`. */
116
+export function deadlineAfter(delayMs: number): number {
117
+ return Date.now() + delayMs;
118
+}
119
+
120
/**
121
* Whether `Date.now()` has reached `deadlineMs`. One timer per distinct
122
* deadline, shared by its subscribers; once passed the snapshot stays true.