diff --git a/frontend/src/components/settings/AgentsEditor.test.tsx b/frontend/src/components/settings/AgentsEditor.test.tsx new file mode 100644 index 00000000..369f4f32 --- /dev/null +++ b/frontend/src/components/settings/AgentsEditor.test.tsx @@ -0,0 +1,96 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { AgentsEditor } from './AgentsEditor' + +vi.mock('./AgentDialog', () => ({ + AgentDialog: ({ open, editingAgent }: { open: boolean; editingAgent?: { name: string } | null }) => + open ?
{editingAgent ? 'Edit Agent' : 'Create Agent'}
: null, +})) + +const mockAgents = { + 'code-reviewer': { + description: 'Reviews code changes', + mode: 'subagent' as const, + }, + 'helper': { + description: 'General helper agent', + mode: 'primary' as const, + disable: true, + }, +} + +describe('AgentsEditor', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('renders empty state when no agents configured', () => { + const onChange = vi.fn() + render() + + expect(screen.getByText('No agents configured')).toBeInTheDocument() + expect(screen.getByText('Add your first agent to get started.')).toBeInTheDocument() + }) + + it('renders agent names', () => { + const onChange = vi.fn() + render() + + expect(screen.getByText('code-reviewer')).toBeInTheDocument() + expect(screen.getByText('helper')).toBeInTheDocument() + }) + + it('opens AgentDialog when clicking Edit on a row', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + const editButtons = screen.getAllByText('Edit') + await user.click(editButtons[0]) + + expect(screen.getByTestId('agent-dialog')).toBeInTheDocument() + expect(screen.getByText('Edit Agent')).toBeInTheDocument() + }) + + it('opens AgentDialog when clicking row body', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + await user.click(screen.getByText('code-reviewer')) + + expect(screen.getByTestId('agent-dialog')).toBeInTheDocument() + }) + + it('opens AgentDialog and displays Create Agent text when clicking Add Agent button', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + await user.click(screen.getByText('Add Agent')) + + expect(screen.getByTestId('agent-dialog')).toBeInTheDocument() + expect(screen.getByText('Create Agent')).toBeInTheDocument() + }) + + it('calls onChange with agent removed when Delete is clicked from overflow menu', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + await user.click(screen.getByLabelText('Actions for code-reviewer')) + await user.click(screen.getByText('Delete')) + + expect(onChange).toHaveBeenCalledTimes(1) + expect(onChange).toHaveBeenCalledWith({ helper: mockAgents.helper }) + }) + + it('renders mode and disabled badges for agents', () => { + const onChange = vi.fn() + render() + + expect(screen.getByText('subagent')).toBeInTheDocument() + expect(screen.getByText('Disabled')).toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/settings/AgentsEditor.tsx b/frontend/src/components/settings/AgentsEditor.tsx index b39dcafa..e567f423 100644 --- a/frontend/src/components/settings/AgentsEditor.tsx +++ b/frontend/src/components/settings/AgentsEditor.tsx @@ -1,8 +1,9 @@ import { useState } from 'react' -import { Plus, Trash2, Edit } from 'lucide-react' +import { Plus } from 'lucide-react' import { Button } from '@/components/ui/button' -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Badge } from '@/components/ui/badge' import { Dialog, DialogTrigger } from '@/components/ui/dialog' +import { SettingsList, SettingsListRow } from '@/components/ui/settings-list' import { AgentDialog } from './AgentDialog' interface Agent { @@ -61,12 +62,12 @@ export function AgentsEditor({ agents, onChange }: AgentsEditorProps) { return (
-
-

Agents

+
-
- {Object.keys(agents).length === 0 ? ( - - -

No agents configured. Add your first agent to get started.

-
-
- ) : ( -
- {Object.entries(agents).map(([name, agent]) => ( - - -
- {name} -
- - -
-
-
- -
- {agent.description && ( -

{agent.description}

- )} -
-

Mode: {agent.mode}

- {agent.temperature !== undefined &&

Temperature: {agent.temperature}

} - {agent.topP !== undefined &&

Top P: {agent.topP}

} - {agent.model &&

Model: {agent.model}

} - {agent.disable &&

Status: Disabled

} -
- {agent.prompt && ( -
- {agent.prompt} -
- )} -
-
-
- ))} -
- )} + + {Object.entries(agents).map(([name, agent]) => ( + + {agent.mode && {agent.mode}} + {agent.disable && Disabled} + + } + onClick={() => startEdit(name, agent)} + primaryAction={{ label: 'Edit', onClick: () => startEdit(name, agent) }} + actions={[{ label: 'Delete', destructive: true, onClick: () => deleteAgent(name) }]} + actionsLabel={`Actions for ${name}`} + /> + ))} + ({ + CommandDialog: ({ open, editingCommand }: { open: boolean; editingCommand?: { name: string } | null }) => + open ?
{editingCommand ? 'Edit Command' : 'Create Command'}
: null, +})) + +const mockCommands = { + 'review': { + template: 'Review this code', + description: 'Reviews code changes', + agent: 'code-reviewer', + }, + 'build': { + template: 'Build the project', + description: 'Builds the project', + }, +} + +describe('CommandsEditor', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('renders empty state when no commands configured', () => { + const onChange = vi.fn() + render() + + expect(screen.getByText('No commands configured')).toBeInTheDocument() + expect(screen.getByText('Add your first command to get started.')).toBeInTheDocument() + }) + + it('renders command names with leading slash', () => { + const onChange = vi.fn() + render() + + expect(screen.getByText('/review')).toBeInTheDocument() + expect(screen.getByText('/build')).toBeInTheDocument() + }) + + it('opens CommandDialog when clicking Edit on a row', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + const editButtons = screen.getAllByText('Edit') + await user.click(editButtons[0]) + + expect(screen.getByTestId('command-dialog')).toBeInTheDocument() + expect(screen.getByText('Edit Command')).toBeInTheDocument() + }) + + it('opens CommandDialog when clicking row body', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + await user.click(screen.getByText('/review')) + + expect(screen.getByTestId('command-dialog')).toBeInTheDocument() + }) + + it('opens CommandDialog and displays Create Command text when clicking Add Command button', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + await user.click(screen.getByText('Add Command')) + + expect(screen.getByTestId('command-dialog')).toBeInTheDocument() + expect(screen.getByText('Create Command')).toBeInTheDocument() + }) + + it('calls onChange with command removed when Delete is clicked from overflow menu', async () => { + const user = userEvent.setup() + const onChange = vi.fn() + render() + + await user.click(screen.getByLabelText('Actions for /review')) + await user.click(screen.getByText('Delete')) + + expect(onChange).toHaveBeenCalledTimes(1) + expect(onChange).toHaveBeenCalledWith({ build: mockCommands.build }) + }) + + it('renders agent badge when command has agent', () => { + const onChange = vi.fn() + render() + + expect(screen.getByText('code-reviewer')).toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/settings/CommandsEditor.tsx b/frontend/src/components/settings/CommandsEditor.tsx index b9d0ec74..0742ebf2 100644 --- a/frontend/src/components/settings/CommandsEditor.tsx +++ b/frontend/src/components/settings/CommandsEditor.tsx @@ -1,8 +1,9 @@ import { useState } from 'react' -import { Plus, Trash2, Edit } from 'lucide-react' +import { Plus } from 'lucide-react' import { Button } from '@/components/ui/button' -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Badge } from '@/components/ui/badge' import { Dialog, DialogTrigger } from '@/components/ui/dialog' +import { SettingsList, SettingsListRow } from '@/components/ui/settings-list' import { CommandDialog } from './CommandDialog' interface Command { @@ -36,6 +37,7 @@ export function CommandsEditor({ commands, onChange }: CommandsEditorProps) { [name]: command } onChange(updatedCommands) + setIsCreateDialogOpen(false) } } @@ -51,13 +53,12 @@ export function CommandsEditor({ commands, onChange }: CommandsEditorProps) { return (
-
-

Commands

+
-
- {Object.keys(commands).length === 0 ? ( - - -

No commands configured. Add your first command to get started.

-
-
- ) : ( -
- {Object.entries(commands).map(([name, command]) => ( - - -
- /{name} -
- - -
-
-
- -
- {command.description && ( -

{command.description}

- )} -
- {command.agent &&

Agent: {command.agent}

} - {command.model &&

Model: {command.model}

} - {command.topP !== undefined &&

Top P: {command.topP}

} - {command.subtask &&

Subtask: Yes

} -
-
- {command.template} -
-
-
-
- ))} -
- )} + + {Object.entries(commands).map(([name, command]) => ( + {command.agent} + } + onClick={() => startEdit(name, command)} + primaryAction={{ label: 'Edit', onClick: () => startEdit(name, command) }} + actions={[{ label: 'Delete', destructive: true, onClick: () => deleteCommand(name) }]} + actionsLabel={`Actions for /${name}`} + /> + ))} +
)} -
-
-

