From 9fca96eceaa953fcf507905164c2b4d99746fb65 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:47:42 -0500 Subject: [PATCH] fix: refuse entity saves while a restart is pending and share replay payloads (OM-179) --- backend/src/routes/opencode-config.ts | 8 ++++- .../src/services/opencode-event-routing.ts | 17 +++++++++ backend/src/services/remote-server-events.ts | 5 +-- backend/src/services/sse-aggregator.ts | 5 +-- .../routes/internal-opencode-config.test.ts | 3 +- backend/test/routes/settings.test.ts | 16 ++++++++- .../services/opencode-event-routing.test.ts | 35 ++++++++++++++++++- frontend/src/api/types/settings.ts | 1 - .../settings/OpenCodeConfigManager.test.tsx | 12 ++----- 9 files changed, 82 insertions(+), 20 deletions(-) diff --git a/backend/src/routes/opencode-config.ts b/backend/src/routes/opencode-config.ts index 9f497147..8c9edf69 100644 --- a/backend/src/routes/opencode-config.ts +++ b/backend/src/routes/opencode-config.ts @@ -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).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, diff --git a/backend/src/services/opencode-event-routing.ts b/backend/src/services/opencode-event-routing.ts index 03d59b15..7ad667e4 100644 --- a/backend/src/services/opencode-event-routing.ts +++ b/backend/src/services/opencode-event-routing.ts @@ -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. diff --git a/backend/src/services/remote-server-events.ts b/backend/src/services/remote-server-events.ts index caf8a386..bfc500e5 100644 --- a/backend/src/services/remote-server-events.ts +++ b/backend/src/services/remote-server-events.ts @@ -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++ diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index 770bbacf..18b432fe 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -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++ } diff --git a/backend/test/routes/internal-opencode-config.test.ts b/backend/test/routes/internal-opencode-config.test.ts index 6fe82295..59ea2e35 100644 --- a/backend/test/routes/internal-opencode-config.test.ts +++ b/backend/test/routes/internal-opencode-config.test.ts @@ -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: '' } }, diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 19451e37..2750c555 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -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 + + 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', diff --git a/backend/test/services/opencode-event-routing.test.ts b/backend/test/services/opencode-event-routing.test.ts index bc62bde0..e20c00c2 100644 --- a/backend/test/services/opencode-event-routing.test.ts +++ b/backend/test/services/opencode-event-routing.test.ts @@ -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('') + }) +}) diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index c4698cf0..6fa0bf31 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -98,7 +98,6 @@ export interface OpenCodeDirectoryFileInfo { } export interface ManagedOpenCodeConfig { - revision: string | null info: OpenCodeConfigInfo } diff --git a/frontend/src/components/settings/OpenCodeConfigManager.test.tsx b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx index 818e0e29..a37b32d5 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.test.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx @@ -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: {