/** * Regression: model selector gray after re-entering a session. * * models_state is a one-shot snapshot — the worker sends it only once per * bridge connect, and the web UI restores it from the last models_state * event in GET /history. Anything that wipes or evicts the event log * (/clear, /new, window eviction) used to make the selector permanently * gray until the worker reconnected. The bus now keeps the latest snapshot * out-of-band: /clear re-seeds it, /history merges it when the log lacks * the event. Covers both worker write paths: * - v1 session-ingress (HybridTransport POST → ingestBridgeMessage) * - v2 CCR worker events (POST /v1/code/sessions/:id/worker/events) */ import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' mock.module('../config', () => mockConfigModule({ pollTimeout: 1 })) import { Hono } from 'hono' import { storeReset } from '../store' import { getAllEventBuses, removeEventBus, getEventBus, } from '../transport/event-bus' import v1SessionIngress from '../routes/v1/session-ingress' import v2WorkerEvents from '../routes/v2/worker-events' import webSessions from '../routes/web/sessions' import { issueToken } from '../auth/token' import { deletePersistedEvents } from '../services/event-persistence' import { publishSessionEvent } from '../services/transport' function createApp() { const app = new Hono() app.route('/v2/session_ingress', v1SessionIngress) app.route('/v1/code/sessions', v2WorkerEvents) app.route('/web', webSessions) return app } const AUTH_HEADERS = { Authorization: 'Bearer test-api-key', 'X-Username': 'testuser', } function auth(user: string): string { return `Bearer ${issueToken(user).token}` } const MODELS_STATE_MSG = { type: 'models_state', models_state: { availableModels: [ { modelId: 'firstParty', name: 'First Party' }, { modelId: 'firstParty:opus', name: 'Opus' }, ], currentModelId: 'firstParty', }, } describe('models_state snapshot survives history loss (gray selector regression)', () => { let app: Hono let sessionId: string beforeEach(async () => { storeReset() for (const [key] of getAllEventBuses()) { removeEventBus(key) } app = createApp() const res = await app.request('/web/sessions', { method: 'POST', headers: { Authorization: auth('user-1'), 'Content-Type': 'application/json', }, body: JSON.stringify({}), }) const body = (await res.json()) as { id: string } sessionId = body.id }) async function fetchHistory(): Promise< Array<{ id: string; type: string; payload: Record }> > { const res = await app.request(`/web/sessions/${sessionId}/history`, { headers: { Authorization: auth('user-1') }, }) expect(res.status).toBe(200) const body = (await res.json()) as { events: Array> } return body.events as Array<{ id: string type: string payload: Record }> } function parseModelsState( events: Array<{ id: string type: string payload: Record }>, ): { availableModels: unknown[]; currentModelId: string } | null { // Same parse the web adapter's loadHistory performs. for (const event of [...events].reverse()) { if (event.type !== 'models_state') continue const raw = event.payload.raw const state = ( raw && typeof raw === 'object' ? (raw as Record).models_state : event.payload.models_state ) as { availableModels: unknown[]; currentModelId: string } | undefined if ( state && Array.isArray(state.availableModels) && typeof state.currentModelId === 'string' ) { return state } } return null } test('v1 session-ingress POST path reaches /history', async () => { const ingestRes = await app.request( `/v2/session_ingress/session/${sessionId}/events`, { method: 'POST', headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [MODELS_STATE_MSG] }), }, ) expect(ingestRes.status).toBe(200) const state = parseModelsState(await fetchHistory()) expect(state).not.toBeNull() expect(state?.currentModelId).toBe('firstParty') }) test('v2 worker events POST path (payload envelope) reaches /history', async () => { const ingestRes = await app.request( `/v1/code/sessions/${sessionId}/worker/events`, { method: 'POST', headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' }, body: JSON.stringify([ { payload: { ...MODELS_STATE_MSG, uuid: 'u1' } }, ]), }, ) expect(ingestRes.status).toBe(200) const state = parseModelsState(await fetchHistory()) expect(state).not.toBeNull() expect(state?.availableModels).toHaveLength(2) }) test('POST /clear re-seeds models_state so re-entry still restores the selector', async () => { await app.request(`/v2/session_ingress/session/${sessionId}/events`, { method: 'POST', headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [MODELS_STATE_MSG] }), }) const clearRes = await app.request(`/web/sessions/${sessionId}/clear`, { method: 'POST', headers: { Authorization: auth('user-1') }, }) expect(clearRes.status).toBe(200) const state = parseModelsState(await fetchHistory()) expect(state).not.toBeNull() expect(state?.currentModelId).toBe('firstParty') }) test('/history merges the bus snapshot when the event log lost the entry', async () => { await app.request(`/v2/session_ingress/session/${sessionId}/events`, { method: 'POST', headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [MODELS_STATE_MSG] }), }) // Simulate pure log loss (server older than the re-seed, eviction, …): // wipe events but keep the bus alive — the snapshot must cover it. getEventBus(sessionId).clearHistory() deletePersistedEvents(sessionId) const state = parseModelsState(await fetchHistory()) expect(state).not.toBeNull() expect(state?.availableModels).toHaveLength(2) }) test('snapshot updates to the latest models_state (set_model re-report)', async () => { publishSessionEvent(sessionId, 'models_state', MODELS_STATE_MSG, 'inbound') publishSessionEvent( sessionId, 'models_state', { type: 'models_state', models_state: { ...MODELS_STATE_MSG.models_state, currentModelId: 'firstParty:opus', }, }, 'inbound', ) const state = parseModelsState(await fetchHistory()) expect(state?.currentModelId).toBe('firstParty:opus') }) test('GET /models returns null before the worker reports models_state', async () => { const res = await app.request(`/web/sessions/${sessionId}/models`, { headers: { Authorization: auth('user-1') }, }) expect(res.status).toBe(200) const body = (await res.json()) as { models: unknown } expect(body.models).toBeNull() }) test('GET /models serves the snapshot for the AI-generate model picker', async () => { await app.request(`/v2/session_ingress/session/${sessionId}/events`, { method: 'POST', headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [MODELS_STATE_MSG] }), }) const res = await app.request(`/web/sessions/${sessionId}/models`, { headers: { Authorization: auth('user-1') }, }) expect(res.status).toBe(200) const body = (await res.json()) as { models: { availableModels: Array<{ modelId: string; name: string }> currentModelId: string } | null } expect(body.models).not.toBeNull() expect(body.models?.currentModelId).toBe('firstParty') expect(body.models?.availableModels).toHaveLength(2) }) test('GET /models still serves the snapshot after /clear (picker survives clear)', async () => { await app.request(`/v2/session_ingress/session/${sessionId}/events`, { method: 'POST', headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [MODELS_STATE_MSG] }), }) await app.request(`/web/sessions/${sessionId}/clear`, { method: 'POST', headers: { Authorization: auth('user-1') }, }) const res = await app.request(`/web/sessions/${sessionId}/models`, { headers: { Authorization: auth('user-1') }, }) expect(res.status).toBe(200) const body = (await res.json()) as { models: { currentModelId: string } | null } expect(body.models?.currentModelId).toBe('firstParty') }) })