diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index ee73b57051..d57f9e5c5d 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -1,5 +1,22 @@ import { autoAnimate } from "@formkit/auto-animate"; import { useAtomValue } from "@effect/atom-react"; +import { + closestCenter, + DndContext, + KeyboardSensor, + PointerSensor, + type DragEndEvent, + useSensor, + useSensors, +} from "@dnd-kit/core"; +import { + SortableContext, + sortableKeyboardCoordinates, + useSortable, + verticalListSortingStrategy, +} from "@dnd-kit/sortable"; +import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers"; +import { CSS } from "@dnd-kit/utilities"; import { canSnooze, effectiveSettled, @@ -26,6 +43,7 @@ import { FolderIcon, FolderPlusIcon, GitBranchIcon, + GripVerticalIcon, EllipsisIcon, MessageSquareIcon, PlusIcon, @@ -46,7 +64,7 @@ import { useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, - type ReactNode, + type ComponentProps, } from "react"; import { useParams, useRouter } from "@tanstack/react-router"; @@ -81,7 +99,11 @@ import { type SidebarProjectGroupMember, type SidebarProjectSnapshot, } from "../sidebarProjectGrouping"; -import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; +import { + legacyProjectCwdPreferenceKey, + type SidebarThreadSection, + useUiStateStore, +} from "../uiStateStore"; import { useThreadSelectionStore } from "../threadSelectionStore"; import { useThreadActions } from "../hooks/useThreadActions"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; @@ -383,6 +405,17 @@ function SnoozePopoverButton(props: { ); } +type SortableThreadBindings = Pick< + ReturnType, + | "attributes" + | "isDragging" + | "listeners" + | "setActivatorNodeRef" + | "setNodeRef" + | "transform" + | "transition" +>; + const SidebarV2Row = memo(function SidebarV2Row(props: { thread: SidebarThreadSummary; variant: "card" | "slim"; @@ -420,6 +453,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void; onUnsnooze: (threadRef: ScopedThreadRef) => void; onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void; + sortable: SortableThreadBindings | null; }) { const { isRenaming, @@ -707,6 +741,29 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { "opacity-70 transition-opacity hover:opacity-100", ); + const dragHandle = props.sortable ? ( + + ) : null; + + const sortableStyle = props.sortable + ? { + transform: CSS.Translate.toString(props.sortable.transform), + transition: props.sortable.transition, + } + : undefined; + const title = isRenaming ? ( } > + {dragHandle} {/* Settled history recedes: dimmed favicon at rest, restored on hover so the tail stays scannable when you're hunting. */}
+ {dragHandle} ; + +function SortableSidebarV2Row( + props: Omit & { + threadKey: string; + section: SidebarThreadSection; + }, +) { + const { threadKey, section, ...rowProps } = props; + const sortable = useSortable({ id: threadKey, data: { section } }); + return ; +} + function latestTurnDiff( thread: SidebarThreadSummary, ): { insertions: number; deletions: number } | null { @@ -1171,6 +1253,8 @@ const SidebarV2SearchResultRow = memo(function SidebarV2SearchResultRow(props: { export default function SidebarV2() { const projects = useProjects(); const projectOrder = useUiStateStore((store) => store.projectOrder); + const threadOrderBySection = useUiStateStore((store) => store.threadOrderBySection); + const reorderThreads = useUiStateStore((store) => store.reorderThreads); const threads = useThreadShells(); const router = useRouter(); const { isMobile, setOpenMobile } = useSidebar(); @@ -1557,7 +1641,12 @@ export default function SidebarV2() { // merging, no optimistic holds. Archived threads remain hidden here — // archive keeps its original "remove from sidebar" meaning. const serverConfigs = useAtomValue(environmentServerConfigsAtom); - const { activeThreads, snoozedThreads, settledThreads, snoozeNow } = useMemo(() => { + const { + activeThreads: defaultActiveThreads, + snoozedThreads: defaultSnoozedThreads, + settledThreads: defaultSettledThreads, + snoozeNow, + } = useMemo(() => { const now = `${nowMinute}:00.000Z`; // Snooze classification uses a REAL clock, not the quantized minute: // wake times are second-precise and a woken thread must not linger on @@ -1620,6 +1709,34 @@ export default function SidebarV2() { threads, ]); + const activeThreads = useMemo( + () => + orderItemsByPreferredIds({ + items: defaultActiveThreads, + preferredIds: threadOrderBySection.active, + getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + }), + [defaultActiveThreads, threadOrderBySection.active], + ); + const snoozedThreads = useMemo( + () => + orderItemsByPreferredIds({ + items: defaultSnoozedThreads, + preferredIds: threadOrderBySection.snoozed, + getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + }), + [defaultSnoozedThreads, threadOrderBySection.snoozed], + ); + const settledThreads = useMemo( + () => + orderItemsByPreferredIds({ + items: defaultSettledThreads, + preferredIds: threadOrderBySection.settled, + getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + }), + [defaultSettledThreads, threadOrderBySection.settled], + ); + const threadSearchInputRef = useRef(null); const [threadSearchQuery, setThreadSearchQuery] = useState(""); const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0); @@ -1648,14 +1765,14 @@ export default function SidebarV2() { }, [activeSearchResultIndex, isSearchingThreads, threadSearchResultOrderKey]); // Arm a timeout for the earliest upcoming wake so the shelf empties the - // moment a snooze expires instead of on the next minute tick. Sorted - // soonest-first, so entry 0 is the boundary. + // moment a snooze expires instead of on the next minute tick. Manual + // ordering means the earliest wake is not necessarily the first row. useEffect(() => { - const nextWakeAtMs = - snoozedThreads.length > 0 && snoozedThreads[0]?.snoozedUntil != null - ? Date.parse(snoozedThreads[0].snoozedUntil) - : Number.NaN; - if (Number.isNaN(nextWakeAtMs)) return; + const nextWakeAtMs = snoozedThreads.reduce((earliest, thread) => { + const wakeAtMs = Date.parse(thread.snoozedUntil ?? ""); + return Number.isNaN(wakeAtMs) ? earliest : Math.min(earliest, wakeAtMs); + }, Number.POSITIVE_INFINITY); + if (!Number.isFinite(nextWakeAtMs)) return; // setTimeout delays are signed 32-bit: anything larger overflows and // fires immediately, turning a far-future wake (event-condition snoozes // synced from elsewhere) into a tight re-arm loop. Clamped, the timer @@ -1729,6 +1846,54 @@ export default function SidebarV2() { return routeThread === undefined ? [] : [routeThread]; }, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]); + const threadKeysBySection = useMemo>( + () => ({ + active: activeThreads.map((thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + ), + snoozed: snoozedThreads.map((thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + ), + settled: settledThreads.map((thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + ), + }), + [activeThreads, settledThreads, snoozedThreads], + ); + const visibleSnoozedThreadKeys = useMemo( + () => + visibleSnoozedThreads.map((thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + ), + [visibleSnoozedThreads], + ); + const renderedSettledThreadKeys = useMemo( + () => + renderedSettledThreads.map((thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + ), + [renderedSettledThreads], + ); + const threadDragSensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: 6 } }), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + const handleThreadDragEnd = useCallback( + (event: DragEndEvent) => { + if (event.over === null) return; + const activeSection = event.active.data.current?.section as SidebarThreadSection | undefined; + const overSection = event.over.data.current?.section as SidebarThreadSection | undefined; + if (activeSection === undefined || activeSection !== overSection) return; + reorderThreads( + activeSection, + threadKeysBySection[activeSection], + String(event.active.id), + String(event.over.id), + ); + }, + [reorderThreads, threadKeysBySection], + ); + const orderedThreads = useMemo( () => [...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads], [activeThreads, visibleSnoozedThreads, renderedSettledThreads], @@ -2580,6 +2745,70 @@ export default function SidebarV2() { const newThreadShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal") ?? shortcutLabelForCommand(keybindings, "chat.new"); + + const renderThreadRow = (thread: EnvironmentThreadShell, section: SidebarThreadSection) => { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + // Settled and snoozed are the ONLY things that collapse a row: every + // other thread is a full card. Density comes from users (or the auto + // rules) actually parking work, not from the sidebar second-guessing + // what still matters. + const isCard = section === "active"; + const rowVariant = isCard ? "card" : "slim"; + return ( + + ); + }; + return ( <> @@ -2819,183 +3048,91 @@ export default function SidebarV2() { closeDelay={0} timeout={400} > -
    - {(() => { - const renderThreadRow = ( - thread: EnvironmentThreadShell, - section: "active" | "snoozed" | "settled", - ) => { - const threadKey = scopedThreadKey( - scopeThreadRef(thread.environmentId, thread.id), - ); - // Settled and snoozed are the ONLY things that collapse a - // row: every other thread is a full card. Density comes - // from users (or the auto rules) actually parking work, - // not from the sidebar second-guessing what still matters. - const isCard = section === "active"; - const rowVariant = isCard ? "card" : "slim"; - return ( - - ); - }; - const items: ReactNode[] = activeThreads.map((thread) => - renderThreadRow(thread, "active"), - ); - // Snoozed shelf: between the inbox and Settled — out of the - // way, never gone. The header always renders while anything - // is snoozed (the count is the whole footprint when - // collapsed); rows only when expanded. Vanishes entirely at - // count 0. - if (snoozedThreads.length > 0) { - items.push( -
  • +
      + + {activeThreads.map((thread) => renderThreadRow(thread, "active"))} + + {snoozedThreads.length > 0 ? ( +
    • + -
    • , - ); - for (const thread of visibleSnoozedThreads) { - items.push(renderThreadRow(thread, "snoozed")); - } - } - if (settledThreads.length > 0) { - items.push( -
    • + {snoozedShelfExpanded ? "Snoozed" : `Snoozed (${snoozedThreads.length})`} + + + + +
    • + ) : null} + + {visibleSnoozedThreads.map((thread) => renderThreadRow(thread, "snoozed"))} + + {settledThreads.length > 0 ? ( +
    • + -
    • , - ); - } - for (const thread of renderedSettledThreads) { - items.push(renderThreadRow(thread, "settled")); - } - return items; - })()} - {settledShelfExpanded && hiddenSettledCount > 0 ? ( -
    • - -
    • - ) : null} -
    + + {settledShelfExpanded ? "Settled" : `Settled (${settledThreads.length})`} + + + + +
  • + ) : null} + + {renderedSettledThreads.map((thread) => renderThreadRow(thread, "settled"))} + + {settledShelfExpanded && hiddenSettledCount > 0 ? ( +
  • + +
  • + ) : null} +
+ ) : null} {!isSearchingThreads && diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 3045028735..1577aadd0c 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -10,6 +10,7 @@ import { type PersistedUiState, persistState, reorderProjects, + reorderThreads, resolveProjectExpanded, setDefaultAdvertisedEndpointKey, setProjectExpanded, @@ -21,6 +22,7 @@ function makeUiState(overrides: Partial = {}): UiState { return { projectExpandedById: {}, projectOrder: [], + threadOrderBySection: { active: [], snoozed: [], settled: [] }, threadLastVisitedAtById: {}, threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, @@ -116,6 +118,53 @@ describe("uiStateStore pure functions", () => { ); }); + it("reorders threads independently within each sidebar section", () => { + const state = makeUiState({ + threadOrderBySection: { + active: ["active-a", "active-b"], + snoozed: ["snoozed-a"], + settled: ["settled-a"], + }, + }); + + const next = reorderThreads( + state, + "active", + ["active-a", "active-b", "active-c"], + "active-c", + "active-a", + ); + + expect(next.threadOrderBySection).toEqual({ + active: ["active-c", "active-a", "active-b"], + snoozed: ["snoozed-a"], + settled: ["settled-a"], + }); + expect( + reorderThreads(next, "active", next.threadOrderBySection.active, "active-a", "active-a"), + ).toBe(next); + }); + + it("preserves hidden thread positions when reordering a filtered section", () => { + const state = makeUiState({ + threadOrderBySection: { + active: ["hidden-a", "visible-a", "hidden-b", "visible-b"], + snoozed: [], + settled: [], + }, + }); + + expect( + reorderThreads( + state, + "active", + ["visible-a", "visible-b", "visible-new"], + "visible-new", + "visible-a", + ).threadOrderBySection.active, + ).toEqual(["hidden-a", "visible-new", "hidden-b", "visible-a", "visible-b"]); + }); + it("stores explicit changed-file expansion choices", () => { const threadId = ThreadId.make("thread-1"); const collapsed = setThreadChangedFilesExpanded(makeUiState(), threadId, "turn-1", false); @@ -154,6 +203,10 @@ describe("parsePersistedState", () => { invalid: "no" as unknown as boolean, }, projectOrder: ["physical-b", "", "physical-a", "physical-b"], + threadOrderBySection: { + active: ["environment:thread-2", "", "environment:thread-1"], + snoozed: ["environment:thread-3", "environment:thread-3"], + }, threadLastVisitedAtById: { "environment:thread-1": "2026-02-25T12:35:00.000Z", invalid: "not-a-date", @@ -173,6 +226,11 @@ describe("parsePersistedState", () => { logical: false, }, projectOrder: ["physical-b", "physical-a"], + threadOrderBySection: { + active: ["environment:thread-2", "environment:thread-1"], + snoozed: ["environment:thread-3"], + settled: [], + }, threadLastVisitedAtById: { "environment:thread-1": "2026-02-25T12:35:00.000Z", }, @@ -270,6 +328,11 @@ describe("uiStateStore persistence", () => { logical: false, }, projectOrder: ["physical-b", "physical-a"], + threadOrderBySection: { + active: ["environment:thread-2", "environment:thread-1"], + snoozed: ["environment:thread-3"], + settled: [], + }, threadLastVisitedAtById: { "environment:thread-1": "2026-02-25T12:35:00.000Z", }, @@ -292,6 +355,11 @@ describe("uiStateStore persistence", () => { logical: false, }, projectOrder: ["physical-b", "physical-a"], + threadOrderBySection: { + active: ["environment:thread-2", "environment:thread-1"], + snoozed: ["environment:thread-3"], + settled: [], + }, threadLastVisitedAtById: { "environment:thread-1": "2026-02-25T12:35:00.000Z", }, diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index 5d744d540a..6dc0689e03 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -17,9 +17,12 @@ const LEGACY_PERSISTED_STATE_KEYS = [ "codething:renderer-state:v1", ] as const; +export type SidebarThreadSection = "active" | "snoozed" | "settled"; + export interface PersistedUiState { projectExpandedById?: Record; projectOrder?: string[]; + threadOrderBySection?: Partial>; threadLastVisitedAtById?: Record; collapsedProjectCwds?: string[]; expandedProjectCwds?: string[]; @@ -35,6 +38,7 @@ export interface UiProjectState { } export interface UiThreadState { + threadOrderBySection: Record; threadLastVisitedAtById: Record; threadChangedFilesExpandedById: Record>; } @@ -48,6 +52,7 @@ export interface UiState extends UiProjectState, UiThreadState, UiEndpointState const initialState: UiState = { projectExpandedById: {}, projectOrder: [], + threadOrderBySection: { active: [], snoozed: [], settled: [] }, threadLastVisitedAtById: {}, threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, @@ -72,6 +77,16 @@ function sanitizeStringArray(value: unknown): string[] { ]; } +function sanitizeThreadOrderBySection( + value: PersistedUiState["threadOrderBySection"], +): Record { + return { + active: sanitizeStringArray(value?.active), + snoozed: sanitizeStringArray(value?.snoozed), + settled: sanitizeStringArray(value?.settled), + }; +} + function sanitizeBooleanRecord(value: unknown): Record { if (!value || typeof value !== "object") { return {}; @@ -125,6 +140,7 @@ export function parsePersistedState(parsed: PersistedUiState): UiState { return { projectExpandedById, projectOrder, + threadOrderBySection: sanitizeThreadOrderBySection(parsed.threadOrderBySection), threadLastVisitedAtById: sanitizeTimestampRecord(parsed.threadLastVisitedAtById), threadChangedFilesExpandedById: parsed.threadChangedFilesExpansionVersion === THREAD_CHANGED_FILES_EXPANSION_VERSION @@ -203,6 +219,7 @@ export function persistState(state: UiState): void { JSON.stringify({ projectExpandedById, projectOrder: state.projectOrder, + threadOrderBySection: state.threadOrderBySection, threadLastVisitedAtById: state.threadLastVisitedAtById, defaultAdvertisedEndpointKey: state.defaultAdvertisedEndpointKey, threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION, @@ -337,6 +354,43 @@ export function setProjectExpanded( }; } +export function reorderThreads( + state: UiState, + section: SidebarThreadSection, + currentThreadOrder: readonly string[], + draggedThreadId: string, + targetThreadId: string, +): UiState { + const draggedIndex = currentThreadOrder.indexOf(draggedThreadId); + const targetIndex = currentThreadOrder.indexOf(targetThreadId); + if (draggedIndex < 0 || targetIndex < 0 || draggedIndex === targetIndex) { + return state; + } + + const reorderedVisibleThreads = [...currentThreadOrder]; + const [dragged] = reorderedVisibleThreads.splice(draggedIndex, 1); + reorderedVisibleThreads.splice(targetIndex, 0, dragged!); + + // A project filter can hide threads from this section. Keep those ids in + // their existing slots while replacing only the visible ids, then append + // any visible threads that did not have a persisted slot yet. + const visibleThreadIds = new Set(currentThreadOrder); + let nextVisibleIndex = 0; + const threadOrder = state.threadOrderBySection[section].map((threadId) => { + if (!visibleThreadIds.has(threadId)) return threadId; + return reorderedVisibleThreads[nextVisibleIndex++]!; + }); + threadOrder.push(...reorderedVisibleThreads.slice(nextVisibleIndex)); + + return { + ...state, + threadOrderBySection: { + ...state.threadOrderBySection, + [section]: threadOrder, + }, + }; +} + export function reorderProjects( state: UiState, currentProjectOrder: readonly string[], @@ -387,6 +441,12 @@ interface UiStateStore extends UiState { setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void; setDefaultAdvertisedEndpointKey: (key: string | null) => void; setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void; + reorderThreads: ( + section: SidebarThreadSection, + currentThreadOrder: readonly string[], + draggedThreadId: string, + targetThreadId: string, + ) => void; reorderProjects: ( currentProjectOrder: readonly string[], draggedProjectIds: readonly string[], @@ -406,6 +466,10 @@ export const useUiStateStore = create((set) => ({ set((state) => setDefaultAdvertisedEndpointKey(state, key)), setProjectExpanded: (projectIds, expanded) => set((state) => setProjectExpanded(state, projectIds, expanded)), + reorderThreads: (section, currentThreadOrder, draggedThreadId, targetThreadId) => + set((state) => + reorderThreads(state, section, currentThreadOrder, draggedThreadId, targetThreadId), + ), reorderProjects: (currentProjectOrder, draggedProjectIds, targetProjectIds) => set((state) => reorderProjects(state, currentProjectOrder, draggedProjectIds, targetProjectIds),