{quickSections.map(section => (
@@ -588,7 +716,7 @@ export function ModelQuickSelect({
{section.title}
- {section.models.map(item => renderModelOption(item))}
+ {section.models.map((item, index) => renderModelOption(item, (quickSectionOffsets.get(section.title) ?? 0) + index))}
))}
diff --git a/frontend/src/components/navigation/DesktopSessionTree.test.tsx b/frontend/src/components/navigation/DesktopSessionTree.test.tsx
index b50eb47d..22b0cc30 100644
--- a/frontend/src/components/navigation/DesktopSessionTree.test.tsx
+++ b/frontend/src/components/navigation/DesktopSessionTree.test.tsx
@@ -34,6 +34,7 @@ const {
getSessionMock,
sessionPinsData,
sessionsHasNextPage,
+ searchError,
} = vi.hoisted(() => ({
listReposMock: vi.fn(),
sessionsData: [] as SessionFixture[],
@@ -45,6 +46,7 @@ const {
getSessionMock: vi.fn(),
sessionPinsData: { current: [] as SessionPinFixture[] },
sessionsHasNextPage: { current: false },
+ searchError: { current: false },
}))
vi.mock('@/api/repos', async (importOriginal) => {
@@ -62,12 +64,17 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
return {
...actual,
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number }) => {
- sessionsHookCalls.push({ directories, options })
+ if (directories.length > 0) sessionsHookCalls.push({ directories, options })
const data =
options?.search && emptyOnSearch.current
? []
: sessionsData.filter((session) => directories.includes(session.location.directory))
- return { data, isLoading: false, isError: false, hasNextPage: sessionsHasNextPage.current }
+ return {
+ data,
+ isLoading: false,
+ isError: Boolean(options?.search) && searchError.current,
+ hasNextPage: sessionsHasNextPage.current,
+ }
},
useCreateSession: (directory?: string) => ({
mutate: (vars?: unknown) => {
@@ -161,6 +168,7 @@ describe('DesktopSessionTree', () => {
getSessionMock.mockResolvedValue(undefined)
sessionPinsData.current = []
sessionsHasNextPage.current = false
+ searchError.current = false
})
it('lists every repo by last access, even inside a repo, with no Recent section', async () => {
@@ -302,6 +310,9 @@ describe('DesktopSessionTree', () => {
await user.type(input, 'Session')
expect(await screen.findByRole('button', { name: /^Session a1/ })).toBeTruthy()
+ await waitFor(() =>
+ expect(sessionsHookCalls.some((call) => call.options?.search === 'Session')).toBe(true),
+ )
const searchCall = sessionsHookCalls.find((call) => call.options?.search === 'Session')
expect(searchCall?.directories).toEqual(['/repos/a', '/repos/b'])
expect(sessionsHookCalls.some((call) => call.options?.search === 'Sess')).toBe(false)
@@ -315,6 +326,19 @@ describe('DesktopSessionTree', () => {
expect(toggleFor('Alpha')).toBeTruthy()
})
+ it('filters loaded sessions by title immediately', async () => {
+ const user = userEvent.setup()
+ render(
, { wrapper: createWrapper(['/']) })
+
+ const input = await screen.findByLabelText('Search sessions')
+ await screen.findByText('Alpha')
+ await user.type(input, 'a1')
+
+ expect(await screen.findByRole('button', { name: /^Session a1/ })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: /^Session b1/ })).toBeNull()
+ expect(screen.queryByRole('button', { name: /^Session c1/ })).toBeNull()
+ })
+
it('clears an active search with the clear button', async () => {
const user = userEvent.setup()
render(
, { wrapper: createWrapper(['/']) })
@@ -340,6 +364,7 @@ describe('DesktopSessionTree', () => {
expect(await screen.findByRole('button', { name: /^Session b1/ })).toBeTruthy()
expect(screen.queryByRole('button', { name: /^Session a1/ })).toBeNull()
+ await waitFor(() => expect(sessionsHookCalls.some((call) => call.options?.search === 'bet')).toBe(true))
const searchCall = sessionsHookCalls.find((call) => call.options?.search === 'bet')
expect(searchCall?.directories).toEqual(['/repos/c', '/repos/a'])
})
@@ -369,6 +394,17 @@ describe('DesktopSessionTree', () => {
expect(await screen.findByText('No sessions found')).toBeTruthy()
})
+ it('shows the error state when the session search fails', async () => {
+ const user = userEvent.setup()
+ searchError.current = true
+ render(
, { wrapper: createWrapper(['/']) })
+
+ const input = await screen.findByLabelText('Search sessions')
+ await user.type(input, 'Session')
+
+ expect(await screen.findByText('Failed to load sessions')).toBeTruthy()
+ })
+
it('creates a session in the repo full path', async () => {
const user = userEvent.setup()
render(
, { wrapper: createWrapper(['/']) })
diff --git a/frontend/src/components/navigation/DesktopSessionTree.tsx b/frontend/src/components/navigation/DesktopSessionTree.tsx
index 98753d55..7b3aa581 100644
--- a/frontend/src/components/navigation/DesktopSessionTree.tsx
+++ b/frontend/src/components/navigation/DesktopSessionTree.tsx
@@ -1,9 +1,11 @@
import { useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Search } from 'lucide-react'
-import type { Repo } from '@/api/types'
+import type { Repo, Session } from '@/api/types'
import { Input } from '@/components/ui/input'
import { useNavigableRepos, useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups'
+import { useSessionSearch } from '@/hooks/useSessionSearch'
+import { useSessionPins } from '@/hooks/useSessionPins'
import {
NewSessionButton,
RepoNavGroup,
@@ -12,12 +14,16 @@ import {
SessionNavRow,
SessionNavStatus,
} from '@/components/navigation/RepoSessionNav'
-import { getActiveRepoId, isCurrentSessionItem, isRepoReady } from '@/components/navigation/sidebar-session-tree'
+import {
+ SIDEBAR_SESSIONS_PER_REPO,
+ buildSidebarRepoGroups,
+ getActiveRepoId,
+ isCurrentSessionItem,
+ isRepoReady,
+} from '@/components/navigation/sidebar-session-tree'
import { getRepoPath } from '@/lib/navigation'
import { getRepoDisplayName } from '@/lib/utils'
-import { useDebouncedValue } from '@/hooks/useDebouncedValue'
-
-const SESSION_SEARCH_DEBOUNCE_MS = 300
+import { buildPinnedSessionKeys } from '@/lib/sessionKey'
function SessionSearchInput({ value, onChange }: { value: string; onChange: (value: string) => void }) {
const clear = () => onChange('')
@@ -46,29 +52,37 @@ function SessionSearchInput({ value, onChange }: { value: string; onChange: (val
)
}
-function SessionSearchResults({ repos, search }: { repos: Repo[]; search: string }) {
+interface SessionSearchResultsProps {
+ nameMatchedRepos: Repo[]
+ otherRepos: Repo[]
+ sessions: Session[]
+ isSearchLoading: boolean
+ isSearchError: boolean
+}
+
+function SessionSearchResults({
+ nameMatchedRepos,
+ otherRepos,
+ sessions,
+ isSearchLoading,
+ isSearchError,
+}: SessionSearchResultsProps) {
const navigate = useNavigate()
const location = useLocation()
- const { nameMatchedRepos, otherRepos } = useMemo(() => {
- const query = search.toLowerCase()
- const readyRepos = repos.filter(isRepoReady)
- const isNameMatch = (repo: Repo) => getRepoDisplayName(repo).toLowerCase().includes(query)
- return {
- nameMatchedRepos: readyRepos.filter(isNameMatch),
- otherRepos: readyRepos.filter((repo) => !isNameMatch(repo)),
- }
- }, [repos, search])
const nameMatches = useSidebarRepoGroups({ repos: nameMatchedRepos })
- const sessionMatches = useSidebarRepoGroups({ repos: otherRepos, search })
- const isLoading = nameMatches.isLoading || sessionMatches.isLoading
- const isError = nameMatches.isError || sessionMatches.isError
+ const { data: sessionPins } = useSessionPins()
+ const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
+ const sessionGroups = useMemo(
+ () => buildSidebarRepoGroups({ repos: otherRepos, sessions, pinnedKeys, now: Date.now() }),
+ [otherRepos, sessions, pinnedKeys],
+ )
const matchingGroups = [
...nameMatches.groups,
- ...sessionMatches.groups.filter((group) => group.items.length > 0),
+ ...sessionGroups.filter((group) => group.items.length > 0),
]
- if (isLoading) return
Loading sessions...
- if (isError) return
Failed to load sessions
+ if (nameMatches.isLoading || isSearchLoading) return
Loading sessions...
+ if (nameMatches.isError || isSearchError) return
Failed to load sessions
if (matchingGroups.length === 0) return
No sessions found
return (
@@ -101,23 +115,53 @@ function SessionSearchResults({ repos, search }: { repos: Repo[]; search: string
export function DesktopSessionTree() {
const navigate = useNavigate()
const location = useLocation()
+ const { repos, isLoading } = useNavigableRepos()
+ const readyRepos = useMemo(() => repos.filter(isRepoReady), [repos])
+
const [draft, setDraft] = useState('')
const trimmedDraft = draft.trim()
- const debouncedSearch = useDebouncedValue(trimmedDraft, SESSION_SEARCH_DEBOUNCE_MS)
- const search = trimmedDraft ? debouncedSearch : ''
- const { repos, isLoading } = useNavigableRepos()
+
+ const { nameMatchedRepos, otherRepos } = useMemo(() => {
+ const query = trimmedDraft.toLowerCase()
+ const isNameMatch = (repo: Repo) => getRepoDisplayName(repo).toLowerCase().includes(query)
+ return {
+ nameMatchedRepos: readyRepos.filter(isNameMatch),
+ otherRepos: readyRepos.filter((repo) => !isNameMatch(repo)),
+ }
+ }, [readyRepos, trimmedDraft])
+
+ const otherDirectories = useMemo(() => otherRepos.map((repo) => repo.fullPath), [otherRepos])
+ const searchDirectories = useMemo(
+ () => (trimmedDraft ? otherDirectories : []),
+ [trimmedDraft, otherDirectories],
+ )
+ const { setQuery, filteredSessions, isLoading: isSearchLoading, isError: isSearchError } = useSessionSearch(
+ searchDirectories,
+ { limit: SIDEBAR_SESSIONS_PER_REPO },
+ )
+
+ const handleSearchChange = (value: string) => {
+ setDraft(value)
+ setQuery(value)
+ }
return (
-
+
{isLoading ? (
Loading repos...
- ) : search ? (
-
+ ) : trimmedDraft ? (
+
) : (
+
{docked ? (
{
+ Reflect.deleteProperty(window, 'matchMedia')
+})
+
describe('ToolSidePanel', () => {
it('shows the tool name in a tooltip when hovering a rail icon', async () => {
const user = userEvent.setup()
@@ -229,4 +235,19 @@ describe('ToolSidePanel', () => {
await waitFor(() => expect(search().get('dialog')).toBe('sourceControl'))
expect(search().has('panel')).toBe(false)
})
+
+ it('moves focus to the chat prompt when the docked panel closes on desktop', async () => {
+ stubMatchMedia(true)
+ const user = userEvent.setup()
+ renderAt('')
+
+ await user.click(screen.getByRole('button', { name: 'Files' }))
+ const closeButton = await screen.findByRole('button', { name: 'Close panel' })
+ closeButton.focus()
+
+ await user.click(closeButton)
+
+ await waitFor(() => expect(search().has('panel')).toBe(false))
+ expect(screen.getByLabelText('prompt')).toHaveFocus()
+ })
})
diff --git a/frontend/src/components/navigation/ToolSidePanel.tsx b/frontend/src/components/navigation/ToolSidePanel.tsx
index be80d5db..1c4bd2b9 100644
--- a/frontend/src/components/navigation/ToolSidePanel.tsx
+++ b/frontend/src/components/navigation/ToolSidePanel.tsx
@@ -1,3 +1,4 @@
+import { useEffect, useRef } from 'react'
import { X } from 'lucide-react'
import { useLocation } from 'react-router-dom'
import { FileBrowser } from '@/components/file-browser/FileBrowser'
@@ -15,10 +16,11 @@ import { RepoActionsContent } from '@/components/repo/RepoActionsDialog'
import { RepoSkillsContent } from '@/components/repo/RepoSkillsDialog'
import { RepoSchedulesContent } from '@/components/schedules/RepoSchedulesContent'
import type { SkillFileInfo } from '@opencode-manager/shared'
-import { buildToolItems, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
+import { buildToolItems, toolKeyOf, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToolPanel'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { restoreOverlayFocus } from '@/lib/overlayFocus'
import { cn } from '@/lib/utils'
interface ToolSidePanelProps {
@@ -90,10 +92,23 @@ export function ToolSidePanel({
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
const openNavItem = useOpenNavItem()
+ const railRef = useRef(null)
+ const previousActiveToolRef = useRef(activeTool)
+
+ useEffect(() => {
+ const previousTool = previousActiveToolRef.current
+ previousActiveToolRef.current = activeTool
+ if (previousTool === null || activeTool !== null) return
+ const active = document.activeElement
+ if (active === null || active === document.body || railRef.current?.contains(active)) {
+ restoreOverlayFocus(null)
+ }
+ }, [activeTool])
+
const panelTools: Array<{ item: MoreDrawerItem; tool: PanelTool }> = []
const actionItems: MoreDrawerItem[] = []
for (const item of buildToolItems(location.pathname)) {
- const tool = item.panelTool ?? item.dialog ?? null
+ const tool = toolKeyOf(item)
if (isPanelTool(tool)) panelTools.push({ item, tool })
else actionItems.push(item)
}
@@ -182,7 +197,7 @@ export function ToolSidePanel({
) : null}
-
+
{panelTools.map(({ item, tool }) => (
toggleTool(tool)} />
))}
diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts
index cd366f52..bbed2aa4 100644
--- a/frontend/src/components/navigation/moreDrawerItems.ts
+++ b/frontend/src/components/navigation/moreDrawerItems.ts
@@ -60,6 +60,11 @@ export function buildToolItems(pathname: string): MoreDrawerItem[] {
return buildNavModel(pathname).items.filter((item) => !NON_TOOL_ITEM_KEYS.has(item.key))
}
+/** The `?panel=`/`?dialog=` tool identifier an item targets, preferring its panel tool. */
+export function toolKeyOf(item: MoreDrawerItem): string | null {
+ return item.panelTool ?? item.dialog ?? null
+}
+
function buildRouteNavModel(pathname: string): NavModel {
const baseItems = getBaseItems()
diff --git a/frontend/src/components/navigation/sidebar-session-tree.test.ts b/frontend/src/components/navigation/sidebar-session-tree.test.ts
index ffa235ba..e154791b 100644
--- a/frontend/src/components/navigation/sidebar-session-tree.test.ts
+++ b/frontend/src/components/navigation/sidebar-session-tree.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'
import type { Repo, Session } from '@/api/types'
import {
+ buildRepoByDirectory,
buildSidebarRepoGroups,
getActiveRepoId,
isCurrentSessionItem,
@@ -112,6 +113,19 @@ describe('selectNavigableRepos', () => {
})
})
+describe('buildRepoByDirectory', () => {
+ it('indexes each repo by full path', () => {
+ const repoA = createRepo({ id: 1, fullPath: '/repos/a' })
+ const repoB = createRepo({ id: 2, fullPath: '/repos/b' })
+
+ const byDirectory = buildRepoByDirectory([repoA, repoB])
+
+ expect(byDirectory.get('/repos/a')).toBe(repoA)
+ expect(byDirectory.get('/repos/b')).toBe(repoB)
+ expect(byDirectory.size).toBe(2)
+ })
+})
+
describe('buildSidebarRepoGroups', () => {
const repoA = createRepo({ id: 1, fullPath: '/repos/a', name: 'Alpha' })
const repoB = createRepo({ id: 2, fullPath: '/repos/b', name: 'Beta' })
diff --git a/frontend/src/components/navigation/sidebar-session-tree.ts b/frontend/src/components/navigation/sidebar-session-tree.ts
index 245187e0..2a1db5a2 100644
--- a/frontend/src/components/navigation/sidebar-session-tree.ts
+++ b/frontend/src/components/navigation/sidebar-session-tree.ts
@@ -1,7 +1,7 @@
import type { Repo, Session } from '@/api/types'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
-import { buildSessionKey } from '@/lib/sessionKey'
+import { getSessionKey } from '@/lib/sessionKey'
import { getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
import { partitionSessions, selectRootSessions } from '@/components/session/session-partition'
@@ -46,6 +46,10 @@ export function selectNavigableRepos(repos: Repo[]): Repo[] {
)
}
+export function buildRepoByDirectory(repos: Repo[]): Map {
+ return new Map(repos.map((repo) => [repo.fullPath, repo]))
+}
+
export function buildSidebarRepoGroups(input: {
repos: Repo[]
sessions: Session[]
@@ -53,8 +57,8 @@ export function buildSidebarRepoGroups(input: {
now: number
}): SidebarRepoGroup[] {
const { repos, sessions, pinnedKeys, now } = input
- const keyFn = (session: Session) => buildSessionKey(session.location.directory, session.id)
- const repoByDirectory = new Map(repos.map((repo) => [repo.fullPath, repo]))
+ const keyFn = getSessionKey
+ const repoByDirectory = buildRepoByDirectory(repos)
const roots = selectRootSessions(sessions, {
directories: new Set(repos.map((repo) => repo.fullPath)),
diff --git a/frontend/src/components/session/FormPrompt.test.tsx b/frontend/src/components/session/FormPrompt.test.tsx
index 0a976055..45c42320 100644
--- a/frontend/src/components/session/FormPrompt.test.tsx
+++ b/frontend/src/components/session/FormPrompt.test.tsx
@@ -1,9 +1,24 @@
-import { render, screen, waitFor, within } from '@testing-library/react'
+import { render as renderRaw, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
+import type { ReactElement } from 'react'
import type { FormInfo } from '@opencode-manager/shared/opencode'
+import { KeyboardShortcutsProvider, useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
import { FormPrompt } from './FormPrompt'
+vi.mock('@/hooks/useSettings', () => ({
+ useSettings: () => ({ preferences: undefined }),
+}))
+
+function render(ui: ReactElement) {
+ return renderRaw(ui, { wrapper: KeyboardShortcutsProvider })
+}
+
+function AbortLayer({ onAbort }: { onAbort: () => void }) {
+ useShortcutActions({ abort: onAbort })
+ return null
+}
+
const selectForm: FormInfo = {
id: 'form-1',
sessionID: 'session-1',
@@ -612,4 +627,22 @@ describe('FormPrompt', () => {
expect(screen.queryByRole('link', { name: /Approve access/ })).not.toBeInTheDocument()
})
})
+
+ describe('keyboard shortcuts', () => {
+ it('minimizes once on Escape while expanded without triggering a registered session abort', async () => {
+ const sessionAbort = vi.fn()
+ const onMinimize = vi.fn()
+ render(
+ <>
+
+
+ >
+ )
+
+ await userEvent.keyboard('{Escape}')
+
+ expect(onMinimize).toHaveBeenCalledTimes(1)
+ expect(sessionAbort).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/frontend/src/components/session/FormPrompt.tsx b/frontend/src/components/session/FormPrompt.tsx
index b6648068..cde00e1f 100644
--- a/frontend/src/components/session/FormPrompt.tsx
+++ b/frontend/src/components/session/FormPrompt.tsx
@@ -7,6 +7,7 @@ import type { FormAnswer, FormField, FormInfo } from '@opencode-manager/shared/o
import { buildAnswer, hasMissingAnswers, visibleFields } from '@/lib/formFields'
import { cn } from '@/lib/utils'
import { showToast } from '@/lib/toast'
+import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
type AnswerableFormField = Exclude
@@ -136,6 +137,10 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize }: FormPromptPr
onMinimize?.()
}
+ useShortcutActions({
+ abort: !isMinimized && !expandedCustom ? handleMinimize : undefined,
+ })
+
const handleSubmit = async () => {
if (!canSubmit) return
setIsSubmitting(true)
@@ -161,6 +166,7 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize }: FormPromptPr
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return
if (e.key === 'Escape' && !isMinimized && !expandedCustom) {
setIsMinimized(true)
onMinimize?.()
diff --git a/frontend/src/components/session/SessionCard.tsx b/frontend/src/components/session/SessionCard.tsx
index 16e5e5d1..e8c4ff07 100644
--- a/frontend/src/components/session/SessionCard.tsx
+++ b/frontend/src/components/session/SessionCard.tsx
@@ -12,7 +12,6 @@ import { Button } from "@/components/ui/button";
interface SessionCardProps {
session: Session;
isSelected: boolean;
- isActive: boolean;
manageMode: boolean;
isPinned?: boolean;
onTogglePin?: () => void;
@@ -24,7 +23,6 @@ interface SessionCardProps {
export const SessionCard = ({
session,
isSelected,
- isActive,
manageMode,
isPinned,
onTogglePin,
@@ -71,9 +69,7 @@ export const SessionCard = ({
} ${
isSelected
? "border-primary shadow-lg shadow-primary/30 bg-accent"
- : isActive
- ? "bg-accent border-border"
- : "bg-card border-border hover:bg-accent hover:border-border"
+ : "bg-card border-border hover:bg-accent hover:border-border"
} hover:shadow-lg`}
onClick={() => {
if (!isOpen) {
diff --git a/frontend/src/components/session/SessionList.test.tsx b/frontend/src/components/session/SessionList.test.tsx
index f2d20999..e445c323 100644
--- a/frontend/src/components/session/SessionList.test.tsx
+++ b/frontend/src/components/session/SessionList.test.tsx
@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { SessionList } from './SessionList'
-const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
+const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, isLoadingRef, isPlaceholderDataRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
createSessionMock: vi.fn(),
deleteSessionMock: vi.fn(),
sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
@@ -14,8 +14,10 @@ const { createSessionMock, deleteSessionMock, sessionsData, createSessionState,
hasNextPageRef: { current: false },
isFetchingNextPageRef: { current: false },
isFetchNextPageErrorRef: { current: false },
+ isLoadingRef: { current: false },
+ isPlaceholderDataRef: { current: false },
useRealSessionsHookRef: { current: false },
- lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number } } | undefined },
+ lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean } } | undefined },
sessionPinsData: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
togglePinMock: vi.fn(),
}))
@@ -24,15 +26,19 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal()
return {
...actual,
- useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number }) => {
+ useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean }) => {
if (useRealSessionsHookRef.current) {
return actual.useSessionsAcrossDirectories(directories, options)
}
lastSessionsHookArgs.current = { directories, options }
- const data = options?.search ? [] : sessionsData
+ const search = options?.search?.toLowerCase() ?? ''
+ const data = search
+ ? sessionsData.filter((session) => session.title.toLowerCase().includes(search))
+ : sessionsData
return {
data,
- isLoading: false,
+ isLoading: isLoadingRef.current,
+ isPlaceholderData: isPlaceholderDataRef.current,
fetchNextPage: fetchNextPageMock,
hasNextPage: hasNextPageRef.current,
isFetchingNextPage: isFetchingNextPageRef.current,
@@ -67,6 +73,8 @@ describe('SessionList', () => {
hasNextPageRef.current = false
isFetchingNextPageRef.current = false
isFetchNextPageErrorRef.current = false
+ isLoadingRef.current = false
+ isPlaceholderDataRef.current = false
useRealSessionsHookRef.current = false
lastSessionsHookArgs.current = undefined
sessionPinsData.splice(0, sessionPinsData.length)
@@ -551,4 +559,161 @@ describe('SessionList', () => {
vi.unstubAllGlobals()
}
})
+
+ it('filters rows by title immediately and keeps the search input focused', async () => {
+ const user = userEvent.setup()
+ sessionsData.splice(0, sessionsData.length,
+ { id: 'ses_alpha', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 2 } },
+ { id: 'ses_beta', title: 'beta task', location: { directory: '/w/a' }, time: { updated: 1 } },
+ )
+
+ render(
+ ,
+ )
+
+ const searchInput = screen.getByPlaceholderText('Search sessions...')
+ await user.click(searchInput)
+ await user.type(searchInput, 'alpha')
+
+ expect(screen.getByText('alpha task')).toBeTruthy()
+ expect(screen.queryByText('beta task')).toBeNull()
+ expect(searchInput).toHaveFocus()
+ })
+
+ it('keeps the search input rendered while the first page is loading', () => {
+ isLoadingRef.current = true
+
+ render(
+ ,
+ )
+
+ expect(screen.getByPlaceholderText('Search sessions...')).toBeTruthy()
+ expect(screen.getByText('Loading sessions...')).toBeTruthy()
+ })
+
+ it('keeps previous rows and the search input mounted while a new search query is fetching', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+
+ const initialItems = [
+ { id: 'ses_a', projectID: 'proj_1', title: 'alpha session', time: { created: 1, updated: 1 }, location: { directory: '/w/a' } },
+ { id: 'ses_b', projectID: 'proj_1', title: 'beta session', time: { created: 2, updated: 2 }, location: { directory: '/w/a' } },
+ ]
+
+ let resolveSearch: ((response: Response) => void) | undefined
+ fetchMock.mockImplementation((input: RequestInfo | URL) => {
+ const url = String(input)
+ if (url.includes('search=beta')) {
+ return new Promise((resolve) => {
+ resolveSearch = resolve
+ })
+ }
+ return Promise.resolve(new Response(JSON.stringify({ data: initialItems, cursor: {} }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }))
+ })
+
+ useRealSessionsHookRef.current = true
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ {children}
+ )
+
+ try {
+ render(
+ ,
+ { wrapper },
+ )
+
+ await waitFor(() => {
+ expect(screen.getByText('beta session')).toBeTruthy()
+ })
+
+ await userEvent.setup().type(screen.getByPlaceholderText('Search sessions...'), 'beta')
+
+ await waitFor(() => {
+ expect(resolveSearch).toBeDefined()
+ })
+
+ expect(screen.getByText('beta session')).toBeTruthy()
+ expect(screen.getByPlaceholderText('Search sessions...')).toBeTruthy()
+ expect(screen.queryByText('Loading sessions...')).toBeNull()
+
+ resolveSearch?.(new Response(JSON.stringify({
+ data: [{ id: 'ses_b', projectID: 'proj_1', title: 'beta session', time: { created: 2, updated: 2 }, location: { directory: '/w/a' } }],
+ cursor: {},
+ }), { status: 200, headers: { 'Content-Type': 'application/json' } }))
+
+ await waitFor(() => {
+ expect(screen.queryByText('alpha session')).toBeNull()
+ })
+ expect(screen.getByText('beta session')).toBeTruthy()
+ } finally {
+ queryClient.clear()
+ vi.unstubAllGlobals()
+ }
+ })
+
+ it('shows the searching state while a search is pending and the empty state once it settles', async () => {
+ const user = userEvent.setup()
+ sessionsData.splice(0, sessionsData.length,
+ { id: 'ses_a', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 1 } },
+ )
+
+ render(
+ ,
+ )
+
+ await user.type(screen.getByPlaceholderText('Search sessions...'), 'zzz')
+
+ expect(screen.getByText('Searching sessions...')).toBeTruthy()
+ expect(screen.queryByText('No sessions found')).toBeNull()
+
+ await waitFor(() => {
+ expect(screen.getByText('No sessions found')).toBeTruthy()
+ })
+ expect(screen.queryByText('Searching sessions...')).toBeNull()
+ })
+
+ it('does not paginate while placeholder data is shown', async () => {
+ const user = userEvent.setup()
+ isPlaceholderDataRef.current = true
+ hasNextPageRef.current = true
+ sessionsData.splice(0, sessionsData.length,
+ { id: 'ses_a', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 1 } },
+ )
+
+ render(
+ ,
+ )
+
+ const scrollContainer = screen.getByRole('region', { name: 'Sessions' })
+ Object.defineProperty(scrollContainer, 'scrollHeight', { value: 1000, configurable: true })
+ Object.defineProperty(scrollContainer, 'clientHeight', { value: 500, configurable: true })
+ Object.defineProperty(scrollContainer, 'scrollTop', { value: 300, configurable: true })
+
+ await user.type(screen.getByPlaceholderText('Search sessions...'), 'zzz')
+ fireEvent.scroll(scrollContainer)
+
+ expect(screen.getByText('Searching sessions...')).toBeTruthy()
+
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ expect(fetchNextPageMock).not.toHaveBeenCalled()
+ })
})
diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx
index a1bebb2d..711cab56 100644
--- a/frontend/src/components/session/SessionList.tsx
+++ b/frontend/src/components/session/SessionList.tsx
@@ -1,22 +1,22 @@
import { useCallback, useState, useMemo, useEffect, useRef, type ReactNode } from "react";
-import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
+import { useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
import type { Session } from "@/api/types";
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins';
-import { buildSessionKey, buildPinnedSessionKeys } from '@/lib/sessionKey';
-import { partitionSessions, selectRootSessions } from './session-partition';
+import { getSessionKey, buildPinnedSessionKeys } from '@/lib/sessionKey';
+import { partitionSessions } from './session-partition';
import { DeleteSessionDialog } from "./DeleteSessionDialog";
import { SessionCard } from "./SessionCard";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Search, Trash2, Pencil, X } from "lucide-react";
+import { useSessionSearch } from "@/hooks/useSessionSearch";
interface SessionListProps {
directory?: string;
directories?: string[];
createDirectory?: string;
- activeSessionID?: string;
onSelectSession: (sessionID: string) => void;
renderSessions?: (args: SessionListRenderArgs) => ReactNode;
}
@@ -35,7 +35,6 @@ export const SessionList = ({
directory,
directories,
createDirectory,
- activeSessionID,
onSelectSession,
renderSessions,
}: SessionListProps) => {
@@ -43,14 +42,23 @@ export const SessionList = ({
const source = directories && directories.length > 0 ? directories : directory ? [directory] : [];
return Array.from(new Set(source.filter(Boolean)));
}, [directory, directories]);
- const directorySet = useMemo(() => new Set(directoriesList), [directoriesList]);
const primaryDirectory = directoriesList[0];
const sessionCreateDirectory = createDirectory ?? primaryDirectory;
- const getSessionSelectionKey = useCallback((session: Session) =>
- buildSessionKey(session.location.directory, session.id),
- []);
- const [searchQuery, setSearchQuery] = useState("");
- const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(directoriesList, { search: searchQuery, limit: 25 });
+ const {
+ query,
+ setQuery,
+ trimmedQuery,
+ sessions,
+ filteredSessions,
+ isSearchPending,
+ isLoading,
+ isPlaceholderData,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ canFetchNextPage,
+ } = useSessionSearch(directoriesList);
const deleteSession = useDeleteSession(directoriesList);
const createSession = useCreateSession(sessionCreateDirectory, (newSession) => {
onSelectSession(newSession.id);
@@ -67,19 +75,14 @@ export const SessionList = ({
const [manageMode, setManageMode] = useState(false);
const sessionListRef = useRef(null);
- const filteredSessions = useMemo(
- () => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }),
- [sessions, directorySet, getSessionSelectionKey],
- );
-
const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo(
- () => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey),
- [filteredSessions, pinnedKeys, getSessionSelectionKey],
+ () => partitionSessions(filteredSessions, pinnedKeys, getSessionKey),
+ [filteredSessions, pinnedKeys],
);
const handleTogglePin = (session: Session) => {
const directory = session.location.directory;
- const key = getSessionSelectionKey(session);
+ const key = getSessionKey(session);
togglePin.mutate({ sessionId: session.id, directory, pinned: !pinnedKeys.has(key) });
};
@@ -89,63 +92,20 @@ export const SessionList = ({
const handleSessionsScroll = useCallback((event: React.UIEvent) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
- if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage && !isFetchNextPageError) {
+ if (scrollHeight - scrollTop - clientHeight <= 240 && canFetchNextPage) {
void fetchNextPage();
}
- }, [hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
+ }, [canFetchNextPage, fetchNextPage]);
useEffect(() => {
const sessionList = sessionListRef.current;
const isNearBottom = sessionList
? sessionList.scrollHeight - sessionList.scrollTop - sessionList.clientHeight <= 240
: filteredSessions.length === 0;
- if (
- !isLoading
- && isNearBottom
- && hasNextPage
- && !isFetchingNextPage
- && !isFetchNextPageError
- ) {
+ if (!isLoading && isNearBottom && canFetchNextPage) {
void fetchNextPage();
}
- }, [isLoading, filteredSessions, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
-
- if (isLoading && !renderSessions) {
- return Loading sessions...
;
- }
-
- if (!sessions || sessions.length === 0) {
- if (isFetchNextPageError) {
- return (
-
-
Failed to load sessions.
-
- Retry
-
-
- );
- }
- if ((hasNextPage || isFetchingNextPage) && !renderSessions) {
- return Loading sessions...
;
- }
- if (!searchQuery.trim() && !renderSessions) {
- return (
-
-
createSession.mutate({ agent: undefined })}
- >
-
-
No sessions yet
-
- Click here to start a new session
-
-
-
-
- );
- }
- }
+ }, [isLoading, filteredSessions, canFetchNextPage, fetchNextPage]);
const getDeleteTarget = (session: Session): DeleteSessionTarget => ({
id: session.id,
@@ -176,7 +136,7 @@ export const SessionList = ({
};
const toggleSessionSelection = (session: Session, selected: boolean) => {
- const selectionKey = getSessionSelectionKey(session);
+ const selectionKey = getSessionKey(session);
const newSelected = new Set(selectedSessions);
if (selected) {
newSelected.add(selectionKey);
@@ -188,20 +148,20 @@ export const SessionList = ({
const allVisibleSelected =
filteredSessions.length > 0 &&
- filteredSessions.every((session) => selectedSessions.has(getSessionSelectionKey(session)));
+ filteredSessions.every((session) => selectedSessions.has(getSessionKey(session)));
const toggleSelectAll = () => {
if (allVisibleSelected) {
setSelectedSessions(new Set());
} else {
- setSelectedSessions(new Set(filteredSessions.map(getSessionSelectionKey)));
+ setSelectedSessions(new Set(filteredSessions.map(getSessionKey)));
}
};
const handleBulkDelete = () => {
if (selectedSessions.size > 0) {
const selectedTargets = filteredSessions
- .filter((session) => selectedSessions.has(getSessionSelectionKey(session)))
+ .filter((session) => selectedSessions.has(getSessionKey(session)))
.map(getDeleteTarget);
if (selectedTargets.length === 0) return;
setSessionToDelete(selectedTargets);
@@ -210,13 +170,12 @@ export const SessionList = ({
};
const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => {
- const key = getSessionSelectionKey(session);
+ const key = getSessionKey(session);
return (
+ Failed to load sessions.
+
+ Retry
+
+
+ );
+ }
+ if ((hasNextPage || isFetchingNextPage) && !renderSessions) {
+ return
Loading sessions...
;
+ }
+ if (!trimmedQuery && !renderSessions) {
+ return (
+
+
createSession.mutate({ agent: undefined })}
+ >
+
+
No sessions yet
+
+ Click here to start a new session
+
+
+
+
+ );
+ }
+ }
+
return (
@@ -264,8 +256,8 @@ export const SessionList = ({
setSearchQuery(e.target.value)}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
className="pl-9 h-9"
autoComplete="off"
name="session-search"
@@ -294,15 +286,17 @@ export const SessionList = ({
onScroll={handleSessionsScroll}
>
- {renderSessions ? (
+ {isLoading && !renderSessions ? (
+
Loading sessions...
+ ) : renderSessions ? (
renderSessions({
sessions: filteredSessions,
- searchQuery,
- renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionSelectionKey(session))),
+ searchQuery: query,
+ renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionKey(session))),
})
) : filteredSessions.length === 0 && !isFetchingNextPage ? (
- No sessions found
+ {isSearchPending ? 'Searching sessions...' : 'No sessions found'}
) : (
<>
@@ -331,7 +325,7 @@ export const SessionList = ({
{olderSessions.map((session) => renderSessionCard(session, false))}
>
)}
- {isFetchNextPageError && (
+ {isFetchNextPageError && (sessions?.length ?? 0) > 0 && (
Failed to load more sessions.
@@ -339,7 +333,7 @@ export const SessionList = ({
)}
- {isFetchingNextPage && (
+ {isFetchingNextPage && (sessions?.length ?? 0) > 0 && (
Loading more sessions...
diff --git a/frontend/src/components/session/SessionPickerDialog.test.tsx b/frontend/src/components/session/SessionPickerDialog.test.tsx
new file mode 100644
index 00000000..747b29aa
--- /dev/null
+++ b/frontend/src/components/session/SessionPickerDialog.test.tsx
@@ -0,0 +1,363 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useState } from 'react'
+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 { SessionPickerDialog } from './SessionPickerDialog'
+
+const mocks = vi.hoisted(() => ({
+ sessionsData: [] as Session[],
+ lastDirectories: [] as string[],
+ lastAllDirectories: false,
+ sessionsHook: vi.fn(),
+ fetchNextPage: vi.fn(),
+ deleteSessionMock: vi.fn(),
+ togglePinMock: vi.fn(),
+ sessionPins: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
+ repos: [] as Repo[],
+}))
+
+vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
+ const actual = await importOriginal
()
+ return {
+ ...actual,
+ useSessionsAcrossDirectories: (
+ directories: string[],
+ options?: { search?: string; allDirectories?: boolean },
+ ) => {
+ mocks.sessionsHook()
+ mocks.lastDirectories = directories
+ mocks.lastAllDirectories = options?.allDirectories ?? false
+ const search = options?.search?.toLowerCase() ?? ''
+ const data = search
+ ? mocks.sessionsData.filter((session) => (session.title ?? '').toLowerCase().includes(search))
+ : mocks.sessionsData
+ return {
+ data,
+ isLoading: false,
+ isPlaceholderData: false,
+ fetchNextPage: mocks.fetchNextPage,
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ isFetchNextPageError: false,
+ }
+ },
+ useDeleteSession: () => ({ mutateAsync: mocks.deleteSessionMock, isPending: false }),
+ }
+})
+
+vi.mock('@/hooks/useSessionPins', () => ({
+ useSessionPins: () => ({ data: mocks.sessionPins }),
+ useToggleSessionPin: () => ({ mutate: mocks.togglePinMock }),
+}))
+
+vi.mock('@/hooks/useSidebarRepoGroups', () => ({
+ useNavigableRepos: () => ({ repos: mocks.repos, isLoading: false, refetch: vi.fn() }),
+}))
+
+vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
+ const actual = await importOriginal()
+ return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
+})
+
+function session(id: string, title: string, directory: string, updated = Date.now()): Session {
+ return {
+ id,
+ projectID: 'proj',
+ title,
+ time: { created: updated, updated },
+ location: { directory },
+ cost: 0,
+ tokens: {},
+ } as unknown as Session
+}
+
+function repo(id: number, name: string, fullPath: string): Repo {
+ return {
+ id,
+ name,
+ localPath: fullPath,
+ fullPath,
+ defaultBranch: 'main',
+ cloneStatus: 'ready',
+ clonedAt: 0,
+ }
+}
+
+function renderPicker(overrides: Partial> = {}) {
+ const onOpenChange = vi.fn()
+ const onSelectSession = vi.fn()
+ const onDeleteActiveSession = vi.fn()
+ render(
+ ,
+ )
+ return { onOpenChange, onSelectSession, onDeleteActiveSession }
+}
+
+const combobox = () => screen.getByRole('combobox')
+
+describe('SessionPickerDialog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ stubMatchMedia(true)
+ localStorage.clear()
+ mocks.deleteSessionMock.mockResolvedValue(undefined)
+ mocks.sessionPins = []
+ mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
+ mocks.sessionsData = []
+ })
+
+ afterEach(() => {
+ Reflect.deleteProperty(window, 'matchMedia')
+ })
+
+ it('opens with the active session as the cursor and marks it with a dot', () => {
+ mocks.sessionsData = [
+ session('ses_active', 'Active session', '/w/a', 3000),
+ session('ses_other', 'Other session', '/w/a', 2000),
+ ]
+
+ renderPicker({ activeSessionID: 'ses_active' })
+
+ const active = screen.getByRole('option', { name: /Active session/ })
+ const other = screen.getByRole('option', { name: /Other session/ })
+ expect(active).toHaveAttribute('aria-selected', 'true')
+ expect(active.textContent).toContain('●')
+ expect(other).toHaveAttribute('aria-selected', 'false')
+ })
+
+ it('filters rows immediately as the query is typed', () => {
+ mocks.sessionsData = [
+ session('ses_alpha', 'alpha task', '/w/a', 2000),
+ session('ses_beta', 'beta task', '/w/a', 1000),
+ ]
+
+ renderPicker()
+
+ fireEvent.change(combobox(), { target: { value: 'beta' } })
+
+ expect(screen.queryByText('alpha task')).not.toBeInTheDocument()
+ expect(screen.getByText('beta task')).toBeInTheDocument()
+ })
+
+ it('moves the cursor with arrow keys and Ctrl+N/Ctrl+P, wrapping, and opens the row on Enter', () => {
+ mocks.sessionsData = [
+ session('ses_1', 'First', '/w/a', 3000),
+ session('ses_2', 'Second', '/w/a', 2000),
+ session('ses_3', 'Third', '/w/a', 1000),
+ ]
+ const { onSelectSession } = renderPicker()
+
+ const first = screen.getByRole('option', { name: /First/ })
+ const second = screen.getByRole('option', { name: /Second/ })
+ const third = screen.getByRole('option', { name: /Third/ })
+
+ expect(first).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
+ expect(second).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
+ expect(first).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
+ expect(third).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'n', ctrlKey: true })
+ expect(first).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'p', ctrlKey: true })
+ expect(third).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'Enter' })
+ expect(onSelectSession).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'ses_3' }),
+ mocks.repos[0],
+ )
+ })
+
+ it('toggles scope with Ctrl+A, persists it, queries every repo directory and shows repo labels', () => {
+ mocks.sessionsData = [
+ session('ses_a', 'Alpha session', '/w/a', 2000),
+ session('ses_b', 'Beta session', '/w/b', 1000),
+ ]
+
+ renderPicker()
+
+ expect(mocks.lastDirectories).toEqual(['/w/a'])
+ expect(mocks.lastAllDirectories).toBe(false)
+ expect(screen.getByText('Alpha session')).toBeInTheDocument()
+ expect(screen.queryByText('Beta session')).not.toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'a', ctrlKey: true })
+
+ expect(mocks.lastDirectories).toEqual(['/w/a', '/w/b'])
+ expect(mocks.lastAllDirectories).toBe(true)
+ expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('true')
+ expect(screen.getByText('Beta session')).toBeInTheDocument()
+ expect(screen.getByText('alpha')).toBeInTheDocument()
+ expect(screen.getByText('beta')).toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'a', ctrlKey: true })
+ expect(mocks.lastDirectories).toEqual(['/w/a'])
+ expect(mocks.lastAllDirectories).toBe(false)
+ expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('false')
+ })
+
+ it('does not query sessions while closed and queries after opening', async () => {
+ mocks.sessionsData = [session('ses_1', 'First', '/w/a', 3000)]
+
+ function Host() {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ setOpen(true)}>open-picker
+
+ >
+ )
+ }
+
+ render( )
+
+ expect(mocks.sessionsHook).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByText('open-picker'))
+
+ await waitFor(() => expect(mocks.sessionsHook).toHaveBeenCalled())
+ })
+
+ it('deletes on a second Ctrl+D and clears the pending state on a move', async () => {
+ mocks.sessionsData = [
+ session('ses_1', 'First', '/w/a', 3000),
+ session('ses_2', 'Second', '/w/a', 2000),
+ ]
+ const { onDeleteActiveSession } = renderPicker()
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument()
+ expect(mocks.deleteSessionMock).not.toHaveBeenCalled()
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
+ expect(screen.queryByText('Press Ctrl+D again to confirm')).not.toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ expect(mocks.deleteSessionMock).toHaveBeenCalledWith({ id: 'ses_2', directory: '/w/a' })
+ expect(onDeleteActiveSession).not.toHaveBeenCalled()
+
+ await waitFor(() =>
+ expect(screen.queryByText('Press Ctrl+D again to confirm')).not.toBeInTheDocument(),
+ )
+ })
+
+ it('notifies when the active session is deleted before the delete completes', async () => {
+ mocks.sessionsData = [session('ses_active', 'Active', '/w/a', 3000)]
+ let resolveDelete: () => void = () => undefined
+ mocks.deleteSessionMock.mockReturnValue(
+ new Promise((resolve) => {
+ resolveDelete = resolve
+ }),
+ )
+ const { onDeleteActiveSession } = renderPicker({ activeSessionID: 'ses_active' })
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+
+ expect(mocks.deleteSessionMock).toHaveBeenCalledWith({ id: 'ses_active', directory: '/w/a' })
+ await waitFor(() => expect(onDeleteActiveSession).toHaveBeenCalled())
+
+ await act(async () => {
+ resolveDelete()
+ })
+ })
+
+ it('moves the cursor when a mouse pointer moves over a row', () => {
+ mocks.sessionsData = [
+ session('ses_1', 'First', '/w/a', 3000),
+ session('ses_2', 'Second', '/w/a', 2000),
+ ]
+ renderPicker()
+
+ const second = screen.getByRole('option', { name: /Second/ })
+ const pointerMove = new Event('pointermove', { bubbles: true })
+ Object.defineProperty(pointerMove, 'pointerType', { value: 'mouse' })
+ fireEvent(second, pointerMove)
+
+ expect(second).toHaveAttribute('aria-selected', 'true')
+ })
+
+ it('opens the delete confirmation from the row menu', async () => {
+ mocks.sessionsData = [session('ses_1', 'First', '/w/a', 3000)]
+ renderPicker()
+ const user = userEvent.setup()
+
+ await user.click(screen.getByRole('button', { name: 'Session actions' }))
+ await user.click(await screen.findByText('Delete'))
+
+ expect(await screen.findByRole('dialog', { name: 'Delete Session' })).toBeInTheDocument()
+ })
+
+ it('groups older sessions under per-day headings', () => {
+ mocks.sessionsData = [
+ session('ses_jan2', 'Jan two', '/w/a', new Date(2020, 0, 2, 12).getTime()),
+ session('ses_jan1', 'Jan one', '/w/a', new Date(2020, 0, 1, 12).getTime()),
+ ]
+
+ renderPicker()
+
+ expect(screen.getByText('Thu, Jan 2, 2020')).toBeInTheDocument()
+ expect(screen.getByText('Wed, Jan 1, 2020')).toBeInTheDocument()
+ })
+
+ it('resets the query and cursor on reopen', async () => {
+ mocks.sessionsData = [
+ session('ses_active', 'Active session', '/w/a', 3000),
+ session('ses_other', 'Other session', '/w/a', 2000),
+ ]
+
+ function Host() {
+ const [open, setOpen] = useState(true)
+ return (
+ <>
+ setOpen(false)}>close-picker
+ setOpen(true)}>open-picker
+
+ >
+ )
+ }
+
+ render( )
+
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Other' } })
+ expect(screen.queryByText('Active session')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('close-picker'))
+ fireEvent.click(screen.getByText('open-picker'))
+
+ await waitFor(() => expect(screen.getByRole('combobox')).toHaveValue(''))
+ expect(screen.getByRole('option', { name: /Active session/ })).toHaveAttribute('aria-selected', 'true')
+ })
+})
diff --git a/frontend/src/components/session/SessionPickerDialog.tsx b/frontend/src/components/session/SessionPickerDialog.tsx
new file mode 100644
index 00000000..7994aa19
--- /dev/null
+++ b/frontend/src/components/session/SessionPickerDialog.tsx
@@ -0,0 +1,655 @@
+import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
+import { format, startOfDay } from 'date-fns'
+import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
+import type { Repo, Session } from '@/api/types'
+import { Button } from '@/components/ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { Input } from '@/components/ui/input'
+import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
+import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
+import { partitionSessions } from '@/components/session/session-partition'
+import { buildRepoByDirectory } from '@/components/navigation/sidebar-session-tree'
+import { useDeleteSession } from '@/hooks/useOpenCode'
+import { useSessionSearch } from '@/hooks/useSessionSearch'
+import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
+import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
+import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
+import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
+import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey'
+import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils'
+import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
+
+const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects'
+const UNTITLED_SESSION_TITLE = 'Untitled Session'
+const PAGE_STEP = 10
+const NEAR_BOTTOM_PX = 240
+
+interface SessionPickerDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ currentRepo: Repo | undefined
+ activeSessionID?: string
+ onSelectSession: (session: Session, repo: Repo) => void
+ onDeleteActiveSession: () => void
+}
+
+interface SessionPickerRow {
+ key: string
+ session: Session
+ repo: Repo
+}
+
+interface SessionPickerSection {
+ id: string
+ heading: string
+ rows: SessionPickerRow[]
+}
+
+function buildSections(
+ sessions: Session[],
+ pinnedKeys: ReadonlySet,
+ keyFn: (session: Session) => string,
+ resolveRepo: (session: Session) => Repo | undefined,
+): SessionPickerSection[] {
+ const { pinned, today, older } = partitionSessions(sessions, pinnedKeys, keyFn)
+ const toRows = (group: Session[]): SessionPickerRow[] =>
+ group.flatMap((session) => {
+ const repo = resolveRepo(session)
+ return repo ? [{ key: keyFn(session), session, repo }] : []
+ })
+
+ const sections: SessionPickerSection[] = []
+ const pinnedRows = toRows(pinned)
+ if (pinnedRows.length > 0) sections.push({ id: 'pinned', heading: 'Pinned', rows: pinnedRows })
+ const todayRows = toRows(today)
+ if (todayRows.length > 0) sections.push({ id: 'today', heading: 'Today', rows: todayRows })
+
+ const currentYear = new Date().getFullYear()
+ const byDay = new Map()
+ for (const row of toRows(older)) {
+ const day = startOfDay(new Date(row.session.time.updated)).getTime()
+ const existing = byDay.get(day)
+ if (existing) existing.push(row)
+ else byDay.set(day, [row])
+ }
+ for (const [day, rows] of byDay) {
+ const date = new Date(day)
+ const heading =
+ date.getFullYear() === currentYear ? format(date, 'EEE, MMM d') : format(date, 'EEE, MMM d, yyyy')
+ sections.push({ id: `day-${day}`, heading, rows })
+ }
+ return sections
+}
+
+function optionId(baseId: string, index: number): string {
+ return `${baseId}-option-${index}`
+}
+
+function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isActive: boolean }) {
+ const status = useSessionStatusForSession(sessionID)
+ if (status.type !== 'idle') {
+ return (
+
+ )
+ }
+ if (isActive) {
+ return ●
+ }
+ return null
+}
+
+interface SessionPickerRowItemProps {
+ row: SessionPickerRow
+ index: number
+ optionId: string
+ isCursor: boolean
+ isActive: boolean
+ isPinned: boolean
+ isPendingDelete: boolean
+ showRepo: boolean
+ onOpen: (row: SessionPickerRow) => void
+ onHover: (index: number) => void
+ onTogglePin: (row: SessionPickerRow) => void
+ onRequestDelete: (session: Session) => void
+ registerRef: (key: string, node: HTMLDivElement | null) => void
+}
+
+const SessionPickerRowItem = memo(function SessionPickerRowItem({
+ row,
+ index,
+ optionId,
+ isCursor,
+ isActive,
+ isPinned,
+ isPendingDelete,
+ showRepo,
+ onOpen,
+ onHover,
+ onTogglePin,
+ onRequestDelete,
+ registerRef,
+}: SessionPickerRowItemProps) {
+ return (
+ registerRef(row.key, node)}
+ role="presentation"
+ onPointerMove={(event) => {
+ if (event.pointerType === 'mouse') onHover(index)
+ }}
+ className={cn(
+ 'group flex items-center rounded-md text-sm min-h-8 pointer-coarse:min-h-11',
+ isPendingDelete
+ ? 'bg-destructive text-destructive-foreground'
+ : isCursor
+ ? 'bg-primary text-primary-foreground'
+ : 'hover:bg-accent',
+ )}
+ >
+
onOpen(row)}
+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2"
+ >
+
+
+
+
+ {isPendingDelete ? 'Press Ctrl+D again to confirm' : row.session.title || UNTITLED_SESSION_TITLE}
+
+
+ {showRepo && {getRepoDisplayName(row.repo)} }
+ {formatShortRelativeTime(new Date(row.session.time.updated))}
+
+
+
+
+
+ event.stopPropagation()}
+ className={cn(
+ 'h-7 w-7 p-0 shrink-0 pointer-coarse:h-11 pointer-coarse:w-11 pointer-coarse:opacity-100',
+ isCursor || isPendingDelete ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100',
+ )}
+ >
+
+
+
+ event.stopPropagation()}>
+ onTogglePin(row)}>
+ {isPinned ? : }
+ {isPinned ? 'Unpin' : 'Pin'}
+
+ onRequestDelete(row.session)}>Delete
+
+
+
+
+ )
+})
+
+interface SessionPickerContentProps {
+ open: boolean
+ currentRepo: Repo | undefined
+ activeSessionID?: string
+ onSelectSession: (session: Session, repo: Repo) => void
+ onDeleteActiveSession: () => void
+ searchInputRef: React.RefObject
+ hasFinePointer: boolean
+}
+
+function SessionPickerContent({
+ open,
+ currentRepo,
+ activeSessionID,
+ onSelectSession,
+ onDeleteActiveSession,
+ searchInputRef,
+ hasFinePointer,
+}: SessionPickerContentProps) {
+ const [allProjects, toggleAllProjects] = usePersistentBoolean(ALL_PROJECTS_STORAGE_KEY, false)
+ const { repos } = useNavigableRepos()
+ const listRef = useRef(null)
+ const rowRefs = useRef(new Map())
+ const listId = useId()
+ const optionBaseId = useId()
+
+ const repoByDirectory = useMemo(() => {
+ const map = buildRepoByDirectory(repos)
+ if (currentRepo) map.set(currentRepo.fullPath, currentRepo)
+ return map
+ }, [repos, currentRepo])
+
+ const directories = useMemo(() => {
+ if (!allProjects) return currentRepo ? [currentRepo.fullPath] : []
+ const paths = repos.map((repo) => repo.fullPath)
+ if (currentRepo) paths.push(currentRepo.fullPath)
+ return Array.from(new Set(paths))
+ }, [allProjects, repos, currentRepo])
+
+ const {
+ query,
+ setQuery,
+ trimmedQuery,
+ filteredSessions,
+ isSearchPending,
+ isLoading,
+ fetchNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ canFetchNextPage,
+ } = useSessionSearch(directories, { allDirectories: allProjects })
+
+ const resolveRepo = useCallback(
+ (session: Session) => repoByDirectory.get(session.location.directory) ?? currentRepo,
+ [repoByDirectory, currentRepo],
+ )
+
+ const { data: sessionPins } = useSessionPins()
+ const togglePin = useToggleSessionPin()
+ const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
+ const deleteSession = useDeleteSession(directories)
+
+ const [cursorKey, setCursorKey] = useState(null)
+ const [pendingDeleteKey, setPendingDeleteKey] = useState(null)
+ const [sessionToDelete, setSessionToDelete] = useState(null)
+
+ const sections = useMemo(
+ () => buildSections(filteredSessions, pinnedKeys, getSessionKey, resolveRepo),
+ [filteredSessions, pinnedKeys, resolveRepo],
+ )
+ const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
+ const rowIndexByKey = useMemo(
+ () => new Map(rows.map((row, index) => [row.key, index])),
+ [rows],
+ )
+
+ const activeRow = useMemo(
+ () => rows.find((row) => row.session.id === activeSessionID),
+ [rows, activeSessionID],
+ )
+ const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
+ const cursorIndex = useMemo(() => {
+ if (cursorKey) {
+ const index = rowIndexByKey.get(cursorKey)
+ if (index !== undefined) return index
+ }
+ return defaultCursorKey ? rowIndexByKey.get(defaultCursorKey) ?? -1 : -1
+ }, [cursorKey, rowIndexByKey, defaultCursorKey])
+ const cursorRow = cursorIndex >= 0 ? rows[cursorIndex] : undefined
+
+ useEffect(() => {
+ setCursorKey(null)
+ setPendingDeleteKey(null)
+ }, [trimmedQuery, allProjects])
+
+ const setRowRef = useCallback((key: string, node: HTMLDivElement | null) => {
+ if (node) rowRefs.current.set(key, node)
+ else rowRefs.current.delete(key)
+ }, [])
+
+ useEffect(() => {
+ if (!cursorRow) return
+ const node = rowRefs.current.get(cursorRow.key)
+ if (node && typeof node.scrollIntoView === 'function') {
+ node.scrollIntoView({ block: 'nearest' })
+ }
+ }, [cursorRow])
+
+ const moveCursor = useCallback(
+ (index: number) => {
+ const row = rows[index]
+ if (!row) return
+ setCursorKey(row.key)
+ setPendingDeleteKey(null)
+ },
+ [rows],
+ )
+
+ const openRow = useCallback(
+ (row: SessionPickerRow | undefined) => {
+ if (!row) return
+ onSelectSession(row.session, row.repo)
+ },
+ [onSelectSession],
+ )
+
+ const performDelete = useCallback(
+ (session: Session) => {
+ if (session.id === activeSessionID) onDeleteActiveSession()
+ return deleteSession
+ .mutateAsync({ id: session.id, directory: session.location.directory })
+ .catch(() => undefined)
+ },
+ [deleteSession, activeSessionID, onDeleteActiveSession],
+ )
+
+ const deleteRow = useCallback(
+ (row: SessionPickerRow | undefined) => {
+ if (!row) return
+ if (pendingDeleteKey !== row.key) {
+ setPendingDeleteKey(row.key)
+ return
+ }
+ void performDelete(row.session).finally(() => {
+ setPendingDeleteKey(null)
+ })
+ },
+ [pendingDeleteKey, performDelete],
+ )
+
+ const handleSearchKeyDown = useCallback(
+ (event: React.KeyboardEvent) => {
+ if (event.nativeEvent.isComposing) return
+ if (event.metaKey || event.altKey) return
+
+ const moveBy = (delta: number, wrap: boolean) => {
+ if (rows.length === 0) return
+ const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
+ const raw = base + delta
+ const next = wrap ? ((raw % rows.length) + rows.length) % rows.length : Math.max(0, Math.min(rows.length - 1, raw))
+ moveCursor(next)
+ }
+
+ const key = event.key
+ const ctrlKey = event.key.toLowerCase()
+
+ 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 (!cursorRow) return
+ event.preventDefault()
+ openRow(cursorRow)
+ return
+ }
+ if (event.ctrlKey && ctrlKey === 'a') {
+ event.preventDefault()
+ toggleAllProjects()
+ return
+ }
+ if (event.ctrlKey && ctrlKey === 'd') {
+ if (!cursorRow) return
+ event.preventDefault()
+ deleteRow(cursorRow)
+ }
+ },
+ [cursorIndex, rows, moveCursor, cursorRow, openRow, toggleAllProjects, deleteRow],
+ )
+
+ const handleListScroll = useCallback(
+ (event: React.UIEvent) => {
+ const { scrollTop, scrollHeight, clientHeight } = event.currentTarget
+ if (scrollHeight - scrollTop - clientHeight <= NEAR_BOTTOM_PX && canFetchNextPage) {
+ void fetchNextPage()
+ }
+ },
+ [canFetchNextPage, fetchNextPage],
+ )
+
+ useEffect(() => {
+ if (!open) return
+ const node = listRef.current
+ const isNearBottom = node
+ ? node.scrollHeight - node.scrollTop - node.clientHeight <= NEAR_BOTTOM_PX
+ : rows.length === 0
+ if (!isLoading && isNearBottom && canFetchNextPage) {
+ void fetchNextPage()
+ }
+ }, [open, isLoading, rows, canFetchNextPage, fetchNextPage])
+
+ const handleTogglePin = useCallback(
+ (row: SessionPickerRow) => {
+ togglePin.mutate({
+ sessionId: row.session.id,
+ directory: row.session.location.directory,
+ pinned: !pinnedKeys.has(row.key),
+ })
+ },
+ [togglePin, pinnedKeys],
+ )
+
+ const handleRequestDelete = useCallback((session: Session) => {
+ setSessionToDelete(session)
+ }, [])
+
+ const confirmDelete = useCallback(() => {
+ if (!sessionToDelete) return
+ void performDelete(sessionToDelete).finally(() => {
+ setSessionToDelete(null)
+ })
+ }, [sessionToDelete, performDelete])
+
+ return (
+ <>
+
+ Sessions
+ {!allProjects && currentRepo && (
+ for {getRepoDisplayName(currentRepo)}
+ )}
+
+
+
+
+
+
+ = 0 ? optionId(optionBaseId, cursorIndex) : undefined}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={handleSearchKeyDown}
+ placeholder="Search sessions..."
+ className="h-9 pl-9"
+ autoComplete="off"
+ name="session-picker-search"
+ />
+
+
+ {allProjects ? 'All projects' : 'This project'}
+ {hasFinePointer && (
+
+ Ctrl+A
+
+ )}
+
+
+
+
+ {rows.length === 0 ? (
+
+ {isLoading
+ ? 'Loading sessions...'
+ : isSearchPending
+ ? 'Searching sessions...'
+ : trimmedQuery
+ ? 'No sessions found'
+ : 'No sessions yet'}
+
+ ) : (
+ <>
+ {sections.map((section) => (
+
+
+ {section.heading}
+
+ {section.rows.map((row) => {
+ const index = rowIndexByKey.get(row.key) ?? -1
+ return (
+
+ )
+ })}
+
+ ))}
+ {isFetchNextPageError && (
+
+
Failed to load more sessions
+
{
+ void fetchNextPage()
+ }}
+ disabled={isFetchingNextPage}
+ >
+ Retry
+
+
+ )}
+ {isFetchingNextPage && rows.length > 0 && (
+
Loading more sessions...
+ )}
+ >
+ )}
+
+
+
+ ↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
+
+
+
+ {
+ if (!nextOpen) setSessionToDelete(null)
+ }}
+ onConfirm={() => {
+ void confirmDelete()
+ }}
+ onCancel={() => setSessionToDelete(null)}
+ isDeleting={deleteSession.isPending}
+ />
+ >
+ )
+}
+
+export function SessionPickerDialog({
+ open,
+ onOpenChange,
+ currentRepo,
+ activeSessionID,
+ onSelectSession,
+ onDeleteActiveSession,
+}: SessionPickerDialogProps) {
+ const searchInputRef = useRef(null)
+ const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
+
+ return (
+
+ onOpenChange(false)}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault()
+ if (hasFinePointer) {
+ searchInputRef.current?.focus()
+ } else {
+ ;(event.currentTarget as HTMLElement).focus()
+ }
+ }}
+ >
+
+
+
+ )
+}
diff --git a/frontend/src/components/settings/KeyboardShortcuts.test.tsx b/frontend/src/components/settings/KeyboardShortcuts.test.tsx
index 5ccbe6e7..da4e65aa 100644
--- a/frontend/src/components/settings/KeyboardShortcuts.test.tsx
+++ b/frontend/src/components/settings/KeyboardShortcuts.test.tsx
@@ -1,9 +1,22 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
-import { render, screen, fireEvent, within } from '@testing-library/react'
+import { render, screen, fireEvent, within, waitFor } from '@testing-library/react'
import { KeyboardShortcuts } from './KeyboardShortcuts'
-import { DEFAULT_KEYBOARD_SHORTCUTS } from '@/api/types/settings'
+import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
-const { updateSettings } = vi.hoisted(() => ({ updateSettings: vi.fn() }))
+const { updateSettings, parseTuiKeybindConfig, applyTuiKeybindImport, showToast } = vi.hoisted(() => ({
+ updateSettings: vi.fn(),
+ parseTuiKeybindConfig: vi.fn(),
+ applyTuiKeybindImport: vi.fn(),
+ showToast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ loading: vi.fn(),
+ promise: vi.fn(),
+ dismiss: vi.fn(),
+ },
+}))
vi.mock('@/hooks/useMobile', () => ({ useMobile: () => false }))
vi.mock('@/hooks/useSettings', () => ({
@@ -13,6 +26,20 @@ vi.mock('@/hooks/useSettings', () => ({
updateSettings,
}),
}))
+vi.mock('@/lib/tuiKeybindImport', () => ({ parseTuiKeybindConfig, applyTuiKeybindImport }))
+vi.mock('@/lib/toast', () => ({ showToast }))
+
+const getFileInput = (container: HTMLElement) => {
+ const input = container.querySelector('input[type="file"]')
+ if (!input) throw new Error('file input not found')
+ return input as HTMLInputElement
+}
+
+const makeFile = (content: string, name: string) => {
+ const file = new File([content], name)
+ Object.defineProperty(file, 'text', { value: () => Promise.resolve(content) })
+ return file
+}
describe('KeyboardShortcuts layout', () => {
beforeEach(() => vi.clearAllMocks())
@@ -36,17 +63,118 @@ describe('KeyboardShortcuts layout', () => {
expect(screen.getByPlaceholderText('Press keys...')).toBe(input)
expect(input).toHaveFocus()
fireEvent.keyDown(input, { key: 'k', ctrlKey: true })
- expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: 'Ctrl+K' }) })
+ expect(updateSettings).toHaveBeenCalledWith({
+ keyboardShortcuts: expect.objectContaining({ customAction: 'Ctrl+K' }),
+ directShortcuts: [...DEFAULT_DIRECT_SHORTCUTS, 'customAction'],
+ })
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
})
+ it('records the leader key followed by a key as a leader shortcut', () => {
+ render( )
+ fireEvent.click(screen.getByRole('button', { name: /Ctrl\+T/ }))
+ const input = screen.getByPlaceholderText('Press keys...')
+
+ fireEvent.keyDown(input, { key: 'x', ctrlKey: true })
+ expect(updateSettings).not.toHaveBeenCalled()
+ expect(input).toHaveValue(`${DEFAULT_LEADER_KEY} → `)
+
+ fireEvent.keyDown(input, { key: 'v' })
+ expect(updateSettings).toHaveBeenCalledWith({
+ keyboardShortcuts: expect.objectContaining({ variantCycle: 'V' }),
+ directShortcuts: DEFAULT_DIRECT_SHORTCUTS.filter((action) => action !== 'variantCycle'),
+ })
+ })
+
it('preserves direct-toggle and clear actions in a grouped row', () => {
render( )
const row = screen.getByText('custom Action').parentElement!.parentElement!
fireEvent.click(within(row).getByRole('button', { name: 'Requires leader key (click to make direct)' }))
- expect(updateSettings).toHaveBeenCalledWith({ directShortcuts: ['submit', 'abort', 'customAction'] })
+ expect(updateSettings).toHaveBeenCalledWith({ directShortcuts: [...DEFAULT_DIRECT_SHORTCUTS, 'customAction'] })
fireEvent.click(within(row).getByTitle('Clear shortcut'))
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: '' }) })
expect(within(row).getByRole('button', { name: 'Not set' })).toBeInTheDocument()
})
})
+
+describe('KeyboardShortcuts TUI import', () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it('parses the selected file and applies the imported shortcuts once', async () => {
+ const imported = {
+ leaderKey: 'Ctrl+Space',
+ shortcuts: { submit: 'S' },
+ leaderActions: [],
+ directActions: [],
+ skipped: [],
+ }
+ parseTuiKeybindConfig.mockReturnValue(imported)
+ applyTuiKeybindImport.mockReturnValue({
+ keyboardShortcuts: { submit: 'S' },
+ directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
+ leaderKey: 'Ctrl+Space',
+ cleared: [],
+ })
+
+ const { container } = render( )
+ fireEvent.change(getFileInput(container), {
+ target: { files: [makeFile('{"keybinds":{}}', 'cli.json')] },
+ })
+
+ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1))
+ expect(parseTuiKeybindConfig).toHaveBeenCalledWith('{"keybinds":{}}')
+ expect(applyTuiKeybindImport).toHaveBeenCalledWith(imported, {
+ keyboardShortcuts: expect.objectContaining({ customAction: 'Alt+J' }),
+ directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
+ })
+ expect(updateSettings).toHaveBeenCalledWith({
+ keyboardShortcuts: { submit: 'S' },
+ directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
+ leaderKey: 'Ctrl+Space',
+ })
+ expect(showToast.success).toHaveBeenCalledWith('Imported 2 shortcuts from cli.json', undefined)
+ })
+
+ it('shows an error and leaves settings untouched when parsing fails', async () => {
+ parseTuiKeybindConfig.mockImplementation(() => {
+ throw new Error('Invalid JSONC')
+ })
+
+ const { container } = render( )
+ fireEvent.change(getFileInput(container), {
+ target: { files: [makeFile('not jsonc', 'cli.json')] },
+ })
+
+ await waitFor(() =>
+ expect(showToast.error).toHaveBeenCalledWith('Could not import shortcuts', { description: 'Invalid JSONC' }),
+ )
+ expect(updateSettings).not.toHaveBeenCalled()
+ expect(applyTuiKeybindImport).not.toHaveBeenCalled()
+ })
+
+ it('lists skipped entries in the success toast description', async () => {
+ const skipped = ['a', 'b', 'c', 'd', 'e', 'f'].map((name) => ({ name, reason: 'unsupported' }))
+ parseTuiKeybindConfig.mockReturnValue({
+ shortcuts: { submit: 'S' },
+ leaderActions: [],
+ directActions: [],
+ skipped,
+ })
+ applyTuiKeybindImport.mockReturnValue({
+ keyboardShortcuts: { submit: 'S' },
+ directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
+ cleared: ['toggleMode'],
+ })
+
+ const { container } = render( )
+ fireEvent.change(getFileInput(container), {
+ target: { files: [makeFile('{}', 'tui.json')] },
+ })
+
+ await waitFor(() => expect(showToast.success).toHaveBeenCalled())
+ expect(showToast.success).toHaveBeenCalledWith('Imported 1 shortcut from tui.json', {
+ description:
+ 'Unbound to avoid conflicts: toggle mode. Skipped: a (unsupported), b (unsupported), c (unsupported), d (unsupported), e (unsupported) and 1 more',
+ })
+ })
+})
diff --git a/frontend/src/components/settings/KeyboardShortcuts.tsx b/frontend/src/components/settings/KeyboardShortcuts.tsx
index d9019416..a68d833d 100644
--- a/frontend/src/components/settings/KeyboardShortcuts.tsx
+++ b/frontend/src/components/settings/KeyboardShortcuts.tsx
@@ -2,19 +2,13 @@ import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useMobile } from '@/hooks/useMobile'
import { Loader2, X } from 'lucide-react'
-import { DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
+import { Button } from '@/components/ui/button'
+import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
+import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
+import { showToast } from '@/lib/toast'
-const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
-const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
-
-const normalizeShortcut = (shortcut: string): string => {
- return shortcut.replace(/Cmd/g, CMD_KEY)
-}
-
-const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
-
-const CONVERSATION_ACTIONS = ['submit', 'abort', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'selectModel', 'variantCycle']
-const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar']
+const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown']
+const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl']
const formatShortcutLabel = (action: string): string => {
return action.replace(/([A-Z])/g, ' $1').trim()
@@ -25,6 +19,15 @@ interface ShortcutGroup {
actions: string[]
}
+const MAX_SKIPPED_IN_TOAST = 5
+
+const buildSkippedDescription = (skipped: Array<{ name: string; reason: string }>): string | undefined => {
+ if (skipped.length === 0) return undefined
+ const shown = skipped.slice(0, MAX_SKIPPED_IN_TOAST).map((entry) => `${entry.name} (${entry.reason})`).join(', ')
+ const remaining = skipped.length - MAX_SKIPPED_IN_TOAST
+ return remaining > 0 ? `${shown} and ${remaining} more` : shown
+}
+
const buildShortcutGroups = (shortcuts: Record): ShortcutGroup[] => {
const knownActions = new Set([...CONVERSATION_ACTIONS, ...NAVIGATION_ACTIONS])
const unknownActions = Object.keys(shortcuts).filter((action) => !knownActions.has(action))
@@ -127,23 +130,31 @@ export function KeyboardShortcuts() {
const [tempLeaderKey, setTempLeaderKey] = useState(null)
const [currentKeys, setCurrentKeys] = useState('')
- const leaderKey = tempLeaderKey ?? preferences?.leaderKey ?? DEFAULT_LEADER_KEY
- const directShortcuts = preferences?.directShortcuts ?? DEFAULT_DIRECT_SHORTCUTS
+ const bindings = useMemo(() => resolveShortcutBindings(preferences), [preferences])
+ const leaderKey = tempLeaderKey ?? bindings.leaderKey
+ const directShortcuts = bindings.directShortcuts
- const shortcuts = useMemo(() => ({
- ...DEFAULT_KEYBOARD_SHORTCUTS,
- ...preferences?.keyboardShortcuts,
+ const shortcuts = useMemo>(() => ({
+ ...bindings.shortcuts,
...tempShortcuts
- }), [preferences?.keyboardShortcuts, tempShortcuts])
+ }), [bindings.shortcuts, tempShortcuts])
const shortcutGroups = useMemo(() => buildShortcutGroups(shortcuts), [shortcuts])
const shortcutsRef = useRef(shortcuts)
shortcutsRef.current = shortcuts
+ const leaderKeyRef = useRef(leaderKey)
+ leaderKeyRef.current = leaderKey
+
+ const directShortcutsRef = useRef(directShortcuts)
+ directShortcutsRef.current = directShortcuts
+
const updateSettingsRef = useRef(updateSettings)
updateSettingsRef.current = updateSettings
+ const fileInputRef = useRef(null)
+
const startRecording = (action: string) => {
setRecordingKey(action)
setRecordingLeader(false)
@@ -172,64 +183,55 @@ export function KeyboardShortcuts() {
useEffect(() => {
if (!recordingKey && !recordingLeader) return
+ let leaderPressed = false
+ const leaderPrefix = () => (leaderPressed ? `${normalizeShortcut(leaderKeyRef.current)} → ` : '')
+
const handleKeyDown = (e: KeyboardEvent) => {
e.preventDefault()
+ e.stopPropagation()
- const keys = []
- if (e.ctrlKey) keys.push('Ctrl')
- if (e.metaKey) keys.push('Cmd')
- if (e.altKey) keys.push('Alt')
- if (e.shiftKey) keys.push('Shift')
-
- const mainKey = e.key
- if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
- let displayKey = mainKey
- if (mainKey === ' ') displayKey = 'Space'
- else if (mainKey === 'ArrowUp') displayKey = 'Up'
- else if (mainKey === 'ArrowDown') displayKey = 'Down'
- else if (mainKey === 'ArrowLeft') displayKey = 'Left'
- else if (mainKey === 'ArrowRight') displayKey = 'Right'
- else if (mainKey === 'Enter') displayKey = 'Return'
- else if (mainKey === 'Escape') displayKey = 'Esc'
- else if (mainKey === 'Tab') displayKey = 'Tab'
- else if (mainKey === 'Backspace') displayKey = 'Backspace'
- else if (mainKey === 'Delete') displayKey = 'Delete'
- else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
-
- keys.push(displayKey)
-
- if (keys.length > 0) {
- const shortcut = keys.join('+')
-
- if (recordingLeader) {
- setTempLeaderKey(shortcut)
- setRecordingLeader(false)
- setCurrentKeys('')
- updateSettingsRef.current({ leaderKey: shortcut })
- } else if (recordingKey) {
- setTempShortcuts(prev => ({ ...prev, [recordingKey]: shortcut }))
- setRecordingKey(null)
- setCurrentKeys('')
- updateSettingsRef.current({
- keyboardShortcuts: { ...shortcutsRef.current, [recordingKey]: shortcut }
- })
- }
- }
- } else {
- setCurrentKeys(keys.join('+'))
+ const shortcut = formatShortcutEvent(e)
+ if (!shortcut) {
+ setCurrentKeys(leaderPrefix() + formatEventModifiers(e))
+ return
}
+
+ if (recordingLeader) {
+ setTempLeaderKey(shortcut)
+ setRecordingLeader(false)
+ setCurrentKeys('')
+ updateSettingsRef.current({ leaderKey: shortcut })
+ return
+ }
+
+ if (!recordingKey) return
+
+ if (!leaderPressed && shortcut === normalizeShortcut(leaderKeyRef.current)) {
+ leaderPressed = true
+ setCurrentKeys(leaderPrefix())
+ return
+ }
+
+ const otherDirectShortcuts = directShortcutsRef.current.filter((action) => action !== recordingKey)
+ setTempShortcuts(prev => ({ ...prev, [recordingKey]: shortcut }))
+ setRecordingKey(null)
+ setCurrentKeys('')
+ updateSettingsRef.current({
+ keyboardShortcuts: { ...shortcutsRef.current, [recordingKey]: shortcut },
+ directShortcuts: leaderPressed ? otherDirectShortcuts : [...otherDirectShortcuts, recordingKey],
+ })
}
const handleKeyUp = (e: KeyboardEvent) => {
- if (['Control', 'Meta', 'Alt', 'Shift'].includes(e.key)) {
- setCurrentKeys('')
+ if (isModifierOnlyEvent(e)) {
+ setCurrentKeys(leaderPrefix())
}
}
- document.addEventListener('keydown', handleKeyDown)
+ document.addEventListener('keydown', handleKeyDown, true)
document.addEventListener('keyup', handleKeyUp)
return () => {
- document.removeEventListener('keydown', handleKeyDown)
+ document.removeEventListener('keydown', handleKeyDown, true)
document.removeEventListener('keyup', handleKeyUp)
}
}, [recordingKey, recordingLeader])
@@ -257,6 +259,54 @@ export function KeyboardShortcuts() {
updateSettings({ directShortcuts: newDirectShortcuts })
}
+ const importFromTui = async (event: React.ChangeEvent) => {
+ const file = event.target.files?.[0]
+ event.target.value = ''
+ if (!file) return
+
+ try {
+ const imported = parseTuiKeybindConfig(await file.text())
+ stopRecording()
+ const applied = applyTuiKeybindImport(imported, {
+ keyboardShortcuts: shortcutsRef.current,
+ directShortcuts: directShortcutsRef.current,
+ })
+ const importedCount = Object.keys(imported.shortcuts).length + (applied.leaderKey ? 1 : 0)
+ const skippedDescription = buildSkippedDescription(imported.skipped)
+
+ if (importedCount === 0) {
+ showToast.info(
+ `No matching shortcuts found in ${file.name}`,
+ skippedDescription ? { description: skippedDescription } : undefined,
+ )
+ return
+ }
+
+ updateSettingsRef.current({
+ keyboardShortcuts: applied.keyboardShortcuts,
+ directShortcuts: applied.directShortcuts,
+ ...(applied.leaderKey ? { leaderKey: applied.leaderKey } : {}),
+ })
+ setTempShortcuts(applied.keyboardShortcuts)
+ if (applied.leaderKey !== undefined) {
+ setTempLeaderKey(applied.leaderKey)
+ }
+
+ const description = [
+ applied.cleared.length > 0 ? `Unbound to avoid conflicts: ${applied.cleared.map((action) => formatShortcutLabel(action).toLowerCase()).join(', ')}` : undefined,
+ skippedDescription ? `Skipped: ${skippedDescription}` : undefined,
+ ].filter(Boolean).join('. ')
+ showToast.success(
+ `Imported ${importedCount} shortcut${importedCount === 1 ? '' : 's'} from ${file.name}`,
+ description ? { description } : undefined,
+ )
+ } catch (error) {
+ showToast.error('Could not import shortcuts', {
+ description: error instanceof Error ? error.message : 'Unknown error',
+ })
+ }
+ }
+
if (isMobile) {
return (
@@ -270,7 +320,25 @@ export function KeyboardShortcuts() {
return (
-
Keyboard Shortcuts
+
+
Keyboard Shortcuts
+
+
+
fileInputRef.current?.click()}>
+ Import from OpenCode TUI
+
+
+
+ Select your OpenCode cli.json (or legacy tui.json), usually in ~/.config/opencode.
+
+
+
@@ -316,7 +384,7 @@ export function KeyboardShortcuts() {
- Click on any shortcut to record a new key combination. Click on the status text below each action to toggle whether it requires the leader key.
+ Click on any shortcut to record a new key combination. Press the leader key first to record a leader shortcut, or press a combination directly to record a direct one. Click on the status text below each action to toggle whether it requires the leader key.
)
diff --git a/frontend/src/components/ui/bottom-sheet.test.tsx b/frontend/src/components/ui/bottom-sheet.test.tsx
index 0e3ef98e..77e94f03 100644
--- a/frontend/src/components/ui/bottom-sheet.test.tsx
+++ b/frontend/src/components/ui/bottom-sheet.test.tsx
@@ -1,5 +1,7 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
-import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { useState } from 'react'
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { stubMatchMedia } from '@/test/test-utils'
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from './bottom-sheet'
import { useSwipeDismiss } from '@/hooks/useMobile'
@@ -11,6 +13,33 @@ vi.mock('@/hooks/useMobile', () => ({
})),
}))
+function renderSheet(isOpen: boolean) {
+ return render(
+ <>
+
+
{}} ariaLabel="Test sheet">
+ inside
+
+ >,
+ )
+}
+
+function AutoFocusSheetHost() {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+
setOpen(true)}>open sheet
+
setOpen(false)} ariaLabel="Auto focus sheet">
+
+
+ >
+ )
+}
+
+afterEach(() => {
+ Reflect.deleteProperty(window, 'matchMedia')
+})
+
describe('BottomSheet', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -132,6 +161,101 @@ describe('BottomSheet', () => {
expect(mockBind).toHaveBeenCalled()
})
+
+ it('moves focus to the chat prompt on desktop when it closes', () => {
+ stubMatchMedia(true)
+ const { rerender } = renderSheet(false)
+
+ rerender(
+ <>
+
+
{}} ariaLabel="Test sheet">
+ inside
+
+ >,
+ )
+ screen.getByRole('button', { name: 'inside' }).focus()
+
+ rerender(
+ <>
+
+
{}} ariaLabel="Test sheet">
+ inside
+
+ >,
+ )
+
+ expect(screen.getByLabelText('prompt')).toHaveFocus()
+ })
+
+ it('does not refocus the chat prompt on touch when it closes', () => {
+ stubMatchMedia(false)
+ const { rerender } = renderSheet(false)
+
+ rerender(
+ <>
+
+
{}} ariaLabel="Test sheet">
+ inside
+
+ >,
+ )
+ screen.getByRole('button', { name: 'inside' }).focus()
+
+ rerender(
+ <>
+
+
{}} ariaLabel="Test sheet">
+ inside
+
+ >,
+ )
+
+ expect(screen.getByLabelText('prompt')).not.toHaveFocus()
+ })
+
+ it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
+ stubMatchMedia(true)
+ render(
)
+ const opener = screen.getByRole('button', { name: 'open sheet' })
+ opener.focus()
+
+ fireEvent.click(opener)
+ expect(screen.getByLabelText('sheet input')).toHaveFocus()
+
+ fireEvent.keyDown(document, { key: 'Escape' })
+
+ await waitFor(() => expect(opener).toHaveFocus())
+ })
+
+ it('captures the opener when mounted already open and restores it on close', () => {
+ stubMatchMedia(true)
+ const { rerender } = render(
+
opener ,
+ )
+ const opener = screen.getByRole('button', { name: 'opener' })
+ opener.focus()
+
+ rerender(
+ <>
+
opener
+
{}} ariaLabel="Mounted open sheet">
+ inside
+
+ >,
+ )
+
+ rerender(
+ <>
+
opener
+
{}} ariaLabel="Mounted open sheet">
+ inside
+
+ >,
+ )
+
+ expect(opener).toHaveFocus()
+ })
})
describe('BottomSheetHeader', () => {
diff --git a/frontend/src/components/ui/bottom-sheet.tsx b/frontend/src/components/ui/bottom-sheet.tsx
index fb2aa5a7..14b7fa6f 100644
--- a/frontend/src/components/ui/bottom-sheet.tsx
+++ b/frontend/src/components/ui/bottom-sheet.tsx
@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'
import { cn } from '@/lib/utils'
import { MODAL_TRANSITION_MS } from '@/lib/utils'
import { useSwipeDismiss } from '@/hooks/useMobile'
+import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
export interface BottomSheetProps {
isOpen: boolean
@@ -24,6 +25,8 @@ export function BottomSheet({
const [shouldRender, setShouldRender] = useState(false)
const panelRef = useRef
(null)
+ useRestoreFocusOnClose(isOpen, panelRef)
+
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
enabled: isOpen,
threshold: 60,
@@ -86,6 +89,7 @@ export function BottomSheet({
role="dialog"
aria-modal="true"
aria-label={ariaLabel}
+ data-state={isOpen ? 'open' : 'closed'}
style={swipeStyles}
>
diff --git a/frontend/src/components/ui/dialog.test.tsx b/frontend/src/components/ui/dialog.test.tsx
index 95b8c72e..2301ecb0 100644
--- a/frontend/src/components/ui/dialog.test.tsx
+++ b/frontend/src/components/ui/dialog.test.tsx
@@ -441,6 +441,22 @@ function ReturnFocusHost({ onCloseAutoFocus }: { onCloseAutoFocus?: (event: Even
)
}
+function PromptReturnFocusHost() {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+
+
setOpen(true)}>open prompt dialog
+
+
+ Prompt Focus Dialog
+
+
+
+ >
+ )
+}
+
async function openAndEscape(returnTarget: HTMLElement) {
returnTarget.focus()
fireEvent.click(screen.getByText('open'))
@@ -495,6 +511,22 @@ describe('Dialog return focus', () => {
expect(prompt).not.toHaveFocus()
})
+
+ it('moves focus to the chat prompt when the dialog closes on desktop', async () => {
+ stubMatchMedia(true)
+ render(
)
+ const opener = screen.getByText('open prompt dialog')
+ opener.focus()
+
+ fireEvent.click(opener)
+ const input = await screen.findByLabelText('prompt dialog input')
+ await waitFor(() => expect(input).toHaveFocus())
+ fireEvent.keyDown(input, { key: 'Escape' })
+ await waitFor(() => expect(screen.queryByLabelText('prompt dialog input')).not.toBeInTheDocument())
+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)))
+
+ expect(screen.getByLabelText('chat prompt')).toHaveFocus()
+ })
})
function stubVisualViewport(height: number) {
diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx
index 9e49feca..fb784690 100644
--- a/frontend/src/components/ui/dialog.tsx
+++ b/frontend/src/components/ui/dialog.tsx
@@ -5,23 +5,11 @@ import { X } from "lucide-react"
import { cn } from "@/lib/utils"
import { useSwipeBack } from '@/hooks/useMobile'
import { useVisualViewport } from '@/hooks/useVisualViewport'
-import { FINE_POINTER_MEDIA_QUERY } from '@/hooks/useMediaQuery'
+import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
const DialogOpenContext = React.createContext
(true)
const DialogReturnFocusContext = React.createContext(null)
-function getFocusedElement(): HTMLElement | null {
- return typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
- ? document.activeElement
- : null
-}
-
-function canRestoreFocus(element: HTMLElement): boolean {
- if (!element.isConnected || element === document.body) return false
- if (!element.matches('input, textarea, [contenteditable="true"]')) return true
- return typeof window.matchMedia === 'function' && window.matchMedia(FINE_POINTER_MEDIA_QUERY).matches
-}
-
function Dialog({ open, ...props }: React.ComponentProps) {
const [openState, setOpenState] = React.useState(() => ({
open,
@@ -83,9 +71,10 @@ const DialogContent = React.forwardRef<
const returnFocus = React.useContext(DialogReturnFocusContext)
const handleCloseAutoFocus = (event: Event) => {
onCloseAutoFocus?.(event)
- if (event.defaultPrevented || !returnFocus || !canRestoreFocus(returnFocus)) return
- event.preventDefault()
- returnFocus.focus()
+ if (event.defaultPrevented) return
+ if (restoreOverlayFocus(returnFocus, event.currentTarget as Element | null)) {
+ event.preventDefault()
+ }
}
const handleEscapeKeyDown = (event: KeyboardEvent) => {
onEscapeKeyDown?.(event)
diff --git a/frontend/src/components/ui/side-drawer.test.tsx b/frontend/src/components/ui/side-drawer.test.tsx
index fe594230..4b667af3 100644
--- a/frontend/src/components/ui/side-drawer.test.tsx
+++ b/frontend/src/components/ui/side-drawer.test.tsx
@@ -1,7 +1,36 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
-import { describe, it, expect, vi } from 'vitest'
+import { useState } from 'react'
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { stubMatchMedia } from '@/test/test-utils'
import { SideDrawer, SideDrawerHeader, SideDrawerContent } from './side-drawer'
+function renderDrawer(isOpen: boolean) {
+ return render(
+ <>
+
+ {}} ariaLabel="Test drawer">
+ inside
+
+ >,
+ )
+}
+
+function AutoFocusDrawerHost() {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ setOpen(true)}>open drawer
+ setOpen(false)} ariaLabel="Auto focus drawer">
+
+
+ >
+ )
+}
+
+afterEach(() => {
+ Reflect.deleteProperty(window, 'matchMedia')
+})
+
describe('SideDrawer', () => {
it('renders when isOpen is true', () => {
render(
@@ -79,6 +108,46 @@ describe('SideDrawer', () => {
expect(closeInner).toHaveBeenCalledTimes(1)
expect(closeOuter).not.toHaveBeenCalled()
})
+
+ it('moves focus to the chat prompt on desktop when it closes', () => {
+ stubMatchMedia(true)
+ const { rerender } = renderDrawer(false)
+
+ rerender(
+ <>
+
+ {}} ariaLabel="Test drawer">
+ inside
+
+ >,
+ )
+ screen.getByRole('button', { name: 'inside' }).focus()
+
+ rerender(
+ <>
+
+ {}} ariaLabel="Test drawer">
+ inside
+
+ >,
+ )
+
+ expect(screen.getByLabelText('prompt')).toHaveFocus()
+ })
+
+ it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
+ stubMatchMedia(true)
+ render( )
+ const opener = screen.getByRole('button', { name: 'open drawer' })
+ opener.focus()
+
+ fireEvent.click(opener)
+ expect(screen.getByLabelText('drawer input')).toHaveFocus()
+
+ fireEvent.keyDown(document, { key: 'Escape' })
+
+ await waitFor(() => expect(opener).toHaveFocus())
+ })
})
describe('SideDrawerHeader', () => {
diff --git a/frontend/src/components/ui/side-drawer.tsx b/frontend/src/components/ui/side-drawer.tsx
index 870ed9d6..3e88f88c 100644
--- a/frontend/src/components/ui/side-drawer.tsx
+++ b/frontend/src/components/ui/side-drawer.tsx
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { cn } from '@/lib/utils'
import { MODAL_TRANSITION_MS } from '@/lib/utils'
import { X } from 'lucide-react'
+import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
const openDrawerStack: symbol[] = []
@@ -25,6 +26,9 @@ export function SideDrawer({
ariaLabel,
}: SideDrawerProps) {
const [shouldRender, setShouldRender] = useState(false)
+ const panelRef = useRef(null)
+
+ useRestoreFocusOnClose(isOpen, panelRef)
useEffect(() => {
if (isOpen) {
@@ -81,6 +85,7 @@ export function SideDrawer({
aria-hidden="true"
/>
{children}
diff --git a/frontend/src/contexts/KeyboardShortcutsContext.test.tsx b/frontend/src/contexts/KeyboardShortcutsContext.test.tsx
new file mode 100644
index 00000000..b772ebc5
--- /dev/null
+++ b/frontend/src/contexts/KeyboardShortcutsContext.test.tsx
@@ -0,0 +1,365 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, render, renderHook, screen } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import { KeyboardShortcutsProvider, useShortcutActions, type ShortcutActions } from './KeyboardShortcutsContext'
+
+const { preferences } = vi.hoisted(() => ({
+ preferences: {
+ leaderKey: 'Ctrl+X',
+ keyboardShortcuts: { submit: 'Ctrl+Enter', abort: 'Escape', newSession: 'N' } as Record,
+ directShortcuts: ['submit', 'abort'],
+ },
+}))
+
+vi.mock('@/hooks/useSettings', () => ({
+ useSettings: () => ({ preferences }),
+}))
+
+function pressKey(target: Element, init: KeyboardEventInit) {
+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
+ act(() => {
+ target.dispatchEvent(event)
+ })
+ return event
+}
+
+function mountElement(tag: K, attributes: Record = {}) {
+ const element = document.createElement(tag)
+ for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value)
+ return document.body.appendChild(element)
+}
+
+function ActionLayer({ actions, scope = 'page' }: { actions: ShortcutActions; scope?: 'global' | 'page' }) {
+ useShortcutActions(actions, scope)
+ return null
+}
+
+function ConditionalLayer({ show, actions }: { show: boolean; actions: ShortcutActions }) {
+ if (!show) return null
+ return
+}
+
+function renderProvider(children: ReactNode) {
+ return render({children} )
+}
+
+describe('KeyboardShortcutsProvider', () => {
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ it('matches stored Enter and Escape bindings against Return and Esc key events', () => {
+ const submit = vi.fn()
+ const abort = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+
+ pressKey(prompt, { key: 'Enter', ctrlKey: true })
+ pressKey(document.body, { key: 'Escape' })
+
+ expect(submit).toHaveBeenCalledTimes(1)
+ expect(abort).toHaveBeenCalledTimes(1)
+ })
+
+ it('activates the leader from the prompt and runs the follow-up action without typing it', () => {
+ const newSession = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+
+ expect(pressKey(prompt, { key: 'x', ctrlKey: true }).defaultPrevented).toBe(true)
+ const followUp = pressKey(prompt, { key: 'n' })
+
+ expect(newSession).toHaveBeenCalledTimes(1)
+ expect(followUp.defaultPrevented).toBe(true)
+ })
+
+ it('applies new default direct actions for users with stored preferences that predate them', () => {
+ const variantCycle = vi.fn()
+ renderProvider( )
+ const input = mountElement('textarea')
+
+ pressKey(input, { key: 't', ctrlKey: true })
+
+ expect(variantCycle).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves submit to the focused input and only interrupts from the prompt', () => {
+ const submit = vi.fn()
+ const abort = vi.fn()
+ renderProvider( )
+ const otherInput = mountElement('input')
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+
+ pressKey(otherInput, { key: 'Enter', ctrlKey: true })
+ pressKey(otherInput, { key: 'Escape' })
+ expect(submit).not.toHaveBeenCalled()
+ expect(abort).not.toHaveBeenCalled()
+
+ pressKey(prompt, { key: 'Escape' })
+ expect(abort).toHaveBeenCalledTimes(1)
+ })
+
+ it('submits from the prompt on plain Enter when submit is bound to Enter, leaving Enter alone elsewhere', () => {
+ const original = preferences.keyboardShortcuts
+ preferences.keyboardShortcuts = { ...original, submit: 'Return' }
+ try {
+ const submit = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+ const button = mountElement('button')
+
+ expect(pressKey(prompt, { key: 'Enter' }).defaultPrevented).toBe(true)
+ expect(submit).toHaveBeenCalledTimes(1)
+
+ expect(pressKey(prompt, { key: 'Enter', shiftKey: true }).defaultPrevented).toBe(false)
+ expect(pressKey(prompt, { key: 'Enter', isComposing: true }).defaultPrevented).toBe(false)
+ expect(pressKey(button, { key: 'Enter' }).defaultPrevented).toBe(false)
+ expect(pressKey(document.body, { key: 'Enter' }).defaultPrevented).toBe(false)
+ expect(submit).toHaveBeenCalledTimes(1)
+ } finally {
+ preferences.keyboardShortcuts = original
+ }
+ })
+
+ it('cycles the agent with a direct Tab only from the prompt, keeping Tab for focus elsewhere', () => {
+ const original = { keyboardShortcuts: preferences.keyboardShortcuts, directShortcuts: preferences.directShortcuts }
+ preferences.keyboardShortcuts = { ...original.keyboardShortcuts, toggleMode: 'Tab' }
+ preferences.directShortcuts = ['submit', 'abort', 'toggleMode']
+ try {
+ const toggleMode = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+ const button = mountElement('button')
+ const otherInput = mountElement('input')
+
+ expect(pressKey(button, { key: 'Tab' }).defaultPrevented).toBe(false)
+ expect(pressKey(document.body, { key: 'Tab' }).defaultPrevented).toBe(false)
+ expect(pressKey(otherInput, { key: 'Tab' }).defaultPrevented).toBe(false)
+ expect(toggleMode).not.toHaveBeenCalled()
+
+ expect(pressKey(prompt, { key: 'Tab' }).defaultPrevented).toBe(true)
+ expect(toggleMode).toHaveBeenCalledTimes(1)
+ } finally {
+ preferences.keyboardShortcuts = original.keyboardShortcuts
+ preferences.directShortcuts = original.directShortcuts
+ }
+ })
+
+ it('never runs a prompt-only shortcut on a key that types a character', () => {
+ const original = { keyboardShortcuts: preferences.keyboardShortcuts, directShortcuts: preferences.directShortcuts }
+ preferences.keyboardShortcuts = { ...original.keyboardShortcuts, toggleMode: 'T' }
+ preferences.directShortcuts = ['submit', 'abort', 'toggleMode']
+ try {
+ const toggleMode = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+
+ expect(pressKey(prompt, { key: 't' }).defaultPrevented).toBe(false)
+ expect(toggleMode).not.toHaveBeenCalled()
+ } finally {
+ preferences.keyboardShortcuts = original.keyboardShortcuts
+ preferences.directShortcuts = original.directShortcuts
+ }
+ })
+
+ it('clears the prompt with a direct Ctrl+C only from the prompt', () => {
+ const original = { keyboardShortcuts: preferences.keyboardShortcuts, directShortcuts: preferences.directShortcuts }
+ preferences.keyboardShortcuts = { ...original.keyboardShortcuts, clearPrompt: 'Ctrl+C' }
+ preferences.directShortcuts = ['submit', 'abort', 'clearPrompt']
+ try {
+ const clearPrompt = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+ const otherInput = mountElement('textarea')
+ const button = mountElement('button')
+
+ expect(pressKey(otherInput, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(false)
+ expect(pressKey(button, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(false)
+ expect(pressKey(document.body, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(false)
+ expect(clearPrompt).not.toHaveBeenCalled()
+
+ expect(pressKey(prompt, { key: 'c', ctrlKey: true }).defaultPrevented).toBe(true)
+ expect(clearPrompt).toHaveBeenCalledTimes(1)
+ } finally {
+ preferences.keyboardShortcuts = original.keyboardShortcuts
+ preferences.directShortcuts = original.directShortcuts
+ }
+ })
+
+ it('runs a direct half-page-down shortcut with Ctrl+D from the body and the prompt', () => {
+ const halfPageDown = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+
+ expect(pressKey(document.body, { key: 'd', ctrlKey: true }).defaultPrevented).toBe(true)
+ expect(halfPageDown).toHaveBeenCalledTimes(1)
+
+ expect(pressKey(prompt, { key: 'd', ctrlKey: true }).defaultPrevented).toBe(true)
+ expect(halfPageDown).toHaveBeenCalledTimes(2)
+ })
+
+ it('runs a direct half-page-up shortcut with Ctrl+U from the body and the prompt, never from another text field', () => {
+ const halfPageUp = vi.fn()
+ renderProvider( )
+ const prompt = mountElement('textarea', { 'data-prompt-input': '' })
+ const otherInput = mountElement('input')
+
+ expect(pressKey(otherInput, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(false)
+ expect(halfPageUp).not.toHaveBeenCalled()
+
+ expect(pressKey(document.body, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(true)
+ expect(pressKey(prompt, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(true)
+ expect(halfPageUp).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not abort while a dialog overlay is open, leaving Escape to the overlay', () => {
+ const abort = vi.fn()
+ renderProvider( )
+ mountElement('div', { role: 'dialog', 'data-state': 'open' })
+
+ expect(pressKey(document.body, { key: 'Escape' }).defaultPrevented).toBe(false)
+ expect(abort).not.toHaveBeenCalled()
+ })
+
+ it('aborts with Escape when no dialog overlay is open', () => {
+ const abort = vi.fn()
+ renderProvider( )
+ mountElement('div', { role: 'dialog', 'data-state': 'closed' })
+
+ expect(pressKey(document.body, { key: 'Escape' }).defaultPrevented).toBe(true)
+ expect(abort).toHaveBeenCalledTimes(1)
+ })
+
+ it('runs leader and direct shortcuts from a terminal before it consumes the keys, passing other keys through', () => {
+ const newSession = vi.fn()
+ const toggleTerminal = vi.fn()
+ renderProvider( )
+ const terminal = mountElement('div', { 'data-terminal-id': 'pty-1' })
+ const terminalInput = terminal.appendChild(document.createElement('textarea'))
+ const shellInput = vi.fn()
+ terminalInput.addEventListener('keydown', (event) => {
+ shellInput(event.key)
+ event.preventDefault()
+ })
+
+ pressKey(terminalInput, { key: 'x', ctrlKey: true })
+ pressKey(terminalInput, { key: 'n' })
+ pressKey(terminalInput, { key: 'x', ctrlKey: true })
+ pressKey(terminalInput, { key: 't' })
+ pressKey(terminalInput, { key: 'l' })
+
+ expect(newSession).toHaveBeenCalledTimes(1)
+ expect(toggleTerminal).toHaveBeenCalledTimes(1)
+ expect(shellInput.mock.calls).toEqual([['l']])
+ })
+
+ it('passes direct shortcuts through in a terminal while keeping the leader and toggleTerminal', () => {
+ const variantCycle = vi.fn()
+ const halfPageUp = vi.fn()
+ const toggleTerminal = vi.fn()
+ renderProvider( )
+ const terminal = mountElement('div', { 'data-terminal-id': 'pty-2' })
+ const terminalInput = terminal.appendChild(document.createElement('textarea'))
+
+ expect(pressKey(terminalInput, { key: 't', ctrlKey: true }).defaultPrevented).toBe(false)
+ expect(pressKey(terminalInput, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(false)
+ expect(variantCycle).not.toHaveBeenCalled()
+ expect(halfPageUp).not.toHaveBeenCalled()
+
+ pressKey(terminalInput, { key: 'x', ctrlKey: true })
+ expect(pressKey(terminalInput, { key: 't' }).defaultPrevented).toBe(true)
+ expect(toggleTerminal).toHaveBeenCalledTimes(1)
+ })
+
+ it('ignores key events a component already handled', () => {
+ const abort = vi.fn()
+ renderProvider( )
+ const element = mountElement('div')
+ element.addEventListener('keydown', (event) => event.preventDefault())
+
+ pressKey(element, { key: 'Escape' })
+
+ expect(abort).not.toHaveBeenCalled()
+ })
+
+ it('does not swallow a key whose action has no handler', () => {
+ renderProvider( )
+
+ expect(pressKey(document.body, { key: 'Escape' }).defaultPrevented).toBe(false)
+ })
+
+ it('prefers a page layer over a global layer for the same action', () => {
+ const globalAbort = vi.fn()
+ const pageAbort = vi.fn()
+ renderProvider(
+ <>
+
+
+ >
+ )
+
+ pressKey(document.body, { key: 'Escape' })
+
+ expect(pageAbort).toHaveBeenCalledTimes(1)
+ expect(globalAbort).not.toHaveBeenCalled()
+ })
+
+ it('falls through to the global handler when a page layer leaves the action undefined', () => {
+ const globalAbort = vi.fn()
+ renderProvider(
+ <>
+
+
+ >
+ )
+
+ pressKey(document.body, { key: 'Escape' })
+
+ expect(globalAbort).toHaveBeenCalledTimes(1)
+ })
+
+ it('restores the global handler when a page layer unmounts', () => {
+ const globalAbort = vi.fn()
+ const pageAbort = vi.fn()
+ const view = renderProvider(
+ <>
+
+
+ >
+ )
+
+ pressKey(document.body, { key: 'Escape' })
+ expect(pageAbort).toHaveBeenCalledTimes(1)
+ expect(globalAbort).not.toHaveBeenCalled()
+
+ view.rerender(
+
+
+
+
+ )
+
+ pressKey(document.body, { key: 'Escape' })
+ expect(globalAbort).toHaveBeenCalledTimes(1)
+ })
+
+ it('shows the leader indicator after the leader key and hides it after the follow-up key', () => {
+ const newSession = vi.fn()
+ renderProvider( )
+
+ pressKey(document.body, { key: 'x', ctrlKey: true })
+ expect(screen.getByText('Waiting for shortcut key...')).toBeInTheDocument()
+
+ pressKey(document.body, { key: 'n' })
+ expect(screen.queryByText('Waiting for shortcut key...')).not.toBeInTheDocument()
+ expect(newSession).toHaveBeenCalledTimes(1)
+ })
+
+ it('throws when used outside the provider', () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ expect(() => renderHook(() => useShortcutActions({ abort: vi.fn() }))).toThrow(
+ 'useShortcutActions must be used within a KeyboardShortcutsProvider'
+ )
+ consoleError.mockRestore()
+ })
+})
diff --git a/frontend/src/contexts/KeyboardShortcutsContext.tsx b/frontend/src/contexts/KeyboardShortcutsContext.tsx
new file mode 100644
index 00000000..8a7a48a9
--- /dev/null
+++ b/frontend/src/contexts/KeyboardShortcutsContext.tsx
@@ -0,0 +1,177 @@
+/* eslint-disable react-refresh/only-export-components */
+import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react'
+import { useSettings } from '@/hooks/useSettings'
+import type { KeyboardShortcutAction } from '@/api/types/settings'
+import { findShortcutAction, formatShortcutEvent, hasCommandModifier, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
+import { isPromptInput, isTextEntryElement } from '@/lib/domTargets'
+import { hasOpenOverlay } from '@/lib/overlayFocus'
+
+const LEADER_TIMEOUT = 2000
+
+export type ShortcutActions = Partial void>>
+
+interface ShortcutLayer {
+ actionsRef: { current: ShortcutActions }
+}
+
+interface ShortcutRegistry {
+ global: ShortcutLayer[]
+ page: ShortcutLayer[]
+}
+
+const KeyboardShortcutsRegistryContext = createContext(null)
+
+const PROMPT_ONLY_DIRECT_ACTIONS: ReadonlySet = new Set(['toggleMode', 'clearPrompt'])
+
+const HALF_PAGE_DIRECT_ACTIONS: ReadonlySet = new Set(['halfPageUp', 'halfPageDown'])
+
+function typesCharacter(shortcut: string): boolean {
+ return !hasCommandModifier(shortcut) && /(^|\+).$/.test(shortcut)
+}
+
+/**
+ * Whether a direct shortcut may run for this focus target. Prompt-only actions (agent cycling, prompt clearing) run only
+ * from the prompt and never on a key that types a character. `submit` runs only from the prompt, so a submit bound to
+ * plain Enter sends the prompt without hijacking Enter on buttons or other fields. Half-page scrolling runs only from the
+ * prompt or a non-text target, so it never hijacks Ctrl+U/Ctrl+D inside another text field. `abort` runs from the prompt
+ * or with no text field focused; other text inputs only accept modified shortcuts.
+ */
+function isDirectActionAllowed(action: string, shortcut: string, target: HTMLElement): boolean {
+ if (PROMPT_ONLY_DIRECT_ACTIONS.has(action)) return isPromptInput(target) && !typesCharacter(shortcut)
+ if (action === 'submit') return isPromptInput(target)
+ if (HALF_PAGE_DIRECT_ACTIONS.has(action)) return isPromptInput(target) || !isTextEntryElement(target)
+ if (!isTextEntryElement(target)) return true
+ if (action === 'abort') return isPromptInput(target)
+ return hasCommandModifier(shortcut)
+}
+
+function isTerminalTarget(target: EventTarget | null): boolean {
+ return target instanceof Element && target.closest('[data-terminal-id]') !== null
+}
+
+function findLayerHandler(layers: ShortcutLayer[], action: string): (() => void) | undefined {
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
+ const handler = layers[index].actionsRef.current[action as KeyboardShortcutAction]
+ if (handler) return handler
+ }
+ return undefined
+}
+
+function findHandler(registry: ShortcutRegistry, action: string): (() => void) | undefined {
+ return findLayerHandler(registry.page, action) ?? findLayerHandler(registry.global, action)
+}
+
+export function KeyboardShortcutsProvider({ children }: { children: ReactNode }) {
+ const { preferences } = useSettings()
+ const [leaderActive, setLeaderActive] = useState(false)
+ const leaderActiveRef = useRef(false)
+ const leaderTimeoutRef = useRef | null>(null)
+ const preferencesRef = useRef(preferences)
+ preferencesRef.current = preferences
+ const registryRef = useRef({ global: [], page: [] })
+
+ const setLeader = useCallback((active: boolean) => {
+ if (leaderTimeoutRef.current) {
+ clearTimeout(leaderTimeoutRef.current)
+ leaderTimeoutRef.current = null
+ }
+ leaderActiveRef.current = active
+ setLeaderActive(active)
+ if (!active) return
+ leaderTimeoutRef.current = setTimeout(() => {
+ leaderTimeoutRef.current = null
+ leaderActiveRef.current = false
+ setLeaderActive(false)
+ }, LEADER_TIMEOUT)
+ }, [])
+
+ const runAction = useCallback((action: string | undefined, e: KeyboardEvent): boolean => {
+ if (!action) return false
+ if (action === 'abort' && hasOpenOverlay()) return false
+ const handler = findHandler(registryRef.current, action)
+ if (!handler) return false
+ e.preventDefault()
+ handler()
+ return true
+ }, [])
+
+ useEffect(() => {
+ const handleShortcut = (e: KeyboardEvent): boolean => {
+ if (e.defaultPrevented || e.isComposing) return false
+ const shortcut = formatShortcutEvent(e)
+ if (!shortcut) return false
+
+ const target = e.target as HTMLElement
+ if (target.closest?.('[data-file-editor="true"]')) return false
+
+ const bindings = resolveShortcutBindings(preferencesRef.current)
+
+ if (leaderActiveRef.current) {
+ setLeader(false)
+ return runAction(findShortcutAction(bindings, shortcut, false), e)
+ }
+
+ if (shortcut === bindings.leaderKey && (!isTextEntryElement(target) || hasCommandModifier(shortcut))) {
+ e.preventDefault()
+ setLeader(true)
+ return true
+ }
+
+ const directAction = findShortcutAction(bindings, shortcut, true)
+ if (!directAction) return false
+ if (isTerminalTarget(e.target) && directAction !== 'toggleTerminal') return false
+ if (!isDirectActionAllowed(directAction, shortcut, target)) return false
+ return runAction(directAction, e)
+ }
+
+ const handleTerminalKeyDown = (e: KeyboardEvent) => {
+ if (!isTerminalTarget(e.target) || !handleShortcut(e)) return
+ e.stopPropagation()
+ }
+
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (isTerminalTarget(e.target)) return
+ handleShortcut(e)
+ }
+
+ document.addEventListener('keydown', handleTerminalKeyDown, true)
+ document.addEventListener('keydown', handleKeyDown)
+ return () => {
+ document.removeEventListener('keydown', handleTerminalKeyDown, true)
+ document.removeEventListener('keydown', handleKeyDown)
+ setLeader(false)
+ }
+ }, [runAction, setLeader])
+
+ return (
+
+ {children}
+ {leaderActive && (
+
+ Waiting for shortcut key...
+
+ )}
+
+ )
+}
+
+/**
+ * Registers a layer of shortcut handlers for the lifetime of the calling component. Page layers take precedence over global
+ * layers, and within a scope the newest layer wins; an action left `undefined` in a layer falls through to lower layers.
+ */
+export function useShortcutActions(actions: ShortcutActions, scope: 'global' | 'page' = 'page'): void {
+ const registry = useContext(KeyboardShortcutsRegistryContext)
+ if (!registry) throw new Error('useShortcutActions must be used within a KeyboardShortcutsProvider')
+ const layerRef = useRef({ actionsRef: { current: actions } })
+ layerRef.current.actionsRef.current = actions
+
+ useEffect(() => {
+ const layers = scope === 'global' ? registry.global : registry.page
+ const layer = layerRef.current
+ layers.push(layer)
+ return () => {
+ const index = layers.indexOf(layer)
+ if (index >= 0) layers.splice(index, 1)
+ }
+ }, [registry, scope])
+}
diff --git a/frontend/src/hooks/useAutoScroll.test.tsx b/frontend/src/hooks/useAutoScroll.test.tsx
index 914b4622..b3d3370b 100644
--- a/frontend/src/hooks/useAutoScroll.test.tsx
+++ b/frontend/src/hooks/useAutoScroll.test.tsx
@@ -30,6 +30,13 @@ function createScrollContainer() {
},
})
+ Object.defineProperty(div, 'scrollBy', {
+ configurable: true,
+ value: (options?: ScrollToOptions) => {
+ div.scrollTop = scrollTopValue + (options?.top ?? 0)
+ },
+ })
+
return {
div,
setScrollHeight: (value: number) => {
@@ -367,6 +374,45 @@ describe('useAutoScroll', () => {
expect(containerHarness.getScrollTop()).toBe(100)
})
+ it('does not scroll to bottom on content update after a half-page scroll up', () => {
+ const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
+ const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
+
+ act(() => {
+ vi.advanceTimersByTime(100)
+ })
+
+ const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
+ expect(containerHarness.getScrollTop()).toBe(bottomPosition)
+
+ act(() => {
+ renderResult.result.current.scrollByUser(-containerHarness.div.clientHeight / 2)
+ })
+
+ const halfPagePosition = containerHarness.getScrollTop()
+ expect(halfPagePosition).toBe(bottomPosition - containerHarness.div.clientHeight / 2)
+ expect(onScrollStateChange).toHaveBeenCalledWith(true)
+
+ act(() => {
+ vi.advanceTimersByTime(400)
+ })
+
+ containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 200)
+
+ act(() => {
+ renderResult.rerender({
+ containerRef: { current: containerHarness.div },
+ messages,
+ sessionId: 'session-1',
+ contentVersion: messages.length + 1,
+ onScrollStateChange,
+ })
+ vi.advanceTimersByTime(100)
+ })
+
+ expect(containerHarness.getScrollTop()).toBe(halfPagePosition)
+ })
+
it('shows scroll button when streaming growth carries disengaged user past threshold', () => {
const messages = [createMessage('1', 'user')]
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
diff --git a/frontend/src/hooks/useAutoScroll.ts b/frontend/src/hooks/useAutoScroll.ts
index 11df6fb1..e801256e 100644
--- a/frontend/src/hooks/useAutoScroll.ts
+++ b/frontend/src/hooks/useAutoScroll.ts
@@ -16,6 +16,7 @@ interface UseAutoScrollOptions {
interface UseAutoScrollReturn {
scrollToBottom: () => void
+ scrollByUser: (delta: number) => void
}
export function useAutoScroll({
@@ -62,6 +63,28 @@ export function useAutoScroll({
onScrollStateChangeRef.current?.(false)
}, [containerRef])
+ const markDisengaged = useCallback(() => {
+ const container = containerRef?.current
+ if (!container) return
+ const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
+ userScrolledAtRef.current = Date.now()
+ scrollRequestIdRef.current += 1
+ if (!isScrollButtonVisibleRef.current && distanceFromBottom > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
+ isScrollButtonVisibleRef.current = true
+ onScrollStateChangeRef.current?.(true)
+ }
+ userDisengagedRef.current = true
+ }, [containerRef])
+
+ const scrollByUser = useCallback((delta: number) => {
+ const container = containerRef?.current
+ if (!container) return
+ if (delta < 0) {
+ markDisengaged()
+ }
+ container.scrollBy({ top: delta })
+ }, [containerRef, markDisengaged])
+
useEffect(() => {
lastMessageCountRef.current = 0
lastMessageIdRef.current = undefined
@@ -76,19 +99,6 @@ export function useAutoScroll({
const container = containerRef?.current
if (!container) return
- const markDisengaged = () => {
- const container = containerRef?.current
- if (!container) return
- const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
- userScrolledAtRef.current = Date.now()
- scrollRequestIdRef.current += 1
- if (!isScrollButtonVisibleRef.current && distanceFromBottom > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
- isScrollButtonVisibleRef.current = true
- onScrollStateChangeRef.current?.(true)
- }
- userDisengagedRef.current = true
- }
-
const updateScrollButtonVisibility = () => {
const container = containerRef?.current
if (!container || !userDisengagedRef.current || isScrollButtonVisibleRef.current) return
@@ -196,7 +206,7 @@ export function useAutoScroll({
container.removeEventListener('keydown', handleKeyDown)
container.removeEventListener('scroll', handleScroll)
}
- }, [containerRef, sessionId, messages])
+ }, [containerRef, sessionId, messages, markDisengaged])
useEffect(() => {
if (!containerRef?.current || !messages) return
@@ -243,5 +253,5 @@ export function useAutoScroll({
scrollToBottom()
}, [messages, containerRef, scrollToBottom, contentVersion])
- return { scrollToBottom }
+ return { scrollToBottom, scrollByUser }
}
diff --git a/frontend/src/hooks/useDialogParam.ts b/frontend/src/hooks/useDialogParam.ts
index de40cce0..63b3aaf2 100644
--- a/frontend/src/hooks/useDialogParam.ts
+++ b/frontend/src/hooks/useDialogParam.ts
@@ -20,14 +20,25 @@ export function dialogSearch(name: string, extraParams?: Record)
return `?${params.toString()}`
}
+/**
+ * Opens a dialog in an existing param set: sets `dialog` to `name`, applies `extraParams`, and clears `mobileTab`.
+ */
+export function openDialogParams(
+ params: URLSearchParams,
+ name: string,
+ extraParams?: Record,
+): void {
+ setDialogParams(params, name, extraParams)
+ params.delete('mobileTab')
+}
+
export function openDialogParam(
updateParams: ReturnType['updateParams'],
name: string,
extraParams?: Record,
): void {
updateParams((p) => {
- setDialogParams(p, name, extraParams)
- p.delete('mobileTab')
+ openDialogParams(p, name, extraParams)
}, 'push')
}
diff --git a/frontend/src/hooks/useGlobalShortcutActions.test.tsx b/frontend/src/hooks/useGlobalShortcutActions.test.tsx
new file mode 100644
index 00000000..b166cfc1
--- /dev/null
+++ b/frontend/src/hooks/useGlobalShortcutActions.test.tsx
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, render, screen, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { MemoryRouter, useLocation } from 'react-router-dom'
+import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
+import { useGlobalShortcutActions } from './useGlobalShortcutActions'
+
+const mocks = vi.hoisted(() => ({
+ getRepo: vi.fn(),
+ createSession: vi.fn(),
+ useMobile: vi.fn(),
+}))
+
+vi.mock('@/hooks/useSettings', () => ({
+ useSettings: () => ({
+ preferences: { leaderKey: 'Ctrl+O', keyboardShortcuts: {}, directShortcuts: undefined },
+ }),
+}))
+
+vi.mock('@/hooks/useMobile', () => ({
+ useMobile: mocks.useMobile,
+}))
+
+vi.mock('@/api/repos', () => ({
+ getRepo: mocks.getRepo,
+}))
+
+vi.mock('@/api/opencode', () => ({
+ createSession: mocks.createSession,
+}))
+
+function Harness() {
+ useGlobalShortcutActions()
+ return null
+}
+
+function LocationDisplay() {
+ const location = useLocation()
+ return {`${location.pathname}${location.search}`}
+}
+
+function pressKey(init: KeyboardEventInit) {
+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
+ act(() => {
+ document.body.dispatchEvent(event)
+ })
+ return event
+}
+
+function pressLeaderFollowUp(key: string) {
+ pressKey({ key: 'o', ctrlKey: true })
+ pressKey({ key })
+}
+
+describe('useGlobalShortcutActions', () => {
+ let queryClient: QueryClient
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ mocks.useMobile.mockReturnValue(false)
+ mocks.getRepo.mockResolvedValue({ id: 5, fullPath: '/repo/five' })
+ mocks.createSession.mockResolvedValue({ id: 'session-new' })
+ })
+
+ afterEach(() => {
+ queryClient.clear()
+ })
+
+ function renderHarness(initialEntry: string) {
+ render(
+
+
+
+
+
+
+
+ ,
+ )
+ return {
+ location: () => screen.getByTestId('location').textContent,
+ }
+ }
+
+ it('opens the terminal dialog on the assistant host from the root route', async () => {
+ const { location } = renderHarness('/')
+
+ pressLeaderFollowUp('t')
+
+ await waitFor(() => expect(location()).toBe('/assistant?dialog=terminal'))
+ })
+
+ it('navigates to the nearest repo host from a repo sub-route without the tool', async () => {
+ const { location } = renderHarness('/repos/5/schedules')
+
+ pressLeaderFollowUp('t')
+
+ await waitFor(() => expect(location()).toBe('/repos/5?dialog=terminal'))
+ })
+
+ it('toggles the docked panel on and off when the route hosts the tool', async () => {
+ const { location } = renderHarness('/repos/5')
+
+ pressLeaderFollowUp('t')
+ await waitFor(() => expect(location()).toBe('/repos/5?panel=terminal'))
+
+ pressLeaderFollowUp('t')
+ await waitFor(() => expect(location()).toBe('/repos/5'))
+ })
+
+ it('toggles the dialog instead of the panel on mobile', async () => {
+ mocks.useMobile.mockReturnValue(true)
+ const { location } = renderHarness('/repos/5')
+
+ pressLeaderFollowUp('t')
+
+ await waitFor(() => expect(location()).toBe('/repos/5?dialog=terminal'))
+ })
+
+ it('creates a session in the repo directory and navigates to it from the leader shortcut', async () => {
+ queryClient.setQueryData(['repo', 5], { id: 5, fullPath: '/repo/five' })
+ const { location } = renderHarness('/repos/5')
+
+ pressKey({ key: 'o', ctrlKey: true })
+ pressKey({ key: 'n' })
+
+ await waitFor(() => expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/repo/five' }))
+ await waitFor(() => expect(location()).toBe('/repos/5/sessions/session-new'))
+ })
+
+ it('does not swallow the follow-up key when the route has no new-session host', async () => {
+ renderHarness('/')
+
+ pressKey({ key: 'o', ctrlKey: true })
+ const followUp = pressKey({ key: 'n' })
+
+ expect(followUp.defaultPrevented).toBe(false)
+ expect(mocks.createSession).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/hooks/useGlobalShortcutActions.ts b/frontend/src/hooks/useGlobalShortcutActions.ts
new file mode 100644
index 00000000..56befd1f
--- /dev/null
+++ b/frontend/src/hooks/useGlobalShortcutActions.ts
@@ -0,0 +1,67 @@
+import { useCallback, useMemo } from 'react'
+import { useLocation, useNavigate } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
+import { getRepo } from '@/api/repos'
+import { buildToolItems, toolKeyOf } from '@/components/navigation/moreDrawerItems'
+import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
+import { dialogSearch } from '@/hooks/useDialogParam'
+import { useCreateSession } from '@/hooks/useOpenCode'
+import { useMobile } from '@/hooks/useMobile'
+import { useSettingsDialog } from '@/hooks/useSettingsDialog'
+import { useUrlParams } from '@/hooks/useUrlParams'
+import { toggleToolDialogParams, toggleToolPanelParams, type PanelTool } from '@/hooks/useToolPanel'
+import { getAssistantPath, getRepoPath, getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
+
+/**
+ * Registers the app-wide shortcut actions: the settings dialog, the route tool panels, and repo-scoped session
+ * creation. Page layers can override any of these by registering the same action name.
+ */
+export function useGlobalShortcutActions(): void {
+ const { pathname } = useLocation()
+ const navigate = useNavigate()
+ const { updateParams } = useUrlParams()
+ const { open: openSettings } = useSettingsDialog()
+ const isMobile = useMobile()
+
+ const repoId = isAssistantPath(pathname) ? ASSISTANT_REPO_ID : parseRepoRoute(pathname).repoId
+
+ const { data: repo } = useQuery({
+ queryKey: ['repo', repoId],
+ queryFn: () => getRepo(repoId as number),
+ enabled: repoId !== null,
+ })
+
+ const createSession = useCreateSession(repo?.fullPath, (session) => {
+ if (repoId === null) return
+ navigate(getSessionPath(repoId, session.id))
+ })
+
+ const toolItems = useMemo(() => buildToolItems(pathname), [pathname])
+ const hasFilesTool = toolItems.some((item) => toolKeyOf(item) === 'files')
+
+ const toggleRouteTool = useCallback((tool: PanelTool) => {
+ if (toolItems.some((item) => toolKeyOf(item) === tool)) {
+ updateParams((params) => {
+ if (isMobile) toggleToolDialogParams(params, tool)
+ else toggleToolPanelParams(params, tool)
+ }, 'push')
+ return
+ }
+ if (tool === 'files') return
+ const host = repoId !== null ? getRepoPath(repoId) : getAssistantPath()
+ navigate(`${host}${dialogSearch(tool)}`)
+ }, [toolItems, isMobile, updateParams, navigate, repoId])
+
+ const newSession = repoId !== null && repo?.fullPath && !createSession.isPending
+ ? () => createSession.mutate({})
+ : undefined
+
+ useShortcutActions({
+ settings: openSettings,
+ toggleTerminal: () => toggleRouteTool('terminal'),
+ toggleSourceControl: () => toggleRouteTool('sourceControl'),
+ toggleSidebar: hasFilesTool ? () => toggleRouteTool('files') : undefined,
+ newSession,
+ }, 'global')
+}
diff --git a/frontend/src/hooks/useKeyboardShortcuts.test.tsx b/frontend/src/hooks/useKeyboardShortcuts.test.tsx
deleted file mode 100644
index d5d1f33e..00000000
--- a/frontend/src/hooks/useKeyboardShortcuts.test.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-import { renderHook } from '@testing-library/react'
-import { useKeyboardShortcuts } from './useKeyboardShortcuts'
-
-vi.mock('./useSettings', () => ({
- useSettings: () => ({
- preferences: { keyboardShortcuts: { submit: 'Return' }, directShortcuts: ['submit'] },
- }),
-}))
-
-describe('useKeyboardShortcuts', () => {
- it('runs a direct shortcut from a text input', () => {
- const submitPrompt = vi.fn()
- renderHook(() => useKeyboardShortcuts({ submitPrompt }))
- const textarea = document.body.appendChild(document.createElement('textarea'))
-
- textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
-
- expect(submitPrompt).toHaveBeenCalledTimes(1)
- textarea.remove()
- })
-
- it('ignores key events a component already handled', () => {
- const submitPrompt = vi.fn()
- renderHook(() => useKeyboardShortcuts({ submitPrompt }))
- const textarea = document.body.appendChild(document.createElement('textarea'))
- textarea.addEventListener('keydown', (event) => event.preventDefault())
-
- textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
-
- expect(submitPrompt).not.toHaveBeenCalled()
- textarea.remove()
- })
-})
diff --git a/frontend/src/hooks/useKeyboardShortcuts.ts b/frontend/src/hooks/useKeyboardShortcuts.ts
deleted file mode 100644
index 034ab4c7..00000000
--- a/frontend/src/hooks/useKeyboardShortcuts.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-import { useEffect, useCallback, useRef, useState } from 'react'
-import { useSettings } from './useSettings'
-import { DEFAULT_LEADER_KEY } from '@/api/types/settings'
-
-const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
-
-const normalizeShortcut = (shortcut: string): string => {
- return shortcut.replace(/Cmd/g, isMac ? 'Cmd' : 'Ctrl')
-}
-
-const parseEventShortcut = (e: KeyboardEvent): string => {
- const keys = []
- if (e.ctrlKey) keys.push('Ctrl')
- if (e.metaKey) keys.push('Cmd')
- if (e.altKey) keys.push('Alt')
- if (e.shiftKey) keys.push('Shift')
-
- const mainKey = e.key
- if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
- let displayKey = mainKey
- if (mainKey === ' ') displayKey = 'Space'
- else if (mainKey === 'ArrowUp') displayKey = 'Up'
- else if (mainKey === 'ArrowDown') displayKey = 'Down'
- else if (mainKey === 'ArrowLeft') displayKey = 'Left'
- else if (mainKey === 'ArrowRight') displayKey = 'Right'
- else if (mainKey === 'Enter') displayKey = 'Return'
- else if (mainKey === 'Escape') displayKey = 'Esc'
- else if (mainKey === 'Tab') displayKey = 'Tab'
- else if (mainKey === 'Backspace') displayKey = 'Backspace'
- else if (mainKey === 'Delete') displayKey = 'Delete'
- else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
-
- keys.push(displayKey)
- return keys.join('+')
- }
- return ''
-}
-
-const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
-const LEADER_TIMEOUT = 1500
-
-interface ShortcutActions {
- openModelDialog?: () => void
- openSessions?: () => void
- sessions?: () => void
- newSession?: () => void
- closeSession?: () => void
- toggleSidebar?: () => void
- submitPrompt?: () => void
- interruptSession?: () => void
- toggleMode?: () => void
- undo?: () => void
- redo?: () => void
- compact?: () => void
- fork?: () => void
- openSettings?: () => void
-}
-
-export function useKeyboardShortcuts(actions: ShortcutActions = {}) {
- const { preferences } = useSettings()
- const [leaderActive, setLeaderActive] = useState(false)
- const leaderTimeoutRef = useRef | null>(null)
- const preferencesRef = useRef(preferences)
- preferencesRef.current = preferences
-
- const actionsRef = useRef(actions)
- actionsRef.current = actions
-
- const clearLeaderTimeout = useCallback(() => {
- if (leaderTimeoutRef.current) {
- clearTimeout(leaderTimeoutRef.current)
- leaderTimeoutRef.current = null
- }
- }, [])
-
- const executeAction = useCallback((action: string, e: KeyboardEvent) => {
- e.preventDefault()
- const currentActions = actionsRef.current
-
- switch (action) {
- case 'selectModel':
- currentActions.openModelDialog?.()
- break
- case 'sessions':
- currentActions.openSessions?.()
- break
- case 'newSession':
- currentActions.newSession?.()
- break
- case 'closeSession':
- currentActions.closeSession?.()
- break
- case 'toggleSidebar':
- currentActions.toggleSidebar?.()
- break
- case 'submit':
- currentActions.submitPrompt?.()
- break
- case 'abort':
- currentActions.interruptSession?.()
- break
- case 'toggleMode':
- currentActions.toggleMode?.()
- break
- case 'undo':
- currentActions.undo?.()
- break
- case 'redo':
- currentActions.redo?.()
- break
- case 'compact':
- currentActions.compact?.()
- break
- case 'fork':
- currentActions.fork?.()
- break
- case 'settings':
- currentActions.openSettings?.()
- break
- }
- }, [])
-
- const handleKeyDown = useCallback((e: KeyboardEvent) => {
- if (e.defaultPrevented) return
- const shortcut = parseEventShortcut(e)
- if (!shortcut) return
-
- const prefs = preferencesRef.current
- const shortcuts = prefs?.keyboardShortcuts || {}
- const leaderKey = normalizeShortcut(prefs?.leaderKey || DEFAULT_LEADER_KEY)
- const directShortcuts = prefs?.directShortcuts ?? DEFAULT_DIRECT_SHORTCUTS
-
- const activeFileEditor = document.querySelector('[data-file-editor="true"]')
- if (activeFileEditor && document.activeElement === activeFileEditor) {
- return
- }
-
- const target = e.target as HTMLElement
- const isInInput = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.contentEditable === 'true'
- const isFileEditor = target.getAttribute('data-file-editor') === 'true'
-
- if (isFileEditor) return
-
- if (leaderActive) {
- clearLeaderTimeout()
- setLeaderActive(false)
-
- const action = Object.entries(shortcuts).find(([actionName, keys]) => {
- if (directShortcuts.includes(actionName)) return false
- if (!keys) return false
- return normalizeShortcut(keys) === shortcut
- })?.[0]
-
- if (action) {
- executeAction(action, e)
- }
- return
- }
-
- if (shortcut === leaderKey && !isInInput) {
- e.preventDefault()
- setLeaderActive(true)
- clearLeaderTimeout()
- leaderTimeoutRef.current = setTimeout(() => {
- setLeaderActive(false)
- }, LEADER_TIMEOUT)
- return
- }
-
- const directAction = Object.entries(shortcuts).find(([actionName, keys]) => {
- if (!directShortcuts.includes(actionName)) return false
- if (!keys) return false
- return normalizeShortcut(keys) === shortcut
- })?.[0]
-
- if (directAction) {
- if (isInInput && directAction !== 'submit' && directAction !== 'abort') {
- return
- }
- executeAction(directAction, e)
- }
- }, [leaderActive, clearLeaderTimeout, executeAction])
-
- useEffect(() => {
- document.addEventListener('keydown', handleKeyDown)
- return () => {
- document.removeEventListener('keydown', handleKeyDown)
- clearLeaderTimeout()
- }
- }, [handleKeyDown, clearLeaderTimeout])
-
- return { leaderActive }
-}
\ No newline at end of file
diff --git a/frontend/src/hooks/useOpenCode.test.tsx b/frontend/src/hooks/useOpenCode.test.tsx
index e5019ca6..68c370a0 100644
--- a/frontend/src/hooks/useOpenCode.test.tsx
+++ b/frontend/src/hooks/useOpenCode.test.tsx
@@ -134,12 +134,58 @@ describe('useSessionsAcrossDirectories', () => {
})
})
- it('deletes each session through the facade and invalidates the session list cache', async () => {
+ it('issues one call per page across all directories and paginates by cursor', async () => {
+ mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
+ if (cursor === 'cursor_all') {
+ return { items: [sessionInfo('ses_all2', '/w/b', 2000)] }
+ }
+ return { items: [sessionInfo('ses_all1', '/w/a')], nextCursor: 'cursor_all' }
+ })
+
+ const queryClient = createQueryClient()
+ const { result } = renderHook(
+ () => useSessionsAcrossDirectories(['/w/a', '/w/b'], { allDirectories: true }),
+ { wrapper: createWrapper(queryClient) },
+ )
+
+ await waitFor(() => {
+ expect(result.current.isLoading).toBe(false)
+ })
+
+ expect(mocks.listSessionPage).toHaveBeenCalledTimes(1)
+ expect(mocks.listSessionPage).toHaveBeenCalledWith({
+ limit: 25,
+ order: 'desc',
+ search: undefined,
+ })
+ expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1'])
+ expect(result.current.hasNextPage).toBe(true)
+
+ await act(async () => {
+ await result.current.fetchNextPage()
+ })
+
+ await waitFor(() => {
+ expect(result.current.data).toHaveLength(2)
+ })
+
+ expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
+ expect(mocks.listSessionPage).toHaveBeenLastCalledWith({ cursor: 'cursor_all' })
+ expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
+ })
+
+ it('deletes each session through the facade and removes it from cached lists without invalidating', async () => {
mocks.deleteSession.mockResolvedValue(undefined)
const queryClient = createQueryClient()
- const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25 }]
- queryClient.setQueryData(listKey, { pages: [{ items: [], cursors: {} }], pageParams: [undefined] })
+ const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25, allDirectories: false }]
+ queryClient.setQueryData(listKey, {
+ pages: [{
+ items: [sessionInfo('ses_a1', '/w/a'), sessionInfo('ses_a2', '/w/a')],
+ nextParam: undefined,
+ }],
+ pageParams: [undefined],
+ })
const { result } = renderHook(() => useDeleteSession(['/w/a']), {
wrapper: createWrapper(queryClient),
@@ -150,10 +196,112 @@ describe('useSessionsAcrossDirectories', () => {
})
expect(mocks.deleteSession).toHaveBeenCalledWith('ses_a1')
+ const cached = queryClient.getQueryData<{ pages: Array<{ items: SessionInfo[] }> }>(listKey)
+ expect(cached?.pages[0].items.map((session) => session.id)).toEqual(['ses_a2'])
+ expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(false)
+ })
+
+ it('invalidates the session list cache when a delete fails', async () => {
+ mocks.deleteSession.mockRejectedValue(new Error('nope'))
+
+ const queryClient = createQueryClient()
+ const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25, allDirectories: false }]
+ queryClient.setQueryData(listKey, {
+ pages: [{ items: [sessionInfo('ses_a1', '/w/a')], nextParam: undefined }],
+ pageParams: [undefined],
+ })
+
+ const { result } = renderHook(() => useDeleteSession(['/w/a']), {
+ wrapper: createWrapper(queryClient),
+ })
+
+ await act(async () => {
+ await expect(
+ result.current.mutateAsync({ id: 'ses_a1', directory: '/w/a' }),
+ ).rejects.toThrow('Failed to delete 1 session(s)')
+ })
+
await waitFor(() => {
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true)
})
})
+
+ it('does not keep previous results across a search change unless requested', async () => {
+ let resolveSearch: ((value: { items: SessionInfo[] }) => void) | undefined
+ mocks.listSessionPage.mockImplementation(({ search }: { search?: string }) => {
+ if (search === 'deploy') {
+ return new Promise<{ items: SessionInfo[] }>((resolve) => { resolveSearch = resolve })
+ }
+ return Promise.resolve({ items: [sessionInfo('ses_a1', '/w/a')] })
+ })
+
+ const queryClient = createQueryClient()
+ const { result, rerender } = renderHook(
+ (props: { search?: string }) => useSessionsAcrossDirectories(['/w/a'], { search: props.search }),
+ { wrapper: createWrapper(queryClient), initialProps: { search: undefined as string | undefined } },
+ )
+
+ await waitFor(() => {
+ expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1'])
+ })
+
+ rerender({ search: 'deploy' })
+
+ await waitFor(() => expect(resolveSearch).toBeDefined())
+
+ expect(result.current.isPlaceholderData).toBe(false)
+ expect(result.current.isLoading).toBe(true)
+ expect(result.current.data).toHaveLength(0)
+
+ await act(async () => {
+ resolveSearch?.({ items: [sessionInfo('ses_b1', '/w/a')] })
+ })
+
+ await waitFor(() => {
+ expect(result.current.data.map((session) => session.id)).toEqual(['ses_b1'])
+ })
+ })
+
+ it('keeps previous results across a search change when requested', async () => {
+ let resolveSearch: ((value: { items: SessionInfo[] }) => void) | undefined
+ mocks.listSessionPage.mockImplementation(({ search }: { search?: string }) => {
+ if (search === 'deploy') {
+ return new Promise<{ items: SessionInfo[] }>((resolve) => { resolveSearch = resolve })
+ }
+ return Promise.resolve({ items: [sessionInfo('ses_a1', '/w/a')] })
+ })
+
+ const queryClient = createQueryClient()
+ const { result, rerender } = renderHook(
+ (props: { search?: string; keepPreviousResults?: boolean }) =>
+ useSessionsAcrossDirectories(['/w/a'], {
+ search: props.search,
+ keepPreviousResults: props.keepPreviousResults,
+ }),
+ {
+ wrapper: createWrapper(queryClient),
+ initialProps: { search: undefined as string | undefined, keepPreviousResults: true },
+ },
+ )
+
+ await waitFor(() => {
+ expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1'])
+ })
+
+ rerender({ search: 'deploy', keepPreviousResults: true })
+
+ await waitFor(() => expect(result.current.isPlaceholderData).toBe(true))
+ expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1'])
+
+ await act(async () => {
+ resolveSearch?.({ items: [sessionInfo('ses_b1', '/w/a')] })
+ })
+
+ await waitFor(() => {
+ expect(result.current.data.map((session) => session.id)).toEqual(['ses_b1'])
+ })
+ expect(result.current.isPlaceholderData).toBe(false)
+ })
})
describe('useSession', () => {
diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts
index 3b5ec6b9..79d22ac3 100644
--- a/frontend/src/hooks/useOpenCode.ts
+++ b/frontend/src/hooks/useOpenCode.ts
@@ -1,4 +1,4 @@
-import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
+import { useQuery, useMutation, useQueryClient, useInfiniteQuery, type InfiniteData } from "@tanstack/react-query";
import { useMemo, useRef, useEffect, useCallback } from "react";
import {
createSession,
@@ -41,9 +41,20 @@ const EMPTY_SESSIONS: SessionInfo[] = []
interface UseSessionsAcrossDirectoriesOptions {
search?: string
limit?: number
+ keepPreviousResults?: boolean
+ allDirectories?: boolean
}
-type SessionPageParam = Record
+type SessionDirectoryCursors = Record
+
+type SessionListPageParam =
+ | { mode: 'directories'; cursors: SessionDirectoryCursors }
+ | { mode: 'all'; cursor: string }
+
+interface SessionListPage {
+ items: SessionInfo[]
+ nextParam?: SessionListPageParam
+}
export const useSessionsAcrossDirectories = (
directories: string[],
@@ -55,12 +66,33 @@ export const useSessionsAcrossDirectories = (
);
const normalizedSearch = options?.search?.trim() || undefined;
const limit = options?.limit ?? SESSION_LIST_PAGE_SIZE;
+ const keepPreviousResults = options?.keepPreviousResults ?? false;
+ const allDirectories = options?.allDirectories ?? false;
const directoryKey = uniqueDirectories.join('|');
- const query = useInfiniteQuery({
- queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit }],
+ const query = useInfiniteQuery<
+ SessionListPage,
+ Error,
+ InfiniteData,
+ readonly unknown[],
+ SessionListPageParam | undefined
+ >({
+ queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit, allDirectories }],
queryFn: async ({ pageParam }) => {
- if (!pageParam) {
+ if (allDirectories) {
+ const cursor = pageParam?.mode === 'all' ? pageParam.cursor : undefined;
+ const page = await listSessionPage(
+ cursor === undefined
+ ? { limit, order: 'desc', search: normalizedSearch }
+ : { cursor },
+ );
+ return {
+ items: page.items,
+ nextParam: page.nextCursor ? { mode: 'all', cursor: page.nextCursor } : undefined,
+ };
+ }
+
+ if (!pageParam || pageParam.mode !== 'directories') {
const pages = await Promise.all(
uniqueDirectories.map((directory) =>
listSessionPage({
@@ -71,7 +103,7 @@ export const useSessionsAcrossDirectories = (
}),
),
);
- const cursors: SessionPageParam = {};
+ const cursors: SessionDirectoryCursors = {};
const items: SessionInfo[] = [];
for (let i = 0; i < pages.length; i++) {
items.push(...pages[i].items);
@@ -79,14 +111,17 @@ export const useSessionsAcrossDirectories = (
cursors[uniqueDirectories[i]] = pages[i].nextCursor!;
}
}
- return { items, cursors };
+ return {
+ items,
+ nextParam: Object.keys(cursors).length > 0 ? { mode: 'directories', cursors } : undefined,
+ };
}
- const entries = Object.entries(pageParam);
+ const entries = Object.entries(pageParam.cursors);
const pages = await Promise.all(
entries.map(([directory, cursor]) => listSessionPage({ directory, cursor })),
);
- const cursors: SessionPageParam = {};
+ const cursors: SessionDirectoryCursors = {};
const items: SessionInfo[] = [];
for (let i = 0; i < pages.length; i++) {
items.push(...pages[i].items);
@@ -94,15 +129,17 @@ export const useSessionsAcrossDirectories = (
cursors[entries[i][0]] = pages[i].nextCursor!;
}
}
- return { items, cursors };
- },
- initialPageParam: undefined as SessionPageParam | undefined,
- getNextPageParam: (lastPage) => {
- if (Object.keys(lastPage.cursors).length > 0) {
- return lastPage.cursors;
- }
- return undefined;
+ return {
+ items,
+ nextParam: Object.keys(cursors).length > 0 ? { mode: 'directories', cursors } : undefined,
+ };
},
+ initialPageParam: undefined as SessionListPageParam | undefined,
+ placeholderData: keepPreviousResults
+ ? (previousData, previousQuery) =>
+ previousQuery?.queryKey[2] === directoryKey ? previousData : undefined
+ : undefined,
+ getNextPageParam: (lastPage) => lastPage.nextParam,
enabled: uniqueDirectories.length > 0,
staleTime: 10000,
refetchOnWindowFocus: true,
@@ -117,6 +154,7 @@ export const useSessionsAcrossDirectories = (
return {
data,
isLoading: query.isLoading,
+ isPlaceholderData: query.isPlaceholderData,
isError: query.isError,
fetchNextPage: query.fetchNextPage,
hasNextPage: query.hasNextPage,
@@ -245,19 +283,43 @@ export const useDeleteSession = (directory?: string | string[]) => {
return { deleted: targets.length, results }
},
- onSuccess: ({ deleted }) => {
+ onSuccess: ({ deleted }, variables) => {
+ removeDeletedSessionsFromListCaches(queryClient, variables);
+ cleanupSessionPins(queryClient, variables, primaryDirectory);
showToast.success(deleted === 1 ? 'Session deleted' : `${deleted} sessions deleted`);
},
- onError: () => {
- showToast.error('Failed to delete sessions');
- },
- onSettled: (_data, _error, variables) => {
+ onError: (_error, variables) => {
invalidateSessionListCaches(queryClient);
cleanupSessionPins(queryClient, variables, primaryDirectory);
+ showToast.error('Failed to delete sessions');
},
});
};
+const removeDeletedSessionsFromListCaches = (
+ queryClient: ReturnType,
+ variables: DeleteSessionTarget | DeleteSessionTarget[],
+) => {
+ const deletedIDs = new Set(
+ (Array.isArray(variables) ? variables : [variables]).map(getDeleteSessionTargetId),
+ );
+ if (deletedIDs.size === 0) return;
+ queryClient.setQueriesData>(
+ { queryKey: ['opencode', 'sessions'] },
+ (current) => {
+ if (!current) return current;
+ let changed = false;
+ const pages = current.pages.map((page) => {
+ const items = page.items.filter((item) => !deletedIDs.has(item.id));
+ if (items.length === page.items.length) return page;
+ changed = true;
+ return { ...page, items };
+ });
+ return changed ? { ...current, pages } : current;
+ },
+ );
+};
+
const cleanupSessionPins = (
queryClient: ReturnType,
variables: DeleteSessionTarget | DeleteSessionTarget[],
diff --git a/frontend/src/hooks/usePersistentBoolean.test.tsx b/frontend/src/hooks/usePersistentBoolean.test.tsx
new file mode 100644
index 00000000..1b928332
--- /dev/null
+++ b/frontend/src/hooks/usePersistentBoolean.test.tsx
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+import { usePersistentBoolean } from './usePersistentBoolean'
+
+const STORAGE_KEY = 'oc:test:flag'
+
+const localStorageMock = {
+ getItem: vi.fn(),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ clear: vi.fn(),
+}
+
+describe('usePersistentBoolean', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ Object.defineProperty(global, 'localStorage', {
+ value: localStorageMock,
+ writable: true,
+ })
+ })
+
+ afterEach(() => {
+ Object.defineProperty(global, 'localStorage', {
+ value: window.localStorage,
+ writable: true,
+ })
+ vi.restoreAllMocks()
+ })
+
+ it('returns the fallback when no stored value', () => {
+ localStorageMock.getItem.mockReturnValue(null)
+
+ const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
+
+ expect(localStorageMock.getItem).toHaveBeenCalledWith(STORAGE_KEY)
+ expect(result.current[0]).toBe(false)
+ })
+
+ it('returns a stored true value', () => {
+ localStorageMock.getItem.mockReturnValue('true')
+
+ const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
+
+ expect(result.current[0]).toBe(true)
+ })
+
+ it('toggles the value and persists it to localStorage', () => {
+ localStorageMock.getItem.mockReturnValue(null)
+
+ const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
+
+ expect(result.current[0]).toBe(false)
+
+ act(() => {
+ result.current[1]()
+ })
+
+ expect(result.current[0]).toBe(true)
+ expect(localStorageMock.setItem).toHaveBeenCalledWith(STORAGE_KEY, 'true')
+ })
+
+ it('returns the fallback when the stored value is malformed JSON', () => {
+ localStorageMock.getItem.mockReturnValue('not-json{{')
+
+ const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
+
+ expect(result.current[0]).toBe(false)
+ })
+
+ it('returns the fallback when the stored value is JSON but not a boolean', () => {
+ localStorageMock.getItem.mockReturnValue('"some string"')
+
+ const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
+
+ expect(result.current[0]).toBe(false)
+ })
+
+ it('honours a true fallback when no value is stored', () => {
+ localStorageMock.getItem.mockReturnValue(null)
+
+ const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, true))
+
+ expect(result.current[0]).toBe(true)
+ })
+})
diff --git a/frontend/src/hooks/usePersistentBoolean.ts b/frontend/src/hooks/usePersistentBoolean.ts
new file mode 100644
index 00000000..82d3f3d4
--- /dev/null
+++ b/frontend/src/hooks/usePersistentBoolean.ts
@@ -0,0 +1,48 @@
+import { useState, useCallback } from 'react'
+
+function readStorage(key: string): string | null {
+ try {
+ return localStorage.getItem(key)
+ } catch {
+ return null
+ }
+}
+
+function writeStorage(key: string, value: unknown): void {
+ try {
+ localStorage.setItem(key, JSON.stringify(value))
+ } catch {
+ return
+ }
+}
+
+function readStoredBoolean(key: string, fallback: boolean): boolean {
+ const stored = readStorage(key)
+ if (stored === null) {
+ return fallback
+ }
+ try {
+ const parsed = JSON.parse(stored)
+ return typeof parsed === 'boolean' ? parsed : fallback
+ } catch {
+ return fallback
+ }
+}
+
+/**
+ * Persists a boolean preference under `key` in localStorage and returns it with a toggler.
+ * Falls back to `fallback` when the stored value is missing or malformed.
+ */
+export function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
+ const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
+
+ const toggle = useCallback(() => {
+ setValue((prev: boolean) => {
+ const newValue = !prev
+ writeStorage(key, newValue)
+ return newValue
+ })
+ }, [key])
+
+ return [value, toggle]
+}
diff --git a/frontend/src/hooks/useRestoreFocusOnClose.ts b/frontend/src/hooks/useRestoreFocusOnClose.ts
new file mode 100644
index 00000000..34e6b320
--- /dev/null
+++ b/frontend/src/hooks/useRestoreFocusOnClose.ts
@@ -0,0 +1,27 @@
+import { useEffect, useRef, type RefObject } from 'react'
+import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
+
+/**
+ * Captures the focused element when an overlay opens and restores focus to it when the overlay closes.
+ *
+ * The opener is captured during render on the closed-to-open transition, before children with
+ * `autoFocus` claim focus during commit, and is idempotent across StrictMode's double render.
+ */
+export function useRestoreFocusOnClose(
+ isOpen: boolean,
+ containerRef: RefObject,
+): void {
+ const returnFocusRef = useRef(null)
+ const wasOpenRef = useRef(false)
+
+ if (isOpen && !wasOpenRef.current) {
+ returnFocusRef.current = getFocusedElement()
+ }
+
+ useEffect(() => {
+ if (!isOpen && wasOpenRef.current) {
+ restoreOverlayFocus(returnFocusRef.current, containerRef.current)
+ }
+ wasOpenRef.current = isOpen
+ }, [isOpen, containerRef])
+}
diff --git a/frontend/src/hooks/useSessionSearch.test.tsx b/frontend/src/hooks/useSessionSearch.test.tsx
new file mode 100644
index 00000000..77b03bda
--- /dev/null
+++ b/frontend/src/hooks/useSessionSearch.test.tsx
@@ -0,0 +1,149 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { useSessionSearch } from './useSessionSearch'
+
+const { sessionsData, lastArgsRef, flagsRef } = vi.hoisted(() => ({
+ sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
+ lastArgsRef: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean } } | undefined },
+ flagsRef: { current: { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false } },
+}))
+
+vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean }) => {
+ lastArgsRef.current = { directories, options }
+ const search = options?.search?.toLowerCase() ?? ''
+ const data = search
+ ? sessionsData.filter((session) => session.title.toLowerCase().includes(search))
+ : sessionsData
+ return {
+ data,
+ isLoading: false,
+ isError: flagsRef.current.isError,
+ isPlaceholderData: flagsRef.current.isPlaceholderData,
+ fetchNextPage: vi.fn(),
+ hasNextPage: flagsRef.current.hasNextPage,
+ isFetchingNextPage: flagsRef.current.isFetchingNextPage,
+ isFetchNextPageError: flagsRef.current.isFetchNextPageError,
+ }
+ },
+ }
+})
+
+describe('useSessionSearch', () => {
+ beforeEach(() => {
+ sessionsData.splice(0, sessionsData.length,
+ { id: 'ses_alpha', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 2 } },
+ { id: 'ses_beta', title: 'beta task', location: { directory: '/w/a' }, time: { updated: 1 } },
+ )
+ lastArgsRef.current = undefined
+ flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('filters sessions locally by title immediately', () => {
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ act(() => {
+ result.current.setQuery('alpha')
+ })
+
+ expect(result.current.filteredSessions.map((session) => session.title)).toEqual(['alpha task'])
+ expect(lastArgsRef.current?.options?.search).toBe('')
+ })
+
+ it('passes the debounced search to useSessionsAcrossDirectories with keepPreviousResults', () => {
+ vi.useFakeTimers()
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ act(() => {
+ result.current.setQuery('deploy')
+ })
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(lastArgsRef.current?.options?.search).toBe('deploy')
+ expect(lastArgsRef.current?.options?.limit).toBe(25)
+ expect(lastArgsRef.current?.options?.keepPreviousResults).toBe(true)
+ })
+
+ it('reports a pending search before the debounce settles', () => {
+ vi.useFakeTimers()
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ act(() => {
+ result.current.setQuery('deploy')
+ })
+
+ expect(result.current.isSearchPending).toBe(true)
+
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(result.current.isSearchPending).toBe(false)
+ })
+
+ it('passes allDirectories through to useSessionsAcrossDirectories', () => {
+ renderHook(() => useSessionSearch(['/w/a'], { allDirectories: true }))
+
+ expect(lastArgsRef.current?.options?.allDirectories).toBe(true)
+ })
+
+ it('passes isError through from useSessionsAcrossDirectories', () => {
+ flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: true }
+
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ expect(result.current.isError).toBe(true)
+ })
+
+ it('blocks pagination while a search is pending', () => {
+ vi.useFakeTimers()
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ expect(result.current.canFetchNextPage).toBe(true)
+
+ act(() => {
+ result.current.setQuery('deploy')
+ })
+
+ expect(result.current.isSearchPending).toBe(true)
+ expect(result.current.canFetchNextPage).toBe(false)
+
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(result.current.isSearchPending).toBe(false)
+ expect(result.current.canFetchNextPage).toBe(true)
+ })
+
+ it('exposes canFetchNextPage only when paging is safe', () => {
+ const { result, rerender } = renderHook(() => useSessionSearch(['/w/a']))
+ expect(result.current.canFetchNextPage).toBe(false)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(true)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: true, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(false)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: true, isPlaceholderData: false, isError: false }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(false)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: true, isError: false }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(false)
+ })
+})
diff --git a/frontend/src/hooks/useSessionSearch.ts b/frontend/src/hooks/useSessionSearch.ts
new file mode 100644
index 00000000..0f33b643
--- /dev/null
+++ b/frontend/src/hooks/useSessionSearch.ts
@@ -0,0 +1,70 @@
+import { useMemo, useState } from 'react'
+import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
+import { useDebouncedValue } from '@/hooks/useDebouncedValue'
+import { selectRootSessions } from '@/components/session/session-partition'
+import { getSessionKey } from '@/lib/sessionKey'
+
+const DEFAULT_LIMIT = 25
+
+export interface UseSessionSearchOptions {
+ limit?: number
+ allDirectories?: boolean
+}
+
+/**
+ * Owns the sessions-dialog search state: the raw query, its debounced server
+ * value, the root-session selection, and the immediate local title filter.
+ */
+export function useSessionSearch(directories: string[], options: UseSessionSearchOptions = {}) {
+ const limit = options.limit ?? DEFAULT_LIMIT
+ const allDirectories = options.allDirectories ?? false
+ const [query, setQuery] = useState('')
+ const trimmedQuery = query.trim()
+ const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
+ const search = trimmedQuery ? debouncedQuery : ''
+ const {
+ data: sessions,
+ isLoading,
+ isError,
+ isPlaceholderData,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ } = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true, allDirectories })
+
+ const directorySet = useMemo(() => new Set(directories), [directories])
+
+ const rootSessions = useMemo(
+ () => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionKey }),
+ [sessions, directorySet],
+ )
+
+ const filteredSessions = useMemo(() => {
+ if (!trimmedQuery) return rootSessions
+ const needle = trimmedQuery.toLowerCase()
+ return rootSessions.filter((session) => (session.title ?? '').toLowerCase().includes(needle))
+ }, [rootSessions, trimmedQuery])
+
+ const isSearchPending = trimmedQuery !== search || isPlaceholderData
+ const canFetchNextPage = Boolean(
+ hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isSearchPending,
+ )
+
+ return {
+ query,
+ setQuery,
+ trimmedQuery,
+ sessions,
+ filteredSessions,
+ isSearchPending,
+ isLoading,
+ isError,
+ isPlaceholderData,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ canFetchNextPage,
+ }
+}
diff --git a/frontend/src/hooks/useSidebarCollapsed.test.tsx b/frontend/src/hooks/useSidebarCollapsed.test.tsx
index 0aed5cef..a849f5cb 100644
--- a/frontend/src/hooks/useSidebarCollapsed.test.tsx
+++ b/frontend/src/hooks/useSidebarCollapsed.test.tsx
@@ -9,7 +9,7 @@ const localStorageMock = {
clear: vi.fn(),
}
-describe('sidebar collapse hooks', () => {
+describe('useSidebarCollapsed', () => {
beforeEach(() => {
vi.clearAllMocks()
Object.defineProperty(global, 'localStorage', {
@@ -26,52 +26,27 @@ describe('sidebar collapse hooks', () => {
vi.restoreAllMocks()
})
- describe('useSidebarCollapsed', () => {
- it('returns false by default when no stored value', () => {
- localStorageMock.getItem.mockReturnValue(null)
+ it('reads and persists under the sidebar storage key with a false default', () => {
+ localStorageMock.getItem.mockReturnValue(null)
- const { result } = renderHook(() => useSidebarCollapsed())
+ const { result } = renderHook(() => useSidebarCollapsed())
- expect(result.current[0]).toBe(false)
+ expect(localStorageMock.getItem).toHaveBeenCalledWith('oc:sidebar:collapsed')
+ expect(result.current[0]).toBe(false)
+
+ act(() => {
+ result.current[1]()
})
- it('returns stored value from localStorage', () => {
- localStorageMock.getItem.mockReturnValue('true')
+ expect(result.current[0]).toBe(true)
+ expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
+ })
- const { result } = renderHook(() => useSidebarCollapsed())
+ it('returns the stored value', () => {
+ localStorageMock.getItem.mockReturnValue('true')
- expect(result.current[0]).toBe(true)
- })
+ const { result } = renderHook(() => useSidebarCollapsed())
- it('toggles collapsed state and persists to localStorage', () => {
- localStorageMock.getItem.mockReturnValue(null)
-
- const { result } = renderHook(() => useSidebarCollapsed())
-
- expect(result.current[0]).toBe(false)
-
- act(() => {
- result.current[1]()
- })
-
- expect(result.current[0]).toBe(true)
- expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
- })
-
- it('returns false when stored value is malformed JSON', () => {
- localStorageMock.getItem.mockReturnValue('not-json{{')
-
- const { result } = renderHook(() => useSidebarCollapsed())
-
- expect(result.current[0]).toBe(false)
- })
-
- it('returns false when stored value is JSON but not a boolean', () => {
- localStorageMock.getItem.mockReturnValue('"some string"')
-
- const { result } = renderHook(() => useSidebarCollapsed())
-
- expect(result.current[0]).toBe(false)
- })
+ expect(result.current[0]).toBe(true)
})
})
diff --git a/frontend/src/hooks/useSidebarCollapsed.ts b/frontend/src/hooks/useSidebarCollapsed.ts
index 3ae6662a..a44ad6a9 100644
--- a/frontend/src/hooks/useSidebarCollapsed.ts
+++ b/frontend/src/hooks/useSidebarCollapsed.ts
@@ -1,50 +1,7 @@
-import { useState, useCallback } from 'react'
+import { usePersistentBoolean } from './usePersistentBoolean'
const STORAGE_KEY = 'oc:sidebar:collapsed'
-function readStorage(key: string): string | null {
- try {
- return localStorage.getItem(key)
- } catch {
- return null
- }
-}
-
-function writeStorage(key: string, value: unknown): void {
- try {
- localStorage.setItem(key, JSON.stringify(value))
- } catch {
- return
- }
-}
-
-function readStoredBoolean(key: string, fallback: boolean): boolean {
- const stored = readStorage(key)
- if (stored === null) {
- return fallback
- }
- try {
- const parsed = JSON.parse(stored)
- return typeof parsed === 'boolean' ? parsed : fallback
- } catch {
- return fallback
- }
-}
-
-function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
- const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
-
- const toggle = useCallback(() => {
- setValue((prev: boolean) => {
- const newValue = !prev
- writeStorage(key, newValue)
- return newValue
- })
- }, [key])
-
- return [value, toggle]
-}
-
export function useSidebarCollapsed(): [boolean, () => void] {
return usePersistentBoolean(STORAGE_KEY, false)
}
diff --git a/frontend/src/hooks/useSidebarRepoGroups.ts b/frontend/src/hooks/useSidebarRepoGroups.ts
index c72e5eb0..4fbd6399 100644
--- a/frontend/src/hooks/useSidebarRepoGroups.ts
+++ b/frontend/src/hooks/useSidebarRepoGroups.ts
@@ -3,7 +3,7 @@ import { useQueries, useQuery } from '@tanstack/react-query'
import { listRepos } from '@/api/repos'
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useSessionPins } from '@/hooks/useSessionPins'
-import { buildPinnedSessionKeys, buildSessionKey } from '@/lib/sessionKey'
+import { buildPinnedSessionKeys, buildSessionKey, getSessionKey } from '@/lib/sessionKey'
import type { Repo, Session } from '@/api/types'
import {
SIDEBAR_SESSIONS_PER_REPO,
@@ -46,9 +46,7 @@ export function useSidebarRepoGroups(input: {
const missingPins = useMemo(() => {
if (search) return []
const repoDirectories = new Set(directories)
- const fetchedKeys = new Set(
- sessions.map((session) => buildSessionKey(session.location.directory, session.id)),
- )
+ const fetchedKeys = new Set(sessions.map(getSessionKey))
return (sessionPins ?? []).filter(
(pin) =>
repoDirectories.has(pin.directory) &&
diff --git a/frontend/src/hooks/useToolPanel.test.ts b/frontend/src/hooks/useToolPanel.test.ts
new file mode 100644
index 00000000..24b41de9
--- /dev/null
+++ b/frontend/src/hooks/useToolPanel.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest'
+import { toggleToolDialogParams, toggleToolPanelParams } from './useToolPanel'
+
+describe('toggleToolPanelParams', () => {
+ it('opens a tool, clears other tools owned params, and preserves unrelated params', () => {
+ const params = new URLSearchParams('previewPort=3000&previewPath=%2Fx&keep=1')
+
+ toggleToolPanelParams(params, 'terminal')
+
+ expect(params.get('panel')).toBe('terminal')
+ expect(params.has('previewPort')).toBe(false)
+ expect(params.has('previewPath')).toBe(false)
+ expect(params.get('keep')).toBe('1')
+ })
+
+ it('keeps the opened tool owned params', () => {
+ const params = new URLSearchParams('previewPort=3000&previewPath=%2Fx')
+
+ toggleToolPanelParams(params, 'preview')
+
+ expect(params.get('panel')).toBe('preview')
+ expect(params.get('previewPort')).toBe('3000')
+ expect(params.get('previewPath')).toBe('/x')
+ })
+
+ it('closes the active tool and clears every tool param', () => {
+ const params = new URLSearchParams('panel=terminal&terminal=%2Fbin%2Fsh&terminalDirectory=%2Fhome&previewPort=3000&keep=1')
+
+ toggleToolPanelParams(params, 'terminal')
+
+ expect(params.has('panel')).toBe(false)
+ expect(params.has('terminal')).toBe(false)
+ expect(params.has('terminalDirectory')).toBe(false)
+ expect(params.has('previewPort')).toBe(false)
+ expect(params.get('keep')).toBe('1')
+ })
+
+ it('switches from one tool to another and clears the previous owned params', () => {
+ const params = new URLSearchParams('panel=preview&previewPort=3000&previewPath=%2Fx')
+
+ toggleToolPanelParams(params, 'files')
+
+ expect(params.get('panel')).toBe('files')
+ expect(params.has('previewPort')).toBe(false)
+ expect(params.has('previewPath')).toBe(false)
+ })
+})
+
+describe('toggleToolDialogParams', () => {
+ it('opens a dialog, clears mobileTab and other tools owned params', () => {
+ const params = new URLSearchParams('mobileTab=more&previewPort=3000&previewPath=%2Fx&keep=1')
+
+ toggleToolDialogParams(params, 'terminal')
+
+ expect(params.get('dialog')).toBe('terminal')
+ expect(params.has('mobileTab')).toBe(false)
+ expect(params.has('previewPort')).toBe(false)
+ expect(params.has('previewPath')).toBe(false)
+ expect(params.get('keep')).toBe('1')
+ })
+
+ it('keeps the opened tool owned params', () => {
+ const params = new URLSearchParams('mobileTab=more&terminal=%2Fbin%2Fsh&terminalDirectory=%2Fhome&previewPort=3000')
+
+ toggleToolDialogParams(params, 'terminal')
+
+ expect(params.get('dialog')).toBe('terminal')
+ expect(params.get('terminal')).toBe('/bin/sh')
+ expect(params.get('terminalDirectory')).toBe('/home')
+ expect(params.has('previewPort')).toBe(false)
+ })
+
+ it('closes the active dialog and clears every tool param', () => {
+ const params = new URLSearchParams('dialog=terminal&terminal=%2Fbin%2Fsh&terminalDirectory=%2Fhome&previewPort=3000&keep=1')
+
+ toggleToolDialogParams(params, 'terminal')
+
+ expect(params.has('dialog')).toBe(false)
+ expect(params.has('terminal')).toBe(false)
+ expect(params.has('terminalDirectory')).toBe(false)
+ expect(params.has('previewPort')).toBe(false)
+ expect(params.get('keep')).toBe('1')
+ })
+})
diff --git a/frontend/src/hooks/useToolPanel.ts b/frontend/src/hooks/useToolPanel.ts
index 29cc045f..d51987b0 100644
--- a/frontend/src/hooks/useToolPanel.ts
+++ b/frontend/src/hooks/useToolPanel.ts
@@ -1,4 +1,5 @@
import { useCallback, useEffect } from 'react'
+import { openDialogParams } from './useDialogParam'
import { useUrlParams } from './useUrlParams'
const PANEL_PARAM = 'panel'
@@ -26,6 +27,26 @@ function clearToolParams(params: URLSearchParams, keep?: PanelTool): void {
}
}
+export function toggleToolPanelParams(params: URLSearchParams, tool: PanelTool): void {
+ if (params.get(PANEL_PARAM) === tool) {
+ params.delete(PANEL_PARAM)
+ clearToolParams(params)
+ return
+ }
+ params.set(PANEL_PARAM, tool)
+ clearToolParams(params, tool)
+}
+
+export function toggleToolDialogParams(params: URLSearchParams, tool: PanelTool): void {
+ if (params.get('dialog') === tool) {
+ params.delete('dialog')
+ clearToolParams(params)
+ return
+ }
+ openDialogParams(params, tool)
+ clearToolParams(params, tool)
+}
+
export interface ToolPanelState {
activeTool: PanelTool | null
toggleTool: (tool: PanelTool) => void
@@ -65,15 +86,7 @@ export function useToolPanel(docked: boolean): ToolPanelState {
}, [docked, dialogParam, panelParam, updateParams])
const toggleTool = useCallback((tool: PanelTool) => {
- updateParams((params) => {
- if (params.get(PANEL_PARAM) === tool) {
- params.delete(PANEL_PARAM)
- clearToolParams(params)
- return
- }
- params.set(PANEL_PARAM, tool)
- clearToolParams(params, tool)
- }, 'push')
+ updateParams((params) => toggleToolPanelParams(params, tool), 'push')
}, [updateParams])
const closePanel = useCallback(() => {
diff --git a/frontend/src/lib/domTargets.ts b/frontend/src/lib/domTargets.ts
new file mode 100644
index 00000000..23e1f6e1
--- /dev/null
+++ b/frontend/src/lib/domTargets.ts
@@ -0,0 +1,25 @@
+const CONTENT_EDITABLE_VALUES = new Set(['', 'true', 'plaintext-only'])
+
+/**
+ * Returns true for free-text entry targets: ` `, `
- {leaderActive && (
-
- Waiting for shortcut key...
-
- )}
{minimizedForm && (
- {/* Sessions Dialog */}
-
-
- Sessions
-
- {sessionDirectory && (
- {
- navigate(`/repos/${repoId}/sessions/${sessionID}${sessionRouteSuffix}`)
- setSessionsDialogOpen(false)
- }}
- />
- )}
-
-
-
+ {/* Sessions Picker */}
+ {
+ if (sessionRepo.id === repoId) {
+ navigate(`/repos/${repoId}/sessions/${session.id}${sessionRouteSuffix}`)
+ } else {
+ navigate(getSessionPath(sessionRepo.id, session.id))
+ }
+ setSessionsDialogOpen(false)
+ }}
+ onDeleteActiveSession={() => {
+ setSessionsDialogOpen(false)
+ handleCloseSession()
+ }}
+ />
{sideQuestion && sessionId && (
({
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
- useKeyboardShortcuts: vi.fn(),
+ useShortcutActions: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
RepoSkillsDialog: vi.fn(() => null),
@@ -63,8 +63,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
-vi.mock('@/hooks/useKeyboardShortcuts', () => ({
- useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
+vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
+ useShortcutActions: mocks.useShortcutActions,
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -131,8 +131,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
-vi.mock('@/components/session/SessionList', () => ({
- SessionList: vi.fn(() => null),
+vi.mock('@/components/session/SessionPickerDialog', () => ({
+ SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/session/PermissionModeToggle', () => ({
@@ -210,7 +210,6 @@ describe('SessionDetail assistant loading at repoId=0', () => {
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
- mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
})
diff --git a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx
index 2f772ede..9088fdd9 100644
--- a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx
+++ b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx
@@ -126,8 +126,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
-vi.mock('@/hooks/useKeyboardShortcuts', () => ({
- useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
+vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
+ useShortcutActions: vi.fn(),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -207,7 +207,7 @@ vi.mock('@/components/navigation/ToolSidePanel', () => ({ ToolSidePanel: vi.fn((
vi.mock('@/hooks/useToolPanel', () => ({
useToolPanel: vi.fn(() => ({ activeTool: null, toggleTool: vi.fn(), closePanel: vi.fn() })),
}))
-vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
+vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
diff --git a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx
index 6926575d..c0ade130 100644
--- a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx
+++ b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx
@@ -86,8 +86,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
-vi.mock('@/hooks/useKeyboardShortcuts', () => ({
- useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
+vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
+ useShortcutActions: vi.fn(),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -159,8 +159,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
-vi.mock('@/components/session/SessionList', () => ({
- SessionList: vi.fn(() => null),
+vi.mock('@/components/session/SessionPickerDialog', () => ({
+ SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
diff --git a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx
index f4ce58a6..9ed44a8c 100644
--- a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx
+++ b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx
@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
- useKeyboardShortcuts: vi.fn(),
+ useShortcutActions: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(),
@@ -65,8 +65,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
-vi.mock('@/hooks/useKeyboardShortcuts', () => ({
- useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
+vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
+ useShortcutActions: mocks.useShortcutActions,
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -137,7 +137,7 @@ vi.mock('@/hooks/useSessionGoals', () => ({
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
-vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
+vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) }))
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
@@ -185,7 +185,6 @@ describe('SessionDetail pending-actions polling gating', () => {
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
- mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
diff --git a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx
index 761323a7..7362bed9 100644
--- a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx
+++ b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx
@@ -18,7 +18,7 @@ const mocks = vi.hoisted(() => ({
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
- useKeyboardShortcuts: vi.fn(),
+ useShortcutActions: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(),
@@ -81,8 +81,8 @@ vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
-vi.mock('@/hooks/useKeyboardShortcuts', () => ({
- useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
+vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
+ useShortcutActions: mocks.useShortcutActions,
}))
vi.mock('@/hooks/useAutoScroll', () => ({
@@ -154,8 +154,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
-vi.mock('@/components/session/SessionList', () => ({
- SessionList: vi.fn(() => null),
+vi.mock('@/components/session/SessionPickerDialog', () => ({
+ SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
@@ -273,7 +273,6 @@ describe('SessionDetail scroll floating button', () => {
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
- mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
mocks.PromptInput.mockImplementation(() => MockedPromptInput
)
diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts
index b51cf006..fa0ed2df 100644
--- a/shared/src/schemas/settings.ts
+++ b/shared/src/schemas/settings.ts
@@ -63,28 +63,36 @@ export type STTConfig = {
lastModelsFetch?: number;
};
-const isBrowser = typeof navigator !== 'undefined';
-const isMac = isBrowser && navigator.platform.toUpperCase().indexOf('MAC') >= 0;
-const CMD_KEY = isMac ? 'Cmd' : 'Ctrl';
+export const DEFAULT_LEADER_KEY = 'Ctrl+X';
-export const DEFAULT_LEADER_KEY = `${CMD_KEY}+O`;
-
-export const DEFAULT_KEYBOARD_SHORTCUTS: Record = {
- submit: `${CMD_KEY}+Enter`,
+export const DEFAULT_KEYBOARD_SHORTCUTS = {
+ submit: 'Cmd+Enter',
abort: 'Escape',
- toggleMode: 'T',
- undo: 'Z',
- redo: 'Shift+Z',
- compact: 'K',
- fork: 'F',
- settings: ',',
- sessions: 'S',
+ clearPrompt: '',
+ toggleMode: 'Shift+Tab',
+ undo: 'U',
+ redo: 'R',
+ compact: 'C',
+ fork: '',
+ settings: '',
+ sessions: 'L',
newSession: 'N',
closeSession: 'W',
toggleSidebar: 'B',
selectModel: 'M',
- variantCycle: `${CMD_KEY}+T`,
-};
+ variantCycle: 'Ctrl+T',
+ favoriteCycle: 'Ctrl+R',
+ toggleTerminal: 'T',
+ toggleSourceControl: '',
+ timeline: 'G',
+ exportSession: 'X',
+ halfPageUp: 'Ctrl+U',
+ halfPageDown: 'Ctrl+D',
+} satisfies Record;
+
+export type KeyboardShortcutAction = keyof typeof DEFAULT_KEYBOARD_SHORTCUTS;
+
+export const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown'];
export const GitCredentialSchema = z.object({
id: z.string().optional(),
@@ -232,9 +240,7 @@ export const DEFAULT_USER_PREFERENCES = {
groupToolCalls: true,
showReasoning: false,
simpleChatMode: false,
- leaderKey: DEFAULT_LEADER_KEY,
- directShortcuts: ['submit', 'abort'],
- keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS,
+ keyboardShortcuts: {} as Record,
customCommands: [],
customAgents: [],
gitCredentials: [] as GitCredential[],