feat: add training drawer with dock, buttons, status line, and loss plot (f08)

Build training drawer UI for milestone training-rl:
- Dock component with 6 icons (Train, Mode, Synth, NISPS, FX, Help)
- TrainingDrawer with Add Example, Train, Clear Ex, Clear All, Randomize
- StatusLine showing 'N examples · loss/noise' reactively
- Loss plot canvas with training history visualization
- ML store: add noiseLevel, exampleCountSignal, lastLossSignal, clearAll, addExample
- Debug probe: add clearAll() and getLossHistory() methods
- 22 Playwright e2e tests covering VAL-TRAIN-001 through VAL-TRAIN-009

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
monkey-w1n5t0n 2026-04-07 19:37:27 +02:00
parent f42732fa16
commit 68bd756311
11 changed files with 946 additions and 4 deletions

View file

@ -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 - 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 - 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. - 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) - `dispose()` destroys both IML instances (called in App.tsx onCleanup)
- Bus topics created: `ml.outputs`, `ml.outputCount`, `mode.output` - Bus topics created: `ml.outputs`, `ml.outputCount`, `mode.output`
- Debug probe (`probe/debug-probe.ts`) now wraps MLStore instead of raw WasmIML - 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 - Per-mode overrides arrays
- Output pipeline config (globalCurve, smoothing, slewRate, freezeGate) - 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<string>) 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 ### Dual IML System
- `imlJoy`: 2 inputs (joystick), dynamic outputs — warm-started on resize - `imlJoy`: 2 inputs (joystick), dynamic outputs — warm-started on resize
- `imlHand`: 14 inputs (hand tracking), dynamic outputs — fresh on resize - `imlHand`: 14 inputs (hand tracking), dynamic outputs — fresh on resize

View file

@ -5,6 +5,9 @@ import { exposeDebugProbe } from './probe/debug-probe';
import bus from './bus'; import bus from './bus';
import Joystick from './components/input/Joystick'; import Joystick from './components/input/Joystick';
import FlowField from './components/visual/FlowField'; 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. * Root application component for the NISPS immersive app.
@ -18,6 +21,29 @@ export default function App() {
let mlStore: MLStore | null = null; let mlStore: MLStore | null = null;
const [inputStore, setInputStore] = createSignal<InputStore | null>(null); const [inputStore, setInputStore] = createSignal<InputStore | null>(null);
// Drawer state — track which drawers are open
const [openDrawers, setOpenDrawers] = createSignal<Set<string>>(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 () => { onMount(async () => {
try { try {
const store = await createMLStore(bus); const store = await createMLStore(bus);
@ -107,6 +133,18 @@ export default function App() {
<Show when={ready() && inputStore()}> <Show when={ready() && inputStore()}>
{(store) => <Joystick inputStore={store()} />} {(store) => <Joystick inputStore={store()} />}
</Show> </Show>
{/* Dock + Drawers + Status (only when ready and ML store exists) */}
<Show when={ready() && mlStore !== null}>
<Dock onToggleDrawer={toggleDrawer} openDrawers={openDrawers} />
<div class="drawer-stack">
<TrainingDrawer
mlStore={mlStore!}
visible={openDrawers().has('training')}
onClose={() => closeDrawer('training')}
/>
</div>
<StatusLine mlStore={mlStore!} />
</Show>
</div> </div>
); );
} }

View file

@ -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: '<path d="M3 8h10"/><rect x="1" y="5" width="3" height="6" rx="0.5"/><rect x="12" y="5" width="3" height="6" rx="0.5"/><rect x="3" y="6.5" width="2" height="3" rx="0.3"/><rect x="11" y="6.5" width="2" height="3" rx="0.3"/>',
},
{
drawer: 'mode',
title: 'Input / Output mode',
label: 'Mode',
svg: '<circle cx="5" cy="5" r="2"/><circle cx="11" cy="11" r="2"/><path d="M3 13L13 3"/>',
},
{
drawer: 'synth',
title: 'Synth controls',
label: 'Synth',
svg: '<path d="M2 10c2-4 4-4 6 0s4-4 6 0"/>',
},
{
drawer: 'params',
title: 'NISPS ML parameters',
label: 'NISPS',
svg: '<circle cx="8" cy="8" r="3"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41"/>',
},
{
drawer: 'eoc',
title: 'Effects Chain',
label: 'FX',
svg: '<path d="M4 8a4 4 0 0 1 4-4h1a1 1 0 0 0 0-2H8a6 6 0 0 0 0 12h1a1 1 0 0 0 0-2H8a4 4 0 0 1-4-4zm8 0a4 4 0 0 1-4 4H7a1 1 0 0 0 0 2h1a6 6 0 0 0 0-12H7a1 1 0 0 0 0 2h1a4 4 0 0 1 4 4z"/>',
},
{
drawer: 'help',
title: 'Help',
label: 'Help',
svg: '<circle cx="8" cy="8" r="6"/><path d="M6 6a2 2 0 0 1 4 0c0 1.5-2 1.5-2 3"/><circle cx="8" cy="12" r="0.5" fill="currentColor"/>',
},
];
export interface DockProps {
/** Callback when a dock icon is clicked */
onToggleDrawer: (drawerName: string) => void;
/** Set of currently open drawer names */
openDrawers: () => Set<string>;
}
export default function Dock(props: DockProps) {
return (
<div class="dock" id="dock">
<For each={DOCK_ICONS}>
{(icon) => (
<button
class={`dock-icon${props.openDrawers().has(icon.drawer) ? ' active' : ''}`}
data-drawer={icon.drawer}
title={icon.title}
onClick={() => props.onToggleDrawer(icon.drawer)}
>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
innerHTML={icon.svg}
/>
<span class="dock-label">{icon.label}</span>
</button>
)}
</For>
</div>
);
}

View file

@ -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 (
<div class="status-line" id="status-line">
<span id="status-text">{statusText()}</span>
</div>
);
}

View file

@ -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 (
<div
class={`drawer${props.visible ? '' : ' hidden'}`}
id="drawer-training"
data-drawer="training"
>
<div class="drawer-header">
<span>Training</span>
<button class="drawer-close" data-drawer="training" onClick={props.onClose}>
×
</button>
</div>
<div class="drawer-body">
<div class="action-row" id="examples-actions">
<button class="action-btn" id="btn-add-example" onClick={onAddExample}>
Add Example
</button>
<button class="action-btn accent" id="btn-train" onClick={onTrain}>
Train
</button>
<button class="action-btn dim" id="btn-clear-examples" onClick={onClearExamples}>
Clear Ex
</button>
<button class="action-btn dim" id="btn-clear-all" onClick={onClearAll}>
Clear All
</button>
<button class="action-btn dim" id="btn-randomize" onClick={onRandomize}>
Randomize
</button>
</div>
<div class="loss-section">
<label>Loss History</label>
<canvas
ref={lossCanvasRef}
id="loss-canvas"
width="280"
height="80"
/>
</div>
</div>
</div>
);
}