MCP Servers

-

- Manage Model Context Protocol servers for {config.name} -

-
-
- - - - - - - -
+
+ + + + + + +
- {Object.keys(mcpServers).length === 0 ? ( -
-

No MCP servers configured. Add your first server to get started.

-
- ) : ( -
- {Object.entries(mcpServers).map(([serverId, serverConfig]) => { - const status = mcpStatus?.[serverId] - const isConnected = status?.status === 'connected' - const errorMessage = getErrorMessage(serverId) - - return ( - setDeleteConfirmServer({ id, name })} - /> - ) - })} -
- )} + + {Object.entries(mcpServers).map(([serverId, serverConfig]) => { + const status = mcpStatus?.[serverId] + const isConnected = status?.status === 'connected' + const errorMessage = getErrorMessage(serverId) + + return ( + setDeleteConfirmServer({ id, name })} + /> + ) + })} + { + it('renders display name and description', () => { + render( + , + ) + + expect(screen.getByText('My test server')).toBeInTheDocument() + expect(screen.getByText('Remote server: https://example.com/mcp')).toBeInTheDocument() + }) + + it('renders the Connected status badge', () => { + render( + , + ) + + expect(screen.getByText('Connected')).toBeInTheDocument() + }) + + it('renders the toggle Switch when not awaiting auth', () => { + render( + , + ) + + const switches = screen.getAllByRole('switch') + expect(switches.length).toBeGreaterThanOrEqual(1) + }) + + it('calls onDeleteServer when Delete Server is clicked from overflow menu', async () => { + const user = userEvent.setup() + const onDeleteServer = vi.fn() + + render( + , + ) + + await user.click(screen.getByLabelText('Actions for My test server')) + await user.click(screen.getByText('Delete Server')) + + expect(onDeleteServer).toHaveBeenCalledTimes(1) + expect(onDeleteServer).toHaveBeenCalledWith('my-test-server', 'My test server') + }) +}) diff --git a/frontend/src/components/settings/McpServerCard.tsx b/frontend/src/components/settings/McpServerCard.tsx index d2dd0a5a..faf6e737 100644 --- a/frontend/src/components/settings/McpServerCard.tsx +++ b/frontend/src/components/settings/McpServerCard.tsx @@ -1,9 +1,8 @@ import { Badge } from '@/components/ui/badge' import { Switch } from '@/components/ui/switch' import { Button } from '@/components/ui/button' -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' -import { DropdownMenuSeparator } from '@/components/ui/dropdown-menu' -import { XCircle, AlertCircle, Key, MoreVertical, Shield, Trash2, RefreshCw } from 'lucide-react' +import { SettingsListRow, type SettingsListRowAction } from '@/components/ui/settings-list' +import { XCircle, AlertCircle, Key, Shield, Trash2, RefreshCw } from 'lucide-react' import type { McpStatus, McpServerConfig } from '@/api/mcp' interface McpServerCardProps { @@ -101,11 +100,23 @@ export function McpServerCard({ const showAuthButton = needsAuth || (isOAuthServer && status?.status === 'failed') const displayName = getServerDisplayName(serverId) + const actions: SettingsListRowAction[] = [] + if (showAuthButton && onAuthenticate) { + actions.push({ label: 'Authenticate', onClick: () => onAuthenticate(serverId), icon: }) + } + if (connectedWithOAuth && onAuthenticate) { + actions.push({ label: 'Re-authenticate', onClick: () => onAuthenticate(serverId), icon: }) + } + if (connectedWithOAuth && onRemoveAuth) { + actions.push({ label: isRemovingAuth ? 'Removing...' : 'Remove Auth', onClick: () => onRemoveAuth(serverId), icon: , disabled: isRemovingAuth }) + } + actions.push({ label: 'Delete Server', onClick: () => onDeleteServer(serverId, displayName), icon: , destructive: true, separatorBefore: showAuthButton || connectedWithOAuth }) + return ( -
-
-
-

