mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat(config): support layered OpenCode config sources with revision-guarded saves (#358)
* feat(config): support layered OpenCode config sources with revision-guarded saves * refactor(config): harden multi-source OpenCode config handling - extract shared config-source helpers and default source name - reject shadowed removals with 409 and require sources/revision - restart the server on reload with session resume - mirror multiple host config files on import and warn on removals - skip restart for mcp-only saves - drop removedFields and CONFIG_PATCH_TIMEOUT_MS * fix(config): return null when archiving broken OpenCode config fails
This commit is contained in:
1 parent
97370a8296
commit
b5dd900efb
53 files changed
+3003
-1665
No files matched your search
@@ -51,7 +51,6 @@ async function handleResponse(response: Response): Promise<never> {
|
||||
{
|
||||
details: data.details,
|
||||
validationIssues: data.validationIssues,
|
||||
removedFields: data.removedFields,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
DEFAULT_LEADER_KEY,
|
||||
BLOCKED_SERVER_ENV_KEYS,
|
||||
DEFAULT_SERVER_ENV_VARS,
|
||||
selectPreferredOpenCodeConfigSourceName,
|
||||
type TTSConfig,
|
||||
type STTConfig,
|
||||
type OpenCodeConfigFile,
|
||||
type OpenCodeConfigSourceFile,
|
||||
type OpenCodeConfigSourceName,
|
||||
type UpdateOpenCodeConfigRequest,
|
||||
type ModelConfig,
|
||||
type ProviderConfig,
|
||||
@@ -21,9 +24,25 @@ import {
|
||||
type InstallSkillResponse,
|
||||
} from '@opencode-manager/shared'
|
||||
import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
import { saveFile } from '@/lib/download'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigFile, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS }
|
||||
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'
|
||||
|
||||
export function getOpenCodeConfigSources(config: OpenCodeConfigFile): OpenCodeConfigSourceFile[] {
|
||||
return config.sources
|
||||
}
|
||||
|
||||
export function getPreferredOpenCodeConfigSource(config: OpenCodeConfigFile): OpenCodeConfigSourceFile | null {
|
||||
const name = selectPreferredOpenCodeConfigSourceName(config.sources.map((source) => source.name))
|
||||
return name ? config.sources.find((source) => source.name === name) ?? null : null
|
||||
}
|
||||
|
||||
export function downloadOpenCodeConfigSource(source: OpenCodeConfigSourceFile): void {
|
||||
const blob = new Blob([source.rawContent], { type: 'application/json' })
|
||||
void saveFile(blob, source.name)
|
||||
}
|
||||
|
||||
export interface CustomCommand {
|
||||
name: string
|
||||
@@ -88,13 +107,14 @@ export interface UpdateSettingsRequest {
|
||||
|
||||
export interface OpenCodeConfigSaveResponse extends OpenCodeConfigFile {
|
||||
restartRequired?: boolean
|
||||
removedFields?: string[]
|
||||
}
|
||||
|
||||
export interface OpenCodeImportStatus {
|
||||
configSourcePath: string | null
|
||||
configSourcePaths: string[]
|
||||
stateSourcePath: string | null
|
||||
workspaceConfigPath: string
|
||||
workspaceConfigPathsToRemove: string[]
|
||||
workspaceStatePath: string
|
||||
workspaceStateExists: boolean
|
||||
}
|
||||
|
||||
@@ -71,4 +71,22 @@ describe('AddMcpServerDialog', () => {
|
||||
})
|
||||
expect(mockAddServerAsync).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('passes only the merged content to onUpdate', async () => {
|
||||
const fetched = makeOpenCodeConfigFile({ revision: 'rev-B' })
|
||||
mockGetOpenCodeConfig.mockResolvedValue(fetched)
|
||||
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'), 'filesystem')
|
||||
await user.type(screen.getByLabelText('Command'), 'npx server-filesystem /tmp')
|
||||
await user.click(screen.getByRole('button', { name: 'Add MCP Server' }))
|
||||
|
||||
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()
|
||||
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,14 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { OpenCodeConfigEditor } from './OpenCodeConfigEditor'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
import { makeOpenCodeConfigFile, makeOpenCodeConfigSource } from '@/test/fixtures/opencode-config'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { saveFile } from '@/lib/download'
|
||||
|
||||
vi.mock('@/lib/download', () => ({
|
||||
saveFile: vi.fn().mockResolvedValue(true),
|
||||
}))
|
||||
|
||||
const RAW = `{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
@@ -10,13 +16,39 @@ const RAW = `{
|
||||
"model": "anthropic/claude-sonnet-4"
|
||||
}`
|
||||
|
||||
const JSONC_RAW = `{
|
||||
// preferred target keeps comments
|
||||
"theme": "system"
|
||||
}`
|
||||
|
||||
const CONFIG_JSON_RAW = `{
|
||||
"theme": "dark"
|
||||
}`
|
||||
|
||||
const config = makeOpenCodeConfigFile({ rawContent: RAW })
|
||||
|
||||
const multiSourceConfig = makeOpenCodeConfigFile({
|
||||
path: '/workspace/.config/opencode/opencode.jsonc',
|
||||
rawContent: JSONC_RAW,
|
||||
revision: 'rev-2',
|
||||
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 }),
|
||||
],
|
||||
})
|
||||
|
||||
function setContent(textarea: HTMLTextAreaElement, value: string) {
|
||||
fireEvent.change(textarea, { target: { value } })
|
||||
}
|
||||
|
||||
describe('OpenCodeConfigEditor', () => {
|
||||
beforeAll(() => {
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
})
|
||||
|
||||
const renderEditor = (
|
||||
overrides: Partial<React.ComponentProps<typeof OpenCodeConfigEditor>> = {},
|
||||
) => {
|
||||
@@ -162,7 +194,7 @@ describe('OpenCodeConfigEditor', () => {
|
||||
setContent(textarea, next)
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(onUpdate).toHaveBeenCalledWith(next)
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: next, source: 'opencode.json', expectedRevision: 'rev-1' })
|
||||
})
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
@@ -318,7 +350,7 @@ describe('OpenCodeConfigEditor', () => {
|
||||
resolveSave()
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))
|
||||
expect(onUpdate).toHaveBeenCalledTimes(1)
|
||||
expect(onUpdate).toHaveBeenCalledWith(RAW)
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: RAW, source: 'opencode.json', expectedRevision: 'rev-1' })
|
||||
})
|
||||
|
||||
it('resolves a validation issue under a dotted provider key to its line', async () => {
|
||||
@@ -335,4 +367,319 @@ describe('OpenCodeConfigEditor', () => {
|
||||
const row = activeLine?.closest('[data-line]')
|
||||
expect(row).toHaveAttribute('data-line', '4')
|
||||
})
|
||||
|
||||
it('loads the preferred source and lists every source file', () => {
|
||||
renderEditor({ config: multiSourceConfig })
|
||||
expect(screen.getByText('Edit opencode.jsonc')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Config content')).toHaveValue(JSONC_RAW)
|
||||
expect(screen.getByText('/workspace/.config/opencode/opencode.jsonc')).toBeInTheDocument()
|
||||
const selector = screen.getByRole('combobox', { name: 'Source file' })
|
||||
expect(selector).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('switches sources without discarding and saves the selected source', async () => {
|
||||
const { onUpdate } = renderEditor({ config: multiSourceConfig })
|
||||
const user = userEvent.setup()
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Source file' }))
|
||||
await user.click(screen.getByRole('option', { name: 'config.json' }))
|
||||
|
||||
expect(screen.getByText('Edit config.json')).toBeInTheDocument()
|
||||
expect(screen.getByText('/workspace/.config/opencode/config.json')).toBeInTheDocument()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
expect(textarea).toHaveValue(CONFIG_JSON_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' })
|
||||
})
|
||||
})
|
||||
|
||||
it('disables the source selector while there are unsaved edits', async () => {
|
||||
const { onClose } = renderEditor({ config: multiSourceConfig })
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, JSONC_RAW + ' ')
|
||||
expect(screen.getByRole('combobox', { name: 'Source file' })).toBeDisabled()
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Discard' }))
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('downloads the exact selected source file', async () => {
|
||||
renderEditor({ config: multiSourceConfig })
|
||||
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('button', { name: 'Download' }))
|
||||
|
||||
expect(saveFile).toHaveBeenCalledWith(expect.any(Blob), 'config.json')
|
||||
})
|
||||
|
||||
it('surfaces a conflict error without discarding the raw text', async () => {
|
||||
const onUpdate = vi.fn().mockRejectedValue(
|
||||
new FetchError('Conflict', 409, 'CONFIG_CONFLICT', 'This configuration changed since you opened it.'),
|
||||
)
|
||||
renderEditor({ onUpdate })
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
const next = RAW + ' '
|
||||
setContent(textarea, next)
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
|
||||
expect(await screen.findByText('This configuration changed since you opened it.')).toBeInTheDocument()
|
||||
expect(textarea).toHaveValue(next)
|
||||
expect(screen.getByText('Edit opencode.json')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the captured revision when the config refreshes with a newer revision while dirty', async () => {
|
||||
const onUpdate = vi.fn().mockRejectedValue(
|
||||
new FetchError('Conflict', 409, 'CONFIG_CONFLICT', 'This configuration changed since you opened it.'),
|
||||
)
|
||||
const onClose = vi.fn()
|
||||
const { rerender } = render(
|
||||
<OpenCodeConfigEditor config={config} isOpen onClose={onClose} onUpdate={onUpdate} />,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
const draft = RAW + ' '
|
||||
setContent(textarea, draft)
|
||||
|
||||
const newerConfig = makeOpenCodeConfigFile({ rawContent: RAW, revision: 'rev-2', updatedAt: 2 })
|
||||
rerender(<OpenCodeConfigEditor config={newerConfig} isOpen onClose={onClose} onUpdate={onUpdate} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: draft, source: 'opencode.json', expectedRevision: 'rev-1' })
|
||||
})
|
||||
expect(await screen.findByText('This configuration changed since you opened it.')).toBeInTheDocument()
|
||||
expect(textarea).toHaveValue(draft)
|
||||
expect(screen.getByText('Edit opencode.json')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the captured source when it disappears from the refreshed config while dirty', async () => {
|
||||
const onUpdate = vi.fn().mockRejectedValue(
|
||||
new FetchError('Conflict', 409, 'CONFIG_CONFLICT', 'This configuration changed since you opened it.'),
|
||||
)
|
||||
const onClose = vi.fn()
|
||||
const { rerender } = render(
|
||||
<OpenCodeConfigEditor config={multiSourceConfig} isOpen onClose={onClose} onUpdate={onUpdate} />,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
const draft = JSONC_RAW + '\n// draft\n'
|
||||
setContent(textarea, draft)
|
||||
|
||||
const sourceRemovedConfig = makeOpenCodeConfigFile({
|
||||
path: '/workspace/.config/opencode/opencode.json',
|
||||
rawContent: RAW,
|
||||
revision: 'rev-3',
|
||||
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} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(onUpdate).toHaveBeenCalledWith({ content: draft, source: 'opencode.jsonc', expectedRevision: 'rev-2' })
|
||||
})
|
||||
expect(await screen.findByText('This configuration changed since you opened it.')).toBeInTheDocument()
|
||||
expect(textarea).toHaveValue(draft)
|
||||
expect(screen.getByText('Edit opencode.jsonc')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the multi-source notice for a single config source', () => {
|
||||
renderEditor()
|
||||
expect(screen.queryByText('Multiple configuration files are merged')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the merged notice expanded with its body visible', () => {
|
||||
renderEditor({ config: multiSourceConfig })
|
||||
|
||||
const details = screen.getByText('Multiple configuration files are merged').closest('details') as HTMLDetailsElement
|
||||
expect(details).toHaveAttribute('open')
|
||||
const paragraphs = Array.from(details.querySelectorAll('p'))
|
||||
expect(paragraphs).toHaveLength(3)
|
||||
paragraphs.forEach((paragraph) => {
|
||||
expect(paragraph).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
it('collapses and reopens the merged notice from its title', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor({ config: multiSourceConfig })
|
||||
|
||||
const title = screen.getByText('Multiple configuration files are merged')
|
||||
const details = title.closest('details') as HTMLDetailsElement
|
||||
expect(title).toBeVisible()
|
||||
const paragraphs = Array.from(details.querySelectorAll('p'))
|
||||
expect(paragraphs).toHaveLength(3)
|
||||
|
||||
await user.click(title)
|
||||
expect(details).not.toHaveAttribute('open')
|
||||
paragraphs.forEach((paragraph) => {
|
||||
expect(paragraph).not.toBeVisible()
|
||||
})
|
||||
expect(title).toBeVisible()
|
||||
|
||||
await user.click(title)
|
||||
expect(details).toHaveAttribute('open')
|
||||
paragraphs.forEach((paragraph) => {
|
||||
expect(paragraph).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the merged notice collapsed when the config refreshes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { rerender, onClose, onUpdate } = renderEditor({ config: multiSourceConfig })
|
||||
|
||||
const title = screen.getByText('Multiple configuration files are merged')
|
||||
await user.click(title)
|
||||
expect(title.closest('details')).not.toHaveAttribute('open')
|
||||
|
||||
const refreshedConfig = makeOpenCodeConfigFile({
|
||||
...multiSourceConfig,
|
||||
revision: 'rev-3',
|
||||
updatedAt: 2,
|
||||
})
|
||||
rerender(
|
||||
<OpenCodeConfigEditor config={refreshedConfig} isOpen onClose={onClose} onUpdate={onUpdate} />,
|
||||
)
|
||||
|
||||
const refreshedTitle = screen.getByText('Multiple configuration files are merged')
|
||||
const refreshedDetails = refreshedTitle.closest('details') as HTMLDetailsElement
|
||||
expect(refreshedDetails).not.toHaveAttribute('open')
|
||||
const refreshedParagraphs = Array.from(refreshedDetails.querySelectorAll('p'))
|
||||
expect(refreshedParagraphs).toHaveLength(3)
|
||||
refreshedParagraphs.forEach((paragraph) => {
|
||||
expect(paragraph).not.toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
it('lists merged config files and names the selected source as the write target', () => {
|
||||
renderEditor({ config: multiSourceConfig })
|
||||
|
||||
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('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.')
|
||||
|
||||
const scrollContainer = notice.closest('.overflow-y-auto')
|
||||
expect(scrollContainer).toHaveClass('max-h-[45dvh]')
|
||||
})
|
||||
|
||||
it('updates the write target when the source selection changes', async () => {
|
||||
renderEditor({ config: multiSourceConfig })
|
||||
const user = userEvent.setup()
|
||||
|
||||
const notice = screen.getByText('Multiple configuration files are merged').closest('[role="alert"]') as HTMLElement
|
||||
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' }))
|
||||
|
||||
const updatedNotice = screen.getByText('Multiple configuration files are merged').closest('[role="alert"]') as HTMLElement
|
||||
expect(updatedNotice).toHaveTextContent('Saves apply only to config.json')
|
||||
})
|
||||
|
||||
it('shows the file details disclosure expanded for a single source', () => {
|
||||
renderEditor()
|
||||
|
||||
const details = screen.getByText('File details').closest('details') as HTMLDetailsElement
|
||||
expect(details).toHaveAttribute('open')
|
||||
expect(screen.getByText('/workspace/.config/opencode/opencode.json')).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'Download' })).toBeVisible()
|
||||
expect(screen.getByText(/Editing this file directly/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('hides path, guidance and download when the file details are collapsed', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
|
||||
const summary = screen.getByText('File details')
|
||||
const details = summary.closest('details') as HTMLDetailsElement
|
||||
|
||||
await user.click(summary)
|
||||
|
||||
expect(details).not.toHaveAttribute('open')
|
||||
expect(screen.getByText('/workspace/.config/opencode/opencode.json')).not.toBeVisible()
|
||||
expect(screen.getByText(/Editing this file directly/)).not.toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'Download' })).not.toBeVisible()
|
||||
expect(screen.getByLabelText('Config content')).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'Update' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('reopens the file details disclosure from its summary', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
|
||||
const summary = screen.getByText('File details')
|
||||
const details = summary.closest('details') as HTMLDetailsElement
|
||||
|
||||
await user.click(summary)
|
||||
expect(details).not.toHaveAttribute('open')
|
||||
|
||||
await user.click(summary)
|
||||
expect(details).toHaveAttribute('open')
|
||||
expect(screen.getByText('/workspace/.config/opencode/opencode.json')).toBeVisible()
|
||||
})
|
||||
|
||||
it('keeps the file details summary keyboard focusable and natively activatable', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
|
||||
const label = screen.getByText('File details')
|
||||
const details = label.closest('details') as HTMLDetailsElement
|
||||
const summary = label.closest('summary') as HTMLElement
|
||||
expect(summary).toBeInTheDocument()
|
||||
|
||||
summary.focus()
|
||||
expect(summary).toHaveFocus()
|
||||
|
||||
await user.click(summary)
|
||||
expect(details).not.toHaveAttribute('open')
|
||||
|
||||
await user.click(summary)
|
||||
expect(details).toHaveAttribute('open')
|
||||
})
|
||||
|
||||
it('keeps the file details collapsed while editing and when the config refreshes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { rerender, onClose, onUpdate } = renderEditor()
|
||||
|
||||
const summary = screen.getByText('File details')
|
||||
await user.click(summary)
|
||||
expect(summary.closest('details')).not.toHaveAttribute('open')
|
||||
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, RAW + ' ')
|
||||
|
||||
const refreshedConfig = makeOpenCodeConfigFile({ rawContent: RAW, revision: 'rev-2', updatedAt: 2 })
|
||||
rerender(<OpenCodeConfigEditor config={refreshedConfig} isOpen onClose={onClose} onUpdate={onUpdate} />)
|
||||
|
||||
const refreshedDetails = screen.getByText('File details').closest('details') as HTMLDetailsElement
|
||||
expect(refreshedDetails).not.toHaveAttribute('open')
|
||||
expect(screen.getByText('/workspace/.config/opencode/opencode.json')).not.toBeVisible()
|
||||
expect(screen.getByLabelText('Config content')).toBeVisible()
|
||||
})
|
||||
|
||||
it('keeps the merged notice chevron tied to its own disclosure', () => {
|
||||
renderEditor({ config: multiSourceConfig })
|
||||
|
||||
const noticeDetails = screen.getByText('Multiple configuration files are merged').closest('details') as HTMLDetailsElement
|
||||
const chevron = noticeDetails.querySelector('svg') as SVGElement
|
||||
expect(chevron).toHaveClass('group-open:rotate-180')
|
||||
expect(chevron).not.toHaveClass('group-open/file-details:rotate-180')
|
||||
|
||||
const fileDetails = screen.getByText('File details').closest('details') as HTMLDetailsElement
|
||||
expect(fileDetails).toHaveClass('group/file-details')
|
||||
expect(fileDetails).not.toHaveClass('group')
|
||||
})
|
||||
})
|
||||
@@ -1,16 +1,25 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { useState, useEffect, useCallback, useId, useMemo, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Loader2, Download, ChevronDown } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { CodeEditor } from '@/components/ui/code-editor'
|
||||
import { EditorFindBar } from '@/components/ui/editor-find-bar'
|
||||
import { UnsavedChangesDialog } from '@/components/ui/unsaved-changes-dialog'
|
||||
import { OpenCodeConfigSourcesNotice } from './OpenCodeConfigSourcesNotice'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useFindInText } from '@/lib/useFindInText'
|
||||
import { parseJsonc, parseJsoncErrorLine, resolveJsoncIssueLine } from '@/lib/jsonc'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared'
|
||||
import type { OpenCodeConfigFile } from '@/api/types/settings'
|
||||
import {
|
||||
downloadOpenCodeConfigSource,
|
||||
getOpenCodeConfigSources,
|
||||
getPreferredOpenCodeConfigSource,
|
||||
isOpenCodeConfigSourceName,
|
||||
} from '@/api/types/settings'
|
||||
import type { OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName } from '@/api/types/settings'
|
||||
|
||||
type ValidationIssue = {
|
||||
path: string
|
||||
@@ -22,7 +31,7 @@ interface OpenCodeConfigEditorProps {
|
||||
config: OpenCodeConfigFile | null
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onUpdate: (content: string) => Promise<void>
|
||||
onUpdate: (request: { content: string; source: OpenCodeConfigSourceName; expectedRevision?: string }) => Promise<void>
|
||||
}
|
||||
|
||||
export function OpenCodeConfigEditor({
|
||||
@@ -31,6 +40,8 @@ export function OpenCodeConfigEditor({
|
||||
onClose,
|
||||
onUpdate,
|
||||
}: OpenCodeConfigEditorProps) {
|
||||
const [draftSource, setDraftSource] = useState<OpenCodeConfigSourceFile | null>(null)
|
||||
const [draftRevision, setDraftRevision] = useState<string>('')
|
||||
const [editConfigContent, setEditConfigContent] = useState('')
|
||||
const [initialContent, setInitialContent] = useState('')
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
@@ -38,11 +49,12 @@ export function OpenCodeConfigEditor({
|
||||
const [editError, setEditError] = useState('')
|
||||
const [editErrorLine, setEditErrorLine] = useState<number | null>(null)
|
||||
const [validationIssues, setValidationIssues] = useState<ValidationIssue[]>([])
|
||||
const [removedFields, setRemovedFields] = useState<string[]>([])
|
||||
const [activeLine, setActiveLine] = useState<number | null>(null)
|
||||
const [revealNonce, setRevealNonce] = useState(0)
|
||||
const hasInitializedSessionRef = useRef(false)
|
||||
const isMobile = useMobile()
|
||||
const sourceSelectId = useId()
|
||||
const sources = useMemo(() => (config ? getOpenCodeConfigSources(config) : []), [config])
|
||||
const isDirty = editConfigContent !== initialContent
|
||||
const { query, setQuery, matches, currentMatchIndex, hasMatches, next, prev } = useFindInText(editConfigContent)
|
||||
|
||||
@@ -51,13 +63,23 @@ export function OpenCodeConfigEditor({
|
||||
setRevealNonce((n) => n + 1)
|
||||
}, [])
|
||||
|
||||
const resetErrors = () => {
|
||||
const resetErrors = useCallback(() => {
|
||||
setEditError('')
|
||||
setEditErrorLine(null)
|
||||
setValidationIssues([])
|
||||
setRemovedFields([])
|
||||
setActiveLine(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const selectSource = useCallback((name: OpenCodeConfigSourceName) => {
|
||||
if (!config) return
|
||||
const next = sources.find((source) => source.name === name)
|
||||
if (!next) return
|
||||
setDraftSource(next)
|
||||
setDraftRevision(config.revision)
|
||||
setEditConfigContent(next.rawContent)
|
||||
setInitialContent(next.rawContent)
|
||||
resetErrors()
|
||||
}, [sources, config, resetErrors])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
@@ -66,13 +88,22 @@ export function OpenCodeConfigEditor({
|
||||
}
|
||||
if (hasInitializedSessionRef.current || !config) return
|
||||
hasInitializedSessionRef.current = true
|
||||
const next = config.rawContent || JSON.stringify(config.content, null, 2)
|
||||
setEditConfigContent(next)
|
||||
setInitialContent(next)
|
||||
const initialSource = getPreferredOpenCodeConfigSource(config)
|
||||
const nextContent = initialSource?.rawContent ?? ''
|
||||
setDraftSource(initialSource)
|
||||
setDraftRevision(config.revision)
|
||||
setEditConfigContent(nextContent)
|
||||
setInitialContent(nextContent)
|
||||
resetErrors()
|
||||
setIsSaving(false)
|
||||
setIsDiscardPromptOpen(false)
|
||||
}, [config, isOpen])
|
||||
}, [config, isOpen, resetErrors])
|
||||
|
||||
const handleSourceChange = (name: string) => {
|
||||
if (isDirty || isSaving) return
|
||||
if (!isOpenCodeConfigSourceName(name)) return
|
||||
selectSource(name)
|
||||
}
|
||||
|
||||
const requestClose = () => {
|
||||
if (isSaving) return
|
||||
@@ -108,7 +139,7 @@ export function OpenCodeConfigEditor({
|
||||
})
|
||||
|
||||
const updateConfig = async () => {
|
||||
if (!config) return
|
||||
if (!config || !draftSource) return
|
||||
|
||||
try {
|
||||
resetErrors()
|
||||
@@ -122,7 +153,7 @@ export function OpenCodeConfigEditor({
|
||||
}
|
||||
|
||||
setIsSaving(true)
|
||||
await onUpdate(editConfigContent)
|
||||
await onUpdate({ content: editConfigContent, source: draftSource.name, expectedRevision: draftRevision })
|
||||
onClose()
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError) {
|
||||
@@ -133,8 +164,11 @@ export function OpenCodeConfigEditor({
|
||||
} else if (error instanceof FetchError) {
|
||||
const issues = resolveIssues(error.validationIssues ?? [])
|
||||
setValidationIssues(issues)
|
||||
setRemovedFields(error.removedFields ?? [])
|
||||
setEditError(error.detail || error.message)
|
||||
if (error.statusCode === 409) {
|
||||
setEditError(error.detail || 'This configuration changed since you opened it. Reload the file, then reapply your edits.')
|
||||
} else {
|
||||
setEditError(error.detail || error.message)
|
||||
}
|
||||
} else if (error instanceof Error) {
|
||||
setEditError(error.message)
|
||||
} else {
|
||||
@@ -145,7 +179,7 @@ export function OpenCodeConfigEditor({
|
||||
}
|
||||
}
|
||||
|
||||
if (!config) return null
|
||||
if (!config || !draftSource) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -160,10 +194,60 @@ export function OpenCodeConfigEditor({
|
||||
>
|
||||
<DialogHeader className="flex shrink-0 flex-row items-center justify-between space-y-0 border-b p-4 sm:p-6">
|
||||
<DialogTitle className="text-lg font-semibold sm:text-xl">
|
||||
Edit opencode.json
|
||||
Edit {draftSource.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<details
|
||||
open
|
||||
className="group/file-details max-h-[45dvh] shrink-0 overflow-y-auto border-b"
|
||||
>
|
||||
<summary className="flex cursor-pointer list-none items-center justify-between gap-2 px-4 py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 sm:px-6 [&::-webkit-details-marker]:hidden">
|
||||
<span className="text-sm font-medium">File details</span>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground transition-transform group-open/file-details:rotate-180" />
|
||||
</summary>
|
||||
<div className="space-y-2 px-4 pb-3 sm:px-6">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
{sources.length > 1 ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor={sourceSelectId} className="shrink-0">Source file</Label>
|
||||
<Select
|
||||
value={draftSource.name}
|
||||
onValueChange={handleSourceChange}
|
||||
disabled={isDirty || isSaving}
|
||||
>
|
||||
<SelectTrigger id={sourceSelectId} className="w-full sm:w-56">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sources.map((source) => (
|
||||
<SelectItem key={source.name} value={source.name}>{source.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm font-medium">{draftSource.name}</p>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => downloadOpenCodeConfigSource(draftSource)}
|
||||
disabled={isSaving}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5 mr-1" />
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
<p className="break-all text-xs text-muted-foreground">{draftSource.path}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Editing this file directly. Other source files and inherited values stay as they are; removing a value deletes its override so an inherited value can reappear.
|
||||
</p>
|
||||
<OpenCodeConfigSourcesNotice config={config} targetName={draftSource.name} />
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<EditorFindBar
|
||||
query={query}
|
||||
onQueryChange={setQuery}
|
||||
@@ -228,11 +312,6 @@ export function OpenCodeConfigEditor({
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{removedFields.length > 0 && (
|
||||
<p className="break-words text-xs text-amber-600 sm:text-sm">
|
||||
Removed invalid fields: {removedFields.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -262,7 +341,7 @@ export function OpenCodeConfigEditor({
|
||||
onOpenChange={(open) => !open && setIsDiscardPromptOpen(false)}
|
||||
onDiscard={discardAndClose}
|
||||
onKeepEditing={() => setIsDiscardPromptOpen(false)}
|
||||
itemName="opencode.json"
|
||||
itemName={draftSource.name}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { OpenCodeConfigManager } from './OpenCodeConfigManager'
|
||||
import type { OpenCodeConfigFile } from '@/api/types/settings'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
import { makeOpenCodeConfigFile, makeOpenCodeConfigSource } from '@/test/fixtures/opencode-config'
|
||||
|
||||
const {
|
||||
mockGetOpenCodeConfig,
|
||||
@@ -15,6 +15,7 @@ const {
|
||||
mockListManagedSkills,
|
||||
mockListOpenCodeDirectoryFiles,
|
||||
mockGetAgentsMd,
|
||||
mockAddServerAsync,
|
||||
healthState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfig: vi.fn(),
|
||||
@@ -25,6 +26,7 @@ const {
|
||||
mockListManagedSkills: vi.fn(),
|
||||
mockListOpenCodeDirectoryFiles: vi.fn(),
|
||||
mockGetAgentsMd: vi.fn(),
|
||||
mockAddServerAsync: vi.fn(),
|
||||
healthState: { data: { opencode: 'healthy', opencodeRestartPending: false } as Record<string, unknown> },
|
||||
}))
|
||||
|
||||
@@ -32,6 +34,34 @@ vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: () => healthState,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMcpServers', () => ({
|
||||
useMcpServers: () => ({
|
||||
status: undefined,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
addServer: vi.fn(),
|
||||
addServerAsync: mockAddServerAsync,
|
||||
isAddingServer: false,
|
||||
connect: vi.fn(),
|
||||
connectAsync: vi.fn(),
|
||||
isConnecting: false,
|
||||
disconnect: vi.fn(),
|
||||
disconnectAsync: vi.fn(),
|
||||
isDisconnecting: false,
|
||||
startAuth: vi.fn(),
|
||||
startAuthAsync: vi.fn(),
|
||||
isStartingAuth: false,
|
||||
completeAuth: vi.fn(),
|
||||
completeAuthAsync: vi.fn(),
|
||||
isCompletingAuth: false,
|
||||
removeAuth: vi.fn(),
|
||||
removeAuthAsync: vi.fn(),
|
||||
isRemovingAuth: false,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
@@ -93,6 +123,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(defaultConfig)
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
mockGetActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
mockAddServerAsync.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('shows uploaded command and agent directory files in settings', async () => {
|
||||
@@ -234,22 +265,22 @@ describe('OpenCodeConfigManager', () => {
|
||||
expect(screen.getByText(`Updated: ${new Date(defaultConfig.updatedAt).toLocaleString()}`)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the editor mounted while the post-save config refresh is in flight', async () => {
|
||||
it('sends the source and expected revision and replaces the cache with the returned snapshot for a raw save', async () => {
|
||||
const configWithRaw: OpenCodeConfigFile = {
|
||||
...defaultConfig,
|
||||
rawContent: '{\n "theme": "system"\n}',
|
||||
}
|
||||
mockGetOpenCodeConfig.mockResolvedValueOnce(configWithRaw)
|
||||
let resolveRefresh!: () => void
|
||||
mockGetOpenCodeConfig.mockReturnValueOnce(
|
||||
new Promise<OpenCodeConfigFile>((resolve) => {
|
||||
resolveRefresh = () => resolve(configWithRaw)
|
||||
}),
|
||||
)
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(configWithRaw)
|
||||
const savedConfig: OpenCodeConfigFile = {
|
||||
...configWithRaw,
|
||||
rawContent: '{\n "theme": "dark"\n}',
|
||||
revision: 'rev-2',
|
||||
updatedAt: 2,
|
||||
}
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(savedConfig)
|
||||
|
||||
const user = userEvent.setup()
|
||||
const { container } = renderWithQuery(<OpenCodeConfigManager />)
|
||||
const { container, queryClient } = renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
const editIcon = container.querySelector('.lucide-square-pen') as SVGElement
|
||||
@@ -257,14 +288,20 @@ describe('OpenCodeConfigManager', () => {
|
||||
await user.click(editButton)
|
||||
|
||||
const textarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
fireEvent.change(textarea, { target: { value: configWithRaw.rawContent + ' ' } })
|
||||
const next = configWithRaw.rawContent + ' '
|
||||
fireEvent.change(textarea, { target: { value: next } })
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
|
||||
await waitFor(() => expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1))
|
||||
expect(screen.getByText('Edit opencode.json')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Update' })).toBeDisabled()
|
||||
|
||||
resolveRefresh()
|
||||
await waitFor(() => {
|
||||
expect(mockUpdateOpenCodeConfig).toHaveBeenCalledWith({
|
||||
content: next,
|
||||
source: 'opencode.json',
|
||||
expectedRevision: 'rev-1',
|
||||
})
|
||||
})
|
||||
const cached = queryClient.getQueryData<OpenCodeConfigFile>(['opencode-config', 'file'])
|
||||
expect(cached?.revision).toBe('rev-2')
|
||||
expect(cached?.rawContent).toBe('{\n "theme": "dark"\n}')
|
||||
await waitFor(() => expect(screen.queryByText('Edit opencode.json')).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
@@ -283,10 +320,20 @@ describe('OpenCodeConfigManager', () => {
|
||||
fireEvent.change(textarea, { target: { value: draft } })
|
||||
|
||||
const refreshedContent = { theme: 'dark' }
|
||||
const refreshedRaw = JSON.stringify(refreshedContent, null, 2)
|
||||
const refreshedConfig: OpenCodeConfigFile = {
|
||||
...defaultConfig,
|
||||
content: refreshedContent,
|
||||
rawContent: JSON.stringify(refreshedContent, null, 2),
|
||||
rawContent: refreshedRaw,
|
||||
sources: [
|
||||
makeOpenCodeConfigSource({
|
||||
name: 'opencode.json',
|
||||
path: defaultConfig.path,
|
||||
rawContent: refreshedRaw,
|
||||
content: refreshedContent,
|
||||
updatedAt: 2,
|
||||
}),
|
||||
],
|
||||
updatedAt: 2,
|
||||
}
|
||||
mockGetOpenCodeConfig.mockResolvedValue(refreshedConfig)
|
||||
@@ -315,7 +362,151 @@ describe('OpenCodeConfigManager', () => {
|
||||
await user.click(reopenButton)
|
||||
|
||||
const reopenedTextarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
expect(reopenedTextarea).toHaveValue(JSON.stringify(refreshedContent, null, 2))
|
||||
expect(reopenedTextarea).toHaveValue(refreshedRaw)
|
||||
})
|
||||
|
||||
it('sends the expected revision for structured updates', async () => {
|
||||
mockUpdateOpenCodeConfig.mockResolvedValueOnce({ ...defaultConfig, restartRequired: true })
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Models/i }))
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for GPT-4o'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
|
||||
await waitFor(() => expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1))
|
||||
const [payload] = mockUpdateOpenCodeConfig.mock.calls[0]
|
||||
expect(payload.expectedRevision).toBe('rev-1')
|
||||
expect(payload.source).toBeUndefined()
|
||||
expect(payload.content.provider.openai.models).not.toHaveProperty('gpt-4o')
|
||||
})
|
||||
|
||||
it('resolves the add-server expected revision from the query cache', async () => {
|
||||
const cachedConfig = { ...defaultConfig, revision: 'rev-A' }
|
||||
const dialogFetchedConfig = { ...defaultConfig, revision: 'rev-B' }
|
||||
let configRequests = 0
|
||||
mockGetOpenCodeConfig.mockImplementation(() => {
|
||||
configRequests += 1
|
||||
return Promise.resolve(configRequests === 1 ? cachedConfig : dialogFetchedConfig)
|
||||
})
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue({ ...cachedConfig, restartRequired: true })
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
await user.click(screen.getByRole('button', { name: /Add Server/i }))
|
||||
|
||||
await user.type(await screen.findByLabelText('Server ID'), 'filesystem')
|
||||
await user.type(screen.getByLabelText('Command'), 'npx server-filesystem /tmp')
|
||||
await user.click(screen.getByRole('button', { name: 'Add MCP Server' }))
|
||||
|
||||
await waitFor(() => expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1))
|
||||
const [payload] = mockUpdateOpenCodeConfig.mock.calls[0]
|
||||
expect(payload.expectedRevision).toBe('rev-A')
|
||||
expect(mockAddServerAsync).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('sends the revision from the previous save on the next structured save', async () => {
|
||||
const twoModelsContent = {
|
||||
provider: {
|
||||
openai: {
|
||||
name: 'OpenAI',
|
||||
models: {
|
||||
'gpt-4o': { name: 'GPT-4o' },
|
||||
'gpt-3.5': { name: 'GPT-3.5' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
const twoModelsConfig = makeOpenCodeConfigFile({
|
||||
path: '/workspace/.opencode/opencode.json',
|
||||
rawContent: JSON.stringify(twoModelsContent, null, 2),
|
||||
content: twoModelsContent,
|
||||
})
|
||||
mockGetOpenCodeConfig.mockResolvedValue(twoModelsConfig)
|
||||
|
||||
const afterFirstDelete = {
|
||||
...twoModelsConfig,
|
||||
content: {
|
||||
provider: {
|
||||
openai: {
|
||||
name: 'OpenAI',
|
||||
models: {
|
||||
'gpt-3.5': { name: 'GPT-3.5' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
revision: 'rev-2',
|
||||
}
|
||||
const afterSecondDelete = { ...afterFirstDelete, revision: 'rev-3' }
|
||||
mockUpdateOpenCodeConfig
|
||||
.mockResolvedValueOnce(afterFirstDelete)
|
||||
.mockResolvedValueOnce(afterSecondDelete)
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
await user.click(screen.getByRole('button', { name: /Models/i }))
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for GPT-4o'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
await waitFor(() => expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1))
|
||||
expect(mockUpdateOpenCodeConfig.mock.calls[0][0].expectedRevision).toBe('rev-1')
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for GPT-3.5'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
await waitFor(() => expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(2))
|
||||
expect(mockUpdateOpenCodeConfig.mock.calls[1][0].expectedRevision).toBe('rev-2')
|
||||
})
|
||||
|
||||
it('reports a comment-only raw save as applied without a restart', async () => {
|
||||
const configWithRaw: OpenCodeConfigFile = {
|
||||
...defaultConfig,
|
||||
rawContent: '{\n // comment only\n "theme": "system"\n}',
|
||||
}
|
||||
mockGetOpenCodeConfig.mockResolvedValue(configWithRaw)
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue({ ...configWithRaw, restartRequired: false, revision: 'rev-2' })
|
||||
|
||||
const user = userEvent.setup()
|
||||
const { container } = renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
const editIcon = container.querySelector('.lucide-square-pen') as SVGElement
|
||||
await user.click(editIcon.closest('button') as HTMLButtonElement)
|
||||
|
||||
const textarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
fireEvent.change(textarea, { target: { value: configWithRaw.rawContent + '\n// another\n' } })
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
|
||||
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.')
|
||||
})
|
||||
|
||||
it('asks for a restart after a semantic structured change', async () => {
|
||||
mockUpdateOpenCodeConfig.mockResolvedValueOnce({ ...defaultConfig, restartRequired: true })
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Models/i }))
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for GPT-4o'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
await waitFor(() => {
|
||||
expect(showToast.success).toHaveBeenCalledWith('Configuration saved. Restart the server to apply changes.')
|
||||
})
|
||||
})
|
||||
|
||||
it('does not reset an in-flight save when the config query refreshes in the background', async () => {
|
||||
@@ -384,6 +575,40 @@ describe('OpenCodeConfigManager', () => {
|
||||
expect(await screen.findByRole('button', { name: /Import From Host/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('warns that importing removes workspace config files absent on the host', async () => {
|
||||
mockGetOpenCodeImportStatus.mockResolvedValue({
|
||||
configSourcePath: '/import/opencode-config/opencode.jsonc',
|
||||
configSourcePaths: ['/import/opencode-config/opencode.json', '/import/opencode-config/opencode.jsonc'],
|
||||
stateSourcePath: null,
|
||||
workspaceConfigPath: '/workspace/.config/opencode/opencode.json',
|
||||
workspaceConfigPathsToRemove: ['/workspace/.config/opencode/opencode.jsonc'],
|
||||
workspaceStatePath: '/workspace/.opencode/state/opencode',
|
||||
workspaceStateExists: false,
|
||||
})
|
||||
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
expect(await screen.findByText(/These files will be removed: opencode.jsonc\./)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Host files imported: opencode.json, opencode.jsonc\./)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not warn about removals when the host has every workspace config file', async () => {
|
||||
mockGetOpenCodeImportStatus.mockResolvedValue({
|
||||
configSourcePath: '/import/opencode-config/opencode.json',
|
||||
configSourcePaths: ['/import/opencode-config/opencode.json'],
|
||||
stateSourcePath: null,
|
||||
workspaceConfigPath: '/workspace/.config/opencode/opencode.json',
|
||||
workspaceConfigPathsToRemove: [],
|
||||
workspaceStatePath: '/workspace/.opencode/state/opencode',
|
||||
workspaceStateExists: false,
|
||||
})
|
||||
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('opencode.json')
|
||||
expect(screen.queryByText(/These files will be removed/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the config file name and an invalid badge when the file is invalid', async () => {
|
||||
mockGetOpenCodeConfig.mockResolvedValue({
|
||||
...defaultConfig,
|
||||
@@ -398,4 +623,32 @@ describe('OpenCodeConfigManager', () => {
|
||||
expect(screen.getByText('Invalid Config')).toBeInTheDocument()
|
||||
expect(screen.getByText('model')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the multi-source notice when only one config file is present', async () => {
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('opencode.json')
|
||||
expect(screen.queryByText('Multiple configuration files are merged')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lists merged config files in override order and names the structured write target', async () => {
|
||||
const multiSourceConfig = makeOpenCodeConfigFile({
|
||||
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' }),
|
||||
],
|
||||
})
|
||||
mockGetOpenCodeConfig.mockResolvedValue(multiSourceConfig)
|
||||
|
||||
renderWithQuery(<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('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.')
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
import { OpenCodeConfigEditor } from './OpenCodeConfigEditor'
|
||||
import { OpenCodeConfigSourcesNotice } from './OpenCodeConfigSourcesNotice'
|
||||
import { CommandsEditor } from './CommandsEditor'
|
||||
import { AgentsEditor } from './AgentsEditor'
|
||||
import { AgentsMdEditor } from './AgentsMdEditor'
|
||||
@@ -18,13 +19,12 @@ 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 { hasJsoncComments } from '@/lib/jsonc'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { saveFile } from '@/lib/download'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import type { OpenCodeConfigFile, OpenCodeImportStatus } from '@/api/types/settings'
|
||||
import { getPreferredOpenCodeConfigSource, downloadOpenCodeConfigSource } from '@/api/types/settings'
|
||||
import type { OpenCodeConfigFile, OpenCodeConfigSaveResponse, OpenCodeImportStatus } from '@/api/types/settings'
|
||||
|
||||
interface Command {
|
||||
template: string
|
||||
@@ -156,37 +156,38 @@ export function OpenCodeConfigManager() {
|
||||
return getApiErrorMessage(error, 'Failed to import existing OpenCode host data')
|
||||
}
|
||||
|
||||
const updateConfigContent = async (newContent: Record<string, unknown>) => {
|
||||
const previousConfig = queryClient.getQueryData<OpenCodeConfigFile>(OPEN_CODE_CONFIG_QUERY_KEY)
|
||||
const now = Date.now()
|
||||
|
||||
queryClient.setQueryData<OpenCodeConfigFile>(OPEN_CODE_CONFIG_QUERY_KEY, (prev) =>
|
||||
prev ? { ...prev, content: newContent, updatedAt: now } : prev
|
||||
)
|
||||
|
||||
try {
|
||||
const result = await settingsApi.updateOpenCodeConfig({ content: newContent })
|
||||
if (result.removedFields && result.removedFields.length > 0) {
|
||||
showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`)
|
||||
} else if (result.restartRequired) {
|
||||
showToast.success('Configuration saved. Restart the server to apply changes.')
|
||||
} else {
|
||||
showToast.success('Configuration updated')
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
} catch (error) {
|
||||
if (previousConfig) {
|
||||
queryClient.setQueryData(OPEN_CODE_CONFIG_QUERY_KEY, previousConfig)
|
||||
}
|
||||
showToast.error(getApiErrorMessage(error, 'Failed to update config'))
|
||||
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 })
|
||||
}
|
||||
|
||||
const updateConfigContent = async (newContent: Record<string, unknown>) => {
|
||||
const expectedRevision = queryClient.getQueryData<OpenCodeConfigFile>(
|
||||
OPEN_CODE_CONFIG_QUERY_KEY,
|
||||
)?.revision
|
||||
const result = await settingsApi.updateOpenCodeConfig({
|
||||
content: newContent,
|
||||
expectedRevision,
|
||||
})
|
||||
applyOpenCodeConfigSave(result)
|
||||
}
|
||||
|
||||
const updateConfigContentSafely = (newContent: Record<string, unknown>) => {
|
||||
void updateConfigContent(newContent).catch((error) => {
|
||||
showToast.error(getApiErrorMessage(error, 'Failed to update config'))
|
||||
})
|
||||
}
|
||||
|
||||
const downloadConfig = (config: OpenCodeConfigFile) => {
|
||||
const content = config.rawContent || JSON.stringify(config.content, null, 2)
|
||||
const extension = config.rawContent && hasJsoncComments(config.rawContent) ? 'jsonc' : 'json'
|
||||
const blob = new Blob([content], { type: 'application/json' })
|
||||
void saveFile(blob, `opencode.${extension}`)
|
||||
const preferredSource = getPreferredOpenCodeConfigSource(config)
|
||||
if (preferredSource) {
|
||||
downloadOpenCodeConfigSource(preferredSource)
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
@@ -198,6 +199,8 @@ export function OpenCodeConfigManager() {
|
||||
}
|
||||
|
||||
const canImportFromHost = Boolean(importStatus?.configSourcePath || importStatus?.stateSourcePath)
|
||||
const workspaceConfigPathsToRemove = importStatus?.workspaceConfigPathsToRemove ?? []
|
||||
const hostConfigSourcePaths = importStatus?.configSourcePaths ?? []
|
||||
|
||||
return (
|
||||
<div className="min-w-0 space-y-4">
|
||||
@@ -274,6 +277,12 @@ export function OpenCodeConfigManager() {
|
||||
</div>
|
||||
</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.
|
||||
</p>
|
||||
|
||||
<OpenCodeConfigSourcesNotice config={config} />
|
||||
|
||||
{!config.isValid && config.validationIssues && config.validationIssues.length > 0 && (
|
||||
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-4">
|
||||
<p className="font-medium text-destructive">This configuration has validation issues</p>
|
||||
@@ -299,9 +308,13 @@ export function OpenCodeConfigManager() {
|
||||
config={config}
|
||||
isOpen={isEditDialogOpen}
|
||||
onClose={() => setIsEditDialogOpen(false)}
|
||||
onUpdate={async (rawContent) => {
|
||||
await settingsApi.updateOpenCodeConfig({ content: rawContent })
|
||||
await queryClient.invalidateQueries({ queryKey: OPEN_CODE_CONFIG_QUERY_KEY })
|
||||
onUpdate={async ({ content, source, expectedRevision }) => {
|
||||
const result = await settingsApi.updateOpenCodeConfig({
|
||||
content,
|
||||
source,
|
||||
expectedRevision,
|
||||
})
|
||||
applyOpenCodeConfigSave(result)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
@@ -364,7 +377,7 @@ export function OpenCodeConfigManager() {
|
||||
commands={(config.content.command as Record<string, Command> | undefined) ?? {}}
|
||||
directoryCommands={directoryCommands}
|
||||
onChange={(commands) => {
|
||||
updateConfigContent({
|
||||
updateConfigContentSafely({
|
||||
...config.content,
|
||||
command: commands
|
||||
})
|
||||
@@ -398,7 +411,7 @@ export function OpenCodeConfigManager() {
|
||||
agents={(config.content.agent as Record<string, Agent> | undefined) ?? {}}
|
||||
directoryAgents={directoryAgents}
|
||||
onChange={(agents) => {
|
||||
updateConfigContent({
|
||||
updateConfigContentSafely({
|
||||
...config.content,
|
||||
agent: agents
|
||||
})
|
||||
@@ -493,7 +506,7 @@ export function OpenCodeConfigManager() {
|
||||
<OpenCodeModelsEditor
|
||||
providers={(config.content.provider as Record<string, ConfigProvider> | undefined) ?? {}}
|
||||
onChange={(providers) => {
|
||||
updateConfigContent({
|
||||
updateConfigContentSafely({
|
||||
...config.content,
|
||||
provider: providers
|
||||
})
|
||||
@@ -567,6 +580,18 @@ export function OpenCodeConfigManager() {
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{!isImportStatusLoading && workspaceConfigPathsToRemove.length > 0 && (
|
||||
<p className="flex items-start gap-2 text-xs text-amber-600 dark:text-amber-500">
|
||||
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
<span>
|
||||
Importing replaces the workspace configuration files. These files will be removed:{' '}
|
||||
{workspaceConfigPathsToRemove.map(getConfigFileName).join(', ')}.
|
||||
{hostConfigSourcePaths.length > 1 && (
|
||||
<> Host files imported: {hostConfigSourcePaths.map(getConfigFileName).join(', ')}.</>
|
||||
)}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
<div className="rounded-lg border border-border p-3">
|
||||
<p className="font-medium">Workspace State</p>
|
||||
<p className="mt-1 break-all text-muted-foreground">
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { ChevronDown, Info } from 'lucide-react'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { OPENCODE_CONFIG_SOURCE_NAMES } from '@opencode-manager/shared'
|
||||
import {
|
||||
getOpenCodeConfigSources,
|
||||
getPreferredOpenCodeConfigSource,
|
||||
} from '@/api/types/settings'
|
||||
import type { OpenCodeConfigFile, OpenCodeConfigSourceName } from '@/api/types/settings'
|
||||
|
||||
interface OpenCodeConfigSourcesNoticeProps {
|
||||
config: OpenCodeConfigFile
|
||||
targetName?: OpenCodeConfigSourceName
|
||||
}
|
||||
|
||||
export function OpenCodeConfigSourcesNotice({ config, targetName }: OpenCodeConfigSourcesNoticeProps) {
|
||||
const sources = getOpenCodeConfigSources(config)
|
||||
if (sources.length <= 1) return null
|
||||
|
||||
const orderedNames = OPENCODE_CONFIG_SOURCE_NAMES.filter((name) =>
|
||||
sources.some((source) => source.name === name),
|
||||
)
|
||||
const writeTargetName = targetName ?? getPreferredOpenCodeConfigSource(config)?.name
|
||||
if (!writeTargetName) return null
|
||||
|
||||
return (
|
||||
<Alert className="border-blue-500/30 bg-blue-500/5">
|
||||
<Info className="h-4 w-4 text-blue-500" />
|
||||
<details className="group" open>
|
||||
<summary className="flex cursor-pointer list-none items-center justify-between gap-2 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 [&::-webkit-details-marker]:hidden">
|
||||
<AlertTitle className="mb-0">Multiple configuration files are merged</AlertTitle>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-blue-500 transition-transform group-open:rotate-180" />
|
||||
</summary>
|
||||
<AlertDescription>
|
||||
<p>
|
||||
OpenCode loads these files in order, with each later file overriding matching settings from the files before it:{' '}
|
||||
{orderedNames.map((name, index) => (
|
||||
<span key={name}>
|
||||
{index > 0 ? ', ' : ''}
|
||||
<code className="font-mono text-foreground">{name}</code>
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
<p className="mt-1">
|
||||
Saves apply only to <code className="font-mono text-foreground">{writeTargetName}</code>. A value saved to a lower-priority file can be overridden by a higher-priority file.
|
||||
</p>
|
||||
<p className="mt-1">
|
||||
For simpler configuration, consolidate the settings you need into one file, then remove redundant files after verifying the result.
|
||||
</p>
|
||||
</AlertDescription>
|
||||
</details>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
@@ -21,14 +21,14 @@ const getEventDirectory = (event: SSEEvent): string | undefined => {
|
||||
}
|
||||
|
||||
const handleRestartServer = async () => {
|
||||
showToast.loading('Reloading OpenCode configuration...', {
|
||||
showToast.loading('Restarting OpenCode server...', {
|
||||
id: 'restart-server',
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await settingsApi.reloadOpenCodeConfig()
|
||||
if (result.success) {
|
||||
showToast.success(result.message || 'OpenCode configuration reloaded successfully', {
|
||||
showToast.success(result.message || 'OpenCode server restarted', {
|
||||
id: 'restart-server',
|
||||
duration: 3000,
|
||||
})
|
||||
@@ -36,13 +36,13 @@ const handleRestartServer = async () => {
|
||||
window.location.reload()
|
||||
}, 2000)
|
||||
} else {
|
||||
showToast.error(result.message || 'Failed to reload OpenCode configuration', {
|
||||
showToast.error(result.message || 'Failed to restart OpenCode server', {
|
||||
id: 'restart-server',
|
||||
duration: 5000,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
showToast.error(error instanceof Error ? error.message : 'Failed to reload OpenCode configuration', {
|
||||
showToast.error(error instanceof Error ? error.message : 'Failed to restart OpenCode server', {
|
||||
id: 'restart-server',
|
||||
duration: 5000,
|
||||
})
|
||||
|
||||
@@ -44,14 +44,14 @@ export function useServerHealth(enabled = true) {
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
toast.success('Server configuration reloaded successfully', { id: 'reload-config' })
|
||||
toast.success('OpenCode server restarted', { id: 'reload-config' })
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to reload configuration')
|
||||
: 'Failed to reload configuration'
|
||||
|| 'Failed to restart OpenCode server')
|
||||
: 'Failed to restart OpenCode server'
|
||||
toast.error(errorMessage, { id: 'reload-config' })
|
||||
},
|
||||
})
|
||||
@@ -103,7 +103,7 @@ export function useServerHealth(enabled = true) {
|
||||
id: 'server-health-unhealthy',
|
||||
duration: Infinity,
|
||||
action: {
|
||||
label: 'Reload',
|
||||
label: 'Restart',
|
||||
onClick: () => restartMutation.mutate(),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -7,10 +7,3 @@ export function resolveJsoncIssueLine(content: string, path: PropertyKey[] | str
|
||||
: parseJsoncPathSegments(path)
|
||||
return findJsoncLineForPath(content, segments)
|
||||
}
|
||||
|
||||
export function hasJsoncComments(content: string): boolean {
|
||||
return content.split('\n').some(line => {
|
||||
const trimmed = line.trim()
|
||||
return trimmed.startsWith('//') || trimmed.startsWith('/*')
|
||||
})
|
||||
}
|
||||
@@ -141,7 +141,7 @@ export function getErrorMessage(error: OpenCodeError | undefined | null): string
|
||||
/**
|
||||
* Extracts a human-readable message from a Manager REST API error, handling
|
||||
* both {@link FetchError} and axios-style `{ response: { data } }` shapes,
|
||||
* including OpenCode config validation issues and removed fields.
|
||||
* including OpenCode config validation issues.
|
||||
*/
|
||||
export function getOpenCodeApiErrorMessage(error: unknown, fallback: string): string {
|
||||
if (error instanceof FetchError) {
|
||||
@@ -154,15 +154,11 @@ export function getOpenCodeApiErrorMessage(error: unknown, fallback: string): st
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (error.removedFields && error.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${error.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { details?: string; error?: string; validationIssues?: Array<{ path: string; message: string }>; removedFields?: string[] } } }).response
|
||||
const response = (error as { response?: { data?: { details?: string; error?: string; validationIssues?: Array<{ path: string; message: string }> } } }).response
|
||||
const data = response?.data
|
||||
|
||||
let message = data?.details || data?.error || fallback
|
||||
@@ -174,10 +170,6 @@ export function getOpenCodeApiErrorMessage(error: unknown, fallback: string): st
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (data?.removedFields && data.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${data.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { refreshOpenCodeServerCaches } from './queryInvalidation'
|
||||
import { invalidateConfigCaches, refreshOpenCodeServerCaches } from './queryInvalidation'
|
||||
|
||||
describe('refreshOpenCodeServerCaches', () => {
|
||||
it('invalidates every cache that displays the installed OpenCode version', () => {
|
||||
@@ -27,3 +27,25 @@ describe('refreshOpenCodeServerCaches', () => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-versions'] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('invalidateConfigCaches', () => {
|
||||
it('invalidates the OpenCode config file cache by default', () => {
|
||||
const queryClient = new QueryClient()
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
invalidateConfigCaches(queryClient)
|
||||
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-config'] })
|
||||
})
|
||||
|
||||
it('skips the OpenCode config file cache while still invalidating dependents', () => {
|
||||
const queryClient = new QueryClient()
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
invalidateConfigCaches(queryClient, { skipOpenCodeConfig: true })
|
||||
|
||||
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode-config'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'config'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['health'] })
|
||||
})
|
||||
})
|
||||
@@ -18,11 +18,20 @@ export function invalidateProviderCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['providers-for-execution-model'] })
|
||||
}
|
||||
|
||||
export function invalidateConfigCaches(queryClient: QueryClient) {
|
||||
interface ConfigInvalidationOptions {
|
||||
skipOpenCodeConfig?: boolean
|
||||
}
|
||||
|
||||
export function invalidateConfigCaches(
|
||||
queryClient: QueryClient,
|
||||
options: ConfigInvalidationOptions = {},
|
||||
) {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'config'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'commands'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
if (!options.skipOpenCodeConfig) {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['health'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-skills'] })
|
||||
|
||||
+37
-3
@@ -1,12 +1,46 @@
|
||||
import type { OpenCodeConfigFile } from '@/api/types/settings'
|
||||
import { DEFAULT_OPENCODE_CONFIG_SOURCE_NAME, isOpenCodeConfigSourceName } from '@opencode-manager/shared'
|
||||
import type { OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName } from '@/api/types/settings'
|
||||
|
||||
export function makeOpenCodeConfigFile(overrides: Partial<OpenCodeConfigFile> = {}): OpenCodeConfigFile {
|
||||
function sourceNameFromPath(path: string): OpenCodeConfigSourceName {
|
||||
const fileName = path.split(/[\\/]/).filter(Boolean).pop() ?? ''
|
||||
return isOpenCodeConfigSourceName(fileName) ? fileName : DEFAULT_OPENCODE_CONFIG_SOURCE_NAME
|
||||
}
|
||||
|
||||
export function makeOpenCodeConfigSource(
|
||||
overrides: Partial<OpenCodeConfigSourceFile> = {},
|
||||
): OpenCodeConfigSourceFile {
|
||||
return {
|
||||
name: 'opencode.json',
|
||||
path: '/workspace/.config/opencode/opencode.json',
|
||||
content: {},
|
||||
rawContent: '{}',
|
||||
content: {},
|
||||
isValid: true,
|
||||
updatedAt: 1,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
export function makeOpenCodeConfigFile(overrides: Partial<OpenCodeConfigFile> = {}): OpenCodeConfigFile {
|
||||
const base: OpenCodeConfigFile = {
|
||||
path: '/workspace/.config/opencode/opencode.json',
|
||||
content: {},
|
||||
rawContent: '{}',
|
||||
isValid: true,
|
||||
updatedAt: 1,
|
||||
revision: 'rev-1',
|
||||
sources: [],
|
||||
}
|
||||
const merged = { ...base, ...overrides }
|
||||
return {
|
||||
...merged,
|
||||
sources: overrides.sources ?? [makeOpenCodeConfigSource({
|
||||
name: sourceNameFromPath(merged.path),
|
||||
path: merged.path,
|
||||
rawContent: merged.rawContent,
|
||||
content: merged.content,
|
||||
isValid: merged.isValid,
|
||||
validationIssues: merged.validationIssues,
|
||||
updatedAt: merged.updatedAt,
|
||||
})],
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user