dmontgomery40 commited on
Commit
d66a97c
·
verified ·
1 Parent(s): 89d9516

Sync from GitHub via hub-sync

Browse files
dashboard/src/main.tsx CHANGED
@@ -1,6 +1,6 @@
1
  import React from 'react';
2
  import ReactDOM from 'react-dom/client';
3
- import App from './App';
4
  import './index.css';
5
 
6
  ReactDOM.createRoot(document.getElementById('root')!).render(
 
1
  import React from 'react';
2
  import ReactDOM from 'react-dom/client';
3
+ import App from './playground/App';
4
  import './index.css';
5
 
6
  ReactDOM.createRoot(document.getElementById('root')!).render(
dashboard/src/playground/App.tsx ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect } from 'react';
2
+ import { Empty } from '../components/panels/Empty';
3
+ import { ChatScreen } from './chat/ChatScreen';
4
+ import { Header } from './Header';
5
+ import { SessionsScreen } from './sessions/SessionsScreen';
6
+ import { SignalsScreen } from './signals/SignalsScreen';
7
+ import { TABS, useStore } from './store';
8
+ import { Button, ErrorBanner } from './ui';
9
+
10
+ function isTyping(target: EventTarget | null): boolean {
11
+ if (!(target instanceof HTMLElement)) return false;
12
+ return ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) || target.isContentEditable;
13
+ }
14
+
15
+ export default function App() {
16
+ const tab = useStore((s) => s.tab);
17
+ const setTab = useStore((s) => s.setTab);
18
+ const error = useStore((s) => s.error);
19
+ const clearError = useStore((s) => s.clearError);
20
+ const bootstrap = useStore((s) => s.bootstrap);
21
+ const health = useStore((s) => s.health);
22
+ const healthChecked = useStore((s) => s.healthChecked);
23
+ const health_public = health?.public ?? false;
24
+
25
+ useEffect(() => {
26
+ void bootstrap();
27
+ }, [bootstrap]);
28
+
29
+ // keys 1–3 switch screens when not typing
30
+ useEffect(() => {
31
+ const onKey = (e: KeyboardEvent) => {
32
+ if (e.metaKey || e.ctrlKey || e.altKey || isTyping(e.target)) return;
33
+ const n = Number(e.key);
34
+ if (n >= 1 && n <= TABS.length) {
35
+ e.preventDefault();
36
+ setTab(TABS[n - 1]);
37
+ }
38
+ };
39
+ window.addEventListener('keydown', onKey);
40
+ return () => window.removeEventListener('keydown', onKey);
41
+ }, [setTab]);
42
+
43
+ const offline = healthChecked && health === null;
44
+ const View = tab === 'chat' ? ChatScreen : tab === 'signals' ? SignalsScreen : SessionsScreen;
45
+
46
+ return (
47
+ <div className="min-h-screen bg-surface">
48
+ <Header />
49
+ <main className="mx-auto max-w-[1500px] px-4 py-4">
50
+ {error ? (
51
+ <div className="mb-4">
52
+ <ErrorBanner message={error} onDismiss={clearError} />
53
+ </div>
54
+ ) : null}
55
+ {offline ? (
56
+ <Empty
57
+ title="Connection unavailable."
58
+ detail={health_public ? 'Try again in a moment.' : 'Start the service and reconnect.'}
59
+ command={health_public ? undefined : 'uv run plastic serve --artifacts-root artifacts --port 13579 --device cpu'}
60
+ >
61
+ <Button onClick={() => void bootstrap()}>Retry</Button>
62
+ </Empty>
63
+ ) : (
64
+ <div key={tab} className="tab-enter">
65
+ <View />
66
+ </div>
67
+ )}
68
+ </main>
69
+ </div>
70
+ );
71
+ }
dashboard/src/playground/Header.tsx ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { backendLabel, modeLabel } from './format';
2
+ import { TABS, TAB_LABELS, useStore } from './store';
3
+ import { Select, StateChip } from './ui';
4
+
5
+ export function Header() {
6
+ const health = useStore((s) => s.health);
7
+ const sessions = useStore((s) => s.sessions);
8
+ const current = useStore((s) => s.currentSessionId);
9
+ const detail = useStore((s) => s.detail);
10
+ const models = useStore((s) => s.models);
11
+ const selectSession = useStore((s) => s.selectSession);
12
+ const stale = useStore((s) => s.stale);
13
+ const tab = useStore((s) => s.tab);
14
+ const setTab = useStore((s) => s.setTab);
15
+
16
+ const text = sessions.filter((s) => s.domain === 'text');
17
+ const model = models.find((m) => m.model_id === detail?.meta.model_id);
18
+ const connected = health !== null && !stale;
19
+
20
+ return (
21
+ <header className="border-b border-edge bg-surface-raised">
22
+ <div className="mx-auto flex max-w-[1500px] flex-wrap items-center gap-x-5 gap-y-3 px-4 py-3">
23
+ <div className="flex items-center gap-3">
24
+ <span className="text-lg font-bold tracking-tight text-ink-primary">plastic</span>
25
+ <StateChip tone={connected ? 'accent' : 'bad'}>{connected ? 'connected' : health ? 'stale' : 'offline'}</StateChip>
26
+ {health?.public ? <StateChip>shared public session</StateChip> : null}
27
+ </div>
28
+ <nav aria-label="Screens" className="flex items-center gap-1">
29
+ {TABS.map((t, i) => (
30
+ <button
31
+ key={t}
32
+ type="button"
33
+ onClick={() => setTab(t)}
34
+ aria-current={tab === t ? 'page' : undefined}
35
+ className={`rounded px-3 py-1.5 text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
36
+ tab === t ? 'bg-accent-soft text-accent' : 'text-ink-secondary hover:text-ink-primary'
37
+ }`}
38
+ >
39
+ <span className="mr-1.5 font-mono text-micro text-ink-muted">{i + 1}</span>
40
+ {TAB_LABELS[t]}
41
+ </button>
42
+ ))}
43
+ </nav>
44
+ <div className="ml-auto flex flex-wrap items-center gap-3">
45
+ {detail ? (
46
+ <>
47
+ <StateChip>{backendLabel(detail.summary.backend ?? model?.backend)}</StateChip>
48
+ <StateChip tone={modeLabel(detail.meta.harness) === 'guarded' ? 'warn' : 'default'}>{modeLabel(detail.meta.harness)}</StateChip>
49
+ {model && model.chat_tuned === false ? <StateChip tone="warn">base model, not chat-tuned</StateChip> : null}
50
+ </>
51
+ ) : null}
52
+ <label className="flex items-center gap-2 text-label font-semibold uppercase tracking-wide text-ink-muted">
53
+ Session
54
+ <span className="w-52">
55
+ <Select aria-label="Session" value={current ?? ''} onChange={(e) => void selectSession(e.target.value || null)} disabled={text.length === 0}>
56
+ {text.length === 0 ? <option value="">no text session</option> : null}
57
+ {text.map((s) => (
58
+ <option key={s.session_id} value={s.session_id}>
59
+ {s.session_id}
60
+ </option>
61
+ ))}
62
+ </Select>
63
+ </span>
64
+ </label>
65
+ </div>
66
+ </div>
67
+ </header>
68
+ );
69
+ }
dashboard/src/playground/chat/ChatScreen.tsx ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { Panel } from '../../components/panels/Panel';
3
+ import { KeyValue } from '../../components/panels/KeyValue';
4
+ import { Empty } from '../../components/panels/Empty';
5
+ import { backendLabel, fmt, fmtInt, modeLabel, thresholdSource, turnTotals, turnsFromTrace } from '../format';
6
+ import { useStore } from '../store';
7
+ import type { Turn } from '../types';
8
+ import { Button, Field, NumberInput, StateChip } from '../ui';
9
+ import { LearningStrip, StripLegend } from './LearningStrip';
10
+
11
+ function TurnCard({ turn }: { turn: Turn }) {
12
+ const t = turnTotals(turn.chunks);
13
+ return (
14
+ <article className="rounded border border-edge bg-surface-raised">
15
+ <div className="border-b border-edge px-4 py-3">
16
+ <p className="text-label font-semibold uppercase tracking-wide text-ink-muted">You</p>
17
+ <p className="mt-1 whitespace-pre-wrap text-base text-ink-primary">{turn.prompt}</p>
18
+ </div>
19
+ <div className="px-4 py-3">
20
+ <p className="text-label font-semibold uppercase tracking-wide text-ink-muted">Model</p>
21
+ <p className="mt-1 whitespace-pre-wrap font-mono text-sm text-ink-primary">{turn.completion || <span className="text-ink-muted">(empty completion)</span>}</p>
22
+ </div>
23
+ <div className="border-t border-edge px-4 py-3">
24
+ <LearningStrip chunks={turn.chunks} />
25
+ <dl className="mt-2 flex flex-wrap gap-x-5 gap-y-1 font-mono text-xs text-ink-secondary">
26
+ <div><dt className="inline text-ink-muted">chunks </dt><dd className="inline">{t.chunks}</dd></div>
27
+ <div><dt className="inline text-ink-muted">committed </dt><dd className="inline">{t.committed}</dd></div>
28
+ <div><dt className="inline text-ink-muted">intervened </dt><dd className="inline">{t.intervened}</dd></div>
29
+ {t.wouldIntervene > 0 ? <div><dt className="inline text-ink-muted">would intervene </dt><dd className="inline">{t.wouldIntervene}</dd></div> : null}
30
+ {t.readOnly > 0 ? <div><dt className="inline text-ink-muted">read-only </dt><dd className="inline">{t.readOnly}</dd></div> : null}
31
+ <div><dt className="inline text-ink-muted">proposed Δ </dt><dd className="inline">{fmt(t.proposed)}</dd></div>
32
+ <div><dt className="inline text-ink-muted">accepted Δ </dt><dd className="inline">{fmt(t.accepted)}</dd></div>
33
+ <div><dt className="inline text-ink-muted">tokens </dt><dd className="inline">{t.promptTokens} prompt · {t.modelTokens} generated</dd></div>
34
+ </dl>
35
+ </div>
36
+ </article>
37
+ );
38
+ }
39
+
40
+ function Composer() {
41
+ const [text, setText] = useState('');
42
+ const busy = useStore((s) => s.busy.chat);
43
+ const detail = useStore((s) => s.detail);
44
+ const sendChat = useStore((s) => s.sendChat);
45
+ const sampling = useStore((s) => s.sampling);
46
+ const setSampling = useStore((s) => s.setSampling);
47
+ const resume = useStore((s) => s.resumeSession);
48
+ const caps = useStore((s) => s.capabilities)();
49
+ const readOnly = detail?.summary.read_only ?? false;
50
+
51
+ const submit = () => {
52
+ const prompt = text.trim();
53
+ if (!prompt || busy || !detail) return;
54
+ setText('');
55
+ void sendChat(prompt);
56
+ };
57
+
58
+ return (
59
+ <div className="rounded border border-edge bg-surface-raised px-4 py-3">
60
+ <label htmlFor="prompt" className="text-label font-semibold uppercase tracking-wide text-ink-muted">
61
+ Prompt
62
+ </label>
63
+ <textarea
64
+ id="prompt"
65
+ value={text}
66
+ onChange={(e) => setText(e.target.value)}
67
+ onKeyDown={(e) => {
68
+ if (e.key === 'Enter' && !e.shiftKey) {
69
+ e.preventDefault();
70
+ submit();
71
+ }
72
+ }}
73
+ rows={3}
74
+ disabled={busy || !detail}
75
+ placeholder={detail ? 'Type a message. Enter sends, Shift+Enter for a new line.' : 'Select a session first.'}
76
+ className="mt-1 w-full resize-y rounded border border-edge-strong bg-surface-overlay px-3 py-2 text-base text-ink-primary focus:border-accent focus:outline-none disabled:text-ink-muted"
77
+ />
78
+ <div className="mt-2 flex flex-wrap items-end gap-3">
79
+ <Button tone="primary" onClick={submit} disabled={busy || !detail || !text.trim()}>
80
+ {busy ? 'Generating…' : 'Send'}
81
+ </Button>
82
+ {readOnly ? (
83
+ <span className="flex items-center gap-2">
84
+ <StateChip tone="warn">read-only: {detail?.summary.read_only_reason ?? 'latched'}</StateChip>
85
+ {caps.resume && detail ? <Button onClick={() => void resume(detail.meta.session_id)}>Resume</Button> : null}
86
+ </span>
87
+ ) : null}
88
+ <div className="ml-auto grid grid-cols-2 gap-3 sm:grid-cols-4">
89
+ <Field label="Max tokens" htmlFor="max-tokens">
90
+ <NumberInput id="max-tokens" min={1} max={512} value={sampling.max_new_tokens} onChange={(e) => setSampling({ max_new_tokens: Number(e.target.value) })} />
91
+ </Field>
92
+ <Field label="Temperature" htmlFor="temperature">
93
+ <NumberInput id="temperature" min={0} max={2} step={0.05} value={sampling.temperature} onChange={(e) => setSampling({ temperature: Number(e.target.value) })} />
94
+ </Field>
95
+ <Field label="Top-k" htmlFor="top-k" hint="0 disables">
96
+ <NumberInput id="top-k" min={0} max={500} value={sampling.top_k} onChange={(e) => setSampling({ top_k: Number(e.target.value) })} />
97
+ </Field>
98
+ <Field label="Seed" htmlFor="seed" hint="blank = random">
99
+ <NumberInput id="seed" value={sampling.seed ?? ''} onChange={(e) => setSampling({ seed: e.target.value === '' ? null : Number(e.target.value) })} />
100
+ </Field>
101
+ </div>
102
+ </div>
103
+ </div>
104
+ );
105
+ }
106
+
107
+ export function ChatScreen() {
108
+ const detail = useStore((s) => s.detail);
109
+ const transactions = useStore((s) => s.transactions);
110
+ const models = useStore((s) => s.models);
111
+ const busy = useStore((s) => s.busy);
112
+ const bottom = useRef<HTMLDivElement>(null);
113
+ const turns = detail ? turnsFromTrace(detail.trace, transactions) : [];
114
+
115
+ useEffect(() => {
116
+ bottom.current?.scrollIntoView({ block: 'end' });
117
+ }, [turns.length, busy.chat]);
118
+
119
+ if (!detail) {
120
+ return <Empty title="No text session selected." detail={busy.session ? 'Loading…' : 'Choose a session above, or create one under Sessions.'} />;
121
+ }
122
+ const model = models.find((m) => m.model_id === detail.meta.model_id);
123
+ const summary = detail.summary;
124
+ const present = summary.signals_available ?? [];
125
+
126
+ return (
127
+ <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_320px]">
128
+ <section className="min-w-0 space-y-3">
129
+ {turns.length === 0 ? <Empty title="No turns yet." detail="Send a message to start." /> : turns.map((t) => <TurnCard key={t.index} turn={t} />)}
130
+ {busy.chat ? <p role="status" className="text-sm text-ink-secondary">Generating…</p> : null}
131
+ <div ref={bottom} />
132
+ <Composer />
133
+ <StripLegend />
134
+ </section>
135
+ <aside className="space-y-4">
136
+ <Panel title="Session">
137
+ <KeyValue
138
+ rows={[
139
+ { label: 'Model', value: detail.meta.model_id },
140
+ { label: 'Learner', value: backendLabel(summary.backend ?? model?.backend) },
141
+ { label: 'Mode', value: modeLabel(detail.meta.harness) },
142
+ { label: 'Position', value: fmtInt(summary.pos) },
143
+ { label: 'Chunks', value: fmtInt(summary.n_transactions) },
144
+ { label: 'State', value: summary.read_only ? `read-only (${summary.read_only_reason ?? 'latched'})` : 'writable' },
145
+ ]}
146
+ />
147
+ </Panel>
148
+ <Panel title="Harness">
149
+ <KeyValue
150
+ rows={[
151
+ { label: 'Thresholds', value: thresholdSource(summary) },
152
+ { label: 'Generated tokens', value: summary.writes_generation ? 'write to memory' : 'read-only' },
153
+ { label: 'CUSUM', value: `${fmt(summary.cusum?.s_hi, 2)} / ${fmt(summary.cusum?.s_lo, 2)}`, note: `h ${fmt(summary.cusum?.h, 2)} · ${summary.cusum?.alarms ?? 0} alarms` },
154
+ { label: 'Budget used', value: fmt(summary.budget_used), note: summary.budget_session === null ? 'no session cap' : `cap ${fmt(summary.budget_session)}` },
155
+ { label: 'Drift from anchor', value: fmt(summary.drift_from_anchor) },
156
+ { label: 'Decision signals', value: present.length ? present.join(', ') : 'none' },
157
+ ]}
158
+ mono={false}
159
+ />
160
+ </Panel>
161
+ </aside>
162
+ </div>
163
+ );
164
+ }
dashboard/src/playground/chat/LearningStrip.tsx ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { DECISION_COLOR, DECISION_GLYPH, DECISION_LABEL, chunkSize, chunkSource, fmt, isFinite_, wouldIntervene } from '../format';
2
+ import type { TransactionRecord } from '../types';
3
+
4
+ /**
5
+ * One cell per chunk of a turn. Fill = the APPLIED decision; a dashed outline = the policy REQUESTED a different
6
+ * decision (observational mode records what would have happened). Height = the chunk's own write (or proposed
7
+ * change), width = its token count. A thin bar marks accepted change where it differs from proposed. Hue is
8
+ * always paired with a glyph, so nothing depends on color alone.
9
+ */
10
+ export function LearningStrip({ chunks, height = 44 }: { chunks: TransactionRecord[]; height?: number }) {
11
+ if (chunks.length === 0) return <p className="text-xs text-ink-muted">No chunks recorded for this turn.</p>;
12
+ const sizes = chunks.map(chunkSize);
13
+ const max = Math.max(1e-9, ...sizes.filter(isFinite_));
14
+ const tokens = chunks.map((c) => Math.max(1, c.signals.n_tokens));
15
+ const totalTokens = tokens.reduce((a, b) => a + b, 0);
16
+ return (
17
+ <ol role="list" aria-label="Learning strip: one cell per chunk" className="flex w-full items-end gap-px" style={{ height }}>
18
+ {chunks.map((tx, i) => {
19
+ const applied = tx.decision.kind;
20
+ const requested = tx.requested.kind;
21
+ const frac = isFinite_(sizes[i]) ? Math.max(0.08, sizes[i] / max) : 0;
22
+ const would = wouldIntervene(tx);
23
+ const accepted = tx.accepted?.delta_norm;
24
+ const proposed = tx.signals.delta_norm;
25
+ const kept = isFinite_(accepted) && isFinite_(proposed) && proposed > 0 ? Math.min(1, accepted / proposed) : 1;
26
+ const src = chunkSource(tx);
27
+ const glyph = src === 'prompt' ? '▲' : src === 'model' ? '●' : src === 'mixed' ? '◆' : '·';
28
+ const title = [
29
+ `chunk ${tx.index} · ${DECISION_LABEL[applied]}${would ? ` (policy would ${DECISION_LABEL[requested].toLowerCase()})` : ''}`,
30
+ `${tx.signals.n_tokens} tokens · ${src}`,
31
+ `loss ${fmt(tx.signals.chunk_loss)}`,
32
+ isFinite_(tx.signals.surprise_mean) ? `surprise ${fmt(tx.signals.surprise_mean)}` : null,
33
+ isFinite_(tx.signals.beta_mean) ? `step ${fmt(tx.signals.beta_mean)}` : null,
34
+ isFinite_(tx.signals.write_norm_sum) ? `write ${fmt(tx.signals.write_norm_sum)}` : null,
35
+ `proposed Δ ${fmt(proposed)} · accepted Δ ${fmt(accepted)}`,
36
+ tx.signals.cusum_alarm ? 'CUSUM alarm' : null,
37
+ ]
38
+ .filter(Boolean)
39
+ .join('\n');
40
+ return (
41
+ <li
42
+ key={tx.index}
43
+ title={title}
44
+ aria-label={title.replace(/\n/g, ', ')}
45
+ className="relative flex min-w-[6px] items-end justify-center"
46
+ style={{ width: `${(tokens[i] / totalTokens) * 100}%`, height: '100%' }}
47
+ >
48
+ <div
49
+ className="relative w-full rounded-sm"
50
+ style={{
51
+ height: `${Math.round(frac * 100)}%`,
52
+ backgroundColor: DECISION_COLOR[applied],
53
+ outline: would ? `2px dashed ${DECISION_COLOR[requested]}` : undefined,
54
+ outlineOffset: would ? '-2px' : undefined,
55
+ }}
56
+ >
57
+ {kept < 0.999 ? (
58
+ <div
59
+ aria-hidden
60
+ className="absolute inset-x-0 bottom-0 border-t-2 border-ink-primary"
61
+ style={{ height: `${Math.round(kept * 100)}%` }}
62
+ />
63
+ ) : null}
64
+ </div>
65
+ <span aria-hidden className="pointer-events-none absolute -top-0.5 text-micro leading-none text-ink-secondary">
66
+ {glyph}
67
+ </span>
68
+ <span aria-hidden className="pointer-events-none absolute bottom-0 text-micro leading-none text-ink-inverse">
69
+ {DECISION_GLYPH[applied]}
70
+ </span>
71
+ </li>
72
+ );
73
+ })}
74
+ </ol>
75
+ );
76
+ }
77
+
78
+ export function StripLegend() {
79
+ return (
80
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-micro text-ink-secondary">
81
+ {(Object.keys(DECISION_LABEL) as (keyof typeof DECISION_LABEL)[]).map((k) => (
82
+ <span key={k} className="inline-flex items-center gap-1">
83
+ <span aria-hidden className="inline-block h-2.5 w-2.5 rounded-sm" style={{ backgroundColor: DECISION_COLOR[k] }} />
84
+ {DECISION_GLYPH[k]} {DECISION_LABEL[k]}
85
+ </span>
86
+ ))}
87
+ <span>▲ prompt tokens · ● generated tokens</span>
88
+ <span>dashed outline = policy would have intervened</span>
89
+ <span>bar = accepted share of proposed change</span>
90
+ </div>
91
+ );
92
+ }
dashboard/src/playground/client.ts ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The only module that talks HTTP. Errors are surfaced as ApiError with a clean message; an HTML error
2
+ // page or a stack trace never reaches the banner raw.
3
+
4
+ import type {
5
+ CalibrationSummary,
6
+ ChatResult,
7
+ Health,
8
+ ModelSummary,
9
+ Sampling,
10
+ SessionDetail,
11
+ SessionState,
12
+ SessionSummary,
13
+ TransactionPage,
14
+ } from './types';
15
+
16
+ export const API_BASE: string = (import.meta.env?.VITE_API_URL as string | undefined) ?? '';
17
+
18
+ export class ApiError extends Error {
19
+ readonly status: number;
20
+ readonly url: string;
21
+
22
+ constructor(message: string, status: number, url: string) {
23
+ super(message);
24
+ this.name = 'ApiError';
25
+ this.status = status;
26
+ this.url = url;
27
+ }
28
+ }
29
+
30
+ type Query = Record<string, string | number | boolean | undefined | null>;
31
+
32
+ export function buildUrl(path: string, query?: Query): string {
33
+ const qs = Object.entries(query ?? {})
34
+ .filter(([, v]) => v !== undefined && v !== null && v !== '')
35
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
36
+ .join('&');
37
+ return `${API_BASE}${path}${qs ? `?${qs}` : ''}`;
38
+ }
39
+
40
+ export function cleanErrorMessage(text: string): string {
41
+ const stripped = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
42
+ return stripped.length > 240 ? `${stripped.slice(0, 237)}...` : stripped || 'request failed';
43
+ }
44
+
45
+ export async function fetchJson<T>(path: string, options: { method?: 'GET' | 'POST' | 'DELETE'; body?: unknown; query?: Query } = {}): Promise<T> {
46
+ const { method = 'GET', body, query } = options;
47
+ const url = buildUrl(path, query);
48
+ const init: RequestInit = { method };
49
+ if (body !== undefined) {
50
+ init.headers = { 'Content-Type': 'application/json' };
51
+ init.body = JSON.stringify(body);
52
+ }
53
+ let response: Response;
54
+ try {
55
+ response = await fetch(url, init);
56
+ } catch (err) {
57
+ throw new ApiError(err instanceof Error ? err.message : 'network request failed', 0, url);
58
+ }
59
+ const text = await response.text();
60
+ let payload: unknown = null;
61
+ if (text) {
62
+ try {
63
+ payload = JSON.parse(text);
64
+ } catch {
65
+ if (!response.ok) throw new ApiError(cleanErrorMessage(text), response.status, url);
66
+ throw new ApiError('response was not JSON', response.status, url);
67
+ }
68
+ }
69
+ if (!response.ok) {
70
+ const detail = payload && typeof payload === 'object' && 'detail' in payload
71
+ ? cleanErrorMessage(String((payload as { detail: unknown }).detail))
72
+ : `request failed with status ${response.status}`;
73
+ throw new ApiError(detail, response.status, url);
74
+ }
75
+ return payload as T;
76
+ }
77
+
78
+ export const getHealth = () => fetchJson<Health>('/api/health');
79
+ export const getModels = () => fetchJson<ModelSummary[]>('/api/models');
80
+ export const calibrateModel = (modelId: string) =>
81
+ fetchJson<CalibrationSummary>(`/api/models/${encodeURIComponent(modelId)}/calibrate`, { method: 'POST', body: {} });
82
+
83
+ export const getSessions = () => fetchJson<SessionSummary[]>('/api/sessions');
84
+ export const createSession = (body: { model_id: string; session_id?: string; harness?: Record<string, unknown> }) =>
85
+ fetchJson<SessionSummary>('/api/sessions', { method: 'POST', body });
86
+ export const getSession = (sessionId: string) => fetchJson<SessionDetail>(`/api/sessions/${encodeURIComponent(sessionId)}`);
87
+ export const getTransactions = (sessionId: string, limit = 400, offset = 0) =>
88
+ fetchJson<TransactionPage>(`/api/sessions/${encodeURIComponent(sessionId)}/transactions`, { query: { limit, offset } });
89
+ export const getSessionState = (sessionId: string) => fetchJson<SessionState>(`/api/sessions/${encodeURIComponent(sessionId)}/state`);
90
+ export const chat = (sessionId: string, prompt: string, sampling: Sampling) =>
91
+ fetchJson<ChatResult>(`/api/sessions/${encodeURIComponent(sessionId)}/chat`, {
92
+ method: 'POST',
93
+ body: { prompt, max_new_tokens: sampling.max_new_tokens, temperature: sampling.temperature, top_k: sampling.top_k, seed: sampling.seed },
94
+ });
95
+ export const forkSession = (sessionId: string) =>
96
+ fetchJson<SessionSummary>(`/api/sessions/${encodeURIComponent(sessionId)}/fork`, { method: 'POST', body: {} });
97
+ export const resetSession = (sessionId: string) => fetchJson<unknown>(`/api/sessions/${encodeURIComponent(sessionId)}/reset`, { method: 'POST' });
98
+ export const resumeSession = (sessionId: string) => fetchJson<unknown>(`/api/sessions/${encodeURIComponent(sessionId)}/resume`, { method: 'POST' });
99
+ export const deleteSession = (sessionId: string) => fetchJson<unknown>(`/api/sessions/${encodeURIComponent(sessionId)}`, { method: 'DELETE' });
dashboard/src/playground/format.test.ts ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest';
2
+ import { chunkSize, chunkSource, firedSignals, fmt, modeLabel, presentFields, thresholdSource, turnTotals, turnsFromTrace, wouldIntervene } from './format';
3
+ import type { HarnessConfig, RunnerSummary, TraceRecord, TransactionRecord } from './types';
4
+
5
+ function tx(index: number, pos_start: number, pos_end: number, opts: Partial<TransactionRecord> & { requested?: TransactionRecord['requested'] } = {}): TransactionRecord {
6
+ const decision = opts.decision ?? { kind: 'commit', reasons: [], scale: 1 };
7
+ return {
8
+ index,
9
+ t_unix: 0,
10
+ pos_start,
11
+ pos_end,
12
+ decision,
13
+ requested: opts.requested ?? decision,
14
+ signals: {
15
+ pos_start,
16
+ pos_end,
17
+ n_tokens: pos_end - pos_start,
18
+ chunk_loss: 2.0,
19
+ delta_norm: 10,
20
+ z: {},
21
+ cusum_alarm: false,
22
+ budget_used: 0,
23
+ budget_remaining: null,
24
+ log_delta_norm: 2.3,
25
+ ...(opts.signals ?? {}),
26
+ },
27
+ accepted: { delta_norm: 10, budget_charge: 10, budget_used: 10, budget_remaining: null, ...(opts.accepted ?? {}) },
28
+ sources: opts.sources,
29
+ eligible: true,
30
+ read_only: false,
31
+ read_only_reason: null,
32
+ seconds: 0.1,
33
+ };
34
+ }
35
+
36
+ describe('turns', () => {
37
+ it('groups chunks under chat turns by position and keeps turn order', () => {
38
+ const trace: TraceRecord[] = [
39
+ { t_unix: 2, kind: 'chat', prompt: 'b', completion: 'B', pos_end: 40, n_transactions: 2 },
40
+ { t_unix: 1, kind: 'chat', prompt: 'a', completion: 'A', pos_end: 20, n_transactions: 2 },
41
+ ];
42
+ const txs = [tx(0, 0, 16), tx(1, 16, 20), tx(2, 20, 36), tx(3, 36, 40)];
43
+ const turns = turnsFromTrace(trace, txs);
44
+ expect(turns.map((t) => t.prompt)).toEqual(['a', 'b']);
45
+ expect(turns[0].chunks.map((c) => c.index)).toEqual([0, 1]);
46
+ expect(turns[1].chunks.map((c) => c.index)).toEqual([2, 3]);
47
+ });
48
+
49
+ it('totals distinguish applied interventions, would-have interventions and read-only observations', () => {
50
+ const chunks = [
51
+ tx(0, 0, 8, { sources: { user: 8, model: 0 } }),
52
+ tx(1, 8, 16, { requested: { kind: 'rollback', reasons: ['would_rollback:chunk_loss(9>8)'], scale: 1 }, sources: { user: 8, model: 0 } }),
53
+ tx(2, 16, 24, { decision: { kind: 'rollback', reasons: ['chunk_loss(9>8)'], scale: 1 }, accepted: { delta_norm: 0, budget_charge: 0, budget_used: 10, budget_remaining: null }, sources: { user: 0, model: 8 } }),
54
+ tx(3, 24, 32, { decision: { kind: 'readonly', reasons: ['learning_ineligible'], scale: 1 }, sources: { user: 0, model: 8 } }),
55
+ ];
56
+ const t = turnTotals(chunks);
57
+ expect(t).toMatchObject({ chunks: 4, committed: 2, intervened: 1, wouldIntervene: 1, readOnly: 1, promptTokens: 16, modelTokens: 16 });
58
+ expect(t.proposed).toBe(40);
59
+ expect(t.accepted).toBe(30);
60
+ expect(wouldIntervene(chunks[1])).toBe(true);
61
+ expect(wouldIntervene(chunks[2])).toBe(false);
62
+ expect(firedSignals(chunks[1])).toEqual(['chunk_loss']);
63
+ });
64
+ });
65
+
66
+ describe('labels and gating', () => {
67
+ it('sizes a cell by the chunk\'s own write norm when present, else by the proposed change', () => {
68
+ expect(chunkSize(tx(0, 0, 8, { signals: { write_norm_sum: 3 } as never }))).toBe(3);
69
+ expect(chunkSize(tx(0, 0, 8))).toBe(10);
70
+ });
71
+
72
+ it('gates fields on presence of any finite value, never on the decision-signal list', () => {
73
+ const a = tx(0, 0, 8, { signals: { beta_mean: 0.01, surprise_mean: null } as never });
74
+ const b = tx(1, 8, 16, { signals: { beta_mean: null, surprise_mean: null } as never });
75
+ expect(presentFields([a, b], ['beta_mean', 'surprise_mean', 'write_norm_sum'])).toEqual(['beta_mean']);
76
+ });
77
+
78
+ it('names the mode and the threshold source as states', () => {
79
+ expect(modeLabel({ log_only: true } as HarnessConfig)).toBe('observational');
80
+ expect(modeLabel({ log_only: false } as HarnessConfig)).toBe('guarded');
81
+ expect(thresholdSource({ calibration: 'installed' } as RunnerSummary)).toBe('calibrated thresholds');
82
+ expect(thresholdSource({ calibration: 'absent' } as RunnerSummary)).toMatch(/session-relative/);
83
+ expect(thresholdSource({ calibration: 'rejected_signature_mismatch' } as RunnerSummary)).toMatch(/another checkpoint/);
84
+ });
85
+
86
+ it('reads the chunk source from token counts', () => {
87
+ expect(chunkSource(tx(0, 0, 8, { sources: { user: 8, model: 0 } }))).toBe('prompt');
88
+ expect(chunkSource(tx(0, 0, 8, { sources: { user: 0, model: 3 } }))).toBe('model');
89
+ expect(chunkSource(tx(0, 0, 8))).toBe('unknown');
90
+ });
91
+
92
+ it('never formats a non-finite value as a number', () => {
93
+ expect(fmt(null)).toBe('n/a');
94
+ expect(fmt(Number.NaN)).toBe('n/a');
95
+ expect(fmt(0)).toBe('0');
96
+ expect(fmt(12345.6)).toBe('12346');
97
+ });
98
+ });
dashboard/src/playground/format.ts ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Formatting and labeling. Every label here is a STATE, stated once, never an explanation.
2
+
3
+ import type { DecisionKind, HarnessConfig, RunnerSummary, TraceRecord, TransactionRecord, Turn } from './types';
4
+
5
+ export const DECISION_COLOR: Record<DecisionKind, string> = {
6
+ commit: '#3fd17a',
7
+ rollback: '#ff6b6b',
8
+ scale: '#f0b429',
9
+ project: '#58a6ff',
10
+ readonly: '#94a3b4',
11
+ };
12
+
13
+ export const DECISION_LABEL: Record<DecisionKind, string> = {
14
+ commit: 'Commit',
15
+ rollback: 'Rollback',
16
+ scale: 'Scale',
17
+ project: 'Project',
18
+ readonly: 'Read-only',
19
+ };
20
+
21
+ /** A second channel beside hue, so decisions are distinguishable without color. */
22
+ export const DECISION_GLYPH: Record<DecisionKind, string> = {
23
+ commit: '●',
24
+ rollback: '✕',
25
+ scale: '◐',
26
+ project: '◇',
27
+ readonly: '○',
28
+ };
29
+
30
+ export function isFinite_(v: unknown): v is number {
31
+ return typeof v === 'number' && Number.isFinite(v);
32
+ }
33
+
34
+ export function fmt(v: unknown, digits = 3): string {
35
+ if (!isFinite_(v)) return 'n/a';
36
+ if (v === 0) return '0';
37
+ const a = Math.abs(v);
38
+ if (a >= 1000) return v.toFixed(0);
39
+ if (a >= 10) return v.toFixed(Math.max(0, digits - 2));
40
+ if (a >= 1) return v.toFixed(digits - 1);
41
+ return v.toPrecision(digits);
42
+ }
43
+
44
+ export function fmtInt(v: unknown): string {
45
+ return isFinite_(v) ? Math.round(v).toLocaleString() : 'n/a';
46
+ }
47
+
48
+ export function ago(unix: number | null | undefined, now = Date.now()): string {
49
+ if (!isFinite_(unix)) return 'n/a';
50
+ const s = Math.max(0, Math.round(now / 1000 - unix));
51
+ if (s < 60) return `${s}s ago`;
52
+ if (s < 3600) return `${Math.round(s / 60)}m ago`;
53
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`;
54
+ return `${Math.round(s / 86400)}d ago`;
55
+ }
56
+
57
+ /** Observational: no gate acts, decisions record what would have happened. Guarded: the harness intervenes. */
58
+ export function modeLabel(harness: HarnessConfig | undefined): 'observational' | 'guarded' {
59
+ return harness?.log_only ? 'observational' : 'guarded';
60
+ }
61
+
62
+ /** Where the harness thresholds come from for THIS session. */
63
+ export function thresholdSource(summary: RunnerSummary | undefined): string {
64
+ switch (summary?.calibration) {
65
+ case 'installed':
66
+ return 'calibrated thresholds';
67
+ case 'rejected_signature_mismatch':
68
+ return 'session-relative thresholds (saved calibration is for another checkpoint)';
69
+ case 'rejected_unsigned':
70
+ return 'session-relative thresholds (saved calibration is unsigned)';
71
+ default:
72
+ return 'session-relative thresholds';
73
+ }
74
+ }
75
+
76
+ export function backendLabel(backend: string | undefined): string {
77
+ switch (backend) {
78
+ case 'ttt':
79
+ return 'TTT-MLP fast weights';
80
+ case 'qwen':
81
+ return 'Gated DeltaNet (Qwen3.5)';
82
+ case 'plastic':
83
+ case undefined:
84
+ return 'Plastic delta memory';
85
+ default:
86
+ return backend;
87
+ }
88
+ }
89
+
90
+ /** An intervention is an applied decision other than commit; read-only is an observation, not an intervention. */
91
+ export function isIntervention(kind: DecisionKind): boolean {
92
+ return kind === 'rollback' || kind === 'scale' || kind === 'project';
93
+ }
94
+
95
+ /** In observational mode the policy's requested decision differs from the applied commit. */
96
+ export function wouldIntervene(tx: TransactionRecord): boolean {
97
+ return tx.requested.kind !== tx.decision.kind && isIntervention(tx.requested.kind);
98
+ }
99
+
100
+ /** The chunk's own size for the learning strip: its tokens' write norm where the backend reports one, else the proposed change. */
101
+ export function chunkSize(tx: TransactionRecord): number {
102
+ const w = tx.signals.write_norm_sum;
103
+ return isFinite_(w) ? w : tx.signals.delta_norm;
104
+ }
105
+
106
+ export function chunkSource(tx: TransactionRecord): 'prompt' | 'model' | 'mixed' | 'unknown' {
107
+ const s = tx.sources;
108
+ if (!s) return 'unknown';
109
+ if (s.user > 0 && s.model > 0) return 'mixed';
110
+ if (s.user > 0) return 'prompt';
111
+ if (s.model > 0) return 'model';
112
+ return 'unknown';
113
+ }
114
+
115
+ /** Group a session's transactions under its chat turns by position. Chunks before the first turn (none, normally) are dropped. */
116
+ export function turnsFromTrace(trace: TraceRecord[], transactions: TransactionRecord[]): Turn[] {
117
+ const chats = trace.filter((t) => t.kind === 'chat').slice().sort((a, b) => a.pos_end - b.pos_end);
118
+ const sorted = transactions.slice().sort((a, b) => a.pos_start - b.pos_start);
119
+ const out: Turn[] = [];
120
+ let start = 0;
121
+ chats.forEach((t, i) => {
122
+ const chunks = sorted.filter((tx) => tx.pos_start >= start && tx.pos_end <= t.pos_end);
123
+ out.push({ index: i, prompt: t.prompt ?? '', completion: t.completion ?? '', t_unix: t.t_unix, pos_end: t.pos_end, chunks });
124
+ start = t.pos_end;
125
+ });
126
+ return out;
127
+ }
128
+
129
+ export interface TurnTotalsData {
130
+ chunks: number;
131
+ committed: number;
132
+ intervened: number;
133
+ wouldIntervene: number;
134
+ readOnly: number;
135
+ proposed: number;
136
+ accepted: number;
137
+ promptTokens: number;
138
+ modelTokens: number;
139
+ }
140
+
141
+ export function turnTotals(chunks: TransactionRecord[]): TurnTotalsData {
142
+ const t: TurnTotalsData = { chunks: chunks.length, committed: 0, intervened: 0, wouldIntervene: 0, readOnly: 0, proposed: 0, accepted: 0, promptTokens: 0, modelTokens: 0 };
143
+ for (const tx of chunks) {
144
+ if (tx.decision.kind === 'commit') t.committed += 1;
145
+ if (isIntervention(tx.decision.kind)) t.intervened += 1;
146
+ if (tx.decision.kind === 'readonly') t.readOnly += 1;
147
+ if (wouldIntervene(tx)) t.wouldIntervene += 1;
148
+ if (isFinite_(tx.signals.delta_norm)) t.proposed += tx.signals.delta_norm;
149
+ if (isFinite_(tx.accepted?.delta_norm)) t.accepted += tx.accepted.delta_norm;
150
+ t.promptTokens += tx.sources?.user ?? 0;
151
+ t.modelTokens += tx.sources?.model ?? 0;
152
+ }
153
+ return t;
154
+ }
155
+
156
+ /** Which per-chunk fields the backend actually produced (any finite value in the records). */
157
+ export function presentFields(transactions: TransactionRecord[], fields: string[]): string[] {
158
+ return fields.filter((f) => transactions.some((tx) => isFinite_((tx.signals as unknown as Record<string, unknown>)[f])));
159
+ }
160
+
161
+ export function firedSignals(tx: TransactionRecord): string[] {
162
+ return tx.requested.reasons.map((r) => r.replace(/^would_(rollback|scale|project):/, '').split('(')[0]);
163
+ }
dashboard/src/playground/sessions/SessionsScreen.tsx ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react';
2
+ import { Empty } from '../../components/panels/Empty';
3
+ import { Panel } from '../../components/panels/Panel';
4
+ import { ago, backendLabel, fmtInt } from '../format';
5
+ import { useStore } from '../store';
6
+ import { Button, Field, Select, StateChip } from '../ui';
7
+
8
+ function CreateSession() {
9
+ const models = useStore((s) => s.models).filter((m) => m.domain === 'text' && m.status === 'completed');
10
+ const createSession = useStore((s) => s.createSession);
11
+ const calibrate = useStore((s) => s.calibrate);
12
+ const caps = useStore((s) => s.capabilities)();
13
+ const busy = useStore((s) => s.busy.mutation);
14
+ const [modelId, setModelId] = useState(models[0]?.model_id ?? '');
15
+ const [guarded, setGuarded] = useState(false);
16
+ const model = models.find((m) => m.model_id === (modelId || models[0]?.model_id));
17
+ if (!caps.create_session) return null;
18
+ if (models.length === 0) return <Empty title="No text model registered." detail="Register or train a text model with the CLI, then reload." command="uv run plastic --help" />;
19
+ return (
20
+ <Panel title="New session">
21
+ <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_auto_auto] sm:items-end">
22
+ <Field label="Model" htmlFor="new-model" hint={model ? `${backendLabel(model.backend)} · ${fmtInt(model.params)} params · ${model.calibrated ? 'calibrated' : 'no calibration'}` : undefined}>
23
+ <Select id="new-model" value={model?.model_id ?? ''} onChange={(e) => setModelId(e.target.value)}>
24
+ {models.map((m) => (
25
+ <option key={m.model_id} value={m.model_id}>
26
+ {m.model_id}
27
+ </option>
28
+ ))}
29
+ </Select>
30
+ </Field>
31
+ <Field label="Mode" htmlFor="new-mode" hint={guarded && !model?.calibrated ? 'session-relative thresholds (no calibration)' : undefined}>
32
+ <Select id="new-mode" value={guarded ? 'guarded' : 'observational'} onChange={(e) => setGuarded(e.target.value === 'guarded')}>
33
+ <option value="observational">observational</option>
34
+ <option value="guarded">guarded</option>
35
+ </Select>
36
+ </Field>
37
+ <div className="flex gap-2">
38
+ <Button tone="primary" disabled={busy || !model} onClick={() => model && void createSession(model.model_id, guarded)}>
39
+ Create
40
+ </Button>
41
+ {caps.calibrate && model ? (
42
+ <Button disabled={busy} onClick={() => void calibrate(model.model_id)} title="Fit thresholds on real chats with this model">
43
+ {model.calibrated ? 'Recalibrate' : 'Calibrate'}
44
+ </Button>
45
+ ) : null}
46
+ </div>
47
+ </div>
48
+ </Panel>
49
+ );
50
+ }
51
+
52
+ export function SessionsScreen() {
53
+ const sessions = useStore((s) => s.sessions).filter((s) => s.domain === 'text');
54
+ const models = useStore((s) => s.models);
55
+ const current = useStore((s) => s.currentSessionId);
56
+ const caps = useStore((s) => s.capabilities)();
57
+ const busy = useStore((s) => s.busy.mutation);
58
+ const selectSession = useStore((s) => s.selectSession);
59
+ const setTab = useStore((s) => s.setTab);
60
+ const reset = useStore((s) => s.resetSession);
61
+ const fork = useStore((s) => s.forkSession);
62
+ const del = useStore((s) => s.deleteSession);
63
+ const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
64
+
65
+ return (
66
+ <div className="space-y-4">
67
+ <CreateSession />
68
+ <Panel title="Text sessions" subtitle={`${sessions.length} session${sessions.length === 1 ? '' : 's'}`}>
69
+ {sessions.length === 0 ? (
70
+ <Empty title="No text sessions." detail={caps.create_session ? 'Create one above.' : 'None available in this deployment.'} />
71
+ ) : (
72
+ <ul role="list" className="divide-y divide-edge">
73
+ {sessions.map((s) => {
74
+ const model = models.find((m) => m.model_id === s.model_id);
75
+ const selected = s.session_id === current;
76
+ return (
77
+ <li key={s.session_id} className={`flex flex-wrap items-center gap-3 py-3 ${selected ? 'bg-accent-soft' : ''}`}>
78
+ <div className="min-w-0 flex-1">
79
+ <div className="flex flex-wrap items-center gap-2">
80
+ <span className="font-mono text-sm font-semibold text-ink-primary">{s.session_id}</span>
81
+ {selected ? <StateChip tone="accent">selected</StateChip> : null}
82
+ {s.read_only ? <StateChip tone="warn">read-only</StateChip> : null}
83
+ {s.parent_session_id ? <StateChip>fork of {s.parent_session_id}</StateChip> : null}
84
+ </div>
85
+ <p className="mt-0.5 text-xs text-ink-secondary">
86
+ {s.model_id} · {backendLabel(model?.backend)} · position {fmtInt(s.pos)} · {fmtInt(s.n_transactions)} chunks · {fmtInt(s.commits)} committed · {fmtInt(s.rollbacks)} rolled back · updated {ago(s.updated_at_unix)}
87
+ </p>
88
+ </div>
89
+ <div className="flex flex-wrap gap-2">
90
+ <Button onClick={() => { void selectSession(s.session_id); setTab('chat'); }}>Chat</Button>
91
+ <Button onClick={() => { void selectSession(s.session_id); setTab('signals'); }}>Signals</Button>
92
+ {caps.fork ? <Button disabled={busy} onClick={() => void fork(s.session_id)}>Fork</Button> : null}
93
+ {caps.reset ? <Button disabled={busy} onClick={() => void reset(s.session_id)}>Reset</Button> : null}
94
+ {caps.delete ? (
95
+ confirmDelete === s.session_id ? (
96
+ <>
97
+ <Button tone="danger" disabled={busy} onClick={() => { setConfirmDelete(null); void del(s.session_id); }}>Confirm delete</Button>
98
+ <Button onClick={() => setConfirmDelete(null)}>Cancel</Button>
99
+ </>
100
+ ) : (
101
+ <Button tone="danger" disabled={busy} onClick={() => setConfirmDelete(s.session_id)}>Delete</Button>
102
+ )
103
+ ) : null}
104
+ </div>
105
+ </li>
106
+ );
107
+ })}
108
+ </ul>
109
+ )}
110
+ </Panel>
111
+ </div>
112
+ );
113
+ }
dashboard/src/playground/signals/SignalsScreen.tsx ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react';
2
+ import { LineChartPanel } from '../../components/charts/LineChartPanel';
3
+ import { Empty } from '../../components/panels/Empty';
4
+ import { Panel, StatTile } from '../../components/panels/Panel';
5
+ import { DECISION_COLOR, DECISION_GLYPH, DECISION_LABEL, chunkSource, firedSignals, fmt, fmtInt, isFinite_, presentFields, wouldIntervene } from '../format';
6
+ import { useStore } from '../store';
7
+ import type { SessionState, TransactionRecord } from '../types';
8
+
9
+ const SERIES_A = '#58a6ff';
10
+ const SERIES_B = '#3fd17a';
11
+ const SERIES_C = '#f0b429';
12
+ const SERIES_D = '#c792ea';
13
+
14
+ interface ChartSpec {
15
+ field: string;
16
+ title: string;
17
+ color: string;
18
+ log?: boolean;
19
+ }
20
+
21
+ // Each chart appears only when the backend produced the field (any finite value in the records).
22
+ const CHARTS: ChartSpec[] = [
23
+ { field: 'chunk_loss', title: 'Chunk loss (nats/token)', color: SERIES_A },
24
+ { field: 'surprise_mean', title: 'Inner surprise (reconstruction error)', color: SERIES_D },
25
+ { field: 'beta_mean', title: 'Inner step size', color: SERIES_C, log: true },
26
+ { field: 'write_norm_sum', title: 'Write norm (sum over the chunk)', color: SERIES_B },
27
+ { field: 'canary_delta_coherence', title: 'Canary Δ coherence', color: SERIES_D },
28
+ { field: 'canary_alignment', title: 'Canary gradient alignment', color: SERIES_C },
29
+ ];
30
+
31
+ function rows(transactions: TransactionRecord[]) {
32
+ return transactions.map((tx) => {
33
+ const s = tx.signals as unknown as Record<string, unknown>;
34
+ const row: Record<string, number | null | string> = { chunk: tx.index };
35
+ for (const c of CHARTS) row[c.field] = isFinite_(s[c.field]) ? (s[c.field] as number) : null;
36
+ row.proposed = isFinite_(tx.signals.delta_norm) ? tx.signals.delta_norm : null;
37
+ row.accepted = isFinite_(tx.accepted?.delta_norm) ? tx.accepted.delta_norm : null;
38
+ return row;
39
+ });
40
+ }
41
+
42
+ function FastWeightPanel({ state }: { state: SessionState | null }) {
43
+ if (!state) return null;
44
+ if (state.kind === 'plastic' && state.layers) {
45
+ return (
46
+ <Panel title="Memory state" subtitle={`per layer · position ${fmtInt(state.pos)}`}>
47
+ <ul className="grid gap-2 sm:grid-cols-2">
48
+ {state.layers.map((l, i) => (
49
+ <li key={i} className="rounded border border-edge bg-surface-overlay px-3 py-2 font-mono text-xs text-ink-secondary">
50
+ <span className="text-ink-muted">layer {i}</span> · ‖S‖ {l.s_norm_per_head.map((v) => fmt(v, 2)).join(' ')} · ‖h‖ {fmt(l.h_norm, 2)} · drift {fmt(l.drift_from_anchor, 2)}
51
+ </li>
52
+ ))}
53
+ </ul>
54
+ </Panel>
55
+ );
56
+ }
57
+ const units = state.units ?? [];
58
+ if (units.length === 0) return null;
59
+ const label = state.kind === 'fast_weight' ? 'Fast weights' : 'Recurrent memory';
60
+ const per = state.kind === 'fast_weight' ? 4 : 1; // TTT reports W1, b1, W2, b2 per layer
61
+ const layers = Math.ceil(units.length / per);
62
+ const max = Math.max(1e-9, ...units.map((u) => u.recurrent_norm ?? 0));
63
+ return (
64
+ <Panel title={`${label} · ${units.length} units`} subtitle={`‖·‖ total ${fmt(state.recurrent_norm_total, 4)} · position ${fmtInt(state.pos)} · bar = norm, tick = drift from anchor`}>
65
+ <ol role="list" aria-label={`${label} norms per layer`} className="flex h-28 items-end gap-px">
66
+ {Array.from({ length: layers }, (_, l) => {
67
+ const group = units.slice(l * per, (l + 1) * per);
68
+ const norm = Math.sqrt(group.reduce((a, u) => a + (u.recurrent_norm ?? 0) ** 2, 0));
69
+ const drift = group.some((u) => u.drift_from_anchor === null) ? null : Math.sqrt(group.reduce((a, u) => a + (u.drift_from_anchor ?? 0) ** 2, 0));
70
+ const missing = group.some((u) => u.recurrent_norm === null);
71
+ const frac = Math.min(1, norm / (max * Math.sqrt(per)));
72
+ return (
73
+ <li
74
+ key={l}
75
+ title={`layer ${l}: norm ${fmt(norm)} · drift ${drift === null ? 'n/a' : fmt(drift)}`}
76
+ className="relative flex h-full flex-1 items-end"
77
+ aria-label={`layer ${l}: norm ${fmt(norm)}, drift ${drift === null ? 'unavailable' : fmt(drift)}`}
78
+ >
79
+ <div className="w-full rounded-sm" style={{ height: `${Math.max(3, Math.round(frac * 100))}%`, backgroundColor: missing ? '#48545f' : SERIES_A }} />
80
+ {drift !== null && norm > 0 ? (
81
+ // drift as a share of the layer's norm, drawn as a tick up the bar (clamped to the bar)
82
+ <div aria-hidden className="absolute inset-x-0 border-t-2 border-status-scale" style={{ bottom: `${Math.min(Math.max(3, Math.round(frac * 100)), Math.round((drift / norm) * frac * 100))}%` }} />
83
+ ) : null}
84
+ </li>
85
+ );
86
+ })}
87
+ </ol>
88
+ </Panel>
89
+ );
90
+ }
91
+
92
+ function ChunkTable({ transactions }: { transactions: TransactionRecord[] }) {
93
+ const [open, setOpen] = useState<number | null>(null);
94
+ const items = transactions.slice().sort((a, b) => b.index - a.index).slice(0, 60);
95
+ const hasSurprise = presentFields(transactions, ['surprise_mean']).length > 0;
96
+ const hasWrite = presentFields(transactions, ['write_norm_sum']).length > 0;
97
+ return (
98
+ <div className="overflow-x-auto">
99
+ <table className="w-full min-w-[720px] text-left font-mono text-xs">
100
+ <thead className="text-label uppercase tracking-wide text-ink-muted">
101
+ <tr>
102
+ <th className="py-1.5 pr-3">#</th>
103
+ <th className="py-1.5 pr-3">decision</th>
104
+ <th className="py-1.5 pr-3">src</th>
105
+ <th className="py-1.5 pr-3">tok</th>
106
+ <th className="py-1.5 pr-3">loss</th>
107
+ {hasSurprise ? <th className="py-1.5 pr-3">surprise</th> : null}
108
+ {hasWrite ? <th className="py-1.5 pr-3">write</th> : null}
109
+ <th className="py-1.5 pr-3">proposed Δ</th>
110
+ <th className="py-1.5 pr-3">accepted Δ</th>
111
+ <th className="py-1.5 pr-3">fired</th>
112
+ </tr>
113
+ </thead>
114
+ <tbody className="text-ink-primary">
115
+ {items.map((tx) => {
116
+ const would = wouldIntervene(tx);
117
+ const fired = firedSignals(tx);
118
+ const src = chunkSource(tx);
119
+ return (
120
+ <>
121
+ <tr key={tx.index} className="cursor-pointer border-t border-edge hover:bg-surface-overlay" onClick={() => setOpen(open === tx.index ? null : tx.index)}>
122
+ <td className="py-1.5 pr-3 text-ink-muted">{tx.index}</td>
123
+ <td className="py-1.5 pr-3">
124
+ <span style={{ color: DECISION_COLOR[tx.decision.kind] }}>{DECISION_GLYPH[tx.decision.kind]} {DECISION_LABEL[tx.decision.kind]}</span>
125
+ {would ? <span className="ml-2 text-ink-secondary">would {DECISION_LABEL[tx.requested.kind].toLowerCase()}</span> : null}
126
+ {tx.signals.cusum_alarm ? <span className="ml-2 text-status-scale">CUSUM</span> : null}
127
+ </td>
128
+ <td className="py-1.5 pr-3 text-ink-secondary">{src === 'prompt' ? '▲ prompt' : src === 'model' ? '● model' : src}</td>
129
+ <td className="py-1.5 pr-3">{tx.signals.n_tokens}</td>
130
+ <td className="py-1.5 pr-3">{fmt(tx.signals.chunk_loss)}</td>
131
+ {hasSurprise ? <td className="py-1.5 pr-3">{fmt(tx.signals.surprise_mean)}</td> : null}
132
+ {hasWrite ? <td className="py-1.5 pr-3">{fmt(tx.signals.write_norm_sum)}</td> : null}
133
+ <td className="py-1.5 pr-3">{fmt(tx.signals.delta_norm)}</td>
134
+ <td className="py-1.5 pr-3">{fmt(tx.accepted?.delta_norm)}</td>
135
+ <td className="py-1.5 pr-3 text-ink-secondary">{fired.length ? fired.join(', ') : '—'}</td>
136
+ </tr>
137
+ {open === tx.index ? (
138
+ <tr key={`${tx.index}-detail`} className="border-t border-edge bg-surface-inset">
139
+ <td colSpan={10} className="px-3 py-2 text-ink-secondary">
140
+ <div className="grid gap-x-6 gap-y-1 sm:grid-cols-2 lg:grid-cols-3">
141
+ <div>z: {Object.entries(tx.signals.z ?? {}).filter(([, v]) => isFinite_(v)).map(([k, v]) => `${k} ${fmt(v, 2)}`).join(' · ') || 'none'}</div>
142
+ <div>reasons: {tx.decision.reasons.join('; ') || '—'}</div>
143
+ <div>requested: {tx.requested.reasons.join('; ') || '—'}</div>
144
+ <div>eligible: {tx.eligible === undefined ? 'n/a' : String(tx.eligible)} · read-only: {String(tx.read_only)}{tx.read_only_reason ? ` (${tx.read_only_reason})` : ''}</div>
145
+ <div>budget: used {fmt(tx.signals.budget_used)} · remaining {tx.signals.budget_remaining === null ? 'uncapped' : fmt(tx.signals.budget_remaining)}</div>
146
+ <div>positions {tx.pos_start}–{tx.pos_end} · {fmt(tx.seconds, 2)} s</div>
147
+ {isFinite_(tx.signals.canary_delta_coherence) ? <div>canary Δcoherence {fmt(tx.signals.canary_delta_coherence)} · Δpoison {fmt(tx.signals.canary_delta_poison)} · alignment {fmt(tx.signals.canary_alignment)}</div> : null}
148
+ {isFinite_(tx.signals.beta_mean) ? <div>step {fmt(tx.signals.beta_mean)} · alpha {fmt(tx.signals.alpha_mean)}</div> : null}
149
+ </div>
150
+ </td>
151
+ </tr>
152
+ ) : null}
153
+ </>
154
+ );
155
+ })}
156
+ </tbody>
157
+ </table>
158
+ </div>
159
+ );
160
+ }
161
+
162
+ export function SignalsScreen() {
163
+ const detail = useStore((s) => s.detail);
164
+ const transactions = useStore((s) => s.transactions);
165
+ const state = useStore((s) => s.state);
166
+ const stale = useStore((s) => s.stale);
167
+ if (!detail) return <Empty title="No text session selected." detail="Choose a session above, or create one under Sessions." />;
168
+ if (transactions.length === 0) return <Empty title="No chunks yet." detail="Send a message in Chat; every chunk it produces is measured here." />;
169
+ const data = rows(transactions);
170
+ const present = new Set(presentFields(transactions, CHARTS.map((c) => c.field)));
171
+ const s = detail.summary;
172
+ const meta = detail.meta;
173
+ return (
174
+ <div className="space-y-4">
175
+ {stale ? <p role="status" className="text-xs text-status-scale">Showing the last data received; the connection failed since.</p> : null}
176
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
177
+ <StatTile label="Position" value={fmtInt(s.pos)} />
178
+ <StatTile label="Chunks" value={fmtInt(s.n_transactions)} />
179
+ <StatTile label="Committed" value={fmtInt(meta.commits)} tone="commit" />
180
+ <StatTile label="Rolled back" value={fmtInt(meta.rollbacks)} tone={meta.rollbacks > 0 ? 'rollback' : 'default'} />
181
+ <StatTile label="Scaled / projected / read-only" value={`${fmtInt(meta.scales)} / ${fmtInt(meta.projects)} / ${fmtInt(meta.readonly)}`} />
182
+ </div>
183
+ <Panel title="Fast-weight change" subtitle="proposed (measured before the decision) and accepted (measured after it), effective coordinates">
184
+ <LineChartPanel
185
+ data={data}
186
+ xKey="chunk"
187
+ series={[
188
+ { key: 'proposed', label: 'Proposed Δ', color: SERIES_C },
189
+ { key: 'accepted', label: 'Accepted Δ', color: SERIES_B },
190
+ ]}
191
+ xLabel="chunk"
192
+ ariaLabel="Proposed and accepted fast-weight change per chunk"
193
+ />
194
+ </Panel>
195
+ <div className="grid gap-4 lg:grid-cols-2">
196
+ {CHARTS.filter((c) => present.has(c.field)).map((c) => (
197
+ <Panel key={c.field} title={c.title}>
198
+ <LineChartPanel data={data} xKey="chunk" series={[{ key: c.field, label: c.title, color: c.color }]} logScale={c.log} xLabel="chunk" showLegend={false} ariaLabel={`${c.title} per chunk`} />
199
+ </Panel>
200
+ ))}
201
+ </div>
202
+ <FastWeightPanel state={state} />
203
+ <Panel title="Chunks" subtitle="newest first · click a row for z-scores, reasons, budget and canaries">
204
+ <ChunkTable transactions={transactions} />
205
+ </Panel>
206
+ </div>
207
+ );
208
+ }
dashboard/src/playground/store.ts ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // One store, three concerns: what the server allows, which session is open, and what it produced.
2
+ // Components read slices and call actions; nothing else talks to the API.
3
+
4
+ import { create } from 'zustand';
5
+ import * as api from './client';
6
+ import { ApiError } from './client';
7
+ import type {
8
+ Capabilities,
9
+ ChatResult,
10
+ Health,
11
+ ModelSummary,
12
+ Sampling,
13
+ SessionDetail,
14
+ SessionState,
15
+ SessionSummary,
16
+ TransactionRecord,
17
+ } from './types';
18
+
19
+ export const TABS = ['chat', 'signals', 'sessions'] as const;
20
+ export type Tab = (typeof TABS)[number];
21
+ export const TAB_LABELS: Record<Tab, string> = { chat: 'Chat', signals: 'Signals', sessions: 'Sessions' };
22
+
23
+ const NO_CAPABILITIES: Capabilities = { create_session: false, fork: false, reset: false, delete: false, resume: false, calibrate: false };
24
+
25
+ export interface PlaygroundState {
26
+ health: Health | null;
27
+ healthChecked: boolean;
28
+ models: ModelSummary[];
29
+ sessions: SessionSummary[];
30
+ currentSessionId: string | null;
31
+ detail: SessionDetail | null;
32
+ transactions: TransactionRecord[];
33
+ state: SessionState | null;
34
+ lastChat: ChatResult | null;
35
+ /** True after a request failed since the last successful refresh: data shown may be stale. */
36
+ stale: boolean;
37
+ sampling: Sampling;
38
+ tab: Tab;
39
+ busy: { chat: boolean; session: boolean; mutation: boolean };
40
+ error: string | null;
41
+
42
+ capabilities: () => Capabilities;
43
+ setTab: (tab: Tab) => void;
44
+ setSampling: (patch: Partial<Sampling>) => void;
45
+ clearError: () => void;
46
+ bootstrap: () => Promise<void>;
47
+ refreshSessions: () => Promise<void>;
48
+ selectSession: (sessionId: string | null) => Promise<void>;
49
+ reloadCurrent: () => Promise<void>;
50
+ sendChat: (prompt: string) => Promise<void>;
51
+ createSession: (modelId: string, guarded: boolean) => Promise<string | null>;
52
+ resetSession: (sessionId: string) => Promise<void>;
53
+ resumeSession: (sessionId: string) => Promise<void>;
54
+ forkSession: (sessionId: string) => Promise<string | null>;
55
+ deleteSession: (sessionId: string) => Promise<void>;
56
+ calibrate: (modelId: string) => Promise<void>;
57
+ }
58
+
59
+ function message(err: unknown): string {
60
+ if (err instanceof ApiError) return err.status === 0 ? `Connection failed: ${err.message}` : err.message;
61
+ return err instanceof Error ? err.message : String(err);
62
+ }
63
+
64
+ export const useStore = create<PlaygroundState>((set, get) => ({
65
+ health: null,
66
+ healthChecked: false,
67
+ models: [],
68
+ sessions: [],
69
+ currentSessionId: null,
70
+ detail: null,
71
+ transactions: [],
72
+ state: null,
73
+ lastChat: null,
74
+ stale: false,
75
+ sampling: { max_new_tokens: 96, temperature: 0.8, top_k: 40, seed: null },
76
+ tab: 'chat',
77
+ busy: { chat: false, session: false, mutation: false },
78
+ error: null,
79
+
80
+ capabilities: () => get().health?.capabilities ?? NO_CAPABILITIES,
81
+ setTab: (tab) => set({ tab }),
82
+ setSampling: (patch) => set({ sampling: { ...get().sampling, ...patch } }),
83
+ clearError: () => set({ error: null }),
84
+
85
+ bootstrap: async () => {
86
+ try {
87
+ const [health, models, sessions] = await Promise.all([api.getHealth(), api.getModels(), api.getSessions()]);
88
+ set({ health, models, sessions, healthChecked: true, stale: false, error: null });
89
+ const text = sessions.filter((s) => s.domain === 'text');
90
+ const current = get().currentSessionId;
91
+ const pick = current && text.some((s) => s.session_id === current) ? current : text[0]?.session_id ?? null;
92
+ await get().selectSession(pick);
93
+ } catch (err) {
94
+ set({ healthChecked: true, stale: true, error: message(err) });
95
+ }
96
+ },
97
+
98
+ refreshSessions: async () => {
99
+ try {
100
+ const sessions = await api.getSessions();
101
+ set({ sessions, stale: false });
102
+ } catch (err) {
103
+ set({ stale: true, error: message(err) });
104
+ }
105
+ },
106
+
107
+ selectSession: async (sessionId) => {
108
+ set({ currentSessionId: sessionId, detail: null, transactions: [], state: null, lastChat: null });
109
+ if (!sessionId) return;
110
+ await get().reloadCurrent();
111
+ },
112
+
113
+ reloadCurrent: async () => {
114
+ const id = get().currentSessionId;
115
+ if (!id) return;
116
+ set({ busy: { ...get().busy, session: true } });
117
+ try {
118
+ const [detail, page, state] = await Promise.all([api.getSession(id), api.getTransactions(id), api.getSessionState(id)]);
119
+ if (get().currentSessionId !== id) return;
120
+ set({ detail, transactions: page.items, state, stale: false, error: null });
121
+ } catch (err) {
122
+ set({ stale: true, error: message(err) });
123
+ } finally {
124
+ set({ busy: { ...get().busy, session: false } });
125
+ }
126
+ },
127
+
128
+ sendChat: async (prompt) => {
129
+ const id = get().currentSessionId;
130
+ if (!id || !prompt.trim()) return;
131
+ set({ busy: { ...get().busy, chat: true }, error: null });
132
+ try {
133
+ const result = await api.chat(id, prompt, get().sampling);
134
+ set({ lastChat: result });
135
+ await Promise.all([get().reloadCurrent(), get().refreshSessions()]);
136
+ } catch (err) {
137
+ set({ stale: true, error: message(err) });
138
+ } finally {
139
+ set({ busy: { ...get().busy, chat: false } });
140
+ }
141
+ },
142
+
143
+ createSession: async (modelId, guarded) => {
144
+ set({ busy: { ...get().busy, mutation: true }, error: null });
145
+ try {
146
+ const created = await api.createSession({ model_id: modelId, harness: guarded ? { log_only: false } : { log_only: true, freeze_on_alarm: false } });
147
+ await get().refreshSessions();
148
+ await get().selectSession(created.session_id);
149
+ set({ tab: 'chat' });
150
+ return created.session_id;
151
+ } catch (err) {
152
+ set({ error: message(err) });
153
+ return null;
154
+ } finally {
155
+ set({ busy: { ...get().busy, mutation: false } });
156
+ }
157
+ },
158
+
159
+ resetSession: async (sessionId) => {
160
+ set({ busy: { ...get().busy, mutation: true }, error: null });
161
+ try {
162
+ await api.resetSession(sessionId);
163
+ await get().refreshSessions();
164
+ if (get().currentSessionId === sessionId) await get().selectSession(sessionId);
165
+ } catch (err) {
166
+ set({ error: message(err) });
167
+ } finally {
168
+ set({ busy: { ...get().busy, mutation: false } });
169
+ }
170
+ },
171
+
172
+ resumeSession: async (sessionId) => {
173
+ set({ busy: { ...get().busy, mutation: true }, error: null });
174
+ try {
175
+ await api.resumeSession(sessionId);
176
+ await get().refreshSessions();
177
+ if (get().currentSessionId === sessionId) await get().reloadCurrent();
178
+ } catch (err) {
179
+ set({ error: message(err) });
180
+ } finally {
181
+ set({ busy: { ...get().busy, mutation: false } });
182
+ }
183
+ },
184
+
185
+ forkSession: async (sessionId) => {
186
+ set({ busy: { ...get().busy, mutation: true }, error: null });
187
+ try {
188
+ const child = await api.forkSession(sessionId);
189
+ await get().refreshSessions();
190
+ await get().selectSession(child.session_id);
191
+ return child.session_id;
192
+ } catch (err) {
193
+ set({ error: message(err) });
194
+ return null;
195
+ } finally {
196
+ set({ busy: { ...get().busy, mutation: false } });
197
+ }
198
+ },
199
+
200
+ deleteSession: async (sessionId) => {
201
+ set({ busy: { ...get().busy, mutation: true }, error: null });
202
+ try {
203
+ await api.deleteSession(sessionId);
204
+ const sessions = await api.getSessions();
205
+ set({ sessions });
206
+ if (get().currentSessionId === sessionId) {
207
+ const next = sessions.find((s) => s.domain === 'text')?.session_id ?? null;
208
+ await get().selectSession(next);
209
+ }
210
+ } catch (err) {
211
+ set({ error: message(err) });
212
+ } finally {
213
+ set({ busy: { ...get().busy, mutation: false } });
214
+ }
215
+ },
216
+
217
+ calibrate: async (modelId) => {
218
+ set({ busy: { ...get().busy, mutation: true }, error: null });
219
+ try {
220
+ await api.calibrateModel(modelId);
221
+ const models = await api.getModels();
222
+ set({ models });
223
+ if (get().currentSessionId) await get().reloadCurrent();
224
+ } catch (err) {
225
+ set({ error: message(err) });
226
+ } finally {
227
+ set({ busy: { ...get().busy, mutation: false } });
228
+ }
229
+ },
230
+ }));
dashboard/src/playground/types.ts ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Types for the playground API. Every shape mirrors a Python `to_dict()` in plastic/api; fields that
2
+ // Python may emit as None or a non-finite float are `number | null` and are guarded before rendering.
3
+ // A missing field means the backend never produces that quantity: the UI omits the panel, never shows 0.
4
+
5
+ export type DecisionKind = 'commit' | 'rollback' | 'scale' | 'project' | 'readonly';
6
+
7
+ export interface Capabilities {
8
+ create_session: boolean;
9
+ fork: boolean;
10
+ reset: boolean;
11
+ delete: boolean;
12
+ resume: boolean;
13
+ calibrate: boolean;
14
+ }
15
+
16
+ export interface Health {
17
+ ok: boolean;
18
+ artifacts_root: string;
19
+ device: string;
20
+ n_models: number;
21
+ n_sessions: number;
22
+ capabilities: Capabilities;
23
+ public: boolean;
24
+ }
25
+
26
+ export interface ModelSummary {
27
+ model_id: string;
28
+ backend?: string; // 'ttt' | 'qwen' | 'plastic'; absent on old records means plastic
29
+ domain: 'text' | 'physics';
30
+ status: string;
31
+ params: number;
32
+ calibrated: boolean;
33
+ has_canary: boolean;
34
+ created_at_unix: number;
35
+ updated_at_unix: number;
36
+ eval?: { heldout_loss?: number | null; memory_value?: number | null } | null;
37
+ /** Set on a chat-tuned checkpoint's record; absent on a base model. */
38
+ chat_tuned?: boolean | null;
39
+ }
40
+
41
+ export interface Decision {
42
+ kind: DecisionKind;
43
+ reasons: string[];
44
+ scale: number;
45
+ }
46
+
47
+ /** PROPOSED: measured on the provisional state before the decision. */
48
+ export interface ChunkSignals {
49
+ pos_start: number;
50
+ pos_end: number;
51
+ n_tokens: number;
52
+ chunk_loss: number | null;
53
+ surprise_mean?: number | null;
54
+ surprise_max?: number | null;
55
+ beta_mean?: number | null;
56
+ alpha_mean?: number | null;
57
+ write_norm_sum?: number | null;
58
+ delta_norm: number;
59
+ fisher_update?: number | null;
60
+ fisher_drift?: number | null;
61
+ canary_delta_coherence?: number | null;
62
+ canary_delta_poison?: number | null;
63
+ canary_alignment?: number | null;
64
+ z: Record<string, number | null>;
65
+ cusum_alarm: boolean;
66
+ budget_used: number;
67
+ budget_remaining: number | null;
68
+ log_delta_norm: number | null;
69
+ log_write_norm?: number | null;
70
+ }
71
+
72
+ /** ACCEPTED: measured on the committed state after the decision. */
73
+ export interface AcceptedMetrics {
74
+ delta_norm: number;
75
+ budget_charge: number;
76
+ budget_used: number;
77
+ budget_remaining: number | null;
78
+ canary_delta_coherence?: number | null;
79
+ canary_delta_poison?: number | null;
80
+ }
81
+
82
+ export interface TransactionRecord {
83
+ index: number;
84
+ t_unix: number;
85
+ pos_start: number;
86
+ pos_end: number;
87
+ /** What was applied. */
88
+ decision: Decision;
89
+ /** What the policy asked for; in observational mode this carries the would-have decision. */
90
+ requested: Decision;
91
+ signals: ChunkSignals;
92
+ accepted: AcceptedMetrics;
93
+ sources?: { user: number; model: number };
94
+ eligible?: boolean;
95
+ read_only: boolean;
96
+ read_only_reason: string | null;
97
+ seconds: number;
98
+ }
99
+
100
+ export interface CusumState {
101
+ k: number;
102
+ h: number;
103
+ s_hi: number;
104
+ s_lo: number;
105
+ alarms: number;
106
+ }
107
+
108
+ export type CalibrationStatus = 'installed' | 'absent' | 'rejected_unsigned' | 'rejected_signature_mismatch';
109
+
110
+ export interface RunnerSummary {
111
+ pos: number;
112
+ pending: number;
113
+ budget_used: number;
114
+ budget_session: number | null;
115
+ read_only: boolean;
116
+ read_only_reason: string | null;
117
+ n_transactions: number;
118
+ cusum: CusumState;
119
+ state_norms: Record<string, number | number[] | undefined>;
120
+ drift_from_anchor: number;
121
+ session_id?: string;
122
+ model_id?: string;
123
+ backend?: string;
124
+ calibration?: CalibrationStatus;
125
+ signals_available?: string[];
126
+ writes_generation?: boolean;
127
+ }
128
+
129
+ export interface HarnessConfig {
130
+ log_only: boolean;
131
+ enable_rollback: boolean;
132
+ enable_stats: boolean;
133
+ enable_projection: boolean;
134
+ enable_budget: boolean;
135
+ freeze_on_alarm: boolean;
136
+ alarm_cooldown?: number;
137
+ learn_from_generation: boolean;
138
+ budget_session: number | null;
139
+ target_fpr: number;
140
+ [key: string]: unknown;
141
+ }
142
+
143
+ export interface SessionSummary {
144
+ session_id: string;
145
+ model_id: string;
146
+ domain: 'text' | 'physics';
147
+ parent_session_id: string | null;
148
+ created_at_unix: number;
149
+ updated_at_unix: number;
150
+ pos: number;
151
+ n_transactions: number;
152
+ commits: number;
153
+ rollbacks: number;
154
+ scales: number;
155
+ projects: number;
156
+ readonly: number;
157
+ read_only: boolean;
158
+ read_only_reason: string | null;
159
+ }
160
+
161
+ export interface SessionMeta extends SessionSummary {
162
+ harness: HarnessConfig;
163
+ }
164
+
165
+ export interface TraceRecord {
166
+ t_unix: number;
167
+ kind: 'chat' | 'episode';
168
+ prompt?: string | null;
169
+ completion?: string | null;
170
+ pos_end: number;
171
+ n_transactions: number;
172
+ }
173
+
174
+ export interface CalibrationSummary {
175
+ n_chunks: number;
176
+ thresholds: Record<string, number | null>;
177
+ achievable_fpr: Record<string, number | null>;
178
+ target_fpr: number;
179
+ created_at_unix: number;
180
+ }
181
+
182
+ export interface SessionDetail {
183
+ meta: SessionMeta;
184
+ summary: RunnerSummary;
185
+ calibration: CalibrationSummary | null;
186
+ lineage: string[];
187
+ transactions: TransactionRecord[];
188
+ trace: TraceRecord[];
189
+ }
190
+
191
+ export interface TransactionPage {
192
+ total: number;
193
+ items: TransactionRecord[];
194
+ }
195
+
196
+ export interface MemoryUnit {
197
+ index: number;
198
+ recurrent_norm: number | null;
199
+ drift_from_anchor: number | null;
200
+ }
201
+
202
+ export interface PlasticLayer {
203
+ s_norm_per_head: number[];
204
+ h_norm: number;
205
+ drift_from_anchor: number;
206
+ }
207
+
208
+ export interface SessionState {
209
+ kind?: 'plastic' | 'recurrent' | 'fast_weight';
210
+ pos: number;
211
+ backend?: string;
212
+ layers?: PlasticLayer[];
213
+ units?: MemoryUnit[];
214
+ recurrent_norm_total?: number | null;
215
+ }
216
+
217
+ export interface ChatResult {
218
+ prompt: string;
219
+ completion: string;
220
+ transactions: TransactionRecord[];
221
+ n_tokens_in: number;
222
+ n_tokens_out: number;
223
+ summary: RunnerSummary;
224
+ }
225
+
226
+ export interface Sampling {
227
+ max_new_tokens: number;
228
+ temperature: number;
229
+ top_k: number;
230
+ seed: number | null;
231
+ }
232
+
233
+ /** One chat exchange with the chunks it produced. */
234
+ export interface Turn {
235
+ index: number;
236
+ prompt: string;
237
+ completion: string;
238
+ t_unix: number;
239
+ pos_end: number;
240
+ chunks: TransactionRecord[];
241
+ }
dashboard/src/playground/ui.tsx ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Small controls with the legibility floor baked in: nothing under 11px, solid backgrounds, visible focus.
2
+
3
+ import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from 'react';
4
+
5
+ type Tone = 'default' | 'primary' | 'danger';
6
+
7
+ export function Button({ tone = 'default', className = '', ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { tone?: Tone }) {
8
+ const tones: Record<Tone, string> = {
9
+ default: 'border-edge-strong bg-surface-overlay text-ink-primary hover:border-accent',
10
+ primary: 'border-accent bg-accent text-ink-inverse hover:bg-accent-hover',
11
+ danger: 'border-status-rollback bg-surface-overlay text-status-rollback hover:bg-statusFill-rollback hover:text-ink-primary',
12
+ };
13
+ return (
14
+ <button
15
+ type="button"
16
+ className={`rounded border px-3 py-1.5 text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:border-edge disabled:text-ink-muted ${tones[tone]} ${className}`}
17
+ {...props}
18
+ />
19
+ );
20
+ }
21
+
22
+ export function Field({ label, htmlFor, children, hint }: { label: string; htmlFor: string; children: ReactNode; hint?: string }) {
23
+ return (
24
+ <div className="min-w-0">
25
+ <label htmlFor={htmlFor} className="block text-label font-semibold uppercase tracking-wide text-ink-muted">
26
+ {label}
27
+ </label>
28
+ <div className="mt-1">{children}</div>
29
+ {hint ? <p className="mt-1 text-micro text-ink-muted">{hint}</p> : null}
30
+ </div>
31
+ );
32
+ }
33
+
34
+ const inputClass =
35
+ 'w-full rounded border border-edge-strong bg-surface-overlay px-2.5 py-1.5 font-mono text-sm text-ink-primary focus:border-accent focus:outline-none disabled:text-ink-muted';
36
+
37
+ export function NumberInput(props: InputHTMLAttributes<HTMLInputElement>) {
38
+ return <input type="number" className={inputClass} {...props} />;
39
+ }
40
+
41
+ export function Select(props: SelectHTMLAttributes<HTMLSelectElement>) {
42
+ return <select className={inputClass} {...props} />;
43
+ }
44
+
45
+ export function ErrorBanner({ message, onDismiss }: { message: string; onDismiss: () => void }) {
46
+ return (
47
+ <div role="alert" className="flex items-start justify-between gap-4 rounded border border-status-rollback bg-surface-raised px-4 py-3">
48
+ <p className="text-sm text-ink-primary">{message}</p>
49
+ <Button onClick={onDismiss} className="shrink-0">Dismiss</Button>
50
+ </div>
51
+ );
52
+ }
53
+
54
+ /** A one-line state label: what the session IS right now. Never an explanation. */
55
+ export function StateChip({ children, tone = 'default' }: { children: ReactNode; tone?: 'default' | 'accent' | 'warn' | 'bad' }) {
56
+ const tones = {
57
+ default: 'border-edge-strong text-ink-secondary',
58
+ accent: 'border-accent text-accent',
59
+ warn: 'border-status-scale text-status-scale',
60
+ bad: 'border-status-rollback text-status-rollback',
61
+ } as const;
62
+ return <span className={`inline-flex items-center rounded border bg-surface-overlay px-2 py-0.5 text-xs font-semibold ${tones[tone]}`}>{children}</span>;
63
+ }
plastic/api/service.py CHANGED
@@ -91,6 +91,8 @@ def model_summary(store: ArtifactStore, rec: dict[str, Any]) -> dict[str, Any]:
91
  "parent_model_id": rec.get("parent_model_id"),
92
  "type": rec.get("type"),
93
  "sleep": rec.get("sleep"),
 
 
94
  }
95
 
96
 
 
91
  "parent_model_id": rec.get("parent_model_id"),
92
  "type": rec.get("type"),
93
  "sleep": rec.get("sleep"),
94
+ # set on a chat-tuned checkpoint's record; None when the record does not say (the UI then shows nothing)
95
+ "chat_tuned": rec.get("chat_tuned"),
96
  }
97
 
98
 
source_snapshot.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "github_repository": "DMontgomery40/plastic",
3
- "github_commit": "c1af60659d7d70e3535caa26c232f59809781953",
4
- "preserved_hf_revision": "3194e65dd1be7dcd70204ab41db0ee3da84b2f50",
5
  "repo_type": "space"
6
  }
 
1
  {
2
  "github_repository": "DMontgomery40/plastic",
3
+ "github_commit": "41a59ccc44d488a4418d9242aa05083594ce6015",
4
+ "preserved_hf_revision": "89d951690f5e92da390f6ad0b7e7b145fd477430",
5
  "repo_type": "space"
6
  }