mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)
* feat(opencode): migrate OpenCode Manager to OpenCode 2 Port the backend lifecycle, generated plugins, event aggregation, schedules, worktrees, provider credentials, MCP, config handling, the frontend chat model, and the ocm CLI to OpenCode 2. Adopt @opencode/client 2.0.15 as the single typed V2 API contract, require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every V1-only code path. * refactor(opencode): reload config in place and drop v1 compatibility shims Route config/skill/AGENTS.md changes through the OpenCode location reload API instead of a full server restart, stop auto-resuming interrupted sessions, remove the restart coordinator and v1 MCP/version shims, and pin support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries, service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers. * refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows - extract shared semver and model-ref utilities, reuse across version checks - share the OpenCode release download script across Docker, entrypoint, dev setup - unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN - scope the repo proxy location rewrite and surface ocm proxy errors - rework frontend session projection, permission lookup, and cache invalidation * fix(schedules): reject unavailable agents before creating a session * feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
1 parent
6c2ebd764b
commit
dacde879d6
383 files changed
+29905
-46566
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
@@ -42,6 +42,13 @@ function renderDialog(onUpdate: (content: Record<string, unknown>) => Promise<vo
|
||||
}
|
||||
|
||||
describe('AddMcpServerDialog', () => {
|
||||
beforeAll(() => {
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
Element.prototype.scrollIntoView ??= () => {}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetOpenCodeConfig.mockResolvedValue(config)
|
||||
@@ -62,16 +69,47 @@ describe('AddMcpServerDialog', () => {
|
||||
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(onUpdate).toHaveBeenCalledWith({
|
||||
mcp: {
|
||||
filesystem: {
|
||||
type: 'local',
|
||||
enabled: true,
|
||||
command: ['npx', 'server-filesystem', '/tmp'],
|
||||
servers: {
|
||||
filesystem: {
|
||||
type: 'local',
|
||||
command: ['npx', 'server-filesystem', '/tmp'],
|
||||
disabled: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(mockAddServerAsync).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('writes a remote server with V2 OAuth keys and the Manager callback', async () => {
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
renderDialog(onUpdate)
|
||||
|
||||
await user.type(screen.getByLabelText('Server ID'), 'remote-tools')
|
||||
await user.click(screen.getByRole('combobox'))
|
||||
await user.click(screen.getByRole('option', { name: 'Remote (HTTP)' }))
|
||||
await user.type(screen.getByLabelText('Server URL'), 'https://mcp.example.com')
|
||||
await user.click(screen.getByLabelText('Enable OAuth'))
|
||||
await user.type(screen.getByLabelText('Client ID'), 'client-1')
|
||||
await user.type(screen.getByLabelText('Timeout (ms)'), '9000')
|
||||
await user.click(screen.getByRole('button', { name: 'Add MCP Server' }))
|
||||
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1))
|
||||
const serverConfig = {
|
||||
type: 'remote',
|
||||
url: 'https://mcp.example.com',
|
||||
oauth: {
|
||||
client_id: 'client-1',
|
||||
redirect_uri: `${window.location.origin}/api/mcp-oauth-proxy/callback`,
|
||||
},
|
||||
disabled: false,
|
||||
timeout: { catalog: 9000, execution: 9000 },
|
||||
}
|
||||
expect(onUpdate).toHaveBeenCalledWith({ mcp: { servers: { 'remote-tools': serverConfig } } })
|
||||
expect(mockAddServerAsync).toHaveBeenCalledWith({ name: 'remote-tools', config: serverConfig })
|
||||
})
|
||||
|
||||
it('passes only the merged content to onUpdate', async () => {
|
||||
const fetched = makeOpenCodeConfigFile({ revision: 'rev-B' })
|
||||
mockGetOpenCodeConfig.mockResolvedValue(fetched)
|
||||
@@ -86,7 +124,8 @@ describe('AddMcpServerDialog', () => {
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1))
|
||||
const [content] = onUpdate.mock.calls[0]
|
||||
expect(onUpdate.mock.calls[0]).toHaveLength(1)
|
||||
expect((content.mcp as Record<string, unknown>).filesystem).toBeDefined()
|
||||
const mcp = content.mcp as Record<string, unknown>
|
||||
expect(mcp.servers).toBeDefined()
|
||||
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,11 @@ import { Loader2 } from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useMcpServers } from '@/hooks/useMcpServers'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import {
|
||||
mcpOAuthRedirectUri,
|
||||
type McpServerConfig,
|
||||
type McpTimeoutConfig,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
|
||||
interface AddMcpServerDialogProps {
|
||||
@@ -37,90 +42,75 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
const queryClient = useQueryClient()
|
||||
const { addServerAsync, isAddingServer } = useMcpServers()
|
||||
|
||||
const buildTimeout = (): McpTimeoutConfig | undefined => {
|
||||
const parsed = parseInt(timeout)
|
||||
return Number.isFinite(parsed) ? { catalog: parsed, execution: parsed } : undefined
|
||||
}
|
||||
|
||||
const buildMcpServerConfig = (): McpServerConfig => {
|
||||
const timeoutConfig = buildTimeout()
|
||||
const shared = {
|
||||
disabled: !enabled,
|
||||
...(timeoutConfig ? { timeout: timeoutConfig } : {}),
|
||||
}
|
||||
|
||||
if (serverType === 'local') {
|
||||
const commandArray = command.split(' ').filter((arg) => arg.trim())
|
||||
if (commandArray.length === 0) {
|
||||
throw new Error('Command is required for local MCP servers')
|
||||
}
|
||||
|
||||
const environmentVariables = Object.fromEntries(
|
||||
environment
|
||||
.filter((env) => env.key.trim() && env.value.trim())
|
||||
.map((env) => [env.key.trim(), env.value.trim()]),
|
||||
)
|
||||
|
||||
return {
|
||||
type: 'local',
|
||||
command: commandArray,
|
||||
...(Object.keys(environmentVariables).length > 0 ? { environment: environmentVariables } : {}),
|
||||
...shared,
|
||||
}
|
||||
}
|
||||
|
||||
if (!url.trim()) {
|
||||
throw new Error('URL is required for remote MCP servers')
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'remote',
|
||||
url: url.trim(),
|
||||
...(oauthEnabled
|
||||
? {
|
||||
oauth: {
|
||||
...(oauthClientId.trim() ? { client_id: oauthClientId.trim() } : {}),
|
||||
...(oauthClientSecret.trim() ? { client_secret: oauthClientSecret.trim() } : {}),
|
||||
...(oauthScope.trim() ? { scope: oauthScope.trim() } : {}),
|
||||
redirect_uri: mcpOAuthRedirectUri(window.location.origin),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...shared,
|
||||
}
|
||||
}
|
||||
|
||||
const addMcpServerMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const config = await settingsApi.getOpenCodeConfig()
|
||||
const currentMcp = (config.content.mcp as Record<string, unknown>) || {}
|
||||
|
||||
const mcpConfig: Record<string, unknown> = {
|
||||
type: serverType,
|
||||
enabled,
|
||||
}
|
||||
const mcpServerConfig = buildMcpServerConfig()
|
||||
const mcp = (config.content.mcp as Record<string, unknown> | undefined) ?? {}
|
||||
|
||||
if (serverType === 'local') {
|
||||
const commandArray = command.split(' ').filter(arg => arg.trim())
|
||||
if (commandArray.length === 0) {
|
||||
throw new Error('Command is required for local MCP servers')
|
||||
}
|
||||
mcpConfig.command = commandArray
|
||||
|
||||
const envVars: Record<string, string> = {}
|
||||
environment.forEach(env => {
|
||||
if (env.key.trim() && env.value.trim()) {
|
||||
envVars[env.key.trim()] = env.value.trim()
|
||||
}
|
||||
})
|
||||
if (Object.keys(envVars).length > 0) {
|
||||
mcpConfig.environment = envVars
|
||||
}
|
||||
} else {
|
||||
if (!url.trim()) {
|
||||
throw new Error('URL is required for remote MCP servers')
|
||||
}
|
||||
mcpConfig.url = url.trim()
|
||||
|
||||
if (oauthEnabled) {
|
||||
const oauthConfig: Record<string, string> = {}
|
||||
if (oauthClientId.trim()) oauthConfig.clientId = oauthClientId.trim()
|
||||
if (oauthClientSecret.trim()) oauthConfig.clientSecret = oauthClientSecret.trim()
|
||||
if (oauthScope.trim()) oauthConfig.scope = oauthScope.trim()
|
||||
mcpConfig.oauth = Object.keys(oauthConfig).length > 0 ? oauthConfig : true
|
||||
}
|
||||
}
|
||||
|
||||
if (timeout && parseInt(timeout)) {
|
||||
mcpConfig.timeout = parseInt(timeout)
|
||||
}
|
||||
|
||||
const updatedConfig = {
|
||||
await onUpdate({
|
||||
...config.content,
|
||||
mcp: {
|
||||
...currentMcp,
|
||||
[serverId]: mcpConfig,
|
||||
...mcp,
|
||||
servers: { ...(mcp.servers as Record<string, unknown> | undefined), [serverId]: mcpServerConfig },
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
await onUpdate(updatedConfig)
|
||||
|
||||
if (enabled) {
|
||||
const buildOauthField = () => {
|
||||
if (serverType !== 'remote' || !oauthEnabled) return undefined
|
||||
const cfg: Record<string, string> = {}
|
||||
if (oauthClientId.trim()) cfg.clientId = oauthClientId.trim()
|
||||
if (oauthClientSecret.trim()) cfg.clientSecret = oauthClientSecret.trim()
|
||||
if (oauthScope.trim()) cfg.scope = oauthScope.trim()
|
||||
return Object.keys(cfg).length > 0 ? cfg : true
|
||||
}
|
||||
|
||||
await addServerAsync({
|
||||
name: serverId,
|
||||
config: {
|
||||
type: serverType,
|
||||
enabled,
|
||||
command: serverType === 'local' ? command.split(' ').filter(arg => arg.trim()) : undefined,
|
||||
url: serverType === 'remote' ? url.trim() : undefined,
|
||||
environment: serverType === 'local' && Object.keys(environment).length > 0
|
||||
? environment.reduce((acc, env) => {
|
||||
if (env.key.trim() && env.value.trim()) {
|
||||
acc[env.key.trim()] = env.value.trim()
|
||||
}
|
||||
return acc
|
||||
}, {} as Record<string, string>)
|
||||
: undefined,
|
||||
timeout: timeout && parseInt(timeout) ? parseInt(timeout) : undefined,
|
||||
oauth: buildOauthField(),
|
||||
}
|
||||
})
|
||||
await addServerAsync({ name: serverId, config: mcpServerConfig })
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
@@ -339,7 +329,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
className="bg-background border-border"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Timeout in milliseconds for fetching tools (default: 5000)
|
||||
Timeout in milliseconds for listing and calling tools
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect, vi, beforeAll } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { AgentDialog } from './AgentDialog'
|
||||
|
||||
vi.mock('@/hooks/useProvidersWithModels', () => ({
|
||||
useProvidersWithModels: () => ({ data: [] }),
|
||||
}))
|
||||
|
||||
const renderDialog = (editingAgent: { name: string; agent: { prompt: string; model?: string } } | null) =>
|
||||
render(<AgentDialog open onOpenChange={vi.fn()} onSubmit={vi.fn()} editingAgent={editingAgent} />)
|
||||
|
||||
describe('AgentDialog model parsing', () => {
|
||||
beforeAll(() => {
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
Element.prototype.scrollIntoView ??= () => {}
|
||||
})
|
||||
|
||||
it('loads provider and model from a model reference', async () => {
|
||||
renderDialog({ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o' } })
|
||||
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('Select or type provider...')).toHaveValue('openai'))
|
||||
expect(screen.getByPlaceholderText('Select or type model...')).toHaveValue('gpt-4o')
|
||||
})
|
||||
|
||||
it('keeps the variant attached to the model id', async () => {
|
||||
renderDialog({ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o#high' } })
|
||||
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('Select or type provider...')).toHaveValue('openai'))
|
||||
expect(screen.getByPlaceholderText('Select or type model...')).toHaveValue('gpt-4o#high')
|
||||
})
|
||||
|
||||
it('leaves provider and model empty when the agent has no model', async () => {
|
||||
renderDialog({ name: 'reviewer', agent: { prompt: 'Review code' } })
|
||||
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('Select or type provider...')).toHaveValue(''))
|
||||
expect(screen.getByPlaceholderText('Select or type model...')).toHaveValue('')
|
||||
})
|
||||
|
||||
it('round-trips a variant model reference on submit', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<AgentDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={onSubmit}
|
||||
editingAgent={{ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o#high' } }}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
'reviewer',
|
||||
expect.objectContaining({ model: 'openai/gpt-4o#high' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,7 @@ import { Switch } from '@/components/ui/switch'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
|
||||
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
|
||||
import { parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
|
||||
const agentFormSchema = z.object({
|
||||
name: z.string().min(1, 'Agent name is required').regex(/^[a-z0-9-]+$/, 'Must be lowercase letters, numbers, and hyphens only'),
|
||||
@@ -52,9 +53,12 @@ interface Agent {
|
||||
}
|
||||
|
||||
function parseModelString(model?: string): { providerId: string; modelId: string } {
|
||||
if (!model) return { providerId: '', modelId: '' }
|
||||
const [providerId, ...rest] = model.split('/')
|
||||
return { providerId: providerId || '', modelId: rest.join('/') || '' }
|
||||
const ref = model ? parseOpenCodeModelRef(model) : undefined
|
||||
if (!ref) return { providerId: '', modelId: '' }
|
||||
return {
|
||||
providerId: ref.providerID,
|
||||
modelId: ref.variant ? `${ref.id}#${ref.variant}` : ref.id,
|
||||
}
|
||||
}
|
||||
|
||||
interface AgentDialogProps {
|
||||
|
||||
@@ -7,11 +7,15 @@ import { AgentsMdEditor } from './AgentsMdEditor'
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
getAgentsMd: vi.fn().mockResolvedValue({ content: '# Rules\n\nline two\nline three\n' }),
|
||||
updateAgentsMd: vi.fn().mockResolvedValue(undefined),
|
||||
updateAgentsMd: vi.fn().mockResolvedValue({ success: true, restartRequired: false }),
|
||||
getDefaultAgentsMd: vi.fn().mockResolvedValue({ content: '# Default' }),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
@@ -83,9 +87,9 @@ describe('AgentsMdEditor', () => {
|
||||
it('locks the editor while a save is pending and preserves submitted content', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { settingsApi } = await import('@/api/settings')
|
||||
let resolveSave: () => void = () => {}
|
||||
let resolveSave: (value: { success: boolean; restartRequired?: boolean }) => void = () => {}
|
||||
;(settingsApi.updateAgentsMd as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
new Promise<void>((resolve) => {
|
||||
new Promise<{ success: boolean; restartRequired?: boolean }>((resolve) => {
|
||||
resolveSave = resolve
|
||||
}),
|
||||
)
|
||||
@@ -101,7 +105,7 @@ describe('AgentsMdEditor', () => {
|
||||
// user-event refuses to type into a disabled element; expected
|
||||
}
|
||||
expect(textarea).toHaveValue(edited)
|
||||
resolveSave()
|
||||
resolveSave({ success: true, restartRequired: false })
|
||||
await waitFor(() => expect(textarea).not.toBeDisabled())
|
||||
expect(textarea).toHaveValue(edited)
|
||||
})
|
||||
@@ -122,4 +126,43 @@ describe('AgentsMdEditor', () => {
|
||||
await waitFor(() => expect(settingsApi.getAgentsMd).toHaveBeenCalledTimes(2))
|
||||
expect(textarea).toHaveValue('A')
|
||||
})
|
||||
|
||||
it('reports a save as applied without a restart', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { settingsApi } = await import('@/api/settings')
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
;(settingsApi.updateAgentsMd as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ success: true, restartRequired: false })
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
const textarea = (await screen.findByLabelText('AGENTS.md content')) as HTMLTextAreaElement
|
||||
fireEvent.change(textarea, { target: { value: '# Rules\n\napplied\n' } })
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(showToast.success).toHaveBeenCalledWith('AGENTS.md saved'))
|
||||
})
|
||||
|
||||
it('requests a restart when the in-place reload fails', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { settingsApi } = await import('@/api/settings')
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
;(settingsApi.updateAgentsMd as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ success: true, restartRequired: true })
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
const textarea = (await screen.findByLabelText('AGENTS.md content')) as HTMLTextAreaElement
|
||||
fireEvent.change(textarea, { target: { value: '# Rules\n\nneeds restart\n' } })
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() =>
|
||||
expect(showToast.success).toHaveBeenCalledWith(
|
||||
'Configuration saved, but OpenCode could not reload it. Restart the server to apply changes.',
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('reports resetting to default as applied without a restart', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { settingsApi } = await import('@/api/settings')
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
;(settingsApi.updateAgentsMd as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ success: true, restartRequired: false })
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
await screen.findByLabelText('AGENTS.md content')
|
||||
await user.click(screen.getByRole('button', { name: 'Reset to Default' }))
|
||||
await waitFor(() => expect(showToast.success).toHaveBeenCalledWith('AGENTS.md reset to default'))
|
||||
})
|
||||
})
|
||||
@@ -6,10 +6,12 @@ import { CodeEditor } from '@/components/ui/code-editor'
|
||||
import { EditorFindBar } from '@/components/ui/editor-find-bar'
|
||||
import { useFindInText } from '@/lib/useFindInText'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useOpenCodeApplyFeedback } from '@/hooks/useOpenCodeApplyFeedback'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
export function AgentsMdEditor() {
|
||||
const queryClient = useQueryClient()
|
||||
const applyOpenCodeSaveFeedback = useOpenCodeApplyFeedback()
|
||||
const [content, setContent] = useState('')
|
||||
const [savedContent, setSavedContent] = useState('')
|
||||
const hasChanges = content !== savedContent
|
||||
@@ -33,11 +35,10 @@ export function AgentsMdEditor() {
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (newContent: string) => settingsApi.updateAgentsMd(newContent),
|
||||
onSuccess: (_data, newContent) => {
|
||||
onSuccess: (result, newContent) => {
|
||||
setSavedContent(newContent)
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
showToast.success('AGENTS.md saved and server restarted')
|
||||
applyOpenCodeSaveFeedback({ appliedMessage: 'AGENTS.md saved', restartRequired: result.restartRequired })
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to save AGENTS.md')
|
||||
@@ -47,14 +48,14 @@ export function AgentsMdEditor() {
|
||||
const resetToDefaultMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const { content: defaultContent } = await settingsApi.getDefaultAgentsMd()
|
||||
await settingsApi.updateAgentsMd(defaultContent)
|
||||
return defaultContent
|
||||
const result = await settingsApi.updateAgentsMd(defaultContent)
|
||||
return { defaultContent, restartRequired: result.restartRequired }
|
||||
},
|
||||
onSuccess: (defaultContent) => {
|
||||
onSuccess: ({ defaultContent, restartRequired }) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
setContent(defaultContent)
|
||||
setSavedContent(defaultContent)
|
||||
showToast.success('AGENTS.md reset to default and server restarted')
|
||||
applyOpenCodeSaveFeedback({ appliedMessage: 'AGENTS.md reset to default', restartRequired })
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to reset AGENTS.md')
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { McpManager } from './McpManager'
|
||||
|
||||
const { mockRemoveServer, mockToastError, mockStatus } = vi.hoisted(() => ({
|
||||
mockRemoveServer: vi.fn(),
|
||||
mockToastError: vi.fn(),
|
||||
mockStatus: {
|
||||
configured: { status: 'connected' as const },
|
||||
'legacy-server': { status: 'disabled' as const },
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMcpServers', () => ({
|
||||
useMcpServers: () => ({
|
||||
status: mockStatus,
|
||||
isLoading: false,
|
||||
refetch: vi.fn(),
|
||||
connect: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
removeAuthAsync: vi.fn(),
|
||||
isRemovingAuth: false,
|
||||
addServerAsync: vi.fn(),
|
||||
isAddingServer: false,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/mcp', () => ({
|
||||
mcpApi: { removeServer: mockRemoveServer, startAuth: vi.fn(), getStatus: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: mockToastError, info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
|
||||
const config = {
|
||||
content: {
|
||||
mcp: {
|
||||
servers: {
|
||||
configured: { type: 'local', command: ['npx', 'server'] },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
function renderManager(onUpdate: (content: Record<string, unknown>) => Promise<void>) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<McpManager config={config} onUpdate={onUpdate} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
async function deleteServer(user: ReturnType<typeof userEvent.setup>, displayName: string) {
|
||||
await user.click(screen.getByLabelText(`Actions for ${displayName}`))
|
||||
await user.click(screen.getByText('Delete Server'))
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }))
|
||||
}
|
||||
|
||||
describe('McpManager', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockRemoveServer.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('lists servers reported by the running server that are not in mcp.servers', () => {
|
||||
renderManager(vi.fn())
|
||||
|
||||
expect(screen.getByText('Configured')).toBeInTheDocument()
|
||||
expect(screen.getByText('Legacy server')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('removes only the mcp.servers entry when deleting a configured server', async () => {
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
renderManager(onUpdate)
|
||||
|
||||
await deleteServer(user, 'Configured')
|
||||
|
||||
await waitFor(() => expect(mockRemoveServer).toHaveBeenCalledWith('configured'))
|
||||
expect(onUpdate).toHaveBeenCalledWith({ mcp: { servers: {} } })
|
||||
})
|
||||
|
||||
it('skips the config update for a server that is not in mcp.servers', async () => {
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
renderManager(onUpdate)
|
||||
|
||||
await deleteServer(user, 'Legacy server')
|
||||
|
||||
await waitFor(() => expect(mockRemoveServer).toHaveBeenCalledWith('legacy-server'))
|
||||
expect(onUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces the shadowed-removal message from the backend', async () => {
|
||||
const message = 'Cannot remove mcp.servers.configured: defined in opencode.json, not in opencode.jsonc'
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockRejectedValue(new FetchError(message, 409))
|
||||
const user = userEvent.setup()
|
||||
renderManager(onUpdate)
|
||||
|
||||
await deleteServer(user, 'Configured')
|
||||
|
||||
await waitFor(() => expect(mockToastError).toHaveBeenCalledWith(message))
|
||||
expect(mockRemoveServer).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { SettingsList } from '@/components/ui/settings-list'
|
||||
@@ -10,10 +10,12 @@ import { McpOAuthDialog } from './McpOAuthDialog'
|
||||
import { useMcpServers } from '@/hooks/useMcpServers'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import type { McpServerConfig } from '@/api/mcp'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
import type { McpAuthStartResponse } from '@/api/mcp'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
import { mcpServersFromConfig } from '@opencode-manager/shared/opencode'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { formatMcpServerName } from '@/lib/mcp'
|
||||
|
||||
interface McpManagerProps {
|
||||
config: {
|
||||
@@ -22,7 +24,12 @@ interface McpManagerProps {
|
||||
onUpdate: (content: Record<string, unknown>) => Promise<void>
|
||||
}
|
||||
|
||||
|
||||
function withoutMcpServer(mcp: unknown, serverId: string): Record<string, unknown> {
|
||||
const current = (mcp && typeof mcp === 'object' ? mcp : {}) as Record<string, unknown>
|
||||
const servers = { ...(current.servers as Record<string, unknown> | undefined) }
|
||||
delete servers[serverId]
|
||||
return { ...current, servers }
|
||||
}
|
||||
|
||||
export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
|
||||
@@ -30,10 +37,10 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
const [togglingServerId, setTogglingServerId] = useState<string | null>(null)
|
||||
const [authDialogServerId, setAuthDialogServerId] = useState<string | null>(null)
|
||||
const [removeAuthConfirmServer, setRemoveAuthConfirmServer] = useState<string | null>(null)
|
||||
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const {
|
||||
status: mcpStatus,
|
||||
const {
|
||||
status: mcpStatus,
|
||||
isLoading: isLoadingStatus,
|
||||
refetch: refetchStatus,
|
||||
connect,
|
||||
@@ -42,51 +49,40 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
isRemovingAuth
|
||||
} = useMcpServers()
|
||||
|
||||
const mcpServers = useMemo(() => mcpServersFromConfig(config?.content?.mcp), [config])
|
||||
const serverIds = useMemo(
|
||||
() => [...new Set([...Object.keys(mcpServers), ...Object.keys(mcpStatus ?? {})])],
|
||||
[mcpServers, mcpStatus],
|
||||
)
|
||||
|
||||
const deleteServerMutation = useMutation({
|
||||
mutationFn: async (serverId: string) => {
|
||||
if (!config) return
|
||||
|
||||
const currentStatus = mcpStatus?.[serverId]
|
||||
if (currentStatus?.status === 'connected') {
|
||||
await disconnect(serverId)
|
||||
if (config && mcpServers[serverId]) {
|
||||
await onUpdate({
|
||||
...config.content,
|
||||
mcp: withoutMcpServer(config.content.mcp, serverId),
|
||||
})
|
||||
}
|
||||
|
||||
const currentMcp = (config.content?.mcp as Record<string, McpServerConfig>) || {}
|
||||
const { [serverId]: _, ...rest } = currentMcp
|
||||
void _
|
||||
|
||||
const updatedConfig = {
|
||||
...config.content,
|
||||
mcp: rest,
|
||||
}
|
||||
|
||||
await onUpdate(updatedConfig)
|
||||
|
||||
await mcpApi.removeServer(serverId)
|
||||
},
|
||||
onSuccess: async () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
await refetchStatus()
|
||||
setDeleteConfirmServer(null)
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to delete MCP server')
|
||||
onError: (error) => {
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to delete MCP server'))
|
||||
},
|
||||
})
|
||||
|
||||
const mcpServers = config?.content?.mcp as Record<string, McpServerConfig> || {}
|
||||
|
||||
const isAnyOperationPending = deleteServerMutation.isPending || togglingServerId !== null
|
||||
|
||||
const handleToggleServer = async (serverId: string) => {
|
||||
const currentStatus = mcpStatus?.[serverId]
|
||||
if (!currentStatus) return
|
||||
|
||||
const serverConfig = mcpServers[serverId]
|
||||
const isRemote = serverConfig?.type === 'remote'
|
||||
const hasOAuthConfig = isRemote && !!serverConfig?.oauth
|
||||
const hasOAuthError = currentStatus.status === 'failed' && isRemote && /oauth|auth.*state/i.test(currentStatus.error)
|
||||
const isOAuthServer = hasOAuthConfig || hasOAuthError || (currentStatus.status === 'needs_auth' && isRemote)
|
||||
|
||||
if (currentStatus.status === 'needs_auth' || (currentStatus.status === 'failed' && isOAuthServer)) {
|
||||
if (currentStatus.status === 'needs_auth') {
|
||||
setAuthDialogServerId(serverId)
|
||||
return
|
||||
}
|
||||
@@ -95,9 +91,7 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
try {
|
||||
if (currentStatus.status === 'connected') {
|
||||
await disconnect(serverId)
|
||||
} else if (currentStatus.status === 'disabled') {
|
||||
await connect(serverId)
|
||||
} else if (currentStatus.status === 'failed') {
|
||||
} else {
|
||||
await connect(serverId)
|
||||
}
|
||||
} finally {
|
||||
@@ -112,30 +106,13 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
|
||||
const handleOAuthStartAuth = async (): Promise<McpAuthStartResponse> => {
|
||||
if (!authDialogServerId) throw new Error('No server ID')
|
||||
const serverConfig = mcpServers[authDialogServerId]
|
||||
if (!serverConfig?.url) throw new Error('Server URL not found')
|
||||
const oauthConfig = typeof serverConfig.oauth === 'object' ? serverConfig.oauth : undefined
|
||||
return await mcpApi.startAuth(
|
||||
authDialogServerId,
|
||||
serverConfig.url,
|
||||
oauthConfig?.scope,
|
||||
oauthConfig?.clientId,
|
||||
oauthConfig?.clientSecret,
|
||||
)
|
||||
}
|
||||
|
||||
const handleOAuthCompleteAuth = async (code: string) => {
|
||||
if (!authDialogServerId) return
|
||||
await mcpApi.completeAuth(authDialogServerId, code)
|
||||
refetchStatus()
|
||||
setAuthDialogServerId(null)
|
||||
return await mcpApi.startAuth(authDialogServerId)
|
||||
}
|
||||
|
||||
const handleOAuthCheckStatus = async (): Promise<boolean> => {
|
||||
if (!authDialogServerId) return false
|
||||
const status = await mcpApi.getStatus()
|
||||
const serverStatus = status[authDialogServerId]
|
||||
if (serverStatus?.status === 'connected') {
|
||||
if (status[authDialogServerId]?.status === 'connected') {
|
||||
refetchStatus()
|
||||
return true
|
||||
}
|
||||
@@ -164,13 +141,9 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
const getErrorMessage = (serverId: string): string | null => {
|
||||
const status = mcpStatus?.[serverId]
|
||||
if (!status) return null
|
||||
if (status.status === 'failed') return status.error
|
||||
if (status.status === 'needs_client_registration') return status.error
|
||||
if (status?.status === 'failed') return status.error ?? null
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -225,11 +198,11 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
<SettingsList
|
||||
isLoading={false}
|
||||
error={null}
|
||||
isEmpty={Object.keys(mcpServers).length === 0}
|
||||
isEmpty={serverIds.length === 0}
|
||||
emptyTitle="No MCP servers configured"
|
||||
emptyHint="Add your first server to get started."
|
||||
>
|
||||
{Object.entries(mcpServers).map(([serverId, serverConfig]) => {
|
||||
{serverIds.map((serverId) => {
|
||||
const status = mcpStatus?.[serverId]
|
||||
const isConnected = status?.status === 'connected'
|
||||
const errorMessage = getErrorMessage(serverId)
|
||||
@@ -238,7 +211,7 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
<McpServerCard
|
||||
key={serverId}
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
serverConfig={mcpServers[serverId]}
|
||||
status={status}
|
||||
isConnected={isConnected}
|
||||
errorMessage={errorMessage}
|
||||
@@ -270,7 +243,6 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
onOpenChange={(open) => !open && setAuthDialogServerId(null)}
|
||||
serverName={authDialogServerId || ''}
|
||||
onStartAuth={handleOAuthStartAuth}
|
||||
onCompleteAuth={handleOAuthCompleteAuth}
|
||||
onCheckStatus={handleOAuthCheckStatus}
|
||||
onSuccess={handleOAuthSuccess}
|
||||
/>
|
||||
@@ -282,14 +254,9 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
onCancel={() => setRemoveAuthConfirmServer(null)}
|
||||
title="Remove Authentication"
|
||||
description="This will remove the OAuth credentials for this MCP server. You will need to re-authenticate to use this server again."
|
||||
itemName={mcpServers[removeAuthConfirmServer || ''] ? getDisplayName(removeAuthConfirmServer || '') : ''}
|
||||
itemName={removeAuthConfirmServer ? formatMcpServerName(removeAuthConfirmServer) : ''}
|
||||
isDeleting={isRemovingAuth}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
function getDisplayName(serverId: string): string {
|
||||
const name = serverId.replace(/[-_]/g, ' ')
|
||||
return name.charAt(0).toUpperCase() + name.slice(1)
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,7 @@ import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Loader2, ExternalLink, Key, XCircle, ChevronDown, ChevronUp, CheckCircle } from 'lucide-react'
|
||||
import { Loader2, ExternalLink, Key, XCircle, CheckCircle } from 'lucide-react'
|
||||
import type { McpAuthStartResponse } from '@/api/mcp'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
|
||||
@@ -13,7 +11,6 @@ interface McpOAuthDialogProps {
|
||||
onOpenChange: (open: boolean) => void
|
||||
serverName: string
|
||||
onStartAuth: () => Promise<McpAuthStartResponse>
|
||||
onCompleteAuth: (code: string) => Promise<void>
|
||||
onCheckStatus?: () => Promise<boolean>
|
||||
onSuccess?: () => void
|
||||
directory?: string
|
||||
@@ -26,17 +23,13 @@ export function McpOAuthDialog({
|
||||
onOpenChange,
|
||||
serverName,
|
||||
onStartAuth,
|
||||
onCompleteAuth,
|
||||
onCheckStatus,
|
||||
onSuccess,
|
||||
directory
|
||||
}: McpOAuthDialogProps) {
|
||||
const [step, setStep] = useState<Step>('loading')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [authUrl, setAuthUrl] = useState<string | null>(null)
|
||||
const [authCode, setAuthCode] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showManualEntry, setShowManualEntry] = useState(false)
|
||||
const flowIdRef = useRef<string | null>(null)
|
||||
const flowPollingRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const statusPollingRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
@@ -78,10 +71,7 @@ export function McpOAuthDialog({
|
||||
const resetState = useCallback(() => {
|
||||
setStep('loading')
|
||||
setAuthUrl(null)
|
||||
setAuthCode('')
|
||||
setError(null)
|
||||
setLoading(false)
|
||||
setShowManualEntry(false)
|
||||
stopAllPolling()
|
||||
doneRef.current = false
|
||||
flowIdRef.current = null
|
||||
@@ -192,21 +182,6 @@ export function McpOAuthDialog({
|
||||
startStatusPolling()
|
||||
}
|
||||
|
||||
const handleCompleteManualAuth = async () => {
|
||||
if (!authCode.trim()) return
|
||||
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
await onCompleteAuth(authCode.trim())
|
||||
handleSuccess()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to complete authentication')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (!newOpen) {
|
||||
resetState()
|
||||
@@ -307,46 +282,15 @@ export function McpOAuthDialog({
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<ManualCodeEntry
|
||||
showManualEntry={showManualEntry}
|
||||
setShowManualEntry={setShowManualEntry}
|
||||
authCode={authCode}
|
||||
setAuthCode={setAuthCode}
|
||||
loading={loading}
|
||||
onSubmit={handleCompleteManualAuth}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'popup_closed' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-blue-500" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Checking authentication status...</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center justify-center py-6 gap-2">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-blue-500" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
If authorization was completed, this will update shortly. Otherwise, paste the <code className="text-xs bg-muted px-1 py-0.5 rounded">code</code> parameter from the redirect URL below.
|
||||
Checking authentication status...
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="auth-code">Authorization Code</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="auth-code"
|
||||
value={authCode}
|
||||
onChange={(e) => setAuthCode(e.target.value)}
|
||||
placeholder="Paste code here..."
|
||||
disabled={loading}
|
||||
className="text-sm"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCompleteManualAuth}
|
||||
disabled={loading || !authCode.trim()}
|
||||
size="sm"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Submit'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{authUrl && (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -355,7 +299,7 @@ export function McpOAuthDialog({
|
||||
onClick={handleOpenAuthPage}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Try Again
|
||||
Re-open authorization page
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -386,7 +330,6 @@ export function McpOAuthDialog({
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
@@ -396,58 +339,3 @@ export function McpOAuthDialog({
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function ManualCodeEntry({
|
||||
showManualEntry,
|
||||
setShowManualEntry,
|
||||
authCode,
|
||||
setAuthCode,
|
||||
loading,
|
||||
onSubmit,
|
||||
}: {
|
||||
showManualEntry: boolean
|
||||
setShowManualEntry: (show: boolean) => void
|
||||
authCode: string
|
||||
setAuthCode: (code: string) => void
|
||||
loading: boolean
|
||||
onSubmit: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="border-t border-border pt-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowManualEntry(!showManualEntry)}
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors w-full"
|
||||
>
|
||||
{showManualEntry ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
Paste authorization code manually
|
||||
</button>
|
||||
|
||||
{showManualEntry && (
|
||||
<div className="space-y-2 mt-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
After authorizing, copy the <code className="bg-muted px-1 py-0.5 rounded">code</code> parameter from the redirect URL in your browser.
|
||||
</p>
|
||||
<Label htmlFor="auth-code" className="text-xs">Authorization Code</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="auth-code"
|
||||
value={authCode}
|
||||
onChange={(e) => setAuthCode(e.target.value)}
|
||||
placeholder="Paste code here..."
|
||||
disabled={loading}
|
||||
className="text-sm"
|
||||
/>
|
||||
<Button
|
||||
onClick={onSubmit}
|
||||
disabled={loading || !authCode.trim()}
|
||||
size="sm"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Submit'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -101,4 +101,73 @@ describe('McpServerCard', () => {
|
||||
expect(onDeleteServer).toHaveBeenCalledTimes(1)
|
||||
expect(onDeleteServer).toHaveBeenCalledWith('my-test-server', 'My test server')
|
||||
})
|
||||
|
||||
it('renders the Connecting badge for a pending server', () => {
|
||||
render(
|
||||
<McpServerCard
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={{ status: 'pending' }}
|
||||
isConnected={false}
|
||||
errorMessage={null}
|
||||
isAnyOperationPending={false}
|
||||
togglingServerId={null}
|
||||
isRemovingAuth={false}
|
||||
onToggleServer={vi.fn()}
|
||||
onDeleteServer={vi.fn()}
|
||||
onAuthenticate={vi.fn()}
|
||||
onRemoveAuth={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Connecting')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('offers auth for an OAuth integration even without an error message', () => {
|
||||
render(
|
||||
<McpServerCard
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={{ status: 'failed', error: 'MCP error -32000', integrationID: 'int-1' }}
|
||||
isConnected={false}
|
||||
errorMessage="MCP error -32000"
|
||||
isAnyOperationPending={false}
|
||||
togglingServerId={null}
|
||||
isRemovingAuth={false}
|
||||
onToggleServer={vi.fn()}
|
||||
onDeleteServer={vi.fn()}
|
||||
onAuthenticate={vi.fn()}
|
||||
onRemoveAuth={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Auth/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('offers remove auth for a connected OAuth integration', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onRemoveAuth = vi.fn()
|
||||
|
||||
render(
|
||||
<McpServerCard
|
||||
serverId={serverId}
|
||||
serverConfig={serverConfig}
|
||||
status={{ status: 'connected', integrationID: 'int-1' }}
|
||||
isConnected={true}
|
||||
errorMessage={null}
|
||||
isAnyOperationPending={false}
|
||||
togglingServerId={null}
|
||||
isRemovingAuth={false}
|
||||
onToggleServer={vi.fn()}
|
||||
onDeleteServer={vi.fn()}
|
||||
onAuthenticate={vi.fn()}
|
||||
onRemoveAuth={onRemoveAuth}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for My test server'))
|
||||
await user.click(screen.getByText('Remove Auth'))
|
||||
|
||||
expect(onRemoveAuth).toHaveBeenCalledWith('my-test-server')
|
||||
})
|
||||
})
|
||||
@@ -2,12 +2,14 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { SettingsListRow, type SettingsListRowAction } from '@/components/ui/settings-list'
|
||||
import { XCircle, AlertCircle, Key, Shield, Trash2, RefreshCw } from 'lucide-react'
|
||||
import { XCircle, Key, Shield, Trash2, RefreshCw } from 'lucide-react'
|
||||
import type { McpStatus, McpServerConfig } from '@/api/mcp'
|
||||
import { formatMcpServerName } from '@/lib/mcp'
|
||||
import { McpStatusBadge } from './McpStatusBadge'
|
||||
|
||||
interface McpServerCardProps {
|
||||
serverId: string
|
||||
serverConfig: McpServerConfig
|
||||
serverConfig?: McpServerConfig
|
||||
status?: McpStatus
|
||||
isConnected: boolean
|
||||
errorMessage: string | null
|
||||
@@ -20,45 +22,8 @@ interface McpServerCardProps {
|
||||
onDeleteServer: (serverId: string, serverName: string) => void
|
||||
}
|
||||
|
||||
function getStatusBadge(status: McpStatus) {
|
||||
switch (status.status) {
|
||||
case 'connected':
|
||||
return <Badge variant="default" className="text-xs bg-green-600">Connected</Badge>
|
||||
case 'disabled':
|
||||
return <Badge variant="secondary" className="text-xs">Disabled</Badge>
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs flex items-center gap-1">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_auth':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs flex items-center gap-1 border-yellow-500 text-yellow-600">
|
||||
<Key className="h-3 w-3" />
|
||||
Auth Required
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_client_registration':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs flex items-center gap-1 border-orange-500 text-orange-600">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Registration Required
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return <Badge variant="outline" className="text-xs">Unknown</Badge>
|
||||
}
|
||||
}
|
||||
|
||||
function getServerDisplayName(serverId: string): string {
|
||||
const name = serverId.replace(/[-_]/g, ' ')
|
||||
return name.charAt(0).toUpperCase() + name.slice(1)
|
||||
}
|
||||
|
||||
function getServerDescription(serverConfig: McpServerConfig): string {
|
||||
if (serverConfig.type === 'local' && serverConfig.command) {
|
||||
function getServerDescription(serverConfig: McpServerConfig | undefined): string {
|
||||
if (serverConfig?.type === 'local') {
|
||||
const command = serverConfig.command.join(' ')
|
||||
if (command.includes('filesystem')) return 'File system access'
|
||||
if (command.includes('git')) return 'Git repository operations'
|
||||
@@ -71,7 +36,7 @@ function getServerDescription(serverConfig: McpServerConfig): string {
|
||||
if (command.includes('fetch')) return 'HTTP requests'
|
||||
if (command.includes('memory')) return 'Persistent memory'
|
||||
return `Local command: ${command}`
|
||||
} else if (serverConfig.type === 'remote' && serverConfig.url) {
|
||||
} else if (serverConfig?.type === 'remote') {
|
||||
return `Remote server: ${serverConfig.url}`
|
||||
}
|
||||
return 'MCP server'
|
||||
@@ -92,13 +57,10 @@ export function McpServerCard({
|
||||
onDeleteServer
|
||||
}: McpServerCardProps) {
|
||||
const needsAuth = status?.status === 'needs_auth'
|
||||
const isRemote = serverConfig.type === 'remote'
|
||||
const hasOAuthConfig = isRemote && !!serverConfig.oauth
|
||||
const hasOAuthError = status?.status === 'failed' && isRemote && /oauth|auth.*state/i.test(status.error)
|
||||
const isOAuthServer = hasOAuthConfig || hasOAuthError || (needsAuth && isRemote)
|
||||
const isOAuthServer = !!status?.integrationID
|
||||
const connectedWithOAuth = isOAuthServer && isConnected
|
||||
const showAuthButton = needsAuth || (isOAuthServer && status?.status === 'failed')
|
||||
const displayName = getServerDisplayName(serverId)
|
||||
const displayName = formatMcpServerName(serverId)
|
||||
|
||||
const actions: SettingsListRowAction[] = []
|
||||
if (showAuthButton && onAuthenticate) {
|
||||
@@ -122,7 +84,7 @@ export function McpServerCard({
|
||||
<Shield className="h-3 w-3 text-muted-foreground" />
|
||||
</span>
|
||||
)}
|
||||
{status ? getStatusBadge(status) : (
|
||||
{status ? <McpStatusBadge status={status} /> : (
|
||||
<Badge variant="outline" className="text-xs">Loading...</Badge>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { AlertCircle, Key } from 'lucide-react'
|
||||
import type { McpStatus } from '@/api/mcp'
|
||||
|
||||
interface McpStatusBadgeProps {
|
||||
status: McpStatus
|
||||
}
|
||||
|
||||
export function McpStatusBadge({ status }: McpStatusBadgeProps) {
|
||||
switch (status.status) {
|
||||
case 'connected':
|
||||
return <Badge variant="default" className="text-xs bg-green-600">Connected</Badge>
|
||||
case 'pending':
|
||||
return <Badge variant="outline" className="text-xs">Connecting</Badge>
|
||||
case 'disabled':
|
||||
return <Badge variant="secondary" className="text-xs">Disabled</Badge>
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs flex items-center gap-1">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_auth':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs flex items-center gap-1 border-yellow-500 text-yellow-600">
|
||||
<Key className="h-3 w-3" />
|
||||
Auth Required
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return <Badge variant="outline" className="text-xs">Unknown</Badge>
|
||||
}
|
||||
}
|
||||
@@ -1,146 +1,114 @@
|
||||
import { useState, useMemo, useEffect, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
import { oauthApi, type OAuthAuthorizeResponse, type ProviderAuthMethod } from '@/api/oauth'
|
||||
import {
|
||||
oauthApi,
|
||||
type FormAnswer,
|
||||
type FormValue,
|
||||
type IntegrationMethod,
|
||||
type IntegrationOAuthMethod,
|
||||
type OAuthAuthorizeResponse,
|
||||
} from '@/api/oauth'
|
||||
import { buildAnswer, hasFields, hasMissingAnswers, resolveAnswers, setAnswerValue, visibleFields } from '@/lib/formFields'
|
||||
import { mapOAuthError } from '@/lib/oauthErrors'
|
||||
import { ProviderAuthField } from './ProviderAuthField'
|
||||
|
||||
interface OAuthAuthorizeDialogProps {
|
||||
providerId: string
|
||||
providerName: string
|
||||
methods: ProviderAuthMethod[]
|
||||
methods: IntegrationMethod[]
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSuccess: (response: OAuthAuthorizeResponse, methodIndex: number) => void
|
||||
onSuccess: (response: OAuthAuthorizeResponse, methodID: string) => void
|
||||
}
|
||||
|
||||
type OAuthPrompt = NonNullable<ProviderAuthMethod['prompts']>[number]
|
||||
|
||||
function isBrowserLocalMethod(method: ProviderAuthMethod): boolean {
|
||||
function isBrowserLocalMethod(method: IntegrationOAuthMethod): boolean {
|
||||
return method.label.toLowerCase().includes('browser')
|
||||
}
|
||||
|
||||
function getVisiblePrompts(method: ProviderAuthMethod, inputs: Record<string, string>): OAuthPrompt[] {
|
||||
const visiblePrompts: OAuthPrompt[] = []
|
||||
const activeInputs: Record<string, string> = {}
|
||||
|
||||
for (const prompt of method.prompts ?? []) {
|
||||
const isVisible = !('when' in prompt) || !prompt.when || activeInputs[prompt.when.key] === prompt.when.value
|
||||
|
||||
if (!isVisible) {
|
||||
continue
|
||||
}
|
||||
|
||||
visiblePrompts.push(prompt)
|
||||
|
||||
if (inputs[prompt.key]) {
|
||||
activeInputs[prompt.key] = inputs[prompt.key]
|
||||
}
|
||||
}
|
||||
|
||||
return visiblePrompts
|
||||
}
|
||||
|
||||
function hasPrompts(method: ProviderAuthMethod): boolean {
|
||||
return (method.prompts?.length ?? 0) > 0
|
||||
}
|
||||
|
||||
export function OAuthAuthorizeDialog({
|
||||
providerId,
|
||||
export function OAuthAuthorizeDialog({
|
||||
providerId,
|
||||
providerName,
|
||||
methods,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
}: OAuthAuthorizeDialogProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [selectedMethodIndex, setSelectedMethodIndex] = useState<number | null>(null)
|
||||
const [promptInputs, setPromptInputs] = useState<Record<number, Record<string, string>>>({})
|
||||
const [selectedMethodID, setSelectedMethodID] = useState<string | null>(null)
|
||||
const [answers, setAnswers] = useState<Record<string, FormAnswer>>({})
|
||||
const [autoStarted, setAutoStarted] = useState(false)
|
||||
|
||||
const getMethodInputs = useCallback((methodIndex: number) => promptInputs[methodIndex] || {}, [promptInputs])
|
||||
|
||||
const oauthMethods = useMemo(() => {
|
||||
return methods
|
||||
.flatMap((method, index) => method.type === 'oauth' ? [{ method, index }] : [])
|
||||
.filter(({ method }: { method: ProviderAuthMethod }) => {
|
||||
if (providerId === 'openai' && isBrowserLocalMethod(method)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
.filter((method): method is IntegrationOAuthMethod => method.type === 'oauth')
|
||||
.filter((method) => !(providerId === 'openai' && isBrowserLocalMethod(method)))
|
||||
}, [methods, providerId])
|
||||
|
||||
const handleAuthorize = useCallback(async (methodIndex: number) => {
|
||||
const method = methods[methodIndex]
|
||||
const methodInputs = getMethodInputs(methodIndex)
|
||||
const visiblePrompts = getVisiblePrompts(method, methodInputs)
|
||||
const missingPrompt = visiblePrompts.some((prompt) => !methodInputs[prompt.key]?.trim())
|
||||
const getAnswer = useCallback(
|
||||
(method: IntegrationOAuthMethod) => resolveAnswers(method.form, answers[method.id]),
|
||||
[answers],
|
||||
)
|
||||
|
||||
if (missingPrompt) {
|
||||
setError('Please complete all authentication fields')
|
||||
setSelectedMethodIndex(methodIndex)
|
||||
const handleAnswerChange = useCallback((methodID: string, key: string, value: FormValue | undefined) => {
|
||||
setAnswers((prev) => setAnswerValue(prev, methodID, key, value))
|
||||
}, [])
|
||||
|
||||
const handleAuthorize = useCallback(async (method: IntegrationOAuthMethod) => {
|
||||
const answer = getAnswer(method)
|
||||
const fields = visibleFields(method.form ?? [], answer)
|
||||
|
||||
if (hasMissingAnswers(method.form ?? [], answer)) {
|
||||
setError('Please complete all required authentication fields')
|
||||
setSelectedMethodID(method.id)
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
setSelectedMethodIndex(methodIndex)
|
||||
setSelectedMethodID(method.id)
|
||||
|
||||
try {
|
||||
const inputs = visiblePrompts.length > 0
|
||||
? Object.fromEntries(
|
||||
visiblePrompts.map((prompt) => [prompt.key, methodInputs[prompt.key].trim()])
|
||||
)
|
||||
: undefined
|
||||
const response = await oauthApi.authorize(providerId, methodIndex, inputs)
|
||||
onSuccess(response, methodIndex)
|
||||
const response = await oauthApi.authorize(
|
||||
providerId,
|
||||
method.id,
|
||||
fields.length > 0 ? buildAnswer(method.form ?? [], answer) : undefined,
|
||||
)
|
||||
onSuccess(response, method.id)
|
||||
} catch (err) {
|
||||
setError(mapOAuthError(err, 'authorize'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [methods, providerId, onSuccess, getMethodInputs])
|
||||
}, [getAnswer, providerId, onSuccess])
|
||||
|
||||
useEffect(() => {
|
||||
if (open && oauthMethods.length === 1 && !autoStarted && !isLoading) {
|
||||
const { index } = oauthMethods[0]
|
||||
const method = oauthMethods[0]
|
||||
setAutoStarted(true)
|
||||
setSelectedMethodIndex(index)
|
||||
if (!hasPrompts(methods[index])) {
|
||||
void handleAuthorize(index)
|
||||
setSelectedMethodID(method.id)
|
||||
if (!hasFields(method.form)) {
|
||||
void handleAuthorize(method)
|
||||
}
|
||||
}
|
||||
}, [open, oauthMethods, autoStarted, isLoading, methods, handleAuthorize])
|
||||
}, [open, oauthMethods, autoStarted, isLoading, handleAuthorize])
|
||||
|
||||
const handleMethodSelection = (methodIndex: number) => {
|
||||
const handleMethodSelection = (method: IntegrationOAuthMethod) => {
|
||||
setError(null)
|
||||
setSelectedMethodIndex(methodIndex)
|
||||
setSelectedMethodID(method.id)
|
||||
|
||||
if (!hasPrompts(methods[methodIndex])) {
|
||||
void handleAuthorize(methodIndex)
|
||||
if (!hasFields(method.form)) {
|
||||
void handleAuthorize(method)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePromptChange = (methodIndex: number, key: string, value: string) => {
|
||||
setPromptInputs((prev) => ({
|
||||
...prev,
|
||||
[methodIndex]: {
|
||||
...prev[methodIndex],
|
||||
[key]: value,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setError(null)
|
||||
setPromptInputs({})
|
||||
setSelectedMethodIndex(null)
|
||||
setAnswers({})
|
||||
setSelectedMethodID(null)
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
@@ -161,23 +129,25 @@ export function OAuthAuthorizeDialog({
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{oauthMethods.map(({ method, index }) => {
|
||||
{oauthMethods.map((method) => {
|
||||
const isBrowserLocal = isBrowserLocalMethod(method)
|
||||
const methodInputs = getMethodInputs(index)
|
||||
const visiblePrompts = getVisiblePrompts(method, methodInputs)
|
||||
const canSubmitPrompts = visiblePrompts.every((prompt) => methodInputs[prompt.key]?.trim())
|
||||
|
||||
const answer = getAnswer(method)
|
||||
const fields = visibleFields(method.form ?? [], answer)
|
||||
const canSubmit = !hasMissingAnswers(method.form ?? [], answer)
|
||||
|
||||
return (
|
||||
<div key={index} className="space-y-3">
|
||||
<div key={method.id} className="space-y-3">
|
||||
<div className="flex items-center gap-2 flex-wrap sm:flex-nowrap">
|
||||
<Button
|
||||
onClick={() => handleMethodSelection(index)}
|
||||
onClick={() => handleMethodSelection(method)}
|
||||
disabled={isLoading}
|
||||
className="flex-1 justify-start min-w-0"
|
||||
variant={selectedMethodIndex === index ? 'default' : 'outline'}
|
||||
variant={selectedMethodID === method.id ? 'default' : 'outline'}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2 shrink-0" />
|
||||
<span className="truncate">{isLoading && selectedMethodIndex === index ? 'Authorizing...' : method.label}</span>
|
||||
<span className="truncate">
|
||||
{isLoading && selectedMethodID === method.id ? 'Authorizing...' : method.label}
|
||||
</span>
|
||||
</Button>
|
||||
{isBrowserLocal && (
|
||||
<Badge variant="secondary" className="text-xs shrink-0">
|
||||
@@ -186,54 +156,28 @@ export function OAuthAuthorizeDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selectedMethodIndex === index && hasPrompts(method) && (
|
||||
{selectedMethodID === method.id && hasFields(method.form) && (
|
||||
<div className="space-y-3 pl-4 sm:pl-10 pr-1 py-2">
|
||||
{visiblePrompts.map((prompt) => (
|
||||
prompt.type === 'text' ? (
|
||||
<div key={prompt.key} className="space-y-2">
|
||||
<Label htmlFor={prompt.key}>{prompt.message}</Label>
|
||||
<Input
|
||||
id={prompt.key}
|
||||
value={methodInputs[prompt.key] || ''}
|
||||
onChange={(e) => handlePromptChange(index, prompt.key, e.target.value)}
|
||||
placeholder={prompt.placeholder}
|
||||
className="bg-background border-border"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div key={prompt.key} className="space-y-2">
|
||||
<Label>{prompt.message}</Label>
|
||||
<Select
|
||||
value={methodInputs[prompt.key] || ''}
|
||||
onValueChange={(value) => handlePromptChange(index, prompt.key, value)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<SelectTrigger className="bg-background border-border">
|
||||
<SelectValue placeholder="Select an option" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{prompt.options.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)
|
||||
{fields.map((field) => (
|
||||
<ProviderAuthField
|
||||
key={field.key}
|
||||
field={field}
|
||||
value={answer[field.key]}
|
||||
disabled={isLoading}
|
||||
onChange={(value) => handleAnswerChange(method.id, field.key, value)}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Button
|
||||
onClick={() => void handleAuthorize(index)}
|
||||
disabled={isLoading || !canSubmitPrompts}
|
||||
onClick={() => void handleAuthorize(method)}
|
||||
disabled={isLoading || !canSubmit}
|
||||
className="w-full"
|
||||
>
|
||||
{isLoading && selectedMethodIndex === index ? 'Authorizing...' : 'Continue'}
|
||||
{isLoading && selectedMethodID === method.id ? 'Authorizing...' : 'Continue'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{isBrowserLocal && (
|
||||
<p className="text-xs text-muted-foreground pl-1 break-words">
|
||||
This method relies on a callback server started by OpenCode and may not work when OCM is remote.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
@@ -13,46 +13,92 @@ interface OAuthCallbackDialogProps {
|
||||
providerId: string
|
||||
providerName: string
|
||||
authResponse: OAuthAuthorizeResponse
|
||||
methodIndex: number
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function OAuthCallbackDialog({
|
||||
providerId,
|
||||
providerName,
|
||||
const POLL_INTERVAL_MS = 2000
|
||||
|
||||
export function OAuthCallbackDialog({
|
||||
providerId,
|
||||
providerName,
|
||||
authResponse,
|
||||
methodIndex,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
}: OAuthCallbackDialogProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [loadingMessage, setLoadingMessage] = useState('')
|
||||
const [authCode, setAuthCode] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const isAutoMethod = authResponse.mode === 'auto'
|
||||
const completedRef = useRef(false)
|
||||
const onSuccessRef = useRef(onSuccess)
|
||||
onSuccessRef.current = onSuccess
|
||||
|
||||
useEffect(() => {
|
||||
completedRef.current = false
|
||||
setIsLoading(false)
|
||||
setAuthCode('')
|
||||
setError(null)
|
||||
}, [authResponse.attemptID])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !isAutoMethod) return
|
||||
|
||||
let cancelled = false
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
const poll = async () => {
|
||||
while (!cancelled) {
|
||||
try {
|
||||
const status = await oauthApi.getStatus(providerId, authResponse.attemptID)
|
||||
if (cancelled) return
|
||||
|
||||
if (status.status === 'complete') {
|
||||
completedRef.current = true
|
||||
setIsLoading(false)
|
||||
onSuccessRef.current()
|
||||
return
|
||||
}
|
||||
|
||||
if (status.status === 'failed' || status.status === 'expired') {
|
||||
setIsLoading(false)
|
||||
setError(status.message ?? 'Authentication failed')
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setIsLoading(false)
|
||||
setError(mapOAuthError(err, 'callback'))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS))
|
||||
}
|
||||
}
|
||||
|
||||
void poll()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, isAutoMethod, providerId, authResponse.attemptID])
|
||||
|
||||
const handleCallback = async () => {
|
||||
setIsLoading(true)
|
||||
setLoadingMessage('Completing authentication...')
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
setLoadingMessage('Restarting server with new credentials...')
|
||||
await oauthApi.callback(
|
||||
providerId,
|
||||
authResponse.method === 'code'
|
||||
? { method: methodIndex, code: authCode.trim() }
|
||||
: { method: methodIndex }
|
||||
)
|
||||
onSuccess()
|
||||
await oauthApi.callback(providerId, authResponse.attemptID, authCode.trim() || undefined)
|
||||
completedRef.current = true
|
||||
onSuccessRef.current()
|
||||
} catch (err) {
|
||||
setError(mapOAuthError(err, 'callback'))
|
||||
console.error('OAuth callback error:', err)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
setLoadingMessage('')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,11 +109,14 @@ export function OAuthCallbackDialog({
|
||||
const handleClose = () => {
|
||||
setError(null)
|
||||
setAuthCode('')
|
||||
|
||||
if (!completedRef.current) {
|
||||
void oauthApi.cancel(providerId, authResponse.attemptID).catch(() => undefined)
|
||||
}
|
||||
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
const isAutoMethod = authResponse.method === 'auto'
|
||||
|
||||
// Extract device/user code from instructions (e.g., "Enter code: 596A-E304")
|
||||
const codeMatch = authResponse.instructions.match(/(?:Enter code|User code|Device code)[:\s]+([A-Z0-9-]+)/i)
|
||||
const deviceCode = codeMatch ? codeMatch[1] : ''
|
||||
@@ -78,7 +127,7 @@ export function OAuthCallbackDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Complete {providerName} Authentication</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isAutoMethod
|
||||
{isAutoMethod
|
||||
? 'Follow the instructions below to complete authentication.'
|
||||
: 'Enter the authorization code from the provider.'
|
||||
}
|
||||
@@ -95,7 +144,7 @@ export function OAuthCallbackDialog({
|
||||
<div className="space-y-3">
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-sm mb-2">{authResponse.instructions}</p>
|
||||
|
||||
|
||||
{deviceCode && (
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<code className="flex-1 bg-background px-3 py-2 rounded text-sm font-mono">
|
||||
@@ -111,7 +160,7 @@ export function OAuthCallbackDialog({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleOpenAuthUrl}
|
||||
@@ -154,26 +203,32 @@ export function OAuthCallbackDialog({
|
||||
className="bg-background border-border"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCallback}
|
||||
className="w-full"
|
||||
disabled={isLoading || !authCode.trim()}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Completing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
Complete Authentication
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
onClick={handleCallback}
|
||||
className="w-full"
|
||||
disabled={isLoading || (!isAutoMethod && !authCode.trim())}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{loadingMessage || 'Completing...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
Complete Authentication
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{isAutoMethod && (
|
||||
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Waiting for authorization to complete...
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
@@ -21,10 +21,6 @@ const JSONC_RAW = `{
|
||||
"theme": "system"
|
||||
}`
|
||||
|
||||
const CONFIG_JSON_RAW = `{
|
||||
"theme": "dark"
|
||||
}`
|
||||
|
||||
const config = makeOpenCodeConfigFile({ rawContent: RAW })
|
||||
|
||||
const multiSourceConfig = makeOpenCodeConfigFile({
|
||||
@@ -34,7 +30,6 @@ const multiSourceConfig = makeOpenCodeConfigFile({
|
||||
sources: [
|
||||
makeOpenCodeConfigSource({ name: 'opencode.jsonc', path: '/workspace/.config/opencode/opencode.jsonc', rawContent: JSONC_RAW }),
|
||||
makeOpenCodeConfigSource({ name: 'opencode.json', path: '/workspace/.config/opencode/opencode.json', rawContent: RAW }),
|
||||
makeOpenCodeConfigSource({ name: 'config.json', path: '/workspace/.config/opencode/config.json', rawContent: CONFIG_JSON_RAW }),
|
||||
],
|
||||
})
|
||||
|
||||
@@ -382,18 +377,18 @@ describe('OpenCodeConfigEditor', () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Source file' }))
|
||||
await user.click(screen.getByRole('option', { name: 'config.json' }))
|
||||
await user.click(screen.getByRole('option', { name: 'opencode.json' }))
|
||||
|
||||
expect(screen.getByText('Edit config.json')).toBeInTheDocument()
|
||||
expect(screen.getByText('/workspace/.config/opencode/config.json')).toBeInTheDocument()
|
||||
expect(screen.getByText('Edit opencode.json')).toBeInTheDocument()
|
||||
expect(screen.getByText('/workspace/.config/opencode/opencode.json')).toBeInTheDocument()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
expect(textarea).toHaveValue(CONFIG_JSON_RAW)
|
||||
expect(textarea).toHaveValue(RAW)
|
||||
|
||||
const next = '{\n "theme": "light"\n}'
|
||||
setContent(textarea, next)
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: next, source: 'config.json', expectedRevision: 'rev-2' })
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: next, source: 'opencode.json', expectedRevision: 'rev-2' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -413,10 +408,10 @@ describe('OpenCodeConfigEditor', () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Source file' }))
|
||||
await user.click(screen.getByRole('option', { name: 'config.json' }))
|
||||
await user.click(screen.getByRole('option', { name: 'opencode.json' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Download' }))
|
||||
|
||||
expect(saveFile).toHaveBeenCalledWith(expect.any(Blob), 'config.json')
|
||||
expect(saveFile).toHaveBeenCalledWith(expect.any(Blob), 'opencode.json')
|
||||
})
|
||||
|
||||
it('surfaces a conflict error without discarding the raw text', async () => {
|
||||
@@ -480,7 +475,6 @@ describe('OpenCodeConfigEditor', () => {
|
||||
updatedAt: 3,
|
||||
sources: [
|
||||
makeOpenCodeConfigSource({ name: 'opencode.json', path: '/workspace/.config/opencode/opencode.json', rawContent: RAW }),
|
||||
makeOpenCodeConfigSource({ name: 'config.json', path: '/workspace/.config/opencode/config.json', rawContent: CONFIG_JSON_RAW }),
|
||||
],
|
||||
})
|
||||
rerender(<OpenCodeConfigEditor config={sourceRemovedConfig} isOpen onClose={onClose} onUpdate={onUpdate} />)
|
||||
@@ -567,7 +561,7 @@ describe('OpenCodeConfigEditor', () => {
|
||||
|
||||
const notice = screen.getByText('Multiple configuration files are merged').closest('[role="alert"]') as HTMLElement
|
||||
expect(notice).toBeInTheDocument()
|
||||
expect(notice).toHaveTextContent('config.json, opencode.json, opencode.jsonc')
|
||||
expect(notice).toHaveTextContent('opencode.json, opencode.jsonc')
|
||||
expect(notice).toHaveTextContent('Saves apply only to opencode.jsonc')
|
||||
expect(notice).toHaveTextContent('For simpler configuration, consolidate the settings you need into one file, then remove redundant files after verifying the result.')
|
||||
|
||||
@@ -583,10 +577,10 @@ describe('OpenCodeConfigEditor', () => {
|
||||
expect(notice).toHaveTextContent('Saves apply only to opencode.jsonc')
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Source file' }))
|
||||
await user.click(screen.getByRole('option', { name: 'config.json' }))
|
||||
await user.click(screen.getByRole('option', { name: 'opencode.json' }))
|
||||
|
||||
const updatedNotice = screen.getByText('Multiple configuration files are merged').closest('[role="alert"]') as HTMLElement
|
||||
expect(updatedNotice).toHaveTextContent('Saves apply only to config.json')
|
||||
expect(updatedNotice).toHaveTextContent('Saves apply only to opencode.json')
|
||||
})
|
||||
|
||||
it('shows the file details disclosure expanded for a single source', () => {
|
||||
|
||||
@@ -487,7 +487,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
await waitFor(() => expect(showToast.success).toHaveBeenCalledWith('Configuration updated'))
|
||||
expect(showToast.success).not.toHaveBeenCalledWith('Configuration saved. Restart the server to apply changes.')
|
||||
expect(showToast.success).not.toHaveBeenCalledWith('Configuration saved, but OpenCode could not reload it. Restart the server to apply changes.')
|
||||
})
|
||||
|
||||
it('asks for a restart after a semantic structured change', async () => {
|
||||
@@ -505,7 +505,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
await waitFor(() => {
|
||||
expect(showToast.success).toHaveBeenCalledWith('Configuration saved. Restart the server to apply changes.')
|
||||
expect(showToast.success).toHaveBeenCalledWith('Configuration saved, but OpenCode could not reload it. Restart the server to apply changes.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -636,7 +636,6 @@ describe('OpenCodeConfigManager', () => {
|
||||
path: '/workspace/.config/opencode/opencode.jsonc',
|
||||
rawContent: '{}',
|
||||
sources: [
|
||||
makeOpenCodeConfigSource({ name: 'config.json', path: '/workspace/.config/opencode/config.json' }),
|
||||
makeOpenCodeConfigSource({ name: 'opencode.json', path: '/workspace/.config/opencode/opencode.json' }),
|
||||
makeOpenCodeConfigSource({ name: 'opencode.jsonc', path: '/workspace/.config/opencode/opencode.jsonc' }),
|
||||
],
|
||||
@@ -647,7 +646,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
|
||||
const notice = (await screen.findByText('Multiple configuration files are merged')).closest('[role="alert"]') as HTMLElement
|
||||
expect(notice).toBeInTheDocument()
|
||||
expect(notice).toHaveTextContent('config.json, opencode.json, opencode.jsonc')
|
||||
expect(notice).toHaveTextContent('opencode.json, opencode.jsonc')
|
||||
expect(notice).toHaveTextContent('Saves apply only to opencode.jsonc')
|
||||
expect(notice).toHaveTextContent('For simpler configuration, consolidate the settings you need into one file, then remove redundant files after verifying the result.')
|
||||
})
|
||||
|
||||
@@ -19,9 +19,11 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { useOpenCodeConfigFile, OPEN_CODE_CONFIG_QUERY_KEY } from '@/hooks/useOpenCodeConfigFile'
|
||||
import { useOpenCodeApplyFeedback } from '@/hooks/useOpenCodeApplyFeedback'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { mcpServersFromConfig } from '@opencode-manager/shared/opencode'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { getPreferredOpenCodeConfigSource, downloadOpenCodeConfigSource } from '@/api/types/settings'
|
||||
import type { OpenCodeConfigFile, OpenCodeConfigSaveResponse, OpenCodeImportStatus } from '@/api/types/settings'
|
||||
@@ -75,6 +77,7 @@ export function OpenCodeConfigManager() {
|
||||
const hostImportContentId = `${sectionIdPrefix}-host-import`
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const applyOpenCodeSaveFeedback = useOpenCodeApplyFeedback()
|
||||
const { data: health } = useServerHealth()
|
||||
const [expandedSections, setExpandedSections] = useState<Record<ConfigSectionKey, boolean>>({
|
||||
agentsMd: false,
|
||||
@@ -158,12 +161,10 @@ export function OpenCodeConfigManager() {
|
||||
|
||||
const applyOpenCodeConfigSave = (result: OpenCodeConfigSaveResponse) => {
|
||||
queryClient.setQueryData<OpenCodeConfigFile>(OPEN_CODE_CONFIG_QUERY_KEY, result)
|
||||
if (result.restartRequired) {
|
||||
showToast.success('Configuration saved. Restart the server to apply changes.')
|
||||
} else {
|
||||
showToast.success('Configuration updated')
|
||||
}
|
||||
invalidateConfigCaches(queryClient, { skipOpenCodeConfig: true })
|
||||
applyOpenCodeSaveFeedback({
|
||||
appliedMessage: 'Configuration updated',
|
||||
restartRequired: result.restartRequired,
|
||||
})
|
||||
}
|
||||
|
||||
const updateConfigContent = async (newContent: Record<string, unknown>) => {
|
||||
@@ -209,7 +210,7 @@ export function OpenCodeConfigManager() {
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-500" />
|
||||
<p className="text-sm">
|
||||
Configuration changes are saved but require a server restart to take effect.
|
||||
Some saved changes require a server restart to take effect.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
@@ -278,7 +279,7 @@ export function OpenCodeConfigManager() {
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Merged persisted settings. Saves write to the preferred config file; removing a value deletes its override so an inherited value can reappear. Restart the server to apply changes.
|
||||
Merged persisted settings. Saves write to the preferred config file; removing a value deletes its override so an inherited value can reappear. Saves are applied to the running server; a restart is only requested if applying them fails.
|
||||
</p>
|
||||
|
||||
<OpenCodeConfigSourcesNotice config={config} />
|
||||
@@ -459,7 +460,7 @@ export function OpenCodeConfigManager() {
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<h4 className={SECTION_TITLE_CLASS}>MCP Servers</h4>
|
||||
<span className={SECTION_META_CLASS}>
|
||||
{Object.keys((config.content.mcp as Record<string, unknown> | undefined) ?? {}).length} configured
|
||||
{Object.keys(mcpServersFromConfig(config.content.mcp)).length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={cn(SECTION_CHEVRON_CLASS, expandedSections.mcp && 'rotate-180')} />
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useOpenCodeServerAuth } from '@/hooks/useOpenCodeServerAuth'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { AlertTriangle, CheckCircle2, Eye, EyeOff, XCircle } from 'lucide-react'
|
||||
import { CheckCircle2, Eye, EyeOff } from 'lucide-react'
|
||||
import { SettingsDisclosure } from './SettingsDisclosure'
|
||||
|
||||
interface OpenCodeServerAuthSettingsProps {
|
||||
@@ -31,14 +31,14 @@ export function OpenCodeServerAuthSettings({ isOpen: controlledOpen, onToggle }:
|
||||
if (!status) return 'Loading...'
|
||||
if (status.source === 'db') return 'Set (configured via UI)'
|
||||
if (status.source === 'env') return 'Set (configured via env var)'
|
||||
return 'Not set'
|
||||
return 'Auto-generated by OpenCode Manager'
|
||||
}
|
||||
|
||||
const getStatusIcon = () => {
|
||||
if (!status) return null
|
||||
if (status.source === 'db') return <CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
if (status.source === 'env') return <CheckCircle2 className="h-4 w-4 text-blue-500" />
|
||||
return <XCircle className="h-4 w-4 text-red-500" />
|
||||
return <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -54,11 +54,10 @@ export function OpenCodeServerAuthSettings({ isOpen: controlledOpen, onToggle }:
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{status?.source === 'none' && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{status?.source === 'managed' && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
If you set OPENCODE_HOST=0.0.0.0 in Docker without a password, the server will refuse to start.
|
||||
OpenCode Manager generates and stores this password automatically. Set your own below to override it.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
@@ -99,7 +98,7 @@ export function OpenCodeServerAuthSettings({ isOpen: controlledOpen, onToggle }:
|
||||
onClick={() => clearPassword.mutate()}
|
||||
disabled={clearPassword.isPending}
|
||||
>
|
||||
{clearPassword.isPending ? 'Clearing...' : 'Clear stored password'}
|
||||
{clearPassword.isPending ? 'Clearing...' : 'Use auto-generated password'}
|
||||
</Button>
|
||||
)}
|
||||
</SettingsDisclosure>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { MultiSelect } from '@/components/ui/multi-select'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { ExternalFieldCard } from '@/components/ui/external-field-card'
|
||||
import type { FormField, FormValue } from '@/api/oauth'
|
||||
|
||||
interface ProviderAuthFieldProps {
|
||||
field: FormField
|
||||
value: FormValue | undefined
|
||||
disabled: boolean
|
||||
onChange: (value: FormValue | undefined) => void
|
||||
}
|
||||
|
||||
function fieldLabel(field: FormField): string {
|
||||
return field.title ?? field.key
|
||||
}
|
||||
|
||||
function FieldControl({ field, value, disabled, onChange }: ProviderAuthFieldProps) {
|
||||
if (field.type === 'boolean') {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={field.key}
|
||||
checked={value === true}
|
||||
onCheckedChange={(checked) => onChange(checked === true)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Label htmlFor={field.key} className="cursor-pointer">
|
||||
{fieldLabel(field)}
|
||||
</Label>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'number' || field.type === 'integer') {
|
||||
return (
|
||||
<Input
|
||||
id={field.key}
|
||||
type="number"
|
||||
value={typeof value === 'number' || typeof value === 'string' ? String(value) : ''}
|
||||
onChange={(e) => onChange(e.target.value === '' ? undefined : Number(e.target.value))}
|
||||
min={typeof field.minimum === 'number' ? field.minimum : undefined}
|
||||
max={typeof field.maximum === 'number' ? field.maximum : undefined}
|
||||
step={field.type === 'integer' ? 1 : 'any'}
|
||||
className="bg-background border-border"
|
||||
disabled={disabled}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'multiselect') {
|
||||
return (
|
||||
<MultiSelect
|
||||
value={Array.isArray(value) ? value : []}
|
||||
onChange={(next) => onChange(next)}
|
||||
options={field.options}
|
||||
disabled={disabled}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'string' && field.options && field.options.length > 0) {
|
||||
return (
|
||||
<Select
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
onValueChange={(next) => onChange(next)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger className="bg-background border-border">
|
||||
<SelectValue placeholder="Select an option" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{field.options.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Input
|
||||
id={field.key}
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={field.type === 'string' ? field.placeholder : undefined}
|
||||
className="bg-background border-border"
|
||||
disabled={disabled}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function ProviderAuthField(props: ProviderAuthFieldProps) {
|
||||
const { field } = props
|
||||
|
||||
if (field.type === 'external') {
|
||||
return <ExternalFieldCard field={field} />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{field.type !== 'boolean' && <Label htmlFor={field.key}>{fieldLabel(field)}</Label>}
|
||||
<FieldControl {...props} />
|
||||
{field.description && <p className="text-xs text-muted-foreground">{field.description}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -37,7 +37,7 @@ vi.mock('./OAuthAuthorizeDialog', () => ({
|
||||
providerName: string
|
||||
methods: unknown[]
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSuccess: (response: OAuthAuthorizeResponse, methodIndex: number) => void
|
||||
onSuccess: (response: OAuthAuthorizeResponse, methodID: string) => void
|
||||
}) => (open ? <div data-testid="oauth-authorize-dialog">{providerId}</div> : null),
|
||||
}))
|
||||
|
||||
@@ -50,7 +50,6 @@ vi.mock('./OAuthCallbackDialog', () => ({
|
||||
providerId: string
|
||||
providerName: string
|
||||
authResponse: OAuthAuthorizeResponse
|
||||
methodIndex: number
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSuccess: () => void
|
||||
}) => (open ? <div data-testid="oauth-callback-dialog">{providerId}</div> : null),
|
||||
@@ -89,7 +88,6 @@ function providerFixture(id: string, name: string, modelCount: number): Provider
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
env: [],
|
||||
models: Object.fromEntries(
|
||||
Array.from({ length: modelCount }, (_, index) => [`model-${index}`, {} as Model]),
|
||||
),
|
||||
@@ -110,12 +108,11 @@ function mockProviderData() {
|
||||
apiKeyProviderWithoutKey,
|
||||
],
|
||||
connected: [],
|
||||
default: {},
|
||||
})
|
||||
vi.mocked(providerCredentialsApi.list).mockResolvedValue(['anthropic', 'openai'])
|
||||
vi.mocked(oauthApi.getAuthMethods).mockResolvedValue({
|
||||
anthropic: [{ type: 'oauth', label: 'OAuth' }],
|
||||
google: [{ type: 'oauth', label: 'OAuth' }],
|
||||
anthropic: [{ id: 'oauth', type: 'oauth', label: 'OAuth' }],
|
||||
google: [{ id: 'oauth', type: 'oauth', label: 'OAuth' }],
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -5,21 +5,22 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { Loader2, Check, X, Shield, ChevronDown, ChevronRight, Key, Search, Pencil, Trash2 } from 'lucide-react'
|
||||
import { providerCredentialsApi, getProviders } from '@/api/providers'
|
||||
import { providerCredentialsApi } from '@/api/providers'
|
||||
import type { Provider } from '@/api/providers'
|
||||
import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth'
|
||||
import { type OAuthAuthorizeResponse } from '@/api/oauth'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { OAuthAuthorizeDialog } from './OAuthAuthorizeDialog'
|
||||
import { OAuthCallbackDialog } from './OAuthCallbackDialog'
|
||||
import { ApiKeyDialog } from '@/components/model/ApiKeyDialog'
|
||||
import { invalidateProviderCaches } from '@/lib/queryInvalidation'
|
||||
import { useProviders } from '@/hooks/useProviders'
|
||||
import { useProviderAuthMethods } from '@/hooks/useProviderAuthMethods'
|
||||
|
||||
export function ProviderSettings() {
|
||||
const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
|
||||
const [oauthDialogOpen, setOauthDialogOpen] = useState(false)
|
||||
const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false)
|
||||
const [oauthResponse, setOauthResponse] = useState<OAuthAuthorizeResponse | null>(null)
|
||||
const [oauthMethodIndex, setOauthMethodIndex] = useState<number | null>(null)
|
||||
const [connectedExpanded, setConnectedExpanded] = useState(false)
|
||||
const [availableExpanded, setAvailableExpanded] = useState(true)
|
||||
const [availableSearch, setAvailableSearch] = useState('')
|
||||
@@ -29,11 +30,7 @@ export function ProviderSettings() {
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data: providersData, isLoading: providersLoading } = useQuery({
|
||||
queryKey: ['providers'],
|
||||
queryFn: () => getProviders(),
|
||||
staleTime: 300000,
|
||||
})
|
||||
const { data: providersData, isLoading: providersLoading } = useProviders()
|
||||
|
||||
const providers = providersData?.providers
|
||||
|
||||
@@ -42,10 +39,7 @@ export function ProviderSettings() {
|
||||
queryFn: () => providerCredentialsApi.list(),
|
||||
})
|
||||
|
||||
const { data: authMethods } = useQuery({
|
||||
queryKey: ['provider-auth-methods'],
|
||||
queryFn: () => oauthApi.getAuthMethods(),
|
||||
})
|
||||
const { data: authMethods } = useProviderAuthMethods()
|
||||
|
||||
const deleteCredentialMutation = useMutation({
|
||||
mutationFn: (providerId: string) => providerCredentialsApi.delete(providerId),
|
||||
@@ -69,16 +63,14 @@ export function ProviderSettings() {
|
||||
setDeleteTarget(null)
|
||||
}
|
||||
|
||||
const handleOAuthAuthorize = (response: OAuthAuthorizeResponse, methodIndex: number) => {
|
||||
const handleOAuthAuthorize = (response: OAuthAuthorizeResponse) => {
|
||||
setOauthResponse(response)
|
||||
setOauthMethodIndex(methodIndex)
|
||||
setOauthDialogOpen(false)
|
||||
setOauthCallbackDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleOAuthDialogClose = () => {
|
||||
setOauthDialogOpen(false)
|
||||
setOauthMethodIndex(null)
|
||||
setSelectedProvider(null)
|
||||
}
|
||||
|
||||
@@ -86,7 +78,6 @@ export function ProviderSettings() {
|
||||
invalidateProviderCaches(queryClient)
|
||||
setOauthCallbackDialogOpen(false)
|
||||
setOauthResponse(null)
|
||||
setOauthMethodIndex(null)
|
||||
setSelectedProvider(null)
|
||||
}
|
||||
|
||||
@@ -252,12 +243,11 @@ export function ProviderSettings() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{selectedProvider && oauthResponse && oauthMethodIndex !== null && (
|
||||
{selectedProvider && oauthResponse && (
|
||||
<OAuthCallbackDialog
|
||||
providerId={selectedProvider}
|
||||
providerName={selectedProviderName}
|
||||
authResponse={oauthResponse}
|
||||
methodIndex={oauthMethodIndex}
|
||||
open={oauthCallbackDialogOpen}
|
||||
onOpenChange={setOauthCallbackDialogOpen}
|
||||
onSuccess={handleOAuthSuccess}
|
||||
@@ -426,7 +416,6 @@ export function ProviderSettings() {
|
||||
id: apiKeyProvider.id,
|
||||
name: apiKeyProvider.name,
|
||||
api: apiKeyProvider.api,
|
||||
env: apiKeyProvider.env || [],
|
||||
npm: apiKeyProvider.npm,
|
||||
models: Object.entries(apiKeyProvider.models || {}).map(([id, model]) => ({
|
||||
id,
|
||||
|
||||
@@ -63,7 +63,7 @@ describe('RestartServerDialog', () => {
|
||||
render(<RestartServerDialog {...baseProps} activeSessionCount={2} />)
|
||||
|
||||
expect(screen.getByText(/2 sessions/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/continue/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/resumes them automatically/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render the active-session warning when activeSessionCount is omitted', () => {
|
||||
|
||||
@@ -28,7 +28,7 @@ export function RestartServerDialog({
|
||||
<DialogTitle>Restart OpenCode Server?</DialogTitle>
|
||||
<DialogDescription>
|
||||
{activeSessionCount && activeSessionCount > 0
|
||||
? `${activeSessionCount} session${activeSessionCount === 1 ? '' : 's'} ${activeSessionCount === 1 ? 'is' : 'are'} currently working. Restarting will interrupt ${activeSessionCount === 1 ? 'it' : 'them'} and send "continue" to resume after the server is healthy.`
|
||||
? `${activeSessionCount} session${activeSessionCount === 1 ? '' : 's'} ${activeSessionCount === 1 ? 'is' : 'are'} currently working. Restarting will interrupt ${activeSessionCount === 1 ? 'it' : 'them'}, and OpenCode resumes ${activeSessionCount === 1 ? 'it' : 'them'} automatically once the server is back.`
|
||||
: 'Restart the OpenCode server after your changes are saved to apply them to the running server.'
|
||||
}
|
||||
</DialogDescription>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ServerEnvVarsSettings } from './ServerEnvVarsSettings'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
updateSettingsAsync: vi.fn(),
|
||||
showToast: { success: vi.fn(), error: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettings')
|
||||
vi.mock('@/lib/toast', () => ({ showToast: mocks.showToast }))
|
||||
|
||||
function mockSettings(serverEnvVars: Array<{ key: string; value: string }> = []): void {
|
||||
vi.mocked(useSettings).mockReturnValue({
|
||||
settings: undefined,
|
||||
preferences: { serverEnvVars },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
updateSettings: vi.fn(),
|
||||
updateSettingsAsync: mocks.updateSettingsAsync,
|
||||
resetSettings: vi.fn(),
|
||||
isUpdating: false,
|
||||
isResetting: false,
|
||||
} as ReturnType<typeof useSettings>)
|
||||
}
|
||||
|
||||
describe('ServerEnvVarsSettings', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.updateSettingsAsync.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('saves only serverEnvVars without the removed default-variable mechanism', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockSettings([{ key: 'FOO', value: 'bar' }])
|
||||
|
||||
render(<ServerEnvVarsSettings />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Server Environment Variables/i }))
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/i }))
|
||||
|
||||
expect(mocks.updateSettingsAsync).toHaveBeenCalledWith({
|
||||
serverEnvVars: [{ key: 'FOO', value: 'bar' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('does not render a default variables section', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockSettings()
|
||||
|
||||
render(<ServerEnvVarsSettings />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Server Environment Variables/i }))
|
||||
|
||||
expect(screen.queryByText('Default variables')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/OPENCODE_EXPERIMENTAL_WORKSPACES/)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -2,12 +2,11 @@ import { useState, useEffect, useMemo } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Plus, Trash2, RotateCcw } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@/api/types/settings'
|
||||
import { BLOCKED_SERVER_ENV_KEYS } from '@/api/types/settings'
|
||||
import { SettingsDisclosure } from './SettingsDisclosure'
|
||||
|
||||
interface EnvVar {
|
||||
@@ -19,13 +18,11 @@ export function ServerEnvVarsSettings() {
|
||||
const { preferences, updateSettingsAsync, isUpdating } = useSettings()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [envVars, setEnvVars] = useState<EnvVar[]>([])
|
||||
const [disabledDefaultKeys, setDisabledDefaultKeys] = useState<string[]>([])
|
||||
const [needsRestart, setNeedsRestart] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setEnvVars(preferences?.serverEnvVars ?? [])
|
||||
setDisabledDefaultKeys(preferences?.disabledDefaultServerEnvVars ?? [])
|
||||
}, [preferences?.disabledDefaultServerEnvVars, preferences?.serverEnvVars])
|
||||
}, [preferences?.serverEnvVars])
|
||||
|
||||
const blockedSet = useMemo(() => new Set<string>(BLOCKED_SERVER_ENV_KEYS), [])
|
||||
|
||||
@@ -36,15 +33,6 @@ export function ServerEnvVarsSettings() {
|
||||
[envVars, blockedSet],
|
||||
)
|
||||
|
||||
const disabledDefaultSet = useMemo(() => new Set(disabledDefaultKeys), [disabledDefaultKeys])
|
||||
const enabledDefaultCount = DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultSet.has(envVar.key)).length
|
||||
|
||||
const handleDefaultToggle = (key: string, enabled: boolean) => {
|
||||
setDisabledDefaultKeys((prev) => enabled
|
||||
? prev.filter((disabledKey) => disabledKey !== key)
|
||||
: [...new Set([...prev, key])])
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
setEnvVars((prev) => [...prev, { key: '', value: '' }])
|
||||
}
|
||||
@@ -65,7 +53,6 @@ export function ServerEnvVarsSettings() {
|
||||
try {
|
||||
await updateSettingsAsync({
|
||||
serverEnvVars: filtered,
|
||||
disabledDefaultServerEnvVars: disabledDefaultKeys,
|
||||
})
|
||||
setNeedsRestart(true)
|
||||
showToast.success('Environment variables saved')
|
||||
@@ -82,7 +69,7 @@ export function ServerEnvVarsSettings() {
|
||||
contentClassName="space-y-3"
|
||||
meta={
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{enabledDefaultCount + (preferences?.serverEnvVars ?? []).length}
|
||||
{(preferences?.serverEnvVars ?? []).length}
|
||||
</Badge>
|
||||
}
|
||||
>
|
||||
@@ -96,29 +83,6 @@ export function ServerEnvVarsSettings() {
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-md bg-muted/20 p-3 space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">Default variables</div>
|
||||
{DEFAULT_SERVER_ENV_VARS.map((envVar) => {
|
||||
const isEnabled = !disabledDefaultSet.has(envVar.key)
|
||||
|
||||
return (
|
||||
<div key={envVar.key} className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-xs truncate">{envVar.key}={envVar.value}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Required for OpenCode workspace listing and deletion.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={(checked) => handleDefaultToggle(envVar.key, checked)}
|
||||
aria-label={`Toggle ${envVar.key}`}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{envVars.map((envVar, index) => {
|
||||
const isBlocked = blockedSet.has(envVar.key.trim())
|
||||
|
||||
|
||||
@@ -37,20 +37,20 @@ describe('VersionSelectDialog', () => {
|
||||
vi.clearAllMocks()
|
||||
mockGetOpenCodeVersions.mockResolvedValue({
|
||||
versions: [
|
||||
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z' },
|
||||
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z' },
|
||||
{ version: '2.1.0', tag: 'v2.1.0', name: '', publishedAt: '2026-01-01T00:00:00Z' },
|
||||
{ version: '2.0.15', tag: 'v2.0.15', name: '', publishedAt: '2025-12-01T00:00:00Z' },
|
||||
],
|
||||
currentVersion: '1.18.16',
|
||||
currentVersion: '2.0.15',
|
||||
})
|
||||
mockInstallOpenCodeVersion.mockResolvedValue({ success: true, message: 'ok', oldVersion: null, newVersion: '1.19.0' })
|
||||
mockInstallOpenCodeVersion.mockResolvedValue({ success: true, message: 'ok', oldVersion: null, newVersion: '2.1.0' })
|
||||
})
|
||||
|
||||
it('lists versions and allows selection', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
expect(await screen.findByText('v1.19.0')).toBeInTheDocument()
|
||||
const row = screen.getByRole('button', { name: /v1\.19\.0/ })
|
||||
expect(await screen.findByText('v2.1.0')).toBeInTheDocument()
|
||||
const row = screen.getByRole('button', { name: /v2\.1\.0/ })
|
||||
expect(row).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
|
||||
|
||||
@@ -62,22 +62,22 @@ describe('VersionSelectDialog', () => {
|
||||
it('installs the selected version', async () => {
|
||||
mockGetOpenCodeVersions.mockResolvedValue({
|
||||
versions: [
|
||||
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z' },
|
||||
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z' },
|
||||
{ version: '2.1.0', tag: 'v2.1.0', name: '', publishedAt: '2026-01-01T00:00:00Z' },
|
||||
{ version: '2.0.15', tag: 'v2.0.15', name: '', publishedAt: '2025-12-01T00:00:00Z' },
|
||||
],
|
||||
currentVersion: '1.17.0',
|
||||
currentVersion: '2.0.14',
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
expect(await screen.findByText('v1.19.0')).toBeInTheDocument()
|
||||
const versionRow = screen.getByRole('button', { name: /v1\.19\.0/ })
|
||||
expect(await screen.findByText('v2.1.0')).toBeInTheDocument()
|
||||
const versionRow = screen.getByRole('button', { name: /v2\.1\.0/ })
|
||||
|
||||
await user.click(versionRow)
|
||||
await user.click(screen.getByRole('button', { name: /^Install$/i }))
|
||||
|
||||
expect(mockInstallOpenCodeVersion).toHaveBeenCalledWith('1.19.0')
|
||||
expect(refreshOpenCodeServerCaches).toHaveBeenCalledWith(expect.any(QueryClient), '1.19.0')
|
||||
expect(mockInstallOpenCodeVersion).toHaveBeenCalledWith('2.1.0')
|
||||
expect(refreshOpenCodeServerCaches).toHaveBeenCalledWith(expect.any(QueryClient), '2.1.0')
|
||||
})
|
||||
})
|
||||
@@ -73,7 +73,7 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
|
||||
<DialogHeader>
|
||||
<DialogTitle>Select OpenCode Version</DialogTitle>
|
||||
<DialogDescription>
|
||||
Choose a version to install. Current version: {data?.currentVersion ? `v${data.currentVersion}` : 'Unknown'}
|
||||
Choose an OpenCode 2 release to install. Current version: {data?.currentVersion ? `v${data.currentVersion}` : 'Unknown'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
|
||||
Reference in new issue
Block a user