import type { ServerWebSocket } from 'bun'; import { expect, test } from 'bun:test'; import { getLogger } from '@stock-bot/logger'; import type { PostgresClient } from '@stock-bot/services'; import { createWebSocketHandler, type RunSocketData, } from '../../apps/stock/web-api/src/websocket/run-updates'; test('dashboard notifications reflect committed state across owners and emit completion once', async () => { const id = '39b3ad03-361c-4ea2-8f5e-2fd702fa3f20'; const messages: { type: string; data?: Record }[] = []; let row = { id, status: 'running', progress: '17', attempt_number: 2, cancel_requested: false, current_simulation_date: new Date('2024-01-02'), updated_at: new Date(), }; const postgres = { async query(_sql: string, params: unknown[]) { expect(params).toEqual([[id]]); return { rows: [row] }; }, } as unknown as PostgresClient; const handler = createWebSocketHandler({ logger: getLogger('notification-test'), postgres }); const ws = { data: { runId: id }, send(message: string) { messages.push(JSON.parse(message)); }, close() {}, } as unknown as ServerWebSocket; try { handler.handleConnection(ws, id); await handler.refreshRunUpdates(); expect(messages.find(message => message.type === 'run_update')?.data).toMatchObject({ status: 'running', attemptNumber: 2, progress: 17, }); row = { ...row, status: 'completed', progress: '100' }; await handler.refreshRunUpdates(); await handler.refreshRunUpdates(); expect(messages.filter(message => message.type === 'completed')).toHaveLength(1); } finally { handler.cleanup(); } });