fix: refuse entity saves while a restart is pending and share replay payloads (OM-179)

This commit is contained in:
Chris Scott committed 2026-11-02 23:47:42 -05:00
1 parent 8a6fd56e9a
commit 9fca96ecea
9 files changed
+82 -20

No files matched your search

+7 -1
View File
@@ -27,6 +27,7 @@ import {
import { readManagedOpenCodeConfig } from '../services/opencode-config-effective'
import { applyOpenCodeConfigUpdate, toOpenCodeConfigApplyResponse } from '../services/opencode-config-apply'
import { redactOpenCodeConfigContent, redactOpenCodeConfigFile } from '../services/opencode-config-redact'
import { opencodeServerManager } from '../services/opencode-single-server'
import { logger } from '../utils/logger'
interface OpenCodeConfigRoutesOptions {
@@ -111,7 +112,6 @@ export function createOpenCodeConfigRoutes(
const snapshot = await withOpenCodeConfigLock(readOpenCodeConfigSnapshot)
const info = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
return c.json({
revision: snapshot.revision,
info: options.redactSecrets
? redactOpenCodeConfigContent(info as Record<string, unknown>).content
: info,
@@ -175,6 +175,12 @@ export function createOpenCodeConfigRoutes(
return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400)
}
if (opencodeServerManager.isRestartPending()) {
return c.json({
error: 'OpenCode has not loaded the saved configuration yet. Restart OpenCode before editing entries.',
}, 409)
}
return applyUpdate(c, {
content: parsed.data.patch,
source: parsed.data.source,
@@ -61,6 +61,23 @@ export function planSessionStatusReplay(
return { idle, busy }
}
/**
* Builds a `session.status` replay event restating the activity state of one session.
*
* @param buildEvent Replay event builder owned by the hub that delivers the event.
* @param directory Directory the replayed event belongs to.
* @param sessionID Session whose status is replayed.
* @param status Activity state to replay.
*/
export function buildSessionStatusReplayEvent(
buildEvent: ReplayEventBuilder,
directory: string,
sessionID: string,
status: 'idle' | 'busy',
): ReplayEvent {
return buildEvent('session.status', directory, { sessionID, status: { type: status } })
}
/**
* Records the activity state an event implies for its session, so that directory-scoped work can be
* limited to the sessions that are actually running.
+3 -2
View File
@@ -12,6 +12,7 @@ import type {
} from './opencode-server-registry'
import {
applySessionActivity,
buildSessionStatusReplayEvent,
collectPendingReplayEvents,
createReplayEventBuilder,
planSessionStatusReplay,
@@ -316,7 +317,7 @@ export class RemoteServerEventHub {
let replayed = 0
for (const { sessionID, directory } of plan.idle) {
const event = this.buildReplayEvent('session.status', directory, { sessionID, status: { type: 'idle' } })
const event = buildSessionStatusReplayEvent(this.buildReplayEvent, directory, sessionID, 'idle')
this.aggregator.deliverRemoteEnvelope(serverId, directory, event)
stream.busySessions.delete(sessionID)
replayed++
@@ -324,7 +325,7 @@ export class RemoteServerEventHub {
for (const sessionID of plan.busy) {
const directory = stream.sessionDirectories.get(sessionID) ?? null
const event = this.buildReplayEvent('session.status', directory ?? '', { sessionID, status: { type: 'busy' } })
const event = buildSessionStatusReplayEvent(this.buildReplayEvent, directory ?? '', sessionID, 'busy')
this.aggregator.deliverRemoteEnvelope(serverId, directory, event)
stream.busySessions.add(sessionID)
replayed++
+3 -2
View File
@@ -4,6 +4,7 @@ import { type V2Event } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from './opencode/client'
import { encodeSSEFrame } from '../utils/sse-frame'
import {
buildSessionStatusReplayEvent,
collectPendingReplayEvents,
createReplayEventBuilder,
planSessionStatusReplay,
@@ -308,7 +309,7 @@ class SSEAggregator {
let replayed = 0
for (const { sessionID, directory } of plan.idle) {
this.deliverEvent(directory, this.buildReplayEvent('session.status', directory, { sessionID, status: { type: 'idle' } }))
this.deliverEvent(directory, buildSessionStatusReplayEvent(this.buildReplayEvent, directory, sessionID, 'idle'))
replayed++
}
@@ -319,7 +320,7 @@ class SSEAggregator {
for (const { sessionID, directory } of runningDirectories) {
if (!directory) continue
this.deliverEvent(directory, this.buildReplayEvent('session.status', directory, { sessionID, status: { type: 'busy' } }))
this.deliverEvent(directory, buildSessionStatusReplayEvent(this.buildReplayEvent, directory, sessionID, 'busy'))
replayed++
}
@@ -558,7 +558,7 @@ describe('internal/opencode-config routes', () => {
it('GET /api/internal/opencode-config/managed merges only Manager source documents and redacts secrets', async () => {
await writeOpenCodeConfigFile(JSON.stringify({ theme: 'light' }), 'opencode.json')
const snapshot = await writeOpenCodeConfigFile(JSON.stringify({ theme: 'dark' }), 'opencode.jsonc')
await writeOpenCodeConfigFile(JSON.stringify({ theme: 'dark' }), 'opencode.jsonc')
configGetMock.mockImplementation(() => Promise.resolve([
{
type: 'document',
@@ -585,7 +585,6 @@ describe('internal/opencode-config routes', () => {
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
revision: snapshot.revision,
info: {
theme: 'dark',
providers: { example: { apiKey: '<redacted>' } },
+15 -1
View File
@@ -476,7 +476,6 @@ describe('Settings Routes - OpenCode Upgrade', () => {
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
revision: 'rev-managed',
info: { theme: 'dark', model: 'a/b' },
})
expect(configGet).toHaveBeenCalledWith({ location: { directory: '/tmp/test-workspace' } })
@@ -612,6 +611,21 @@ describe('Settings Routes - OpenCode Upgrade', () => {
})
})
it('refuses a PATCH entity save with 409 while an OpenCode restart is pending', async () => {
vi.mocked(opencodeServerManager.isRestartPending).mockReturnValueOnce(true)
const res = await settingsApp.fetch(new Request('http://localhost/opencode-config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ patch: { agents: { reviewer: { description: 'stale' } } } }),
}))
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(409)
expect(json.error).toContain('Restart OpenCode')
expect(mockApplyOpenCodeConfigUpdate).not.toHaveBeenCalled()
})
it('returns 400 when the PUT body fails schema validation', async () => {
const res = await settingsApp.fetch(new Request('http://localhost/opencode-config', {
method: 'PUT',
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { V2Event } from '@opencode-manager/shared/opencode'
import { createReplayEventBuilder, routeOpenCodeEvent } from '../../src/services/opencode-event-routing'
import { buildSessionStatusReplayEvent, createReplayEventBuilder, routeOpenCodeEvent } from '../../src/services/opencode-event-routing'
const locatedStatus = {
id: 'evt_status_located',
@@ -118,3 +118,36 @@ describe('createReplayEventBuilder', () => {
expect([permission.id, form.id, status.id]).toEqual(['replay_1', 'replay_2', 'replay_3'])
})
})
describe('buildSessionStatusReplayEvent', () => {
it('builds idle and busy session status replays through the hub builder', () => {
const buildEvent = createReplayEventBuilder('ocm_replay_')
const idle = buildSessionStatusReplayEvent(buildEvent, '/work/alpha', 'ses_1', 'idle')
const busy = buildSessionStatusReplayEvent(buildEvent, '/work/beta', 'ses_2', 'busy')
expect(idle).toEqual({
id: 'ocm_replay_1',
created: expect.any(Number),
type: 'session.status',
location: { directory: '/work/alpha' },
data: { sessionID: 'ses_1', status: { type: 'idle' } },
})
expect(busy).toEqual({
id: 'ocm_replay_2',
created: expect.any(Number),
type: 'session.status',
location: { directory: '/work/beta' },
data: { sessionID: 'ses_2', status: { type: 'busy' } },
})
})
it('keeps the directory and id prefix owned by the caller', () => {
const buildEvent = createReplayEventBuilder('ocm_replay_remote_')
const event = buildSessionStatusReplayEvent(buildEvent, '', 'ses_1', 'busy')
expect(event.id).toBe('ocm_replay_remote_1')
expect(event.location?.directory).toBe('')
})
})
-1
View File
@@ -98,7 +98,6 @@ export interface OpenCodeDirectoryFileInfo {
}
export interface ManagedOpenCodeConfig {
revision: string | null
info: OpenCodeConfigInfo
}
@@ -146,7 +146,7 @@ describe('OpenCodeConfigManager', () => {
vi.clearAllMocks()
healthState.data = { opencode: 'healthy', opencodeRestartPending: false }
mockGetOpenCodeConfig.mockResolvedValue(defaultConfig)
mockGetManagedOpenCodeConfig.mockResolvedValue({ revision: 'rev-1', info: defaultManagedInfo })
mockGetManagedOpenCodeConfig.mockResolvedValue({ info: defaultManagedInfo })
mockPatchOpenCodeConfig.mockResolvedValue({ ...defaultConfig, revision: 'rev-2' })
mockGetOpenCodeImportStatus.mockResolvedValue({})
mockGetAgentsMd.mockResolvedValue({ content: '# Agent Instructions' })
@@ -445,7 +445,6 @@ describe('OpenCodeConfigManager', () => {
it('deletes a configured MCP server through an mcp.servers patch', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: { mcp: { servers: { filesystem: { type: 'local', command: ['npx', 'server'] } } } },
})
mockPatchOpenCodeConfig.mockResolvedValue({ ...defaultConfig, revision: 'rev-2' })
@@ -467,7 +466,6 @@ describe('OpenCodeConfigManager', () => {
it('sends the revision from the previous save on the next structured save', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: {
providers: {
openai: {
@@ -504,7 +502,7 @@ describe('OpenCodeConfigManager', () => {
})
it('adds a model to a new API provider through a providers patch', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({ revision: 'rev-1', info: {} })
mockGetManagedOpenCodeConfig.mockResolvedValue({ info: {} })
mockPatchOpenCodeConfig.mockResolvedValue({ ...defaultConfig, revision: 'rev-2' })
const user = userEvent.setup()
@@ -543,7 +541,6 @@ describe('OpenCodeConfigManager', () => {
it('saves an edited model under providers when the managed response converted a v1 entry', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: {
providers: {
openai: {
@@ -582,7 +579,6 @@ describe('OpenCodeConfigManager', () => {
it('keeps a converted provider and its sibling models when deleting one model', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: {
providers: {
p: {
@@ -810,7 +806,6 @@ describe('OpenCodeConfigManager', () => {
it('lists agents and commands from the managed config query', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: {
agents: { reviewer: { system: 'Review code', description: 'Reviews code', mode: 'subagent' } },
commands: { deploy: { template: 'Deploy it', description: 'Deploys the app' } },
@@ -880,7 +875,6 @@ describe('OpenCodeConfigManager', () => {
it('saves an agent with an entity patch through the managed config endpoint', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: { agents: { reviewer: { system: 'Review code', mode: 'subagent' } } },
})
@@ -902,7 +896,6 @@ describe('OpenCodeConfigManager', () => {
it('deletes the previous agent name in the same patch when renaming', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: { agents: { reviewer: { system: 'Review code', mode: 'subagent' } } },
})
@@ -929,7 +922,6 @@ describe('OpenCodeConfigManager', () => {
it('sends null for cleared command fields and a disabled subagent', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
info: {
commands: {
review: {