Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Sort sidebar projects and threads by recency (#1372)
Julius Marminge28afb14004bb
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 69decd359..2b1759da3 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -19,6 +19,7 @@"@dnd-kit/modifiers": "^9.0.0","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",+ "@formkit/auto-animate": "^0.9.0","@lexical/react": "^0.41.0","@pierre/diffs": "^1.1.0-beta.16","@t3tools/contracts": "workspace:*",diff --git a/apps/web/src/appSettings.test.ts b/apps/web/src/appSettings.test.tsindex 16b0a840f..74d5b29df 100644--- a/apps/web/src/appSettings.test.ts+++ b/apps/web/src/appSettings.test.ts@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";import {AppSettingsSchema,+ DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,+ DEFAULT_SIDEBAR_THREAD_SORT_ORDER,DEFAULT_TIMESTAMP_FORMAT,getAppModelOptions,getCustomModelOptionsByProvider,@@ -111,6 +113,16 @@ describe("timestamp format defaults", () => {});});+describe("sidebar sort defaults", () => {+ it("defaults project sorting to updated_at", () => {+ expect(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER).toBe("updated_at");+ });++ it("defaults thread sorting to updated_at", () => {+ expect(DEFAULT_SIDEBAR_THREAD_SORT_ORDER).toBe("updated_at");+ });+});+describe("provider-specific custom models", () => {it("includes provider-specific custom slugs in non-codex model lists", () => {const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);@@ -245,6 +257,8 @@ describe("AppSettingsSchema", () => {defaultThreadEnvMode: "local",confirmThreadDelete: false,enableAssistantStreaming: false,+ sidebarProjectSortOrder: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,+ sidebarThreadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,timestampFormat: DEFAULT_TIMESTAMP_FORMAT,customCodexModels: [],customClaudeModels: [],diff --git a/apps/web/src/appSettings.ts b/apps/web/src/appSettings.tsindex cb7b5fd9c..be9c37698 100644--- a/apps/web/src/appSettings.ts+++ b/apps/web/src/appSettings.ts@@ -21,6 +21,12 @@ export const MAX_CUSTOM_MODEL_LENGTH = 256;export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);export type TimestampFormat = typeof TimestampFormat.Type;export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";+export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);+export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;+export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";+export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);+export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;+export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";export type ProviderCustomModelConfig = {provider: ProviderKind;@@ -58,6 +64,12 @@ export const AppSettingsSchema = Schema.Struct({confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),+ sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(+ withDefaults(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),+ ),+ sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(+ withDefaults(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),+ ),timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex 19d6f3060..6925b5391 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -1,13 +1,24 @@import { describe, expect, it } from "vitest";import {+ getVisibleThreadsForProject,+ getProjectSortTimestamp,hasUnseenCompletion,resolveProjectStatusIndicator,resolveSidebarNewThreadEnvMode,resolveThreadRowClassName,resolveThreadStatusPill,shouldClearThreadSelectionOnMouseDown,+ sortProjectsForSidebar,+ sortThreadsForSidebar,} from "./Sidebar.logic";+import { ProjectId, ThreadId } from "@t3tools/contracts";+import {+ DEFAULT_INTERACTION_MODE,+ DEFAULT_RUNTIME_MODE,+ type Project,+ type Thread,+} from "../types";function makeLatestTurn(overrides?: {completedAt?: string | null;@@ -281,3 +292,338 @@ describe("resolveProjectStatusIndicator", () => {).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });});});++describe("getVisibleThreadsForProject", () => {+ it("includes the active thread even when it falls below the folded preview", () => {+ const threads = Array.from({ length: 8 }, (_, index) =>+ makeThread({+ id: ThreadId.makeUnsafe(`thread-${index + 1}`),+ title: `Thread ${index + 1}`,+ }),+ );++ const result = getVisibleThreadsForProject({+ threads,+ activeThreadId: ThreadId.makeUnsafe("thread-8"),+ isThreadListExpanded: false,+ previewLimit: 6,+ });++ expect(result.hasHiddenThreads).toBe(true);+ expect(result.visibleThreads.map((thread) => thread.id)).toEqual([+ ThreadId.makeUnsafe("thread-1"),+ ThreadId.makeUnsafe("thread-2"),+ ThreadId.makeUnsafe("thread-3"),+ ThreadId.makeUnsafe("thread-4"),+ ThreadId.makeUnsafe("thread-5"),+ ThreadId.makeUnsafe("thread-6"),+ ThreadId.makeUnsafe("thread-8"),+ ]);+ });++ it("returns all threads when the list is expanded", () => {+ const threads = Array.from({ length: 8 }, (_, index) =>+ makeThread({+ id: ThreadId.makeUnsafe(`thread-${index + 1}`),+ }),+ );++ const result = getVisibleThreadsForProject({+ threads,+ activeThreadId: ThreadId.makeUnsafe("thread-8"),+ isThreadListExpanded: true,+ previewLimit: 6,+ });++ expect(result.hasHiddenThreads).toBe(true);+ expect(result.visibleThreads.map((thread) => thread.id)).toEqual(+ threads.map((thread) => thread.id),+ );+ });+});++function makeProject(overrides: Partial<Project> = {}): Project {+ return {+ id: ProjectId.makeUnsafe("project-1"),+ name: "Project",+ cwd: "/tmp/project",+ model: "gpt-5.4",+ expanded: true,+ createdAt: "2026-03-09T10:00:00.000Z",+ updatedAt: "2026-03-09T10:00:00.000Z",+ scripts: [],+ ...overrides,+ };+}++function makeThread(overrides: Partial<Thread> = {}): Thread {+ return {+ id: ThreadId.makeUnsafe("thread-1"),+ codexThreadId: null,+ projectId: ProjectId.makeUnsafe("project-1"),+ title: "Thread",+ model: "gpt-5.4",+ runtimeMode: DEFAULT_RUNTIME_MODE,+ interactionMode: DEFAULT_INTERACTION_MODE,+ session: null,+ messages: [],+ proposedPlans: [],+ error: null,+ createdAt: "2026-03-09T10:00:00.000Z",+ updatedAt: "2026-03-09T10:00:00.000Z",+ latestTurn: null,+ branch: null,+ worktreePath: null,+ turnDiffSummaries: [],+ activities: [],+ ...overrides,+ };+}++describe("sortThreadsForSidebar", () => {+ it("sorts threads by the latest user message in recency mode", () => {+ const sorted = sortThreadsForSidebar(+ [+ makeThread({+ id: ThreadId.makeUnsafe("thread-1"),+ createdAt: "2026-03-09T10:00:00.000Z",+ updatedAt: "2026-03-09T10:10:00.000Z",+ messages: [+ {+ id: "message-1" as never,+ role: "user",+ text: "older",+ createdAt: "2026-03-09T10:01:00.000Z",+ streaming: false,+ completedAt: "2026-03-09T10:01:00.000Z",+ },+ ],+ }),+ makeThread({+ id: ThreadId.makeUnsafe("thread-2"),+ createdAt: "2026-03-09T10:05:00.000Z",+ updatedAt: "2026-03-09T10:05:00.000Z",+ messages: [+ {+ id: "message-2" as never,+ role: "user",+ text: "newer",+ createdAt: "2026-03-09T10:06:00.000Z",+ streaming: false,+ completedAt: "2026-03-09T10:06:00.000Z",+ },+ ],+ }),+ ],+ "updated_at",+ );++ expect(sorted.map((thread) => thread.id)).toEqual([+ ThreadId.makeUnsafe("thread-2"),+ ThreadId.makeUnsafe("thread-1"),+ ]);+ });++ it("falls back to thread timestamps when there is no user message", () => {+ const sorted = sortThreadsForSidebar(+ [+ makeThread({+ id: ThreadId.makeUnsafe("thread-1"),+ createdAt: "2026-03-09T10:00:00.000Z",+ updatedAt: "2026-03-09T10:01:00.000Z",+ messages: [+ {+ id: "message-1" as never,+ role: "assistant",+ text: "assistant only",+ createdAt: "2026-03-09T10:02:00.000Z",+ streaming: false,+ completedAt: "2026-03-09T10:02:00.000Z",+ },+ ],+ }),+ makeThread({+ id: ThreadId.makeUnsafe("thread-2"),+ createdAt: "2026-03-09T10:05:00.000Z",+ updatedAt: "2026-03-09T10:05:00.000Z",+ messages: [],+ }),+ ],+ "updated_at",+ );++ expect(sorted.map((thread) => thread.id)).toEqual([+ ThreadId.makeUnsafe("thread-2"),+ ThreadId.makeUnsafe("thread-1"),+ ]);+ });++ it("falls back to id ordering when threads have no sortable timestamps", () => {+ const sorted = sortThreadsForSidebar(+ [+ makeThread({+ id: ThreadId.makeUnsafe("thread-1"),+ createdAt: "" as never,+ updatedAt: undefined,+ messages: [],+ }),+ makeThread({+ id: ThreadId.makeUnsafe("thread-2"),+ createdAt: "" as never,+ updatedAt: undefined,+ messages: [],+ }),+ ],+ "updated_at",+ );++ expect(sorted.map((thread) => thread.id)).toEqual([+ ThreadId.makeUnsafe("thread-2"),+ ThreadId.makeUnsafe("thread-1"),+ ]);+ });++ it("can sort threads by createdAt when configured", () => {+ const sorted = sortThreadsForSidebar(+ [+ makeThread({+ id: ThreadId.makeUnsafe("thread-1"),+ createdAt: "2026-03-09T10:05:00.000Z",+ updatedAt: "2026-03-09T10:05:00.000Z",+ }),+ makeThread({+ id: ThreadId.makeUnsafe("thread-2"),+ createdAt: "2026-03-09T10:00:00.000Z",+ updatedAt: "2026-03-09T10:10:00.000Z",+ }),+ ],+ "created_at",+ );++ expect(sorted.map((thread) => thread.id)).toEqual([+ ThreadId.makeUnsafe("thread-1"),+ ThreadId.makeUnsafe("thread-2"),+ ]);+ });+});++describe("sortProjectsForSidebar", () => {+ it("sorts projects by the most recent user message across their threads", () => {+ const projects = [+ makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "Older project" }),+ makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Newer project" }),+ ];+ const threads = [+ makeThread({+ projectId: ProjectId.makeUnsafe("project-1"),+ updatedAt: "2026-03-09T10:20:00.000Z",+ messages: [+ {+ id: "message-1" as never,+ role: "user",+ text: "older project user message",+ createdAt: "2026-03-09T10:01:00.000Z",+ streaming: false,+ completedAt: "2026-03-09T10:01:00.000Z",+ },+ ],+ }),+ makeThread({+ id: ThreadId.makeUnsafe("thread-2"),+ projectId: ProjectId.makeUnsafe("project-2"),+ updatedAt: "2026-03-09T10:05:00.000Z",+ messages: [+ {+ id: "message-2" as never,+ role: "user",+ text: "newer project user message",+ createdAt: "2026-03-09T10:05:00.000Z",+ streaming: false,+ completedAt: "2026-03-09T10:05:00.000Z",+ },+ ],+ }),+ ];++ const sorted = sortProjectsForSidebar(projects, threads, "updated_at");++ expect(sorted.map((project) => project.id)).toEqual([+ ProjectId.makeUnsafe("project-2"),+ ProjectId.makeUnsafe("project-1"),+ ]);+ });++ it("falls back to project timestamps when a project has no threads", () => {+ const sorted = sortProjectsForSidebar(+ [+ makeProject({+ id: ProjectId.makeUnsafe("project-1"),+ name: "Older project",+ updatedAt: "2026-03-09T10:01:00.000Z",+ }),+ makeProject({+ id: ProjectId.makeUnsafe("project-2"),+ name: "Newer project",+ updatedAt: "2026-03-09T10:05:00.000Z",+ }),+ ],+ [],+ "updated_at",+ );++ expect(sorted.map((project) => project.id)).toEqual([+ ProjectId.makeUnsafe("project-2"),+ ProjectId.makeUnsafe("project-1"),+ ]);+ });++ it("falls back to name and id ordering when projects have no sortable timestamps", () => {+ const sorted = sortProjectsForSidebar(+ [+ makeProject({+ id: ProjectId.makeUnsafe("project-2"),+ name: "Beta",+ createdAt: undefined,+ updatedAt: undefined,+ }),+ makeProject({+ id: ProjectId.makeUnsafe("project-1"),+ name: "Alpha",+ createdAt: undefined,+ updatedAt: undefined,+ }),+ ],+ [],+ "updated_at",+ );++ expect(sorted.map((project) => project.id)).toEqual([+ ProjectId.makeUnsafe("project-1"),+ ProjectId.makeUnsafe("project-2"),+ ]);+ });++ it("preserves manual project ordering", () => {+ const projects = [+ makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }),+ makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First" }),+ ];++ const sorted = sortProjectsForSidebar(projects, [], "manual");++ expect(sorted.map((project) => project.id)).toEqual([+ ProjectId.makeUnsafe("project-2"),+ ProjectId.makeUnsafe("project-1"),+ ]);+ });++ it("returns the project timestamp when no threads are present", () => {+ const timestamp = getProjectSortTimestamp(+ makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),+ [],+ "updated_at",+ );++ expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));+ });+});diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex ef338dab6..9ce12d3b8 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -1,3 +1,4 @@+import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../appSettings";import type { Thread } from "../types";import { cn } from "../lib/utils";import {@@ -8,6 +9,13 @@ import {export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";export type SidebarNewThreadEnvMode = "local" | "worktree";+type SidebarProject = {+ id: string;+ name: string;+ createdAt?: string | undefined;+ updatedAt?: string | undefined;+};+type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;export interface ThreadStatusPill {label:@@ -178,3 +186,147 @@ export function resolveProjectStatusIndicator(return highestPriorityStatus;}++export function getVisibleThreadsForProject(input: {+ threads: readonly Thread[];+ activeThreadId: Thread["id"] | undefined;+ isThreadListExpanded: boolean;+ previewLimit: number;+}): {+ hasHiddenThreads: boolean;+ visibleThreads: Thread[];+} {+ const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;+ const hasHiddenThreads = threads.length > previewLimit;++ if (!hasHiddenThreads || isThreadListExpanded) {+ return {+ hasHiddenThreads,+ visibleThreads: [...threads],+ };+ }++ const previewThreads = threads.slice(0, previewLimit);+ if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {+ return {+ hasHiddenThreads: true,+ visibleThreads: previewThreads,+ };+ }++ const activeThread = threads.find((thread) => thread.id === activeThreadId);+ if (!activeThread) {+ return {+ hasHiddenThreads: true,+ visibleThreads: previewThreads,+ };+ }++ const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));++ return {+ hasHiddenThreads: true,+ visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),+ };+}++function toSortableTimestamp(iso: string | undefined): number | null {+ if (!iso) return null;+ const ms = Date.parse(iso);+ return Number.isFinite(ms) ? ms : null;+}++function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {+ let latestUserMessageTimestamp: number | null = null;++ for (const message of thread.messages) {+ if (message.role !== "user") continue;+ const messageTimestamp = toSortableTimestamp(message.createdAt);+ if (messageTimestamp === null) continue;+ latestUserMessageTimestamp =+ latestUserMessageTimestamp === null+ ? messageTimestamp+ : Math.max(latestUserMessageTimestamp, messageTimestamp);+ }++ if (latestUserMessageTimestamp !== null) {+ return latestUserMessageTimestamp;+ }++ return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;+}++function getThreadSortTimestamp(+ thread: SidebarThreadSortInput,+ sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,+): number {+ if (sortOrder === "created_at") {+ return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;+ }+ return getLatestUserMessageTimestamp(thread);+}++export function sortThreadsForSidebar<+ T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,+>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {+ return threads.toSorted((left, right) => {+ const rightTimestamp = getThreadSortTimestamp(right, sortOrder);+ const leftTimestamp = getThreadSortTimestamp(left, sortOrder);+ const byTimestamp =+ rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;+ if (byTimestamp !== 0) return byTimestamp;+ return right.id.localeCompare(left.id);+ });+}++export function getProjectSortTimestamp(+ project: SidebarProject,+ projectThreads: readonly SidebarThreadSortInput[],+ sortOrder: Exclude<SidebarProjectSortOrder, "manual">,+): number {+ if (projectThreads.length > 0) {+ return projectThreads.reduce(+ (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),+ Number.NEGATIVE_INFINITY,+ );+ }++ if (sortOrder === "created_at") {+ return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;+ }+ return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;+}++export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(+ projects: readonly TProject[],+ threads: readonly TThread[],+ sortOrder: SidebarProjectSortOrder,+): TProject[] {+ if (sortOrder === "manual") {+ return [...projects];+ }++ const threadsByProjectId = new Map<string, TThread[]>();+ for (const thread of threads) {+ const existing = threadsByProjectId.get(thread.projectId) ?? [];+ existing.push(thread);+ threadsByProjectId.set(thread.projectId, existing);+ }++ return [...projects].toSorted((left, right) => {+ const rightTimestamp = getProjectSortTimestamp(+ right,+ threadsByProjectId.get(right.id) ?? [],+ sortOrder,+ );+ const leftTimestamp = getProjectSortTimestamp(+ left,+ threadsByProjectId.get(left.id) ?? [],+ sortOrder,+ );+ const byTimestamp =+ rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;+ if (byTimestamp !== 0) return byTimestamp;+ return left.name.localeCompare(right.name) || left.id.localeCompare(right.id);+ });+}diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex e1d126b06..a8a58a13b 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -1,5 +1,6 @@import {ArrowLeftIcon,+ ArrowUpDownIcon,ChevronRightIcon,FolderIcon,GitPullRequestIcon,@@ -10,6 +11,7 @@ import {TerminalIcon,TriangleAlertIcon,} from "lucide-react";+import { autoAnimate } from "@formkit/auto-animate";import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent } from "react";import {DndContext,@@ -36,7 +38,11 @@ import {} from "@t3tools/contracts";import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";import { useLocation, useNavigate, useParams } from "@tanstack/react-router";-import { useAppSettings } from "../appSettings";+import {+ type SidebarProjectSortOrder,+ type SidebarThreadSortOrder,+ useAppSettings,+} from "../appSettings";import { isElectron } from "../env";import { APP_STAGE_LABEL, APP_VERSION } from "../branding";import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";@@ -64,6 +70,7 @@ import {import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";import { Button } from "./ui/button";import { Collapsible, CollapsibleContent } from "./ui/collapsible";+import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";import {SidebarContent,@@ -84,16 +91,33 @@ import { useThreadSelectionStore } from "../threadSelectionStore";import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";import { isNonEmpty as isNonEmptyString } from "effect/String";import {+ getVisibleThreadsForProject,resolveProjectStatusIndicator,resolveSidebarNewThreadEnvMode,resolveThreadRowClassName,resolveThreadStatusPill,shouldClearThreadSelectionOnMouseDown,+ sortProjectsForSidebar,+ sortThreadsForSidebar,} from "./Sidebar.logic";import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];const THREAD_PREVIEW_LIMIT = 6;+const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {+ updated_at: "Last user message",+ created_at: "Created at",+ manual: "Manual",+};+const SIDEBAR_THREAD_SORT_LABELS: Record<SidebarThreadSortOrder, string> = {+ updated_at: "Last user message",+ created_at: "Created at",+};+const SIDEBAR_LIST_ANIMATION_OPTIONS = {+ duration: 180,+ easing: "ease-out",+} as const;+const loadedProjectFaviconSrcs = new Set<string>();function formatRelativeTime(iso: string): string {const diff = Date.now() - new Date(iso).getTime();@@ -204,9 +228,10 @@ function getServerHttpOrigin(): string {const serverHttpOrigin = getServerHttpOrigin();function ProjectFavicon({ cwd }: { cwd: string }) {- const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");-const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;+ const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>+ loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",+ );if (status === "error") {return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;@@ -217,23 +242,106 @@ function ProjectFavicon({ cwd }: { cwd: string }) {src={src}alt=""className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}- onLoad={() => setStatus("loaded")}+ onLoad={() => {+ loadedProjectFaviconSrcs.add(src);+ setStatus("loaded");+ }}onError={() => setStatus("error")}/>);}-type SortableProjectHandleProps = Pick<ReturnType<typeof useSortable>, "attributes" | "listeners">;+type SortableProjectHandleProps = Pick<+ ReturnType<typeof useSortable>,+ "attributes" | "listeners" | "setActivatorNodeRef"+>;++function ProjectSortMenu({+ projectSortOrder,+ threadSortOrder,+ onProjectSortOrderChange,+ onThreadSortOrderChange,+}: {+ projectSortOrder: SidebarProjectSortOrder;+ threadSortOrder: SidebarThreadSortOrder;+ onProjectSortOrderChange: (sortOrder: SidebarProjectSortOrder) => void;+ onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;+}) {+ return (+ <Menu>+ <Tooltip>+ <TooltipTrigger+ render={+ <MenuTrigger className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground" />+ }+ >+ <ArrowUpDownIcon className="size-3.5" />+ </TooltipTrigger>+ <TooltipPopup side="right">Sort projects</TooltipPopup>+ </Tooltip>+ <MenuPopup align="end" side="bottom" className="min-w-44">+ <MenuGroup>+ <div className="px-2 py-1 sm:text-xs font-medium text-muted-foreground">+ Sort projects+ </div>+ <MenuRadioGroup+ value={projectSortOrder}+ onValueChange={(value) => {+ onProjectSortOrderChange(value as SidebarProjectSortOrder);+ }}+ >+ {(Object.entries(SIDEBAR_SORT_LABELS) as Array<[SidebarProjectSortOrder, string]>).map(+ ([value, label]) => (+ <MenuRadioItem key={value} value={value} className="min-h-7 py-1 sm:text-xs">+ {label}+ </MenuRadioItem>+ ),+ )}+ </MenuRadioGroup>+ </MenuGroup>+ <MenuGroup>+ <div className="px-2 pt-2 pb-1 sm:text-xs font-medium text-muted-foreground">+ Sort threads+ </div>+ <MenuRadioGroup+ value={threadSortOrder}+ onValueChange={(value) => {+ onThreadSortOrderChange(value as SidebarThreadSortOrder);+ }}+ >+ {(+ Object.entries(SIDEBAR_THREAD_SORT_LABELS) as Array<[SidebarThreadSortOrder, string]>+ ).map(([value, label]) => (+ <MenuRadioItem key={value} value={value} className="min-h-7 py-1 sm:text-xs">+ {label}+ </MenuRadioItem>+ ))}+ </MenuRadioGroup>+ </MenuGroup>+ </MenuPopup>+ </Menu>+ );+}function SortableProjectItem({projectId,+ disabled = false,children,}: {projectId: ProjectId;+ disabled?: boolean;children: (handleProps: SortableProjectHandleProps) => React.ReactNode;}) {- const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver } =- useSortable({ id: projectId });+ const {+ attributes,+ listeners,+ setActivatorNodeRef,+ setNodeRef,+ transform,+ transition,+ isDragging,+ isOver,+ } = useSortable({ id: projectId, disabled });return (<liref={setNodeRef}@@ -247,7 +355,7 @@ function SortableProjectItem({data-sidebar="menu-item"data-slot="sidebar-menu-item">- {children({ attributes, listeners })}+ {children({ attributes, listeners, setActivatorNodeRef })}</li>);}@@ -272,7 +380,7 @@ export default function Sidebar() {);const navigate = useNavigate();const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });- const { settings: appSettings } = useAppSettings();+ const { settings: appSettings, updateSettings } = useAppSettings();const { handleNewThread } = useHandleNewThread();const routeThreadId = useParams({strict: false,@@ -385,13 +493,10 @@ export default function Sidebar() {const focusMostRecentThreadForProject = useCallback((projectId: ProjectId) => {- const latestThread = threads- .filter((thread) => thread.projectId === projectId)- .toSorted((a, b) => {- const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();- if (byDate !== 0) return byDate;- return b.id.localeCompare(a.id);- })[0];+ const latestThread = sortThreadsForSidebar(+ threads.filter((thread) => thread.projectId === projectId),+ appSettings.sidebarThreadSortOrder,+ )[0];if (!latestThread) return;void navigate({@@ -399,7 +504,7 @@ export default function Sidebar() {params: { threadId: latestThread.id },});},- [navigate, threads],+ [appSettings.sidebarThreadSortOrder, navigate, threads],);const addProjectFromPath = useCallback(@@ -931,6 +1036,10 @@ export default function Sidebar() {const handleProjectDragEnd = useCallback((event: DragEndEvent) => {+ if (appSettings.sidebarProjectSortOrder !== "manual") {+ dragInProgressRef.current = false;+ return;+ }dragInProgressRef.current = false;const { active, over } = event;if (!over || active.id === over.id) return;@@ -939,22 +1048,361 @@ export default function Sidebar() {if (!activeProject || !overProject) return;reorderProjects(activeProject.id, overProject.id);},- [projects, reorderProjects],+ [appSettings.sidebarProjectSortOrder, projects, reorderProjects],);- const handleProjectDragStart = useCallback((_event: DragStartEvent) => {- dragInProgressRef.current = true;- suppressProjectClickAfterDragRef.current = true;- }, []);+ const handleProjectDragStart = useCallback(+ (_event: DragStartEvent) => {+ if (appSettings.sidebarProjectSortOrder !== "manual") {+ return;+ }+ dragInProgressRef.current = true;+ suppressProjectClickAfterDragRef.current = true;+ },+ [appSettings.sidebarProjectSortOrder],+ );const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => {dragInProgressRef.current = false;}, []);+ const animatedProjectListsRef = useRef(new WeakSet<HTMLElement>());+ const attachProjectListAutoAnimateRef = useCallback((node: HTMLElement | null) => {+ if (!node || animatedProjectListsRef.current.has(node)) {+ return;+ }+ autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);+ animatedProjectListsRef.current.add(node);+ }, []);++ const animatedThreadListsRef = useRef(new WeakSet<HTMLElement>());+ const attachThreadListAutoAnimateRef = useCallback((node: HTMLElement | null) => {+ if (!node || animatedThreadListsRef.current.has(node)) {+ return;+ }+ autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);+ animatedThreadListsRef.current.add(node);+ }, []);+const handleProjectTitlePointerDownCapture = useCallback(() => {suppressProjectClickAfterDragRef.current = false;}, []);+ const sortedProjects = useMemo(+ () => sortProjectsForSidebar(projects, threads, appSettings.sidebarProjectSortOrder),+ [appSettings.sidebarProjectSortOrder, projects, threads],+ );+ const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual";++ function renderProjectItem(+ project: (typeof sortedProjects)[number],+ dragHandleProps: SortableProjectHandleProps | null,+ ) {+ const projectThreads = sortThreadsForSidebar(+ threads.filter((thread) => thread.projectId === project.id),+ appSettings.sidebarThreadSortOrder,+ );+ const projectStatus = resolveProjectStatusIndicator(+ projectThreads.map((thread) =>+ resolveThreadStatusPill({+ thread,+ hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,+ hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,+ }),+ ),+ );+ const activeThreadId = routeThreadId ?? undefined;+ const isThreadListExpanded = expandedThreadListsByProject.has(project.id);+ const pinnedCollapsedThread =+ !project.expanded && activeThreadId+ ? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)+ : null;+ const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;+ const { hasHiddenThreads, visibleThreads } = getVisibleThreadsForProject({+ threads: projectThreads,+ activeThreadId,+ isThreadListExpanded,+ previewLimit: THREAD_PREVIEW_LIMIT,+ });+ const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);+ const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleThreads;+ const renderThreadRow = (thread: (typeof projectThreads)[number]) => {+ const isActive = routeThreadId === thread.id;+ const isSelected = selectedThreadIds.has(thread.id);+ const isHighlighted = isActive || isSelected;+ const threadStatus = resolveThreadStatusPill({+ thread,+ hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,+ hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,+ });+ const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);+ const terminalStatus = terminalStatusFromRunningIds(+ selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,+ );++ return (+ <SidebarMenuSubItem key={thread.id} className="w-full" data-thread-item>+ <SidebarMenuSubButton+ render={<div role="button" tabIndex={0} />}+ size="sm"+ isActive={isActive}+ className={resolveThreadRowClassName({+ isActive,+ isSelected,+ })}+ onClick={(event) => {+ handleThreadClick(event, thread.id, orderedProjectThreadIds);+ }}+ onKeyDown={(event) => {+ if (event.key !== "Enter" && event.key !== " ") return;+ event.preventDefault();+ if (selectedThreadIds.size > 0) {+ clearSelection();+ }+ setSelectionAnchor(thread.id);+ void navigate({+ to: "/$threadId",+ params: { threadId: thread.id },+ });+ }}+ onContextMenu={(event) => {+ event.preventDefault();+ if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {+ void handleMultiSelectContextMenu({+ x: event.clientX,+ y: event.clientY,+ });+ } else {+ if (selectedThreadIds.size > 0) {+ clearSelection();+ }+ void handleThreadContextMenu(thread.id, {+ x: event.clientX,+ y: event.clientY,+ });+ }+ }}+ >+ <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">+ {prStatus && (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ aria-label={prStatus.tooltip}+ className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}+ onClick={(event) => {+ openPrLink(event, prStatus.url);+ }}+ >+ <GitPullRequestIcon className="size-3" />+ </button>+ }+ />+ <TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>+ </Tooltip>+ )}+ {threadStatus && (+ <span+ className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}+ >+ <span+ className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${+ threadStatus.pulse ? "animate-pulse" : ""+ }`}+ />+ <span className="hidden md:inline">{threadStatus.label}</span>+ </span>+ )}+ {renamingThreadId === thread.id ? (+ <input+ ref={(el) => {+ 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()}+ />+ ) : (+ <span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>+ )}+ </div>+ <div className="ml-auto flex shrink-0 items-center gap-1.5">+ {terminalStatus && (+ <span+ role="img"+ aria-label={terminalStatus.label}+ title={terminalStatus.label}+ className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}+ >+ <TerminalIcon+ className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}+ />+ </span>+ )}+ <span+ className={`text-[10px] ${+ isHighlighted+ ? "text-foreground/72 dark:text-foreground/82"+ : "text-muted-foreground/40"+ }`}+ >+ {formatRelativeTime(thread.updatedAt ?? thread.createdAt)}+ </span>+ </div>+ </SidebarMenuSubButton>+ </SidebarMenuSubItem>+ );+ };++ return (+ <Collapsible className="group/collapsible" open={shouldShowThreadPanel}>+ <div className="group/project-header relative">+ <SidebarMenuButton+ ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined}+ size="sm"+ className={`gap-2 px-2 py-1.5 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground ${+ isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"+ }`}+ {...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}+ {...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})}+ onPointerDownCapture={handleProjectTitlePointerDownCapture}+ onClick={(event) => handleProjectTitleClick(event, project.id)}+ onKeyDown={(event) => handleProjectTitleKeyDown(event, project.id)}+ onContextMenu={(event) => {+ event.preventDefault();+ void handleProjectContextMenu(project.id, {+ x: event.clientX,+ y: event.clientY,+ });+ }}+ >+ {!project.expanded && projectStatus ? (+ <span+ aria-hidden="true"+ title={projectStatus.label}+ className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`}+ >+ <span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">+ <span+ className={`size-[9px] rounded-full ${projectStatus.dotClass} ${+ projectStatus.pulse ? "animate-pulse" : ""+ }`}+ />+ </span>+ <ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />+ </span>+ ) : (+ <ChevronRightIcon+ className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${+ project.expanded ? "rotate-90" : ""+ }`}+ />+ )}+ <ProjectFavicon cwd={project.cwd} />+ <span className="flex-1 truncate text-xs font-medium text-foreground/90">+ {project.name}+ </span>+ </SidebarMenuButton>+ <Tooltip>+ <TooltipTrigger+ render={+ <SidebarMenuAction+ render={+ <button+ type="button"+ aria-label={`Create new thread in ${project.name}`}+ data-testid="new-thread-button"+ />+ }+ 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, {+ envMode: resolveSidebarNewThreadEnvMode({+ defaultEnvMode: appSettings.defaultThreadEnvMode,+ }),+ });+ }}+ >+ <SquarePenIcon className="size-3.5" />+ </SidebarMenuAction>+ }+ />+ <TooltipPopup side="top">+ {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"}+ </TooltipPopup>+ </Tooltip>+ </div>++ <CollapsibleContent>+ <SidebarMenuSub+ ref={attachThreadListAutoAnimateRef}+ className="mx-1 my-0 w-full translate-x-0 gap-0.5 px-1.5 py-0"+ >+ {renderedThreads.map((thread) => renderThreadRow(thread))}++ {project.expanded && hasHiddenThreads && !isThreadListExpanded && (+ <SidebarMenuSubItem className="w-full">+ <SidebarMenuSubButton+ render={<button type="button" />}+ data-thread-selection-safe+ 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);+ }}+ >+ <span>Show more</span>+ </SidebarMenuSubButton>+ </SidebarMenuSubItem>+ )}+ {project.expanded && hasHiddenThreads && isThreadListExpanded && (+ <SidebarMenuSubItem className="w-full">+ <SidebarMenuSubButton+ render={<button type="button" />}+ data-thread-selection-safe+ 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);+ }}+ >+ <span>Show less</span>+ </SidebarMenuSubButton>+ </SidebarMenuSubItem>+ )}+ </SidebarMenuSub>+ </CollapsibleContent>+ </Collapsible>+ );+ }+const handleProjectTitleClick = useCallback((event: React.MouseEvent<HTMLButtonElement>, projectId: ProjectId) => {if (dragInProgressRef.current) {@@ -1063,12 +1511,9 @@ export default function Sidebar() {: shouldHighlightDesktopUpdateError(desktopUpdateState)? "text-rose-500 animate-pulse": "text-amber-500 animate-pulse";- const newThreadShortcutLabel = useMemo(- () =>- shortcutLabelForCommand(keybindings, "chat.newLocal") ??- shortcutLabelForCommand(keybindings, "chat.new"),- [keybindings],- );+ const newThreadShortcutLabel =+ shortcutLabelForCommand(keybindings, "chat.newLocal") ??+ shortcutLabelForCommand(keybindings, "chat.new");const handleDesktopUpdateButtonClick = useCallback(() => {const bridge = window.desktopBridge;@@ -1232,28 +1677,40 @@ export default function Sidebar() {<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">Projects</span>- <Tooltip>- <TooltipTrigger- render={- <button- type="button"- aria-label={shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}- aria-pressed={shouldShowProjectPathEntry}- className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"- onClick={handleStartAddProject}+ <div className="flex items-center gap-1">+ <ProjectSortMenu+ projectSortOrder={appSettings.sidebarProjectSortOrder}+ threadSortOrder={appSettings.sidebarThreadSortOrder}+ onProjectSortOrderChange={(sortOrder) => {+ updateSettings({ sidebarProjectSortOrder: sortOrder });+ }}+ onThreadSortOrderChange={(sortOrder) => {+ updateSettings({ sidebarThreadSortOrder: sortOrder });+ }}+ />+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ aria-label={shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}+ aria-pressed={shouldShowProjectPathEntry}+ className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"+ onClick={handleStartAddProject}+ />+ }+ >+ <PlusIcon+ className={`size-3.5 transition-transform duration-150 ${+ shouldShowProjectPathEntry ? "rotate-45" : "rotate-0"+ }`}/>- }- >- <PlusIcon- className={`size-3.5 transition-transform duration-150 ${- shouldShowProjectPathEntry ? "rotate-45" : "rotate-0"- }`}- />- </TooltipTrigger>- <TooltipPopup side="right">- {shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}- </TooltipPopup>- </Tooltip>+ </TooltipTrigger>+ <TooltipPopup side="right">+ {shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}+ </TooltipPopup>+ </Tooltip>+ </div></div>{shouldShowProjectPathEntry && (@@ -1321,352 +1778,37 @@ export default function Sidebar() {</div>)}- <DndContext- sensors={projectDnDSensors}- collisionDetection={projectCollisionDetection}- modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}- onDragStart={handleProjectDragStart}- onDragEnd={handleProjectDragEnd}- onDragCancel={handleProjectDragCancel}- >- <SidebarMenu>- <SortableContext- items={projects.map((project) => project.id)}- strategy={verticalListSortingStrategy}- >- {projects.map((project) => {- const projectThreads = threads- .filter((thread) => thread.projectId === project.id)- .toSorted((a, b) => {- const byDate =- new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();- if (byDate !== 0) return byDate;- return b.id.localeCompare(a.id);- });- const projectStatus = resolveProjectStatusIndicator(- projectThreads.map((thread) =>- resolveThreadStatusPill({- thread,- hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,- hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,- }),- ),- );- const isThreadListExpanded = expandedThreadListsByProject.has(project.id);- const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;- const visibleThreads =- hasHiddenThreads && !isThreadListExpanded- ? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)- : projectThreads;- const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);-- return (+ {isManualProjectSorting ? (+ <DndContext+ sensors={projectDnDSensors}+ collisionDetection={projectCollisionDetection}+ modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}+ onDragStart={handleProjectDragStart}+ onDragEnd={handleProjectDragEnd}+ onDragCancel={handleProjectDragCancel}+ >+ <SidebarMenu>+ <SortableContext+ items={sortedProjects.map((project) => project.id)}+ strategy={verticalListSortingStrategy}+ >+ {sortedProjects.map((project) => (<SortableProjectItem key={project.id} projectId={project.id}>- {(dragHandleProps) => (- <Collapsible className="group/collapsible" open={project.expanded}>- <div className="group/project-header relative">- <SidebarMenuButton- size="sm"- className="gap-2 px-2 py-1.5 text-left cursor-grab active:cursor-grabbing hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground"- {...dragHandleProps.attributes}- {...dragHandleProps.listeners}- onPointerDownCapture={handleProjectTitlePointerDownCapture}- onClick={(event) => handleProjectTitleClick(event, project.id)}- onKeyDown={(event) => handleProjectTitleKeyDown(event, project.id)}- onContextMenu={(event) => {- event.preventDefault();- void handleProjectContextMenu(project.id, {- x: event.clientX,- y: event.clientY,- });- }}- >- {!project.expanded && projectStatus ? (- <span- aria-hidden="true"- title={projectStatus.label}- className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`}- >- <span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">- <span- className={`size-[9px] rounded-full ${projectStatus.dotClass} ${- projectStatus.pulse ? "animate-pulse" : ""- }`}- />- </span>- <ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />- </span>- ) : (- <ChevronRightIcon- className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${- project.expanded ? "rotate-90" : ""- }`}- />- )}- <ProjectFavicon cwd={project.cwd} />- <span className="flex-1 truncate text-xs font-medium text-foreground/90">- {project.name}- </span>- </SidebarMenuButton>- <Tooltip>- <TooltipTrigger- render={- <SidebarMenuAction- render={- <button- type="button"- aria-label={`Create new thread in ${project.name}`}- data-testid="new-thread-button"- />- }- 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, {- envMode: resolveSidebarNewThreadEnvMode({- defaultEnvMode: appSettings.defaultThreadEnvMode,- }),- });- }}- >- <SquarePenIcon className="size-3.5" />- </SidebarMenuAction>- }- />- <TooltipPopup side="top">- {newThreadShortcutLabel- ? `New thread (${newThreadShortcutLabel})`- : "New thread"}- </TooltipPopup>- </Tooltip>- </div>-- <CollapsibleContent keepMounted>- <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0.5 px-1.5 py-0">- {visibleThreads.map((thread) => {- const isActive = routeThreadId === thread.id;- const isSelected = selectedThreadIds.has(thread.id);- const isHighlighted = isActive || isSelected;- const threadStatus = resolveThreadStatusPill({- thread,- hasPendingApprovals:- derivePendingApprovals(thread.activities).length > 0,- hasPendingUserInput:- derivePendingUserInputs(thread.activities).length > 0,- });- const prStatus = prStatusIndicator(- prByThreadId.get(thread.id) ?? null,- );- const terminalStatus = terminalStatusFromRunningIds(- selectThreadTerminalState(terminalStateByThreadId, thread.id)- .runningTerminalIds,- );-- return (- <SidebarMenuSubItem- key={thread.id}- className="w-full"- data-thread-item- >- <SidebarMenuSubButton- render={<div role="button" tabIndex={0} />}- size="sm"- isActive={isActive}- className={resolveThreadRowClassName({- isActive,- isSelected,- })}- onClick={(event) => {- handleThreadClick(- event,- thread.id,- orderedProjectThreadIds,- );- }}- onKeyDown={(event) => {- if (event.key !== "Enter" && event.key !== " ") return;- event.preventDefault();- if (selectedThreadIds.size > 0) {- clearSelection();- }- setSelectionAnchor(thread.id);- void navigate({- to: "/$threadId",- params: { threadId: thread.id },- });- }}- onContextMenu={(event) => {- event.preventDefault();- if (- selectedThreadIds.size > 0 &&- selectedThreadIds.has(thread.id)- ) {- void handleMultiSelectContextMenu({- x: event.clientX,- y: event.clientY,- });- } else {- if (selectedThreadIds.size > 0) {- clearSelection();- }- void handleThreadContextMenu(thread.id, {- x: event.clientX,- y: event.clientY,- });- }- }}- >- <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">- {prStatus && (- <Tooltip>- <TooltipTrigger- render={- <button- type="button"- aria-label={prStatus.tooltip}- className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}- onClick={(event) => {- openPrLink(event, prStatus.url);- }}- >- <GitPullRequestIcon className="size-3" />- </button>- }- />- <TooltipPopup side="top">- {prStatus.tooltip}- </TooltipPopup>- </Tooltip>- )}- {threadStatus && (- <span- className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}- >- <span- className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${- threadStatus.pulse ? "animate-pulse" : ""- }`}- />- <span className="hidden md:inline">- {threadStatus.label}- </span>- </span>- )}- {renamingThreadId === thread.id ? (- <input- ref={(el) => {- 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()}- />- ) : (- <span className="min-w-0 flex-1 truncate text-xs">- {thread.title}- </span>- )}- </div>- <div className="ml-auto flex shrink-0 items-center gap-1.5">- {terminalStatus && (- <span- role="img"- aria-label={terminalStatus.label}- title={terminalStatus.label}- className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}- >- <TerminalIcon- className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}- />- </span>- )}- <span- className={`text-[10px] ${- isHighlighted- ? "text-foreground/72 dark:text-foreground/82"- : "text-muted-foreground/40"- }`}- >- {formatRelativeTime(thread.createdAt)}- </span>- </div>- </SidebarMenuSubButton>- </SidebarMenuSubItem>- );- })}-- {hasHiddenThreads && !isThreadListExpanded && (- <SidebarMenuSubItem className="w-full">- <SidebarMenuSubButton- render={<button type="button" />}- data-thread-selection-safe- 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);- }}- >- <span>Show more</span>- </SidebarMenuSubButton>- </SidebarMenuSubItem>- )}- {hasHiddenThreads && isThreadListExpanded && (- <SidebarMenuSubItem className="w-full">- <SidebarMenuSubButton- render={<button type="button" />}- data-thread-selection-safe- 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);- }}- >- <span>Show less</span>- </SidebarMenuSubButton>- </SidebarMenuSubItem>- )}- </SidebarMenuSub>- </CollapsibleContent>- </Collapsible>- )}+ {(dragHandleProps) => renderProjectItem(project, dragHandleProps)}</SortableProjectItem>- );- })}- </SortableContext>+ ))}+ </SortableContext>+ </SidebarMenu>+ </DndContext>+ ) : (+ <SidebarMenu ref={attachProjectListAutoAnimateRef}>+ {sortedProjects.map((project) => (+ <SidebarMenuItem key={project.id} className="rounded-md">+ {renderProjectItem(project, null)}+ </SidebarMenuItem>+ ))}</SidebarMenu>- </DndContext>+ )}{projects.length === 0 && !shouldShowProjectPathEntry && (<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.tsindex f1919ec72..f2d5a5be4 100644--- a/apps/web/src/store.test.ts+++ b/apps/web/src/store.test.ts@@ -226,6 +226,20 @@ describe("store read model sync", () => {expect(next.threads[0]?.model).toBe("claude-sonnet-4-6");});+ it("preserves project and thread updatedAt timestamps from the read model", () => {+ const initialState = makeState(makeThread());+ const readModel = makeReadModel(+ makeReadModelThread({+ updatedAt: "2026-02-27T00:05:00.000Z",+ }),+ );++ const next = syncServerReadModel(initialState, readModel);++ expect(next.projects[0]?.updatedAt).toBe("2026-02-27T00:00:00.000Z");+ expect(next.threads[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");+ });+it("preserves the current project order when syncing incoming read model updates", () => {const project1 = ProjectId.makeUnsafe("project-1");const project2 = ProjectId.makeUnsafe("project-2");diff --git a/apps/web/src/store.ts b/apps/web/src/store.tsindex 8269b30a6..9784aa972 100644--- a/apps/web/src/store.ts+++ b/apps/web/src/store.ts@@ -145,6 +145,8 @@ function mapProjectsFromReadModel((persistedExpandedProjectCwds.size > 0? persistedExpandedProjectCwds.has(project.workspaceRoot): true),+ createdAt: project.createdAt,+ updatedAt: project.updatedAt,scripts: project.scripts.map((script) => ({ ...script })),} satisfies Project;});@@ -304,6 +306,7 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea})),error: thread.session?.lastError ?? null,createdAt: thread.createdAt,+ updatedAt: thread.updatedAt,latestTurn: thread.latestTurn,lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,branch: thread.branch,diff --git a/apps/web/src/types.ts b/apps/web/src/types.tsindex 32a7fe02b..03e6665c0 100644--- a/apps/web/src/types.ts+++ b/apps/web/src/types.ts@@ -82,6 +82,8 @@ export interface Project {cwd: string;model: string;expanded: boolean;+ createdAt?: string | undefined;+ updatedAt?: string | undefined;scripts: ProjectScript[];}@@ -98,6 +100,7 @@ export interface Thread {proposedPlans: ProposedPlan[];error: string | null;createdAt: string;+ updatedAt?: string | undefined;latestTurn: OrchestrationLatestTurn | null;lastVisitedAt?: string | undefined;branch: string | null;diff --git a/bun.lock b/bun.lockindex 4e1959c15..e4db9faca 100644--- a/bun.lock+++ b/bun.lock@@ -80,6 +80,7 @@"@dnd-kit/modifiers": "^9.0.0","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",+ "@formkit/auto-animate": "^0.9.0","@lexical/react": "^0.41.0","@pierre/diffs": "^1.1.0-beta.16","@t3tools/contracts": "workspace:*",@@ -358,6 +359,8 @@"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="],+ "@formkit/auto-animate": ["@formkit/[email protected]", "", {}, "sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA=="],+"@hapi/address": ["@hapi/[email protected]", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA=="],"@hapi/formula": ["@hapi/[email protected]", "", {}, "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw=="],