Merge pull request #425 from chriswritescode-dev/feat/session-picker-projects-tab

feat(sessions): switch between sessions and projects in the session picker
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-15 16:45:20 -04:00
commit 1902fe5878
8 files changed
+572 -30

No files matched your search

@@ -0,0 +1,224 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { Search } from 'lucide-react'
import type { Repo } from '@/api/types'
import { Input } from '@/components/ui/input'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { cn, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
const PAGE_STEP = 10
interface ProjectPickerContentProps {
open: boolean
currentRepo: Repo | undefined
onSelectRepo: (repo: Repo) => void
switchHint: string
searchInputRef: React.RefObject<HTMLInputElement | null>
}
function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
}
export function ProjectPickerContent({
open,
currentRepo,
onSelectRepo,
switchHint,
searchInputRef,
}: ProjectPickerContentProps) {
const { repos, isLoading } = useNavigableRepos()
const rowRefs = useRef(new Map<number, HTMLDivElement>())
const listId = useId()
const optionBaseId = useId()
const [query, setQuery] = useState('')
const [cursorIndex, setCursorIndex] = useState<number | null>(null)
const trimmedQuery = query.trim()
const filteredRepos = useMemo(() => {
const needle = trimmedQuery.toLowerCase()
if (!needle) return repos
return repos.filter((repo) => {
const name = getRepoDisplayName(repo).toLowerCase()
const branch = (getRepoBranchLabel(repo) ?? '').toLowerCase()
return name.includes(needle) || branch.includes(needle)
})
}, [repos, trimmedQuery])
const defaultCursorIndex = useMemo(() => {
if (!trimmedQuery && currentRepo) {
const index = filteredRepos.findIndex((repo) => repo.id === currentRepo.id)
if (index >= 0) return index
}
return filteredRepos.length > 0 ? 0 : -1
}, [trimmedQuery, currentRepo, filteredRepos])
const effectiveCursorIndex = cursorIndex ?? defaultCursorIndex
const cursorRepo = effectiveCursorIndex >= 0 ? filteredRepos[effectiveCursorIndex] : undefined
useEffect(() => {
setCursorIndex(null)
}, [trimmedQuery])
const setRowRef = useCallback((key: number, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRepo) return
const node = rowRefs.current.get(cursorRepo.id)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRepo])
const moveCursor = useCallback(
(index: number) => {
if (!filteredRepos[index]) return
setCursorIndex(index)
},
[filteredRepos],
)
const handleSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const key = event.key
const ctrlKey = event.key.toLowerCase()
const moveBy = (delta: number, wrap: boolean) => {
if (filteredRepos.length === 0) return
const base = effectiveCursorIndex < 0 ? (delta > 0 ? -1 : 0) : effectiveCursorIndex
const raw = base + delta
const next = wrap
? ((raw % filteredRepos.length) + filteredRepos.length) % filteredRepos.length
: Math.max(0, Math.min(filteredRepos.length - 1, raw))
moveCursor(next)
}
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRepo) return
event.preventDefault()
onSelectRepo(cursorRepo)
}
},
[filteredRepos, effectiveCursorIndex, moveCursor, cursorRepo, onSelectRepo],
)
return (
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
ref={searchInputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={effectiveCursorIndex >= 0 ? optionId(optionBaseId, effectiveCursorIndex) : undefined}
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search projects..."
className="h-9 pl-9"
autoComplete="off"
name="project-picker-search"
/>
</div>
</div>
<div
role="listbox"
id={listId}
aria-label="Projects"
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{filteredRepos.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">
{isLoading ? 'Loading projects...' : 'No projects found'}
</div>
) : (
filteredRepos.map((repo, index) => {
const isCursor = index === effectiveCursorIndex
const isCurrent = repo.id === currentRepo?.id
const branch = getRepoBranchLabel(repo)
return (
<div
key={repo.id}
ref={(node) => setRowRef(repo.id, node)}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') moveCursor(index)
}}
className={cn(
'group flex items-center rounded-md text-sm min-h-8 pointer-coarse:min-h-11',
isCursor ? 'bg-primary text-primary-foreground' : 'hover:bg-accent',
)}
>
<div
role="option"
id={optionId(optionBaseId, index)}
aria-selected={isCursor}
onClick={() => onSelectRepo(repo)}
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2"
>
<span className="flex w-4 shrink-0 items-center justify-center">
{isCurrent && <span aria-hidden="true">●</span>}
</span>
<span
className={cn(
'min-w-0 flex-1 truncate',
isCursor ? 'text-primary-foreground' : isCurrent ? 'text-primary' : 'text-foreground',
)}
>
{getRepoDisplayName(repo)}
</span>
{branch && (
<span
className={cn(
'shrink-0 text-xs',
isCursor ? 'text-primary-foreground/80' : 'text-muted-foreground',
)}
>
{branch}
</span>
)}
</div>
</div>
)
})
)}
</div>
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open
{switchHint ? ` · ${switchHint} sessions` : ''}
</div>
</div>
)
}
@@ -5,6 +5,7 @@ import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Repo, Session } from '@/api/types'
import { stubMatchMedia } from '@/test/test-utils'
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
import { SessionPickerDialog } from './SessionPickerDialog'
const mocks = vi.hoisted(() => ({
@@ -22,6 +23,13 @@ const mocks = vi.hoisted(() => ({
getOpenCodeLocation: vi.fn(),
sessionPins: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
repos: [] as Repo[],
preferences: undefined as
| { leaderKey?: string; keyboardShortcuts?: Record<string, string>; directShortcuts?: string[] }
| undefined,
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: () => ({ preferences: mocks.preferences }),
}))
vi.mock('@/api/opencode', async (importOriginal) => {
@@ -104,13 +112,18 @@ function renderWithClient(ui: React.ReactElement) {
if (mocks.locationData && directory) {
queryClient.setQueryData(['opencode', 'location', directory], mocks.locationData)
}
return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)
return render(
<QueryClientProvider client={queryClient}>
<KeyboardShortcutsProvider>{ui}</KeyboardShortcutsProvider>
</QueryClientProvider>,
)
}
function renderPicker(overrides: Partial<React.ComponentProps<typeof SessionPickerDialog>> = {}) {
const onOpenChange = vi.fn()
const onSelectSession = vi.fn()
const onDeleteActiveSession = vi.fn()
const onSelectRepo = vi.fn()
renderWithClient(
<SessionPickerDialog
open
@@ -118,14 +131,19 @@ function renderPicker(overrides: Partial<React.ComponentProps<typeof SessionPick
currentRepo={mocks.repos[0]}
onSelectSession={onSelectSession}
onDeleteActiveSession={onDeleteActiveSession}
onSelectRepo={onSelectRepo}
{...overrides}
/>,
)
return { onOpenChange, onSelectSession, onDeleteActiveSession }
return { onOpenChange, onSelectSession, onDeleteActiveSession, onSelectRepo }
}
const combobox = () => screen.getByRole('combobox')
const openProjectsTab = () => {
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Projects' }))
}
describe('SessionPickerDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -141,6 +159,7 @@ describe('SessionPickerDialog', () => {
mocks.sessionPins = []
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.sessionsData = []
mocks.preferences = undefined
})
afterEach(() => {
@@ -336,6 +355,7 @@ describe('SessionPickerDialog', () => {
currentRepo={mocks.repos[0]}
onSelectSession={vi.fn()}
onDeleteActiveSession={vi.fn()}
onSelectRepo={vi.fn()}
/>
</>
)
@@ -454,6 +474,7 @@ describe('SessionPickerDialog', () => {
activeSessionID="ses_active"
onSelectSession={vi.fn()}
onDeleteActiveSession={vi.fn()}
onSelectRepo={vi.fn()}
/>
</>
)
@@ -470,4 +491,204 @@ describe('SessionPickerDialog', () => {
await waitFor(() => expect(screen.getByRole('combobox')).toHaveValue(''))
expect(screen.getByRole('option', { name: /Active session/ })).toHaveAttribute('aria-selected', 'true')
})
it('renders a Sessions/Projects tab switcher and defaults to the sessions tab', () => {
renderPicker()
expect(screen.getByRole('tab', { name: 'Sessions' })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByRole('tab', { name: 'Projects' })).toHaveAttribute('aria-selected', 'false')
expect(combobox()).toHaveAttribute('placeholder', 'Search sessions...')
})
it('exposes a tabpanel labelled by the active tab and swaps panels on tab switch', async () => {
renderPicker()
const sessionsPanel = screen.getByRole('tabpanel', { name: 'Sessions' })
expect(sessionsPanel).toHaveAttribute('data-state', 'active')
expect(screen.queryByRole('tabpanel', { name: 'Projects' })).not.toBeInTheDocument()
openProjectsTab()
const projectsPanel = await screen.findByRole('tabpanel', { name: 'Projects' })
expect(projectsPanel).toHaveAttribute('data-state', 'active')
expect(screen.queryByRole('tabpanel', { name: 'Sessions' })).not.toBeInTheDocument()
})
it('focuses the projects search input after clicking the Projects tab and filters on typing', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const user = userEvent.setup()
renderPicker()
await user.click(screen.getByRole('tab', { name: 'Projects' }))
await waitFor(() => expect(screen.getByPlaceholderText('Search projects...')).toHaveFocus())
await user.keyboard('beta')
expect(screen.getByRole('option', { name: /beta/ })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: /alpha/ })).not.toBeInTheDocument()
})
it('focuses the projects search input after switching tabs with the shortcut', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const user = userEvent.setup()
renderPicker()
await user.click(screen.getByPlaceholderText('Search sessions...'))
await user.keyboard('{Control>}s{/Control}')
await waitFor(() => expect(screen.getByPlaceholderText('Search projects...')).toHaveFocus())
})
it('focuses the projects search input after the switch shortcut on a coarse pointer device', async () => {
stubMatchMedia(false)
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const user = userEvent.setup()
renderPicker()
await user.click(screen.getByPlaceholderText('Search sessions...'))
await user.keyboard('{Control>}s{/Control}')
await waitFor(() => expect(screen.getByPlaceholderText('Search projects...')).toHaveFocus())
})
it('does not focus the projects search input when switching tabs by pointer on a coarse pointer device', async () => {
stubMatchMedia(false)
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const user = userEvent.setup()
renderPicker()
await user.click(screen.getByRole('tab', { name: 'Projects' }))
expect(await screen.findByPlaceholderText('Search projects...')).not.toHaveFocus()
})
it('lists repos in the projects tab and opens the cursor repo on Enter', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const { onSelectRepo } = renderPicker()
openProjectsTab()
const alpha = await screen.findByRole('option', { name: /alpha/ })
expect(alpha).toHaveAttribute('aria-selected', 'true')
expect(screen.getByRole('option', { name: /beta/ })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 'Enter' })
expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[0])
})
it('opens a repo on click in the projects tab', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const { onSelectRepo } = renderPicker()
openProjectsTab()
fireEvent.click(await screen.findByRole('option', { name: /beta/ }))
expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[1])
})
it('filters projects by name and branch', async () => {
mocks.repos = [
{ ...repo(1, 'alpha', '/w/a'), currentBranch: 'feature/x' },
repo(2, 'beta', '/w/b'),
]
renderPicker()
openProjectsTab()
await screen.findByRole('option', { name: /alpha/ })
fireEvent.change(combobox(), { target: { value: 'beta' } })
expect(screen.queryByRole('option', { name: /alpha/ })).not.toBeInTheDocument()
expect(screen.getByRole('option', { name: /beta/ })).toBeInTheDocument()
fireEvent.change(combobox(), { target: { value: 'feature/x' } })
expect(screen.getByRole('option', { name: /alpha/ })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: /beta/ })).not.toBeInTheDocument()
})
it('shows the empty projects state when nothing matches', async () => {
renderPicker()
openProjectsTab()
await screen.findByRole('option', { name: /alpha/ })
fireEvent.change(combobox(), { target: { value: 'zzz' } })
expect(screen.getByText('No projects found')).toBeInTheDocument()
})
it('toggles between tabs with the default Ctrl+S binding in either search input', async () => {
renderPicker()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
})
it('honors a configured switch binding and shows it in the footer', async () => {
mocks.preferences = { keyboardShortcuts: { switchPickerTab: 'Ctrl+G' } }
renderPicker()
expect(screen.getByText(/Ctrl\+G projects/)).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 'g', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
expect(screen.getByText(/Ctrl\+G sessions/)).toBeInTheDocument()
})
it('shows the normalized leader, arrow and key in the footer for a leader switch binding', () => {
mocks.preferences = {
keyboardShortcuts: { switchPickerTab: 'G' },
directShortcuts: [],
leaderKey: 'Ctrl+X',
}
renderPicker()
expect(screen.getByText(/Ctrl\+X → G projects/)).toBeInTheDocument()
})
it('no longer switches tabs on Ctrl+O', () => {
renderPicker()
fireEvent.keyDown(combobox(), { key: 'o', ctrlKey: true })
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
})
it('resets to the sessions tab when the dialog reopens', async () => {
function Host() {
const [open, setOpen] = useState(true)
return (
<>
<button type="button" onClick={() => setOpen(false)}>close-picker</button>
<button type="button" onClick={() => setOpen(true)}>open-picker</button>
<SessionPickerDialog
open={open}
onOpenChange={setOpen}
currentRepo={mocks.repos[0]}
onSelectSession={vi.fn()}
onDeleteActiveSession={vi.fn()}
onSelectRepo={vi.fn()}
/>
</>
)
}
renderWithClient(<Host />)
openProjectsTab()
expect(screen.getByRole('tab', { name: 'Projects' })).toHaveAttribute('aria-selected', 'true')
fireEvent.click(screen.getByText('close-picker'))
fireEvent.click(screen.getByText('open-picker'))
await waitFor(() =>
expect(screen.getByRole('tab', { name: 'Sessions' })).toHaveAttribute('aria-selected', 'true'),
)
})
})
@@ -14,7 +14,9 @@ import {
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
import { ProjectPickerContent } from '@/components/session/ProjectPickerContent'
import { partitionSessions } from '@/components/session/session-partition'
import { buildRepoByDirectory } from '@/components/navigation/sidebar-session-tree'
import { useDeleteSession } from '@/hooks/useOpenCode'
@@ -23,7 +25,10 @@ import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
import { useSettings } from '@/hooks/useSettings'
import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey'
import { formatShortcutLabel, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
@@ -32,6 +37,8 @@ const UNTITLED_SESSION_TITLE = 'Untitled Session'
const PAGE_STEP = 10
const NEAR_BOTTOM_PX = 240
type SessionPickerTab = 'sessions' | 'projects'
interface SessionPickerDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
@@ -39,6 +46,7 @@ interface SessionPickerDialogProps {
activeSessionID?: string
onSelectSession: (session: Session, repo: Repo) => void
onDeleteActiveSession: () => void
onSelectRepo: (repo: Repo) => void
}
interface SessionPickerRow {
@@ -281,6 +289,7 @@ interface SessionPickerContentProps {
activeSessionID?: string
onSelectSession: (session: Session, repo: Repo) => void
onDeleteActiveSession: () => void
switchHint: string
searchInputRef: React.RefObject<HTMLInputElement | null>
hasFinePointer: boolean
}
@@ -291,6 +300,7 @@ function SessionPickerContent({
activeSessionID,
onSelectSession,
onDeleteActiveSession,
switchHint,
searchInputRef,
hasFinePointer,
}: SessionPickerContentProps) {
@@ -548,13 +558,6 @@ function SessionPickerContent({
return (
<>
<DialogTitle className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
Sessions
{!allProjects && currentRepo && (
<span className="font-normal text-muted-foreground"> for {getRepoDisplayName(currentRepo)}</span>
)}
</DialogTitle>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
<div className="relative flex-1">
@@ -672,6 +675,7 @@ function SessionPickerContent({
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
{switchHint ? ` · ${switchHint} projects` : ''}
</div>
</div>
@@ -697,9 +701,52 @@ export function SessionPickerDialog({
activeSessionID,
onSelectSession,
onDeleteActiveSession,
onSelectRepo,
}: SessionPickerDialogProps) {
const searchInputRef = useRef<HTMLInputElement>(null)
const projectSearchInputRef = useRef<HTMLInputElement>(null)
const focusSearchAfterSwitchRef = useRef(false)
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
const { preferences } = useSettings()
const switchHint = useMemo(
() => {
const bindings = resolveShortcutBindings(preferences)
return formatShortcutLabel(
bindings.shortcuts.switchPickerTab,
bindings.directShortcuts.includes('switchPickerTab'),
bindings.leaderKey,
)
},
[preferences],
)
const [tab, setTab] = useState<SessionPickerTab>('sessions')
const [prevOpen, setPrevOpen] = useState(open)
if (prevOpen !== open) {
setPrevOpen(open)
if (open) setTab('sessions')
}
const toggleTab = useCallback(() => {
focusSearchAfterSwitchRef.current = true
setTab((current) => (current === 'sessions' ? 'projects' : 'sessions'))
}, [])
useShortcutActions({ switchPickerTab: open ? toggleTab : undefined })
useEffect(() => {
if (!open) {
focusSearchAfterSwitchRef.current = false
return
}
if (!hasFinePointer && !focusSearchAfterSwitchRef.current) return
const frame = requestAnimationFrame(() => {
focusSearchAfterSwitchRef.current = false
if (tab === 'projects') projectSearchInputRef.current?.focus()
else searchInputRef.current?.focus()
})
return () => cancelAnimationFrame(frame)
}, [open, tab, hasFinePointer])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -716,15 +763,46 @@ export function SessionPickerDialog({
}
}}
>
<SessionPickerContent
open={open}
currentRepo={currentRepo}
activeSessionID={activeSessionID}
onSelectSession={onSelectSession}
onDeleteActiveSession={onDeleteActiveSession}
searchInputRef={searchInputRef}
hasFinePointer={hasFinePointer}
/>
<Tabs
value={tab}
onValueChange={(value) => setTab(value as SessionPickerTab)}
className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0"
>
<div className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
<DialogTitle className="sr-only">{tab === 'sessions' ? 'Sessions' : 'Projects'}</DialogTitle>
<TabsList>
<TabsTrigger value="sessions">Sessions</TabsTrigger>
<TabsTrigger value="projects">Projects</TabsTrigger>
</TabsList>
</div>
<TabsContent
value="sessions"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
>
<SessionPickerContent
open={open}
currentRepo={currentRepo}
activeSessionID={activeSessionID}
onSelectSession={onSelectSession}
onDeleteActiveSession={onDeleteActiveSession}
switchHint={switchHint}
searchInputRef={searchInputRef}
hasFinePointer={hasFinePointer}
/>
</TabsContent>
<TabsContent
value="projects"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
>
<ProjectPickerContent
open={open}
currentRepo={currentRepo}
onSelectRepo={onSelectRepo}
switchHint={switchHint}
searchInputRef={projectSearchInputRef}
/>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
)
@@ -3,14 +3,14 @@ import { useSettings } from '@/hooks/useSettings'
import { useMobile } from '@/hooks/useMobile'
import { Loader2, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
import { formatEventModifiers, formatShortcutEvent, formatShortcutLabel, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
import { showToast } from '@/lib/toast'
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown', 'speakVisible']
const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl']
const NAVIGATION_ACTIONS = ['settings', 'sessions', 'switchPickerTab', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl']
const formatShortcutLabel = (action: string): string => {
const formatActionLabel = (action: string): string => {
return action.replace(/([A-Z])/g, ' $1').trim()
}
@@ -87,7 +87,7 @@ function ShortcutRow({ action, keys, isDirect, display, isRecording, currentKeys
return (
<div className="flex flex-wrap items-center justify-between gap-2 py-2.5 border-b border-border last:border-0">
<div className="min-w-0 flex-1 basis-48 space-y-0.5">
<p className="truncate text-sm font-medium capitalize text-foreground">{formatShortcutLabel(action)}</p>
<p className="truncate text-sm font-medium capitalize text-foreground">{formatActionLabel(action)}</p>
<button
onClick={() => onToggleDirect(action)}
className="text-xs text-muted-foreground hover:text-foreground transition-colors text-left"
@@ -246,10 +246,7 @@ export function KeyboardShortcuts() {
const formatShortcutDisplay = (action: string, keys: string) => {
if (!keys) return 'Not set'
if (directShortcuts.includes(action)) {
return normalizeShortcut(keys)
}
return `${normalizeShortcut(leaderKey)} → ${normalizeShortcut(keys)}`
return formatShortcutLabel(keys, directShortcuts.includes(action), leaderKey)
}
const toggleDirectShortcut = (action: string) => {
@@ -293,7 +290,7 @@ export function KeyboardShortcuts() {
}
const description = [
applied.cleared.length > 0 ? `Unbound to avoid conflicts: ${applied.cleared.map((action) => formatShortcutLabel(action).toLowerCase()).join(', ')}` : undefined,
applied.cleared.length > 0 ? `Unbound to avoid conflicts: ${applied.cleared.map((action) => formatActionLabel(action).toLowerCase()).join(', ')}` : undefined,
skippedDescription ? `Skipped: ${skippedDescription}` : undefined,
].filter(Boolean).join('. ')
showToast.success(
+8 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
import { formatShortcutEvent, getDefaultKeyboardShortcuts, normalizeShortcut, resolveDirectShortcuts, resolveShortcutBindings } from './keyboardShortcuts'
import { formatShortcutEvent, formatShortcutLabel, getDefaultKeyboardShortcuts, normalizeShortcut, resolveDirectShortcuts, resolveShortcutBindings } from './keyboardShortcuts'
describe('keyboardShortcuts', () => {
it('normalizes key aliases, modifier order and bare symbol keys', () => {
@@ -11,6 +11,13 @@ describe('keyboardShortcuts', () => {
expect(normalizeShortcut('+')).toBe('+')
})
it('formats empty, direct and leader bindings as labels', () => {
expect(formatShortcutLabel('', true, 'Ctrl+X')).toBe('')
expect(formatShortcutLabel('', false, 'Ctrl+X')).toBe('')
expect(formatShortcutLabel('Shift+Ctrl+z', true, 'Ctrl+X')).toBe('Ctrl+Shift+Z')
expect(formatShortcutLabel('G', false, 'Ctrl+Enter')).toBe('Ctrl+Return → G')
})
it('reads letters from the physical key when Alt rewrites the character', () => {
expect(formatShortcutEvent(new KeyboardEvent('keydown', { key: '†', code: 'KeyT', altKey: true }))).toBe('Alt+T')
expect(formatShortcutEvent(new KeyboardEvent('keydown', { key: 'Shift', shiftKey: true }))).toBeNull()
+10
View File
@@ -75,6 +75,16 @@ export function normalizeShortcut(shortcut: string): string {
return [...orderedModifiers, mainKey].join('+')
}
/**
* Formats a stored binding for display: empty keys render as an empty string, a direct binding as its normalized keys,
* and a leader binding as `leader → keys`, with both the leader and the keys normalized.
*/
export function formatShortcutLabel(keys: string, isDirect: boolean, leaderKey: string): string {
if (!keys) return ''
if (isDirect) return normalizeShortcut(keys)
return `${normalizeShortcut(leaderKey)} → ${normalizeShortcut(keys)}`
}
export function hasCommandModifier(shortcut: string): boolean {
return /(^|\+)(Ctrl|Cmd|Alt)\+./.test(shortcut)
}
+5 -1
View File
@@ -9,7 +9,7 @@ import { X, CornerUpLeft } from "lucide-react";
import { SquareFill } from "@/components/ui/square-fill";
import { Header } from "@/components/ui/header";
import { SessionPickerDialog } from "@/components/session/SessionPickerDialog";
import { getSessionListPath, getSessionPath } from '@/lib/navigation'
import { getRepoPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
import { FetchError } from '@/api/fetchWrapper'
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
@@ -882,6 +882,10 @@ export function SessionDetail() {
setSessionsDialogOpen(false)
handleCloseSession()
}}
onSelectRepo={(selectedRepo) => {
navigate(getRepoPath(selectedRepo.id))
setSessionsDialogOpen(false)
}}
/>
{sideQuestion && sessionId && (
+2 -1
View File
@@ -76,6 +76,7 @@ export const DEFAULT_KEYBOARD_SHORTCUTS = {
fork: '',
settings: '',
sessions: 'L',
switchPickerTab: 'Ctrl+S',
newSession: 'N',
closeSession: 'W',
toggleSidebar: 'B',
@@ -93,7 +94,7 @@ export const DEFAULT_KEYBOARD_SHORTCUTS = {
export type KeyboardShortcutAction = keyof typeof DEFAULT_KEYBOARD_SHORTCUTS;
export const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown'];
export const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown', 'switchPickerTab'];
export const GitCredentialSchema = z.object({
id: z.string().optional(),