mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix: address findings from the full Docker evaluation of main
Critical and high: - repos: unlinking a local repo removes only the Manager reference and alias, never the repository files; confirm button reads "Unlink" - auth: rate-limit by the socket address; trust proxy headers only when AUTH_TRUSTED_PROXY_HEADERS is set (documented and forwarded in compose) - composer: per-session in-memory drafts (text, bash mode, attachments); Escape no longer clears the prompt - url params: compose same-tick updates so schedule dialogs stay closed after create/delete; delete dialog names the job Medium: - tool rows show failures (non-zero shell exit, failed exploration members) - voice conversation shows the specific error and a starting state - settings: Escape in dropdowns and the shortcut recorder no longer closes the dialog; mobile deep links open the requested section; one content tree per platform - closing pushed sheets, settings, tool panels and schedule dialogs goes back in history - login returns to the requested page; signed-out pages make no authenticated requests - action terminals keep their output (Manager-side output capture and replay) - unpushed-commit detection, commit message kept on failure - binary files with unknown extensions are detected and not editable - tool panel resizes when docked and floats as a dismissible sheet when the page is too narrow - Docker image runs tini as PID 1 Low: not-found states, add-repo and branch validation errors (4xx), search-aware empty states, mobile repo sort/filter/select cues, sidebar resize affordance and collapse shortcut, mobile unread badge, preview port filtering, terminal close handling, walkthrough empty state and helper session filtering, placeholder contrast, permission labels and focus, TTS task-list sanitizing, git identity email validation, quieter git logging, hermetic worktree tests, and accessible names for icon-only controls.
This commit is contained in:
1 parent
1c22ef6ea1
commit
4ec62cd4e7
191 files changed
+6674
-696
No files matched your search
@@ -615,7 +615,7 @@ useEffect(() => {
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button variant="outline" size="sm" onClick={handleRefresh}>
|
||||
<Button variant="outline" size="sm" aria-label="Refresh files" onClick={handleRefresh}>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
</Button>
|
||||
<FileOperations
|
||||
@@ -705,7 +705,7 @@ useEffect(() => {
|
||||
<FolderOpen className="w-5 h-5" />
|
||||
File Browser
|
||||
</CardTitle>
|
||||
<Button variant="outline" size="sm" onClick={handleRefresh}>
|
||||
<Button variant="outline" size="sm" aria-label="Refresh files" onClick={handleRefresh}>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -117,6 +117,7 @@ export function FileDiffContent({
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
className="h-7 w-7 p-0 mr-1"
|
||||
aria-label="Back to file list"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
@@ -57,7 +57,7 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
|
||||
{isMobile ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<Button variant="outline" size="sm" aria-label="Upload files">
|
||||
<Upload className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
@@ -73,7 +73,7 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
<Button variant="outline" size="sm" aria-label="Upload files" onClick={() => fileInputRef.current?.click()}>
|
||||
<Upload className="w-4 h-4" />
|
||||
<span className="hidden sm:inline ml-1">Upload</span>
|
||||
</Button>
|
||||
@@ -81,7 +81,7 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
|
||||
|
||||
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<Button variant="outline" size="sm" aria-label="Create file or folder">
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
|
||||
@@ -105,6 +105,14 @@ describe('FilePreview header buttons', () => {
|
||||
expect(external).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
})
|
||||
|
||||
it('shows the binary message and no edit action for non-text files', () => {
|
||||
render(<FilePreview file={{ ...textFile('blob.bin', 'application/octet-stream'), content: btoa('\u0000\u0001\u0002') }} />)
|
||||
|
||||
expect(screen.getByText('Binary file - download to view content')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Edit file' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Download file' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the success and destructive tints on the edit actions in dark mode', () => {
|
||||
render(<FilePreview file={textFile('Dockerfile', 'text/plain')} />)
|
||||
|
||||
|
||||
@@ -426,25 +426,25 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
)}
|
||||
|
||||
{isTextFile && viewMode !== 'edit' && (
|
||||
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleEdit() }} className="h-7 w-7 p-0">
|
||||
<Button variant="outline" size="sm" aria-label="Edit file" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleEdit() }} className="h-7 w-7 p-0">
|
||||
<Edit3 className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{showSaveButton && (
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); if (shouldVirtualize) { handleVirtualizedSaveClick(); } else { handleSave(); } }} disabled={isSaving || (shouldVirtualize && !hasVirtualizedChanges)} className={SUCCESS_TINT_BUTTON_CLASS}>
|
||||
<Button variant="ghost" size="sm" aria-label="Save file" onClick={(e) => { e.stopPropagation(); e.preventDefault(); if (shouldVirtualize) { handleVirtualizedSaveClick(); } else { handleSave(); } }} disabled={isSaving || (shouldVirtualize && !hasVirtualizedChanges)} className={SUCCESS_TINT_BUTTON_CLASS}>
|
||||
<Save className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{showCancelButton && (
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleCancel() }} className={DESTRUCTIVE_TINT_BUTTON_CLASS}>
|
||||
<Button variant="ghost" size="sm" aria-label="Cancel editing" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleCancel() }} className={DESTRUCTIVE_TINT_BUTTON_CLASS}>
|
||||
<XIcon className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{viewMode !== 'edit' && (
|
||||
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleDownload() }} className="h-7 w-7 p-0">
|
||||
<Button variant="outline" size="sm" aria-label="Download file" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleDownload() }} className="h-7 w-7 p-0">
|
||||
<Download className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import { FileTree } from './FileTree'
|
||||
|
||||
const file: FileInfo = {
|
||||
name: 'notes.txt',
|
||||
path: 'docker/notes.txt',
|
||||
isDirectory: false,
|
||||
size: 5,
|
||||
mimeType: 'text/plain',
|
||||
content: '',
|
||||
lastModified: new Date('2026-07-28T09:12:40Z'),
|
||||
}
|
||||
|
||||
describe('FileTree row actions', () => {
|
||||
it('names the per-row actions trigger after the file', () => {
|
||||
render(
|
||||
<FileTree
|
||||
files={[file]}
|
||||
onFileSelect={vi.fn()}
|
||||
onDirectoryClick={vi.fn()}
|
||||
selectedFile={null}
|
||||
onDelete={vi.fn()}
|
||||
onRename={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Actions for notes.txt' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -181,7 +181,8 @@ function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, o
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={`w-6 h-6 p-0 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}
|
||||
aria-label={`Actions for ${file.name}`}
|
||||
className={`w-6 h-6 p-0 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100'}`}
|
||||
>
|
||||
<MoreVertical className="w-3 h-3" />
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
|
||||
import { ExplorationGroup } from './ExplorationGroup'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useSettings: vi.fn(),
|
||||
useToolCallPermission: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: mocks.useSettings,
|
||||
}))
|
||||
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
useToolCallPermission: mocks.useToolCallPermission,
|
||||
}))
|
||||
|
||||
const readTool = (id: string, status: 'completed' | 'running' | 'error'): SessionMessageAssistantTool => {
|
||||
if (status === 'completed') {
|
||||
return {
|
||||
type: 'tool',
|
||||
id,
|
||||
name: 'read',
|
||||
state: { status, input: { filePath: '/repo/a.ts' }, content: [], metadata: {} },
|
||||
time: { created: 0, ran: 1, completed: 2 },
|
||||
}
|
||||
}
|
||||
if (status === 'error') {
|
||||
return {
|
||||
type: 'tool',
|
||||
id,
|
||||
name: 'read',
|
||||
state: { status, input: { filePath: '/repo/missing.ts' }, error: { type: 'tool.failed', message: 'File not found' }, metadata: {} },
|
||||
time: { created: 0, ran: 1, completed: 2 },
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: 'tool',
|
||||
id,
|
||||
name: 'read',
|
||||
state: { status, input: { filePath: '/repo/a.ts' } },
|
||||
time: { created: 0, ran: 1 },
|
||||
}
|
||||
}
|
||||
|
||||
describe('ExplorationGroup', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: { expandToolCalls: false },
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
isUpdating: false,
|
||||
})
|
||||
mocks.useToolCallPermission.mockReturnValue(null)
|
||||
})
|
||||
|
||||
it('summarises a successful run and keeps the arrow marker', () => {
|
||||
render(<ExplorationGroup parts={[readTool('r1', 'completed'), readTool('r2', 'completed')]} messageID="msg_1" />)
|
||||
|
||||
const summary = screen.getByRole('button', { name: /Explored: 2 reads/ })
|
||||
expect(summary).toHaveTextContent('→')
|
||||
expect(summary).not.toHaveTextContent('✗')
|
||||
})
|
||||
|
||||
it('marks a run with a failed member and counts it in the label', () => {
|
||||
render(<ExplorationGroup parts={[readTool('r1', 'completed'), readTool('r2', 'error')]} messageID="msg_1" />)
|
||||
|
||||
const summary = screen.getByRole('button', { name: /Explored: 2 reads, 1 failed/ })
|
||||
const marker = screen.getByText('✗')
|
||||
expect(marker).toHaveClass('text-destructive')
|
||||
expect(summary).not.toHaveTextContent('→')
|
||||
})
|
||||
|
||||
it('keeps the spinner while an exploration run is still in progress', () => {
|
||||
const { container } = render(
|
||||
<ExplorationGroup parts={[readTool('r1', 'error'), readTool('r2', 'running')]} messageID="msg_1" />,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Exploring: 2 reads/ })).toBeInTheDocument()
|
||||
expect(screen.queryByText('✗')).not.toBeInTheDocument()
|
||||
expect(container.querySelector('.animate-spin')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import { ChevronRight, Loader2 } from 'lucide-react'
|
||||
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useToolCallPermission } from '@/contexts/EventContext'
|
||||
import { explorationLabel, isExplorationComplete } from '@/lib/explorationGroups'
|
||||
import { explorationFailureCount, explorationLabel, isExplorationComplete } from '@/lib/explorationGroups'
|
||||
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
|
||||
import { MessagePart } from './MessagePart'
|
||||
|
||||
@@ -31,6 +31,7 @@ export const ExplorationGroup = memo(function ExplorationGroup({ parts, ...membe
|
||||
const { preferences } = useSettings()
|
||||
const [expanded, setExpanded] = useState(preferences?.expandToolCalls ?? false)
|
||||
const completed = isExplorationComplete(parts)
|
||||
const failed = completed && explorationFailureCount(parts) > 0
|
||||
|
||||
return (
|
||||
<div className="my-1">
|
||||
@@ -40,7 +41,13 @@ export const ExplorationGroup = memo(function ExplorationGroup({ parts, ...membe
|
||||
aria-expanded={expanded}
|
||||
className="group flex w-full min-w-0 items-center gap-2 py-0.5 text-left text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{completed ? <span className="shrink-0">→</span> : <Loader2 className="w-3.5 h-3.5 shrink-0 animate-spin" />}
|
||||
{failed ? (
|
||||
<span className="shrink-0 text-destructive">✗</span>
|
||||
) : completed ? (
|
||||
<span className="shrink-0">→</span>
|
||||
) : (
|
||||
<Loader2 className="w-3.5 h-3.5 shrink-0 animate-spin" />
|
||||
)}
|
||||
<span className="truncate">{explorationLabel(parts)}</span>
|
||||
<ChevronRight className={`w-3.5 h-3.5 shrink-0 opacity-0 group-hover:opacity-100 transition-transform ${expanded ? 'rotate-90 opacity-100' : ''}`} />
|
||||
</button>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput, type PromptInputHandle } from './PromptInput'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
|
||||
import { createCommandActionsMock, stubMatchMedia, createVoiceConversationControllerMock } from '@/test/test-utils'
|
||||
|
||||
@@ -174,6 +175,7 @@ describe('PromptInput command submission', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useComposerDraftStore.setState({ drafts: {} })
|
||||
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
|
||||
mocks.runCommand.mockResolvedValue(undefined)
|
||||
mocks.switchSessionModel.mockResolvedValue(undefined)
|
||||
@@ -496,7 +498,7 @@ describe('PromptInput command submission', () => {
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears attachments and exits bash mode on Escape while idle', async () => {
|
||||
it('exits bash mode on Escape while idle and keeps the attachments', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
const input = await screen.findByPlaceholderText('Send a message...')
|
||||
@@ -510,7 +512,7 @@ describe('PromptInput command submission', () => {
|
||||
|
||||
expect(input).toHaveValue('')
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('pic.png')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('pic.png')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps attachments and clears only the text when a built-in command is submitted', async () => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor, within, act } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
|
||||
|
||||
@@ -116,6 +117,7 @@ describe('PromptInput composer layout', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useComposerDraftStore.setState({ drafts: {} })
|
||||
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
|
||||
mocks.hasPendingPermission.mockReturnValue(false)
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useSTT: vi.fn(),
|
||||
useVoiceConversation: vi.fn(),
|
||||
useMobile: vi.fn(),
|
||||
useCommands: vi.fn(),
|
||||
useCommandHandler: vi.fn(),
|
||||
useFileSearch: vi.fn(),
|
||||
useModelSelection: vi.fn(),
|
||||
useVariants: vi.fn(),
|
||||
useSessionAgent: vi.fn(),
|
||||
useUserBash: vi.fn(),
|
||||
useSessionAgentStore: vi.fn(),
|
||||
useSendErrorStore: vi.fn(),
|
||||
useHasBackgroundActivity: vi.fn(),
|
||||
useSendPrompt: vi.fn(),
|
||||
hasPendingPermission: vi.fn(() => false),
|
||||
setShowDialog: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSTT', () => ({
|
||||
useSTT: mocks.useSTT,
|
||||
useSttAvailability: () => ({ isEnabled: true, isSupported: true }),
|
||||
}))
|
||||
vi.mock('@/hooks/useVoiceConversation', () => ({ useVoiceConversation: mocks.useVoiceConversation }))
|
||||
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
|
||||
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
|
||||
vi.mock('@/hooks/useCommandHandler', () => ({ useCommandHandler: mocks.useCommandHandler }))
|
||||
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
|
||||
vi.mock('@/hooks/useModelSelection', () => ({ useModelSelection: mocks.useModelSelection }))
|
||||
vi.mock('@/hooks/useVariants', () => ({ useVariants: mocks.useVariants }))
|
||||
vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAgent }))
|
||||
vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash }))
|
||||
vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore }))
|
||||
vi.mock('@/stores/sendErrorStore', () => ({ useSendErrorStore: mocks.useSendErrorStore }))
|
||||
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
|
||||
return { ...actual, useHasBackgroundActivity: mocks.useHasBackgroundActivity }
|
||||
})
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
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/useOpenCode', () => ({
|
||||
useSendPrompt: () => ({ mutate: mocks.useSendPrompt, isPending: false }),
|
||||
useInterruptSession: () => ({ mutate: vi.fn() }),
|
||||
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useAgents: () => ({ data: [] }),
|
||||
useSkills: () => ({ data: [] }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ data: undefined }) }))
|
||||
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
usePermissions: () => ({
|
||||
hasForSession: mocks.hasPendingPermission,
|
||||
setShowDialog: mocks.setShowDialog,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/agent/AgentQuickSelect', () => ({
|
||||
AgentQuickSelect: () => <div data-testid="agent-quick-select" />,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/model/ModelQuickSelect', () => ({
|
||||
ModelQuickSelect: ({ children }: { children?: React.ReactNode }) => (
|
||||
<div data-testid="model-quick-select">{children}</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: () => null }))
|
||||
vi.mock('@/components/session/SessionSandboxMenu', () => ({ SessionSandboxMenu: () => null }))
|
||||
vi.mock('./ComposerToolsMenu', () => ({ ComposerToolsMenu: () => null }))
|
||||
vi.mock('./PromptSuggestions', () => ({ PromptSuggestions: () => null }))
|
||||
vi.mock('@/hooks/useSessionGoals', () => ({
|
||||
useSessionGoal: () => ({ data: undefined }),
|
||||
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
|
||||
}))
|
||||
vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: () => ({ data: undefined }) }))
|
||||
|
||||
const createTestQueryClient = () => new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
|
||||
const defaultProps = {
|
||||
directory: '/test',
|
||||
sessionID: 'session-a',
|
||||
showScrollButton: false,
|
||||
isSessionActive: false,
|
||||
isStreamingResponse: false,
|
||||
onScrollToBottom: vi.fn(),
|
||||
commandActions: createCommandActionsMock(),
|
||||
onPromptChange: vi.fn(),
|
||||
}
|
||||
|
||||
describe('PromptInput per-session composer draft', () => {
|
||||
const harness = (sessionID: string, overrides: Partial<typeof defaultProps> = {}) => (
|
||||
<QueryClientProvider client={createTestQueryClient()}>
|
||||
<PromptInput key={sessionID} {...defaultProps} {...overrides} sessionID={sessionID} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
const renderSession = (sessionID: string, overrides: Partial<typeof defaultProps> = {}) =>
|
||||
render(harness(sessionID, overrides))
|
||||
|
||||
const promptInput = () => screen.getByPlaceholderText(/Send a message\.\.\.|Enter bash command\.\.\./)
|
||||
|
||||
const attachImage = async (container: HTMLElement) => {
|
||||
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['img'], 'pic.png', { type: 'image/png' })] } })
|
||||
await screen.findByText('pic.png')
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useComposerDraftStore.setState({ drafts: {} })
|
||||
mocks.useSendPrompt.mockImplementation((_variables, options) => {
|
||||
options?.onSuccess?.()
|
||||
})
|
||||
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
|
||||
mocks.hasPendingPermission.mockReturnValue(false)
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
mocks.useSTT.mockReturnValue({
|
||||
isRecording: false,
|
||||
isProcessing: false,
|
||||
isSupported: false,
|
||||
isEnabled: false,
|
||||
interimTranscript: '',
|
||||
transcript: '',
|
||||
startRecording: vi.fn(),
|
||||
stopRecording: vi.fn(),
|
||||
abortRecording: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
})
|
||||
mocks.useCommands.mockReturnValue({ searchCommands: () => [], findCommand: () => undefined, recentNames: [] })
|
||||
mocks.useCommandHandler.mockReturnValue({ executeCommand: vi.fn() })
|
||||
mocks.useFileSearch.mockReturnValue({ files: [] })
|
||||
mocks.useModelSelection.mockReturnValue({
|
||||
model: null,
|
||||
modelString: 'test-model',
|
||||
setModel: vi.fn(),
|
||||
setActiveAgent: vi.fn(),
|
||||
recentModels: [],
|
||||
favoriteModels: [],
|
||||
toggleFavorite: vi.fn(),
|
||||
isModelReady: true,
|
||||
})
|
||||
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: vi.fn() })
|
||||
mocks.useSessionAgent.mockReturnValue({ agent: 'default' })
|
||||
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
|
||||
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
|
||||
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
|
||||
mocks.useHasBackgroundActivity.mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('keeps the typed draft of each session', () => {
|
||||
const { rerender } = renderSession('session-a')
|
||||
|
||||
fireEvent.change(promptInput(), { target: { value: 'draft for A' } })
|
||||
|
||||
rerender(harness('session-b'))
|
||||
expect(promptInput()).toHaveValue('')
|
||||
|
||||
fireEvent.change(promptInput(), { target: { value: 'draft for B' } })
|
||||
|
||||
rerender(harness('session-a'))
|
||||
expect(promptInput()).toHaveValue('draft for A')
|
||||
|
||||
rerender(harness('session-b'))
|
||||
expect(promptInput()).toHaveValue('draft for B')
|
||||
})
|
||||
|
||||
it('keeps bash mode and attachments of each session', async () => {
|
||||
const { container, rerender } = renderSession('session-a')
|
||||
|
||||
fireEvent.change(promptInput(), { target: { value: '!' } })
|
||||
await attachImage(container)
|
||||
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
|
||||
|
||||
rerender(harness('session-b'))
|
||||
expect(promptInput()).toHaveValue('')
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('pic.png')).not.toBeInTheDocument()
|
||||
|
||||
rerender(harness('session-a'))
|
||||
expect(promptInput()).toHaveValue('!')
|
||||
expect(screen.getByPlaceholderText('Enter bash command...')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
|
||||
expect(screen.getByText('pic.png')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('sends the restored draft to the session that owns it and clears only that draft', () => {
|
||||
const { rerender } = renderSession('session-a')
|
||||
|
||||
fireEvent.change(promptInput(), { target: { value: 'draft for A' } })
|
||||
|
||||
rerender(harness('session-b'))
|
||||
fireEvent.change(promptInput(), { target: { value: 'draft for B' } })
|
||||
|
||||
rerender(harness('session-a'))
|
||||
fireEvent.click(screen.getByTitle('Send'))
|
||||
|
||||
expect(mocks.useSendPrompt).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ sessionID: 'session-a', text: 'draft for A' }),
|
||||
expect.anything(),
|
||||
)
|
||||
expect(promptInput()).toHaveValue('')
|
||||
|
||||
rerender(harness('session-b'))
|
||||
expect(promptInput()).toHaveValue('draft for B')
|
||||
})
|
||||
|
||||
it('keeps the draft when Escape is pressed while the session is idle', () => {
|
||||
renderSession('session-a')
|
||||
|
||||
fireEvent.change(promptInput(), { target: { value: 'an important draft' } })
|
||||
fireEvent.keyDown(promptInput(), { key: 'Escape' })
|
||||
|
||||
expect(promptInput()).toHaveValue('an important draft')
|
||||
})
|
||||
|
||||
it('reports suggestion list changes instead of clearing on Escape', async () => {
|
||||
const onSuggestionsOpenChange = vi.fn()
|
||||
mocks.useCommands.mockReturnValue({
|
||||
searchCommands: () => [{ item: { name: 'alpha', description: 'Alpha' }, ranges: [] }],
|
||||
findCommand: () => undefined,
|
||||
recentNames: [],
|
||||
})
|
||||
|
||||
renderSession('session-a', { onSuggestionsOpenChange })
|
||||
expect(onSuggestionsOpenChange).toHaveBeenLastCalledWith(false)
|
||||
|
||||
fireEvent.change(promptInput(), { target: { value: '/al', selectionStart: 3 } })
|
||||
|
||||
await waitFor(() => expect(onSuggestionsOpenChange).toHaveBeenLastCalledWith(true))
|
||||
expect(promptInput()).toHaveValue('/al')
|
||||
|
||||
fireEvent.keyDown(promptInput(), { key: 'Escape' })
|
||||
|
||||
await waitFor(() => expect(onSuggestionsOpenChange).toHaveBeenLastCalledWith(false))
|
||||
expect(promptInput()).toHaveValue('/al')
|
||||
})
|
||||
|
||||
it('labels the attachment remove button with the filename', async () => {
|
||||
const { container } = renderSession('session-a')
|
||||
|
||||
await attachImage(container)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Remove pic.png' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import { createCommandActionsMock, stubMatchMedia, createVoiceConversationControllerMock } from '@/test/test-utils'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -164,6 +165,7 @@ describe('PromptInput goal mode', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useComposerDraftStore.setState({ drafts: {} })
|
||||
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
|
||||
mocks.useSessionGoal.mockReturnValue({ data: null })
|
||||
mocks.useSessionPermissionMode.mockReturnValue({ data: undefined })
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -9,7 +10,7 @@ const mocks = vi.hoisted(() => ({
|
||||
switchSessionModel: vi.fn(),
|
||||
switchSessionAgent: vi.fn(),
|
||||
runCommand: vi.fn(),
|
||||
agents: [] as Array<{ name: string; description?: string }>,
|
||||
agents: [] as Array<{ name: string; description?: string; mode?: string; hidden?: boolean }>,
|
||||
skills: [] as Array<{ id: string; name: string; description?: string }>,
|
||||
useSTT: vi.fn(),
|
||||
useVoiceConversation: vi.fn(),
|
||||
@@ -24,7 +25,7 @@ const mocks = vi.hoisted(() => ({
|
||||
useSendErrorStore: vi.fn(),
|
||||
}))
|
||||
|
||||
const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0 }))
|
||||
const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0, labels: [] as string[] }))
|
||||
|
||||
vi.mock('@/api/opencode', async () => {
|
||||
const actual = await vi.importActual('@/api/opencode')
|
||||
@@ -95,10 +96,11 @@ vi.mock('@/hooks/useSessionPermissionMode', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('./PromptSuggestions', () => ({
|
||||
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number }) => {
|
||||
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number; items: Array<{ label: string }> }) => {
|
||||
if (props.isOpen) {
|
||||
suggestionProps.isOpen = true
|
||||
suggestionProps.selectedIndex = props.selectedIndex
|
||||
suggestionProps.labels = props.items.map((item) => item.label)
|
||||
}
|
||||
return null
|
||||
},
|
||||
@@ -153,6 +155,7 @@ describe('PromptInput agent mention submission', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useComposerDraftStore.setState({ drafts: {} })
|
||||
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
|
||||
mocks.sendPrompt.mockResolvedValue({
|
||||
id: 'inbox_1',
|
||||
@@ -199,6 +202,7 @@ describe('PromptInput agent mention submission', () => {
|
||||
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
|
||||
suggestionProps.isOpen = false
|
||||
suggestionProps.selectedIndex = 0
|
||||
suggestionProps.labels = []
|
||||
})
|
||||
|
||||
it('sends an @agent mention as an attachment without switching the session agent', async () => {
|
||||
@@ -311,4 +315,23 @@ describe('PromptInput agent mention submission', () => {
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' })
|
||||
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1))
|
||||
})
|
||||
|
||||
it('offers only mentionable subagents in the @ list', async () => {
|
||||
mocks.agents = [
|
||||
{ name: 'build', description: 'Build', mode: 'primary', hidden: false },
|
||||
{ name: 'plan', description: 'Plan', mode: 'primary', hidden: false },
|
||||
{ name: 'explore', description: 'Explore', mode: 'subagent', hidden: false },
|
||||
{ name: 'general', description: 'General', mode: 'all', hidden: false },
|
||||
{ name: 'Compaction', description: 'Compaction', mode: 'primary', hidden: true },
|
||||
{ name: 'Title', description: 'Title', mode: 'primary', hidden: true },
|
||||
]
|
||||
mocks.skills = []
|
||||
renderComponent()
|
||||
|
||||
const input = await screen.findByPlaceholderText('Send a message...')
|
||||
fireEvent.change(input, { target: { value: '@', selectionStart: 1 } })
|
||||
|
||||
await waitFor(() => expect(suggestionProps.isOpen).toBe(true))
|
||||
expect(suggestionProps.labels).toEqual(['explore', 'general'])
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import {
|
||||
SessionTranscriptContext,
|
||||
type SessionTranscriptSnapshot,
|
||||
@@ -220,6 +221,7 @@ describe('PromptInput voice conversation', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useComposerDraftStore.setState({ drafts: {} })
|
||||
mocks.useSendPromptMutate.mockImplementation((_variables, options) => {
|
||||
options?.onSuccess?.()
|
||||
})
|
||||
@@ -423,6 +425,7 @@ describe('PromptInput submission', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useComposerDraftStore.setState({ drafts: {} })
|
||||
mocks.useSendPromptMutate.mockImplementation((_variables, options) => {
|
||||
options?.onSuccess?.()
|
||||
})
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useSttAvailability } from '@/hooks/useSTT'
|
||||
import { useUserBash } from '@/stores/userBashStore'
|
||||
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
|
||||
import { useSendErrorStore } from '@/stores/sendErrorStore'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import { useRecentCommandsStore } from '@/stores/recentCommandsStore'
|
||||
import { useHasBackgroundActivity } from '@/stores/sessionStatusStore'
|
||||
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
|
||||
@@ -119,6 +120,7 @@ interface PromptInputProps {
|
||||
directory?: string
|
||||
sessionID: string
|
||||
onVoiceConversationActiveChange?: (active: boolean) => void
|
||||
onSuggestionsOpenChange?: (open: boolean) => void
|
||||
showScrollButton?: boolean
|
||||
isSessionActive?: boolean
|
||||
isStreamingResponse?: boolean
|
||||
@@ -131,6 +133,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
directory,
|
||||
sessionID,
|
||||
onVoiceConversationActiveChange,
|
||||
onSuggestionsOpenChange,
|
||||
showScrollButton,
|
||||
isSessionActive = false,
|
||||
isStreamingResponse = false,
|
||||
@@ -138,13 +141,14 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
commandActions,
|
||||
onPromptChange
|
||||
}, ref) {
|
||||
const [prompt, setPrompt] = useState('')
|
||||
const [isBashMode, setIsBashMode] = useState(false)
|
||||
const [restoredDraft] = useState(() => useComposerDraftStore.getState().getDraft(sessionID))
|
||||
const [prompt, setPrompt] = useState(restoredDraft.prompt)
|
||||
const [isBashMode, setIsBashMode] = useState(restoredDraft.isBashMode)
|
||||
const [isGoalArmed, setIsGoalArmed] = useState(false)
|
||||
const [showSuggestions, setShowSuggestions] = useState(false)
|
||||
const [suggestionQuery, setSuggestionQuery] = useState('')
|
||||
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileAttachmentInfo>())
|
||||
const [imageAttachments, setImageAttachments] = useState<ImageAttachment[]>([])
|
||||
const [attachedFiles, setAttachedFiles] = useState(restoredDraft.attachedFiles)
|
||||
const [imageAttachments, setImageAttachments] = useState(restoredDraft.imageAttachments)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [isModelPickerOpen, setIsModelPickerOpen] = useState(false)
|
||||
const [showMentionSuggestions, setShowMentionSuggestions] = useState(false)
|
||||
@@ -183,6 +187,17 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
imageAttachmentsRef.current = imageAttachments
|
||||
}, [attachedFiles, imageAttachments, prompt])
|
||||
|
||||
const saveDraft = useComposerDraftStore((state) => state.saveDraft)
|
||||
const clearDraft = useComposerDraftStore((state) => state.clearDraft)
|
||||
|
||||
useEffect(() => {
|
||||
if (prompt === '' && !isBashMode && attachedFiles.size === 0 && imageAttachments.length === 0) {
|
||||
clearDraft(sessionID)
|
||||
return
|
||||
}
|
||||
saveDraft(sessionID, { prompt, isBashMode, attachedFiles, imageAttachments })
|
||||
}, [sessionID, prompt, isBashMode, attachedFiles, imageAttachments, saveDraft, clearDraft])
|
||||
|
||||
const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map<string, FileAttachmentInfo>, submittedImageAttachments: ImageAttachment[], options?: { keepAttachments?: boolean }) => {
|
||||
if (
|
||||
promptRef.current !== submittedPrompt ||
|
||||
@@ -246,6 +261,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
|
||||
const { data: agents = [] } = useAgents(directory)
|
||||
const { data: skills = [] } = useSkills(directory)
|
||||
const mentionableAgents = useMemo(
|
||||
() => agents.filter((agent) => !agent.hidden && agent.mode !== 'primary'),
|
||||
[agents],
|
||||
)
|
||||
const agentNames = useMemo(() => agents.map((agent) => agent.name), [agents])
|
||||
const skillIds = useMemo(() => skills.map((skill) => skill.id), [skills])
|
||||
const failedPrompt = useSendErrorStore((state) => state.errors[sessionID]?.failedPrompt)
|
||||
@@ -269,7 +288,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
}, [failedPrompt])
|
||||
|
||||
const mentionSuggestions = useMemo((): PromptSuggestion<MentionItem>[] => {
|
||||
const agentMatches = rankByMatch(agents, mentionQuery, {
|
||||
const agentMatches = rankByMatch(mentionableAgents, mentionQuery, {
|
||||
getName: (agent) => agent.name,
|
||||
getDescription: (agent) => agent.description,
|
||||
}).map(({ item, tier, ranges }) => ({
|
||||
@@ -321,7 +340,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
return [...agentMatches, ...skillMatches, ...fileMatches]
|
||||
.sort((a, b) => a.tier - b.tier)
|
||||
.map(({ suggestion }) => suggestion)
|
||||
}, [agents, skills, searchResults, mentionQuery])
|
||||
}, [mentionableAgents, skills, searchResults, mentionQuery])
|
||||
|
||||
const commandSuggestions = useMemo((): PromptSuggestion<CommandInfo>[] =>
|
||||
searchCommands(suggestionQuery).map(({ item, ranges }) => ({
|
||||
@@ -735,7 +754,10 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isBashMode && e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
resetPrompt()
|
||||
if (prompt === '!' || prompt === '') {
|
||||
setIsBashMode(false)
|
||||
setPrompt('')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -815,8 +837,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
textareaRef.current?.blur()
|
||||
}
|
||||
handleSubmit()
|
||||
} else if (e.key === 'Escape' && !isSessionActive) {
|
||||
resetPrompt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1063,6 +1083,12 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
})
|
||||
const isCommandListOpen = showSuggestions && commandSuggestions.length > 0
|
||||
const isMentionListOpen = showMentionSuggestions && mentionSuggestions.length > 0
|
||||
const isSuggestionListOpen = isCommandListOpen || isMentionListOpen
|
||||
|
||||
useEffect(() => {
|
||||
onSuggestionsOpenChange?.(isSuggestionListOpen)
|
||||
}, [isSuggestionListOpen, onSuggestionsOpenChange])
|
||||
|
||||
const composerMode: ComposerMode | null = isBashMode
|
||||
? 'bash'
|
||||
: isMentionListOpen
|
||||
@@ -1071,7 +1097,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
? 'command'
|
||||
: null
|
||||
const composerModeStyle = composerMode ? COMPOSER_MODE_STYLES[composerMode] : null
|
||||
const isTakeoverOpen = isMobile && (isCommandListOpen || isMentionListOpen)
|
||||
const isTakeoverOpen = isMobile && isSuggestionListOpen
|
||||
const showStopButton = isSessionActive
|
||||
const showMobileScrollButton = isMobile && showScrollButton
|
||||
const hasOpenGoal = isOpenSessionGoal(sessionGoal)
|
||||
@@ -1279,6 +1305,7 @@ return (
|
||||
<span className="max-w-[120px] truncate">{attachment.filename}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove ${attachment.filename}`}
|
||||
onClick={() => removeImageAttachment(attachment.id)}
|
||||
className="p-0.5 rounded hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { TextPart } from './TextPart'
|
||||
|
||||
describe('TextPart code blocks', () => {
|
||||
it('reserves room for the copy button so the first code line is not covered', () => {
|
||||
const { container } = render(<TextPart text={'```ts\nconst answer = 42\n```'} />)
|
||||
|
||||
const pre = container.querySelector('pre')
|
||||
expect(pre).not.toBeNull()
|
||||
expect(pre).toHaveClass('pr-10')
|
||||
expect(screen.getByTitle('Copy code')).toBeInTheDocument()
|
||||
expect(pre?.textContent).toContain('const answer = 42')
|
||||
})
|
||||
})
|
||||
@@ -167,7 +167,7 @@ function CodeBlock({ children, className, ...props }: CodeBlockProps) {
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<pre className={`bg-accent p-1 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4 ${className || ''}`} {...props}>
|
||||
<pre className={`bg-accent py-1 pl-1 pr-10 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4 ${className || ''}`} {...props}>
|
||||
{children}
|
||||
</pre>
|
||||
<CopyButton content={codeContent} title="Copy code" className="absolute top-2 right-2" />
|
||||
|
||||
@@ -292,6 +292,78 @@ describe('ToolCallPart background indicator', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ToolCallPart shell exit status', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: { expandToolCalls: false },
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
isUpdating: false,
|
||||
})
|
||||
mocks.useToolCallPermission.mockReturnValue(null)
|
||||
useUserBash.setState({ userBashCommands: new Map() })
|
||||
})
|
||||
|
||||
const completedShell = (metadata: Record<string, unknown>): SessionMessageAssistantTool => ({
|
||||
type: 'tool',
|
||||
id: 'call_exit',
|
||||
name: 'shell',
|
||||
time: { created: 1, ran: 2, completed: 3 },
|
||||
state: {
|
||||
status: 'completed',
|
||||
input: { command: 'cat does-not-exist.txt' },
|
||||
content: [{ type: 'text', text: 'Exited with code 1' }],
|
||||
metadata,
|
||||
},
|
||||
})
|
||||
|
||||
it('marks a completed shell with a non-zero exit as failed', () => {
|
||||
renderWithProviders(<ToolCallPart part={completedShell({ exit: 1 })} messageID="msg_1" />)
|
||||
|
||||
expect(screen.getByText('exit 1')).toBeInTheDocument()
|
||||
expect(screen.queryByText('completed')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('✗').parentElement).toHaveClass('text-destructive')
|
||||
})
|
||||
|
||||
it('keeps a completed shell with exit code zero successful', () => {
|
||||
renderWithProviders(<ToolCallPart part={completedShell({ exit: 0 })} messageID="msg_1" />)
|
||||
|
||||
expect(screen.getByText('completed')).toBeInTheDocument()
|
||||
expect(screen.getByText('✓').parentElement).toHaveClass('text-success')
|
||||
expect(screen.queryByText('✗')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps a completed shell without an exit code successful', () => {
|
||||
renderWithProviders(<ToolCallPart part={completedShell({})} messageID="msg_1" />)
|
||||
|
||||
expect(screen.getByText('completed')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not read an exit code from a non-shell tool', () => {
|
||||
renderWithProviders(
|
||||
<ToolCallPart
|
||||
part={{
|
||||
type: 'tool',
|
||||
id: 'call_fetch',
|
||||
name: 'webfetch',
|
||||
time: { created: 1, ran: 2, completed: 3 },
|
||||
state: {
|
||||
status: 'completed',
|
||||
input: { url: 'https://example.com' },
|
||||
content: [{ type: 'text', text: 'ok' }],
|
||||
metadata: { exit: 1 },
|
||||
},
|
||||
}}
|
||||
messageID="msg_1"
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('completed')).toBeInTheDocument()
|
||||
expect(screen.queryByText('✗')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ToolCallPart execute renderer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
@@ -121,6 +121,12 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
return typeof provider === 'string' ? provider : undefined
|
||||
})()
|
||||
const sandboxProviderLabel = sandboxProvider !== undefined && sandboxProvider !== 'ocm' ? sandboxProvider : undefined
|
||||
const foregroundShellExit =
|
||||
part.name === 'shell' && !isBackgroundShell && part.state.status === 'completed'
|
||||
? toolMetadata(part).exit
|
||||
: undefined
|
||||
const failedShellExit =
|
||||
typeof foregroundShellExit === 'number' && foregroundShellExit !== 0 ? foregroundShellExit : undefined
|
||||
const [detailsOpen, setDetailsOpen] = useToolDetailsState(preferences?.expandToolCalls ?? false)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -132,6 +138,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
|
||||
const getStatusColor = () => {
|
||||
if (isBackgroundShell) return backgroundTaskStatusColor(shellStatus)
|
||||
if (failedShellExit !== undefined) return 'text-destructive'
|
||||
switch (part.state.status) {
|
||||
case 'completed':
|
||||
return 'text-success'
|
||||
@@ -151,6 +158,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
|
||||
const getStatusIcon = () => {
|
||||
if (isBackgroundShell) return renderShellLifecycleIcon(shellStatus)
|
||||
if (failedShellExit !== undefined) return <span>✗</span>
|
||||
switch (part.state.status) {
|
||||
case 'completed':
|
||||
return <span>✓</span>
|
||||
@@ -294,7 +302,9 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
? 'awaiting permission'
|
||||
: isBackgroundShell
|
||||
? lifecycleLabel(shellStatus)
|
||||
: part.state.status
|
||||
: failedShellExit !== undefined
|
||||
? `exit ${failedShellExit}`
|
||||
: part.state.status
|
||||
const commandBlock = (
|
||||
<div className="text-sm">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
|
||||
@@ -188,6 +188,22 @@ describe('VoiceConversationBar', () => {
|
||||
expect(screen.getByRole('button', { name: 'Sending' })).toHaveAttribute('aria-busy', 'true')
|
||||
})
|
||||
|
||||
it('shows the failure reason and its fix instead of a bare retry', () => {
|
||||
renderBar(
|
||||
buildController({
|
||||
phase: 'paused',
|
||||
label: 'Microphone access denied. Please allow microphone permissions.',
|
||||
hint: 'Allow microphone access, then tap to retry',
|
||||
orbLabel: 'Resume voice conversation',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(
|
||||
screen.getByText('Microphone access denied. Please allow microphone permissions.'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText('Allow microphone access, then tap to retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the notice when there is one and keeps the reserved hint line empty', () => {
|
||||
renderBar(
|
||||
buildController({
|
||||
|
||||
@@ -74,7 +74,14 @@ export function VoiceConversationBar({
|
||||
return (
|
||||
<div className="flex flex-col gap-1 border-t border-border bg-card px-3 pt-2 pb-2">
|
||||
<div role="status" aria-live="polite" className="flex h-5 items-center gap-2">
|
||||
<span className="max-w-[50%] shrink-0 truncate text-xs font-semibold">{label}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'truncate text-xs font-semibold',
|
||||
liveTranscript ? 'max-w-[50%] shrink-0' : 'min-w-0 flex-1',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
{liveTranscript ? (
|
||||
<span
|
||||
dir="rtl"
|
||||
|
||||
@@ -593,7 +593,7 @@ export function ModelQuickSelect({
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder="Search models..."
|
||||
className="h-9 border-border bg-muted pl-9 text-sm text-foreground placeholder:text-muted-foreground"
|
||||
className="h-9 border-border bg-muted pl-9 text-sm text-foreground placeholder:text-placeholder"
|
||||
autoComplete="off"
|
||||
name="model-search"
|
||||
/>
|
||||
|
||||
@@ -16,6 +16,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { MobileTabBar } from './MobileTabBar'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
function LocationSpy() {
|
||||
@@ -27,6 +28,9 @@ describe('MobileTabBar', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
vi.mocked(useUnreadScheduleRuns).mockReturnValue(
|
||||
{ data: undefined } as unknown as ReturnType<typeof useUnreadScheduleRuns>,
|
||||
)
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
})
|
||||
|
||||
@@ -420,4 +424,43 @@ describe('MobileTabBar', () => {
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('shows the unread schedule indicator on More when the Schedules tab is replaced by Git', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(useUnreadScheduleRuns).mockReturnValue({
|
||||
data: { total: 2, runs: [] },
|
||||
} as unknown as ReturnType<typeof useUnreadScheduleRuns>)
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Schedules')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'More' }).querySelector('[data-unread-badge]')).not.toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Git' }).querySelector('[data-unread-badge]')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the unread schedule indicator on Schedules and off More when that tab is shown', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(useUnreadScheduleRuns).mockReturnValue({
|
||||
data: { total: 1, runs: [] },
|
||||
} as unknown as ReturnType<typeof useUnreadScheduleRuns>)
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Schedules' }).querySelector('[data-unread-badge]')).not.toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'More' }).querySelector('[data-unread-badge]')).toBeNull()
|
||||
})
|
||||
|
||||
})
|
||||
@@ -159,6 +159,7 @@ function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideR
|
||||
icon: Menu,
|
||||
onClick: () => open('more'),
|
||||
active: openSheet === 'more',
|
||||
badge: !showsSchedules && unreadScheduleCount > 0,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -213,7 +214,11 @@ const TabBarRow = memo(function TabBarRow({ tabs }: TabBarRowProps) {
|
||||
<div className="relative">
|
||||
<Icon className="w-5 h-5" />
|
||||
{tab.badge && (
|
||||
<span className="absolute -top-0.5 -right-1 w-2 h-2 rounded-full bg-highlight ring-2 ring-card animate-pulse" />
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-unread-badge
|
||||
className="absolute -top-0.5 -right-1 w-2 h-2 rounded-full bg-highlight ring-2 ring-card animate-pulse"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<span className="leading-none">{tab.label}</span>
|
||||
|
||||
@@ -229,7 +229,7 @@ describe('MoreDrawer', () => {
|
||||
renderMoreDrawer({ onClose: handleClose })
|
||||
fireEvent.click(screen.getByText('Settings'))
|
||||
expect(navigateMock).toHaveBeenCalledWith(
|
||||
{ search: 'settings=open&settingsTab=account' },
|
||||
{ search: 'settings=open' },
|
||||
{ replace: true },
|
||||
)
|
||||
})
|
||||
@@ -332,7 +332,10 @@ describe('MoreDrawer', () => {
|
||||
|
||||
fireEvent.click(screen.getByText('Repos'))
|
||||
|
||||
expect(navigateMock).toHaveBeenCalledWith({ search: 'mobileTab=repos' }, { replace: false })
|
||||
expect(navigateMock).toHaveBeenCalledWith(
|
||||
{ search: 'mobileTab=repos' },
|
||||
{ state: { urlParamHistory: { previousSearch: '?mobileTab=more' } } },
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps Home and hides the Repos row outside a session', () => {
|
||||
|
||||
@@ -110,7 +110,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
updateParams((p) => {
|
||||
p.delete('mobileTab')
|
||||
p.set('settings', 'open')
|
||||
p.set('settingsTab', 'account')
|
||||
p.delete('settingsTab')
|
||||
}, 'replace')
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
|
||||
import { getRepoSiblings, listRepos } from '@/api/repos'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { listProjects, type OpenCodeProject } from '@/api/opencode'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
@@ -236,6 +237,7 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
|
||||
setActivityGroups({})
|
||||
setLinkedServers([])
|
||||
stubMatchMedia(true)
|
||||
})
|
||||
|
||||
it('renders with loading state', async () => {
|
||||
@@ -246,7 +248,7 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText('Search projects...')).toBeInTheDocument()
|
||||
expect(screen.getByPlaceholderText('Search repos...')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -294,7 +296,7 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
expect(screen.getByText('repo2')).toBeInTheDocument()
|
||||
})
|
||||
const input = screen.getByPlaceholderText('Search projects...')
|
||||
const input = screen.getByPlaceholderText('Search repos...')
|
||||
fireEvent.change(input, { target: { value: 'repo1' } })
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
@@ -773,7 +775,7 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
|
||||
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
const input = await screen.findByPlaceholderText('Search projects...')
|
||||
const input = await screen.findByPlaceholderText('Search repos...')
|
||||
await waitFor(() => expect(screen.getByText('repo2')).toBeInTheDocument())
|
||||
expect(screen.queryByLabelText('Clear search')).toBeNull()
|
||||
|
||||
@@ -927,7 +929,7 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'Activity' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Search projects...'), { target: { value: 'repo' } })
|
||||
fireEvent.change(screen.getByPlaceholderText('Search repos...'), { target: { value: 'repo' } })
|
||||
|
||||
expect(screen.queryByRole('heading', { name: 'Activity' })).toBeNull()
|
||||
expect(screen.queryByText('Session s1')).toBeNull()
|
||||
@@ -1093,4 +1095,34 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
)
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves the search input unfocused on touch screens so the keyboard stays closed', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
|
||||
stubMatchMedia(false)
|
||||
|
||||
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
const input = await screen.findByPlaceholderText('Search repos...')
|
||||
expect(input).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('focuses the search input when a fine pointer is available', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
|
||||
stubMatchMedia(true)
|
||||
|
||||
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
const input = await screen.findByPlaceholderText('Search repos...')
|
||||
await waitFor(() => expect(input).toHaveFocus())
|
||||
})
|
||||
|
||||
it('uses project wording for the search placeholder when a linked server is selected', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
|
||||
vi.mocked(listProjects).mockResolvedValue([createProject('p1', 'Alpha', '/projects/alpha')])
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(await screen.findByPlaceholderText('Search projects...')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { useState, useMemo } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
|
||||
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -32,6 +33,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
const [selectedServerId] = useSidebarServerSelection()
|
||||
const isRemote = selectedServerId !== LOCAL_OPENCODE_SERVER_ID
|
||||
const activeRepoId = getActiveRepoId(location.pathname)
|
||||
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
|
||||
|
||||
const { repos, isLoading, refetch } = useNavigableRepos(isOpen)
|
||||
|
||||
@@ -76,10 +78,10 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search projects..."
|
||||
placeholder={isRemote ? 'Search projects...' : 'Search repos...'}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
autoFocus
|
||||
autoFocus={hasFinePointer}
|
||||
className="pr-9"
|
||||
autoComplete="off"
|
||||
name="repo-quick-switch"
|
||||
|
||||
@@ -36,6 +36,9 @@ vi.mock('@/components/terminal/TerminalPanel', () => ({
|
||||
TerminalWorkspace: ({ onLastTerminalExited }: { onLastTerminalExited?: () => void }) => (
|
||||
<div>
|
||||
terminal-tool
|
||||
<div className="xterm">
|
||||
<textarea aria-label="terminal input" />
|
||||
</div>
|
||||
<button type="button" onClick={onLastTerminalExited}>Exit last terminal</button>
|
||||
</div>
|
||||
),
|
||||
@@ -100,6 +103,14 @@ function search(): URLSearchParams {
|
||||
return new URLSearchParams(screen.getByTestId('search').textContent ?? '')
|
||||
}
|
||||
|
||||
function stubNarrowPage(): () => void {
|
||||
const main = document.createElement('main')
|
||||
main.getBoundingClientRect = () =>
|
||||
({ width: 560, height: 800, top: 0, left: 0, right: 560, bottom: 800, x: 0, y: 0, toJSON: () => ({}) }) as DOMRect
|
||||
document.body.append(main)
|
||||
return () => main.remove()
|
||||
}
|
||||
|
||||
const WINDOW_MINUTES = 30
|
||||
const NOW = Date.now()
|
||||
|
||||
@@ -276,6 +287,137 @@ describe('ToolSidePanel', () => {
|
||||
await waitFor(() => expect(search().has('panel')).toBe(false))
|
||||
})
|
||||
|
||||
it('renders the panel as a modal sheet over the page when docking would squeeze it', async () => {
|
||||
const removePage = stubNarrowPage()
|
||||
|
||||
try {
|
||||
renderAt('?panel=files')
|
||||
|
||||
const panel = await screen.findByRole('dialog', { name: 'Files' })
|
||||
const backdrop = screen.getByTestId('tool-panel-backdrop')
|
||||
expect(panel.className).toContain('fixed')
|
||||
expect(panel).toHaveAttribute('aria-modal', 'true')
|
||||
expect(panel).not.toHaveAttribute('style')
|
||||
expect(panel.className).toContain('z-50')
|
||||
expect(backdrop.className).toContain('z-50')
|
||||
expect(backdrop).toHaveAttribute('aria-hidden', 'true')
|
||||
expect(screen.queryByRole('separator', { name: 'Resize panel' })).not.toBeInTheDocument()
|
||||
} finally {
|
||||
removePage()
|
||||
}
|
||||
})
|
||||
|
||||
it('portals the floating overlay into the document body so page stacking contexts cannot cover it', async () => {
|
||||
const removePage = stubNarrowPage()
|
||||
|
||||
try {
|
||||
renderAt('?panel=files')
|
||||
|
||||
const panel = await screen.findByRole('dialog', { name: 'Files' })
|
||||
const backdrop = screen.getByTestId('tool-panel-backdrop')
|
||||
|
||||
expect(panel.parentElement).toBe(document.body)
|
||||
expect(backdrop.parentElement).toBe(document.body)
|
||||
expect(backdrop.className).toContain('inset-y-0')
|
||||
} finally {
|
||||
removePage()
|
||||
}
|
||||
})
|
||||
|
||||
it('moves focus into the floating panel and returns it to the rail on close', async () => {
|
||||
const user = userEvent.setup()
|
||||
const removePage = stubNarrowPage()
|
||||
|
||||
try {
|
||||
renderAt('')
|
||||
|
||||
const filesButton = screen.getByRole('button', { name: 'Files' })
|
||||
await user.click(filesButton)
|
||||
const panel = await screen.findByRole('dialog', { name: 'Files' })
|
||||
|
||||
await waitFor(() => expect(document.activeElement).toBe(panel))
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Files' })).not.toBeInTheDocument())
|
||||
await waitFor(() => expect(document.activeElement).toBe(filesButton))
|
||||
expect(search().has('panel')).toBe(false)
|
||||
} finally {
|
||||
removePage()
|
||||
}
|
||||
})
|
||||
|
||||
it('closes the floating panel on Escape and on an outside click', async () => {
|
||||
const user = userEvent.setup()
|
||||
const removePage = stubNarrowPage()
|
||||
|
||||
try {
|
||||
renderAt('?panel=files')
|
||||
|
||||
await screen.findByRole('dialog', { name: 'Files' })
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => expect(search().has('panel')).toBe(false))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Files' }))
|
||||
await screen.findByRole('dialog', { name: 'Files' })
|
||||
|
||||
await user.click(screen.getByTestId('tool-panel-backdrop'))
|
||||
await waitFor(() => expect(search().has('panel')).toBe(false))
|
||||
} finally {
|
||||
removePage()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the floating terminal open on Escape typed into the terminal', async () => {
|
||||
const user = userEvent.setup()
|
||||
const removePage = stubNarrowPage()
|
||||
|
||||
try {
|
||||
renderAt('?panel=terminal&terminal=pty-1')
|
||||
|
||||
await screen.findByRole('dialog', { name: 'Terminal' })
|
||||
const terminalInput = screen.getByLabelText('terminal input')
|
||||
await user.click(terminalInput)
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Terminal' })).toBeInTheDocument()
|
||||
expect(search().get('panel')).toBe('terminal')
|
||||
} finally {
|
||||
removePage()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a docked panel open on Escape', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderAt('?panel=files')
|
||||
|
||||
await screen.findByRole('complementary', { name: 'Files' })
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
expect(search().get('panel')).toBe('files')
|
||||
})
|
||||
|
||||
it('resizes the docked panel from the keyboard and clamps it', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderAt('?panel=files')
|
||||
|
||||
const handle = await screen.findByRole('separator', { name: 'Resize panel' })
|
||||
const panel = screen.getByRole('complementary', { name: 'Files' })
|
||||
expect(panel.parentElement).not.toBe(document.body)
|
||||
const initial = Number(handle.getAttribute('aria-valuenow'))
|
||||
|
||||
handle.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
|
||||
expect(Number(handle.getAttribute('aria-valuenow'))).toBe(initial - 16)
|
||||
expect(panel).toHaveStyle({ width: `${initial - 16}px` })
|
||||
|
||||
await user.keyboard('{Home}')
|
||||
|
||||
expect(Number(handle.getAttribute('aria-valuenow'))).toBe(320)
|
||||
expect(panel).toHaveStyle({ width: '320px' })
|
||||
})
|
||||
|
||||
it('opens non-panel session items from the rail as dialogs', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderAt('?panel=files')
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import type { ReactNode, RefObject } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { X } from 'lucide-react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { FileBrowser } from '@/components/file-browser/FileBrowser'
|
||||
@@ -32,15 +33,138 @@ import { useActiveWorkCounts, useActivityWindowMinutes } from '@/hooks/useActive
|
||||
import { formatActivityWindow } from '@/lib/activeWork'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TOOLTIP_OPEN_DELAY_MS } from '@/components/ui/tooltip'
|
||||
import { restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useToolPanelLayout, useToolPanelWidth } from '@/hooks/useToolPanelLayout'
|
||||
import { isLocalOpenCodeServer, useRouteOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
|
||||
const PANEL_WIDTH_CLASSES: Partial<Record<PanelTool, string>> = {
|
||||
activity: 'w-80',
|
||||
}
|
||||
|
||||
interface PanelResizeState {
|
||||
pointerId: number
|
||||
startX: number
|
||||
startWidth: number
|
||||
}
|
||||
|
||||
interface PanelResizeHandleProps {
|
||||
width: number
|
||||
minWidth: number
|
||||
maxWidth: number
|
||||
onWidthChange: (width: number) => void
|
||||
}
|
||||
|
||||
function PanelResizeHandle({ width, minWidth, maxWidth, onWidthChange }: PanelResizeHandleProps) {
|
||||
const dragRef = useRef<PanelResizeState | null>(null)
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0) return
|
||||
event.preventDefault()
|
||||
event.currentTarget.setPointerCapture?.(event.pointerId)
|
||||
dragRef.current = { pointerId: event.pointerId, startX: event.clientX, startWidth: width }
|
||||
},
|
||||
[width],
|
||||
)
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current
|
||||
if (!drag || drag.pointerId !== event.pointerId) return
|
||||
onWidthChange(drag.startWidth - (event.clientX - drag.startX))
|
||||
},
|
||||
[onWidthChange],
|
||||
)
|
||||
|
||||
const handlePointerEnd = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current
|
||||
if (!drag || drag.pointerId !== event.pointerId) return
|
||||
if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture?.(event.pointerId)
|
||||
}
|
||||
dragRef.current = null
|
||||
}, [])
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
const step = event.shiftKey ? 64 : 16
|
||||
let nextWidth: number
|
||||
switch (event.key) {
|
||||
case 'ArrowLeft':
|
||||
nextWidth = width + step
|
||||
break
|
||||
case 'ArrowRight':
|
||||
nextWidth = width - step
|
||||
break
|
||||
case 'Home':
|
||||
nextWidth = minWidth
|
||||
break
|
||||
case 'End':
|
||||
nextWidth = maxWidth
|
||||
break
|
||||
default:
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
onWidthChange(nextWidth)
|
||||
},
|
||||
[maxWidth, minWidth, onWidthChange, width],
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Resize panel"
|
||||
tabIndex={0}
|
||||
aria-valuenow={width}
|
||||
aria-valuemin={minWidth}
|
||||
aria-valuemax={maxWidth}
|
||||
className="absolute inset-y-0 -left-1 z-10 w-2 cursor-col-resize touch-none bg-transparent hover:bg-highlight/30 focus-visible:bg-highlight/30 focus-visible:outline-none"
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerEnd}
|
||||
onPointerCancel={handlePointerEnd}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const REMOTE_TOOL_KEYS: ReadonlySet<string> = new Set(['activity', 'mcp', 'skills', 'source-control', 'terminal'])
|
||||
|
||||
/**
|
||||
* Escape closes the floating panel, except while a nested menu is open or the terminal owns
|
||||
* the key. Focus moving into the opener is handled by `useRestoreFocusOnClose`.
|
||||
*/
|
||||
function useFloatingPanelDismiss(
|
||||
floating: boolean,
|
||||
closePanel: () => void,
|
||||
panelRef: RefObject<HTMLElement | null>,
|
||||
) {
|
||||
const closeRef = useRef(closePanel)
|
||||
closeRef.current = closePanel
|
||||
|
||||
useEffect(() => {
|
||||
if (!floating) return
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || event.defaultPrevented) return
|
||||
const target = event.target
|
||||
if (target instanceof Element) {
|
||||
if (target.closest('.xterm')) return
|
||||
if (target.closest('[role="listbox"], [role="menu"]')) return
|
||||
const dialog = target.closest('[role="dialog"]')
|
||||
if (dialog !== null && dialog !== panelRef.current) return
|
||||
}
|
||||
closeRef.current()
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||
}, [floating, panelRef])
|
||||
}
|
||||
|
||||
function ActivityWindowLabel() {
|
||||
const minutes = useActivityWindowMinutes()
|
||||
return (
|
||||
@@ -141,8 +265,10 @@ function RailButton({ item, active, onClick, indicator }: RailButtonProps) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop-only docked tool panel with its icon rail, rendered to the right of a page's content.
|
||||
* The rail lists the current route's tool items; repo- and session-scoped tools render only when their context is given.
|
||||
* Desktop-only tool panel with its icon rail, rendered to the right of a page's content. The panel
|
||||
* docks when the page has room and otherwise floats over the page as a sheet, so the content keeps
|
||||
* a usable width. The rail lists the current route's tool items; repo- and session-scoped tools
|
||||
* render only when their context is given.
|
||||
*/
|
||||
export function ToolSidePanel({
|
||||
panel,
|
||||
@@ -167,7 +293,21 @@ export function ToolSidePanel({
|
||||
const routeServerId = useRouteOpenCodeServerId()
|
||||
const isRemoteRoute = !isLocalOpenCodeServer(routeServerId)
|
||||
const railRef = useRef<HTMLElement>(null)
|
||||
const panelRef = useRef<HTMLElement>(null)
|
||||
const previousActiveToolRef = useRef(activeTool)
|
||||
const panelWidth = useToolPanelWidth()
|
||||
const { docked } = useToolPanelLayout()
|
||||
const floating = activeTool !== null && !docked
|
||||
|
||||
useRestoreFocusOnClose(floating, panelRef)
|
||||
useFloatingPanelDismiss(floating, closePanel, panelRef)
|
||||
|
||||
useEffect(() => {
|
||||
if (!floating) return
|
||||
const panelElement = panelRef.current
|
||||
if (panelElement === null || panelElement.contains(document.activeElement)) return
|
||||
panelElement.focus()
|
||||
}, [floating])
|
||||
|
||||
useEffect(() => {
|
||||
const previousTool = previousActiveToolRef.current
|
||||
@@ -247,40 +387,73 @@ export function ToolSidePanel({
|
||||
}
|
||||
}
|
||||
|
||||
const panelContent =
|
||||
const fixedWidthClass = activeTool ? PANEL_WIDTH_CLASSES[activeTool] : undefined
|
||||
|
||||
const panelBody =
|
||||
activeTool && activeLabel ? (
|
||||
<aside
|
||||
aria-label={activeLabel}
|
||||
className={cn(
|
||||
'flex shrink-0 flex-col border-l border-border bg-background',
|
||||
PANEL_WIDTH_CLASSES[activeTool] ?? 'w-[min(600px,45vw)]',
|
||||
)}
|
||||
>
|
||||
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
|
||||
<div className="flex min-w-0 flex-1 items-baseline gap-2">
|
||||
<h2 className="min-w-0 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
|
||||
{activeTool === 'activity' ? <ActivityWindowLabel /> : null}
|
||||
</div>
|
||||
{activeTool === 'walkthrough' ? (
|
||||
<>
|
||||
<ChangesWalkthroughSourcePicker />
|
||||
<ChangesWalkthroughCancel />
|
||||
<ChangesWalkthroughRegenerate />
|
||||
</>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
<>
|
||||
{docked ? null : (
|
||||
<div
|
||||
data-testid="tool-panel-backdrop"
|
||||
aria-hidden="true"
|
||||
className="fixed inset-y-0 left-0 right-11 z-50 bg-black/50 backdrop-blur-sm"
|
||||
onClick={closePanel}
|
||||
aria-label="Close panel"
|
||||
className="rounded-sm p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col">{renderTool(activeTool)}</div>
|
||||
</aside>
|
||||
/>
|
||||
)}
|
||||
<aside
|
||||
ref={panelRef}
|
||||
aria-label={activeLabel}
|
||||
role={docked ? undefined : 'dialog'}
|
||||
aria-modal={docked ? undefined : true}
|
||||
tabIndex={docked ? undefined : -1}
|
||||
className={cn(
|
||||
'flex flex-col border-l border-border bg-background outline-none',
|
||||
docked
|
||||
? 'relative shrink-0'
|
||||
: 'fixed inset-y-0 right-11 z-50 w-[min(420px,calc(100vw-2.75rem))] pt-safe pb-safe shadow-2xl',
|
||||
fixedWidthClass,
|
||||
)}
|
||||
style={docked && !fixedWidthClass ? { width: panelWidth.width } : undefined}
|
||||
>
|
||||
{docked && !fixedWidthClass ? (
|
||||
<PanelResizeHandle
|
||||
width={panelWidth.width}
|
||||
minWidth={panelWidth.minWidth}
|
||||
maxWidth={panelWidth.maxWidth}
|
||||
onWidthChange={panelWidth.setWidth}
|
||||
/>
|
||||
) : null}
|
||||
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
|
||||
<div className="flex min-w-0 flex-1 items-baseline gap-2">
|
||||
<h2 className="min-w-0 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
|
||||
{activeTool === 'activity' ? <ActivityWindowLabel /> : null}
|
||||
</div>
|
||||
{activeTool === 'walkthrough' ? (
|
||||
<>
|
||||
<ChangesWalkthroughSourcePicker />
|
||||
<ChangesWalkthroughCancel />
|
||||
<ChangesWalkthroughRegenerate />
|
||||
</>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={closePanel}
|
||||
aria-label="Close panel"
|
||||
className="rounded-sm p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col">{renderTool(activeTool)}</div>
|
||||
</aside>
|
||||
</>
|
||||
) : null
|
||||
|
||||
const panelContent =
|
||||
panelBody !== null && !docked && typeof document !== 'undefined'
|
||||
? createPortal(panelBody, document.body)
|
||||
: panelBody
|
||||
|
||||
return (
|
||||
<>
|
||||
{panelContent ? (
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useState } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { AddRepoDialog } from './AddRepoDialog'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createRepo: vi.fn(),
|
||||
discoverRepos: vi.fn(),
|
||||
listRepos: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
createRepo: mocks.createRepo,
|
||||
discoverRepos: mocks.discoverRepos,
|
||||
listRepos: mocks.listRepos,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
function Harness() {
|
||||
const [open, setOpen] = useState(true)
|
||||
const [queryClient] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }))
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<button onClick={() => setOpen(true)}>reopen</button>
|
||||
<AddRepoDialog open={open} onOpenChange={setOpen} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('AddRepoDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.listRepos.mockResolvedValue([])
|
||||
})
|
||||
|
||||
it('links each field label to its input', () => {
|
||||
render(<Harness />)
|
||||
|
||||
expect(screen.getByLabelText('Repository URL')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Directory Name')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Branch (optional)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('rejects a URL containing whitespace before submitting', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness />)
|
||||
|
||||
await user.type(screen.getByLabelText('Repository URL'), 'not a url !!')
|
||||
|
||||
expect(screen.getByText('Enter a valid repository URL without spaces.')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Add Repository' })).toBeDisabled()
|
||||
expect(mocks.createRepo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears the previous error and input when reopened', async () => {
|
||||
mocks.createRepo.mockRejectedValue(new Error('Repository not found or access denied: https://github.com/test/missing.'))
|
||||
const user = userEvent.setup()
|
||||
render(<Harness />)
|
||||
|
||||
const input = screen.getByLabelText('Repository URL')
|
||||
await user.type(input, 'test/missing')
|
||||
await user.click(screen.getByRole('button', { name: 'Add Repository' }))
|
||||
|
||||
expect(await screen.findByText('Repository not found or access denied: https://github.com/test/missing.')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }))
|
||||
await user.click(screen.getByRole('button', { name: 'reopen' }))
|
||||
|
||||
expect(screen.getByLabelText('Repository URL')).toHaveValue('')
|
||||
expect(screen.queryByText('Repository not found or access denied: https://github.com/test/missing.')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -39,6 +39,22 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const resetForm = useCallback(() => {
|
||||
setRepoUrl('')
|
||||
setLocalPath('')
|
||||
setFolderPath('')
|
||||
setDirectoryName('')
|
||||
setBranch('')
|
||||
setRepoType('remote')
|
||||
setSkipSSHVerification(false)
|
||||
directoryTouched.current = false
|
||||
}, [])
|
||||
|
||||
const repoUrlError = useMemo(() => {
|
||||
if (repoType !== 'remote' || !repoUrl.trim()) return null
|
||||
return /\s/.test(repoUrl.trim()) ? 'Enter a valid repository URL without spaces' : null
|
||||
}, [repoType, repoUrl])
|
||||
|
||||
const directoryNameError = useMemo(() => {
|
||||
if (!showDirectoryName || !directoryName) return null
|
||||
return getRepoDirectoryNameError(directoryName)
|
||||
@@ -82,14 +98,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
invalidateRepoListCaches(queryClient)
|
||||
setRepoUrl('')
|
||||
setLocalPath('')
|
||||
setFolderPath('')
|
||||
setDirectoryName('')
|
||||
setBranch('')
|
||||
setRepoType('remote')
|
||||
setSkipSSHVerification(false)
|
||||
directoryTouched.current = false
|
||||
resetForm()
|
||||
|
||||
if (result.mode === 'discover') {
|
||||
const summary = [
|
||||
@@ -118,11 +127,19 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if ((repoType === 'remote' && repoUrl) || (repoType === 'local' && localPath) || (repoType === 'folder' && folderPath)) {
|
||||
if ((repoType === 'remote' && repoUrl && !repoUrlError) || (repoType === 'local' && localPath) || (repoType === 'folder' && folderPath)) {
|
||||
mutation.mutate()
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen) {
|
||||
resetForm()
|
||||
mutation.reset()
|
||||
}
|
||||
onOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
const handleRepoUrlChange = useCallback((value: string) => {
|
||||
setRepoUrl(value)
|
||||
if (!isSSHUrl(value)) {
|
||||
@@ -140,7 +157,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent mobileFullscreen mobileSwipeToClose className="content-start gap-0 sm:max-w-[500px] sm:max-h-[80vh] sm:h-auto sm:top-[50%] sm:translate-y-[-50%] bg-card border-border">
|
||||
<DialogHeader className="px-4 sm:px-6 pt-2 sm:pt-6 pb-2 sm:pb-3 h-fit">
|
||||
<DialogTitle className="text-xl text-foreground">
|
||||
@@ -161,28 +178,34 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
|
||||
{repoType === 'remote' ? (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm text-muted-foreground">Repository URL</label>
|
||||
<label htmlFor="add-repo-url" className="text-sm text-muted-foreground">Repository URL</label>
|
||||
<Input
|
||||
id="add-repo-url"
|
||||
placeholder="owner/repo or https://github.com/user/repo.git"
|
||||
value={repoUrl}
|
||||
onChange={(e) => handleRepoUrlChange(e.target.value)}
|
||||
disabled={mutation.isPending}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
|
||||
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Full URL or shorthand format (owner/repo for GitHub)
|
||||
</p>
|
||||
{repoUrlError ? (
|
||||
<p className="text-xs text-warning">{repoUrlError}.</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Full URL or shorthand format (owner/repo for GitHub)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : repoType === 'local' ? (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm text-muted-foreground">Local Path</label>
|
||||
<label htmlFor="add-repo-local-path" className="text-sm text-muted-foreground">Local Path</label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="add-repo-local-path"
|
||||
placeholder="my-local-project OR /absolute/path/to/git-repo"
|
||||
value={localPath}
|
||||
onChange={(e) => setLocalPath(e.target.value)}
|
||||
disabled={mutation.isPending}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
|
||||
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -201,14 +224,15 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm text-muted-foreground">Folder Path</label>
|
||||
<label htmlFor="add-repo-folder-path" className="text-sm text-muted-foreground">Folder Path</label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="add-repo-folder-path"
|
||||
placeholder="/absolute/path/to/projects"
|
||||
value={folderPath}
|
||||
onChange={(e) => setFolderPath(e.target.value)}
|
||||
disabled={mutation.isPending}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
|
||||
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -229,13 +253,14 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
|
||||
{showDirectoryName && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm text-muted-foreground">Directory Name</label>
|
||||
<label htmlFor="add-repo-directory-name" className="text-sm text-muted-foreground">Directory Name</label>
|
||||
<Input
|
||||
id="add-repo-directory-name"
|
||||
placeholder="Auto-detected from URL"
|
||||
value={directoryName}
|
||||
onChange={(e) => handleDirectoryNameChange(e.target.value)}
|
||||
disabled={mutation.isPending}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
|
||||
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
|
||||
/>
|
||||
{directoryNameError ? (
|
||||
<p className="text-xs text-warning">
|
||||
@@ -259,13 +284,14 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm text-muted-foreground">Branch (optional)</label>
|
||||
<label htmlFor="add-repo-branch" className="text-sm text-muted-foreground">Branch (optional)</label>
|
||||
<Input
|
||||
id="add-repo-branch"
|
||||
placeholder="Uses default if empty"
|
||||
value={branch}
|
||||
onChange={(e) => setBranch(e.target.value)}
|
||||
disabled={mutation.isPending || repoType === 'folder'}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
|
||||
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{repoType === 'folder'
|
||||
@@ -300,7 +326,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={(!repoUrl && repoType === 'remote') || (!localPath && repoType === 'local') || (!folderPath && repoType === 'folder') || mutation.isPending || (showDirectoryName && (!!directoryNameError || !!directoryCollision))}
|
||||
disabled={(!repoUrl && repoType === 'remote') || !!repoUrlError || (!localPath && repoType === 'local') || (!folderPath && repoType === 'folder') || mutation.isPending || (showDirectoryName && (!!directoryNameError || !!directoryCollision))}
|
||||
className="w-full min-h-[48px] bg-primary hover:bg-primary-hover text-primary-foreground text-base font-medium"
|
||||
>
|
||||
{mutation.isPending ? (
|
||||
|
||||
@@ -317,6 +317,25 @@ describe('MultiRunSheet', () => {
|
||||
expect(screen.getByText('1/5 selected')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('names the missing required fields while Launch is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderSheet()
|
||||
await openNewRun(user)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Launch' })).toBeDisabled()
|
||||
expect(screen.getByText('Required: group name, prompt, at least one model')).toBeInTheDocument()
|
||||
|
||||
await user.type(screen.getByLabelText('Group name'), 'Sweep')
|
||||
|
||||
expect(screen.getByText('Required: prompt, at least one model')).toBeInTheDocument()
|
||||
|
||||
await user.type(screen.getByLabelText('Prompt'), 'go')
|
||||
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
|
||||
|
||||
expect(screen.queryByText(/^Required:/)).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Launch' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('caps model selection at five', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderSheet()
|
||||
|
||||
@@ -308,8 +308,13 @@ function NewRunForm({ target, directory, defaultBaseRef, open, onLaunched }: New
|
||||
})
|
||||
}, [])
|
||||
|
||||
const canSubmit =
|
||||
name.trim().length > 0 && prompt.trim().length > 0 && selectedModels.length > 0 && !launch.isPending
|
||||
const missingRequirements = [
|
||||
name.trim().length > 0 ? null : 'group name',
|
||||
prompt.trim().length > 0 ? null : 'prompt',
|
||||
selectedModels.length > 0 ? null : 'at least one model',
|
||||
].filter((requirement): requirement is string => requirement !== null)
|
||||
|
||||
const canSubmit = missingRequirements.length === 0 && !launch.isPending
|
||||
|
||||
const handleLaunch = () => {
|
||||
if (!canSubmit) return
|
||||
@@ -411,11 +416,22 @@ function NewRunForm({ target, directory, defaultBaseRef, open, onLaunched }: New
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button className="min-w-32" onClick={handleLaunch} disabled={!canSubmit} aria-busy={launch.isPending}>
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<Button
|
||||
className="min-w-32"
|
||||
onClick={handleLaunch}
|
||||
disabled={!canSubmit}
|
||||
aria-busy={launch.isPending}
|
||||
aria-describedby={missingRequirements.length > 0 ? 'multi-run-requirements' : undefined}
|
||||
>
|
||||
{launch.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
{launch.isPending ? 'Launching…' : 'Launch'}
|
||||
</Button>
|
||||
{missingRequirements.length > 0 ? (
|
||||
<p id="multi-run-requirements" className="text-xs text-muted-foreground">
|
||||
Required: {missingRequirements.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</SideDrawerContent>
|
||||
)
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { createUseSettingsMock } from '@/test/test-utils'
|
||||
import { RepoList } from './RepoList'
|
||||
import type { Repo } from '@/api/types'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ listRepos: vi.fn() }))
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listRepos: vi.fn(),
|
||||
useRepoActivityState: vi.fn(),
|
||||
fetchReposGitStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
listRepos: mocks.listRepos,
|
||||
@@ -13,23 +19,75 @@ vi.mock('@/api/repos', () => ({
|
||||
updateRepoOrder: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/git', () => ({
|
||||
fetchReposGitStatus: mocks.fetchReposGitStatus,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useActiveWork', () => ({
|
||||
useRepoActivityState: mocks.useRepoActivityState,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: () => createUseSettingsMock(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({ useMobile: () => true }))
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: () => false,
|
||||
useSwipeBack: () => ({
|
||||
bind: vi.fn(),
|
||||
swipeProgress: 0,
|
||||
swipeStyles: {},
|
||||
}),
|
||||
}))
|
||||
|
||||
function renderRepoList(onAddRepo: () => void) {
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom')
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
function createRepo(overrides: Partial<Repo> = {}): Repo {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'demo-app',
|
||||
localPath: 'demo-app',
|
||||
fullPath: '/workspace/repos/demo-app',
|
||||
defaultBranch: 'main',
|
||||
branch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isWorktree: false,
|
||||
isLocal: true,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function renderRepoList(onAddRepo: () => void = vi.fn()) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RepoList onAddRepo={onAddRepo} />
|
||||
<BrowserRouter>
|
||||
<RepoList onAddRepo={onAddRepo} />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
async function openRepoDeleteDialog(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.click(await screen.findByRole('button', { name: /Unlink Repository|Delete Repository/ }))
|
||||
return screen.findByRole('dialog')
|
||||
}
|
||||
|
||||
describe('RepoList', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useRepoActivityState.mockReturnValue(null)
|
||||
mocks.fetchReposGitStatus.mockResolvedValue(new Map())
|
||||
})
|
||||
|
||||
it('calls onAddRepo once from the empty state', async () => {
|
||||
mocks.listRepos.mockResolvedValue([])
|
||||
const onAddRepo = vi.fn()
|
||||
@@ -41,4 +99,50 @@ describe('RepoList', () => {
|
||||
|
||||
expect(onAddRepo).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows a search-aware empty message when nothing matches the query', async () => {
|
||||
mocks.listRepos.mockResolvedValue([createRepo()])
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderRepoList()
|
||||
|
||||
await screen.findByText('demo-app')
|
||||
await user.type(screen.getByPlaceholderText('Search repositories...'), 'zzzz-nomatch')
|
||||
|
||||
expect(await screen.findByText('No repositories found matching "zzzz-nomatch"')).toBeInTheDocument()
|
||||
expect(screen.queryByText('No recently accessed repositories')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the filter empty message when no search query is active', async () => {
|
||||
mocks.listRepos.mockResolvedValue([createRepo({ cloneStatus: 'cloning' })])
|
||||
|
||||
renderRepoList()
|
||||
|
||||
expect(await screen.findByText('No recently accessed repositories')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels the confirm button "Unlink" for a local repository', async () => {
|
||||
mocks.listRepos.mockResolvedValue([createRepo()])
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderRepoList()
|
||||
const dialog = await openRepoDeleteDialog(user)
|
||||
|
||||
expect(within(dialog).getByText('Unlink Repository')).toBeInTheDocument()
|
||||
expect(within(dialog).getByRole('button', { name: 'Unlink' })).toBeInTheDocument()
|
||||
expect(within(dialog).queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels the confirm button "Delete" for a cloned repository', async () => {
|
||||
mocks.listRepos.mockResolvedValue([
|
||||
createRepo({ id: 2, name: 'cloned', localPath: 'cloned', repoUrl: 'https://github.com/test/cloned', isLocal: false }),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderRepoList()
|
||||
const dialog = await openRepoDeleteDialog(user)
|
||||
|
||||
expect(within(dialog).getByText('Delete Repository')).toBeInTheDocument()
|
||||
expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
sortRepos,
|
||||
groupReposIntoSections,
|
||||
countAttentionItems,
|
||||
getRepoListEmptyMessage,
|
||||
type RepoFilterMode,
|
||||
type RepoSortMode,
|
||||
} from "./repo-list-state"
|
||||
@@ -181,11 +182,15 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
|
||||
if (!repos) return { hasLocalRepos: false, hasClonedRepos: false }
|
||||
const selectedRepoObjects = repos.filter(r => selectedRepos.has(r.id))
|
||||
return {
|
||||
hasLocalRepos: selectedRepoObjects.some(r => r.isLocal),
|
||||
hasClonedRepos: selectedRepoObjects.some(r => !r.isLocal),
|
||||
hasLocalRepos: selectedRepoObjects.some(r => r.isLocal && !r.isWorktree),
|
||||
hasClonedRepos: selectedRepoObjects.some(r => !r.isLocal || r.isWorktree),
|
||||
}
|
||||
}, [selectedRepos, repos])
|
||||
|
||||
const unlinkOnly = selectedRepos.size > 0
|
||||
? hasLocalRepos && !hasClonedRepos
|
||||
: Boolean(repoForDelete?.isLocal && !repoForDelete?.isWorktree)
|
||||
|
||||
const repoIds = regularRepos?.map((repo) => repo.id) || []
|
||||
|
||||
const { data: gitStatuses } = useQuery({
|
||||
@@ -430,7 +435,7 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
|
||||
<div className="text-center p-12">
|
||||
<Search className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
{sections[0]?.emptyMessage || `No repositories found${searchQuery ? ` matching "${searchQuery}"` : ''}`}
|
||||
{getRepoListEmptyMessage(sections, searchQuery)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
@@ -565,6 +570,8 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
|
||||
: "Are you sure you want to delete this repository? This will remove all local files. This action cannot be undone."
|
||||
}
|
||||
isDeleting={deleteMutation.isPending || batchDeleteMutation.isPending}
|
||||
confirmLabel={unlinkOnly ? 'Unlink' : 'Delete'}
|
||||
pendingLabel={unlinkOnly ? 'Unlinking...' : 'Deleting...'}
|
||||
>
|
||||
{selectedRepos.size === 0 && repoForDelete?.isWorktree && (
|
||||
<div>
|
||||
|
||||
@@ -67,4 +67,63 @@ describe('RepoListControls', () => {
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Add repository' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('offers the sort options in the mobile filter menu', async () => {
|
||||
mocks.mobile.current = true
|
||||
const props = baseProps()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(<RepoListControls {...props} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Filter and sort repositories' }))
|
||||
|
||||
expect(await screen.findByText('Sort by')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('menuitem', { name: 'Name' }))
|
||||
|
||||
expect(props.onSortModeChange).toHaveBeenCalledWith('name')
|
||||
})
|
||||
|
||||
it('shows the active non-default filter on mobile and clears it back to the default', async () => {
|
||||
mocks.mobile.current = true
|
||||
const props = { ...baseProps(), filterMode: 'attention' as const }
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(<RepoListControls {...props} />)
|
||||
|
||||
const chip = screen.getByRole('button', { name: 'Clear filter: Changes' })
|
||||
expect(chip).toHaveTextContent('Changes')
|
||||
|
||||
await user.click(chip)
|
||||
|
||||
expect(props.onFilterModeChange).toHaveBeenCalledWith('recent')
|
||||
})
|
||||
|
||||
it('hides the active filter chip for the default filter', () => {
|
||||
mocks.mobile.current = true
|
||||
|
||||
render(<RepoListControls {...baseProps()} />)
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Clear filter/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the selection toolbar as soon as select mode is on', () => {
|
||||
mocks.mobile.current = true
|
||||
|
||||
render(<RepoListControls {...baseProps()} selectionMode selectedCount={0} />)
|
||||
|
||||
expect(screen.getByText('0 selected')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Select All' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Done selecting repositories' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('exits select mode from the Done button', async () => {
|
||||
mocks.mobile.current = true
|
||||
const props = { ...baseProps(), selectionMode: true, selectedCount: 2 }
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(<RepoListControls {...props} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Done selecting repositories' }))
|
||||
|
||||
expect(props.onClearSelection).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
@@ -73,7 +74,10 @@ export function RepoListControls({
|
||||
|
||||
const currentSortLabel =
|
||||
SORT_OPTIONS.find((s) => s.value === sortMode)?.label ?? "Recent";
|
||||
const inSelectionMode = selectedCount > 0;
|
||||
const activeFilterLabel =
|
||||
FILTER_OPTIONS.find((option) => option.value === filterMode)?.label ?? "All";
|
||||
const showActiveFilter = isMobile && filterMode !== "recent";
|
||||
const inSelectionMode = selectionMode || selectedCount > 0;
|
||||
|
||||
const getDeleteLabel = () => {
|
||||
if (hasLocalRepos && !hasClonedRepos) {
|
||||
@@ -85,14 +89,14 @@ export function RepoListControls({
|
||||
if (inSelectionMode) {
|
||||
return (
|
||||
<div className="px-2 md:px-0">
|
||||
<div className="flex items-center gap-2 bg-accent/50 rounded-md p-2">
|
||||
<span className="text-sm font-medium text-foreground shrink-0 min-w-[80px]">
|
||||
<div className="flex items-center gap-1.5 bg-accent/50 rounded-md p-2">
|
||||
<span className="text-sm font-medium text-foreground shrink-0">
|
||||
{selectedCount} selected
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={onSelectAll}
|
||||
className="shrink-0 h-9 text-xs"
|
||||
className="shrink-0 h-8 px-2 text-xs"
|
||||
size="sm"
|
||||
>
|
||||
{allVisibleSelected ? "Unselect All" : "Select All"}
|
||||
@@ -100,7 +104,8 @@ export function RepoListControls({
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={onDelete}
|
||||
className="shrink-0 h-9 text-xs text-destructive hover:text-destructive"
|
||||
disabled={selectedCount === 0}
|
||||
className="shrink-0 h-8 px-2 text-xs text-destructive hover:text-destructive"
|
||||
size="sm"
|
||||
>
|
||||
<Trash2 className="w-3 h-3 mr-1" />
|
||||
@@ -108,11 +113,13 @@ export function RepoListControls({
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClearSelection}
|
||||
className="shrink-0 size-9 ml-auto text-destructive hover:text-destructive"
|
||||
aria-label="Done selecting repositories"
|
||||
className="shrink-0 h-8 px-2 text-xs gap-1 ml-auto"
|
||||
size="sm"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
<X className="w-3.5 h-3.5" />
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -150,7 +157,7 @@ export function RepoListControls({
|
||||
<SlidersHorizontal className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuContent align="end" className="w-52">
|
||||
<DropdownMenuCheckboxItem
|
||||
checked={selectionMode}
|
||||
onCheckedChange={(checked) =>
|
||||
@@ -160,6 +167,21 @@ export function RepoListControls({
|
||||
Select repositories
|
||||
</DropdownMenuCheckboxItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuLabel>Sort by</DropdownMenuLabel>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<DropdownMenuItem
|
||||
key={option.value}
|
||||
onClick={() => {
|
||||
onSortModeChange(option.value);
|
||||
setShowMenu(false);
|
||||
}}
|
||||
className={sortMode === option.value ? "bg-accent" : ""}
|
||||
>
|
||||
{option.label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuLabel>Filter</DropdownMenuLabel>
|
||||
{FILTER_OPTIONS.map((option) => {
|
||||
const count =
|
||||
option.value === "attention"
|
||||
@@ -214,6 +236,21 @@ export function RepoListControls({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showActiveFilter && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onFilterModeChange("recent")}
|
||||
aria-label={`Clear filter: ${activeFilterLabel}`}
|
||||
className="h-7 gap-1 rounded-full px-2.5 text-xs"
|
||||
>
|
||||
{activeFilterLabel}
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="flex items-center gap-2 overflow-x-auto pb-1 -mb-1">
|
||||
{FILTER_OPTIONS.map((option) => {
|
||||
|
||||
@@ -97,7 +97,8 @@ export function RepoRowActions({
|
||||
}
|
||||
|
||||
const canCreateWorktree = isReady && !repo.isWorktree && Boolean(repo.repoUrl)
|
||||
const deleteLabel = repo.isLocal ? 'Unlink Repository' : 'Delete Repository'
|
||||
const isUnlinkableLocalRepo = Boolean(repo.isLocal && !repo.isWorktree)
|
||||
const deleteLabel = isUnlinkableLocalRepo ? 'Unlink Repository' : 'Delete Repository'
|
||||
|
||||
const handleDownload = async (options: { includeGit?: boolean; includePaths?: string[] }) => {
|
||||
try {
|
||||
@@ -158,7 +159,7 @@ export function RepoRowActions({
|
||||
) : (
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{repo.isLocal ? 'Unlink' : 'Delete'}
|
||||
{isUnlinkableLocalRepo ? 'Unlink' : 'Delete'}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
dedupeRepos,
|
||||
filterReposBySearch,
|
||||
filterReposByMode,
|
||||
getRepoListEmptyMessage,
|
||||
sortRepos,
|
||||
groupReposIntoSections,
|
||||
countAttentionItems,
|
||||
@@ -351,6 +352,24 @@ describe('repo-list-state', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getRepoListEmptyMessage', () => {
|
||||
it('prefers a search-aware message when a query is active', () => {
|
||||
const sections = [{ title: 'Recent', repos: [], emptyMessage: 'No recently accessed repositories' }]
|
||||
|
||||
expect(getRepoListEmptyMessage(sections, 'zzzz-nomatch')).toBe('No repositories found matching "zzzz-nomatch"')
|
||||
})
|
||||
|
||||
it('falls back to the section empty message without a query', () => {
|
||||
const sections = [{ title: 'Needs Attention', repos: [], emptyMessage: 'No repositories need attention' }]
|
||||
|
||||
expect(getRepoListEmptyMessage(sections, ' ')).toBe('No repositories need attention')
|
||||
})
|
||||
|
||||
it('falls back to the generic message when no section has one', () => {
|
||||
expect(getRepoListEmptyMessage([], '')).toBe('No repositories found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('countAttentionItems', () => {
|
||||
it('should count repos with changes, ahead, or behind', () => {
|
||||
const repos = [
|
||||
|
||||
@@ -112,6 +112,14 @@ export function filterReposByMode(repos: RepoViewModel[], mode: RepoFilterMode):
|
||||
}
|
||||
}
|
||||
|
||||
export function getRepoListEmptyMessage(sections: RepoListSection[], searchQuery: string): string {
|
||||
const query = searchQuery.trim()
|
||||
if (query) {
|
||||
return `No repositories found matching "${query}"`
|
||||
}
|
||||
return sections[0]?.emptyMessage ?? 'No repositories found'
|
||||
}
|
||||
|
||||
export function sortRepos(repos: RepoViewModel[], mode: RepoSortMode, manualOrder?: number[]): RepoViewModel[] {
|
||||
switch (mode) {
|
||||
case 'recent':
|
||||
|
||||
@@ -158,10 +158,10 @@ export function GeneralTab({
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium">Enabled</p>
|
||||
<p id="schedule-enabled-label" className="text-sm font-medium">Enabled</p>
|
||||
<InfoHint text="Auto-run this job on its schedule while still allowing manual runs from the dashboard." />
|
||||
</div>
|
||||
<Switch checked={enabled} onCheckedChange={onEnabledChange} />
|
||||
<Switch checked={enabled} onCheckedChange={onEnabledChange} aria-labelledby="schedule-enabled-label" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -201,19 +201,27 @@ export function GeneralTab({
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium">Allow access outside the working directory</p>
|
||||
<p id="schedule-allow-external-label" className="text-sm font-medium">Allow access outside the working directory</p>
|
||||
<InfoHint text="When disabled, runs are confined to the worktree. Enable to allow the agent to read/write files elsewhere on the system." />
|
||||
</div>
|
||||
<Switch checked={allowExternalDirectory} onCheckedChange={onAllowExternalDirectoryChange} />
|
||||
<Switch
|
||||
checked={allowExternalDirectory}
|
||||
onCheckedChange={onAllowExternalDirectoryChange}
|
||||
aria-labelledby="schedule-allow-external-label"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium">Allow questions</p>
|
||||
<p id="schedule-allow-questions-label" className="text-sm font-medium">Allow questions</p>
|
||||
<InfoHint text="Scheduled runs are unattended. When disabled, the agent's question tool is denied so a run can never stall waiting for an answer that nobody is there to give." />
|
||||
</div>
|
||||
<Switch checked={allowQuestions} onCheckedChange={onAllowQuestionsChange} />
|
||||
<Switch
|
||||
checked={allowQuestions}
|
||||
onCheckedChange={onAllowQuestionsChange}
|
||||
aria-labelledby="schedule-allow-questions-label"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { act, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
|
||||
import type { ScheduleJobWithRepo } from '@/api/schedules'
|
||||
import { RepoSchedulesContent } from './RepoSchedulesContent'
|
||||
|
||||
function createJob(id: number, name: string): ScheduleJobWithRepo {
|
||||
return {
|
||||
id,
|
||||
repoId: 1,
|
||||
name,
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: `${name} prompt`,
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
lastRunAt: null,
|
||||
nextRunAt: null,
|
||||
repoName: 'demo',
|
||||
repoPath: '/workspace/repos/demo',
|
||||
repoUrl: '',
|
||||
serverName: null,
|
||||
lastRun: null,
|
||||
retainedWorktreeCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const store = vi.hoisted(() => ({
|
||||
jobs: [] as ScheduleJobWithRepo[],
|
||||
setJobs: null as ((jobs: ScheduleJobWithRepo[]) => void) | null,
|
||||
deleteMutate: vi.fn(),
|
||||
createMutate: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useAllSchedules: () => ({ data: store.jobs, isLoading: false }),
|
||||
useRepoSchedule: () => ({ data: undefined, isFetching: false }),
|
||||
useRepoScheduleRuns: () => ({ data: [], isLoading: false }),
|
||||
useScheduleWorktrees: () => ({ data: [] }),
|
||||
useCreateRepoSchedule: () => ({ mutate: store.createMutate, isPending: false }),
|
||||
useUpdateRepoSchedule: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useDeleteRepoSchedule: () => ({ mutate: store.deleteMutate, isPending: false }),
|
||||
useRunRepoSchedule: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useCancelRepoScheduleRun: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useClearRepoScheduleRuns: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useDeleteRepoScheduleRun: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/schedules', () => ({
|
||||
ScheduleJobsTable: ({ jobs, onDelete }: { jobs: ScheduleJob[]; onDelete: (job: ScheduleJob) => void }) => (
|
||||
<div>
|
||||
{jobs.map((job) => (
|
||||
<button key={job.id} onClick={() => onDelete(job)}>{`delete ${job.name}`}</button>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
ScheduleJobDialog: ({ open, onSubmit }: { open: boolean; onSubmit: (data: CreateScheduleJobRequest) => void }) => (
|
||||
open ? <button onClick={() => onSubmit({} as CreateScheduleJobRequest)}>submit schedule</button> : null
|
||||
),
|
||||
ScheduleListToolbar: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
|
||||
ScheduleTabMenu: () => null,
|
||||
JobDetailTab: () => null,
|
||||
RunHistoryTab: () => null,
|
||||
ScheduleRunRemovalDialog: () => null,
|
||||
}))
|
||||
|
||||
function Harness({ initialJobs }: { initialJobs: ScheduleJobWithRepo[] }) {
|
||||
const [jobs, setJobs] = useState(initialJobs)
|
||||
store.jobs = jobs
|
||||
store.setJobs = setJobs
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="search">{location.search}</span>
|
||||
<RepoSchedulesContent repoId={1} embedded={false} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function renderContent(initialJobs: ScheduleJobWithRepo[], initialEntry = '/repos/1/schedules') {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<Harness initialJobs={initialJobs} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('RepoSchedulesContent dialogs', () => {
|
||||
beforeEach(() => {
|
||||
store.jobs = []
|
||||
store.setJobs = null
|
||||
store.deleteMutate.mockReset()
|
||||
store.createMutate.mockReset()
|
||||
})
|
||||
|
||||
it('names the schedule in the delete confirmation', async () => {
|
||||
const user = userEvent.setup()
|
||||
const alpha = createJob(1, 'Alpha')
|
||||
const beta = createJob(2, 'Beta')
|
||||
store.deleteMutate.mockImplementation(() => {})
|
||||
|
||||
renderContent([alpha, beta])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'delete Beta' }))
|
||||
|
||||
const dialog = screen.getByRole('dialog')
|
||||
expect(within(dialog).getByText('Beta')).toBeInTheDocument()
|
||||
expect(within(dialog).getByText(/This will permanently delete/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes the delete dialog after deleting and keeps it closed', async () => {
|
||||
const user = userEvent.setup()
|
||||
const alpha = createJob(1, 'Alpha')
|
||||
const beta = createJob(2, 'Beta')
|
||||
store.deleteMutate.mockImplementation((_args: unknown, options: { onSuccess: () => void }) => {
|
||||
store.setJobs?.([alpha])
|
||||
options.onSuccess()
|
||||
})
|
||||
|
||||
const { rerender } = renderContent([alpha, beta], '/repos/1/schedules?jobId=2')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'delete Beta' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }))
|
||||
|
||||
expect(screen.getByTestId('search').textContent).not.toContain('scheduleDialog')
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
|
||||
rerender(
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules?jobId=2']}>
|
||||
<Harness initialJobs={[alpha, beta]} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
act(() => { store.setJobs?.([alpha]) })
|
||||
|
||||
expect(screen.getByTestId('search').textContent).not.toContain('scheduleDialog')
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('closes the New schedule dialog after creating the first schedule', async () => {
|
||||
const user = userEvent.setup()
|
||||
const created = createJob(4, 'Gamma')
|
||||
store.createMutate.mockImplementation((_args: unknown, options: { onSuccess: (job: ScheduleJob) => void }) => {
|
||||
store.setJobs?.([created])
|
||||
options.onSuccess(created)
|
||||
})
|
||||
|
||||
renderContent([], '/repos/1/schedules')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Create First Schedule' }))
|
||||
expect(screen.getByRole('button', { name: 'submit schedule' })).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'submit schedule' }))
|
||||
|
||||
expect(screen.getByTestId('search').textContent).not.toContain('scheduleDialog')
|
||||
expect(screen.getByTestId('search').textContent).toContain('jobId=4')
|
||||
expect(screen.queryByRole('button', { name: 'submit schedule' })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -101,14 +101,22 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
|
||||
[dialog, jobId, jobs],
|
||||
)
|
||||
|
||||
const deleteJob = useMemo<ScheduleJob | undefined>(
|
||||
() => (dialog === 'delete' && jobId !== null ? jobs?.find((j) => j.id === jobId) : undefined),
|
||||
[dialog, jobId, jobs],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (jobs === undefined) return
|
||||
|
||||
const dialogNeedsJob = dialog === 'edit' || dialog === 'delete'
|
||||
|
||||
if (!jobs.length) {
|
||||
if (jobId !== null || scheduleTab !== 'jobs') {
|
||||
if (jobId !== null || scheduleTab !== 'jobs' || dialogNeedsJob) {
|
||||
replaceUrlParams((p) => {
|
||||
p.delete('jobId')
|
||||
p.delete('scheduleTab')
|
||||
if (dialogNeedsJob) p.delete('scheduleDialog')
|
||||
})
|
||||
}
|
||||
return
|
||||
@@ -117,15 +125,16 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
|
||||
const stillExists = jobId !== null && jobs.some((job) => job.id === jobId)
|
||||
if (!stillExists) {
|
||||
const newId = jobs[0]?.id ?? null
|
||||
if (newId !== jobId || scheduleTab !== 'jobs') {
|
||||
if (newId !== jobId || scheduleTab !== 'jobs' || dialogNeedsJob) {
|
||||
replaceUrlParams((p) => {
|
||||
if (newId === null) p.delete('jobId')
|
||||
else p.set('jobId', String(newId))
|
||||
p.delete('scheduleTab')
|
||||
if (dialogNeedsJob) p.delete('scheduleDialog')
|
||||
})
|
||||
}
|
||||
}
|
||||
}, [jobs, jobId, scheduleTab, replaceUrlParams])
|
||||
}, [jobs, jobId, scheduleTab, dialog, replaceUrlParams])
|
||||
|
||||
useEffect(() => {
|
||||
if (runs === undefined) return
|
||||
@@ -170,7 +179,7 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
if (dialog !== 'delete' || jobId === null) {
|
||||
if (dialog !== 'delete' || jobId === null || deleteJob === undefined) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -357,6 +366,7 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
|
||||
onCancel={() => closeDialog()}
|
||||
title="Delete Schedule"
|
||||
description={DELETE_SCHEDULE_DESCRIPTION}
|
||||
itemName={deleteJob?.name}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
|
||||
|
||||
@@ -132,6 +132,50 @@ describe('ScheduleJobDialog — permission config', () => {
|
||||
expect(getAllowQuestionsSwitch()).not.toBeChecked()
|
||||
})
|
||||
|
||||
it('names each form switch after its visible label', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={vi.fn()}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'Enabled' })).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('switch', { name: 'Allow access outside the working directory' }),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Allow questions' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('names the missing required fields while Create schedule is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={vi.fn()}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Create schedule' })).toBeDisabled()
|
||||
expect(screen.getByText('Required: name, prompt')).toBeInTheDocument()
|
||||
|
||||
await user.type(screen.getByLabelText('Name'), 'Test Job')
|
||||
|
||||
expect(screen.getByText('Required: prompt')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Create schedule' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('initializes permission config from an existing job', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
|
||||
@@ -263,6 +263,13 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
((schedulePreset === 'daily' || schedulePreset === 'weekdays' || schedulePreset === 'weekly' || schedulePreset === 'monthly') && !timezone.trim()) ||
|
||||
(schedulePreset === 'weekly' && weeklyDays.length === 0)
|
||||
|
||||
const missingRequirements = [
|
||||
name.trim() ? null : 'name',
|
||||
prompt.trim() ? null : 'prompt',
|
||||
isScheduleConfigInvalid ? 'valid timing' : null,
|
||||
showRepoSelector && !job && selectedRepoId === undefined ? 'repository' : null,
|
||||
].filter((requirement): requirement is string => requirement !== null)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
@@ -368,9 +375,19 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
/>
|
||||
</Tabs>
|
||||
|
||||
<div className="mt-0 shrink-0 border-t border-border px-3 sm:px-6 py-4 flex flex-row gap-2 sm:justify-end">
|
||||
<div className="mt-0 shrink-0 border-t border-border px-3 sm:px-6 py-4 flex flex-row flex-wrap items-center gap-2 sm:justify-end">
|
||||
{missingRequirements.length > 0 ? (
|
||||
<p id="schedule-requirements" className="order-last w-full text-xs text-muted-foreground sm:order-first sm:mr-auto sm:w-auto">
|
||||
Required: {missingRequirements.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving} className="flex-1 sm:flex-none">Cancel</Button>
|
||||
<Button onClick={handleSubmit} disabled={isSaving || !name.trim() || !prompt.trim() || isScheduleConfigInvalid || (!!showRepoSelector && !job && selectedRepoId === undefined)} className="flex-1 sm:flex-none">
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={isSaving || missingRequirements.length > 0}
|
||||
aria-describedby={missingRequirements.length > 0 ? 'schedule-requirements' : undefined}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
{isSaving ? 'Saving...' : job ? 'Save changes' : 'Create schedule'}
|
||||
</Button>
|
||||
|
||||
@@ -46,7 +46,7 @@ const generatingWalkthrough: ChangeWalkthrough = {
|
||||
}
|
||||
|
||||
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
|
||||
return { walkthrough, currentDiffHash: 'hash-1', stale: false, generating: false, running: false, error: null, ...overrides }
|
||||
return { walkthrough, currentDiffHash: 'hash-1', hasChanges: true, stale: false, generating: false, running: false, error: null, ...overrides }
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
@@ -490,6 +490,37 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
expect(screen.getByRole('button', { name: 'Generate walkthrough' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('shows an upfront empty state when the session has no changes', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({ walkthrough: null, currentDiffHash: 'e3b0c44298fc1c149afbf4c8996fb924', hasChanges: false }),
|
||||
)
|
||||
renderSheet()
|
||||
|
||||
expect(await screen.findByText('No changes in this session')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the refine form until a walkthrough is published', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({
|
||||
walkthrough: {
|
||||
...walkthrough,
|
||||
status: 'failed',
|
||||
artifactPath: null,
|
||||
publishedAt: null,
|
||||
error: { message: 'The walkthrough session did not publish within 15 minutes', code: 'WALKTHROUGH_TIMEOUT' },
|
||||
},
|
||||
error: { message: 'The walkthrough session did not publish within 15 minutes', code: 'WALKTHROUGH_TIMEOUT' },
|
||||
}),
|
||||
)
|
||||
renderSheet()
|
||||
|
||||
expect(
|
||||
await screen.findByText('The walkthrough session did not publish within 15 minutes'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Refine walkthrough')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['WALKTHROUGH_NO_CHANGES', 'This session has no changes to walk through', 'This session has no changes to walk through'],
|
||||
['WALKTHROUGH_NO_CHANGES', 'The staged changes contain no changes to walk through', 'The staged changes contain no changes to walk through'],
|
||||
|
||||
@@ -49,6 +49,7 @@ function walkthroughErrorMessage(error: unknown): string {
|
||||
interface ChangesWalkthroughContextValue {
|
||||
isLoading: boolean
|
||||
walkthrough: ChangeWalkthrough | null
|
||||
hasChanges: boolean
|
||||
stale: boolean
|
||||
generating: boolean
|
||||
running: boolean
|
||||
@@ -239,6 +240,7 @@ export function ChangesWalkthroughProvider({
|
||||
const value: ChangesWalkthroughContextValue = {
|
||||
isLoading: stateQuery.isLoading,
|
||||
walkthrough,
|
||||
hasChanges: state?.hasChanges ?? true,
|
||||
stale,
|
||||
generating,
|
||||
running,
|
||||
@@ -309,6 +311,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
const {
|
||||
isLoading,
|
||||
walkthrough,
|
||||
hasChanges,
|
||||
stale,
|
||||
generating,
|
||||
running,
|
||||
@@ -325,6 +328,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
|
||||
const artifactPath = walkthrough?.artifactPath ?? null
|
||||
const published = walkthrough?.publishedAt != null && artifactPath !== null
|
||||
const noChanges = !hasChanges && !generating && !published
|
||||
const artifactUrl = artifactPath === null ? null : getFileApiUrl(artifactPath, { params: { raw: true } })
|
||||
const walkthroughSessionId = walkthrough?.walkthroughSessionId ?? null
|
||||
|
||||
@@ -346,7 +350,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
|
||||
<WalkthroughSourceInputs />
|
||||
|
||||
{error ? <p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p> : null}
|
||||
{error && !noChanges ? <p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p> : null}
|
||||
|
||||
{stale && !generating ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2">
|
||||
@@ -367,12 +371,23 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
) : null}
|
||||
|
||||
{!isLoading && !walkthrough && !generating ? (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Build an interactive walkthrough of {describeWalkthroughSource(source)}.
|
||||
</p>
|
||||
<Button onClick={generate}>Generate walkthrough</Button>
|
||||
</div>
|
||||
noChanges ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{source.kind === 'session' ? 'No changes in this session' : 'No changes to walk through'}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
A walkthrough covers changed files. Change something, then generate one.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Build an interactive walkthrough of {describeWalkthroughSource(source)}.
|
||||
</p>
|
||||
<Button onClick={generate}>Generate walkthrough</Button>
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
|
||||
{generating && !published ? (
|
||||
@@ -426,7 +441,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{walkthroughSessionId && !generating && !running ? (
|
||||
{published && walkthroughSessionId && !generating && !running ? (
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={(event) => {
|
||||
|
||||
@@ -41,7 +41,7 @@ describe('PermissionModeToggle', () => {
|
||||
mockHooks()
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Permissions: ask every time' })).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: 'Permissions: follow configured rules' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('switches to accept-everything with the directory when clicked', async () => {
|
||||
@@ -50,7 +50,7 @@ describe('PermissionModeToggle', () => {
|
||||
mockHooks({ mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: ask every time' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: follow configured rules' }))
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'auto' })
|
||||
})
|
||||
@@ -61,7 +61,7 @@ describe('PermissionModeToggle', () => {
|
||||
mockHooks({ state: { mode: 'auto' }, mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: accept everything' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: auto-accept all' }))
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
|
||||
})
|
||||
@@ -114,7 +114,7 @@ describe('PermissionModeToggle', () => {
|
||||
mockHooks({ data: { ...baseState, mode: 'auto' }, mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: accept everything' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: auto-accept all' }))
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
|
||||
})
|
||||
|
||||
@@ -123,6 +123,14 @@ describe('PermissionRequestDialog', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Open session' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('focuses the allow action instead of the optional reason field', async () => {
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
|
||||
|
||||
const allowOnce = screen.getByRole('button', { name: 'Allow Once' })
|
||||
await waitFor(() => expect(allowOnce).toHaveFocus())
|
||||
expect(screen.getByLabelText('Reason (optional)')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('replies with the selected decision for the permission request', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -51,6 +51,7 @@ export function PermissionRequestDialog({
|
||||
const [loadingAction, setLoadingAction] = useState<PermissionResponse | null>(null)
|
||||
const [rejectReason, setRejectReason] = useState('')
|
||||
const reasonInputId = useId()
|
||||
const allowOnceRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setRejectReason('')
|
||||
@@ -81,7 +82,13 @@ export function PermissionRequestDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={parentOpen ?? true} onOpenChange={onOpenChange ?? (() => {})}>
|
||||
<DialogContent className="max-w-[calc(100vw-2rem)] sm:max-w-md p-4 sm:p-6">
|
||||
<DialogContent
|
||||
className="max-w-[calc(100vw-2rem)] sm:max-w-md p-4 sm:p-6"
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
allowOnceRef.current?.focus()
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 flex-wrap">
|
||||
<span>Permission Request</span>
|
||||
@@ -215,6 +222,7 @@ export function PermissionRequestDialog({
|
||||
variant="default"
|
||||
onClick={() => handleResponse('once')}
|
||||
disabled={isLoading}
|
||||
ref={allowOnceRef}
|
||||
className={cn(
|
||||
"w-full sm:flex-1 text-sm h-9 sm:h-10",
|
||||
loadingAction === 'once' && "opacity-70"
|
||||
|
||||
@@ -58,6 +58,10 @@ vi.mock('@/hooks/useSessionPins', () => ({
|
||||
useToggleSessionPin: () => ({ mutate: togglePinMock }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useChangeWalkthrough', () => ({
|
||||
useWalkthroughHelperSessionIds: () => new Set<string>(),
|
||||
}))
|
||||
|
||||
describe('SessionList', () => {
|
||||
beforeEach(() => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
|
||||
@@ -164,7 +164,7 @@ export function AccountSettings() {
|
||||
<CardTitle className="text-base sm:text-lg">Profile</CardTitle>
|
||||
</div>
|
||||
{!editingProfile && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} className="h-8">
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} aria-label="Edit profile" className="h-8">
|
||||
<Edit2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -229,6 +229,24 @@ describe('GitSettings draft preservation', () => {
|
||||
await waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['repoGitIdentity'] }))
|
||||
})
|
||||
|
||||
it('blocks saving and shows an inline error for an invalid identity email', async () => {
|
||||
const user = userEvent.setup()
|
||||
setupServer(buildPreferences())
|
||||
renderGitSettings()
|
||||
|
||||
const emailInput = await screen.findByLabelText('Email', { selector: 'input#git-email' })
|
||||
await user.type(emailInput, 'not-an-email')
|
||||
|
||||
expect(emailInput).toHaveAttribute('aria-invalid', 'true')
|
||||
expect(screen.getByText('Enter a valid email address')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /save changes/i }))
|
||||
|
||||
expect(updateSettingsMock).not.toHaveBeenCalled()
|
||||
expect(showToastMock.success).not.toHaveBeenCalled()
|
||||
expect(emailInput).toHaveValue('not-an-email')
|
||||
})
|
||||
|
||||
it('retains identity drafts when saving fails', async () => {
|
||||
const user = userEvent.setup()
|
||||
setupServer(buildPreferences())
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { randomId } from '@/lib/utils'
|
||||
import type { GitCredential, GitIdentity, GitIdentityProfile, UserPreferences } from '@/api/types/settings'
|
||||
import { isValidGitIdentityEmail } from '@opencode-manager/shared'
|
||||
import { listRepos, updateRepoGitCredential } from '@/api/repos'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
|
||||
@@ -191,6 +192,9 @@ export function GitSettings() {
|
||||
}
|
||||
|
||||
const saveAll = async () => {
|
||||
if (![gitIdentity, ...gitIdentities].every((identity) => isValidGitIdentityEmail(identity.email))) {
|
||||
return
|
||||
}
|
||||
setIsSaving(true)
|
||||
try {
|
||||
showToast.loading('Saving git configuration...', { id: 'git-config' })
|
||||
@@ -265,7 +269,7 @@ export function GitSettings() {
|
||||
value={gitIdentity.name}
|
||||
onChange={(e) => updateIdentity('name', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
className="bg-background border-border text-foreground placeholder:text-placeholder"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
@@ -277,8 +281,13 @@ export function GitSettings() {
|
||||
value={gitIdentity.email}
|
||||
onChange={(e) => updateIdentity('email', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
aria-invalid={!isValidGitIdentityEmail(gitIdentity.email)}
|
||||
aria-describedby={!isValidGitIdentityEmail(gitIdentity.email) ? 'git-email-error' : undefined}
|
||||
className="bg-background border-border text-foreground placeholder:text-placeholder"
|
||||
/>
|
||||
{!isValidGitIdentityEmail(gitIdentity.email) && (
|
||||
<p id="git-email-error" className="text-xs text-destructive">Enter a valid email address</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -439,7 +448,7 @@ export function GitSettings() {
|
||||
value={identity.name}
|
||||
onChange={(e) => updateSavedIdentity(index, 'name', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
className="bg-background border-border text-foreground placeholder:text-placeholder"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
@@ -451,8 +460,13 @@ export function GitSettings() {
|
||||
value={identity.email}
|
||||
onChange={(e) => updateSavedIdentity(index, 'email', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
aria-invalid={!isValidGitIdentityEmail(identity.email)}
|
||||
aria-describedby={!isValidGitIdentityEmail(identity.email) ? `git-identity-${index}-email-error` : undefined}
|
||||
className="bg-background border-border text-foreground placeholder:text-placeholder"
|
||||
/>
|
||||
{!isValidGitIdentityEmail(identity.email) && (
|
||||
<p id={`git-identity-${index}-email-error`} className="text-xs text-destructive">Enter a valid email address</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, within, waitFor } from '@testing-library/react'
|
||||
import { KeyboardShortcuts } from './KeyboardShortcuts'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
|
||||
|
||||
const { updateSettings, parseTuiKeybindConfig, applyTuiKeybindImport, showToast } = vi.hoisted(() => ({
|
||||
@@ -18,7 +19,10 @@ const { updateSettings, parseTuiKeybindConfig, applyTuiKeybindImport, showToast
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({ useMobile: () => false }))
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: () => false,
|
||||
useSwipeBack: () => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} }),
|
||||
}))
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: () => ({
|
||||
preferences: { keyboardShortcuts: { customAction: 'Alt+J' } },
|
||||
@@ -26,7 +30,10 @@ vi.mock('@/hooks/useSettings', () => ({
|
||||
updateSettings,
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/lib/tuiKeybindImport', () => ({ parseTuiKeybindConfig, applyTuiKeybindImport }))
|
||||
vi.mock('@/lib/tuiKeybindImport', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/tuiKeybindImport')>('@/lib/tuiKeybindImport')
|
||||
return { parseTuiKeybindConfig, applyTuiKeybindImport, applyRecordedShortcut: actual.applyRecordedShortcut }
|
||||
})
|
||||
vi.mock('@/lib/toast', () => ({ showToast }))
|
||||
|
||||
const getFileInput = (container: HTMLElement) => {
|
||||
@@ -95,6 +102,69 @@ describe('KeyboardShortcuts layout', () => {
|
||||
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: '' }) })
|
||||
expect(within(row).getByRole('button', { name: 'Not set' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('cancels recording on Escape without saving a binding', () => {
|
||||
render(<KeyboardShortcuts />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Alt\+J/ }))
|
||||
const input = screen.getByPlaceholderText('Press keys...')
|
||||
|
||||
expect(fireEvent.keyDown(input, { key: 'Escape' })).toBe(false)
|
||||
|
||||
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels recording a leader key on Escape without binding Escape as the leader', () => {
|
||||
render(<KeyboardShortcuts />)
|
||||
fireEvent.click(screen.getByRole('button', { name: DEFAULT_LEADER_KEY }))
|
||||
const input = screen.getByPlaceholderText('Press keys...')
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
|
||||
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps an open Radix dialog open when Escape cancels recording', () => {
|
||||
const onOpenChange = vi.fn()
|
||||
render(
|
||||
<Dialog open onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogTitle>Settings</DialogTitle>
|
||||
<KeyboardShortcuts />
|
||||
</DialogContent>
|
||||
</Dialog>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Alt\+J/ }))
|
||||
fireEvent.keyDown(screen.getByPlaceholderText('Press keys...'), { key: 'Escape' })
|
||||
|
||||
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
expect(onOpenChange).not.toHaveBeenCalledWith(false)
|
||||
})
|
||||
|
||||
it('unbinds the action already using the recorded binding and names it in a toast', () => {
|
||||
render(<KeyboardShortcuts />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Alt\+J/ }))
|
||||
fireEvent.keyDown(screen.getByPlaceholderText('Press keys...'), { key: 't', ctrlKey: true })
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith({
|
||||
keyboardShortcuts: expect.objectContaining({ customAction: 'Ctrl+T', variantCycle: '' }),
|
||||
directShortcuts: [...DEFAULT_DIRECT_SHORTCUTS, 'customAction'],
|
||||
})
|
||||
expect(showToast.info).toHaveBeenCalledWith('Shortcut conflict resolved', {
|
||||
description: 'Unbound to avoid conflicts: variant cycle',
|
||||
})
|
||||
})
|
||||
|
||||
it('resets custom shortcuts and the leader key to the defaults', () => {
|
||||
render(<KeyboardShortcuts />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Reset to defaults' }))
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: {}, directShortcuts: [], leaderKey: '' })
|
||||
expect(showToast.success).toHaveBeenCalledWith('Keyboard shortcuts reset to defaults')
|
||||
})
|
||||
})
|
||||
|
||||
describe('KeyboardShortcuts TUI import', () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useMobile } from '@/hooks/useMobile'
|
||||
import { Loader2, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { formatEventModifiers, formatShortcutEvent, formatShortcutLabel, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
|
||||
import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
|
||||
import { applyRecordedShortcut, applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown', 'speakVisible']
|
||||
@@ -180,6 +180,14 @@ export function KeyboardShortcuts() {
|
||||
})
|
||||
}, [])
|
||||
|
||||
const resetShortcuts = () => {
|
||||
stopRecording()
|
||||
setTempShortcuts({})
|
||||
setTempLeaderKey(null)
|
||||
updateSettings({ keyboardShortcuts: {}, directShortcuts: [], leaderKey: '' })
|
||||
showToast.success('Keyboard shortcuts reset to defaults')
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!recordingKey && !recordingLeader) return
|
||||
|
||||
@@ -190,6 +198,11 @@ export function KeyboardShortcuts() {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
stopRecording()
|
||||
return
|
||||
}
|
||||
|
||||
const shortcut = formatShortcutEvent(e)
|
||||
if (!shortcut) {
|
||||
setCurrentKeys(leaderPrefix() + formatEventModifiers(e))
|
||||
@@ -212,14 +225,22 @@ export function KeyboardShortcuts() {
|
||||
return
|
||||
}
|
||||
|
||||
const otherDirectShortcuts = directShortcutsRef.current.filter((action) => action !== recordingKey)
|
||||
setTempShortcuts(prev => ({ ...prev, [recordingKey]: shortcut }))
|
||||
const applied = applyRecordedShortcut(recordingKey, shortcut, leaderPressed, {
|
||||
keyboardShortcuts: shortcutsRef.current,
|
||||
directShortcuts: directShortcutsRef.current,
|
||||
})
|
||||
setTempShortcuts(applied.keyboardShortcuts)
|
||||
setRecordingKey(null)
|
||||
setCurrentKeys('')
|
||||
updateSettingsRef.current({
|
||||
keyboardShortcuts: { ...shortcutsRef.current, [recordingKey]: shortcut },
|
||||
directShortcuts: leaderPressed ? otherDirectShortcuts : [...otherDirectShortcuts, recordingKey],
|
||||
keyboardShortcuts: applied.keyboardShortcuts,
|
||||
directShortcuts: applied.directShortcuts,
|
||||
})
|
||||
if (applied.cleared.length > 0) {
|
||||
showToast.info('Shortcut conflict resolved', {
|
||||
description: `Unbound to avoid conflicts: ${applied.cleared.map((action) => formatActionLabel(action).toLowerCase()).join(', ')}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleKeyUp = (e: KeyboardEvent) => {
|
||||
@@ -228,13 +249,13 @@ export function KeyboardShortcuts() {
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown, true)
|
||||
document.addEventListener('keyup', handleKeyUp)
|
||||
window.addEventListener('keydown', handleKeyDown, true)
|
||||
window.addEventListener('keyup', handleKeyUp)
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown, true)
|
||||
document.removeEventListener('keyup', handleKeyUp)
|
||||
window.removeEventListener('keydown', handleKeyDown, true)
|
||||
window.removeEventListener('keyup', handleKeyUp)
|
||||
}
|
||||
}, [recordingKey, recordingLeader])
|
||||
}, [recordingKey, recordingLeader, stopRecording])
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -321,9 +342,14 @@ export function KeyboardShortcuts() {
|
||||
<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>
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={resetShortcuts}>
|
||||
Reset to defaults
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
Import from OpenCode TUI
|
||||
</Button>
|
||||
</div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
|
||||
@@ -57,6 +57,7 @@ export function ManagerTokenSettings({ isOpen: controlledOpen, onToggle }: Manag
|
||||
type="button"
|
||||
onClick={() => setShowToken(!showToken)}
|
||||
disabled={!token}
|
||||
aria-label={showToken ? 'Hide token' : 'Show token'}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{showToken ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
@@ -73,6 +74,8 @@ export function ManagerTokenSettings({ isOpen: controlledOpen, onToggle }: Manag
|
||||
type="button"
|
||||
onClick={handleRotate}
|
||||
disabled={rotate.isPending || isLoading}
|
||||
aria-label="Rotate token"
|
||||
title="Rotate token"
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 ${rotate.isPending ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
|
||||
@@ -77,6 +77,7 @@ export function OpenCodeServerAuthSettings({ isOpen: controlledOpen, onToggle }:
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
aria-label={showPassword ? 'Hide password' : 'Show password'}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
|
||||
@@ -273,7 +273,7 @@ export function STTSettings() {
|
||||
<input
|
||||
type="text"
|
||||
placeholder="https://api.openai.com"
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] md:text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] md:text-sm ring-offset-background placeholder:text-placeholder focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -296,7 +296,7 @@ export function STTSettings() {
|
||||
<input
|
||||
type={showApiKey ? 'text' : 'password'}
|
||||
placeholder="sk-..."
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-[16px] md:text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-[16px] md:text-sm ring-offset-background placeholder:text-placeholder focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
{...field}
|
||||
/>
|
||||
<button
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, fireEvent, within, act } from '@testing-library/react'
|
||||
import { render, screen, fireEvent, within, act, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { SettingsDialog } from './SettingsDialog'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
|
||||
vi.mock('@/components/settings/GeneralSettings', () => ({
|
||||
GeneralSettings: () => <div data-testid="general-settings">General Settings Content</div>,
|
||||
GeneralSettings: () => (
|
||||
<div data-testid="general-settings">
|
||||
General Settings Content
|
||||
<label htmlFor="settings-general-field">Appearance</label>
|
||||
<input id="settings-general-field" data-testid="general-field" />
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/settings/GitSettings', () => ({
|
||||
@@ -136,6 +144,38 @@ describe('SettingsDialog', () => {
|
||||
expect(mobile.queryByTestId('logs-settings')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the mobile settings menu when opened through the settings action', () => {
|
||||
function TestWrapper() {
|
||||
const { open } = useSettingsDialog()
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={open}>Open Settings</button>
|
||||
<span data-testid="location-search">{location.search}</span>
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText('Open Settings'))
|
||||
|
||||
expect(screen.getByTestId('location-search')).toHaveTextContent('settings=open')
|
||||
expect(screen.getByTestId('location-search')).not.toHaveTextContent('settingsTab')
|
||||
|
||||
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
|
||||
const mobile = within(mobileContainer)
|
||||
expect(mobile.getByRole('heading', { name: 'Settings' })).toBeInTheDocument()
|
||||
expect(mobileContainer.querySelector('svg.lucide-chevron-left')).toBeNull()
|
||||
expect(mobile.queryByTestId('account-settings')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('navigates to the Logs section and reflects settingsTab=logs in the URL', () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
@@ -171,20 +211,14 @@ describe('SettingsDialog', () => {
|
||||
expect(screen.getByTestId('location-search')).toHaveTextContent('settingsTab=logs')
|
||||
})
|
||||
|
||||
it('starts at the menu on mobile even with a deep-linked settingsTab and navigates from there', () => {
|
||||
it('opens the deep-linked settingsTab on mobile and returns to the menu from it', () => {
|
||||
stubMatchMedia(false)
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const searchParams = new URLSearchParams(location.search)
|
||||
const isOpen = searchParams.get('settings') === 'open'
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => navigate('/')}>Close Settings</button>
|
||||
{isOpen && <span data-testid="dialog-open">Dialog Open</span>}
|
||||
{isOpen && <span data-testid="location-search">{location.search}</span>}
|
||||
<span data-testid="location-search">{location.search}</span>
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
@@ -196,24 +230,11 @@ describe('SettingsDialog', () => {
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('dialog-open')).toBeInTheDocument()
|
||||
|
||||
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
|
||||
const mobile = within(mobileContainer)
|
||||
|
||||
expect(mobile.getByRole('heading', { name: 'Settings' })).toBeInTheDocument()
|
||||
expect(mobile.getByText('Live manager and OpenCode server logs')).toBeInTheDocument()
|
||||
expect(mobile.queryByTestId('logs-settings')).not.toBeInTheDocument()
|
||||
expect(mobileContainer.querySelector('svg.lucide-chevron-left')).toBeNull()
|
||||
expect(screen.queryByTestId('logs-settings')).not.toBeInTheDocument()
|
||||
|
||||
const logsMenuButton = mobile.getByText('Live manager and OpenCode server logs').closest('button')
|
||||
expect(logsMenuButton).not.toBeNull()
|
||||
fireEvent.click(logsMenuButton!)
|
||||
|
||||
expect(mobile.getByTestId('logs-settings')).toBeInTheDocument()
|
||||
expect(mobile.getByRole('heading', { name: 'Logs' })).toBeInTheDocument()
|
||||
expect(screen.getAllByTestId('logs-settings')).toHaveLength(1)
|
||||
expect(screen.getByTestId('location-search')).toHaveTextContent('settingsTab=logs')
|
||||
|
||||
const backButton = mobileContainer.querySelector('svg.lucide-chevron-left')?.closest('button')
|
||||
@@ -225,6 +246,36 @@ describe('SettingsDialog', () => {
|
||||
expect(mobileContainer.querySelector('svg.lucide-chevron-left')).toBeNull()
|
||||
})
|
||||
|
||||
it('switches the mobile section when the settingsTab param changes while open', () => {
|
||||
stubMatchMedia(false)
|
||||
function TestWrapper() {
|
||||
const navigate = useNavigate()
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => navigate('?settings=open')}>Open Settings</button>
|
||||
<button onClick={() => navigate('?settings=open&settingsTab=git')}>Open Git</button>
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText('Open Settings'))
|
||||
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
|
||||
const mobile = within(mobileContainer)
|
||||
expect(mobile.getByRole('heading', { name: 'Settings' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByText('Open Git'))
|
||||
expect(mobile.getByTestId('git-settings')).toBeInTheDocument()
|
||||
expect(mobile.getByRole('heading', { name: 'Git' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('mounts exactly one LogsViewer on desktop when the Logs tab is selected', () => {
|
||||
stubMatchMedia(true)
|
||||
function TestWrapper() {
|
||||
@@ -252,12 +303,23 @@ describe('SettingsDialog', () => {
|
||||
fireEvent.click(screen.getByText('Open Logs'))
|
||||
|
||||
expect(screen.getAllByTestId('logs-settings')).toHaveLength(1)
|
||||
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
|
||||
expect(within(mobileContainer).queryByTestId('logs-settings')).not.toBeInTheDocument()
|
||||
expect(within(mobileContainer).getByRole('heading', { name: 'Logs' })).toBeInTheDocument()
|
||||
expect(document.querySelector('.sm\\:hidden')).toBeNull()
|
||||
})
|
||||
|
||||
it('falls back to the menu and account tab for an unknown settingsTab value', () => {
|
||||
it('mounts the deep-linked tab content once on desktop', () => {
|
||||
stubMatchMedia(true)
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?settings=open&settingsTab=general']}>
|
||||
<SettingsDialog />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(screen.getAllByTestId('general-settings')).toHaveLength(1)
|
||||
expect(document.querySelectorAll('#settings-general-field')).toHaveLength(1)
|
||||
expect(document.querySelector('.sm\\:hidden')).toBeNull()
|
||||
})
|
||||
|
||||
it('falls back to the menu for an unknown settingsTab value', () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const isOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
@@ -284,8 +346,38 @@ describe('SettingsDialog', () => {
|
||||
expect(mobile.queryByTestId('logs-settings')).not.toBeInTheDocument()
|
||||
expect(mobileContainer.querySelector('svg.lucide-chevron-left')).toBeNull()
|
||||
|
||||
const desktopTrigger = screen.getByRole('tab', { name: 'Account' })
|
||||
expect(desktopTrigger).toHaveAttribute('data-state', 'active')
|
||||
expect(screen.queryByRole('tablist')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('selects the account tab on desktop for an unknown settingsTab value', () => {
|
||||
stubMatchMedia(true)
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?settings=open&settingsTab=log']}>
|
||||
<SettingsDialog />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(screen.getByRole('tab', { name: 'Account' })).toHaveAttribute('data-state', 'active')
|
||||
expect(document.querySelector('.sm\\:hidden')).toBeNull()
|
||||
})
|
||||
|
||||
it('mounts a deep-linked mobile section once and keeps label associations', () => {
|
||||
stubMatchMedia(false)
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?settings=open&settingsTab=general']}>
|
||||
<SettingsDialog />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(screen.getAllByTestId('general-settings')).toHaveLength(1)
|
||||
expect(document.querySelectorAll('#settings-general-field')).toHaveLength(1)
|
||||
|
||||
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
|
||||
const mobile = within(mobileContainer)
|
||||
const mobileField = mobile.getByTestId('general-field')
|
||||
const label = mobile.getByText('Appearance') as HTMLLabelElement
|
||||
expect(label.control).toBe(mobileField)
|
||||
expect(document.getElementById('settings-general-field')).toBe(mobileField)
|
||||
})
|
||||
|
||||
it('renders a vertical desktop sidebar driven by menu items with URL and keyboard navigation', async () => {
|
||||
@@ -361,4 +453,63 @@ describe('SettingsDialog', () => {
|
||||
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps Settings open when Escape closes an open Select', async () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const settingsOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
return (
|
||||
<>
|
||||
{settingsOpen && <span data-testid="settings-open" />}
|
||||
<SettingsDialog />
|
||||
<Select defaultOpen>
|
||||
<SelectTrigger aria-label="Theme">
|
||||
<SelectValue placeholder="Theme" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="dark">Dark</SelectItem>
|
||||
<SelectItem value="light">Light</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?settings=open&settingsTab=general']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
const listbox = await screen.findByRole('listbox')
|
||||
fireEvent.keyDown(listbox, { key: 'Escape' })
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument())
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes Settings on Escape when no dropdown or nested dialog is open', () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const settingsOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
return (
|
||||
<>
|
||||
{settingsOpen && <span data-testid="settings-open" />}
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?settings=open']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(document.body, { key: 'Escape' })
|
||||
|
||||
expect(screen.queryByTestId('settings-open')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { GeneralSettings } from '@/components/settings/GeneralSettings'
|
||||
import { GitSettings } from '@/components/settings/GitSettings'
|
||||
import { OpenCodeServersSettings } from '@/components/settings/OpenCodeServersSettings'
|
||||
@@ -25,6 +25,14 @@ import { DESKTOP_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
|
||||
|
||||
type SettingsView = 'menu' | SettingsContentTab
|
||||
|
||||
const NESTED_OVERLAY_SELECTOR = [
|
||||
'[role="listbox"]',
|
||||
'[role="menu"]',
|
||||
'[data-radix-popper-content-wrapper]',
|
||||
'[role="alertdialog"]',
|
||||
'[role="dialog"]:not([data-settings-dialog])',
|
||||
].join(', ')
|
||||
|
||||
function OpenCodeSettings({ onOpenVersionDialog }: { onOpenVersionDialog: () => void }) {
|
||||
const [authSectionsOpen, setAuthSectionsOpen] = useState(true)
|
||||
const toggleAuthSections = useCallback(() => setAuthSectionsOpen((open) => !open), [])
|
||||
@@ -49,11 +57,12 @@ function OpenCodeSettings({ onOpenVersionDialog }: { onOpenVersionDialog: () =>
|
||||
}
|
||||
|
||||
export function SettingsDialog() {
|
||||
const { isOpen, close, activeTab, setActiveTab } = useSettingsDialog()
|
||||
const { isOpen, close, activeTab, selectedTab, setActiveTab } = useSettingsDialog()
|
||||
const isDesktop = useMediaQuery(DESKTOP_MEDIA_QUERY)
|
||||
const [mobileView, setMobileView] = useState<SettingsView>('menu')
|
||||
const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false)
|
||||
const [sectionHistory, setSectionHistory] = useState<SettingsView[]>([])
|
||||
const syncedTabRef = useRef<SettingsContentTab | null>(null)
|
||||
|
||||
const pushSectionHistory = useCallback((view: SettingsView) => {
|
||||
if (view === 'menu') return
|
||||
@@ -88,26 +97,35 @@ export function SettingsDialog() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
syncedTabRef.current = null
|
||||
setMobileView('menu')
|
||||
setSectionHistory([])
|
||||
return
|
||||
}
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && !isVersionDialogOpen) {
|
||||
const target = e.target
|
||||
if (target instanceof Element) {
|
||||
const closestDialog = target.closest('[role="dialog"]')
|
||||
if (closestDialog && !closestDialog.hasAttribute('data-settings-dialog')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
close()
|
||||
}
|
||||
if (e.key !== 'Escape' || e.defaultPrevented || isVersionDialogOpen) return
|
||||
if (e.target instanceof Element && e.target.closest(NESTED_OVERLAY_SELECTOR)) return
|
||||
close()
|
||||
}
|
||||
document.addEventListener('keydown', handleKeyDown, { capture: true })
|
||||
return () => document.removeEventListener('keydown', handleKeyDown, { capture: true })
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||
}, [isOpen, close, isVersionDialogOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || isDesktop) return
|
||||
if (!selectedTab) {
|
||||
if (syncedTabRef.current === null) return
|
||||
syncedTabRef.current = null
|
||||
setMobileView('menu')
|
||||
setSectionHistory([])
|
||||
return
|
||||
}
|
||||
if (syncedTabRef.current === selectedTab) return
|
||||
syncedTabRef.current = selectedTab
|
||||
setMobileView(selectedTab)
|
||||
pushSectionHistory(selectedTab)
|
||||
}, [isOpen, isDesktop, selectedTab, pushSectionHistory])
|
||||
|
||||
const menuItems: Array<{ id: SettingsContentTab; icon: LucideIcon; label: string; description: string }> = [
|
||||
{ id: 'account', icon: User, label: 'Account', description: 'Profile, passkeys, and sign out' },
|
||||
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
|
||||
@@ -147,6 +165,7 @@ export function SettingsDialog() {
|
||||
data-settings-dialog
|
||||
>
|
||||
<DialogTitle className="sr-only">Settings</DialogTitle>
|
||||
{isDesktop && (
|
||||
<div className="hidden sm:flex sm:h-full sm:min-h-0 sm:flex-col">
|
||||
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border bg-background px-4">
|
||||
<h2 className="text-lg font-semibold text-foreground">Settings</h2>
|
||||
@@ -191,12 +210,14 @@ export function SettingsDialog() {
|
||||
<TabsContent key="opencode" value="opencode" className="mt-0 px-0">
|
||||
<OpenCodeSettings onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
|
||||
</TabsContent>
|
||||
<TabsContent key="logs" value="logs" className="mt-0 h-full min-h-0 px-0">{isDesktop && <LogsViewer />}</TabsContent>
|
||||
<TabsContent key="logs" value="logs" className="mt-0 h-full min-h-0 px-0"><LogsViewer /></TabsContent>
|
||||
<TabsContent key="providers" value="providers" className="mt-0 px-0 max-w-7xl"><ProviderSettings /></TabsContent>
|
||||
</div>
|
||||
</Tabs>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isDesktop && (
|
||||
<div className="sm:hidden flex flex-col h-full min-h-0">
|
||||
<div className="flex-shrink-0 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-3 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
@@ -205,12 +226,13 @@ export function SettingsDialog() {
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleSettingsBack}
|
||||
aria-label="Back"
|
||||
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px]"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6" />
|
||||
</Button>
|
||||
)}
|
||||
<h2 className="text-xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
|
||||
<h2 className="min-w-0 text-xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
|
||||
{mobileView === 'menu' ? 'Settings' : menuItems.find(item => item.id === mobileView)?.label}
|
||||
</h2>
|
||||
</div>
|
||||
@@ -259,9 +281,10 @@ export function SettingsDialog() {
|
||||
<OpenCodeSettings key="opencode" onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
|
||||
)}
|
||||
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
|
||||
{mobileView === 'logs' && !isDesktop && <div key="logs" className="h-full min-h-0"><LogsViewer /></div>}
|
||||
{mobileView === 'logs' && <div key="logs" className="h-full min-h-0"><LogsViewer /></div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</DialogContent>
|
||||
<VersionSelectDialog
|
||||
|
||||
@@ -73,8 +73,8 @@ async function settleTime(ms: number): Promise<void> {
|
||||
|
||||
function openLogsFromMenu(): void {
|
||||
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
|
||||
const logsMenuButton = within(mobileContainer).getByText('Live manager and OpenCode server logs').closest('button')
|
||||
fireEvent.click(logsMenuButton!)
|
||||
const logsMenuButton = within(mobileContainer).queryByText('Live manager and OpenCode server logs')?.closest('button')
|
||||
if (logsMenuButton) fireEvent.click(logsMenuButton)
|
||||
}
|
||||
|
||||
describe('SettingsDialog live Logs view integration', () => {
|
||||
|
||||
@@ -51,7 +51,7 @@ export function SettingsDisclosure({
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{icon}
|
||||
<h3 className="text-sm font-semibold truncate">{title}</h3>
|
||||
<h3 className="text-sm font-semibold">{title}</h3>
|
||||
{meta}
|
||||
</div>
|
||||
<ChevronDown className={cn('h-4 w-4 shrink-0 transition-transform', isOpen && 'rotate-180')} />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { render, screen, act } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
@@ -182,4 +182,33 @@ describe('TTSSettings audio cache', () => {
|
||||
expect(screen.getByRole('button', { name: 'Clear audio cache' })).toBeInTheDocument()
|
||||
expect(await screen.findByText('1 voices available in your browser')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('discovers models and voices only when external TTS is configured', async () => {
|
||||
renderTTSSettings()
|
||||
await act(async () => {})
|
||||
expect(vi.mocked(useTTSModels).mock.calls.at(-1)?.[1]).toBe(true)
|
||||
expect(vi.mocked(useTTSVoices).mock.calls.at(-1)?.[1]).toBe(true)
|
||||
})
|
||||
|
||||
it('skips server discovery while TTS is disabled, builtin, or missing credentials', async () => {
|
||||
mockHooks(buildPreferences({ tts: { ...baseTts, enabled: false } }))
|
||||
const disabledRender = renderTTSSettings()
|
||||
await act(async () => {})
|
||||
expect(vi.mocked(useTTSModels).mock.calls.at(-1)?.[1]).toBe(false)
|
||||
expect(vi.mocked(useTTSVoices).mock.calls.at(-1)?.[1]).toBe(false)
|
||||
disabledRender.unmount()
|
||||
|
||||
mockHooks(buildPreferences({ tts: { ...baseTts, provider: 'builtin', voice: 'Alex' } }))
|
||||
const builtinRender = renderTTSSettings()
|
||||
await act(async () => {})
|
||||
expect(vi.mocked(useTTSModels).mock.calls.at(-1)?.[1]).toBe(false)
|
||||
expect(vi.mocked(useTTSVoices).mock.calls.at(-1)?.[1]).toBe(false)
|
||||
builtinRender.unmount()
|
||||
|
||||
mockHooks(buildPreferences({ tts: { ...baseTts, apiKey: '' } }))
|
||||
renderTTSSettings()
|
||||
await act(async () => {})
|
||||
expect(vi.mocked(useTTSModels).mock.calls.at(-1)?.[1]).toBe(false)
|
||||
expect(vi.mocked(useTTSVoices).mock.calls.at(-1)?.[1]).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -94,15 +94,22 @@ export function TTSSettings() {
|
||||
|
||||
const { reset, formState: { isDirty, isValid }, getValues } = form
|
||||
|
||||
const shouldDiscoverTTS = Boolean(
|
||||
preferences?.tts?.enabled
|
||||
&& preferences.tts.provider === 'external'
|
||||
&& preferences.tts.apiKey
|
||||
&& preferences.tts.endpoint,
|
||||
)
|
||||
|
||||
// Fetch available models and voices for external provider
|
||||
const { data: modelsData, isLoading: isLoadingModels, refetch: refetchModels } = useTTSModels(
|
||||
undefined,
|
||||
true
|
||||
shouldDiscoverTTS
|
||||
)
|
||||
|
||||
const { data: voicesData, isLoading: isLoadingVoices, refetch: refetchVoices } = useTTSVoices(
|
||||
undefined,
|
||||
true
|
||||
shouldDiscoverTTS
|
||||
)
|
||||
|
||||
const availableModels = modelsData?.models || preferences?.tts?.availableModels || []
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useGitStatus } from '@/api/git'
|
||||
import type { GitStatusResponse } from '@/types/git'
|
||||
import { ChangesTab } from './ChangesTab'
|
||||
|
||||
const { commitMutate } = vi.hoisted(() => ({ commitMutate: vi.fn() }))
|
||||
|
||||
vi.mock('@/hooks/useGit', () => ({
|
||||
useGit: () => ({
|
||||
commit: { mutate: commitMutate, isPending: false },
|
||||
stageFiles: { mutate: vi.fn(), isPending: false },
|
||||
unstageFiles: { mutate: vi.fn(), isPending: false },
|
||||
discardFiles: { mutate: vi.fn(), isPending: false },
|
||||
generateCommitMessage: { mutate: vi.fn(), isPending: false },
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/git', () => ({
|
||||
useGitStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('./RepoGitIdentitySelect', () => ({
|
||||
RepoGitIdentitySelect: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/file-browser/FileDiffView', () => ({
|
||||
FileDiffView: () => null,
|
||||
}))
|
||||
|
||||
const stagedStatus: GitStatusResponse = {
|
||||
branch: 'main',
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
hasChanges: true,
|
||||
operation: null,
|
||||
files: [
|
||||
{ path: 'notes.txt', status: 'modified', staged: true },
|
||||
{ path: 'todo.txt', status: 'modified', staged: false },
|
||||
],
|
||||
}
|
||||
|
||||
function renderTab() {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: stagedStatus,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as unknown as ReturnType<typeof useGitStatus>)
|
||||
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ChangesTab repoId={1} onFileSelect={vi.fn()} isMobile={false} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('ChangesTab commit message', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('keeps the message when the commit fails', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderTab()
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Commit message...'), 'fix the thing')
|
||||
await user.click(screen.getByRole('button', { name: /^Commit/ }))
|
||||
|
||||
expect(commitMutate).toHaveBeenCalledWith(
|
||||
{ message: 'fix the thing' },
|
||||
expect.objectContaining({ onSuccess: expect.any(Function) }),
|
||||
)
|
||||
expect(screen.getByPlaceholderText('Commit message...')).toHaveValue('fix the thing')
|
||||
})
|
||||
|
||||
it('clears the message after a successful commit', async () => {
|
||||
const user = userEvent.setup()
|
||||
commitMutate.mockImplementation((_variables, options?: { onSuccess?: () => void }) => {
|
||||
options?.onSuccess?.()
|
||||
})
|
||||
renderTab()
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Commit message...'), 'fix the thing')
|
||||
await user.click(screen.getByRole('button', { name: /^Commit/ }))
|
||||
|
||||
expect(screen.getByPlaceholderText('Commit message...')).toHaveValue('')
|
||||
})
|
||||
})
|
||||
@@ -57,8 +57,10 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
|
||||
}
|
||||
|
||||
const handleCommit = () => {
|
||||
git.commit.mutate({ message: commitMessage.trim() })
|
||||
setCommitMessage('')
|
||||
git.commit.mutate(
|
||||
{ message: commitMessage.trim() },
|
||||
{ onSuccess: () => setCommitMessage('') },
|
||||
)
|
||||
}
|
||||
|
||||
const handleGenerateMessage = () => {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { GitFileStatus } from '@/types/git'
|
||||
import { GitFlatFileItem } from './GitFlatFileItem'
|
||||
|
||||
const defaultViewportWidth = window.innerWidth
|
||||
|
||||
function buildFile(overrides: Partial<GitFileStatus> = {}): GitFileStatus {
|
||||
return { path: 'notes.txt', status: 'modified', staged: false, ...overrides }
|
||||
}
|
||||
|
||||
function setViewportWidth(width: number) {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width })
|
||||
}
|
||||
|
||||
describe('GitFlatFileItem', () => {
|
||||
afterEach(() => {
|
||||
setViewportWidth(defaultViewportWidth)
|
||||
})
|
||||
|
||||
it('renders an untracked directory once with its trailing slash', () => {
|
||||
render(
|
||||
<GitFlatFileItem
|
||||
file={buildFile({ path: '.ocm/', status: 'untracked' })}
|
||||
isSelected={false}
|
||||
onSelect={vi.fn()}
|
||||
onStage={vi.fn()}
|
||||
onDiscard={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('.ocm/')).toBeInTheDocument()
|
||||
expect(screen.queryByText('.ocm')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the parent directory of a nested untracked directory', () => {
|
||||
render(
|
||||
<GitFlatFileItem
|
||||
file={buildFile({ path: 'src/.ocm/', status: 'untracked' })}
|
||||
isSelected={false}
|
||||
onSelect={vi.fn()}
|
||||
onStage={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('.ocm/')).toBeInTheDocument()
|
||||
expect(screen.getByText('src')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('names the stage and discard actions after the file', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onStage = vi.fn()
|
||||
const onDiscard = vi.fn()
|
||||
render(
|
||||
<GitFlatFileItem
|
||||
file={buildFile({ path: 'src/notes.txt' })}
|
||||
isSelected={false}
|
||||
onSelect={vi.fn()}
|
||||
onStage={onStage}
|
||||
onDiscard={onDiscard}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Stage notes.txt' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Discard changes to notes.txt' }))
|
||||
|
||||
expect(onStage).toHaveBeenCalledWith('src/notes.txt')
|
||||
expect(onDiscard).toHaveBeenCalledWith('src/notes.txt', false)
|
||||
})
|
||||
|
||||
it('names the unstage action for staged files', () => {
|
||||
render(
|
||||
<GitFlatFileItem
|
||||
file={buildFile({ path: 'notes.txt', staged: true })}
|
||||
isSelected={false}
|
||||
onSelect={vi.fn()}
|
||||
onUnstage={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Unstage notes.txt' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reveals the row actions without hovering on touch-sized viewports', () => {
|
||||
setViewportWidth(500)
|
||||
render(
|
||||
<GitFlatFileItem
|
||||
file={buildFile()}
|
||||
isSelected={false}
|
||||
onSelect={vi.fn()}
|
||||
onStage={vi.fn()}
|
||||
onDiscard={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Stage notes.txt' })).toHaveClass('opacity-100')
|
||||
})
|
||||
|
||||
it('reveals hover-only actions when they receive focus', () => {
|
||||
setViewportWidth(1280)
|
||||
render(
|
||||
<GitFlatFileItem
|
||||
file={buildFile()}
|
||||
isSelected={false}
|
||||
onSelect={vi.fn()}
|
||||
onStage={vi.fn()}
|
||||
onDiscard={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
const stageButton = screen.getByRole('button', { name: 'Stage notes.txt' })
|
||||
expect(stageButton).toHaveClass('opacity-0')
|
||||
expect(stageButton).toHaveClass('focus-visible:opacity-100')
|
||||
expect(stageButton).toHaveClass('group-focus-within:opacity-100')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot, RotateCcw } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import type { GitFileStatus } from '@/types/git'
|
||||
import { GIT_STATUS_COLORS, GIT_UI_COLORS } from '@/lib/git-status-styles'
|
||||
|
||||
@@ -23,11 +24,21 @@ const statusIcons = {
|
||||
}
|
||||
|
||||
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage, onDiscard }: GitFlatFileItemProps) {
|
||||
const isMobile = useMobile()
|
||||
const StatusIcon = statusIcons[file.status] || FileText
|
||||
const statusColor = GIT_STATUS_COLORS[file.status] || 'text-muted-foreground'
|
||||
|
||||
const fileName = file.path.split('/').pop() || file.path
|
||||
const dirPath = file.path.includes('/') ? file.path.substring(0, file.path.lastIndexOf('/')) : ''
|
||||
const isDirectory = file.path.endsWith('/')
|
||||
const normalizedPath = file.path.replace(/\/+$/, '')
|
||||
const baseName = normalizedPath.split('/').pop() || normalizedPath
|
||||
const fileName = isDirectory ? `${baseName}/` : baseName
|
||||
const dirPath = normalizedPath.includes('/') ? normalizedPath.substring(0, normalizedPath.lastIndexOf('/')) : ''
|
||||
const actionButtonClass = cn(
|
||||
'h-6 w-6 p-0 transition-opacity flex-shrink-0',
|
||||
isMobile
|
||||
? 'opacity-100'
|
||||
: 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100 group-focus-within:opacity-100'
|
||||
)
|
||||
|
||||
const handleAction = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
@@ -81,8 +92,9 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
|
||||
className={actionButtonClass}
|
||||
onClick={handleAction}
|
||||
aria-label={file.staged ? `Unstage ${fileName}` : `Stage ${fileName}`}
|
||||
>
|
||||
{file.staged ? (
|
||||
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
|
||||
@@ -95,9 +107,10 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
|
||||
className={actionButtonClass}
|
||||
onClick={handleDiscard}
|
||||
title="Discard changes"
|
||||
aria-label={`Discard changes to ${fileName}`}
|
||||
>
|
||||
<RotateCcw className="w-3 h-3 text-destructive" />
|
||||
</Button>
|
||||
|
||||
@@ -117,7 +117,7 @@ describe('TerminalPanel', () => {
|
||||
renderPanel()
|
||||
|
||||
expect(createMutate).toHaveBeenCalledTimes(1)
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo', title: 'Terminal 1' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('does not auto-create while the list request is unresolved or failed', () => {
|
||||
@@ -140,7 +140,7 @@ describe('TerminalPanel', () => {
|
||||
)
|
||||
|
||||
expect(createMutate).toHaveBeenCalledTimes(1)
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo', title: 'Terminal 1' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('auto-creates a shell when only exited terminals exist and none is requested', () => {
|
||||
@@ -148,7 +148,7 @@ describe('TerminalPanel', () => {
|
||||
renderPanel()
|
||||
|
||||
expect(createMutate).toHaveBeenCalledTimes(1)
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo', title: 'Terminal 1' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('decides on auto-creation once per opening, so a shell exiting later is not replaced', () => {
|
||||
@@ -260,10 +260,10 @@ describe('TerminalPanel', () => {
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Terminal'))
|
||||
|
||||
expect(screen.getByText('Stop the running process?')).toBeInTheDocument()
|
||||
expect(screen.getByText('Close this terminal?')).toBeInTheDocument()
|
||||
expect(removeMutate).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Stop' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close terminal' }))
|
||||
|
||||
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't1', directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
@@ -275,7 +275,7 @@ describe('TerminalPanel', () => {
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Build'))
|
||||
|
||||
expect(screen.queryByText('Stop the running process?')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Close this terminal?')).not.toBeInTheDocument()
|
||||
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't2', directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
@@ -346,6 +346,97 @@ describe('TerminalPanel', () => {
|
||||
expect(createMutate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps an action terminal that exited cleanly so its output stays visible', async () => {
|
||||
const runningActionTerminal: TerminalInfo = {
|
||||
id: 't4',
|
||||
title: 'Say hi',
|
||||
kind: 'action',
|
||||
actionId: 'say-hi',
|
||||
cwd: '/repo',
|
||||
status: 'running',
|
||||
}
|
||||
mockTerminalHooks([runningActionTerminal])
|
||||
refetch.mockResolvedValue({ data: [{ ...runningActionTerminal, status: 'exited', exitCode: 0 }] })
|
||||
const onClose = vi.fn()
|
||||
const { rerender } = renderPanel('/repos/1?dialog=terminal&terminal=t4', onClose)
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
|
||||
fireEvent.click(screen.getByLabelText('exit t4'))
|
||||
|
||||
await waitFor(() => expect(refetch).toHaveBeenCalledTimes(1))
|
||||
expect(removeMutate).not.toHaveBeenCalled()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(screen.getByLabelText('Close Say hi')).toBeInTheDocument()
|
||||
|
||||
mockTerminalHooks([{ ...runningActionTerminal, status: 'exited', exitCode: 0 }])
|
||||
rerender(
|
||||
<MemoryRouter initialEntries={['/repos/1?dialog=terminal&terminal=t4']}>
|
||||
<TerminalPanel target={{ kind: 'repo', repoId: 1 }} directory="/repo" isOpen onClose={onClose} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
expect(await screen.findByText('exited (0)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('sends a single delete when a closed terminal reports its exit', async () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
const onClose = vi.fn()
|
||||
renderPanel('/repos/1?dialog=terminal&terminal=t1', onClose)
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Terminal'))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close terminal' }))
|
||||
|
||||
expect(removeMutate).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.click(screen.getByLabelText('exit t1'))
|
||||
|
||||
expect(refetch).not.toHaveBeenCalled()
|
||||
expect(removeMutate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('closes the panel after the user closes the last terminal', async () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
removeMutate.mockImplementation((_variables: unknown, options: { onSuccess?: () => void }) => {
|
||||
options.onSuccess?.()
|
||||
})
|
||||
const onClose = vi.fn()
|
||||
renderPanel('/repos/1?dialog=terminal&terminal=t1', onClose)
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Terminal'))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close terminal' }))
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the panel open when other terminals remain after a manual close', async () => {
|
||||
const otherTerminal: TerminalInfo = { ...runningTerminal, id: 't3', title: 'Shell' }
|
||||
mockTerminalHooks([runningTerminal, otherTerminal])
|
||||
removeMutate.mockImplementation((_variables: unknown, options: { onSuccess?: () => void }) => {
|
||||
options.onSuccess?.()
|
||||
})
|
||||
const onClose = vi.fn()
|
||||
renderPanel('/repos/1?dialog=terminal&terminal=t3', onClose)
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Shell'))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close terminal' }))
|
||||
|
||||
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't3', directory: '/repo' }, expect.any(Object))
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('numbers new shell tabs so they can be told apart', async () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
renderPanel()
|
||||
await screen.findAllByTestId('terminal-view')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'New terminal' }))
|
||||
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo', title: 'Terminal 2' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('renders the key bar only on mobile', async () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExi
|
||||
const [ctrlArmed, setCtrlArmed] = useState(false)
|
||||
const [pendingClose, setPendingClose] = useState<TerminalInfo | null>(null)
|
||||
const [dismissedTerminalIds, setDismissedTerminalIds] = useState<ReadonlySet<string>>(() => new Set())
|
||||
const removingTerminalIdsRef = useRef(new Set<string>())
|
||||
const viewHandlesRef = useRef(new Map<string, TerminalViewHandle>())
|
||||
const autoCreateCheckedDirectoryRef = useRef<string | null>(null)
|
||||
|
||||
@@ -54,6 +55,11 @@ export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExi
|
||||
[data, dismissedTerminalIds],
|
||||
)
|
||||
|
||||
const nextShellTitle = useCallback(
|
||||
() => `Terminal ${terminals.filter((terminal) => terminal.kind === 'shell').length + 1}`,
|
||||
[terminals],
|
||||
)
|
||||
|
||||
const selectTerminal = useCallback((id: string) => {
|
||||
updateParams((params) => {
|
||||
params.set('terminal', id)
|
||||
@@ -76,23 +82,25 @@ export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExi
|
||||
autoCreateCheckedDirectoryRef.current = directory
|
||||
if (!needsShell) return
|
||||
createTerminal(
|
||||
{ directory },
|
||||
{ directory, title: nextShellTitle() },
|
||||
{ onSuccess: (terminal) => selectTerminal(terminal.id) },
|
||||
)
|
||||
}, [isOpen, directory, isSuccess, isFetching, needsShell, createTerminal, selectTerminal])
|
||||
}, [isOpen, directory, isSuccess, isFetching, needsShell, createTerminal, selectTerminal, nextShellTitle])
|
||||
|
||||
const handleCreate = useCallback(() => {
|
||||
createTerminal(
|
||||
{ directory },
|
||||
{ directory, title: nextShellTitle() },
|
||||
{ onSuccess: (terminal) => selectTerminal(terminal.id) },
|
||||
)
|
||||
}, [createTerminal, directory, selectTerminal])
|
||||
}, [createTerminal, directory, selectTerminal, nextShellTitle])
|
||||
|
||||
const performRemove = useCallback(
|
||||
(
|
||||
terminalId: string,
|
||||
options: { onRemoved?: () => void; onError?: () => void } = {},
|
||||
) => {
|
||||
if (removingTerminalIdsRef.current.has(terminalId)) return
|
||||
removingTerminalIdsRef.current.add(terminalId)
|
||||
removeTerminal(
|
||||
{ ptyID: terminalId, directory },
|
||||
{
|
||||
@@ -102,22 +110,34 @@ export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExi
|
||||
}, 'replace')
|
||||
options.onRemoved?.()
|
||||
},
|
||||
onError: options.onError,
|
||||
onError: () => {
|
||||
removingTerminalIdsRef.current.delete(terminalId)
|
||||
options.onError?.()
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
[removeTerminal, directory, updateParams],
|
||||
)
|
||||
|
||||
const closeTerminal = useCallback((terminal: TerminalInfo) => {
|
||||
performRemove(terminal.id, {
|
||||
onRemoved: () => {
|
||||
if (terminals.every((entry) => entry.id === terminal.id)) onLastTerminalExited?.()
|
||||
},
|
||||
})
|
||||
}, [performRemove, terminals, onLastTerminalExited])
|
||||
|
||||
const handleCloseTab = useCallback((terminal: TerminalInfo) => {
|
||||
if (terminal.status === 'running') {
|
||||
setPendingClose(terminal)
|
||||
return
|
||||
}
|
||||
performRemove(terminal.id)
|
||||
}, [performRemove])
|
||||
closeTerminal(terminal)
|
||||
}, [closeTerminal])
|
||||
|
||||
const handleTerminalExited = useCallback((terminalId: string) => {
|
||||
if (removingTerminalIdsRef.current.has(terminalId)) return
|
||||
const settleExit = async () => {
|
||||
let latestTerminals: TerminalInfo[]
|
||||
try {
|
||||
@@ -126,8 +146,9 @@ export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExi
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const exitCode = latestTerminals.find((terminal) => terminal.id === terminalId)?.exitCode
|
||||
if (exitCode !== undefined && exitCode !== 0) return
|
||||
const exitedTerminal = latestTerminals.find((terminal) => terminal.id === terminalId)
|
||||
if (exitedTerminal?.kind === 'action') return
|
||||
if (exitedTerminal?.exitCode !== undefined && exitedTerminal.exitCode !== 0) return
|
||||
setDismissedTerminalIds((ids) => new Set(ids).add(terminalId))
|
||||
performRemove(terminalId, {
|
||||
onRemoved: () => {
|
||||
@@ -186,7 +207,10 @@ export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExi
|
||||
type="button"
|
||||
onClick={() => handleCloseTab(terminal)}
|
||||
aria-label={`Close ${terminal.title}`}
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
className={cn(
|
||||
'flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground',
|
||||
isMobile ? 'h-8 w-8' : 'h-6 w-6',
|
||||
)}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
@@ -246,14 +270,14 @@ export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExi
|
||||
open={pendingClose !== null}
|
||||
onOpenChange={(open) => { if (!open) setPendingClose(null) }}
|
||||
onConfirm={() => {
|
||||
if (pendingClose) performRemove(pendingClose.id)
|
||||
if (pendingClose) closeTerminal(pendingClose)
|
||||
setPendingClose(null)
|
||||
}}
|
||||
onCancel={() => setPendingClose(null)}
|
||||
title="Close Terminal"
|
||||
description="Stop the running process?"
|
||||
confirmLabel="Stop"
|
||||
pendingLabel="Stopping..."
|
||||
description="Close this terminal?"
|
||||
confirmLabel="Close terminal"
|
||||
pendingLabel="Closing..."
|
||||
isPending={isRemoving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -214,7 +214,7 @@ export function Combobox({
|
||||
className={cn(
|
||||
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-[16px] md:text-sm shadow-sm transition-colors',
|
||||
'file:border-0 file:bg-transparent file:text-sm file:font-medium',
|
||||
'placeholder:text-muted-foreground',
|
||||
'placeholder:text-placeholder',
|
||||
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'pr-8'
|
||||
|
||||
@@ -44,7 +44,7 @@ export function ConfirmDestructiveDialog({
|
||||
{warning && (
|
||||
<Alert className="overflow-hidden">
|
||||
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
|
||||
<AlertDescription className="break-all">{warning}</AlertDescription>
|
||||
<AlertDescription className="break-words">{warning}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ interface DeleteDialogProps {
|
||||
description: ReactNode
|
||||
itemName?: string
|
||||
isDeleting?: boolean
|
||||
confirmLabel?: string
|
||||
pendingLabel?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
@@ -22,6 +24,8 @@ export function DeleteDialog({
|
||||
description,
|
||||
itemName,
|
||||
isDeleting = false,
|
||||
confirmLabel,
|
||||
pendingLabel = 'Deleting...',
|
||||
children
|
||||
}: DeleteDialogProps) {
|
||||
return (
|
||||
@@ -35,8 +39,8 @@ export function DeleteDialog({
|
||||
warning={itemName ? (
|
||||
<>This will permanently delete "<span className="font-medium">{itemName}</span>". This action cannot be undone.</>
|
||||
) : undefined}
|
||||
confirmLabel={title.includes('Configuration') ? 'Delete Configuration' : 'Delete'}
|
||||
pendingLabel="Deleting..."
|
||||
confirmLabel={confirmLabel ?? (title.includes('Configuration') ? 'Delete Configuration' : 'Delete')}
|
||||
pendingLabel={pendingLabel}
|
||||
isPending={isDeleting}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -201,9 +201,28 @@ describe("DialogContent", () => {
|
||||
);
|
||||
const closeTrigger = document.querySelector('[data-swipe-close-trigger]');
|
||||
expect(closeTrigger).toBeInTheDocument();
|
||||
expect(closeTrigger).toHaveAccessibleName('Dismiss dialog');
|
||||
});
|
||||
});
|
||||
|
||||
it('extends the close button hit area without enlarging the icon', () => {
|
||||
render(
|
||||
<Dialog open>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Close Target Dialog</DialogTitle>
|
||||
</DialogHeader>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
const closeButton = screen.getByRole('button', { name: 'Close' });
|
||||
const icon = closeButton.querySelector('svg');
|
||||
|
||||
expect(closeButton).toHaveClass('after:-inset-2', 'pointer-coarse:after:-inset-3.5');
|
||||
expect(icon).toHaveClass('h-4', 'w-4');
|
||||
});
|
||||
|
||||
it('does not render hidden close trigger when mobileSwipeToClose is false', () => {
|
||||
withMobileViewport(() => {
|
||||
render(
|
||||
|
||||
@@ -149,11 +149,16 @@ const DialogContent = React.forwardRef<
|
||||
>
|
||||
{children}
|
||||
{shouldEnableMobileSwipe && (
|
||||
<DialogPrimitive.Close ref={closeTriggerRef} className="sr-only" data-swipe-close-trigger />
|
||||
<DialogPrimitive.Close
|
||||
ref={closeTriggerRef}
|
||||
className="sr-only"
|
||||
aria-label="Dismiss dialog"
|
||||
data-swipe-close-trigger
|
||||
/>
|
||||
)}
|
||||
{!hideCloseButton && !fullscreen && (
|
||||
<DialogPrimitive.Close
|
||||
className="absolute right-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"
|
||||
className="absolute right-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground after:absolute after:-inset-2 after:content-[''] pointer-coarse:after:-inset-3.5"
|
||||
style={mobileFullscreen ? {
|
||||
top: 'calc(env(safe-area-inset-top, 0px) + 1rem)',
|
||||
} : { top: '1rem' }}
|
||||
|
||||
@@ -8,7 +8,7 @@ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] text-foreground file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] text-foreground file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-placeholder focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
|
||||
@@ -174,7 +174,7 @@ export function MultiSelect({
|
||||
placeholder={searchPlaceholder}
|
||||
className={cn(
|
||||
'flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors',
|
||||
'placeholder:text-muted-foreground',
|
||||
'placeholder:text-placeholder',
|
||||
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring'
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
interface NotFoundStateProps {
|
||||
message: string
|
||||
backTo: string
|
||||
backLabel: string
|
||||
title?: string
|
||||
}
|
||||
|
||||
export function NotFoundState({ message, backTo, backLabel, title }: NotFoundStateProps) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-background via-background to-background p-6">
|
||||
<div className="flex flex-col items-center gap-3 text-center">
|
||||
{title && <h1 className="text-lg font-semibold text-foreground">{title}</h1>}
|
||||
<span className="text-muted-foreground">{message}</span>
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(backTo)}>{backLabel}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { LocationCatcher } from '@/test/test-utils'
|
||||
import { RouteErrorBoundary } from './route-error-boundary'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
error: undefined as unknown,
|
||||
}))
|
||||
|
||||
vi.mock('react-router-dom', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react-router-dom')>()
|
||||
return { ...actual, useRouteError: () => mocks.error }
|
||||
})
|
||||
|
||||
function renderBoundary() {
|
||||
const capturedPathname: { current: string } = { current: '' }
|
||||
const capturedSearch: { current: string } = { current: '' }
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/does-not-exist']}>
|
||||
<LocationCatcher capturedSearch={capturedSearch} capturedPathname={capturedPathname} />
|
||||
<Routes>
|
||||
<Route path="/" element={null} />
|
||||
<Route path="*" element={<RouteErrorBoundary />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
return { capturedPathname, capturedSearch }
|
||||
}
|
||||
|
||||
describe('RouteErrorBoundary', () => {
|
||||
beforeEach(() => {
|
||||
mocks.error = undefined
|
||||
})
|
||||
|
||||
it('offers a way home for a 404', async () => {
|
||||
mocks.error = { status: 404, statusText: 'Not Found', internal: false, data: {} }
|
||||
|
||||
const { capturedPathname } = renderBoundary()
|
||||
|
||||
expect(screen.getByText('Page Not Found')).toBeInTheDocument()
|
||||
expect(screen.getByText('The page you are looking for does not exist.')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Go home' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedPathname.current).toBe('/')
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the retry action for other statuses', () => {
|
||||
mocks.error = { status: 500, statusText: 'Server Error', internal: false, data: { message: 'Boom' } }
|
||||
|
||||
renderBoundary()
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Go home' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the login action for auth errors', () => {
|
||||
mocks.error = { status: 401, statusText: 'Unauthorized', internal: false, data: {} }
|
||||
|
||||
renderBoundary()
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Log in' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useRouteError, isRouteErrorResponse } from 'react-router-dom'
|
||||
import { AlertTriangle, RefreshCw, LogIn, WifiOff } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { NotFoundState } from '@/components/ui/not-found-state'
|
||||
import { parseNetworkError } from '@/lib/opencode-errors'
|
||||
|
||||
function getErrorDetails(error: unknown) {
|
||||
@@ -57,6 +58,10 @@ export function RouteErrorBoundary() {
|
||||
|
||||
const isAuthError = statusCode === 401 || statusCode === 403
|
||||
|
||||
if (statusCode === 404) {
|
||||
return <NotFoundState title={title} message={message} backTo="/" backLabel="Go home" />
|
||||
}
|
||||
|
||||
if ('variant' in details && details.variant === 'offline') {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center gap-6 bg-background text-foreground">
|
||||
|
||||
@@ -186,6 +186,21 @@ describe('Sidebar resize handle', () => {
|
||||
|
||||
expect(handleWidthChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the collapse toggle clear of the full-height resize strip', () => {
|
||||
render(
|
||||
<Sidebar collapsed={false} onToggle={vi.fn()} width={300} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
const toggle = screen.getByRole('button', { name: 'Collapse sidebar' })
|
||||
|
||||
expect(handle).toHaveClass('inset-y-0')
|
||||
expect(handle).not.toContainElement(toggle)
|
||||
expect(toggle).not.toHaveClass('absolute')
|
||||
})
|
||||
})
|
||||
|
||||
describe('SidebarSection', () => {
|
||||
|
||||
@@ -122,7 +122,11 @@ export function Sidebar({
|
||||
style={!collapsed && width !== undefined ? { width } : undefined}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
{onToggle && <SidebarCollapseToggle collapsed={collapsed} onToggle={onToggle} />}
|
||||
{onToggle && (
|
||||
<div className={cn('flex h-9 shrink-0 items-center pt-1', collapsed ? 'justify-center' : 'justify-end px-1.5')}>
|
||||
<SidebarCollapseToggle collapsed={collapsed} onToggle={onToggle} />
|
||||
</div>
|
||||
)}
|
||||
{showResizeHandle && (
|
||||
<div
|
||||
role="separator"
|
||||
@@ -132,13 +136,18 @@ export function Sidebar({
|
||||
aria-valuenow={width}
|
||||
aria-valuemin={SIDEBAR_MIN_WIDTH}
|
||||
aria-valuemax={SIDEBAR_MAX_WIDTH}
|
||||
className="absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize touch-none bg-transparent hover:bg-highlight/30 focus-visible:bg-highlight/30 focus-visible:outline-none"
|
||||
className="group absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize touch-none bg-transparent focus-visible:outline-none"
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerEnd}
|
||||
onPointerCancel={handlePointerEnd}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute inset-y-0 right-0.5 w-0.5 rounded-full bg-muted-foreground/30 transition-all duration-150 group-hover:w-1 group-hover:bg-highlight group-focus-visible:w-1 group-focus-visible:bg-highlight"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</aside>
|
||||
@@ -231,41 +240,22 @@ export interface SidebarCollapseToggleProps {
|
||||
}
|
||||
|
||||
export function SidebarCollapseToggle({ collapsed, onToggle }: SidebarCollapseToggleProps) {
|
||||
const Chevron = collapsed ? ChevronRight : ChevronLeft
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
className={cn(
|
||||
'group absolute -right-3 top-1/2 z-20 h-16 w-6 -translate-y-1/2',
|
||||
'flex items-center justify-center bg-transparent',
|
||||
'inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors',
|
||||
'hover:bg-accent hover:text-foreground',
|
||||
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background'
|
||||
)}
|
||||
title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
|
||||
aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
|
||||
aria-expanded={!collapsed}
|
||||
>
|
||||
<span aria-hidden="true" className="relative flex items-center justify-center">
|
||||
<span
|
||||
className={cn(
|
||||
'h-8 w-1 rounded-full bg-highlight/60 transition-colors duration-150',
|
||||
'group-hover:bg-highlight group-focus-visible:bg-highlight'
|
||||
)}
|
||||
/>
|
||||
<ChevronLeft
|
||||
className={cn(
|
||||
'absolute left-full ml-0.5 h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity duration-150',
|
||||
'group-hover:opacity-100 group-focus-visible:opacity-100',
|
||||
collapsed && 'hidden'
|
||||
)}
|
||||
/>
|
||||
<ChevronRight
|
||||
className={cn(
|
||||
'absolute left-full ml-0.5 h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity duration-150',
|
||||
'group-hover:opacity-100 group-focus-visible:opacity-100',
|
||||
!collapsed && 'hidden'
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
<Chevron aria-hidden="true" className="h-4 w-4" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -9,7 +9,7 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] placeholder:text-muted-foreground focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] placeholder:text-placeholder focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
|
||||
Reference in new issue
Block a user