View file

@ -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;
}

View file

@ -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);
}
}

View file

@ -20,6 +20,7 @@ export interface DebugProbe {
trainAsync: () => Promise<number | null>; trainAsync: () => Promise<number | null>;
randomise: () => void; randomise: () => void;
clearExamples: () => void; clearExamples: () => void;
clearAll: () => void;
saveState: () => void; saveState: () => void;
evalLoss: () => number | null; evalLoss: () => number | null;
inferBatch: (points: number[][]) => number[][]; inferBatch: (points: number[][]) => number[][];
@ -29,6 +30,7 @@ export interface DebugProbe {
deadFrac: number; deadFrac: number;
satFrac: number; satFrac: number;
}>; }>;
getLossHistory: () => number[];
} }
/** /**
@ -68,6 +70,8 @@ export function createDebugProbe(store: MLStore): DebugProbe {
clearExamples: () => store.clearExamples(), clearExamples: () => store.clearExamples(),
clearAll: () => store.clearAll(),
saveState: () => store.saveState(), saveState: () => store.saveState(),
evalLoss: () => store.evalLoss(), evalLoss: () => store.evalLoss(),
@ -75,6 +79,8 @@ export function createDebugProbe(store: MLStore): DebugProbe {
inferBatch: (points: number[][]) => store.inferBatch(points), inferBatch: (points: number[][]) => store.inferBatch(points),
getLayerStats: () => store.getLayerStats(), getLayerStats: () => store.getLayerStats(),
getLossHistory: () => store.getLossHistory(),
}; };
} }

View file

@ -57,6 +57,12 @@ export interface MLStore {
readonly state: MLState; readonly state: MLState;
readonly outputs: () => Float32Array; readonly outputs: () => Float32Array;
readonly outputCount: () => number; 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) // IML access (opaque handles, NOT reactive)
getActiveIml(): WasmIML | null; getActiveIml(): WasmIML | null;
@ -72,6 +78,10 @@ export interface MLStore {
setInputs(x: number, y: number): void; setInputs(x: number, y: number): void;
randomise(): void; randomise(): void;
clearExamples(): 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; train(): number | null;
trainAsync(): Promise<number | null>; trainAsync(): Promise<number | null>;
thumbsUp(): Promise<number | null>; thumbsUp(): Promise<number | null>;
@ -82,6 +92,7 @@ export interface MLStore {
getWeights(): number[]; getWeights(): number[];
getExampleCount(): number; getExampleCount(): number;
getLoss(): number | null; getLoss(): number | null;
getLossHistory(): number[];
saveState(): void; saveState(): void;
// Lifecycle // Lifecycle
@ -103,6 +114,13 @@ export async function createMLStore(bus: SignalBus): Promise<MLStore> {
const [outputs, setOutputs] = createSignal<Float32Array>(new Float32Array(initialCount)); const [outputs, setOutputs] = createSignal<Float32Array>(new Float32Array(initialCount));
const [outputCount, setOutputCount] = createSignal<number>(initialCount); const [outputCount, setOutputCount] = createSignal<number>(initialCount);
// Noise level signal for RL exploration (reactive for status line + noise ring)
const [noiseLevel, setNoiseLevel] = createSignal<number>(0.05);
// Reactive example count and last loss (for status line to watch)
const [exampleCountSignal, setExampleCountSignal] = createSignal<number>(0);
const [lastLossSignal, setLastLossSignal] = createSignal<number | null>(null);
// IML instances — module-scope opaque handles (not reactive) // IML instances — module-scope opaque handles (not reactive)
let imlJoy: WasmIML | null = null; let imlJoy: WasmIML | null = null;
let imlHand: WasmIML | null = null; let imlHand: WasmIML | null = null;
@ -144,6 +162,9 @@ export async function createMLStore(bus: SignalBus): Promise<MLStore> {
const newOutputs = new Float32Array(activeIml.getOutputs()); const newOutputs = new Float32Array(activeIml.getOutputs());
setOutputs(newOutputs); setOutputs(newOutputs);
outputsTopic.emit(newOutputs); outputsTopic.emit(newOutputs);
// Update reactive state signals
setExampleCountSignal(activeIml.exampleCount);
setLastLossSignal(activeIml.lastLoss);
} }
// ─── Helper: resize MLP (mode switch) ─── // ─── Helper: resize MLP (mode switch) ───
@ -196,6 +217,9 @@ export async function createMLStore(bus: SignalBus): Promise<MLStore> {
get state() { return state; }, get state() { return state; },
outputs, outputs,
outputCount, outputCount,
noiseLevel,
exampleCountSignal,
lastLossSignal,
getActiveIml: () => activeIml, getActiveIml: () => activeIml,
getImlJoy: () => imlJoy, getImlJoy: () => imlJoy,
@ -235,11 +259,35 @@ export async function createMLStore(bus: SignalBus): Promise<MLStore> {
randomise: () => { randomise: () => {
if (!activeIml) return; if (!activeIml) return;
activeIml.randomiseWeights(state.spreadLevel); activeIml.randomiseWeights(state.spreadLevel);
setNoiseLevel(0.05);
runInference(); runInference();
}, },
clearExamples: () => { clearExamples: () => {
activeIml?.clearDataset(); 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: () => { train: () => {
@ -251,7 +299,9 @@ export async function createMLStore(bus: SignalBus): Promise<MLStore> {
trainAsync: () => { trainAsync: () => {
if (!activeIml) return Promise.resolve(null); if (!activeIml) return Promise.resolve(null);
return activeIml.trainAsync(() => runInference()); return activeIml.trainAsync(() => {
runInference();
});
}, },
thumbsUp: () => { thumbsUp: () => {
@ -260,13 +310,21 @@ export async function createMLStore(bus: SignalBus): Promise<MLStore> {
activeIml.inputState.slice(), activeIml.inputState.slice(),
activeIml.outputState.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()); return activeIml.trainAsync(() => runInference());
}, },
thumbsDown: (speed?: number) => { thumbsDown: (speed?: number) => {
if (!activeIml) return; if (!activeIml) return;
const spread = state.spreadLevel; 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); activeIml.moveWeights(s, spread);
runInference(); runInference();
}, },
@ -286,6 +344,8 @@ export async function createMLStore(bus: SignalBus): Promise<MLStore> {
getLoss: () => activeIml?.lastLoss ?? null, getLoss: () => activeIml?.lastLoss ?? null,
getLossHistory: () => activeIml?.lossHistory.slice() ?? [],
saveState: () => { saveState: () => {
if (!activeIml) return; if (!activeIml) return;
const data = { const data = {

View file

@ -19,10 +19,12 @@ const EXPECTED_METHODS = [
'trainAsync', 'trainAsync',
'randomise', 'randomise',
'clearExamples', 'clearExamples',
'clearAll',
'saveState', 'saveState',
'evalLoss', 'evalLoss',
'inferBatch', 'inferBatch',
'getLayerStats', 'getLayerStats',
'getLossHistory',
] as const; ] as const;
test.describe('Debug Probe (f03)', () => { test.describe('Debug Probe (f03)', () => {
@ -61,8 +63,8 @@ test.describe('Debug Probe (f03)', () => {
const expectedMethods = [ const expectedMethods = [
'getOutputs', 'getLoss', 'getWeights', 'getExampleCount', 'getOutputs', 'getLoss', 'getWeights', 'getExampleCount',
'setInputs', 'thumbsUp', 'thumbsDown', 'train', 'trainAsync', 'setInputs', 'thumbsUp', 'thumbsDown', 'train', 'trainAsync',
'randomise', 'clearExamples', 'saveState', 'evalLoss', 'randomise', 'clearExamples', 'clearAll', 'saveState', 'evalLoss',
'inferBatch', 'getLayerStats', 'inferBatch', 'getLayerStats', 'getLossHistory',
]; ];
for (const name of expectedMethods) { for (const name of expectedMethods) {
checks[name] = typeof probe[name] === 'function'; checks[name] = typeof probe[name] === 'function';

View file

@ -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');
});
});