diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 018e89d14b..a3c733a610 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -2,11 +2,12 @@ import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, + GripVerticalIcon, RocketIcon, SquarePenIcon, TerminalIcon, } from "lucide-react"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { DEFAULT_MODEL, type DesktopUpdateState, @@ -261,6 +262,7 @@ export default function Sidebar() { const threads = useStore((store) => store.threads); const markThreadUnread = useStore((store) => store.markThreadUnread); const toggleProject = useStore((store) => store.toggleProject); + const reorderProjects = useStore((store) => store.reorderProjects); const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft); const getDraftThreadByProjectId = useComposerDraftStore( (store) => store.getDraftThreadByProjectId, @@ -297,6 +299,8 @@ export default function Sidebar() { const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState< ReadonlySet >(() => new Set()); + const [draggedProjectId, setDraggedProjectId] = useState(null); + const [projectDropIndex, setProjectDropIndex] = useState(null); const renamingCommittedRef = useRef(false); const renamingInputRef = useRef(null); const [desktopUpdateState, setDesktopUpdateState] = useState(null); @@ -982,6 +986,11 @@ export default function Sidebar() { ); + const resetProjectDrag = () => { + setDraggedProjectId(null); + setProjectDropIndex(null); + }; + return ( <> {isElectron ? ( @@ -1018,7 +1027,7 @@ export default function Sidebar() { - {projects.map((project) => { + {projects.map((project, projectIndex) => { const projectThreads = threads .filter((thread) => thread.projectId === project.id) .toSorted((a, b) => { @@ -1034,246 +1043,298 @@ export default function Sidebar() { : projectThreads; return ( - { - if (open === project.expanded) return; - toggleProject(project.id); - }} - > - -
- - } - onContextMenu={(event) => { - event.preventDefault(); - void handleProjectContextMenu(project.id, { - x: event.clientX, - y: event.clientY, - }); - }} - > - - - - {project.name} - - - - + {draggedProjectId !== null && projectDropIndex === projectIndex && ( + +
+ + )} + { + if (open === project.expanded) return; + toggleProject(project.id); + }} + > + +
+ - } - showOnHover - className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground" - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - void handleNewThread(project.id); + { + setDraggedProjectId(project.id); + setProjectDropIndex(null); + event.dataTransfer.effectAllowed = "move"; + event.dataTransfer.setData("text/plain", project.cwd); }} - > - - + onDragEnd={() => { + resetProjectDrag(); + }} + onDragOver={(event) => { + if (draggedProjectId === null) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + const bounds = event.currentTarget.getBoundingClientRect(); + const nextDropIndex = + event.clientY < bounds.top + bounds.height / 2 + ? projectIndex + : projectIndex + 1; + if (projectDropIndex !== nextDropIndex) { + setProjectDropIndex(nextDropIndex); + } + }} + onDrop={(event) => { + if (draggedProjectId === null) return; + event.preventDefault(); + const bounds = event.currentTarget.getBoundingClientRect(); + const destinationIndex = + event.clientY < bounds.top + bounds.height / 2 + ? projectIndex + : projectIndex + 1; + reorderProjects(draggedProjectId, destinationIndex); + resetProjectDrag(); + }} + /> } - /> - - {newThreadShortcutLabel - ? `New thread (${newThreadShortcutLabel})` - : "New thread"} - - -
- - - - {visibleThreads.map((thread) => { - const isActive = routeThreadId === thread.id; - const threadStatus = threadStatusPill( - thread, - pendingApprovalByThreadId.get(thread.id) === true, - ); - const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null); - const terminalStatus = terminalStatusFromRunningIds( - selectThreadTerminalState(terminalStateByThreadId, thread.id) - .runningTerminalIds, - ); - - return ( - - } - size="sm" - isActive={isActive} - className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${ - isActive - ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50" - : "text-muted-foreground" - }`} - onClick={() => { - void navigate({ - to: "/$threadId", - params: { threadId: thread.id }, - }); - }} - onKeyDown={(event) => { - if (event.key !== "Enter" && event.key !== " ") return; + onContextMenu={(event) => { + event.preventDefault(); + void handleProjectContextMenu(project.id, { + x: event.clientX, + y: event.clientY, + }); + }} + > + + + + + {project.name} + + + + + } + showOnHover + className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground" + onClick={(event) => { event.preventDefault(); - void navigate({ - to: "/$threadId", - params: { threadId: thread.id }, - }); - }} - onContextMenu={(event) => { - event.preventDefault(); - void handleThreadContextMenu(thread.id, { - x: event.clientX, - y: event.clientY, - }); + event.stopPropagation(); + void handleNewThread(project.id); }} > -
- {prStatus && ( - - { - openPrLink(event, prStatus.url); - }} - > - - - } - /> - {prStatus.tooltip} - - )} - {threadStatus && ( - + + + } + /> + + {newThreadShortcutLabel + ? `New thread (${newThreadShortcutLabel})` + : "New thread"} + + +
+ + + + {visibleThreads.map((thread) => { + const isActive = routeThreadId === thread.id; + const threadStatus = threadStatusPill( + thread, + pendingApprovalByThreadId.get(thread.id) === true, + ); + const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null); + const terminalStatus = terminalStatusFromRunningIds( + selectThreadTerminalState(terminalStateByThreadId, thread.id) + .runningTerminalIds, + ); + + return ( + + } + size="sm" + isActive={isActive} + className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${ + isActive + ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50" + : "text-muted-foreground" + }`} + onClick={() => { + void navigate({ + to: "/$threadId", + params: { threadId: thread.id }, + }); + }} + onKeyDown={(event) => { + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + void navigate({ + to: "/$threadId", + params: { threadId: thread.id }, + }); + }} + onContextMenu={(event) => { + event.preventDefault(); + void handleThreadContextMenu(thread.id, { + x: event.clientX, + y: event.clientY, + }); + }} + > +
+ {prStatus && ( + + { + openPrLink(event, prStatus.url); + }} + > + + + } + /> + {prStatus.tooltip} + + )} + {threadStatus && ( + + {threadStatus.label} + + )} + {renamingThreadId === thread.id ? ( + { + if (el && renamingInputRef.current !== el) { + renamingInputRef.current = el; + el.focus(); + el.select(); + } + }} + className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5" + value={renamingTitle} + onChange={(e) => setRenamingTitle(e.target.value)} + onKeyDown={(e) => { + e.stopPropagation(); + if (e.key === "Enter") { + e.preventDefault(); + renamingCommittedRef.current = true; + void commitRename(thread.id, renamingTitle, thread.title); + } else if (e.key === "Escape") { + e.preventDefault(); + renamingCommittedRef.current = true; + cancelRename(); + } + }} + onBlur={() => { + if (!renamingCommittedRef.current) { + void commitRename(thread.id, renamingTitle, thread.title); + } + }} + onClick={(e) => e.stopPropagation()} /> - {threadStatus.label} - - )} - {renamingThreadId === thread.id ? ( - { - if (el && renamingInputRef.current !== el) { - renamingInputRef.current = el; - el.focus(); - el.select(); - } - }} - className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5" - value={renamingTitle} - onChange={(e) => setRenamingTitle(e.target.value)} - onKeyDown={(e) => { - e.stopPropagation(); - if (e.key === "Enter") { - e.preventDefault(); - renamingCommittedRef.current = true; - void commitRename(thread.id, renamingTitle, thread.title); - } else if (e.key === "Escape") { - e.preventDefault(); - renamingCommittedRef.current = true; - cancelRename(); - } - }} - onBlur={() => { - if (!renamingCommittedRef.current) { - void commitRename(thread.id, renamingTitle, thread.title); - } - }} - onClick={(e) => e.stopPropagation()} - /> - ) : ( - - {thread.title} - - )} -
-
- {terminalStatus && ( + ) : ( + + {thread.title} + + )} +
+
+ {terminalStatus && ( + + + + )} - + {formatRelativeTime(thread.createdAt)} - )} - - {formatRelativeTime(thread.createdAt)} - -
+
+ + + ); + })} + + {hasHiddenThreads && !isThreadListExpanded && ( + + } + size="sm" + className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" + onClick={() => { + expandThreadListForProject(project.id); + }} + > + Show more - ); - })} - - {hasHiddenThreads && !isThreadListExpanded && ( - - } - size="sm" - className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" - onClick={() => { - expandThreadListForProject(project.id); - }} - > - Show more - - - )} - {hasHiddenThreads && isThreadListExpanded && ( - - } - size="sm" - className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" - onClick={() => { - collapseThreadListForProject(project.id); - }} - > - Show less - - - )} - - -
- + )} + {hasHiddenThreads && isThreadListExpanded && ( + + } + size="sm" + className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" + onClick={() => { + collapseThreadListForProject(project.id); + }} + > + Show less + + + )} + + + + + {draggedProjectId !== null && + projectDropIndex === projectIndex + 1 && + projectIndex === projects.length - 1 && ( + +
+ + )} + ); })} diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 2b29dd8ff8..ddb59d7357 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -1,8 +1,19 @@ -import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { ProjectId, ThreadId, TurnId, type OrchestrationReadModel } from "@t3tools/contracts"; import { describe, expect, it } from "vitest"; -import { markThreadUnread, type AppState } from "./store"; -import type { Thread } from "./types"; +import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store"; +import type { Project, Thread } from "./types"; + +function makeProject(id: string, cwd = `/tmp/${id}`): Project { + return { + id: ProjectId.makeUnsafe(id), + name: id, + cwd, + model: "gpt-5-codex", + expanded: true, + scripts: [], + }; +} function makeThread(overrides: Partial = {}): Thread { return { @@ -24,25 +35,72 @@ function makeThread(overrides: Partial = {}): Thread { }; } -function makeState(thread: Thread): AppState { +function makeState(thread: Thread, projects: Project[] = [makeProject("project-1")]): AppState { return { - projects: [ - { - id: ProjectId.makeUnsafe("project-1"), - name: "Project", - cwd: "/tmp/project", - model: "gpt-5-codex", - expanded: true, - scripts: [], - }, - ], + projects, threads: [thread], threadsHydrated: true, runtimeMode: "full-access", }; } +function makeReadModel(projects: Array<{ id: string; cwd?: string }>): OrchestrationReadModel { + return { + snapshotSequence: 1, + projects: projects.map((project) => ({ + id: ProjectId.makeUnsafe(project.id), + title: project.id, + workspaceRoot: project.cwd ?? `/tmp/${project.id}`, + defaultModel: "gpt-5-codex", + scripts: [], + createdAt: "2026-02-25T12:00:00.000Z", + updatedAt: "2026-02-25T12:00:00.000Z", + deletedAt: null, + })), + threads: [], + updatedAt: "2026-02-25T12:00:00.000Z", + }; +} + describe("store pure functions", () => { + it("reorderProjects moves a project to the end insertion slot", () => { + const initialState = makeState(makeThread(), [ + makeProject("project-1"), + makeProject("project-2"), + makeProject("project-3"), + ]); + + const next = reorderProjects(initialState, ProjectId.makeUnsafe("project-1"), 3); + + expect(next.projects.map((project) => project.id)).toEqual([ + ProjectId.makeUnsafe("project-2"), + ProjectId.makeUnsafe("project-3"), + ProjectId.makeUnsafe("project-1"), + ]); + }); + + it("syncServerReadModel keeps the existing local project order and appends new projects", () => { + const initialState = makeState(makeThread(), [ + makeProject("project-b", "/tmp/project-b"), + makeProject("project-a", "/tmp/project-a"), + ]); + + const next = syncServerReadModel( + initialState, + makeReadModel([ + { id: "project-a", cwd: "/tmp/project-a" }, + { id: "project-b", cwd: "/tmp/project-b" }, + { id: "project-c", cwd: "/tmp/project-c" }, + ]), + ); + + expect(next.projects.map((project) => project.cwd)).toEqual([ + "/tmp/project-b", + "/tmp/project-a", + "/tmp/project-c", + ]); + }); + it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => { const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z"; const initialState = makeState( diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index e761bc30d4..97a433ac1f 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -44,24 +44,32 @@ const initialState: AppState = { runtimeMode: DEFAULT_RUNTIME_MODE, }; const persistedExpandedProjectCwds = new Set(); +const persistedProjectOrderCwds: string[] = []; // ── Persist helpers ────────────────────────────────────────────────── function readPersistedState(): AppState { if (typeof window === "undefined") return initialState; try { + persistedExpandedProjectCwds.clear(); + persistedProjectOrderCwds.length = 0; const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); if (!raw) return initialState; const parsed = JSON.parse(raw) as { runtimeMode?: RuntimeMode; expandedProjectCwds?: string[]; + projectOrderCwds?: string[]; }; - persistedExpandedProjectCwds.clear(); for (const cwd of parsed.expandedProjectCwds ?? []) { if (typeof cwd === "string" && cwd.length > 0) { persistedExpandedProjectCwds.add(cwd); } } + for (const cwd of parsed.projectOrderCwds ?? []) { + if (typeof cwd === "string" && cwd.length > 0) { + persistedProjectOrderCwds.push(cwd); + } + } return { ...initialState, runtimeMode: @@ -84,6 +92,7 @@ function persistState(state: AppState): void { expandedProjectCwds: state.projects .filter((project) => project.expanded) .map((project) => project.cwd), + projectOrderCwds: state.projects.map((project) => project.cwd), }), ); for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) { @@ -115,7 +124,7 @@ function mapProjectsFromReadModel( incoming: OrchestrationReadModel["projects"], previous: Project[], ): Project[] { - return incoming.map((project) => { + const mappedProjects = incoming.map((project) => { const existing = previous.find((entry) => entry.id === project.id) ?? previous.find((entry) => entry.cwd === project.workspaceRoot); @@ -132,6 +141,25 @@ function mapProjectsFromReadModel( scripts: project.scripts.map((script) => ({ ...script })), }; }); + const preferredProjectOrderCwds = + previous.length > 0 ? previous.map((project) => project.cwd) : persistedProjectOrderCwds; + if (preferredProjectOrderCwds.length === 0 || mappedProjects.length <= 1) { + return mappedProjects; + } + const orderByCwd = new Map( + preferredProjectOrderCwds.map((cwd, index) => [cwd, index] as const), + ); + const orderedProjects = mappedProjects.toSorted((left, right) => { + const leftIndex = orderByCwd.get(left.cwd); + const rightIndex = orderByCwd.get(right.cwd); + if (leftIndex === undefined && rightIndex === undefined) return 0; + if (leftIndex === undefined) return 1; + if (rightIndex === undefined) return -1; + return leftIndex - rightIndex; + }); + return orderedProjects.every((project, index) => project === mappedProjects[index]) + ? mappedProjects + : orderedProjects; } function toLegacySessionStatus( @@ -333,6 +361,24 @@ export function setProjectExpanded( return changed ? { ...state, projects } : state; } +export function reorderProjects( + state: AppState, + sourceProjectId: Project["id"], + destinationIndex: number, +): AppState { + const sourceIndex = state.projects.findIndex((project) => project.id === sourceProjectId); + if (sourceIndex === -1) return state; + const boundedDestinationIndex = Math.max(0, Math.min(destinationIndex, state.projects.length)); + const normalizedDestinationIndex = + sourceIndex < boundedDestinationIndex ? boundedDestinationIndex - 1 : boundedDestinationIndex; + if (normalizedDestinationIndex === sourceIndex) return state; + const projects = [...state.projects]; + const [movedProject] = projects.splice(sourceIndex, 1); + if (!movedProject) return state; + projects.splice(normalizedDestinationIndex, 0, movedProject); + return { ...state, projects }; +} + export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState { const threads = updateThread(state.threads, threadId, (t) => { if (t.error === error) return t; @@ -373,6 +419,7 @@ interface AppStore extends AppState { markThreadUnread: (threadId: ThreadId) => void; toggleProject: (projectId: Project["id"]) => void; setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void; + reorderProjects: (sourceProjectId: Project["id"], destinationIndex: number) => void; setError: (threadId: ThreadId, error: string | null) => void; setThreadBranch: ( threadId: ThreadId, @@ -394,6 +441,8 @@ export const useStore = create((set) => ({ set((state) => toggleProject(state, projectId)), setProjectExpanded: (projectId, expanded) => set((state) => setProjectExpanded(state, projectId, expanded)), + reorderProjects: (sourceProjectId, destinationIndex) => + set((state) => reorderProjects(state, sourceProjectId, destinationIndex)), setError: (threadId, error) => set((state) => setError(state, threadId, error)), setThreadBranch: (threadId, branch, worktreePath) => @@ -402,7 +451,7 @@ export const useStore = create((set) => ({ set((state) => setRuntimeMode(state, mode)), })); -// Persist on every state change (only runtimeMode + expandedProjectCwds) +// Persist on every state change (runtimeMode + sidebar project UI state) useStore.subscribe((state) => persistState(state)); export function StoreProvider({ children }: { children: ReactNode }) {