diff --git a/.compozy/tasks/server-side-simulation/_tasks.md b/.compozy/tasks/server-side-simulation/_tasks.md index f6bf081..d904854 100644 --- a/.compozy/tasks/server-side-simulation/_tasks.md +++ b/.compozy/tasks/server-side-simulation/_tasks.md @@ -10,7 +10,7 @@ | 04 | `SimulationManager` — ciclo de vida, `sim_id`, TTL, limite | completed | high | task_03 | | 05 | `WsGateway` + `MessageRouter` + rota `/ws` | completed | high | task_02, task_04 | | 06 | `SimulationSocket` (web) — WS client, reconexão, `localStorage` | completed | medium | task_02, task_05 | -| 07 | Religar `simulationStore` ao `SimulationSocket` | pending | medium | task_06 | +| 07 | Religar `simulationStore` ao `SimulationSocket` | completed | medium | task_06 | | 08 | Remoção do motor no cliente (worker, mock, public/wasm, tipos) | pending | medium | task_07 | | 09 | CI: build WASM (emsdk) + cache antes dos testes | completed | medium | task_01 | diff --git a/.compozy/tasks/server-side-simulation/task_07.md b/.compozy/tasks/server-side-simulation/task_07.md index 8182806..2987f07 100644 --- a/.compozy/tasks/server-side-simulation/task_07.md +++ b/.compozy/tasks/server-side-simulation/task_07.md @@ -1,5 +1,5 @@ --- -status: pending +status: completed title: Religar `simulationStore` ao `SimulationSocket` type: frontend complexity: medium @@ -33,11 +33,11 @@ componentes React, nada muda. ## Subtasks -- [ ] 7.1 Injetar/instanciar o `SimulationSocket` no store no lugar do `Worker`. -- [ ] 7.2 Mapear play/pause/reset/loadScenario/applyEnvironment → `ClientMessage`. -- [ ] 7.3 Atualizar `state`/`status`/`error` a partir de `ServerMessage` e estados de conexão. -- [ ] 7.4 Reemitir comandos pendentes após (re)conexão. -- [ ] 7.5 Atualizar os testes do store para o novo backend (transporte mockado, sem motor). +- [x] 7.1 Injetar/instanciar o `SimulationSocket` no store no lugar do `Worker`. +- [x] 7.2 Mapear play/pause/reset/loadScenario/applyEnvironment → `ClientMessage`. +- [x] 7.3 Atualizar `state`/`status`/`error` a partir de `ServerMessage` e estados de conexão. +- [x] 7.4 Reemitir comandos pendentes após (re)conexão. +- [x] 7.5 Atualizar os testes do store para o novo backend (transporte mockado, sem motor). ## Implementation Details Ver TechSpec seções "System Architecture" (simulationStore religado) e "Development Sequencing" diff --git a/apps/web/src/features/scenario-creator/components/SimulationControls.test.tsx b/apps/web/src/features/scenario-creator/components/SimulationControls.test.tsx index 1468424..9cf1fd9 100644 --- a/apps/web/src/features/scenario-creator/components/SimulationControls.test.tsx +++ b/apps/web/src/features/scenario-creator/components/SimulationControls.test.tsx @@ -38,23 +38,22 @@ describe('SimulationControls (status strip)', () => { expect(screen.getByText(/erro/i)).toBeInTheDocument() }) - it('warns when the physics engine fell back to the mock', () => { - useSimulationStore.setState({ status: 'running', state: { t: 1, vessels: [] }, engine: 'mock' }) + it('warns when the connection is reconnecting', () => { + useSimulationStore.setState({ status: 'running', state: { t: 1, vessels: [] }, connection: 'reconnecting' }) render() - expect(screen.getByRole('alert')).toHaveTextContent(/mock/i) - expect(screen.getByRole('alert')).toHaveTextContent(/build:wasm/) + expect(screen.getByRole('alert')).toHaveTextContent(/reconect/i) }) - it('confirms when real WASM physics is loaded', () => { - useSimulationStore.setState({ status: 'running', state: { t: 1, vessels: [] }, engine: 'wasm' }) + it('confirms when connected to the server', () => { + useSimulationStore.setState({ status: 'running', state: { t: 1, vessels: [] }, connection: 'open' }) render() - expect(screen.getByText(/Física real \(WASM\)/i)).toBeInTheDocument() + expect(screen.getByText(/Conectado ao servidor/i)).toBeInTheDocument() expect(screen.queryByRole('alert')).toBeNull() }) - it('shows no engine badge before the worker reports ready', () => { - useSimulationStore.setState({ status: 'idle', engine: null }) + it('shows no connection badge before a session exists', () => { + useSimulationStore.setState({ status: 'idle', connection: 'idle' }) render() - expect(screen.queryByText(/Física/i)).toBeNull() + expect(screen.queryByText(/servidor/i)).toBeNull() }) }) diff --git a/apps/web/src/features/scenario-creator/components/SimulationControls.tsx b/apps/web/src/features/scenario-creator/components/SimulationControls.tsx index e2c6e07..c332fd3 100644 --- a/apps/web/src/features/scenario-creator/components/SimulationControls.tsx +++ b/apps/web/src/features/scenario-creator/components/SimulationControls.tsx @@ -2,12 +2,12 @@ import { useSimulationStore } from '../../../stores/simulationStore' import { tokens } from '../../../theme/tokens' /** - * Compact simulation status strip: lifecycle text + which physics engine is - * actually loaded (real WASM vs JS mock fallback). The Build/Play/Stop actions - * live in the floating {@link SimulationControl} pill in the app shell. + * Compact simulation status strip: lifecycle text + connection to the + * server-side simulation. The Build/Play/Stop actions live in the floating + * {@link SimulationControl} pill in the app shell. */ export function SimulationControls() { - const { status, state, engine } = useSimulationStore() + const { status, state, connection } = useSimulationStore() return (
@@ -20,17 +20,17 @@ export function SimulationControls() { {status === 'running' && !state && '▶ Rodando'} {status === 'error' && ⚠ Erro na simulação}
- {engine === 'mock' && (status === 'paused' || status === 'running') && ( + {connection === 'reconnecting' && (
- ⚠ Física simulada (mock) — o módulo WASM não foi compilado. Rode pnpm build:wasm para a dinâmica real. + ⚠ Reconectando ao servidor de simulação...
)} - {engine === 'wasm' && (status === 'paused' || status === 'running') && ( + {connection === 'open' && (status === 'paused' || status === 'running') && (
- ● Física real (WASM) + ● Conectado ao servidor
)} diff --git a/apps/web/src/features/scenario-creator/components/VesselPanel.test.tsx b/apps/web/src/features/scenario-creator/components/VesselPanel.test.tsx index 0fd44ef..8178e65 100644 --- a/apps/web/src/features/scenario-creator/components/VesselPanel.test.tsx +++ b/apps/web/src/features/scenario-creator/components/VesselPanel.test.tsx @@ -32,7 +32,7 @@ function resetStores() { selectedVesselId: null, vesselTypeId: null, config: null, configLoading: false, rudderAngles: {}, thrusterPowers: {}, thrusterAzimuths: {}, }) - useSimulationStore.setState({ status: 'idle', state: null, worker: null }) + useSimulationStore.setState({ status: 'idle', state: null }) } describe('VesselPanel', () => { @@ -75,10 +75,10 @@ describe('VesselPanel', () => { expect(screen.getByText('0.0057 rad/s')).toBeInTheDocument() }) - it('Controles tab moves a rudder and posts an actuator command', async () => { + it('Controles tab moves a rudder and sends an actuator command', async () => { vi.stubGlobal('fetch', mockFetchOnce(true)) - const postMessage = vi.fn() - useSimulationStore.setState({ worker: { postMessage } as unknown as Worker }) + const sendActuator = vi.fn() + useSimulationStore.setState({ sendActuator }) render() useVesselPanelStore.getState().open(1, 1) await screen.findByText('Dimensões') @@ -89,14 +89,12 @@ describe('VesselPanel', () => { fireEvent.change(sliders[0], { target: { value: '20' } }) expect(useVesselPanelStore.getState().rudderAngles[0]).toBe(20) - expect(postMessage).toHaveBeenCalledWith( - expect.objectContaining({ type: 'setActuator', deviceType: 'rudder', value: 20 }), - ) + expect(sendActuator).toHaveBeenCalledWith(1, 'rudder', 0, 20) }) it('renders an azimuth dial for azimuthal thrusters and reacts to clicks', async () => { vi.stubGlobal('fetch', mockFetchOnce(true)) - useSimulationStore.setState({ worker: { postMessage: vi.fn() } as unknown as Worker }) + useSimulationStore.setState({ sendActuator: vi.fn() }) render() useVesselPanelStore.getState().open(1, 1) await screen.findByText('Dimensões') diff --git a/apps/web/src/features/scenario-creator/components/VesselPanel.tsx b/apps/web/src/features/scenario-creator/components/VesselPanel.tsx index 3ea9eeb..3b00c5f 100644 --- a/apps/web/src/features/scenario-creator/components/VesselPanel.tsx +++ b/apps/web/src/features/scenario-creator/components/VesselPanel.tsx @@ -143,19 +143,19 @@ function ControlesTab({ config, vesselId }: { config: VesselConfigDTO; vesselId: rudderAngles, thrusterPowers, thrusterAzimuths, setRudderAngle, setThrusterPower, setThrusterAzimuth, } = useVesselPanelStore() - const { worker } = useSimulationStore() + const sendActuator = useSimulationStore((s) => s.sendActuator) function sendRudder(rudderId: number, deg: number) { setRudderAngle(rudderId, deg) - worker?.postMessage({ type: 'setActuator', vesselId, deviceType: 'rudder', deviceId: rudderId, value: deg }) + sendActuator(vesselId, 'rudder', rudderId, deg) } function sendThrusterPower(thrusterId: number, pct: number) { setThrusterPower(thrusterId, pct) - worker?.postMessage({ type: 'setActuator', vesselId, deviceType: 'thruster', deviceId: thrusterId, value: pct, value2: thrusterAzimuths[thrusterId] ?? 0 }) + sendActuator(vesselId, 'thruster', thrusterId, pct, thrusterAzimuths[thrusterId] ?? 0) } function sendThrusterAzimuth(thrusterId: number, deg: number) { setThrusterAzimuth(thrusterId, deg) - worker?.postMessage({ type: 'setActuator', vesselId, deviceType: 'thruster', deviceId: thrusterId, value: thrusterPowers[thrusterId] ?? 0, value2: deg }) + sendActuator(vesselId, 'thruster', thrusterId, thrusterPowers[thrusterId] ?? 0, deg) } if (config.rudders.length === 0 && config.thrusters.length === 0) { diff --git a/apps/web/src/features/shell/AppShell.tsx b/apps/web/src/features/shell/AppShell.tsx index 2bec05f..47dcc32 100644 --- a/apps/web/src/features/shell/AppShell.tsx +++ b/apps/web/src/features/shell/AppShell.tsx @@ -63,7 +63,7 @@ export function AppShell() { // current (live) position so the scene doesn't jump back to the start. function handlePlay() { const sim = useSimulationStore.getState() - if (!sim.worker) { + if (!sim.socket) { loadScenario(vessels) play() return diff --git a/apps/web/src/stores/simulationStore.test.ts b/apps/web/src/stores/simulationStore.test.ts index 4a54562..8fc9ee0 100644 --- a/apps/web/src/stores/simulationStore.test.ts +++ b/apps/web/src/stores/simulationStore.test.ts @@ -1,269 +1,205 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import type { ClientMessage, ServerMessage } from '@ymir/types' +import { SimulationSocket } from '../lib/simulation-socket' +import { useSimulationStore, __setSocketFactory } from './simulationStore' +import { useEnvironmentStore } from './environmentStore' +import { useVesselPanelStore } from './vesselPanelStore' -// MockWorker must be defined before the store is imported so that vi.stubGlobal -// is in place when the module is first evaluated. -class MockWorker { - onmessage: ((e: MessageEvent) => void) | null = null - onerror: ((e: ErrorEvent) => void) | null = null - postMessage = vi.fn() - terminate = vi.fn() +class FakeWebSocket { + static CONNECTING = 0 + static OPEN = 1 + static CLOSED = 3 + static instances: FakeWebSocket[] = [] + readyState = FakeWebSocket.CONNECTING + onopen: (() => void) | null = null + onmessage: ((e: { data: string }) => void) | null = null + onclose: (() => void) | null = null + sent: string[] = [] + constructor(public url: string) { FakeWebSocket.instances.push(this) } + send(data: string) { this.sent.push(data) } + close() { this.readyState = FakeWebSocket.CLOSED; this.onclose?.() } + open() { this.readyState = FakeWebSocket.OPEN; this.onopen?.() } + emit(msg: ServerMessage) { this.onmessage?.({ data: JSON.stringify(msg) }) } + get sentMessages(): ClientMessage[] { return this.sent.map((s) => JSON.parse(s) as ClientMessage) } +} - /** Helper: simulate an inbound message from the worker */ - _emit(data: unknown) { - this.onmessage?.({ data } as MessageEvent) +function makeStorage() { + const m = new Map() + return { + getItem: (k: string) => m.get(k) ?? null, + setItem: (k: string, v: string) => { m.set(k, v) }, + removeItem: (k: string) => { m.delete(k) }, } } -vi.stubGlobal('Worker', MockWorker) - -// Also stub URL constructor used inside start() -vi.stubGlobal('URL', class { - constructor(public href: string, public base?: string) {} -}) - -// Import AFTER stubs are in place -import { useSimulationStore } from './simulationStore' -import { useEnvironmentStore } from './environmentStore' - -// Helper to access raw store state without React hooks +let storage = makeStorage() const store = () => useSimulationStore.getState() +const lastWs = () => FakeWebSocket.instances[FakeWebSocket.instances.length - 1] beforeEach(() => { - // Reset store to initial state before every test + FakeWebSocket.instances = [] + storage = makeStorage() + __setSocketFactory(() => new SimulationSocket({ + url: 'ws://test/ws', + WebSocketImpl: FakeWebSocket as unknown as typeof WebSocket, + storage, + })) store().reset() useEnvironmentStore.getState().reset() - vi.clearAllMocks() + useVesselPanelStore.setState({ selectedVesselId: null, rudderAngles: {}, thrusterPowers: {}, thrusterAzimuths: {} }) }) +afterEach(() => { __setSocketFactory(null) }) + +/** Boot a session up to a confirmed simulation and return its id. */ +function createSession(dt = 0.05): string { + store().play(dt) + lastWs().open() + lastWs().emit({ type: 'SimulationCreated', simId: 'sim-1' }) + return 'sim-1' +} + describe('simulationStore — initial state', () => { - it('starts with status idle', () => { + it('starts idle with no socket or session', () => { + expect(store().status).toBe('idle') + expect(store().socket).toBeNull() + expect(store().simId).toBeNull() + expect(store().scenarioVessels).toEqual([]) + expect(store().hasSession()).toBe(false) + }) +}) + +describe('simulationStore — play/create flow', () => { + it('creates a socket and enters loading on first play', () => { + store().play(0.05) + expect(store().status).toBe('loading') + expect(store().socket).not.toBeNull() + expect(FakeWebSocket.instances).toHaveLength(1) + }) + + it('sends CreateSimulation on open and Play after SimulationCreated', () => { + store().loadScenario([{ instanceId: 1, vesselId: 1, name: 'A', x: 0, y: 0, headingDeg: 0 }]) + store().play(0.1) + lastWs().open() + expect(lastWs().sentMessages.some((m) => m.type === 'CreateSimulation')).toBe(true) + lastWs().emit({ type: 'SimulationCreated', simId: 'sim-9' }) + expect(store().simId).toBe('sim-9') + const play = lastWs().sentMessages.find((m) => m.type === 'Play') + expect(play).toEqual({ type: 'Play', simId: 'sim-9', dt: 0.1 }) + expect(store().status).toBe('running') + }) + + it('resumes with a Play when a sim id already exists (reconnect)', () => { + storage.setItem('ymir.simId', 'sim-existing') + store().play(0.05) + lastWs().open() + const msgs = lastWs().sentMessages + expect(msgs).toContainEqual({ type: 'AttachSimulation', simId: 'sim-existing' }) + expect(msgs.some((m) => m.type === 'Play' && m.simId === 'sim-existing')).toBe(true) + expect(store().status).toBe('running') + }) +}) + +describe('simulationStore — server messages', () => { + it('State updates the store state', () => { + createSession() + lastWs().emit({ type: 'State', payload: { t: 3, vessels: [] } }) + expect(store().state).toEqual({ t: 3, vessels: [] }) + }) + + it('Status paused sets status; ended maps to idle', () => { + createSession() + lastWs().emit({ type: 'Status', status: 'paused' }) + expect(store().status).toBe('paused') + lastWs().emit({ type: 'Status', status: 'ended' }) expect(store().status).toBe('idle') }) - it('starts with null error, state, and worker', () => { - expect(store().error).toBeNull() - expect(store().state).toBeNull() - expect(store().worker).toBeNull() + it('Error sets status error and message', () => { + createSession() + lastWs().emit({ type: 'Error', message: 'boom' }) + expect(store().status).toBe('error') + expect(store().error).toBe('boom') }) - it('starts with empty scenarioVessels', () => { - expect(store().scenarioVessels).toEqual([]) + it('re-syncs actuator state after SimulationCreated', () => { + useVesselPanelStore.setState({ selectedVesselId: 1, thrusterPowers: { 0: 80 }, thrusterAzimuths: { 0: 10 }, rudderAngles: { 0: 15 } }) + createSession() + const acts = lastWs().sentMessages.filter((m) => m.type === 'SetActuator') + expect(acts.some((m) => m.type === 'SetActuator' && m.deviceType === 'thruster' && m.value === 80)).toBe(true) + expect(acts.some((m) => m.type === 'SetActuator' && m.deviceType === 'rudder' && m.value === 15)).toBe(true) + }) + + it('tracks connection state changes', () => { + store().play() + expect(store().connection).toBe('connecting') + lastWs().open() + expect(store().connection).toBe('open') }) }) -describe('simulationStore — loadScenario', () => { - it('sets scenarioVessels without a worker', () => { - const vessels = [{ instanceId: 1, vesselId: 1, name: 'Ship A', x: 0, y: 0, headingDeg: 90 }] +describe('simulationStore — commands', () => { + it('pause sends Pause and sets status paused', () => { + const simId = createSession() + store().pause() + expect(lastWs().sentMessages.some((m) => m.type === 'Pause' && m.simId === simId)).toBe(true) + expect(store().status).toBe('paused') + }) + + it('pause sets paused even without a session', () => { + store().pause() + expect(store().status).toBe('paused') + }) + + it('loadScenario forwards to an active session', () => { + createSession() + const vessels = [{ instanceId: 2, vesselId: 2, name: 'B', x: 1, y: 2, headingDeg: 90 }] + store().loadScenario(vessels) + expect(lastWs().sentMessages.some((m) => m.type === 'LoadScenario')).toBe(true) + expect(store().scenarioVessels).toEqual(vessels) + }) + + it('loadScenario without a session only stores vessels', () => { + const vessels = [{ instanceId: 3, vesselId: 3, name: 'C', x: 0, y: 0, headingDeg: 0 }] store().loadScenario(vessels) expect(store().scenarioVessels).toEqual(vessels) }) - it('posts loadScenario message to existing worker', () => { - // Manually set a mock worker into the store - const mockWorker = new MockWorker() - useSimulationStore.setState({ worker: mockWorker as unknown as Worker, status: 'paused' }) - - const vessels = [{ instanceId: 2, vesselId: 2, name: 'Ship B', x: 10, y: 20, headingDeg: 0 }] - store().loadScenario(vessels) - - expect(mockWorker.postMessage).toHaveBeenCalledWith({ type: 'loadScenario', vessels }) - expect(store().scenarioVessels).toEqual(vessels) - }) -}) - -describe('simulationStore — stop', () => { - it('sets status to paused and sends stop message to worker', () => { - const mockWorker = new MockWorker() - useSimulationStore.setState({ worker: mockWorker as unknown as Worker, status: 'running' }) - - store().pause() - - expect(store().status).toBe('paused') - expect(mockWorker.postMessage).toHaveBeenCalledWith({ type: 'stop' }) + it('applyEnvironment sends LoadEnvironment when conditions exist', () => { + createSession() + useEnvironmentStore.setState({ currentSeries: [[{ t: 0, speed: 2, dirNaut: 90 }]] }) + store().applyEnvironment() + const env = lastWs().sentMessages.find((m) => m.type === 'LoadEnvironment') + expect(env).toBeTruthy() }) - it('sets status to paused even when no worker is present', () => { - useSimulationStore.setState({ status: 'running', worker: null }) - store().pause() - expect(store().status).toBe('paused') + it('applyEnvironment is a no-op with an empty environment', () => { + createSession() + store().applyEnvironment() + expect(lastWs().sentMessages.some((m) => m.type === 'LoadEnvironment')).toBe(false) + }) + + it('sendActuator sends SetActuator with the sim id', () => { + const simId = createSession() + store().sendActuator(1, 'thruster', 0, 75, 20) + const act = lastWs().sentMessages.find((m) => m.type === 'SetActuator') + expect(act).toEqual({ type: 'SetActuator', simId, vesselId: 1, deviceType: 'thruster', deviceId: 0, value: 75, value2: 20 }) + }) + + it('sendActuator is a no-op without a session', () => { + store().sendActuator(1, 'rudder', 0, 10) + expect(FakeWebSocket.instances).toHaveLength(0) }) }) describe('simulationStore — reset', () => { - it('clears status, error, state, worker, and scenarioVessels', () => { - const mockWorker = new MockWorker() - useSimulationStore.setState({ - worker: mockWorker as unknown as Worker, - status: 'running', - error: 'some error', - state: { vessels: [] } as never, - scenarioVessels: [{ instanceId: 3, vesselId: 3, name: 'Ship C', x: 5, y: 5, headingDeg: 45 }], - }) - + it('sends Reset, closes the socket, and clears state', () => { + const simId = createSession() store().reset() - + expect(lastWs().sentMessages.some((m) => m.type === 'Reset' && m.simId === simId)).toBe(true) expect(store().status).toBe('idle') - expect(store().error).toBeNull() - expect(store().state).toBeNull() - expect(store().worker).toBeNull() + expect(store().socket).toBeNull() + expect(store().simId).toBeNull() expect(store().scenarioVessels).toEqual([]) }) - - it('terminates the worker on reset', () => { - const mockWorker = new MockWorker() - useSimulationStore.setState({ worker: mockWorker as unknown as Worker, status: 'running' }) - - store().reset() - - expect(mockWorker.terminate).toHaveBeenCalledOnce() - }) -}) - -describe('simulationStore — start (with mock worker)', () => { - it('transitions to loading then running after worker emits ready', () => { - store().play(0.05) - - // Status should be loading while worker is being set up - expect(store().status).toBe('loading') - - // Retrieve the worker instance created by start() - const mockWorker = store().worker as unknown as MockWorker - - // Simulate the worker posting a 'ready' message - mockWorker._emit({ type: 'ready' }) - - expect(store().status).toBe('running') - }) - - it('sends loadScenario before start when scenarioVessels are set', () => { - const vessels = [{ instanceId: 4, vesselId: 4, name: 'Ship D', x: 1, y: 2, headingDeg: 180 }] - useSimulationStore.setState({ scenarioVessels: vessels }) - - store().play(0.05) - - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'ready' }) - - const calls = mockWorker.postMessage.mock.calls.map((c) => c[0] as { type: string }) - const loadCall = calls.find((c) => c.type === 'loadScenario') - const startCall = calls.find((c) => c.type === 'start') - - expect(loadCall).toBeDefined() - expect(startCall).toBeDefined() - - // loadScenario must precede start - const loadIdx = calls.indexOf(loadCall!) - const startIdx = calls.indexOf(startCall!) - expect(loadIdx).toBeLessThan(startIdx) - }) - - it('sets status to error when worker emits error message', () => { - store().play() - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'error', message: 'WASM failed to load' }) - - expect(store().status).toBe('error') - expect(store().error).toBe('WASM failed to load') - }) - - it('uses Unknown error fallback when error message is undefined', () => { - store().play() - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'error' }) - expect(store().error).toBe('Unknown error') - }) - - it('handles state message with undefined payload (sets null)', () => { - store().play() - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'ready' }) - mockWorker._emit({ type: 'state' }) - expect(store().state).toBeNull() - }) - - it('calls postMessage on existing worker when start called again', () => { - const mockWorker = new MockWorker() - useSimulationStore.setState({ worker: mockWorker as unknown as Worker, status: 'paused' }) - store().play(0.1) - expect(mockWorker.postMessage).toHaveBeenCalledWith({ type: 'start', dt: 0.1 }) - expect(store().status).toBe('running') - }) -}) - -describe('simulationStore — loadEnvironment on start', () => { - it('sends loadEnvironment before start when environment has conditions', () => { - useEnvironmentStore.setState({ - currentSeries: [[{ t: 0, speed: 1.0, dirNaut: 90 }]], - }) - - store().play(0.05) - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'ready' }) - - const calls = mockWorker.postMessage.mock.calls.map((c) => c[0] as { type: string }) - const loadEnvIdx = calls.findIndex((c) => c.type === 'loadEnvironment') - const startIdx = calls.findIndex((c) => c.type === 'start') - - expect(loadEnvIdx).toBeGreaterThanOrEqual(0) - expect(startIdx).toBeGreaterThanOrEqual(0) - expect(loadEnvIdx).toBeLessThan(startIdx) - }) - - it('does not send loadEnvironment when environment is empty', () => { - store().play(0.05) - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'ready' }) - - const calls = mockWorker.postMessage.mock.calls.map((c) => c[0] as { type: string }) - expect(calls.some((c) => c.type === 'loadEnvironment')).toBe(false) - }) - - it('loadEnvironment message contains valid JSON with environment data', () => { - useEnvironmentStore.setState({ - currentSeries: [[{ t: 0, speed: 2.0, dirNaut: 180 }]], - }) - - store().play(0.05) - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'ready' }) - - const calls = mockWorker.postMessage.mock.calls.map((c) => c[0]) - const loadEnvCall = calls.find((c: { type: string }) => c.type === 'loadEnvironment') as - | { type: string; json: string } - | undefined - expect(loadEnvCall).toBeDefined() - expect(typeof loadEnvCall!.json).toBe('string') - const parsed = JSON.parse(loadEnvCall!.json) - expect(parsed.currentSeries).toHaveLength(1) - expect(parsed.currentSeries[0][0].speed).toBe(2.0) - }) - - it('does not send loadEnvironment when only wind conditions are empty', () => { - // Explicitly verify wind conditions trigger the send - useEnvironmentStore.setState({ - windSeries: [[{ t: 0, speed: 5.0, dirNaut: 0 }]], - }) - - store().play(0.05) - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'ready' }) - - const calls = mockWorker.postMessage.mock.calls.map((c) => c[0] as { type: string }) - expect(calls.some((c) => c.type === 'loadEnvironment')).toBe(true) - }) - - it('existing start/stop/loadScenario/setActuator paths unaffected by environment integration', () => { - const vessels = [{ instanceId: 1, vesselId: 1, name: 'Ship A', x: 0, y: 0, headingDeg: 0 }] - useSimulationStore.setState({ scenarioVessels: vessels }) - - store().play(0.05) - const mockWorker = store().worker as unknown as MockWorker - mockWorker._emit({ type: 'ready' }) - - const calls = mockWorker.postMessage.mock.calls.map((c) => c[0] as { type: string }) - expect(calls.some((c) => c.type === 'loadScenario')).toBe(true) - expect(calls.some((c) => c.type === 'start')).toBe(true) - // No loadEnvironment when store is empty - expect(calls.some((c) => c.type === 'loadEnvironment')).toBe(false) - }) }) diff --git a/apps/web/src/stores/simulationStore.ts b/apps/web/src/stores/simulationStore.ts index d1bc53d..631c511 100644 --- a/apps/web/src/stores/simulationStore.ts +++ b/apps/web/src/stores/simulationStore.ts @@ -1,141 +1,164 @@ import { create } from 'zustand' -import type { SimulationStateDTO, SimulationEngine } from '@ymir/types' +import type { SimulationStateDTO, ScenarioDraftVesselDTO, ServerMessage } from '@ymir/types' +import { SimulationSocket, type ConnectionState } from '../lib/simulation-socket' import { useVesselPanelStore } from './vesselPanelStore' import { useEnvironmentStore } from './environmentStore' type Status = 'idle' | 'loading' | 'running' | 'paused' | 'error' -interface ScenarioDraftVessel { - instanceId: number - vesselId: number - name: string - x: number - y: number - headingDeg: number +type ScenarioDraftVessel = ScenarioDraftVesselDTO + +/** Socket factory — overridable in tests to inject a fake transport. */ +let socketFactory: () => SimulationSocket = () => new SimulationSocket() +export function __setSocketFactory(factory: (() => SimulationSocket) | null): void { + socketFactory = factory ?? (() => new SimulationSocket()) } +// dt to send with Play once the server confirms a freshly created simulation. +let pendingPlayDt: number | null = null + interface SimulationStore { status: Status error: string | null state: SimulationStateDTO | null - engine: SimulationEngine | null - worker: Worker | null + connection: ConnectionState | 'idle' + socket: SimulationSocket | null + simId: string | null scenarioVessels: ScenarioDraftVessel[] - /** Start (first time) or resume (after pause) the simulation loop. */ + /** True once a session (socket) exists. */ + hasSession: () => boolean + /** Start (first time: create the sim) or resume the simulation. */ play: (dt?: number) => void - /** Freeze the loop at the current state — does NOT reset position/time. */ + /** Pause the simulation on the server; state is retained. */ pause: () => void + /** End the simulation, close the socket, and clear local state. */ reset: () => void loadScenario: (vessels: ScenarioDraftVessel[]) => void - /** Push the current environment profile to a running/paused worker. */ + /** Push the current environment profile to the running simulation. */ applyEnvironment: () => void + /** Send an actuator command (rudder/thruster) to a vessel. */ + sendActuator: ( + vesselId: number, + deviceType: 'rudder' | 'thruster', + deviceId: number, + value: number, + value2?: number, + ) => void } -export const useSimulationStore = create((set, get) => ({ - status: 'idle', - error: null, - state: null, - engine: null, - worker: null, - scenarioVessels: [], +export const useSimulationStore = create((set, get) => { + function resyncActuators(simId: string): void { + const panel = useVesselPanelStore.getState() + if (panel.selectedVesselId === null) return + const vesselId = panel.selectedVesselId + const { socket } = get() + if (!socket) return + for (const [id, pct] of Object.entries(panel.thrusterPowers)) { + const thrusterId = Number(id) + socket.send({ + type: 'SetActuator', simId, vesselId, deviceType: 'thruster', + deviceId: thrusterId, value: pct, value2: panel.thrusterAzimuths[thrusterId] ?? 0, + }) + } + for (const [id, deg] of Object.entries(panel.rudderAngles)) { + socket.send({ type: 'SetActuator', simId, vesselId, deviceType: 'rudder', deviceId: Number(id), value: deg }) + } + } - play(dt = 0.05) { - let { worker } = get() - - if (!worker) { - set({ status: 'loading', error: null }) - worker = new Worker( - new URL('../workers/simulation.worker.ts', import.meta.url), - { type: 'module' }, - ) - - worker.onmessage = (e: MessageEvent) => { - const msg = e.data as { type: string; payload?: SimulationStateDTO; message?: string; engine?: SimulationEngine } - switch (msg.type) { - case 'ready': { - // Worker booted; engine known. We go straight to running below. - set({ engine: msg.engine ?? null }) - const { scenarioVessels } = get() - if (scenarioVessels.length > 0) { - get().worker!.postMessage({ type: 'loadScenario', vessels: scenarioVessels }) - } - // Re-sync any actuator state that was set before the worker was created. - const panel = useVesselPanelStore.getState() - if (panel.selectedVesselId !== null) { - const vesselId = panel.selectedVesselId - const w = get().worker! - Object.entries(panel.thrusterPowers).forEach(([id, pct]) => { - const thrusterId = Number(id) - w.postMessage({ - type: 'setActuator', vesselId, deviceType: 'thruster', - deviceId: thrusterId, value: pct, - value2: panel.thrusterAzimuths[thrusterId] ?? 0, - }) - }) - Object.entries(panel.rudderAngles).forEach(([id, deg]) => { - w.postMessage({ - type: 'setActuator', vesselId, deviceType: 'rudder', - deviceId: Number(id), value: deg, - }) - }) - } - const envStore = useEnvironmentStore.getState() - if (envStore.hasConditions()) { - get().worker!.postMessage({ type: 'loadEnvironment', json: envStore.toJson() }) - } - get().worker!.postMessage({ type: 'start', dt }) - set({ status: 'running' }) - break - } - case 'state': - set({ state: msg.payload ?? null }) - break - case 'error': - set({ status: 'error', error: msg.message ?? 'Unknown error' }) - break + function handleServer(msg: ServerMessage): void { + const { socket } = get() + switch (msg.type) { + case 'SimulationCreated': { + set({ simId: msg.simId }) + if (socket && pendingPlayDt !== null) { + socket.send({ type: 'Play', simId: msg.simId, dt: pendingPlayDt }) + pendingPlayDt = null + set({ status: 'running' }) } + resyncActuators(msg.simId) + break } + case 'State': + set({ state: msg.payload }) + break + case 'Status': + set({ status: msg.status === 'ended' ? 'idle' : msg.status }) + break + case 'Error': + set({ status: 'error', error: msg.message }) + break + case 'VesselConfig': + break + } + } - worker.onerror = (e) => { - set({ status: 'error', error: e.message }) + return { + status: 'idle', + error: null, + state: null, + connection: 'idle', + socket: null, + simId: null, + scenarioVessels: [], + + hasSession: () => get().socket !== null, + + play(dt = 0.05) { + let { socket } = get() + if (!socket) { + socket = socketFactory() + socket.onMessage(handleServer) + socket.onConnectionChange((c) => set({ connection: c })) + set({ socket, status: 'loading', error: null, simId: socket.simId }) + socket.connect() } + const { simId, scenarioVessels } = get() + if (simId) { + socket.send({ type: 'Play', simId, dt }) + set({ status: 'running' }) + } else { + pendingPlayDt = dt + const env = useEnvironmentStore.getState() + socket.createSimulation({ + vessels: scenarioVessels, + environmentJson: env.hasConditions() ? env.toJson() : undefined, + }) + } + }, - set({ worker }) - } else { - // Resume from the frozen state — the worker keeps the simulation object, - // so position and elapsed time carry over. - worker.postMessage({ type: 'start', dt }) - set({ status: 'running' }) - } - }, + pause() { + const { socket, simId } = get() + if (socket && simId) socket.send({ type: 'Pause', simId }) + set({ status: 'paused' }) + }, - pause() { - const { worker } = get() - worker?.postMessage({ type: 'stop' }) - set({ status: 'paused' }) - }, + applyEnvironment() { + const { socket, simId } = get() + const env = useEnvironmentStore.getState() + if (socket && simId && env.hasConditions()) { + socket.send({ type: 'LoadEnvironment', simId, json: env.toJson() }) + } + }, - applyEnvironment() { - const { worker } = get() - const envStore = useEnvironmentStore.getState() - if (worker && envStore.hasConditions()) { - worker.postMessage({ type: 'loadEnvironment', json: envStore.toJson() }) - } - }, + reset() { + const { socket, simId } = get() + if (socket && simId) socket.send({ type: 'Reset', simId }) + socket?.close() + pendingPlayDt = null + set({ status: 'idle', error: null, state: null, connection: 'idle', socket: null, simId: null, scenarioVessels: [] }) + }, - reset() { - const { worker } = get() - if (worker) { - worker.terminate() - } - set({ status: 'idle', error: null, state: null, engine: null, worker: null, scenarioVessels: [] }) - }, + loadScenario(vessels) { + set({ scenarioVessels: vessels }) + const { socket, simId } = get() + if (socket && simId) socket.send({ type: 'LoadScenario', simId, vessels }) + }, - loadScenario(vessels: ScenarioDraftVessel[]) { - set({ scenarioVessels: vessels }) - const { worker } = get() - if (worker) { - worker.postMessage({ type: 'loadScenario', vessels }) - } - }, -})) + sendActuator(vesselId, deviceType, deviceId, value, value2) { + const { socket, simId } = get() + if (socket && simId) { + socket.send({ type: 'SetActuator', simId, vesselId, deviceType, deviceId, value, value2 }) + } + }, + } +}) diff --git a/apps/web/src/test/setup.ts b/apps/web/src/test/setup.ts index c44951a..88bb40e 100644 --- a/apps/web/src/test/setup.ts +++ b/apps/web/src/test/setup.ts @@ -1 +1,23 @@ import '@testing-library/jest-dom' +import { vi } from 'vitest' + +// jsdom has no usable WebSocket for our client. Stub a no-op implementation so +// components that open a SimulationSocket in tests don't hit the network. +// Tests that need to drive frames inject their own WebSocketImpl into +// SimulationSocket instead of relying on this global. +class StubWebSocket { + static CONNECTING = 0 + static OPEN = 1 + static CLOSING = 2 + static CLOSED = 3 + readyState = StubWebSocket.CONNECTING + onopen: (() => void) | null = null + onmessage: ((e: { data: string }) => void) | null = null + onclose: (() => void) | null = null + onerror: (() => void) | null = null + constructor(public url: string) {} + send(): void {} + close(): void {} +} + +vi.stubGlobal('WebSocket', StubWebSocket)