mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
refactor(config): make on-disk opencode.json the single source of truth (#354)
* refactor(config): make on-disk opencode.json the single source of truth Make <workspace>/.config/opencode/opencode.json the only store for the active OpenCode configuration. One owner (opencode-config-file.ts) reads, validates, writes, archives, and seeds the file; one owner (opencode-config-apply.ts) decides how an edit is applied: restart pending, or a live patch with recovery. Settings routes, the internal assistant API, the health-watch supervisor, boot, and host import all go through them, so an edit that lands on the file without going through the database is visible immediately instead of at the next Manager boot. Remove the named-config profiles. Migration 019 archives every opencode_configs row to .config/opencode-configs-archive/<name>.json, restores the default row to opencode.json when no file exists, then drops the table, its indexes, and repos.opencode_config_name. The /opencode-configs* and config/switch routes and the CreateConfigDialog/SwitchConfigDialog dialogs are gone, and the ocm tool gains GET/PUT /opencode-config backed by the same apply owner. Harden the write path: serialize and atomically write config updates while preserving the file mode, keep withFileLock usable after a rejection, route reloadConfig's cleaned-config write through the file owner, stop boot from rewriting an existing valid config when importing state, prune the health-watch directory to its newest 20 entries, resolve archive paths with realpath, and share one frontend config query across dialogs. * fix(mirror): canonicalize worktree paths before branch ownership check * refactor(config): unify opencode config apply and rollback paths - share one config route factory between public and internal mounts - capture last-known-good before every config write and restore via one helper - stop auto-restarting on save; flag restart-required fields and live-patch the rest - add CONFIG_PATCH_TIMEOUT_MS for config patch requests - extract canonicalPath helpers, health-watch artifact writer, and useProvidersWithModels hook * refactor(model-state): use OpenCode state file as model state source of truth
This commit is contained in:
1 parent
7a3c5229df
commit
295d24ced7
116 files changed
+10291
-4208
No files matched your search
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { getProvidersWithModels } from './providers'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
|
||||
const { mockGetOpenCodeConfig, mockFetchWrapper } = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfig: vi.fn(),
|
||||
mockFetchWrapper: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('./settings', () => ({
|
||||
settingsApi: {
|
||||
getOpenCodeConfig: mockGetOpenCodeConfig,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./fetchWrapper', () => ({
|
||||
fetchWrapper: mockFetchWrapper,
|
||||
}))
|
||||
|
||||
const config = makeOpenCodeConfigFile({
|
||||
content: {
|
||||
provider: {
|
||||
openai: {
|
||||
name: 'OpenAI',
|
||||
models: {
|
||||
'gpt-4o': { name: 'GPT-4o' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
describe('getProvidersWithModels', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockFetchWrapper.mockResolvedValue({ all: [], connected: [], default: {} })
|
||||
})
|
||||
|
||||
it('uses the supplied config instead of re-reading it', async () => {
|
||||
const providers = await getProvidersWithModels(undefined, config)
|
||||
|
||||
expect(mockGetOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(providers.map((provider) => provider.id)).toEqual(['openai'])
|
||||
})
|
||||
|
||||
it('reads the config when none is supplied', async () => {
|
||||
mockGetOpenCodeConfig.mockResolvedValue(config)
|
||||
|
||||
const providers = await getProvidersWithModels(undefined)
|
||||
|
||||
expect(mockGetOpenCodeConfig).toHaveBeenCalledTimes(1)
|
||||
expect(providers.map((provider) => provider.id)).toEqual(['openai'])
|
||||
})
|
||||
|
||||
it('degrades to no configured providers when the config read fails', async () => {
|
||||
mockGetOpenCodeConfig.mockRejectedValue(new Error('no config file'))
|
||||
|
||||
const providers = await getProvidersWithModels(undefined)
|
||||
|
||||
expect(providers).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { API_BASE_URL } from "@/config";
|
||||
import { settingsApi } from "./settings";
|
||||
import { fetchWrapper } from "./fetchWrapper";
|
||||
import type { OpenCodeConfigFile } from "./types/settings";
|
||||
|
||||
export type ProviderSource = "configured" | "local" | "builtin";
|
||||
|
||||
@@ -265,12 +266,12 @@ export async function toggleOpenCodeFavoriteModel(model: ModelSelection): Promis
|
||||
});
|
||||
}
|
||||
|
||||
async function getConfiguredProviders(connectedIds: Set<string>): Promise<ProviderWithModels[]> {
|
||||
async function getConfiguredProviders(connectedIds: Set<string>, config?: OpenCodeConfigFile): Promise<ProviderWithModels[]> {
|
||||
try {
|
||||
const config = await settingsApi.getDefaultOpenCodeConfig();
|
||||
if (!config?.content?.provider) return [];
|
||||
const resolvedConfig = config ?? await settingsApi.getOpenCodeConfig();
|
||||
if (!resolvedConfig.content.provider) return [];
|
||||
|
||||
const configProviders = config.content.provider as Record<string, ConfigProvider>;
|
||||
const configProviders = resolvedConfig.content.provider as Record<string, ConfigProvider>;
|
||||
const result: ProviderWithModels[] = [];
|
||||
|
||||
for (const [providerId, providerConfig] of Object.entries(configProviders)) {
|
||||
@@ -314,11 +315,11 @@ async function getConfiguredProviders(connectedIds: Set<string>): Promise<Provid
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProvidersWithModels(directory?: string): Promise<ProviderWithModels[]> {
|
||||
export async function getProvidersWithModels(directory?: string, config?: OpenCodeConfigFile): Promise<ProviderWithModels[]> {
|
||||
const { providers: builtinProviders, connected } = await getProviders(directory);
|
||||
const connectedIds = new Set(connected);
|
||||
|
||||
const configuredProviders = await getConfiguredProviders(connectedIds);
|
||||
const configuredProviders = await getConfiguredProviders(connectedIds, config);
|
||||
const configuredIds = new Set(configuredProviders.map((p) => p.id));
|
||||
|
||||
const builtinResult: ProviderWithModels[] = builtinProviders
|
||||
|
||||
@@ -9,7 +9,6 @@ export interface CreateRepoOptions {
|
||||
localPath?: string
|
||||
branch?: string
|
||||
directoryName?: string
|
||||
openCodeConfigName?: string
|
||||
useWorktree?: boolean
|
||||
skipSSHVerification?: boolean
|
||||
baseBranch?: string
|
||||
@@ -87,34 +86,6 @@ export async function deleteRepo(id: number): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
export async function startServer(id: number, openCodeConfigName?: string): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/server/start`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ openCodeConfigName }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function stopServer(id: number): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/server/stop`, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function pullRepo(id: number): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/pull`, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function switchRepoConfig(id: number, configName: string): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/config/switch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ configName }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateRepoGitCredential(id: number, credentialId?: string): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-credential`, {
|
||||
method: 'PATCH',
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import type {
|
||||
SettingsResponse,
|
||||
UpdateSettingsRequest,
|
||||
OpenCodeConfig,
|
||||
OpenCodeConfigResponse,
|
||||
CreateOpenCodeConfigRequest,
|
||||
OpenCodeConfigFile,
|
||||
OpenCodeConfigSaveResponse,
|
||||
UpdateOpenCodeConfigRequest,
|
||||
OpenCodeImportStatus,
|
||||
SyncOpenCodeImportResponse,
|
||||
@@ -59,77 +58,18 @@ export const settingsApi = {
|
||||
})
|
||||
},
|
||||
|
||||
getOpenCodeConfigs: async (userId = DEFAULT_USER_ID): Promise<OpenCodeConfigResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs`, {
|
||||
params: { userId },
|
||||
})
|
||||
},
|
||||
|
||||
createOpenCodeConfig: async (
|
||||
request: CreateOpenCodeConfigRequest,
|
||||
userId = DEFAULT_USER_ID
|
||||
): Promise<OpenCodeConfig> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs`, {
|
||||
method: 'POST',
|
||||
params: { userId },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
getOpenCodeConfig: async (): Promise<OpenCodeConfigFile> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`)
|
||||
},
|
||||
|
||||
updateOpenCodeConfig: async (
|
||||
configName: string,
|
||||
request: UpdateOpenCodeConfigRequest,
|
||||
userId = DEFAULT_USER_ID
|
||||
): Promise<OpenCodeConfig> => {
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
params: { userId },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
}
|
||||
)
|
||||
},
|
||||
|
||||
deleteOpenCodeConfig: async (
|
||||
configName: string,
|
||||
userId = DEFAULT_USER_ID
|
||||
): Promise<boolean> => {
|
||||
await fetchWrapper(
|
||||
`${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
params: { userId },
|
||||
}
|
||||
)
|
||||
return true
|
||||
},
|
||||
|
||||
setDefaultOpenCodeConfig: async (
|
||||
configName: string,
|
||||
userId = DEFAULT_USER_ID
|
||||
): Promise<OpenCodeConfig> => {
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}/set-default`,
|
||||
{
|
||||
method: 'POST',
|
||||
params: { userId },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
}
|
||||
)
|
||||
},
|
||||
|
||||
getDefaultOpenCodeConfig: async (userId = DEFAULT_USER_ID): Promise<OpenCodeConfig | null> => {
|
||||
try {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs/default`, {
|
||||
params: { userId },
|
||||
})
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
request: UpdateOpenCodeConfigRequest
|
||||
): Promise<OpenCodeConfigSaveResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
},
|
||||
|
||||
discoverOpenCodeModels: async (
|
||||
@@ -173,7 +113,7 @@ export const settingsApi = {
|
||||
}
|
||||
},
|
||||
|
||||
rollbackOpenCodeConfig: async (): Promise<{ success: boolean; message: string; configName?: string }> => {
|
||||
rollbackOpenCodeConfig: async (): Promise<{ success: boolean; message: string; fallback?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-rollback`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -12,7 +12,6 @@ export interface Repo {
|
||||
clonedAt: number
|
||||
lastPulled?: number
|
||||
lastAccessedAt?: number
|
||||
openCodeConfigName?: string
|
||||
gitCredentialId?: string
|
||||
isWorktree?: boolean
|
||||
isLocal?: boolean
|
||||
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
DEFAULT_SERVER_ENV_VARS,
|
||||
type TTSConfig,
|
||||
type STTConfig,
|
||||
type OpenCodeConfigContent,
|
||||
type OpenCodeConfigFile,
|
||||
type UpdateOpenCodeConfigRequest,
|
||||
type ModelConfig,
|
||||
type ProviderConfig,
|
||||
type SandboxPreferences,
|
||||
@@ -21,7 +22,7 @@ import {
|
||||
} from '@opencode-manager/shared'
|
||||
import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigFile, 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 interface CustomCommand {
|
||||
@@ -85,37 +86,9 @@ export interface UpdateSettingsRequest {
|
||||
preferences: Partial<UserPreferences>
|
||||
}
|
||||
|
||||
export interface OpenCodeConfig {
|
||||
id: number
|
||||
name: string
|
||||
content: Record<string, unknown>
|
||||
rawContent?: string
|
||||
validationIssues?: Array<{
|
||||
path: string
|
||||
message: string
|
||||
}>
|
||||
removedFields?: string[]
|
||||
export interface OpenCodeConfigSaveResponse extends OpenCodeConfigFile {
|
||||
restartRequired?: boolean
|
||||
isValid: boolean
|
||||
isDefault: boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface CreateOpenCodeConfigRequest {
|
||||
name: string
|
||||
content: OpenCodeConfigContent | string
|
||||
isDefault?: boolean
|
||||
}
|
||||
|
||||
export interface UpdateOpenCodeConfigRequest {
|
||||
content: OpenCodeConfigContent | string
|
||||
isDefault?: boolean
|
||||
}
|
||||
|
||||
export interface OpenCodeConfigResponse {
|
||||
configs: OpenCodeConfig[]
|
||||
defaultConfig: OpenCodeConfig | null
|
||||
removedFields?: string[]
|
||||
}
|
||||
|
||||
export interface OpenCodeImportStatus {
|
||||
|
||||
Reference in new issue
Block a user