perf(ui): streamline session sidebar state

This commit is contained in:
c_w_xiaohei
2026-08-26 00:42:36 +08:00
parent 3b7d5e1c34
commit 26dbc2f309
84 changed files with 5159 additions and 2809 deletions
@@ -0,0 +1,227 @@
import React from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Icon } from "@/components/icon/Icon";
import type { Session } from '@opencode-ai/sdk/v2';
import { useI18n } from '@/lib/i18n';
export type DeleteSessionConfirmState = {
session: Session;
descendantCount: number;
// Snapshot of the descendant IDs computed when the dialog opened, so the
// executed list matches the count shown to the user even if childrenMap
// changes while the dialog is open.
descendantIds: string[];
archivedBucket: boolean;
} | null;
export function SessionDeleteConfirmDialog(props: {
value: DeleteSessionConfirmState;
setValue: (next: DeleteSessionConfirmState) => void;
showDeletionDialog: boolean;
setShowDeletionDialog: (next: boolean) => void;
onConfirm: () => Promise<void> | void;
}): React.ReactNode {
const { t } = useI18n();
const { value, setValue, showDeletionDialog, setShowDeletionDialog, onConfirm } = props;
const untitledSession = t('sessions.sidebar.session.untitled');
return (
<Dialog open={Boolean(value)} onOpenChange={(open) => { if (!open) setValue(null); }}>
<DialogContent showCloseButton={false} className="max-w-sm gap-5">
<DialogHeader>
<DialogTitle>{value?.archivedBucket
? t('sessions.sidebar.dialogs.deleteSession.title')
: t('sessions.sidebar.dialogs.archiveSession.title')}</DialogTitle>
<DialogDescription>
{value && value.descendantCount > 0
? value.archivedBucket
? value.descendantCount === 1
? t('sessions.sidebar.dialogs.deleteSession.withOneSubtask', {
sessionTitle: value.session.title || untitledSession,
count: value.descendantCount,
})
: t('sessions.sidebar.dialogs.deleteSession.withManySubtasks', {
sessionTitle: value.session.title || untitledSession,
count: value.descendantCount,
})
: value.descendantCount === 1
? t('sessions.sidebar.dialogs.archiveSession.withOneSubtask', {
sessionTitle: value.session.title || untitledSession,
count: value.descendantCount,
})
: t('sessions.sidebar.dialogs.archiveSession.withManySubtasks', {
sessionTitle: value.session.title || untitledSession,
count: value.descendantCount,
})
: value?.archivedBucket
? t('sessions.sidebar.dialogs.deleteSession.single', {
sessionTitle: value?.session.title || untitledSession,
})
: t('sessions.sidebar.dialogs.archiveSession.single', {
sessionTitle: value?.session.title || untitledSession,
})}
</DialogDescription>
</DialogHeader>
<DialogFooter className="w-full sm:items-center sm:justify-between">
<button
type="button"
onClick={() => setShowDeletionDialog(!showDeletionDialog)}
className="inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50"
aria-pressed={!showDeletionDialog}
>
{!showDeletionDialog ? <Icon name="checkbox" className="h-4 w-4 text-primary" /> : <Icon name="checkbox-blank" className="h-4 w-4" />}
{t('sessions.sidebar.dialogs.neverAsk')}
</button>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setValue(null)}
className="inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
>
{t('sessions.sidebar.dialogs.cancel')}
</button>
<button
type="button"
onClick={() => void onConfirm()}
className="inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"
>
{value?.archivedBucket ? t('sessions.sidebar.bulkActions.delete') : t('sessions.sidebar.bulkActions.archive')}
</button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export type BulkDeleteSessionsConfirmState = {
sessionCount: number;
archivedBucket: boolean;
} | null;
export function BulkSessionDeleteConfirmDialog(props: {
value: BulkDeleteSessionsConfirmState;
setValue: (next: BulkDeleteSessionsConfirmState) => void;
showDeletionDialog: boolean;
setShowDeletionDialog: (next: boolean) => void;
onConfirm: () => Promise<void> | void;
}): React.ReactNode {
const { t } = useI18n();
const { value, setValue, showDeletionDialog, setShowDeletionDialog, onConfirm } = props;
const archived = value?.archivedBucket === true;
const n = value?.sessionCount ?? 0;
const title = archived
? (n === 1
? t('sessions.sidebar.dialogs.deleteSession.title')
: t('sessions.sidebar.dialogs.deleteSessions.title'))
: (n === 1
? t('sessions.sidebar.dialogs.archiveSession.title')
: t('sessions.sidebar.dialogs.archiveSessions.title'));
const description = archived
? (n === 1
? t('sessions.sidebar.dialogs.deleteSessions.singleDescription', { count: n })
: t('sessions.sidebar.dialogs.deleteSessions.pluralDescription', { count: n }))
: (n === 1
? t('sessions.sidebar.dialogs.archiveSessions.singleDescription', { count: n })
: t('sessions.sidebar.dialogs.archiveSessions.pluralDescription', { count: n }));
return (
<Dialog open={Boolean(value)} onOpenChange={(open) => { if (!open) setValue(null); }}>
<DialogContent showCloseButton={false} className="max-w-sm gap-5">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter className="w-full sm:items-center sm:justify-between">
<button
type="button"
onClick={() => setShowDeletionDialog(!showDeletionDialog)}
className="inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50"
aria-pressed={!showDeletionDialog}
>
{!showDeletionDialog ? <Icon name="checkbox" className="h-4 w-4 text-primary" /> : <Icon name="checkbox-blank" className="h-4 w-4" />}
{t('sessions.sidebar.dialogs.neverAsk')}
</button>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setValue(null)}
className="inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
>
{t('sessions.sidebar.dialogs.cancel')}
</button>
<button
type="button"
onClick={() => void onConfirm()}
className="inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"
>
{archived ? t('sessions.sidebar.bulkActions.delete') : t('sessions.sidebar.bulkActions.archive')}
</button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export type DeleteFolderConfirmState = {
scopeKey: string;
folderId: string;
folderName: string;
subFolderCount: number;
sessionCount: number;
} | null;
export function FolderDeleteConfirmDialog(props: {
value: DeleteFolderConfirmState;
setValue: (next: DeleteFolderConfirmState) => void;
onConfirm: () => void;
}): React.ReactNode {
const { t } = useI18n();
const { value, setValue, onConfirm } = props;
return (
<Dialog open={Boolean(value)} onOpenChange={(open) => { if (!open) setValue(null); }}>
<DialogContent showCloseButton={false} className="max-w-sm gap-5">
<DialogHeader>
<DialogTitle>{t('sessions.sidebar.dialogs.deleteFolder.title')}</DialogTitle>
<DialogDescription>
{value && (value.subFolderCount > 0 || value.sessionCount > 0)
? value.subFolderCount > 0
? value.subFolderCount === 1
? t('sessions.sidebar.dialogs.deleteFolder.withOneSubfolder', {
folderName: value.folderName,
count: value.subFolderCount,
})
: t('sessions.sidebar.dialogs.deleteFolder.withManySubfolders', {
folderName: value.folderName,
count: value.subFolderCount,
})
: t('sessions.sidebar.dialogs.deleteFolder.withContentsNoSubfolders', {
folderName: value.folderName,
})
: t('sessions.sidebar.dialogs.deleteFolder.single', {
folderName: value?.folderName ?? '',
})}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<button
type="button"
onClick={() => setValue(null)}
className="inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
>
{t('sessions.sidebar.dialogs.cancel')}
</button>
<button
type="button"
onClick={onConfirm}
className="inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"
>
{t('sessions.sidebar.bulkActions.delete')}
</button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,75 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Icon } from "@/components/icon/Icon";
import { useI18n } from '@/lib/i18n';
type Props = {
onOpenSettings: () => void;
onOpenShortcuts: () => void;
onOpenAbout: () => void;
onOpenUpdate: () => void;
showRuntimeButtons?: boolean;
showUpdateButton?: boolean;
};
const footerButtonClassName = 'inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50';
export function SidebarFooter({
onOpenSettings,
onOpenShortcuts,
onOpenAbout,
onOpenUpdate,
showRuntimeButtons = true,
showUpdateButton = true,
}: Props): React.ReactNode {
const { t } = useI18n();
if (!showRuntimeButtons && !showUpdateButton) {
return null;
}
return (
<div className="flex shrink-0 items-center justify-start gap-1 px-2.5 py-2">
{showRuntimeButtons ? (
<>
<Tooltip>
<TooltipTrigger asChild>
<button type="button" onClick={onOpenSettings} className={footerButtonClassName} aria-label={t('sessions.sidebar.footer.actions.settings')}>
<Icon name="settings-3" className="h-4.5 w-4.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}><p>{t('sessions.sidebar.footer.actions.settings')}</p></TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button type="button" onClick={onOpenShortcuts} className={footerButtonClassName} aria-label={t('sessions.sidebar.footer.actions.shortcuts')}>
<Icon name="command" className="h-4.5 w-4.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}><p>{t('sessions.sidebar.footer.actions.shortcuts')}</p></TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button type="button" onClick={onOpenAbout} className={footerButtonClassName} aria-label={t('sessions.sidebar.footer.actions.aboutOpenChamber')}>
<Icon name="information" className="h-4.5 w-4.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}><p>{t('sessions.sidebar.footer.actions.aboutOpenChamber')}</p></TooltipContent>
</Tooltip>
</>
) : null}
{showUpdateButton ? (
<Button
type="button"
variant="default"
size="xs"
className="ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80"
onClick={onOpenUpdate}
>
{t('sessions.sidebar.footer.actions.update')}
</Button>
) : null}
</div>
);
}
@@ -0,0 +1,347 @@
import React from 'react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import { Icon } from "@/components/icon/Icon";
import { ArrowsMerge } from '@/components/icons/ArrowsMerge';
import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore';
import { useSessionMultiSelectStore } from '@/stores/useSessionMultiSelectStore';
import { useI18n } from '@/lib/i18n';
import { updateDesktopSettings } from '@/lib/persistence';
type Props = {
hideDirectoryControls: boolean;
showProjectDisplayControls: boolean;
showRecentControls: boolean;
handleOpenDirectoryDialog: () => void;
onOpenScheduled: () => void;
onOpenMultiRun: () => void;
canOpenMultiRun: boolean;
onOpenArchive: () => void;
headerActionIconClass: string;
headerActionButtonClass: string;
isSessionSearchOpen: boolean;
setIsSessionSearchOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
sessionSearchInputRef: React.RefObject<HTMLInputElement | null>;
sessionSearchQuery: string;
setSessionSearchQuery: (value: string) => void;
hasSessionSearchQuery: boolean;
searchMatchCount: number;
collapseAllProjects: () => void;
expandAllProjects: () => void;
};
export function SidebarHeader(props: Props): React.ReactNode {
const { t } = useI18n();
const {
hideDirectoryControls,
showProjectDisplayControls,
showRecentControls,
handleOpenDirectoryDialog,
onOpenScheduled,
onOpenMultiRun,
canOpenMultiRun,
onOpenArchive,
headerActionIconClass,
headerActionButtonClass,
isSessionSearchOpen,
setIsSessionSearchOpen,
sessionSearchInputRef,
sessionSearchQuery,
setSessionSearchQuery,
hasSessionSearchQuery,
searchMatchCount,
collapseAllProjects,
expandAllProjects,
} = props;
const selectionModeEnabled = useSessionMultiSelectStore((state) => state.enabled);
const toggleSelectionMode = useSessionMultiSelectStore((state) => state.toggleMode);
const showRecentSection = useSessionDisplayStore((state) => state.showRecentSection);
const toggleRecentSection = useSessionDisplayStore((state) => state.toggleRecentSection);
const projectSortOrder = useSessionDisplayStore((state) => state.projectSortOrder);
const setProjectSortOrder = useSessionDisplayStore((state) => state.setProjectSortOrder);
const sessionGroupingMode = useSessionDisplayStore((state) => state.sessionGroupingMode);
const setSessionGroupingMode = useSessionDisplayStore((state) => state.setSessionGroupingMode);
const stickyZoneHeaders = useSessionDisplayStore((state) => state.stickyZoneHeaders);
const toggleStickyZoneHeaders = useSessionDisplayStore((state) => state.toggleStickyZoneHeaders);
const projectDisplayMode = useSessionDisplayStore((state) => state.projectDisplayMode);
const setProjectDisplayMode = useSessionDisplayStore((state) => state.setProjectDisplayMode);
const isSingleProjectMode = showProjectDisplayControls && projectDisplayMode === 'single';
if (hideDirectoryControls) {
return null;
}
return (
<div className="select-none flex-shrink-0 px-2.5 py-1">
<div className="flex h-auto min-h-8 flex-col gap-1">
<div className="flex h-8 items-center justify-between gap-2">
{/* Quiet toolbar under the New-session CTA: project/surface entry
points at left, list controls at right. ml-[3px] compensates the
icon inset inside the 24px buttons so the first glyph lines up
with the New-session icon above (16px from the sidebar edge). */}
<div className="ml-[3px] flex items-center gap-1.5">
<Tooltip delayDuration={500}>
<TooltipTrigger asChild>
<button
type="button"
onClick={handleOpenDirectoryDialog}
className={cn(headerActionButtonClass, 'text-muted-foreground hover:text-foreground hover:bg-transparent')}
aria-label={t('sessions.sidebar.header.actions.addProject')}
>
<Icon name="folder-add" className={headerActionIconClass} />
</button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}><p>{t('sessions.sidebar.header.actions.addProject')}</p></TooltipContent>
</Tooltip>
<Tooltip delayDuration={500}>
<TooltipTrigger asChild>
<button
type="button"
onClick={onOpenScheduled}
className={cn(headerActionButtonClass, 'text-muted-foreground hover:text-foreground hover:bg-transparent')}
aria-label={t('sessions.sidebar.header.actions.scheduledTasks')}
>
<Icon name="calendar-schedule" className={headerActionIconClass} />
</button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}><p>{t('sessions.sidebar.header.actions.scheduledTasks')}</p></TooltipContent>
</Tooltip>
<Tooltip delayDuration={500}>
<TooltipTrigger asChild>
<button
type="button"
onClick={onOpenMultiRun}
className={cn(headerActionButtonClass, 'text-muted-foreground hover:text-foreground hover:bg-transparent')}
aria-label={t('sessions.sidebar.header.actions.newMultiRun')}
disabled={!canOpenMultiRun}
>
<ArrowsMerge className={headerActionIconClass} />
</button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}><p>{t('sessions.sidebar.header.actions.newMultiRun')}</p></TooltipContent>
</Tooltip>
<Tooltip delayDuration={500}>
<TooltipTrigger asChild>
<button
type="button"
onClick={onOpenArchive}
className={cn(headerActionButtonClass, 'text-muted-foreground hover:text-foreground hover:bg-transparent')}
aria-label={t('sessions.sidebar.nav.archive')}
>
<Icon name="archive" className={headerActionIconClass} />
</button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}><p>{t('sessions.sidebar.nav.archive')}</p></TooltipContent>
</Tooltip>
</div>
<div className="flex items-center gap-1.5">
<Tooltip delayDuration={500}>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => setIsSessionSearchOpen((prev) => !prev)}
className={cn(headerActionButtonClass, 'text-muted-foreground hover:text-foreground hover:bg-transparent')}
aria-label={t('sessions.sidebar.header.actions.searchSessions')}
aria-expanded={isSessionSearchOpen}
>
<Icon name="search" className={headerActionIconClass} />
</button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}><p>{t('sessions.sidebar.header.actions.searchSessions')}</p></TooltipContent>
</Tooltip>
<Tooltip delayDuration={500}>
<TooltipTrigger asChild>
<button
type="button"
onClick={toggleSelectionMode}
className={cn(headerActionButtonClass, 'text-muted-foreground hover:text-foreground hover:bg-transparent', selectionModeEnabled && 'bg-interactive-hover text-primary')}
aria-label={selectionModeEnabled
? t('sessions.sidebar.header.actions.exitSelection')
: t('sessions.sidebar.header.actions.selectSessions')}
aria-pressed={selectionModeEnabled}
>
<Icon name="checkbox-multiple" className={headerActionIconClass} />
</button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}>
<p>{selectionModeEnabled
? t('sessions.sidebar.header.actions.exitSelection')
: t('sessions.sidebar.header.actions.selectSessions')}</p>
</TooltipContent>
</Tooltip>
<DropdownMenu>
<Tooltip delayDuration={500}>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<button
type="button"
className={cn(headerActionButtonClass, 'text-muted-foreground hover:text-foreground hover:bg-transparent')}
aria-label={t('sessions.sidebar.header.displayMode.label')}
>
<Icon name="equalizer-2" className={headerActionIconClass} />
</button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}><p>{t('sessions.sidebar.header.displayMode.label')}</p></TooltipContent>
</Tooltip>
<DropdownMenuContent align="end" className="min-w-[180px]">
<DropdownMenuLabel>{t('sessions.sidebar.header.actions.sortProjects')}</DropdownMenuLabel>
{([
['manual', 'sessions.sidebar.header.projectSort.manual'],
['a-z', 'sessions.sidebar.header.projectSort.aToZ'],
['z-a', 'sessions.sidebar.header.projectSort.zToA'],
['date-added', 'sessions.sidebar.header.projectSort.dateAdded'],
['recent', 'sessions.sidebar.header.projectSort.recent'],
] as const).map(([order, labelKey]) => (
<DropdownMenuItem
key={order}
onClick={() => {
setProjectSortOrder(order);
void updateDesktopSettings({ sidebarProjectSortOrder: order });
}}
className="flex items-center justify-between"
>
<span>{t(labelKey)}</span>
{projectSortOrder === order ? <Icon name="check" className="h-4 w-4 text-primary" /> : null}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
{showProjectDisplayControls ? (
<>
<DropdownMenuLabel>{t('sessions.sidebar.header.projectDisplay.label')}</DropdownMenuLabel>
{([
['all', 'sessions.sidebar.header.projectDisplay.all'],
['single', 'sessions.sidebar.header.projectDisplay.single'],
] as const).map(([mode, labelKey]) => (
<DropdownMenuItem
key={mode}
onClick={() => {
setProjectDisplayMode(mode);
void updateDesktopSettings({ sidebarProjectDisplayMode: mode });
}}
className="flex items-center justify-between"
>
<span>{t(labelKey)}</span>
{projectDisplayMode === mode ? <Icon name="check" className="h-4 w-4 text-primary" /> : null}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
</>
) : null}
<DropdownMenuLabel>{t('sessions.sidebar.header.grouping.label')}</DropdownMenuLabel>
{([
['by-worktree', 'sessions.sidebar.header.grouping.byWorktree'],
['flat', 'sessions.sidebar.header.grouping.flat'],
] as const).map(([mode, labelKey]) => (
<DropdownMenuItem
key={mode}
onClick={() => {
setSessionGroupingMode(mode);
void updateDesktopSettings({ sidebarSessionGroupingMode: mode });
}}
className="flex items-center justify-between"
>
<span>{t(labelKey)}</span>
{sessionGroupingMode === mode ? <Icon name="check" className="h-4 w-4 text-primary" /> : null}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
{showRecentControls && !isSingleProjectMode ? (
<DropdownMenuItem
onClick={() => {
toggleRecentSection();
void updateDesktopSettings({ sidebarShowRecentSection: !showRecentSection });
}}
className="flex items-center justify-between"
>
<span>{t('sessions.sidebar.header.displayMode.showRecent')}</span>
{showRecentSection ? <Icon name="check" className="h-4 w-4 text-primary" /> : null}
</DropdownMenuItem>
) : null}
<DropdownMenuItem
onClick={toggleStickyZoneHeaders}
className="flex items-center justify-between"
>
<span>{t('sessions.sidebar.header.displayMode.stickyHeaders')}</span>
{stickyZoneHeaders ? <Icon name="check" className="h-4 w-4 text-primary" /> : null}
</DropdownMenuItem>
{!isSingleProjectMode ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={collapseAllProjects} className="flex items-center gap-2">
<Icon name="contract-up-down" className="h-4 w-4" />
<span>{t('sessions.sidebar.header.displayMode.collapseAll')}</span>
</DropdownMenuItem>
<DropdownMenuItem onClick={expandAllProjects} className="flex items-center gap-2">
<Icon name="expand-up-down" className="h-4 w-4" />
<span>{t('sessions.sidebar.header.displayMode.expandAll')}</span>
</DropdownMenuItem>
</>
) : null}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{isSessionSearchOpen ? (
<div className="pb-1">
<div className="mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80">
{hasSessionSearchQuery ? (
<span>{searchMatchCount === 1
? t('sessions.sidebar.header.search.matchCountSingle', { count: searchMatchCount })
: t('sessions.sidebar.header.search.matchCountPlural', { count: searchMatchCount })}</span>
) : <span />}
<span>{t('sessions.sidebar.header.search.escapeHint')}</span>
</div>
<div className="relative">
<Icon name="search" className="pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<input
ref={sessionSearchInputRef}
value={sessionSearchQuery}
onChange={(event) => setSessionSearchQuery(event.target.value)}
placeholder={t('sessions.sidebar.header.search.placeholder')}
className="h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
onKeyDown={(event) => {
if (event.key === 'Escape') {
event.stopPropagation();
if (hasSessionSearchQuery) {
setSessionSearchQuery('');
} else {
setIsSessionSearchOpen(false);
}
}
}}
/>
{sessionSearchQuery.length > 0 ? (
<button
type="button"
onClick={() => setSessionSearchQuery('')}
className="absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
aria-label={t('sessions.sidebar.header.search.clear')}
>
<Icon name="close" className="h-3.5 w-3.5" />
</button>
) : null}
</div>
</div>
) : null}
</div>
</div>
);
}
@@ -0,0 +1,26 @@
import React from 'react';
import { Icon } from '@/components/icon/Icon';
import { useI18n } from '@/lib/i18n';
// Primary sidebar action: starting a session is the one control worth its own
// row; it keeps the quiet text-row form so the top reads as content, while
// every other control lives in the icon toolbar below.
type Props = {
onNewSession: () => void;
};
export function SidebarNav(props: Props): React.ReactNode {
const { t } = useI18n();
return (
<div className="select-none flex-shrink-0 px-2.5 pt-1.5">
<button
type="button"
onClick={props.onNewSession}
className="flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1 text-left typography-ui-label font-normal text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
>
<Icon name="chat-new" className="h-4 w-4 flex-shrink-0" />
<span className="truncate">{t('sessions.sidebar.header.actions.newSession')}</span>
</button>
</div>
);
}
@@ -0,0 +1,44 @@
import React from 'react';
type Args = {
enabled?: boolean;
isSessionSearchOpen: boolean;
setIsSessionSearchOpen: (open: boolean) => void;
sessionSearchInputRef: React.RefObject<HTMLInputElement | null>;
sessionSearchContainerRef: React.RefObject<HTMLDivElement | null>;
};
export const useSessionSearchEffects = ({
enabled = true,
isSessionSearchOpen,
setIsSessionSearchOpen,
sessionSearchInputRef,
sessionSearchContainerRef,
}: Args): void => {
React.useEffect(() => {
if (!enabled || !isSessionSearchOpen || typeof window === 'undefined') {
return;
}
const raf = window.requestAnimationFrame(() => {
sessionSearchInputRef.current?.focus();
sessionSearchInputRef.current?.select();
});
return () => window.cancelAnimationFrame(raf);
}, [enabled, isSessionSearchOpen, sessionSearchInputRef]);
React.useEffect(() => {
if (!enabled || !isSessionSearchOpen || typeof document === 'undefined') {
return;
}
const handlePointerDown = (event: MouseEvent) => {
if (!sessionSearchContainerRef.current) {
return;
}
if (!sessionSearchContainerRef.current.contains(event.target as Node)) {
setIsSessionSearchOpen(false);
}
};
document.addEventListener('mousedown', handlePointerDown);
return () => document.removeEventListener('mousedown', handlePointerDown);
}, [enabled, isSessionSearchOpen, setIsSessionSearchOpen, sessionSearchContainerRef]);
};
@@ -0,0 +1,164 @@
import React from 'react';
import type { Session } from '@opencode-ai/sdk/v2';
import { useGlobalSessionsStore, resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore';
import { isBtwSession } from '@/lib/sessionBtwMetadata';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useSessionPinnedStore } from '@/stores/useSessionPinnedStore';
import { useGitAllBranches } from '@/stores/useGitStore';
import type { SessionNode } from '../types';
import { isPathWithinProject } from '../utils';
import { compareSessionsByLifecycleOrder, useSessionOrderingStore } from '@/sync/session-ordering';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { isVSCodeRuntime } from '@/lib/desktop';
import { isChatDirectoryPath } from '@/lib/chatDirectories';
export type SwitcherItem = {
node: SessionNode;
projectId: string | null;
groupDirectory: string | null;
secondaryMeta: {
projectLabel?: string | null;
branchLabel?: string | null;
} | null;
};
const MAX_PARENT_SESSIONS = 7;
type SwitcherItemsOptions = {
scopeProjectId?: string | null;
/** How many parent sessions to return (default 7 — the desktop dropdown). */
maxParents?: number;
};
const normalize = (value: string | null | undefined): string | null => {
if (!value) return null;
const replaced = value.replace(/\\/g, '/');
if (replaced === '/') return '/';
return replaced.length > 1 ? replaced.replace(/\/+$/, '') : replaced;
};
const formatProjectLabel = (project: { label?: string | null; path: string } | null): string | null => {
if (!project) return null;
const trimmed = project.label?.trim();
if (trimmed) return trimmed;
const segments = project.path.split(/[\\/]/).filter(Boolean);
return segments[segments.length - 1] ?? null;
};
export const useSwitcherItems = (enabled: boolean, options: SwitcherItemsOptions = {}): SwitcherItem[] => {
const { scopeProjectId = null, maxParents = MAX_PARENT_SESSIONS } = options;
const activeSessions = useGlobalSessionsStore((state) => state.activeSessions);
const projects = useProjectsStore((state) => state.projects);
const pinnedSessionIds = useSessionPinnedStore((state) => state.ids);
const sessionOrderRanks = useSessionOrderingStore((state) => state.rankById);
const branchesByDirectory = useGitAllBranches();
const availableWorktreesByProject = useSessionUIStore((state) => state.availableWorktreesByProject);
const isVSCode = React.useMemo(() => isVSCodeRuntime(), []);
// Worktree sessions live OUTSIDE their project's path, so prefix matching
// can't resolve their project — and their branch is known from worktree
// discovery long before any git status is fetched for that directory.
const worktreeInfoByPath = React.useMemo(() => {
const map = new Map<string, { projectPath: string; branch: string | null }>();
for (const [projectPath, worktrees] of availableWorktreesByProject) {
const normalizedProjectPath = normalize(projectPath);
if (!normalizedProjectPath) continue;
for (const worktree of worktrees) {
const worktreePath = normalize(worktree.path);
if (!worktreePath) continue;
map.set(worktreePath, { projectPath: normalizedProjectPath, branch: worktree.branch?.trim() || null });
}
}
return map;
}, [availableWorktreesByProject]);
const normalizedProjects = React.useMemo(
() => projects
.map((project) => ({ ...project, normalizedPath: normalize(project.path) }))
.filter((project) => project.normalizedPath),
[projects],
);
const findProjectForDirectory = React.useCallback(
(directory: string | null) => {
if (!directory) return null;
// Known worktree → its project, regardless of where the worktree lives.
const worktreeInfo = worktreeInfoByPath.get(normalize(directory) ?? directory);
if (worktreeInfo) {
const byPath = normalizedProjects.find((project) => project.normalizedPath === worktreeInfo.projectPath);
if (byPath) return byPath;
}
const matches = normalizedProjects
.filter((project) => isPathWithinProject(directory, project.normalizedPath))
.sort((a, b) => (b.normalizedPath?.length ?? 0) - (a.normalizedPath?.length ?? 0));
return matches[0] ?? null;
},
[normalizedProjects, worktreeInfoByPath],
);
const items = React.useMemo<SwitcherItem[]>(() => {
if (!enabled) return [];
const childrenByParent = new Map<string, Session[]>();
for (const session of activeSessions) {
const parentId = (session as Session & { parentID?: string | null }).parentID;
if (!parentId) continue;
if (session.time?.archived) continue;
const bucket = childrenByParent.get(parentId);
if (bucket) {
bucket.push(session);
} else {
childrenByParent.set(parentId, [session]);
}
}
childrenByParent.forEach((list) => {
list.sort((a, b) => compareSessionsByLifecycleOrder(a, b, pinnedSessionIds, sessionOrderRanks));
});
const parents = activeSessions
.filter((session) => !session.time?.archived)
// btw forks stay hidden until promoted to a full session
.filter((session) => !isBtwSession(session))
.filter((session) => !isVSCode || !isChatDirectoryPath(resolveGlobalSessionDirectory(session)))
.filter((session) => !(session as Session & { parentID?: string | null }).parentID)
.filter((session) => {
if (!scopeProjectId) return true;
const directory = resolveGlobalSessionDirectory(session);
return findProjectForDirectory(directory)?.id === scopeProjectId;
})
.sort((a, b) => compareSessionsByLifecycleOrder(a, b, pinnedSessionIds, sessionOrderRanks))
.slice(0, maxParents);
const buildNode = (session: Session): SessionNode => {
const childSessions = childrenByParent.get(session.id) ?? [];
return {
session,
children: childSessions.map((child) => buildNode(child)),
worktree: null,
};
};
return parents.map((session) => {
const directory = resolveGlobalSessionDirectory(session);
const matchedProject = findProjectForDirectory(directory);
const projectLabel = formatProjectLabel(matchedProject);
// Live git branch when available; the discovered worktree branch fills
// in for directories whose git status hasn't been fetched yet.
const worktreeInfo = directory ? worktreeInfoByPath.get(normalize(directory) ?? directory) : null;
const liveBranch = directory ? branchesByDirectory.get(directory) : undefined;
const branchLabel = liveBranch ?? worktreeInfo?.branch ?? null;
return {
node: buildNode(session),
projectId: matchedProject?.id ?? null,
groupDirectory: directory,
secondaryMeta: {
projectLabel,
branchLabel: branchLabel && branchLabel !== projectLabel ? branchLabel : null,
},
};
});
}, [activeSessions, branchesByDirectory, enabled, findProjectForDirectory, isVSCode, maxParents, pinnedSessionIds, scopeProjectId, sessionOrderRanks, worktreeInfoByPath]);
return items;
};