From bbb429fe93544ef691d77899daf43be4dae88e22 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 21 Oct 2026 07:07:49 +0000 Subject: [PATCH 1/2] feat(sidebar): sort workspaces and pin them to the top (#271) Add a sort menu beside the workspace search (None, Alphabetical, Last updated) and, while a sort is active, a pin toggle per workspace. Pinned workspaces lead in their own manual order (pinOrder in projects.json); unpinned ones follow the sort and lose Move up/down and drag. Last updated uses the last message time from the session tail scan (SessionInfo.lastMessageAt), falling back to the file mtime. --- AGENTS.md | 14 ++- CHANGELOG.md | 4 + app/api/projects/route.ts | 28 +++--- app/globals.css | 8 +- components/SessionSidebar-chrome.tsx | 22 +++-- components/SessionSidebar-helpers.ts | 24 +++++ components/SessionSidebar-rows.tsx | 40 +++++++-- components/SessionSidebar.tsx | 130 ++++++++++++++++++++++----- lib/i18n/locales/en.json | 6 ++ lib/i18n/locales/ja.json | 6 ++ lib/i18n/locales/zh-CN.json | 6 ++ lib/omp/session-files.ts | 19 ++-- lib/project-ordering.test.mjs | 46 ++++++++++ lib/project-ordering.ts | 53 +++++++++-- lib/project-registry.test.mjs | 7 ++ lib/project-registry.ts | 13 ++- lib/session-reader.test.mjs | 17 ++++ lib/session-reader.ts | 1 + lib/types.ts | 5 ++ 19 files changed, 378 insertions(+), 71 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1795324d2..bdf688b58 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -514,10 +514,16 @@ during the wait. - `GET /api/projects` re-authorizes registered roots with `allowFileRoot()` — the in-memory browse allowlist does not survive restarts, and empty managed projects derive no root from sessions. -- The client sorts the merged list by most-recently-added (registration - order), then by path for session-discovered projects - (`lib/project-ordering.ts`); the order deliberately does NOT depend on - session activity, so project rows never jump around while sessions refresh. +- By default (sort "None") the client orders the merged list manually + (`sortOrder`, set by drag/Move up/down), then most-recently-added, then by + path (`lib/project-ordering.ts`), so rows never jump while sessions refresh. + The header sort button (`omp-web:project-sort` in `localStorage`, per + browser) switches to Alphabetical (label A→Z) or Last updated (newest last + message first: `lastMessageAt` from the session tail scan, else the file + mtime) — the latter deliberately reorders on activity. While a + sort is active, rows get a pin toggle: pinned projects (`pinOrder` in the + registry, pinned to the end of the group) lead in their own manual order and + alone keep Move up/down and drag; pins are ignored under "None". Expanded project paths live in `localStorage` (`omp-web:expanded-projects`), defaulting to only the active/restored project expanded, and stale keys are pruned against the diff --git a/CHANGELOG.md b/CHANGELOG.md index 458891860..f2fadf349 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **On desktop, notifications open from a bell in the top bar**, left of the right-panel toggle. The bell shows the unread count and opens a floating panel with the notification history, **Mark all as read** and **Clear**; the list scrolls inside a panel of limited width and height. Opening a notification closes the panel, and closing it marks the shown notifications as read. The right panel's Notifications tab and the right-panel toggle's unread count remain on phones only. - On phones and narrow windows, the top bar's tools menu is only as wide as its buttons instead of spanning the screen, and its **System** button opens the system prompt again. The prompt panel used to open inside the menu's sideways-scrolling strip, which clipped it out of view. +### Sidebar + +- **Sort and pin workspaces.** A sort button next to the workspace search switches between None (your manual order), Alphabetical and Last updated (the workspace whose session got the newest message first). While a sort is active, each workspace has a pin button: pinned workspaces stay at the top in the order you give them with Move up, Move down or dragging, and newly pinned ones join the end of that group. Unpinned workspaces follow the sort and cannot be moved by hand. The sort is remembered per browser; pins are stored with the workspace list. (#271) + --- ## [v0.5.2] - 2026-10-15 diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts index fd97cd1bc..5639d5195 100644 --- a/app/api/projects/route.ts +++ b/app/api/projects/route.ts @@ -43,9 +43,9 @@ function parseLaunchConfig(value: unknown): ProjectLaunchConfig | undefined { // GET /api/projects → { projects: ManagedProject[] } // Registered (non-hidden) projects plus session-discovered projects, excluding -// hidden entries. Session-discovered paths get no addedAt; the client orders -// the merged list by most-recently-added (registration order), then by path — -// deliberately not by session activity, which would reorder rows on refresh. +// hidden entries. Session-discovered paths get no addedAt; the client applies +// the ordering (manual / most-recently-added by default, or the user's chosen +// sort with pins first — see lib/project-ordering.ts). export async function GET() { try { const registry = loadProjectRegistry(); @@ -91,7 +91,7 @@ export async function POST(req: Request) { } // PATCH /api/projects -// Single shape: { cwd, alias?, sortOrder? } Batch shape: { updates: [{ cwd, alias?, sortOrder? }, ...] } +// Single shape: { cwd, alias?, sortOrder?, pinOrder? } Batch shape: { updates: [{ cwd, alias?, sortOrder?, pinOrder? }, ...] } // Applied atomically in one registry load/save so a drag reorder (one request, // many entries) can never interleave with another writer and lose updates. // Renaming or ordering a project is an explicit act of managing it: paths that @@ -105,13 +105,14 @@ export async function PATCH(req: Request) { cwd?: unknown; alias?: unknown; sortOrder?: unknown; + pinOrder?: unknown; launchConfig?: unknown; updates?: unknown; }; const rawUpdates: unknown[] = Array.isArray(body.updates) ? body.updates - : body.cwd !== undefined || body.alias !== undefined || body.sortOrder !== undefined || body.launchConfig !== undefined - ? [{ cwd: body.cwd, alias: body.alias, sortOrder: body.sortOrder, launchConfig: body.launchConfig }] + : body.cwd !== undefined || body.alias !== undefined || body.sortOrder !== undefined || body.pinOrder !== undefined || body.launchConfig !== undefined + ? [{ cwd: body.cwd, alias: body.alias, sortOrder: body.sortOrder, pinOrder: body.pinOrder, launchConfig: body.launchConfig }] : []; if (rawUpdates.length === 0) { return NextResponse.json({ error: "Path is required", code: "path_required" }, { status: 400 }); @@ -138,16 +139,18 @@ export async function PATCH(req: Request) { return match ? match.path : null; }; - const parsed: Array<{ path: string; alias?: string | null; sortOrder?: number | null; launchConfig?: ProjectLaunchConfig | null }> = []; + const parsed: Array<{ path: string; alias?: string | null; sortOrder?: number | null; pinOrder?: number | null; launchConfig?: ProjectLaunchConfig | null }> = []; const skipped: Array<{ cwd: string; code: string; error: string }> = []; for (const item of rawUpdates) { - const entry = item as { cwd?: unknown; alias?: unknown; sortOrder?: unknown; launchConfig?: unknown }; + const entry = item as { cwd?: unknown; alias?: unknown; sortOrder?: unknown; pinOrder?: unknown; launchConfig?: unknown }; const cwd = typeof entry.cwd === "string" ? entry.cwd.trim() : ""; if (!cwd) return NextResponse.json({ error: "Path is required", code: "path_required" }, { status: 400 }); const alias = entry.alias === null ? null : typeof entry.alias === "string" ? entry.alias : undefined; const sortOrder = entry.sortOrder === null ? null : typeof entry.sortOrder === "number" && Number.isFinite(entry.sortOrder) ? entry.sortOrder : undefined; + const pinOrder = entry.pinOrder === null ? null : typeof entry.pinOrder === "number" && Number.isFinite(entry.pinOrder) ? entry.pinOrder : undefined; if (entry.alias !== undefined && alias === undefined) return NextResponse.json({ error: "Alias must be a string", code: "invalid_alias" }, { status: 400 }); if (entry.sortOrder !== undefined && sortOrder === undefined) return NextResponse.json({ error: "Sort order must be a number", code: "invalid_sort_order" }, { status: 400 }); + if (entry.pinOrder !== undefined && pinOrder === undefined) return NextResponse.json({ error: "Pin order must be a number", code: "invalid_pin_order" }, { status: 400 }); const launchConfig = entry.launchConfig === null ? null : parseLaunchConfig(entry.launchConfig); // Same existence/directory checks as POST: an auto-registering endpoint // must never persist ghost entries for deleted paths, plain files, or @@ -158,7 +161,7 @@ export async function PATCH(req: Request) { // workspace stays reorderable/renamable even after its directory is removed. const managedPath = isAlreadyManaged(cwd); if (managedPath) { - parsed.push({ path: managedPath, alias, sortOrder, launchConfig }); + parsed.push({ path: managedPath, alias, sortOrder, pinOrder, launchConfig }); continue; } let normalized: string; @@ -185,7 +188,7 @@ export async function PATCH(req: Request) { } throw error; } - parsed.push({ path: projectRoot, alias, sortOrder, launchConfig }); + parsed.push({ path: projectRoot, alias, sortOrder, pinOrder, launchConfig }); } // Bulk path: every entry was a ghost — propagate the first failure so the // client gets a meaningful 400 instead of a misleading 200 with no changes. @@ -196,7 +199,7 @@ export async function PATCH(req: Request) { // Duplicate targets within one batch merge per-field (later defined // fields win) instead of the whole later update replacing the earlier. - const merged = new Map(); + const merged = new Map(); for (const update of parsed) { const key = comparableProjectPath(update.path); const previous = merged.get(key); @@ -204,6 +207,7 @@ export async function PATCH(req: Request) { path: previous.path, alias: update.alias !== undefined ? update.alias : previous.alias, sortOrder: update.sortOrder !== undefined ? update.sortOrder : previous.sortOrder, + pinOrder: update.pinOrder !== undefined ? update.pinOrder : previous.pinOrder, launchConfig: update.launchConfig !== undefined ? update.launchConfig : previous.launchConfig, } : update); } @@ -232,7 +236,7 @@ export async function PATCH(req: Request) { const updatedKeys = new Set(updates.map((update) => comparableProjectPath(update.path))); const projects = next.projects .filter((entry) => updatedKeys.has(comparableProjectPath(entry.path))) - .map((entry) => ({ path: entry.path, addedAt: entry.addedAt, hidden: entry.hidden, alias: entry.alias, sortOrder: entry.sortOrder, launchConfig: entry.launchConfig })); + .map((entry) => ({ path: entry.path, addedAt: entry.addedAt, hidden: entry.hidden, alias: entry.alias, sortOrder: entry.sortOrder, pinOrder: entry.pinOrder, launchConfig: entry.launchConfig })); return NextResponse.json({ projects }); } catch (error) { if (error instanceof ProjectPathError) { diff --git a/app/globals.css b/app/globals.css index 32299ab56..c08fd3c5d 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1614,16 +1614,18 @@ html[data-touch-targets="accessible"] :is(.image-lightbox-stepper button, .image height: 24px; } .sidebar-project-actions { - /* Match the session status column after reserving timestamp + menu space. */ - width: 46px; + /* Match the session status column after reserving timestamp + menu space; + grows when the pin toggle sits beside the menu. */ + min-width: 46px; display: flex; justify-content: flex-end; + gap: 2px; } /* Touch rows keep the compact timestamp immediately beside a full-size menu target. */ @media (hover: none), (pointer: coarse) { .sidebar-project-actions { - width: 56px; + min-width: 56px; } .sidebar-icon-button, .sidebar-project-action, diff --git a/components/SessionSidebar-chrome.tsx b/components/SessionSidebar-chrome.tsx index 84a9bd8dd..ed9f90df2 100644 --- a/components/SessionSidebar-chrome.tsx +++ b/components/SessionSidebar-chrome.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from "react"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref, type RefObject } from "react"; import { createPortal } from "react-dom"; import { useI18n } from "@/lib/i18n"; import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion"; @@ -36,32 +36,40 @@ const SIDEBAR_BUTTON_TRANSITION = "background var(--dur-fast) var(--ease-out-war /** Quiet square icon button used across the sidebar chrome (header, section * headers, footer). Stays visually subdued; the accent appears on hover and - * when active (e.g. an applied filter). */ + * when active (e.g. an applied filter). `menuExpanded` makes it a menu + * trigger (aria-haspopup/aria-expanded instead of aria-pressed). */ function SidebarIconButton({ + ref, label, title, onClick, active = false, + menuExpanded, disabled = false, children, }: { + ref?: Ref; label: string; title?: string; onClick: () => void; active?: boolean; + menuExpanded?: boolean; disabled?: boolean; children: ReactNode; }) { const [hovered, setHovered] = useState(false); return ( + )} - - + {canReorder && ( + <> + + + + )} diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index 6c2213d3f..a658b4386 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -10,9 +10,9 @@ import { ProviderUsageBar } from "./ProviderUsageBar"; import { Tooltip } from "./ui/primitives"; import { toast } from "./ui/toast"; import { clearLastOpenSession, setLastOpenSession, workspaceKeyOf } from "@/lib/workspace-memory"; -import { groupSessionsByProject, projectActivityCounts, sortManagedProjects } from "@/lib/project-ordering"; +import { groupSessionsByProject, nextPinOrder, orderProjects, projectActivityCounts, type ProjectSortMode } from "@/lib/project-ordering"; import { comparableProjectPath } from "@/lib/comparable-path"; -import { Archive, ArrowLeft, ArrowRight, Check, ChevronRight, FileUp, Plus, RefreshCw, Search, Settings2, SlidersHorizontal, X } from "lucide-react"; +import { Archive, ArrowDownUp, ArrowLeft, ArrowRight, Check, ChevronRight, FileUp, Plus, RefreshCw, Search, Settings2, SlidersHorizontal, X } from "lucide-react"; import { publishSessionsChanged } from "@/lib/session-change-bus"; import { openEventStream } from "@/lib/event-stream"; import { @@ -22,21 +22,25 @@ import { MAX_PROJECT_SESSIONS, buildSessionTree, loadExpandedProjects, + loadProjectSortMode, loadUnreadSessionIds, normalizeProjectKey, projectLabel, saveExpandedProjects, + saveProjectSortMode, saveUnreadSessionIds, type WorktreeContext, type WorktreeEntry, type WorktreeState, } from "./SessionSidebar-helpers"; -import { OmpWebTitle, SIDEBAR_BUTTON_TRANSITION, SidebarIconButton } from "./SessionSidebar-chrome"; +import { OmpWebTitle, SIDEBAR_BUTTON_TRANSITION, SidebarIconButton, SidebarPortalMenu } from "./SessionSidebar-chrome"; import { ProjectRow } from "./SessionSidebar-rows"; /** Deadline for one /api/sessions fetch. A wedged-but-listening server never * answers; without this the initial spinner would pend forever. */ const SESSIONS_FETCH_TIMEOUT_MS = 15_000; +/** Stable empty list: sort modes that ignore sessions keep their memo inputs fixed. */ +const NO_SESSIONS: SessionInfo[] = []; declare global { interface Window { @@ -135,6 +139,12 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, const [searchQuery, setSearchQuery] = useState(""); const [runningOnly, setRunningOnly] = useState(false); const searchInputRef = useRef(null); + // Workspace sort (per browser). Pins apply only while a sort is active. + const [projectSortMode, setProjectSortMode] = useState(() => loadProjectSortMode()); + const [sortMenuOpen, setSortMenuOpen] = useState(false); + const sortButtonRef = useRef(null); + const closeSortMenu = useCallback(() => setSortMenuOpen(false), []); + const pinsActive = projectSortMode !== "none"; // Once the SSE stream has delivered a frame it is the source of truth for // running state; late /api/sessions responses must not overwrite it. @@ -640,24 +650,36 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, const selectedProject = useMemo(() => projectRootFor(selectedCwd), [projectRootFor, selectedCwd]); // While a fresh optimistic/placeholder is pending (JSONL not yet on disk), // freeze ordering so the new project row does not flicker optimistic -> - // confirmed position. New projects are allowed to append at the end. + // confirmed position. New projects are allowed to append at the end. A + // user ordering action (sort mode, pin, manual order) ends the freeze, and + // frozen rows still show the fresh project data. const hasPendingNewSession = Boolean( optimisticSession || [...runningSessionIds, ...exitedSessions.keys()].some((id) => !allSessions.some((session) => session.id === id)), ); - const sortedProjectsBase = useMemo(() => sortManagedProjects(visibleProjects), [visibleProjects]); - const sortedProjectsRef = useRef(null); + // Only "Last updated" reads sessions; other modes must not re-sort on every session refresh. + const orderingSessions = projectSortMode === "updated" ? visibleSessions : NO_SESSIONS; + const sortedProjectsBase = useMemo( + () => orderProjects(visibleProjects, projectSortMode, orderingSessions, (project) => project.alias ?? projectLabel(project.path)), + [visibleProjects, projectSortMode, orderingSessions], + ); + const orderingKey = useMemo( + () => [projectSortMode, ...projects.map((p) => `${p.path}\t${p.sortOrder ?? ""}\t${p.pinOrder ?? ""}`)].join("\n"), + [projectSortMode, projects], + ); + const sortedProjectsRef = useRef<{ key: string; list: ManagedProject[] } | null>(null); const sortedProjects = useMemo(() => { - if (hasPendingNewSession && sortedProjectsRef.current) { - const prev = sortedProjectsRef.current; - const prevKeys = new Set(prev.map((p) => comparableProjectPath(p.path))); - const next = [...prev]; + const prev = sortedProjectsRef.current; + if (hasPendingNewSession && prev && prev.key === orderingKey) { + const fresh = new Map(sortedProjectsBase.map((p) => [comparableProjectPath(p.path), p])); + const next = prev.list.map((p) => fresh.get(comparableProjectPath(p.path)) ?? p); + const prevKeys = new Set(prev.list.map((p) => comparableProjectPath(p.path))); for (const p of sortedProjectsBase) if (!prevKeys.has(comparableProjectPath(p.path))) next.push(p); return next; } - sortedProjectsRef.current = sortedProjectsBase; + sortedProjectsRef.current = { key: orderingKey, list: sortedProjectsBase }; return sortedProjectsBase; - }, [sortedProjectsBase, hasPendingNewSession]); + }, [sortedProjectsBase, hasPendingNewSession, orderingKey]); useEffect(() => { onWorkspaceOptionsChange?.(sortedProjects, selectedProject, selectedCwd); }, [onWorkspaceOptionsChange, sortedProjects, selectedProject, selectedCwd]); @@ -822,7 +844,7 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, } }, [addProjectBusy, loadProjects, expandProject, setAddProjectOpen]); - const handleUpdateProjectPresentation = useCallback(async (projectPath: string, updates: { alias?: string | null; sortOrder?: number | null; launchConfig?: ProjectLaunchConfig | null }) => { + const handleUpdateProjectPresentation = useCallback(async (projectPath: string, updates: { alias?: string | null; sortOrder?: number | null; pinOrder?: number | null; launchConfig?: ProjectLaunchConfig | null }) => { try { const response = await fetch("/api/projects", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cwd: projectPath, ...updates }) }); if (!response.ok) throw new Error(t("projects.updateFailed")); @@ -833,8 +855,21 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, } }, [loadProjects, t]); + /** Projects Move up/down and drag can reorder: all of them in manual mode, + * only the pinned ones while a sort is active (the rest follow the sort). */ + const reorderableProjects = useMemo( + () => (pinsActive ? sortedProjects.filter((project) => project.pinOrder !== undefined) : sortedProjects), + [pinsActive, sortedProjects], + ); + + // One ordering write (reorder or pin) at a time: each computes its payload + // from the list on screen, which is stale until the previous write reloads it. + const orderWriteBusyRef = useRef(false); + /** Persist one whole-list order as a single atomic batched PATCH. */ const persistProjectOrder = useCallback(async (next: ManagedProject[]) => { + if (orderWriteBusyRef.current) return; + orderWriteBusyRef.current = true; try { // One batched request: the server applies every entry in a single // atomic registry save, so per-project writes can't interleave and lose @@ -842,20 +877,22 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, const response = await fetch("/api/projects", { method: "PATCH", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ updates: next.map((project, index) => ({ cwd: project.path, sortOrder: index })) }), + body: JSON.stringify({ updates: next.map((project, index) => ({ cwd: project.path, ...(pinsActive ? { pinOrder: index } : { sortOrder: index }) })) }), }); if (!response.ok) throw new Error(t("projects.reorderFailed")); await loadProjects(); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); + } finally { + orderWriteBusyRef.current = false; } - }, [loadProjects, t]); + }, [loadProjects, pinsActive, t]); const handleProjectDrop = useCallback(async (targetPath: string) => { const sourcePath = draggedProjectPath; setDraggedProjectPath(null); if (!sourcePath || sourcePath === targetPath) return; - const next = [...sortedProjects]; + const next = [...reorderableProjects]; const from = next.findIndex((project) => project.path === sourcePath); const to = next.findIndex((project) => project.path === targetPath); if (from < 0 || to < 0) return; @@ -863,11 +900,11 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, if (!moved) return; next.splice(to, 0, moved); await persistProjectOrder(next); - }, [draggedProjectPath, sortedProjects, persistProjectOrder]); + }, [draggedProjectPath, reorderableProjects, persistProjectOrder]); /** Keyboard-accessible reorder: move one project up/down the list. */ const handleMoveProject = useCallback(async (projectPath: string, delta: -1 | 1) => { - const next = [...sortedProjects]; + const next = [...reorderableProjects]; const index = next.findIndex((project) => project.path === projectPath); const target = index + delta; if (index < 0 || target < 0 || target >= next.length) return; @@ -875,7 +912,27 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, if (!moved) return; next.splice(target, 0, moved); await persistProjectOrder(next); - }, [sortedProjects, persistProjectOrder]); + }, [reorderableProjects, persistProjectOrder]); + + /** Pin to the end of the pinned group, or unpin. */ + const handleTogglePin = useCallback(async (project: ManagedProject) => { + if (orderWriteBusyRef.current) return; + orderWriteBusyRef.current = true; + const pinOrder = project.pinOrder !== undefined ? null : nextPinOrder(sortedProjects); + try { + await handleUpdateProjectPresentation(project.path, { pinOrder }); + } catch { + // handleUpdateProjectPresentation already toasted the failure. + } finally { + orderWriteBusyRef.current = false; + } + }, [sortedProjects, handleUpdateProjectPresentation]); + + // The menu closes itself on a menu item click and returns focus to the trigger. + const chooseProjectSortMode = useCallback((mode: ProjectSortMode) => { + setProjectSortMode(mode); + saveProjectSortMode(mode); + }, []); const handleRemoveProject = useCallback(async (projectPath: string) => { if (removeProjectPath) return; @@ -1246,7 +1303,7 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, - {/* Workspaces section header: label + search / filter / add */} + {/* Workspaces section header: label + search / sort / filter / add */}