/** * POST /web/sessions/:id/rewind — event-sourced conversation rewind. * * The endpoint resolves the worker-side message_uuid from the target event, * publishes a PERSISTED conversation_rewound marker (viewers + future history * replays truncate), and forwards a TRANSIENT rewind_conversation control to * the worker (replay-safe: reconnects must not re-rewind). */ import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' mock.module('../config', () => mockConfigModule({})) import { freshDb } from './helpers/db' import { createUserDirectly } from './helpers/fixtures' import { Hono } from 'hono' import { storeReset, storeCreateSession, storeBindSession } from '../store' import { getDb } from '../db/sqlite' import { createSession } from '../services/session' import { publishSessionEvent } from '../services/transport' import { getEventBus, type SessionEvent } from '../transport/event-bus' import webSessions from '../routes/web/sessions' import { issueToken } from '../auth/token' function createApp() { const app = new Hono() app.route('/web', webSessions) return app } let ownerToken = '' let ownerId = '' beforeEach(() => { freshDb() storeReset() const owner = createUserDirectly(getDb(), { username: 'rewind-owner' }) ownerId = owner.id ownerToken = issueToken('rewind-owner').token }) function auth(): string { return `Bearer ${ownerToken}` } function makeOwnedSession(): string { const session = storeCreateSession({ title: 'rewind test' }) // sessionAuth 的 userId 是 username(resolveToken 返回用户名)— 绑定用 // username 而非 usr_ id,与线上 /web/auth/login 建立的归属一致。 storeBindSession(session.id, 'rewind-owner') return session.id } function seedConversation(sessionId: string): { firstUserEventId: string secondUserEventId: string } { const first = publishSessionEvent( sessionId, 'user', { type: 'user', content: '第一条消息', uuid: 'uuid-first' }, 'outbound', ) publishSessionEvent( sessionId, 'assistant', { content: '第一条回复', uuid: 'a-1' }, 'inbound', ) const second = publishSessionEvent( sessionId, 'user', { type: 'user', content: '第二条消息', uuid: 'uuid-second' }, 'outbound', ) publishSessionEvent( sessionId, 'assistant', { content: '第二条回复', uuid: 'a-2' }, 'inbound', ) return { firstUserEventId: first.id, secondUserEventId: second.id } } describe('POST /web/sessions/:id/rewind', () => { test('publishes a persisted marker and a transient worker control', async () => { const sessionId = makeOwnedSession() const { firstUserEventId } = seedConversation(sessionId) const bus = getEventBus(sessionId) const outbound: SessionEvent[] = [] bus.subscribe(e => { if (e.direction === 'outbound') outbound.push(e) }) const res = await createApp().request(`/web/sessions/${sessionId}/rewind`, { method: 'POST', headers: { Authorization: auth(), 'Content-Type': 'application/json' }, body: JSON.stringify({ target_event_id: firstUserEventId }), }) expect(res.status).toBe(200) const body = (await res.json()) as { message_uuid?: string } expect(body.message_uuid).toBe('uuid-first') // Persisted marker — retained in the replay window for all viewers const marker = bus .getEventsSince(0) .find(e => e.type === 'conversation_rewound') expect(marker).toBeDefined() expect(marker?.direction).toBe('inbound') const markerPayload = marker?.payload as Record expect(markerPayload.target_event_id).toBe(firstUserEventId) expect(markerPayload.message_uuid).toBe('uuid-first') // Transient control — never retained expect( bus.getEventsSince(0).filter(e => e.type === 'control_request').length, ).toBe(0) const control = outbound.find(e => e.type === 'control_request') expect(control).toBeDefined() expect((control?.payload as Record).request).toEqual({ subtype: 'rewind_conversation', message_uuid: 'uuid-first', }) }) test('rejects missing or non-user target events', async () => { const sessionId = makeOwnedSession() seedConversation(sessionId) const app = createApp() const noBody = await app.request(`/web/sessions/${sessionId}/rewind`, { method: 'POST', headers: { Authorization: auth(), 'Content-Type': 'application/json' }, body: JSON.stringify({}), }) expect(noBody.status).toBe(400) const bogus = await app.request(`/web/sessions/${sessionId}/rewind`, { method: 'POST', headers: { Authorization: auth(), 'Content-Type': 'application/json' }, body: JSON.stringify({ target_event_id: 'does-not-exist' }), }) expect(bogus.status).toBe(400) // 非用户消息事件也不可回退 const assistantEvent = getEventBus(sessionId) .getEventsSince(0) .find(e => e.type === 'assistant') const notUser = await app.request(`/web/sessions/${sessionId}/rewind`, { method: 'POST', headers: { Authorization: auth(), 'Content-Type': 'application/json' }, body: JSON.stringify({ target_event_id: assistantEvent?.id }), }) expect(notUser.status).toBe(400) }) test('falls back to the event id when the payload has no uuid', async () => { const sessionId = makeOwnedSession() const target = publishSessionEvent( sessionId, 'user', { type: 'user', content: 'legacy shape' }, 'outbound', ) const res = await createApp().request(`/web/sessions/${sessionId}/rewind`, { method: 'POST', headers: { Authorization: auth(), 'Content-Type': 'application/json' }, body: JSON.stringify({ target_event_id: target.id }), }) expect(res.status).toBe(200) const body = (await res.json()) as { message_uuid?: string } expect(body.message_uuid).toBe(target.id) }) test('requires authentication', async () => { const sessionId = makeOwnedSession() const { firstUserEventId } = seedConversation(sessionId) const res = await createApp().request(`/web/sessions/${sessionId}/rewind`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ target_event_id: firstUserEventId }), }) expect(res.status).toBe(401) }) })