diff --git a/packages/ui/src/apps/MobileSessionSwitcher.tsx b/packages/ui/src/apps/MobileSessionSwitcher.tsx index c05b9ecf..fdaf436f 100644 --- a/packages/ui/src/apps/MobileSessionSwitcher.tsx +++ b/packages/ui/src/apps/MobileSessionSwitcher.tsx @@ -3,7 +3,7 @@ import type { Session } from '@opencode-ai/sdk/v2'; import { SessionActivityDuration } from '@/components/session/SessionActivityDuration'; import { formatSessionCompactDateLabel } from '@/components/session/sidebar/utils'; -import { useSwitcherItems } from '@/components/session/sidebar/hooks/useSwitcherItems'; +import { useSwitcherItems } from '@/components/session/sidebar/shell/useSwitcherItems'; import { useTabletLayout } from '@/lib/device'; import { useI18n } from '@/lib/i18n'; import { cn } from '@/lib/utils'; diff --git a/packages/ui/src/components/layout/MainLayout.tsx b/packages/ui/src/components/layout/MainLayout.tsx index 0f30dad5..7e392460 100644 --- a/packages/ui/src/components/layout/MainLayout.tsx +++ b/packages/ui/src/components/layout/MainLayout.tsx @@ -23,6 +23,7 @@ import { useUpdatePolling } from '@/hooks/useUpdatePolling'; import { useDeviceInfo } from '@/lib/device'; import { cn } from '@/lib/utils'; import { lazyWithChunkRecovery } from '@/lib/chunkLoadRecovery'; +import { useSessionListSync } from '@/components/session/sidebar/list/useSessionListSync'; import { ChatView } from '@/components/views/ChatView'; @@ -35,6 +36,7 @@ const SettingsWindow = lazyWithChunkRecovery(() => import('@/components/views/Se * crossing the threshold reloads into it (see watchHostedSurfaceViewport). */ export const MainLayout: React.FC = () => { + useSessionListSync({ isVSCode: false }); const isSidebarOpen = useUIStore((state) => state.isSidebarOpen); const setIsMobile = useUIStore((state) => state.setIsMobile); const isSettingsDialogOpen = useUIStore((state) => state.isSettingsDialogOpen); diff --git a/packages/ui/src/components/layout/VSCodeLayout.tsx b/packages/ui/src/components/layout/VSCodeLayout.tsx index 0b81613c..59dec89c 100644 --- a/packages/ui/src/components/layout/VSCodeLayout.tsx +++ b/packages/ui/src/components/layout/VSCodeLayout.tsx @@ -41,6 +41,7 @@ import type { Session } from '@opencode-ai/sdk/v2'; import type { UsageWindow } from '@/types'; import type { SessionContextUsage } from '@/stores/types/sessionTypes'; import { useUIStore, type TimeFormatPreference } from '@/stores/useUIStore'; +import { useSessionListSync } from '@/components/session/sidebar/list/useSessionListSync'; const SettingsView = lazyWithChunkRecovery(() => import('@/components/views/SettingsView').then(m => ({ default: m.SettingsView }))); @@ -526,8 +527,11 @@ export const VSCodeLayout: React.FC = () => { } }, [usesExpandedLayout, currentView, viewMode]); + useSessionListSync({ isVSCode: true }); + return ( -
+ <> +
{viewMode === 'editor' ? ( // Editor mode: just chat, no sidebar
@@ -639,7 +643,8 @@ export const VSCodeLayout: React.FC = () => { )} -
+
+ ); }; diff --git a/packages/ui/src/components/session/SessionFolderItem.tsx b/packages/ui/src/components/session/SessionFolderItem.tsx index 21f5078c..483d6efd 100644 --- a/packages/ui/src/components/session/SessionFolderItem.tsx +++ b/packages/ui/src/components/session/SessionFolderItem.tsx @@ -4,9 +4,7 @@ import type { SessionFolder } from '@/stores/useSessionFoldersStore'; import { useI18n } from '@/lib/i18n'; import { Icon } from "@/components/icon/Icon"; import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; -import type { SessionNodeChildRenderExtras, SessionNodeRenderExtras } from './sidebar/sessionNodeItemUtils'; -import { CollapsedActivityIndicator } from './sidebar/collapsedActivityIndicator'; -import type { CollapsedActivityState } from './sidebar/collapsedActivityState'; +import { CollapsedActivityIndicator, type CollapsedActivityState } from './sidebar/sessions/collapsedActivityIndicator'; interface SessionFolderItemProps { folder: SessionFolder; @@ -24,23 +22,7 @@ interface SessionFolderItemProps { onToggle: () => void; onRename: (name: string) => void; onDelete: () => void; - renderSessionNode: ( - node: TSessionNode, - depth?: number, - groupDir?: string | null, - projectId?: string | null, - archivedBucket?: boolean, - secondaryMeta?: { projectLabel?: string | null; branchLabel?: string | null } | null, - renderContext?: 'project' | 'recent', - renderExtras?: SessionNodeChildRenderExtras, - ) => React.ReactNode; - /** - * Returns the precomputed per-row render extras for a given node. The - * group precomputes subtree-contains lookups once, then resolves a - * per-node structure key here so SessionNodeItem's React.memo comparator - * can answer with a single string compare instead of a recursive walk. - */ - getRenderExtras?: (node: TSessionNode) => SessionNodeRenderExtras | undefined; + children?: React.ReactNode; groupDirectory?: string | null; projectId?: string | null; mobileVariant?: boolean; @@ -74,8 +56,7 @@ const SessionFolderItemBase = ({ onToggle, onRename, onDelete, - renderSessionNode, - getRenderExtras, + children, groupDirectory, projectId, mobileVariant = false, @@ -97,6 +78,7 @@ const SessionFolderItemBase = ({ const [localDraft, setLocalDraft] = React.useState(''); const inputRef = React.useRef(null); + const renaming = isRenaming || localRenaming; const draft = isRenaming ? renameDraft : localDraft; @@ -167,6 +149,7 @@ const SessionFolderItemBase = ({ isDropTarget && 'bg-primary/10 ring-1 ring-inset ring-primary/30', )} onClick={renaming ? undefined : (event) => { + // SAFETY: this handler is attached to the div rendered directly above. (event.currentTarget as HTMLElement).blur(); onToggle(); }} @@ -346,11 +329,7 @@ const SessionFolderItemBase = ({ {subFolderItems} {/* Then sessions */} {sessions.length > 0 ? ( -
- {sessions.map((node) => - renderSessionNode(node, 0, groupDirectory ?? null, projectId ?? null, archivedBucket, undefined, 'project', getRenderExtras?.(node)), - )} -
+ children ) : !subFolderItems ? (
{t('sessions.sidebar.folderItem.emptyFolder')} @@ -362,6 +341,9 @@ const SessionFolderItemBase = ({ ); }; -export const SessionFolderItem = React.memo(SessionFolderItemBase) as ( +export const SessionFolderItem = ( + /* SAFETY: React.memo preserves the generic component's props and return type. */ + React.memo(SessionFolderItemBase) as ( props: SessionFolderItemProps, -) => React.ReactElement; + ) => React.ReactElement +); diff --git a/packages/ui/src/components/session/SessionSidebar.tsx b/packages/ui/src/components/session/SessionSidebar.tsx index b59178da..9a7361bd 100644 --- a/packages/ui/src/components/session/SessionSidebar.tsx +++ b/packages/ui/src/components/session/SessionSidebar.tsx @@ -1,52 +1,28 @@ import React from 'react'; -import { getChatsRootForHome, getChatsRootFromDirectory, isChatDirectoryForHome, isChatDirectoryPath } from '@/lib/chatDirectories'; -import { isBtwSession } from '@/lib/sessionBtwMetadata'; -import { mergeSidebarSessionSources } from './sidebar/sidebarSessionSources'; -import type { Session } from '@opencode-ai/sdk/v2'; import { toast } from '@/components/ui'; import { useI18n } from '@/lib/i18n'; import { useDeviceInfo } from '@/lib/device'; -import { isDesktopShell } from '@/lib/desktop'; +import { isDesktopShell, isVSCodeRuntime } from '@/lib/desktop'; import { sessionEvents } from '@/lib/sessionEvents'; -import { formatDirectoryName, cn } from '@/lib/utils'; +import { cn } from '@/lib/utils'; import { useSessionUIStore } from '@/sync/session-ui-store'; -import { useChildStoreManager } from '@/sync/sync-context'; -import { getAllSyncSessionMap } from '@/sync/sync-refs'; import { useDirectoryStore } from '@/stores/useDirectoryStore'; -import { useSync } from '@/sync/use-sync'; -import { SessionPrefetchEffect } from './sidebar/hooks/useSessionPrefetch'; import { useProjectsStore } from '@/stores/useProjectsStore'; import { useUIStore } from '@/stores/useUIStore'; import { getDeferredSafeStorage } from '@/stores/utils/safeStorage'; import { useGitStore, useGitAllBranches, useGitRepoStatusMap } from '@/stores/useGitStore'; -import { isVSCodeRuntime } from '@/lib/desktop'; import { TooltipProvider } from '@/components/ui/tooltip'; import { NewWorktreeDialog } from './NewWorktreeDialog'; -import { useSessionFoldersStore } from '@/stores/useSessionFoldersStore'; import { useDebouncedValue } from '@/hooks/useDebouncedValue'; -import { useArchivedAutoFolders } from './sidebar/hooks/useArchivedAutoFolders'; -import { useGroupOrdering } from './sidebar/hooks/useGroupOrdering'; -import { useSessionSidebarSections } from './sidebar/hooks/useSessionSidebarSections'; -import { ProjectSessionSelectionEffect } from './sidebar/hooks/useProjectSessionSelection'; -import { useSessionGrouping } from './sidebar/hooks/useSessionGrouping'; -import { useSessionSearchEffects } from './sidebar/hooks/useSessionSearchEffects'; -import { useSessionActions } from './sidebar/hooks/useSessionActions'; -import { useSidebarPersistence } from './sidebar/hooks/useSidebarPersistence'; -import { useProjectRepoStatus } from './sidebar/hooks/useProjectRepoStatus'; -import { useProjectSessionLists } from './sidebar/hooks/useProjectSessionLists'; -import { useAuthoritativeSessionCleanup } from './sidebar/hooks/useAuthoritativeSessionCleanup'; -import { createSessionOwnershipIndex } from './sidebar/sessionOwnership'; -import { useStickyProjectHeaders } from './sidebar/hooks/useStickyProjectHeaders'; +import { useSessionSearchEffects } from './sidebar/shell/useSessionSearchEffects'; +import { useSessionProjectViewState } from './sidebar/projects/useSessionProjectViewState'; +import { useProjectRepoStatus } from './sidebar/projects/useProjectRepoStatus'; import { ProjectEditDialog } from '@/components/layout/ProjectEditDialog'; import { UpdateDialog } from '@/components/ui/UpdateDialog'; -import { SessionGroupSection } from './sidebar/SessionGroupSection'; -import { SidebarHeader } from './sidebar/SidebarHeader'; -import { SidebarNav } from './sidebar/SidebarNav'; -import { SidebarActivitySections, type ActivityItem } from './sidebar/SidebarActivitySections'; -import { SidebarFooter } from './sidebar/SidebarFooter'; -import { SidebarProjectsList } from './sidebar/SidebarProjectsList'; -import { SessionNodeItem } from './sidebar/SessionNodeItem'; -import type { SessionNodeRenderExtras } from './sidebar/sessionNodeItemUtils'; +import { SidebarHeader } from './sidebar/shell/SidebarHeader'; +import { SidebarNav } from './sidebar/shell/SidebarNav'; +import { SidebarFooter } from './sidebar/shell/SidebarFooter'; +import { SessionProjectCollection } from './sidebar/list/SessionProjectCollection'; import { useUpdateStore } from '@/stores/useUpdateStore'; import { useShallow } from 'zustand/react/shallow'; import { @@ -55,110 +31,19 @@ import { worktreeMapsEqual, } from '@/lib/worktrees/worktreeManager'; import { checkIsGitRepository } from '@/lib/gitApi'; -import type { WorktreeMetadata } from '@/types/worktree'; -import type { SortableDragHandleProps } from './sidebar/sortableItems'; -import { - BulkSessionDeleteConfirmDialog, - FolderDeleteConfirmDialog, - SessionDeleteConfirmDialog, - type BulkDeleteSessionsConfirmState, - type DeleteFolderConfirmState, - type DeleteSessionConfirmState, -} from './sidebar/ConfirmDialogs'; -import { BulkActionBar } from './sidebar/BulkActionBar'; -import { useSidebarBulkActions } from './sidebar/hooks/useSidebarBulkActions'; import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore'; -import { type SessionGroup, type SessionNode } from './sidebar/types'; -import { - deriveRecentSessions, -} from './sidebar/activitySections'; -import { useSessionPinnedStore } from '@/stores/useSessionPinnedStore'; -import { - formatProjectLabel, - normalizePath, - selectExpandedParentKeysForContext, - toggleExpandedParentKey, -} from './sidebar/utils'; -import { - compareSessionsByLifecycleOrder, - EMPTY_SESSION_ORDER_RANKS, - orderSessionsByLifecycleScopes, - useSessionOrderingStore, -} from '@/sync/session-ordering'; -import { useGlobalSessionStatusStore } from '@/sync/global-session-status'; -import { - refreshGlobalSessions, - refreshGlobalSessionsForDirectories, - getSessionStructuralSignature, - resolveGlobalSessionDirectory, - useGlobalSessionsStore, -} from '@/stores/useGlobalSessionsStore'; -import { useGitHubAuthStore } from '@/stores/useGitHubAuthStore'; -import { useNotificationStore } from '@/sync/notification-store'; -import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs'; -import { getGitHubPrStatusKey, useGitHubPrStatusStore } from '@/stores/useGitHubPrStatusStore'; -import { subscribeOpenchamberEvents } from '@/lib/openchamberEvents'; -import { buildSessionBootstrapDemands } from './sidebar/sessionBootstrapDemands'; -import { recordWorktreesSeen } from './sidebar/worktreeFirstSeen'; +import { normalizePath } from './sidebar/utils'; +import { recordWorktreesSeen } from './sidebar/projects/worktreeFirstSeen'; import { getRuntimeKey } from '@/lib/runtime-switch'; import { streamPerfCount, streamPerfMark } from '@/stores/utils/streamDebug'; import { runBackgroundNetworkTask } from '@/lib/background-network'; -import { isCapacitorApp } from '@/lib/platform'; +import { buildKnownSessionDirectories } from './sidebar/list/sessionListDirectories'; +import { z } from 'zod'; +import { subscribeOpenchamberEvents } from '@/lib/openchamberEvents'; -const PROJECT_COLLAPSE_STORAGE_KEY = 'oc.sessions.projectCollapse'; -const GROUP_ORDER_STORAGE_KEY = 'oc.sessions.groupOrder'; -const GROUP_COLLAPSE_STORAGE_KEY = 'oc.sessions.groupCollapse'; const PROJECT_ACTIVE_SESSION_STORAGE_KEY = 'oc.sessions.activeSessionByProject'; -// v3 holds composite "${renderContext}:${active|archived}:${sessionId}" -// entries so the same session in different render contexts (e.g. "Recent" -// and a project's root) has independent expand state. Older expansion state -// mixed contexts and is intentionally not migrated. -const SESSION_EXPANDED_STORAGE_KEY = 'oc.sessions.expandedParents.v3'; - -const buildKnownSessionDirectories = ( - projects: Array<{ path: string }>, - availableWorktreesByProject: Map, - options?: { includeWorktrees?: boolean }, -): Set => { - const directories = new Set(); - for (const project of projects) { - const normalized = normalizePath(project.path)?.toLowerCase(); - if (normalized) directories.add(normalized); - } - if (options?.includeWorktrees === false) { - return directories; - } - for (const worktrees of availableWorktreesByProject.values()) { - for (const worktree of worktrees) { - const normalized = normalizePath(worktree.path)?.toLowerCase(); - if (normalized) directories.add(normalized); - } - } - return directories; -}; - -const isKnownActiveSessionDirectory = ( - session: Session, - knownDirectories: Set, - options?: { allowUnknownDirectory?: boolean; allowEmptyDirectorySet?: boolean }, -): boolean => { - if (session.time?.archived) return true; - const directory = normalizePath(resolveGlobalSessionDirectory(session))?.toLowerCase(); - if (!directory) return options?.allowUnknownDirectory ?? true; - if (knownDirectories.size === 0) return options?.allowEmptyDirectorySet ?? true; - return knownDirectories.has(directory); -}; - -const SIDEBAR_PR_NO_PR_RETRY_MS = 5 * 60_000; - -const EMPTY_SUBTREE_SET: Set = new Set(); const EMPTY_STRING_ARRAY: string[] = []; - -const useStableRenderCallback = (handler: (...args: Args) => Return): ((...args: Args) => Return) => { - const handlerRef = React.useRef(handler); - handlerRef.current = handler; - return React.useCallback((...args: Args) => handlerRef.current(...args), []); -}; +const activeSessionByProjectSchema = z.record(z.string(), z.string().min(1).catch('')); interface SessionSidebarProps { isVisible?: boolean; @@ -169,106 +54,6 @@ interface SessionSidebarProps { showOnlyMainWorkspace?: boolean; } -const SidebarBootstrapDemandEffect: React.FC<{ - owner: string; - childStores: ReturnType; - projectSections: Parameters[0]['projectSections']; - activeProjectId: string | null; - collapsedProjects: ReadonlySet; - collapsedGroups: ReadonlySet; - currentDirectory: string | null; -}> = ({ - owner, - childStores, - projectSections, - activeProjectId, - collapsedProjects, - collapsedGroups, - currentDirectory, -}) => { - const currentSessionDirectory = useSessionUIStore((state) => state.currentSessionDirectory); - - React.useEffect(() => { - childStores.setBootstrapDemand(owner, buildSessionBootstrapDemands({ - projectSections, - activeProjectId, - collapsedProjects, - collapsedGroups, - currentDirectory, - currentSessionDirectory, - })); - }, [ - activeProjectId, - childStores, - collapsedGroups, - collapsedProjects, - currentDirectory, - currentSessionDirectory, - owner, - projectSections, - ]); - - React.useEffect( - () => () => childStores.clearBootstrapDemand(owner), - [childStores, owner], - ); - - return null; -}; - -// Aggregated activity/attention dot for a collapsed project header. Only -// mounted while the project is collapsed, so the per-status-event scans stay -// rare and bounded by the project's directory count. -const ProjectAggregateStatusIndicator: React.FC<{ directories: Array }> = ({ directories }) => { - const { t } = useI18n(); - const directorySet = React.useMemo(() => { - const set = new Set(); - directories.forEach((directory) => { - const normalized = normalizePath(directory)?.toLowerCase(); - if (normalized) set.add(normalized); - }); - return set; - }, [directories]); - const hasBusySession = useGlobalSessionStatusStore(React.useCallback((state) => { - for (const entry of state.statusById.values()) { - if (entry.status.type !== 'busy' && entry.status.type !== 'retry') continue; - const directory = normalizePath(entry.directory)?.toLowerCase(); - if (directory && directorySet.has(directory)) return true; - } - return false; - }, [directorySet])); - const hasUnseenNotification = useNotificationStore(React.useCallback((state) => { - for (const [directory, count] of Object.entries(state.index.project.unseenCount)) { - if (!count) continue; - const normalized = normalizePath(directory)?.toLowerCase(); - if (normalized && directorySet.has(normalized)) return true; - } - return false; - }, [directorySet])); - - // Aggregate header: dot only. A collapsed project can hold several running - // turns, so a single elapsed counter would have nothing to count. - if (hasBusySession) { - return ( - - ); - } - if (hasUnseenNotification) { - return ( - - ); - } - return null; -}; - const SessionSidebarComponent: React.FC = ({ isVisible = true, mobileVariant = false, @@ -286,91 +71,29 @@ const SessionSidebarComponent: React.FC = ({ const [sessionSearchQuery, setSessionSearchQuery] = React.useState(''); const sessionSearchContainerRef = React.useRef(null); const sessionSearchInputRef = React.useRef(null); - const [editingId, setEditingId] = React.useState(null); - const [editTitle, setEditTitle] = React.useState(''); const [editingProjectDialogId, setEditingProjectDialogId] = React.useState(null); - const [expandedParents, setExpandedParents] = React.useState>(new Set()); const safeStorage = React.useMemo(() => getDeferredSafeStorage(), []); - const [collapsedProjects, setCollapsedProjects] = React.useState>(new Set()); - const [projectRepoStatus, setProjectRepoStatus] = React.useState>(new Map()); - const [visibleSessionCountByGroup, setVisibleSessionCountByGroup] = React.useState>(new Map()); const newWorktreeDialogOpen = useUIStore((state) => state.isNewWorktreeDialogOpen); const setNewWorktreeDialogOpen = useUIStore((state) => state.setNewWorktreeDialogOpen); const [updateDialogOpen, setUpdateDialogOpen] = React.useState(false); - const [openSidebarMenuKey, setOpenSidebarMenuKey] = React.useState(null); - const [renamingFolderId, setRenamingFolderId] = React.useState(null); - const [renameFolderDraft, setRenameFolderDraft] = React.useState(''); - const [deleteSessionConfirm, setDeleteSessionConfirm] = React.useState(null); - const [deleteFolderConfirm, setDeleteFolderConfirm] = React.useState(null); - const [bulkDeleteConfirm, setBulkDeleteConfirm] = React.useState(null); - const pinnedSessionIds = useSessionPinnedStore((state) => state.ids); - const sessionOrderRanks = useSessionOrderingStore(React.useCallback( - (state) => isVisible ? state.rankById : EMPTY_SESSION_ORDER_RANKS, - [isVisible], - )); - const activeSessionIds = useGlobalSessionStatusStore(useShallow( - (state) => isVisible ? [...state.statusById.keys()].sort() : EMPTY_STRING_ARRAY, - )); - const activeSessionIdSet = React.useMemo(() => new Set(activeSessionIds), [activeSessionIds]); - const unreadSessionIds = useNotificationStore(useShallow( - (state) => isVisible - ? Object.entries(state.index.session.unseenCount) - .filter(([, count]) => count > 0) - .map(([sessionId]) => sessionId) - .sort() - : EMPTY_STRING_ARRAY, - )); - const unreadSessionIdSet = React.useMemo(() => new Set(unreadSessionIds), [unreadSessionIds]); - const togglePinnedSession = useSessionPinnedStore((state) => state.toggle); - const [collapsedGroups, setCollapsedGroups] = React.useState>(() => { - try { - const raw = getDeferredSafeStorage().getItem(GROUP_COLLAPSE_STORAGE_KEY); - if (!raw) { - return new Set(); - } - const parsed = JSON.parse(raw) as string[]; - return new Set(Array.isArray(parsed) ? parsed.filter((item) => typeof item === 'string') : []); - } catch { - return new Set(); - } - }); - const [groupOrderByProject, setGroupOrderByProject] = React.useState>(() => { - try { - const raw = getDeferredSafeStorage().getItem(GROUP_ORDER_STORAGE_KEY); - if (!raw) { - return new Map(); - } - const parsed = JSON.parse(raw) as Record; - const next = new Map(); - Object.entries(parsed).forEach(([projectId, order]) => { - if (Array.isArray(order)) { - next.set(projectId, order.filter((item) => typeof item === 'string')); - } - }); - return next; - } catch { - return new Map(); - } - }); const initialActiveSessionByProject = React.useMemo>(() => { try { - const raw = getDeferredSafeStorage().getItem(PROJECT_ACTIVE_SESSION_STORAGE_KEY); + const raw = safeStorage.getItem(PROJECT_ACTIVE_SESSION_STORAGE_KEY); if (!raw) { return new Map(); } - const parsed = JSON.parse(raw) as Record; + const parsed = activeSessionByProjectSchema.safeParse(JSON.parse(raw)); + if (!parsed.success) return new Map(); const next = new Map(); - Object.entries(parsed).forEach(([projectId, sessionId]) => { - if (typeof sessionId === 'string' && sessionId.length > 0) { - next.set(projectId, sessionId); - } + Object.entries(parsed.data).forEach(([projectId, sessionId]) => { + if (sessionId) next.set(projectId, sessionId); }); return next; } catch { return new Map(); } - }, []); + }, [safeStorage]); const persistActiveSessionByProject = React.useCallback((value: Map) => { try { safeStorage.setItem(PROJECT_ACTIVE_SESSION_STORAGE_KEY, JSON.stringify(Object.fromEntries(value.entries()))); @@ -378,11 +101,8 @@ const SessionSidebarComponent: React.FC = ({ }, [safeStorage]); const [projectRootBranches, setProjectRootBranches] = React.useState>(new Map()); - const projectHeaderSentinelRefs = React.useRef>(new Map()); - const ignoreIntersectionUntil = React.useRef(0); const homeDirectory = useDirectoryStore((state) => state.homeDirectory); - const currentDirectory = useDirectoryStore((state) => state.currentDirectory); const projects = useProjectsStore((state) => state.projects); const activeProjectId = useProjectsStore((state) => state.activeProjectId); @@ -391,7 +111,6 @@ const SessionSidebarComponent: React.FC = ({ const updateProjectMeta = useProjectsStore((state) => state.updateProjectMeta); const reorderProjects = useProjectsStore((state) => state.reorderProjects); - const openContextPanelTab = useUIStore((state) => state.openContextPanelTab); const setSettingsDialogOpen = useUIStore((state) => state.setSettingsDialogOpen); const toggleHelpDialog = useUIStore((state) => state.toggleHelpDialog); const setAboutDialogOpen = useUIStore((state) => state.setAboutDialogOpen); @@ -401,8 +120,6 @@ const SessionSidebarComponent: React.FC = ({ const setWorktreesPageProjectId = useUIStore((state) => state.setWorktreesPageProjectId); const openMultiRunLauncher = useUIStore((state) => state.openMultiRunLauncher); const notifyOnSubtasks = useUIStore((state) => state.notifyOnSubtasks); - const showDeletionDialog = useUIStore((state) => state.showDeletionDialog); - const setShowDeletionDialog = useUIStore((state) => state.setShowDeletionDialog); const debouncedSessionSearchQuery = useDebouncedValue(sessionSearchQuery, 120); const normalizedSessionSearchQuery = React.useMemo( @@ -412,19 +129,6 @@ const SessionSidebarComponent: React.FC = ({ const hasSessionSearchQuery = normalizedSessionSearchQuery.length > 0; - // Session Folders store - const collapsedFolderIds = useSessionFoldersStore((state) => state.collapsedFolderIds); - const foldersMap = useSessionFoldersStore((state) => state.foldersMap); - const getFoldersForScope = useSessionFoldersStore((state) => state.getFoldersForScope); - const createFolder = useSessionFoldersStore((state) => state.createFolder); - const renameFolder = useSessionFoldersStore((state) => state.renameFolder); - const deleteFolder = useSessionFoldersStore((state) => state.deleteFolder); - const addSessionToFolder = useSessionFoldersStore((state) => state.addSessionToFolder); - const addSessionsToFolder = useSessionFoldersStore((state) => state.addSessionsToFolder); - const removeSessionFromFolder = useSessionFoldersStore((state) => state.removeSessionFromFolder); - const removeSessionsFromFolders = useSessionFoldersStore((state) => state.removeSessionsFromFolders); - const toggleFolderCollapse = useSessionFoldersStore((state) => state.toggleFolderCollapse); - const getSessionFolderId = useSessionFoldersStore((state) => state.getSessionFolderId); useSessionSearchEffects({ enabled: isVisible, @@ -436,47 +140,16 @@ const SessionSidebarComponent: React.FC = ({ const gitBranches = useGitAllBranches(isVisible); - const sync = useSync(); - const childStores = useChildStoreManager(); - const bootstrapDemandOwner = `session-sidebar:${React.useId()}`; - const liveSessionIndex = getAllSyncSessionMap(); - const liveSessions = React.useMemo(() => Array.from(liveSessionIndex.values()), [liveSessionIndex]); const isVSCode = React.useMemo(() => isVSCodeRuntime(), []); - const runtimeKey = getRuntimeKey(); - const hasAuthoritativeGlobalSessions = useGlobalSessionsStore((state) => state.status === 'ready'); - const activeSessionStructure = useGlobalSessionsStore(useShallow( - (state) => state.activeSessions.map(getSessionStructuralSignature).sort(), - )); - const archivedSessionStructure = useGlobalSessionsStore(useShallow( - (state) => state.archivedSessions.map(getSessionStructuralSignature).sort(), - )); - const globalActiveSessions = useGlobalSessionsStore((state) => state.activeSessions); - const archivedSessions = useGlobalSessionsStore((state) => state.archivedSessions); - const liveFallbackCacheRef = React.useRef<{ signature: string; sessions: Session[] }>({ - signature: '', - sessions: [], - }); - const globalActiveSessionIds = React.useMemo( - () => new Set(globalActiveSessions.map((session) => session.id)), - [globalActiveSessions], - ); - const liveFallbackSessions = (() => { - const candidates = liveSessions.filter((session) => !globalActiveSessionIds.has(session.id)); - const signature = candidates.map(getSessionStructuralSignature).sort().join('\n'); - if (liveFallbackCacheRef.current.signature === signature) { - return liveFallbackCacheRef.current.sessions; - } - liveFallbackCacheRef.current = { signature, sessions: candidates }; - return candidates; - })(); const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession); - const updateSessionTitle = useSessionUIStore((state) => state.updateSessionTitle); - const shareSession = useSessionUIStore((state) => state.shareSession); - const unshareSession = useSessionUIStore((state) => state.unshareSession); // sessionAttentionStates removed — now using notification-store directly in SessionNodeItem const worktreeMetadata = useSessionUIStore((state) => state.worktreeMetadata); const availableWorktreesByProject = useSessionUIStore((state) => state.availableWorktreesByProject); const openNewSessionDraft = useSessionUIStore((state) => state.openNewSessionDraft); + const knownSessionDirectories = React.useMemo( + () => buildKnownSessionDirectories(projects, availableWorktreesByProject, { includeWorktrees: !isVSCode }), + [availableWorktreesByProject, isVSCode, projects], + ); // The sidebar tree's +-buttons (project / group / folder) open a draft but, // unlike selecting an existing session, don't navigate. VS Code's compact view // is driven by the openchamber:navigate event, so switch to chat explicitly @@ -503,37 +176,7 @@ const SessionSidebarComponent: React.FC = ({ restartToUpdate: s.restartToUpdate, }))); - const knownSessionDirectories = React.useMemo( - () => buildKnownSessionDirectories(projects, availableWorktreesByProject, { includeWorktrees: !isVSCode }), - [availableWorktreesByProject, isVSCode, projects], - ); - - const sessions = React.useMemo(() => { - const merged = mergeSidebarSessionSources(globalActiveSessions, liveFallbackSessions); - - return merged.filter((session) => ( - // btw forks stay hidden until promoted to a full session - !isBtwSession(session) - && ( - (!isVSCode && isChatDirectoryPath(session.directory)) - || isKnownActiveSessionDirectory(session, knownSessionDirectories, { - allowUnknownDirectory: !isVSCode, - allowEmptyDirectorySet: !isVSCode, - }) - ) - )); - }, [globalActiveSessions, isVSCode, knownSessionDirectories, liveFallbackSessions]); - - const persistenceSessions = React.useMemo( - () => [...globalActiveSessions, ...archivedSessions], - [archivedSessions, globalActiveSessions], - ); - - const syncSessionsSnapshotRef = React.useRef(liveSessions); - React.useEffect(() => { - syncSessionsSnapshotRef.current = liveSessions; - }, [liveSessions]); - + const runtimeKey = getRuntimeKey(); const projectWorktreeDiscoveryKey = React.useMemo( () => `${runtimeKey}|${projects .map((project) => `${project.id}:${normalizePath(project.path) ?? ''}`) @@ -640,117 +283,17 @@ const SessionSidebarComponent: React.FC = ({ }, [isVSCode, projectWorktreeDiscoveryKey, runtimeKey, worktreeDiscoveryRevision]); React.useEffect(() => { - let refreshTimeout: ReturnType | null = null; - let needsGlobalRefresh = false; - const sessionDirectories = new Set(); - const unsubscribe = subscribeOpenchamberEvents((event) => { - if (event.type === 'scheduled-task-ran') { - needsGlobalRefresh = true; - } else if (event.type === 'session-created') { - sessionDirectories.add(event.directory); - requestWorktreeDiscovery(); - } else { - // Browser control events carry no session state; nothing to refresh. - return; - } - if (refreshTimeout) { - clearTimeout(refreshTimeout); - } - refreshTimeout = setTimeout(() => { - refreshTimeout = null; - if (needsGlobalRefresh) { - needsGlobalRefresh = false; - sessionDirectories.clear(); - void refreshGlobalSessions(syncSessionsSnapshotRef.current); - return; - } - const directories = [...sessionDirectories]; - sessionDirectories.clear(); - if (directories.length > 0) { - void refreshGlobalSessionsForDirectories(directories, syncSessionsSnapshotRef.current); - } - }, 500); + if (isVSCode) return; + return subscribeOpenchamberEvents((event) => { + if (event.type === 'session-created') requestWorktreeDiscovery(); }); - return () => { - if (refreshTimeout) { - clearTimeout(refreshTimeout); - } - unsubscribe(); - }; - }, []); + }, [isVSCode]); const isDesktopShellRuntime = React.useMemo(() => isDesktopShell(), []); const { isTablet } = useDeviceInfo(); const alwaysShowSidebarActions = mobileVariant || isTablet; - const { - buildGroupSearchText, - filterSessionNodesForSearch, - buildGroupedSessions, - } = useSessionGrouping({ - homeDirectory, - worktreeMetadata, - pinnedSessionIds, - sessionOrderRanks, - gitBranches, - isVSCode, - }); - - const { scheduleCollapsedProjectsPersist } = useSidebarPersistence({ - isVSCode, - safeStorage, - keys: { - sessionExpanded: SESSION_EXPANDED_STORAGE_KEY, - projectCollapse: PROJECT_COLLAPSE_STORAGE_KEY, - groupOrder: GROUP_ORDER_STORAGE_KEY, - groupCollapse: GROUP_COLLAPSE_STORAGE_KEY, - }, - groupOrderByProject, - collapsedGroups, - setExpandedParents, - setCollapsedProjects, - }); - - const orderedSessions = React.useMemo(() => { - return orderSessionsByLifecycleScopes(sessions, pinnedSessionIds, sessionOrderRanks); - }, [pinnedSessionIds, sessionOrderRanks, sessions]); - - // Reuse the index while the ordered IDs stay unchanged. - // Without this, a fresh `orderedSessions` array (cheap to rebuild) would - // still hand a new Map identity to the entire SessionGroupSection - // memo chain, invalidating sourceGroupNodes, nodeBySessionId, and the - // rest of the down-stream useMemo chain. - const sessionOrderSignature = React.useMemo( - () => orderedSessions.map((session) => session.id).join('|'), - [orderedSessions], - ); - - const sessionOrderIndexRef = React.useRef<{ signature: string; map: Map } | null>(null); - const sessionOrderIndex = React.useMemo(() => { - const cached = sessionOrderIndexRef.current; - if (cached && cached.signature === sessionOrderSignature) { - return cached.map; - } - const next = new Map(orderedSessions.map((session, index) => [session.id, index])); - sessionOrderIndexRef.current = { signature: sessionOrderSignature, map: next }; - return next; - }, [orderedSessions, sessionOrderSignature]); - - const childrenMap = React.useMemo(() => { - const map = new Map(); - orderedSessions.forEach((session) => { - const parentID = (session as Session & { parentID?: string | null }).parentID; - if (!parentID) { - return; - } - const collection = map.get(parentID) ?? []; - collection.push(session); - map.set(parentID, collection); - }); - map.forEach((list) => list.sort((a, b) => compareSessionsByLifecycleOrder(a, b, pinnedSessionIds, sessionOrderRanks))); - return map; - }, [orderedSessions, pinnedSessionIds, sessionOrderRanks]); const emptyState = React.useMemo(() => (
@@ -819,224 +362,30 @@ const SessionSidebarComponent: React.FC = ({ updateStore.available && (updateStore.runtimeType === 'desktop' || updateStore.runtimeType === 'web'); - const deleteSession = useSessionUIStore((state) => state.deleteSession); - const deleteSessions = useSessionUIStore((state) => state.deleteSessions); - const archiveSession = useSessionUIStore((state) => state.archiveSession); - const archiveSessions = useSessionUIStore((state) => state.archiveSessions); - const unarchiveSession = useSessionUIStore((state) => state.unarchiveSession); - const unarchiveSessions = useSessionUIStore((state) => state.unarchiveSessions); - - const { - copiedSessionId, - handleSessionSelect, - handleSessionDoubleClick, - handleSaveEdit, - handleCancelEdit, - handleShareSession, - handleCopyShareUrl, - handleCopySessionId, - handleUnshareSession, - handleDeleteSession, - handleRestoreSession, - confirmDeleteSession, - } = useSessionActions({ - mobileVariant, - allowReselect, - onSessionSelected, - isSessionSearchOpen, - sessionSearchQuery, - setSessionSearchQuery, - setIsSessionSearchOpen, - setSessionSwitcherOpen, - setCurrentSession, - updateSessionTitle, - shareSession, - unshareSession, - deleteSession, - deleteSessions, - archiveSession, - archiveSessions, - unarchiveSession, - childrenMap, - showDeletionDialog, - setDeleteSessionConfirm, - deleteSessionConfirm, - setEditingId, - setEditTitle, - editingId, - editTitle, - }); - - const confirmDeleteFolder = React.useCallback(() => { - if (!deleteFolderConfirm) return; - const { scopeKey, folderId } = deleteFolderConfirm; - setDeleteFolderConfirm(null); - deleteFolder(scopeKey, folderId); - }, [deleteFolderConfirm, deleteFolder]); - const handleOpenDirectoryDialog = React.useCallback(() => { sessionEvents.requestDirectoryDialog(); }, []); - const toggleParent = React.useCallback((expansionKey: string) => { - setExpandedParents((previous) => { - const next = toggleExpandedParentKey(previous, expansionKey); - try { - safeStorage.setItem(SESSION_EXPANDED_STORAGE_KEY, JSON.stringify(Array.from(next))); - } catch { /* ignored */ } - return next; - }); - }, [safeStorage]); - const createFolderAndStartRename = React.useCallback( - (scopeKey: string, parentId?: string | null) => { - if (!scopeKey) { - return null; - } - - if (parentId && collapsedFolderIds.has(parentId)) { - toggleFolderCollapse(parentId); - } - - const newFolder = createFolder(scopeKey, t('sessions.sidebar.folder.newFolderName'), parentId); - setRenamingFolderId(newFolder.id); - setRenameFolderDraft(newFolder.name); - return newFolder; - }, - [collapsedFolderIds, toggleFolderCollapse, createFolder, t], - ); - - const stableHandleSessionSelect = useStableRenderCallback(handleSessionSelect); - const stableHandleSessionDoubleClick = useStableRenderCallback(handleSessionDoubleClick); - const stableHandleSaveEdit = useStableRenderCallback(handleSaveEdit); - const stableHandleCancelEdit = useStableRenderCallback(handleCancelEdit); - const stableHandleShareSession = useStableRenderCallback(handleShareSession); - const stableHandleCopyShareUrl = useStableRenderCallback(handleCopyShareUrl); - const stableHandleCopySessionId = useStableRenderCallback(handleCopySessionId); - const stableHandleUnshareSession = useStableRenderCallback(handleUnshareSession); - const stableHandleDeleteSession = useStableRenderCallback(handleDeleteSession); - const stableHandleRestoreSession = useStableRenderCallback(handleRestoreSession); - const stableCreateFolderAndStartRename = useStableRenderCallback(createFolderAndStartRename); - - const showMoreGroupSessions = React.useCallback((groupId: string, currentVisibleCount: number, increment: number = 7) => { - setVisibleSessionCountByGroup((prev) => { - const next = new Map(prev); - next.set(groupId, currentVisibleCount + increment); - return next; - }); - }, []); - - const resetGroupSessionLimit = React.useCallback((groupId: string) => { - setVisibleSessionCountByGroup((prev) => { - if (!prev.has(groupId)) { - return prev; - } - const next = new Map(prev); - next.delete(groupId); - return next; - }); - }, []); - - const resetProjectSessionLimits = React.useCallback((projectId: string) => { - setVisibleSessionCountByGroup((prev) => { - let changed = false; - const next = new Map(prev); - const projectGroupPrefix = `${projectId}:`; - for (const groupId of next.keys()) { - if (groupId.startsWith(projectGroupPrefix)) { - next.delete(groupId); - changed = true; - } - } - return changed ? next : prev; - }); - }, []); - - // Collapse/expand covers both levels: projects and their worktree groups. - const projectSectionsRef = React.useRef([]); - - const collapseAllProjects = React.useCallback(() => { - ignoreIntersectionUntil.current = Date.now() + 150; - setVisibleSessionCountByGroup(new Map()); - setCollapsedGroups(() => { - const allGroupKeys = new Set(); - projectSectionsRef.current.forEach((section) => { - section.groups.forEach((group) => { - if (!group.isMain) allGroupKeys.add(`${section.project.id}:${group.id}`); - }); - }); - return allGroupKeys; - }); - setCollapsedProjects(() => { - const allIds = new Set(projects.map((p) => p.id)); - try { - safeStorage.setItem(PROJECT_COLLAPSE_STORAGE_KEY, JSON.stringify(Array.from(allIds))); - } catch { /* ignored */ } - if (!isVSCode) { - scheduleCollapsedProjectsPersist(allIds); - } - return allIds; - }); - }, [projects, isVSCode, safeStorage, scheduleCollapsedProjectsPersist]); - - const expandAllProjects = React.useCallback(() => { - ignoreIntersectionUntil.current = Date.now() + 150; - setVisibleSessionCountByGroup(new Map()); - setCollapsedGroups(new Set()); - setCollapsedProjects(() => { - const empty = new Set(); - try { - safeStorage.setItem(PROJECT_COLLAPSE_STORAGE_KEY, JSON.stringify([])); - } catch { /* ignored */ } - if (!isVSCode) { - scheduleCollapsedProjectsPersist(empty); - } - return empty; - }); - }, [isVSCode, safeStorage, scheduleCollapsedProjectsPersist]); - - const toggleProject = React.useCallback((projectId: string) => { - // Ignore intersection events for a short period after toggling - ignoreIntersectionUntil.current = Date.now() + 150; - resetProjectSessionLimits(projectId); - setCollapsedProjects((prev) => { - const next = new Set(prev); - if (next.has(projectId)) { - next.delete(projectId); - } else { - next.add(projectId); - } - try { - safeStorage.setItem(PROJECT_COLLAPSE_STORAGE_KEY, JSON.stringify(Array.from(next))); - } catch { /* ignored */ } - - // Persist collapse state to server settings (web + desktop local/remote). - if (!isVSCode) { - scheduleCollapsedProjectsPersist(next); - } - return next; - }); - }, [isVSCode, resetProjectSessionLimits, safeStorage, scheduleCollapsedProjectsPersist]); const normalizedProjects = React.useMemo(() => { - return projects - .map((project) => ({ - ...project, - normalizedPath: normalizePath(project.path), - })) - .filter((project) => Boolean(project.normalizedPath)) as Array<{ - id: string; - path: string; - label?: string; - normalizedPath: string; - icon?: string; - color?: string; - iconImage?: { mime: string; updatedAt: number; source: 'custom' | 'auto' }; - iconBackground?: string; - addedAt?: number; - lastOpenedAt?: number; - sidebarCollapsed?: boolean; - }>; + return projects.flatMap((project) => { + const normalizedPath = normalizePath(project.path); + if (!normalizedPath) return []; + return [{ + id: project.id, + path: project.path, + label: project.label, + normalizedPath, + icon: project.icon ?? undefined, + color: project.color ?? undefined, + iconImage: project.iconImage ?? undefined, + iconBackground: project.iconBackground ?? undefined, + addedAt: project.addedAt, + lastOpenedAt: project.lastOpenedAt, + sidebarCollapsed: project.sidebarCollapsed, + }]; + }); }, [projects]); const normalizedProjectPaths = React.useMemo( @@ -1044,47 +393,7 @@ const SessionSidebarComponent: React.FC = ({ [normalizedProjects], ); - const projectSessionDirectories = React.useMemo(() => { - const directories = new Set(normalizedProjects.map((project) => project.normalizedPath)); - if (!isVSCode) { - for (const worktrees of availableWorktreesByProject.values()) { - for (const worktree of worktrees) { - const directory = normalizePath(worktree.path); - if (directory) directories.add(directory); - } - } - } - return [...directories].sort(); - }, [availableWorktreesByProject, isVSCode, normalizedProjects]); - - const knownProjectSessionDirectoriesRef = React.useRef | null>(null); - React.useEffect(() => { - const nextDirectories = new Set(projectSessionDirectories); - const previousDirectories = knownProjectSessionDirectoriesRef.current; - knownProjectSessionDirectoriesRef.current = nextDirectories; - if (!previousDirectories) { - if (isVSCode && projectSessionDirectories.length > 0) { - void refreshGlobalSessionsForDirectories(projectSessionDirectories, syncSessionsSnapshotRef.current); - } - return; - } - - const addedDirectories = projectSessionDirectories.filter((directory) => !previousDirectories.has(directory)); - if (addedDirectories.length === 0) { - return; - } - - void refreshGlobalSessionsForDirectories(addedDirectories, syncSessionsSnapshotRef.current); - }, [isVSCode, projectSessionDirectories]); - - const { github } = useRuntimeAPIs(); - const githubAuthStatus = useGitHubAuthStore((state) => state.status); - const githubAuthChecked = useGitHubAuthStore((state) => state.hasChecked); const gitRepoStatus = useGitRepoStatusMap(isVisible ? normalizedProjectPaths : EMPTY_STRING_ARRAY); - const ensurePrStatusEntry = useGitHubPrStatusStore((state) => state.ensureEntry); - const setPrStatusParams = useGitHubPrStatusStore((state) => state.setParams); - const refreshPrStatusTargets = useGitHubPrStatusStore((state) => state.refreshTargets); - useProjectRepoStatus({ enabled: isVisible, normalizedProjects, @@ -1094,64 +403,16 @@ const SessionSidebarComponent: React.FC = ({ }); const isSessionsLoading = useSessionUIStore((state) => state.isLoading); - const sessionOwnership = React.useMemo( - () => createSessionOwnershipIndex(sessions, normalizedProjects, availableWorktreesByProject, isVSCode, archivedSessions), - [archivedSessions, availableWorktreesByProject, isVSCode, normalizedProjects, sessions], - ); - useAuthoritativeSessionCleanup({ - enabled: isVisible, - hasAuthoritativeGlobalSessions, - sessions: persistenceSessions, - }); - - const { getSessionsForProject, getArchivedSessionsForProject } = useProjectSessionLists({ - ownership: sessionOwnership, - }); - - useArchivedAutoFolders({ - enabled: isVisible, - normalizedProjects, - ownership: sessionOwnership, - isSessionsLoading, - hasAuthoritativeGlobalSessions, - isWorktreeTopologyLoading, - unresolvedWorktreeProjectPaths, - foldersMap, - createFolder, - addSessionToFolder, - }); - // Keep last-known repo status to avoid UI jiggling during project switch const lastRepoStatusRef = React.useRef(false); if (activeProjectId && projectRepoStatus.has(activeProjectId)) { lastRepoStatusRef.current = Boolean(projectRepoStatus.get(activeProjectId)); } - const showRecentSection = useSessionDisplayStore((state) => state.showRecentSection); - const projectDisplayMode = useSessionDisplayStore((state) => state.projectDisplayMode); - const singleProjectId = useSessionDisplayStore((state) => state.singleProjectId); - const setSingleProjectId = useSessionDisplayStore((state) => state.setSingleProjectId); const showArchivedSessions = useSessionDisplayStore((state) => state.showArchivedSessions); const projectSortOrder = useSessionDisplayStore((state) => state.projectSortOrder); const stickyZoneHeaders = useSessionDisplayStore((state) => state.stickyZoneHeaders); const manualProjectOrder = useProjectsStore((state) => state.manualProjectOrder); - const supportsSingleProjectMode = !isVSCode && !isCapacitorApp(); - const isSingleProjectMode = projectDisplayMode === 'single' && supportsSingleProjectMode; - const shouldShowRecentSection = showRecentSection && !isSingleProjectMode; - const projectExpandedParentsRef = React.useRef>(new Set()); - const recentExpandedParentsRef = React.useRef>(new Set()); - const projectExpandedParents = selectExpandedParentKeysForContext( - projectExpandedParentsRef.current, - expandedParents, - 'project', - ); - const recentExpandedParents = selectExpandedParentKeysForContext( - recentExpandedParentsRef.current, - expandedParents, - 'recent', - ); - projectExpandedParentsRef.current = projectExpandedParents; - recentExpandedParentsRef.current = recentExpandedParents; const sidebarRenderSources = { isVisible, @@ -1162,27 +423,14 @@ const SessionSidebarComponent: React.FC = ({ showOnlyMainWorkspace, t, isTablet, - liveSessions, - activeSessionStructure, - archivedSessionStructure, - globalActiveSessions, - archivedSessions, projects, activeProjectId, manualProjectOrder, - currentDirectory, worktreeMetadata, availableWorktreesByProject, - pinnedSessionIds, - sessionOrderRanks, - foldersMap, - collapsedFolderIds, gitBranches, gitRepoStatus, - githubAuthStatus, - githubAuthChecked, updateStore, - showRecentSection: shouldShowRecentSection, showArchivedSessions, projectSortOrder, projectRepoStatus, @@ -1191,25 +439,14 @@ const SessionSidebarComponent: React.FC = ({ unresolvedWorktreeProjectPaths, isSessionSearchOpen, sessionSearchQuery, - editingId, - editTitle, editingProjectDialogId, - expandedParents, - collapsedProjects, - visibleSessionCountByGroup, updateDialogOpen, - openSidebarMenuKey, - renamingFolderId, - renameFolderDraft, - deleteSessionConfirm, - deleteFolderConfirm, - bulkDeleteConfirm, - collapsedGroups, }; const previousSidebarRenderSourcesRef = React.useRef(null); const previousSidebarRenderSources = previousSidebarRenderSourcesRef.current; if (previousSidebarRenderSources) { let attributed = false; + // SAFETY: Object.keys is constrained to the immediately constructed object's own keys. for (const source of Object.keys(sidebarRenderSources) as Array) { if (!Object.is(previousSidebarRenderSources[source], sidebarRenderSources[source])) { streamPerfCount(`ui.session_sidebar.source.${source}`); @@ -1259,30 +496,7 @@ const SessionSidebarComponent: React.FC = ({ return list; }, [normalizedProjects, projectSortOrder, manualProjectOrder]); - - const { - projectSections, - groupSearchDataByGroup, - sectionsForRender, - flatSectionsForRender, - searchMatchCount, - } = useSessionSidebarSections({ - normalizedProjects: sortedProjects, - getSessionsForProject, - getArchivedSessionsForProject, - availableWorktreesByProject, - projectRepoStatus, - projectRootBranches, - lastRepoStatus: lastRepoStatusRef.current, - buildGroupedSessions, - hasSessionSearchQuery, - normalizedSessionSearchQuery, - filterSessionNodesForSearch, - buildGroupSearchText, - foldersMap, - }); - - projectSectionsRef.current = projectSections; + const projectView = useSessionProjectViewState({ isVSCode, projects: sortedProjects }); const searchEmptyState = React.useMemo(() => (
@@ -1291,143 +505,6 @@ const SessionSidebarComponent: React.FC = ({
), [t]); - const { getOrderedGroups } = useGroupOrdering(groupOrderByProject); - const hasInitializedArchivedCollapseRef = React.useRef(false); - - React.useEffect(() => { - if (hasInitializedArchivedCollapseRef.current || projectSections.length === 0) { - return; - } - const archivedGroupKeys = projectSections.flatMap((section) => - section.groups - .filter((group) => group.isArchivedBucket) - .map((group) => `${section.project.id}:${group.id}`), - ); - if (archivedGroupKeys.length > 0) { - setCollapsedGroups((prev) => new Set([...prev, ...archivedGroupKeys])); - } - hasInitializedArchivedCollapseRef.current = true; - }, [projectSections]); - - const sessionSidebarMetaById = React.useMemo(() => { - const meta = new Map(); - const projectPathLengthBySessionId = new Map(); - - projectSections.forEach((section) => { - const projectLabel = formatProjectLabel( - section.project.label?.trim() - || formatDirectoryName(section.project.normalizedPath, homeDirectory) - || section.project.normalizedPath, - ); - section.groups.forEach((group) => { - const branchCandidate = group.branch && group.branch !== 'HEAD' && group.branch !== projectLabel - ? group.branch - : null; - const secondaryMeta = { projectLabel, branchLabel: branchCandidate }; - - const visit = (nodes: SessionNode[]) => { - nodes.forEach((node) => { - const nextProjectPathLength = section.project.normalizedPath.length; - const currentProjectPathLength = projectPathLengthBySessionId.get(node.session.id) ?? -1; - if (nextProjectPathLength < currentProjectPathLength) { - return; - } - - meta.set(node.session.id, { - node, - projectId: section.project.id, - groupDirectory: group.directory, - secondaryMeta, - }); - projectPathLengthBySessionId.set(node.session.id, nextProjectPathLength); - if (node.children.length > 0) { - visit(node.children); - } - }); - }; - - visit(group.sessions); - }); - }); - - return meta; - }, [projectSections, homeDirectory]); - - const recentSessions = React.useMemo(() => { - if (!shouldShowRecentSection || isVSCode) { - return []; - } - - return deriveRecentSessions(sessions.filter((session) => !isChatDirectoryForHome(session.directory, homeDirectory)), activeSessionIdSet) - .sort((a, b) => compareSessionsByLifecycleOrder(a, b, pinnedSessionIds, sessionOrderRanks)); - }, [activeSessionIdSet, homeDirectory, isVSCode, pinnedSessionIds, sessionOrderRanks, sessions, shouldShowRecentSection]); - - const chatSessions = React.useMemo(() => sessions - .filter((session) => !session.parentID && !session.time?.archived && isChatDirectoryForHome(session.directory, homeDirectory)) - .sort((a, b) => compareSessionsByLifecycleOrder(a, b, pinnedSessionIds, sessionOrderRanks)), [homeDirectory, pinnedSessionIds, sessionOrderRanks, sessions]); - - // Prefetch is wired below, after recentSessions is computed. - - const activitySections = React.useMemo(() => { - // VS Code renders the full grouped project view (one group per open - // workspace, folders + pinned native); the flat "recent" activity list is - // web/desktop-only. - if (isVSCode) { - return []; - } - - const toItem = (session: Session) => { - const existing = sessionSidebarMetaById.get(session.id); - const sessionDirectory = normalizePath(session.directory ?? null); - const node = existing?.node ?? { session, children: [], worktree: null }; - const filteredNodes = hasSessionSearchQuery - ? filterSessionNodesForSearch([node], normalizedSessionSearchQuery) - : [node]; - const filteredNode = filteredNodes[0]; - if (!filteredNode) { - return null; - } - const secondaryMeta = existing?.secondaryMeta - ? { - projectLabel: existing.secondaryMeta.projectLabel, - branchLabel: isVSCode ? null : existing.secondaryMeta.branchLabel, - } - : null; - return { - node: filteredNode, - projectId: existing?.projectId ?? null, - groupDirectory: existing?.groupDirectory ?? sessionDirectory, - secondaryMeta, - }; - }; - - const recentItems = shouldShowRecentSection ? recentSessions - .map(toItem) - .filter((item): item is NonNullable> => item !== null) : []; - - const chatItems = chatSessions - .map(toItem) - .filter((item): item is NonNullable> => item !== null); - return [ - { key: 'chats' as const, title: t('sessions.sidebar.activity.chatsTitle'), items: chatItems }, - { key: 'active-now' as const, title: t('sessions.sidebar.activity.recentTitle'), items: recentItems }, - ]; - }, [chatSessions, filterSessionNodesForSearch, hasSessionSearchQuery, isVSCode, normalizedSessionSearchQuery, recentSessions, sessionSidebarMetaById, shouldShowRecentSection, t]); - - const hasActivitySectionItems = React.useMemo( - () => activitySections.some((section) => section.key === 'chats' || section.items.length > 0), - [activitySections], - ); - - // Web/desktop route archived sessions to the Archive page; only the VS Code // compact webview keeps inline archived buckets behind its toggle. const showInlineArchived = isVSCode && showArchivedSessions; @@ -1436,326 +513,19 @@ const SessionSidebarComponent: React.FC = ({ // worktree groups, so both resolve to the same shape — use flat there. const sessionGroupingMode = useSessionDisplayStore((state) => state.sessionGroupingMode); const useGroupedSections = sessionGroupingMode === 'by-worktree' && !isVSCode; - const sectionsForSidebarRender = React.useMemo(() => { - const source = useGroupedSections ? sectionsForRender : flatSectionsForRender; - return showInlineArchived - ? source - : source.map((section) => ( - section.groups.some((group) => group.isArchivedBucket) - ? { ...section, groups: section.groups.filter((group) => !group.isArchivedBucket) } - : section - )); - }, [flatSectionsForRender, sectionsForRender, showInlineArchived, useGroupedSections]); - const effectiveSingleProjectId = React.useMemo(() => { - if (!isSingleProjectMode) return null; - if (singleProjectId && projectSections.some((section) => section.project.id === singleProjectId)) { - return singleProjectId; - } - if (activeProjectId && projectSections.some((section) => section.project.id === activeProjectId)) { - return activeProjectId; - } - return projectSections[0]?.project.id ?? null; - }, [activeProjectId, isSingleProjectMode, projectSections, singleProjectId]); - const handleSingleProjectSelect = React.useCallback((projectId: string) => { - setSingleProjectId(projectId); - }, [setSingleProjectId]); - - // Discover/refresh PR status for expanded projects' worktree branches so - // session rows can tint their branch marker and show PR state in tooltips. - // The data source is the worktree-grouped projectSections (data layer), not - // the flat display sections. - const retriedNoPrStatusKeysRef = React.useRef>(new Set()); - React.useEffect(() => { - if (!isVisible || !githubAuthChecked || !githubAuthStatus?.connected || !github) { - return; - } - - const targetsByKey = new Map(); - const now = Date.now(); - - projectSections.forEach((section) => { - if (collapsedProjects.has(section.project.id)) { - return; - } - - section.groups.forEach((group) => { - if (group.isArchivedBucket || group.isMain) { - return; - } - const directory = normalizePath(group.directory ?? null); - const branch = group.branch?.trim() || gitBranches.get(directory || '')?.trim(); - if (!directory || !branch) { - return; - } - const key = getGitHubPrStatusKey(directory, branch); - const entry = useGitHubPrStatusStore.getState().entries[key]; - const prState = entry?.status?.pr?.state; - const isTerminalPr = prState === 'closed' || prState === 'merged'; - // Closed/merged associations are not live branch status — retry them on - // the same cadence as missing PRs so a newer open PR can appear. - const hasLivePr = Boolean(entry?.status?.pr) && !isTerminalPr; - const retryKey = `${directory}::${branch}`; - const noPrLastCheckedAt = Math.max(entry?.lastRefreshAt ?? 0, entry?.lastDiscoveryPollAt ?? 0); - const shouldRetryNoPr = Boolean( - entry?.isInitialStatusResolved - && !hasLivePr - && ( - !retriedNoPrStatusKeysRef.current.has(retryKey) - || now - noPrLastCheckedAt >= SIDEBAR_PR_NO_PR_RETRY_MS - ), - ); - - if (!entry || !entry.isInitialStatusResolved || shouldRetryNoPr) { - if (shouldRetryNoPr) { - retriedNoPrStatusKeysRef.current.add(retryKey); - } - if (!targetsByKey.has(key)) { - targetsByKey.set(key, { directory, branch }); - } - } - }); - }); - - if (targetsByKey.size === 0) { - return; - } - - targetsByKey.forEach((target, key) => { - ensurePrStatusEntry(key); - setPrStatusParams(key, { - directory: target.directory, - branch: target.branch, - remoteName: null, - canShow: true, - github, - githubAuthChecked, - githubConnected: githubAuthStatus.connected, - }); - }); - - void refreshPrStatusTargets([...targetsByKey.values()], { - silent: true, - markInitialResolved: true, - }); - }, [ - collapsedProjects, - ensurePrStatusEntry, - github, - githubAuthChecked, - githubAuthStatus?.connected, - isVisible, - gitBranches, - projectSections, - refreshPrStatusTargets, - setPrStatusParams, - ]); - const desktopHeaderActionButtonClass = 'inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed'; const mobileHeaderActionButtonClass = 'inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed'; const headerActionButtonClass = mobileVariant ? mobileHeaderActionButtonClass : desktopHeaderActionButtonClass; const headerActionIconClass = 'h-4.5 w-4.5'; - const stuckProjectHeaders = useStickyProjectHeaders({ - enabled: isVisible && stickyZoneHeaders, - isDesktopShellRuntime, - projectSections, - projectHeaderSentinelRefs, - }); - const renderSessionNode = useStableRenderCallback( - ( - node: SessionNode, - depth: number = 0, - groupDirectory?: string | null, - projectId?: string | null, - archivedBucket: boolean = false, - secondaryMeta?: { projectLabel?: string | null; branchLabel?: string | null } | null, - renderContext: 'project' | 'recent' = 'project', - renderExtras?: SessionNodeRenderExtras, - ): React.ReactNode => ( - - ), - ); - - // Selection scope is the project id; bulk folder actions need the project's - // directory scopes (root + worktrees) to resolve folders across worktrees. - const folderScopesByProject = React.useMemo(() => { - const map = new Map>(); - flatSectionsForRender.forEach((section) => { - const flatGroup = section.groups.find((group) => !group.isArchivedBucket); - if (flatGroup?.folderScopes && flatGroup.folderScopes.length > 0) { - map.set(section.project.id, flatGroup.folderScopes); - } - }); - return map; - }, [flatSectionsForRender]); - - const renderProjectStatusIndicator = React.useCallback((_projectId: string, groups: SessionGroup[]) => { - const directories: Array = []; - groups.forEach((group) => { - if (group.isArchivedBucket) return; - directories.push(group.directory); - group.folderScopes?.forEach((scope) => directories.push(scope.directory)); - }); - return ; - }, []); - - const toggleCollapsedGroup = React.useCallback((key: string) => { - resetGroupSessionLimit(key); - setCollapsedGroups((prev) => { - const next = new Set(prev); - if (next.has(key)) next.delete(key); - else next.add(key); - return next; - }); - }, [resetGroupSessionLimit]); - - const renderGroupSessions = React.useCallback( - ( - group: SessionGroup, - groupKey: string, - projectId?: string | null, - hideGroupLabel?: boolean, - dragHandleProps?: SortableDragHandleProps | null, - compactBodyPadding?: boolean, - scrollContainerRef?: React.RefObject, - ) => ( - - ), - [ - hasSessionSearchQuery, - normalizedSessionSearchQuery, - groupSearchDataByGroup, - visibleSessionCountByGroup, - isSingleProjectMode, - sessionGroupingMode, - collapsedGroups, - hideDirectoryControls, - collapsedFolderIds, - toggleFolderCollapse, - renameFolder, - deleteFolder, - showDeletionDialog, - renderSessionNode, - showMoreGroupSessions, - resetGroupSessionLimit, - mobileVariant, - alwaysShowSidebarActions, - activeProjectId, - setActiveProjectIdOnly, - setSessionSwitcherOpen, - openNewSessionDraftFromTree, - addSessionToFolder, - stableCreateFolderAndStartRename, - renamingFolderId, - renameFolderDraft, - pinnedSessionIds, - projectExpandedParents, - sessionOrderIndex, - editingId, - editTitle, - openSidebarMenuKey, - activeSessionIdSet, - unreadSessionIdSet, - notifyOnSubtasks, - toggleCollapsedGroup, - ], - ); + const handleOpenMultiRunFromHeader = React.useCallback(() => { + if (mobileVariant) { + setSessionSwitcherOpen(false); + } + openMultiRunLauncher(); + }, [mobileVariant, openMultiRunLauncher, setSessionSwitcherOpen]); const handleOpenNewSessionDraftFromHeader = React.useCallback(() => { useUIStore.getState().closeMainSurfaces(); @@ -1765,92 +535,6 @@ const SessionSidebarComponent: React.FC = ({ openNewSessionDraft(); }, [mobileVariant, openNewSessionDraft, setSessionSwitcherOpen]); - const renderChatsSection = React.useCallback((items: ActivityItem[]) => { - const chatsRoot = getChatsRootForHome(homeDirectory) - ?? items.map((item) => getChatsRootFromDirectory(item.node.session.directory)).find(Boolean) - ?? null; - if (!chatsRoot) return items.map((item) => renderSessionNode(item.node, 0, item.groupDirectory)); - - const folderDirectories = [ - chatsRoot, - ...items.map((item) => normalizePath(item.node.session.directory ?? null)).filter((directory): directory is string => Boolean(directory)), - ]; - const folderScopes = Array.from(new Set(folderDirectories)).map((directory) => ({ - scopeKey: directory, - directory, - })); - const group: SessionGroup = { - id: 'managed-chats', - label: '', - branch: null, - description: null, - isMain: true, - worktree: null, - directory: chatsRoot, - folderScopeKey: chatsRoot, - folderScopes, - draftTarget: 'chat', - emptyMessage: t('sessions.sidebar.activity.chatsEmpty'), - sessions: items.map((item) => item.node), - }; - return renderGroupSessions(group, 'managed-chats', null, true); - }, [homeDirectory, renderGroupSessions, renderSessionNode, t]); - - const topContent = React.useMemo( - () => (!isVSCode && !hasSessionSearchQuery && hasActivitySectionItems) ? ( - - ) : null, - [activitySections, alwaysShowSidebarActions, editingId, handleOpenNewSessionDraftFromHeader, hasActivitySectionItems, hasSessionSearchQuery, isDesktopShellRuntime, isVSCode, openSidebarMenuKey, recentExpandedParents, renderChatsSection, renderSessionNode], - ); - const isInlineEditing = Boolean(renamingFolderId || editingId || editingProjectDialogId); - - const { - selectionModeEnabled, - hasSelection, - selectedIdsSize, - bulkScopeIsArchived, - derivedSelectionScope, - bulkScopeFolders, - bulkCanRemoveFromFolder, - handleToggleSelectionMode, - handleExitSelectionMode, - handleBulkMoveToFolder, - handleBulkCreateFolderAndMove, - handleBulkRemoveFromFolder, - handleBulkDelete, - handleBulkRestore, - confirmBulkDelete, - } = useSidebarBulkActions({ - isInlineEditing, - showDeletionDialog, - foldersMap, - folderScopesByProject, - addSessionsToFolder, - removeSessionsFromFolders, - createFolderAndStartRename, - archiveSessions, - unarchiveSessions, - deleteSessions, - setBulkDeleteConfirm, - }); - const handleOpenMultiRunFromHeader = React.useCallback(() => { - if (mobileVariant) { - setSessionSwitcherOpen(false); - } - openMultiRunLauncher(); - }, [mobileVariant, openMultiRunLauncher, setSessionSwitcherOpen]); - return ( // One shared tooltip provider for the whole sidebar: session tooltips open // instantly, and moving between rows hands the tooltip over (grouping) @@ -1866,39 +550,13 @@ const SessionSidebarComponent: React.FC = ({ mobileVariant ? '' : 'bg-transparent', )} > - - - {!hideDirectoryControls && !isVSCode ? ( ) : null} { @@ -1919,74 +577,71 @@ const SessionSidebarComponent: React.FC = ({ sessionSearchQuery={sessionSearchQuery} setSessionSearchQuery={setSessionSearchQuery} hasSessionSearchQuery={hasSessionSearchQuery} - searchMatchCount={searchMatchCount} - collapseAllProjects={collapseAllProjects} - expandAllProjects={expandAllProjects} - selectionModeEnabled={selectionModeEnabled} - onToggleSelectionMode={handleToggleSelectionMode} + searchMatchCount={0} + collapseAllProjects={projectView.actions.collapseAllProjects} + expandAllProjects={projectView.actions.expandAllProjects} /> - {isVisible ? { - if (mobileVariant) setSessionSwitcherOpen(false); - setWorktreesPageProjectId(projectId); + : null} - - {selectionModeEnabled && hasSelection ? ( - - ) : null} + view={{ + isVisible, + hasSessionSearchQuery, + normalizedSessionSearchQuery, + activeProjectId, + showInlineArchived, + useGroupedSections, + homeDirectory, + mobileVariant, + hideDirectoryControls, + showOnlyMainWorkspace, + isDesktopShellRuntime, + stickyZoneHeaders, + projectSortOrder, + emptyState, + searchEmptyState, + isSessionsLoading, + isWorktreeTopologyLoading, + unresolvedWorktreeProjectPaths, + projectView: projectView.state, + }} + actions={{ + rowActions: { + allowReselect, + onSessionSelected, + isSessionSearchOpen, + sessionSearchQuery, + setSessionSearchQuery, + setIsSessionSearchOpen, + }, + alwaysShowActions: alwaysShowSidebarActions, + notifyOnSubtasks, + setActiveProjectIdOnly, + setSessionSwitcherOpen, + openNewSessionDraft: openNewSessionDraftFromTree, + openNewWorktreeDialog, + openWorktreesPage: (projectId) => { + if (mobileVariant) setSessionSwitcherOpen(false); + setWorktreesPageProjectId(projectId); + }, + openProjectEditDialog: setEditingProjectDialogId, + removeProject, + reorderProjects, + initialActiveSessionByProject, + persistActiveSessionByProject, + projectViewActions: projectView.actions, + }} + /> = ({ open={newWorktreeDialogOpen} onOpenChange={setNewWorktreeDialogOpen} onWorktreeCreated={(worktreePath, options) => { - if (mobileVariant) { + useUIStore.getState().closeMainSurfaces(); + if (mobileVariant) { setSessionSwitcherOpen(false); } if (options?.sessionId) { @@ -2036,27 +692,6 @@ const SessionSidebarComponent: React.FC = ({ }} /> - - - - -
); diff --git a/packages/ui/src/components/session/SessionSwitcherDropdown.tsx b/packages/ui/src/components/session/SessionSwitcherDropdown.tsx index f2adfc74..91a874cc 100644 --- a/packages/ui/src/components/session/SessionSwitcherDropdown.tsx +++ b/packages/ui/src/components/session/SessionSwitcherDropdown.tsx @@ -11,7 +11,7 @@ import { Icon } from '@/components/icon/Icon'; import { useSessionUIStore } from '@/sync/session-ui-store'; import { useGlobalSessionStatus } from '@/sync/sync-context'; import { useSessionUnseenCount } from '@/sync/notification-store'; -import { useSwitcherItems, type SwitcherItem } from '@/components/session/sidebar/hooks/useSwitcherItems'; +import { useSwitcherItems, type SwitcherItem } from '@/components/session/sidebar/shell/useSwitcherItems'; import { useUIStore } from '@/stores/useUIStore'; import { resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore'; import { formatSessionCompactDateLabel } from './sidebar/utils'; diff --git a/packages/ui/src/components/session/sidebar/DOCUMENTATION.md b/packages/ui/src/components/session/sidebar/DOCUMENTATION.md index 0e894e2d..15a94964 100644 --- a/packages/ui/src/components/session/sidebar/DOCUMENTATION.md +++ b/packages/ui/src/components/session/sidebar/DOCUMENTATION.md @@ -1,89 +1,37 @@ -# Session Sidebar Documentation +# Session Sidebar -## Refactor result +Sidebar code is organized by the business object it owns. Shared contracts are +kept at this root in `types.ts` and `utils.tsx`. -- `SessionSidebar.tsx` now acts mainly as orchestration; core logic moved to focused hooks/components. -- Layout (web/desktop): top navigation (`SidebarNav`: New session, Scheduled, Multi-run, Archive), then the `recent` zone, then one zone per project with a **flat** session list. There is no rendered worktree grouping level. -- **Two grouping display modes** (`useSessionDisplayStore.sessionGroupingMode`, toggled in the view dropdown): `'by-worktree'` (default) renders the worktree-grouped `sectionsForRender` with slim PR-aware branch sub-headers inside each project zone; `'flat'` renders `flatSectionsForRender` — one merged non-archived group per project (`id: 'flat'`, `folderScopes` listing every contributing scope) with per-row branch markers. Both derive from the same `projectSections` data layer, which alone feeds bootstrap demand planning and PR polling. -- **Project display is independent from grouping.** `'all'` keeps every project zone; `'single'` is web/desktop/PWA-only and renders one selected project under the always-present Chats section. Its project header is a non-collapsible picker ordered by the current project sort. Recent and collapse/expand-all controls are hidden without changing their persisted preferences. Opening a materialized project session updates the picker from the session's confirmed directory; changing only a draft target does not. In `'single'` + `'flat'`, active sessions reveal in batches of 20. `'single'` + `'by-worktree'` retains the ordinary per-group limits. Project display mode, session grouping, project sort, and the Recent preference are server-backed shared settings with the hydrated browser store as the migration/failure cache. The selected single project and sticky-header preference remain device-local. -- When sticky zone headers are enabled, project headers are sticky "zone" bands (`SortableProjectItem`); on a vibrant desktop the scrolling content fades behind an unmasked, non-interactive copy of the stuck icon/title without painting a background. The transparent fade zone blocks interaction with obscured rows. The `recent` section uses the same overlay while it is the leading sticky header. Collapsed projects show an aggregated busy/unseen indicator (`ProjectAggregateStatusIndicator`), derived from the live status index and notification store scoped to the project's directories. -- **Activity is a dot plus a counter, never a spinner.** The row's left gutter shows a static dot — primary while the session runs (`busy`/`retry`), info while it is unread — and the metadata slot on the right swaps the goal/branch/date group for the elapsed time of the turn (`SessionActivityDuration`, ticking once per second). The readout takes the dot's color in each state — primary while running, info once it is waiting to be read — so the pair reads as one indicator. A running spinner repainted a composited layer per row every frame for the whole turn; the counter conveys the same "something is happening" at 1 fps. The counter follows the unread marker's lifetime exactly: it survives the turn ending, disappears when the session is read, and never lingers on the session being watched (which is marked read as it goes idle). Aggregate indicators for collapsed groups, folders, and projects show the dot only — a group may hold several running turns, so a single counter would have nothing to count. The same treatment applies to the mobile sessions sheet and session switcher rows. The worktree-move indicator stays a spinner: it marks a short user-initiated operation, not a session state. -- Session rows have a single layout (former `minimal`); the `default`/`minimal` display mode was removed (`session-display-mode` store v4 migration drops the key). Rows show an inline branch label (from `node.worktree` or recent's `secondaryMeta`) when the session lives outside the project root, and bold titles while unread. -- Folders render **flat** after the loose sessions: nested folders keep `parentId` in the data model but display at one level with a "Parent / Child" path label (`SessionFolderItem.displayName`); collapsing a folder hides its whole subtree. Folder actions resolve their owning scope per folder entry (folders from multiple worktree scopes can coexist under one project). -- Archived sessions are not shown in the web/desktop sidebar; the Archive page (`ArchiveView`, `useUIStore.isArchivePageOpen`) replaces the old toggle. VS Code keeps inline archived buckets behind `showArchivedSessions` (compact webview has no page surfaces). Restore (unarchive) is available per session (row context menu, Archive page row) and in bulk (selection bar) and writes `time.archived = 0` — the server cannot clear the field over HTTP, so the global session cache splits active/archived client-side (see "Restore (unarchive) contract" in `sync/DOCUMENTATION.md`). -- Scheduled tasks (`ScheduledTasksDialog`, now a full-page surface on web/desktop) and per-project worktree management (`WorktreesView`, opened from the project menu) render as overlays inside `
` in `MainLayout`; the sidebar no longer mounts them. -- Group-level PR-status polling/indicators and worktree-group drag-to-reorder were removed together with the worktree grouping level; `oc.sessions.groupOrder` is no longer read or written. Worktree PR/branch context lives in the Worktrees surface. -- Root session menus can quickly create a worktree from the session directory's current branch and move the full session subtree there while idle. -- Managed Chats never offer the worktree-move action in either the sidebar row menu or the active-session header menu because their directories are not project repositories. -- Managed Chats use the shared Chats root as their folder scope. Their activity section renders the normal folder tree, and sessions created from a Chats folder are assigned back to that root-scoped folder after their date/session directory materializes. Per-session folder scopes created by older builds remain visible for compatibility. -- An empty Chats section says that there are no chats yet; it never reuses the project/workspace empty message. -- The New session keyboard command inherits the active materialized session directory. Explicit sidebar entry points, including the top New session row and the Chats `+`, open a fresh managed Chat draft instead. -- The new-worktree keyboard command is a silent no-op while a managed Chat draft is open. It must not retarget that draft to the active project or show a Git/worktree error because Chats never participate in worktrees. -- Directory loading is demand-driven: the sidebar publishes one complete priority plan for all known project/worktree directories, while the sync layer owns bounded execution. -- When multiple configured projects are checkouts of the same Git repository, exactly one project owns the shared worktree topology: the configured canonical primary root when present, otherwise the first configured source for that repository. Any worktree path that is also a configured project is omitted from subordinate worktree groups, so every directory has one sidebar location while remaining part of bootstrap demand. +- `shell/` owns sidebar chrome, navigation, search, confirmations, and switcher effects. +- `list/` owns global-first session collection, directory bootstrap demand, + layout-owned synchronization, authoritative cleanup, and nearby-session prefetch. +- `projects/` owns project zones, grouping, ordering, scroller behavior, project + view state, repository state, and worktree presentation. +- `sessions/` owns session rows, row actions, expansion, ownership, and activity indicators. +- `recent/` owns Recent and managed Chats activity projections. +- `folders/` owns folder DnD, bulk actions, archived folders, and folder UI. -## VS Code grouping +`MainLayout` and `VSCodeLayout` call `useSessionListSync({ isVSCode })` +unconditionally. The hook publishes complete directory bootstrap demand, +refreshes newly added topology, coalesces control events, and performs +authoritative cleanup. Root-level `useGlobalSessionsPolling` remains the only +initial and 45-second global poller. `useSessionListSync` must not create a +second global polling lifecycle. -- VS Code uses the **same grouped project tree** as web/desktop (project headers + folders + pinned-first ordering), not a separate flat list. Each open VS Code workspace folder is a project header. -- VS Code groups strictly **by open workspace**: `useSessionGrouping` funnels every non-archived session into the project's root group and emits **no per-worktree subgroups** (worktrees aren't registered in VS Code). `getSessionsForProject` buckets sessions to a workspace by exact directory match, so only sessions whose directory is an open workspace folder appear. -- VS Code passes `hideDirectoryControls` (clean workspace headers, no worktree/close chrome) and no longer passes `showOnlyMainWorkspace`/`sharedSessionsOnly`. Folders and pinning therefore work natively, scoped to the workspace root. +The global sessions cache is the complete source for active and archived +coverage. Initialized directory stores only supply sessions missing from that +cache. Live busy and retry state comes from `global-session-status`, never from +the global cache or persisted history. A failed global or directory fetch keeps +existing data; it is never treated as an authoritative empty list. -## File summaries +Web and desktop show managed Chats before optional Recent activity. Chats use +their shared managed root for folders and never expose worktree actions. Project +display can be all projects or one selected project. VS Code excludes worktrees +and managed Chats, while retaining its workspace-scoped grouped list and inline +archived buckets. -### Components - -- `SidebarHeader.tsx`: Top header UI for add-project, session search, selection mode, project sort, and the display menu (recent toggle, collapse/expand all). -- A successful add/create/clone from the project-directory dialog transitions to a new-session draft targeted at that project, matching the project's `+` action; changing project metadata alone must not leave the visible session or draft on a different directory. -- `SidebarNav.tsx`: Text navigation rows above the tree (New session, Scheduled, Multi-run, Archive); hidden in VS Code. -- `SidebarActivitySections.tsx`: Global top section renderer for OpenChamber-managed `chats` followed by optional project-only `recent` sessions, styled as zone headers. The desktop sticky identity overlay follows the activity header whose sentinel has crossed the scroller edge, so a small scroll cannot relabel Chats as Recent. -- `SidebarFooter.tsx`: Static footer with icon-only settings, shortcuts, and about actions. -- `SidebarProjectsList.tsx`: Main scrollable renderer for project zones and their flat/archived groups plus empty/search states; owns project drag-to-reorder. -- `SessionGroupSection.tsx`: Renders one flat (or archived) group: sessions first, then flat folder entries with path labels, show-more batching, and explicit loading/error/retry state for empty groups. Archived buckets (VS Code) virtualize past 50 rows. -- `SessionNodeItem.tsx`: Renders one session row/tree node with a single-line layout, inline branch label, indicators, menu actions, and nested children. Pending-question counts stay per-session while expanded and roll up hidden descendants from their owning directory stores while collapsed. Rows do not initiate directory bootstrap on mount. -- `collapsedActivityIndicator.tsx`: Aggregate busy/unseen dot for collapsed groups and folders. -- `ConfirmDialogs.tsx`: Shared confirm dialog wrappers for session delete and folder delete flows. -- `sortableItems.tsx`: DnD sortable wrapper for project ordering plus the sticky zone-band project header and its action affordances. -- `sessionFolderDnd.tsx`: Folder/session DnD scope and wrappers for dropping/moving sessions into folders. -- `sessionOwnership.ts`: Resolves session directories once into shared project/worktree ownership and folder-scope indexes. - -### Hooks - -- `hooks/useSessionActions.ts`: Centralizes session row actions (select/open, rename, share/unshare, archive/delete, confirmations). -- `hooks/useSessionSearchEffects.ts`: Handles search open/close UX and input focus behavior. -- `hooks/useSessionPrefetch.ts`: Publishes directory-aware nearby/active session prefetch demand to the shared message loader. Recent may prefetch across projects without substituting the current directory. -- `hooks/useSessionGrouping.ts`: Builds grouped session structures and search text/filter helpers. -- `hooks/useSessionSidebarSections.ts`: Composes final per-project sections and group search metadata for rendering. -- `hooks/useProjectSessionSelection.ts`: Resolves active/current project-session selection logic and session-directory context. -- `hooks/useArchivedAutoFolders.ts`: Maintains archived auto-folder structure and assignment behavior. -- `hooks/useSidebarPersistence.ts`: Persists sidebar UI state (expanded/collapsed/pinned/group order/active session) to storage + desktop settings. -- `hooks/useProjectRepoStatus.ts`: Tracks per-project git-repo state and root branch metadata. -- `hooks/useProjectSessionLists.ts`: Reads live and archived project buckets from the shared ownership index. -- `hooks/useAuthoritativeSessionCleanup.ts`: Establishes the first complete active+archived list as a non-destructive baseline, then cleans persisted state only for sessions omitted by a later authoritative snapshot. -- `hooks/useStickyProjectHeaders.ts`: Tracks which project headers are sticky/stuck via `IntersectionObserver`. - -### Types and utilities - -- `types.ts`: Shared sidebar types (`SessionNode`, `SessionGroup`, summary/search metadata). -- `activitySections.ts`: Persisted top-section storage/helpers for the current `recent` session list. -- `sessionBootstrapDemands.ts`: Builds the deduplicated directory demand plan. Selected directories rank above active projects, expanded groups, visible collapsed groups, and background/collapsed projects. -- `utils.tsx`: Shared sidebar utilities (path normalization, dedupe, archived scope keys, project relation checks, text highlight, labels, compact/default date formatting). Shared session ranking lives in `sync/session-ordering.ts`. - -## Loading rules - -- Always publish every known project root and worktree directory. Collapse/visibility changes priority only; they do not opt a directory out of authoritative refresh. -- Current directory and selected-session directory are `selected` demand and therefore run first. -- Expanded projects/worktrees outrank merely visible and background groups. -- The sync scheduler deduplicates, promotes, retries, and limits work. Sidebar components must not reproduce that lifecycle with mount effects. -- Hide speculative work when the sidebar/chat surface is hidden: message prefetch, Git/PR enrichment and subscriptions, search listeners, sticky-header observation, and archived-folder derivation stop. The session row tree unmounts so row-owned status, permission, unseen, and viewport subscriptions do no background work. The outer sidebar remains mounted, preserving UI state and authoritative directory refresh for an immediate reopen; deferred derived work reruns from current state when visibility returns. -- The sidebar does not subscribe its whole tree to the cross-directory live-session aggregate. Global create/structural/lifecycle snapshots drive rendered session metadata; the cached sync index only fills sessions not yet present globally and provides refresh fallback data. Row activity continues to come from the session-keyed live status index. -- Session selection does not invalidate the sidebar orchestration component. Each mounted row selects only whether its own session ID is active, while parent expansion, project selection memory, and neighbor prefetch run in small effect-only subscribers. -- Parent expansion is exclusively manual. Selecting or navigating to a subsession never expands its parent automatically. Project/worktree and `recent` trees use independent persisted context keys and receive separate stable projections, so expansion changes in one context neither invalidate nor change the other. The persisted storage key remains `v3`; older state mixed contexts and is not migrated into this contract. -- Folder membership may contain both a parent session and its descendants. Rendering treats only the highest assigned ancestors as folder roots because their normal session trees already include assigned descendants; persisted membership remains unchanged for cleanup and move semantics. -- Sidebar selection holds the clicked row's viewport position across navigation-driven sidebar updates. Wheel or touch input cancels the hold immediately, so programmatic compensation never fights intentional scrolling. -- Global session subscriptions are structural: create/delete, title, share, archive, directory, parent, and slug changes invalidate the tree. Recency-only `time.updated` changes do not trigger a rebuild. The separate lifecycle rank invalidates ordering only on `settled ↔ active` transitions, with root sessions ranked among roots and child sessions only among siblings of the same parent. -- CLI/server-created sessions use the low-frequency OpenChamber control event stream to refresh only the created session directory. The same event retriggers bounded worktree discovery so a newly created external worktree gains ownership without a view reload; it does not re-enable broad session or streaming subscriptions. -- Recent membership includes active root sessions immediately even when their last committed `time.updated` falls outside the 48-hour window. Children and archived sessions remain excluded, and inactive roots remain timestamp-based. The active-ID subscription is disabled while the sidebar is hidden and ignores retry/status detail changes, avoiding streaming-frequency rerenders. -- Structural updates rebuild grouped nodes only for projects whose local sessions, worktrees, repository state, or branch changed; unchanged project sections preserve references so memoized group/session descendants skip the update wave. -- Empty successful lists, unresolved loads, and failed loads are separate UI states. Failed groups expose Retry and retain prior data. -- Directory permission failures remain visible even when stale sessions are retained. Flat groups inspect every represented root/worktree directory; local Desktop may open the native picker for the exact failed directory, while other runtimes keep the ordinary Retry action. -- Pins and folder assignments are not pruned from the first startup snapshot or from optimistic mutations. Confirmed local deletion and routed external deletion clean immediately; a later authoritative omission after an established baseline covers missed external delete events. +Directory demand always includes known project roots and worktrees. Visibility +only changes priority. Row mounts must not start bootstrap work. Selection and +activity subscriptions stay session-scoped so a structural list update does not +make every row observe unrelated streaming updates. diff --git a/packages/ui/src/components/session/sidebar/activitySections.ts b/packages/ui/src/components/session/sidebar/activitySections.ts deleted file mode 100644 index 5c689d7d..00000000 --- a/packages/ui/src/components/session/sidebar/activitySections.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { Session } from '@opencode-ai/sdk/v2'; - -const RECENT_SESSION_MAX_AGE_MS = 48 * 60 * 60 * 1000; - -const isSubtaskSession = (session: Session): boolean => { - return Boolean((session as Session & { parentID?: string | null }).parentID); -}; - -const isArchivedSession = (session: Session): boolean => { - return Boolean(session.time?.archived); -}; - -const getSessionUpdatedAt = (session: Session): number => { - const updated = session.time?.updated; - const created = session.time?.created; - if (typeof updated === 'number' && Number.isFinite(updated)) { - return updated; - } - if (typeof created === 'number' && Number.isFinite(created)) { - return created; - } - return 0; -}; - -// Recent contains non-archived root sessions that are active now or were -// updated within the retention window. The caller applies shared lifecycle -// ordering after this membership filter; batching ("Show more") handles long -// windows in the UI. -export const deriveRecentSessions = ( - sessions: Session[], - activeSessionIds: ReadonlySet, - now = Date.now(), -): Session[] => { - const minUpdatedAt = now - RECENT_SESSION_MAX_AGE_MS; - return sessions.filter((session) => { - if (isArchivedSession(session) || isSubtaskSession(session)) { - return false; - } - return activeSessionIds.has(session.id) || getSessionUpdatedAt(session) >= minUpdatedAt; - }); -}; diff --git a/packages/ui/src/components/session/sidebar/collapsedActivityIndicator.tsx b/packages/ui/src/components/session/sidebar/collapsedActivityIndicator.tsx deleted file mode 100644 index d5cd2a50..00000000 --- a/packages/ui/src/components/session/sidebar/collapsedActivityIndicator.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import React from 'react'; -import { cn } from '@/lib/utils'; -import type { CollapsedActivityState } from './collapsedActivityState'; - -export function CollapsedActivityIndicator({ - state, - activeLabel, - unreadLabel, - className, -}: { - state: Exclude; - activeLabel: string; - unreadLabel: string; - className?: string; -}): React.ReactNode { - const label = state === 'active' ? activeLabel : unreadLabel; - // Aggregate rows carry the dot only; the elapsed counter is per session and - // has no meaning for a collapsed group that may hold several running turns. - return ( - - ); -} diff --git a/packages/ui/src/components/session/sidebar/collapsedActivityState.ts b/packages/ui/src/components/session/sidebar/collapsedActivityState.ts deleted file mode 100644 index 18827e32..00000000 --- a/packages/ui/src/components/session/sidebar/collapsedActivityState.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type { Session } from '@opencode-ai/sdk/v2'; -import type { SessionNode } from './types'; - -export type CollapsedActivityState = 'active' | 'unread' | null; - -export const mergeCollapsedActivityStates = ( - current: CollapsedActivityState, - next: CollapsedActivityState, -): CollapsedActivityState => { - if (current === 'active' || next === 'active') return 'active'; - if (current === 'unread' || next === 'unread') return 'unread'; - return null; -}; - -const getSessionNodeActivityState = ( - node: SessionNode, - activeSessionIds: Set, - unreadSessionIds: Set, - includeUnreadSubtasks: boolean, -): CollapsedActivityState => { - if (activeSessionIds.has(node.session.id)) { - return 'active'; - } - - let state: CollapsedActivityState = null; - const isSubtask = Boolean((node.session as Session & { parentID?: string | null }).parentID); - if (unreadSessionIds.has(node.session.id) && (includeUnreadSubtasks || !isSubtask)) { - state = 'unread'; - } - - for (const child of node.children) { - state = mergeCollapsedActivityStates( - state, - getSessionNodeActivityState(child, activeSessionIds, unreadSessionIds, includeUnreadSubtasks), - ); - if (state === 'active') return state; - } - - return state; -}; - -export const getSessionNodesActivityState = ( - nodes: SessionNode[], - activeSessionIds: Set, - unreadSessionIds: Set, - includeUnreadSubtasks: boolean, -): CollapsedActivityState => { - let state: CollapsedActivityState = null; - for (const node of nodes) { - state = mergeCollapsedActivityStates( - state, - getSessionNodeActivityState(node, activeSessionIds, unreadSessionIds, includeUnreadSubtasks), - ); - if (state === 'active') return state; - } - return state; -}; diff --git a/packages/ui/src/components/session/sidebar/BulkActionBar.tsx b/packages/ui/src/components/session/sidebar/folders/BulkActionBar.tsx similarity index 100% rename from packages/ui/src/components/session/sidebar/BulkActionBar.tsx rename to packages/ui/src/components/session/sidebar/folders/BulkActionBar.tsx diff --git a/packages/ui/src/components/session/sidebar/folders/SessionBulkActions.behavior.test.tsx b/packages/ui/src/components/session/sidebar/folders/SessionBulkActions.behavior.test.tsx new file mode 100644 index 00000000..edb9a4d3 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/folders/SessionBulkActions.behavior.test.tsx @@ -0,0 +1,79 @@ +import { describe, expect, mock, test } from 'bun:test'; +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { I18nProvider } from '@/lib/i18n'; +import { useSessionFoldersStore } from '@/stores/useSessionFoldersStore'; +import { useSessionMultiSelectStore } from '@/stores/useSessionMultiSelectStore'; +import { installHookTestDom } from '../test-utils/testDom'; + +type BulkActionCapture = { + onCreateFolderAndMove: () => void; +}; + +let bulkActionCapture: BulkActionCapture | null = null; + +mock.module('./BulkActionBar', () => ({ + BulkActionBar: (props: BulkActionCapture) => { + bulkActionCapture = props; + return null; + }, +})); + +mock.module('./ConfirmDialogs', () => ({ + BulkSessionDeleteConfirmDialog: () => null, +})); + +const { SessionBulkActions } = await import('./SessionBulkActions'); + +describe('SessionBulkActions public behavior', () => { + test('moves the selected sessions into a newly created folder while a row edit is active', async () => { + const dom = installHookTestDom(); + const root = createRoot(dom.container); + const originalFolders = useSessionFoldersStore.getState(); + const originalSelection = useSessionMultiSelectStore.getState(); + const cssDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'CSS'); + const renameRequests: Array<{ scopeKey: string; folder: { id: string; name: string } }> = []; + const moved: Array<{ scopeKey: string; folderId: string; ids: string[] }> = []; + useSessionFoldersStore.setState({ + foldersMap: {}, + addSessionsToFolder: (scopeKey, folderId, ids) => moved.push({ scopeKey, folderId, ids }), + }); + useSessionMultiSelectStore.setState({ + enabled: true, + selectedIds: new Set(['session-a']), + scopeKey: 'project-a', + anchorId: 'session-a', + }); + Object.defineProperty(globalThis, 'CSS', { + configurable: true, + value: { escape: (value: string) => value }, + }); + + try { + await act(async () => root.render( + + [{ scopeKey: '/workspace', directory: '/workspace' }]} + isInlineEditing + startFolderRename={(scopeKey, folder) => renameRequests.push({ scopeKey, folder })} + /> + , + )); + expect(bulkActionCapture).not.toBeNull(); + + await act(async () => bulkActionCapture?.onCreateFolderAndMove()); + const createdFolder = useSessionFoldersStore.getState().foldersMap['/workspace']?.[0]; + expect(createdFolder?.name).toBe('New folder'); + expect(renameRequests).toEqual([{ scopeKey: '/workspace', folder: createdFolder }]); + expect(moved).toEqual([{ scopeKey: '/workspace', folderId: createdFolder?.id ?? '', ids: ['session-a'] }]); + } finally { + await act(async () => root.unmount()); + useSessionFoldersStore.setState(originalFolders, true); + useSessionMultiSelectStore.setState(originalSelection, true); + if (cssDescriptor) Object.defineProperty(globalThis, 'CSS', cssDescriptor); + else Reflect.deleteProperty(globalThis, 'CSS'); + bulkActionCapture = null; + dom.restore(); + } + }); +}); diff --git a/packages/ui/src/components/session/sidebar/folders/SessionBulkActions.tsx b/packages/ui/src/components/session/sidebar/folders/SessionBulkActions.tsx new file mode 100644 index 00000000..8af5a023 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/folders/SessionBulkActions.tsx @@ -0,0 +1,67 @@ +import React from 'react'; +import { useSessionUIStore } from '@/sync/session-ui-store'; +import { useUIStore } from '@/stores/useUIStore'; +import { useSessionFoldersStore } from '@/stores/useSessionFoldersStore'; +import { BulkActionBar } from './BulkActionBar'; +import { BulkSessionDeleteConfirmDialog, type BulkDeleteSessionsConfirmState } from '../shell/ConfirmDialogs'; +import { useSidebarBulkActions } from './useSidebarBulkActions'; + +type Props = { + getFolderScopesForProject: (projectId: string) => readonly { scopeKey: string; directory: string | null }[]; + isInlineEditing: boolean; + startFolderRename: (scopeKey: string, folder: { id: string; name: string }) => void; +}; + +/** Owns the sidebar selection projection and its destructive confirmation. */ +export function SessionBulkActions({ getFolderScopesForProject, isInlineEditing, startFolderRename }: Props): React.ReactNode { + const [bulkDeleteConfirm, setBulkDeleteConfirm] = React.useState(null); + const showDeletionDialog = useUIStore((state) => state.showDeletionDialog); + const setShowDeletionDialog = useUIStore((state) => state.setShowDeletionDialog); + const foldersMap = useSessionFoldersStore((state) => state.foldersMap); + const createFolder = useSessionFoldersStore((state) => state.createFolder); + const addSessionsToFolder = useSessionFoldersStore((state) => state.addSessionsToFolder); + const removeSessionsFromFolders = useSessionFoldersStore((state) => state.removeSessionsFromFolders); + const archiveSessions = useSessionUIStore((state) => state.archiveSessions); + const unarchiveSessions = useSessionUIStore((state) => state.unarchiveSessions); + const deleteSessions = useSessionUIStore((state) => state.deleteSessions); + const bulk = useSidebarBulkActions({ + isInlineEditing, + showDeletionDialog, + foldersMap, + getFolderScopesForProject, + addSessionsToFolder, + removeSessionsFromFolders, + createFolderAndStartRename: (scopeKey) => { + const folder = createFolder(scopeKey, 'New folder'); + startFolderRename(scopeKey, folder); + return folder; + }, + archiveSessions, + unarchiveSessions, + deleteSessions, + setBulkDeleteConfirm, + }); + + return <> + {bulk.selectionModeEnabled && bulk.hasSelection ? : null} + + ; +} diff --git a/packages/ui/src/components/session/sidebar/folders/sessionFolderDnd.behavior.test.tsx b/packages/ui/src/components/session/sidebar/folders/sessionFolderDnd.behavior.test.tsx new file mode 100644 index 00000000..3a7ed1f9 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/folders/sessionFolderDnd.behavior.test.tsx @@ -0,0 +1,58 @@ +import { describe, expect, mock, test } from 'bun:test'; +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { installHookTestDom } from '../test-utils/testDom'; + +type DragEnd = (event: { + active: { data: { current: { type: string; sessionId: string } } }; + over: { data: { current: { type: string; folderId: string } } } | null; +}) => void; + +let handleDragEnd: DragEnd | null = null; + +mock.module('@dnd-kit/core', () => ({ + DndContext: ({ children, onDragEnd }: { children: React.ReactNode; onDragEnd: DragEnd }) => { + handleDragEnd = onDragEnd; + return <>{children}; + }, + DragOverlay: ({ children }: { children: React.ReactNode }) => <>{children}, + PointerSensor: class {}, + closestCenter: () => null, + useSensor: () => null, + useSensors: () => [], + useDraggable: () => ({ attributes: {}, listeners: {}, setNodeRef: () => undefined, isDragging: false }), + useDroppable: () => ({ setNodeRef: () => undefined, isOver: false }), +})); + +const { SessionFolderDndScope } = await import('./sessionFolderDnd'); + +describe('SessionFolderDndScope public behavior', () => { + test('routes a session-folder drop without depending on row edit or menu state', async () => { + const dom = installHookTestDom(); + const root = createRoot(dom.container); + const drops: Array<{ sessionId: string; folderId: string }> = []; + + try { + await act(async () => root.render( + drops.push({ sessionId, folderId })} + > + {null} + , + )); + expect(handleDragEnd).not.toBeNull(); + + await act(async () => handleDragEnd?.({ + active: { data: { current: { type: 'session', sessionId: 'session-a' } } }, + over: { data: { current: { type: 'folder', folderId: 'folder-a' } } }, + })); + expect(drops).toEqual([{ sessionId: 'session-a', folderId: 'folder-a' }]); + } finally { + await act(async () => root.unmount()); + handleDragEnd = null; + dom.restore(); + } + }); +}); diff --git a/packages/ui/src/components/session/sidebar/sessionFolderDnd.tsx b/packages/ui/src/components/session/sidebar/folders/sessionFolderDnd.tsx similarity index 100% rename from packages/ui/src/components/session/sidebar/sessionFolderDnd.tsx rename to packages/ui/src/components/session/sidebar/folders/sessionFolderDnd.tsx diff --git a/packages/ui/src/components/session/sidebar/hooks/useArchivedAutoFolders.ts b/packages/ui/src/components/session/sidebar/folders/useArchivedAutoFolders.ts similarity index 97% rename from packages/ui/src/components/session/sidebar/hooks/useArchivedAutoFolders.ts rename to packages/ui/src/components/session/sidebar/folders/useArchivedAutoFolders.ts index 0031b36d..9ded6a87 100644 --- a/packages/ui/src/components/session/sidebar/hooks/useArchivedAutoFolders.ts +++ b/packages/ui/src/components/session/sidebar/folders/useArchivedAutoFolders.ts @@ -3,7 +3,7 @@ import { getArchivedScopeKey, resolveArchivedFolderName, } from '../utils'; -import type { SessionOwnershipIndex } from '../sessionOwnership'; +import type { SessionOwnershipIndex } from '../sessions/sessionOwnership'; type ProjectForArchivedFolders = { id: string; diff --git a/packages/ui/src/components/session/sidebar/folders/useSidebarBulkActions.test.ts b/packages/ui/src/components/session/sidebar/folders/useSidebarBulkActions.test.ts new file mode 100644 index 00000000..f0d3d2ab --- /dev/null +++ b/packages/ui/src/components/session/sidebar/folders/useSidebarBulkActions.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from 'bun:test'; +import { resolveSelectionFolderScopes } from './useSidebarBulkActions'; + +describe('sidebar bulk project scopes', () => { + test('uses every root and worktree scope owned by the selected project', () => { + const scopes = resolveSelectionFolderScopes('project-a', (projectId) => projectId === 'project-a' + ? [ + { scopeKey: '/workspace/project-a', directory: '/workspace/project-a' }, + { scopeKey: '/workspace/project-a-worktree', directory: '/workspace/project-a-worktree' }, + ] + : []); + + expect(scopes).toEqual(['/workspace/project-a', '/workspace/project-a-worktree']); + }); + + test('keeps a directory scope when no project scope owns it', () => { + expect(resolveSelectionFolderScopes('/workspace/vscode', () => [])).toEqual(['/workspace/vscode']); + }); +}); diff --git a/packages/ui/src/components/session/sidebar/hooks/useSidebarBulkActions.ts b/packages/ui/src/components/session/sidebar/folders/useSidebarBulkActions.ts similarity index 94% rename from packages/ui/src/components/session/sidebar/hooks/useSidebarBulkActions.ts rename to packages/ui/src/components/session/sidebar/folders/useSidebarBulkActions.ts index af3c5428..a520f3d0 100644 --- a/packages/ui/src/components/session/sidebar/hooks/useSidebarBulkActions.ts +++ b/packages/ui/src/components/session/sidebar/folders/useSidebarBulkActions.ts @@ -13,7 +13,7 @@ type Args = { * map resolves it to the project's folder scopes (root + worktrees). When * the scope is missing here it is treated as a plain directory scope. */ - folderScopesByProject: Map>; + getFolderScopesForProject: (projectId: string) => readonly { scopeKey: string; directory: string | null }[]; addSessionsToFolder: (scopeKey: string, folderId: string, sessionIds: string[]) => void; removeSessionsFromFolders: (scopeKey: string, sessionIds: string[]) => void; createFolderAndStartRename: (scopeKey: string, parentId?: string | null) => { id: string } | null; @@ -26,6 +26,17 @@ type Args = { } | null>>; }; +export const resolveSelectionFolderScopes = ( + selectionScope: string | null, + getFolderScopesForProject: Args['getFolderScopesForProject'], +): string[] => { + if (!selectionScope) return []; + const projectScopes = getFolderScopesForProject(selectionScope); + return projectScopes.length > 0 + ? projectScopes.map((scope) => scope.scopeKey) + : [selectionScope]; +}; + /** * Bulk-action logic for the sidebar. The hot-path concern is that this * hook subscribes to `useSessionMultiSelectStore` — which can fire on @@ -46,7 +57,7 @@ export const useSidebarBulkActions = (args: Args) => { isInlineEditing, showDeletionDialog, foldersMap, - folderScopesByProject, + getFolderScopesForProject, addSessionsToFolder, removeSessionsFromFolders, createFolderAndStartRename, @@ -101,14 +112,8 @@ export const useSidebarBulkActions = (args: Args) => { // The selection scope is a project id; folders live per directory scope // (project root + each worktree). Resolve all of them, in project order. const selectionFolderScopes = React.useMemo(() => { - if (!derivedSelectionScope) return []; - const projectScopes = folderScopesByProject.get(derivedSelectionScope); - if (projectScopes && projectScopes.length > 0) { - return projectScopes.map((scope) => scope.scopeKey); - } - // Fallback: the scope is already a directory (e.g. VS Code workspaces). - return [derivedSelectionScope]; - }, [derivedSelectionScope, folderScopesByProject]); + return resolveSelectionFolderScopes(derivedSelectionScope, getFolderScopesForProject); + }, [derivedSelectionScope, getFolderScopesForProject]); const bulkScopeFolders = React.useMemo(() => { return selectionFolderScopes.flatMap((scope) => foldersMap[scope] ?? []); diff --git a/packages/ui/src/components/session/sidebar/hooks/useAuthoritativeSessionCleanup.test.ts b/packages/ui/src/components/session/sidebar/hooks/useAuthoritativeSessionCleanup.test.ts deleted file mode 100644 index d33089e5..00000000 --- a/packages/ui/src/components/session/sidebar/hooks/useAuthoritativeSessionCleanup.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { Session } from '@opencode-ai/sdk/v2'; -import { - buildAuthoritativeSessionIdentityMap, - findRemovedAuthoritativeSessions, -} from '../authoritativeSessionCleanup'; - -const session = (id: string, directory = '/repo'): Session => ({ id, directory }) as Session; - -describe('authoritative session cleanup', () => { - test('does not infer deletion from the first authoritative startup snapshot', () => { - const current = buildAuthoritativeSessionIdentityMap([]); - - expect(findRemovedAuthoritativeSessions(null, current)).toEqual([]); - }); - - test('finds sessions omitted after an established authoritative baseline', () => { - const previous = buildAuthoritativeSessionIdentityMap([ - session('deleted'), - session('retained'), - ]); - const current = buildAuthoritativeSessionIdentityMap([session('retained')]); - - expect(findRemovedAuthoritativeSessions(previous, current)).toEqual([ - { directory: '/repo', sessionId: 'deleted' }, - ]); - }); - - test('treats archive membership as retained authority', () => { - const previous = buildAuthoritativeSessionIdentityMap([session('archived')]); - const current = buildAuthoritativeSessionIdentityMap([ - { ...session('archived'), time: { archived: 10 } } as Session, - ]); - - expect(findRemovedAuthoritativeSessions(previous, current)).toEqual([]); - }); - - test('does not treat a directory move as session deletion', () => { - const previous = buildAuthoritativeSessionIdentityMap([session('moved', '/repo-a')]); - const current = buildAuthoritativeSessionIdentityMap([session('moved', '/repo-b')]); - - expect(findRemovedAuthoritativeSessions(previous, current)).toEqual([]); - }); -}); diff --git a/packages/ui/src/components/session/sidebar/hooks/useSidebarPersistence.ts b/packages/ui/src/components/session/sidebar/hooks/useSidebarPersistence.ts deleted file mode 100644 index d2e8604e..00000000 --- a/packages/ui/src/components/session/sidebar/hooks/useSidebarPersistence.ts +++ /dev/null @@ -1,123 +0,0 @@ -import React from 'react'; -import { updateDesktopSettings } from '@/lib/persistence'; -import { useProjectsStore } from '@/stores/useProjectsStore'; - -type SafeStorageLike = { - getItem: (key: string) => string | null; - setItem: (key: string, value: string) => void; -}; - -type Keys = { - sessionExpanded: string; - projectCollapse: string; - groupOrder: string; - groupCollapse: string; -}; - -type Args = { - isVSCode: boolean; - safeStorage: SafeStorageLike; - keys: Keys; - groupOrderByProject: Map; - collapsedGroups: Set; - setExpandedParents: React.Dispatch>>; - setCollapsedProjects: React.Dispatch>>; -}; - -export const useSidebarPersistence = (args: Args) => { - const { - isVSCode, - safeStorage, - keys, - groupOrderByProject, - collapsedGroups, - setExpandedParents, - setCollapsedProjects, - } = args; - - const persistCollapsedProjectsTimer = React.useRef(null); - const pendingCollapsedProjects = React.useRef | null>(null); - - const flushCollapsedProjectsPersist = React.useCallback(() => { - if (isVSCode) { - return; - } - const collapsed = pendingCollapsedProjects.current; - pendingCollapsedProjects.current = null; - persistCollapsedProjectsTimer.current = null; - if (!collapsed) { - return; - } - - const { projects } = useProjectsStore.getState(); - const updatedProjects = projects.map((project) => ({ - ...project, - sidebarCollapsed: collapsed.has(project.id), - })); - void updateDesktopSettings({ projects: updatedProjects }).catch(() => {}); - }, [isVSCode]); - - const scheduleCollapsedProjectsPersist = React.useCallback((collapsed: Set) => { - if (typeof window === 'undefined' || isVSCode) { - return; - } - - pendingCollapsedProjects.current = collapsed; - if (persistCollapsedProjectsTimer.current !== null) { - window.clearTimeout(persistCollapsedProjectsTimer.current); - } - persistCollapsedProjectsTimer.current = window.setTimeout(() => { - flushCollapsedProjectsPersist(); - }, 700); - }, [isVSCode, flushCollapsedProjectsPersist]); - - React.useEffect(() => { - return () => { - if (typeof window !== 'undefined' && persistCollapsedProjectsTimer.current !== null) { - window.clearTimeout(persistCollapsedProjectsTimer.current); - } - persistCollapsedProjectsTimer.current = null; - pendingCollapsedProjects.current = null; - }; - }, []); - - React.useEffect(() => { - try { - const storedParents = safeStorage.getItem(keys.sessionExpanded); - if (storedParents) { - const parsed = JSON.parse(storedParents); - if (Array.isArray(parsed)) { - setExpandedParents(new Set(parsed.filter((item) => typeof item === 'string'))); - } - } - const storedProjects = safeStorage.getItem(keys.projectCollapse); - if (storedProjects) { - const parsed = JSON.parse(storedProjects); - if (Array.isArray(parsed)) { - setCollapsedProjects(new Set(parsed.filter((item) => typeof item === 'string'))); - } - } - } catch { - // ignored - } - }, [keys.projectCollapse, keys.sessionExpanded, safeStorage, setCollapsedProjects, setExpandedParents]); - - React.useEffect(() => { - try { - const serialized = Object.fromEntries(groupOrderByProject.entries()); - safeStorage.setItem(keys.groupOrder, JSON.stringify(serialized)); - } catch { - // ignored - } - }, [groupOrderByProject, keys.groupOrder, safeStorage]); - - React.useEffect(() => { - try { - safeStorage.setItem(keys.groupCollapse, JSON.stringify(Array.from(collapsedGroups))); - } catch { - // ignored - } - }, [collapsedGroups, keys.groupCollapse, safeStorage]); - - return { scheduleCollapsedProjectsPersist }; -}; diff --git a/packages/ui/src/components/session/sidebar/list/SessionProjectCollection.test.tsx b/packages/ui/src/components/session/sidebar/list/SessionProjectCollection.test.tsx new file mode 100644 index 00000000..194c0b58 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/SessionProjectCollection.test.tsx @@ -0,0 +1,21 @@ +import { describe, expect, test } from 'bun:test'; +import { buildSessionBootstrapDemands } from './sessionBootstrapDemands'; + +describe('SessionProjectCollection', () => { + test('preserves authoritative background demand when its visible rows are absent', () => { + const demands = buildSessionBootstrapDemands({ + knownDirectories: ['/project', '/project/worktree'], + activeProjectDirectory: '/project', + activeProjectId: 'project', + collapsedProjects: new Set(), + collapsedGroups: new Set(), + currentDirectory: null, + currentSessionDirectory: null, + }); + + expect(demands.map((demand) => demand.directory)).toEqual(['/project', '/project/worktree']); + expect(demands[0]?.priority).toBe('active-project'); + expect(demands[1]?.priority).toBe('background'); + }); + +}); diff --git a/packages/ui/src/components/session/sidebar/list/SessionProjectCollection.tsx b/packages/ui/src/components/session/sidebar/list/SessionProjectCollection.tsx new file mode 100644 index 00000000..efc736a9 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/SessionProjectCollection.tsx @@ -0,0 +1,501 @@ +import React from 'react'; +import { useSessionUIStore } from '@/sync/session-ui-store'; +import { useSync } from '@/sync/use-sync'; +import { useGitHubAuthStore } from '@/stores/useGitHubAuthStore'; +import { getGitHubPrStatusKey, useGitHubPrStatusStore } from '@/stores/useGitHubPrStatusStore'; +import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs'; +import { useArchivedAutoFolders } from '../folders/useArchivedAutoFolders'; +import { ProjectSessionSelectionEffect } from '../projects/useProjectSessionSelection'; +import type { WorktreeMetadata } from '@/types/worktree'; +import { useRecentSessionCollection, useSessionProjectCollection } from './sessionCollection'; +import { createSessionOwnershipIndex } from '../sessions/sessionOwnership'; +import { useProjectSessionLists } from '../projects/useProjectSessionLists'; +import { useSessionSidebarSections } from '../projects/useSessionSidebarSections'; +import { SessionPrefetchEffect } from './useSessionPrefetch'; +import { normalizePath } from '../utils'; +import type { SessionGroup } from '../types'; +import { SessionProjectScroller } from '../projects/SessionProjectScroller'; +import { useSessionGrouping } from '../projects/useSessionGrouping'; +import { useStickyProjectHeaders } from '../projects/useStickyProjectHeaders'; +import { SessionBulkActions } from '../folders/SessionBulkActions'; +import { RecentSessionSection } from '../recent/RecentSessionSection'; +import { useSessionFoldersStore } from '@/stores/useSessionFoldersStore'; +import type { useSessionProjectViewState } from '../projects/useSessionProjectViewState'; +import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore'; +import type { DeleteSessionConfirmState } from '../sessions/useSessionActions'; +import { useExpandedParents } from '../sessions/useExpandedParents'; + +const PR_NO_PR_RETRY_MS = 5 * 60_000; + +type Project = { + id: string; + path: string; + label?: string; + normalizedPath: string; + icon?: string; + color?: string; + iconImage?: { mime: string; updatedAt: number; source: 'custom' | 'auto' }; + iconBackground?: string; +}; + +type SessionProjectCollectionProps = { + topology: { + projects: Project[]; + availableWorktreesByProject: Map; + knownDirectories: Set; + isVSCode: boolean; + worktreeMetadata: Map; + gitBranches: Map; + projectRepoStatus: Map; + projectRootBranches: Map; + lastRepoStatus: boolean; + }; + view: { + isVisible: boolean; + hasSessionSearchQuery: boolean; + normalizedSessionSearchQuery: string; + activeProjectId: string | null; + showInlineArchived: boolean; + useGroupedSections: boolean; + homeDirectory: string | null; + mobileVariant: boolean; + hideDirectoryControls: boolean; + showOnlyMainWorkspace: boolean; + isDesktopShellRuntime: boolean; + stickyZoneHeaders: boolean; + projectSortOrder: import('@/stores/useSessionDisplayStore').ProjectSortOrder; + emptyState: React.ReactNode; + searchEmptyState: React.ReactNode; + isSessionsLoading: boolean; + isWorktreeTopologyLoading: boolean; + unresolvedWorktreeProjectPaths: ReadonlySet; + projectView: ReturnType['state']; + }; + actions: { + rowActions: { + allowReselect: boolean; + onSessionSelected?: (sessionId: string) => void; + isSessionSearchOpen: boolean; + sessionSearchQuery: string; + setSessionSearchQuery: (value: string) => void; + setIsSessionSearchOpen: (open: boolean) => void; + }; + alwaysShowActions: boolean; + notifyOnSubtasks: boolean; + setActiveProjectIdOnly: (id: string) => void; + setActiveMainTab: (tab: import('@/stores/useUIStore').MainTab) => void; + setSessionSwitcherOpen: (open: boolean) => void; + openNewSessionDraft: (options?: { selectedProjectId?: string | null; directoryOverride?: string | null }) => void; + openNewWorktreeDialog: () => void; + openWorktreesPage: (id: string) => void; + openProjectEditDialog: (id: string) => void; + removeProject: (id: string) => void; + reorderProjects: (fromIndex: number, toIndex: number) => void; + renderProjectStatusIndicator?: (projectId: string, groups: SessionGroup[]) => React.ReactNode; + initialActiveSessionByProject: Map; + persistActiveSessionByProject: (value: Map) => void; + projectViewActions: Pick< + ReturnType['actions'], + 'getOrderedGroups' | 'setGroupOrderByProject' | 'toggleGroup' | 'toggleProject' + >; + }; +}; + +const VisibleSessionProjects: React.FC = ({ topology, view, actions }) => { + const { alwaysShowActions, notifyOnSubtasks, projectViewActions, rowActions, ...scrollerActions } = actions; + const foldersMap = useSessionFoldersStore((state) => state.foldersMap); + const createFolder = useSessionFoldersStore((state) => state.createFolder); + const addSessionToFolder = useSessionFoldersStore((state) => state.addSessionToFolder); + const projectView = view.projectView; + const { getOrderedGroups, setGroupOrderByProject, toggleGroup, toggleProject } = projectViewActions; + const collection = useSessionProjectCollection({ knownDirectories: topology.knownDirectories, isVSCode: topology.isVSCode, isVisible: true }); + const [visibleSessionCountByGroup, setVisibleSessionCountByGroup] = React.useState>(new Map()); + const showMoreGroupSessions = React.useCallback((groupId: string, currentVisibleCount: number) => { + setVisibleSessionCountByGroup((current) => new Map(current).set(groupId, currentVisibleCount + 7)); + }, []); + const resetGroupSessionLimit = React.useCallback((groupId: string) => { + setVisibleSessionCountByGroup((current) => { + if (!current.has(groupId)) return current; + const next = new Map(current); + next.delete(groupId); + return next; + }); + }, []); + const showRecentSection = useSessionDisplayStore((state) => state.showRecentSection); + const recentSessions = useRecentSessionCollection({ + enabled: showRecentSection, + isVSCode: topology.isVSCode, + pinnedSessionIds: collection.pinnedSessionIds, + sessionOrderRanks: collection.sessionOrderRanks, + sessions: collection.sessions, + }); + const [editingId, setEditingId] = React.useState(null); + const [editTitle, setEditTitle] = React.useState(''); + const [openSidebarMenuKey, setOpenSidebarMenuKey] = React.useState(null); + const [deleteSessionConfirm, setDeleteSessionConfirm] = React.useState(null); + const [copiedSessionId, setCopiedSessionId] = React.useState(null); + const [folderRename, setFolderRename] = React.useState<{ scopeKey: string; folderId: string; draft: string } | null>(null); + const startFolderRename = React.useCallback((scopeKey: string, folder: { id: string; name: string }) => { + setFolderRename({ scopeKey, folderId: folder.id, draft: folder.name }); + }, []); + const setFolderRenameDraft = React.useCallback((draft: string) => { + setFolderRename((current) => current ? { ...current, draft } : null); + }, []); + const clearFolderRename = React.useCallback(() => setFolderRename(null), []); + const { expandedParents, toggleParent } = useExpandedParents(); + const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession); + const selectSessionForProject = React.useCallback((sessionId: string, sessionDirectory: string | null) => { + if (sessionId === useSessionUIStore.getState().currentSessionId) return; + setCurrentSession(sessionId, sessionDirectory); + }, [setCurrentSession]); + const sync = useSync(); + const { buildGroupedSessions, filterSessionNodesForSearch, buildGroupSearchText } = useSessionGrouping({ + homeDirectory: view.homeDirectory, + worktreeMetadata: topology.worktreeMetadata, + pinnedSessionIds: collection.pinnedSessionIds, + sessionOrderRanks: collection.sessionOrderRanks, + gitBranches: topology.gitBranches, + isVSCode: topology.isVSCode, + }); + const ownership = React.useMemo( + () => createSessionOwnershipIndex(collection.sessions, topology.projects, topology.availableWorktreesByProject, topology.isVSCode, collection.archivedSessions), + [collection.archivedSessions, collection.sessions, topology.availableWorktreesByProject, topology.isVSCode, topology.projects], + ); + const { getSessionsForProject, getArchivedSessionsForProject } = useProjectSessionLists({ ownership }); + const { projectSections, groupSearchDataByGroup, sectionsForRender, flatSectionsForRender } = useSessionSidebarSections({ + normalizedProjects: topology.projects, + getSessionsForProject, + getArchivedSessionsForProject, + availableWorktreesByProject: topology.availableWorktreesByProject, + projectRepoStatus: topology.projectRepoStatus, + projectRootBranches: topology.projectRootBranches, + lastRepoStatus: topology.lastRepoStatus, + buildGroupedSessions, + hasSessionSearchQuery: view.hasSessionSearchQuery, + normalizedSessionSearchQuery: view.normalizedSessionSearchQuery, + filterSessionNodesForSearch, + buildGroupSearchText, + foldersMap, + }); + const source = view.useGroupedSections ? sectionsForRender : flatSectionsForRender; + const sectionsForSidebarRender = React.useMemo(() => view.showInlineArchived ? source : source.map((section) => ( + section.groups.some((group) => group.isArchivedBucket) + ? { ...section, groups: section.groups.filter((group) => !group.isArchivedBucket) } + : section + )), [source, view.showInlineArchived]); + const getFolderScopesForProject = React.useCallback((projectId: string) => { + const section = flatSectionsForRender.find((entry) => entry.project.id === projectId); + return section?.groups.find((group) => !group.isArchivedBucket)?.folderScopes ?? []; + }, [flatSectionsForRender]); + const projectHeaderSentinelRefs = React.useRef>(new Map()); + const stuckProjectHeaders = useStickyProjectHeaders({ + enabled: view.stickyZoneHeaders, + isDesktopShellRuntime: view.isDesktopShellRuntime, + projectSections, + projectHeaderSentinelRefs, + }); + useArchivedAutoFolders({ + enabled: true, + normalizedProjects: topology.projects, + ownership, + isSessionsLoading: view.isSessionsLoading, + hasAuthoritativeGlobalSessions: collection.hasAuthoritativeGlobalSessions, + isWorktreeTopologyLoading: view.isWorktreeTopologyLoading, + unresolvedWorktreeProjectPaths: view.unresolvedWorktreeProjectPaths, + foldersMap, + createFolder, + addSessionToFolder, + }); + const { github } = useRuntimeAPIs(); + const githubAuthStatus = useGitHubAuthStore((state) => state.status); + const githubAuthChecked = useGitHubAuthStore((state) => state.hasChecked); + const ensureEntry = useGitHubPrStatusStore((state) => state.ensureEntry); + const setParams = useGitHubPrStatusStore((state) => state.setParams); + const refreshTargets = useGitHubPrStatusStore((state) => state.refreshTargets); + const retriedRef = React.useRef(new Set()); + React.useEffect(() => { + if (!github || !githubAuthChecked || !githubAuthStatus?.connected) return; + const targets = new Map(); + const now = Date.now(); + projectSections.forEach((section) => { + if (projectView.collapsedProjects.has(section.project.id)) return; + section.groups.forEach((group) => { + if (group.isArchivedBucket || group.isMain) return; + const directory = normalizePath(group.directory ?? null); + const branch = group.branch?.trim() || topology.gitBranches.get(directory || '')?.trim(); + if (!directory || !branch) return; + const key = getGitHubPrStatusKey(directory, branch); + const entry = useGitHubPrStatusStore.getState().entries[key]; + const terminal = entry?.status?.pr?.state === 'closed' || entry?.status?.pr?.state === 'merged'; + const retryKey = `${directory}::${branch}`; + const lastChecked = Math.max(entry?.lastRefreshAt ?? 0, entry?.lastDiscoveryPollAt ?? 0); + const retry = Boolean(entry?.isInitialStatusResolved && (!entry.status?.pr || terminal) && (!retriedRef.current.has(retryKey) || now - lastChecked >= PR_NO_PR_RETRY_MS)); + if (!entry || !entry.isInitialStatusResolved || retry) { + if (retry) retriedRef.current.add(retryKey); + targets.set(key, { directory, branch }); + } + }); + }); + targets.forEach((target, key) => { + ensureEntry(key); + setParams(key, { ...target, remoteName: null, canShow: true, github, githubAuthChecked, githubConnected: githubAuthStatus.connected }); + }); + if (targets.size) void refreshTargets([...targets.values()], { silent: true, markInitialResolved: true }); + }, [ensureEntry, github, githubAuthChecked, githubAuthStatus?.connected, projectSections, projectView.collapsedProjects, refreshTargets, setParams, topology.gitBranches]); + const sessionOrderIndex = React.useMemo( + () => new Map(collection.orderedSessions.map((session, index) => [session.id, index])), + [collection.orderedSessions], + ); + const orderedSectionsForRender = React.useMemo( + () => sectionsForSidebarRender.map((section) => { + const groups = getOrderedGroups(section.project.id, section.groups); + return groups === section.groups ? section : { ...section, groups }; + }), + [getOrderedGroups, sectionsForSidebarRender], + ); + const groupProps = React.useMemo(() => ({ + hasSessionSearchQuery: view.hasSessionSearchQuery, + normalizedSessionSearchQuery: view.normalizedSessionSearchQuery, + groupSearchDataByGroup, + collapsedGroups: projectView.collapsedGroups, + hideDirectoryControls: view.hideDirectoryControls, + mobileVariant: view.mobileVariant, + alwaysShowActions, + activeProjectId: view.activeProjectId, + notifyOnSubtasks, + pinnedSessionIds: collection.pinnedSessionIds, + sessionOrderIndex, + expandedParents, + editingId, + editTitle, + copiedSessionId, + setEditingId, + setEditTitle, + toggleParent, + allowReselect: rowActions.allowReselect, + onSessionSelected: rowActions.onSessionSelected, + isSessionSearchOpen: rowActions.isSessionSearchOpen, + sessionSearchQuery: rowActions.sessionSearchQuery, + setSessionSearchQuery: rowActions.setSessionSearchQuery, + setIsSessionSearchOpen: rowActions.setIsSessionSearchOpen, + deleteSessionConfirm, + setDeleteSessionConfirm, + startFolderRename, + setCopiedSessionId, + folderRename, + setFolderRenameDraft, + clearFolderRename, + }), [ + collection.pinnedSessionIds, + alwaysShowActions, + notifyOnSubtasks, + projectView.collapsedGroups, + groupSearchDataByGroup, + sessionOrderIndex, + editTitle, + editingId, + expandedParents, + folderRename, + setFolderRenameDraft, + clearFolderRename, + startFolderRename, + deleteSessionConfirm, + copiedSessionId, + setCopiedSessionId, + rowActions, + toggleParent, + view.activeProjectId, + view.hideDirectoryControls, + view.hasSessionSearchQuery, + view.mobileVariant, + view.normalizedSessionSearchQuery, + ]); + const groupActions = React.useMemo(() => ({ + showMoreGroupSessions, + resetGroupSessionLimit, + setActiveProjectIdOnly: scrollerActions.setActiveProjectIdOnly, + setActiveMainTab: scrollerActions.setActiveMainTab, + setSessionSwitcherOpen: scrollerActions.setSessionSwitcherOpen, + openNewSessionDraft: scrollerActions.openNewSessionDraft, + onToggleCollapsedGroup: toggleGroup, + }), [ + resetGroupSessionLimit, + showMoreGroupSessions, + toggleGroup, + scrollerActions.openNewSessionDraft, + scrollerActions.setActiveMainTab, + scrollerActions.setActiveProjectIdOnly, + scrollerActions.setSessionSwitcherOpen, + ]); + const recentSection = React.useMemo(() => ( + !topology.isVSCode && showRecentSection ? : null + ), [ + alwaysShowActions, + collection.childrenMap, + collection.pinnedSessionIds, + collection.sessions, + copiedSessionId, + deleteSessionConfirm, + editTitle, + editingId, + expandedParents, + notifyOnSubtasks, + openSidebarMenuKey, + recentSessions, + rowActions, + showRecentSection, + startFolderRename, + toggleParent, + topology.availableWorktreesByProject, + topology.gitBranches, + topology.isVSCode, + topology.projects, + view.hasSessionSearchQuery, + view.homeDirectory, + view.isDesktopShellRuntime, + view.mobileVariant, + view.normalizedSessionSearchQuery, + ]); + const scrollerModel = React.useMemo(() => ({ + topContent: recentSection, + hasSharedSessions: Boolean(recentSection), + sectionsForRender: orderedSectionsForRender, + projectSections, + activeProjectId: view.activeProjectId, + emptyState: view.emptyState, + searchEmptyState: view.searchEmptyState, + projectRepoStatus: topology.projectRepoStatus, + stuckProjectHeaders, + projectHeaderSentinelRefs, + state: { editingId, openSidebarMenuKey, setOpenSidebarMenuKey, visibleSessionCountByGroup }, + groupProps, + }), [ + groupProps, + editingId, + openSidebarMenuKey, + projectSections, + orderedSectionsForRender, + stuckProjectHeaders, + topology.projectRepoStatus, + view.activeProjectId, + view.emptyState, + view.searchEmptyState, + visibleSessionCountByGroup, + recentSection, + ]); + const scrollerView = React.useMemo(() => ({ + homeDirectory: view.homeDirectory, + collapsedProjects: projectView.collapsedProjects, + showOnlyMainWorkspace: view.showOnlyMainWorkspace, + hasSessionSearchQuery: view.hasSessionSearchQuery, + normalizedSessionSearchQuery: view.normalizedSessionSearchQuery, + hideDirectoryControls: view.hideDirectoryControls, + isDesktopShellRuntime: view.isDesktopShellRuntime, + stickyZoneHeaders: view.stickyZoneHeaders, + mobileVariant: view.mobileVariant, + alwaysShowActions, + projectSortOrder: view.projectSortOrder, + }), [ + projectView.collapsedProjects, + view.homeDirectory, + view.hasSessionSearchQuery, + view.hideDirectoryControls, + view.isDesktopShellRuntime, + view.mobileVariant, + alwaysShowActions, + view.normalizedSessionSearchQuery, + view.projectSortOrder, + view.showOnlyMainWorkspace, + view.stickyZoneHeaders, + ]); + const scrollerActionSet = React.useMemo(() => ({ + group: groupActions, + toggleProject, + setActiveProjectIdOnly: scrollerActions.setActiveProjectIdOnly, + setActiveMainTab: scrollerActions.setActiveMainTab, + setSessionSwitcherOpen: scrollerActions.setSessionSwitcherOpen, + openNewSessionDraft: scrollerActions.openNewSessionDraft, + openNewWorktreeDialog: scrollerActions.openNewWorktreeDialog, + openWorktreesPage: scrollerActions.openWorktreesPage, + openProjectEditDialog: scrollerActions.openProjectEditDialog, + removeProject: scrollerActions.removeProject, + reorderProjects: scrollerActions.reorderProjects, + setGroupOrderByProject, + renderProjectStatusIndicator: scrollerActions.renderProjectStatusIndicator, + }), [ + groupActions, + scrollerActions.openNewSessionDraft, + scrollerActions.openNewWorktreeDialog, + scrollerActions.openProjectEditDialog, + scrollerActions.openWorktreesPage, + scrollerActions.removeProject, + scrollerActions.reorderProjects, + scrollerActions.setActiveMainTab, + scrollerActions.setActiveProjectIdOnly, + scrollerActions.setSessionSwitcherOpen, + setGroupOrderByProject, + toggleProject, + scrollerActions.renderProjectStatusIndicator, + ]); + return <> + + + + + ; +}; + +export const SessionProjectCollection: React.FC = (props) => props.view.isVisible ? : null; diff --git a/packages/ui/src/components/session/sidebar/authoritativeSessionCleanup.ts b/packages/ui/src/components/session/sidebar/list/authoritativeSessionCleanup.ts similarity index 100% rename from packages/ui/src/components/session/sidebar/authoritativeSessionCleanup.ts rename to packages/ui/src/components/session/sidebar/list/authoritativeSessionCleanup.ts diff --git a/packages/ui/src/components/session/sidebar/sessionBootstrapDemands.test.ts b/packages/ui/src/components/session/sidebar/list/sessionBootstrapDemands.test.ts similarity index 73% rename from packages/ui/src/components/session/sidebar/sessionBootstrapDemands.test.ts rename to packages/ui/src/components/session/sidebar/list/sessionBootstrapDemands.test.ts index 302b46cd..1919c995 100644 --- a/packages/ui/src/components/session/sidebar/sessionBootstrapDemands.test.ts +++ b/packages/ui/src/components/session/sidebar/list/sessionBootstrapDemands.test.ts @@ -44,4 +44,22 @@ describe("buildSessionBootstrapDemands", () => { expect(byDirectory.get("/repo/wt-a")?.priority).toBe("expanded") expect(byDirectory.get("/repo/wt-b")?.priority).toBe("selected") }) + + test("keeps the complete known topology demanded without a visible section projection", () => { + const demands = buildSessionBootstrapDemands({ + knownDirectories: ["/repo", "/repo/wt-a", "/repo/wt-b"], + activeProjectDirectory: "/repo", + activeProjectId: "project-a", + collapsedProjects: new Set(), + collapsedGroups: new Set(), + currentDirectory: null, + currentSessionDirectory: null, + }) + + expect(demands.map(({ directory, priority }) => [directory, priority])).toEqual([ + ["/repo", "active-project"], + ["/repo/wt-a", "background"], + ["/repo/wt-b", "background"], + ]) + }) }) diff --git a/packages/ui/src/components/session/sidebar/sessionBootstrapDemands.ts b/packages/ui/src/components/session/sidebar/list/sessionBootstrapDemands.ts similarity index 83% rename from packages/ui/src/components/session/sidebar/sessionBootstrapDemands.ts rename to packages/ui/src/components/session/sidebar/list/sessionBootstrapDemands.ts index a8ff2357..d781f065 100644 --- a/packages/ui/src/components/session/sidebar/sessionBootstrapDemands.ts +++ b/packages/ui/src/components/session/sidebar/list/sessionBootstrapDemands.ts @@ -1,5 +1,5 @@ import type { DirectoryBootstrapDemand, DirectoryBootstrapPriority } from "@/sync/child-store" -import { normalizePath } from "./utils" +import { normalizePath } from "../utils" type BootstrapProjectSection = { project: { id: string; normalizedPath: string } @@ -11,16 +11,18 @@ type BootstrapProjectSection = { }> } -const PRIORITY_RANK: Record = { +const PRIORITY_RANK = { selected: 0, "active-project": 1, expanded: 2, visible: 3, background: 4, -} +} satisfies Record export function buildSessionBootstrapDemands(input: { - projectSections: BootstrapProjectSection[] + projectSections?: BootstrapProjectSection[] + knownDirectories?: Iterable + activeProjectDirectory?: string | null activeProjectId: string | null collapsedProjects: ReadonlySet collapsedGroups: ReadonlySet @@ -40,7 +42,12 @@ export function buildSessionBootstrapDemands(input: { byDirectory.set(normalizedDirectory, { directory: normalizedDirectory, priority, reason }) } - for (const section of input.projectSections) { + for (const directory of input.knownDirectories ?? []) { + add(directory, "background", "known-project") + } + add(input.activeProjectDirectory, "active-project", "project-expanded") + + for (const section of input.projectSections ?? []) { const projectExpanded = !input.collapsedProjects.has(section.project.id) let projectPriority: DirectoryBootstrapPriority = "background" if (section.project.id === input.activeProjectId) { diff --git a/packages/ui/src/components/session/sidebar/list/sessionCollection.test.ts b/packages/ui/src/components/session/sidebar/list/sessionCollection.test.ts new file mode 100644 index 00000000..e6930554 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/sessionCollection.test.ts @@ -0,0 +1,250 @@ +import { describe, expect, test } from 'bun:test'; +import type { Session } from '@opencode-ai/sdk/v2'; +import type { Event } from '@opencode-ai/sdk/v2/client'; +import React, { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { deriveRecentSessions } from '../recent/activitySections'; +import { applyGlobalSessionStatusEvent, useGlobalSessionStatusStore } from '@/sync/global-session-status'; +import { getDescendantIds, projectSidebarActiveSessions, projectSidebarCollection, useRecentSessionCollection } from './sessionCollection'; + +const installMinimalDom = () => { + const descriptors = new Map(); + const setGlobal = (name: string, value: unknown) => { + descriptors.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); + Object.defineProperty(globalThis, name, { configurable: true, writable: true, value }); + }; + class ElementStub {} + const documentStub: Record = { + nodeType: 9, defaultView: globalThis, activeElement: null, + addEventListener: () => undefined, removeEventListener: () => undefined, + }; + const container = { + nodeType: 1, tagName: 'DIV', nodeName: 'DIV', namespaceURI: 'http://www.w3.org/1999/xhtml', ownerDocument: documentStub, + addEventListener: () => undefined, removeEventListener: () => undefined, + }; + documentStub.documentElement = container; + documentStub.body = container; + setGlobal('document', documentStub); + setGlobal('window', globalThis); + setGlobal('Element', ElementStub); + setGlobal('HTMLElement', ElementStub); + setGlobal('HTMLIFrameElement', ElementStub); + setGlobal('IS_REACT_ACT_ENVIRONMENT', true); + return { + container: container as unknown as Element, + restore: () => { + for (const [name, descriptor] of descriptors) { + if (descriptor) Object.defineProperty(globalThis, name, descriptor); + else Reflect.deleteProperty(globalThis, name); + } + }, + }; +}; + +const session = (id: string, directory: string | null): Session => { + // SAFETY: Sidebar projection reads only id, directory, and time from session fixtures. + return { + id, + directory, + time: { created: 1, updated: 1 }, + } as Session; +}; + +describe('projectSidebarActiveSessions', () => { + test('keeps global precedence and order, then appends missing live sessions', () => { + const global = [session('global-b', '/workspace/b'), session('global-a', '/workspace/a')]; + const live = [session('global-a', '/workspace/a'), session('live-c', '/workspace/c')]; + + expect(projectSidebarActiveSessions({ + globalActiveSessions: global, + liveSessions: live, + knownDirectories: new Set(['/workspace/a', '/workspace/b', '/workspace/c']), + isVSCode: false, + }).map((entry) => entry.id)).toEqual(['global-b', 'global-a', 'live-c']); + }); + + test('filters unknown VS Code directories', () => { + const sessions = [session('known', '/workspace/known'), session('unknown', '/workspace/unknown')]; + + expect(projectSidebarActiveSessions({ + globalActiveSessions: sessions, + liveSessions: [], + knownDirectories: new Set(['/workspace/known']), + isVSCode: true, + }).map((entry) => entry.id)).toEqual(['known']); + }); + + test('allows missing or unknown directories for web when no directories are known', () => { + const sessions = [session('unknown', '/workspace/unknown'), session('empty', null)]; + + expect(projectSidebarActiveSessions({ + globalActiveSessions: sessions, + liveSessions: [], + knownDirectories: new Set(), + isVSCode: false, + }).map((entry) => entry.id)).toEqual(['unknown', 'empty']); + }); + + test('keeps archived sessions despite directory filtering', () => { + const archived = session('archived', '/workspace/unknown'); + archived.time.archived = 1; + + expect(projectSidebarActiveSessions({ + globalActiveSessions: [archived], + liveSessions: [], + knownDirectories: new Set(['/workspace/known']), + isVSCode: true, + }).map((entry) => entry.id)).toEqual(['archived']); + }); + + test('does not replace a filtered global record with a live duplicate', () => { + expect(projectSidebarActiveSessions({ + globalActiveSessions: [session('same', '/workspace/unknown')], + liveSessions: [session('same', '/workspace/known')], + knownDirectories: new Set(['/workspace/known']), + isVSCode: true, + })).toEqual([]); + }); +}); + +describe('projectSidebarCollection', () => { + test('returns the same structural projection for unchanged inputs without module caching', () => { + const globalActiveSessions = [session('a', '/workspace/a'), session('b', '/workspace/b')]; + const input = { + globalActiveSessions, + liveSessions: [], + knownDirectories: new Set(['/workspace/a', '/workspace/b']), + isVSCode: false, + }; + + const beforeSelection = projectSidebarCollection(input); + const afterSelection = projectSidebarCollection(input); + + expect(afterSelection).toEqual(beforeSelection); + }); + + test('rebuilds when a structural session collection input changes', () => { + const input = { + globalActiveSessions: [session('a', '/workspace/a')], + liveSessions: [], + knownDirectories: new Set(['/workspace/a']), + isVSCode: false, + }; + + const before = projectSidebarCollection(input); + const after = projectSidebarCollection({ + ...input, + globalActiveSessions: [session('a', '/workspace/a'), session('b', '/workspace/a')], + }); + + expect(after).not.toBe(before); + expect(after.map((entry) => entry.id)).toEqual(['a', 'b']); + }); + + test('keeps project membership independent from Recent active membership', () => { + const input = { + globalActiveSessions: [session('old-root', '/workspace/a')], + liveSessions: [], + knownDirectories: new Set(['/workspace/a']), + isVSCode: false, + }; + const projectBefore = projectSidebarCollection(input); + const recentBefore = deriveRecentSessions(projectBefore, new Set(), 200_000_000); + const projectAfter = projectSidebarCollection(input); + const recentAfter = deriveRecentSessions(projectAfter, new Set(['old-root']), 200_000_000); + + expect(projectAfter).toEqual(projectBefore); + expect(recentBefore).toEqual([]); + expect(recentAfter.map((entry) => entry.id)).toEqual(['old-root']); + }); +}); + +describe('useRecentSessionCollection', () => { + test('updates mounted Recent membership when global active status changes', async () => { + const dom = installMinimalDom(); + const root: Root = createRoot(dom.container); + const oldSession = { ...session('old-root', '/workspace/a'), time: { created: 1, updated: 1 } }; + let renderedIds: string[] = []; + let renderCount = 0; + let timeReadCount = 0; + Object.defineProperty(oldSession, 'time', { + get: () => { + timeReadCount += 1; + return { created: 1, updated: 1 }; + }, + }); + timeReadCount = 0; + const Harness = () => { + renderCount += 1; + const recent = useRecentSessionCollection({ + enabled: true, + isVSCode: false, + pinnedSessionIds: new Set(), + sessionOrderRanks: new Map(), + sessions: [oldSession], + }); + renderedIds = recent.map((entry) => entry.id); + return null; + }; + + try { + useGlobalSessionStatusStore.setState({ statusById: new Map() }); + await act(async () => root.render(React.createElement(Harness))); + expect(renderedIds).toEqual([]); + + await act(async () => { + // SAFETY: This fixture matches the SDK event shape consumed by the status event reducer. + applyGlobalSessionStatusEvent('/workspace/a', { + type: 'session.status', + properties: { sessionID: 'old-root', status: { type: 'busy' } }, + } as Event); + }); + expect(renderedIds).toEqual(['old-root']); + const activeRenderCount = renderCount; + const activeDeriveOperationCount = timeReadCount; + + await act(async () => { + // SAFETY: This fixture matches the SDK event shape consumed by the status event reducer. + applyGlobalSessionStatusEvent('/other-workspace', { + type: 'session.status', + properties: { sessionID: 'old-root', status: { type: 'retry', attempt: 2, message: 'waiting' } }, + } as Event); + }); + expect(renderCount).toBe(activeRenderCount); + expect(timeReadCount).toBe(activeDeriveOperationCount); + } finally { + await act(async () => root.unmount()); + useGlobalSessionStatusStore.setState({ statusById: new Map() }); + dom.restore(); + } + }); +}); + +describe('getDescendantIds', () => { + test('returns a depth-first subtree without exposing session entities', () => { + const childA = session('child-a', '/workspace/a'); + const grandchild = session('grandchild', '/workspace/a'); + const childB = session('child-b', '/workspace/a'); + const childrenMap = new Map([ + ['root', [childA, childB]], + ['child-a', [grandchild]], + ]); + + expect(getDescendantIds(childrenMap, 'root')) + .toEqual(['child-a', 'grandchild', 'child-b']); + }); + + test('cuts a parent cycle with deterministic unique descendants and excludes the root', () => { + const childA = session('a', '/workspace/a'); + const childB = session('b', '/workspace/a'); + const childC = session('c', '/workspace/a'); + const childrenMap = new Map([ + ['root', [childA]], + ['a', [childB, childC]], + ['b', [childA]], + ]); + + expect(getDescendantIds(childrenMap, 'root')).toEqual(['a', 'b', 'c']); + expect(new Set(getDescendantIds(childrenMap, 'root')).size).toBe(3); + }); +}); diff --git a/packages/ui/src/components/session/sidebar/list/sessionCollection.ts b/packages/ui/src/components/session/sidebar/list/sessionCollection.ts new file mode 100644 index 00000000..4c62c9f7 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/sessionCollection.ts @@ -0,0 +1,179 @@ +import React from 'react'; +import type { Session } from '@opencode-ai/sdk/v2'; +import { useAllLiveSessions } from '@/sync/sync-context'; +import { + compareSessionsByLifecycleOrder, + EMPTY_SESSION_ORDER_RANKS, + orderSessionsByLifecycleScopes, + useSessionOrderingStore, +} from '@/sync/session-ordering'; +import { useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore'; +import { useSessionPinnedStore } from '@/stores/useSessionPinnedStore'; +import { useGlobalSessionStatusStore } from '@/sync/global-session-status'; +import { resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore'; +import { deriveRecentSessions } from '../recent/activitySections'; +import { normalizePath } from '../utils'; + +type ProjectSidebarActiveSessionsArgs = { + globalActiveSessions: Session[]; + liveSessions: Session[]; + knownDirectories: Set; + isVSCode: boolean; +}; + +const EMPTY_ACTIVE_SESSION_IDS: ReadonlySet = new Set(); + +const isKnownActiveSessionDirectory = ( + session: Session, + knownDirectories: Set, + isVSCode: boolean, +): boolean => { + if (session.time?.archived) return true; + const directory = normalizePath(resolveGlobalSessionDirectory(session))?.toLowerCase(); + if (!directory) return !isVSCode; + if (knownDirectories.size === 0) return !isVSCode; + return knownDirectories.has(directory); +}; + +// Global sessions provide complete sidebar coverage; initialized directory +// stores only fill gaps until the global cache catches up. +export const projectSidebarActiveSessions = ({ + globalActiveSessions, + liveSessions, + knownDirectories, + isVSCode, +}: ProjectSidebarActiveSessionsArgs): Session[] => { + const sessions = [...globalActiveSessions]; + const knownIds = new Set(globalActiveSessions.map((session) => session.id)); + + for (const session of liveSessions) { + if (knownIds.has(session.id)) continue; + sessions.push(session); + } + + return sessions.filter((session) => isKnownActiveSessionDirectory(session, knownDirectories, isVSCode)); +}; + +export const projectSidebarCollection = (args: ProjectSidebarActiveSessionsArgs): Session[] => { + return projectSidebarActiveSessions(args); +}; + +// The collection owns hierarchy membership. Consumers receive this narrow +// resolver instead of retaining the collection's mutable indexing detail. +export const getDescendantIds = ( + childrenMap: ReadonlyMap, + sessionId: string, +): string[] => { + const descendants: string[] = []; + const visited = new Set([sessionId]); + const visit = (parentId: string): void => { + for (const child of childrenMap.get(parentId) ?? []) { + if (visited.has(child.id)) continue; + visited.add(child.id); + descendants.push(child.id); + visit(child.id); + } + }; + visit(sessionId); + return descendants; +}; + +type UseSessionProjectCollectionArgs = { + knownDirectories: Set; + isVSCode: boolean; + isVisible: boolean; +}; + +// The collection owns the global-first/live-gap merge and lifecycle ordering. +// Selection state intentionally never enters this boundary: rows subscribe to +// active state themselves, leaving this projection referentially stable. +export const useSessionProjectCollection = ({ + knownDirectories, + isVSCode, + isVisible, +}: UseSessionProjectCollectionArgs) => { + const globalActiveSessions = useGlobalSessionsStore((state) => state.activeSessions); + const archivedSessions = useGlobalSessionsStore((state) => state.archivedSessions); + const hasAuthoritativeGlobalSessions = useGlobalSessionsStore((state) => state.status === 'ready'); + const liveSessions = useAllLiveSessions(); + const pinnedSessionIds = useSessionPinnedStore((state) => state.ids); + const sessionOrderRanks = useSessionOrderingStore(React.useCallback( + (state) => isVisible ? state.rankById : EMPTY_SESSION_ORDER_RANKS, + [isVisible], + )); + const sessions = React.useMemo(() => projectSidebarCollection({ + globalActiveSessions, + liveSessions, + knownDirectories, + isVSCode, + }), [globalActiveSessions, isVSCode, knownDirectories, liveSessions]); + const orderedSessions = React.useMemo( + () => orderSessionsByLifecycleScopes(sessions, pinnedSessionIds, sessionOrderRanks), + [pinnedSessionIds, sessionOrderRanks, sessions], + ); + const sessionById = React.useMemo(() => new Map( + [...orderedSessions, ...archivedSessions].map((session) => [session.id, session]), + ), [archivedSessions, orderedSessions]); + const childrenMap = React.useMemo(() => { + const children = new Map(); + for (const session of sessionById.values()) { + // SAFETY: OpenCode's session records carry parentID for sub-session + // hierarchy; the SDK's base Session type does not currently expose it. + const parentID = (session as Session & { parentID?: string | null }).parentID; + if (!parentID) continue; + const siblings = children.get(parentID) ?? []; + siblings.push(session); + children.set(parentID, siblings); + } + return children; + }, [sessionById]); + const getDescendantIdsForAction = React.useCallback( + (sessionId: string, options: { includeArchived: boolean }) => getDescendantIds(childrenMap, sessionId) + .filter((id) => options.includeArchived || !Boolean(sessionById.get(id)?.time?.archived)), + [childrenMap, sessionById], + ); + + return { + archivedSessions, + childrenMap, + getDescendantIds: getDescendantIdsForAction, + globalActiveSessions, + hasAuthoritativeGlobalSessions, + liveSessions, + orderedSessions, + pinnedSessionIds, + sessionOrderRanks, + sessions, + }; +}; + +type UseRecentSessionCollectionArgs = { + enabled: boolean; + isVSCode: boolean; + pinnedSessionIds: Set; + sessionOrderRanks: ReadonlyMap; + sessions: Session[]; +}; + +// Recent is a separate high-frequency collection view. Its active membership +// never participates in project ownership or project section projection. +export const useRecentSessionCollection = ({ + enabled, + isVSCode, + pinnedSessionIds, + sessionOrderRanks, + sessions, +}: UseRecentSessionCollectionArgs): Session[] => { + const activeSessionIdSet = useGlobalSessionStatusStore( + React.useCallback( + (state) => enabled && !isVSCode ? state.activeSessionIds : EMPTY_ACTIVE_SESSION_IDS, + [enabled, isVSCode], + ), + ); + + return React.useMemo(() => { + if (!enabled || isVSCode) return []; + return deriveRecentSessions(sessions, activeSessionIdSet) + .sort((left, right) => compareSessionsByLifecycleOrder(left, right, pinnedSessionIds, sessionOrderRanks)); + }, [activeSessionIdSet, enabled, isVSCode, pinnedSessionIds, sessionOrderRanks, sessions]); +}; diff --git a/packages/ui/src/components/session/sidebar/list/sessionListDirectories.test.ts b/packages/ui/src/components/session/sidebar/list/sessionListDirectories.test.ts new file mode 100644 index 00000000..285b8841 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/sessionListDirectories.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, test } from 'bun:test'; +import { buildKnownSessionDirectories } from './sessionListDirectories'; + +describe('buildKnownSessionDirectories', () => { + test('normalizes project roots and optionally includes worktrees', () => { + const worktrees = new Map([ + ['/repo', [{ path: '/repo/worktree', projectDirectory: '/repo', branch: 'worktree', label: 'worktree' }]], + ]); + + expect([...buildKnownSessionDirectories([{ path: '/Repo' }], worktrees)]).toEqual([ + '/repo', + '/repo/worktree', + ]); + expect([...buildKnownSessionDirectories([{ path: '/Repo' }], worktrees, { includeWorktrees: false })]).toEqual([ + '/repo', + ]); + }); +}); diff --git a/packages/ui/src/components/session/sidebar/list/sessionListDirectories.ts b/packages/ui/src/components/session/sidebar/list/sessionListDirectories.ts new file mode 100644 index 00000000..e4d40764 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/sessionListDirectories.ts @@ -0,0 +1,24 @@ +import type { WorktreeMetadata } from '@/types/worktree'; +import { normalizePath } from '../utils'; + +export const buildKnownSessionDirectories = ( + projects: Array<{ path: string }>, + availableWorktreesByProject: Map, + options?: { includeWorktrees?: boolean }, +): Set => { + const directories = new Set(); + for (const project of projects) { + const normalized = normalizePath(project.path)?.toLowerCase(); + if (normalized) directories.add(normalized); + } + if (options?.includeWorktrees === false) { + return directories; + } + for (const worktrees of availableWorktreesByProject.values()) { + for (const worktree of worktrees) { + const normalized = normalizePath(worktree.path)?.toLowerCase(); + if (normalized) directories.add(normalized); + } + } + return directories; +}; diff --git a/packages/ui/src/components/session/sidebar/list/useAuthoritativeSessionCleanup.test.ts b/packages/ui/src/components/session/sidebar/list/useAuthoritativeSessionCleanup.test.ts new file mode 100644 index 00000000..9a4e18ed --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/useAuthoritativeSessionCleanup.test.ts @@ -0,0 +1,102 @@ +import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'; +import React from 'react'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import type { Session } from '@opencode-ai/sdk/v2'; +import { installHookTestDom } from '../test-utils/testDom'; +import { + buildAuthoritativeSessionIdentityMap, + findRemovedAuthoritativeSessions, +} from './authoritativeSessionCleanup'; + +// SAFETY: cleanup identity tests only consume the SDK session ID and directory fields. +const session = (id: string, directory = '/repo'): Session => ({ id, directory }) as Session; + +const cleanups: Array<{ runtimeKey: string; directory: string; sessionId: string }> = []; +mock.module('@/lib/runtime-switch', () => ({ getRuntimeKey: () => 'runtime' })); +mock.module('@/sync/session-deletion-cleanup', () => ({ + cleanupPersistedSessionState: (identity: { runtimeKey: string; directory: string; sessionId: string }) => cleanups.push(identity), +})); +const { useAuthoritativeSessionCleanup } = await import('./useAuthoritativeSessionCleanup'); + +const CleanupProbe: React.FC<{ sessions: Session[]; revision: number }> = ({ sessions, revision }) => { + useAuthoritativeSessionCleanup({ enabled: true, hasAuthoritativeGlobalSessions: true, sessions }); + return React.createElement('span', null, revision); +}; + +describe('authoritative session cleanup', () => { + let root: Root; + let dom: ReturnType; + + beforeEach(() => { + cleanups.length = 0; + dom = installHookTestDom(); + root = createRoot(dom.container); + }); + + afterEach(() => { + act(() => root.unmount()); + dom.restore(); + }); + + test('does not infer deletion from the first authoritative startup snapshot', () => { + const current = buildAuthoritativeSessionIdentityMap([]); + + expect(findRemovedAuthoritativeSessions(null, current)).toEqual([]); + }); + + test('finds sessions omitted after an established authoritative baseline', () => { + const previous = buildAuthoritativeSessionIdentityMap([ + session('deleted'), + session('retained'), + ]); + const current = buildAuthoritativeSessionIdentityMap([session('retained')]); + + expect(findRemovedAuthoritativeSessions(previous, current)).toEqual([ + { directory: '/repo', sessionId: 'deleted' }, + ]); + }); + + test('treats archive membership as retained authority', () => { + const previous = buildAuthoritativeSessionIdentityMap([session('archived')]); + const current = buildAuthoritativeSessionIdentityMap([ + // SAFETY: cleanup identity tests only consume the SDK session ID and directory fields. + { ...session('archived'), time: { archived: 10 } } as Session, + ]); + + expect(findRemovedAuthoritativeSessions(previous, current)).toEqual([]); + }); + + test('does not treat a directory move as session deletion', () => { + const previous = buildAuthoritativeSessionIdentityMap([session('moved', '/repo-a')]); + const current = buildAuthoritativeSessionIdentityMap([session('moved', '/repo-b')]); + + expect(findRemovedAuthoritativeSessions(previous, current)).toEqual([]); + }); + + test('uses the first mounted complete snapshot as a baseline, then cleans an omission once', () => { + const baseline = [session('deleted'), session('retained')]; + act(() => root.render(React.createElement(CleanupProbe, { sessions: baseline, revision: 0 }))); + expect(cleanups).toEqual([]); + + act(() => root.render(React.createElement(CleanupProbe, { sessions: [session('retained')], revision: 1 }))); + expect(cleanups).toEqual([{ runtimeKey: 'runtime', directory: '/repo', sessionId: 'deleted' }]); + + act(() => root.render(React.createElement(CleanupProbe, { sessions: [session('retained')], revision: 2 }))); + expect(cleanups).toHaveLength(1); + }); + + test('retains archive and move identities, preserves the same-array baseline on unrelated rerender, and resets on remount', () => { + const baseline = [session('session', '/repo-a')]; + act(() => root.render(React.createElement(CleanupProbe, { sessions: baseline, revision: 0 }))); + act(() => root.render(React.createElement(CleanupProbe, { sessions: baseline, revision: 1 }))); + act(() => root.render(React.createElement(CleanupProbe, { sessions: [{ ...session('session', '/repo-a'), time: { created: 0, updated: 0, archived: 1 } }], revision: 2 }))); + act(() => root.render(React.createElement(CleanupProbe, { sessions: [session('session', '/repo-b')], revision: 3 }))); + expect(cleanups).toEqual([]); + + act(() => root.unmount()); + root = createRoot(dom.container); + act(() => root.render(React.createElement(CleanupProbe, { sessions: [], revision: 4 }))); + expect(cleanups).toEqual([]); + }); +}); diff --git a/packages/ui/src/components/session/sidebar/hooks/useAuthoritativeSessionCleanup.ts b/packages/ui/src/components/session/sidebar/list/useAuthoritativeSessionCleanup.ts similarity index 96% rename from packages/ui/src/components/session/sidebar/hooks/useAuthoritativeSessionCleanup.ts rename to packages/ui/src/components/session/sidebar/list/useAuthoritativeSessionCleanup.ts index a86cc08b..4c7798bc 100644 --- a/packages/ui/src/components/session/sidebar/hooks/useAuthoritativeSessionCleanup.ts +++ b/packages/ui/src/components/session/sidebar/list/useAuthoritativeSessionCleanup.ts @@ -5,7 +5,7 @@ import { cleanupPersistedSessionState } from '@/sync/session-deletion-cleanup'; import { buildAuthoritativeSessionIdentityMap, findRemovedAuthoritativeSessions, -} from '../authoritativeSessionCleanup'; +} from './authoritativeSessionCleanup'; export const useAuthoritativeSessionCleanup = (args: { enabled?: boolean; diff --git a/packages/ui/src/components/session/sidebar/list/useSessionListSync.test.tsx b/packages/ui/src/components/session/sidebar/list/useSessionListSync.test.tsx new file mode 100644 index 00000000..20d0622b --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/useSessionListSync.test.tsx @@ -0,0 +1,248 @@ +import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'; +import React from 'react'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { installHookTestDom } from '../test-utils/testDom'; +import { useDirectoryStore } from '@/stores/useDirectoryStore'; +import { useProjectsStore } from '@/stores/useProjectsStore'; +import { useSessionUIStore } from '@/sync/session-ui-store'; +import type { WorktreeMetadata } from '@/types/worktree'; + +type Event = + | { type: 'scheduled-task-ran' } + | { type: 'session-created'; directory: string }; + +type LifecycleState = { + demands: Array<{ owner: string; directories: string[] }>; + clearedOwners: string[]; + globalRefreshes: number; + directoryRefreshes: string[][]; + cleanupInputs: Array<{ enabled: boolean; hasAuthoritativeGlobalSessions: boolean; sessionCount: number; sessions: unknown[] }>; + listener: ((event: Event) => void) | null; + subscriptions: number; + unsubscriptions: number; +}; +const state: LifecycleState = { + demands: [], + clearedOwners: [], + globalRefreshes: 0, + directoryRefreshes: [], + cleanupInputs: [], + listener: null, + subscriptions: 0, + unsubscriptions: 0, +}; +const childStores = { + setBootstrapDemand: (owner: string, demands: Array<{ directory: string }>) => { + state.demands.push({ owner, directories: demands.map((demand) => demand.directory) }); + }, + clearBootstrapDemand: (owner: string) => state.clearedOwners.push(owner), +}; +type GlobalSessionsState = { activeSessions: never[]; archivedSessions: never[]; status: 'ready' }; +const globalSessions: GlobalSessionsState = { activeSessions: [], archivedSessions: [], status: 'ready' }; + +mock.module('@/sync/sync-context', () => ({ + useChildStoreManager: () => childStores, +})); +mock.module('@/sync/sync-refs', () => ({ getAllSyncSessions: () => [] })); +mock.module('@/stores/useGlobalSessionsStore', () => ({ + useGlobalSessionsStore: (selector: (value: GlobalSessionsState) => T): T => selector(globalSessions), + refreshGlobalSessions: () => { state.globalRefreshes += 1; }, + refreshGlobalSessionsForDirectories: (directories: string[]) => { state.directoryRefreshes.push(directories); }, +})); +mock.module('@/lib/openchamberEvents', () => ({ + subscribeOpenchamberEvents: (listener: (event: Event) => void) => { + state.subscriptions += 1; + state.listener = listener; + return () => { + state.unsubscriptions += 1; + state.listener = null; + }; + }, +})); +mock.module('./useAuthoritativeSessionCleanup', () => ({ + useAuthoritativeSessionCleanup: (input: { enabled: boolean; hasAuthoritativeGlobalSessions: boolean; sessions: unknown[] }) => { + state.cleanupInputs.push({ + enabled: input.enabled, + hasAuthoritativeGlobalSessions: input.hasAuthoritativeGlobalSessions, + sessionCount: input.sessions.length, + sessions: input.sessions, + }); + }, +})); + +const { useSessionListSync } = await import('./useSessionListSync'); + +const projects = [{ id: 'project', path: '/project' }]; +const projectDirectories = new Set(['/project']); +const worktree: WorktreeMetadata = { path: '/worktree', projectDirectory: '/project', branch: 'feature', label: 'feature' }; + +const LifecycleProbe: React.FC<{ isVSCode: boolean }> = ({ isVSCode }) => { + useSessionListSync({ isVSCode }); + return null; +}; + +const LifecycleHarness: React.FC<{ isVSCode: boolean; branch: 'hidden' | 'visible' | 'compact-sessions' | 'compact-chat' | 'expanded' }> = ({ isVSCode, branch }) => <> + + {branch} +; + +describe('useSessionListSync', () => { + let root: Root; + let dom: ReturnType; + + beforeEach(() => { + state.demands = []; + state.clearedOwners = []; + state.globalRefreshes = 0; + state.directoryRefreshes = []; + state.cleanupInputs = []; + state.listener = null; + state.subscriptions = 0; + state.unsubscriptions = 0; + dom = installHookTestDom(); + root = createRoot(dom.container); + useProjectsStore.setState({ projects, activeProjectId: 'project' }); + useDirectoryStore.setState({ currentDirectory: '/project' }); + useSessionUIStore.setState({ currentSessionDirectory: null, availableWorktreesByProject: new Map() }); + }); + + afterEach(() => { + act(() => root.unmount()); + dom.restore(); + }); + + test('leaves initial global refresh to the root poller while publishing complete demand', () => { + act(() => useSessionUIStore.setState({ availableWorktreesByProject: new Map([['/project', [worktree]]]) })); + act(() => root.render()); + + expect(state.globalRefreshes).toBe(0); + expect(state.demands).toHaveLength(1); + expect(state.demands[0]?.directories).toEqual(['/project', '/worktree']); + expect(state.directoryRefreshes).toEqual([]); + expect(state.subscriptions).toBe(1); + expect(state.cleanupInputs.at(-1)).toEqual({ enabled: true, hasAuthoritativeGlobalSessions: true, sessionCount: 0, sessions: [] }); + }); + + test('refreshes every VS Code directory on first mount and only topology additions afterward', () => { + act(() => root.render()); + act(() => useProjectsStore.setState({ projects: [...projects, { id: 'added', path: '/added' }] })); + + expect(state.directoryRefreshes).toEqual([['/project'], ['/added']]); + }); + + test('coalesces control events and clears the listener, timeout, and demand on unmount', async () => { + act(() => root.render()); + state.listener?.({ type: 'session-created', directory: '/created-a' }); + state.listener?.({ type: 'session-created', directory: '/created-b' }); + state.listener?.({ type: 'scheduled-task-ran' }); + + await new Promise((resolve) => setTimeout(resolve, 550)); + expect(state.globalRefreshes).toBe(1); + expect(state.directoryRefreshes).toEqual([]); + + const owner = state.demands[0]?.owner; + act(() => root.unmount()); + expect(state.unsubscriptions).toBe(1); + expect(state.clearedOwners).toEqual([owner]); + }); + + test('does not duplicate lifecycle ownership when a hidden MainLayout or compact VS Code view rerenders', () => { + act(() => root.render()); + const cleanupSessions = state.cleanupInputs.at(-1)?.sessions; + act(() => root.render()); + expect(state.globalRefreshes).toBe(0); + expect(state.subscriptions).toBe(1); + expect(state.demands).toHaveLength(1); + expect(state.cleanupInputs.at(-1)?.sessions).toBe(cleanupSessions); + + act(() => root.unmount()); + root = createRoot(dom.container); + act(() => root.render()); + expect(state.globalRefreshes).toBe(0); + expect(state.subscriptions).toBe(2); + expect(state.unsubscriptions).toBe(1); + }); + + test('cancels a pending control-event refresh before a layout remount', async () => { + act(() => root.render()); + state.listener?.({ type: 'session-created', directory: '/created' }); + act(() => root.unmount()); + + await new Promise((resolve) => setTimeout(resolve, 550)); + expect(state.directoryRefreshes).toEqual([]); + expect(state.unsubscriptions).toBe(1); + }); + + test('binds MainLayout ownership to real Store worktrees without duplicating lifecycle work across branches', () => { + useProjectsStore.setState({ + projects: [{ id: 'project', path: '/project' }], + activeProjectId: 'project', + }); + useDirectoryStore.setState({ currentDirectory: '/project' }); + useSessionUIStore.setState({ + currentSessionDirectory: '/worktree', + availableWorktreesByProject: new Map([['/project', [worktree]]]), + }); + + act(() => root.render()); + act(() => root.render()); + act(() => root.render()); + + expect(state.demands).toHaveLength(1); + expect(state.demands[0]?.directories).toEqual(['/project', '/worktree']); + expect(state.globalRefreshes).toBe(0); + expect(state.subscriptions).toBe(1); + }); + + test('binds VS Code ownership to Store projects without worktrees and refreshes its first directories once', () => { + useProjectsStore.setState({ + projects: [{ id: 'project', path: '/project' }], + activeProjectId: 'project', + }); + useDirectoryStore.setState({ currentDirectory: '/project' }); + useSessionUIStore.setState({ + currentSessionDirectory: '/project', + availableWorktreesByProject: new Map([['/project', [worktree]]]), + }); + + act(() => root.render()); + act(() => root.render()); + act(() => root.unmount()); + root = createRoot(dom.container); + act(() => root.render()); + + expect(state.demands.map((demand) => demand.directories)).toEqual([['/project'], ['/project']]); + expect(state.directoryRefreshes).toEqual([['/project'], ['/project']]); + expect(state.globalRefreshes).toBe(0); + expect(state.subscriptions).toBe(2); + expect(state.unsubscriptions).toBe(1); + }); + + test('does not rerender VS Code lifecycle ownership for worktree-map-only changes', () => { + useProjectsStore.setState({ + projects: [{ id: 'project', path: '/project' }], + activeProjectId: 'project', + }); + useDirectoryStore.setState({ currentDirectory: '/project' }); + useSessionUIStore.setState({ + currentSessionDirectory: '/project', + availableWorktreesByProject: new Map([['/project', [worktree]]]), + }); + + act(() => root.render()); + const cleanupInputCount = state.cleanupInputs.length; + const demandCount = state.demands.length; + const directoryRefreshCount = state.directoryRefreshes.length; + const subscriptionCount = state.subscriptions; + + act(() => useSessionUIStore.setState({ + availableWorktreesByProject: new Map([['/project', [{ ...worktree, path: '/other-worktree' }]]]), + })); + + expect(state.cleanupInputs).toHaveLength(cleanupInputCount); + expect(state.demands).toHaveLength(demandCount); + expect(state.directoryRefreshes).toHaveLength(directoryRefreshCount); + expect(state.subscriptions).toBe(subscriptionCount); + }); +}); diff --git a/packages/ui/src/components/session/sidebar/list/useSessionListSync.ts b/packages/ui/src/components/session/sidebar/list/useSessionListSync.ts new file mode 100644 index 00000000..fc493588 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/useSessionListSync.ts @@ -0,0 +1,97 @@ +import React from 'react'; +import { subscribeOpenchamberEvents } from '@/lib/openchamberEvents'; +import { refreshGlobalSessions, refreshGlobalSessionsForDirectories, useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore'; +import { useChildStoreManager } from '@/sync/sync-context'; +import { getAllSyncSessions } from '@/sync/sync-refs'; +import { useSessionUIStore } from '@/sync/session-ui-store'; +import { useDirectoryStore } from '@/stores/useDirectoryStore'; +import { useProjectsStore } from '@/stores/useProjectsStore'; +import { buildSessionBootstrapDemands } from './sessionBootstrapDemands'; +import { buildKnownSessionDirectories } from './sessionListDirectories'; +import { useAuthoritativeSessionCleanup } from './useAuthoritativeSessionCleanup'; +import { normalizePath } from '../utils'; + +const EMPTY_WORKTREES_BY_PROJECT = new Map(); + +type UseSessionListSyncOptions = { + isVSCode: boolean; +}; + +export const useSessionListSync = ({ + isVSCode, +}: UseSessionListSyncOptions) => { + const childStores = useChildStoreManager(); + const projects = useProjectsStore((state) => state.projects); + const activeProjectId = useProjectsStore((state) => state.activeProjectId); + const currentDirectory = useDirectoryStore((state) => state.currentDirectory); + const currentSessionDirectory = useSessionUIStore((state) => state.currentSessionDirectory); + const availableWorktreesByProject = useSessionUIStore((state) => isVSCode ? EMPTY_WORKTREES_BY_PROJECT : state.availableWorktreesByProject); + const knownDirectories = React.useMemo( + () => buildKnownSessionDirectories(projects, availableWorktreesByProject, { includeWorktrees: !isVSCode }), + [availableWorktreesByProject, isVSCode, projects], + ); + const globalActiveSessions = useGlobalSessionsStore((state) => state.activeSessions); + const archivedSessions = useGlobalSessionsStore((state) => state.archivedSessions); + const hasAuthoritativeGlobalSessions = useGlobalSessionsStore((state) => state.status === 'ready'); + const bootstrapDemandOwner = `session-list-sync:${React.useId()}`; + + React.useEffect(() => { + childStores.setBootstrapDemand(bootstrapDemandOwner, buildSessionBootstrapDemands({ + knownDirectories, + activeProjectDirectory: normalizePath(projects.find((project) => project.id === activeProjectId)?.path ?? null), + activeProjectId, + collapsedProjects: new Set(), + collapsedGroups: new Set(), + currentDirectory, + currentSessionDirectory, + })); + return () => childStores.clearBootstrapDemand(bootstrapDemandOwner); + }, [activeProjectId, bootstrapDemandOwner, childStores, currentDirectory, currentSessionDirectory, knownDirectories, projects]); + + const knownProjectSessionDirectoriesRef = React.useRef | null>(null); + React.useEffect(() => { + const directories = new Set(knownDirectories); + const previous = knownProjectSessionDirectoriesRef.current; + knownProjectSessionDirectoriesRef.current = directories; + const added = previous ? [...directories].filter((directory) => !previous.has(directory)) : isVSCode ? [...directories] : []; + if (added.length) void refreshGlobalSessionsForDirectories(added, getAllSyncSessions()); + }, [isVSCode, knownDirectories]); + + React.useEffect(() => { + let timeout: ReturnType | null = null; + let refreshAll = false; + const directories = new Set(); + const unsubscribe = subscribeOpenchamberEvents((event) => { + if (event.type === 'scheduled-task-ran') refreshAll = true; + else if (event.type === 'session-created') directories.add(event.directory); + else return; + if (timeout) clearTimeout(timeout); + timeout = setTimeout(() => { + timeout = null; + if (refreshAll) { + refreshAll = false; + directories.clear(); + void refreshGlobalSessions(getAllSyncSessions()); + return; + } + const requested = [...directories]; + directories.clear(); + if (requested.length) void refreshGlobalSessionsForDirectories(requested, getAllSyncSessions()); + }, 500); + }); + return () => { + if (timeout) clearTimeout(timeout); + unsubscribe(); + }; + }, []); + + const cleanupSessions = React.useMemo( + () => [...globalActiveSessions, ...archivedSessions], + [archivedSessions, globalActiveSessions], + ); + useAuthoritativeSessionCleanup({ + enabled: true, + hasAuthoritativeGlobalSessions, + sessions: cleanupSessions, + }); +}; diff --git a/packages/ui/src/components/session/sidebar/list/useSessionPrefetch.test.tsx b/packages/ui/src/components/session/sidebar/list/useSessionPrefetch.test.tsx new file mode 100644 index 00000000..badc6457 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/list/useSessionPrefetch.test.tsx @@ -0,0 +1,44 @@ +import { describe, expect, test } from 'bun:test'; +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import type { Session } from '@opencode-ai/sdk/v2'; +import { useSessionPrefetch } from './useSessionPrefetch'; +import { installHookTestDom } from '../test-utils/testDom'; + +const session = (id: string): Session => ({ + id, + slug: id, + projectID: 'project', + title: id, + version: '1', + directory: '/workspace', + time: { created: 1, updated: 1 }, +}); + +describe('session prefetch demand', () => { + test('deduplicates the same nearby session from project and Recent projections', async () => { + const dom = installHookTestDom(); + const root = createRoot(dom.container); + const current = session('current'); + const nearby = session('nearby'); + const calls: string[] = []; + const Harness = () => { + useSessionPrefetch({ + enabled: true, + currentSessionId: current.id, + sortedSessions: [current, nearby], + recentSessions: [current, nearby], + prefetchSession: async (sessionId) => { calls.push(sessionId); }, + }); + return null; + }; + try { + await act(async () => root.render(React.createElement(Harness))); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 850)); }); + expect(calls).toEqual(['nearby']); + } finally { + await act(async () => root.unmount()); + dom.restore(); + } + }); +}); diff --git a/packages/ui/src/components/session/sidebar/hooks/useSessionPrefetch.ts b/packages/ui/src/components/session/sidebar/list/useSessionPrefetch.ts similarity index 92% rename from packages/ui/src/components/session/sidebar/hooks/useSessionPrefetch.ts rename to packages/ui/src/components/session/sidebar/list/useSessionPrefetch.ts index 9cf895c3..c8dc60c5 100644 --- a/packages/ui/src/components/session/sidebar/hooks/useSessionPrefetch.ts +++ b/packages/ui/src/components/session/sidebar/list/useSessionPrefetch.ts @@ -14,7 +14,7 @@ type Args = { currentSessionId: string | null; sortedSessions: Session[]; recentSessions?: Session[]; - prefetchSession: (sessionId: string, directory: string) => Promise; + prefetchSession: (sessionId: string, directory: string) => Promise; }; type PrefetchRequest = { @@ -24,11 +24,11 @@ type PrefetchRequest = { }; const sessionDirectory = (session: Session | null | undefined): string | null => { - const directory = (session as (Session & { directory?: string | null }) | null | undefined)?.directory; - return typeof directory === 'string' && directory.trim() ? directory : null; + const directory = session?.directory?.trim(); + return directory || null; }; -const useSessionPrefetch = ({ enabled = true, currentSessionId, sortedSessions, recentSessions = [], prefetchSession }: Args): void => { +export const useSessionPrefetch = ({ enabled = true, currentSessionId, sortedSessions, recentSessions = [], prefetchSession }: Args): void => { const sessionPrefetchTimersRef = React.useRef>(new Map()); const sessionPrefetchQueueRef = React.useRef([]); const sessionPrefetchInFlightRef = React.useRef>(new Set()); @@ -47,7 +47,7 @@ const useSessionPrefetch = ({ enabled = true, currentSessionId, sortedSessions, }, []); const pumpSessionPrefetchQueue = React.useCallback(() => { - if (!enabled || prefetchDisabled || typeof window === 'undefined') { + if (!enabled || prefetchDisabled) { return; } @@ -82,7 +82,7 @@ const useSessionPrefetch = ({ enabled = true, currentSessionId, sortedSessions, const scheduleSessionPrefetch = React.useCallback((session: Session | null | undefined) => { const sessionId = session?.id; const directory = sessionDirectory(session); - if (!enabled || prefetchDisabled || !sessionId || !directory || sessionId === currentSessionId || typeof window === 'undefined') { + if (!enabled || prefetchDisabled || !sessionId || !directory || sessionId === currentSessionId) { return; } const request = { sessionId, directory, generation: generationRef.current }; diff --git a/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.behavior.test.tsx b/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.behavior.test.tsx new file mode 100644 index 00000000..03f2b031 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.behavior.test.tsx @@ -0,0 +1,227 @@ +import { describe, expect, mock, test } from 'bun:test'; +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { I18nProvider } from '@/lib/i18n'; +import { useSessionFoldersStore } from '@/stores/useSessionFoldersStore'; +import { useUIStore } from '@/stores/useUIStore'; +import type { SessionFolder } from '@/stores/useSessionFoldersStore'; +import type { Session } from '@opencode-ai/sdk/v2'; +import type { SessionGroupSectionProps } from './SessionGroupSection'; +import { SessionProjectScroller } from './SessionProjectScroller'; +import { RecentSessionSection } from '../recent/RecentSessionSection'; +import { SidebarActivitySections } from '../recent/SidebarActivitySections'; +import { installHookTestDom } from '../test-utils/testDom'; + +type FolderCallbacks = { + onRename: (name: string) => void; + onDelete: () => void; +}; + +type RowPropsCapture = Pick; + +type ExpectNever = T; +type RowDomainCallback = + | 'handleSaveEdit' + | 'handleCancelEdit' + | 'handleSessionSelect' + | 'handleSessionDoubleClick' + | 'handleShareSession' + | 'handleCopyShareUrl' + | 'handleCopySessionId' + | 'handleUnshareSession' + | 'handleDeleteSession' + | 'handleRestoreSession'; + +// Structural group contracts must not expose the row domain action surface. +type _SessionGroupSectionHasNoRowDomainCallbacks = ExpectNever>; +type _SessionProjectScrollerHasNoRowDomainCallbacks = ExpectNever, RowDomainCallback>>; +type _RecentSessionSectionHasNoRowDomainCallbacks = ExpectNever, RowDomainCallback>>; +type _SidebarActivitySectionsHasNoRowDomainCallbacks = ExpectNever, RowDomainCallback>>; + +let folderCallbacks: FolderCallbacks | null = null; +let rowPropsCapture: RowPropsCapture | null = null; + +mock.module('../../SessionFolderItem', () => ({ + SessionFolderItem: (props: FolderCallbacks) => { + folderCallbacks = props; + return null; + }, +})); + +mock.module('../folders/sessionFolderDnd', () => ({ + DroppableFolderWrapper: ({ children }: { children: (ref: () => void, isOver: boolean) => React.ReactNode }) => <>{children(() => undefined, false)}, + SessionFolderDndScope: ({ children }: { children: React.ReactNode }) => <>{children}, +})); + +mock.module('@/sync/sync-context', () => ({ + setActiveSession: () => undefined, + useChildStoreManager: () => ({ + subscribeBootstrap: () => () => undefined, + getBootstrapState: () => null, + getBootstrapFailure: () => undefined, + requestBootstrap: () => undefined, + }), + useDirectoryStore: () => null, + useGlobalSessionStatus: () => null, + useSessionPermissions: () => null, + useSessionQuestionCount: () => 0, + useSyncSDK: () => null, + useSyncDirectory: () => null, + buildSessionMessageRecordsSnapshot: () => [], +})); + +mock.module('../sessions/collapsedActivityIndicator', () => ({ + CollapsedSessionActivityIndicator: () => null, + useCollapsedSessionActivityState: () => null, +})); + +mock.module('../sessions/SessionTreeItem', () => ({ + SessionTreeItem: (props: RowPropsCapture) => { + rowPropsCapture = props; + return null; + }, +})); + +const { SessionGroupSection } = await import('./SessionGroupSection'); + +const folder: SessionFolder = { + id: 'folder-a', + name: 'Initial folder', + parentId: null, + sessionIds: [], + createdAt: 1, +}; + +const group: SessionGroupSectionProps['group'] = { + id: 'main', + label: 'Main', + branch: null, + description: null, + isMain: true, + worktree: null, + directory: '/workspace', + folderScopeKey: '/workspace', + sessions: [], +}; + +const groupWithSession: SessionGroupSectionProps['group'] = { + ...group, + // SAFETY: SessionGroupSection only reads the fixture session's id in this test. + sessions: [{ session: { id: 'session-a' } as Session, children: [], worktree: null }], +}; + +const createProps = (): SessionGroupSectionProps => ({ + group, + groupKey: 'project:main', + projectId: 'project', + hideGroupLabel: true, + hasSessionSearchQuery: false, + normalizedSessionSearchQuery: '', + groupSearchDataByGroup: new WeakMap(), + collapsedGroups: new Set(), + hideDirectoryControls: false, + showMoreGroupSessions: () => undefined, + resetGroupSessionLimit: () => undefined, + mobileVariant: false, + alwaysShowActions: false, + activeProjectId: 'project', + setActiveProjectIdOnly: () => undefined, + setActiveMainTab: () => undefined, + setSessionSwitcherOpen: () => undefined, + openNewSessionDraft: () => undefined, + pinnedSessionIds: new Set(), + sessionOrderIndex: new Map(), + notifyOnSubtasks: false, + expandedParents: new Set(), + editingId: null, + editTitle: '', + copiedSessionId: null, + openSidebarMenuKey: null, + setEditingId: () => undefined, + setEditTitle: () => undefined, + toggleParent: () => undefined, + setOpenSidebarMenuKey: () => undefined, + startFolderRename: () => undefined, + allowReselect: false, + isSessionSearchOpen: false, + sessionSearchQuery: '', + setSessionSearchQuery: () => undefined, + setIsSessionSearchOpen: () => undefined, + deleteSessionConfirm: null, + setDeleteSessionConfirm: () => undefined, + setCopiedSessionId: () => undefined, + onToggleCollapsedGroup: () => undefined, + folderRename: null, + setFolderRenameDraft: () => undefined, + clearFolderRename: () => undefined, +}); + +describe('SessionGroupSection public behavior', () => { + test('routes rendered folder rename and delete actions to the owning folder store', async () => { + const dom = installHookTestDom(); + const root = createRoot(dom.container); + const originalFolders = useSessionFoldersStore.getState(); + const originalUi = useUIStore.getState(); + useSessionFoldersStore.setState({ foldersMap: { '/workspace': [folder] } }); + useUIStore.setState({ showDeletionDialog: false }); + + try { + await act(async () => root.render()); + expect(folderCallbacks).not.toBeNull(); + + await act(async () => folderCallbacks?.onRename('Renamed folder')); + expect(useSessionFoldersStore.getState().foldersMap['/workspace']?.[0]?.name).toBe('Renamed folder'); + + await act(async () => folderCallbacks?.onDelete()); + expect(useSessionFoldersStore.getState().foldersMap['/workspace']).toEqual([]); + } finally { + await act(async () => root.unmount()); + useSessionFoldersStore.setState(originalFolders, true); + useUIStore.setState(originalUi, true); + folderCallbacks = null; + dom.restore(); + } + }); + + test('propagates confirmation, search/navigation, and copy ownership changes to rendered rows', async () => { + const dom = installHookTestDom(); + const root = createRoot(dom.container); + const firstSelected = () => undefined; + const nextSelected = () => undefined; + const firstCopied = () => undefined; + const nextCopied = () => undefined; + const initialProps = createProps(); + + try { + await act(async () => root.render()); + expect(rowPropsCapture?.onSessionSelected).toBe(firstSelected); + expect(rowPropsCapture?.sessionSearchQuery).toBe(''); + expect(rowPropsCapture?.deleteSessionConfirm).toBeNull(); + expect(rowPropsCapture?.copiedSessionId).toBeNull(); + expect(rowPropsCapture?.setCopiedSessionId).toBe(firstCopied); + + // SAFETY: the confirmation is only forwarded by identity to the row mock. + const confirmation = { session: { id: 'session-a' } as Session, descendantCount: 0, descendantIds: [], archivedBucket: false }; + await act(async () => root.render()); + expect(rowPropsCapture?.allowReselect).toBe(true); + expect(rowPropsCapture?.onSessionSelected).toBe(nextSelected); + expect(rowPropsCapture?.isSessionSearchOpen).toBe(true); + expect(rowPropsCapture?.sessionSearchQuery).toBe('search'); + expect(rowPropsCapture?.deleteSessionConfirm).toBe(confirmation); + expect(rowPropsCapture?.copiedSessionId).toBe('session-a'); + expect(rowPropsCapture?.setCopiedSessionId).toBe(nextCopied); + } finally { + await act(async () => root.unmount()); + rowPropsCapture = null; + dom.restore(); + } + }); +}); diff --git a/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.test.ts b/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.test.ts new file mode 100644 index 00000000..a3edd2d7 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, test } from 'bun:test'; +import type { SessionFolder } from '@/stores/useSessionFoldersStore'; +import { normalizeFolderRoots, selectFolderIdsForProjection } from '../sessions/sessionNodeItemUtils'; + +const folder = (id: string, parentId: string | null = null, sessionIds: string[] = []): SessionFolder => ({ + id, + name: id, + parentId, + sessionIds, + createdAt: 1, +}); + +describe('normalizeFolderRoots', () => { + test('returns cycle and orphan folders as deterministic fallback roots without duplication', () => { + const folders = [ + folder('cycle-a', 'cycle-b', ['session-a']), + folder('cycle-b', 'cycle-a'), + folder('orphan', 'missing-parent'), + folder('root'), + ]; + + expect(normalizeFolderRoots(folders).map((entry) => entry.id)) + .toEqual(['orphan', 'root', 'cycle-a']); + }); + + test('keeps normal nested folder root order unchanged', () => { + const folders = [folder('root-a'), folder('child-a', 'root-a'), folder('root-b')]; + + expect(normalizeFolderRoots(folders).map((entry) => entry.id)).toEqual(['root-a', 'root-b']); + }); +}); + +describe('selectFolderIdsForProjection', () => { + const malformedFolders = [ + { id: 'cycle-a', name: 'cycle-a', parentId: 'cycle-b', nodeCount: 0 }, + { id: 'cycle-b', name: 'cycle-b', parentId: 'cycle-a', nodeCount: 1 }, + { id: 'orphan', name: 'orphan', parentId: 'missing-parent', nodeCount: 0 }, + ]; + + test('keeps malformed empty and nonempty folders in every projection mode', () => { + for (const archivedBucket of [false, true]) { + for (const searchQuery of ['', 'does-not-match']) { + expect([...selectFolderIdsForProjection(malformedFolders, { archivedBucket, searchQuery })]) + .toEqual(['cycle-a', 'cycle-b', 'orphan']); + } + } + }); + + test('keeps normal archived/search nesting semantics', () => { + const folders = [ + { id: 'root', name: 'root', parentId: null, nodeCount: 0 }, + { id: 'child', name: 'matching-child', parentId: 'root', nodeCount: 1 }, + ]; + + expect([...selectFolderIdsForProjection(folders, { archivedBucket: true, searchQuery: 'matching' })]) + .toEqual(['root', 'child']); + }); +}); diff --git a/packages/ui/src/components/session/sidebar/SessionGroupSection.tsx b/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.tsx similarity index 77% rename from packages/ui/src/components/session/sidebar/SessionGroupSection.tsx rename to packages/ui/src/components/session/sidebar/projects/SessionGroupSection.tsx index c80d3d73..d1fec86b 100644 --- a/packages/ui/src/components/session/sidebar/SessionGroupSection.tsx +++ b/packages/ui/src/components/session/sidebar/projects/SessionGroupSection.tsx @@ -1,6 +1,6 @@ -import { matchesRankQuery } from '@/lib/search/fuzzySearch'; import React from 'react'; import { useVirtualizer } from '@tanstack/react-virtual'; +import { useShallow } from 'zustand/react/shallow'; import type { Session } from '@opencode-ai/sdk/v2'; // Archived buckets routinely grow into the hundreds/thousands; virtualize @@ -9,37 +9,40 @@ const ARCHIVED_VIRTUALIZE_THRESHOLD = 50; // Compact rows in the archived bucket without nested subagents render // around 24-32px; virtua measures mounted rows and uses this as the initial hint. const ARCHIVED_ROW_ESTIMATE_PX = 28; +const EMPTY_FOLDERS: readonly never[] = []; import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; import { Button } from '@/components/ui/button'; import { Icon } from "@/components/icon/Icon"; import { cn } from '@/lib/utils'; import { sessionEvents } from '@/lib/sessionEvents'; -import { SessionFolderItem } from '../SessionFolderItem'; +import { useUIStore } from '@/stores/useUIStore'; +import { SessionFolderItem } from '../../SessionFolderItem'; import type { SortableDragHandleProps } from './sortableItems'; -import { DroppableFolderWrapper, SessionFolderDndScope } from './sessionFolderDnd'; -import type { GroupSearchData, SessionGroup, SessionNode } from './types'; -import { isBranchDifferentFromLabel, normalizePath, renderHighlightedText } from './utils'; +import { DroppableFolderWrapper, SessionFolderDndScope } from '../folders/sessionFolderDnd'; +import type { GroupSearchData, SessionGroup, SessionNode } from '../types'; +import { isBranchDifferentFromLabel, normalizePath, renderHighlightedText } from '../utils'; import { compareSessionsByLifecycleOrder, EMPTY_SESSION_ORDER_RANKS } from '@/sync/session-ordering'; import { collectSubtreeContainingId, computeNodeStructureKey, nodeHasPinnedMembershipChange, nodeContainsSessionId, + normalizeFolderRoots, resolveMenuOpenSessionId, + selectFolderIdsForProjection, selectFolderRootNodes, -} from './sessionNodeItemUtils'; -import type { SessionNodeRenderExtras } from './sessionNodeItemUtils'; +} from '../sessions/sessionNodeItemUtils'; +import type { SessionNodeRenderExtras } from '../sessions/sessionNodeItemUtils'; import { useSessionFoldersStore } from '@/stores/useSessionFoldersStore'; + +type FolderScope = { scopeKey: string; directory: string | null }; import { getGitHubPrStatusKey, usePrVisualSummary } from '@/stores/useGitHubPrStatusStore'; import { useI18n } from '@/lib/i18n'; import { useChildStoreManager } from '@/sync/sync-context'; import { canRequestNativeDirectoryAccess, requestDirectoryAccess } from '@/lib/desktop'; -import { CollapsedActivityIndicator } from './collapsedActivityIndicator'; -import { - getSessionNodesActivityState, - mergeCollapsedActivityStates, - type CollapsedActivityState, -} from './collapsedActivityState'; +import { CollapsedSessionActivityIndicator, useCollapsedSessionActivityState } from '../sessions/collapsedActivityIndicator'; +import { SessionTreeItem, type SessionTreeItemProps } from '../sessions/SessionTreeItem'; +import { FolderDeleteConfirmDialog } from '../shell/ConfirmDialogs'; type DeleteFolderConfirm = { scopeKey: string; @@ -49,7 +52,7 @@ type DeleteFolderConfirm = { sessionCount: number; } | null; -type Props = { +export type SessionGroupSectionProps = { group: SessionGroup; groupKey: string; projectId?: string | null; @@ -61,22 +64,6 @@ type Props = { sessionBatchSize?: number; collapsedGroups: Set; hideDirectoryControls: boolean; - collapsedFolderIds: Set; - toggleFolderCollapse: (folderId: string) => void; - renameFolder: (scopeKey: string, folderId: string, name: string) => void; - deleteFolder: (scopeKey: string, folderId: string) => void; - showDeletionDialog: boolean; - setDeleteFolderConfirm: React.Dispatch>; - renderSessionNode: ( - node: SessionNode, - depth?: number, - groupDirectory?: string | null, - projectId?: string | null, - archivedBucket?: boolean, - secondaryMeta?: { projectLabel?: string | null; branchLabel?: string | null } | null, - renderContext?: 'project' | 'recent', - renderExtras?: SessionNodeRenderExtras, - ) => React.ReactNode; showMoreGroupSessions: (groupKey: string, currentVisibleCount: number, increment?: number) => void; resetGroupSessionLimit: (groupKey: string) => void; mobileVariant: boolean; @@ -85,21 +72,14 @@ type Props = { setActiveProjectIdOnly: (id: string) => void; setSessionSwitcherOpen: (open: boolean) => void; openNewSessionDraft: (options?: { selectedProjectId?: string | null; directoryOverride?: string | null; targetFolderId?: string; target?: 'chat' | 'project' }) => void; - addSessionToFolder: (scopeKey: string, folderId: string, sessionId: string) => void; - createFolderAndStartRename: (scopeKey: string, parentId?: string | null) => { id: string } | null; - renamingFolderId: string | null; - renameFolderDraft: string; - setRenameFolderDraft: React.Dispatch>; - setRenamingFolderId: React.Dispatch>; pinnedSessionIds: Set; - expandedParents: Set; sessionOrderIndex: Map; + notifyOnSubtasks: boolean; + expandedParents: Set; editingId: string | null; editTitle: string; + copiedSessionId: string | null; openSidebarMenuKey: string | null; - activeActivitySessionIds: Set; - unreadActivitySessionIds: Set; - notifyOnSubtasks: boolean; onToggleCollapsedGroup: (groupKey: string) => void; dragHandleProps?: SortableDragHandleProps | null; compactBodyPadding?: boolean; @@ -110,7 +90,34 @@ type Props = { * render of an expanded archived bucket. */ scrollContainerRef?: React.RefObject; -}; + folderRename: { scopeKey: string; folderId: string; draft: string } | null; + setFolderRenameDraft: (draft: string) => void; + clearFolderRename: () => void; +} & Pick; + +const CollapsedFolderActivity: React.FC<{ + nodes: SessionNode[]; + includeUnreadSubtasks: boolean; + children: (state: ReturnType) => React.ReactNode; +}> = ({ nodes, includeUnreadSubtasks, children }) => children(useCollapsedSessionActivityState({ + nodes, + includeUnreadSubtasks, +})); const groupContainsSessionId = (group: SessionGroup, sessionId: string | null): boolean => { if (!sessionId) return false; @@ -145,26 +152,6 @@ const groupHasSessionOrderChange = ( return group.sessions.some(visit); }; -const groupHasActivityMembershipChange = ( - group: SessionGroup, - prevSessionIds: Set, - nextSessionIds: Set, -): boolean => { - const visit = (node: SessionNode): boolean => { - if (prevSessionIds.has(node.session.id) !== nextSessionIds.has(node.session.id)) return true; - return node.children.some(visit); - }; - return group.sessions.some(visit); -}; - -const groupHasAnyActivityMembership = (group: SessionGroup, sessionIds: Set): boolean => { - const visit = (node: SessionNode): boolean => { - if (sessionIds.has(node.session.id)) return true; - return node.children.some(visit); - }; - return group.sessions.some(visit); -}; - const groupHasExpansionMembershipChange = ( group: SessionGroup, prevExpandedParents: Set, @@ -179,7 +166,7 @@ const groupHasExpansionMembershipChange = ( return group.sessions.some(visit); }; -const areGroupPropsEqual = (prev: Props, next: Props): boolean => { +const areGroupPropsEqual = (prev: SessionGroupSectionProps, next: SessionGroupSectionProps): boolean => { // Bail on Object.is for the props that drive the most work: the group // itself, its key, and the group-level chrome. These change rarely and // any change should force a re-render of this group. @@ -202,45 +189,36 @@ const areGroupPropsEqual = (prev: Props, next: Props): boolean => { return false; } - if (prev.expandedParents !== next.expandedParents - && groupHasExpansionMembershipChange(next.group, prev.expandedParents, next.expandedParents)) { - return false; - } - if (prev.sessionOrderIndex !== next.sessionOrderIndex && groupHasSessionOrderChange(next.group, prev.sessionOrderIndex, next.sessionOrderIndex)) { return false; } + if (prev.expandedParents !== next.expandedParents + && groupHasExpansionMembershipChange(next.group, prev.expandedParents, next.expandedParents)) { + return false; + } if (prev.editingId !== next.editingId - && (groupContainsSessionId(prev.group, prev.editingId) || groupContainsSessionId(next.group, next.editingId))) { + && (groupContainsSessionId(next.group, prev.editingId) || groupContainsSessionId(next.group, next.editingId))) { return false; } - - if (prev.editTitle !== next.editTitle - && (groupContainsSessionId(prev.group, prev.editingId) || groupContainsSessionId(next.group, next.editingId))) { + if (prev.editTitle !== next.editTitle && groupContainsSessionId(next.group, next.editingId)) return false; + if (prev.copiedSessionId !== next.copiedSessionId + && (groupContainsSessionId(next.group, prev.copiedSessionId) || groupContainsSessionId(next.group, next.copiedSessionId))) { return false; } - if (prev.openSidebarMenuKey !== next.openSidebarMenuKey) { - const prevMenuSessionId = resolveMenuOpenSessionId(prev.group.sessions, prev.openSidebarMenuKey, 'project', Boolean(prev.group.isArchivedBucket)); - const nextMenuSessionId = resolveMenuOpenSessionId(next.group.sessions, next.openSidebarMenuKey, 'project', Boolean(next.group.isArchivedBucket)); - if (prevMenuSessionId || nextMenuSessionId) return false; + const archived = next.group.isArchivedBucket === true; + const previousMenuSessionId = resolveMenuOpenSessionId(next.group.sessions, prev.openSidebarMenuKey, 'project', archived); + const nextMenuSessionId = resolveMenuOpenSessionId(next.group.sessions, next.openSidebarMenuKey, 'project', archived); + if (previousMenuSessionId || nextMenuSessionId) return false; } - - if (prev.activeActivitySessionIds !== next.activeActivitySessionIds - && groupHasActivityMembershipChange(next.group, prev.activeActivitySessionIds, next.activeActivitySessionIds)) { - return false; - } - - if (prev.unreadActivitySessionIds !== next.unreadActivitySessionIds - && groupHasActivityMembershipChange(next.group, prev.unreadActivitySessionIds, next.unreadActivitySessionIds)) { - return false; - } - - if (prev.notifyOnSubtasks !== next.notifyOnSubtasks - && groupHasAnyActivityMembership(next.group, next.unreadActivitySessionIds)) { - return false; + if (prev.folderRename !== next.folderRename) { + const scopes = next.group.folderScopes?.map((scope) => scope.scopeKey) + ?? [next.group.folderScopeKey ?? normalizePath(next.group.directory ?? null)]; + if (scopes.includes(prev.folderRename?.scopeKey ?? null) || scopes.includes(next.folderRename?.scopeKey ?? null)) { + return false; + } } // Other props are typically stable references from the parent. Default @@ -250,13 +228,6 @@ const areGroupPropsEqual = (prev: Props, next: Props): boolean => { prev.hasSessionSearchQuery === next.hasSessionSearchQuery && prev.normalizedSessionSearchQuery === next.normalizedSessionSearchQuery && prev.hideDirectoryControls === next.hideDirectoryControls - && prev.collapsedFolderIds === next.collapsedFolderIds - && prev.toggleFolderCollapse === next.toggleFolderCollapse - && prev.renameFolder === next.renameFolder - && prev.deleteFolder === next.deleteFolder - && prev.showDeletionDialog === next.showDeletionDialog - && prev.setDeleteFolderConfirm === next.setDeleteFolderConfirm - && prev.renderSessionNode === next.renderSessionNode && prev.showMoreGroupSessions === next.showMoreGroupSessions && prev.resetGroupSessionLimit === next.resetGroupSessionLimit && prev.mobileVariant === next.mobileVariant @@ -265,19 +236,30 @@ const areGroupPropsEqual = (prev: Props, next: Props): boolean => { && prev.setActiveProjectIdOnly === next.setActiveProjectIdOnly && prev.setSessionSwitcherOpen === next.setSessionSwitcherOpen && prev.openNewSessionDraft === next.openNewSessionDraft - && prev.addSessionToFolder === next.addSessionToFolder - && prev.createFolderAndStartRename === next.createFolderAndStartRename - && prev.renamingFolderId === next.renamingFolderId - && prev.renameFolderDraft === next.renameFolderDraft - && prev.setRenameFolderDraft === next.setRenameFolderDraft - && prev.setRenamingFolderId === next.setRenamingFolderId && prev.onToggleCollapsedGroup === next.onToggleCollapsedGroup && prev.dragHandleProps === next.dragHandleProps && prev.scrollContainerRef === next.scrollContainerRef + && prev.notifyOnSubtasks === next.notifyOnSubtasks + && prev.setEditingId === next.setEditingId + && prev.setEditTitle === next.setEditTitle + && prev.toggleParent === next.toggleParent + && prev.setOpenSidebarMenuKey === next.setOpenSidebarMenuKey + && prev.allowReselect === next.allowReselect + && prev.onSessionSelected === next.onSessionSelected + && prev.isSessionSearchOpen === next.isSessionSearchOpen + && prev.sessionSearchQuery === next.sessionSearchQuery + && prev.setSessionSearchQuery === next.setSessionSearchQuery + && prev.setIsSessionSearchOpen === next.setIsSessionSearchOpen + && prev.deleteSessionConfirm === next.deleteSessionConfirm + && prev.setDeleteSessionConfirm === next.setDeleteSessionConfirm + && prev.startFolderRename === next.startFolderRename + && prev.setCopiedSessionId === next.setCopiedSessionId + && prev.setFolderRenameDraft === next.setFolderRenameDraft + && prev.clearFolderRename === next.clearFolderRename ); }; -function SessionGroupSectionBase(props: Props): React.ReactNode { +function SessionGroupSectionBase(props: SessionGroupSectionProps): React.ReactNode { const { t } = useI18n(); const { group, @@ -291,13 +273,6 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { sessionBatchSize, collapsedGroups, hideDirectoryControls, - collapsedFolderIds, - toggleFolderCollapse, - renameFolder, - deleteFolder, - showDeletionDialog, - setDeleteFolderConfirm, - renderSessionNode, showMoreGroupSessions, resetGroupSessionLimit, mobileVariant, @@ -306,26 +281,28 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { setActiveProjectIdOnly, setSessionSwitcherOpen, openNewSessionDraft, - addSessionToFolder, - createFolderAndStartRename, - renamingFolderId, - renameFolderDraft, - setRenameFolderDraft, - setRenamingFolderId, pinnedSessionIds, - expandedParents, sessionOrderIndex, - editingId, - openSidebarMenuKey, - activeActivitySessionIds, - unreadActivitySessionIds, notifyOnSubtasks, onToggleCollapsedGroup, dragHandleProps, compactBodyPadding = false, scrollContainerRef, + expandedParents, + editingId, + openSidebarMenuKey, + editTitle, + copiedSessionId, + folderRename, + setFolderRenameDraft, + clearFolderRename, } = props; - + const toggleFolderCollapse = useSessionFoldersStore((state) => state.toggleFolderCollapse); + const renameFolder = useSessionFoldersStore((state) => state.renameFolder); + const deleteFolder = useSessionFoldersStore((state) => state.deleteFolder); + const addSessionToFolder = useSessionFoldersStore((state) => state.addSessionToFolder); + const showDeletionDialog = useUIStore((state) => state.showDeletionDialog); + const [deleteFolderConfirm, setDeleteFolderConfirm] = React.useState(null); const compareSessionNodes = React.useCallback((a: SessionNode, b: SessionNode) => { const aIndex = sessionOrderIndex.get(a.session.id); const bIndex = sessionOrderIndex.get(b.session.id); @@ -338,7 +315,6 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { }, [pinnedSessionIds, sessionOrderIndex]); const searchData = hasSessionSearchQuery ? groupSearchDataByGroup.get(group) : null; - const foldersMap = useSessionFoldersStore((state) => state.foldersMap); const isCollapsed = hasSessionSearchQuery ? false : collapsedGroups.has(groupKey); // PR state for the worktree sub-header (grouped display mode). const groupPrKey = React.useMemo(() => { @@ -413,15 +389,26 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { const folderScopeKey = group.folderScopeKey ?? normalizePath(group.directory ?? null); // Merged flat groups list every contributing scope; single-scope groups // (archived buckets, VS Code workspaces) fall back to folderScopeKey. - const folderScopes = React.useMemo>(() => { + const folderScopes = React.useMemo(() => { if (group.folderScopes && group.folderScopes.length > 0) return group.folderScopes; return folderScopeKey ? [{ scopeKey: folderScopeKey, directory: group.directory ?? null }] : []; }, [folderScopeKey, group.directory, group.folderScopes]); - const scopeFolders = React.useMemo( - () => folderScopes.flatMap(({ scopeKey, directory }) => - (foldersMap[scopeKey] ?? []).map((folder) => ({ folder, scopeKey, scopeDirectory: directory }))), - [folderScopes, foldersMap] - ); + // A group only needs folders and collapse state from its own scopes. The + // shallow projection retains its reference for mutations elsewhere. + const folderProjection = useSessionFoldersStore(useShallow(React.useCallback( + (state) => folderScopes.map(({ scopeKey }) => state.foldersMap[scopeKey] ?? EMPTY_FOLDERS), + [folderScopes], + ))); + const scopeFolders = React.useMemo(() => folderScopes.flatMap(({ scopeKey, directory }, index) => { + const folders = folderProjection[index] ?? EMPTY_FOLDERS; + return folders.map((folder) => ({ folder, scopeKey, scopeDirectory: directory })); + }), [folderProjection, folderScopes]); + const collapsedFolderIds = useSessionFoldersStore(useShallow(React.useCallback( + (state) => new Set(folderProjection.flatMap((folders) => folders + .filter((folder) => state.collapsedFolderIds.has(folder.id)) + .map((folder) => folder.id))), + [folderProjection], + ))); const nodeBySessionId = React.useMemo(() => { const map = new Map(); @@ -443,60 +430,45 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { }), [scopeFolders, nodeBySessionId, compareSessionNodes]); const allFoldersForGroup = React.useMemo(() => { - const folderMapById = new Map(allFoldersForGroupBase.map((entry) => [entry.folder.id, entry])); - const childFolderIdsByParentId = new Map(); - for (const { folder } of allFoldersForGroupBase) { - if (!folder.parentId) continue; - const existing = childFolderIdsByParentId.get(folder.parentId); - if (existing) { - existing.push(folder.id); - } else { - childFolderIdsByParentId.set(folder.parentId, [folder.id]); - } - } - - const keepByFolderId = new Map(); - const shouldKeepFolder = (folderId: string): boolean => { - const cached = keepByFolderId.get(folderId); - if (cached !== undefined) return cached; - - const entry = folderMapById.get(folderId); - if (!entry) { - keepByFolderId.set(folderId, false); - return false; - } - - const childFolderIds = childFolderIdsByParentId.get(folderId) ?? []; - - // For archived buckets, hide folders with no sessions unless descendants have content. - if (group.isArchivedBucket && entry.nodes.length === 0) { - const hasContentInChildren = childFolderIds.some((childId) => shouldKeepFolder(childId)); - keepByFolderId.set(folderId, hasContentInChildren); - return hasContentInChildren; - } - - if (!hasSessionSearchQuery) { - keepByFolderId.set(folderId, true); - return true; - } - - const folderMatches = matchesRankQuery([entry.folder.name], normalizedSessionSearchQuery); - if (folderMatches || entry.nodes.length > 0) { - keepByFolderId.set(folderId, true); - return true; - } - - const hasMatchingChildren = childFolderIds.some((childId) => shouldKeepFolder(childId)); - keepByFolderId.set(folderId, hasMatchingChildren); - return hasMatchingChildren; - }; - - return allFoldersForGroupBase.filter(({ folder }) => shouldKeepFolder(folder.id)); + const visibleFolderIds = selectFolderIdsForProjection( + allFoldersForGroupBase.map(({ folder, nodes }) => ({ + id: folder.id, + name: folder.name, + parentId: folder.parentId, + nodeCount: nodes.length, + })), + { + archivedBucket: group.isArchivedBucket === true, + searchQuery: hasSessionSearchQuery ? normalizedSessionSearchQuery : '', + }, + ); + return allFoldersForGroupBase.filter(({ folder }) => visibleFolderIds.has(folder.id)); }, [allFoldersForGroupBase, group.isArchivedBucket, hasSessionSearchQuery, normalizedSessionSearchQuery]); + const groupSessionIds = React.useMemo(() => { + const ids = new Set(); + const visit = (nodes: SessionNode[]) => nodes.forEach((node) => { + ids.add(node.session.id); + visit(node.children); + }); + visit(sourceGroupNodes); + return ids; + }, [sourceGroupNodes]); + const groupExpansionKeys = React.useMemo(() => new Set( + [...groupSessionIds].map((id) => `project:${group.isArchivedBucket ? 'archived' : 'active'}:${id}`), + ), [group.isArchivedBucket, groupSessionIds]); + const effectiveEditingId = editingId; + const effectiveOpenMenuKey = openSidebarMenuKey; + const effectiveExpandedParents = expandedParents; + const sessionIdsInFolders = React.useMemo(() => new Set(allFoldersForGroup.flatMap((f) => f.folder.sessionIds)), [allFoldersForGroup]); const ungroupedSessions = React.useMemo(() => sourceGroupNodes.filter((node) => !sessionIdsInFolders.has(node.session.id)), [sourceGroupNodes, sessionIdsInFolders]); - const rootFolders = React.useMemo(() => allFoldersForGroup.filter(({ folder }) => !folder.parentId), [allFoldersForGroup]); + const rootFolders = React.useMemo(() => { + const entryById = new Map(allFoldersForGroup.map((entry) => [entry.folder.id, entry])); + return normalizeFolderRoots(allFoldersForGroup.map((entry) => entry.folder)) + .map((folder) => entryById.get(folder.id)) + .filter((entry): entry is (typeof allFoldersForGroup)[number] => Boolean(entry)); + }, [allFoldersForGroup]); const childFoldersByParentId = React.useMemo(() => { const map = new Map(); allFoldersForGroup.forEach((entry) => { @@ -507,30 +479,25 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { }); return map; }, [allFoldersForGroup]); - const folderActivityStateById = React.useMemo(() => { + const activityNodesByFolderId = React.useMemo(() => { const foldersById = new Map(allFoldersForGroup.map((entry) => [entry.folder.id, entry] as const)); - const result = new Map(); - const visit = (folderId: string, seen: Set): CollapsedActivityState => { + const result = new Map(); + const visit = (folderId: string, seen: Set): SessionNode[] => { const cached = result.get(folderId); if (cached !== undefined) return cached; - if (seen.has(folderId)) return null; + if (seen.has(folderId)) return []; seen.add(folderId); - const entry = foldersById.get(folderId); - let state = entry - ? getSessionNodesActivityState(entry.nodes, activeActivitySessionIds, unreadActivitySessionIds, notifyOnSubtasks) - : null; + const nodes = entry ? [...entry.nodes] : []; for (const child of childFoldersByParentId.get(folderId) ?? []) { - state = mergeCollapsedActivityStates(state, visit(child.folder.id, seen)); - if (state === 'active') break; + nodes.push(...visit(child.folder.id, seen)); } - result.set(folderId, state); - return state; + result.set(folderId, nodes); + return nodes; }; - allFoldersForGroup.forEach(({ folder }) => visit(folder.id, new Set())); return result; - }, [activeActivitySessionIds, allFoldersForGroup, childFoldersByParentId, notifyOnSubtasks, unreadActivitySessionIds]); + }, [allFoldersForGroup, childFoldersByParentId]); // Precompute the per-row "subtree contains editing session" lookup once per // render. The previous design walked the @@ -540,23 +507,23 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { const renderContextForGroup = 'project' as const; const subtreeContainsEditing = React.useMemo(() => { const set = new Set(); - collectSubtreeContainingId(sourceGroupNodes, editingId, set); + collectSubtreeContainingId(sourceGroupNodes, effectiveEditingId, set); allFoldersForGroup.forEach(({ nodes }) => { - collectSubtreeContainingId(nodes, editingId, set); + collectSubtreeContainingId(nodes, effectiveEditingId, set); }); return set; - }, [sourceGroupNodes, allFoldersForGroup, editingId]); + }, [sourceGroupNodes, allFoldersForGroup, effectiveEditingId]); const menuOpenSessionId = React.useMemo(() => { - if (!openSidebarMenuKey) return null; - const fromSource = resolveMenuOpenSessionId(sourceGroupNodes, openSidebarMenuKey, renderContextForGroup, Boolean(group.isArchivedBucket)); + if (!effectiveOpenMenuKey) return null; + const fromSource = resolveMenuOpenSessionId(sourceGroupNodes, effectiveOpenMenuKey, renderContextForGroup, Boolean(group.isArchivedBucket)); if (fromSource) return fromSource; for (const { nodes } of allFoldersForGroup) { - const id = resolveMenuOpenSessionId(nodes, openSidebarMenuKey, renderContextForGroup, Boolean(group.isArchivedBucket)); + const id = resolveMenuOpenSessionId(nodes, effectiveOpenMenuKey, renderContextForGroup, Boolean(group.isArchivedBucket)); if (id) return id; } return null; - }, [openSidebarMenuKey, sourceGroupNodes, allFoldersForGroup, group.isArchivedBucket]); + }, [effectiveOpenMenuKey, sourceGroupNodes, allFoldersForGroup, group.isArchivedBucket]); const buildNodeStructureKeyByNode = React.useCallback((nodes: SessionNode[]): WeakMap => { const map = new WeakMap(); @@ -620,7 +587,7 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { const hasExpandedParent = shouldVirtualize && visibleSessions.some((node) => { if (node.children.length === 0) return false; const expansionKey = `project:${bucketTag}:${node.session.id}`; - return expandedParents.has(expansionKey); + return effectiveExpandedParents.has(expansionKey); }); const archivedVirtualContainerRef = React.useRef(null); @@ -649,7 +616,7 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { if (!shouldVirtualize) return; const container = archivedVirtualContainerRef.current; if (!container) return; - if (typeof ResizeObserver === 'undefined') return; + if (!globalThis.ResizeObserver) return; const ro = new ResizeObserver(() => setLayoutVersion((v) => v + 1)); ro.observe(container); return () => ro.disconnect(); @@ -785,28 +752,23 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { } const showBranchSubtitle = !group.isMain && Boolean(group.branch); + // SAFETY: null is the intentional no-color branch for a status line. const statusLine = group.branch && isBranchDifferentFromLabel(group.branch, group.label) ? { label: group.branch, color: null as string | null } : null; - const groupActivityState = isCollapsed - ? getSessionNodesActivityState(sourceGroupNodes, activeActivitySessionIds, unreadActivitySessionIds, notifyOnSubtasks) + const groupActivityIndicator = isCollapsed + ? : null; - const groupActivityIndicator = groupActivityState ? ( - - ) : null; type FolderEntry = (typeof allFoldersForGroup)[number]; const renderOneFolderItem = (entry: FolderEntry, displayName: string): React.ReactNode => { const { folder, scopeKey, scopeDirectory, nodes } = entry; const folderSessionsForDelete = folderSessionsForDeleteById.get(folder.id) ?? []; + const isRenamingFolder = folderRename?.folderId === folder.id && folderRename?.scopeKey === scopeKey; const isFolderCollapsed = hasSessionSearchQuery ? false : collapsedFolderIds.has(folder.id); - return ( + const item = (collapsedActivityState: ReturnType) => ( {(droppableRef, isDropTarget) => ( toggleFolderCollapse(folder.id)} onRename={(name) => { renameFolder(scopeKey, folder.id, name); @@ -843,34 +805,21 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { sessionCount, }); }} - renderSessionNode={renderSessionNode} - getRenderExtras={resolveNodeStructureKey - ? (node) => ({ - subtreeContainsEditing, - menuOpenSessionId, - nodeStructureKey: resolveNodeStructureKey(node), - childRenderExtrasFor, - }) - : undefined} groupDirectory={scopeDirectory ?? group.directory} projectId={projectId} mobileVariant={mobileVariant} alwaysShowActions={alwaysShowActions} - isRenaming={renamingFolderId === folder.id} - renameDraft={renamingFolderId === folder.id ? renameFolderDraft : undefined} - onRenameDraftChange={(value) => setRenameFolderDraft(value)} + isRenaming={isRenamingFolder} + renameDraft={isRenamingFolder ? folderRename?.draft : undefined} + onRenameDraftChange={setFolderRenameDraft} onRenameSave={() => { - const trimmed = renameFolderDraft.trim(); + const trimmed = folderRename?.draft.trim() ?? ''; if (trimmed) { renameFolder(scopeKey, folder.id, trimmed); } - setRenamingFolderId(null); - setRenameFolderDraft(''); - }} - onRenameCancel={() => { - setRenamingFolderId(null); - setRenameFolderDraft(''); + clearFolderRename(); }} + onRenameCancel={clearFolderRename} droppableRef={droppableRef} isDropTarget={isDropTarget} depth={0} @@ -886,10 +835,50 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { }} hideActions={false} archivedBucket={group.isArchivedBucket === true} - /> + > + {nodes.map((node) => )} + )} ); + if (!isFolderCollapsed) return item(null); + return {item}; }; // Folders render flat: nested folders keep their data-model parent link but @@ -905,7 +894,10 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { else childEntriesByParentId.set(parentId, [entry]); } const out: React.ReactNode[] = []; + const visited = new Set(); const visit = (entry: FolderEntry, parentPath: string) => { + if (visited.has(entry.folder.id)) return; + visited.add(entry.folder.id); const displayName = parentPath ? `${parentPath} / ${entry.folder.name}` : entry.folder.name; out.push(renderOneFolderItem(entry, displayName)); const isFolderCollapsed = !hasSessionSearchQuery && collapsedFolderIds.has(entry.folder.id); @@ -951,6 +943,40 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { ) : null; + const renderSessionNode = (node: SessionNode): React.ReactNode => ; + const body = ( renderSessionNode(node, 0, group.directory, projectId, group.isArchivedBucket === true, undefined, 'project', { - subtreeContainsEditing, - menuOpenSessionId, - nodeStructureKey: resolveNodeStructureKey(node), - childRenderExtrasFor, - })) + visibleSessions.map(renderSessionNode) ) : (
{/* Absolutely positioned rows (canonical tanstack layout): with @@ -1017,12 +1038,7 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { transform: `translateY(${item.start - archivedScrollMargin}px)`, }} > - {renderSessionNode(node, 0, group.directory, projectId, group.isArchivedBucket === true, undefined, 'project', { - subtreeContainsEditing, - menuOpenSessionId, - nodeStructureKey: resolveNodeStructureKey(node), - childRenderExtrasFor, - })} + {renderSessionNode(node)}
); })} @@ -1030,12 +1046,7 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { )}
) : ( - visibleSessions.map((node) => renderSessionNode(node, 0, group.directory, projectId, group.isArchivedBucket === true, undefined, 'project', { - subtreeContainsEditing, - menuOpenSessionId, - nodeStructureKey: resolveNodeStructureKey(node), - childRenderExtrasFor, - })) + visibleSessions.map(renderSessionNode) )} {totalSessions === 0 && allFoldersForGroup.length === 0 ? ( // pl-[26px] lines the text up with the worktree sub-header label @@ -1086,15 +1097,24 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { void compactBodyPadding; // Folder nesting is legacy-only: existing sub-folders keep working (path // labels), but the UI no longer offers creating new ones. - void createFolderAndStartRename; const groupBodyPaddingClass = 'pb-2'; + const folderDeleteDialog = { + const value = deleteFolderConfirm; + if (!value) return; + deleteFolder(value.scopeKey, value.folderId); + setDeleteFolderConfirm(null); + }} + />; if (hideGroupLabel) { - return
{body}
; + return <>
{body}
{folderDeleteDialog}; } return ( -
+ <>
onToggleCollapsedGroup(groupKey)} @@ -1243,7 +1263,7 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { onClick={(event) => { event.stopPropagation(); if (projectId && projectId !== activeProjectId) setActiveProjectIdOnly(projectId); - if (mobileVariant) setSessionSwitcherOpen(false); + if (mobileVariant) setSessionSwitcherOpen(false); openNewSessionDraft({ selectedProjectId: projectId, directoryOverride: group.directory }); }} className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50" @@ -1258,7 +1278,7 @@ function SessionGroupSectionBase(props: Props): React.ReactNode { ) : null}
{!isCollapsed ?
{body}
: null} -
+
{folderDeleteDialog} ); } diff --git a/packages/ui/src/components/session/sidebar/projects/SessionProjectScroller.test.ts b/packages/ui/src/components/session/sidebar/projects/SessionProjectScroller.test.ts new file mode 100644 index 00000000..e7cbc684 --- /dev/null +++ b/packages/ui/src/components/session/sidebar/projects/SessionProjectScroller.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, test } from 'bun:test'; +import { buildGroupRenderDescriptors } from './sessionProjectRender'; +import type { SessionGroup } from '../types'; + +const makeGroup = (id: string, overrides: Partial = {}): SessionGroup => ({ + id, + label: id, + branch: null, + description: null, + isMain: id === 'main', + worktree: null, + directory: '/workspace', + sessions: [], + ...overrides, +}); + +describe('buildGroupRenderDescriptors', () => { + test('renders the main group and archived bucket for the main workspace', () => { + const section = { + project: { id: 'project-a', normalizedPath: '/workspace' }, + groups: [makeGroup('main'), makeGroup('archived', { isArchivedBucket: true })], + }; + + expect(buildGroupRenderDescriptors(section, { mainWorkspaceOnly: true })).toEqual([ + { + group: section.groups[0], + groupKey: 'project-a:main', + projectId: 'project-a', + hideGroupLabel: true, + }, + { + group: section.groups[1], + groupKey: 'project-a:archived', + projectId: 'project-a', + hideGroupLabel: false, + }, + ]); + }); + + test('renders the primary group without a label and nested groups with labels', () => { + const section = { + project: { id: 'project-a', normalizedPath: '/workspace' }, + groups: [makeGroup('main'), makeGroup('feature')], + }; + + expect(buildGroupRenderDescriptors(section, { mainWorkspaceOnly: false })).toEqual([ + { + group: section.groups[0], + groupKey: 'project-a:main', + projectId: 'project-a', + hideGroupLabel: true, + }, + { + group: section.groups[1], + groupKey: 'project-a:feature', + projectId: 'project-a', + hideGroupLabel: false, + }, + ]); + }); + + test('keeps labels when a flat section has no main group', () => { + const section = { + project: { id: 'project-a', normalizedPath: '/workspace' }, + groups: [makeGroup('feature', { isMain: false }), makeGroup('other', { isMain: false })], + }; + + expect(buildGroupRenderDescriptors(section, { mainWorkspaceOnly: false }).map((descriptor) => descriptor.hideGroupLabel)).toEqual([false, false]); + }); +}); diff --git a/packages/ui/src/components/session/sidebar/SidebarProjectsList.tsx b/packages/ui/src/components/session/sidebar/projects/SessionProjectScroller.tsx similarity index 52% rename from packages/ui/src/components/session/sidebar/SidebarProjectsList.tsx rename to packages/ui/src/components/session/sidebar/projects/SessionProjectScroller.tsx index 83dac8f6..0682302c 100644 --- a/packages/ui/src/components/session/sidebar/SidebarProjectsList.tsx +++ b/packages/ui/src/components/session/sidebar/projects/SessionProjectScroller.tsx @@ -11,38 +11,120 @@ import { import { SortableContext, arrayMove, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable'; import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay'; import { formatDirectoryName, formatPathForDisplay, cn } from '@/lib/utils'; -import type { SessionGroup } from './types'; -import type { SortableDragHandleProps } from './sortableItems'; +import type { SessionGroup } from '../types'; import { ProjectHeaderIdentity, SortableGroupItem, SortableProjectItem } from './sortableItems'; -import { formatProjectLabel } from './utils'; +import { SessionGroupSection, type SessionGroupSectionProps } from './SessionGroupSection'; +import { buildGroupRenderDescriptors, type ProjectSection } from './sessionProjectRender'; +import { formatProjectLabel } from '../utils'; import { useI18n } from '@/lib/i18n'; import type { ProjectSortOrder } from '@/stores/useSessionDisplayStore'; import { streamPerfCount } from '@/stores/utils/streamDebug'; import { Icon } from '@/components/icon/Icon'; -type ProjectSection = { - project: { - id: string; - label?: string; - normalizedPath: string; - icon?: string; - color?: string; - iconImage?: { mime: string; updatedAt: number; source: 'custom' | 'auto' }; - iconBackground?: string; - }; - groups: SessionGroup[]; +type SessionProjectScrollerState = Pick & { + visibleSessionCountByGroup: Map; +}; + +type SessionProjectScrollerGroupProps = Pick & { + activeProjectId: string | null; + pinnedSessionIds: Set; + sessionOrderIndex: Map; +}; + +type SessionProjectScrollerGroupActions = Pick; + +type SessionProjectScrollerModel = { + topContent?: React.ReactNode; + hasSharedSessions?: boolean; + sectionsForRender: ProjectSection[]; + projectSections: ProjectSection[]; + activeProjectId: string | null; + emptyState: React.ReactNode; + searchEmptyState: React.ReactNode; + projectRepoStatus: Map; + stuckProjectHeaders: Set; + projectHeaderSentinelRefs: React.MutableRefObject>; + state: SessionProjectScrollerState; + groupProps: SessionProjectScrollerGroupProps; +}; + +type SessionProjectScrollerView = { + homeDirectory: string | null; + collapsedProjects: Set; + showOnlyMainWorkspace: boolean; + hasSessionSearchQuery: boolean; + normalizedSessionSearchQuery: string; + hideDirectoryControls: boolean; + isDesktopShellRuntime: boolean; + stickyZoneHeaders: boolean; + mobileVariant: boolean; + alwaysShowActions: boolean; + projectSortOrder: ProjectSortOrder; +}; + +type SessionProjectScrollerActions = { + group: SessionProjectScrollerGroupActions; + toggleProject: (id: string) => void; + setActiveProjectIdOnly: (id: string) => void; + setSessionSwitcherOpen: (open: boolean) => void; + openNewSessionDraft: (options?: { selectedProjectId?: string | null; directoryOverride?: string | null }) => void; + openNewWorktreeDialog: () => void; + openWorktreesPage: (id: string) => void; + openProjectEditDialog: (id: string) => void; + removeProject: (id: string) => void; + reorderProjects: (fromIndex: number, toIndex: number) => void; + setGroupOrderByProject: React.Dispatch>>; + renderProjectStatusIndicator?: (projectId: string, groups: SessionGroup[]) => React.ReactNode; +}; + +type Props = { + model: SessionProjectScrollerModel; + view: SessionProjectScrollerView; + actions: SessionProjectScrollerActions; }; const TOP_FADE_MAX_SIZE = 48; const TOP_FADE_MIN_SIZE = 32; const TOP_FADE_CLEAR_MAX_SIZE = 24; -type ActivitySectionKey = 'chats' | 'active-now'; - -const readActivitySectionKey = (element: Element): ActivitySectionKey | null => { - const key = element.getAttribute('data-sidebar-activity-sentinel'); - if (key === 'chats' || key === 'active-now') return key; - return null; -}; const getProjectLabel = (project: ProjectSection['project'], homeDirectory: string | null): string => ( formatProjectLabel( @@ -52,62 +134,12 @@ const getProjectLabel = (project: ProjectSection['project'], homeDirectory: stri ) ); -type Props = { - topContent?: React.ReactNode; - sharedSessionsOnly?: boolean; - hasSharedSessions?: boolean; - sectionsForRender: ProjectSection[]; - projectSections: ProjectSection[]; - projectPickerSections: ProjectSection[]; - activeProjectId: string | null; - singleProjectMode: boolean; - singleProjectId: string | null; - setSingleProjectId: (id: string) => void; - showOnlyMainWorkspace: boolean; - hasSessionSearchQuery: boolean; - emptyState: React.ReactNode; - searchEmptyState: React.ReactNode; - renderGroupSessions: ( - group: SessionGroup, - groupKey: string, - projectId?: string | null, - hideGroupLabel?: boolean, - dragHandleProps?: SortableDragHandleProps | null, - compactBodyPadding?: boolean, - scrollContainerRef?: React.RefObject, - ) => React.ReactNode; - getOrderedGroups: (projectId: string, groups: SessionGroup[]) => SessionGroup[]; - setGroupOrderByProject: React.Dispatch>>; - renderProjectStatusIndicator?: (projectId: string, groups: SessionGroup[]) => React.ReactNode; - homeDirectory: string | null; - collapsedProjects: Set; - hideDirectoryControls: boolean; - projectRepoStatus: Map; - isDesktopShellRuntime: boolean; - stickyZoneHeaders: boolean; - stuckProjectHeaders: Set; - mobileVariant: boolean; - alwaysShowActions: boolean; - toggleProject: (id: string) => void; - setActiveProjectIdOnly: (id: string) => void; - setSessionSwitcherOpen: (open: boolean) => void; - openNewSessionDraft: (options?: { selectedProjectId?: string | null; directoryOverride?: string | null }) => void; - openNewWorktreeDialog: () => void; - openWorktreesPage: (id: string) => void; - openProjectEditDialog: (id: string) => void; - removeProject: (id: string) => void; - projectHeaderSentinelRefs: React.MutableRefObject>; - reorderProjects: (fromIndex: number, toIndex: number) => void; - projectSortOrder: ProjectSortOrder; - openSidebarMenuKey: string | null; - setOpenSidebarMenuKey: (key: string | null) => void; - isInlineEditing: boolean; -}; - -function SidebarProjectsListComponent(props: Props): React.ReactNode { +function SessionProjectScrollerComponent(props: Props): React.ReactNode { streamPerfCount('ui.sidebar_projects_list.render'); const { t } = useI18n(); - const enableStickyFade = props.isDesktopShellRuntime && props.stickyZoneHeaders && !props.singleProjectMode; + const { model, view, actions } = props; + const isInlineEditing = model.state.editingId !== null; + const enableStickyFade = view.isDesktopShellRuntime && view.stickyZoneHeaders; const projectSensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 8 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), @@ -115,51 +147,11 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { const groupSensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 8 } }), ); - const selectedSingleProjectSection = props.singleProjectMode - ? props.sectionsForRender.find((section) => section.project.id === props.singleProjectId) - : null; - const renderedProjectSections = props.singleProjectMode - ? (selectedSingleProjectSection ? [selectedSingleProjectSection] : []) - : props.sectionsForRender; - const projectPickerOptions = React.useMemo(() => props.projectPickerSections.map((section) => ({ - id: section.project.id, - projectLabel: getProjectLabel(section.project, props.homeDirectory), - projectDescription: formatPathForDisplay(section.project.normalizedPath, props.homeDirectory), - projectIcon: section.project.icon, - projectColor: section.project.color, - projectIconImage: section.project.iconImage, - projectIconBackground: section.project.iconBackground, - })), [props.homeDirectory, props.projectPickerSections]); - - // Memoize getOrderedGroups per project so downstream consumers see a stable - // array reference while inputs are unchanged (avoids O(P) fresh arrays per - // list render invalidating the memoized group subtrees). - const orderedGroupsCacheRef = React.useRef>(new Map()); - const orderedGroupsCacheGetOrderedGroupsRef = React.useRef(props.getOrderedGroups); - if (orderedGroupsCacheGetOrderedGroupsRef.current !== props.getOrderedGroups) { - orderedGroupsCacheGetOrderedGroupsRef.current = props.getOrderedGroups; - orderedGroupsCacheRef.current.clear(); - } - const cachedGetOrderedGroups = (projectId: string, groups: SessionGroup[]): SessionGroup[] => { - const cache = orderedGroupsCacheRef.current; - const hit = cache.get(projectId); - if (hit && hit.groups === groups) { - return hit.ordered; - } - const ordered = props.getOrderedGroups(projectId, groups); - cache.set(projectId, { groups, ordered }); - if (cache.size > 256) { - const firstKey = cache.keys().next().value; - if (firstKey !== undefined) cache.delete(firstKey); - } - return ordered; - }; // Threaded into SessionGroupSection so the archived-bucket virtualizer // can resolve the scrolling ancestor synchronously (no getComputedStyle // walk) and skip the cost of a style recalc on every render. const scrollContainerRef = React.useRef(null); - const [leadingActivitySection, setLeadingActivitySection] = React.useState('chats'); // Keep per-scroll measurements out of React state so the interaction guard // can read the current fade boundary without rerendering the sidebar. const topFadeSizeRef = React.useRef(0); @@ -180,53 +172,22 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { const blockObscuredInteraction = React.useCallback(( event: React.MouseEvent | React.PointerEvent, ) => { + // SAFETY: React's mouse and pointer events are dispatched from Elements. if ((event.target as Element).closest('[data-overlay-scrollbar-thumb], [data-sidebar-sticky-header]')) return; const eventY = event.clientY - event.currentTarget.getBoundingClientRect().top; if (eventY >= topFadeSizeRef.current) return; event.preventDefault(); event.stopPropagation(); }, []); - const hasProjectScroller = props.projectSections.length > 0 && renderedProjectSections.length > 0; + const hasProjectScroller = model.projectSections.length > 0 && model.sectionsForRender.length > 0; React.useLayoutEffect(() => { if (enableStickyFade && hasProjectScroller && scrollContainerRef.current) { syncTopFade(scrollContainerRef.current); } }, [enableStickyFade, hasProjectScroller, syncTopFade]); - React.useEffect(() => { - const root = scrollContainerRef.current; - if (!enableStickyFade || !root || !props.hasSharedSessions) return; - - const sentinels = Array.from(root.querySelectorAll('[data-sidebar-activity-sentinel]')); - if (sentinels.length === 0) return; - const stuckSections = new Set(); - const syncLeadingSection = (): void => { - let nextSection = sentinels[0] ? readActivitySectionKey(sentinels[0]) : null; - for (const sentinel of sentinels) { - const key = readActivitySectionKey(sentinel); - if (key && stuckSections.has(key)) nextSection = key; - } - if (nextSection) setLeadingActivitySection((current) => current === nextSection ? current : nextSection); - }; - const observer = new IntersectionObserver((entries) => { - const rootTop = root.getBoundingClientRect().top; - for (const entry of entries) { - const key = readActivitySectionKey(entry.target); - if (!key) continue; - if (!entry.isIntersecting && entry.boundingClientRect.top < (entry.rootBounds?.top ?? rootTop)) { - stuckSections.add(key); - } else { - stuckSections.delete(key); - } - } - syncLeadingSection(); - }, { root, threshold: 0 }); - sentinels.forEach((sentinel) => observer.observe(sentinel)); - syncLeadingSection(); - return () => observer.disconnect(); - }, [enableStickyFade, props.hasSharedSessions, props.topContent]); let stuckProject: ProjectSection['project'] | null = null; - for (const section of props.projectSections) { - if (props.stuckProjectHeaders.has(section.project.id)) { + for (const section of model.projectSections) { + if (model.stuckProjectHeaders.has(section.project.id)) { stuckProject = section.project; } } @@ -237,24 +198,15 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { // ready in the same frame; the observer then corrects it. When shared sessions // lead the list, the Recent fallback below owns the top instead of a project. const leadingProject = - stuckProject ?? (props.hasSharedSessions ? null : renderedProjectSections[0]?.project ?? null); - const leadingProjectLabel = leadingProject ? getProjectLabel(leadingProject, props.homeDirectory) : null; + stuckProject ?? (model.hasSharedSessions ? null : model.sectionsForRender[0]?.project ?? null); + const leadingProjectLabel = leadingProject ? getProjectLabel(leadingProject, view.homeDirectory) : null; - if (props.sharedSessionsOnly) { - return ( - - {props.topContent} - {!props.hasSharedSessions ? (props.hasSessionSearchQuery ? props.searchEmptyState : props.emptyState) : null} - - ); + if (model.projectSections.length === 0) { + return {model.topContent}{model.emptyState}; } - if (props.projectSections.length === 0) { - return {props.topContent}{props.emptyState}; - } - - if (props.sectionsForRender.length === 0) { - return {props.searchEmptyState}; + if (model.sectionsForRender.length === 0) { + return {model.searchEmptyState}; } return ( @@ -275,38 +227,27 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { hideTopScrollShadow={!enableStickyFade} scrollShadowSize={96} outerClassName="flex-1 min-h-0" - className={cn('oc-sidebar-scroller oc-sticky-fade-scroller space-y-1.5 pb-1 pl-2.5 pr-2 [overflow-anchor:none]', props.mobileVariant ? '' : '')} + className={cn('oc-sidebar-scroller oc-sticky-fade-scroller space-y-1.5 pb-1 pl-2.5 pr-2 [overflow-anchor:none]', view.mobileVariant ? '' : '')} + // SAFETY: the custom property is the only dynamic CSS declaration here. style={enableStickyFade ? { '--scroll-shadow-top-size': '0px' } as React.CSSProperties : undefined} onScroll={enableStickyFade ? (event) => syncTopFade(event.currentTarget) : undefined} > - {props.topContent} - {props.showOnlyMainWorkspace ? ( + {model.topContent} + {view.showOnlyMainWorkspace ? (
{(() => { - const activeSection = props.sectionsForRender.find((section) => section.project.id === props.activeProjectId) ?? props.sectionsForRender[0]; + const activeSection = model.sectionsForRender.find((section) => section.project.id === model.activeProjectId) ?? model.sectionsForRender[0]; if (!activeSection) { - return props.hasSessionSearchQuery ? props.searchEmptyState : props.emptyState; + return view.hasSessionSearchQuery ? model.searchEmptyState : model.emptyState; } - const primaryGroup = - activeSection.groups.find((candidate) => candidate.isMain && candidate.sessions.length > 0) - ?? activeSection.groups.find((candidate) => candidate.sessions.length > 0) - ?? activeSection.groups.find((candidate) => candidate.isMain) - ?? activeSection.groups[0]; - if (!primaryGroup) { + const descriptors = buildGroupRenderDescriptors(activeSection, { mainWorkspaceOnly: true }); + if (!descriptors.length) { return
{t('sessions.sidebar.empty.noSessions.title')}
; } - const archivedGroup = activeSection.groups.find((candidate) => candidate.isArchivedBucket); - const groupsToRender = [ - primaryGroup, - ...(archivedGroup && archivedGroup.id !== primaryGroup.id ? [archivedGroup] : []), - ]; - - return groupsToRender.map((group) => { - const groupKey = `${activeSection.project.id}:${group.id}`; - const hideGroupLabel = group.id === primaryGroup.id; + return descriptors.map(({ group, groupKey, projectId, hideGroupLabel }) => { return ( - {props.renderGroupSessions(group, groupKey, activeSection.project.id, hideGroupLabel, null, true, scrollContainerRef)} + ); }); @@ -317,31 +258,31 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { sensors={projectSensors} collisionDetection={closestCenter} onDragEnd={(event) => { - if (props.isInlineEditing) return; + if (isInlineEditing) return; // Drag only allowed in manual sort mode - indices from visual order don't match store order in other modes - if (props.projectSortOrder !== 'manual') return; + if (view.projectSortOrder !== 'manual') return; const { active, over } = event; if (!over || active.id === over.id) return; - const oldIndex = props.sectionsForRender.findIndex((section) => section.project.id === active.id); - const newIndex = props.sectionsForRender.findIndex((section) => section.project.id === over.id); + const oldIndex = model.sectionsForRender.findIndex((section) => section.project.id === active.id); + const newIndex = model.sectionsForRender.findIndex((section) => section.project.id === over.id); if (oldIndex === -1 || newIndex === -1 || oldIndex === newIndex) return; - props.reorderProjects(oldIndex, newIndex); + actions.reorderProjects(oldIndex, newIndex); }} > - section.project.id)} strategy={verticalListSortingStrategy}> - {renderedProjectSections.map((section) => { + section.project.id)} strategy={verticalListSortingStrategy}> + {model.sectionsForRender.map((section) => { const project = section.project; const projectKey = project.id; - const projectLabel = getProjectLabel(project, props.homeDirectory); - const projectDescription = formatPathForDisplay(project.normalizedPath, props.homeDirectory); - const isCollapsed = props.singleProjectMode ? false : props.collapsedProjects.has(projectKey); - const isRepo = props.projectRepoStatus.get(projectKey); + const projectLabel = getProjectLabel(project, view.homeDirectory); + const projectDescription = formatPathForDisplay(project.normalizedPath, view.homeDirectory); + const isCollapsed = view.collapsedProjects.has(projectKey); + const isRepo = model.projectRepoStatus.get(projectKey); return ( { - if (!props.singleProjectMode) props.toggleProject(projectKey); - }} + isDesktopShell={view.isDesktopShellRuntime} + hideDirectoryControls={view.hideDirectoryControls} + mobileVariant={view.mobileVariant} + alwaysShowActions={view.alwaysShowActions} + statusIndicator={isCollapsed ? actions.renderProjectStatusIndicator?.(projectKey, section.groups) : null} + openSidebarMenuKey={model.state.openSidebarMenuKey} + setOpenSidebarMenuKey={model.state.setOpenSidebarMenuKey} + onToggle={() => actions.toggleProject(projectKey)} onNewSession={() => { - if (projectKey !== props.activeProjectId) props.setActiveProjectIdOnly(projectKey); - if (props.mobileVariant) props.setSessionSwitcherOpen(false); - props.openNewSessionDraft({ + if (projectKey !== model.activeProjectId) actions.setActiveProjectIdOnly(projectKey); + if (view.mobileVariant) actions.setSessionSwitcherOpen(false); + actions.openNewSessionDraft({ selectedProjectId: projectKey, directoryOverride: project.normalizedPath, }); }} onNewWorktreeSession={() => { - if (projectKey !== props.activeProjectId) props.setActiveProjectIdOnly(projectKey); - props.openNewWorktreeDialog(); + if (projectKey !== model.activeProjectId) actions.setActiveProjectIdOnly(projectKey); + actions.openNewWorktreeDialog(); }} - onManageWorktrees={() => props.openWorktreesPage(projectKey)} - onRenameStart={() => props.openProjectEditDialog(projectKey)} - onClose={() => props.removeProject(projectKey)} - sentinelRef={(el) => { props.projectHeaderSentinelRefs.current.set(projectKey, el); }} + onManageWorktrees={() => actions.openWorktreesPage(projectKey)} + onRenameStart={() => actions.openProjectEditDialog(projectKey)} + onClose={() => actions.removeProject(projectKey)} + sentinelRef={(el) => { model.projectHeaderSentinelRefs.current.set(projectKey, el); }} showCreateButtons - openSidebarMenuKey={props.openSidebarMenuKey} - setOpenSidebarMenuKey={props.setOpenSidebarMenuKey} - projectPickerOptions={props.singleProjectMode ? projectPickerOptions : undefined} - onProjectSelect={props.singleProjectMode ? props.setSingleProjectId : undefined} - > + > {!isCollapsed ? (
{(() => { - const orderedGroups = cachedGetOrderedGroups(projectKey, section.groups); + const orderedGroups = section.groups; const rootGroup = orderedGroups.find((group) => group.isMain) ?? null; const nestedGroups = rootGroup ? orderedGroups.filter((group) => group.id !== rootGroup.id) @@ -393,7 +330,7 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { sensors={groupSensors} collisionDetection={closestCenter} onDragEnd={(event) => { - if (props.isInlineEditing) return; + if (isInlineEditing) return; const { active, over } = event; if (!over || active.id === over.id) return; const oldIndex = nestedGroups.findIndex((item) => item.id === active.id); @@ -401,7 +338,7 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { if (oldIndex === -1 || newIndex === -1 || oldIndex === newIndex) return; const nextNested = arrayMove(nestedGroups, oldIndex, newIndex).map((item) => item.id); const next = rootGroup ? [rootGroup.id, ...nextNested] : nextNested; - props.setGroupOrderByProject((prev) => { + actions.setGroupOrderByProject((prev) => { const map = new Map(prev); map.set(projectKey, next); return map; @@ -411,13 +348,13 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { {/* Root/flat sessions render directly under the project zone header; worktree and archived groups keep their own slim sortable sub-header. */} - {rootGroup ? props.renderGroupSessions(rootGroup, `${projectKey}:${rootGroup.id}`, projectKey, true, null, undefined, scrollContainerRef) : null} + {rootGroup ? : null} group.id)} strategy={verticalListSortingStrategy}> {nestedGroups.map((group) => { const groupKey = `${projectKey}:${group.id}`; return ( - - {(dragHandleProps) => props.renderGroupSessions(group, groupKey, projectKey, false, dragHandleProps, undefined, scrollContainerRef)} + + {(dragHandleProps) => } ); })} @@ -436,14 +373,14 @@ function SidebarProjectsListComponent(props: Props): React.ReactNode { )} - {enableStickyFade && (leadingProject || props.hasSharedSessions) ? ( + {enableStickyFade && (leadingProject || model.hasSharedSessions) ? (