mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Merge pull request #403 from chriswritescode-dev/feat/sessions-dialog-tui-parity
feat(sessions): TUI-style session picker dialog with search, scope toggle, and delete
This commit is contained in:
72 files changed
+5306
-779
No files matched your search
@@ -12,7 +12,7 @@ import {
|
||||
fileExists,
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@opencode-manager/shared/schemas'
|
||||
import { MANAGER_COLOR_THEME_ID, OPENCODE_THEMES } from '@opencode-manager/shared/themes'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env'
|
||||
@@ -699,6 +699,18 @@ Partial object with any of the allowed keys.
|
||||
**Response:**
|
||||
Returns the updated settings object with the same structure as GET.
|
||||
|
||||
### Keyboard Shortcut Preferences
|
||||
|
||||
\`keyboardShortcuts\`, \`leaderKey\`, and \`directShortcuts\` control keyboard bindings.
|
||||
|
||||
**Actions:** ${Object.keys(DEFAULT_KEYBOARD_SHORTCUTS).join(', ')}
|
||||
|
||||
**Key format:** modifiers joined with \`+\`, using \`Ctrl\`, \`Cmd\`, \`Alt\`, and \`Shift\` (for example \`Ctrl+Alt+U\` or \`Shift+Tab\`). \`Cmd\` is the Command key on macOS and Ctrl on other platforms. An empty string unbinds the action.
|
||||
|
||||
**Leader vs direct:** by default a binding is a leader binding, pressed after the \`leaderKey\` (default \`${DEFAULT_LEADER_KEY}\`). List an action in \`directShortcuts\` to fire it without the leader key.
|
||||
|
||||
**Sending changes:** \`keyboardShortcuts\` and \`directShortcuts\` are replaced wholesale. Read the current \`keyboardShortcuts\` (and \`directShortcuts\` when changing binding kinds) from GET /settings, modify only the actions you need, and send the complete map or list back; actions absent from the stored map use their built-in defaults.
|
||||
|
||||
### POST /assistant/reload
|
||||
|
||||
Reload the OpenCode configuration without restarting the server, rebuilding every loaded location. OpenCode re-reads \`opencode.json\`/\`opencode.jsonc\`, agents, commands, skills, plugins, and \`AGENTS.md\`; running sessions, including this one, keep running. Use this after editing \`.opencode/agents/assistant.md\` or other workspace files so changes take effect on the next message. Returns \`400\` with \`validationIssues\` when the OpenCode configuration is invalid.
|
||||
|
||||
+25
-15
@@ -24,6 +24,7 @@ import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { TTSProvider } from './contexts/TTSContext'
|
||||
import { ThemeProvider, useThemeMode } from './contexts/ThemeContext'
|
||||
import { AuthProvider } from './contexts/AuthContext'
|
||||
import { KeyboardShortcutsProvider } from './contexts/KeyboardShortcutsContext'
|
||||
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
|
||||
import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
|
||||
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
|
||||
@@ -34,6 +35,7 @@ import { onNotificationClick } from '@/lib/serviceWorker'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { useGlobalShortcutActions } from '@/hooks/useGlobalShortcutActions'
|
||||
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -116,6 +118,11 @@ function PermissionDialogWrapper() {
|
||||
)
|
||||
}
|
||||
|
||||
function GlobalShortcuts() {
|
||||
useGlobalShortcutActions()
|
||||
return null
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
@@ -188,21 +195,24 @@ function AppShell() {
|
||||
<ThemeProvider>
|
||||
<AuthProvider>
|
||||
<EventProvider>
|
||||
<div ref={rootRef} className="flex h-dvh w-full min-w-0">
|
||||
<DesktopSidebar />
|
||||
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
<MobileTabBar />
|
||||
<MobileSheetHost />
|
||||
<PermissionDialogWrapper />
|
||||
<SSHHostKeyDialogWrapper />
|
||||
<SettingsDialog />
|
||||
<HealthMonitor />
|
||||
<VersionNotifier />
|
||||
<PwaUpdatePrompt />
|
||||
<ThemedToaster />
|
||||
<KeyboardShortcutsProvider>
|
||||
<GlobalShortcuts />
|
||||
<div ref={rootRef} className="flex h-dvh w-full min-w-0">
|
||||
<DesktopSidebar />
|
||||
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
<MobileTabBar />
|
||||
<MobileSheetHost />
|
||||
<PermissionDialogWrapper />
|
||||
<SSHHostKeyDialogWrapper />
|
||||
<SettingsDialog />
|
||||
<HealthMonitor />
|
||||
<VersionNotifier />
|
||||
<PwaUpdatePrompt />
|
||||
<ThemedToaster />
|
||||
</KeyboardShortcutsProvider>
|
||||
</EventProvider>
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
|
||||
@@ -98,6 +98,32 @@ describe('OpenCode facade', () => {
|
||||
expect(page.nextCursor).toBeUndefined()
|
||||
})
|
||||
|
||||
it('omits the directory when listing sessions across all directories', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({ data: [sessionInfo('ses_1', '/repo')], cursor: { next: 'cursor_next' } }),
|
||||
)
|
||||
|
||||
const page = await listSessionPage({ limit: 25, order: 'desc' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?limit=25&order=desc&parentID=null',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(page.items).toEqual([sessionInfo('ses_1', '/repo')])
|
||||
expect(page.nextCursor).toBe('cursor_next')
|
||||
})
|
||||
|
||||
it('omits the directory on an all-directories continuation page', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: [], cursor: {} }))
|
||||
|
||||
await listSessionPage({ cursor: 'cursor_1' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?parentID=null&cursor=cursor_1',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
})
|
||||
|
||||
it('reads a single session from the V2 session route', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_1', '/repo') }))
|
||||
|
||||
@@ -529,15 +555,27 @@ describe('OpenCode facade', () => {
|
||||
})
|
||||
|
||||
it('stages, commits, and clears a session revert', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: { messageID: 'msg_1' } }))
|
||||
fetchMock.mockImplementation((input: RequestInfo | URL) => {
|
||||
const url = String(input)
|
||||
if (url.endsWith('/interrupt')) return Promise.resolve(jsonResponse({ data: { interrupted: true } }))
|
||||
if (url.endsWith('/wait')) return Promise.resolve(new Response(null, { status: 204 }))
|
||||
if (url.endsWith('/revert/stage')) return Promise.resolve(jsonResponse({ data: { messageID: 'msg_1' } }))
|
||||
return Promise.resolve(new Response(null, { status: 204 }))
|
||||
})
|
||||
|
||||
await stageRevert('ses_1', 'msg_1')
|
||||
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/revert/stage')
|
||||
expect(lastRequest().init.method).toBe('POST')
|
||||
expect(lastRequest().init.body).toBe(JSON.stringify({ messageID: 'msg_1' }))
|
||||
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
const stageRequests = fetchMock.mock.calls.map(([input, init]) => ({
|
||||
url: String(input),
|
||||
init: init as RequestInit,
|
||||
}))
|
||||
expect(stageRequests.map((request) => request.url)).toEqual([
|
||||
'http://localhost/api/opencode/api/session/ses_1/interrupt',
|
||||
'http://localhost/api/opencode/api/experimental/session/ses_1/wait',
|
||||
'http://localhost/api/opencode/api/session/ses_1/revert/stage',
|
||||
])
|
||||
expect(stageRequests.map((request) => request.init.method)).toEqual(['POST', 'POST', 'POST'])
|
||||
expect(stageRequests[2].init.body).toBe(JSON.stringify({ messageID: 'msg_1' }))
|
||||
|
||||
await commitRevert('ses_1')
|
||||
expect(lastRequest().url).toBe('http://localhost/api/opencode/api/session/ses_1/revert/commit')
|
||||
|
||||
@@ -37,7 +37,7 @@ export interface SessionPage {
|
||||
}
|
||||
|
||||
export interface SessionPageInput {
|
||||
directory: string
|
||||
directory?: string
|
||||
limit?: number
|
||||
order?: 'asc' | 'desc'
|
||||
search?: string
|
||||
@@ -93,7 +93,7 @@ function buildPromptFields(input: PromptFields) {
|
||||
export async function listSessionPage(input: SessionPageInput): Promise<SessionPage> {
|
||||
const { data, cursor } = await callOpenCode((api) =>
|
||||
api.session.list({
|
||||
directory: input.directory,
|
||||
...(input.directory === undefined ? {} : { directory: input.directory }),
|
||||
parentID: 'null',
|
||||
limit: input.limit,
|
||||
order: input.order,
|
||||
@@ -241,6 +241,8 @@ export async function removeShell(id: string, directory: string): Promise<void>
|
||||
}
|
||||
|
||||
export async function stageRevert(sessionID: string, messageID: string): Promise<SessionRevert> {
|
||||
await interruptSession(sessionID)
|
||||
await callOpenCode((api) => api.session.wait({ sessionID }))
|
||||
return callOpenCode((api) => api.session.revert.stage({ sessionID, messageID }))
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
DEFAULT_USER_PREFERENCES,
|
||||
DEFAULT_LEADER_KEY,
|
||||
DEFAULT_DIRECT_SHORTCUTS,
|
||||
BLOCKED_SERVER_ENV_KEYS,
|
||||
selectPreferredOpenCodeConfigSourceName,
|
||||
type TTSConfig,
|
||||
@@ -27,8 +28,8 @@ import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
import { saveFile } from '@/lib/download'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile } from '@opencode-manager/shared'
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS }
|
||||
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile, KeyboardShortcutAction } from '@opencode-manager/shared'
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, DEFAULT_DIRECT_SHORTCUTS, BLOCKED_SERVER_ENV_KEYS }
|
||||
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'
|
||||
|
||||
export function getOpenCodeConfigSources(config: OpenCodeConfigFile): OpenCodeConfigSourceFile[] {
|
||||
|
||||
@@ -54,7 +54,6 @@ export function AgentQuickSelect({
|
||||
|
||||
const buttonContent = (
|
||||
<button
|
||||
data-toggle-mode
|
||||
style={styleVars as React.CSSProperties}
|
||||
className="px-2 md:px-3.5 py-1 h-[36px] rounded-lg text-sm font-medium border min-w-[56px] max-w-[80px] md:max-w-[100px] flex-shrink-0 flex items-center justify-center transition-all duration-200 active:scale-95 hover:scale-105 shadow-md text-[var(--agent-color)] bg-[var(--agent-bg)] border-[var(--agent-border)] hover:bg-[var(--agent-bg-hover)] hover:border-[var(--agent-border-hover)] shadow-[var(--agent-shadow)] hover:shadow-[var(--agent-shadow-hover)]"
|
||||
>
|
||||
|
||||
@@ -422,6 +422,47 @@ describe('PromptInput command submission', () => {
|
||||
expect(screen.getByTestId('model-quick-select')).toHaveAttribute('data-open', 'true')
|
||||
})
|
||||
|
||||
it('resets bash mode through the imperative clearPrompt', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo())
|
||||
const ref = createRef<PromptInputHandle>()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PromptInput {...defaultProps} ref={ref} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
const input = await screen.findByPlaceholderText('Send a message...')
|
||||
fireEvent.change(input, { target: { value: '!' } })
|
||||
expect(input).toHaveValue('!')
|
||||
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
|
||||
|
||||
act(() => {
|
||||
ref.current?.clearPrompt()
|
||||
})
|
||||
|
||||
expect(input).toHaveValue('')
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears attachments and exits bash mode on Escape while idle', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
const input = await screen.findByPlaceholderText('Send a message...')
|
||||
fireEvent.change(input, { target: { value: '!' } })
|
||||
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
|
||||
|
||||
await attachImage(container)
|
||||
expect(screen.getByText('pic.png')).toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
|
||||
expect(input).toHaveValue('')
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('pic.png')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps attachments and clears only the text when a built-in command is submitted', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
|
||||
@@ -34,9 +34,10 @@ import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
|
||||
import { detectMentionTrigger, parsePromptToInput, getFilename, getDirectory, type MentionItem } from '@/lib/promptParser'
|
||||
import { matchText, rankByMatch, type MatchRange } from '@/lib/fuzzyMatch'
|
||||
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
|
||||
import { getNextFavoriteModel } from '@/lib/favoriteModels'
|
||||
import { randomId } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { findModelInfo } from '@opencode-manager/shared/opencode'
|
||||
import { findModelInfo, isSameModelSelection } from '@opencode-manager/shared/opencode'
|
||||
import { isOpenSessionGoal } from '@opencode-manager/shared/schemas'
|
||||
import { useProviders } from '@/hooks/useProviders'
|
||||
|
||||
@@ -110,6 +111,9 @@ export interface PromptInputHandle {
|
||||
clearPrompt: () => void
|
||||
triggerFileUpload: () => void
|
||||
openModelPicker: () => void
|
||||
cycleAgent: () => void
|
||||
cycleVariant: () => void
|
||||
cycleFavoriteModel: () => void
|
||||
}
|
||||
|
||||
interface PromptInputProps {
|
||||
@@ -243,29 +247,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
fileInputRef.current?.click()
|
||||
}, [])
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
setPromptValue: (value: string) => {
|
||||
setPrompt(value)
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
clearPrompt: () => {
|
||||
setPrompt('')
|
||||
setAttachedFiles(new Map())
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
resetVoiceGestureState()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
clearSTT()
|
||||
}
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
triggerFileUpload: openFilePicker,
|
||||
openModelPicker: () => {
|
||||
setIsModelPickerOpen(true)
|
||||
}
|
||||
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, openFilePicker])
|
||||
const sessionAgent = useSessionAgent(sessionID, directory)
|
||||
const currentMode = localMode ?? sessionAgent.agent
|
||||
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
|
||||
@@ -1009,8 +990,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isBashMode && e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
setIsBashMode(false)
|
||||
setPrompt('')
|
||||
resetPrompt()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1090,16 +1070,8 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
textareaRef.current?.blur()
|
||||
}
|
||||
handleSubmit()
|
||||
} else if (e.key === 'Escape') {
|
||||
closeSuggestions()
|
||||
setPrompt('')
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
resetVoiceGestureState()
|
||||
clearSTT()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') {
|
||||
e.preventDefault()
|
||||
handleCycleVariant()
|
||||
} else if (e.key === 'Escape' && !isSessionActive) {
|
||||
resetPrompt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1125,13 +1097,28 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
updateSuggestionTriggers(value, e.target.selectionStart)
|
||||
}
|
||||
|
||||
const closeSuggestions = () => {
|
||||
const closeSuggestions = useCallback(() => {
|
||||
setShowSuggestions(false)
|
||||
setSuggestionQuery('')
|
||||
setShowMentionSuggestions(false)
|
||||
setMentionQuery('')
|
||||
setMentionRange(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const resetPrompt = useCallback(() => {
|
||||
setPrompt('')
|
||||
setAttachedFiles(new Map())
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
closeSuggestions()
|
||||
setIsBashMode(false)
|
||||
resetVoiceGestureState()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
clearSTT()
|
||||
}
|
||||
}, [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, closeSuggestions])
|
||||
|
||||
const updateSuggestionTriggers = (value: string, cursorPosition: number) => {
|
||||
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
|
||||
@@ -1244,7 +1231,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
[sessionID, sessionAgent.sessionAgentId, sessionAgent.modelRef],
|
||||
)
|
||||
|
||||
const { model, modelString, modelRef, setActiveAgent, isModelReady } = useModelSelection(directory, modelSelectionSession)
|
||||
const { model, modelString, modelRef, favoriteModels, setModel, setActiveAgent, isModelReady } = useModelSelection(directory, modelSelectionSession)
|
||||
|
||||
useEffect(() => {
|
||||
setActiveAgent({
|
||||
@@ -1281,6 +1268,18 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
cycleVariant()
|
||||
}, [hasVariants, cycleVariant])
|
||||
|
||||
const handleCycleFavoriteModel = useCallback(() => {
|
||||
const next = getNextFavoriteModel(favoriteModels, model)
|
||||
if (!next) {
|
||||
showToast.info('No favorite models')
|
||||
return
|
||||
}
|
||||
if (model && isSameModelSelection(model, next)) {
|
||||
return
|
||||
}
|
||||
setModel(next)
|
||||
}, [favoriteModels, model, setModel])
|
||||
|
||||
const handleCycleAgent = useCallback(() => {
|
||||
const next = getNextPrimaryAgentId(agents, currentMode)
|
||||
if (!next) {
|
||||
@@ -1290,6 +1289,24 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
handleAgentChange(next)
|
||||
}, [agents, currentMode, handleAgentChange])
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
setPromptValue: (value: string) => {
|
||||
setPrompt(value)
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
clearPrompt: () => {
|
||||
resetPrompt()
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
triggerFileUpload: openFilePicker,
|
||||
openModelPicker: () => {
|
||||
setIsModelPickerOpen(true)
|
||||
},
|
||||
cycleAgent: handleCycleAgent,
|
||||
cycleVariant: handleCycleVariant,
|
||||
cycleFavoriteModel: handleCycleFavoriteModel,
|
||||
}), [resetPrompt, openFilePicker, handleCycleAgent, handleCycleVariant, handleCycleFavoriteModel])
|
||||
|
||||
const commandActionsWithPrompt = useMemo<CommandActions>(
|
||||
() => ({
|
||||
...commandActions,
|
||||
@@ -1466,6 +1483,7 @@ return (
|
||||
)}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
data-prompt-input
|
||||
value={prompt}
|
||||
onChange={handleInput}
|
||||
onFocus={handlePromptFocus}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ModelQuickSelect } from './ModelQuickSelect'
|
||||
import { buildModelSections } from '@/lib/modelSections'
|
||||
@@ -9,8 +9,17 @@ import type { Provider } from '@/api/providers'
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useModelSelection: vi.fn(),
|
||||
useModelSections: vi.fn(),
|
||||
deferredSearchValue: { current: null as string | null },
|
||||
}))
|
||||
|
||||
vi.mock('react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react')>()
|
||||
return {
|
||||
...actual,
|
||||
useDeferredValue: (value: string) => mocks.deferredSearchValue.current ?? value,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useModelSelection: mocks.useModelSelection,
|
||||
}))
|
||||
@@ -144,6 +153,32 @@ async function openSelector(user: ReturnType<typeof userEvent.setup>) {
|
||||
return screen.findByRole('dialog', { name: 'Select model' })
|
||||
}
|
||||
|
||||
function focusDetachedTextarea() {
|
||||
const textarea = document.createElement('textarea')
|
||||
document.body.appendChild(textarea)
|
||||
textarea.focus()
|
||||
return textarea
|
||||
}
|
||||
|
||||
const originalInnerWidth = window.innerWidth
|
||||
|
||||
function setViewportWidth(width: number) {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width })
|
||||
}
|
||||
|
||||
function mobileModelList() {
|
||||
const lists = Array.from(document.querySelectorAll<HTMLElement>('.overflow-y-auto.px-4.pb-4'))
|
||||
const list = lists.find((element) => !element.classList.contains('pt-2'))
|
||||
if (!list) throw new Error('No mobile model list found')
|
||||
return list
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.querySelectorAll('textarea').forEach((element) => element.remove())
|
||||
setViewportWidth(originalInnerWidth)
|
||||
mocks.deferredSearchValue.current = null
|
||||
})
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
|
||||
configurable: true,
|
||||
@@ -371,3 +406,160 @@ describe('ModelQuickSelect more models', () => {
|
||||
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('ModelQuickSelect keyboard navigation', () => {
|
||||
it('moves the active quick row with ArrowDown and selects it with Enter', () => {
|
||||
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(false)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).toHaveBeenCalledWith(selection('opencode', 'zen-1'))
|
||||
})
|
||||
|
||||
it('clamps at the first quick row and jumps to the last with End', () => {
|
||||
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: 'Select model' })
|
||||
|
||||
fireEvent.keyDown(dialog, { key: 'ArrowUp' })
|
||||
fireEvent.keyDown(dialog, { key: 'Enter' })
|
||||
expect(setModel).toHaveBeenLastCalledWith(selection('opencode-go', 'go-1'))
|
||||
|
||||
setModel.mockClear()
|
||||
|
||||
fireEvent.keyDown(dialog, { key: 'End' })
|
||||
fireEvent.keyDown(dialog, { key: 'Enter' })
|
||||
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
|
||||
})
|
||||
|
||||
it('navigates the search results with the arrow keys and Enter', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
const searchInput = screen.getByPlaceholderText('Search models...')
|
||||
await user.type(searchInput, '5')
|
||||
|
||||
await screen.findAllByText('Claude Opus 5.5')
|
||||
|
||||
expect(fireEvent.keyDown(searchInput, { key: 'ArrowDown' })).toBe(false)
|
||||
expect(fireEvent.keyDown(searchInput, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).toHaveBeenCalledWith(selection('openai', 'gpt-5'))
|
||||
})
|
||||
|
||||
it('does not select a model when Enter is pressed on a row button', () => {
|
||||
const { setModel } = setModelSelection({ favorite: [selection('anthropic', 'claude-sonnet-4')] })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const star = screen.getByRole('button', { name: /favorites/ })
|
||||
star.focus()
|
||||
|
||||
fireEvent.keyDown(star, { key: 'Enter' })
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not intercept arrow keys when the sheet is closed', () => {
|
||||
render(<ModelQuickSelect />)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores keyboard navigation when the mobile provider list hides the models', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
setViewportWidth(500)
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(true)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('navigates the provider models that are visible on mobile', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
setViewportWidth(500)
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(false)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-opus-5-5-fast'))
|
||||
})
|
||||
|
||||
it('ignores keydown events while an IME composition is active', () => {
|
||||
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown', isComposing: true })).toBe(true)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter', isComposing: true })).toBe(true)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not select while the deferred search query is still catching up', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search models...')
|
||||
mocks.deferredSearchValue.current = ''
|
||||
await user.type(searchInput, '5')
|
||||
|
||||
expect(fireEvent.keyDown(searchInput, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('scrolls the mobile provider model list to follow the active row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight')
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, get: () => 60 })
|
||||
setViewportWidth(500)
|
||||
|
||||
try {
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
|
||||
|
||||
const list = mobileModelList()
|
||||
expect(list.scrollTop).toBe(0)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
fireEvent.keyDown(textarea, { key: 'ArrowDown' })
|
||||
|
||||
expect(list.scrollTop).toBe(60)
|
||||
} finally {
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', clientHeight!)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Check, ChevronDown, ChevronLeft, ChevronRight, Search, Star, Trash2, X, type LucideIcon } from 'lucide-react'
|
||||
import { useModelSelection, type ModelSelectionSession } from '@/hooks/useModelSelection'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useModelSections } from '@/hooks/useModelSections'
|
||||
import { useVariants } from '@/hooks/useVariants'
|
||||
import { modelSelectionRef, type Model } from '@/api/providers'
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { buildModelSections, filterModelSections, type ModelOption } from '@/lib/modelSections'
|
||||
import { isTextEntryElement } from '@/lib/domTargets'
|
||||
|
||||
interface ModelQuickSelectProps {
|
||||
directory?: string
|
||||
@@ -48,12 +50,13 @@ interface ProviderListItem {
|
||||
interface VirtualizedListProps<T> {
|
||||
items: T[]
|
||||
itemHeight: number
|
||||
renderItem: (item: T) => React.ReactNode
|
||||
renderItem: (item: T, index: number) => React.ReactNode
|
||||
getKey: (item: T) => string
|
||||
emptyLabel: string
|
||||
className?: string
|
||||
resetKey?: string
|
||||
overscan?: number
|
||||
activeIndex?: number
|
||||
}
|
||||
|
||||
const MODEL_OPTION_ROW_HEIGHT = 60
|
||||
@@ -76,6 +79,7 @@ function VirtualizedList<T>({
|
||||
className,
|
||||
resetKey,
|
||||
overscan = VIRTUAL_LIST_OVERSCAN,
|
||||
activeIndex,
|
||||
}: VirtualizedListProps<T>) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const [scrollTop, setScrollTop] = useState(0)
|
||||
@@ -104,6 +108,21 @@ function VirtualizedList<T>({
|
||||
setScrollTop(0)
|
||||
}, [resetKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeIndex === undefined) return
|
||||
const element = scrollRef.current
|
||||
if (!element) return
|
||||
|
||||
const rowTop = activeIndex * itemHeight
|
||||
const rowBottom = rowTop + itemHeight
|
||||
if (rowTop < element.scrollTop) {
|
||||
element.scrollTop = rowTop
|
||||
} else if (rowBottom > element.scrollTop + element.clientHeight) {
|
||||
element.scrollTop = rowBottom - element.clientHeight
|
||||
}
|
||||
setScrollTop(element.scrollTop)
|
||||
}, [activeIndex, itemHeight])
|
||||
|
||||
const visibleRange = useMemo(() => {
|
||||
if (items.length === 0 || viewportHeight === 0) {
|
||||
return { start: 0, end: 0 }
|
||||
@@ -141,7 +160,7 @@ function VirtualizedList<T>({
|
||||
height: itemHeight,
|
||||
}}
|
||||
>
|
||||
{renderItem(item)}
|
||||
{renderItem(item, visibleRange.start + index)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -164,6 +183,9 @@ export function ModelQuickSelect({
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const deferredSearchQuery = useDeferredValue(searchQuery)
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
|
||||
const [activeIndex, setActiveIndex] = useState(0)
|
||||
const quickListRef = useRef<HTMLDivElement>(null)
|
||||
const isMobile = useMobile()
|
||||
const { model, modelString, info, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
|
||||
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory, session)
|
||||
|
||||
@@ -265,12 +287,111 @@ export function ModelQuickSelect({
|
||||
|
||||
const browseModels = selectedProviderId ? selectedProviderModels : browseData?.allModels ?? EMPTY_MODELS
|
||||
|
||||
const handleModelSelect = (providerID: string, modelID: string) => {
|
||||
const navigableItems = useMemo((): ModelListItem[] => {
|
||||
if (showAllModels) {
|
||||
if (isSearching) return searchResults
|
||||
if (isMobile && !selectedProviderId) return EMPTY_MODELS
|
||||
return browseModels
|
||||
}
|
||||
return quickSections.flatMap((section) => section.models)
|
||||
}, [showAllModels, isSearching, isMobile, selectedProviderId, searchResults, browseModels, quickSections])
|
||||
|
||||
const quickSectionOffsets = useMemo(() => {
|
||||
const offsets = new Map<string, number>()
|
||||
let running = 0
|
||||
for (const section of quickSections) {
|
||||
offsets.set(section.title, running)
|
||||
running += section.models.length
|
||||
}
|
||||
return offsets
|
||||
}, [quickSections])
|
||||
|
||||
const activeResetKey = `${isOpen}|${showAllModels}|${isSearching ? deferredSearchQuery : ''}|${selectedProviderId ?? ''}`
|
||||
const navigableItemsRef = useRef(navigableItems)
|
||||
navigableItemsRef.current = navigableItems
|
||||
const modelStringRef = useRef(modelString)
|
||||
modelStringRef.current = modelString
|
||||
const searchQueryRef = useRef(searchQuery)
|
||||
searchQueryRef.current = searchQuery
|
||||
const deferredSearchQueryRef = useRef(deferredSearchQuery)
|
||||
deferredSearchQueryRef.current = deferredSearchQuery
|
||||
|
||||
useEffect(() => {
|
||||
const selectedIndex = navigableItemsRef.current.findIndex((item) => item.key === modelStringRef.current)
|
||||
setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0)
|
||||
}, [activeResetKey])
|
||||
|
||||
useEffect(() => {
|
||||
setActiveIndex((current) => {
|
||||
if (navigableItems.length === 0) return 0
|
||||
return Math.min(current, navigableItems.length - 1)
|
||||
})
|
||||
}, [navigableItems.length])
|
||||
|
||||
useEffect(() => {
|
||||
if (showAllModels) return
|
||||
const container = quickListRef.current
|
||||
if (!container) return
|
||||
const element = container.querySelector<HTMLElement>(`[data-model-index="${activeIndex}"]`)
|
||||
if (element && typeof element.scrollIntoView === 'function') {
|
||||
element.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
}, [activeIndex, showAllModels])
|
||||
|
||||
const handleModelSelect = useCallback((providerID: string, modelID: string) => {
|
||||
setModel({ providerID, modelID })
|
||||
setShowAllModels(false)
|
||||
setSearchQuery('')
|
||||
setSelectedProviderId(null)
|
||||
}
|
||||
}, [setModel])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return
|
||||
if (event.isComposing) return
|
||||
|
||||
const target = event.target
|
||||
if (target instanceof HTMLElement && target.closest('[role="menu"]')) return
|
||||
|
||||
const isTextInput = target instanceof Element && isTextEntryElement(target)
|
||||
|
||||
if (event.key === 'Enter') {
|
||||
if (target instanceof HTMLElement && target.closest('button')) return
|
||||
if (searchQueryRef.current !== deferredSearchQueryRef.current) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
const item = navigableItems[activeIndex]
|
||||
if (!item) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
handleModelSelect(item.providerID, item.modelID)
|
||||
return
|
||||
}
|
||||
|
||||
let nextIndex: number | null = null
|
||||
if (event.key === 'ArrowDown') {
|
||||
nextIndex = Math.min(activeIndex + 1, navigableItems.length - 1)
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
nextIndex = Math.max(activeIndex - 1, 0)
|
||||
} else if (event.key === 'Home' && !isTextInput) {
|
||||
nextIndex = 0
|
||||
} else if (event.key === 'End' && !isTextInput) {
|
||||
nextIndex = navigableItems.length - 1
|
||||
}
|
||||
|
||||
if (nextIndex === null || navigableItems.length === 0) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
setActiveIndex(nextIndex)
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown, true)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown, true)
|
||||
}, [isOpen, activeIndex, navigableItems, handleModelSelect])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (open === undefined) {
|
||||
@@ -301,15 +422,19 @@ export function ModelQuickSelect({
|
||||
|
||||
const getPrimaryLabel = (item: ModelListItem) => item.displayName || item.modelID
|
||||
|
||||
const renderModelOption = (item: ModelListItem) => {
|
||||
const renderModelOption = (item: ModelListItem, index: number) => {
|
||||
const isSelected = modelString === item.key
|
||||
const isFavorite = favoriteKeySet.has(item.key)
|
||||
const isRecent = recentKeySet.has(item.key)
|
||||
const isActive = index === activeIndex
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.key}
|
||||
className={`group flex w-full items-center gap-2 rounded-xl py-2 text-left transition-colors hover:bg-accent ${isSelected ? 'bg-highlight/10' : ''}`}
|
||||
data-model-index={index}
|
||||
data-active={isActive ? 'true' : undefined}
|
||||
onMouseMove={() => setActiveIndex(index)}
|
||||
className={`group flex w-full items-center gap-2 rounded-xl py-2 text-left transition-colors hover:bg-accent ${isSelected ? 'bg-highlight/10' : ''} ${isActive ? 'bg-accent ring-1 ring-border' : ''}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -521,11 +646,12 @@ export function ModelQuickSelect({
|
||||
<VirtualizedList
|
||||
items={searchResults}
|
||||
itemHeight={MODEL_OPTION_ROW_HEIGHT}
|
||||
renderItem={(item) => renderModelOption(item)}
|
||||
renderItem={(item, index) => renderModelOption(item, index)}
|
||||
getKey={(item) => item.key}
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4 pt-2"
|
||||
resetKey={`${selectedProviderId ?? 'all'}:${deferredSearchQuery}`}
|
||||
activeIndex={activeIndex}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
@@ -544,11 +670,12 @@ export function ModelQuickSelect({
|
||||
<VirtualizedList
|
||||
items={browseModels}
|
||||
itemHeight={MODEL_OPTION_ROW_HEIGHT}
|
||||
renderItem={(item) => renderModelOption(item)}
|
||||
renderItem={(item, index) => renderModelOption(item, index)}
|
||||
getKey={(item) => item.key}
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4 pt-2"
|
||||
resetKey={selectedProviderId ?? 'all'}
|
||||
activeIndex={activeIndex}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -558,11 +685,12 @@ export function ModelQuickSelect({
|
||||
<VirtualizedList
|
||||
items={selectedProviderModels}
|
||||
itemHeight={MODEL_OPTION_ROW_HEIGHT}
|
||||
renderItem={(item) => renderModelOption(item)}
|
||||
renderItem={(item, index) => renderModelOption(item, index)}
|
||||
getKey={(item) => item.key}
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4"
|
||||
resetKey={selectedProviderId}
|
||||
activeIndex={activeIndex}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full overflow-y-auto px-4 pb-4">
|
||||
@@ -580,7 +708,7 @@ export function ModelQuickSelect({
|
||||
)
|
||||
) : (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden pb-safe pt-0">
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
|
||||
<div ref={quickListRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
|
||||
{quickSections.map(section => (
|
||||
<section key={section.title}>
|
||||
<h3 className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
|
||||
@@ -588,7 +716,7 @@ export function ModelQuickSelect({
|
||||
{section.title}
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{section.models.map(item => renderModelOption(item))}
|
||||
{section.models.map((item, index) => renderModelOption(item, (quickSectionOffsets.get(section.title) ?? 0) + index))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
@@ -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(<DesktopSessionTree />, { 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(<DesktopSessionTree />, { 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(<DesktopSessionTree />, { 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(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
|
||||
|
||||
@@ -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 <SessionNavStatus>Loading sessions...</SessionNavStatus>
|
||||
if (isError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
|
||||
if (nameMatches.isLoading || isSearchLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
|
||||
if (nameMatches.isError || isSearchError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
|
||||
if (matchingGroups.length === 0) return <SessionNavStatus>No sessions found</SessionNavStatus>
|
||||
|
||||
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 (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="px-2 pb-2">
|
||||
<SessionSearchInput value={draft} onChange={setDraft} />
|
||||
<SessionSearchInput value={draft} onChange={handleSearchChange} />
|
||||
</div>
|
||||
|
||||
<div role="region" aria-label="Session navigator" className="min-h-0 flex-1 overflow-y-auto pb-2">
|
||||
{isLoading ? (
|
||||
<SessionNavStatus>Loading repos...</SessionNavStatus>
|
||||
) : search ? (
|
||||
<SessionSearchResults repos={repos} search={search} />
|
||||
) : trimmedDraft ? (
|
||||
<SessionSearchResults
|
||||
nameMatchedRepos={nameMatchedRepos}
|
||||
otherRepos={otherRepos}
|
||||
sessions={filteredSessions}
|
||||
isSearchLoading={isSearchLoading}
|
||||
isSearchError={isSearchError}
|
||||
/>
|
||||
) : (
|
||||
<RepoSessionNavList
|
||||
repos={repos}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { ReactNode } from 'react'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { ToolSidePanel } from './ToolSidePanel'
|
||||
import { useToolPanel } from '@/hooks/useToolPanel'
|
||||
|
||||
@@ -43,6 +44,7 @@ function Harness({ docked }: { docked: boolean }) {
|
||||
const panel = useToolPanel(docked)
|
||||
return (
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
{docked ? (
|
||||
<ToolSidePanel
|
||||
panel={panel}
|
||||
@@ -83,6 +85,10 @@ function HomeHarness() {
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<HTMLElement>(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}
|
||||
|
||||
<TooltipProvider>
|
||||
<nav aria-label="Tools" className="flex w-11 shrink-0 flex-col items-center gap-1 overflow-y-auto border-l border-border bg-background py-2">
|
||||
<nav ref={railRef} aria-label="Tools" className="flex w-11 shrink-0 flex-col items-center gap-1 overflow-y-auto border-l border-border bg-background py-2">
|
||||
{panelTools.map(({ item, tool }) => (
|
||||
<RailButton key={item.key} item={item} active={tool === activeTool} onClick={() => toggleTool(tool)} />
|
||||
))}
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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' })
|
||||
|
||||
@@ -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<string, Repo> {
|
||||
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)),
|
||||
|
||||
@@ -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(
|
||||
<>
|
||||
<AbortLayer onAbort={sessionAbort} />
|
||||
<FormPrompt form={selectForm} onReply={vi.fn()} onCancel={vi.fn()} onMinimize={onMinimize} />
|
||||
</>
|
||||
)
|
||||
|
||||
await userEvent.keyboard('{Escape}')
|
||||
|
||||
expect(onMinimize).toHaveBeenCalledTimes(1)
|
||||
expect(sessionAbort).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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<FormField, { type: 'external' }>
|
||||
|
||||
@@ -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?.()
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<typeof import('@/hooks/useOpenCode')>()
|
||||
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(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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<Response>((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 }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
try {
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
{ 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(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<HTMLDivElement>(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<HTMLDivElement>) => {
|
||||
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 <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
|
||||
}
|
||||
|
||||
if (!sessions || sessions.length === 0) {
|
||||
if (isFetchNextPageError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 p-4 text-sm text-muted-foreground">
|
||||
<p>Failed to load sessions.</p>
|
||||
<Button variant="outline" size="sm" onClick={handleRetryNextPage} disabled={isFetchingNextPage}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if ((hasNextPage || isFetchingNextPage) && !renderSessions) {
|
||||
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
|
||||
}
|
||||
if (!searchQuery.trim() && !renderSessions) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<Card
|
||||
className="p-6 cursor-pointer hover:bg-accent hover:border-border transition-all border-dashed"
|
||||
onClick={() => createSession.mutate({ agent: undefined })}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center gap-2 text-center">
|
||||
<p className="font-medium">No sessions yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Click here to start a new session
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
}, [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 (
|
||||
<SessionCard
|
||||
key={key}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(key)}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
isPinned={isPinned}
|
||||
onSelect={onSelectSession}
|
||||
@@ -227,6 +186,39 @@ export const SessionList = ({
|
||||
);
|
||||
};
|
||||
|
||||
if (!isLoading && !isPlaceholderData && (!sessions || sessions.length === 0)) {
|
||||
if (isFetchNextPageError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 p-4 text-sm text-muted-foreground">
|
||||
<p>Failed to load sessions.</p>
|
||||
<Button variant="outline" size="sm" onClick={handleRetryNextPage} disabled={isFetchingNextPage}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if ((hasNextPage || isFetchingNextPage) && !renderSessions) {
|
||||
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
|
||||
}
|
||||
if (!trimmedQuery && !renderSessions) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<Card
|
||||
className="p-6 cursor-pointer hover:bg-accent hover:border-border transition-all border-dashed"
|
||||
onClick={() => createSession.mutate({ agent: undefined })}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center gap-2 text-center">
|
||||
<p className="font-medium">No sessions yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Click here to start a new session
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
@@ -264,8 +256,8 @@ export const SessionList = ({
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search sessions..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => 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}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{renderSessions ? (
|
||||
{isLoading && !renderSessions ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">Loading sessions...</div>
|
||||
) : 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 ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">
|
||||
No sessions found
|
||||
{isSearchPending ? 'Searching sessions...' : 'No sessions found'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
@@ -331,7 +325,7 @@ export const SessionList = ({
|
||||
{olderSessions.map((session) => renderSessionCard(session, false))}
|
||||
</>
|
||||
)}
|
||||
{isFetchNextPageError && (
|
||||
{isFetchNextPageError && (sessions?.length ?? 0) > 0 && (
|
||||
<div className="flex flex-col items-center gap-2 py-4">
|
||||
<p className="text-sm text-muted-foreground">Failed to load more sessions.</p>
|
||||
<Button variant="outline" size="sm" onClick={handleRetryNextPage} disabled={isFetchingNextPage}>
|
||||
@@ -339,7 +333,7 @@ export const SessionList = ({
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isFetchingNextPage && (
|
||||
{isFetchingNextPage && (sessions?.length ?? 0) > 0 && (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">
|
||||
Loading more sessions...
|
||||
</div>
|
||||
|
||||
@@ -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<typeof import('@/hooks/useOpenCode')>()
|
||||
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<typeof import('@/stores/sessionStatusStore')>()
|
||||
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<React.ComponentProps<typeof SessionPickerDialog>> = {}) {
|
||||
const onOpenChange = vi.fn()
|
||||
const onSelectSession = vi.fn()
|
||||
const onDeleteActiveSession = vi.fn()
|
||||
render(
|
||||
<SessionPickerDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
currentRepo={mocks.repos[0]}
|
||||
onSelectSession={onSelectSession}
|
||||
onDeleteActiveSession={onDeleteActiveSession}
|
||||
{...overrides}
|
||||
/>,
|
||||
)
|
||||
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 (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open-picker</button>
|
||||
<SessionPickerDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
currentRepo={mocks.repos[0]}
|
||||
onSelectSession={vi.fn()}
|
||||
onDeleteActiveSession={vi.fn()}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(<Host />)
|
||||
|
||||
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<void>((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 (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(false)}>close-picker</button>
|
||||
<button type="button" onClick={() => setOpen(true)}>open-picker</button>
|
||||
<SessionPickerDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
currentRepo={mocks.repos[0]}
|
||||
activeSessionID="ses_active"
|
||||
onSelectSession={vi.fn()}
|
||||
onDeleteActiveSession={vi.fn()}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(<Host />)
|
||||
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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<string>,
|
||||
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<number, SessionPickerRow[]>()
|
||||
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 (
|
||||
<SessionStatusIndicator
|
||||
sessionID={sessionID}
|
||||
size="sm"
|
||||
className="[&>div]:gap-0 [&>div>div]:h-1.5 [&>div>div]:w-px"
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (isActive) {
|
||||
return <span aria-hidden="true">●</span>
|
||||
}
|
||||
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 (
|
||||
<div
|
||||
ref={(node) => 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',
|
||||
)}
|
||||
>
|
||||
<div
|
||||
role="option"
|
||||
id={optionId}
|
||||
aria-selected={isCursor}
|
||||
onClick={() => onOpen(row)}
|
||||
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2"
|
||||
>
|
||||
<span className="flex w-4 shrink-0 items-center justify-center">
|
||||
<SessionPickerGutter sessionID={row.session.id} isActive={isActive} />
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'min-w-0 flex-1 truncate',
|
||||
isPendingDelete
|
||||
? 'text-destructive-foreground'
|
||||
: isCursor
|
||||
? 'text-primary-foreground'
|
||||
: isActive
|
||||
? 'text-primary'
|
||||
: 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{isPendingDelete ? 'Press Ctrl+D again to confirm' : row.session.title || UNTITLED_SESSION_TITLE}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'flex shrink-0 items-center gap-2 text-xs',
|
||||
isPendingDelete
|
||||
? 'text-destructive-foreground/80'
|
||||
: isCursor
|
||||
? 'text-primary-foreground/80'
|
||||
: 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{showRepo && <span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>}
|
||||
<span>{formatShortRelativeTime(new Date(row.session.time.updated))}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center pr-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
aria-label="Session actions"
|
||||
onClick={(event) => 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',
|
||||
)}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="z-[200]" onClick={(event) => event.stopPropagation()}>
|
||||
<DropdownMenuItem onClick={() => onTogglePin(row)}>
|
||||
{isPinned ? <PinOff className="h-4 w-4 mr-2" /> : <Pin className="h-4 w-4 mr-2" />}
|
||||
{isPinned ? 'Unpin' : 'Pin'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => onRequestDelete(row.session)}>Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
interface SessionPickerContentProps {
|
||||
open: boolean
|
||||
currentRepo: Repo | undefined
|
||||
activeSessionID?: string
|
||||
onSelectSession: (session: Session, repo: Repo) => void
|
||||
onDeleteActiveSession: () => void
|
||||
searchInputRef: React.RefObject<HTMLInputElement | null>
|
||||
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<HTMLDivElement>(null)
|
||||
const rowRefs = useRef(new Map<string, HTMLDivElement>())
|
||||
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<string | null>(null)
|
||||
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
|
||||
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(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<HTMLInputElement>) => {
|
||||
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<HTMLDivElement>) => {
|
||||
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 (
|
||||
<>
|
||||
<DialogTitle className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
|
||||
Sessions
|
||||
{!allProjects && currentRepo && (
|
||||
<span className="font-normal text-muted-foreground"> for {getRepoDisplayName(currentRepo)}</span>
|
||||
)}
|
||||
</DialogTitle>
|
||||
|
||||
<div className="mt-4 flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
ref={searchInputRef}
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-controls={listId}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={cursorIndex >= 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"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-pressed={allProjects}
|
||||
onClick={toggleAllProjects}
|
||||
className="h-9 shrink-0"
|
||||
>
|
||||
{allProjects ? 'All projects' : 'This project'}
|
||||
{hasFinePointer && (
|
||||
<kbd className="ml-1 rounded border border-border bg-muted px-1 text-[10px] text-muted-foreground">
|
||||
Ctrl+A
|
||||
</kbd>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={listRef}
|
||||
role="listbox"
|
||||
id={listId}
|
||||
aria-label="Sessions"
|
||||
onScroll={handleListScroll}
|
||||
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">
|
||||
{isLoading
|
||||
? 'Loading sessions...'
|
||||
: isSearchPending
|
||||
? 'Searching sessions...'
|
||||
: trimmedQuery
|
||||
? 'No sessions found'
|
||||
: 'No sessions yet'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{sections.map((section) => (
|
||||
<div
|
||||
key={section.id}
|
||||
role="group"
|
||||
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
|
||||
>
|
||||
<div
|
||||
id={`${optionBaseId}-heading-${section.id}`}
|
||||
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
|
||||
>
|
||||
{section.heading}
|
||||
</div>
|
||||
{section.rows.map((row) => {
|
||||
const index = rowIndexByKey.get(row.key) ?? -1
|
||||
return (
|
||||
<SessionPickerRowItem
|
||||
key={row.key}
|
||||
row={row}
|
||||
index={index}
|
||||
optionId={optionId(optionBaseId, index)}
|
||||
isCursor={index === cursorIndex}
|
||||
isActive={row.session.id === activeSessionID}
|
||||
isPinned={pinnedKeys.has(row.key)}
|
||||
isPendingDelete={pendingDeleteKey === row.key}
|
||||
showRepo={allProjects}
|
||||
onOpen={openRow}
|
||||
onHover={moveCursor}
|
||||
onTogglePin={handleTogglePin}
|
||||
onRequestDelete={handleRequestDelete}
|
||||
registerRef={setRowRef}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
{isFetchNextPageError && (
|
||||
<div className="flex flex-col items-center gap-2 py-4">
|
||||
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void fetchNextPage()
|
||||
}}
|
||||
disabled={isFetchingNextPage}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isFetchingNextPage && rows.length > 0 && (
|
||||
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
|
||||
↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteSessionDialog
|
||||
open={sessionToDelete !== null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
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<HTMLInputElement>(null)
|
||||
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
mobileFullscreen
|
||||
className="flex min-h-0 w-full min-w-0 flex-col gap-0 p-0 sm:h-[70vh] sm:max-w-3xl sm:p-6"
|
||||
onEscapeKeyDown={() => onOpenChange(false)}
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
if (hasFinePointer) {
|
||||
searchInputRef.current?.focus()
|
||||
} else {
|
||||
;(event.currentTarget as HTMLElement).focus()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SessionPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
activeSessionID={activeSessionID}
|
||||
onSelectSession={onSelectSession}
|
||||
onDeleteActiveSession={onDeleteActiveSession}
|
||||
searchInputRef={searchInputRef}
|
||||
hasFinePointer={hasFinePointer}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -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(<KeyboardShortcuts />)
|
||||
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(<KeyboardShortcuts />)
|
||||
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(<KeyboardShortcuts />)
|
||||
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(<KeyboardShortcuts />)
|
||||
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(<KeyboardShortcuts />)
|
||||
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',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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<string, string>): 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<string | null>(null)
|
||||
const [currentKeys, setCurrentKeys] = useState<string>('')
|
||||
|
||||
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<Record<string, string>>(() => ({
|
||||
...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<HTMLInputElement>(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<HTMLInputElement>) => {
|
||||
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 (
|
||||
<div className="bg-card border border-border rounded-lg p-6">
|
||||
@@ -270,7 +320,25 @@ export function KeyboardShortcuts() {
|
||||
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-lg p-6">
|
||||
<h2 className="text-lg font-semibold text-foreground mb-6">Keyboard Shortcuts</h2>
|
||||
<div className="mb-6 flex flex-wrap items-start justify-between gap-3">
|
||||
<h2 className="text-lg font-semibold text-foreground">Keyboard Shortcuts</h2>
|
||||
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
Import from OpenCode TUI
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".json,.jsonc,application/json"
|
||||
className="hidden"
|
||||
onChange={importFromTui}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground text-right">
|
||||
Select your OpenCode cli.json (or legacy tui.json), usually in ~/.config/opencode.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 py-3 border-b border-border">
|
||||
<div className="flex min-w-0 flex-wrap items-baseline gap-x-2">
|
||||
@@ -316,7 +384,7 @@ export function KeyboardShortcuts() {
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-sm text-muted-foreground">
|
||||
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.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -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(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<BottomSheet isOpen={isOpen} onClose={() => {}} ariaLabel="Test sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
}
|
||||
|
||||
function AutoFocusSheetHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open sheet</button>
|
||||
<BottomSheet isOpen={open} onClose={() => setOpen(false)} ariaLabel="Auto focus sheet">
|
||||
<input aria-label="sheet input" autoFocus />
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
screen.getByRole('button', { name: 'inside' }).focus()
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Test sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(screen.getByLabelText('prompt')).toHaveFocus()
|
||||
})
|
||||
|
||||
it('does not refocus the chat prompt on touch when it closes', () => {
|
||||
stubMatchMedia(false)
|
||||
const { rerender } = renderSheet(false)
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
screen.getByRole('button', { name: 'inside' }).focus()
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Test sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(screen.getByLabelText('prompt')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
|
||||
stubMatchMedia(true)
|
||||
render(<AutoFocusSheetHost />)
|
||||
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(
|
||||
<button type="button">opener</button>,
|
||||
)
|
||||
const opener = screen.getByRole('button', { name: 'opener' })
|
||||
opener.focus()
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<button type="button">opener</button>
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Mounted open sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<button type="button">opener</button>
|
||||
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Mounted open sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(opener).toHaveFocus()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BottomSheetHeader', () => {
|
||||
|
||||
@@ -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<HTMLDivElement>(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}
|
||||
>
|
||||
<div className="w-full flex justify-center pt-3 pb-2">
|
||||
|
||||
@@ -441,6 +441,22 @@ function ReturnFocusHost({ onCloseAutoFocus }: { onCloseAutoFocus?: (event: Even
|
||||
)
|
||||
}
|
||||
|
||||
function PromptReturnFocusHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="chat prompt" />
|
||||
<button type="button" onClick={() => setOpen(true)}>open prompt dialog</button>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogTitle>Prompt Focus Dialog</DialogTitle>
|
||||
<input aria-label="prompt dialog input" autoFocus />
|
||||
</DialogContent>
|
||||
</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(<PromptReturnFocusHost />)
|
||||
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) {
|
||||
|
||||
@@ -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<boolean>(true)
|
||||
const DialogReturnFocusContext = React.createContext<HTMLElement | null>(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<typeof DialogPrimitive.Root>) {
|
||||
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)
|
||||
|
||||
@@ -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(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<SideDrawer isOpen={isOpen} onClose={() => {}} ariaLabel="Test drawer">
|
||||
<button type="button">inside</button>
|
||||
</SideDrawer>
|
||||
</>,
|
||||
)
|
||||
}
|
||||
|
||||
function AutoFocusDrawerHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open drawer</button>
|
||||
<SideDrawer isOpen={open} onClose={() => setOpen(false)} ariaLabel="Auto focus drawer">
|
||||
<input aria-label="drawer input" autoFocus />
|
||||
</SideDrawer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<SideDrawer isOpen onClose={() => {}} ariaLabel="Test drawer">
|
||||
<button type="button">inside</button>
|
||||
</SideDrawer>
|
||||
</>,
|
||||
)
|
||||
screen.getByRole('button', { name: 'inside' }).focus()
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<textarea data-prompt-input aria-label="prompt" />
|
||||
<SideDrawer isOpen={false} onClose={() => {}} ariaLabel="Test drawer">
|
||||
<button type="button">inside</button>
|
||||
</SideDrawer>
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(screen.getByLabelText('prompt')).toHaveFocus()
|
||||
})
|
||||
|
||||
it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
|
||||
stubMatchMedia(true)
|
||||
render(<AutoFocusDrawerHost />)
|
||||
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', () => {
|
||||
|
||||
@@ -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<HTMLDivElement>(null)
|
||||
|
||||
useRestoreFocusOnClose(isOpen, panelRef)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -81,6 +85,7 @@ export function SideDrawer({
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div
|
||||
ref={panelRef}
|
||||
className={cn(
|
||||
'fixed top-0 bottom-0 bg-background border-l border-border pt-safe flex flex-col z-50',
|
||||
side === 'right' ? 'right-0' : 'left-0',
|
||||
@@ -90,6 +95,7 @@ export function SideDrawer({
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={ariaLabel}
|
||||
data-state={isOpen ? 'open' : 'closed'}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
@@ -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<string, string>,
|
||||
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<K extends keyof HTMLElementTagNameMap>(tag: K, attributes: Record<string, string> = {}) {
|
||||
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 <ActionLayer actions={actions} />
|
||||
}
|
||||
|
||||
function renderProvider(children: ReactNode) {
|
||||
return render(<KeyboardShortcutsProvider>{children}</KeyboardShortcutsProvider>)
|
||||
}
|
||||
|
||||
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(<ActionLayer actions={{ submit, abort }} />)
|
||||
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(<ActionLayer actions={{ newSession }} />)
|
||||
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(<ActionLayer actions={{ variantCycle }} />)
|
||||
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(<ActionLayer actions={{ submit, abort }} />)
|
||||
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(<ActionLayer actions={{ submit }} />)
|
||||
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(<ActionLayer actions={{ toggleMode }} />)
|
||||
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(<ActionLayer actions={{ toggleMode }} />)
|
||||
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(<ActionLayer actions={{ clearPrompt }} />)
|
||||
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(<ActionLayer actions={{ halfPageDown }} />)
|
||||
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(<ActionLayer actions={{ halfPageUp }} />)
|
||||
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(<ActionLayer actions={{ abort }} />)
|
||||
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(<ActionLayer actions={{ abort }} />)
|
||||
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(<ActionLayer actions={{ newSession, toggleTerminal }} />)
|
||||
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(<ActionLayer actions={{ variantCycle, halfPageUp, toggleTerminal }} />)
|
||||
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(<ActionLayer actions={{ abort }} />)
|
||||
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(<ActionLayer actions={{ abort: undefined }} />)
|
||||
|
||||
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(
|
||||
<>
|
||||
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
|
||||
<ActionLayer actions={{ abort: pageAbort }} scope="page" />
|
||||
</>
|
||||
)
|
||||
|
||||
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(
|
||||
<>
|
||||
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
|
||||
<ActionLayer actions={{ abort: undefined }} scope="page" />
|
||||
</>
|
||||
)
|
||||
|
||||
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(
|
||||
<>
|
||||
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
|
||||
<ConditionalLayer show actions={{ abort: pageAbort }} />
|
||||
</>
|
||||
)
|
||||
|
||||
pressKey(document.body, { key: 'Escape' })
|
||||
expect(pageAbort).toHaveBeenCalledTimes(1)
|
||||
expect(globalAbort).not.toHaveBeenCalled()
|
||||
|
||||
view.rerender(
|
||||
<KeyboardShortcutsProvider>
|
||||
<ActionLayer actions={{ abort: globalAbort }} scope="global" />
|
||||
<ConditionalLayer show={false} actions={{ abort: pageAbort }} />
|
||||
</KeyboardShortcutsProvider>
|
||||
)
|
||||
|
||||
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(<ActionLayer actions={{ newSession }} />)
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<Record<KeyboardShortcutAction, () => void>>
|
||||
|
||||
interface ShortcutLayer {
|
||||
actionsRef: { current: ShortcutActions }
|
||||
}
|
||||
|
||||
interface ShortcutRegistry {
|
||||
global: ShortcutLayer[]
|
||||
page: ShortcutLayer[]
|
||||
}
|
||||
|
||||
const KeyboardShortcutsRegistryContext = createContext<ShortcutRegistry | null>(null)
|
||||
|
||||
const PROMPT_ONLY_DIRECT_ACTIONS: ReadonlySet<string> = new Set(['toggleMode', 'clearPrompt'])
|
||||
|
||||
const HALF_PAGE_DIRECT_ACTIONS: ReadonlySet<string> = 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<ReturnType<typeof setTimeout> | null>(null)
|
||||
const preferencesRef = useRef(preferences)
|
||||
preferencesRef.current = preferences
|
||||
const registryRef = useRef<ShortcutRegistry>({ 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 (
|
||||
<KeyboardShortcutsRegistryContext.Provider value={registryRef.current}>
|
||||
{children}
|
||||
{leaderActive && (
|
||||
<div className="fixed bottom-24 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse">
|
||||
<span className="text-sm font-medium">Waiting for shortcut key...</span>
|
||||
</div>
|
||||
)}
|
||||
</KeyboardShortcutsRegistryContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<ShortcutLayer>({ 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])
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -20,14 +20,25 @@ export function dialogSearch(name: string, extraParams?: Record<string, string>)
|
||||
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<string, string>,
|
||||
): void {
|
||||
setDialogParams(params, name, extraParams)
|
||||
params.delete('mobileTab')
|
||||
}
|
||||
|
||||
export function openDialogParam(
|
||||
updateParams: ReturnType<typeof useUrlParams>['updateParams'],
|
||||
name: string,
|
||||
extraParams?: Record<string, string>,
|
||||
): void {
|
||||
updateParams((p) => {
|
||||
setDialogParams(p, name, extraParams)
|
||||
p.delete('mobileTab')
|
||||
openDialogParams(p, name, extraParams)
|
||||
}, 'push')
|
||||
}
|
||||
|
||||
|
||||
@@ -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 <div data-testid="location">{`${location.pathname}${location.search}`}</div>
|
||||
}
|
||||
|
||||
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(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<KeyboardShortcutsProvider>
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<Harness />
|
||||
<LocationDisplay />
|
||||
</MemoryRouter>
|
||||
</KeyboardShortcutsProvider>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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<ReturnType<typeof setTimeout> | 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 }
|
||||
}
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<string, string>
|
||||
type SessionDirectoryCursors = Record<string, string>
|
||||
|
||||
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<SessionListPage, SessionListPageParam | undefined>,
|
||||
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<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
) => {
|
||||
const deletedIDs = new Set(
|
||||
(Array.isArray(variables) ? variables : [variables]).map(getDeleteSessionTargetId),
|
||||
);
|
||||
if (deletedIDs.size === 0) return;
|
||||
queryClient.setQueriesData<InfiniteData<SessionListPage, SessionListPageParam | undefined>>(
|
||||
{ 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<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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]
|
||||
}
|
||||
@@ -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<HTMLElement | null>,
|
||||
): void {
|
||||
const returnFocusRef = useRef<HTMLElement | null>(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])
|
||||
}
|
||||
@@ -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<typeof import('@/hooks/useOpenCode')>()
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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) &&
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
const CONTENT_EDITABLE_VALUES = new Set(['', 'true', 'plaintext-only'])
|
||||
|
||||
/**
|
||||
* Returns true for free-text entry targets: `<input>`, `<textarea>`, and any content-editable
|
||||
* element (`contenteditable=""`, `"true"`, or `"plaintext-only"`).
|
||||
*/
|
||||
export function isTextEntryElement(element: Element): boolean {
|
||||
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) return true
|
||||
if (!(element instanceof HTMLElement)) return false
|
||||
if (element.isContentEditable) return true
|
||||
const contentEditable = element.getAttribute('contenteditable')
|
||||
return contentEditable !== null && CONTENT_EDITABLE_VALUES.has(contentEditable.toLowerCase())
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when the element carries the `data-prompt-input` attribute that marks the chat prompt.
|
||||
*/
|
||||
export function isPromptInput(element: Element): boolean {
|
||||
return element.hasAttribute('data-prompt-input')
|
||||
}
|
||||
|
||||
/**
|
||||
* Selector matching the chat prompt input.
|
||||
*/
|
||||
export const PROMPT_INPUT_SELECTOR = 'textarea[data-prompt-input]'
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getNextFavoriteModel } from './favoriteModels'
|
||||
import type { ModelSelection } from '@/api/providers'
|
||||
|
||||
const model = (providerID: string, modelID: string): ModelSelection => ({ providerID, modelID })
|
||||
|
||||
describe('getNextFavoriteModel', () => {
|
||||
it('returns undefined when there are no favorites', () => {
|
||||
expect(getNextFavoriteModel([], model('anthropic', 'claude-sonnet-4'))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns the first favorite when nothing is selected', () => {
|
||||
const favorites = [model('anthropic', 'claude-sonnet-4'), model('openai', 'gpt-5')]
|
||||
expect(getNextFavoriteModel(favorites, null)).toEqual(favorites[0])
|
||||
})
|
||||
|
||||
it('returns the first favorite when the current model is not a favorite', () => {
|
||||
const favorites = [model('anthropic', 'claude-sonnet-4'), model('openai', 'gpt-5')]
|
||||
expect(getNextFavoriteModel(favorites, model('opencode-go', 'go-1'))).toEqual(favorites[0])
|
||||
})
|
||||
|
||||
it('returns the next favorite in the middle of the list', () => {
|
||||
const favorites = [model('a', 'x'), model('b', 'y'), model('c', 'z')]
|
||||
expect(getNextFavoriteModel(favorites, favorites[0])).toEqual(favorites[1])
|
||||
expect(getNextFavoriteModel(favorites, favorites[1])).toEqual(favorites[2])
|
||||
})
|
||||
|
||||
it('wraps around from the last favorite to the first', () => {
|
||||
const favorites = [model('a', 'x'), model('b', 'y'), model('c', 'z')]
|
||||
expect(getNextFavoriteModel(favorites, favorites[2])).toEqual(favorites[0])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
import { isSameModelSelection } from '@opencode-manager/shared/opencode'
|
||||
import type { ModelSelection } from '@/api/providers'
|
||||
|
||||
export function getNextFavoriteModel(
|
||||
favorites: readonly ModelSelection[],
|
||||
current: ModelSelection | null,
|
||||
): ModelSelection | undefined {
|
||||
if (favorites.length === 0) return undefined
|
||||
if (!current) return favorites[0]
|
||||
|
||||
const index = favorites.findIndex((favorite) => isSameModelSelection(favorite, current))
|
||||
if (index === -1) return favorites[0]
|
||||
|
||||
return favorites[(index + 1) % favorites.length]
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
|
||||
import { formatShortcutEvent, getDefaultKeyboardShortcuts, normalizeShortcut, resolveDirectShortcuts, resolveShortcutBindings } from './keyboardShortcuts'
|
||||
|
||||
describe('keyboardShortcuts', () => {
|
||||
it('normalizes key aliases, modifier order and bare symbol keys', () => {
|
||||
expect(normalizeShortcut('Ctrl+Enter')).toBe('Ctrl+Return')
|
||||
expect(normalizeShortcut('Escape')).toBe('Esc')
|
||||
expect(normalizeShortcut('Shift+Ctrl+z')).toBe('Ctrl+Shift+Z')
|
||||
expect(normalizeShortcut('Ctrl++')).toBe('Ctrl++')
|
||||
expect(normalizeShortcut('+')).toBe('+')
|
||||
})
|
||||
|
||||
it('reads letters from the physical key when Alt rewrites the character', () => {
|
||||
expect(formatShortcutEvent(new KeyboardEvent('keydown', { key: '†', code: 'KeyT', altKey: true }))).toBe('Alt+T')
|
||||
expect(formatShortcutEvent(new KeyboardEvent('keydown', { key: 'Shift', shiftKey: true }))).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the shared defaults with the key set', () => {
|
||||
expect(Object.keys(getDefaultKeyboardShortcuts())).toEqual(Object.keys(DEFAULT_KEYBOARD_SHORTCUTS))
|
||||
})
|
||||
|
||||
it('never rewrites a stored direct-shortcut list', () => {
|
||||
expect(resolveDirectShortcuts(['abort', 'submit'])).toEqual(['abort', 'submit'])
|
||||
expect(resolveDirectShortcuts(undefined)).toBe(DEFAULT_DIRECT_SHORTCUTS)
|
||||
})
|
||||
|
||||
it('adds default direct actions the stored shortcut map does not know about', () => {
|
||||
expect(resolveDirectShortcuts(['submit'], { submit: 'Return' })).toEqual(DEFAULT_DIRECT_SHORTCUTS)
|
||||
expect(resolveDirectShortcuts(['submit'], { submit: 'Return', abort: 'Escape' })).toEqual(
|
||||
DEFAULT_DIRECT_SHORTCUTS.filter((action) => action !== 'abort'),
|
||||
)
|
||||
expect(resolveDirectShortcuts(['abort', 'submit'], { abort: 'Escape', submit: 'Return' })).toEqual([
|
||||
'abort',
|
||||
'submit',
|
||||
...DEFAULT_DIRECT_SHORTCUTS.filter((action) => action !== 'abort' && action !== 'submit'),
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves the built-in bindings for a user with no stored preferences', () => {
|
||||
const bindings = resolveShortcutBindings(undefined)
|
||||
expect(bindings.leaderKey).toBe(DEFAULT_LEADER_KEY)
|
||||
expect(bindings.shortcuts.submit).toBe(DEFAULT_KEYBOARD_SHORTCUTS.submit)
|
||||
expect(bindings.shortcuts.toggleMode).toBe('Shift+Tab')
|
||||
expect(bindings.shortcuts.toggleTerminal).toBe('T')
|
||||
expect(bindings.shortcuts.halfPageDown).toBe('Ctrl+D')
|
||||
expect(bindings.directShortcuts).toBe(DEFAULT_DIRECT_SHORTCUTS)
|
||||
})
|
||||
|
||||
it('keeps stored bindings and fills the rest from the defaults', () => {
|
||||
const bindings = resolveShortcutBindings({
|
||||
keyboardShortcuts: { submit: 'Return', newSession: 'K' },
|
||||
directShortcuts: ['submit'],
|
||||
})
|
||||
expect(bindings.shortcuts.submit).toBe('Return')
|
||||
expect(bindings.shortcuts.newSession).toBe('K')
|
||||
expect(bindings.shortcuts.toggleMode).toBe('Shift+Tab')
|
||||
})
|
||||
|
||||
it('drops a new default that would collide with a stored binding of the same kind', () => {
|
||||
const bindings = resolveShortcutBindings({
|
||||
keyboardShortcuts: { toggleMode: 'T' },
|
||||
directShortcuts: ['submit', 'abort'],
|
||||
})
|
||||
expect(bindings.shortcuts.toggleMode).toBe('T')
|
||||
expect(bindings.shortcuts.toggleTerminal).toBe('')
|
||||
})
|
||||
|
||||
it('keeps a new default whose kind differs from the stored binding on the same key', () => {
|
||||
const bindings = resolveShortcutBindings({
|
||||
keyboardShortcuts: { toggleMode: 'T' },
|
||||
directShortcuts: ['submit', 'abort', 'toggleMode'],
|
||||
})
|
||||
expect(bindings.shortcuts.toggleMode).toBe('T')
|
||||
expect(bindings.shortcuts.toggleTerminal).toBe('T')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
|
||||
|
||||
const isMac = typeof navigator !== 'undefined' && navigator.platform.toUpperCase().includes('MAC')
|
||||
|
||||
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
|
||||
|
||||
const MODIFIER_ORDER = ['Ctrl', 'Cmd', 'Alt', 'Shift']
|
||||
|
||||
const MODIFIER_EVENT_KEYS = ['Control', 'Meta', 'Alt', 'Shift']
|
||||
|
||||
const KEY_ALIASES: Record<string, string> = {
|
||||
' ': 'Space',
|
||||
ArrowUp: 'Up',
|
||||
ArrowDown: 'Down',
|
||||
ArrowLeft: 'Left',
|
||||
ArrowRight: 'Right',
|
||||
Enter: 'Return',
|
||||
Escape: 'Esc',
|
||||
}
|
||||
|
||||
interface ShortcutPreferences {
|
||||
leaderKey?: string
|
||||
directShortcuts?: string[]
|
||||
keyboardShortcuts?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface ShortcutBindings {
|
||||
leaderKey: string
|
||||
shortcuts: Record<string, string>
|
||||
directShortcuts: string[]
|
||||
}
|
||||
|
||||
function canonicalKey(key: string): string {
|
||||
return KEY_ALIASES[key] ?? (key.length === 1 ? key.toUpperCase() : key)
|
||||
}
|
||||
|
||||
function eventModifiers(e: KeyboardEvent): string[] {
|
||||
return [e.ctrlKey && 'Ctrl', e.metaKey && 'Cmd', e.altKey && 'Alt', e.shiftKey && 'Shift'].filter((key): key is string => Boolean(key))
|
||||
}
|
||||
|
||||
/**
|
||||
* The main key of an event; with Alt held, letters and digits come from the physical key because macOS Option rewrites `key`.
|
||||
*/
|
||||
function eventMainKey(e: KeyboardEvent): string {
|
||||
if (e.altKey && /^Key[A-Z]$/.test(e.code)) return e.code.slice(3)
|
||||
if (e.altKey && /^Digit\d$/.test(e.code)) return e.code.slice(5)
|
||||
return canonicalKey(e.key)
|
||||
}
|
||||
|
||||
export function isModifierOnlyEvent(e: KeyboardEvent): boolean {
|
||||
return MODIFIER_EVENT_KEYS.includes(e.key)
|
||||
}
|
||||
|
||||
export function formatEventModifiers(e: KeyboardEvent): string {
|
||||
return eventModifiers(e).join('+')
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a keydown event as a canonical shortcut string such as `Cmd+Shift+Z`, or null for a lone modifier key.
|
||||
*/
|
||||
export function formatShortcutEvent(e: KeyboardEvent): string | null {
|
||||
if (isModifierOnlyEvent(e)) return null
|
||||
return [...eventModifiers(e), eventMainKey(e)].join('+')
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonicalizes a stored shortcut: `Cmd` becomes `Ctrl` off macOS, key aliases such as `Enter`/`Return` collapse, and modifiers are ordered.
|
||||
*/
|
||||
export function normalizeShortcut(shortcut: string): string {
|
||||
if (!shortcut) return ''
|
||||
const separator = shortcut.length < 2 ? -1 : shortcut.lastIndexOf('+', shortcut.length - 2)
|
||||
const mainKey = canonicalKey(shortcut.slice(separator + 1))
|
||||
const modifiers = separator < 0 ? [] : shortcut.slice(0, separator).split('+').map((modifier) => (modifier === 'Cmd' ? CMD_KEY : modifier))
|
||||
const orderedModifiers = MODIFIER_ORDER.filter((modifier) => modifiers.includes(modifier))
|
||||
return [...orderedModifiers, mainKey].join('+')
|
||||
}
|
||||
|
||||
export function hasCommandModifier(shortcut: string): boolean {
|
||||
return /(^|\+)(Ctrl|Cmd|Alt)\+./.test(shortcut)
|
||||
}
|
||||
|
||||
/**
|
||||
* The built-in shortcut defaults for the current platform: the shared table plus the macOS-only clear-prompt binding,
|
||||
* which shared cannot express because it must contain no platform detection.
|
||||
*/
|
||||
export function getDefaultKeyboardShortcuts(): Record<string, string> {
|
||||
return {
|
||||
...DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
clearPrompt: isMac ? 'Ctrl+C' : '',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The direct-shortcut list, adding any default direct action that the stored shortcut map does not yet know about, so
|
||||
* newly added direct defaults reach users who customized their list. A default direct action that is already a key of
|
||||
* the stored map is treated as stored, never re-added. When `storedShortcuts` is omitted the list is returned unchanged.
|
||||
*/
|
||||
export function resolveDirectShortcuts(directShortcuts: string[] | undefined, storedShortcuts?: Record<string, string>): string[] {
|
||||
if (!directShortcuts) return DEFAULT_DIRECT_SHORTCUTS
|
||||
if (!storedShortcuts) return directShortcuts
|
||||
const additions = DEFAULT_DIRECT_SHORTCUTS.filter(
|
||||
(action) => !(action in storedShortcuts) && !directShortcuts.includes(action),
|
||||
)
|
||||
return additions.length > 0 ? [...directShortcuts, ...additions] : directShortcuts
|
||||
}
|
||||
|
||||
function bindingSignature(action: string, keys: string, directShortcuts: string[]): string {
|
||||
const kind = directShortcuts.includes(action) ? 'direct' : 'leader'
|
||||
return `${kind}:${normalizeShortcut(keys)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective shortcut map: stored bindings always win, defaults fill the actions the user never stored, and a default
|
||||
* for an action outside the stored map is dropped to unbound when its normalized key and leader/direct kind would
|
||||
* collide with a binding that is stored.
|
||||
*/
|
||||
function resolveShortcutMap(stored: Record<string, string>, directShortcuts: string[]): Record<string, string> {
|
||||
const resolved: Record<string, string> = { ...stored }
|
||||
const storedBindings = new Set(
|
||||
Object.entries(stored)
|
||||
.filter(([, keys]) => Boolean(keys))
|
||||
.map(([action, keys]) => bindingSignature(action, keys, directShortcuts)),
|
||||
)
|
||||
for (const [action, defaultKeys] of Object.entries(getDefaultKeyboardShortcuts())) {
|
||||
if (action in stored) continue
|
||||
const collides = Boolean(defaultKeys) && storedBindings.has(bindingSignature(action, defaultKeys, directShortcuts))
|
||||
resolved[action] = collides ? '' : defaultKeys
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
export function resolveShortcutBindings(preferences: ShortcutPreferences | undefined): ShortcutBindings {
|
||||
const directShortcuts = resolveDirectShortcuts(preferences?.directShortcuts, preferences?.keyboardShortcuts)
|
||||
return {
|
||||
leaderKey: normalizeShortcut(preferences?.leaderKey || DEFAULT_LEADER_KEY),
|
||||
shortcuts: resolveShortcutMap(preferences?.keyboardShortcuts ?? {}, directShortcuts),
|
||||
directShortcuts,
|
||||
}
|
||||
}
|
||||
|
||||
export function findShortcutAction(bindings: ShortcutBindings, shortcut: string, direct: boolean): string | undefined {
|
||||
return Object.entries(bindings.shortcuts).find(([action, keys]) => (
|
||||
Boolean(keys) && bindings.directShortcuts.includes(action) === direct && normalizeShortcut(keys) === shortcut
|
||||
))?.[0]
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { getFocusedElement, hasOpenOverlay, restoreOverlayFocus } from './overlayFocus'
|
||||
import { PROMPT_INPUT_SELECTOR, isPromptInput, isTextEntryElement } from './domTargets'
|
||||
|
||||
function createElement<K extends keyof HTMLElementTagNameMap>(
|
||||
tag: K,
|
||||
attrs: Record<string, string> = {},
|
||||
): HTMLElementTagNameMap[K] {
|
||||
const element = document.createElement(tag)
|
||||
for (const [name, value] of Object.entries(attrs)) element.setAttribute(name, value)
|
||||
document.body.appendChild(element)
|
||||
return element
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
describe('getFocusedElement', () => {
|
||||
it('returns the focused element', () => {
|
||||
const button = createElement('button')
|
||||
button.focus()
|
||||
expect(getFocusedElement()).toBe(button)
|
||||
})
|
||||
})
|
||||
|
||||
describe('restoreOverlayFocus', () => {
|
||||
it('focuses the chat prompt on desktop when focus was on a button', () => {
|
||||
stubMatchMedia(true)
|
||||
const prompt = createElement('textarea', { 'data-prompt-input': '' })
|
||||
const button = createElement('button')
|
||||
button.focus()
|
||||
|
||||
const moved = restoreOverlayFocus(button, null)
|
||||
|
||||
expect(moved).toBe(true)
|
||||
expect(document.activeElement).toBe(prompt)
|
||||
})
|
||||
|
||||
it('returns focus to a specific text field on desktop', () => {
|
||||
stubMatchMedia(true)
|
||||
const prompt = createElement('textarea', { 'data-prompt-input': '' })
|
||||
const search = createElement('input')
|
||||
|
||||
const moved = restoreOverlayFocus(search, null)
|
||||
|
||||
expect(moved).toBe(true)
|
||||
expect(document.activeElement).toBe(search)
|
||||
expect(document.activeElement).not.toBe(prompt)
|
||||
})
|
||||
|
||||
it('keeps focus inside another open overlay', () => {
|
||||
stubMatchMedia(true)
|
||||
const prompt = createElement('textarea', { 'data-prompt-input': '' })
|
||||
const overlay = createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
const overlayInput = createElement('input')
|
||||
overlay.appendChild(overlayInput)
|
||||
|
||||
const moved = restoreOverlayFocus(overlayInput, null)
|
||||
|
||||
expect(moved).toBe(true)
|
||||
expect(document.activeElement).toBe(overlayInput)
|
||||
expect(document.activeElement).not.toBe(prompt)
|
||||
})
|
||||
|
||||
it('does not jump to the prompt behind another open overlay', () => {
|
||||
stubMatchMedia(true)
|
||||
const prompt = createElement('textarea', { 'data-prompt-input': '' })
|
||||
createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
const button = createElement('button')
|
||||
|
||||
const moved = restoreOverlayFocus(button, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(prompt)
|
||||
})
|
||||
|
||||
it('focuses a non-text return target on touch devices', () => {
|
||||
stubMatchMedia(false)
|
||||
const prompt = createElement('textarea', { 'data-prompt-input': '' })
|
||||
const button = createElement('button')
|
||||
|
||||
const moved = restoreOverlayFocus(button, null)
|
||||
|
||||
expect(moved).toBe(true)
|
||||
expect(document.activeElement).toBe(button)
|
||||
expect(document.activeElement).not.toBe(prompt)
|
||||
})
|
||||
|
||||
it('does not refocus a text field on touch devices', () => {
|
||||
stubMatchMedia(false)
|
||||
const comment = createElement('textarea')
|
||||
|
||||
const moved = restoreOverlayFocus(comment, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(comment)
|
||||
})
|
||||
|
||||
it('falls back to the return target when no prompt exists', () => {
|
||||
stubMatchMedia(true)
|
||||
const button = createElement('button')
|
||||
|
||||
const moved = restoreOverlayFocus(button, null)
|
||||
|
||||
expect(moved).toBe(true)
|
||||
expect(document.activeElement).toBe(button)
|
||||
})
|
||||
|
||||
it('returns false for a disabled button inside another open overlay', () => {
|
||||
stubMatchMedia(true)
|
||||
const overlay = createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
const disabled = createElement('button')
|
||||
disabled.disabled = true
|
||||
overlay.appendChild(disabled)
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
|
||||
it('returns false for a disabled input inside another open overlay', () => {
|
||||
stubMatchMedia(true)
|
||||
const overlay = createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
const disabled = createElement('input')
|
||||
disabled.disabled = true
|
||||
overlay.appendChild(disabled)
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
|
||||
it('returns false for a disabled button when no prompt exists', () => {
|
||||
stubMatchMedia(true)
|
||||
const disabled = createElement('button')
|
||||
disabled.disabled = true
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
|
||||
it('returns false for a disabled input when no prompt exists', () => {
|
||||
stubMatchMedia(true)
|
||||
const disabled = createElement('input')
|
||||
disabled.disabled = true
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasOpenOverlay', () => {
|
||||
it('returns false when no overlay is open', () => {
|
||||
expect(hasOpenOverlay()).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when a dialog is open', () => {
|
||||
createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
expect(hasOpenOverlay()).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true when an alertdialog is open', () => {
|
||||
createElement('div', { role: 'alertdialog', 'data-state': 'open' })
|
||||
expect(hasOpenOverlay()).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores closed overlays', () => {
|
||||
createElement('div', { role: 'dialog', 'data-state': 'closed' })
|
||||
expect(hasOpenOverlay()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('domTargets', () => {
|
||||
it('treats inputs and textareas as text entry', () => {
|
||||
expect(isTextEntryElement(createElement('input'))).toBe(true)
|
||||
expect(isTextEntryElement(createElement('textarea'))).toBe(true)
|
||||
})
|
||||
|
||||
it('treats contenteditable variants as text entry', () => {
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: '' }))).toBe(true)
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: 'true' }))).toBe(true)
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: 'plaintext-only' }))).toBe(true)
|
||||
})
|
||||
|
||||
it('does not treat contenteditable=false or plain elements as text entry', () => {
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: 'false' }))).toBe(false)
|
||||
expect(isTextEntryElement(createElement('button'))).toBe(false)
|
||||
})
|
||||
|
||||
it('detects the prompt input by its data attribute', () => {
|
||||
expect(isPromptInput(createElement('textarea', { 'data-prompt-input': '' }))).toBe(true)
|
||||
expect(isPromptInput(createElement('textarea'))).toBe(false)
|
||||
})
|
||||
|
||||
it('exposes the prompt input selector', () => {
|
||||
expect(PROMPT_INPUT_SELECTOR).toBe('textarea[data-prompt-input]')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { FINE_POINTER_MEDIA_QUERY } from '@/hooks/useMediaQuery'
|
||||
import { PROMPT_INPUT_SELECTOR, isPromptInput, isTextEntryElement } from '@/lib/domTargets'
|
||||
|
||||
const OPEN_OVERLAY_SELECTOR = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]'
|
||||
|
||||
/**
|
||||
* Returns the element that currently owns focus, or null outside a DOM environment.
|
||||
*/
|
||||
export function getFocusedElement(): HTMLElement | null {
|
||||
return typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null
|
||||
}
|
||||
|
||||
function isFinePointer(): boolean {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.matchMedia === 'function' &&
|
||||
window.matchMedia(FINE_POINTER_MEDIA_QUERY).matches
|
||||
)
|
||||
}
|
||||
|
||||
function focusElement(el: HTMLElement): boolean {
|
||||
el.focus({ preventScroll: true })
|
||||
return document.activeElement === el
|
||||
}
|
||||
|
||||
function isInside(element: Element, container: Element | null): boolean {
|
||||
return container !== null && container.contains(element)
|
||||
}
|
||||
|
||||
function findOpenOverlays(closing: Element | null): Element[] {
|
||||
if (typeof document === 'undefined') return []
|
||||
return Array.from(document.querySelectorAll(OPEN_OVERLAY_SELECTOR)).filter(
|
||||
(overlay) => overlay !== closing && !isInside(overlay, closing),
|
||||
)
|
||||
}
|
||||
|
||||
function findPromptInput(): HTMLTextAreaElement | null {
|
||||
if (typeof document === 'undefined') return null
|
||||
const prompt = document.querySelector<HTMLTextAreaElement>(PROMPT_INPUT_SELECTOR)
|
||||
return prompt && prompt.isConnected && !prompt.disabled ? prompt : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether any dialog or alertdialog overlay is currently open.
|
||||
*/
|
||||
export function hasOpenOverlay(): boolean {
|
||||
if (typeof document === 'undefined') return false
|
||||
return document.querySelector(OPEN_OVERLAY_SELECTOR) !== null
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves focus after an overlay closes, preferring the chat prompt on desktop while leaving
|
||||
* touch devices untouched so the on-screen keyboard stays closed.
|
||||
*
|
||||
* @returns true when focus was moved, so the caller can prevent its default handling.
|
||||
*/
|
||||
export function restoreOverlayFocus(returnFocus: HTMLElement | null, closing: Element | null = null): boolean {
|
||||
if (typeof document === 'undefined') return false
|
||||
|
||||
const isDesktop = isFinePointer()
|
||||
const openOverlays = findOpenOverlays(closing)
|
||||
|
||||
if (openOverlays.length > 0) {
|
||||
const target = returnFocus
|
||||
return Boolean(
|
||||
target?.isConnected &&
|
||||
openOverlays.some((overlay) => overlay.contains(target)) &&
|
||||
(isDesktop || !isTextEntryElement(target)) &&
|
||||
focusElement(target),
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
isDesktop &&
|
||||
returnFocus?.isConnected &&
|
||||
isTextEntryElement(returnFocus) &&
|
||||
!isPromptInput(returnFocus) &&
|
||||
!isInside(returnFocus, closing) &&
|
||||
focusElement(returnFocus)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (isDesktop) {
|
||||
const prompt = findPromptInput()
|
||||
if (prompt && focusElement(prompt)) return true
|
||||
}
|
||||
|
||||
if (
|
||||
returnFocus?.isConnected &&
|
||||
returnFocus !== document.body &&
|
||||
!isInside(returnFocus, closing) &&
|
||||
!(isTextEntryElement(returnFocus) && !isDesktop) &&
|
||||
focusElement(returnFocus)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildPinnedSessionKeys } from './sessionKey'
|
||||
import { buildPinnedSessionKeys, getSessionKey } from './sessionKey'
|
||||
import type { Session } from '@/api/types'
|
||||
|
||||
describe('getSessionKey', () => {
|
||||
it('combines the session directory and id', () => {
|
||||
const session = { id: 'ses_1', location: { directory: '/w/a' } } as Session
|
||||
|
||||
expect(getSessionKey(session)).toBe('/w/a:ses_1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildPinnedSessionKeys', () => {
|
||||
it('builds a session key for each pin', () => {
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { Session } from '@/api/types'
|
||||
|
||||
export function buildSessionKey(directory: string | undefined, id: string): string {
|
||||
return `${directory ?? ''}:${id}`
|
||||
}
|
||||
|
||||
export function getSessionKey(session: Pick<Session, 'id' | 'location'>): string {
|
||||
return buildSessionKey(session.location.directory, session.id)
|
||||
}
|
||||
|
||||
export function buildPinnedSessionKeys(
|
||||
pins: ReadonlyArray<{ directory: string; sessionId: string }>,
|
||||
): Set<string> {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyTuiKeybindImport,
|
||||
parseTuiKeybindConfig,
|
||||
type TuiKeybindImport,
|
||||
} from './tuiKeybindImport'
|
||||
|
||||
const REAL_FILE = `{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"theme": "system",
|
||||
"keybinds": {
|
||||
"leader": "ctrl+o",
|
||||
"terminal.toggle": "<leader>t",
|
||||
"session.new": "ctrl+n,<leader>n",
|
||||
"session.interrupt": "ctrl+s",
|
||||
"session.compact": "<leader>c",
|
||||
"model.list": "<leader>m",
|
||||
"agent.cycle": "tab",
|
||||
"session.undo": "<leader>u",
|
||||
"session.redo": "none",
|
||||
"session.tab.next": "ctrl+tab",
|
||||
"app.exit": "ctrl+c,ctrl+d,<leader>q"
|
||||
}
|
||||
}`
|
||||
|
||||
describe('parseTuiKeybindConfig', () => {
|
||||
it('converts the real cli.json keybinds excerpt', () => {
|
||||
const result = parseTuiKeybindConfig(REAL_FILE)
|
||||
expect(result.leaderKey).toBe('Ctrl+O')
|
||||
expect(result.shortcuts).toEqual({
|
||||
toggleTerminal: 'T',
|
||||
newSession: 'N',
|
||||
abort: 'Ctrl+S',
|
||||
compact: 'C',
|
||||
selectModel: 'M',
|
||||
toggleMode: 'Tab',
|
||||
undo: 'U',
|
||||
redo: '',
|
||||
})
|
||||
expect(result.leaderActions).toEqual(['toggleTerminal', 'newSession', 'compact', 'selectModel', 'undo'])
|
||||
expect(result.directActions).toEqual(['abort', 'toggleMode'])
|
||||
expect(result.skipped).toEqual([])
|
||||
})
|
||||
|
||||
it('parses JSONC with comments and trailing commas', () => {
|
||||
const content = `{
|
||||
// leader is ctrl+o
|
||||
"keybinds": {
|
||||
"leader": "ctrl+o",
|
||||
"session.compact": "<leader>c", // compact
|
||||
},
|
||||
}`
|
||||
const result = parseTuiKeybindConfig(content)
|
||||
expect(result.leaderKey).toBe('Ctrl+O')
|
||||
expect(result.shortcuts.compact).toBe('C')
|
||||
expect(result.leaderActions).toEqual(['compact'])
|
||||
})
|
||||
|
||||
it('reads legacy snake_case names', () => {
|
||||
const content = `{
|
||||
"keybinds": {
|
||||
"session_new": "ctrl+n",
|
||||
"messages_undo": "<leader>u",
|
||||
"sidebar_toggle": "<leader>b",
|
||||
"session_list": "<leader>l"
|
||||
}
|
||||
}`
|
||||
const result = parseTuiKeybindConfig(content)
|
||||
expect(result.shortcuts).toEqual({
|
||||
newSession: 'Ctrl+N',
|
||||
undo: 'U',
|
||||
toggleSidebar: 'B',
|
||||
sessions: 'L',
|
||||
})
|
||||
expect(result.leaderActions).toEqual(['undo', 'toggleSidebar', 'sessions'])
|
||||
expect(result.directActions).toEqual(['newSession'])
|
||||
})
|
||||
|
||||
it('prefers the dotted name over the legacy alias', () => {
|
||||
const content = `{
|
||||
"keybinds": {
|
||||
"session_new": "ctrl+n",
|
||||
"session.new": "<leader>n"
|
||||
}
|
||||
}`
|
||||
const result = parseTuiKeybindConfig(content)
|
||||
expect(result.shortcuts.newSession).toBe('N')
|
||||
expect(result.leaderActions).toEqual(['newSession'])
|
||||
expect(result.directActions).toEqual([])
|
||||
})
|
||||
|
||||
it('converts KeyStroke, binding object and array values', () => {
|
||||
const content = `{
|
||||
"keybinds": {
|
||||
"session.interrupt": { "name": "t", "ctrl": true },
|
||||
"session.compact": { "key": "ctrl+k", "preventDefault": false },
|
||||
"agent.cycle": ["ctrl+a", "<leader>z"],
|
||||
"model.list": { "name": "pageup", "meta": true }
|
||||
}
|
||||
}`
|
||||
const result = parseTuiKeybindConfig(content)
|
||||
expect(result.shortcuts).toEqual({
|
||||
abort: 'Ctrl+T',
|
||||
compact: 'Ctrl+K',
|
||||
toggleMode: 'Z',
|
||||
selectModel: 'Alt+PageUp',
|
||||
})
|
||||
expect(result.leaderActions).toEqual(['toggleMode'])
|
||||
expect(result.directActions).toEqual(['abort', 'compact', 'selectModel'])
|
||||
})
|
||||
|
||||
it('converts <leader>pageup and ctrl++', () => {
|
||||
const pageUp = parseTuiKeybindConfig('{ "keybinds": { "session.compact": "<leader>pageup" } }')
|
||||
expect(pageUp.shortcuts.compact).toBe('PageUp')
|
||||
expect(pageUp.leaderActions).toEqual(['compact'])
|
||||
|
||||
const ctrlPlus = parseTuiKeybindConfig('{ "keybinds": { "session.interrupt": "ctrl++" } }')
|
||||
expect(ctrlPlus.shortcuts.abort).toBe('Ctrl++')
|
||||
expect(ctrlPlus.directActions).toEqual(['abort'])
|
||||
})
|
||||
|
||||
it('imports prompt.clear as a direct clearPrompt binding', () => {
|
||||
const result = parseTuiKeybindConfig('{ "keybinds": { "prompt.clear": "ctrl+c" } }')
|
||||
expect(result.shortcuts.clearPrompt).toBe('Ctrl+C')
|
||||
expect(result.directActions).toEqual(['clearPrompt'])
|
||||
expect(result.leaderActions).toEqual([])
|
||||
})
|
||||
|
||||
it('imports the legacy input_clear alias as clearPrompt', () => {
|
||||
const result = parseTuiKeybindConfig('{ "keybinds": { "input_clear": "ctrl+c" } }')
|
||||
expect(result.shortcuts.clearPrompt).toBe('Ctrl+C')
|
||||
expect(result.directActions).toEqual(['clearPrompt'])
|
||||
})
|
||||
|
||||
it('records unconvertible bindings in skipped', () => {
|
||||
const result = parseTuiKeybindConfig('{ "keybinds": { "session.undo": "gg" } }')
|
||||
expect(result.shortcuts.undo).toBeUndefined()
|
||||
expect(result.leaderActions).toEqual([])
|
||||
expect(result.directActions).toEqual([])
|
||||
expect(result.skipped).toEqual([{ name: 'session.undo', reason: 'unsupported key "gg"' }])
|
||||
})
|
||||
|
||||
it('treats false and empty strings as disabled', () => {
|
||||
const result = parseTuiKeybindConfig(`{
|
||||
"keybinds": {
|
||||
"session.fork": false,
|
||||
"session.redo": ""
|
||||
}
|
||||
}`)
|
||||
expect(result.shortcuts).toEqual({ fork: '', redo: '' })
|
||||
expect(result.leaderActions).toEqual([])
|
||||
expect(result.directActions).toEqual([])
|
||||
expect(result.skipped).toEqual([])
|
||||
})
|
||||
|
||||
it('ignores unknown keys silently', () => {
|
||||
const result = parseTuiKeybindConfig('{ "keybinds": { "unknown.binding": "ctrl+x" } }')
|
||||
expect(result.shortcuts).toEqual({})
|
||||
expect(result.skipped).toEqual([])
|
||||
})
|
||||
|
||||
it('throws when the file has no keybinds', () => {
|
||||
expect(() => parseTuiKeybindConfig('{ "theme": "system" }')).toThrow('No keybinds found in this file')
|
||||
expect(() => parseTuiKeybindConfig('[]')).toThrow('No keybinds found in this file')
|
||||
expect(() => parseTuiKeybindConfig('{ "keybinds": [] }')).toThrow('No keybinds found in this file')
|
||||
})
|
||||
|
||||
it('throws a SyntaxError for invalid JSONC', () => {
|
||||
expect(() => parseTuiKeybindConfig('{ "keybinds": {')).toThrow(SyntaxError)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyTuiKeybindImport', () => {
|
||||
it('merges shortcuts and updates the direct list', () => {
|
||||
const imported: TuiKeybindImport = {
|
||||
leaderKey: 'Ctrl+O',
|
||||
shortcuts: { newSession: 'N', redo: '' },
|
||||
leaderActions: ['newSession'],
|
||||
directActions: ['abort'],
|
||||
skipped: [],
|
||||
}
|
||||
const applied = applyTuiKeybindImport(imported, {
|
||||
keyboardShortcuts: { abort: 'Escape', submit: 'Ctrl+Return', newSession: 'Ctrl+N' },
|
||||
directShortcuts: ['submit', 'abort', 'newSession'],
|
||||
})
|
||||
expect(applied.keyboardShortcuts).toEqual({
|
||||
abort: 'Escape',
|
||||
submit: 'Ctrl+Return',
|
||||
newSession: 'N',
|
||||
redo: '',
|
||||
})
|
||||
expect(applied.directShortcuts).toEqual(['submit', 'abort'])
|
||||
expect(applied.leaderKey).toBe('Ctrl+O')
|
||||
})
|
||||
|
||||
it('adds new direct actions without duplicates and omits an undefined leader', () => {
|
||||
const applied = applyTuiKeybindImport(
|
||||
{ shortcuts: {}, leaderActions: [], directActions: ['compact', 'submit'], skipped: [] },
|
||||
{ keyboardShortcuts: {}, directShortcuts: ['submit'] },
|
||||
)
|
||||
expect(applied.directShortcuts).toEqual(['submit', 'compact'])
|
||||
expect(applied.leaderKey).toBeUndefined()
|
||||
expect('leaderKey' in applied).toBe(false)
|
||||
})
|
||||
|
||||
it('unbinds a current action that conflicts with an imported binding of the same kind', () => {
|
||||
const applied = applyTuiKeybindImport(
|
||||
{ shortcuts: { toggleTerminal: 'T', abort: 'Ctrl+S' }, leaderActions: ['toggleTerminal'], directActions: ['abort'], skipped: [] },
|
||||
{
|
||||
keyboardShortcuts: { toggleMode: 'T', toggleTerminal: 'Ctrl+`', variantCycle: 't', submit: 'Ctrl+S', abort: 'Escape' },
|
||||
directShortcuts: ['submit', 'abort', 'variantCycle', 'toggleTerminal'],
|
||||
},
|
||||
)
|
||||
expect(applied.cleared).toEqual(['toggleMode', 'submit'])
|
||||
expect(applied.keyboardShortcuts).toMatchObject({ toggleMode: '', submit: '', variantCycle: 't', toggleTerminal: 'T', abort: 'Ctrl+S' })
|
||||
expect(applied.directShortcuts).toEqual(['submit', 'abort', 'variantCycle'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,288 @@
|
||||
import { isRecord } from '@opencode-manager/shared/utils'
|
||||
import type { KeyboardShortcutAction } from '@/api/types/settings'
|
||||
import { parseJsonc } from '@/lib/jsonc'
|
||||
import { normalizeShortcut } from '@/lib/keyboardShortcuts'
|
||||
|
||||
export interface TuiKeybindImport {
|
||||
leaderKey?: string
|
||||
shortcuts: Partial<Record<KeyboardShortcutAction, string>>
|
||||
leaderActions: KeyboardShortcutAction[]
|
||||
directActions: KeyboardShortcutAction[]
|
||||
skipped: Array<{ name: string; reason: string }>
|
||||
}
|
||||
|
||||
interface KeyStroke {
|
||||
name: string
|
||||
ctrl?: boolean
|
||||
shift?: boolean
|
||||
meta?: boolean
|
||||
super?: boolean
|
||||
hyper?: boolean
|
||||
}
|
||||
|
||||
type Alternative = string | KeyStroke
|
||||
|
||||
type ResolvedBinding =
|
||||
| { kind: 'disabled' }
|
||||
| { kind: 'leader'; shortcut: string }
|
||||
| { kind: 'direct'; shortcut: string }
|
||||
| { kind: 'unconvertible'; reason: string }
|
||||
|
||||
type ConvertedAlternative = { shortcut: string; leader: boolean } | { reason: string }
|
||||
|
||||
const ACTION_BY_TUI_NAME = new Map<string, KeyboardShortcutAction>([
|
||||
['session.interrupt', 'abort'],
|
||||
['prompt.clear', 'clearPrompt'],
|
||||
['agent.cycle', 'toggleMode'],
|
||||
['variant.cycle', 'variantCycle'],
|
||||
['model.cycle_favorite', 'favoriteCycle'],
|
||||
['session.undo', 'undo'],
|
||||
['session.redo', 'redo'],
|
||||
['session.compact', 'compact'],
|
||||
['session.fork', 'fork'],
|
||||
['opencode.settings', 'settings'],
|
||||
['session.list', 'sessions'],
|
||||
['session.new', 'newSession'],
|
||||
['session.tab.close', 'closeSession'],
|
||||
['session.sidebar.toggle', 'toggleSidebar'],
|
||||
['model.list', 'selectModel'],
|
||||
['terminal.toggle', 'toggleTerminal'],
|
||||
['diff.open', 'toggleSourceControl'],
|
||||
['session.timeline', 'timeline'],
|
||||
['session.export', 'exportSession'],
|
||||
['session.half.page.up', 'halfPageUp'],
|
||||
['session.half.page.down', 'halfPageDown'],
|
||||
])
|
||||
|
||||
const ACTION_BY_LEGACY_NAME = new Map<string, KeyboardShortcutAction>([
|
||||
['session_interrupt', 'abort'],
|
||||
['input_clear', 'clearPrompt'],
|
||||
['agent_cycle', 'toggleMode'],
|
||||
['variant_cycle', 'variantCycle'],
|
||||
['model_cycle_favorite', 'favoriteCycle'],
|
||||
['messages_undo', 'undo'],
|
||||
['messages_redo', 'redo'],
|
||||
['session_compact', 'compact'],
|
||||
['session_fork', 'fork'],
|
||||
['session_list', 'sessions'],
|
||||
['session_new', 'newSession'],
|
||||
['session_tab_close', 'closeSession'],
|
||||
['sidebar_toggle', 'toggleSidebar'],
|
||||
['model_list', 'selectModel'],
|
||||
['diff_open', 'toggleSourceControl'],
|
||||
['session_timeline', 'timeline'],
|
||||
['session_export', 'exportSession'],
|
||||
['messages_half_page_up', 'halfPageUp'],
|
||||
['messages_half_page_down', 'halfPageDown'],
|
||||
])
|
||||
|
||||
const MODIFIER_LABELS = new Map<string, string | null>([
|
||||
['ctrl', 'Ctrl'],
|
||||
['shift', 'Shift'],
|
||||
['meta', 'Alt'],
|
||||
['alt', 'Alt'],
|
||||
['option', 'Alt'],
|
||||
['super', 'Cmd'],
|
||||
['cmd', 'Cmd'],
|
||||
['hyper', null],
|
||||
])
|
||||
|
||||
const KEY_LABELS = new Map<string, string>([
|
||||
['return', 'Return'],
|
||||
['enter', 'Return'],
|
||||
['escape', 'Esc'],
|
||||
['esc', 'Esc'],
|
||||
['space', 'Space'],
|
||||
['tab', 'Tab'],
|
||||
['up', 'Up'],
|
||||
['down', 'Down'],
|
||||
['left', 'Left'],
|
||||
['right', 'Right'],
|
||||
['pageup', 'PageUp'],
|
||||
['pagedown', 'PageDown'],
|
||||
['home', 'Home'],
|
||||
['end', 'End'],
|
||||
['delete', 'Delete'],
|
||||
['backspace', 'Backspace'],
|
||||
['insert', 'Insert'],
|
||||
])
|
||||
|
||||
function isKeyStroke(value: unknown): value is KeyStroke {
|
||||
return isRecord(value) && typeof value.name === 'string'
|
||||
}
|
||||
|
||||
function convertKey(name: string): string | null {
|
||||
const lower = name.toLowerCase()
|
||||
const mapped = KEY_LABELS.get(lower)
|
||||
if (mapped) return mapped
|
||||
if (/^f([1-9]|1\d|2[0-4])$/.test(lower)) return `F${lower.slice(1)}`
|
||||
if (name.length === 1) return name.toUpperCase()
|
||||
return null
|
||||
}
|
||||
|
||||
function splitToken(token: string): string[] {
|
||||
const trailingPlus = token.endsWith('+')
|
||||
const body = trailingPlus ? token.slice(0, -1) : token
|
||||
const parts = body.split('+').filter((part) => part.length > 0)
|
||||
return trailingPlus ? [...parts, '+'] : parts
|
||||
}
|
||||
|
||||
function convertToken(token: string): ConvertedAlternative {
|
||||
const lower = token.trim().toLowerCase()
|
||||
if (!lower) return { reason: 'empty key' }
|
||||
const leader = lower.startsWith('<leader>')
|
||||
const body = leader ? lower.slice('<leader>'.length) : lower
|
||||
if (!body) return { reason: 'missing key after <leader>' }
|
||||
const parts = splitToken(body)
|
||||
if (parts.length === 0) return { reason: `unsupported key "${token.trim()}"` }
|
||||
const keyPart = parts[parts.length - 1]!
|
||||
const key = convertKey(keyPart)
|
||||
if (!key) return { reason: `unsupported key "${keyPart}"` }
|
||||
const modifiers: string[] = []
|
||||
for (const part of parts.slice(0, -1)) {
|
||||
const label = MODIFIER_LABELS.get(part)
|
||||
if (!label) return { reason: `unsupported modifier "${part}"` }
|
||||
modifiers.push(label)
|
||||
}
|
||||
return { shortcut: normalizeShortcut([...modifiers, key].join('+')), leader }
|
||||
}
|
||||
|
||||
function convertAlternative(alternative: Alternative): ConvertedAlternative {
|
||||
if (typeof alternative === 'string') return convertToken(alternative)
|
||||
const leader = alternative.name.startsWith('<leader>')
|
||||
const name = leader ? alternative.name.slice('<leader>'.length) : alternative.name
|
||||
if (!name) return { reason: 'missing key after <leader>' }
|
||||
if (alternative.hyper) return { reason: 'unsupported modifier "hyper"' }
|
||||
const key = convertKey(name)
|
||||
if (!key) return { reason: `unsupported key "${name}"` }
|
||||
const modifiers: string[] = []
|
||||
if (alternative.ctrl) modifiers.push('Ctrl')
|
||||
if (alternative.shift) modifiers.push('Shift')
|
||||
if (alternative.meta) modifiers.push('Alt')
|
||||
if (alternative.super) modifiers.push('Cmd')
|
||||
return { shortcut: normalizeShortcut([...modifiers, key].join('+')), leader }
|
||||
}
|
||||
|
||||
function collectAlternatives(value: unknown): Alternative[] {
|
||||
if (typeof value === 'string') {
|
||||
return value.split(',').map((part) => part.trim()).filter((part) => part.length > 0)
|
||||
}
|
||||
if (Array.isArray(value)) return value.flatMap(collectAlternatives)
|
||||
if (isKeyStroke(value)) return [value]
|
||||
if (isRecord(value) && 'key' in value) return collectAlternatives(value.key)
|
||||
return []
|
||||
}
|
||||
|
||||
function isMeaningfulAlternative(alternative: Alternative): boolean {
|
||||
return typeof alternative !== 'string' || alternative.toLowerCase() !== 'none'
|
||||
}
|
||||
|
||||
function resolveBinding(value: unknown, preferLeader: boolean): ResolvedBinding {
|
||||
if (value === false) return { kind: 'disabled' }
|
||||
if (typeof value === 'string' && (value.trim() === '' || value.trim().toLowerCase() === 'none')) {
|
||||
return { kind: 'disabled' }
|
||||
}
|
||||
const alternatives = collectAlternatives(value).filter(isMeaningfulAlternative)
|
||||
let reason: string | null = null
|
||||
let leaderShortcut: string | null = null
|
||||
let directShortcut: string | null = null
|
||||
for (const alternative of alternatives) {
|
||||
const result = convertAlternative(alternative)
|
||||
if ('reason' in result) {
|
||||
reason ??= result.reason
|
||||
continue
|
||||
}
|
||||
if (result.leader) {
|
||||
leaderShortcut ??= result.shortcut
|
||||
continue
|
||||
}
|
||||
directShortcut ??= result.shortcut
|
||||
}
|
||||
if (preferLeader && leaderShortcut !== null) return { kind: 'leader', shortcut: leaderShortcut }
|
||||
if (directShortcut !== null) return { kind: 'direct', shortcut: directShortcut }
|
||||
return { kind: 'unconvertible', reason: reason ?? 'unsupported value' }
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an OpenCode TUI keybind config (cli.json, JSONC, or legacy tui.json) into this app's shortcut preferences.
|
||||
*/
|
||||
export function parseTuiKeybindConfig(content: string): TuiKeybindImport {
|
||||
const root = parseJsonc<unknown>(content)
|
||||
if (!isRecord(root) || !isRecord(root.keybinds)) {
|
||||
throw new Error('No keybinds found in this file')
|
||||
}
|
||||
const keybinds = root.keybinds
|
||||
const shortcuts: Partial<Record<KeyboardShortcutAction, string>> = {}
|
||||
const leaderActions: KeyboardShortcutAction[] = []
|
||||
const directActions: KeyboardShortcutAction[] = []
|
||||
const skipped: Array<{ name: string; reason: string }> = []
|
||||
let leaderKey: string | undefined
|
||||
|
||||
if ('leader' in keybinds) {
|
||||
const resolved = resolveBinding(keybinds.leader, false)
|
||||
if (resolved.kind === 'disabled') {
|
||||
skipped.push({ name: 'leader', reason: 'leader key is disabled' })
|
||||
} else if (resolved.kind === 'unconvertible') {
|
||||
skipped.push({ name: 'leader', reason: resolved.reason })
|
||||
} else {
|
||||
leaderKey = resolved.shortcut
|
||||
}
|
||||
}
|
||||
|
||||
const byAction = new Map<KeyboardShortcutAction, { name: string; value: unknown; dotted: boolean }>()
|
||||
for (const [name, value] of Object.entries(keybinds)) {
|
||||
if (name === 'leader') continue
|
||||
const action = ACTION_BY_TUI_NAME.get(name) ?? ACTION_BY_LEGACY_NAME.get(name)
|
||||
if (!action) continue
|
||||
const dotted = ACTION_BY_TUI_NAME.has(name)
|
||||
const existing = byAction.get(action)
|
||||
if (!existing || (dotted && !existing.dotted)) byAction.set(action, { name, value, dotted })
|
||||
}
|
||||
|
||||
for (const [action, entry] of byAction) {
|
||||
const resolved = resolveBinding(entry.value, true)
|
||||
if (resolved.kind === 'disabled') {
|
||||
shortcuts[action] = ''
|
||||
continue
|
||||
}
|
||||
if (resolved.kind === 'unconvertible') {
|
||||
skipped.push({ name: entry.name, reason: resolved.reason })
|
||||
continue
|
||||
}
|
||||
shortcuts[action] = resolved.shortcut
|
||||
if (resolved.kind === 'leader') leaderActions.push(action)
|
||||
else directActions.push(action)
|
||||
}
|
||||
|
||||
return { leaderKey, shortcuts, leaderActions, directActions, skipped }
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges an imported TUI keybind result into the current shortcut preferences. The imported bindings win: an action the
|
||||
* file does not set is unbound (and listed in `cleared`) when it has the same key and leader/direct kind as an imported one.
|
||||
*/
|
||||
export function applyTuiKeybindImport(
|
||||
imported: TuiKeybindImport,
|
||||
current: { keyboardShortcuts: Record<string, string>; directShortcuts: string[] },
|
||||
): { keyboardShortcuts: Record<string, string>; directShortcuts: string[]; leaderKey?: string; cleared: string[] } {
|
||||
const leaderSet = new Set<string>(imported.leaderActions)
|
||||
const directShortcuts = [
|
||||
...current.directShortcuts.filter((action) => !leaderSet.has(action)),
|
||||
...imported.directActions.filter((action) => !current.directShortcuts.includes(action)),
|
||||
]
|
||||
const bindingKey = (action: string, keys: string) => `${directShortcuts.includes(action) ? 'direct' : 'leader'}:${normalizeShortcut(keys)}`
|
||||
const importedBindings = new Set(
|
||||
Object.entries(imported.shortcuts).filter(([, keys]) => Boolean(keys)).map(([action, keys]) => bindingKey(action, keys ?? '')),
|
||||
)
|
||||
const cleared = Object.entries(current.keyboardShortcuts)
|
||||
.filter(([action, keys]) => !(action in imported.shortcuts) && Boolean(keys) && importedBindings.has(bindingKey(action, keys)))
|
||||
.map(([action]) => action)
|
||||
const keyboardShortcuts = {
|
||||
...current.keyboardShortcuts,
|
||||
...Object.fromEntries(cleared.map((action) => [action, ''])),
|
||||
...imported.shortcuts,
|
||||
}
|
||||
return imported.leaderKey !== undefined
|
||||
? { keyboardShortcuts, directShortcuts, leaderKey: imported.leaderKey, cleared }
|
||||
: { keyboardShortcuts, directShortcuts, cleared }
|
||||
}
|
||||
@@ -99,19 +99,6 @@ export function GlobalSchedules() {
|
||||
selectRun(nextUnreadRun.id)
|
||||
}, [nextUnreadRun, selectRun])
|
||||
|
||||
useEffect(() => {
|
||||
if (scheduleTab !== 'runs' && runId === null) return
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'u' || event.metaKey || event.ctrlKey || event.altKey) return
|
||||
const target = event.target as HTMLElement | null
|
||||
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return
|
||||
event.preventDefault()
|
||||
handleNextUnread()
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [scheduleTab, runId, handleNextUnread])
|
||||
|
||||
const createMutation = useCreateRepoSchedule()
|
||||
const deleteMutation = useDeleteRepoSchedule()
|
||||
const runMutation = useRunRepoSchedule()
|
||||
|
||||
@@ -8,12 +8,11 @@ import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
|
||||
import { X, CornerUpLeft } from "lucide-react";
|
||||
import { SquareFill } from "@/components/ui/square-fill";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { SessionList } from "@/components/session/SessionList";
|
||||
import { getSessionListPath } from '@/lib/navigation'
|
||||
import { SessionPickerDialog } from "@/components/session/SessionPickerDialog";
|
||||
import { getSessionListPath, getSessionPath } from '@/lib/navigation'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
|
||||
import { useSession, useInterruptSession, useUpdateSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
@@ -23,7 +22,7 @@ import { useSSE } from "@/hooks/useSSE";
|
||||
import { useUIState } from "@/stores/uiStateStore";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import { useModelSelection } from "@/hooks/useModelSelection";
|
||||
import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts";
|
||||
import { useShortcutActions } from "@/contexts/KeyboardShortcutsContext";
|
||||
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
|
||||
import { useAutoScroll } from "@/hooks/useAutoScroll";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
@@ -249,7 +248,7 @@ export function SessionDetail() {
|
||||
|
||||
const messagesContentVersion = useMemo(() => getMessagesContentVersion(messages), [messages]);
|
||||
|
||||
const { scrollToBottom } = useAutoScroll({
|
||||
const { scrollToBottom, scrollByUser } = useAutoScroll({
|
||||
containerRef: messageContainerRef,
|
||||
messages,
|
||||
sessionId,
|
||||
@@ -455,34 +454,6 @@ export function SessionDetail() {
|
||||
}
|
||||
};
|
||||
|
||||
const { leaderActive } = useKeyboardShortcuts({
|
||||
openModelDialog: handleOpenModelDialog,
|
||||
openSessions: handleShowSessionsDialog,
|
||||
openSettings,
|
||||
newSession: handleNewSession,
|
||||
closeSession: handleCloseSession,
|
||||
compact: handleCompact,
|
||||
undo: handleUndo,
|
||||
redo: handleRedo,
|
||||
fork: openForkPicker,
|
||||
toggleSidebar: () => (docked ? sidePanel.toggleTool('files') : setFileBrowserOpen(!fileBrowserOpen)),
|
||||
toggleMode: () => {
|
||||
const modeButton = document.querySelector(
|
||||
"[data-toggle-mode]",
|
||||
) as HTMLButtonElement;
|
||||
modeButton?.click();
|
||||
},
|
||||
submitPrompt: () => {
|
||||
const submitButton = document.querySelector(
|
||||
"[data-submit-prompt]",
|
||||
) as HTMLButtonElement;
|
||||
submitButton?.click();
|
||||
},
|
||||
interruptSession: handleInterruptSession,
|
||||
});
|
||||
|
||||
|
||||
|
||||
const handleFileClick = useCallback((filePath: string) => {
|
||||
setSelectedFilePath(getWorkspaceFilePath(filePath, {
|
||||
directory: sessionDirectory,
|
||||
@@ -611,14 +582,41 @@ export function SessionDetail() {
|
||||
handleConnectProvider,
|
||||
]);
|
||||
|
||||
const handleUndoMessage = useCallback((restoredPrompt: string) => {
|
||||
promptInputRef.current?.setPromptValue(restoredPrompt)
|
||||
}, []);
|
||||
|
||||
const handleClearPrompt = useCallback(() => {
|
||||
promptInputRef.current?.clearPrompt()
|
||||
}, []);
|
||||
|
||||
const scrollMessagesByHalfPage = useCallback((direction: 1 | -1) => {
|
||||
const container = messageContainerRef.current;
|
||||
if (!container) return;
|
||||
scrollByUser((direction * container.clientHeight) / 2);
|
||||
}, [scrollByUser]);
|
||||
|
||||
useShortcutActions({
|
||||
selectModel: handleOpenModelDialog,
|
||||
sessions: handleShowSessionsDialog,
|
||||
newSession: handleNewSession,
|
||||
closeSession: handleCloseSession,
|
||||
compact: handleCompact,
|
||||
undo: handleUndo,
|
||||
redo: handleRedo,
|
||||
fork: openForkPicker,
|
||||
timeline: openTimelinePicker,
|
||||
exportSession: handleExportSession,
|
||||
toggleMode: () => promptInputRef.current?.cycleAgent(),
|
||||
variantCycle: () => promptInputRef.current?.cycleVariant(),
|
||||
favoriteCycle: () => promptInputRef.current?.cycleFavoriteModel(),
|
||||
submit: () => document.querySelector<HTMLButtonElement>("[data-submit-prompt]")?.click(),
|
||||
abort: isSessionActive ? handleInterruptSession : undefined,
|
||||
clearPrompt: handleClearPrompt,
|
||||
halfPageUp: () => scrollMessagesByHalfPage(-1),
|
||||
halfPageDown: () => scrollMessagesByHalfPage(1),
|
||||
});
|
||||
|
||||
const handleUndoMessage = useCallback((restoredPrompt: string) => {
|
||||
promptInputRef.current?.setPromptValue(restoredPrompt)
|
||||
}, []);
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -773,11 +771,6 @@ export function SessionDetail() {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{leaderActive && (
|
||||
<div className="absolute -top-12 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse">
|
||||
<span className="text-sm font-medium">Waiting for shortcut key...</span>
|
||||
</div>
|
||||
)}
|
||||
{minimizedForm && (
|
||||
<MinimizedFormIndicator
|
||||
form={minimizedForm}
|
||||
@@ -833,24 +826,25 @@ export function SessionDetail() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sessions Dialog */}
|
||||
<Dialog open={sessionsDialogOpen} onOpenChange={setSessionsDialogOpen}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogTitle>Sessions</DialogTitle>
|
||||
<div className="overflow-y-auto max-h-[60vh] mt-4">
|
||||
{sessionDirectory && (
|
||||
<SessionList
|
||||
directory={repoDirectory}
|
||||
activeSessionID={sessionId || undefined}
|
||||
onSelectSession={(sessionID) => {
|
||||
navigate(`/repos/${repoId}/sessions/${sessionID}${sessionRouteSuffix}`)
|
||||
setSessionsDialogOpen(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{/* Sessions Picker */}
|
||||
<SessionPickerDialog
|
||||
open={sessionsDialogOpen}
|
||||
onOpenChange={setSessionsDialogOpen}
|
||||
currentRepo={repo}
|
||||
activeSessionID={sessionId || undefined}
|
||||
onSelectSession={(session, sessionRepo) => {
|
||||
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 && (
|
||||
<SideQuestionDialog
|
||||
|
||||
@@ -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(),
|
||||
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()])
|
||||
})
|
||||
|
||||
@@ -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) }))
|
||||
|
||||
@@ -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', () => ({
|
||||
|
||||
@@ -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' })
|
||||
|
||||
@@ -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(() => <div>MockedPromptInput</div>)
|
||||
|
||||
@@ -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<string, string> = {
|
||||
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<string, string>;
|
||||
|
||||
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<string, string>,
|
||||
customCommands: [],
|
||||
customAgents: [],
|
||||
gitCredentials: [] as GitCredential[],
|
||||
|
||||
Reference in new issue
Block a user