Skip to content
TypeScript

refactor(web): sidebar thread lists derive state instead of syncing it in effects (#25234)

Julius Marminge6a3a460b09e7
diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx
index bf5a40095f2..4d1f6f8ef5d 100644
--- a/apps/web/src/components/LegacySidebar.tsx
+++ b/apps/web/src/components/LegacySidebar.tsx
@@ -24,7 +24,15 @@ import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { ProjectFavicon } from "./ProjectFavicon";
import { useAtomValue } from "@effect/atom-react";
import { autoAnimate } from "@formkit/auto-animate";
-import React, { useEffect, useEffectEvent, memo, useRef, useState } from "react";
+import React, {
+ createContext,
+ useEffect,
+ useEffectEvent,
+ memo,
+ useContext,
+ useRef,
+ useState,
+} from "react";
import { cn } from "~/lib/utils";
import { useShallow } from "zustand/react/shallow";
import {
@@ -199,7 +207,8 @@ import {
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
useSidebarRowSubscriptionLease,
- useThreadJumpHintVisibility,
+ setFileDragActive,
+ useThreadJumpHintsVisible,
ThreadStatusPill,
} from "./Sidebar.logic";
import { sortThreads } from "../lib/threadSort";
@@ -227,11 +236,7 @@ import {
} from "../sidebarProjectGrouping";
import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
-import {
- completeSidebarRouteReveal,
- pendingSidebarRouteReveal,
- type SidebarRouteReveal,
-} from "./sidebar/routeReveal";
+import { type SidebarRouteReveal, useActiveRowReveal } from "./sidebar/routeReveal";
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
updated_at: "Last user message",
created_at: "Created at",
@@ -383,6 +388,11 @@ function checkTaskPermission(environmentId: EnvironmentId): boolean {
return false;
}
+// The active row reports itself, so a route change scrolls to it once it mounts.
+const RevealActiveRowContext = createContext<(row: HTMLElement | null, threadKey: string) => void>(
+ () => {},
+);
+
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
orderedProjectThreadKeys,
@@ -415,12 +425,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
const canOperatePreview = useEnvironmentScope(thread.environmentId, AuthPreviewOperateScope);
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
const [isFileDragOver, setIsFileDragOver] = useState(false);
- useEffect(() => {
- if (!isFileDragOver) return;
- const clearFileDrag = () => setIsFileDragOver(false);
- window.addEventListener("dragend", clearFileDrag);
- return () => window.removeEventListener("dragend", clearFileDrag);
- }, [isFileDragOver]);
+ const revealActiveRow = useContext(RevealActiveRowContext);
const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(isActive);
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
@@ -466,7 +471,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
// Hooks must precede this ref's plain uses for the compiler to cache it.
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const fileDropHandlers = makeWorkspaceFileDropHandlers({
- setDragActive: setIsFileDragOver,
+ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active),
addFiles: (files) => {
onFileDropThreads(threadRef, files);
},
@@ -669,6 +674,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
onBlurCapture={handleBlurCapture}
>
<div
+ ref={isActive ? (node) => revealActiveRow(node, threadKey) : undefined}
role="button"
tabIndex={0}
data-active={isActive}
@@ -3259,6 +3265,13 @@ function useLegacySidebarThreads(input: {
};
}
+function clearThreadSelectionOnOutsideMouseDown(event: globalThis.MouseEvent) {
+ const selection = useThreadSelectionStore.getState();
+ if (!selection.hasSelection()) return;
+ const target = event.target instanceof HTMLElement ? event.target : null;
+ if (shouldClearThreadSelectionOnMouseDown(target)) selection.clearSelection();
+}
+
export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) {
const reorderProjects = useUiStateStore((store) => store.reorderProjects);
const navigate = useNavigate();
@@ -3283,7 +3296,6 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<string>
>(() => new Set());
- const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility();
const dragInProgressRef = useRef(false);
const suppressProjectClickAfterDragRef = useRef(false);
const suppressProjectClickForContextMenuRef = useRef(false);
@@ -3323,25 +3335,7 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
sidebarThreadPreviewCount,
expandedThreadListsByProject,
});
- // History and the command palette can open a thread scrolled out of view,
- // and a remount starts the list at the top, so each route change and each
- // mount scroll to the open thread once. Its row can mount after the route
- // does, once its environment's shells arrive, so the reveal waits for it.
- const mountRevealOwed = useRef(true);
- const routeRowRendered =
- routeThreadKey !== null && visibleSidebarThreadKeys.includes(routeThreadKey);
- const revealRouteRow = useStableCallback(() => {
- const pendingKey = pendingSidebarRouteReveal(routeReveal, routeThreadKey);
- if (pendingKey === null && (!mountRevealOwed.current || routeThreadKey === null)) return;
- const activeRow = document.querySelector(
- '[data-sidebar="content"] [data-thread-item] [data-active="true"]',
- );
- if (!activeRow) return;
- completeSidebarRouteReveal(routeReveal);
- mountRevealOwed.current = false;
- activeRow.scrollIntoView({ block: "nearest" });
- });
- useEffect(revealRouteRow, [revealRouteRow, routeThreadKey, routeRowRendered]);
+ const revealActiveRow = useActiveRowReveal(routeReveal, routeThreadKey);
const newThreadShortcutLabelOptions = {
platform,
context: {
@@ -3438,15 +3432,12 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
context: sidebarShortcutContext,
},
);
+ const showThreadJumpHints = useThreadJumpHintsVisible(shouldShowThreadJumpHintsNow);
const visibleThreadJumpLabelByKey = showThreadJumpHints
? threadJumpLabelByKey
: EMPTY_THREAD_JUMP_LABELS;
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
- useEffect(() => {
- updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
- }, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]);
-
const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => {
const shortcutContext = {
terminalFocus: isTerminalFocused(),
@@ -3508,20 +3499,11 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
window.removeEventListener("keydown", handleWindowKeyDown);
};
}, []);
-
+ // A window listener whose lifetime is the sidebar's: no element owns outside clicks.
useEffect(() => {
- const onMouseDown = (event: globalThis.MouseEvent) => {
- if (!useThreadSelectionStore.getState().hasSelection()) return;
- const target = event.target instanceof HTMLElement ? event.target : null;
- if (!shouldClearThreadSelectionOnMouseDown(target)) return;
- clearSelection();
- };
-
- window.addEventListener("mousedown", onMouseDown);
- return () => {
- window.removeEventListener("mousedown", onMouseDown);
- };
- }, [clearSelection]);
+ window.addEventListener("mousedown", clearThreadSelectionOnOutsideMouseDown);
+ return () => window.removeEventListener("mousedown", clearThreadSelectionOnOutsideMouseDown);
+ }, []);
const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState);
const desktopUpdateButtonAction = desktopUpdateState
@@ -3647,7 +3629,7 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
};
return (
- <>
+ <RevealActiveRowContext value={revealActiveRow}>
{prewarmedSidebarThreadRefs.map((threadRef) => (
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
))}
@@ -3693,6 +3675,6 @@ export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRou
projectsLength={projectsLength}
/>
<SidebarChromeFooter />
- </>
+ </RevealActiveRowContext>
);
}
diff --git a/apps/web/src/components/Sidebar.logic.browser.test.tsx b/apps/web/src/components/Sidebar.logic.browser.test.tsx
new file mode 100644
index 00000000000..c7c5e6bcb24
--- /dev/null
+++ b/apps/web/src/components/Sidebar.logic.browser.test.tsx
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { render } from "../../test/render";
+import { useSnoozeWakeClock } from "./Sidebar.logic";
+
+const MOUNTED_AT_MS = Date.parse("2026-10-24T08:00:00.000Z");
+
+function WakeClock(props: { readonly threads: ReadonlyArray<{ readonly snoozedUntil: string }> }) {
+ return <output>{useSnoozeWakeClock(props.threads)}</output>;
+}
+
+describe("useSnoozeWakeClock", () => {
+ it("settles in one step when many distinct wakes passed during a sleep", async () => {
+ using now = vi.spyOn(Date, "now").mockReturnValue(MOUNTED_AT_MS);
+ // More distinct wakes than React's 25 render-phase re-render limit.
+ const threads = Array.from({ length: 40 }, (_, index) => ({
+ snoozedUntil: new Date(MOUNTED_AT_MS + 1 + index * 60_000).toISOString(),
+ }));
+ await using screen = await render(<WakeClock threads={threads} />, {
+ // A bare hook host; nothing here links or navigates.
+ router: false,
+ });
+ await expect.element(screen.getByRole("status")).toHaveTextContent(String(MOUNTED_AT_MS));
+
+ // The machine resumes after every wake has passed; the first wake's timer fires late.
+ const resumedAtMs = MOUNTED_AT_MS + 24 * 60 * 60_000;
+ now.mockReturnValue(resumedAtMs);
+
+ // The clock lands on the last elapsed wake, so every woken thread has left the shelf.
+ const lastWakeMs = MOUNTED_AT_MS + 1 + 39 * 60_000;
+ await expect.element(screen.getByRole("status")).toHaveTextContent(String(lastWakeMs));
+ });
+});
diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts
index 503a6160df7..a66540ff4fd 100644
--- a/apps/web/src/components/Sidebar.logic.test.ts
+++ b/apps/web/src/components/Sidebar.logic.test.ts
@@ -44,7 +44,11 @@ import {
type Thread,
} from "../types";
import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures";
-import { completeSidebarRouteReveal, pendingSidebarRouteReveal } from "./sidebar/routeReveal";
+import {
+ completeSidebarRouteReveal,
+ pendingSidebarRouteReveal,
+ resolveSidebarRouteReveal,
+} from "./sidebar/routeReveal";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -1288,3 +1292,63 @@ describe("pendingSidebarRouteReveal", () => {
expect(pendingSidebarRouteReveal(reveal, "env:a1")).toBe("env:a1");
});
});
+
+describe("resolveSidebarRouteReveal", () => {
+ const scopedProjectKeys = new Set(["environment-test:project-scoped"]);
+ const hidden = makeThreadFixture({ projectId: ProjectId.make("project-other") });
+ const hiddenKey = "environment-test:thread-test";
+ const findThread = (key: string) => (key === hiddenKey ? hidden : undefined);
+
+ it("widens the scope for a newly opened thread the scope hides", () => {
+ expect(
+ resolveSidebarRouteReveal({
+ reveal: { observedKey: "environment-test:other", pendingKey: null },
+ routeKey: hiddenKey,
+ isSearching: false,
+ scopedProjectKeys,
+ findThread,
+ }),
+ ).toEqual({ pendingKey: hiddenKey, widensScope: true });
+ });
+
+ it("never widens for a thread whose reveal already completed", () => {
+ // A remount's once-per-mount scroll must keep the scope the user chose.
+ expect(
+ resolveSidebarRouteReveal({
+ reveal: { observedKey: hiddenKey, pendingKey: null },
+ routeKey: hiddenKey,
+ isSearching: false,
+ scopedProjectKeys,
+ findThread,
+ }),
+ ).toEqual({ pendingKey: null, widensScope: false });
+ });
+
+ it("widens again for a thread reopened before the thread between them listed its row", () => {
+ // The user scoped away from the open thread, then went to a thread whose row
+ // never mounted, then came back.
+ const reveal = { observedKey: hiddenKey, pendingKey: null };
+ const resolve = (routeKey: string) =>
+ resolveSidebarRouteReveal({
+ reveal,
+ routeKey,
+ isSearching: false,
+ scopedProjectKeys,
+ findThread,
+ });
+ resolve("environment-test:unlisted");
+ expect(resolve(hiddenKey)).toEqual({ pendingKey: hiddenKey, widensScope: true });
+ });
+
+ it("holds a pending reveal without widening while searching", () => {
+ expect(
+ resolveSidebarRouteReveal({
+ reveal: { observedKey: hiddenKey, pendingKey: hiddenKey },
+ routeKey: hiddenKey,
+ isSearching: true,
+ scopedProjectKeys,
+ findThread,
+ }),
+ ).toEqual({ pendingKey: hiddenKey, widensScope: false });
+ });
+});
diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts
index 1164cfa5261..475ca412711 100644
--- a/apps/web/src/components/Sidebar.logic.ts
+++ b/apps/web/src/components/Sidebar.logic.ts
@@ -31,6 +31,8 @@ import type { SidebarThreadSummary, Thread } from "../types";
import { normalizeSearchText } from "../lib/utils";
import { isLatestRunSettled } from "../session-logic";
import { observeIntersection } from "../lib/observeIntersection";
+import { deadlineAfter, deadlineStore } from "@t3tools/client-runtime/clock";
+import { useDeadlinePassed } from "../hooks/useDeadline";
export function shouldNavigateAfterThreadPark(input: {
readonly threadKey: string;
@@ -89,6 +91,61 @@ export function useSidebarRowSubscriptionLease(isActive: boolean): {
};
}
+const fileDragClears = new Set<(active: false) => void>();
+function clearFileDrags() {
+ const clears = [...fileDragClears];
+ fileDragClears.clear();
+ for (const clear of clears) clear(false);
+}
+
+/**
+ * A file drag that ends outside every drop target (Escape, or a drop elsewhere)
+ * sends no dragleave to the row it last entered, so the window's dragend clears it.
+ */
+export function setFileDragActive(setActive: (active: boolean) => void, active: boolean) {
+ setActive(active);
+ if (typeof window === "undefined") return;
+ if (!active) {
+ if (fileDragClears.delete(setActive) && fileDragClears.size === 0) {
+ window.removeEventListener("dragend", clearFileDrags);
+ }
+ return;
+ }
+ if (fileDragClears.size === 0) window.addEventListener("dragend", clearFileDrags, { once: true });
+ fileDragClears.add(setActive);
+}
+
+/**
+ * A clock that advances exactly when a snooze wake time passes, so a woken
+ * thread leaves the shelf on time without a per-second clock.
+ */
+export function useSnoozeWakeClock(
+ threads: ReadonlyArray<{ readonly snoozedUntil?: string | null | undefined }>,
+): number {
+ const [clockMs, setClockMs] = React.useState(() => Date.now());
+ const wakeTimes: number[] = [];
+ let nextWakeAt: number | null = null;
+ for (const thread of threads) {
+ const wakeAt = thread.snoozedUntil == null ? Number.NaN : Date.parse(thread.snoozedUntil);
+ if (!(wakeAt > clockMs)) continue;
+ wakeTimes.push(wakeAt);
+ if (nextWakeAt === null || wakeAt < nextWakeAt) nextWakeAt = wakeAt;
+ }
+ const woke = useDeadlinePassed(nextWakeAt);
+ // Advancing to the latest wake that has passed skips every wake that elapsed
+ // meanwhile, e.g. across a laptop sleep. Stepping one wake at a time would
+ // re-render once per elapsed wake and hit React's limit.
+ if (woke && nextWakeAt !== null) {
+ let nextClockMs = nextWakeAt;
+ for (const wakeAt of wakeTimes) {
+ if (wakeAt > nextClockMs && deadlineStore(wakeAt).getSnapshot()) nextClockMs = wakeAt;
+ }
+ setClockMs(nextClockMs);
+ return nextClockMs;
+ }
+ return clockMs;
+}
+
export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
const [retained, setRetained] = React.useState<{
readonly key: string;
@@ -607,89 +664,16 @@ type ThreadStatusInput = Pick<
blockedOnThreadWait?: boolean | undefined;
};
-export interface ThreadJumpHintVisibilityController {
- sync: (shouldShow: boolean) => void;
- dispose: () => void;
-}
-
-function createThreadJumpHintVisibilityController(input: {
- delayMs: number;
- onVisibilityChange: (visible: boolean) => void;
- setTimeoutFn?: typeof globalThis.setTimeout;
- clearTimeoutFn?: typeof globalThis.clearTimeout;
-}): ThreadJumpHintVisibilityController {
- const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
- const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
- let isVisible = false;
- let timeoutId: NodeJS.Timeout | null = null;
-
- const clearPendingShow = () => {
- if (timeoutId === null) {
- return;
- }
- clearTimeoutFn(timeoutId);
- timeoutId = null;
- };
-
- return {
- sync: (shouldShow) => {
- if (!shouldShow) {
- clearPendingShow();
- if (isVisible) {
- isVisible = false;
- input.onVisibilityChange(false);
- }
- return;
- }
-
- if (isVisible || timeoutId !== null) {
- return;
- }
-
- timeoutId = setTimeoutFn(() => {
- timeoutId = null;
- isVisible = true;
- input.onVisibilityChange(true);
- }, input.delayMs);
- },
- dispose: () => {
- clearPendingShow();
- },
- };
-}
-
-export function useThreadJumpHintVisibility(): {
- showThreadJumpHints: boolean;
- updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
-} {
- const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
- const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
-
- React.useEffect(() => {
- const controller = createThreadJumpHintVisibilityController({
- delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
- onVisibilityChange: (visible) => {
- setShowThreadJumpHints(visible);
- },
- setTimeoutFn: window.setTimeout.bind(window),
- clearTimeoutFn: window.clearTimeout.bind(window),
- });
- controllerRef.current = controller;
-
- return () => {
- controller.dispose();
- controllerRef.current = null;
- };
- }, []);
-
- const updateThreadJumpHintsVisibility = (shouldShow: boolean) => {
- controllerRef.current?.sync(shouldShow);
- };
-
- return {
- showThreadJumpHints,
- updateThreadJumpHintsVisibility,
- };
+/**
+ * Thread jump hints appear once the jump modifier has been held for a moment,
+ * so a quick shortcut never flashes them, and hide as soon as it is released.
+ */
+export function useThreadJumpHintsVisible(shouldShow: boolean): boolean {
+ const [showAt, setShowAt] = React.useState<number | null>(null);
+ let nextShowAt = shouldShow ? showAt : null;
+ if (shouldShow && showAt === null) nextShowAt = deadlineAfter(THREAD_JUMP_HINT_SHOW_DELAY_MS);
+ if (nextShowAt !== showAt) setShowAt(nextShowAt);
+ return useDeadlinePassed(nextShowAt);
}
export function resolveThreadLastVisitedAt(
diff --git a/apps/web/src/components/Sidebar.pointer.ts b/apps/web/src/components/Sidebar.pointer.ts
index 282e8728a53..5a0ce373c07 100644
--- a/apps/web/src/components/Sidebar.pointer.ts
+++ b/apps/web/src/components/Sidebar.pointer.ts
@@ -1,13 +1,7 @@
-import { useLayoutEffect, type PointerEvent as ReactPointerEvent } from "react";
+import { type PointerEvent as ReactPointerEvent } from "react";
import { type SensorProps } from "@dnd-kit/core";
import { getOwnerDocument, getWindow } from "@dnd-kit/utilities";
-// Search unmounts the drag context while its owning Sidebar remains mounted.
-export function SidebarDragLifecycle({ onUnmount }: { onUnmount: () => void }) {
- useLayoutEffect(() => onUnmount, [onUnmount]);
- return null;
-}
-
type Options = {
distance: number;
onAttach: (sensor: SidebarPointerSensor) => void;
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 29ca99efee3..4a3d41bf556 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -71,7 +71,7 @@ import {
type MouseEvent as ReactMouseEvent,
type ReactNode,
} from "react";
-import { useRouter } from "@tanstack/react-router";
+import { type AnyRouter, useRouter } from "@tanstack/react-router";
import {
isAtomCommandInterrupted,
@@ -138,11 +138,15 @@ import { threadEnvironment } from "../state/threads";
import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../state/olderSettledShelf";
import { useThreadSearch } from "../state/queries";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
-import { readEnvironmentScope } from "../state/session";
+import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
import { openGuestShareDialog } from "./chat/guestShareDialogState";
-import { buildThreadRouteParams, resolveActiveThreadRouteRef } from "../threadRoutes";
+import {
+ buildThreadRouteParams,
+ resolveActiveThreadRouteRef,
+ resolveThreadRouteTarget,
+} from "../threadRoutes";
import type { SidebarThreadSummary } from "../types";
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
import { cn } from "~/lib/utils";
@@ -179,7 +183,8 @@ import {
sortPinnedThreadsForSidebar,
sortThreadsForSidebar,
sortWorkingThreadsBySend,
- useThreadJumpHintVisibility,
+ useSnoozeWakeClock,
+ useThreadJumpHintsVisible,
type SidebarListItem,
type SidebarSection,
resolveSidebarRowThreadId,
@@ -189,16 +194,16 @@ import {
createSidebarSortingStrategy,
restrictBelowSidebarLabel,
} from "./Sidebar.drag";
-import { SidebarDragLifecycle, SidebarPointerSensor } from "./Sidebar.pointer";
+import { SidebarPointerSensor } from "./Sidebar.pointer";
import { createSidebarListMotion } from "./Sidebar.motion";
import { resolveSnoozePresets, snoozeWakeLabel, type SnoozePreset } from "./Sidebar.snooze";
import { ProjectFavicon } from "./ProjectFavicon";
import { deriveProviderEntriesByEnvironment } from "../providerInstances";
import { useStableCallback } from "../hooks/useStableCallback";
import {
- completeSidebarRouteReveal,
- pendingSidebarRouteReveal,
+ resolveSidebarRouteReveal,
type SidebarRouteReveal,
+ useActiveRowReveal,
} from "./sidebar/routeReveal";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { Button } from "./ui/button";
@@ -365,24 +370,17 @@ function useSidebarThreads(input: {
readonly scopedProjectKeys: ReadonlySet<string> | null;
readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
readonly optimisticDrop: SidebarOptimisticDrop | null;
- readonly routeThreadRef: ScopedThreadRef | null;
+ readonly threads: readonly EnvironmentThreadShell[];
+ readonly routeRowThreadKey: string | null;
}) {
- const { projectScopeKey, scopedProjectKeys, serverConfigs, optimisticDrop, routeThreadRef } =
- input;
- const threads = useQuietThreadShells();
- const routeRowThreadKey =
- routeThreadRef === null
- ? null
- : scopedThreadKey(
- scopeThreadRef(
- routeThreadRef.environmentId,
- resolveSidebarRowThreadId(
- routeThreadRef.threadId,
- routeThreadRef.environmentId,
- threads,
- ),
- ),
- );
+ const {
+ projectScopeKey,
+ scopedProjectKeys,
+ serverConfigs,
+ optimisticDrop,
+ threads,
+ routeRowThreadKey,
+ } = input;
const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled);
const inboxReturnsVersion = useSyncExternalStore(
inboxReturns.subscribe,
@@ -390,12 +388,7 @@ function useSidebarThreads(input: {
);
const nowMinute = useNowMinute();
// Minute-quantized clocks would delay second-precise snooze wakes by up to a minute.
- const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
- const [nextSnoozeWakeAt, setNextSnoozeWakeAt] = useState<string | null>(null);
- useEffect(
- () => scheduleSnoozeWake(nextSnoozeWakeAt, () => bumpSnoozeWakeTick((tick) => tick + 1)),
- [nextSnoozeWakeAt],
- );
+ const snoozeWakeClock = useSnoozeWakeClock(threads);
const [settledShelfExpanded, setSettledShelfExpanded] = useLocalStorage(
SETTLED_SHELF_EXPANDED_KEY,
false,
@@ -427,10 +420,8 @@ function useSidebarThreads(input: {
serverConfigs,
optimisticDrop,
workingShelfEnabled,
- clockKey: `${nowMinute}:${snoozeWakeTick}:${inboxReturnsVersion}`,
+ clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`,
});
- const partitionNextWakeAt = partition.snoozedThreads[0]?.snoozedUntil ?? null;
- if (partitionNextWakeAt !== nextSnoozeWakeAt) setNextSnoozeWakeAt(partitionNextWakeAt);
const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } =
partition;
@@ -484,7 +475,6 @@ function useSidebarThreads(input: {
for (const thread of list) sectionByThreadKey.set(threadShellKey(thread), section);
}
return {
- routeRowThreadKey,
...partition,
threads,
workingShelfEnabled,
@@ -752,15 +742,6 @@ function useSidebarLookups() {
};
}
-function scheduleSnoozeWake(wakeAt: string | null, onWake: () => void): (() => void) | undefined {
- const wakeAtMs = wakeAt === null ? Number.NaN : Date.parse(wakeAt);
- if (Number.isNaN(wakeAtMs)) return undefined;
- // Delays beyond signed 32-bit range fire immediately and loop for far-future snoozes.
- const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
- const id = window.setTimeout(onWake, delayMs);
- return () => window.clearTimeout(id);
-}
-
function canOperateThreads(
threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,
): boolean {
@@ -785,6 +766,19 @@ const SIDEBAR_DRAG_DISTANCE = 6;
const SIDEBAR_DRAG_LABEL_HEIGHT = 24;
+const threadSearchResultId = (index: number) => `sidebar-thread-search-result-${index}`;
+
+// Continuations that outlive a render read the open thread from the router.
+function readRouteThreadKey(router: AnyRouter): string | null {
+ const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
+ const draft =
+ target?.kind === "draft"
+ ? useComposerDraftStore.getState().getDraftSession(target.draftId)
+ : null;
+ const ref = resolveActiveThreadRouteRef(target, draft);
+ return ref === null ? null : scopedThreadKey(ref);
+}
+
export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) {
const {
projects,
@@ -878,6 +872,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
},
});
const newThreadContext = useHandleNewThread();
+ // Row callbacks capture only the handler; the rest of the context changes with the route.
+ const { handleNewThread } = newThreadContext;
const primaryEnvironmentId = usePrimaryEnvironmentId();
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
@@ -909,10 +905,20 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
const [threadSearchQuery, setThreadSearchQuery] = useState("");
const [searchHighlightKey, setSearchHighlightKey] = useState<string | null>(null);
const searchEnvironmentIds = useConnectedEnvironmentIds();
- const handleNewThreadRef = useRef(newThreadContext.handleNewThread);
const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
- const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
+ const [renamingThreadRef, setRenamingThreadRef] = useState<ScopedThreadRef | null>(null);
+ const canOperateRenamingThread = useEnvironmentScope(
+ renamingThreadRef?.environmentId ?? null,
+ AuthOrchestrationOperateScope,
+ );
+ // Losing operate access cancels the rename without committing the title, so
+ // the editor does not return and take focus when access comes back.
+ if (renamingThreadRef !== null && !canOperateRenamingThread) setRenamingThreadRef(null);
+ const renamingThreadKey =
+ renamingThreadRef !== null && canOperateRenamingThread
+ ? scopedThreadKey(renamingThreadRef)
+ : null;
const [renamingTitle, setRenamingTitle] = useState("");
const settlingThreadKeysRef = useRef(new Set<string>());
const threadListRef = useRef<HTMLUListElement | null>(null);
@@ -939,18 +945,70 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
const openAddProjectCommandPalette = () => openCommandPalette({ open: "add-project" });
const routeThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
- const routeThreadKeyRef = useRef(routeThreadKey);
// A selection made under one scope can hold threads the next scope hides.
const setProjectScopeKey = (key: string | null) => {
clearSelection();
setPersistedProjectScopeKey(key);
};
- const projectScopeKey = resolveSidebarProjectScopeKey({
+ // A scope whose project is gone reads as all projects once every snapshot has
+ // loaded. The stored key is left alone, so the scope returns with its project.
+ const chosenProjectScopeKey = resolveSidebarProjectScopeKey({
groups: projectGroups,
key: persistedProjectScopeKey,
settings: projectGroupingSettings,
+ canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,
+ });
+ const chosenProjectGroup =
+ chosenProjectScopeKey === null
+ ? null
+ : (projectGroups.find((project) => project.projectKey === chosenProjectScopeKey) ?? null);
+ const chosenScopeProjectKeys =
+ chosenProjectGroup === null
+ ? null
+ : new Set(
+ chosenProjectGroup.memberProjectRefs.map(
+ (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
+ ),
+ );
+ const threads = useQuietThreadShells();
+ const routeRowThreadKey =
+ routeThreadRef === null
+ ? null
+ : scopedThreadKey(
+ scopeThreadRef(
+ routeThreadRef.environmentId,
+ resolveSidebarRowThreadId(
+ routeThreadRef.threadId,
+ routeThreadRef.environmentId,
+ threads,
+ ),
+ ),
+ );
+ const isSearchingThreads = threadSearchQuery.trim().length > 0;
+
+ // History, the palette and links can open a thread the scope hides or the list
+ // scrolled away; a remount starts at the top, so each mount scrolls to the open
+ // thread once. Render decides the widening, so the first frame of the new route
+ // already lists the row; the active row's ref callback scrolls to it.
+ const { widensScope: revealWidensScope } = resolveSidebarRouteReveal({
+ reveal: routeReveal,
+ routeKey: routeRowThreadKey,
+ isSearching: isSearchingThreads,
+ scopedProjectKeys: chosenScopeProjectKeys,
+ findThread: (key) => threads.find((candidate) => threadShellKey(candidate) === key),
});
+ const projectScopeKey = revealWidensScope ? null : chosenProjectScopeKey;
+ // The widened scope outlives the reveal, so it is written back to the persisted
+ // scope. Route changes arrive from history, links and the palette, and only this
+ // component holds the project groups that decide a widening, so no single
+ // navigation handler can make the write.
+ useEffect(() => {
+ if (!revealWidensScope) return;
+ clearSelection();
+ setPersistedProjectScopeKey(null);
+ }, [clearSelection, revealWidensScope, setPersistedProjectScopeKey]);
+ const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey);
const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups);
const scratchMachineLabelFor = (
thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">,
@@ -974,18 +1032,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
matches: (item, query) =>
projectScopeFilter.contains(item, query, (candidate) => candidate.label),
});
- const scopedProjectGroup =
- projectScopeKey === null
- ? null
- : (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null);
- const scopedProjectKeys =
- scopedProjectGroup === null
- ? null
- : new Set(
- scopedProjectGroup.memberProjectRefs.map(
- (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
- ),
- );
+ const scopedProjectGroup = revealWidensScope ? null : chosenProjectGroup;
+ const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys;
const threadSearch = useThreadSearch(
searchEnvironmentIds,
threadSearchQuery,
@@ -997,26 +1045,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
),
},
);
- useEffect(() => {
- const nextKey = resolveSidebarProjectScopeKey({
- groups: projectGroups,
- key: persistedProjectScopeKey,
- settings: projectGroupingSettings,
- canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,
- });
- if (nextKey !== persistedProjectScopeKey) {
- clearSelection();
- setPersistedProjectScopeKey(nextKey);
- }
- }, [
- allProjectConfigsReady,
- allProjectSnapshotsReady,
- clearSelection,
- persistedProjectScopeKey,
- projectGroups,
- projectGroupingSettings,
- setPersistedProjectScopeKey,
- ]);
const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
const visibleDraftSessionCount = useComposerDraftStore((store) => {
let count = 0;
@@ -1070,7 +1098,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
);
const {
- threads,
workingShelfEnabled,
pinnedThreads,
draggableThreadKeys,
@@ -1104,53 +1131,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
activeKeys,
pinnedKeysById,
activeKeysById,
- routeRowThreadKey,
} = useSidebarThreads({
projectScopeKey,
scopedProjectKeys,
serverConfigs,
optimisticDrop,
- routeThreadRef,
- });
-
- const isSearchingThreads = threadSearchQuery.trim().length > 0;
-
- // History, the command palette, and links can open a thread the project
- // scope hides or the list has scrolled away. A remount starts the list at
- // the top, so each mount also scrolls to the open thread once, without
- // widening the scope.
- const mountRevealOwed = useRef(true);
- const revealRouteRow = useStableCallback(() => {
- const pendingKey = pendingSidebarRouteReveal(routeReveal, routeRowThreadKey);
- // Search results replace the thread list; reveal once the list returns.
- if (isSearchingThreads) return;
- const revealKey = pendingKey ?? (mountRevealOwed.current ? routeRowThreadKey : null);
- if (revealKey === null) return;
- const thread = threads.find((candidate) => threadShellKey(candidate) === revealKey);
- if (thread === undefined) return;
- if (
- pendingKey !== null &&
- scopedProjectKeys !== null &&
- filterSidebarV2VisibleThreads([thread], scopedProjectKeys).length === 0 &&
- filterSidebarV2VisibleThreads([thread], null).length === 1
- ) {
- // The row renders under the widened scope; scroll on that pass.
- setProjectScopeKey(null);
- return;
- }
- const activeRow = document.querySelector('[data-sidebar="content"] [aria-current="page"]');
- if (!activeRow) return;
- completeSidebarRouteReveal(routeReveal);
- mountRevealOwed.current = false;
- activeRow.scrollIntoView({ block: "nearest" });
- });
- useEffect(revealRouteRow, [
- revealRouteRow,
- routeRowThreadKey,
threads,
- projectScopeKey,
- isSearchingThreads,
- ]);
+ routeRowThreadKey,
+ });
// Ranked across environments as the palette ranks them, so one
// environment's list does not sit above another's better matches; rows
@@ -1220,15 +1208,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
typeof index === "function" ? index(activeSearchResultIndex) : index
] ?? null,
);
- const activeSearchResultKey = isSearchingThreads
- ? (threadSearchResultKeys[activeSearchResultIndex] ?? null)
- : null;
- useEffect(() => {
- if (activeSearchResultKey === null) return;
- document
- .querySelector(`[data-search-result-key="${globalThis.CSS.escape(activeSearchResultKey)}"]`)
- ?.scrollIntoView({ block: "nearest" });
- }, [activeSearchResultKey]);
+ const moveSearchHighlight = (step: 1 | -1) => {
+ const count = threadSearchResults.length;
+ setActiveSearchResultIndex((activeSearchResultIndex + step + count) % count);
+ };
const orderedThreadKeysRef = useRef(orderedThreadKeys);
// Read changing maps/sets through refs so streamed events preserve row callbacks.
@@ -1246,8 +1229,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
}
return mapping;
})();
- const { showThreadJumpHints: showJumpHints, updateThreadJumpHintsVisibility } =
- useThreadJumpHintVisibility();
const navigateToThread = (threadRef: ScopedThreadRef) => {
if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
@@ -1319,14 +1300,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
if (threadSearchResults.length === 0) return;
if (event.key === "ArrowDown") {
event.preventDefault();
- setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length);
+ moveSearchHighlight(1);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
- setActiveSearchResultIndex(
- (index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length,
- );
+ moveSearchHighlight(-1);
return;
}
if (event.key === "Enter") {
@@ -1338,15 +1317,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
const startThreadRename = (threadRef: ScopedThreadRef, title: string) => {
if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
- setRenamingThreadKey(scopedThreadKey(threadRef));
+ setRenamingThreadRef(threadRef);
setRenamingTitle(title);
};
- const cancelThreadRename = () => setRenamingThreadKey(null);
+ const cancelThreadRename = () => setRenamingThreadRef(null);
const commitThreadRename = (threadRef: ScopedThreadRef, title: string, originalTitle: string) => {
void (async () => {
if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
const trimmed = title.trim();
- setRenamingThreadKey(null);
+ setRenamingThreadRef(null);
if (trimmed.length === 0) {
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
return;
@@ -1395,7 +1374,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
threadKey: string,
coParkingKeys?: ReadonlySet<string>,
): (() => void) | null => {
- if (routeThreadKeyRef.current !== threadKey) return null;
+ if (readRouteThreadKey(router) !== threadKey) return null;
const shell = threadByKeyRef.current.get(threadKey);
const orderedKeys = orderedThreadKeysRef.current;
const settledKeys = settledThreadKeysRef.current;
@@ -1411,8 +1390,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
return nextThread
? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id))
: shell
- ? () =>
- void handleNewThreadRef.current(scopeProjectRef(shell.environmentId, shell.projectId))
+ ? () => void handleNewThread(scopeProjectRef(shell.environmentId, shell.projectId))
: () => void router.navigate({ to: "/" });
};
@@ -1443,7 +1421,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
if (
shouldNavigateAfterThreadPark({
threadKey,
- currentThreadKey: routeThreadKeyRef.current,
+ currentThreadKey: readRouteThreadKey(router),
action: "settle",
now: new Date().toISOString(),
thread: readThreadShell(threadRef),
@@ -1499,11 +1477,20 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
restrictBelowPins,
restrictToFirstScrollableAncestor,
];
- const attachListMotionRef = (node: HTMLUListElement | null) => {
+ const attachListMotionRef = (node: HTMLUListElement) => {
threadListRef.current = node;
- listMotionRef.current?.dispose();
- listMotionRef.current = node === null ? null : createSidebarListMotion(node);
- listMotionRef.current?.update(false);
+ const motion = createSidebarListMotion(node);
+ listMotionRef.current = motion;
+ motion.update(false);
+ return () => {
+ // Search replaces this list while the Sidebar stays mounted, and a drag
+ // whose rows are gone can never drop. The compiler memoizes this callback
+ // with no deps (it reads only refs), so the cleanup runs only on unmount.
+ dragSensorRef.current?.cancel();
+ motion.dispose();
+ if (listMotionRef.current === motion) listMotionRef.current = null;
+ if (threadListRef.current === node) threadListRef.current = null;
+ };
};
const isContextDrag = dragState?.contextDrag === true || dragState?.activeSection === "working";
@@ -1570,11 +1557,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
const dndSensors = useSensors(useSensor(SidebarPointerSensor, pointerSensorOptions));
const sectionByThreadKeyRef = useRef(sectionByThreadKey);
useLayoutEffect(() => {
- routeThreadKeyRef.current = routeThreadKey;
projectGroupsRef.current = projectGroups;
orderedThreadKeysRef.current = orderedThreadKeys;
threadByKeyRef.current = threadByKey;
- handleNewThreadRef.current = newThreadContext.handleNewThread;
settledThreadKeysRef.current = settledThreadKeys;
snoozedThreadKeysRef.current = snoozedThreadKeys;
sectionByThreadKeyRef.current = sectionByThreadKey;
@@ -1943,7 +1928,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
settled &&
shouldNavigateAfterThreadPark({
threadKey: activeKey,
- currentThreadKey: routeThreadKeyRef.current,
+ currentThreadKey: readRouteThreadKey(router),
action: "settle",
now: new Date().toISOString(),
thread: readThreadShell(threadRef),
@@ -2014,7 +1999,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
if (
shouldNavigateAfterThreadPark({
threadKey,
- currentThreadKey: routeThreadKeyRef.current,
+ currentThreadKey: readRouteThreadKey(router),
action: "snooze",
now: new Date().toISOString(),
thread: readThreadShell(threadRef),
@@ -2454,7 +2439,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
return;
case "new-thread-on-branch": {
const result = await settlePromise(() =>
- handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId), {
+ handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
branch: thread.branch,
worktreePath: thread.worktreePath,
envMode: thread.worktreePath ? "worktree" : "local",
@@ -2685,9 +2670,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
},
},
);
- useEffect(() => {
- updateThreadJumpHintsVisibility(shouldShowJumpHintsNow);
- }, [shouldShowJumpHintsNow, updateThreadJumpHintsVisibility]);
+ const showJumpHints = useThreadJumpHintsVisible(shouldShowJumpHintsNow);
const handleNewThreadClick = (event?: ReactMouseEvent) => {
if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) {
@@ -2696,7 +2679,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
activeDraftThread: newThreadContext.activeDraftThread,
activeThread: newThreadContext.activeThread ?? undefined,
defaultProjectRef: newThreadContext.defaultProjectRef,
- handleNewThread: newThreadContext.handleNewThread,
+ handleNewThread,
});
return;
}
@@ -2906,7 +2889,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
}
isHighlighted={activeSearchResultIndex === index}
isRouteActive={routeRowThreadKey === threadKey}
- resultId={`sidebar-thread-search-result-${index}`}
+ resultId={threadSearchResultId(index)}
searchMatch={
threadSearchMatchByKey.get(
threadSearchMatchKey({
@@ -2950,7 +2933,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
onDragOver={handleThreadDragOver}
onDragEnd={handleThreadDragEnd}
>
- <SidebarDragLifecycle onUnmount={cancelThreadDrag} />
<SortableContext items={sortableIds} strategy={sidebarSortingStrategy}>
<ul
ref={attachListMotionRef}
@@ -3026,6 +3008,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
}
wokeAt={threadWokeAt(thread, { now: snoozeNow })}
isActive={routeRowThreadKey === threadKey}
+ revealRef={
+ routeRowThreadKey === threadKey ? revealActiveRow : undefined
+ }
isRouteThread={routeThreadKey === threadKey}
openPullRequestsInRightPanel={routeThreadRef !== null}
jumpLabel={
diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx
index 7e631a9acaa..8837d47ae0e 100644
--- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx
+++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx
@@ -3,6 +3,7 @@ import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators";
import { discardComposerDraft } from "../../lib/discardComposerDraft";
import { requestCustomSnooze } from "../CustomSnoozeDialog";
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
+import { useDeadlinePassed } from "~/hooks/useDeadline";
import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
@@ -49,7 +50,6 @@ import {
} from "lucide-react";
import {
memo,
- useEffect,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
@@ -84,6 +84,7 @@ import {
resolveWorkingStartedAt,
useRetainedValue,
useSidebarRowSubscriptionLease,
+ setFileDragActive,
} from "../Sidebar.logic";
import { resolveLocalCheckoutBranchMismatch } from "../BranchToolbar.logic";
import {
@@ -524,6 +525,8 @@ type SidebarThreadRowProps = {
snoozeWakeLabelText: string | null;
wokeAt: string | null;
isActive: boolean;
+ // Set on the active row only; scrolls it into view when a reveal is owed.
+ revealRef?: ((row: HTMLElement, threadKey: string) => void) | undefined;
// Unlike isActive, never true for the ancestor standing in for an open
// subagent: drafts and PR clicks care about which composer is on screen.
isRouteThread: boolean;
@@ -560,6 +563,47 @@ type SidebarThreadRowProps = {
onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined;
};
+// Mounted only while renaming, so each rename starts uncommitted.
+function ThreadRenameInput(props: {
+ title: string;
+ onTitleChange: (title: string) => void;
+ onCommit: () => void;
+ onCancel: () => void;
+}) {
+ // Enter and Escape blur the input as it unmounts; that blur must not commit again.
+ const settledRef = useRef(false);
+ const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
+ event.stopPropagation();
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
+ if (event.key === "Enter") {
+ event.preventDefault();
+ settledRef.current = true;
+ props.onCommit();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ settledRef.current = true;
+ props.onCancel();
+ }
+ };
+ return (
+ <input
+ autoFocus
+ value={props.title}
+ dir="auto"
+ aria-label="Thread title"
+ onChange={(event) => props.onTitleChange(event.target.value)}
+ onFocus={(event) => event.currentTarget.select()}
+ onKeyDown={handleKeyDown}
+ onBlur={() => {
+ if (!settledRef.current) props.onCommit();
+ }}
+ onClick={(event) => event.stopPropagation()}
+ onDoubleClick={(event) => event.stopPropagation()}
+ 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"
+ />
+ );
+}
+
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
isRenaming,
@@ -587,10 +631,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const threadKey = scopedThreadKey(threadRef);
const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
- useEffect(() => {
- if (!canOperateThread && isRenaming) onCancelRename();
- }, [canOperateThread, isRenaming, onCancelRename]);
- const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(props.isActive);
+ const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease(props.isActive);
+ const { revealRef } = props;
+ const rowRef = (row: HTMLElement | null) => {
+ if (row !== null) revealRef?.(row, threadKey);
+ return leaseRowRef(row);
+ };
const isRegeneratingTitle = thread.titleRegeneration != null;
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
@@ -786,41 +832,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
const [isFileDragOver, setIsFileDragOver] = useState(false);
const fileDropHandlers = onFileDropThreads
? makeWorkspaceFileDropHandlers({
- setDragActive: setIsFileDragOver,
+ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active),
addFiles: (files) => {
onFileDropThreads(threadRef, files);
},
addFolders: () => {},
})
: null;
- useEffect(() => {
- if (!isFileDragOver) return;
- const clearFileDrag = () => setIsFileDragOver(false);
- window.addEventListener("dragend", clearFileDrag);
- return () => window.removeEventListener("dragend", clearFileDrag);
- }, [isFileDragOver]);
- const renameCommittedRef = useRef(false);
- useEffect(() => {
- if (isRenaming) renameCommittedRef.current = false;
- }, [isRenaming]);
- const handleRenameKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
- event.stopPropagation();
- if (event.nativeEvent.isComposing || event.keyCode === 229) return;
- if (event.key === "Enter") {
- event.preventDefault();
- renameCommittedRef.current = true;
- onCommitRename(threadRef, renamingTitle, thread.title);
- } else if (event.key === "Escape") {
- event.preventDefault();
- renameCommittedRef.current = true;
- onCancelRename();
- }
- };
- const handleRenameBlur = () => {
- if (!renameCommittedRef.current) {
- onCommitRename(threadRef, renamingTitle, thread.title);
- }
- };
const handleSettleClick = (event: ReactMouseEvent) => {
event.preventDefault();
event.stopPropagation();
@@ -865,18 +883,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
const snoozeGateExpiryMs = hasQueuedTurnStart(thread, { now: snoozeGateNow })
? Date.parse(thread.latestUserMessageAt ?? "") + QUEUED_TURN_START_GRACE_MS
: Number.NaN;
- useEffect(() => {
- // A gate still closed past its expiry is held by runtime status, not time,
- // so no clock tick can open it.
- if (!Number.isFinite(snoozeGateExpiryMs) || snoozeGateExpiryMs <= Date.parse(snoozeGateNow)) {
- return;
- }
- const id = window.setTimeout(
- () => setSnoozeGateClock({ thread, now: new Date().toISOString() }),
- Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647),
- );
- return () => window.clearTimeout(id);
- }, [snoozeGateExpiryMs, snoozeGateNow, thread]);
+ // A gate still closed past its expiry is held by runtime status, not time,
+ // so no clock tick can open it.
+ const snoozeGateOpensAt =
+ Number.isFinite(snoozeGateExpiryMs) && snoozeGateExpiryMs > Date.parse(snoozeGateNow)
+ ? snoozeGateExpiryMs + 50
+ : null;
+ const snoozeGateOpened = useDeadlinePassed(snoozeGateOpensAt);
+ if (snoozeGateOpened && snoozeGateOpensAt !== null) {
+ setSnoozeGateClock({ thread, now: new Date(snoozeGateOpensAt).toISOString() });
+ }
const showSnoozeButton =
canOperateThread && props.snoozeSupported && canSnooze(thread, { now: snoozeGateNow });
// 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
isActive: props.isActive,
});
- const title =
- isRenaming && canOperateThread ? (
- <input
- autoFocus
- value={renamingTitle}
- dir="auto"
- aria-label="Thread title"
- onChange={(event) => onRenameTitleChange(event.target.value)}
- onFocus={(event) => event.currentTarget.select()}
- onKeyDown={handleRenameKeyDown}
- onBlur={handleRenameBlur}
- onClick={(event) => event.stopPropagation()}
- onDoubleClick={(event) => event.stopPropagation()}
- 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"
- />
- ) : (
- <span
- aria-hidden
- className={cn(
- "min-w-0 flex-1 text-start text-sm transition-opacity motion-reduce:transition-none",
- shouldRecede ? "font-normal" : "font-medium",
- variant === "card"
- ? cn(
- "truncate",
- shouldRecede
- ? "text-secondary-label redesign:text-foreground/75 redesign:group-hover/sidebar-row:text-foreground redesign:group-focus-visible/sidebar-row:text-foreground"
- : isUnread || isWoke || status === "input" || status === "request"
- ? "text-foreground"
- : status === "failed"
- ? "text-foreground/95"
- : "text-foreground/90 redesign:text-foreground",
- )
- : cn(
- "truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",
- shouldRecede
- ? "text-secondary-label/70 redesign:text-secondary-label"
- : props.isActive || isWoke || status === "input" || status === "request"
- ? "text-foreground"
- : isUnread
- ? "text-muted-foreground"
- : "text-secondary-label/70",
- ),
- isRegeneratingTitle && "opacity-55",
- )}
- dir={textDirection(thread.title)}
- >
- {thread.title}
- </span>
- );
+ const title = isRenaming ? (
+ <ThreadRenameInput
+ title={renamingTitle}
+ onTitleChange={onRenameTitleChange}
+ onCommit={() => onCommitRename(threadRef, renamingTitle, thread.title)}
+ onCancel={onCancelRename}
+ />
+ ) : (
+ <span
+ aria-hidden
+ className={cn(
+ "min-w-0 flex-1 text-start text-sm transition-opacity motion-reduce:transition-none",
+ shouldRecede ? "font-normal" : "font-medium",
+ variant === "card"
+ ? cn(
+ "truncate",
+ shouldRecede
+ ? "text-secondary-label redesign:text-foreground/75 redesign:group-hover/sidebar-row:text-foreground redesign:group-focus-visible/sidebar-row:text-foreground"
+ : isUnread || isWoke || status === "input" || status === "request"
+ ? "text-foreground"
+ : status === "failed"
+ ? "text-foreground/95"
+ : "text-foreground/90 redesign:text-foreground",
+ )
+ : cn(
+ "truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",
+ shouldRecede
+ ? "text-secondary-label/70 redesign:text-secondary-label"
+ : props.isActive || isWoke || status === "input" || status === "request"
+ ? "text-foreground"
+ : isUnread
+ ? "text-muted-foreground"
+ : "text-secondary-label/70",
+ ),
+ isRegeneratingTitle && "opacity-55",
+ )}
+ dir={textDirection(thread.title)}
+ >
+ {thread.title}
+ </span>
+ );
const accessibleTitle = isRenaming ? null : <span className="sr-only">{thread.title}</span>;
const prBadgeShape = supportsMultiplePullRequests
@@ -1540,6 +1548,13 @@ function latestRunDiff(
return null;
}
+// Attached only to the highlighted result, so React calls it each time the
+// highlight lands on a different row: a new query, late rows replacing the first
+// result, or arrow keys moving past the scrolled edge.
+const scrollHighlightedResultIntoView = (node: HTMLLIElement | null) => {
+ node?.scrollIntoView({ block: "nearest" });
+};
+
export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
isSettled: boolean;
thread: SidebarThreadSummary;
@@ -1609,27 +1624,25 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props
const [isFileDragOver, setIsFileDragOver] = useState(false);
const onFileDropThreads = props.onFileDropThreads;
const fileDropHandlers = makeWorkspaceFileDropHandlers({
- setDragActive: setIsFileDragOver,
+ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active),
addFiles: (files) => {
onFileDropThreads(threadRef, files);
},
addFolders: () => {},
});
- useEffect(() => {
- if (!isFileDragOver) return;
- const clearFileDrag = () => setIsFileDragOver(false);
- window.addEventListener("dragend", clearFileDrag);
- return () => window.removeEventListener("dragend", clearFileDrag);
- }, [isFileDragOver]);
return (
- <li role="presentation" className="list-none" {...fileDropHandlers}>
+ <li
+ ref={props.isHighlighted ? scrollHighlightedResultIntoView : undefined}
+ role="presentation"
+ className="list-none"
+ {...fileDropHandlers}
+ >
<Tooltip>
<TooltipTrigger
render={
<button
ref={rowRef}
id={props.resultId}
- data-search-result-key={scopedThreadKey(threadRef)}
type="button"
role="option"
tabIndex={-1}
diff --git a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.browser.test.tsx b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.browser.test.tsx
deleted file mode 100644
index 049ef07ad80..00000000000
--- a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.browser.test.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it, vi } from "vite-plus/test";
-
-import { act, fakeTimers, render } from "../../../test/render";
-import { useThreadUndoNotice } from "../../hooks/showThreadUndoNotice";
-import { SidebarThreadUndoNotice } from "./SidebarThreadUndoNotice";
-
-const spoken = () =>
- [...document.querySelectorAll('body > [aria-live="polite"]')]
- .map((region) => region.textContent)
- .join("");
-
-describe("SidebarThreadUndoNotice", () => {
- it("speaks the notice, and drops it when the notice clears before it is spoken", async () => {
- using _notice = { [Symbol.dispose]: () => useThreadUndoNotice.setState({ notice: null }) };
- await using _screen = await render(<SidebarThreadUndoNotice />);
- using _timers = fakeTimers();
- const showSettled = () =>
- act(async () =>
- useThreadUndoNotice.setState({
- notice: { action: "Settled", count: 1, undo: async () => {} },
- }),
- );
-
- await showSettled();
- await act(async () => vi.advanceTimersByTime(300));
- expect(spoken()).toMatch(/^Settled 1 thread, /);
-
- await act(async () => useThreadUndoNotice.setState({ notice: null }));
- for (const region of document.querySelectorAll('body > [aria-live="polite"]')) {
- region.textContent = "";
- }
- await showSettled();
- await act(async () => useThreadUndoNotice.setState({ notice: null }));
- await act(async () => vi.advanceTimersByTime(300));
- expect(spoken()).toBe("");
- });
-});
diff --git a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx
index 71818e154a1..7cfa4bdb703 100644
--- a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx
+++ b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx
@@ -1,9 +1,11 @@
import { useAtomValue } from "@effect/atom-react";
-import { useEffect } from "react";
-import { undoLatestThreadAction, useThreadUndoNotice } from "../../hooks/showThreadUndoNotice";
-import { shortcutLabelForCommand } from "../../keybindings";
-import { announce, cancelAnnouncement } from "../../lib/announce";
+import {
+ threadUndoLabel,
+ threadUndoNoticeSummary,
+ undoLatestThreadAction,
+ useThreadUndoNotice,
+} from "../../hooks/showThreadUndoNotice";
import { primaryServerKeybindingsAtom } from "../../state/server";
import { Alert, AlertDescription } from "../ui/alert";
import { InlineButton } from "../ui/button";
@@ -12,25 +14,13 @@ export function SidebarThreadUndoNotice() {
const notice = useThreadUndoNotice((state) => state.notice);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
- const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
- const undoLabel = shortcut ? `${shortcut} to undo` : "Undo";
- const summary = notice
- ? `${notice.action} ${notice.count} ${notice.action === "Discarded" ? "draft" : "thread"}${notice.count === 1 ? "" : "s"}`
- : null;
-
- // A live region that mounts already filled is skipped by screen readers, and settling
- // usually moves focus to the next thread at the same moment.
- useEffect(() => {
- if (summary) announce(`${summary}, ${undoLabel}`, "thread-undo-notice");
- else cancelAnnouncement("thread-undo-notice");
- }, [summary, undoLabel]);
-
- if (!summary) return null;
+ if (!notice) return null;
return (
<Alert role="group" variant="sidebar">
<AlertDescription>
- {summary}, <InlineButton onClick={undoLatestThreadAction}>{undoLabel}</InlineButton>
+ {threadUndoNoticeSummary(notice)},{" "}
+ <InlineButton onClick={undoLatestThreadAction}>{threadUndoLabel(keybindings)}</InlineButton>
</AlertDescription>
</Alert>
);
diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx
new file mode 100644
index 00000000000..edbe293b979
--- /dev/null
+++ b/apps/web/src/components/sidebar/SidebarUpdatePill.browser.test.tsx
@@ -0,0 +1,96 @@
+import type { DesktopUpdateState } from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+import { userEvent } from "vite-plus/test/browser";
+
+import { act, render } from "../../../test/render";
+import { SidebarUpdatePill } from "./SidebarUpdatePill";
+
+const mocks = vi.hoisted(() => {
+ const listeners = new Set<() => void>();
+ return {
+ update: null as DesktopUpdateState | null,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ notify: () => {
+ for (const listener of listeners) listener();
+ },
+ };
+});
+vi.mock("../../state/desktopUpdate", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../state/desktopUpdate")>()),
+ useDesktopUpdateState: (await import("react")).useSyncExternalStore.bind(
+ null,
+ mocks.subscribe,
+ () => mocks.update,
+ ),
+}));
+// The pill only renders in the desktop app.
+vi.mock("../../env", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../env")>()),
+ isElectron: true,
+}));
+vi.mock("./useUpdateEverything", () => ({
+ useUpdateEverything: () => ({ hasUpdates: false, summary: "", lines: [], restarts: [] }),
+}));
+
+function nightlyUpdate(releaseNotes: DesktopUpdateState["releaseNotes"]): DesktopUpdateState {
+ return {
+ enabled: true,
+ status: "available",
+ channel: "nightly",
+ currentVersion: "0.0.50-nightly.1",
+ hostArch: "arm64",
+ appArch: "arm64",
+ runningUnderArm64Translation: false,
+ availableVersion: "0.0.50-nightly.2",
+ downloadedVersion: null,
+ releaseNotes,
+ omittedReleaseCount: 0,
+ downloadPercent: null,
+ checkedAt: null,
+ message: null,
+ errorContext: null,
+ canRetry: false,
+ };
+}
+
+const RELEASE_NOTES: DesktopUpdateState["releaseNotes"] = [
+ { version: "0.0.50-nightly.2", items: ["Faster sidebar."], totalItems: 1 },
+];
+
+function setup(update: DesktopUpdateState | null) {
+ mocks.update = update;
+}
+
+function publish(update: DesktopUpdateState | null) {
+ return act(() => {
+ mocks.update = update;
+ mocks.notify();
+ });
+}
+
+const releaseNotes = () => document.querySelector('[aria-label="Nightly update release notes"]');
+
+describe("SidebarUpdatePill release notes", () => {
+ it("closes when the release notes stop applying", async () => {
+ setup(nightlyUpdate(RELEASE_NOTES));
+ await using _screen = await render(<SidebarUpdatePill />);
+ await userEvent.tab();
+ await vi.waitFor(() => expect(releaseNotes()).not.toBeNull());
+
+ await publish(nightlyUpdate([]));
+ await vi.waitFor(() => expect(releaseNotes()).toBeNull());
+ });
+
+ it("opens when release notes arrive while the trigger has keyboard focus", async () => {
+ setup(nightlyUpdate([]));
+ await using _screen = await render(<SidebarUpdatePill />);
+ await userEvent.tab();
+ expect(releaseNotes()).toBeNull();
+
+ await publish(nightlyUpdate(RELEASE_NOTES));
+ await vi.waitFor(() => expect(releaseNotes()).not.toBeNull());
+ });
+});
diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
index 68b95370842..89c992f8cc9 100644
--- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
@@ -1,6 +1,6 @@
import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
import { TriangleAlertIcon } from "lucide-react";
-import { type ComponentProps, useEffect, useId, useRef, useState } from "react";
+import { type ComponentProps, useId, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { isElectron } from "../../env";
@@ -259,17 +259,15 @@ function SidebarUpdateControl() {
const showReleaseNotesPopover =
!isRunningEverything && shouldUseSidebarUpdateReleaseNotesPopover(showUpdateDetails, state);
- useEffect(() => {
- if (!showReleaseNotesPopover) {
- releaseNotesPopoverHandle.close();
- return;
- }
-
- const trigger = document.getElementById(releaseNotesTriggerId);
- if (trigger?.matches(":focus-visible")) {
- releaseNotesPopoverHandle.open(releaseNotesTriggerId);
- }
- }, [releaseNotesPopoverHandle, releaseNotesTriggerId, showReleaseNotesPopover]);
+ const [releaseNotesOpen, setReleaseNotesOpen] = useState(false);
+ const [releaseNotesTriggerFocusVisible, setReleaseNotesTriggerFocusVisible] = useState(false);
+ // Release notes close when they stop applying, and open when they start
+ // applying while the trigger already holds keyboard focus.
+ const [releaseNotesShownBefore, setReleaseNotesShownBefore] = useState(showReleaseNotesPopover);
+ if (releaseNotesShownBefore !== showReleaseNotesPopover) {
+ setReleaseNotesShownBefore(showReleaseNotesPopover);
+ setReleaseNotesOpen(showReleaseNotesPopover && releaseNotesTriggerFocusVisible);
+ }
const handleAction = async () => {
const bridge = window.desktopBridge;
@@ -463,9 +461,12 @@ function SidebarUpdateControl() {
onClick={handleAction}
onBlur={() => {
suppressReleaseNotesFocusOpen.current = false;
+ setReleaseNotesTriggerFocusVisible(false);
}}
onFocus={(event) => {
- if (!showReleaseNotesPopover || !event.currentTarget.matches(":focus-visible")) return;
+ const focusVisible = event.currentTarget.matches(":focus-visible");
+ setReleaseNotesTriggerFocusVisible(focusVisible);
+ if (!showReleaseNotesPopover || !focusVisible) return;
if (suppressReleaseNotesFocusOpen.current) {
suppressReleaseNotesFocusOpen.current = false;
return;
@@ -489,12 +490,15 @@ function SidebarUpdateControl() {
<SidebarMenuItem className="ml-auto shrink-0">
<Popover
handle={releaseNotesPopoverHandle}
+ open={releaseNotesOpen && showReleaseNotesPopover}
+ triggerId={releaseNotesTriggerId}
onOpenChange={(open, details) => {
if (open && !showReleaseNotesPopover) {
details.cancel();
return;
}
handleSidebarUpdateReleaseNotesPopoverOpenChange(open, details);
+ if (!details.isCanceled) setReleaseNotesOpen(open);
}}
>
<Tooltip disabled={showReleaseNotesPopover}>
diff --git a/apps/web/src/components/sidebar/routeReveal.browser.test.tsx b/apps/web/src/components/sidebar/routeReveal.browser.test.tsx
new file mode 100644
index 00000000000..f15a2a1ebca
--- /dev/null
+++ b/apps/web/src/components/sidebar/routeReveal.browser.test.tsx
@@ -0,0 +1,107 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { render } from "../../../test/render";
+import { type SidebarRouteReveal, useActiveRowReveal } from "./routeReveal";
+
+const ROW_HEIGHT_PX = 24;
+
+function RevealList(props: {
+ readonly reveal: SidebarRouteReveal;
+ readonly rowKeys: ReadonlyArray<string>;
+ readonly activeKey: string | null;
+}) {
+ const revealActiveRow = useActiveRowReveal(props.reveal, props.activeKey);
+ return (
+ <ul aria-label="Threads" style={{ height: ROW_HEIGHT_PX * 4, overflowY: "auto", margin: 0 }}>
+ {props.rowKeys.map((key) => (
+ <li
+ key={key}
+ ref={key === props.activeKey ? (row) => revealActiveRow(row, key) : undefined}
+ style={{ height: ROW_HEIGHT_PX }}
+ >
+ {key}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+const rowKeys = (count: number) => Array.from({ length: count }, (_, index) => `thread-${index}`);
+const newReveal = (): SidebarRouteReveal => ({ observedKey: null, pendingKey: null });
+
+describe("useActiveRowReveal", () => {
+ it("scrolls an off-screen row into view when the route opens its thread", async () => {
+ const reveal = newReveal();
+ const keys = rowKeys(50);
+ await using screen = await render(
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-0" />,
+ // No router: the route arrives as the activeKey prop.
+ { router: false },
+ );
+ const target = screen.getByText("thread-40", { exact: true });
+ await expect.element(target).not.toBeInViewport();
+
+ await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />);
+
+ await expect.element(target).toBeInViewport();
+ });
+
+ it("reveals the active row when it mounts after the shells arrive", async () => {
+ const reveal = newReveal();
+ // The route already names the thread, but its environment's shells have not
+ // listed it yet.
+ await using screen = await render(
+ <RevealList reveal={reveal} rowKeys={rowKeys(5)} activeKey="thread-40" />,
+ // No router: the route arrives as the activeKey prop.
+ { router: false },
+ );
+ await expect.element(screen.getByText("thread-4", { exact: true })).toBeInTheDocument();
+
+ await screen.rerender(
+ <RevealList reveal={reveal} rowKeys={rowKeys(50)} activeKey="thread-40" />,
+ );
+
+ await expect.element(screen.getByText("thread-40", { exact: true })).toBeInViewport();
+ });
+
+ it("reveals a thread reopened after a thread whose row never mounted", async () => {
+ const reveal = newReveal();
+ const keys = rowKeys(50);
+ await using screen = await render(
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />,
+ // No router: the route arrives as the activeKey prop.
+ { router: false },
+ );
+ const target = screen.getByText("thread-40", { exact: true });
+ await expect.element(target).toBeInViewport();
+ screen.getByRole("list", { name: "Threads" }).element().scrollTop = 0;
+ await expect.element(target).not.toBeInViewport();
+
+ // The route moves to a thread the list does not hold yet, then back.
+ await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-99" />);
+ await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />);
+
+ await expect.element(target).toBeInViewport();
+ });
+
+ it("reveals the open thread again when the sidebar remounts on the same route", async () => {
+ const reveal = newReveal();
+ const keys = rowKeys(50);
+ {
+ await using screen = await render(
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />,
+ // No router: the route arrives as the activeKey prop.
+ { router: false },
+ );
+ await expect.element(screen.getByText("thread-40", { exact: true })).toBeInViewport();
+ }
+
+ // A remount starts the list at the top; the record outlives it with no reveal pending.
+ await using screen = await render(
+ <RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />,
+ // No router: the route arrives as the activeKey prop.
+ { router: false },
+ );
+ await expect.element(screen.getByText("thread-40", { exact: true })).toBeInViewport();
+ });
+});
diff --git a/apps/web/src/components/sidebar/routeReveal.ts b/apps/web/src/components/sidebar/routeReveal.ts
index 599b53308ce..de2a64ca858 100644
--- a/apps/web/src/components/sidebar/routeReveal.ts
+++ b/apps/web/src/components/sidebar/routeReveal.ts
@@ -1,3 +1,7 @@
+import { useRef } from "react";
+
+import { filterSidebarV2VisibleThreads } from "../Sidebar.logic";
+
// AppSidebarLayout owns this so drawer and Settings remounts preserve the chosen project scope.
// Only route changes may widen that scope; scroll position is lost on remount.
// Leaving Settings commits the router's location before its matches, briefly hiding thread params.
@@ -22,3 +26,42 @@ export function pendingSidebarRouteReveal(
export function completeSidebarRouteReveal(reveal: SidebarRouteReveal): void {
reveal.pendingKey = null;
}
+
+// Each route change and each mount scroll to the open thread once. Render records
+// the route, so a thread left before its row mounted still counts as a change.
+// The row can mount after the route, once its shells arrive, so its ref scrolls.
+export function useActiveRowReveal(reveal: SidebarRouteReveal, routeKey: string | null) {
+ const mountRevealOwed = useRef(true);
+ pendingSidebarRouteReveal(reveal, routeKey);
+ return (row: HTMLElement | null, rowKey: string) => {
+ if (row === null) return;
+ if (reveal.pendingKey !== rowKey && !mountRevealOwed.current) return;
+ completeSidebarRouteReveal(reveal);
+ mountRevealOwed.current = false;
+ row.scrollIntoView({ block: "nearest" });
+ };
+}
+
+type RevealableThread = Parameters<typeof filterSidebarV2VisibleThreads>[0][number];
+
+// Render records the route before deciding, so the first render of a new route
+// already widens the scope. Only a route reveal widens: the once-per-mount
+// scroll never changes a scope the user chose.
+export function resolveSidebarRouteReveal<T extends RevealableThread>(input: {
+ readonly reveal: SidebarRouteReveal;
+ readonly routeKey: string | null;
+ readonly isSearching: boolean;
+ readonly scopedProjectKeys: ReadonlySet<string> | null;
+ readonly findThread: (key: string) => T | undefined;
+}): { readonly pendingKey: string | null; readonly widensScope: boolean } {
+ const { reveal, routeKey, isSearching, scopedProjectKeys, findThread } = input;
+ const pendingKey = pendingSidebarRouteReveal(reveal, routeKey);
+ // Search results replace the thread list; the reveal waits for it to return.
+ const thread = pendingKey === null || isSearching ? undefined : findThread(pendingKey);
+ const widensScope =
+ thread !== undefined &&
+ scopedProjectKeys !== null &&
+ filterSidebarV2VisibleThreads([thread], scopedProjectKeys).length === 0 &&
+ filterSidebarV2VisibleThreads([thread], null).length === 1;
+ return { pendingKey, widensScope };
+}
diff --git a/apps/web/src/hooks/showThreadUndoNotice.test.ts b/apps/web/src/hooks/showThreadUndoNotice.test.ts
index 568e4cc70ae..edc09db724d 100644
--- a/apps/web/src/hooks/showThreadUndoNotice.test.ts
+++ b/apps/web/src/hooks/showThreadUndoNotice.test.ts
@@ -2,6 +2,7 @@ import { AsyncResult } from "effect/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { toastManager } from "../components/ui/toast";
+import { announce, cancelAnnouncement } from "../lib/announce";
import {
releaseThreadUndoShortcut,
showThreadUndoNotice,
@@ -10,6 +11,8 @@ import {
} from "./showThreadUndoNotice";
import * as ThreadUndo from "./threadUndo";
+vi.mock("../lib/announce", () => ({ announce: vi.fn(), cancelAnnouncement: vi.fn() }));
+
beforeEach(() => vi.useFakeTimers());
afterEach(() => {
vi.runAllTimers();
@@ -65,4 +68,24 @@ describe("thread undo notice", () => {
vi.advanceTimersByTime(5_000);
expect(threadUndoClaimsShortcut()).toBe(false);
});
+
+ it("announces each new summary once, and cancels it when the notice clears", async () => {
+ const { options } = setup();
+ vi.mocked(announce).mockClear();
+ vi.mocked(cancelAnnouncement).mockClear();
+ showThreadUndoNotice(options);
+ expect(announce).toHaveBeenCalledExactlyOnceWith(
+ expect.stringMatching(/^Unpinned 1 thread, /),
+ "thread-undo-notice",
+ );
+ ThreadUndo.invalidate("pin", "env/other");
+ expect(announce).toHaveBeenCalledOnce();
+ showThreadUndoNotice({ ...options, claim: ThreadUndo.begin("pin", "env/second") });
+ expect(announce).toHaveBeenLastCalledWith(
+ expect.stringMatching(/^Unpinned 2 threads, /),
+ "thread-undo-notice",
+ );
+ await notice().undo();
+ expect(cancelAnnouncement).toHaveBeenCalledWith("thread-undo-notice");
+ });
});
diff --git a/apps/web/src/hooks/showThreadUndoNotice.ts b/apps/web/src/hooks/showThreadUndoNotice.ts
index c6be67384e8..10bca7cdc3c 100644
--- a/apps/web/src/hooks/showThreadUndoNotice.ts
+++ b/apps/web/src/hooks/showThreadUndoNotice.ts
@@ -6,6 +6,10 @@ import {
import { create } from "zustand";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
+import { shortcutLabelForCommand } from "../keybindings";
+import { announce, cancelAnnouncement } from "../lib/announce";
+import { appAtomRegistry } from "../rpc/atomRegistry";
+import { primaryServerKeybindingsAtom } from "../state/server";
import * as ThreadUndo from "./threadUndo";
type UndoOptions = {
@@ -24,6 +28,34 @@ type UndoNotice = {
export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null }));
+export function threadUndoNoticeSummary(notice: Pick<UndoNotice, "action" | "count">): string {
+ const noun = notice.action === "Discarded" ? "draft" : "thread";
+ return `${notice.action} ${notice.count} ${noun}${notice.count === 1 ? "" : "s"}`;
+}
+
+export function threadUndoLabel(keybindings: Parameters<typeof shortcutLabelForCommand>[0]) {
+ const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
+ return shortcut ? `${shortcut} to undo` : "Undo";
+}
+
+let announcedSummary: string | null = null;
+
+// A live region that mounts already filled is skipped by screen readers, and settling
+// usually moves focus to the next thread at the same moment, so the notice is announced
+// separately from the alert that shows it.
+function setNotice(notice: UndoNotice | null) {
+ useThreadUndoNotice.setState({ notice });
+ const summary = notice ? threadUndoNoticeSummary(notice) : null;
+ if (summary === announcedSummary) return;
+ announcedSummary = summary;
+ if (summary) {
+ const label = threadUndoLabel(appAtomRegistry.get(primaryServerKeybindingsAtom));
+ announce(`${summary}, ${label}`, "thread-undo-notice");
+ } else {
+ cancelAnnouncement("thread-undo-notice");
+ }
+}
+
let liveUndos: UndoOptions[] = [];
let expiry: ReturnType<typeof setTimeout> | undefined;
// A new notice owns mod+z even inside a text field, until the user presses
@@ -37,7 +69,7 @@ function refreshNotice() {
const latest = liveUndos.at(-1);
if (!latest) {
clearTimeout(expiry);
- useThreadUndoNotice.setState({ notice: null });
+ setNotice(null);
return;
}
const group: UndoOptions[] = [];
@@ -46,40 +78,36 @@ function refreshNotice() {
if (entry.action !== latest.action) break;
group.push(entry);
}
- useThreadUndoNotice.setState({
- notice: {
- action: latest.action,
- count: group.length,
- undo: async () => {
- const current = group.filter(
- (entry) => liveUndos.includes(entry) && entry.claim.isCurrent(),
- );
- liveUndos = liveUndos.filter((entry) => !group.includes(entry));
- // Claim before awaiting to prevent repeated actions restoring a group twice.
- for (const entry of current) entry.claim.finish();
- refreshNotice();
- await Promise.all(
- current.map(async ({ undo, failureTitle }) => {
- const reportFailure = (error: unknown) => {
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: failureTitle,
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- };
- try {
- const result = await undo();
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- reportFailure(squashAtomCommandFailure(result));
- }
- } catch (error) {
- reportFailure(error);
+ setNotice({
+ action: latest.action,
+ count: group.length,
+ undo: async () => {
+ const current = group.filter((entry) => liveUndos.includes(entry) && entry.claim.isCurrent());
+ liveUndos = liveUndos.filter((entry) => !group.includes(entry));
+ // Claim before awaiting to prevent repeated actions restoring a group twice.
+ for (const entry of current) entry.claim.finish();
+ refreshNotice();
+ await Promise.all(
+ current.map(async ({ undo, failureTitle }) => {
+ const reportFailure = (error: unknown) => {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: failureTitle,
+ description: error instanceof Error ? error.message : "An error occurred.",
+ }),
+ );
+ };
+ try {
+ const result = await undo();
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ reportFailure(squashAtomCommandFailure(result));
}
- }),
- );
- },
+ } catch (error) {
+ reportFailure(error);
+ }
+ }),
+ );
},
});
}
diff --git a/apps/web/src/lib/announce.ts b/apps/web/src/lib/announce.ts
index 20036b82a6d..e95bed66304 100644
--- a/apps/web/src/lib/announce.ts
+++ b/apps/web/src/lib/announce.ts
@@ -37,6 +37,8 @@ function createRegion() {
* replaces one still waiting from the same `source`, so a superseded status isn't read out.
*/
export function announce(message: string, source?: string) {
+ // Stores announce without a mounted owner, so they also run where no DOM exists (unit tests).
+ if (typeof document === "undefined") return;
if (!regions) {
regions = [createRegion(), createRegion()];
document.addEventListener("focusin", () => {
diff --git a/packages/client-runtime/src/clock.ts b/packages/client-runtime/src/clock.ts
index 2e36bb95a50..d0e9db72595 100644
--- a/packages/client-runtime/src/clock.ts
+++ b/packages/client-runtime/src/clock.ts
@@ -112,6 +112,11 @@ function armDeadline(entry: DeadlineEntry, deadlineMs: number) {
entry.timer = setTimeout(() => armDeadline(entry, deadlineMs), Math.min(delay, MAX_TIMEOUT_MS));
}
+/** The epoch-ms deadline `delayMs` from now, for `deadlineStore`. */
+export function deadlineAfter(delayMs: number): number {
+ return Date.now() + delayMs;
+}
+
/**
* Whether `Date.now()` has reached `deadlineMs`. One timer per distinct
* deadline, shared by its subscribers; once passed the snapshot stays true.