mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
refactor: extract SettingsList component and unify settings editor layouts (#280)
This commit is contained in:
1 parent
6e80cdfb8c
commit
d268182610
16 files changed
+1105
-453
No files matched your search
@@ -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 ? <div data-testid="agent-dialog">{editingAgent ? 'Edit Agent' : 'Create Agent'}</div> : 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(<AgentsEditor agents={{}} onChange={onChange} />)
|
||||
|
||||
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(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
|
||||
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(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
|
||||
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(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
|
||||
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(<AgentsEditor agents={{}} onChange={onChange} />)
|
||||
|
||||
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(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
|
||||
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(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
|
||||
expect(screen.getByText('subagent')).toBeInTheDocument()
|
||||
expect(screen.getByText('Disabled')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -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 (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Agents</h3>
|
||||
<div className="flex items-center justify-end">
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className='mr-1 h-6'>
|
||||
<Plus className="h-4 w-4" />
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add Agent
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<AgentDialog
|
||||
@@ -77,61 +78,30 @@ export function AgentsEditor({ agents, onChange }: AgentsEditorProps) {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{Object.keys(agents).length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="p-2 sm:p-8 text-center">
|
||||
<p className="text-muted-foreground">No agents configured. Add your first agent to get started.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
{Object.entries(agents).map(([name, agent]) => (
|
||||
<Card key={name}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">{name}</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => startEdit(name, agent)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteAgent(name)}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className='p-2'>
|
||||
<div className="space-y-2">
|
||||
{agent.description && (
|
||||
<p className="text-sm text-muted-foreground">{agent.description}</p>
|
||||
)}
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<p>Mode: {agent.mode}</p>
|
||||
{agent.temperature !== undefined && <p>Temperature: {agent.temperature}</p>}
|
||||
{agent.topP !== undefined && <p>Top P: {agent.topP}</p>}
|
||||
{agent.model && <p>Model: {agent.model}</p>}
|
||||
{agent.disable && <p>Status: Disabled</p>}
|
||||
</div>
|
||||
{agent.prompt && (
|
||||
<div className="mt-2 bg-muted rounded text-xs font-mono overflow-y-auto p-1 rounded-lg">
|
||||
{agent.prompt}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<SettingsList
|
||||
isEmpty={Object.keys(agents).length === 0}
|
||||
emptyTitle="No agents configured"
|
||||
emptyHint="Add your first agent to get started."
|
||||
maxHeightClassName="max-h-[calc(100dvh-300px)] sm:max-h-[420px]"
|
||||
>
|
||||
{Object.entries(agents).map(([name, agent]) => (
|
||||
<SettingsListRow
|
||||
key={name}
|
||||
title={name}
|
||||
description={agent.description}
|
||||
badges={
|
||||
<>
|
||||
{agent.mode && <Badge variant="outline" className="shrink-0">{agent.mode}</Badge>}
|
||||
{agent.disable && <Badge variant="secondary" className="shrink-0">Disabled</Badge>}
|
||||
</>
|
||||
}
|
||||
onClick={() => startEdit(name, agent)}
|
||||
primaryAction={{ label: 'Edit', onClick: () => startEdit(name, agent) }}
|
||||
actions={[{ label: 'Delete', destructive: true, onClick: () => deleteAgent(name) }]}
|
||||
actionsLabel={`Actions for ${name}`}
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
|
||||
<AgentDialog
|
||||
open={!!editingAgent}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { CommandsEditor } from './CommandsEditor'
|
||||
|
||||
vi.mock('./CommandDialog', () => ({
|
||||
CommandDialog: ({ open, editingCommand }: { open: boolean; editingCommand?: { name: string } | null }) =>
|
||||
open ? <div data-testid="command-dialog">{editingCommand ? 'Edit Command' : 'Create Command'}</div> : 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(<CommandsEditor commands={{}} onChange={onChange} />)
|
||||
|
||||
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(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
|
||||
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(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
|
||||
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(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
|
||||
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(<CommandsEditor commands={{}} onChange={onChange} />)
|
||||
|
||||
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(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
|
||||
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(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
|
||||
expect(screen.getByText('code-reviewer')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -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 (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Commands</h3>
|
||||
<div className="flex items-center justify-end">
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className='mr-1 h-6'>
|
||||
<Plus className="h-4 w-4" />
|
||||
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add Command
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<CommandDialog
|
||||
@@ -68,58 +69,27 @@ export function CommandsEditor({ commands, onChange }: CommandsEditorProps) {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{Object.keys(commands).length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="p-2 sm:p-8 text-center">
|
||||
<p className="text-muted-foreground">No commands configured. Add your first command to get started.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
{Object.entries(commands).map(([name, command]) => (
|
||||
<Card key={name}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">/{name}</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => startEdit(name, command)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteCommand(name)}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className='p-2'>
|
||||
<div className="space-y-2">
|
||||
{command.description && (
|
||||
<p className="text-sm text-muted-foreground">{command.description}</p>
|
||||
)}
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
{command.agent && <p>Agent: {command.agent}</p>}
|
||||
{command.model && <p>Model: {command.model}</p>}
|
||||
{command.topP !== undefined && <p>Top P: {command.topP}</p>}
|
||||
{command.subtask && <p>Subtask: Yes</p>}
|
||||
</div>
|
||||
<div className="mt-2 bg-muted rounded text-xs font-mono overflow-y-auto p-1 rounded-lg">
|
||||
{command.template}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<SettingsList
|
||||
isEmpty={Object.keys(commands).length === 0}
|
||||
emptyTitle="No commands configured"
|
||||
emptyHint="Add your first command to get started."
|
||||
maxHeightClassName="max-h-[calc(100dvh-300px)] sm:max-h-[420px]"
|
||||
>
|
||||
{Object.entries(commands).map(([name, command]) => (
|
||||
<SettingsListRow
|
||||
key={name}
|
||||
title={`/${name}`}
|
||||
description={command.description}
|
||||
badges={
|
||||
command.agent && <Badge variant="outline" className="shrink-0">{command.agent}</Badge>
|
||||
}
|
||||
onClick={() => startEdit(name, command)}
|
||||
primaryAction={{ label: 'Edit', onClick: () => startEdit(name, command) }}
|
||||
actions={[{ label: 'Delete', destructive: true, onClick: () => deleteCommand(name) }]}
|
||||
actionsLabel={`Actions for /${name}`}
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
|
||||
<CommandDialog
|
||||
open={!!editingCommand}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { SettingsList } from '@/components/ui/settings-list'
|
||||
import { Plus, Loader2, RefreshCw } from 'lucide-react'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { AddMcpServerDialog } from './AddMcpServerDialog'
|
||||
@@ -198,69 +199,62 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">MCP Servers</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Manage Model Context Protocol servers for {config.name}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-6"
|
||||
onClick={() => refetchStatus()}
|
||||
disabled={isLoadingStatus}
|
||||
>
|
||||
<RefreshCw className={`h-3 w-3 ${isLoadingStatus ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className='mr-1 h-6'>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<AddMcpServerDialog
|
||||
open={isAddDialogOpen}
|
||||
onOpenChange={setIsAddDialogOpen}
|
||||
onUpdate={onConfigUpdate}
|
||||
/>
|
||||
</Dialog>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => refetchStatus()}
|
||||
disabled={isLoadingStatus}
|
||||
>
|
||||
<RefreshCw className={`h-3 w-3 mr-1 ${isLoadingStatus ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add Server
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<AddMcpServerDialog
|
||||
open={isAddDialogOpen}
|
||||
onOpenChange={setIsAddDialogOpen}
|
||||
onUpdate={onConfigUpdate}
|
||||
/>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{Object.keys(mcpServers).length === 0 ? (
|
||||
<div className="rounded-lg border border-border p-6 sm:p-8 text-center">
|
||||
<p className="text-muted-foreground">No MCP servers configured. Add your first server to get started.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{Object.entries(mcpServers).map(([serverId, serverConfig]) => {
|
||||
const status = mcpStatus?.[serverId]
|
||||
const isConnected = status?.status === 'connected'
|
||||
const errorMessage = getErrorMessage(serverId)
|
||||
|
||||
return (
|
||||
<McpServerCard
|
||||
key={serverId}
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={status}
|
||||
isConnected={isConnected}
|
||||
errorMessage={errorMessage}
|
||||
isAnyOperationPending={isAnyOperationPending}
|
||||
togglingServerId={togglingServerId}
|
||||
isRemovingAuth={isRemovingAuth}
|
||||
onToggleServer={handleToggleServer}
|
||||
onAuthenticate={handleAuthenticate}
|
||||
onRemoveAuth={handleRemoveAuth}
|
||||
onDeleteServer={(id, name) => setDeleteConfirmServer({ id, name })}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<SettingsList
|
||||
isLoading={false}
|
||||
error={null}
|
||||
isEmpty={Object.keys(mcpServers).length === 0}
|
||||
emptyTitle="No MCP servers configured"
|
||||
emptyHint="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 (
|
||||
<McpServerCard
|
||||
key={serverId}
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={status}
|
||||
isConnected={isConnected}
|
||||
errorMessage={errorMessage}
|
||||
isAnyOperationPending={isAnyOperationPending}
|
||||
togglingServerId={togglingServerId}
|
||||
isRemovingAuth={isRemovingAuth}
|
||||
onToggleServer={handleToggleServer}
|
||||
onAuthenticate={handleAuthenticate}
|
||||
onRemoveAuth={handleRemoveAuth}
|
||||
onDeleteServer={(id, name) => setDeleteConfirmServer({ id, name })}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</SettingsList>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!deleteConfirmServer}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { McpServerCard } from './McpServerCard'
|
||||
import type { McpServerConfig, McpStatus } from '@/api/mcp'
|
||||
|
||||
const serverId = 'my-test-server'
|
||||
const serverConfig: McpServerConfig = { type: 'remote', url: 'https://example.com/mcp' }
|
||||
const status: McpStatus = { status: 'connected' }
|
||||
|
||||
describe('McpServerCard', () => {
|
||||
it('renders display name and description', () => {
|
||||
render(
|
||||
<McpServerCard
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={status}
|
||||
isConnected={true}
|
||||
errorMessage={null}
|
||||
isAnyOperationPending={false}
|
||||
togglingServerId={null}
|
||||
isRemovingAuth={false}
|
||||
onToggleServer={vi.fn()}
|
||||
onDeleteServer={vi.fn()}
|
||||
onAuthenticate={vi.fn()}
|
||||
onRemoveAuth={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('My test server')).toBeInTheDocument()
|
||||
expect(screen.getByText('Remote server: https://example.com/mcp')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the Connected status badge', () => {
|
||||
render(
|
||||
<McpServerCard
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={status}
|
||||
isConnected={true}
|
||||
errorMessage={null}
|
||||
isAnyOperationPending={false}
|
||||
togglingServerId={null}
|
||||
isRemovingAuth={false}
|
||||
onToggleServer={vi.fn()}
|
||||
onDeleteServer={vi.fn()}
|
||||
onAuthenticate={vi.fn()}
|
||||
onRemoveAuth={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the toggle Switch when not awaiting auth', () => {
|
||||
render(
|
||||
<McpServerCard
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={status}
|
||||
isConnected={true}
|
||||
errorMessage={null}
|
||||
isAnyOperationPending={false}
|
||||
togglingServerId={null}
|
||||
isRemovingAuth={false}
|
||||
onToggleServer={vi.fn()}
|
||||
onDeleteServer={vi.fn()}
|
||||
onAuthenticate={vi.fn()}
|
||||
onRemoveAuth={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<McpServerCard
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={status}
|
||||
isConnected={true}
|
||||
errorMessage={null}
|
||||
isAnyOperationPending={false}
|
||||
togglingServerId={null}
|
||||
isRemovingAuth={false}
|
||||
onToggleServer={vi.fn()}
|
||||
onDeleteServer={onDeleteServer}
|
||||
onAuthenticate={vi.fn()}
|
||||
onRemoveAuth={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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: <Key className="h-4 w-4 mr-2" /> })
|
||||
}
|
||||
if (connectedWithOAuth && onAuthenticate) {
|
||||
actions.push({ label: 'Re-authenticate', onClick: () => onAuthenticate(serverId), icon: <RefreshCw className="h-4 w-4 mr-2" /> })
|
||||
}
|
||||
if (connectedWithOAuth && onRemoveAuth) {
|
||||
actions.push({ label: isRemovingAuth ? 'Removing...' : 'Remove Auth', onClick: () => onRemoveAuth(serverId), icon: <Shield className="h-4 w-4 mr-2" />, disabled: isRemovingAuth })
|
||||
}
|
||||
actions.push({ label: 'Delete Server', onClick: () => onDeleteServer(serverId, displayName), icon: <Trash2 className="h-4 w-4 mr-2" />, destructive: true, separatorBefore: showAuthButton || connectedWithOAuth })
|
||||
|
||||
return (
|
||||
<div className={`flex items-center justify-between gap-3 p-3 rounded-lg border bg-card ${errorMessage ? 'border-red-500/50' : 'border-border'}`}>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-0.5">
|
||||
<p className="text-sm font-medium truncate">{displayName}</p>
|
||||
<SettingsListRow
|
||||
title={displayName}
|
||||
badges={
|
||||
<>
|
||||
{connectedWithOAuth && (
|
||||
<span title="OAuth authenticated">
|
||||
<Shield className="h-3 w-3 text-muted-foreground" />
|
||||
@@ -114,20 +125,17 @@ export function McpServerCard({
|
||||
{status ? getStatusBadge(status) : (
|
||||
<Badge variant="outline" className="text-xs">Loading...</Badge>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
description={getServerDescription(serverConfig)}
|
||||
belowDescription={errorMessage ? (
|
||||
<div className="flex items-start gap-1.5 mt-1.5 text-xs text-red-500">
|
||||
<XCircle className="h-3 w-3 flex-shrink-0 mt-0.5" />
|
||||
<span className="break-words line-clamp-2">{errorMessage}</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{getServerDescription(serverConfig)}
|
||||
</p>
|
||||
{errorMessage && (
|
||||
<div className="flex items-start gap-1.5 mt-1.5 text-xs text-red-500">
|
||||
<XCircle className="h-3 w-3 flex-shrink-0 mt-0.5" />
|
||||
<span className="break-words line-clamp-2">{errorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{showAuthButton && onAuthenticate ? (
|
||||
) : undefined}
|
||||
trailing={
|
||||
showAuthButton && onAuthenticate ? (
|
||||
<Button
|
||||
onClick={() => onAuthenticate(serverId)}
|
||||
disabled={isAnyOperationPending || togglingServerId === serverId}
|
||||
@@ -143,48 +151,10 @@ export function McpServerCard({
|
||||
onCheckedChange={() => onToggleServer(serverId)}
|
||||
disabled={isAnyOperationPending || togglingServerId === serverId}
|
||||
/>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{showAuthButton && onAuthenticate && (
|
||||
<DropdownMenuItem onSelect={() => setTimeout(() => onAuthenticate(serverId), 0)}>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && onAuthenticate && (
|
||||
<DropdownMenuItem onSelect={() => setTimeout(() => onAuthenticate(serverId), 0)}>
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Re-authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && onRemoveAuth && (
|
||||
<DropdownMenuItem
|
||||
onSelect={() => setTimeout(() => onRemoveAuth(serverId), 0)}
|
||||
disabled={isRemovingAuth}
|
||||
>
|
||||
<Shield className="h-4 w-4 mr-2" />
|
||||
{isRemovingAuth ? 'Removing...' : 'Remove Auth'}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{(showAuthButton || connectedWithOAuth) && <DropdownMenuSeparator />}
|
||||
<DropdownMenuItem
|
||||
onSelect={() => {
|
||||
setTimeout(() => onDeleteServer(serverId, displayName), 0)
|
||||
}}
|
||||
className="text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Server
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
actions={actions}
|
||||
actionsLabel={`Actions for ${displayName}`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)
|
||||
}
|
||||
|
||||
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<OpenCodeConfig>((resolve) => {
|
||||
resolveUpdate = resolve
|
||||
}))
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
|
||||
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(<OpenCodeConfigManager hideHealthStatus />)
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<OpenCodeConfig | null>(null)
|
||||
const [isRestartPromptOpen, setIsRestartPromptOpen] = useState(false)
|
||||
|
||||
const agentsMdRef = useRef<HTMLButtonElement>(null)
|
||||
const commandsRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -232,58 +234,44 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
}
|
||||
}
|
||||
|
||||
const updateConfigContent = async (configName: string, newContent: Record<string, unknown>, restartServer = false) => {
|
||||
const updateConfigContent = async (configName: string, newContent: Record<string, unknown>) => {
|
||||
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}
|
||||
/>
|
||||
|
||||
<RestartServerDialog
|
||||
open={isRestartPromptOpen}
|
||||
onOpenChange={setIsRestartPromptOpen}
|
||||
isSaving={isUpdating && !restartServerMutation.isPending}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => 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' })
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<string, ConfigProvider> = {
|
||||
},
|
||||
}
|
||||
|
||||
const findTrashButton = (): HTMLButtonElement | null => {
|
||||
const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>('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(<OpenCodeModelsEditor providers={mockProviders} onChange={onChange} />)
|
||||
|
||||
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<string, ConfigProvider> = {
|
||||
openai: {
|
||||
@@ -108,12 +96,11 @@ describe('OpenCodeModelsEditor', () => {
|
||||
},
|
||||
}
|
||||
|
||||
const user = userEvent.setup()
|
||||
render(<OpenCodeModelsEditor providers={providersWithExtras} onChange={onChange} />)
|
||||
|
||||
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]
|
||||
|
||||
@@ -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 (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Models</h3>
|
||||
<div className="flex items-center justify-end">
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="mr-1 h-6" onClick={() => openCreateDialog()}>
|
||||
<Plus className="h-4 w-4" />
|
||||
<Button size="sm" onClick={() => openCreateDialog()}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add Model
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<OpenCodeModelDialog
|
||||
@@ -162,73 +162,45 @@ export function OpenCodeModelsEditor({ providers, onChange }: OpenCodeModelsEdit
|
||||
</div>
|
||||
|
||||
{totalModelCount === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="p-2 sm:p-8 text-center">
|
||||
<p className="text-muted-foreground">
|
||||
No models configured. Add your first model to get started.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<SettingsList
|
||||
isEmpty
|
||||
emptyTitle="No models configured"
|
||||
emptyHint="Add your first model to get started."
|
||||
>
|
||||
<div />
|
||||
</SettingsList>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
<div className="space-y-3">
|
||||
{providerEntries.map(({ providerId, providerName, models }) => {
|
||||
const modelEntries = Object.entries(models)
|
||||
if (modelEntries.length === 0) return null
|
||||
|
||||
return (
|
||||
<Card key={providerId}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Box className="h-4 w-4" />
|
||||
{providerName}
|
||||
<span className="text-xs text-muted-foreground font-normal">
|
||||
({modelEntries.length} model{modelEntries.length !== 1 ? 's' : ''})
|
||||
</span>
|
||||
</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-2 space-y-3">
|
||||
<div key={providerId} className="space-y-2">
|
||||
<div className="flex items-center gap-2 px-1 text-xs font-medium text-muted-foreground">
|
||||
<Box className="h-3.5 w-3.5" />
|
||||
<span>{providerName}</span>
|
||||
<span>{modelEntries.length} model{modelEntries.length !== 1 ? 's' : ''}</span>
|
||||
</div>
|
||||
<SettingsList isEmpty={false} maxHeightClassName="max-h-[420px]">
|
||||
{modelEntries.map(([modelId, model]) => (
|
||||
<div
|
||||
<SettingsListRow
|
||||
key={modelId}
|
||||
className="flex items-center justify-between p-2 bg-muted/50 rounded-lg"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm truncate">{model.name || modelId}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono truncate">
|
||||
{modelId}
|
||||
title={model.name || modelId}
|
||||
description={<span className="font-mono">{modelId}</span>}
|
||||
belowDescription={(model.limit?.context || model.limit?.output) && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Limits: {model.limit?.context && `Context ${model.limit.context}`}{model.limit?.context && model.limit?.output && ' / '}{model.limit?.output && `Output ${model.limit.output}`}
|
||||
</p>
|
||||
{(model.limit?.context || model.limit?.output) && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Limits:{' '}
|
||||
{model.limit.context && `Context ${model.limit.context}`}
|
||||
{model.limit.context && model.limit.output && ' / '}
|
||||
{model.limit.output && `Output ${model.limit.output}`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 ml-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => startEdit(providerId, modelId, model)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteModel(providerId, modelId)}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
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}`}
|
||||
/>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</SettingsList>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -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(<RestartServerDialog {...baseProps} />)
|
||||
|
||||
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(<RestartServerDialog {...baseProps} open={false} />)
|
||||
|
||||
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(<RestartServerDialog {...baseProps} onConfirm={onConfirm} />)
|
||||
|
||||
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(<RestartServerDialog {...baseProps} onCancel={onCancel} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
expect(onCancel).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('disables confirm button and shows Restarting... when isRestarting is true', () => {
|
||||
render(<RestartServerDialog {...baseProps} isRestarting={true} />)
|
||||
|
||||
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(<RestartServerDialog {...baseProps} isSaving={true} />)
|
||||
|
||||
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(<RestartServerDialog {...baseProps} isRestarting={true} />)
|
||||
|
||||
const laterButton = screen.getByRole('button', { name: /later/i })
|
||||
expect(laterButton).toBeDisabled()
|
||||
})
|
||||
})
|
||||
@@ -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 (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[90%] sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Restart OpenCode Server?</DialogTitle>
|
||||
<DialogDescription>
|
||||
Restart the OpenCode server after your changes are saved to apply them to the running server.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="outline" onClick={onCancel} disabled={isRestarting}>
|
||||
Later
|
||||
</Button>
|
||||
<Button onClick={onConfirm} disabled={isConfirmDisabled}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : isRestarting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
||||
Restarting...
|
||||
</>
|
||||
) : (
|
||||
'Restart now'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -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({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Loading...</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<AlertCircle className="w-10 h-10 mx-auto mb-3 opacity-50 text-red-500" />
|
||||
<p className="text-sm">Failed to load skills</p>
|
||||
<p className="text-xs mt-1">{error.message}</p>
|
||||
</div>
|
||||
) : filteredSkills.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-border bg-card/50 p-6 text-center text-muted-foreground">
|
||||
<p className="text-sm font-medium text-foreground">{emptyTitle || 'No skills available'}</p>
|
||||
<p className="text-xs mt-1">{emptyHint || 'Create or install a skill to get started.'}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className={`${maxHeightClassName} overflow-y-auto rounded-lg border border-border`}>
|
||||
<div className="divide-y divide-border">
|
||||
{filteredSkills.map((skill) => (
|
||||
<div
|
||||
key={getSkillKey(skill)}
|
||||
onClick={primaryAction ? () => 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' : ''}`}
|
||||
>
|
||||
<div className="min-w-0 flex-1 self-stretch sm:self-auto">
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<p className="min-w-0 flex-1 truncate text-sm font-medium text-orange-600 dark:text-orange-400">{skill.name}</p>
|
||||
<Badge variant={skill.scope === 'global' ? 'secondary' : 'outline'} className="shrink-0 sm:hidden">
|
||||
{getCompactScopeLabel(skill)}
|
||||
</Badge>
|
||||
<Badge variant={skill.scope === 'global' ? 'secondary' : 'outline'} className="hidden max-w-full truncate sm:inline-flex">
|
||||
{getScopeLabel(skill)}
|
||||
</Badge>
|
||||
</div>
|
||||
{skill.description && (
|
||||
<p className="mt-1 truncate text-xs text-muted-foreground">{skill.description}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex w-full shrink-0 items-center justify-end gap-1 sm:w-auto sm:justify-start" onClick={(event) => event.stopPropagation()}>
|
||||
{primaryAction && (
|
||||
<Button type="button" size="sm" onClick={() => primaryAction.onClick(skill)} className="flex-1 sm:flex-none">
|
||||
{primaryAction.label}
|
||||
</Button>
|
||||
)}
|
||||
{rowActions.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className="h-8 w-8" aria-label={`Actions for ${skill.name}`}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{rowActions.map((action) => (
|
||||
<DropdownMenuItem
|
||||
key={action.label}
|
||||
onClick={() => action.onClick(skill)}
|
||||
className={action.destructive ? 'text-destructive focus:text-destructive' : undefined}
|
||||
>
|
||||
{action.label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<SettingsList
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
isEmpty={filteredSkills.length === 0}
|
||||
emptyTitle={emptyTitle ?? 'No skills available'}
|
||||
emptyHint={emptyHint ?? 'Create or install a skill to get started.'}
|
||||
errorTitle="Failed to load skills"
|
||||
maxHeightClassName={maxHeightClassName}
|
||||
>
|
||||
{filteredSkills.map((skill) => (
|
||||
<SettingsListRow
|
||||
key={getSkillKey(skill)}
|
||||
title={skill.name}
|
||||
titleClassName="text-orange-600 dark:text-orange-400"
|
||||
description={skill.description}
|
||||
onClick={primaryAction ? () => 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={
|
||||
<>
|
||||
<Badge variant={skill.scope === 'global' ? 'secondary' : 'outline'} className="shrink-0 sm:hidden">
|
||||
{getCompactScopeLabel(skill)}
|
||||
</Badge>
|
||||
<Badge variant={skill.scope === 'global' ? 'secondary' : 'outline'} className="hidden max-w-full truncate sm:inline-flex">
|
||||
{getScopeLabel(skill)}
|
||||
</Badge>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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(
|
||||
<SettingsList isEmpty emptyTitle="Nothing here" emptyHint="Try adding something">
|
||||
<div>child</div>
|
||||
</SettingsList>,
|
||||
)
|
||||
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(
|
||||
<SettingsList isEmpty={false} isLoading loadingLabel="Please wait...">
|
||||
<div>child</div>
|
||||
</SettingsList>,
|
||||
)
|
||||
expect(screen.getByText('Please wait...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders error.message when error passed', () => {
|
||||
render(
|
||||
<SettingsList isEmpty={false} error={new Error('Something broke')}>
|
||||
<div>child</div>
|
||||
</SettingsList>,
|
||||
)
|
||||
expect(screen.getByText('Something broke')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SettingsListRow', () => {
|
||||
it('renders title, description, and badges content', () => {
|
||||
render(
|
||||
<SettingsListRow
|
||||
title="Row Title"
|
||||
description="Row description"
|
||||
badges={<span data-testid="badge">Badge</span>}
|
||||
/>,
|
||||
)
|
||||
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(<SettingsListRow title="Row" primaryAction={{ label: 'Do It', onClick }} />)
|
||||
|
||||
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(
|
||||
<SettingsListRow
|
||||
title="Row"
|
||||
onClick={rowClick}
|
||||
primaryAction={{ label: 'Action', onClick: primaryClick }}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<SettingsListRow
|
||||
title="Row"
|
||||
actionsLabel="More options"
|
||||
actions={[
|
||||
{ label: 'Edit', onClick: vi.fn() },
|
||||
{ label: 'Delete', onClick: actionClick, destructive: true },
|
||||
]}
|
||||
/>,
|
||||
)
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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 (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">{loadingLabel ?? 'Loading...'}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<AlertCircle className="w-10 h-10 mx-auto mb-3 opacity-50 text-red-500" />
|
||||
<p className="text-sm">{errorTitle ?? 'Failed to load'}</p>
|
||||
<p className="text-xs mt-1">{error.message}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isEmpty) {
|
||||
return (
|
||||
<div className="rounded-lg border border-dashed border-border bg-card/50 p-6 text-center text-muted-foreground">
|
||||
<p className="text-sm font-medium text-foreground">{emptyTitle}</p>
|
||||
<p className="text-xs mt-1">{emptyHint}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn(maxHeightClassName ?? 'max-h-[420px]', 'overflow-y-auto rounded-lg border border-border')}>
|
||||
<div className="divide-y divide-border">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function SettingsListRow({
|
||||
title,
|
||||
titleClassName,
|
||||
description,
|
||||
badges,
|
||||
belowDescription,
|
||||
trailing,
|
||||
primaryAction,
|
||||
actions,
|
||||
actionsLabel,
|
||||
onClick,
|
||||
className,
|
||||
}: SettingsListRowProps) {
|
||||
return (
|
||||
<div
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'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',
|
||||
onClick && 'cursor-pointer',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="min-w-0 flex-1 self-stretch sm:self-auto">
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<p className={cn('min-w-0 flex-1 truncate text-sm font-medium', titleClassName)}>{title}</p>
|
||||
{badges}
|
||||
</div>
|
||||
{description && <div className="mt-1 truncate text-xs text-muted-foreground">{description}</div>}
|
||||
{belowDescription}
|
||||
</div>
|
||||
<div
|
||||
className="flex w-full shrink-0 items-center justify-end gap-1 sm:w-auto sm:justify-start"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{trailing}
|
||||
{primaryAction && (
|
||||
<Button type="button" size="sm" onClick={primaryAction.onClick} className="flex-1 sm:flex-none">
|
||||
{primaryAction.label}
|
||||
</Button>
|
||||
)}
|
||||
{actions && actions.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className="h-8 w-8" aria-label={actionsLabel}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{actions.map((action, i) => (
|
||||
<Fragment key={action.label}>
|
||||
{action.separatorBefore && i > 0 && <DropdownMenuSeparator />}
|
||||
<DropdownMenuItem
|
||||
disabled={action.disabled}
|
||||
onSelect={() => setTimeout(action.onClick, 0)}
|
||||
className={action.destructive ? 'text-destructive focus:text-destructive' : undefined}
|
||||
>
|
||||
{action.icon}
|
||||
{action.label}
|
||||
</DropdownMenuItem>
|
||||
</Fragment>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user