@devries-cameron20 / t3code Mirror · read-only / commits / 2de98f035c
Fork 0

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 23, 08:00 UTC

perf(web): the sidebar compiles with no manual memoization (#20396)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 17:43 UTC 2de98f035c3aa84768c2d3a547ed91f0d3daa83e
3 files changed +1333 -1583
apps/web/reactCompiledFiles.ts
+1
@@ -6,6 +6,7 @@
6 */
7 export const REACT_COMPILED_FILES = [
8 "apps/web/src/components/PersistentThreadTerminals.tsx",
9 + "apps/web/src/components/Sidebar.tsx",
10 "apps/web/src/components/chat/usePendingThreadRequests.ts",
11 "apps/web/src/components/chat/composerFocusRedirect.ts",
12 "apps/web/src/components/chat/useChatShortcuts.ts",
apps/web/src/components/Sidebar.tsx
+1332 -1561
@@ -1,10 +1,7 @@
1 -import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts";
1 +import { type EnvironmentId, type ScopedProjectRef, type ServerConfig } from "@t3tools/contracts";
2 import { ThreadHoverCard, ThreadHoverCardPopup } from "./ThreadHoverCard";
3 import { CollapsibleSectionHeader } from "./ui/collapsible-section-header";
4 -import {
5 - setThreadChangeRequestSnapshot,
6 - ThreadTerminalStatusButton,
7 -} from "./ThreadStatusIndicators";
4 +import { ThreadTerminalStatusButton } from "./ThreadStatusIndicators";
5 import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost";
6 import {
7 dropThreadContext,
@@ -74,7 +71,6 @@ import {
71 CircleDashedIcon,
72 CircleDotDashedIcon,
73 ClockIcon,
77 - EyeIcon,
74 FolderIcon,
75 GitBranchIcon,
76 ListFilterIcon,
@@ -91,10 +87,8 @@ import {
87 } from "lucide-react";
88 import {
89 memo,
94 - useCallback,
90 useEffect,
91 useLayoutEffect,
97 - useMemo,
92 useReducer,
93 useRef,
94 useState,
@@ -246,12 +240,9 @@ import {
240 ThreadPullRequestBadgeControl,
241 ThreadPullRequestsMiniList,
242 ThreadWorktreeIndicator,
249 - nextThreadChangeRequestSnapshot,
243 prStatusIndicator,
244 resolveThreadPullRequestBadge,
245 terminalStatusFromRunningIds,
253 - threadChangeRequestSnapshotsAtom,
254 - type ThreadChangeRequestSnapshot,
246 type TerminalStatusIndicator,
247 useLinkedThreadPullRequest,
248 ThreadSearchPullRequestNumber,
@@ -309,6 +300,442 @@ const WORKING_SHELF_EXPANDED_KEY = "t3code:sidebar:working-expanded";
300
301 const inboxReturns = createInboxReturnTracker();
302
303 +type SidebarOptimisticDrop = {
304 + readonly key: string;
305 + readonly sourceSection: SidebarSection;
306 + readonly section: "pinned" | "active" | "settled";
307 + readonly occurredAt: string;
308 + readonly clearsSnooze: boolean;
309 + readonly order: readonly string[] | null;
310 + readonly keysAtDrop: ReadonlyMap<string, string | null>;
311 + readonly assignedKeys: ReadonlyMap<string, string>;
312 +};
313 +
314 +interface SidebarThreadPartitionInput {
315 + readonly threads: readonly EnvironmentThreadShell[];
316 + readonly scopedProjectKeys: ReadonlySet<string> | null;
317 + readonly serverConfigs: ReadonlyMap<EnvironmentId, ServerConfig>;
318 + readonly optimisticDrop: SidebarOptimisticDrop | null;
319 + readonly workingShelfEnabled: boolean;
320 + // Snooze wakes and the queued-turn grace depend on the clock, so the minute
321 + // tick and the precise snooze-wake tick are inputs: a new key repartitions.
322 + readonly clockKey: string;
323 +}
324 +
325 +function threadShellKey(thread: Pick<SidebarThreadSummary, "environmentId" | "id">): string {
326 + return scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
327 +}
328 +
329 +const NO_DRAGGED_ORDER: readonly string[] = [];
330 +const NO_DRAGGED_ORDERS: {
331 + readonly settledOrder: readonly string[];
332 + readonly activeOrder: readonly string[] | undefined;
333 +} = { settledOrder: NO_DRAGGED_ORDER, activeOrder: undefined };
334 +
335 +// Where the dragged row would sort if dropped on the settled or the
336 +// time-ordered active shelf; the strategy previews those slots.
337 +function resolveDraggedOrders(input: {
338 + readonly drag: { readonly activeKey: string; readonly occurredAt: string };
339 + readonly threadByKey: ReadonlyMap<string, EnvironmentThreadShell>;
340 + readonly settledThreads: readonly EnvironmentThreadShell[];
341 + readonly activeThreads: readonly EnvironmentThreadShell[];
342 + readonly workingShelfEnabled: boolean;
343 +}): typeof NO_DRAGGED_ORDERS {
344 + const { drag, threadByKey, settledThreads, activeThreads, workingShelfEnabled } = input;
345 + const thread = threadByKey.get(drag.activeKey);
346 + if (thread === undefined) return NO_DRAGGED_ORDERS;
347 + const others = (list: readonly EnvironmentThreadShell[]) =>
348 + list.filter((candidate) => threadShellKey(candidate) !== drag.activeKey);
349 + return {
350 + settledOrder: sortSettledThreads([
351 + ...others(settledThreads),
352 + applySidebarThreadDrop(thread, "settled", drag.occurredAt),
353 + ]).map(threadShellKey),
354 + activeOrder: workingShelfEnabled
355 + ? sortInboxThreadsByReturn(
356 + [...others(activeThreads), applySidebarThreadDrop(thread, "active", drag.occurredAt)],
357 + inboxReturns.returnedAt,
358 + ).map(threadShellKey)
359 + : undefined,
360 + };
361 +}
362 +
363 +function routeThreadOnly(
364 + threads: readonly EnvironmentThreadShell[],
365 + routeThreadKey: string | null,
366 +): readonly EnvironmentThreadShell[] {
367 + if (routeThreadKey === null) return EMPTY_THREADS;
368 + const routeThread = threads.find((thread) => threadShellKey(thread) === routeThreadKey);
369 + return routeThread === undefined ? EMPTY_THREADS : [routeThread];
370 +}
371 +
372 +// Everything Sidebar derives from thread shells. Computed inside one hook so
373 +// each value reaches the component frozen and cached on its real inputs: in
374 +// the component body, later hook calls made the compiler treat these maps as
375 +// possibly mutated and recompute them, and every dnd-kit input with them.
376 +function useSidebarThreads(input: {
377 + readonly projectScopeKey: string | null;
378 + readonly scopedProjectKeys: ReadonlySet<string> | null;
379 + readonly serverConfigs: ReadonlyMap<EnvironmentId, ServerConfig>;
380 + readonly optimisticDrop: SidebarOptimisticDrop | null;
381 + readonly routeThreadKey: string | null;
382 +}) {
383 + const { projectScopeKey, scopedProjectKeys, serverConfigs, optimisticDrop, routeThreadKey } =
384 + input;
385 + const threads = useThreadShells();
386 + const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled);
387 + const nowMinute = useNowMinute();
388 + // Snooze wake times are second-precise, so classifying with the quantized
389 + // minute would hold a woken thread on the shelf for up to a minute.
390 + const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
391 + const [nextSnoozeWakeAt, setNextSnoozeWakeAt] = useState<string | null>(null);
392 + useEffect(
393 + () => scheduleSnoozeWake(nextSnoozeWakeAt, () => bumpSnoozeWakeTick((tick) => tick + 1)),
394 + [nextSnoozeWakeAt],
395 + );
396 + const [settledShelfExpanded, setSettledShelfExpanded] = useLocalStorage(
397 + SETTLED_SHELF_EXPANDED_KEY,
398 + false,
399 + Schema.Boolean,
400 + );
401 + const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useLocalStorage(
402 + SNOOZED_SHELF_EXPANDED_KEY,
403 + false,
404 + Schema.Boolean,
405 + );
406 + const [workingShelfExpanded, setWorkingShelfExpanded] = useLocalStorage(
407 + WORKING_SHELF_EXPANDED_KEY,
408 + false,
409 + Schema.Boolean,
410 + );
411 + // The settled tail restarts whenever the project scope changes.
412 + const [settledTail, setSettledTail] = useState({
413 + scopeKey: projectScopeKey,
414 + count: SETTLED_TAIL_INITIAL_COUNT,
415 + });
416 + if (settledTail.scopeKey !== projectScopeKey) {
417 + setSettledTail({ scopeKey: projectScopeKey, count: SETTLED_TAIL_INITIAL_COUNT });
418 + }
419 + const settledVisibleCount =
420 + settledTail.scopeKey === projectScopeKey ? settledTail.count : SETTLED_TAIL_INITIAL_COUNT;
421 +
422 + const partition = partitionSidebarThreads({
423 + threads,
424 + scopedProjectKeys,
425 + serverConfigs,
426 + optimisticDrop,
427 + workingShelfEnabled,
428 + clockKey: `${nowMinute}:${snoozeWakeTick}`,
429 + });
430 + const partitionNextWakeAt = partition.snoozedThreads[0]?.snoozedUntil ?? null;
431 + if (partitionNextWakeAt !== nextSnoozeWakeAt) setNextSnoozeWakeAt(partitionNextWakeAt);
432 +
433 + const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } =
434 + partition;
435 + const visibleSettledThreads = (() => {
436 + if (settledThreads.length <= settledVisibleCount) return settledThreads;
437 + const visible = settledThreads.slice(0, settledVisibleCount);
438 + if (routeThreadKey !== null) {
439 + const routeThread = settledThreads
440 + .slice(settledVisibleCount)
441 + .find((thread) => threadShellKey(thread) === routeThreadKey);
442 + if (routeThread !== undefined) visible.push(routeThread);
443 + }
444 + return visible;
445 + })();
446 + const renderedSettledThreads = settledShelfExpanded
447 + ? visibleSettledThreads
448 + : routeThreadOnly(visibleSettledThreads, routeThreadKey);
449 + const visibleSnoozedThreads = snoozedShelfExpanded
450 + ? snoozedThreads
451 + : routeThreadOnly(snoozedThreads, routeThreadKey);
452 + const visibleWorkingThreads = workingShelfExpanded
453 + ? workingThreads
454 + : routeThreadOnly(workingThreads, routeThreadKey);
455 + const orderedThreads = [
456 + ...pinnedThreads,
457 + ...activeThreads,
458 + ...visibleWorkingThreads,
459 + ...visibleSnoozedThreads,
460 + ...renderedSettledThreads,
461 + ];
462 + const sectionByThreadKey = new Map<string, SidebarSection>();
463 + for (const [list, section] of [
464 + [pinnedThreads, "pinned"],
465 + [activeThreads, "active"],
466 + [workingThreads, "working"],
467 + [snoozedThreads, "snoozed"],
468 + [settledThreads, "settled"],
469 + ] as const) {
470 + for (const thread of list) sectionByThreadKey.set(threadShellKey(thread), section);
471 + }
472 + return {
473 + ...partition,
474 + threads,
475 + workingShelfEnabled,
476 + searchableThreads: [
477 + ...pinnedThreads,
478 + ...activeThreads,
479 + ...workingThreads,
480 + ...snoozedThreads,
481 + ...settledThreads,
482 + ],
483 + settledVisibleCount,
484 + hiddenSettledCount: settledThreads.length - visibleSettledThreads.length,
485 + showMoreSettled: () =>
486 + setSettledTail((current) => ({
487 + scopeKey: current.scopeKey,
488 + count: current.count + SETTLED_TAIL_PAGE_COUNT,
489 + })),
490 + settledShelfExpanded,
491 + toggleSettledShelf: () => setSettledShelfExpanded((value) => !value),
492 + snoozedShelfExpanded,
493 + toggleSnoozedShelf: () => setSnoozedShelfExpanded((value) => !value),
494 + workingShelfExpanded,
495 + toggleWorkingShelf: () => setWorkingShelfExpanded((value) => !value),
496 + renderedSettledThreads,
497 + visibleSnoozedThreads,
498 + visibleWorkingThreads,
499 + orderedThreadKeys: orderedThreads.map(threadShellKey),
500 + threadByKey: new Map(orderedThreads.map((thread) => [threadShellKey(thread), thread] as const)),
501 + settledThreadKeys: new Set(settledThreads.map(threadShellKey)),
502 + snoozedThreadKeys: new Set(snoozedThreads.map(threadShellKey)),
503 + sectionByThreadKey,
504 + pinnedKeys: pinnedThreads.map(threadShellKey),
505 + activeKeys: activeThreads.map(threadShellKey),
506 + pinnedKeysById: new Map(
507 + threads.map((thread) => [threadShellKey(thread), thread.pinOrderKey ?? null] as const),
508 + ),
509 + activeKeysById: new Map(
510 + threads.map((thread) => [threadShellKey(thread), thread.activeOrderKey ?? null] as const),
511 + ),
512 + };
513 +}
514 +
515 +function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
516 + const { threads, scopedProjectKeys, serverConfigs, optimisticDrop, workingShelfEnabled } = input;
517 + const preciseNow = new Date().toISOString();
518 + const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys);
519 + inboxReturns.observe(workingShelfEnabled ? threads : null);
520 + const pinned: EnvironmentThreadShell[] = [];
521 + const active: EnvironmentThreadShell[] = [];
522 + const working: EnvironmentThreadShell[] = [];
523 + const inbox = (thread: EnvironmentThreadShell) =>
524 + workingShelfEnabled && isSidebarThreadWorking(thread) ? working : active;
525 + const snoozed: EnvironmentThreadShell[] = [];
526 + const settled: EnvironmentThreadShell[] = [];
527 + const draggable = new Set<string>();
528 + const activeReorderable = new Set<string>();
529 + for (const thread of visible) {
530 + const capabilities = serverConfigs.get(thread.environmentId)?.environment.capabilities;
531 + const supportsSettlement = capabilities?.threadSettlement === true;
532 + const supportsSnooze = capabilities?.threadSnooze === true;
533 + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
534 + if (capabilities?.threadActiveReorder === true) activeReorderable.add(threadKey);
535 + if (capabilities?.threadPinning === true && capabilities.threadPinReorder === true) {
536 + draggable.add(threadKey);
537 + }
538 + if (optimisticDrop?.key === threadKey) {
539 + const projected = applySidebarThreadDrop(
540 + thread,
541 + optimisticDrop.section,
542 + optimisticDrop.occurredAt,
543 + optimisticDrop.assignedKeys.get(threadKey),
544 + );
545 + (optimisticDrop.section === "pinned"
546 + ? pinned
547 + : optimisticDrop.section === "settled"
548 + ? settled
549 + : inbox(projected)
550 + ).push(
551 + optimisticDrop.clearsSnooze
552 + ? projected
553 + : { ...projected, snoozedAt: thread.snoozedAt, snoozedUntil: thread.snoozedUntil },
554 + );
555 + } else {
556 + const section = resolveSidebarThreadSection({
557 + snoozed: supportsSnooze && effectiveSnoozed(thread, { now: preciseNow }),
558 + settled: supportsSettlement && thread.settledOverride === "settled",
559 + pinned: thread.pinnedAt != null,
560 + });
561 + (section === "snoozed"
562 + ? snoozed
563 + : section === "settled"
564 + ? settled
565 + : section === "pinned"
566 + ? pinned
567 + : inbox(thread)
568 + ).push(thread);
569 + }
570 + }
571 + // Server capability only gates DRAGGING — it must not influence the
572 + // sort, or mixed-version fleets would render different pinned orders on
573 + // web and mobile from the same data.
574 + const sortedPinned = sortPinnedThreadsForSidebar(pinned);
575 + const sortedActive = workingShelfEnabled
576 + ? sortInboxThreadsByReturn(active, inboxReturns.returnedAt)
577 + : sortThreadsForSidebar(active);
578 + return {
579 + pinnedThreads:
580 + optimisticDrop?.section !== "pinned" || optimisticDrop.order === null
581 + ? sortedPinned
582 + : orderItemsByPreferredIds({
583 + items: sortedPinned,
584 + preferredIds: optimisticDrop.order,
585 + getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
586 + }),
587 + draggableThreadKeys: draggable,
588 + activeReorderableThreadKeys: activeReorderable,
589 + activeThreads:
590 + optimisticDrop?.section !== "active" || optimisticDrop.order === null
591 + ? sortedActive
592 + : orderItemsByPreferredIds({
593 + items: sortedActive,
594 + preferredIds: optimisticDrop.order,
595 + getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
596 + }),
597 + workingThreads: sortWorkingThreadsBySend(working),
598 + snoozedThreads: snoozed.toSorted(
599 + (left, right) =>
600 + firstValidTimestampMs(left.snoozedUntil ?? null) -
601 + firstValidTimestampMs(right.snoozedUntil ?? null),
602 + ),
603 + settledThreads: sortSettledThreads(settled),
604 + snoozeNow: preciseNow,
605 + };
606 +}
607 +
608 +function isOptimisticDropReleased(input: {
609 + readonly optimisticDrop: SidebarOptimisticDrop;
610 + readonly threads: readonly EnvironmentThreadShell[];
611 + readonly pinnedKeys: readonly string[];
612 + readonly activeKeys: readonly string[];
613 + readonly now: string;
614 +}): boolean {
615 + const { optimisticDrop, threads, pinnedKeys, activeKeys, now } = input;
616 + const canonicalByKey = new Map(
617 + threads.map((thread) => [
618 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
619 + thread,
620 + ]),
621 + );
622 + const thread = canonicalByKey.get(optimisticDrop.key);
623 + if (thread === undefined || thread.archivedAt !== null) {
624 + return true;
625 + }
626 + const canonicalSection = effectiveSnoozed(thread, { now })
627 + ? "snoozed"
628 + : thread.settledOverride === "settled"
629 + ? "settled"
630 + : thread.pinnedAt != null
631 + ? "pinned"
632 + : "active";
633 + if (
634 + canonicalSection !== optimisticDrop.sourceSection &&
635 + canonicalSection !== optimisticDrop.section
636 + ) {
637 + return true;
638 + }
639 + if (optimisticDrop.order === null) {
640 + // Settle also emits unpin/unsnooze events. Wait for the entire move
641 + // before releasing the projected fields and sort timestamps.
642 + if (
643 + canonicalSection === optimisticDrop.section &&
644 + thread.pinnedAt == null &&
645 + (!optimisticDrop.clearsSnooze || thread.snoozedUntil == null)
646 + ) {
647 + return true;
648 + }
649 + return false;
650 + }
651 + if (canonicalSection !== optimisticDrop.section) return false;
652 + if (optimisticDrop.clearsSnooze && thread.snoozedUntil != null) return false;
653 + const destinationKeys = optimisticDrop.section === "pinned" ? pinnedKeys : activeKeys;
654 + const canonicalDestination = destinationKeys.flatMap((key) => {
655 + const canonical = canonicalByKey.get(key);
656 + return canonical === undefined ? [] : [canonical];
657 + });
658 + const keyByThread = new Map(
659 + canonicalDestination.map((thread) => [
660 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
661 + (optimisticDrop.section === "pinned" ? thread.pinOrderKey : thread.activeOrderKey) ?? null,
662 + ]),
663 + );
664 + const heldOrder = optimisticDrop.order;
665 + const heldKeys = new Set(heldOrder);
666 + const membershipChanged =
667 + destinationKeys.length !== heldOrder.length ||
668 + destinationKeys.some((key) => !heldKeys.has(key));
669 + const foreignKeyLanded = destinationKeys.some((threadKey) => {
670 + const currentKey = keyByThread.get(threadKey) ?? null;
671 + if (currentKey === (optimisticDrop.keysAtDrop.get(threadKey) ?? null)) return false;
672 + return currentKey !== optimisticDrop.assignedKeys.get(threadKey);
673 + });
674 + const allAssignmentsLanded = [...optimisticDrop.assignedKeys].every(
675 + ([threadKey, orderKey]) => keyByThread.get(threadKey) === orderKey,
676 + );
677 + return membershipChanged || foreignKeyLanded || allAssignmentsLanded;
678 +}
679 +
680 +// Sidebar() is large enough that the compiler cannot prove its local maps stay
681 +// unmutated; built inside a hook they reach it frozen and cached.
682 +function useSidebarLookups() {
683 + const projects = useProjects();
684 + const environments = useEnvironmentIdentities();
685 + const serverConfigs = useAtomValue(environmentServerConfigsAtom);
686 + const projectGroups = useSidebarProjectGroups();
687 + const environmentLabelById = new Map(
688 + environments.map((environment) => [environment.environmentId, environment.label] as const),
689 + );
690 + // Threads on non-primary environments (T3 Connect, hosted) resolve their
691 + // provider entry from their own environment's config: default instance ids
692 + // are driver slugs, so a flat map would collide across environments.
693 + const providerEntriesByEnvironment = deriveProviderEntriesByEnvironment(
694 + [...serverConfigs].map(
695 + ([environmentId, config]) => [environmentId, config.providers, config.settings] as const,
696 + ),
697 + );
698 + const projectByKey = new Map(
699 + projects.map((project) => [`${project.environmentId}:${project.id}`, project] as const),
700 + );
701 + const projectDisplayNameByKey = new Map(
702 + projectGroups.flatMap((group) =>
703 + group.memberProjects.map(
704 + (project) => [`${project.environmentId}:${project.id}`, group.displayName] as const,
705 + ),
706 + ),
707 + );
708 + const projectGroupByScopeKey = new Map(
709 + projectGroups.map((project) => [project.projectKey, project] as const),
710 + );
711 + const projectScopeItems = [
712 + { value: "all", label: "All projects" },
713 + ...projectGroups.map((project) => ({ value: project.projectKey, label: project.displayName })),
714 + ];
715 + return {
716 + projects,
717 + serverConfigs,
718 + projectGroups,
719 + environmentLabelById,
720 + providerEntriesByEnvironment,
721 + projectByKey,
722 + projectDisplayNameByKey,
723 + projectGroupByScopeKey,
724 + projectScopeItems,
725 + };
726 +}
727 +
728 +function scheduleSnoozeWake(wakeAt: string | null, onWake: () => void): (() => void) | undefined {
729 + const wakeAtMs = wakeAt === null ? Number.NaN : Date.parse(wakeAt);
730 + if (Number.isNaN(wakeAtMs)) return undefined;
731 + // setTimeout delays are signed 32-bit: anything larger overflows and fires
732 + // immediately, turning a far-future wake (event-condition snoozes synced
733 + // from elsewhere) into a tight re-arm loop.
734 + const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
735 + const id = window.setTimeout(onWake, delayMs);
736 + return () => window.clearTimeout(id);
737 +}
738 +
739 function canOperateThreads(
740 threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,
741 ): boolean {
@@ -358,14 +785,15 @@ function JumpHintBadge(props: { label: string }) {
785 // Self-ticking so only this span re-renders each second, not the whole row.
786 function WorkingDuration(props: { startedAt: string | null }) {
787 const startedMs = props.startedAt !== null ? Date.parse(props.startedAt) : Number.NaN;
361 - const [, setTick] = useState(0);
788 + // Mount time is close enough for the first frame; the interval keeps it current.
789 + const [nowMs, setNowMs] = useState(() => Date.now());
790 useEffect(() => {
791 if (Number.isNaN(startedMs)) return;
364 - const id = window.setInterval(() => setTick((tick) => tick + 1), 1_000);
792 + const id = window.setInterval(() => setNowMs(Date.now()), 1_000);
793 return () => window.clearInterval(id);
794 }, [startedMs]);
795 if (Number.isNaN(startedMs)) return null;
368 - return <span className="tabular-nums">{formatWorkingDurationLabel(Date.now() - startedMs)}</span>;
796 + return <span className="tabular-nums">{formatWorkingDurationLabel(nowMs - startedMs)}</span>;
797 }
798
799 function terminalProcessLabel(count: number): string {
@@ -566,10 +994,7 @@ function SnoozeMenuButton(props: {
994 timestampFormat: TimestampFormat;
995 }) {
996 const { open, onOpenChange, onSnooze, timestampFormat } = props;
569 - const presets = useMemo(
570 - () => (open ? resolveSnoozePresets(new Date(), timestampFormat) : []),
571 - [open, timestampFormat],
572 - );
997 + const presets = open ? resolveSnoozePresets(new Date(), timestampFormat) : [];
998 return (
999 <Menu open={open} onOpenChange={onOpenChange}>
1000 <Tooltip>
@@ -625,7 +1050,6 @@ type SortableThreadRowBag = Pick<
1050 "listeners" | "setNodeRef" | "transform" | "transition" | "isDragging"
1051 >;
1052
628 -const NO_DRAGGED_ORDER: readonly string[] = [];
1053 // useSortable memoizes on its `disabled` object, so a fresh one per render
1054 // re-renders every row and marker on each sidebar update.
1055 const SIDEBAR_SORTABLE_DRAG_DISABLED = { draggable: true } as const;
@@ -649,16 +1073,13 @@ function SortableThreadRow(props: {
1073 });
1074 // dnd-kit memoizes each field but not the bag, so the memoized row would
1075 // rerender on every shell update without this.
652 - const bag = useMemo(
653 - () => ({
654 - listeners,
655 - setNodeRef,
656 - transform: props.contextDrag ? null : transform,
657 - transition: props.contextDrag && isDragging ? "transform 150ms ease-out" : transition,
658 - isDragging: isDragging && !props.contextDrag,
659 - }),
660 - [listeners, setNodeRef, transform, transition, isDragging, props.contextDrag],
661 - );
1076 + const bag = {
1077 + listeners,
1078 + setNodeRef,
1079 + transform: props.contextDrag ? null : transform,
1080 + transition: props.contextDrag && isDragging ? "transform 150ms ease-out" : transition,
1081 + isDragging: isDragging && !props.contextDrag,
1082 + };
1083 return props.children(bag);
1084 }
1085
@@ -828,39 +1249,30 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
1249 projectDisplayName: props.projectDisplayName,
1250 isActive: props.isActive,
1251 });
831 - const handleActivate = useCallback(() => onNavigate(draftId), [draftId, onNavigate]);
832 - const handleKeyDown = useCallback(
833 - (event: ReactKeyboardEvent) => {
834 - // Keys targeting the nested discard button belong to the button:
835 - // preventDefault here would swallow Space's synthesized click and
836 - // navigate instead of discarding.
837 - if ((event.target as HTMLElement).closest("button")) return;
838 - if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
839 - event.preventDefault();
840 - const rect = event.currentTarget.getBoundingClientRect();
841 - onContextMenu(draftId, { x: rect.left, y: rect.bottom });
842 - } else if (event.key === "Enter" || event.key === " ") {
843 - event.preventDefault();
844 - onNavigate(draftId);
845 - }
846 - },
847 - [draftId, onContextMenu, onNavigate],
848 - );
849 - const handleContextMenu = useCallback(
850 - (event: ReactMouseEvent) => {
1252 + const handleActivate = () => onNavigate(draftId);
1253 + const handleKeyDown = (event: ReactKeyboardEvent) => {
1254 + // Keys targeting the nested discard button belong to the button:
1255 + // preventDefault here would swallow Space's synthesized click and
1256 + // navigate instead of discarding.
1257 + if ((event.target as HTMLElement).closest("button")) return;
1258 + if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
1259 event.preventDefault();
852 - onContextMenu(draftId, { x: event.clientX, y: event.clientY });
853 - },
854 - [draftId, onContextMenu],
855 - );
856 - const handleDiscard = useCallback(
857 - (event: ReactMouseEvent) => {
1260 + const rect = event.currentTarget.getBoundingClientRect();
1261 + onContextMenu(draftId, { x: rect.left, y: rect.bottom });
1262 + } else if (event.key === "Enter" || event.key === " ") {
1263 event.preventDefault();
859 - event.stopPropagation();
860 - onDiscard(draftId);
861 - },
862 - [draftId, onDiscard],
863 - );
1264 + onNavigate(draftId);
1265 + }
1266 + };
1267 + const handleContextMenu = (event: ReactMouseEvent) => {
1268 + event.preventDefault();
1269 + onContextMenu(draftId, { x: event.clientX, y: event.clientY });
1270 + };
1271 + const handleDiscard = (event: ReactMouseEvent) => {
1272 + event.preventDefault();
1273 + event.stopPropagation();
1274 + onDiscard(draftId);
1275 + };
1276 return (
1277 <li className="list-none py-0.5">
1278 <div
@@ -938,9 +1350,8 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
1350 let row: SidebarDraftRowData | null = null;
1351 if (props.routeDraftId !== null) {
1352 const draftId = DraftId.make(props.routeDraftId);
941 - const store = useComposerDraftStore.getState();
942 - const session = store.getDraftSession(draftId);
943 - const composer = store.getComposerDraft(draftId);
1353 + const session = draftThreadsByThreadKey[draftId];
1354 + const composer = draftsByThreadKey[draftId];
1355 row =
1356 session && session.promotedTo == null && composer && composerDraftHasUserContent(composer)
1357 ? { draftId, session, composer }
@@ -948,7 +1359,7 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
1359 }
1360 setFrozenActive({ routeDraftId: props.routeDraftId, row });
1361 }
951 - const drafts = useMemo(() => {
1362 + const drafts = (() => {
1363 const rows: SidebarDraftRowData[] = [];
1364 for (const [draftKey, session] of Object.entries(draftThreadsByThreadKey)) {
1365 if (session.promotedTo != null) {
@@ -974,13 +1385,7 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
1385 }
1386 rows.sort((left, right) => right.session.createdAt.localeCompare(left.session.createdAt));
1387 return rows;
977 - }, [
978 - draftThreadsByThreadKey,
979 - draftsByThreadKey,
980 - frozenActive,
981 - props.routeDraftId,
982 - props.scopedProjectKeys,
983 - ]);
1388 + })();
1389 if (drafts.length === 0) {
1390 return null;
1391 }
@@ -1090,16 +1495,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1495 onUnpin: (threadRef: ScopedThreadRef) => void;
1496 onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
1497 onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined;
1093 - changeRequestSnapshot: ThreadChangeRequestSnapshot | null;
1094 - onChangeRequestSnapshot: (
1095 - threadKey: string,
1096 - snapshot: ThreadChangeRequestSnapshot | null,
1097 - ) => void;
1498 }) {
1499 const {
1500 isRenaming,
1101 - changeRequestSnapshot,
1102 - onChangeRequestSnapshot,
1501 onCancelRename,
1502 onCommitRename,
1503 onContextMenu,
@@ -1121,10 +1519,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1519 variant,
1520 variantAction,
1521 } = props;
1124 - const threadRef = useMemo(
1125 - () => scopeThreadRef(thread.environmentId, thread.id),
1126 - [thread.environmentId, thread.id],
1127 - );
1522 + const threadRef = scopeThreadRef(thread.environmentId, thread.id);
1523 const threadKey = scopedThreadKey(threadRef);
1524 const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
1525 useEffect(() => {
@@ -1143,14 +1538,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1538 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
1539 const terminalProcessCount = runningTerminalIds.length;
1540 const hasUnsentDraft = useThreadHasUnsentDraft(threadRef) && !props.isActive;
1146 - const handleDiscardDraftClick = useCallback(
1147 - (event: ReactMouseEvent) => {
1148 - event.preventDefault();
1149 - event.stopPropagation();
1150 - discardComposerDraft(threadRef);
1151 - },
1152 - [threadRef],
1153 - );
1541 + const handleDiscardDraftClick = (event: ReactMouseEvent) => {
1542 + event.preventDefault();
1543 + event.stopPropagation();
1544 + discardComposerDraft(threadRef);
1545 + };
1546
1547 const gitCwd = thread.worktreePath ?? props.project?.workspaceRoot ?? null;
1548 const linkedPullRequestStatus = useLinkedThreadPullRequest(
@@ -1180,8 +1572,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1572
1573 const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt });
1574 const status = resolveSidebarThreadStatus(thread);
1183 - const isInFlight =
1184 - status === "working" || status === "waiting" || status === "approval" || status === "input";
1575 const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt);
1576 const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt);
1577 const isWoke =
@@ -1288,69 +1678,50 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1678 />
1679 );
1680
1291 - const handleClick = useCallback(
1292 - (event: ReactMouseEvent) => {
1293 - onThreadClick(event, threadRef);
1294 - },
1295 - [onThreadClick, threadRef],
1296 - );
1297 - const handleAcknowledgeWokeClick = useCallback(
1298 - (event: ReactMouseEvent) => {
1299 - event.preventDefault();
1300 - event.stopPropagation();
1301 - if (props.wokeAt === null) return;
1302 - onAcknowledgeWoke(threadRef, props.wokeAt);
1303 - },
1304 - [onAcknowledgeWoke, props.wokeAt, threadRef],
1305 - );
1306 - const handleContextMenu = useCallback(
1307 - (event: ReactMouseEvent) => {
1308 - event.preventDefault();
1309 - onContextMenu(threadRef, { x: event.clientX, y: event.clientY });
1310 - },
1311 - [onContextMenu, threadRef],
1312 - );
1313 - const handleKeyDown = useCallback(
1314 - (event: ReactKeyboardEvent) => {
1315 - if (event.target !== event.currentTarget) return;
1316 - if (event.key !== "Enter" && event.key !== " ") return;
1317 - event.preventDefault();
1318 - onThreadActivate(threadRef);
1319 - },
1320 - [onThreadActivate, threadRef],
1321 - );
1322 - const handleDoubleClick = useCallback(
1323 - (event: ReactMouseEvent) => {
1324 - if (
1325 - !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) ||
1326 - isRenaming ||
1327 - event.metaKey ||
1328 - event.ctrlKey ||
1329 - event.shiftKey ||
1330 - event.altKey
1331 - ) {
1332 - return;
1333 - }
1334 - if ((event.target as HTMLElement).closest("button, a, input")) return;
1335 - event.preventDefault();
1336 - onStartRename(threadRef, thread.title);
1337 - },
1338 - [isRenaming, onStartRename, thread.title, threadRef],
1339 - );
1681 + const handleClick = (event: ReactMouseEvent) => {
1682 + onThreadClick(event, threadRef);
1683 + };
1684 + const handleAcknowledgeWokeClick = (event: ReactMouseEvent) => {
1685 + event.preventDefault();
1686 + event.stopPropagation();
1687 + if (props.wokeAt === null) return;
1688 + onAcknowledgeWoke(threadRef, props.wokeAt);
1689 + };
1690 + const handleContextMenu = (event: ReactMouseEvent) => {
1691 + event.preventDefault();
1692 + onContextMenu(threadRef, { x: event.clientX, y: event.clientY });
1693 + };
1694 + const handleKeyDown = (event: ReactKeyboardEvent) => {
1695 + if (event.target !== event.currentTarget) return;
1696 + if (event.key !== "Enter" && event.key !== " ") return;
1697 + event.preventDefault();
1698 + onThreadActivate(threadRef);
1699 + };
1700 + const handleDoubleClick = (event: ReactMouseEvent) => {
1701 + if (
1702 + !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) ||
1703 + isRenaming ||
1704 + event.metaKey ||
1705 + event.ctrlKey ||
1706 + event.shiftKey ||
1707 + event.altKey
1708 + ) {
1709 + return;
1710 + }
1711 + if ((event.target as HTMLElement).closest("button, a, input")) return;
1712 + event.preventDefault();
1713 + onStartRename(threadRef, thread.title);
1714 + };
1715 const [isFileDragOver, setIsFileDragOver] = useState(false);
1341 - const fileDropHandlers = useMemo(
1342 - () =>
1343 - onFileDropThreads
1344 - ? makeWorkspaceFileDropHandlers({
1345 - setDragActive: setIsFileDragOver,
1346 - addFiles: (files) => {
1347 - onFileDropThreads(threadRef, files);
1348 - },
1349 - addFolders: () => {},
1350 - })
1351 - : null,
1352 - [onFileDropThreads, threadRef],
1353 - );
1716 + const fileDropHandlers = onFileDropThreads
1717 + ? makeWorkspaceFileDropHandlers({
1718 + setDragActive: setIsFileDragOver,
1719 + addFiles: (files) => {
1720 + onFileDropThreads(threadRef, files);
1721 + },
1722 + addFolders: () => {},
1723 + })
1724 + : null;
1725 useEffect(() => {
1726 if (!isFileDragOver) return;
1727 const clearFileDrag = () => setIsFileDragOver(false);
@@ -1361,104 +1732,69 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1732 useEffect(() => {
1733 if (isRenaming) renameCommittedRef.current = false;
1734 }, [isRenaming]);
1364 - const handleRenameKeyDown = useCallback(
1365 - (event: ReactKeyboardEvent<HTMLInputElement>) => {
1366 - event.stopPropagation();
1367 - if (event.nativeEvent.isComposing || event.keyCode === 229) return;
1368 - if (event.key === "Enter") {
1369 - event.preventDefault();
1370 - renameCommittedRef.current = true;
1371 - onCommitRename(threadRef, renamingTitle, thread.title);
1372 - } else if (event.key === "Escape") {
1373 - event.preventDefault();
1374 - renameCommittedRef.current = true;
1375 - onCancelRename();
1376 - }
1377 - },
1378 - [onCancelRename, onCommitRename, renamingTitle, thread.title, threadRef],
1379 - );
1380 - const handleRenameBlur = useCallback(() => {
1735 + const handleRenameKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
1736 + event.stopPropagation();
1737 + if (event.nativeEvent.isComposing || event.keyCode === 229) return;
1738 + if (event.key === "Enter") {
1739 + event.preventDefault();
1740 + renameCommittedRef.current = true;
1741 + onCommitRename(threadRef, renamingTitle, thread.title);
1742 + } else if (event.key === "Escape") {
1743 + event.preventDefault();
1744 + renameCommittedRef.current = true;
1745 + onCancelRename();
1746 + }
1747 + };
1748 + const handleRenameBlur = () => {
1749 if (!renameCommittedRef.current) {
1750 onCommitRename(threadRef, renamingTitle, thread.title);
1751 }
1384 - }, [onCommitRename, renamingTitle, thread.title, threadRef]);
1385 - const handleSettleClick = useCallback(
1386 - (event: ReactMouseEvent) => {
1387 - event.preventDefault();
1388 - event.stopPropagation();
1389 - onSettle(threadRef);
1390 - },
1391 - [onSettle, threadRef],
1392 - );
1393 - const handleActionPointerDown = useCallback(
1394 - (event: ReactPointerEvent) => {
1395 - if (!event.isPrimary || event.button !== 0) return;
1396 - event.stopPropagation();
1397 - onActionSweepStart(threadRef, variantAction, event.nativeEvent);
1398 - },
1399 - [onActionSweepStart, threadRef, variantAction],
1400 - );
1401 - const handleUnsettleClick = useCallback(
1402 - (event: ReactMouseEvent) => {
1403 - event.preventDefault();
1404 - event.stopPropagation();
1405 - onUnsettle(threadRef);
1406 - },
1407 - [onUnsettle, threadRef],
1408 - );
1409 - const handleUnsnoozeClick = useCallback(
1410 - (event: ReactMouseEvent) => {
1411 - event.preventDefault();
1412 - event.stopPropagation();
1413 - onUnsnooze(threadRef);
1414 - },
1415 - [onUnsnooze, threadRef],
1416 - );
1417 - const handleUnpinClick = useCallback(
1418 - (event: ReactMouseEvent) => {
1419 - event.preventDefault();
1420 - event.stopPropagation();
1421 - onUnpin(threadRef);
1422 - },
1423 - [onUnpin, threadRef],
1424 - );
1425 - const handleSnoozePreset = useCallback(
1426 - (preset: Pick<SnoozePreset, "snoozedUntil">) => {
1427 - onSnooze(threadRef, preset);
1428 - },
1429 - [onSnooze, threadRef],
1430 - );
1752 + };
1753 + const handleSettleClick = (event: ReactMouseEvent) => {
1754 + event.preventDefault();
1755 + event.stopPropagation();
1756 + onSettle(threadRef);
1757 + };
1758 + const handleActionPointerDown = (event: ReactPointerEvent) => {
1759 + if (!event.isPrimary || event.button !== 0) return;
1760 + event.stopPropagation();
1761 + onActionSweepStart(threadRef, variantAction, event.nativeEvent);
1762 + };
1763 + const handleUnsettleClick = (event: ReactMouseEvent) => {
1764 + event.preventDefault();
1765 + event.stopPropagation();
1766 + onUnsettle(threadRef);
1767 + };
1768 + const handleUnsnoozeClick = (event: ReactMouseEvent) => {
1769 + event.preventDefault();
1770 + event.stopPropagation();
1771 + onUnsnooze(threadRef);
1772 + };
1773 + const handleUnpinClick = (event: ReactMouseEvent) => {
1774 + event.preventDefault();
1775 + event.stopPropagation();
1776 + onUnpin(threadRef);
1777 + };
1778 + const handleSnoozePreset = (preset: Pick<SnoozePreset, "snoozedUntil">) => {
1779 + onSnooze(threadRef, preset);
1780 + };
1781 const [snoozeMenuOpenRaw, setSnoozeMenuOpen] = useState(false);
1782 const showSnoozeButton =
1783 canOperateThread &&
1784 props.snoozeSupported &&
1785 canSnooze(thread, { now: new Date().toISOString() });
1436 - const showHoverActions =
1437 - (canOperateThread && props.settlementSupported) || showSnoozeButton || hasUnsentDraft;
1786 + // Closing here, not just masking, keeps the menu from reopening when the button returns.
1787 + if (snoozeMenuOpenRaw && !showSnoozeButton) setSnoozeMenuOpen(false);
1788 const snoozeMenuOpen = snoozeMenuOpenRaw && showSnoozeButton;
1439 - useEffect(() => {
1440 - if (!showSnoozeButton) setSnoozeMenuOpen(false);
1441 - }, [showSnoozeButton]);
1442 - const handlePrClick = useCallback(
1443 - (event: ReactMouseEvent<HTMLElement>, targetUrl?: string) => {
1444 - const url = targetUrl ?? pr?.url ?? currentLinkedPr?.url;
1445 - if (!url) return;
1446 - const showInRightPanel = targetUrl !== undefined || openPullRequestsInRightPanel;
1447 - const openedInRightPanel = openPrLink(event, url, showInRightPanel ? threadRef : undefined);
1448 - if (openedInRightPanel && showInRightPanel && !props.isActive) {
1449 - onThreadActivate(threadRef);
1450 - }
1451 - },
1452 - [
1453 - onThreadActivate,
1454 - openPrLink,
1455 - openPullRequestsInRightPanel,
1456 - pr,
1457 - currentLinkedPr,
1458 - props.isActive,
1459 - threadRef,
1460 - ],
1461 - );
1789 + const handlePrClick = (event: ReactMouseEvent<HTMLElement>, targetUrl?: string) => {
1790 + const url = targetUrl ?? pr?.url ?? currentLinkedPr?.url;
1791 + if (!url) return;
1792 + const showInRightPanel = targetUrl !== undefined || openPullRequestsInRightPanel;
1793 + const openedInRightPanel = openPrLink(event, url, showInRightPanel ? threadRef : undefined);
1794 + if (openedInRightPanel && showInRightPanel && !props.isActive) {
1795 + onThreadActivate(threadRef);
1796 + }
1797 + };
1798
1799 const rowSurfaceClassName = cn(
1800 "group/sidebar-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
@@ -1571,10 +1907,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
1907 const prBadgeShape = supportsMultiplePullRequests
1908 ? resolveThreadPullRequestBadge(thread.pullRequests)
1909 : null;
1574 - const handlePrListClick = useCallback(() => {
1910 + const handlePrListClick = () => {
1911 useRightPanelStore.getState().open(threadRef, "pull-requests");
1912 if (!props.isActive) onThreadActivate(threadRef);
1577 - }, [onThreadActivate, props.isActive, threadRef]);
1913 + };
1914 const prBadge =
1915 prBadgeShape?.kind === "stack" || pr || currentLinkedPr ? (
1916 <ThreadPullRequestBadgeControl
@@ -2093,10 +2429,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
2429 projectDisplayName: props.projectDisplayName,
2430 isActive: props.isRouteActive,
2431 });
2096 - const threadRef = useMemo(
2097 - () => scopeThreadRef(thread.environmentId, thread.id),
2098 - [thread.environmentId, thread.id],
2099 - );
2432 + const threadRef = scopeThreadRef(thread.environmentId, thread.id);
2433 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(
2434 props.isHighlighted || props.isRouteActive,
2435 );
@@ -2136,17 +2469,14 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
2469 });
2470 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
2471 const [isFileDragOver, setIsFileDragOver] = useState(false);
2139 - const fileDropHandlers = useMemo(
2140 - () =>
2141 - makeWorkspaceFileDropHandlers({
2142 - setDragActive: setIsFileDragOver,
2143 - addFiles: (files) => {
2144 - props.onFileDropThreads(threadRef, files);
2145 - },
2146 - addFolders: () => {},
2147 - }),
2148 - [props.onFileDropThreads, threadRef],
2149 - );
2472 + const onFileDropThreads = props.onFileDropThreads;
2473 + const fileDropHandlers = makeWorkspaceFileDropHandlers({
2474 + setDragActive: setIsFileDragOver,
2475 + addFiles: (files) => {
2476 + onFileDropThreads(threadRef, files);
2477 + },
2478 + addFolders: () => {},
2479 + });
2480 useEffect(() => {
2481 if (!isFileDragOver) return;
2482 const clearFileDrag = () => setIsFileDragOver(false);
@@ -2161,6 +2491,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
2491 <button
2492 ref={rowRef}
2493 id={props.resultId}
2494 + data-search-result-key={scopedThreadKey(threadRef)}
2495 type="button"
2496 role="option"
2497 tabIndex={-1}
@@ -2251,15 +2582,23 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
2582 });
2583
2584 export default function Sidebar() {
2254 - const projects = useProjects();
2255 - const threads = useThreadShells();
2585 + const {
2586 + projects,
2587 + serverConfigs,
2588 + projectGroups,
2589 + environmentLabelById,
2590 + providerEntriesByEnvironment,
2591 + projectByKey,
2592 + projectDisplayNameByKey,
2593 + projectGroupByScopeKey,
2594 + projectScopeItems,
2595 + } = useSidebarLookups();
2596 const router = useRouter();
2597 const { isMobile, setOpenMobile } = useSidebar();
2598 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
2599 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
2600 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
2601 const timestampFormat = useClientSettings((s) => s.timestampFormat);
2262 - const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled);
2602 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
2603 const {
2604 settleThread,
@@ -2335,12 +2674,6 @@ export default function Sidebar() {
2674 },
2675 });
2676 const newThreadContext = useHandleNewThread();
2338 - const openAddProjectCommandPalette = useCallback(
2339 - () => openCommandPalette({ open: "add-project" }),
2340 - [],
2341 - );
2342 - const environments = useEnvironmentIdentities();
2343 - const serverConfigs = useAtomValue(environmentServerConfigsAtom);
2677 const primaryEnvironmentId = usePrimaryEnvironmentId();
2678 const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
2679 const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
@@ -2354,86 +2687,74 @@ export default function Sidebar() {
2687 const routeDraftThread = useComposerDraftStore((store) =>
2688 routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
2689 );
2357 - const routeThreadRef = useMemo(
2358 - () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread),
2359 - [routeDraftThread, routeTarget],
2360 - );
2361 - const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
2362 - const routeTargetRef = useRef(routeTarget);
2363 - routeTargetRef.current = routeTarget;
2364 - const routeThreadKeyRef = useRef(routeThreadKey);
2365 - routeThreadKeyRef.current = routeThreadKey;
2366 -
2367 - const environmentLabelById = useMemo(
2368 - () =>
2369 - new Map(
2370 - environments.map((environment) => [environment.environmentId, environment.label] as const),
2371 - ),
2372 - [environments],
2373 - );
2690 const environmentMachineById = useEnvironmentMachines();
2375 - const projectGroups = useSidebarProjectGroups();
2691 const projectGroupsRef = useRef(projectGroups);
2377 - projectGroupsRef.current = projectGroups;
2378 - // Threads on non-primary environments (T3 Connect, hosted) resolve their
2379 - // provider entry from their own environment's config: default instance ids
2380 - // are driver slugs, so a flat map would collide across environments.
2381 - const providerEntriesByEnvironment = useMemo(
2382 - () =>
2383 - deriveProviderEntriesByEnvironment(
2384 - [...serverConfigs].map(
2385 - ([environmentId, config]) => [environmentId, config.providers, config.settings] as const,
2386 - ),
2387 - ),
2388 - [serverConfigs],
2389 - );
2390 - const projectByKey = useMemo(
2391 - () => new Map(projects.map((project) => [`${project.environmentId}:${project.id}`, project])),
2392 - [projects],
2393 - );
2394 - const projectDisplayNameByKey = useMemo(
2395 - () =>
2396 - new Map(
2397 - projectGroups.flatMap((group) =>
2398 - group.memberProjects.map(
2399 - (project) => [`${project.environmentId}:${project.id}`, group.displayName] as const,
2400 - ),
2401 - ),
2402 - ),
2403 - [projectGroups],
2404 - );
2405 -
2406 - const nowMinute = useNowMinute();
2407 - const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom);
2408 - // Snooze wake times are second-precise, so classifying with the quantized
2409 - // minute would hold a woken thread on the shelf for up to a minute.
2410 - const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
2411 -
2692 const persistedProjectScopeKey = useUiStateStore((store) => store.sidebarProjectScopeKey);
2413 - const setProjectScopeKey = useUiStateStore((store) => store.setSidebarProjectScopeKey);
2414 - const projectScopeKey = useMemo(
2415 - () =>
2416 - resolveSidebarProjectScopeKey({
2417 - groups: projectGroups,
2418 - key: persistedProjectScopeKey,
2419 - settings: projectGroupingSettings,
2420 - }),
2421 - [persistedProjectScopeKey, projectGroups, projectGroupingSettings],
2422 - );
2423 - const projectScopeItems = useMemo(
2424 - () => [
2425 - { value: "all", label: "All projects" },
2426 - ...projectGroups.map((project) => ({
2427 - value: project.projectKey,
2428 - label: project.displayName,
2429 - })),
2430 - ],
2431 - [projectGroups],
2432 - );
2433 - const showProjectEnvironments = useMemo(
2434 - () => projectGroupsSpanEnvironments(projectGroups),
2435 - [projectGroups],
2693 + const setPersistedProjectScopeKey = useUiStateStore((store) => store.setSidebarProjectScopeKey);
2694 + const [projectScopeMenuState, dispatchProjectScopeMenu] = useReducer(
2695 + reduceSidebarProjectScopeMenuState,
2696 + { open: false, query: "" },
2697 );
2698 + const projectScopeFilter = useComboboxFilter();
2699 + const allProjectSnapshotsReady = useAllEnvironmentProjectSnapshotsReady();
2700 + const allProjectConfigsReady = useAtomValue(environmentProjects.projectConfigsReadyAtom);
2701 + const headerSearchRef = useRef<HTMLDivElement | null>(null);
2702 + // Safari can send a click after Ctrl+click opens settings. Ignore that one
2703 + // selection, then clear the guard when the picker opens again.
2704 + const suppressNextScopeChangeRef = useRef(false);
2705 + const highlightedProjectScopeKeyRef = useRef<string | null>(null);
2706 + // Keep a dropped row at its destination while its server applies the
2707 + // lifecycle command and any order-key writes. The next pickup waits for
2708 + // this hold so a second drop cannot replace an unconfirmed placement.
2709 + const [optimisticDrop, setOptimisticDrop] = useState<SidebarOptimisticDrop | null>(null);
2710 + const threadSearchInputRef = useRef<HTMLInputElement>(null);
2711 + const [threadSearchQuery, setThreadSearchQuery] = useState("");
2712 + const [searchHighlight, setSearchHighlight] = useState({ orderKey: "", index: 0 });
2713 + const searchEnvironmentIds = useConnectedEnvironmentIds();
2714 + const threadSearch = useThreadSearch(searchEnvironmentIds, threadSearchQuery);
2715 + const handleNewThreadRef = useRef(newThreadContext.handleNewThread);
2716 + const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
2717 + const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
2718 + const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
2719 + const [renamingTitle, setRenamingTitle] = useState("");
2720 + const settlingThreadKeysRef = useRef(new Set<string>());
2721 + const threadListRef = useRef<HTMLUListElement | null>(null);
2722 + const dragLabelOffsetRef = useRef(0);
2723 + const listMotionRef = useRef<ReturnType<typeof createSidebarListMotion> | null>(null);
2724 + const [dragState, setDragState] = useState<{
2725 + readonly activeKey: string;
2726 + readonly activeSection: SidebarSection;
2727 + readonly occurredAt: string;
2728 + readonly activationY: number | null;
2729 + readonly targetSection: SidebarSection | null;
2730 + readonly contextDrag: boolean;
2731 + } | null>(null);
2732 + const dragSensorRef = useRef<SidebarPointerSensor | null>(null);
2733 + const contextDragKeyRef = useRef<string | null>(null);
2734 + const [actionSweep, setActionSweep] = useState<{
2735 + action: SidebarSweepAction;
2736 + keys: ReadonlySet<string>;
2737 + } | null>(null);
2738 + const snoozingThreadKeysRef = useRef(new Set<string>());
2739 + const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
2740 + const shortcutModifiers = useShortcutModifierState();
2741 + const terminalFocused = useTerminalFocus();
2742 + const openAddProjectCommandPalette = () => openCommandPalette({ open: "add-project" });
2743 + const routeThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);
2744 + const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
2745 + const routeThreadKeyRef = useRef(routeThreadKey);
2746 +
2747 + // A selection made under one scope can hold threads the next scope hides.
2748 + const setProjectScopeKey = (key: string | null) => {
2749 + clearSelection();
2750 + setPersistedProjectScopeKey(key);
2751 + };
2752 + const projectScopeKey = resolveSidebarProjectScopeKey({
2753 + groups: projectGroups,
2754 + key: persistedProjectScopeKey,
2755 + settings: projectGroupingSettings,
2756 + });
2757 + const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups);
2758 const scratchMachineLabelFor = (
2759 thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">,
2760 ) => {
@@ -2447,51 +2768,27 @@ export default function Sidebar() {
2768 }
2769 return environmentLabelById.get(thread.environmentId) ?? null;
2770 };
2450 - const projectGroupByScopeKey = useMemo(
2451 - () => new Map(projectGroups.map((project) => [project.projectKey, project] as const)),
2452 - [projectGroups],
2453 - );
2454 - const selectedProjectScopeItem = useMemo(
2455 - () =>
2456 - projectScopeItems.find((item) => item.value === (projectScopeKey ?? "all")) ??
2457 - projectScopeItems[0]!,
2458 - [projectScopeItems, projectScopeKey],
2459 - );
2460 - const [projectScopeMenuState, dispatchProjectScopeMenu] = useReducer(
2461 - reduceSidebarProjectScopeMenuState,
2462 - { open: false, query: "" },
2463 - );
2464 - const projectScopeFilter = useComboboxFilter();
2465 - const filteredProjectScopeItems = useMemo(
2466 - () =>
2467 - filterSidebarProjectScopeItems({
2468 - items: projectScopeItems,
2469 - query: projectScopeMenuState.query,
2470 - matches: (item, query) =>
2471 - projectScopeFilter.contains(item, query, (candidate) => candidate.label),
2472 - }),
2473 - [projectScopeFilter, projectScopeItems, projectScopeMenuState.query],
2474 - );
2475 - const scopedProjectGroup = useMemo(
2476 - () =>
2477 - projectScopeKey === null
2478 - ? null
2479 - : (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null),
2480 - [projectGroups, projectScopeKey],
2481 - );
2482 - const scopedProjectKeys = useMemo(
2483 - () =>
2484 - scopedProjectGroup === null
2485 - ? null
2486 - : new Set(
2487 - scopedProjectGroup.memberProjectRefs.map(
2488 - (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
2489 - ),
2771 + const selectedProjectScopeItem =
2772 + projectScopeItems.find((item) => item.value === (projectScopeKey ?? "all")) ??
2773 + projectScopeItems[0]!;
2774 + const filteredProjectScopeItems = filterSidebarProjectScopeItems({
2775 + items: projectScopeItems,
2776 + query: projectScopeMenuState.query,
2777 + matches: (item, query) =>
2778 + projectScopeFilter.contains(item, query, (candidate) => candidate.label),
2779 + });
2780 + const scopedProjectGroup =
2781 + projectScopeKey === null
2782 + ? null
2783 + : (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null);
2784 + const scopedProjectKeys =
2785 + scopedProjectGroup === null
2786 + ? null
2787 + : new Set(
2788 + scopedProjectGroup.memberProjectRefs.map(
2789 + (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
2790 ),
2491 - [scopedProjectGroup],
2492 - );
2493 - const allProjectSnapshotsReady = useAllEnvironmentProjectSnapshotsReady();
2494 - const allProjectConfigsReady = useAtomValue(environmentProjects.projectConfigsReadyAtom);
2791 + );
2792 useEffect(() => {
2793 const nextKey = resolveSidebarProjectScopeKey({
2794 groups: projectGroups,
@@ -2500,15 +2797,17 @@ export default function Sidebar() {
2797 canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,
2798 });
2799 if (nextKey !== persistedProjectScopeKey) {
2503 - setProjectScopeKey(nextKey);
2800 + clearSelection();
2801 + setPersistedProjectScopeKey(nextKey);
2802 }
2803 }, [
2804 allProjectConfigsReady,
2805 allProjectSnapshotsReady,
2806 + clearSelection,
2807 persistedProjectScopeKey,
2808 projectGroups,
2809 projectGroupingSettings,
2511 - setProjectScopeKey,
2810 + setPersistedProjectScopeKey,
2811 ]);
2812 const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
2813 const visibleDraftSessionCount = useComposerDraftStore((store) => {
@@ -2530,9 +2829,6 @@ export default function Sidebar() {
2829 }
2830 return count;
2831 });
2533 - useEffect(() => {
2534 - clearSelection();
2535 - }, [clearSelection, projectScopeKey]);
2832
2833 const openProjectSettings = useStableCallback(
2834 (projectGroup: SidebarProjectSnapshot, projectRef?: ScopedProjectRef) => {
@@ -2552,11 +2848,6 @@ export default function Sidebar() {
2848 });
2849 },
2850 );
2555 - const headerSearchRef = useRef<HTMLDivElement | null>(null);
2556 - // Safari can send a click after Ctrl+click opens settings. Ignore that one
2557 - // selection, then clear the guard when the picker opens again.
2558 - const suppressNextScopeChangeRef = useRef(false);
2559 - const highlightedProjectScopeKeyRef = useRef<string | null>(null);
2851 const handleProjectSettings = useStableCallback(
2852 (
2853 event: ReactMouseEvent<HTMLElement> | ReactKeyboardEvent<HTMLInputElement>,
@@ -2570,20 +2861,9 @@ export default function Sidebar() {
2861 },
2862 );
2863
2573 - // Keep a dropped row at its destination while its server applies the
2574 - // lifecycle command and any order-key writes. The next pickup waits for
2575 - // this hold so a second drop cannot replace an unconfirmed placement.
2576 - const [optimisticDrop, setOptimisticDrop] = useState<{
2577 - readonly key: string;
2578 - readonly sourceSection: SidebarSection;
2579 - readonly section: "pinned" | "active" | "settled";
2580 - readonly occurredAt: string;
2581 - readonly clearsSnooze: boolean;
2582 - readonly order: readonly string[] | null;
2583 - readonly keysAtDrop: ReadonlyMap<string, string | null>;
2584 - readonly assignedKeys: ReadonlyMap<string, string>;
2585 - } | null>(null);
2864 const {
2865 + threads,
2866 + workingShelfEnabled,
2867 pinnedThreads,
2868 draggableThreadKeys,
2869 activeReorderableThreadKeys,
@@ -2592,315 +2872,83 @@ export default function Sidebar() {
2872 snoozedThreads,
2873 settledThreads,
2874 snoozeNow,
2595 - } = useMemo(() => {
2596 - void snoozeWakeTick;
2597 - const preciseNow = new Date().toISOString();
2598 - const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys);
2599 - inboxReturns.observe(workingShelfEnabled ? threads : null);
2600 - const pinned: EnvironmentThreadShell[] = [];
2601 - const active: EnvironmentThreadShell[] = [];
2602 - const working: EnvironmentThreadShell[] = [];
2603 - const inbox = (thread: EnvironmentThreadShell) =>
2604 - workingShelfEnabled && isSidebarThreadWorking(thread) ? working : active;
2605 - const snoozed: EnvironmentThreadShell[] = [];
2606 - const settled: EnvironmentThreadShell[] = [];
2607 - const draggable = new Set<string>();
2608 - const activeReorderable = new Set<string>();
2609 - for (const thread of visible) {
2610 - const capabilities = serverConfigs.get(thread.environmentId)?.environment.capabilities;
2611 - const supportsSettlement = capabilities?.threadSettlement === true;
2612 - const supportsSnooze = capabilities?.threadSnooze === true;
2613 - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
2614 - if (capabilities?.threadActiveReorder === true) activeReorderable.add(threadKey);
2615 - if (capabilities?.threadPinning === true && capabilities.threadPinReorder === true) {
2616 - draggable.add(threadKey);
2617 - }
2618 - if (optimisticDrop?.key === threadKey) {
2619 - const projected = applySidebarThreadDrop(
2620 - thread,
2621 - optimisticDrop.section,
2622 - optimisticDrop.occurredAt,
2623 - optimisticDrop.assignedKeys.get(threadKey),
2624 - );
2625 - (optimisticDrop.section === "pinned"
2626 - ? pinned
2627 - : optimisticDrop.section === "settled"
2628 - ? settled
2629 - : inbox(projected)
2630 - ).push(
2631 - optimisticDrop.clearsSnooze
2632 - ? projected
2633 - : { ...projected, snoozedAt: thread.snoozedAt, snoozedUntil: thread.snoozedUntil },
2634 - );
2635 - } else {
2636 - const section = resolveSidebarThreadSection({
2637 - snoozed: supportsSnooze && effectiveSnoozed(thread, { now: preciseNow }),
2638 - settled: supportsSettlement && thread.settledOverride === "settled",
2639 - pinned: thread.pinnedAt != null,
2640 - });
2641 - (section === "snoozed"
2642 - ? snoozed
2643 - : section === "settled"
2644 - ? settled
2645 - : section === "pinned"
2646 - ? pinned
2647 - : inbox(thread)
2648 - ).push(thread);
2649 - }
2650 - }
2651 - // Server capability only gates DRAGGING — it must not influence the
2652 - // sort, or mixed-version fleets would render different pinned orders on
2653 - // web and mobile from the same data.
2654 - const sortedPinned = sortPinnedThreadsForSidebar(pinned);
2655 - const sortedActive = workingShelfEnabled
2656 - ? sortInboxThreadsByReturn(active, inboxReturns.returnedAt)
2657 - : sortThreadsForSidebar(active);
2658 - return {
2659 - pinnedThreads:
2660 - optimisticDrop?.section !== "pinned" || optimisticDrop.order === null
2661 - ? sortedPinned
2662 - : orderItemsByPreferredIds({
2663 - items: sortedPinned,
2664 - preferredIds: optimisticDrop.order,
2665 - getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
2666 - }),
2667 - draggableThreadKeys: draggable,
2668 - activeReorderableThreadKeys: activeReorderable,
2669 - activeThreads:
2670 - optimisticDrop?.section !== "active" || optimisticDrop.order === null
2671 - ? sortedActive
2672 - : orderItemsByPreferredIds({
2673 - items: sortedActive,
2674 - preferredIds: optimisticDrop.order,
2675 - getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
2676 - }),
2677 - workingThreads: sortWorkingThreadsBySend(working),
2678 - snoozedThreads: snoozed.toSorted(
2679 - (left, right) =>
2680 - firstValidTimestampMs(left.snoozedUntil ?? null) -
2681 - firstValidTimestampMs(right.snoozedUntil ?? null),
2682 - ),
2683 - settledThreads: sortSettledThreads(settled),
2684 - snoozeNow: preciseNow,
2685 - };
2686 - }, [
2687 - nowMinute,
2688 - optimisticDrop,
2875 + searchableThreads,
2876 + settledVisibleCount,
2877 + hiddenSettledCount,
2878 + showMoreSettled,
2879 + settledShelfExpanded,
2880 + toggleSettledShelf,
2881 + snoozedShelfExpanded,
2882 + toggleSnoozedShelf,
2883 + workingShelfExpanded,
2884 + toggleWorkingShelf,
2885 + renderedSettledThreads,
2886 + visibleSnoozedThreads,
2887 + visibleWorkingThreads,
2888 + orderedThreadKeys,
2889 + threadByKey,
2890 + settledThreadKeys,
2891 + snoozedThreadKeys,
2892 + sectionByThreadKey,
2893 + pinnedKeys,
2894 + activeKeys,
2895 + pinnedKeysById,
2896 + activeKeysById,
2897 + } = useSidebarThreads({
2898 + projectScopeKey,
2899 scopedProjectKeys,
2900 serverConfigs,
2691 - snoozeWakeTick,
2692 - threads,
2693 - workingShelfEnabled,
2694 - ]);
2901 + optimisticDrop,
2902 + routeThreadKey,
2903 + });
2904
2696 - const threadSearchInputRef = useRef<HTMLInputElement>(null);
2697 - const [threadSearchQuery, setThreadSearchQuery] = useState("");
2698 - const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0);
2905 const isSearchingThreads = threadSearchQuery.trim().length > 0;
2700 - const searchableThreads = useMemo(
2701 - () => [
2702 - ...pinnedThreads,
2703 - ...activeThreads,
2704 - ...workingThreads,
2705 - ...snoozedThreads,
2706 - ...settledThreads,
2707 - ],
2708 - [activeThreads, pinnedThreads, settledThreads, snoozedThreads, workingThreads],
2709 - );
2710 - const searchEnvironmentIds = useConnectedEnvironmentIds();
2711 - const threadSearch = useThreadSearch(searchEnvironmentIds, threadSearchQuery);
2712 - const threadSearchMatchByKey = useMemo(
2713 - () =>
2714 - new Map(threadSearch.matches.map((match) => [threadSearchMatchKey(match), match] as const)),
2715 - [threadSearch.matches],
2906 + const threadSearchMatchByKey = new Map(
2907 + threadSearch.matches.map((match) => [threadSearchMatchKey(match), match] as const),
2908 );
2717 - const threadSearchResults = useMemo(
2718 - () =>
2719 - searchSidebarThreads(
2720 - searchableThreads,
2721 - threadSearchQuery,
2722 - new Set(threadSearchMatchByKey.keys()),
2723 - ),
2724 - [searchableThreads, threadSearchQuery, threadSearchMatchByKey],
2909 + const threadSearchResults = searchSidebarThreads(
2910 + searchableThreads,
2911 + threadSearchQuery,
2912 + new Set(threadSearchMatchByKey.keys()),
2913 );
2914 const threadSearchResultOrderKey = threadSearchResults
2915 .map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)))
2916 .join("\0");
2917
2918 + // The highlight belongs to one result list; a new list starts at the top.
2919 + const activeSearchResultIndex =
2920 + searchHighlight.orderKey === threadSearchResultOrderKey ? searchHighlight.index : 0;
2921 + const setActiveSearchResultIndex = (index: number | ((index: number) => number)) =>
2922 + setSearchHighlight((current) => {
2923 + const currentIndex = current.orderKey === threadSearchResultOrderKey ? current.index : 0;
2924 + return {
2925 + orderKey: threadSearchResultOrderKey,
2926 + index: typeof index === "function" ? index(currentIndex) : index,
2927 + };
2928 + });
2929 + const activeSearchResult = isSearchingThreads
2930 + ? threadSearchResults[activeSearchResultIndex]
2931 + : undefined;
2932 + const activeSearchResultKey =
2933 + activeSearchResult === undefined
2934 + ? null
2935 + : scopedThreadKey(scopeThreadRef(activeSearchResult.environmentId, activeSearchResult.id));
2936 useEffect(() => {
2731 - setActiveSearchResultIndex(0);
2732 - }, [threadSearchResultOrderKey]);
2733 -
2734 - useEffect(() => {
2735 - if (!isSearchingThreads) return;
2937 + if (activeSearchResultKey === null) return;
2938 document
2737 - .getElementById(`sidebar-thread-search-result-${activeSearchResultIndex}`)
2939 + .querySelector(`[data-search-result-key="${globalThis.CSS.escape(activeSearchResultKey)}"]`)
2940 ?.scrollIntoView({ block: "nearest" });
2739 - }, [activeSearchResultIndex, isSearchingThreads, threadSearchResultOrderKey]);
2740 -
2741 - useEffect(() => {
2742 - const nextWakeAtMs =
2743 - snoozedThreads.length > 0 && snoozedThreads[0]?.snoozedUntil != null
2744 - ? Date.parse(snoozedThreads[0].snoozedUntil)
2745 - : Number.NaN;
2746 - if (Number.isNaN(nextWakeAtMs)) return;
2747 - // setTimeout delays are signed 32-bit: anything larger overflows and fires
2748 - // immediately, turning a far-future wake (event-condition snoozes synced
2749 - // from elsewhere) into a tight re-arm loop.
2750 - const delayMs = Math.min(Math.max(0, nextWakeAtMs - Date.now()) + 50, 2_147_483_647);
2751 - const id = window.setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
2752 - return () => window.clearTimeout(id);
2753 - }, [snoozedThreads]);
2754 -
2755 - const [settledVisibleCount, setSettledVisibleCount] = useState(SETTLED_TAIL_INITIAL_COUNT);
2756 - const settledResetKey = projectScopeKey ?? "all";
2757 - const lastSettledResetKeyRef = useRef(settledResetKey);
2758 - if (lastSettledResetKeyRef.current !== settledResetKey) {
2759 - lastSettledResetKeyRef.current = settledResetKey;
2760 - setSettledVisibleCount(SETTLED_TAIL_INITIAL_COUNT);
2761 - }
2762 - const visibleSettledThreads = useMemo(() => {
2763 - if (settledThreads.length <= settledVisibleCount) return settledThreads;
2764 - const visible = settledThreads.slice(0, settledVisibleCount);
2765 - if (routeThreadKey !== null) {
2766 - const routeThread = settledThreads
2767 - .slice(settledVisibleCount)
2768 - .find(
2769 - (thread) =>
2770 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
2771 - );
2772 - if (routeThread !== undefined) visible.push(routeThread);
2773 - }
2774 - return visible;
2775 - }, [routeThreadKey, settledThreads, settledVisibleCount]);
2776 - const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length;
2777 - const showMoreSettled = useCallback(
2778 - () => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT),
2779 - [],
2780 - );
2781 - const [settledShelfExpanded, setSettledShelfExpanded] = useLocalStorage(
2782 - SETTLED_SHELF_EXPANDED_KEY,
2783 - false,
2784 - Schema.Boolean,
2785 - );
2786 - const toggleSettledShelf = useCallback(
2787 - () => setSettledShelfExpanded((value) => !value),
2788 - [setSettledShelfExpanded],
2789 - );
2790 - const renderedSettledThreads = useMemo(() => {
2791 - if (settledShelfExpanded) return visibleSettledThreads;
2792 - if (routeThreadKey === null) return EMPTY_THREADS;
2793 - const routeThread = visibleSettledThreads.find(
2794 - (thread) =>
2795 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
2796 - );
2797 - return routeThread === undefined ? EMPTY_THREADS : [routeThread];
2798 - }, [routeThreadKey, settledShelfExpanded, visibleSettledThreads]);
2941 + }, [activeSearchResultKey]);
2942
2800 - const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useLocalStorage(
2801 - SNOOZED_SHELF_EXPANDED_KEY,
2802 - false,
2803 - Schema.Boolean,
2804 - );
2805 - const toggleSnoozedShelf = useCallback(
2806 - () => setSnoozedShelfExpanded((value) => !value),
2807 - [setSnoozedShelfExpanded],
2808 - );
2809 - const visibleSnoozedThreads = useMemo(() => {
2810 - if (snoozedShelfExpanded) return snoozedThreads;
2811 - if (routeThreadKey === null) return EMPTY_THREADS;
2812 - const routeThread = snoozedThreads.find(
2813 - (thread) =>
2814 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
2815 - );
2816 - return routeThread === undefined ? EMPTY_THREADS : [routeThread];
2817 - }, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]);
2818 -
2819 - const [workingShelfExpanded, setWorkingShelfExpanded] = useLocalStorage(
2820 - WORKING_SHELF_EXPANDED_KEY,
2821 - false,
2822 - Schema.Boolean,
2823 - );
2824 - const toggleWorkingShelf = useCallback(
2825 - () => setWorkingShelfExpanded((value) => !value),
2826 - [setWorkingShelfExpanded],
2827 - );
2828 - const visibleWorkingThreads = useMemo(() => {
2829 - if (workingShelfExpanded) return workingThreads;
2830 - if (routeThreadKey === null) return EMPTY_THREADS;
2831 - const routeThread = workingThreads.find(
2832 - (thread) =>
2833 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
2834 - );
2835 - return routeThread === undefined ? EMPTY_THREADS : [routeThread];
2836 - }, [routeThreadKey, workingShelfExpanded, workingThreads]);
2837 -
2838 - const orderedThreads = useMemo(
2839 - () => [
2840 - ...pinnedThreads,
2841 - ...activeThreads,
2842 - ...visibleWorkingThreads,
2843 - ...visibleSnoozedThreads,
2844 - ...renderedSettledThreads,
2845 - ],
2846 - [
2847 - pinnedThreads,
2848 - activeThreads,
2849 - visibleWorkingThreads,
2850 - visibleSnoozedThreads,
2851 - renderedSettledThreads,
2852 - ],
2853 - );
2854 - const orderedThreadKeys = useMemo(
2855 - () =>
2856 - orderedThreads.map((thread) =>
2857 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
2858 - ),
2859 - [orderedThreads],
2860 - );
2943 const orderedThreadKeysRef = useRef(orderedThreadKeys);
2862 - orderedThreadKeysRef.current = orderedThreadKeys;
2863 - const threadByKey = useMemo(
2864 - () =>
2865 - new Map(
2866 - orderedThreads.map(
2867 - (thread) =>
2868 - [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
2869 - ),
2870 - ),
2871 - [orderedThreads],
2872 - );
2944 // Handlers read these through refs: depending on per-update Map/Set
2945 // identities would give every row a fresh callback prop on each shell
2946 // event and defeat row memoization during streaming.
2947 const threadByKeyRef = useRef(threadByKey);
2877 - threadByKeyRef.current = threadByKey;
2878 - const handleNewThreadRef = useRef(newThreadContext.handleNewThread);
2879 - handleNewThreadRef.current = newThreadContext.handleNewThread;
2880 - const settledThreadKeys = useMemo(
2881 - () =>
2882 - new Set(
2883 - settledThreads.map((thread) =>
2884 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
2885 - ),
2886 - ),
2887 - [settledThreads],
2888 - );
2948 const settledThreadKeysRef = useRef(settledThreadKeys);
2890 - settledThreadKeysRef.current = settledThreadKeys;
2891 - const snoozedThreadKeys = useMemo(
2892 - () =>
2893 - new Set(
2894 - snoozedThreads.map((thread) =>
2895 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
2896 - ),
2897 - ),
2898 - [snoozedThreads],
2899 - );
2949 const snoozedThreadKeysRef = useRef(snoozedThreadKeys);
2901 - snoozedThreadKeysRef.current = snoozedThreadKeys;
2950
2903 - const jumpLabelByKey = useMemo(() => {
2951 + const jumpLabelByKey = (() => {
2952 const mapping = new Map<string, string>();
2953 for (const [index, threadKey] of orderedThreadKeys.entries()) {
2954 const jumpCommand = threadJumpCommandForIndex(index);
@@ -2909,323 +2957,265 @@ export default function Sidebar() {
2957 if (label) mapping.set(threadKey, label);
2958 }
2959 return mapping;
2912 - }, [keybindings, orderedThreadKeys]);
2960 + })();
2961 const { showThreadJumpHints: showJumpHints, updateThreadJumpHintsVisibility } =
2962 useThreadJumpHintVisibility();
2963
2916 - const navigateToThread = useCallback(
2917 - (threadRef: ScopedThreadRef) => {
2918 - if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
2919 - clearSelection();
2920 - }
2921 - setSelectionAnchor(scopedThreadKey(threadRef));
2922 - if (isMobile) {
2923 - setOpenMobile(false);
2924 - }
2925 - return router.navigate({
2964 + const navigateToThread = (threadRef: ScopedThreadRef) => {
2965 + if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
2966 + clearSelection();
2967 + }
2968 + setSelectionAnchor(scopedThreadKey(threadRef));
2969 + if (isMobile) {
2970 + setOpenMobile(false);
2971 + }
2972 + return router.navigate({
2973 + to: "/$environmentId/$threadId",
2974 + params: buildThreadRouteParams(threadRef),
2975 + });
2976 + };
2977 +
2978 + const handleThreadFileDrop = async (threadRef: ScopedThreadRef, files: File[]) => {
2979 + const dropId = queuePendingFileDrop({ threadRef, files });
2980 + const landedBefore =
2981 + router.buildLocation({
2982 to: "/$environmentId/$threadId",
2983 params: buildThreadRouteParams(threadRef),
2928 - });
2929 - },
2930 - [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor],
2931 - );
2984 + }).pathname === router.state.location.pathname;
2985 + if (landedBefore) return;
2986
2933 - const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
2934 - const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
2935 - const handleThreadFileDrop = useCallback(
2936 - async (threadRef: ScopedThreadRef, files: File[]) => {
2937 - const dropId = queuePendingFileDrop({ threadRef, files });
2938 - const landedBefore =
2987 + try {
2988 + await navigateToThread(threadRef);
2989 + const landed =
2990 router.buildLocation({
2991 to: "/$environmentId/$threadId",
2992 params: buildThreadRouteParams(threadRef),
2993 }).pathname === router.state.location.pathname;
2943 - if (landedBefore) return;
2944 -
2945 - try {
2946 - await navigateToThread(threadRef);
2947 - const landed =
2948 - router.buildLocation({
2949 - to: "/$environmentId/$threadId",
2950 - params: buildThreadRouteParams(threadRef),
2951 - }).pathname === router.state.location.pathname;
2952 - if (!landed) clearPendingFileDrop(dropId);
2953 - } catch {
2954 - clearPendingFileDrop(dropId);
2955 - }
2956 - },
2957 - [clearPendingFileDrop, navigateToThread, queuePendingFileDrop, router],
2958 - );
2994 + if (!landed) clearPendingFileDrop(dropId);
2995 + } catch {
2996 + clearPendingFileDrop(dropId);
2997 + }
2998 + };
2999
2960 - const navigateToDraft = useCallback(
2961 - (draftId: DraftId) => {
2962 - clearSelection();
2963 - if (isMobile) {
2964 - setOpenMobile(false);
2965 - }
2966 - void router.navigate({ to: "/draft/$draftId", params: { draftId } });
2967 - },
2968 - [clearSelection, isMobile, router, setOpenMobile],
2969 - );
3000 + const navigateToDraft = (draftId: DraftId) => {
3001 + clearSelection();
3002 + if (isMobile) {
3003 + setOpenMobile(false);
3004 + }
3005 + void router.navigate({ to: "/draft/$draftId", params: { draftId } });
3006 + };
3007
2971 - const clearThreadSearch = useCallback(() => {
3008 + const clearThreadSearch = () => {
3009 setThreadSearchQuery("");
3010 setActiveSearchResultIndex(0);
2974 - }, []);
2975 - const selectThreadSearchResult = useCallback(
2976 - (thread: EnvironmentThreadShell) => {
3011 + };
3012 + const selectThreadSearchResult = (thread: EnvironmentThreadShell) => {
3013 + clearThreadSearch();
3014 + navigateToThread(scopeThreadRef(thread.environmentId, thread.id));
3015 + };
3016 + const handleThreadSearchKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
3017 + if (event.nativeEvent.isComposing || event.keyCode === 229) return;
3018 + if (event.key === "Escape" && isSearchingThreads) {
3019 + event.preventDefault();
3020 + event.stopPropagation();
3021 clearThreadSearch();
2978 - navigateToThread(scopeThreadRef(thread.environmentId, thread.id));
2979 - },
2980 - [clearThreadSearch, navigateToThread],
2981 - );
2982 - const handleThreadSearchKeyDown = useCallback(
2983 - (event: ReactKeyboardEvent<HTMLInputElement>) => {
2984 - if (event.nativeEvent.isComposing || event.keyCode === 229) return;
2985 - if (event.key === "Escape" && isSearchingThreads) {
2986 - event.preventDefault();
2987 - event.stopPropagation();
2988 - clearThreadSearch();
2989 - return;
2990 - }
2991 - if (threadSearchResults.length === 0) return;
2992 - if (event.key === "ArrowDown") {
2993 - event.preventDefault();
2994 - setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length);
2995 - return;
2996 - }
2997 - if (event.key === "ArrowUp") {
2998 - event.preventDefault();
2999 - setActiveSearchResultIndex(
3000 - (index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length,
3001 - );
3002 - return;
3003 - }
3004 - if (event.key === "Enter") {
3005 - event.preventDefault();
3006 - const result = threadSearchResults[activeSearchResultIndex];
3007 - if (result) selectThreadSearchResult(result);
3008 - }
3009 - },
3010 - [
3011 - activeSearchResultIndex,
3012 - clearThreadSearch,
3013 - isSearchingThreads,
3014 - selectThreadSearchResult,
3015 - threadSearchResults,
3016 - ],
3017 - );
3022 + return;
3023 + }
3024 + if (threadSearchResults.length === 0) return;
3025 + if (event.key === "ArrowDown") {
3026 + event.preventDefault();
3027 + setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length);
3028 + return;
3029 + }
3030 + if (event.key === "ArrowUp") {
3031 + event.preventDefault();
3032 + setActiveSearchResultIndex(
3033 + (index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length,
3034 + );
3035 + return;
3036 + }
3037 + if (event.key === "Enter") {
3038 + event.preventDefault();
3039 + const result = threadSearchResults[activeSearchResultIndex];
3040 + if (result) selectThreadSearchResult(result);
3041 + }
3042 + };
3043
3019 - const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
3020 - const [renamingTitle, setRenamingTitle] = useState("");
3021 - const startThreadRename = useCallback((threadRef: ScopedThreadRef, title: string) => {
3044 + const startThreadRename = (threadRef: ScopedThreadRef, title: string) => {
3045 if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
3046 setRenamingThreadKey(scopedThreadKey(threadRef));
3047 setRenamingTitle(title);
3025 - }, []);
3026 - const cancelThreadRename = useCallback(() => setRenamingThreadKey(null), []);
3027 - const commitThreadRename = useCallback(
3028 - (threadRef: ScopedThreadRef, title: string, originalTitle: string) => {
3029 - void (async () => {
3030 - if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
3031 - const trimmed = title.trim();
3032 - setRenamingThreadKey(null);
3033 - if (trimmed.length === 0) {
3034 - toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
3035 - return;
3036 - }
3037 - if (trimmed === originalTitle) return;
3038 - const result = await updateThreadMetadata({
3039 - environmentId: threadRef.environmentId,
3040 - input: { threadId: threadRef.threadId, title: trimmed },
3041 - });
3042 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3043 - const error = squashAtomCommandFailure(result);
3044 - toastManager.add(
3045 - stackedThreadToast({
3046 - type: "error",
3047 - title: "Failed to rename thread",
3048 - description: error instanceof Error ? error.message : "An error occurred.",
3049 - }),
3050 - );
3051 - }
3052 - })();
3053 - },
3054 - [updateThreadMetadata],
3055 - );
3056 -
3057 - const handleThreadClick = useCallback(
3058 - (event: ReactMouseEvent, threadRef: ScopedThreadRef) => {
3059 - if (isSidebarNestedLinkClick(event.target)) return;
3060 - const isMac = isMacPlatform(navigator.platform);
3061 - const isModClick = isMac ? event.metaKey : event.ctrlKey;
3062 - const threadKey = scopedThreadKey(threadRef);
3063 - if (isModClick) {
3064 - event.preventDefault();
3065 - toggleThreadSelection(threadKey);
3066 - return;
3067 - }
3068 - if (event.shiftKey) {
3069 - event.preventDefault();
3070 - rangeSelectTo(threadKey, orderedThreadKeysRef.current);
3048 + };
3049 + const cancelThreadRename = () => setRenamingThreadKey(null);
3050 + const commitThreadRename = (threadRef: ScopedThreadRef, title: string, originalTitle: string) => {
3051 + void (async () => {
3052 + if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
3053 + const trimmed = title.trim();
3054 + setRenamingThreadKey(null);
3055 + if (trimmed.length === 0) {
3056 + toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
3057 return;
3058 }
3073 - if (isTrailingDoubleClick(event.detail)) {
3074 - return;
3059 + if (trimmed === originalTitle) return;
3060 + const result = await updateThreadMetadata({
3061 + environmentId: threadRef.environmentId,
3062 + input: { threadId: threadRef.threadId, title: trimmed },
3063 + });
3064 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3065 + const error = squashAtomCommandFailure(result);
3066 + toastManager.add(
3067 + stackedThreadToast({
3068 + type: "error",
3069 + title: "Failed to rename thread",
3070 + description: error instanceof Error ? error.message : "An error occurred.",
3071 + }),
3072 + );
3073 }
3076 - navigateToThread(threadRef);
3077 - },
3078 - [navigateToThread, rangeSelectTo, toggleThreadSelection],
3079 - );
3074 + })();
3075 + };
3076 +
3077 + const handleThreadClick = (event: ReactMouseEvent, threadRef: ScopedThreadRef) => {
3078 + if (isSidebarNestedLinkClick(event.target)) return;
3079 + const isMac = isMacPlatform(navigator.platform);
3080 + const isModClick = isMac ? event.metaKey : event.ctrlKey;
3081 + const threadKey = scopedThreadKey(threadRef);
3082 + if (isModClick) {
3083 + event.preventDefault();
3084 + toggleThreadSelection(threadKey);
3085 + return;
3086 + }
3087 + if (event.shiftKey) {
3088 + event.preventDefault();
3089 + rangeSelectTo(threadKey, orderedThreadKeysRef.current);
3090 + return;
3091 + }
3092 + if (isTrailingDoubleClick(event.detail)) {
3093 + return;
3094 + }
3095 + navigateToThread(threadRef);
3096 + };
3097
3081 - const settlingThreadKeysRef = useRef(new Set<string>());
3098 // Callers snapshot the plan BEFORE the command mutates the partition;
3099 // background parks never navigate (null plan).
3084 - const planForwardNavigation = useCallback(
3085 - (threadKey: string, coParkingKeys?: ReadonlySet<string>): (() => void) | null => {
3086 - if (routeThreadKeyRef.current !== threadKey) return null;
3087 - const shell = threadByKeyRef.current.get(threadKey);
3088 - const orderedKeys = orderedThreadKeysRef.current;
3089 - const settledKeys = settledThreadKeysRef.current;
3090 - const snoozedKeys = snoozedThreadKeysRef.current;
3091 - const currentIndex = orderedKeys.indexOf(threadKey);
3092 - const nextCardKey =
3093 - currentIndex === -1
3094 - ? null
3095 - : ([...orderedKeys.slice(currentIndex + 1), ...orderedKeys.slice(0, currentIndex)].find(
3096 - (key) => !settledKeys.has(key) && !snoozedKeys.has(key) && !coParkingKeys?.has(key),
3097 - ) ?? null);
3098 - const nextThread = nextCardKey ? threadByKeyRef.current.get(nextCardKey) : null;
3099 - return nextThread
3100 - ? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id))
3101 - : shell
3102 - ? () =>
3103 - void handleNewThreadRef.current(scopeProjectRef(shell.environmentId, shell.projectId))
3104 - : () => void router.navigate({ to: "/" });
3105 - },
3106 - [navigateToThread, router],
3107 - );
3100 + const planForwardNavigation = (
3101 + threadKey: string,
3102 + coParkingKeys?: ReadonlySet<string>,
3103 + ): (() => void) | null => {
3104 + if (routeThreadKeyRef.current !== threadKey) return null;
3105 + const shell = threadByKeyRef.current.get(threadKey);
3106 + const orderedKeys = orderedThreadKeysRef.current;
3107 + const settledKeys = settledThreadKeysRef.current;
3108 + const snoozedKeys = snoozedThreadKeysRef.current;
3109 + const currentIndex = orderedKeys.indexOf(threadKey);
3110 + const nextCardKey =
3111 + currentIndex === -1
3112 + ? null
3113 + : ([...orderedKeys.slice(currentIndex + 1), ...orderedKeys.slice(0, currentIndex)].find(
3114 + (key) => !settledKeys.has(key) && !snoozedKeys.has(key) && !coParkingKeys?.has(key),
3115 + ) ?? null);
3116 + const nextThread = nextCardKey ? threadByKeyRef.current.get(nextCardKey) : null;
3117 + return nextThread
3118 + ? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id))
3119 + : shell
3120 + ? () =>
3121 + void handleNewThreadRef.current(scopeProjectRef(shell.environmentId, shell.projectId))
3122 + : () => void router.navigate({ to: "/" });
3123 + };
3124
3109 - const attemptSettle = useCallback(
3110 - (threadRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet<string> } = {}) => {
3111 - void (async () => {
3112 - const threadKey = scopedThreadKey(threadRef);
3113 - if (settlingThreadKeysRef.current.has(threadKey)) return;
3114 - settlingThreadKeysRef.current.add(threadKey);
3115 - try {
3116 - const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys);
3117 - const result = await settleThread(threadRef);
3118 - if (result._tag === "Failure") {
3119 - if (!isAtomCommandInterrupted(result)) {
3120 - const error = squashAtomCommandFailure(result);
3121 - toastManager.add(
3122 - stackedThreadToast({
3123 - type: "error",
3124 - title: "Failed to settle thread",
3125 - description: error instanceof Error ? error.message : "An error occurred.",
3126 - }),
3127 - );
3128 - }
3129 - return;
3130 - }
3131 - if (
3132 - shouldNavigateAfterThreadPark({
3133 - threadKey,
3134 - currentThreadKey: routeThreadKeyRef.current,
3135 - action: "settle",
3136 - now: new Date().toISOString(),
3137 - thread: readThreadShell(threadRef),
3138 - })
3139 - ) {
3140 - navigateAfterSettle?.();
3141 - }
3142 - } finally {
3143 - settlingThreadKeysRef.current.delete(threadKey);
3144 - }
3145 - })();
3146 - },
3147 - [planForwardNavigation, settleThread],
3148 - );
3149 - useEffect(() => registerSettleAndAdvance(attemptSettle), [attemptSettle]);
3150 - const settleThreads = useCallback(
3151 - (threadKeys: readonly string[]) => {
3152 - const coSettlingKeys = new Set(threadKeys);
3153 - for (const threadKey of threadKeys) {
3154 - const thread = threadByKeyRef.current.get(threadKey);
3155 - if (!thread || thread.settledOverride === "settled") continue;
3156 - attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys });
3157 - }
3158 - },
3159 - [attemptSettle],
3160 - );
3161 - const attemptUnsettle = useCallback(
3162 - (threadRef: ScopedThreadRef) => {
3163 - void (async () => {
3164 - const result = await unsettleThread(threadRef);
3165 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3166 - const error = squashAtomCommandFailure(result);
3167 - toastManager.add(
3168 - stackedThreadToast({
3169 - type: "error",
3170 - title: "Failed to un-settle thread",
3171 - description: error instanceof Error ? error.message : "An error occurred.",
3172 - }),
3173 - );
3174 - }
3175 - })();
3176 - },
3177 - [unsettleThread],
3178 - );
3179 - const attemptUnsnooze = useCallback(
3180 - (threadRef: ScopedThreadRef) => {
3181 - void (async () => {
3182 - const result = await unsnoozeThread(threadRef);
3183 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3125 + const attemptSettle = (
3126 + threadRef: ScopedThreadRef,
3127 + opts: { coSettlingKeys?: ReadonlySet<string> } = {},
3128 + ) => {
3129 + void (async () => {
3130 + const threadKey = scopedThreadKey(threadRef);
3131 + if (settlingThreadKeysRef.current.has(threadKey)) return;
3132 + settlingThreadKeysRef.current.add(threadKey);
3133 + const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys);
3134 + const result = await settleThread(threadRef);
3135 + settlingThreadKeysRef.current.delete(threadKey);
3136 + if (result._tag === "Failure") {
3137 + if (!isAtomCommandInterrupted(result)) {
3138 const error = squashAtomCommandFailure(result);
3139 toastManager.add(
3140 stackedThreadToast({
3141 type: "error",
3188 - title: "Failed to wake thread",
3142 + title: "Failed to settle thread",
3143 description: error instanceof Error ? error.message : "An error occurred.",
3144 }),
3145 );
3146 }
3193 - })();
3194 - },
3195 - [unsnoozeThread],
3196 - );
3197 - const threadListRef = useRef<HTMLUListElement | null>(null);
3198 - const dragLabelOffsetRef = useRef(0);
3199 - const restrictBelowPins = useCallback<Modifier>(
3200 - (args) => restrictBelowSidebarLabel(args, dragLabelOffsetRef.current),
3201 - [],
3202 - );
3147 + return;
3148 + }
3149 + if (
3150 + shouldNavigateAfterThreadPark({
3151 + threadKey,
3152 + currentThreadKey: routeThreadKeyRef.current,
3153 + action: "settle",
3154 + now: new Date().toISOString(),
3155 + thread: readThreadShell(threadRef),
3156 + })
3157 + ) {
3158 + navigateAfterSettle?.();
3159 + }
3160 + })();
3161 + };
3162 + useEffect(() => registerSettleAndAdvance(attemptSettle), [attemptSettle]);
3163 + const settleThreads = (threadKeys: readonly string[]) => {
3164 + const coSettlingKeys = new Set(threadKeys);
3165 + for (const threadKey of threadKeys) {
3166 + const thread = threadByKeyRef.current.get(threadKey);
3167 + if (!thread || thread.settledOverride === "settled") continue;
3168 + attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys });
3169 + }
3170 + };
3171 + const attemptUnsettle = (threadRef: ScopedThreadRef) => {
3172 + void (async () => {
3173 + const result = await unsettleThread(threadRef);
3174 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3175 + const error = squashAtomCommandFailure(result);
3176 + toastManager.add(
3177 + stackedThreadToast({
3178 + type: "error",
3179 + title: "Failed to un-settle thread",
3180 + description: error instanceof Error ? error.message : "An error occurred.",
3181 + }),
3182 + );
3183 + }
3184 + })();
3185 + };
3186 + const attemptUnsnooze = (threadRef: ScopedThreadRef) => {
3187 + void (async () => {
3188 + const result = await unsnoozeThread(threadRef);
3189 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3190 + const error = squashAtomCommandFailure(result);
3191 + toastManager.add(
3192 + stackedThreadToast({
3193 + type: "error",
3194 + title: "Failed to wake thread",
3195 + description: error instanceof Error ? error.message : "An error occurred.",
3196 + }),
3197 + );
3198 + }
3199 + })();
3200 + };
3201 + const restrictBelowPins: Modifier = (args) =>
3202 + restrictBelowSidebarLabel(args, dragLabelOffsetRef.current);
3203 // A new array re-renders DndContext and with it every sortable row.
3204 - const dndModifiers = useMemo(
3205 - () => [restrictToVerticalAxis, restrictBelowPins, restrictToFirstScrollableAncestor],
3206 - [restrictBelowPins],
3207 - );
3208 - const listMotionRef = useRef<ReturnType<typeof createSidebarListMotion> | null>(null);
3209 - const attachListMotionRef = useCallback((node: HTMLUListElement | null) => {
3204 + const dndModifiers = [
3205 + restrictToVerticalAxis,
3206 + restrictBelowPins,
3207 + restrictToFirstScrollableAncestor,
3208 + ];
3209 + const attachListMotionRef = (node: HTMLUListElement | null) => {
3210 threadListRef.current = node;
3211 listMotionRef.current?.dispose();
3212 listMotionRef.current = node === null ? null : createSidebarListMotion(node);
3213 listMotionRef.current?.update(false);
3214 - }, []);
3214 + };
3215
3216 - const [dragState, setDragState] = useState<{
3217 - readonly activeKey: string;
3218 - readonly activeSection: SidebarSection;
3219 - readonly occurredAt: string;
3220 - readonly activationY: number | null;
3221 - readonly targetSection: SidebarSection | null;
3222 - readonly contextDrag: boolean;
3223 - } | null>(null);
3216 const isContextDrag = dragState?.contextDrag === true;
3217 const dragTargetSection = isContextDrag ? null : (dragState?.targetSection ?? null);
3226 - const dragSensorRef = useRef<SidebarPointerSensor | null>(null);
3227 - const contextDragKeyRef = useRef<string | null>(null);
3228 - const finishThreadDrag = useCallback((started: boolean) => {
3218 + const finishThreadDrag = (started: boolean) => {
3219 dragSensorRef.current = null;
3220 contextDragKeyRef.current = null;
3221 endThreadContextDrag();
@@ -3233,14 +3223,14 @@ export default function Sidebar() {
3223 listMotionRef.current?.release();
3224 setDragState(null);
3225 }
3236 - }, []);
3237 - const attachDragSensor = useCallback((sensor: SidebarPointerSensor) => {
3226 + };
3227 + const attachDragSensor = (sensor: SidebarPointerSensor) => {
3228 dragSensorRef.current = sensor;
3239 - }, []);
3240 - const cancelThreadDrag = useCallback(() => {
3229 + };
3230 + const cancelThreadDrag = () => {
3231 dragSensorRef.current?.cancel();
3242 - }, []);
3243 - const contextDragThreads = useCallback((): ReadonlyArray<ScopedThreadRef> => {
3232 + };
3233 + const contextDragThreads = (): ReadonlyArray<ScopedThreadRef> => {
3234 const key = contextDragKeyRef.current;
3235 if (key === null) return [];
3236 const selected = useThreadSelectionStore.getState().selectedThreadKeys;
@@ -3249,72 +3239,54 @@ export default function Sidebar() {
3239 const ref = parseScopedThreadKey(candidate);
3240 return ref ? [ref] : [];
3241 });
3252 - }, []);
3253 - const pointerOutsideThreadList = useCallback((point: { x: number; y: number }) => {
3242 + };
3243 + const pointerOutsideThreadList = (point: { x: number; y: number }) => {
3244 const bounds = threadListRef.current?.getBoundingClientRect();
3245 return bounds !== undefined && (point.x < bounds.left || point.x > bounds.right);
3256 - }, []);
3257 - const moveThreadContextDrag = useCallback(
3258 - (point: { x: number; y: number }) => {
3259 - const contextDrag = pointerOutsideThreadList(point);
3260 - setDragState((current) =>
3261 - current === null || current.contextDrag === contextDrag
3262 - ? current
3263 - : { ...current, contextDrag },
3264 - );
3265 - if (!contextDrag) {
3266 - endThreadContextDrag();
3267 - return false;
3268 - }
3269 - const threads = contextDragThreads();
3270 - const title =
3271 - threadByKeyRef.current.get(contextDragKeyRef.current ?? "")?.title.trim() || "Thread";
3272 - moveThreadContextDragGhost(point, { title, count: threads.length });
3273 - return true;
3274 - },
3275 - [contextDragThreads, pointerOutsideThreadList],
3276 - );
3277 - const dropThreadContextDrag = useCallback(
3278 - (point: { x: number; y: number }) => {
3279 - if (!pointerOutsideThreadList(point)) return false;
3280 - dropThreadContext(point, contextDragThreads());
3281 - return true;
3282 - },
3283 - [contextDragThreads, pointerOutsideThreadList],
3284 - );
3246 + };
3247 + const moveThreadContextDrag = (point: { x: number; y: number }) => {
3248 + const contextDrag = pointerOutsideThreadList(point);
3249 + setDragState((current) =>
3250 + current === null || current.contextDrag === contextDrag
3251 + ? current
3252 + : { ...current, contextDrag },
3253 + );
3254 + if (!contextDrag) {
3255 + endThreadContextDrag();
3256 + return false;
3257 + }
3258 + const threads = contextDragThreads();
3259 + const title =
3260 + threadByKeyRef.current.get(contextDragKeyRef.current ?? "")?.title.trim() || "Thread";
3261 + moveThreadContextDragGhost(point, { title, count: threads.length });
3262 + return true;
3263 + };
3264 + const dropThreadContextDrag = (point: { x: number; y: number }) => {
3265 + if (!pointerOutsideThreadList(point)) return false;
3266 + dropThreadContext(point, contextDragThreads());
3267 + return true;
3268 + };
3269 // useSensor memoizes on the options object; a fresh one each render rebuilds
3270 // the sensors, and with them DndContext and every sortable row.
3287 - const pointerSensorOptions = useMemo(
3288 - () => ({
3289 - distance: SIDEBAR_DRAG_DISTANCE,
3290 - onAttach: attachDragSensor,
3291 - onFinish: finishThreadDrag,
3292 - onMove: moveThreadContextDrag,
3293 - onDrop: dropThreadContextDrag,
3294 - }),
3295 - [attachDragSensor, dropThreadContextDrag, finishThreadDrag, moveThreadContextDrag],
3296 - );
3271 + const pointerSensorOptions = {
3272 + distance: SIDEBAR_DRAG_DISTANCE,
3273 + onAttach: attachDragSensor,
3274 + onFinish: finishThreadDrag,
3275 + onMove: moveThreadContextDrag,
3276 + onDrop: dropThreadContextDrag,
3277 + };
3278 const dndSensors = useSensors(useSensor(SidebarPointerSensor, pointerSensorOptions));
3298 - const sectionByThreadKey = useMemo(() => {
3299 - const map = new Map<string, SidebarSection>();
3300 - const add = (list: readonly EnvironmentThreadShell[], section: SidebarSection) => {
3301 - for (const thread of list) {
3302 - map.set(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), section);
3303 - }
3304 - };
3305 - add(pinnedThreads, "pinned");
3306 - add(activeThreads, "active");
3307 - add(workingThreads, "working");
3308 - add(snoozedThreads, "snoozed");
3309 - add(settledThreads, "settled");
3310 - return map;
3311 - }, [activeThreads, pinnedThreads, settledThreads, snoozedThreads, workingThreads]);
3279 const sectionByThreadKeyRef = useRef(sectionByThreadKey);
3313 - sectionByThreadKeyRef.current = sectionByThreadKey;
3314 - const [actionSweep, setActionSweep] = useState<{
3315 - action: SidebarSweepAction;
3316 - keys: ReadonlySet<string>;
3317 - } | null>(null);
3280 + useLayoutEffect(() => {
3281 + routeThreadKeyRef.current = routeThreadKey;
3282 + projectGroupsRef.current = projectGroups;
3283 + orderedThreadKeysRef.current = orderedThreadKeys;
3284 + threadByKeyRef.current = threadByKey;
3285 + handleNewThreadRef.current = newThreadContext.handleNewThread;
3286 + settledThreadKeysRef.current = settledThreadKeys;
3287 + snoozedThreadKeysRef.current = snoozedThreadKeys;
3288 + sectionByThreadKeyRef.current = sectionByThreadKey;
3289 + });
3290 const startActionSweep = useStableCallback(
3291 (threadRef: ScopedThreadRef, action: SidebarSweepAction, event: PointerEvent) => {
3292 const originKey = scopedThreadKey(threadRef);
@@ -3372,160 +3344,82 @@ export default function Sidebar() {
3344 });
3345 },
3346 );
3375 - const pinnedKeys = useMemo(
3376 - () =>
3377 - pinnedThreads.map((thread) =>
3378 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3379 - ),
3380 - [pinnedThreads],
3381 - );
3382 - const activeKeys = useMemo(
3383 - () =>
3384 - activeThreads.map((thread) =>
3385 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3386 - ),
3387 - [activeThreads],
3388 - );
3389 - useEffect(() => {
3390 - if (optimisticDrop === null) return;
3391 - const canonicalByKey = new Map(
3392 - threads.map((thread) => [
3393 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3394 - thread,
3395 - ]),
3396 - );
3397 - const thread = canonicalByKey.get(optimisticDrop.key);
3398 - if (thread === undefined || thread.archivedAt !== null) {
3399 - setOptimisticDrop(null);
3400 - return;
3401 - }
3402 - const canonicalSection = effectiveSnoozed(thread, { now: new Date().toISOString() })
3403 - ? "snoozed"
3404 - : thread.settledOverride === "settled"
3405 - ? "settled"
3406 - : thread.pinnedAt != null
3407 - ? "pinned"
3408 - : "active";
3409 - if (
3410 - canonicalSection !== optimisticDrop.sourceSection &&
3411 - canonicalSection !== optimisticDrop.section
3412 - ) {
3413 - setOptimisticDrop(null);
3414 - return;
3415 - }
3416 - if (optimisticDrop.order === null) {
3417 - // Settle also emits unpin/unsnooze events. Wait for the entire move
3418 - // before releasing the projected fields and sort timestamps.
3419 - if (
3420 - canonicalSection === optimisticDrop.section &&
3421 - thread.pinnedAt == null &&
3422 - (!optimisticDrop.clearsSnooze || thread.snoozedUntil == null)
3423 - ) {
3424 - setOptimisticDrop(null);
3347 + // Release the hold during render once the server state catches up, so the
3348 + // canonical order shows in the same frame instead of after an effect pass.
3349 + if (
3350 + optimisticDrop !== null &&
3351 + isOptimisticDropReleased({
3352 + optimisticDrop,
3353 + threads,
3354 + pinnedKeys,
3355 + activeKeys,
3356 + now: snoozeNow,
3357 + })
3358 + ) {
3359 + setOptimisticDrop(null);
3360 + }
3361 + const attemptPin = (threadRef: ScopedThreadRef) => {
3362 + void (async () => {
3363 + // Fresh pins take the top of the arranged run: pinThread computes a
3364 + // key before the smallest key across ALL pinned shells — including
3365 + // snoozed pins hidden from this list, whose keys are still part of
3366 + // the run — so the new pin can't land beneath a hidden head.
3367 + const result = await pinThread(threadRef);
3368 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3369 + const error = squashAtomCommandFailure(result);
3370 + toastManager.add(
3371 + stackedThreadToast({
3372 + type: "error",
3373 + title: "Failed to pin thread",
3374 + description: error instanceof Error ? error.message : "An error occurred.",
3375 + }),
3376 + );
3377 }
3426 - return;
3378 + })();
3379 + };
3380 + const attemptUnpin = (threadRef: ScopedThreadRef) => {
3381 + void (async () => {
3382 + const result = await confirmAndUnpinThread(threadRef);
3383 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3384 + const error = squashAtomCommandFailure(result);
3385 + toastManager.add(
3386 + stackedThreadToast({
3387 + type: "error",
3388 + title: "Failed to unpin thread",
3389 + description: error instanceof Error ? error.message : "An error occurred.",
3390 + }),
3391 + );
3392 + }
3393 + })();
3394 + };
3395 +
3396 + const handleThreadDragStart = (event: DragStartEvent) => {
3397 + const activeKey = String(event.active.id);
3398 + contextDragKeyRef.current = activeKey;
3399 + const activeSection = sectionByThreadKey.get(activeKey);
3400 + if (activeSection === undefined) return;
3401 + listMotionRef.current?.suspend();
3402 + const list = threadListRef.current;
3403 + const header = list?.querySelector<HTMLElement>('[data-testid="sidebar-pinned-header"]');
3404 + if (list && header) {
3405 + const listRect = list.getBoundingClientRect();
3406 + const scale = list.offsetWidth > 0 ? listRect.width / list.offsetWidth : 1;
3407 + dragLabelOffsetRef.current =
3408 + header.getBoundingClientRect().top - listRect.top + SIDEBAR_DRAG_LABEL_HEIGHT * scale;
3409 + } else {
3410 + dragLabelOffsetRef.current = 0;
3411 }
3428 - if (canonicalSection !== optimisticDrop.section) return;
3429 - if (optimisticDrop.clearsSnooze && thread.snoozedUntil != null) return;
3430 - const destinationKeys = optimisticDrop.section === "pinned" ? pinnedKeys : activeKeys;
3431 - const canonicalDestination = destinationKeys.flatMap((key) => {
3432 - const canonical = canonicalByKey.get(key);
3433 - return canonical === undefined ? [] : [canonical];
3434 - });
3435 - const keyByThread = new Map(
3436 - canonicalDestination.map((thread) => [
3437 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3438 - (optimisticDrop.section === "pinned" ? thread.pinOrderKey : thread.activeOrderKey) ?? null,
3439 - ]),
3440 - );
3441 - const heldOrder = optimisticDrop.order;
3442 - const heldKeys = new Set(heldOrder);
3443 - const membershipChanged =
3444 - destinationKeys.length !== heldOrder.length ||
3445 - destinationKeys.some((key) => !heldKeys.has(key));
3446 - const foreignKeyLanded = destinationKeys.some((threadKey) => {
3447 - const currentKey = keyByThread.get(threadKey) ?? null;
3448 - if (currentKey === (optimisticDrop.keysAtDrop.get(threadKey) ?? null)) return false;
3449 - return currentKey !== optimisticDrop.assignedKeys.get(threadKey);
3412 + setDragState({
3413 + activeKey,
3414 + activeSection,
3415 + targetSection: activeSection,
3416 + contextDrag: false,
3417 + occurredAt: new Date().toISOString(),
3418 + activationY:
3419 + event.activatorEvent instanceof PointerEvent ? event.activatorEvent.clientY : null,
3420 });
3451 - const allAssignmentsLanded = [...optimisticDrop.assignedKeys].every(
3452 - ([threadKey, orderKey]) => keyByThread.get(threadKey) === orderKey,
3453 - );
3454 - if (membershipChanged || foreignKeyLanded || allAssignmentsLanded) {
3455 - setOptimisticDrop(null);
3456 - }
3457 - }, [activeKeys, optimisticDrop, pinnedKeys, threads]);
3458 - const attemptPin = useCallback(
3459 - (threadRef: ScopedThreadRef) => {
3460 - void (async () => {
3461 - // Fresh pins take the top of the arranged run: pinThread computes a
3462 - // key before the smallest key across ALL pinned shells — including
3463 - // snoozed pins hidden from this list, whose keys are still part of
3464 - // the run — so the new pin can't land beneath a hidden head.
3465 - const result = await pinThread(threadRef);
3466 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3467 - const error = squashAtomCommandFailure(result);
3468 - toastManager.add(
3469 - stackedThreadToast({
3470 - type: "error",
3471 - title: "Failed to pin thread",
3472 - description: error instanceof Error ? error.message : "An error occurred.",
3473 - }),
3474 - );
3475 - }
3476 - })();
3477 - },
3478 - [pinThread],
3479 - );
3480 - const attemptUnpin = useCallback(
3481 - (threadRef: ScopedThreadRef) => {
3482 - void (async () => {
3483 - const result = await confirmAndUnpinThread(threadRef);
3484 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3485 - const error = squashAtomCommandFailure(result);
3486 - toastManager.add(
3487 - stackedThreadToast({
3488 - type: "error",
3489 - title: "Failed to unpin thread",
3490 - description: error instanceof Error ? error.message : "An error occurred.",
3491 - }),
3492 - );
3493 - }
3494 - })();
3495 - },
3496 - [confirmAndUnpinThread],
3497 - );
3498 -
3499 - const handleThreadDragStart = useCallback(
3500 - (event: DragStartEvent) => {
3501 - const activeKey = String(event.active.id);
3502 - contextDragKeyRef.current = activeKey;
3503 - const activeSection = sectionByThreadKey.get(activeKey);
3504 - if (activeSection === undefined) return;
3505 - listMotionRef.current?.suspend();
3506 - const list = threadListRef.current;
3507 - const header = list?.querySelector<HTMLElement>('[data-testid="sidebar-pinned-header"]');
3508 - if (list && header) {
3509 - const listRect = list.getBoundingClientRect();
3510 - const scale = list.offsetWidth > 0 ? listRect.width / list.offsetWidth : 1;
3511 - dragLabelOffsetRef.current =
3512 - header.getBoundingClientRect().top - listRect.top + SIDEBAR_DRAG_LABEL_HEIGHT * scale;
3513 - } else {
3514 - dragLabelOffsetRef.current = 0;
3515 - }
3516 - setDragState({
3517 - activeKey,
3518 - activeSection,
3519 - targetSection: activeSection,
3520 - contextDrag: false,
3521 - occurredAt: new Date().toISOString(),
3522 - activationY:
3523 - event.activatorEvent instanceof PointerEvent ? event.activatorEvent.clientY : null,
3524 - });
3525 - },
3526 - [sectionByThreadKey],
3527 - );
3528 - const sidebarListItemsFresh = useMemo((): readonly SidebarListItem[] => {
3421 + };
3422 + const sidebarListItemsFresh = ((): readonly SidebarListItem[] => {
3423 const rowsOf = (
3424 list: readonly EnvironmentThreadShell[],
3425 section: SidebarSection,
@@ -3564,16 +3458,7 @@ export default function Sidebar() {
3458 items.push({ kind: "marker", marker: "settled-placeholder" });
3459 items.push(...settledRows);
3460 return items;
3567 - }, [
3568 - activeThreads,
3569 - pinnedThreads,
3570 - renderedSettledThreads,
3571 - settledThreads.length,
3572 - snoozedThreads.length,
3573 - visibleSnoozedThreads,
3574 - visibleWorkingThreads,
3575 - workingThreads.length,
3576 - ]);
3461 + })();
3462 // Thread shells update on every streamed event without moving rows. Keep the
3463 // list's identity until its order changes, so the sorting strategy, the
3464 // sortable context and every sortable row stay memoized meanwhile.
@@ -3594,113 +3479,60 @@ export default function Sidebar() {
3479 cancelThreadDrag();
3480 }
3481 }, [cancelThreadDrag, dragState, sidebarListItems]);
3597 - const listMotionPaused = dragState !== null;
3598 - // Every shell event rebuilds sidebarListItems, but rows only move when the
3599 - // rendered order or a row's section changes. Keying the motion pass on that
3600 - // keeps ordinary updates from forcing a layout read and animating rows
3601 - // whose position drifted for other reasons.
3602 - const sidebarListOrderKey = useMemo(
3603 - () =>
3604 - sidebarListItems
3605 - .map((item) => (item.kind === "thread" ? `${item.key}:${item.section}` : item.marker))
3606 - .join("\0"),
3607 - [sidebarListItems],
3608 - );
3609 - const sidebarListHasRows = sidebarListItems.length + visibleDraftSessionCount > 0;
3610 - useLayoutEffect(() => {
3611 - void sidebarListOrderKey;
3612 - listMotionRef.current?.update(!listMotionPaused && sidebarListHasRows);
3613 - }, [
3614 - listMotionPaused,
3615 - routeDraftIdForRows,
3616 - sidebarListHasRows,
3617 - sidebarListOrderKey,
3482 + // Rows only move when the rendered order, a row's section, or the draft block
3483 + // changes. Running the motion pass on that alone keeps ordinary shell events
3484 + // from forcing a layout read and animating rows that drifted for other reasons.
3485 + const listMotionLayoutKey = [
3486 + sidebarListItemsKey,
3487 visibleDraftSessionCount,
3619 - ]);
3620 - const handleThreadDragOver = useCallback(
3621 - (event: DragOverEvent) => {
3622 - const target = event.over
3623 - ? resolveSidebarDropTarget(sidebarListItems, String(event.active.id), String(event.over.id))
3624 - : null;
3625 - setDragState((current) =>
3626 - current === null || current.activeKey !== String(event.active.id)
3627 - ? current
3628 - : { ...current, targetSection: target?.section ?? null },
3629 - );
3630 - },
3631 - [sidebarListItems],
3632 - );
3633 - const sortableIds = useMemo(() => sidebarListItems.map(sidebarListItemId), [sidebarListItems]);
3634 - const draggedSettledOrder = useMemo(() => {
3635 - const thread = dragState === null ? undefined : threadByKey.get(dragState.activeKey);
3636 - // Outside a drag this must keep one identity: the sorting strategy, and with
3637 - // it every sortable row, rebuilds when it changes.
3638 - if (dragState === null || thread === undefined) return NO_DRAGGED_ORDER;
3639 - const key = (candidate: EnvironmentThreadShell) =>
3640 - scopedThreadKey(scopeThreadRef(candidate.environmentId, candidate.id));
3641 - return sortSettledThreads([
3642 - ...settledThreads.filter((candidate) => key(candidate) !== dragState.activeKey),
3643 - applySidebarThreadDrop(thread, "settled", dragState.occurredAt),
3644 - ]).map(key);
3645 - }, [dragState, settledThreads, threadByKey]);
3646 - const draggedActiveOrder = useMemo(() => {
3647 - const thread = dragState === null ? undefined : threadByKey.get(dragState.activeKey);
3648 - if (!workingShelfEnabled || dragState === null || thread === undefined) return undefined;
3649 - const key = (candidate: EnvironmentThreadShell) =>
3650 - scopedThreadKey(scopeThreadRef(candidate.environmentId, candidate.id));
3651 - return sortInboxThreadsByReturn(
3652 - [
3653 - ...activeThreads.filter((candidate) => key(candidate) !== dragState.activeKey),
3654 - applySidebarThreadDrop(thread, "active", dragState.occurredAt),
3655 - ],
3656 - inboxReturns.returnedAt,
3657 - ).map(key);
3658 - }, [activeThreads, dragState, threadByKey, workingShelfEnabled]);
3659 - const sidebarSortingStrategy = useMemo(
3660 - () =>
3661 - createSidebarSortingStrategy({
3662 - items: sidebarListItems,
3663 - enabled: !isContextDrag,
3664 - boundaryLabelHeight: SIDEBAR_DRAG_LABEL_HEIGHT,
3665 - settledOrder: draggedSettledOrder,
3666 - ...(draggedActiveOrder === undefined ? {} : { activeOrder: draggedActiveOrder }),
3667 - settledExpanded: settledShelfExpanded,
3668 - settledVisibleCount,
3669 - routeThreadKey,
3670 - snoozedThreadCount: snoozedThreads.length,
3671 - }),
3672 - [
3673 - draggedActiveOrder,
3674 - draggedSettledOrder,
3675 - isContextDrag,
3676 - routeThreadKey,
3677 - settledShelfExpanded,
3678 - settledVisibleCount,
3679 - sidebarListItems,
3680 - snoozedThreads.length,
3681 - ],
3682 - );
3683 - const { pinnedKeysById, activeKeysById } = useMemo(
3684 - () => ({
3685 - pinnedKeysById: new Map(
3686 - threads.map((thread) => [
3687 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3688 - thread.pinOrderKey ?? null,
3689 - ]),
3690 - ),
3691 - activeKeysById: new Map(
3692 - threads.map((thread) => [
3693 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3694 - thread.activeOrderKey ?? null,
3695 - ]),
3696 - ),
3697 - }),
3698 - [threads],
3699 - );
3488 + routeDraftIdForRows ?? "",
3489 + ].join("\0");
3490 + const listMotionAnimate =
3491 + dragState === null && sidebarListItems.length + visibleDraftSessionCount > 0;
3492 + // The effect reads only `animate`; the pass object is cached on both fields,
3493 + // so a new layout key alone also triggers it.
3494 + const listMotionPass = { layoutKey: listMotionLayoutKey, animate: listMotionAnimate };
3495 + useLayoutEffect(() => {
3496 + listMotionRef.current?.update(listMotionPass.animate);
3497 + }, [listMotionPass]);
3498 + const handleThreadDragOver = (event: DragOverEvent) => {
3499 + const target = event.over
3500 + ? resolveSidebarDropTarget(sidebarListItems, String(event.active.id), String(event.over.id))
3501 + : null;
3502 + setDragState((current) =>
3503 + current === null || current.activeKey !== String(event.active.id)
3504 + ? current
3505 + : { ...current, targetSection: target?.section ?? null },
3506 + );
3507 + };
3508 + const sortableIds = sidebarListItems.map(sidebarListItemId);
3509 + // Outside a drag the orders are constants, so the strategy, and with it
3510 + // every sortable row, keeps its identity while thread shells stream in.
3511 + const { settledOrder: draggedSettledOrder, activeOrder: draggedActiveOrder } =
3512 + dragState === null
3513 + ? NO_DRAGGED_ORDERS
3514 + : resolveDraggedOrders({
3515 + drag: dragState,
3516 + threadByKey,
3517 + settledThreads,
3518 + activeThreads,
3519 + workingShelfEnabled,
3520 + });
3521 + const sidebarSortingStrategy = createSidebarSortingStrategy({
3522 + items: sidebarListItems,
3523 + enabled: !isContextDrag,
3524 + boundaryLabelHeight: SIDEBAR_DRAG_LABEL_HEIGHT,
3525 + settledOrder: draggedSettledOrder,
3526 + ...(draggedActiveOrder === undefined ? {} : { activeOrder: draggedActiveOrder }),
3527 + settledExpanded: settledShelfExpanded,
3528 + settledVisibleCount,
3529 + routeThreadKey,
3530 + snoozedThreadCount: snoozedThreads.length,
3531 + });
3532 const draggedThreadKey = dragState?.activeKey;
3533 const draggedFromSection = dragState?.activeSection;
3534 const dragActivationY = dragState?.activationY;
3703 - const dndCollisionDetection = useMemo(() => {
3535 + const dndCollisionDetection = (() => {
3536 if (draggedThreadKey === undefined || draggedFromSection === undefined)
3537 return createSidebarCollisionDetection(() => true);
3538 const source = threadByKey.get(draggedThreadKey);
@@ -3734,253 +3566,201 @@ export default function Sidebar() {
3566 activationY: dragActivationY ?? null,
3567 },
3568 );
3737 - }, [
3738 - activeKeysById,
3739 - pinnedKeysById,
3740 - serverConfigs,
3741 - activeKeys,
3742 - activeReorderableThreadKeys,
3743 - draggedThreadKey,
3744 - draggedFromSection,
3745 - dragActivationY,
3746 - draggableThreadKeys,
3747 - pinnedKeys,
3748 - sidebarListItems,
3749 - threadByKey,
3750 - workingShelfEnabled,
3751 - ]);
3752 - const handleThreadDragEnd = useCallback(
3753 - (event: DragEndEvent) => {
3754 - const activeKey = String(event.active.id);
3755 - const activeSection = sectionByThreadKey.get(activeKey);
3756 - const target =
3757 - event.over === null
3758 - ? null
3759 - : resolveSidebarDropTarget(sidebarListItems, activeKey, String(event.over.id));
3760 - const activeThread = threadByKey.get(activeKey);
3761 - if (activeSection === undefined || target === null || activeThread === undefined) return;
3762 - const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);
3763 - const plan = planSidebarThreadDrop({
3764 - activeKey,
3765 - activeSection,
3766 - activePinned: activeThread.pinnedAt != null,
3767 - activeSettled: activeThread.settledOverride === "settled",
3768 - supportsSettlement:
3769 - serverConfigs.get(activeThread.environmentId)?.environment.capabilities
3770 - .threadSettlement === true,
3771 - target,
3772 - pinnedOrder: pinnedKeys,
3773 - pinnedKeysById,
3774 - reorderableKeys: draggableThreadKeys,
3775 - activeOrder: activeKeys,
3776 - activeKeysById,
3777 - activeReorderableKeys: activeReorderableThreadKeys,
3778 - activeTimeOrdered: workingShelfEnabled,
3779 - });
3780 - if (plan.kind === "none") return;
3781 - if (plan.kind === "settle" && settlingThreadKeysRef.current.has(activeKey)) return;
3782 - const assignments =
3783 - plan.kind === "pin"
3784 - ? [
3785 - ...(plan.orderKey === undefined ? [] : [{ id: activeKey, orderKey: plan.orderKey }]),
3786 - ...plan.extraAssignments,
3787 - ]
3788 - : plan.kind === "reorder-pinned" || plan.kind === "move-active"
3789 - ? plan.assignments
3790 - : [];
3791 - if (
3792 - !checkThreadOperations(
3793 - [activeKey, ...assignments.map(({ id }) => id)].flatMap((key) => {
3794 - const thread = threadByKey.get(key);
3795 - return thread ? [thread] : [];
3796 - }),
3797 - )
3569 + })();
3570 + const handleThreadDragEnd = (event: DragEndEvent) => {
3571 + const activeKey = String(event.active.id);
3572 + const activeSection = sectionByThreadKey.get(activeKey);
3573 + const target =
3574 + event.over === null
3575 + ? null
3576 + : resolveSidebarDropTarget(sidebarListItems, activeKey, String(event.over.id));
3577 + const activeThread = threadByKey.get(activeKey);
3578 + if (activeSection === undefined || target === null || activeThread === undefined) return;
3579 + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);
3580 + const plan = planSidebarThreadDrop({
3581 + activeKey,
3582 + activeSection,
3583 + activePinned: activeThread.pinnedAt != null,
3584 + activeSettled: activeThread.settledOverride === "settled",
3585 + supportsSettlement:
3586 + serverConfigs.get(activeThread.environmentId)?.environment.capabilities.threadSettlement ===
3587 + true,
3588 + target,
3589 + pinnedOrder: pinnedKeys,
3590 + pinnedKeysById,
3591 + reorderableKeys: draggableThreadKeys,
3592 + activeOrder: activeKeys,
3593 + activeKeysById,
3594 + activeReorderableKeys: activeReorderableThreadKeys,
3595 + activeTimeOrdered: workingShelfEnabled,
3596 + });
3597 + if (plan.kind === "none") return;
3598 + if (plan.kind === "settle" && settlingThreadKeysRef.current.has(activeKey)) return;
3599 + const assignments =
3600 + plan.kind === "pin"
3601 + ? [
3602 + ...(plan.orderKey === undefined ? [] : [{ id: activeKey, orderKey: plan.orderKey }]),
3603 + ...plan.extraAssignments,
3604 + ]
3605 + : plan.kind === "reorder-pinned" || plan.kind === "move-active"
3606 + ? plan.assignments
3607 + : [];
3608 + if (
3609 + !checkThreadOperations(
3610 + [activeKey, ...assignments.map(({ id }) => id)].flatMap((key) => {
3611 + const thread = threadByKey.get(key);
3612 + return thread ? [thread] : [];
3613 + }),
3614 )
3799 - return;
3800 - const drop = {
3801 - key: activeKey,
3802 - sourceSection: activeSection,
3803 - section: target.section,
3804 - occurredAt: new Date().toISOString(),
3805 - clearsSnooze:
3806 - plan.kind === "pin" ||
3807 - plan.kind === "settle" ||
3808 - (plan.kind === "move-active" && plan.unsnooze),
3809 - order: plan.kind === "settle" ? null : plan.order,
3810 - keysAtDrop: target.section === "active" ? activeKeysById : pinnedKeysById,
3811 - assignedKeys: new Map(assignments.map(({ id, orderKey }) => [id, orderKey])),
3615 + )
3616 + return;
3617 + const drop = {
3618 + key: activeKey,
3619 + sourceSection: activeSection,
3620 + section: target.section,
3621 + occurredAt: new Date().toISOString(),
3622 + clearsSnooze:
3623 + plan.kind === "pin" ||
3624 + plan.kind === "settle" ||
3625 + (plan.kind === "move-active" && plan.unsnooze),
3626 + order: plan.kind === "settle" ? null : plan.order,
3627 + keysAtDrop: target.section === "active" ? activeKeysById : pinnedKeysById,
3628 + assignedKeys: new Map(assignments.map(({ id, orderKey }) => [id, orderKey])),
3629 + };
3630 + setOptimisticDrop(drop);
3631 + void (async () => {
3632 + const run = async (
3633 + operation: Promise<AtomCommandResult<unknown, unknown>>,
3634 + title: string,
3635 + ) => {
3636 + const result = await operation;
3637 + if (result._tag === "Success") return true;
3638 + setOptimisticDrop((current) => (current === drop ? null : current));
3639 + if (!isAtomCommandInterrupted(result)) {
3640 + const error = squashAtomCommandFailure(result);
3641 + toastManager.add(
3642 + stackedThreadToast({
3643 + type: "error",
3644 + title,
3645 + description: error instanceof Error ? error.message : "An error occurred.",
3646 + }),
3647 + );
3648 + }
3649 + return false;
3650 };
3813 - setOptimisticDrop(drop);
3814 - void (async () => {
3815 - const run = async (
3816 - operation: Promise<AtomCommandResult<unknown, unknown>>,
3817 - title: string,
3818 - ) => {
3819 - const result = await operation;
3820 - if (result._tag === "Success") return true;
3821 - setOptimisticDrop((current) => (current === drop ? null : current));
3822 - if (!isAtomCommandInterrupted(result)) {
3823 - const error = squashAtomCommandFailure(result);
3824 - toastManager.add(
3825 - stackedThreadToast({
3826 - type: "error",
3827 - title,
3828 - description: error instanceof Error ? error.message : "An error occurred.",
3829 - }),
3830 - );
3831 - }
3832 - return false;
3833 - };
3834 - switch (plan.kind) {
3835 - case "settle": {
3836 - settlingThreadKeysRef.current.add(activeKey);
3837 - const navigateAfterSettle = planForwardNavigation(activeKey);
3838 - const settled = await run(settleThread(threadRef), "Failed to settle thread").finally(
3839 - () => settlingThreadKeysRef.current.delete(activeKey),
3840 - );
3841 - if (
3842 - settled &&
3843 - shouldNavigateAfterThreadPark({
3844 - threadKey: activeKey,
3845 - currentThreadKey: routeThreadKeyRef.current,
3846 - action: "settle",
3847 - now: new Date().toISOString(),
3848 - thread: readThreadShell(threadRef),
3849 - })
3850 - )
3851 - navigateAfterSettle?.();
3852 - return;
3853 - }
3854 - case "move-active":
3855 - if (plan.unpin && !(await run(unpinThread(threadRef), "Failed to unpin thread")))
3856 - return;
3857 - if (
3858 - plan.unsettle &&
3859 - !(await run(unsettleThread(threadRef), "Failed to un-settle thread"))
3860 - )
3861 - return;
3862 - if (plan.unsnooze && !(await run(unsnoozeThread(threadRef), "Failed to wake thread")))
3863 - return;
3864 - break;
3865 - case "pin":
3866 - if (
3867 - !(await run(
3868 - pinThread(
3869 - threadRef,
3870 - plan.orderKey === undefined ? {} : { orderKey: plan.orderKey },
3871 - ),
3872 - "Failed to pin thread",
3873 - ))
3874 - )
3875 - return;
3876 - break;
3877 - case "reorder-pinned":
3878 - break;
3651 + switch (plan.kind) {
3652 + case "settle": {
3653 + settlingThreadKeysRef.current.add(activeKey);
3654 + const navigateAfterSettle = planForwardNavigation(activeKey);
3655 + const settled = await run(settleThread(threadRef), "Failed to settle thread").finally(
3656 + () => settlingThreadKeysRef.current.delete(activeKey),
3657 + );
3658 + if (
3659 + settled &&
3660 + shouldNavigateAfterThreadPark({
3661 + threadKey: activeKey,
3662 + currentThreadKey: routeThreadKeyRef.current,
3663 + action: "settle",
3664 + now: new Date().toISOString(),
3665 + thread: readThreadShell(threadRef),
3666 + })
3667 + )
3668 + navigateAfterSettle?.();
3669 + return;
3670 }
3880 - const keyWrites = plan.kind === "pin" ? plan.extraAssignments : plan.assignments;
3881 - for (const assignment of keyWrites) {
3882 - const thread = threadByKey.get(assignment.id);
3883 - if (thread === undefined) continue;
3671 + case "move-active":
3672 + if (plan.unpin && !(await run(unpinThread(threadRef), "Failed to unpin thread"))) return;
3673 + if (
3674 + plan.unsettle &&
3675 + !(await run(unsettleThread(threadRef), "Failed to un-settle thread"))
3676 + )
3677 + return;
3678 + if (plan.unsnooze && !(await run(unsnoozeThread(threadRef), "Failed to wake thread")))
3679 + return;
3680 + break;
3681 + case "pin":
3682 if (
3683 !(await run(
3886 - (plan.kind === "move-active" ? reorderActiveThread : reorderPinnedThread)(
3887 - scopeThreadRef(thread.environmentId, thread.id),
3888 - assignment.orderKey,
3889 - ),
3890 - plan.kind === "move-active"
3891 - ? "Failed to reorder active threads"
3892 - : "Failed to reorder pinned threads",
3684 + pinThread(threadRef, plan.orderKey === undefined ? {} : { orderKey: plan.orderKey }),
3685 + "Failed to pin thread",
3686 ))
3687 )
3688 return;
3896 - }
3897 - })();
3898 - },
3899 - [
3900 - activeKeysById,
3901 - pinnedKeysById,
3902 - serverConfigs,
3903 - activeKeys,
3904 - activeReorderableThreadKeys,
3905 - draggableThreadKeys,
3906 - pinThread,
3907 - pinnedKeys,
3908 - planForwardNavigation,
3909 - reorderPinnedThread,
3910 - reorderActiveThread,
3911 - sectionByThreadKey,
3912 - settleThread,
3913 - sidebarListItems,
3914 - threadByKey,
3915 - unpinThread,
3916 - unsettleThread,
3917 - unsnoozeThread,
3918 - workingShelfEnabled,
3919 - ],
3920 - );
3921 - const snoozingThreadKeysRef = useRef(new Set<string>());
3922 - const performSnooze = useCallback(
3923 - async (
3924 - threadRef: ScopedThreadRef,
3925 - preset: Pick<SnoozePreset, "snoozedUntil">,
3926 - opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
3927 - ) => {
3928 - const threadKey = scopedThreadKey(threadRef);
3929 - if (snoozingThreadKeysRef.current.has(threadKey)) {
3930 - return { status: "skipped" } as const;
3689 + break;
3690 + case "reorder-pinned":
3691 + break;
3692 }
3932 - snoozingThreadKeysRef.current.add(threadKey);
3933 - try {
3934 - const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);
3935 - const result = await snoozeThread(threadRef, preset.snoozedUntil);
3936 - if (result._tag === "Failure") {
3937 - return isAtomCommandInterrupted(result)
3938 - ? ({ status: "interrupted" } as const)
3939 - : ({ status: "failure", error: squashAtomCommandFailure(result) } as const);
3940 - }
3693 + const keyWrites = plan.kind === "pin" ? plan.extraAssignments : plan.assignments;
3694 + for (const assignment of keyWrites) {
3695 + const thread = threadByKey.get(assignment.id);
3696 + if (thread === undefined) continue;
3697 if (
3942 - shouldNavigateAfterThreadPark({
3943 - threadKey,
3944 - currentThreadKey: routeThreadKeyRef.current,
3945 - action: "snooze",
3946 - now: new Date().toISOString(),
3947 - thread: readThreadShell(threadRef),
3948 - })
3949 - ) {
3950 - navigateAfterSnooze?.();
3951 - }
3952 - return { status: "success" } as const;
3953 - } finally {
3954 - snoozingThreadKeysRef.current.delete(threadKey);
3955 - }
3956 - },
3957 - [planForwardNavigation, snoozeThread],
3958 - );
3959 - const attemptSnooze = useCallback(
3960 - (
3961 - threadRef: ScopedThreadRef,
3962 - preset: Pick<SnoozePreset, "snoozedUntil">,
3963 - opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
3964 - ) => {
3965 - void (async () => {
3966 - const outcome = await performSnooze(threadRef, preset, opts);
3967 - if (outcome.status === "failure") {
3968 - toastManager.add(
3969 - stackedThreadToast({
3970 - type: "error",
3971 - title: "Failed to snooze thread",
3972 - description:
3973 - outcome.error instanceof Error ? outcome.error.message : "An error occurred.",
3974 - }),
3975 - );
3698 + !(await run(
3699 + (plan.kind === "move-active" ? reorderActiveThread : reorderPinnedThread)(
3700 + scopeThreadRef(thread.environmentId, thread.id),
3701 + assignment.orderKey,
3702 + ),
3703 + plan.kind === "move-active"
3704 + ? "Failed to reorder active threads"
3705 + : "Failed to reorder pinned threads",
3706 + ))
3707 + )
3708 return;
3977 - }
3978 - })();
3979 - },
3980 - [performSnooze],
3981 - );
3709 + }
3710 + })();
3711 + };
3712 + const performSnooze = async (
3713 + threadRef: ScopedThreadRef,
3714 + preset: Pick<SnoozePreset, "snoozedUntil">,
3715 + opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
3716 + ) => {
3717 + const threadKey = scopedThreadKey(threadRef);
3718 + if (snoozingThreadKeysRef.current.has(threadKey)) {
3719 + return { status: "skipped" } as const;
3720 + }
3721 + snoozingThreadKeysRef.current.add(threadKey);
3722 + const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);
3723 + const result = await snoozeThread(threadRef, preset.snoozedUntil);
3724 + snoozingThreadKeysRef.current.delete(threadKey);
3725 + if (result._tag === "Failure") {
3726 + return isAtomCommandInterrupted(result)
3727 + ? ({ status: "interrupted" } as const)
3728 + : ({ status: "failure", error: squashAtomCommandFailure(result) } as const);
3729 + }
3730 + if (
3731 + shouldNavigateAfterThreadPark({
3732 + threadKey,
3733 + currentThreadKey: routeThreadKeyRef.current,
3734 + action: "snooze",
3735 + now: new Date().toISOString(),
3736 + thread: readThreadShell(threadRef),
3737 + })
3738 + ) {
3739 + navigateAfterSnooze?.();
3740 + }
3741 + return { status: "success" } as const;
3742 + };
3743 + const attemptSnooze = (
3744 + threadRef: ScopedThreadRef,
3745 + preset: Pick<SnoozePreset, "snoozedUntil">,
3746 + opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
3747 + ) => {
3748 + void (async () => {
3749 + const outcome = await performSnooze(threadRef, preset, opts);
3750 + if (outcome.status === "failure") {
3751 + toastManager.add(
3752 + stackedThreadToast({
3753 + type: "error",
3754 + title: "Failed to snooze thread",
3755 + description:
3756 + outcome.error instanceof Error ? outcome.error.message : "An error occurred.",
3757 + }),
3758 + );
3759 + return;
3760 + }
3761 + })();
3762 + };
3763
3983 - const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
3764 const handleMultiSelectContextMenu = useStableCallback(
3765 async (position: { x: number; y: number }) => {
3766 const api = readLocalApi();
@@ -4602,8 +4382,6 @@ export default function Sidebar() {
4382 threadByKey,
4383 ]);
4384
4605 - const shortcutModifiers = useShortcutModifierState();
4606 - const terminalFocused = useTerminalFocus();
4385 const shouldShowJumpHintsNow = shouldShowThreadJumpHintsForModifiers(
4386 shortcutModifiers,
4387 keybindings,
@@ -4622,23 +4400,20 @@ export default function Sidebar() {
4400 updateThreadJumpHintsVisibility(shouldShowJumpHintsNow);
4401 }, [shouldShowJumpHintsNow, updateThreadJumpHintsVisibility]);
4402
4625 - const handleNewThreadClick = useCallback(
4626 - (event?: ReactMouseEvent) => {
4627 - if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) {
4628 - if (isMobile) setOpenMobile(false);
4629 - void startNewThreadFromContext({
4630 - activeDraftThread: newThreadContext.activeDraftThread,
4631 - activeThread: newThreadContext.activeThread ?? undefined,
4632 - defaultProjectRef: newThreadContext.defaultProjectRef,
4633 - handleNewThread: newThreadContext.handleNewThread,
4634 - });
4635 - return;
4636 - }
4403 + const handleNewThreadClick = (event?: ReactMouseEvent) => {
4404 + if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) {
4405 if (isMobile) setOpenMobile(false);
4638 - openCommandPalette({ open: "new-thread-in" });
4639 - },
4640 - [isMobile, newThreadContext, projectGroups.length, setOpenMobile],
4641 - );
4406 + void startNewThreadFromContext({
4407 + activeDraftThread: newThreadContext.activeDraftThread,
4408 + activeThread: newThreadContext.activeThread ?? undefined,
4409 + defaultProjectRef: newThreadContext.defaultProjectRef,
4410 + handleNewThread: newThreadContext.handleNewThread,
4411 + });
4412 + return;
4413 + }
4414 + if (isMobile) setOpenMobile(false);
4415 + openCommandPalette({ open: "new-thread-in" });
4416 + };
4417
4418 const newThreadShortcutLabel =
4419 shortcutLabelForCommand(keybindings, "chat.new") ??
@@ -5001,10 +4776,6 @@ export default function Sidebar() {
4776 onUnpin={attemptUnpin}
4777 onAcknowledgeWoke={acknowledgeWoke}
4778 onFileDropThreads={handleThreadFileDrop}
5004 - changeRequestSnapshot={
5005 - changeRequestSnapshotByKey.get(threadKey) ?? null
5006 - }
5007 - onChangeRequestSnapshot={setThreadChangeRequestSnapshot}
4779 />
4780 );
4781 };
apps/web/src/components/ThreadStatusIndicators.tsx
-22
@@ -17,7 +17,6 @@ import {
17 import { Atom } from "effect/reactivity";
18 import { FolderGit2Icon, TerminalIcon } from "lucide-react";
19 import { useCallback, useMemo } from "react";
20 -import { appAtomRegistry } from "../rpc/atomRegistry";
20 import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
21 import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
22 import { useProject } from "../state/entities";
@@ -536,27 +535,6 @@ export function threadChangeRequestSnapshotsEqual(
535 );
536 }
537
539 -export function setThreadChangeRequestSnapshot(
540 - threadKey: string,
541 - snapshot: ThreadChangeRequestSnapshot | null,
542 -): void {
543 - appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
544 - const existing = current.get(threadKey);
545 - if (snapshot === null) {
546 - if (existing === undefined) return [false, current];
547 - const next = new Map(current);
548 - next.delete(threadKey);
549 - return [true, next];
550 - }
551 - if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
552 - return [false, current];
553 - }
554 - const next = new Map(current);
555 - next.set(threadKey, snapshot);
556 - return [true, next];
557 - });
558 -}
559 -
538 export function nextThreadChangeRequestSnapshot(input: {
539 threadBranch: string | null;
540 gitStatus: VcsStatusResult | null;