{displayName}

+ {connectedWithOAuth && ( @@ -114,20 +125,17 @@ export function McpServerCard({ {status ? getStatusBadge(status) : ( Loading... )} + + } + description={getServerDescription(serverConfig)} + belowDescription={errorMessage ? ( +
+ + {errorMessage}
-

- {getServerDescription(serverConfig)} -

- {errorMessage && ( -
- - {errorMessage} -
- )} -
- -
- {showAuthButton && onAuthenticate ? ( + ) : undefined} + trailing={ + showAuthButton && onAuthenticate ? ( - - - {showAuthButton && onAuthenticate && ( - setTimeout(() => onAuthenticate(serverId), 0)}> - - Authenticate - - )} - {connectedWithOAuth && onAuthenticate && ( - setTimeout(() => onAuthenticate(serverId), 0)}> - - Re-authenticate - - )} - {connectedWithOAuth && onRemoveAuth && ( - setTimeout(() => onRemoveAuth(serverId), 0)} - disabled={isRemovingAuth} - > - - {isRemovingAuth ? 'Removing...' : 'Remove Auth'} - - )} - {(showAuthButton || connectedWithOAuth) && } - { - setTimeout(() => onDeleteServer(serverId, displayName), 0) - }} - className="text-red-600" - > - - Delete Server - - - -
-
+ ) + } + actions={actions} + actionsLabel={`Actions for ${displayName}`} + /> ) } diff --git a/frontend/src/components/settings/OpenCodeConfigManager.test.tsx b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx new file mode 100644 index 00000000..d9d7b594 --- /dev/null +++ b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx @@ -0,0 +1,141 @@ +import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest' +import { act, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { OpenCodeConfigManager } from './OpenCodeConfigManager' +import type { OpenCodeConfig } from '@/api/types/settings' + +const { + mockGetOpenCodeConfigs, + mockUpdateOpenCodeConfig, + mockRestartOpenCodeServer, + mockGetOpenCodeImportStatus, + mockListManagedSkills, +} = vi.hoisted(() => ({ + mockGetOpenCodeConfigs: vi.fn(), + mockUpdateOpenCodeConfig: vi.fn(), + mockRestartOpenCodeServer: vi.fn(), + mockGetOpenCodeImportStatus: vi.fn(), + mockListManagedSkills: vi.fn(), +})) + +vi.mock('@/hooks/useServerHealth', () => ({ + useServerHealth: () => ({ data: { opencode: 'healthy' } }), +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() }, +})) + +vi.mock('@/api/settings', () => ({ + settingsApi: { + getOpenCodeConfigs: mockGetOpenCodeConfigs, + updateOpenCodeConfig: mockUpdateOpenCodeConfig, + restartOpenCodeServer: mockRestartOpenCodeServer, + getOpenCodeImportStatus: mockGetOpenCodeImportStatus, + listManagedSkills: mockListManagedSkills, + syncOpenCodeImport: vi.fn(), + upgradeOpenCode: vi.fn(), + }, +})) + +const defaultConfig: OpenCodeConfig = { + id: 1, + name: 'default', + isDefault: true, + isValid: true, + createdAt: 1, + updatedAt: 1, + content: { + provider: { + openai: { + name: 'OpenAI', + models: { + 'gpt-4o': { name: 'GPT-4o' }, + }, + }, + }, + }, +} + +function renderWithQuery(ui: React.ReactElement) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render({ui}) +} + +describe('OpenCodeConfigManager', () => { + beforeAll(() => { + Element.prototype.scrollIntoView = vi.fn() + }) + + beforeEach(() => { + vi.clearAllMocks() + mockGetOpenCodeConfigs.mockResolvedValue({ configs: [defaultConfig] }) + mockGetOpenCodeImportStatus.mockResolvedValue({}) + mockListManagedSkills.mockResolvedValue([]) + mockUpdateOpenCodeConfig.mockResolvedValue(defaultConfig) + mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' }) + }) + + it('optimistic delete + restart prompt', async () => { + let resolveUpdate: (config: OpenCodeConfig) => void = () => {} + mockUpdateOpenCodeConfig.mockImplementationOnce(() => new Promise((resolve) => { + resolveUpdate = resolve + })) + + const user = userEvent.setup() + renderWithQuery() + + await screen.findByText('GPT-4o') + + await user.click(screen.getByRole('button', { name: /Models/i })) + + await user.click(screen.getByLabelText('Actions for GPT-4o')) + await user.click(screen.getByText('Delete')) + + expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1) + const [configName, payload] = mockUpdateOpenCodeConfig.mock.calls[0] + expect(configName).toBe('default') + expect(payload.content.provider.openai.models).not.toHaveProperty('gpt-4o') + + await screen.findByText('Restart OpenCode Server?') + expect(screen.getByRole('button', { name: /saving/i })).toBeDisabled() + + await act(async () => { + resolveUpdate(defaultConfig) + }) + + await vi.waitFor(() => { + expect(screen.getByRole('button', { name: /restart now/i })).not.toBeDisabled() + }) + + await user.click(screen.getByRole('button', { name: /restart now/i })) + + expect(mockRestartOpenCodeServer).toHaveBeenCalledTimes(1) + }) + + it('rollback on failure', async () => { + mockUpdateOpenCodeConfig.mockRejectedValueOnce(new Error('boom')) + + const user = userEvent.setup() + renderWithQuery() + + await screen.findByText('GPT-4o') + + await user.click(screen.getByRole('button', { name: /Models/i })) + + await user.click(screen.getByLabelText('Actions for GPT-4o')) + await user.click(screen.getByText('Delete')) + + expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1) + + const { showToast } = await import('@/lib/toast') + await vi.waitFor(() => { + expect(showToast.error).toHaveBeenCalled() + }) + + expect(screen.getByText('GPT-4o')).toBeInTheDocument() + + expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index d9ae1046..8fe113bb 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -8,6 +8,7 @@ import { Badge } from '@/components/ui/badge' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' import { DeleteDialog } from '@/components/ui/delete-dialog' +import { RestartServerDialog } from './RestartServerDialog' import { CreateConfigDialog } from './CreateConfigDialog' import { OpenCodeConfigEditor } from './OpenCodeConfigEditor' import { CommandsEditor } from './CommandsEditor' @@ -78,6 +79,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf const [isEditDialogOpen, setIsEditDialogOpen] = useState(false) const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false) const [deleteConfirmConfig, setDeleteConfirmConfig] = useState(null) + const [isRestartPromptOpen, setIsRestartPromptOpen] = useState(false) const agentsMdRef = useRef(null) const commandsRef = useRef(null) @@ -232,58 +234,44 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf } } - const updateConfigContent = async (configName: string, newContent: Record, restartServer = false) => { + const updateConfigContent = async (configName: string, newContent: Record) => { + const previousConfig = configs.find(c => c.name === configName) + const previousContent = previousConfig?.content + const previousSelectedConfig = selectedConfig + const shouldPromptRestart = Boolean(previousConfig?.isDefault) + const now = Date.now() + + setConfigs(prev => prev.map(config => + config.name === configName ? { ...config, content: newContent, updatedAt: now } : config + )) + if (selectedConfig && selectedConfig.name === configName) { + setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: now }) + } + if (shouldPromptRestart) { + setIsRestartPromptOpen(true) + } + try { setIsUpdating(true) - const previousConfig = configs.find(c => c.name === configName) - const previousContent = previousConfig?.content - const result = await settingsApi.updateOpenCodeConfig(configName, { content: newContent }) - - setConfigs(prev => prev.map(config => - config.name === configName - ? { ...config, content: newContent, updatedAt: Date.now() } - : config - )) - - if (selectedConfig && selectedConfig.name === configName) { - setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: Date.now() }) - } - - const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent) - const pluginsChanged = JSON.stringify(previousContent?.plugin) !== JSON.stringify(newContent.plugin) - const skillsChanged = JSON.stringify(previousContent?.skills) !== JSON.stringify(newContent.skills) - const providersChanged = JSON.stringify(previousContent?.provider) !== JSON.stringify(newContent.provider) - const defaultConfigChanged = Boolean(previousConfig?.isDefault && (agentsChanged || pluginsChanged || skillsChanged || providersChanged)) - if (restartServer || defaultConfigChanged) { - showToast.loading(restartServer ? 'Restarting server...' : 'Applying server configuration...', { id: 'update-restart' }) - try { - if (restartServer && !defaultConfigChanged) { - await restartServerMutation.mutateAsync() - } - if (result.removedFields && result.removedFields.length > 0) { - showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'update-restart' }) - } else if (pluginsChanged || restartServer) { - showToast.success('Configuration updated and server restarted', { id: 'update-restart' }) - } else { - showToast.success('Configuration updated and server applied', { id: 'update-restart' }) - } - invalidateConfigCaches(queryClient) - } catch (error) { - showToast.error(getRestartErrorMessage(error), { id: 'update-restart' }) - throw error - } + if (result.removedFields && result.removedFields.length > 0) { + showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`) } else { - if (result.removedFields && result.removedFields.length > 0) { - showToast.info(`Configuration applied after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'update-restart' }) - } else { - showToast.success('Configuration updated') - } - invalidateConfigCaches(queryClient) + showToast.success('Configuration updated') } + invalidateConfigCaches(queryClient) } catch (error) { + setConfigs(prev => prev.map(config => + config.name === configName ? { ...config, content: previousContent ?? {}, updatedAt: previousConfig?.updatedAt ?? now } : config + )) + if (previousSelectedConfig && previousSelectedConfig.name === configName) { + setSelectedConfig(previousSelectedConfig) + } + if (shouldPromptRestart) { + setIsRestartPromptOpen(false) + } console.error('Failed to update config:', error) - showToast.error(getApiErrorMessage(error, 'Failed to update config'), { id: 'update-restart' }) + showToast.error(getApiErrorMessage(error, 'Failed to update config')) } finally { setIsUpdating(false) } @@ -1053,6 +1041,24 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf itemName={deleteConfirmConfig?.name} isDeleting={isUpdating} /> + + setIsRestartPromptOpen(false)} + onConfirm={async () => { + showToast.loading('Restarting OpenCode server...', { id: 'config-restart' }) + try { + await restartServerMutation.mutateAsync() + showToast.success('Server restarted successfully', { id: 'config-restart' }) + setIsRestartPromptOpen(false) + } catch (error) { + showToast.error(getRestartErrorMessage(error), { id: 'config-restart' }) + } + }} + />
) } diff --git a/frontend/src/components/settings/OpenCodeModelsEditor.test.tsx b/frontend/src/components/settings/OpenCodeModelsEditor.test.tsx index e47d1fa8..6c2c36f6 100644 --- a/frontend/src/components/settings/OpenCodeModelsEditor.test.tsx +++ b/frontend/src/components/settings/OpenCodeModelsEditor.test.tsx @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' import { OpenCodeModelsEditor } from './OpenCodeModelsEditor' import type { ConfigProvider, ConfigModel } from './OpenCodeModelsEditor' @@ -24,17 +25,6 @@ const mockProviders: Record = { }, } -const findTrashButton = (): HTMLButtonElement | null => { - const buttons = Array.from(document.querySelectorAll('button')) - for (const btn of buttons) { - const svg = btn.querySelector('svg') - if (svg && svg.getAttribute('class')?.includes('trash')) { - return btn - } - } - return null -} - describe('OpenCodeModelsEditor', () => { describe('rendering', () => { it('should render empty state when no providers configured', () => { @@ -51,7 +41,7 @@ describe('OpenCodeModelsEditor', () => { expect(screen.getByText('OpenAI')).toBeInTheDocument() expect(screen.getByText('Anthropic')).toBeInTheDocument() - const modelCountSpans = screen.getAllByText(/\(1 model\)/) + const modelCountSpans = screen.getAllByText(/1 model/) expect(modelCountSpans.length).toBe(2) }) @@ -75,15 +65,13 @@ describe('OpenCodeModelsEditor', () => { }) describe('delete model', () => { - it('should call onChange with updated providers when model is deleted', () => { + it('should call onChange with updated providers when model is deleted', async () => { const onChange = vi.fn() + const user = userEvent.setup() render() - const deleteButton = findTrashButton() - expect(deleteButton).not.toBeNull() - if (deleteButton) { - fireEvent.click(deleteButton) - } + await user.click(screen.getByLabelText('Actions for GPT-4o')) + await user.click(screen.getByText('Delete')) expect(onChange).toHaveBeenCalled() const updatedProviders = onChange.mock.calls[0][0] @@ -93,7 +81,7 @@ describe('OpenCodeModelsEditor', () => { }) describe('model content structure', () => { - it('should preserve provider structure when models change', () => { + it('should preserve provider structure when models change', async () => { const onChange = vi.fn() const providersWithExtras: Record = { openai: { @@ -108,12 +96,11 @@ describe('OpenCodeModelsEditor', () => { }, } + const user = userEvent.setup() render() - const deleteButton = findTrashButton() - if (deleteButton) { - fireEvent.click(deleteButton) - } + await user.click(screen.getByLabelText('Actions for GPT-4o')) + await user.click(screen.getByText('Delete')) expect(onChange).toHaveBeenCalled() const updatedProviders = onChange.mock.calls[0][0] diff --git a/frontend/src/components/settings/OpenCodeModelsEditor.tsx b/frontend/src/components/settings/OpenCodeModelsEditor.tsx index deeaf3d5..ebba4b4c 100644 --- a/frontend/src/components/settings/OpenCodeModelsEditor.tsx +++ b/frontend/src/components/settings/OpenCodeModelsEditor.tsx @@ -1,8 +1,8 @@ import { useMemo, useState } from 'react' -import { Plus, Trash2, Edit, Box } from 'lucide-react' +import { Plus, Box } from 'lucide-react' import { Button } from '@/components/ui/button' -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Dialog, DialogTrigger } from '@/components/ui/dialog' +import { SettingsList, SettingsListRow } from '@/components/ui/settings-list' import { OpenCodeModelDialog, type NewProviderConfig } from './OpenCodeModelDialog' import type { ModelConfig, ProviderConfig } from '@/api/types/settings' @@ -142,12 +142,12 @@ export function OpenCodeModelsEditor({ providers, onChange }: OpenCodeModelsEdit return (
-
-

