diff --git a/.factory/library/architecture.md b/.factory/library/architecture.md index 732c69e..b1c7691 100644 --- a/.factory/library/architecture.md +++ b/.factory/library/architecture.md @@ -53,6 +53,12 @@ Unified event system replacing EventBus + CustomEvents. Topics with `equals: fal - Mode switching via `setOutputMode()` triggers MLP recreation with warm-start weight transfer - Output count per mode: visual=20, synth=126, midi-cc=8 (configurable), audio-canvas=36 - All ML operations exposed as methods: setInputs, train, trainAsync, randomise, thumbsUp, thumbsDown, etc. +- `noiseLevel` signal — reactive RL exploration noise level (default 0.05) +- `exampleCountSignal` — reactive example count (updates on add/clear) +- `lastLossSignal` — reactive loss value (updates after training) +- `addExample()` — adds current I/O as training example, updates reactive count +- `clearAll()` — clears examples, loss history, resets noise to default +- `getLossHistory()` — returns copy of loss history array - `dispose()` destroys both IML instances (called in App.tsx onCleanup) - Bus topics created: `ml.outputs`, `ml.outputCount`, `mode.output` - Debug probe (`probe/debug-probe.ts`) now wraps MLStore instead of raw WasmIML @@ -91,6 +97,26 @@ Unified event system replacing EventBus + CustomEvents. Topics with `equals: fal - Per-mode overrides arrays - Output pipeline config (globalCurve, smoothing, slewRate, freezeGate) +### Dock Component (`components/layout/Dock.tsx`) — IMPLEMENTED +- Right-side vertical dock with 6 icon buttons: Train, Mode, Synth, NISPS, FX, Help +- macOS-style dock with glass morphism background +- `openDrawers` signal (Set) tracks which drawers are open +- Clicking icon toggles corresponding drawer +- Active state (accent color) shown when drawer is open +- SVG icons matching old playground design + +### TrainingDrawer Component (`components/layout/TrainingDrawer.tsx`) — IMPLEMENTED +- Drawer panel with training controls, visible when drawer 'training' is open +- Action buttons: Add Example, Train (async), Clear Ex, Clear All, Randomize +- Loss plot canvas (280×80) drawn with orange line on last 200 loss history entries +- Button flash animation on click +- Uses ML store methods: addExample(), trainAsync(), clearExamples(), clearAll(), randomise() + +### StatusLine Component (`components/layout/StatusLine.tsx`) — IMPLEMENTED +- Floating pill at bottom center showing example count, loss/noise state +- Format: "N examples · loss X.XXXXX · noise X.XXX" or "N examples · untrained · noise X.XXX" +- Reactively watches exampleCountSignal, lastLossSignal, noiseLevel signals + ### Dual IML System - `imlJoy`: 2 inputs (joystick), dynamic outputs — warm-started on resize - `imlHand`: 14 inputs (hand tracking), dynamic outputs — fresh on resize diff --git a/src/App.tsx b/src/App.tsx index 12c8e36..ad26cd8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -5,6 +5,9 @@ import { exposeDebugProbe } from './probe/debug-probe'; import bus from './bus'; import Joystick from './components/input/Joystick'; import FlowField from './components/visual/FlowField'; +import Dock from './components/layout/Dock'; +import TrainingDrawer from './components/layout/TrainingDrawer'; +import StatusLine from './components/layout/StatusLine'; /** * Root application component for the NISPS immersive app. @@ -18,6 +21,29 @@ export default function App() { let mlStore: MLStore | null = null; const [inputStore, setInputStore] = createSignal(null); + // Drawer state — track which drawers are open + const [openDrawers, setOpenDrawers] = createSignal>(new Set()); + + function toggleDrawer(drawerName: string): void { + setOpenDrawers(prev => { + const next = new Set(prev); + if (next.has(drawerName)) { + next.delete(drawerName); + } else { + next.add(drawerName); + } + return next; + }); + } + + function closeDrawer(drawerName: string): void { + setOpenDrawers(prev => { + const next = new Set(prev); + next.delete(drawerName); + return next; + }); + } + onMount(async () => { try { const store = await createMLStore(bus); @@ -107,6 +133,18 @@ export default function App() { {(store) => } + {/* Dock + Drawers + Status (only when ready and ML store exists) */} + + +
+ closeDrawer('training')} + /> +
+ +
); } diff --git a/src/components/layout/Dock.tsx b/src/components/layout/Dock.tsx new file mode 100644 index 0000000..5a3b6b0 --- /dev/null +++ b/src/components/layout/Dock.tsx @@ -0,0 +1,97 @@ +/** + * Dock Component — Right-side vertical dock with icon buttons. + * + * macOS-style dock with 6 icons: Train, Mode, Synth, NISPS, FX, Help. + * Each icon toggles its corresponding drawer. + * Active state (accent color) shown when drawer is open. + */ + +import { createSignal, For } from 'solid-js'; +import './dock.css'; + +export interface DockIcon { + /** Unique identifier matching drawer name */ + drawer: string; + /** Tooltip text */ + title: string; + /** Label below icon */ + label: string; + /** SVG content */ + svg: string; +} + +export const DOCK_ICONS: DockIcon[] = [ + { + drawer: 'training', + title: 'Training', + label: 'Train', + svg: '', + }, + { + drawer: 'mode', + title: 'Input / Output mode', + label: 'Mode', + svg: '', + }, + { + drawer: 'synth', + title: 'Synth controls', + label: 'Synth', + svg: '', + }, + { + drawer: 'params', + title: 'NISPS ML parameters', + label: 'NISPS', + svg: '', + }, + { + drawer: 'eoc', + title: 'Effects Chain', + label: 'FX', + svg: '', + }, + { + drawer: 'help', + title: 'Help', + label: 'Help', + svg: '', + }, +]; + +export interface DockProps { + /** Callback when a dock icon is clicked */ + onToggleDrawer: (drawerName: string) => void; + /** Set of currently open drawer names */ + openDrawers: () => Set; +} + +export default function Dock(props: DockProps) { + return ( +
+ + {(icon) => ( + + )} + +
+ ); +} diff --git a/src/components/layout/StatusLine.tsx b/src/components/layout/StatusLine.tsx new file mode 100644 index 0000000..0c314a0 --- /dev/null +++ b/src/components/layout/StatusLine.tsx @@ -0,0 +1,42 @@ +/** + * StatusLine — Floating status bar showing example count, loss state, and noise level. + * + * Text format: "N examples · loss X.XXXXX · noise X.XXX" + * Or "N examples · untrained" when no training has occurred. + * + * Reactively watches exampleCountSignal, lastLossSignal, and noiseLevel. + */ + +import { createEffect } from 'solid-js'; +import type { MLStore } from '../../stores/ml-store'; + +export interface StatusLineProps { + mlStore: MLStore; +} + +export default function StatusLine(props: StatusLineProps) { + // Reactive status text — watches all relevant signals + const statusText = () => { + const count = props.mlStore.exampleCountSignal(); + const loss = props.mlStore.lastLossSignal(); + const noise = props.mlStore.noiseLevel(); + + let text = `${count} example${count !== 1 ? 's' : ''}`; + + if (loss !== null) { + text += ` \u00b7 loss ${loss.toFixed(5)}`; + } else { + text += ' \u00b7 untrained'; + } + + text += ` \u00b7 noise ${noise.toFixed(3)}`; + + return text; + }; + + return ( +
+ {statusText()} +
+ ); +} diff --git a/src/components/layout/TrainingDrawer.tsx b/src/components/layout/TrainingDrawer.tsx new file mode 100644 index 0000000..961467a --- /dev/null +++ b/src/components/layout/TrainingDrawer.tsx @@ -0,0 +1,146 @@ +/** + * TrainingDrawer — Drawer panel with training controls. + * + * Contains: + * - Add Example button (captures current input/output as training example) + * - Train button (triggers async training) + * - Clear Ex button (clears examples only) + * - Clear All button (clears everything including loss history) + * - Randomize button (randomizes weights) + * - Loss plot canvas (shows loss history) + * + * Status line is rendered separately at the bottom of the screen. + */ + +import { + createSignal, + onCleanup, +} from 'solid-js'; +import type { MLStore } from '../../stores/ml-store'; +import './drawer.css'; + +export interface TrainingDrawerProps { + mlStore: MLStore; + visible: boolean; + onClose: () => void; +} + +export default function TrainingDrawer(props: TrainingDrawerProps) { + let lossCanvasRef: HTMLCanvasElement | undefined; + + // ─── Button handlers ─── + + function onAddExample(): void { + props.mlStore.addExample(); + flashButton('btn-add-example'); + } + + function onTrain(): void { + const iml = props.mlStore.getActiveIml(); + if (!iml || (iml as any).isTraining) return; + flashButton('btn-train'); + props.mlStore.trainAsync().then(() => { + drawLossPlot(); + }); + } + + function onClearExamples(): void { + props.mlStore.clearExamples(); + drawLossPlot(); + } + + function onClearAll(): void { + props.mlStore.clearAll(); + drawLossPlot(); + } + + function onRandomize(): void { + props.mlStore.randomise(); + } + + // ─── Button flash effect ─── + + function flashButton(id: string): void { + const btn = document.getElementById(id); + if (btn) { + btn.classList.add('flash'); + setTimeout(() => btn.classList.remove('flash'), 300); + } + } + + // ─── Loss plot drawing ─── + + function drawLossPlot(): void { + const canvas = lossCanvasRef; + if (!canvas) return; + const ctx = canvas.getContext('2d'); + if (!ctx) return; + + const w = canvas.width; + const h = canvas.height; + const history = props.mlStore.getLossHistory(); + + ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'; + ctx.fillRect(0, 0, w, h); + + if (history.length < 2) return; + + const maxLoss = Math.max(...history.slice(-200)) || 1; + const points = history.slice(-200); + + ctx.strokeStyle = 'rgba(255, 106, 0, 0.6)'; + ctx.lineWidth = 1.5; + ctx.beginPath(); + + for (let i = 0; i < points.length; i++) { + const x = (i / (points.length - 1)) * w; + const y = h - (points[i] / maxLoss) * h * 0.9; + if (i === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + } + ctx.stroke(); + } + + return ( +
+
+ Training + +
+
+
+ + + + + +
+
+ + +
+
+
+ ); +} diff --git a/src/components/layout/dock.css b/src/components/layout/dock.css new file mode 100644 index 0000000..fabcd3a --- /dev/null +++ b/src/components/layout/dock.css @@ -0,0 +1,54 @@ +/* Dock — right-side vertical icon bar */ + +.dock { + position: fixed; + right: 0; + top: 50%; + transform: translateY(-50%); + z-index: 200; + display: flex; + flex-direction: column; + gap: 2px; + padding: 6px 4px; + background: var(--glass-bg, rgba(10, 10, 20, 0.65)); + backdrop-filter: blur(var(--glass-blur, 12px)); + border-left: 1px solid var(--glass-border, rgba(255, 255, 255, 0.12)); + border-radius: 8px 0 0 8px; +} + +.dock-icon { + display: flex; + flex-direction: column; + align-items: center; + gap: 2px; + padding: 6px 8px; + border: none; + background: transparent; + color: #888; + cursor: pointer; + border-radius: 6px; + transition: color 0.2s, background 0.2s; + font-family: var(--font-mono, monospace); + font-size: 8px; +} + +.dock-icon:hover { + color: #ccc; + background: rgba(255, 255, 255, 0.06); +} + +.dock-icon.active { + color: var(--accent, #00d4ff); + background: rgba(0, 212, 255, 0.1); +} + +.dock-icon svg { + width: 18px; + height: 18px; +} + +.dock-label { + font-size: 8px; + letter-spacing: 0.02em; + white-space: nowrap; +} diff --git a/src/components/layout/drawer.css b/src/components/layout/drawer.css new file mode 100644 index 0000000..3b7cdd7 --- /dev/null +++ b/src/components/layout/drawer.css @@ -0,0 +1,175 @@ +/* Drawer panels — slide in from the right */ + +.drawer-stack { + position: fixed; + right: 56px; /* dock width */ + top: 50%; + transform: translateY(-50%); + z-index: 190; + display: flex; + flex-direction: column; + gap: 8px; + max-height: 90vh; + pointer-events: none; +} + +.drawer-stack > * { + pointer-events: auto; +} + +.drawer { + width: 300px; + max-height: 80vh; + background: var(--glass-bg, rgba(10, 10, 20, 0.65)); + backdrop-filter: blur(var(--glass-blur, 12px)); + border: 1px solid var(--glass-border, rgba(255, 255, 255, 0.12)); + border-radius: 12px; + overflow: hidden; + animation: drawerSlideIn 0.25s ease-out; +} + +.drawer.hidden { + display: none; +} + +.drawer-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 12px; + border-bottom: 1px solid var(--glass-border, rgba(255, 255, 255, 0.08)); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.05em; + text-transform: uppercase; + color: #aaa; +} + +.drawer-close { + background: none; + border: none; + color: #888; + font-size: 18px; + cursor: pointer; + padding: 0 4px; + line-height: 1; + transition: color 0.2s; +} + +.drawer-close:hover { + color: #fff; +} + +.drawer-body { + padding: 10px 12px; + font-size: 11px; +} + +/* Action buttons row */ +.action-row { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 10px; +} + +.action-btn { + padding: 5px 10px; + border: 1px solid var(--glass-border, rgba(255, 255, 255, 0.15)); + background: rgba(255, 255, 255, 0.05); + color: #ccc; + font-size: 10px; + font-family: var(--font-mono, monospace); + border-radius: 6px; + cursor: pointer; + transition: background 0.2s, color 0.2s, border-color 0.2s; + white-space: nowrap; +} + +.action-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; +} + +.action-btn.accent { + background: rgba(0, 212, 255, 0.15); + border-color: rgba(0, 212, 255, 0.3); + color: var(--accent, #00d4ff); +} + +.action-btn.accent:hover { + background: rgba(0, 212, 255, 0.25); +} + +.action-btn.dim { + color: #777; + border-color: rgba(255, 255, 255, 0.08); +} + +.action-btn.dim:hover { + color: #aaa; + border-color: rgba(255, 255, 255, 0.15); +} + +/* Button flash effect */ +.action-btn.flash { + animation: btn-flash 0.3s ease-out; +} + +@keyframes btn-flash { + 0% { background: rgba(0, 212, 255, 0.3); } + 100% { background: rgba(255, 255, 255, 0.05); } +} + +/* Loss section */ +.loss-section { + margin-top: 8px; +} + +.loss-section label { + display: block; + font-size: 9px; + color: #777; + text-transform: uppercase; + letter-spacing: 0.05em; + margin-bottom: 4px; +} + +.loss-section canvas { + width: 100%; + height: 80px; + border-radius: 6px; + border: 1px solid var(--glass-border, rgba(255, 255, 255, 0.08)); + background: rgba(0, 0, 0, 0.2); +} + +/* Status line */ +.status-line { + position: fixed; + bottom: 20px; + left: 50%; + transform: translateX(-50%); + z-index: 150; + padding: 4px 16px; + background: var(--glass-bg, rgba(10, 10, 20, 0.65)); + backdrop-filter: blur(var(--glass-blur, 12px)); + border: 1px solid var(--glass-border, rgba(255, 255, 255, 0.12)); + border-radius: 20px; + font-size: 10px; + font-family: var(--font-mono, monospace); + color: #888; + white-space: nowrap; + pointer-events: none; +} + +/* Drawer slide-in animation */ +@keyframes drawerSlideIn { + from { + opacity: 0; + transform: translateX(20px); + } + to { + opacity: 1; + transform: translateX(0); + } +} diff --git a/src/probe/debug-probe.ts b/src/probe/debug-probe.ts index 0421462..001baaa 100644 --- a/src/probe/debug-probe.ts +++ b/src/probe/debug-probe.ts @@ -20,6 +20,7 @@ export interface DebugProbe { trainAsync: () => Promise; randomise: () => void; clearExamples: () => void; + clearAll: () => void; saveState: () => void; evalLoss: () => number | null; inferBatch: (points: number[][]) => number[][]; @@ -29,6 +30,7 @@ export interface DebugProbe { deadFrac: number; satFrac: number; }>; + getLossHistory: () => number[]; } /** @@ -68,6 +70,8 @@ export function createDebugProbe(store: MLStore): DebugProbe { clearExamples: () => store.clearExamples(), + clearAll: () => store.clearAll(), + saveState: () => store.saveState(), evalLoss: () => store.evalLoss(), @@ -75,6 +79,8 @@ export function createDebugProbe(store: MLStore): DebugProbe { inferBatch: (points: number[][]) => store.inferBatch(points), getLayerStats: () => store.getLayerStats(), + + getLossHistory: () => store.getLossHistory(), }; } diff --git a/src/stores/ml-store.ts b/src/stores/ml-store.ts index ff0df5a..69b6f45 100644 --- a/src/stores/ml-store.ts +++ b/src/stores/ml-store.ts @@ -57,6 +57,12 @@ export interface MLStore { readonly state: MLState; readonly outputs: () => Float32Array; readonly outputCount: () => number; + /** Current noise level for RL exploration */ + readonly noiseLevel: () => number; + /** Reactive example count — updates when examples are added/cleared */ + readonly exampleCountSignal: () => number; + /** Reactive last loss — updates after training */ + readonly lastLossSignal: () => number | null; // IML access (opaque handles, NOT reactive) getActiveIml(): WasmIML | null; @@ -72,6 +78,10 @@ export interface MLStore { setInputs(x: number, y: number): void; randomise(): void; clearExamples(): void; + /** Clear examples, loss history, and reset noise to default */ + clearAll(): void; + /** Add current input/output as a training example (updates reactive count) */ + addExample(): void; train(): number | null; trainAsync(): Promise; thumbsUp(): Promise; @@ -82,6 +92,7 @@ export interface MLStore { getWeights(): number[]; getExampleCount(): number; getLoss(): number | null; + getLossHistory(): number[]; saveState(): void; // Lifecycle @@ -103,6 +114,13 @@ export async function createMLStore(bus: SignalBus): Promise { const [outputs, setOutputs] = createSignal(new Float32Array(initialCount)); const [outputCount, setOutputCount] = createSignal(initialCount); + // Noise level signal for RL exploration (reactive for status line + noise ring) + const [noiseLevel, setNoiseLevel] = createSignal(0.05); + + // Reactive example count and last loss (for status line to watch) + const [exampleCountSignal, setExampleCountSignal] = createSignal(0); + const [lastLossSignal, setLastLossSignal] = createSignal(null); + // IML instances — module-scope opaque handles (not reactive) let imlJoy: WasmIML | null = null; let imlHand: WasmIML | null = null; @@ -144,6 +162,9 @@ export async function createMLStore(bus: SignalBus): Promise { const newOutputs = new Float32Array(activeIml.getOutputs()); setOutputs(newOutputs); outputsTopic.emit(newOutputs); + // Update reactive state signals + setExampleCountSignal(activeIml.exampleCount); + setLastLossSignal(activeIml.lastLoss); } // ─── Helper: resize MLP (mode switch) ─── @@ -196,6 +217,9 @@ export async function createMLStore(bus: SignalBus): Promise { get state() { return state; }, outputs, outputCount, + noiseLevel, + exampleCountSignal, + lastLossSignal, getActiveIml: () => activeIml, getImlJoy: () => imlJoy, @@ -235,11 +259,35 @@ export async function createMLStore(bus: SignalBus): Promise { randomise: () => { if (!activeIml) return; activeIml.randomiseWeights(state.spreadLevel); + setNoiseLevel(0.05); runInference(); }, clearExamples: () => { activeIml?.clearDataset(); + setExampleCountSignal(0); + }, + + clearAll: () => { + activeIml?.clearDataset(); + if (activeIml) { + activeIml.lossHistory.length = 0; + activeIml.lastLoss = null; + activeIml.bestLoss = null; + activeIml.totalTrainingIterations = 0; + } + setNoiseLevel(0.05); + setExampleCountSignal(0); + setLastLossSignal(null); + }, + + addExample: () => { + if (!activeIml) return; + activeIml.addExample( + activeIml.inputState.slice(), + activeIml.outputState.slice() + ); + setExampleCountSignal(activeIml.exampleCount); }, train: () => { @@ -251,7 +299,9 @@ export async function createMLStore(bus: SignalBus): Promise { trainAsync: () => { if (!activeIml) return Promise.resolve(null); - return activeIml.trainAsync(() => runInference()); + return activeIml.trainAsync(() => { + runInference(); + }); }, thumbsUp: () => { @@ -260,13 +310,21 @@ export async function createMLStore(bus: SignalBus): Promise { activeIml.inputState.slice(), activeIml.outputState.slice() ); + // Update reactive signals immediately + setExampleCountSignal(activeIml.exampleCount); + // Decay noise on positive feedback + const decayed = Math.max(noiseLevel() * 0.7, 0.005); + setNoiseLevel(decayed); return activeIml.trainAsync(() => runInference()); }, thumbsDown: (speed?: number) => { if (!activeIml) return; const spread = state.spreadLevel; - const s = speed ?? (0.15 * (1 - spread) + 0.05 * spread); + const noiseCap = 0.3 * (1 - spread) + 0.05 * spread; + const newNoise = Math.min(noiseLevel() * 1.5, noiseCap); + setNoiseLevel(newNoise); + const s = speed ?? newNoise; activeIml.moveWeights(s, spread); runInference(); }, @@ -286,6 +344,8 @@ export async function createMLStore(bus: SignalBus): Promise { getLoss: () => activeIml?.lastLoss ?? null, + getLossHistory: () => activeIml?.lossHistory.slice() ?? [], + saveState: () => { if (!activeIml) return; const data = { diff --git a/tests/solidjs/debug-probe.spec.ts b/tests/solidjs/debug-probe.spec.ts index 7801ab0..da8e065 100644 --- a/tests/solidjs/debug-probe.spec.ts +++ b/tests/solidjs/debug-probe.spec.ts @@ -19,10 +19,12 @@ const EXPECTED_METHODS = [ 'trainAsync', 'randomise', 'clearExamples', + 'clearAll', 'saveState', 'evalLoss', 'inferBatch', 'getLayerStats', + 'getLossHistory', ] as const; test.describe('Debug Probe (f03)', () => { @@ -61,8 +63,8 @@ test.describe('Debug Probe (f03)', () => { const expectedMethods = [ 'getOutputs', 'getLoss', 'getWeights', 'getExampleCount', 'setInputs', 'thumbsUp', 'thumbsDown', 'train', 'trainAsync', - 'randomise', 'clearExamples', 'saveState', 'evalLoss', - 'inferBatch', 'getLayerStats', + 'randomise', 'clearExamples', 'clearAll', 'saveState', 'evalLoss', + 'inferBatch', 'getLayerStats', 'getLossHistory', ]; for (const name of expectedMethods) { checks[name] = typeof probe[name] === 'function'; diff --git a/tests/solidjs/training-drawer.spec.ts b/tests/solidjs/training-drawer.spec.ts new file mode 100644 index 0000000..d045dc7 --- /dev/null +++ b/tests/solidjs/training-drawer.spec.ts @@ -0,0 +1,296 @@ +/** + * Training Drawer tests — VAL-TRAIN-* assertions. + * + * Covers feature f08-training-drawer-controls: + * - Training drawer opens/closes via dock icon + * - Add Example button increments count and updates status + * - Train triggers async training, shows loss + * - Clear Ex resets examples + * - Clear All clears examples, loss history, resets noise + * - Randomize changes outputs + * - Loss plot shows training history + * - Status line shows proper text + */ + +import { test, expect } from '@playwright/test'; +import { loadSolidApp } from './helpers'; + +test.describe('Training Drawer (f08)', () => { + test.beforeEach(async ({ page }) => { + await loadSolidApp(page); + }); + + // ─── VAL-TRAIN-001: Training drawer opens/closes ─── + + test('VAL-TRAIN-001a: training drawer is not visible on load', async ({ page }) => { + const drawer = page.locator('#drawer-training'); + await expect(drawer).toBeHidden(); + }); + + test('VAL-TRAIN-001b: clicking Train dock icon opens the training drawer', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + const drawer = page.locator('#drawer-training'); + await expect(drawer).toBeVisible(); + }); + + test('VAL-TRAIN-001c: clicking Train dock icon again closes the drawer', async ({ page }) => { + const dockBtn = page.locator('.dock-icon[data-drawer="training"]'); + await dockBtn.click(); + await expect(page.locator('#drawer-training')).toBeVisible(); + + await dockBtn.click(); + await expect(page.locator('#drawer-training')).toBeHidden(); + }); + + test('VAL-TRAIN-001d: dock icon shows active state when drawer is open', async ({ page }) => { + const dockBtn = page.locator('.dock-icon[data-drawer="training"]'); + await dockBtn.click(); + await expect(dockBtn).toHaveClass(/active/); + }); + + // ─── VAL-TRAIN-002: Add Example button ─── + + test('VAL-TRAIN-002a: Add Example button exists in training drawer', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await expect(page.locator('#btn-add-example')).toBeVisible(); + }); + + test('VAL-TRAIN-002b: Add Example increments example count', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + const countBefore = await page.evaluate(() => (window as any).__nisps.getExampleCount()); + expect(countBefore).toBe(0); + + await page.locator('#btn-add-example').click(); + + const countAfter = await page.evaluate(() => (window as any).__nisps.getExampleCount()); + expect(countAfter).toBe(1); + }); + + test('VAL-TRAIN-002c: Add Example updates status line', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await page.locator('#btn-add-example').click(); + + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('1 example'); + }); + + test('VAL-TRAIN-002d: multiple Add Example clicks increment count', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + await page.locator('#btn-add-example').click(); + await page.locator('#btn-add-example').click(); + await page.locator('#btn-add-example').click(); + + const count = await page.evaluate(() => (window as any).__nisps.getExampleCount()); + expect(count).toBe(3); + + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('3 examples'); + }); + + // ─── VAL-TRAIN-003: Train button ─── + + test('VAL-TRAIN-003a: Train button exists in training drawer', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await expect(page.locator('#btn-train')).toBeVisible(); + }); + + test('VAL-TRAIN-003b: Train triggers async training and shows loss', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + // Add an example first + await page.locator('#btn-add-example').click(); + + // Click train + await page.locator('#btn-train').click(); + + // Wait for training to complete + await page.waitForFunction( + () => (window as any).__nisps.getLoss() !== null, + { timeout: 10_000 } + ); + + const loss = await page.evaluate(() => (window as any).__nisps.getLoss()); + expect(loss).not.toBeNull(); + expect(typeof loss).toBe('number'); + expect(isFinite(loss as number)).toBe(true); + + // Status should show loss + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('loss'); + expect(statusText).not.toContain('untrained'); + }); + + // ─── VAL-TRAIN-004: Clear Ex button ─── + + test('VAL-TRAIN-004a: Clear Ex button exists in training drawer', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await expect(page.locator('#btn-clear-examples')).toBeVisible(); + }); + + test('VAL-TRAIN-004b: Clear Ex resets example count to 0', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + // Add examples + await page.locator('#btn-add-example').click(); + await page.locator('#btn-add-example').click(); + let count = await page.evaluate(() => (window as any).__nisps.getExampleCount()); + expect(count).toBe(2); + + // Clear examples + await page.locator('#btn-clear-examples').click(); + + count = await page.evaluate(() => (window as any).__nisps.getExampleCount()); + expect(count).toBe(0); + + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('0 examples'); + }); + + // ─── VAL-TRAIN-005: Clear All button ─── + + test('VAL-TRAIN-005a: Clear All button exists in training drawer', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await expect(page.locator('#btn-clear-all')).toBeVisible(); + }); + + test('VAL-TRAIN-005b: Clear All resets examples, loss history, and noise', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + // Add example and train + await page.locator('#btn-add-example').click(); + await page.locator('#btn-train').click(); + await page.waitForFunction( + () => (window as any).__nisps.getLoss() !== null, + { timeout: 10_000 } + ); + + // Verify state before clear + let count = await page.evaluate(() => (window as any).__nisps.getExampleCount()); + expect(count).toBe(1); + let loss = await page.evaluate(() => (window as any).__nisps.getLoss()); + expect(loss).not.toBeNull(); + + // Clear all + await page.locator('#btn-clear-all').click(); + + // Verify state after clear + count = await page.evaluate(() => (window as any).__nisps.getExampleCount()); + expect(count).toBe(0); + + loss = await page.evaluate(() => (window as any).__nisps.getLoss()); + expect(loss).toBeNull(); + }); + + // ─── VAL-TRAIN-006: Randomize button ─── + + test('VAL-TRAIN-006a: Randomize button exists in training drawer', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await expect(page.locator('#btn-randomize')).toBeVisible(); + }); + + test('VAL-TRAIN-006b: Randomize changes outputs', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + const outputsBefore = await page.evaluate(() => (window as any).__nisps.getOutputs()); + + await page.locator('#btn-randomize').click(); + + const outputsAfter = await page.evaluate(() => (window as any).__nisps.getOutputs()); + + // At least one output should differ + let changed = false; + for (let i = 0; i < outputsBefore.length; i++) { + if (Math.abs(outputsBefore[i] - outputsAfter[i]) > 0.001) { + changed = true; + break; + } + } + expect(changed).toBe(true); + }); + + // ─── VAL-TRAIN-008: Loss plot ─── + + test('VAL-TRAIN-008a: loss canvas exists in training drawer', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await expect(page.locator('#loss-canvas')).toBeVisible(); + }); + + test('VAL-TRAIN-008b: loss plot draws something after training', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + // Add example and train to generate loss history + await page.locator('#btn-add-example').click(); + await page.locator('#btn-train').click(); + await page.waitForFunction( + () => (window as any).__nisps.getLoss() !== null, + { timeout: 10_000 } + ); + + // Check that the canvas has been drawn on (has non-transparent pixels) + const hasContent = await page.evaluate(() => { + const canvas = document.getElementById('loss-canvas') as HTMLCanvasElement; + if (!canvas) return false; + const ctx = canvas.getContext('2d'); + if (!ctx) return false; + const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data; + // Check for non-transparent pixels (loss line is drawn) + for (let i = 3; i < data.length; i += 4) { + if (data[i] > 0) return true; + } + return false; + }); + expect(hasContent).toBe(true); + }); + + // ─── VAL-TRAIN-009: Status line display ─── + + test('VAL-TRAIN-009a: status line shows "0 examples · untrained" on fresh load', async ({ page }) => { + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('0 examples'); + expect(statusText).toContain('untrained'); + }); + + test('VAL-TRAIN-009b: status line shows "N examples · untrained" after adding examples', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await page.locator('#btn-add-example').click(); + + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('1 example'); + expect(statusText).toContain('untrained'); + }); + + test('VAL-TRAIN-009c: status line shows "N examples · loss X.XXXXX" after training', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + await page.locator('#btn-add-example').click(); + await page.locator('#btn-train').click(); + await page.waitForFunction( + () => (window as any).__nisps.getLoss() !== null, + { timeout: 10_000 } + ); + + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('1 example'); + expect(statusText).toMatch(/loss \d/); + expect(statusText).not.toContain('untrained'); + }); + + test('VAL-TRAIN-009d: status line resets to untrained after clear examples', async ({ page }) => { + await page.locator('.dock-icon[data-drawer="training"]').click(); + + // Add and train + await page.locator('#btn-add-example').click(); + await page.locator('#btn-train').click(); + await page.waitForFunction( + () => (window as any).__nisps.getLoss() !== null, + { timeout: 10_000 } + ); + + // Clear examples + await page.locator('#btn-clear-examples').click(); + + const statusText = await page.locator('#status-text').textContent(); + expect(statusText).toContain('0 examples'); + }); +});