Models

+
- {totalModelCount === 0 ? ( - - -

- No models configured. Add your first model to get started. -

-
-
+ +
+ ) : ( -
+
{providerEntries.map(({ providerId, providerName, models }) => { const modelEntries = Object.entries(models) if (modelEntries.length === 0) return null return ( - - -
- - - {providerName} - - ({modelEntries.length} model{modelEntries.length !== 1 ? 's' : ''}) - - -
-
- +
+
+ + {providerName} + {modelEntries.length} model{modelEntries.length !== 1 ? 's' : ''} +
+ {modelEntries.map(([modelId, model]) => ( -
-
-

{model.name || modelId}

-

- {modelId} + title={model.name || modelId} + description={{modelId}} + belowDescription={(model.limit?.context || model.limit?.output) && ( +

+ Limits: {model.limit?.context && `Context ${model.limit.context}`}{model.limit?.context && model.limit?.output && ' / '}{model.limit?.output && `Output ${model.limit.output}`}

- {(model.limit?.context || model.limit?.output) && ( -

- Limits:{' '} - {model.limit.context && `Context ${model.limit.context}`} - {model.limit.context && model.limit.output && ' / '} - {model.limit.output && `Output ${model.limit.output}`} -

- )} -
-
- - -
-
+ )} + onClick={() => startEdit(providerId, modelId, model)} + primaryAction={{ label: 'Edit', onClick: () => startEdit(providerId, modelId, model) }} + actions={[{ label: 'Delete', destructive: true, onClick: () => deleteModel(providerId, modelId) }]} + actionsLabel={`Actions for ${model.name || modelId}`} + /> ))} - - +
+
) })}
diff --git a/frontend/src/components/settings/RestartServerDialog.test.tsx b/frontend/src/components/settings/RestartServerDialog.test.tsx new file mode 100644 index 00000000..5125e004 --- /dev/null +++ b/frontend/src/components/settings/RestartServerDialog.test.tsx @@ -0,0 +1,69 @@ +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { RestartServerDialog } from './RestartServerDialog' + +const baseProps = { + open: true, + onOpenChange: vi.fn(), + onConfirm: vi.fn(), + onCancel: vi.fn(), +} + +describe('RestartServerDialog', () => { + it('renders the title and description when open is true', () => { + render() + + expect(screen.getByText('Restart OpenCode Server?')).toBeInTheDocument() + expect( + screen.getByText(/Restart the OpenCode server after your changes are saved to apply them to the running server\./) + ).toBeInTheDocument() + }) + + it('renders nothing visible when open is false', () => { + render() + + expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument() + }) + + it('calls onConfirm when Restart now is clicked', async () => { + const onConfirm = vi.fn() + const user = userEvent.setup() + render() + + await user.click(screen.getByRole('button', { name: /restart now/i })) + expect(onConfirm).toHaveBeenCalled() + }) + + it('calls onCancel when Later is clicked', async () => { + const onCancel = vi.fn() + const user = userEvent.setup() + render() + + await user.click(screen.getByRole('button', { name: /later/i })) + expect(onCancel).toHaveBeenCalled() + }) + + it('disables confirm button and shows Restarting... when isRestarting is true', () => { + render() + + const confirmButton = screen.getByRole('button', { name: /restarting/i }) + expect(confirmButton).toBeDisabled() + expect(screen.getByText('Restarting...')).toBeInTheDocument() + }) + + it('disables confirm button and shows Saving... when isSaving is true', () => { + render() + + const confirmButton = screen.getByRole('button', { name: /saving/i }) + expect(confirmButton).toBeDisabled() + expect(screen.getByText('Saving...')).toBeInTheDocument() + }) + + it('disables Later button when isRestarting is true', () => { + render() + + const laterButton = screen.getByRole('button', { name: /later/i }) + expect(laterButton).toBeDisabled() + }) +}) diff --git a/frontend/src/components/settings/RestartServerDialog.tsx b/frontend/src/components/settings/RestartServerDialog.tsx new file mode 100644 index 00000000..bfea86e6 --- /dev/null +++ b/frontend/src/components/settings/RestartServerDialog.tsx @@ -0,0 +1,56 @@ +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Loader2 } from 'lucide-react' + +interface RestartServerDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + onConfirm: () => void + onCancel: () => void + isSaving?: boolean + isRestarting?: boolean +} + +export function RestartServerDialog({ + open, + onOpenChange, + onConfirm, + onCancel, + isSaving = false, + isRestarting = false, +}: RestartServerDialogProps) { + const isConfirmDisabled = isSaving || isRestarting + + return ( + + + + Restart OpenCode Server? + + Restart the OpenCode server after your changes are saved to apply them to the running server. + + + + + + + + + ) +} diff --git a/frontend/src/components/skills/SkillLibraryList.tsx b/frontend/src/components/skills/SkillLibraryList.tsx index fd569b40..0bcdcfc6 100644 --- a/frontend/src/components/skills/SkillLibraryList.tsx +++ b/frontend/src/components/skills/SkillLibraryList.tsx @@ -1,14 +1,9 @@ import { useMemo, useState } from 'react' -import { AlertCircle, Loader2, MoreHorizontal, Search } from 'lucide-react' +import { Search } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Badge } from '@/components/ui/badge' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu' +import { SettingsList, SettingsListRow } from '@/components/ui/settings-list' import type { SkillFileInfo, SkillScope } from '@opencode-manager/shared' type SkillFilter = 'all' | SkillScope @@ -100,77 +95,38 @@ export function SkillLibraryList({
- {isLoading ? ( -
- - Loading... -
- ) : error ? ( -
- -

Failed to load skills

-

{error.message}

-
- ) : filteredSkills.length === 0 ? ( -
-

{emptyTitle || 'No skills available'}

-

{emptyHint || 'Create or install a skill to get started.'}

-
- ) : ( -
-
- {filteredSkills.map((skill) => ( -
primaryAction.onClick(skill) : undefined} - className={`group flex flex-col gap-2 bg-card px-3 py-3 hover:bg-accent/50 sm:flex-row sm:items-center sm:gap-3 ${primaryAction ? 'cursor-pointer' : ''}`} - > -
-
-

{skill.name}

- - {getCompactScopeLabel(skill)} - - - {getScopeLabel(skill)} - -
- {skill.description && ( -

{skill.description}

- )} -
-
event.stopPropagation()}> - {primaryAction && ( - - )} - {rowActions.length > 0 && ( - - - - - - {rowActions.map((action) => ( - action.onClick(skill)} - className={action.destructive ? 'text-destructive focus:text-destructive' : undefined} - > - {action.label} - - ))} - - - )} -
-
- ))} -
-
- )} + + {filteredSkills.map((skill) => ( + primaryAction.onClick(skill) : undefined} + primaryAction={primaryAction ? { label: primaryAction.label, onClick: () => primaryAction.onClick(skill) } : undefined} + actions={rowActions.map((a) => ({ label: a.label, destructive: a.destructive, onClick: () => a.onClick(skill) }))} + actionsLabel={`Actions for ${skill.name}`} + badges={ + <> + + {getCompactScopeLabel(skill)} + + + {getScopeLabel(skill)} + + + } + /> + ))} +
) } diff --git a/frontend/src/components/ui/settings-list.test.tsx b/frontend/src/components/ui/settings-list.test.tsx new file mode 100644 index 00000000..4a02b67c --- /dev/null +++ b/frontend/src/components/ui/settings-list.test.tsx @@ -0,0 +1,105 @@ +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, it, expect, vi } from 'vitest' +import { SettingsList, SettingsListRow } from './settings-list' + +describe('SettingsList', () => { + it('renders emptyTitle and emptyHint when isEmpty and no children visible', () => { + render( + +
child
+
, + ) + expect(screen.getByText('Nothing here')).toBeInTheDocument() + expect(screen.getByText('Try adding something')).toBeInTheDocument() + expect(screen.queryByText('child')).not.toBeInTheDocument() + }) + + it('renders loadingLabel when isLoading', () => { + render( + +
child
+
, + ) + expect(screen.getByText('Please wait...')).toBeInTheDocument() + }) + + it('renders error.message when error passed', () => { + render( + +
child
+
, + ) + expect(screen.getByText('Something broke')).toBeInTheDocument() + }) +}) + +describe('SettingsListRow', () => { + it('renders title, description, and badges content', () => { + render( + Badge} + />, + ) + expect(screen.getByText('Row Title')).toBeInTheDocument() + expect(screen.getByText('Row description')).toBeInTheDocument() + expect(screen.getByTestId('badge')).toHaveTextContent('Badge') + }) + + it('calls primaryAction.onClick when primary action button is clicked', async () => { + const user = userEvent.setup() + const onClick = vi.fn() + render() + + await user.click(screen.getByText('Do It')) + expect(onClick).toHaveBeenCalledTimes(1) + }) + + it('fires row onClick when row body is clicked and does not fire when action-column button is clicked', async () => { + const user = userEvent.setup() + const rowClick = vi.fn() + const primaryClick = vi.fn() + + render( + , + ) + + await user.click(screen.getByText('Row')) + expect(rowClick).toHaveBeenCalledTimes(1) + + await user.click(screen.getByText('Action')) + expect(primaryClick).toHaveBeenCalledTimes(1) + expect(rowClick).toHaveBeenCalledTimes(1) + }) + + it('opens overflow menu and clicking action calls onClick; destructive item has text-destructive class', async () => { + const user = userEvent.setup() + const actionClick = vi.fn() + + render( + , + ) + + await user.click(screen.getByLabelText('More options')) + + const deleteItem = screen.getByText('Delete') + expect(deleteItem).toBeInTheDocument() + expect(deleteItem.closest('div[class*="text-destructive"]')).toBeInTheDocument() + + await user.click(deleteItem) + expect(actionClick).toHaveBeenCalledTimes(1) + }) +}) diff --git a/frontend/src/components/ui/settings-list.tsx b/frontend/src/components/ui/settings-list.tsx new file mode 100644 index 00000000..e239eb78 --- /dev/null +++ b/frontend/src/components/ui/settings-list.tsx @@ -0,0 +1,161 @@ +import { Fragment, type ReactNode } from 'react' +import { MoreHorizontal, Loader2, AlertCircle } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu' +import { cn } from '@/lib/utils' + +export interface SettingsListRowAction { + label: string + onClick: () => void + icon?: ReactNode + destructive?: boolean + disabled?: boolean + separatorBefore?: boolean +} + +interface SettingsListProps { + isLoading?: boolean + error?: Error | null + isEmpty: boolean + emptyTitle?: string + emptyHint?: string + loadingLabel?: string + errorTitle?: string + maxHeightClassName?: string + children: ReactNode +} + +interface SettingsListRowProps { + title: ReactNode + titleClassName?: string + description?: ReactNode + badges?: ReactNode + belowDescription?: ReactNode + trailing?: ReactNode + primaryAction?: { label: string; onClick: () => void } + actions?: SettingsListRowAction[] + actionsLabel?: string + onClick?: () => void + className?: string +} + +export function SettingsList({ + isLoading, + error, + isEmpty, + emptyTitle, + emptyHint, + loadingLabel, + errorTitle, + maxHeightClassName, + children, +}: SettingsListProps) { + if (isLoading) { + return ( +
+ + {loadingLabel ?? 'Loading...'} +
+ ) + } + + if (error) { + return ( +
+ +

{errorTitle ?? 'Failed to load'}

+

{error.message}

+
+ ) + } + + if (isEmpty) { + return ( +
+

{emptyTitle}

+

{emptyHint}

+
+ ) + } + + return ( +
+
{children}
+
+ ) +} + +export function SettingsListRow({ + title, + titleClassName, + description, + badges, + belowDescription, + trailing, + primaryAction, + actions, + actionsLabel, + onClick, + className, +}: SettingsListRowProps) { + return ( +
+
+
+

{title}

+ {badges} +
+ {description &&
{description}
} + {belowDescription} +
+
e.stopPropagation()} + > + {trailing} + {primaryAction && ( + + )} + {actions && actions.length > 0 && ( + + + + + + {actions.map((action, i) => ( + + {action.separatorBefore && i > 0 && } + setTimeout(action.onClick, 0)} + className={action.destructive ? 'text-destructive focus:text-destructive' : undefined} + > + {action.icon} + {action.label} + + + ))} + + + )} +
+
+ ) +}