The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(neuron): Neurons for beginners: four steps, an introduction, coordinates
purplea0622f5c4058
diff --git a/src/components/neuron/NeuronIntro.tsx b/src/components/neuron/NeuronIntro.tsxnew file mode 100644index 00000000..78ff457f--- /dev/null+++ b/src/components/neuron/NeuronIntro.tsx@@ -0,0 +1,254 @@+// The Neurons introduction (N2, 3.0.9). David, 31.10.2026: once, on the+// first click on Neurons, explain how it works and what it can do, "with+// nice graphics, nicely animated". Five short cards, skippable, and back+// any time from the "How it works" button on the page or the command+// palette. The drawings are plain SVG and CSS; with reduced motion they+// stand still and the cards switch without sliding.++import { useEffect, useState } from 'react'+import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'+import { ArrowLeft, ArrowRight, FlaskConical, Hash, Sliders, Sparkles } from 'lucide-react'+import { Modal } from '../ui/Modal'+import { MOTION_S } from '../ui/motion'+import { HINWEIS_TEXT } from '../../lib/hinweis'+import { ICON_SM } from '../ui/icon-size'+import { useNeuronStore } from '../../stores/neuronStore'+import { useNeuronIntroRequest } from '../../stores/neuronIntroStore'+++interface Card {+ title: string+ text: string+ art: () => React.ReactElement+}++/** Layers with words flowing up, and a push added in the middle. */+function ArtLayers() {+ const layers = [0, 1, 2, 3, 4, 5]+ return (+ <svg viewBox="0 0 320 168" className="w-full h-full" aria-hidden>+ {layers.map((i) => (+ <rect key={i} x="70" y={142 - i * 24} width="130" height="14" rx="5" className={i === 2 || i === 3 ? 'nintro-layer nintro-layer--hit' : 'nintro-layer'} style={{ animationDelay: `${i * 0.25}s` }} />+ ))}+ {[0, 1, 2].map((i) => (+ <circle key={i} cx={105 + i * 30} cy="160" r="4" className="nintro-token" style={{ animationDelay: `${i * 0.7}s` }} />+ ))}+ <g className="nintro-push">+ <path d="M290 88 C 255 88, 240 98, 210 100" fill="none" strokeWidth="2.5" strokeLinecap="round" className="nintro-accent-stroke" />+ <path d="M216 94 L206 100 L216 106" fill="none" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="nintro-accent-stroke" />+ <rect x="248" y="58" width="58" height="20" rx="10" className="nintro-accent-fill-soft" />+ <text x="277" y="72" textAnchor="middle" className="nintro-label nintro-accent-text">push</text>+ </g>+ <text x="135" y="18" textAnchor="middle" className="nintro-label nintro-muted-text">answer</text>+ <text x="40" y="153" textAnchor="middle" className="nintro-label nintro-muted-text">words</text>+ <text x="40" y="105" textAnchor="middle" className="nintro-label nintro-muted-text">layers</text>+ </svg>+ )+}++/** Equalizer: five sliders that settle at different heights. */+function ArtEqualizer() {+ const bars = ['Creative', 'Detailed', 'Casual', 'Cheerful', 'Yours']+ return (+ <svg viewBox="0 0 320 168" className="w-full h-full" aria-hidden>+ {bars.map((b, i) => {+ const x = 48 + i * 56+ return (+ <g key={b}>+ <line x1={x} y1="24" x2={x} y2="128" strokeWidth="4" strokeLinecap="round" className="nintro-track" />+ <line x1={x - 9} y1="76" x2={x + 9} y2="76" strokeWidth="1.5" className="nintro-track" />+ <g className="nintro-knob" style={{ animationDelay: `${i * 0.35}s`, ['--nintro-to' as string]: `${[-30, 18, -12, -38, 26][i]}px` }}>+ <rect x={x - 13} y="68" width="26" height="16" rx="5" className={i === 4 ? 'nintro-accent-fill' : 'nintro-knob-fill'} />+ </g>+ <text x={x} y="150" textAnchor="middle" className="nintro-label nintro-muted-text">{b}</text>+ </g>+ )+ })}+ <text x="12" y="30" className="nintro-label nintro-muted-text">more</text>+ <text x="12" y="128" className="nintro-label nintro-muted-text">less</text>+ </svg>+ )+}++/** Before and after: the same question, two answers being written. */+function ArtCompare() {+ return (+ <svg viewBox="0 0 320 168" className="w-full h-full" aria-hidden>+ <rect x="16" y="20" width="136" height="128" rx="12" className="nintro-card" />+ <rect x="168" y="20" width="136" height="128" rx="12" className="nintro-card nintro-card--accent" />+ <text x="32" y="42" className="nintro-label nintro-muted-text">BEFORE</text>+ <text x="184" y="42" className="nintro-label nintro-accent-text">AFTER</text>+ {[0, 1, 2, 3].map((i) => (+ <rect key={`b${i}`} x="32" y={58 + i * 18} width={[104, 92, 100, 60][i]} height="7" rx="3.5" className="nintro-line" style={{ animationDelay: `${i * 0.3}s` }} />+ ))}+ {[0, 1, 2, 3].map((i) => (+ <rect key={`a${i}`} x="184" y={58 + i * 18} width={[96, 104, 84, 70][i]} height="7" rx="3.5" className="nintro-line nintro-line--accent" style={{ animationDelay: `${1.3 + i * 0.3}s` }} />+ ))}+ </svg>+ )+}++/** Coordinates: a code being typed, copied, and pasted elsewhere. */+function ArtShare() {+ return (+ <svg viewBox="0 0 320 168" className="w-full h-full" aria-hidden>+ <text x="16" y="22" className="nintro-label nintro-muted-text">layer · neuron · strength</text>+ <rect x="16" y="32" width="250" height="34" rx="10" className="nintro-card" />+ <g className="nintro-type">+ <text x="30" y="54" className="nintro-code">L14N8949+1.0 @cheerful+0.5</text>+ </g>+ <rect x="16" y="32" width="250" height="34" rx="10" fill="none" strokeWidth="1.5" className="nintro-accent-stroke nintro-glow" />+ <path d="M150 72 C 160 100, 190 112, 214 118" fill="none" strokeWidth="2" strokeDasharray="4 5" className="nintro-accent-stroke nintro-dash" />+ <rect x="216" y="98" width="88" height="48" rx="10" className="nintro-card nintro-card--accent nintro-arrive" />+ <text x="260" y="119" textAnchor="middle" className="nintro-label nintro-accent-text nintro-arrive">pasted</text>+ <text x="260" y="134" textAnchor="middle" className="nintro-label nintro-muted-text nintro-arrive">same mix</text>+ </svg>+ )+}++/** The four ways, as tiles that come in one after the other. */+function ArtWays() {+ const ways = [+ { icon: <Sliders size={18} />, name: 'Ready-made', line: 'Five sliders, any model' },+ { icon: <Sparkles size={18} />, name: 'From examples', line: 'Write lines, get a slider' },+ { icon: <FlaskConical size={18} />, name: 'Features', line: 'Search what a model knows' },+ { icon: <Hash size={18} />, name: 'Coordinates', line: 'Paste what others share' },+ ]+ return (+ <div className="grid grid-cols-2 gap-2.5 w-full px-2" aria-hidden>+ {ways.map((w, i) => (+ <div key={w.name} className="nintro-tile rounded-xl border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-white/[0.03] px-3 py-2.5" style={{ animationDelay: `${i * 0.18}s` }}>+ <div className="flex items-center gap-2 text-lu-accent">{w.icon}<span className="t-body font-medium text-gray-900 dark:text-white">{w.name}</span></div>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1`}>{w.line}</p>+ </div>+ ))}+ </div>+ )+}++export const INTRO_CARDS: Card[] = [+ {+ title: 'Change how your model answers, from the inside',+ text: 'A model passes your words through many layers. Neurons adds a small push to some of them. That changes the tone and style of every answer, without touching your prompt.',+ art: ArtLayers,+ },+ {+ title: 'Sliders, like an equalizer',+ text: 'Each slider is one trait. Right for more, left for less. At 0 the model is exactly as before, so you can always go back.',+ art: ArtEqualizer,+ },+ {+ title: 'Four ways to get a slider',+ text: 'Start with a ready-made one. Make your own from a few example lines. Search the features of a model that has them. Or paste coordinates someone shared.',+ art: ArtWays,+ },+ {+ title: 'See the difference',+ text: 'Compare asks the same question twice, with the sliders off and on, and shows both answers side by side.',+ art: ArtCompare,+ },+ {+ title: 'Share your mix as coordinates',+ text: 'Copy your sliders as one short line or a link. Paste lines from others under Coordinates. LU reads only numbers and example sentences from them, never files or commands.',+ art: ArtShare,+ },+]++export function NeuronIntro({ open, onClose }: { open: boolean; onClose: () => void }) {+ // The Modal mounts its content only while open, so every showing starts+ // on the first card.+ return (+ <Modal open={open} onClose={onClose} title="" ariaLabel="Introduction to Neurons" hideHeader maxWidth="max-w-xl" panelPad="p-0">+ <IntroCards onClose={onClose} />+ </Modal>+ )+}++function IntroCards({ onClose }: { onClose: () => void }) {+ const [i, setI] = useState(0)+ const [dir, setDir] = useState(1)+ const reduce = useReducedMotion()+ const last = i === INTRO_CARDS.length - 1+ const go = (to: number) => {+ setDir(to > i ? 1 : -1)+ setI(Math.max(0, Math.min(INTRO_CARDS.length - 1, to)))+ }+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'ArrowRight') go(i + 1)+ else if (e.key === 'ArrowLeft') go(i - 1)+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ })+ const card = INTRO_CARDS[i]+ const Art = card.art+ const slide = reduce ? 0 : 24+ return (+ <div className="neuron-intro" data-testid="neuron-intro">+ <div className="relative h-52 rounded-t-2xl overflow-hidden bg-gradient-to-b from-lu-accent/[0.10] to-transparent flex items-center justify-center px-6 pt-6">+ <AnimatePresence mode="wait" initial={false}>+ <motion.div+ key={i}+ className="w-full h-full flex items-center justify-center"+ initial={{ opacity: 0, x: slide * dir }}+ animate={{ opacity: 1, x: 0 }}+ exit={{ opacity: 0, x: -slide * dir }}+ transition={{ duration: reduce ? 0 : MOTION_S.slow }}+ >+ <Art />+ </motion.div>+ </AnimatePresence>+ </div>+ <div className="px-6 pt-4 pb-5">+ <p className="t-label text-lu-accent mb-1.5" data-testid="neuron-intro-step">Step {i + 1} of {INTRO_CARDS.length}</p>+ <h2 className="t-display text-gray-900 dark:text-white" data-testid="neuron-intro-title">{card.title}</h2>+ <p className="t-body text-gray-600 dark:text-gray-300 mt-2 min-h-[4.5em]">{card.text}</p>+ <div className="flex items-center justify-between mt-4">+ <div className="flex items-center gap-1.5" role="tablist" aria-label="Introduction cards">+ {INTRO_CARDS.map((c, k) => (+ <button+ key={c.title}+ type="button"+ role="tab"+ aria-selected={k === i}+ aria-label={`Card ${k + 1}: ${c.title}`}+ onClick={() => go(k)}+ className={`h-1.5 rounded-full transition-[width,background-color] ${k === i ? 'w-5 bg-lu-accent' : 'w-1.5 bg-gray-300 dark:bg-white/20'}`}+ />+ ))}+ </div>+ <div className="flex items-center gap-2">+ {!last && <button type="button" className="lu-control" onClick={onClose} data-testid="neuron-intro-skip">Skip</button>}+ {i > 0 && (+ <button type="button" className="lu-control lu-control--outline" onClick={() => go(i - 1)} aria-label="Back" data-testid="neuron-intro-back">+ <ArrowLeft size={ICON_SM} />+ </button>+ )}+ {last ? (+ <button type="button" className="lu-control lu-primary" onClick={onClose} data-testid="neuron-intro-done">Start tweaking</button>+ ) : (+ <button type="button" className="lu-control lu-primary" onClick={() => go(i + 1)} data-testid="neuron-intro-next">+ Next <ArrowRight size={ICON_SM} />+ </button>+ )}+ </div>+ </div>+ </div>+ </div>+ )+}++/** The introduction on the page: once by itself, then on request. */+export function NeuronIntroHost() {+ const seen = useNeuronStore((s) => s.introSeen)+ const setSeen = useNeuronStore((s) => s.setIntroSeen)+ const requested = useNeuronIntroRequest((s) => s.open)+ const hide = useNeuronIntroRequest((s) => s.hide)+ return (+ <NeuronIntro+ open={!seen || requested}+ onClose={() => { setSeen(true); hide() }}+ />+ )+}diff --git a/src/components/neuron/NeuronView.tsx b/src/components/neuron/NeuronView.tsxindex eedc31d6..e25945de 100644--- a/src/components/neuron/NeuronView.tsx+++ b/src/components/neuron/NeuronView.tsx@@ -1,30 +1,35 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { Download, FilePlus, Loader2, RotateCcw, Search, Sliders, Trash2 } from 'lucide-react'+import { CircleHelp, Download, FilePlus, FlaskConical, Hash, Loader2, RotateCcw, Sliders, Sparkles } from 'lucide-react'import { Hinweis } from '../ui/Hinweis'import { HINWEIS_TEXT } from '../../lib/hinweis'import { HOWTO } from '../../lib/howto'import { ICON_SM } from '../ui/icon-size'-import { openExternal } from '../../api/backend'import { addGgufFile, listBundledModels, bundledEngineStatus, isEmbeddingGgufName, type BundledModel } from '../../api/engine'+import * as neuronApi from '../../api/neuron'import {- neuronApply, neuronBuildOwn, neuronBuildPreset, neuronCancel, neuronCompare, neuronDelete, neuronDismiss,- neuronFeatureAdd, neuronInfo, neuronPresets, neuronSaeDownload, neuronSaeSearch, neuronStatus,- type CompareResult, type FeatureHit, type NeuronInfo, type NeuronJob, type NeuronPreset, type NeuronVector,+ neuronApply, neuronBuildOwn, neuronBuildPreset, neuronCancel, neuronDelete, neuronDismiss,+ neuronFeatureAdd, neuronInfo, neuronPresets, neuronSaeDownload, neuronStatus,+ type NeuronInfo, type NeuronJob, type NeuronPreset,} from '../../api/neuron'import { getProviderIdFromModel } from '../../api/providers/model-name'import { isManagedBuiltinSlot } from '../../api/builtin-ensure'import { preservedSwapCtx } from '../../lib/builtin-ctx'import { builtinModelMatches } from '../../lib/builtin-model-identity'import {- backendNote, effectiveStrengths, entriesFor, hasPersonaProfile, jobProgressText, jobShare, sameEntries,- clampStrength, steeringPersona, strengthWarning, warningText, type BackendKind,+ backendNote, effectiveStrengths, entriesFor, hasPersonaProfile,+ clampStrength, steeringPersona, strengthWarning, warningText, type BackendKind, type Strengths,} from '../../lib/neuron'+import { featureVectorId, neuronVectorId, recipeOwnId, type Recipe, type RecipeEntry } from '../../lib/neuron-recipe'import { editingKey, useNeuronStore } from '../../stores/neuronStore'import { useModelStore } from '../../stores/modelStore'import { useChatStore } from '../../stores/chatStore'import { useSettingsStore } from '../../stores/settingsStore'import { useUIStore } from '../../stores/uiStore'import type { BuiltinEngineTuning } from '../../types/settings'+import { JobPanel, ScopeButton, SliderRow, StepCard, WayIntro, WayTabs, signedValue } from './parts'+import { ComparePanel, CoordinatesPanel, FeaturePanel, OwnSliderForm, SharePanel, entryState, type NeuronInfoPlus } from './panels'+import { NeuronIntroHost } from './NeuronIntro'+import { useNeuronIntroRequest } from '../../stores/neuronIntroStore'const APPLY_DELAY_MS = 700@@ -33,6 +38,8 @@ const GGUF_STEPS = HOWTO['gguf-file'].films[0].steps/** Why a model the user already has in Ollama or LM Studio is not offered. */const OTHER_APPS = 'Models in Ollama or LM Studio do not show up here: those programs take no control vectors, so the sliders cannot reach them.'+type Way = 'ready' | 'own' | 'features' | 'coords'+/** Which program answers the chat's model right now. */function chatBackend(activeModel: string | null, appMode: string | undefined): BackendKind {if (appMode === 'cloud') return 'cloud'@@ -62,6 +69,17 @@ async function restartTuning(model: BundledModel | undefined): Promise<BuiltinEn}}+/** The engine piece for single neurons (AN-P11-N2.md), when this build has+ * it. Read through the module, so the page needs no change once it lands. */+function mlpAdd(): ((modelPath: string, layer: number, neuron: number) => Promise<unknown>) | null {+ try {+ const fn = (neuronApi as Record<string, unknown>).neuronMlpAdd+ return typeof fn === 'function' ? fn as (p: string, l: number, n: number) => Promise<unknown> : null+ } catch {+ return null+ }+}+export function NeuronView() {const activeModel = useModelStore((s) => s.activeModel)const appMode = useSettingsStore((s) => s.settings.appMode)@@ -85,10 +103,15 @@ export function NeuronView() {const [error, setError] = useState<string | null>(null)const [applyState, setApplyState] = useState<'idle' | 'applying' | 'applied'>('idle')const [lastApplied, setLastApplied] = useState<string>('')+ const [way, setWay] = useState<Way>('ready')+ const [compared, setCompared] = useState(false)+ // Jobs a recipe asked for, run one after the other.+ const [queue, setQueue] = useState<Array<() => Promise<unknown>>>([])+ const [undo, setUndo] = useState<{ key: string; prev: Strengths | undefined } | null>(null)const backend = chatBackend(activeModel, appMode)const model = models.find((m) => m.path === modelPath)- const info = loadedInfo?.path === modelPath ? loadedInfo.info : null+ const info = loadedInfo?.path === modelPath ? loadedInfo.info as NeuronInfoPlus : nullconst pathRef = useRef(modelPath)pathRef.current = modelPath@@ -183,7 +206,7 @@ export function NeuronView() {return () => window.clearTimeout(t)}, [entries, modelPath, info, lastApplied, model, refreshInfo])- const startJob = async (start: () => Promise<unknown>) => {+ const startJob = useCallback(async (start: () => Promise<unknown>) => {setError(null)try {await start()@@ -191,7 +214,17 @@ export function NeuronView() {} catch (e) {setError(String(e))}- }+ }, [poll])++ // A recipe's jobs, one at a time: the next starts when nothing runs.+ const [starting, setStarting] = useState(false)+ useEffect(() => {+ if (running || starting || queue.length === 0) return+ const [next, ...rest] = queue+ setStarting(true)+ setQueue(rest)+ void startJob(next).finally(() => setStarting(false))+ }, [running, starting, queue, startJob])// A persona without its own profile shows the model's; its first move// starts from what is shown, so the other sliders keep their place (T1:@@ -207,154 +240,327 @@ export function NeuronView() {else setProfile(editKey, {})}+ const deleteVector = (id: string) => void neuronDelete(modelPath, id).then(() => { removeSlider(modelKey, id); return refreshInfo(modelPath) })++ const ids = useMemo(() => ({+ feature: (n: number) => featureVectorId(info?.sae?.id ?? '', n),+ neuron: neuronVectorId,+ own: recipeOwnId,+ }), [info])+ const mlp = info?.mlpNeurons ? mlpAdd() : null+ const states = useCallback((e: RecipeEntry) => {+ if (!info) return { state: 'blocked' as const, why: 'The model is still loading.' }+ return entryState(e, { ...info, mlpNeurons: !!mlp }, available, ids)+ }, [info, mlp, available, ids])++ /** A recipe replaces the sliders (one Undo brings them back); what is not+ * computed for this model yet is queued and prepared one by one. */+ const applyRecipe = (recipe: Recipe) => {+ if (!modelKey || !info) return+ setUndo({ key: editKey, prev: profiles[editKey] })+ const next: Strengths = {}+ const jobs: Array<() => Promise<unknown>> = []+ for (const e of recipe.entries) {+ const st = states(e)+ if (st.state === 'blocked') continue+ if (e.kind === 'preset') {+ next[e.id] = clampStrength(e.strength)+ if (st.state === 'prepare') jobs.push(() => neuronBuildPreset(modelPath, e.id))+ } else if (e.kind === 'feature') {+ next[ids.feature(e.feature)] = clampStrength(e.strength)+ if (st.state === 'prepare') jobs.push(() => neuronFeatureAdd(modelPath, e.feature))+ } else if (e.kind === 'own') {+ const id = recipeOwnId(e)+ next[id] = clampStrength(e.strength)+ if (st.state === 'prepare') jobs.push(() => neuronBuildOwn(modelPath, e.name, e.more, e.less, id))+ } else {+ next[neuronVectorId(e.layer, e.neuron)] = clampStrength(e.dose)+ if (st.state === 'prepare' && mlp) jobs.push(() => mlp(modelPath, e.layer, e.neuron))+ }+ }+ setProfile(editKey, next)+ setQueue(jobs)+ }++ const undoRecipe = () => {+ if (!undo) return+ if (undo.prev) setProfile(undo.key, undo.prev)+ else removeProfile(undo.key)+ setQueue([])+ setUndo(null)+ }++ // The mix as a recipe to share: what is on, by its kind.+ const share = useMemo(() => {+ const out: RecipeEntry[] = []+ const skipped: string[] = []+ for (const e of entries) {+ const v = vectors.find((x) => x.id === e.id)+ if (!v) continue+ const nm = /^n-L(\d+)-N(\d+)$/.exec(v.id)+ if (v.kind === 'preset') out.push({ kind: 'preset', id: v.id, strength: e.strength })+ else if (v.kind === 'feature' && v.feature != null) out.push({ kind: 'feature', feature: v.feature, strength: e.strength })+ else if (v.kind === 'own') {+ const clean = (ls: string[]) => ls.map((l) => l.replace(/\s+/g, ' ').trim().slice(0, 300)).filter(Boolean).slice(0, 40)+ const more = clean(v.more)+ const less = clean(v.less)+ if (more.length && less.length) out.push({ kind: 'own', name: v.name.slice(0, 40), more, less, strength: e.strength })+ else skipped.push(v.name)+ } else if (nm) out.push({ kind: 'neuron', layer: Number(nm[1]), neuron: Number(nm[2]), dose: e.strength })+ else skipped.push(v.name)+ }+ const recipe: Recipe = { model: info?.facts.name || model?.name || null, entries: out }+ return { recipe, skipped }+ }, [entries, vectors, info, model])++ const showIntro = useNeuronIntroRequest((s) => s.show)+if (modelsLoaded && models.length === 0) {return (- <NoModel- onDownload={() => {- useModelStore.getState().setCategoryFilter('text')- useUIStore.getState().openDiscoverFor('builtin')- }}- onAddFile={async () => {- try {- if (await addGgufFile()) setModelsSeq((n) => n + 1)- } catch (e) {- setError(String(e))- }- }}- error={error}- onDismissError={() => setError(null)}- />+ <>+ <NoModel+ onDownload={() => {+ useModelStore.getState().setCategoryFilter('text')+ useUIStore.getState().openDiscoverFor('builtin')+ }}+ onAddFile={async () => {+ try {+ if (await addGgufFile()) setModelsSeq((n) => n + 1)+ } catch (e) {+ setError(String(e))+ }+ }}+ onIntro={showIntro}+ error={error}+ onDismissError={() => setError(null)}+ />+ <NeuronIntroHost />+ </>)}+ const presetRows = presets.map((p) => ({ p, v: vectors.find((x) => x.id === p.id) }))+ const own = vectors.filter((v) => v.kind === 'own')+ const features = vectors.filter((v) => v.kind === 'feature')+ const neurons = vectors.filter((v) => /^n-L\d+-N\d+$/.test(v.id))+ const onCount = (pred: (id: string) => boolean) => entries.filter((e) => pred(e.id)).length+ const labelOf = (id: string) => {+ const v = vectors.find((x) => x.id === id)+ if (!v) return id+ if (v.kind === 'preset') return v.right+ return v.name+ }+return (- <Shell>- {backend !== 'lu-engine' && <Hinweis className="mb-3">{backendNote(backend)}</Hinweis>}- {error && <Hinweis ton="fehler" className="mb-3" onDismiss={() => setError(null)}>{error}</Hinweis>}-- <div className="flex flex-wrap items-center gap-2 mb-1">- <label className="t-body text-gray-600 dark:text-gray-300" htmlFor="neuron-model">Model</label>- <select- id="neuron-model"- data-testid="neuron-model"- className="t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white max-w-full"- value={modelPath}- onChange={(e) => { setModelPath(e.target.value); setLastApplied('') }}- >- {models.map((m) => <option key={m.path} value={m.path}>{m.name}{m.loaded ? ' (loaded)' : ''}</option>)}- </select>- {applyState === 'applying' && <span className={`t-micro ${HINWEIS_TEXT.ruhig} inline-flex items-center gap-1`}><Loader2 size={12} className="animate-spin" /> Restarting the engine with your sliders…</span>}- {applyState === 'applied' && <span className={`t-micro ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-applied">{entries.length ? `Active in chat: ${entries.length} slider${entries.length > 1 ? 's' : ''}` : 'Off: the model runs unchanged'}</span>}- </div>- {info && (- <p className={`t-micro ${HINWEIS_TEXT.ruhig} mb-3`}>- {info.facts.arch} · {info.facts.nLayer} layers · sliders act on layers {info.band[0]}–{info.band[1]}- </p>- )}-- {persona && modelKey && (- <div className="flex flex-wrap items-center gap-1 mb-4 t-body" role="radiogroup" aria-label="Save sliders for">- <span className="text-gray-600 dark:text-gray-300 mr-1">Save for</span>- <ScopeButton on={scope === 'model'} onClick={() => setScope(modelKey, 'model')}>This model</ScopeButton>- <ScopeButton on={scope === 'persona'} onClick={() => { setScope(modelKey, 'persona'); if (!hasPersonaProfile(profiles, modelKey, persona.id)) setProfile(editingKey(modelKey, persona.id, 'persona'), { ...(profiles[modelKey] ?? {}) }) }}>- This model with “{persona.name}”- </ScopeButton>+ <Shell onIntro={showIntro}>+ <StepCard+ n={1}+ title="Pick a model"+ lead="Neurons works on chat models that run in the LU Engine."+ done={!!info && backend === 'lu-engine'}+ testId="neuron-step-model"+ >+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-2">+ <label className="t-body font-medium text-gray-700 dark:text-gray-200" htmlFor="neuron-model">Model</label>+ <select+ id="neuron-model"+ data-testid="neuron-model"+ className="t-body rounded-md border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-white/[0.04] px-2.5 py-1.5 text-gray-900 dark:text-white min-w-0 w-full"+ value={modelPath}+ onChange={(e) => { setModelPath(e.target.value); setLastApplied(''); setCompared(false) }}+ >+ {models.map((m) => <option key={m.path} value={m.path}>{m.name}{m.loaded ? ' (loaded)' : ''}</option>)}+ </select>+ <span />+ <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>+ {info ? `${info.facts.arch} · ${info.facts.nLayer} layers · sliders act on layers ${info.band[0]}–${info.band[1]}` : 'Reading the model…'}+ </p></div>- )}+ {backend !== 'lu-engine' && <Hinweis className="mt-3">{backendNote(backend)}</Hinweis>}+ {steering.group && (+ <Hinweis className="mt-3"><span data-testid="neuron-group-note">This chat is a group chat: the model's sliders apply to every speaker. Sliders saved for one persona apply in its own chats (per speaker: later version).</span></Hinweis>+ )}+ </StepCard>++ <StepCard+ n={2}+ title="Choose your sliders"+ lead="Pick a way to change the model. Everything you turn on is listed at the bottom of this step."+ done={entries.length > 0}+ testId="neuron-step-sliders"+ >+ {error && <Hinweis ton="fehler" className="mb-3" onDismiss={() => setError(null)}>{error}</Hinweis>}+ {job && job.status !== 'idle' && <JobPanel job={job} onStop={() => { setQueue([]); void neuronCancel().then(poll) }} onDismiss={() => void neuronDismiss().then(poll)} />}+ {queue.length > 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig} mb-3`} data-testid="neuron-queue">{queue.length} more to prepare from the recipe, one after the other.</p>}+ {info && !info.generator && (+ <Hinweis className="mb-3">This install is missing its vector tool, so ready-made and own sliders cannot be computed. Reinstall LU to bring it back. Feature sliders still work where the model has one.</Hinweis>+ )}- {steering.group && (- <Hinweis className="mb-3"><span data-testid="neuron-group-note">This chat is a group chat: the model's sliders apply to every speaker. Sliders saved for one persona apply in its own chats (per speaker: later version).</span></Hinweis>- )}+ <WayTabs<Way>+ current={way}+ onPick={setWay}+ ways={[+ { id: 'ready', label: 'Ready-made', count: onCount((id) => presets.some((p) => p.id === id)) },+ { id: 'own', label: 'From examples', count: onCount((id) => id.startsWith('own-')) },+ { id: 'features', label: 'Features', count: onCount((id) => id.startsWith('f-')) },+ { id: 'coords', label: 'Coordinates', count: onCount((id) => id.startsWith('n-')) },+ ]}+ />- {job && job.status !== 'idle' && <JobPanel job={job} onStop={() => void neuronCancel().then(poll)} onDismiss={() => void neuronDismiss().then(poll)} />}+ <div role="tabpanel" id={`neuron-way-${way}`} aria-labelledby={`neuron-way-tab-${way}`}>+ {way === 'ready' && (+ <>+ <WayIntro icon={<Sliders size={16} />} title="Ready-made sliders">+ Five common traits. The first time, LU prepares each one for your model (it reads short example pairs and measures how far it can push).+ </WayIntro>+ <div className="grid grid-cols-1 gap-2" data-testid="neuron-presets">+ {presetRows.map(({ p, v }) => (+ <SliderRow+ key={p.id}+ id={p.id}+ left={p.left}+ right={p.right}+ value={strengths[p.id] ?? 0}+ computed={!!v}+ disabled={running || !modelPath || (!v && !info?.generator)}+ onCompute={() => void startJob(() => neuronBuildPreset(modelPath, p.id))}+ onChange={(x) => move(p.id, x)}+ />+ ))}+ </div>+ </>+ )}- <Section title="Sliders">- {info && !info.generator && (- <Hinweis className="mb-2">This install is missing its vector tool, so ready-made and own sliders cannot be computed. Reinstall LU to bring it back. Feature sliders still work where the model has one.</Hinweis>- )}- <div className="space-y-2" data-testid="neuron-presets">- {presets.map((p) => {- const v = vectors.find((x) => x.id === p.id)- return (- <SliderRow- key={p.id}- id={p.id}- left={p.left}- right={p.right}- value={strengths[p.id] ?? 0}- computed={!!v}- disabled={running || !modelPath || (!v && !info?.generator)}- onCompute={() => void startJob(() => neuronBuildPreset(modelPath, p.id))}- onChange={(x) => move(p.id, x)}- />- )- })}- </div>- </Section>-- <Section title="Your own sliders">- <div className="space-y-2" data-testid="neuron-own">- {vectors.filter((v) => v.kind === 'own').map((v) => (- <SliderRow- key={v.id}- id={v.id}- left={v.left}- right={v.right}- value={strengths[v.id] ?? 0}- computed- disabled={running}- onChange={(x) => move(v.id, x)}- onDelete={() => void neuronDelete(modelPath, v.id).then(() => { removeSlider(modelKey, v.id); return refreshInfo(modelPath) })}- />- ))}+ {way === 'own' && (+ <>+ <WayIntro icon={<Sparkles size={16} />} title="Your own slider, from examples">+ Write a few lines in the style you want more of, and a few you want less of. LU turns the difference into a slider. This is how most people make new traits (control vectors).+ </WayIntro>+ <div className="space-y-2 mb-3" data-testid="neuron-own">+ {own.map((v) => (+ <SliderRow key={v.id} id={v.id} left={v.left} right={v.right} value={strengths[v.id] ?? 0} computed disabled={running} onChange={(x) => move(v.id, x)} onDelete={() => deleteVector(v.id)} />+ ))}+ </div>+ <OwnSliderForm disabled={running || !info?.generator || !modelPath} onCompute={(name, more, less) => void startJob(() => neuronBuildOwn(modelPath, name, more, less))} />+ </>+ )}++ {way === 'features' && (+ <>+ <WayIntro icon={<FlaskConical size={16} />} title="Features: what the model knows">+ Some models come with a map of their inner concepts (a sparse autoencoder). Search a word, add the concept, and turn it up or down.+ </WayIntro>+ {info?.sae ? (+ <FeaturePanel+ info={info}+ modelPath={modelPath}+ vectors={features}+ strengths={strengths}+ disabled={running}+ onDownload={() => void startJob(() => neuronSaeDownload(modelPath))}+ onAdd={(hit) => void startJob(() => neuronFeatureAdd(modelPath, hit.feature, hit.label))}+ onChange={(id, x) => move(id, x)}+ onDelete={deleteVector}+ onError={setError}+ />+ ) : (+ <p className={`t-body ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-features-none">+ This model has no official feature map. Features exist for Gemma 3 270M IT and Gemma 3 1B IT (Gemma Scope 2 by Google DeepMind, CC-BY-4.0). Pick one of those in step 1, or use the other ways.+ </p>+ )}+ </>+ )}++ {way === 'coords' && (+ <>+ <WayIntro icon={<Hash size={16} />} title="Coordinates people share">+ A coordinate points at one spot inside a model, like “layer 14, neuron 8949, +1.0”. Paste what someone shared, check what it does, then use it.+ </WayIntro>+ {neurons.length > 0 && (+ <div className="space-y-2 mb-4">+ {neurons.map((v) => (+ <SliderRow key={v.id} id={v.id} left="Less" right={v.name} value={strengths[v.id] ?? 0} computed disabled={running} onChange={(x) => move(v.id, x)} onDelete={() => deleteVector(v.id)} />+ ))}+ </div>+ )}+ {info ? (+ <CoordinatesPanel+ presets={presets}+ modelNames={[info.facts.name, model?.name]}+ states={states}+ onUse={applyRecipe}+ disabled={running || !modelPath}+ />+ ) : <p className={`t-body ${HINWEIS_TEXT.ruhig}`}>Reading the model…</p>}+ </>+ )}</div>- <OwnSliderForm disabled={running || !info?.generator || !modelPath} onCompute={(name, more, less) => void startJob(() => neuronBuildOwn(modelPath, name, more, less))} />- </Section>-- {info?.sae && (- <Section title="Features">- <FeaturePanel- info={info}- modelPath={modelPath}- vectors={vectors.filter((v) => v.kind === 'feature')}- strengths={strengths}- disabled={running}- onDownload={() => void startJob(() => neuronSaeDownload(modelPath))}- onAdd={(hit) => void startJob(() => neuronFeatureAdd(modelPath, hit.feature, hit.label))}- onChange={(id, x) => move(id, x)}- onDelete={(id) => void neuronDelete(modelPath, id).then(() => { removeSlider(modelKey, id); return refreshInfo(modelPath) })}- onError={setError}- />- </Section>- )}-- {warning && <Hinweis className="mb-3" >{warning}</Hinweis>}-- <div className="flex items-center gap-2 mb-6">- <button- type="button"- data-testid="neuron-reset"- onClick={reset}- className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md t-body bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-800 dark:text-gray-100"- >- <RotateCcw size={ICON_SM} /> Reset- </button>- <span className={`t-micro ${HINWEIS_TEXT.ruhig}`}>All sliders to 0: the model answers exactly as without the tweaker.</span>- </div>- <Section title="Before and after">- <ComparePanel modelPath={modelPath} entries={entries} disabled={running || !modelPath} model={model} onError={setError} />- </Section>+ <div className="mt-5 pt-4 border-t border-gray-200 dark:border-white/[0.06]" data-testid="neuron-mix">+ <div className="flex items-center justify-between gap-2 mb-2">+ <p className="t-body font-medium text-gray-900 dark:text-white">On right now</p>+ <button type="button" data-testid="neuron-reset" onClick={reset} className="lu-control lu-control--outline">+ <RotateCcw size={ICON_SM} /> Reset all+ </button>+ </div>+ {entries.length === 0 ? (+ <p className={`t-body ${HINWEIS_TEXT.ruhig}`}>Nothing. The model answers exactly as without Neurons.</p>+ ) : (+ <ul className="flex flex-wrap gap-1.5">+ {entries.map((e) => (+ <li key={e.id} className="t-control inline-flex items-center gap-1.5 rounded-full border border-lu-accent/40 bg-lu-accent/[0.08] px-2.5 py-1 text-gray-900 dark:text-white">+ {labelOf(e.id)} <span className="tabular-nums text-lu-accent">{signedValue(e.strength)}</span>+ </li>+ ))}+ </ul>+ )}+ {warning && <Hinweis className="mt-2">{warning}</Hinweis>}+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-2 flex items-center gap-1`} aria-live="polite">+ {applyState === 'applying' && <><Loader2 size={12} className="animate-spin" /> Restarting the engine with your sliders…</>}+ {applyState === 'applied' && <span data-testid="neuron-applied">{entries.length ? `Active in chat: ${entries.length} slider${entries.length > 1 ? 's' : ''}` : 'Off: the model runs unchanged'}</span>}+ </p>+ </div>+ </StepCard>++ <StepCard+ n={3}+ title="Try it: before and after"+ lead="Ask one question and see the answer without and with your sliders."+ done={compared}+ testId="neuron-step-compare"+ >+ <ComparePanel modelPath={modelPath} entries={entries} disabled={running || !modelPath} model={model} tuning={restartTuning} onError={setError} onDone={() => setCompared(true)} />+ </StepCard>++ <StepCard+ n={4}+ title="Keep and share"+ lead="Your sliders stay for this model, also after a restart of LU. Every new chat uses them."+ testId="neuron-step-share"+ >+ {persona && modelKey && (+ <div className="flex flex-wrap items-center gap-2 mb-4 t-body" role="radiogroup" aria-label="Save sliders for">+ <span className="text-gray-700 dark:text-gray-200 font-medium mr-1">Save for</span>+ <ScopeButton on={scope === 'model'} onClick={() => setScope(modelKey, 'model')}>This model</ScopeButton>+ <ScopeButton on={scope === 'persona'} onClick={() => { setScope(modelKey, 'persona'); if (!hasPersonaProfile(profiles, modelKey, persona.id)) setProfile(editingKey(modelKey, persona.id, 'persona'), { ...(profiles[modelKey] ?? {}) }) }}>+ This model with “{persona.name}”+ </ScopeButton>+ </div>+ )}+ <SharePanel recipe={share.recipe} skipped={share.skipped} onUndo={undo ? undoRecipe : undefined} />+ </StepCard>- <Section title="What this can and cannot do">- <ul className={`t-micro ${HINWEIS_TEXT.ruhig} list-disc pl-4 space-y-1`}>+ <details className="ml-10 mt-1 mb-8 rounded-xl border border-gray-200 dark:border-white/[0.08] px-4 py-3" data-testid="neuron-limits">+ <summary className="t-body font-medium text-gray-900 dark:text-white cursor-pointer">What this can and cannot do</summary>+ <ul className={`t-micro ${HINWEIS_TEXT.ruhig} list-disc pl-4 space-y-1 mt-2`}><li>Works with models in LU Engine (llama.cpp control vectors). Ollama, LM Studio and cloud models take no control vectors, so the sliders cannot reach them.</li><li>Each slider is computed for this model the first time: LU reads short example pairs through the model and measures how far it can push before answers break. Seconds for small models, a few minutes for large ones. The chat pauses meanwhile.</li><li>±1 is just under where the measured answer started to break. Strong settings or many sliders at once can still make text repeat or wander.</li><li>A change restarts the engine with the new sliders (a few seconds). The settings stay for this model across restarts of LU.</li><li>Features exist only for models with an official sparse autoencoder: Gemma 3 270M IT and 1B IT (Gemma Scope 2, CC-BY-4.0). Their names come from the words each feature pushes, and some are hard to name.</li>+ <li>Small models (under 1B) show traits weakly; special ones like a pirate voice need a bigger model.</li></ul>- </Section>+ </details></Shell>)}@@ -363,9 +569,10 @@ export function NeuronView() {* one (David, 2026-10-30: the line used to sit at the top, "hingeklatscht").* Download opens Discover with the LU Engine as the target whatever the chat* model is, so the file lands where the tweaker can read it. */-function NoModel({ onDownload, onAddFile, error, onDismissError }: {+function NoModel({ onDownload, onAddFile, onIntro, error, onDismissError }: {onDownload: () => voidonAddFile: () => void+ onIntro: () => voiderror: string | nullonDismissError: () => void}) {@@ -380,6 +587,9 @@ function NoModel({ onDownload, onAddFile, error, onDismissError }: {<button className="lu-tonal" onClick={onDownload} data-testid="neuron-get-model"><Download size={ICON_SM} /> Get a model for the LU Engine</button>+ <button className="lu-control" onClick={onIntro} data-testid="neuron-intro-open">+ <CircleHelp size={ICON_SM} /> How Neurons works+ </button></div>{/* A file the user already has, in three steps (David, 30.10.2026).The lines are the how-to's, so Help and this state say the same. */}@@ -398,278 +608,25 @@ function NoModel({ onDownload, onAddFile, error, onDismissError }: {)}-function Shell({ children }: { children: React.ReactNode }) {+function Shell({ onIntro, children }: { onIntro: () => void; children: React.ReactNode }) {return (<div className="h-full overflow-y-auto scrollbar-thin" data-testid="neuron-view">- <div className="max-w-2xl mx-auto px-4 py-4">- <div className="flex items-center gap-2 mb-1">- <Sliders size={16} className="text-gray-500" />- <h1 className="t-title text-gray-900 dark:text-white">Neuron tweaker</h1>- </div>- <p className={`t-body ${HINWEIS_TEXT.ruhig} mb-4`}>Turn your local model’s traits up or down, like an equalizer. It acts inside the model, not in the prompt.</p>- {children}- </div>- </div>- )-}--function Section({ title, children }: { title: string; children: React.ReactNode }) {- return (- <section className="mb-6">- <h2 className="t-body font-medium text-gray-900 dark:text-white mb-2">{title}</h2>- {children}- </section>- )-}--function ScopeButton({ on, onClick, children }: { on: boolean; onClick: () => void; children: React.ReactNode }) {- return (- <button- type="button"- role="radio"- aria-checked={on}- onClick={onClick}- className={`px-2 py-0.5 rounded-md ${on ? 'bg-lu-accent/20 text-gray-900 dark:text-white' : 'bg-gray-100 dark:bg-white/[0.06] text-gray-600 dark:text-gray-300'}`}- >- {children}- </button>- )-}--interface SliderRowProps {- id: string- left: string- right: string- value: number- computed: boolean- disabled?: boolean- onChange: (v: number) => void- onCompute?: () => void- onDelete?: () => void-}--function SliderRow({ id, left, right, value, computed, disabled, onChange, onCompute, onDelete }: SliderRowProps) {- return (- <div className="grid grid-cols-[7rem_1fr_7rem_3rem_auto] items-center gap-2" data-testid={`neuron-slider-${id}`}>- <span className="t-body text-right text-gray-700 dark:text-gray-200 truncate" title={left}>{left}</span>- {computed ? (- <input- type="range"- min={-1}- max={1}- step={0.05}- value={value}- disabled={disabled}- aria-label={`${left} to ${right}`}- onChange={(e) => onChange(Number(e.target.value))}- onDoubleClick={() => onChange(0)}- className="w-full accent-lu-accent"- />- ) : (- <button- type="button"- disabled={disabled}- onClick={onCompute}- data-testid={`neuron-compute-${id}`}- className="t-micro rounded-md px-2 py-1 bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-700 dark:text-gray-200 disabled:opacity-50"- >- Compute for this model- </button>- )}- <span className="t-body text-gray-700 dark:text-gray-200 truncate" title={right}>{right}</span>- <span className={`t-micro tabular-nums ${HINWEIS_TEXT.ruhig}`}>{computed ? (value > 0 ? `+${value.toFixed(2)}` : value.toFixed(2)) : ''}</span>- {onDelete ? (- <button type="button" onClick={onDelete} aria-label={`Delete ${right}`} className="p-1 text-gray-400 hover:text-red-500"><Trash2 size={ICON_SM} /></button>- ) : <span />}- </div>- )-}--function JobPanel({ job, onStop, onDismiss }: { job: NeuronJob; onStop: () => void; onDismiss: () => void }) {- const share = jobShare(job)- if (job.status === 'running') {- return (- <div className="space-y-1.5 mb-5" data-testid="neuron-job">- <p className="flex items-center gap-1.5 t-body text-gray-700 dark:text-gray-200">- <Loader2 size={ICON_SM} className="animate-spin" /> {job.title}: {job.phaseLabel || 'starting…'}- </p>- <div className="h-1 rounded-full bg-gray-200 dark:bg-white/[0.08] overflow-hidden">- <div className="h-full rounded-full bg-lu-accent transition-[width]" style={{ width: share == null ? '0%' : `${Math.round(share * 100)}%` }} />- </div>- <p className={`t-micro font-mono ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-job-progress">{jobProgressText(job)}</p>- {job.logs.length > 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig} truncate`}>{job.logs[job.logs.length - 1]}</p>}- <button type="button" onClick={onStop} className="t-micro text-red-600 dark:text-red-400 hover:underline">Stop</button>- </div>- )- }- return (- <div className="mb-5" data-testid="neuron-job-ended">- {job.status === 'done' && <Hinweis onDismiss={onDismiss}>{job.title}: done{job.elapsedSecs ? ` in ${job.elapsedSecs} s` : ''}.{job.logs.find((l) => l.includes('full strength')) ? ` ${job.logs.find((l) => l.includes('full strength'))?.trim()}.` : ''}</Hinweis>}- {job.status === 'failed' && <Hinweis ton="fehler" onDismiss={onDismiss}>{job.title} failed: {job.error}</Hinweis>}- {job.status === 'cancelled' && <Hinweis onDismiss={onDismiss}>{job.title}: stopped.</Hinweis>}- </div>- )-}--function OwnSliderForm({ disabled, onCompute }: { disabled: boolean; onCompute: (name: string, more: string[], less: string[]) => void }) {- const [open, setOpen] = useState(false)- const [name, setName] = useState('')- const [more, setMore] = useState('')- const [less, setLess] = useState('')- const lines = (t: string) => t.split('\n').map((l) => l.trim()).filter(Boolean)- if (!open) {- return (- <button type="button" disabled={disabled} onClick={() => setOpen(true)} data-testid="neuron-own-new" className="mt-2 t-body text-lu-accent hover:underline disabled:opacity-50">- + New slider from examples- </button>- )- }- const ok = name.trim() && lines(more).length > 0 && lines(less).length > 0- return (- <div className="mt-3 space-y-2" data-testid="neuron-own-form">- <input- className="w-full t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white"- placeholder="Name, e.g. Pirate"- value={name}- maxLength={40}- onChange={(e) => setName(e.target.value)}- data-testid="neuron-own-name"- />- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">- <label className="t-micro text-gray-600 dark:text-gray-300">More like this (one per line)- <textarea rows={4} className="mt-1 w-full t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" placeholder={'Talk like a pirate.\nSay arr and matey.'} value={more} onChange={(e) => setMore(e.target.value)} data-testid="neuron-own-more" />- </label>- <label className="t-micro text-gray-600 dark:text-gray-300">Less like this (one per line)- <textarea rows={4} className="mt-1 w-full t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" placeholder={'Talk in plain modern English.'} value={less} onChange={(e) => setLess(e.target.value)} data-testid="neuron-own-less" />- </label>- </div>- <div className="flex gap-2">- <button type="button" disabled={disabled || !ok} onClick={() => { onCompute(name.trim(), lines(more), lines(less)); setOpen(false); setName(''); setMore(''); setLess('') }} data-testid="neuron-own-compute" className="px-3 py-1.5 rounded-md t-body bg-lu-accent text-white disabled:opacity-50">- Compute slider- </button>- <button type="button" onClick={() => setOpen(false)} className="px-3 py-1.5 rounded-md t-body text-gray-600 dark:text-gray-300">Cancel</button>- </div>- </div>- )-}--interface FeaturePanelProps {- info: NeuronInfo- modelPath: string- vectors: NeuronVector[]- strengths: Record<string, number>- disabled: boolean- onDownload: () => void- onAdd: (hit: FeatureHit) => void- onChange: (id: string, v: number) => void- onDelete: (id: string) => void- onError: (e: string) => void-}--function FeaturePanel({ info, modelPath, vectors, strengths, disabled, onDownload, onAdd, onChange, onDelete, onError }: FeaturePanelProps) {- const sae = info.sae!- const [query, setQuery] = useState('')- const [hits, setHits] = useState<FeatureHit[] | null>(null)- const [searching, setSearching] = useState(false)- const search = async () => {- if (!query.trim()) return- setSearching(true)- try {- setHits((await neuronSaeSearch(modelPath, query)).hits)- } catch (e) {- onError(String(e))- } finally {- setSearching(false)- }- }- return (- <div data-testid="neuron-features">- <p className={`t-micro ${HINWEIS_TEXT.ruhig} mb-2`}>- {sae.title}. License {sae.license}.{' '}- <button type="button" className="underline" onClick={() => void openExternal(sae.source)}>Source</button>- {!sae.instruct && ' This file does not look like the instruction-tuned model the features were trained on; they may act weaker.'}- </p>- {!sae.downloaded ? (- <button type="button" disabled={disabled} onClick={onDownload} data-testid="neuron-sae-download" className="px-3 py-1.5 rounded-md t-body bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-800 dark:text-gray-100 disabled:opacity-50">- Download feature data ({Math.round(sae.bytes / 1e6)} MB)- </button>- ) : (- <>- <form className="flex gap-2 mb-2" onSubmit={(e) => { e.preventDefault(); void search() }}>- <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search features, e.g. location, love, #1234" data-testid="neuron-feature-query" className="flex-1 t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" />- <button type="submit" disabled={searching} data-testid="neuron-feature-search" className="px-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-gray-700 dark:text-gray-200">- {searching ? <Loader2 size={ICON_SM} className="animate-spin" /> : <Search size={ICON_SM} />}- </button>- </form>- {hits && hits.length === 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>No feature pushes that word. Try another word or a feature number (#1234).</p>}- {hits && hits.length > 0 && (- <ul className="mb-3 max-h-56 overflow-y-auto scrollbar-thin space-y-1" data-testid="neuron-feature-hits">- {hits.map((h) => (- <li key={h.feature} className="flex items-center gap-2 t-micro">- <span className="tabular-nums text-gray-500 w-12">#{h.feature}</span>- <span className="flex-1 truncate text-gray-700 dark:text-gray-200" title={h.label}>{h.label}</span>- <button type="button" disabled={disabled || vectors.some((v) => v.feature === h.feature)} onClick={() => onAdd(h)} className="text-lu-accent hover:underline disabled:opacity-40">Add</button>- </li>- ))}- </ul>- )}- <div className="space-y-2">- {vectors.map((v) => (- <SliderRow key={v.id} id={v.id} left="Less" right={v.name} value={strengths[v.id] ?? 0} computed disabled={disabled} onChange={(x) => onChange(v.id, x)} onDelete={() => onDelete(v.id)} />- ))}- </div>- </>- )}- </div>- )-}--function ComparePanel({ modelPath, entries, disabled, model, onError }: { modelPath: string; entries: ReturnType<typeof entriesFor>; disabled: boolean; model: BundledModel | undefined; onError: (e: string) => void }) {- const [question, setQuestion] = useState('Write two sentences about rain.')- const [seed, setSeed] = useState(42)- const [busy, setBusy] = useState(false)- const [result, setResult] = useState<(CompareResult & { entries: typeof entries }) | null>(null)- const run = async () => {- setBusy(true)- try {- const r = await neuronCompare(modelPath, question, seed, entries, await restartTuning(model))- setResult({ ...r, entries })- } catch (e) {- onError(String(e))- } finally {- setBusy(false)- }- }- const stale = result && !sameEntries(result.entries, entries)- return (- <div data-testid="neuron-compare">- <div className="flex flex-wrap gap-2 mb-2">- <input value={question} onChange={(e) => setQuestion(e.target.value)} data-testid="neuron-compare-question" className="flex-1 min-w-[12rem] t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" />- <label className={`t-micro ${HINWEIS_TEXT.ruhig} flex items-center gap-1`}>Seed- <input type="number" value={seed} onChange={(e) => setSeed(Math.max(0, Math.floor(Number(e.target.value) || 0)))} className="w-20 t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" />- </label>- <button type="button" disabled={disabled || busy || !question.trim()} onClick={() => void run()} data-testid="neuron-compare-run" className="px-3 py-1.5 rounded-md t-body bg-lu-accent text-white disabled:opacity-50 inline-flex items-center gap-1.5">- {busy && <Loader2 size={ICON_SM} className="animate-spin" />} Compare- </button>- </div>- <p className={`t-micro ${HINWEIS_TEXT.ruhig} mb-2`}>Same question, same seed, temperature 0: once with the sliders off, once on. The engine restarts twice.</p>- {result && (- <>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3" data-testid="neuron-compare-result">- <div>- <p className="t-micro text-gray-500 mb-1">Before (sliders off)</p>- <p className="t-body text-gray-800 dark:text-gray-100 whitespace-pre-wrap" data-testid="neuron-compare-before">{result.before}</p>- </div>- <div>- <p className="t-micro text-gray-500 mb-1">After ({result.entries.map((e) => `${e.id} ${e.strength > 0 ? '+' : ''}${e.strength}`).join(', ') || 'all at 0'})</p>- <p className="t-body text-gray-800 dark:text-gray-100 whitespace-pre-wrap" data-testid="neuron-compare-after">{result.after}</p>+ <div className="max-w-3xl mx-auto px-6 py-6">+ <header className="flex items-start justify-between gap-4 mb-6">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <Sliders size={18} className="text-lu-accent" aria-hidden />+ <h1 className="t-display text-gray-900 dark:text-white">Neurons</h1></div>+ <p className={`t-body ${HINWEIS_TEXT.ruhig} mt-1 max-w-xl`}>Turn traits of your local model up or down, like an equalizer. It acts inside the model, not in your prompt. Four steps, top to bottom.</p></div>- <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1`} data-testid="neuron-compare-same">- {result.same ? 'Identical answers.' : 'The answers differ.'}{stale ? ' The sliders changed since; compare again.' : ''}- </p>- </>- )}+ <button type="button" className="lu-control lu-control--outline flex-none" onClick={onIntro} data-testid="neuron-intro-open">+ <CircleHelp size={ICON_SM} /> How it works+ </button>+ </header>+ {children}+ </div>+ <NeuronIntroHost /></div>)}diff --git a/src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsx b/src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsxindex d79ddd24..8d8f8b9e 100644--- a/src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsx+++ b/src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsx@@ -77,7 +77,7 @@ beforeEach(() => {job.status = 'idle'job.modelPath = ''disk.models = [NOMIC, QWEN]- useNeuronStore.setState({ profiles: {}, scopeByModel: {} })+ useNeuronStore.setState({ profiles: {}, scopeByModel: {}, introSeen: true })useModelStore.setState({ activeModel: 'openai::qwen2.5-0.5b-instruct-q8_0' })})afterEach(() => cleanup())diff --git a/src/components/neuron/__tests__/neurons-for-beginners.test.tsx b/src/components/neuron/__tests__/neurons-for-beginners.test.tsxnew file mode 100644index 00000000..3d310968--- /dev/null+++ b/src/components/neuron/__tests__/neurons-for-beginners.test.tsx@@ -0,0 +1,205 @@+/**+ * @vitest-environment jsdom+ *+ * N2 (3.0.9), David 31.10.2026: Neurons "for people without experience".+ * One page in four numbered steps, the ways to make a slider as tabs, a+ * one-time introduction that Help brings back, and coordinates to paste and+ * to share. A pasted recipe sets the values and prepares what the model does+ * not have yet, one job after the other; Undo brings the old sliders back.+ *+ * Run: npx vitest run src/components/neuron/__tests__/neurons-for-beginners.test.tsx+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { createElement } from 'react'+import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++const apply = vi.fn(async (_path: string, _entries: unknown[], _tuning?: unknown) => ({ mix: null, restarted: true, load: 0 }))+const buildPreset = vi.fn(async (_path: string, _id: string) => ({ started: true }))+const buildOwn = vi.fn(async (..._a: unknown[]) => ({ started: true }))+const vectors: Array<Record<string, unknown>> = []+const job = vi.hoisted(() => ({ status: 'idle' }))++vi.mock('../../../api/neuron', () => ({+ neuronPresets: async () => [+ { id: 'creative', left: 'Sober', right: 'Creative' },+ { id: 'detailed', left: 'Concise', right: 'Detailed' },+ { id: 'cheerful', left: 'Serious', right: 'Cheerful' },+ ],+ neuronInfo: async () => ({+ facts: { arch: 'qwen2', nLayer: 24, nEmbd: 896, template: 'chatMl', name: 'Qwen2.5 0.5B Instruct' },+ modelKey: 'qwen-1', generator: true, band: [3, 20], vectors: [...vectors], sae: null, activeMix: null,+ }),+ neuronStatus: async () => ({ status: job.status, kind: '', title: 'Computing', modelPath: '/models/qwen.gguf', phaseLabel: '', step: 0, total: 0, bytesDone: 0, bytesTotal: 0, rateBps: 0, etaSecs: null, elapsedSecs: 0, resultId: null, error: null, logs: [] }),+ neuronApply: (p: string, e: unknown[], t?: unknown) => apply(p, e, t),+ neuronBuildPreset: (p: string, id: string) => buildPreset(p, id),+ neuronBuildOwn: (...a: unknown[]) => buildOwn(...a),+ neuronCancel: vi.fn(), neuronCompare: vi.fn(), neuronDelete: vi.fn(), neuronDismiss: vi.fn(),+ neuronFeatureAdd: vi.fn(), neuronSaeDownload: vi.fn(), neuronSaeSearch: vi.fn(),+}))+vi.mock('../../../api/engine', () => ({+ addGgufFile: vi.fn(),+ listBundledModels: async () => [{ name: 'qwen2.5-0.5b-instruct-q8_0', path: '/models/qwen.gguf', size: 1, loaded: true }],+ isEmbeddingGgufName: () => false,+ bundledEngineStatus: async () => ({ running: true, healthy: true, port: 8127, model_path: '/models/qwen.gguf', ctx: 8192 }),+}))+vi.mock('../../../api/backend', async (orig) => ({ ...(await orig<object>()), openExternal: vi.fn(), backendCall: vi.fn() }))+vi.mock('../../../api/builtin-ensure', () => ({ isManagedBuiltinSlot: () => true }))++import { NeuronView } from '../NeuronView'+import { useModelStore } from '../../../stores/modelStore'+import { useNeuronStore } from '../../../stores/neuronStore'+import { useNeuronIntroRequest } from '../../../stores/neuronIntroStore'+import { buildCommands } from '../../ui/command-actions'+import { SHORTCUT_ACTIONS, shortcutKeys } from '../../../hooks/useKeyboardShortcuts'++const CHEERFUL = { id: 'cheerful', kind: 'preset', name: 'Serious ↔ Cheerful', left: 'Serious', right: 'Cheerful', unit: 0.6, builtAt: 1, more: [], less: [] }++beforeEach(() => {+ apply.mockClear()+ buildPreset.mockClear()+ buildOwn.mockClear()+ vectors.length = 0+ job.status = 'idle'+ useNeuronStore.setState({ profiles: {}, scopeByModel: {}, introSeen: true })+ useNeuronIntroRequest.setState({ open: false })+ useModelStore.setState({ activeModel: 'openai::qwen2.5-0.5b-instruct-q8_0' })+})+afterEach(() => cleanup())++describe('Neurons for beginners: one page in steps', () => {+ it('reads top to bottom in four numbered steps', async () => {+ render(createElement(NeuronView))+ await screen.findByTestId('neuron-step-model')+ const titles = [...document.querySelectorAll('section h2')].map((h) => h.textContent)+ expect(titles).toEqual(['Pick a model', 'Choose your sliders', 'Try it: before and after', 'Keep and share'])+ // Each step has its number, and the model step is done once the model is read.+ await waitFor(() => expect(screen.getByTestId('neuron-step-model').querySelector('[data-step-done]')?.getAttribute('data-step-done')).toBe('true'))+ expect(screen.getByTestId('neuron-step-sliders').querySelector('[data-step-done]')?.getAttribute('data-step-done')).toBe('false')+ })++ it('shows the ways to make a slider as tabs, each with one line on what it is', async () => {+ render(createElement(NeuronView))+ const tabs = await screen.findAllByRole('tab')+ expect(tabs.map((t) => t.textContent)).toEqual(['Ready-made', 'From examples', 'Features', 'Coordinates'])+ fireEvent.click(screen.getByTestId('neuron-way-features'))+ expect(screen.getByTestId('neuron-features-none').textContent).toMatch(/Gemma 3 270M IT and Gemma 3 1B IT/)+ fireEvent.click(screen.getByTestId('neuron-way-own'))+ expect(screen.getByText(/Your own slider, from examples/)).toBeTruthy()+ })++ it('puts both ends and the value of a slider on one line, the slider under it', async () => {+ vectors.push(CHEERFUL)+ useNeuronStore.setState({ profiles: { 'qwen-1': { cheerful: 0.6 } } })+ render(createElement(NeuronView))+ const row = await screen.findByTestId('neuron-slider-cheerful')+ const line = row.firstElementChild as HTMLElement+ await waitFor(() => expect(row.querySelector('input[type=range]')).toBeTruthy())+ expect(line.className).toMatch(/grid-cols-\[1fr_auto_1fr\]/)+ expect(line.textContent).toBe('Serious+0.60Cheerful')+ expect(line.nextElementSibling?.tagName).toBe('INPUT')+ // And it is listed under "On right now".+ expect(within(screen.getByTestId('neuron-mix')).getByText('Cheerful')).toBeTruthy()+ })+})++describe('the introduction', () => {+ it('opens by itself the first time, once, and Help brings it back', async () => {+ useNeuronStore.setState({ introSeen: false })+ render(createElement(NeuronView))+ expect(await screen.findByTestId('neuron-intro')).toBeTruthy()+ expect(screen.getByTestId('neuron-intro-step').textContent).toBe('Step 1 of 5')+ fireEvent.click(screen.getByTestId('neuron-intro-next'))+ expect(screen.getByTestId('neuron-intro-step').textContent).toBe('Step 2 of 5')+ fireEvent.click(screen.getByTestId('neuron-intro-skip'))+ await waitFor(() => expect(screen.queryByTestId('neuron-intro')).toBeNull())+ expect(useNeuronStore.getState().introSeen).toBe(true)+ // Back from the page's own "How it works".+ fireEvent.click(screen.getAllByTestId('neuron-intro-open')[0])+ expect(await screen.findByTestId('neuron-intro')).toBeTruthy()+ expect(screen.getByTestId('neuron-intro-step').textContent).toBe('Step 1 of 5')+ })++ it('is in the command palette too', () => {+ const actions = buildCommands({ shortcuts: SHORTCUT_ACTIONS, keysFor: shortcutKeys, localViewsAvailable: true, setView: vi.fn(), openCompare: vi.fn(), toggleSidebar: vi.fn(), setActiveModel: vi.fn(), models: [], activeModel: null, quit: null })+ const intro = actions.find((a) => a.id === 'neuron-intro')+ expect(intro?.label).toBe('Neurons: how it works')+ intro!.run()+ expect(useNeuronIntroRequest.getState().open).toBe(true)+ })++ it('stands still with reduced motion', () => {+ const css = readFileSync(resolve(__dirname, '../../../index.css'), 'utf8')+ const block = css.slice(css.indexOf('Neurons introduction (N2'))+ const reduced = block.slice(block.indexOf('@media (prefers-reduced-motion: reduce)'))+ for (const cls of ['nintro-token', 'nintro-push', 'nintro-knob', 'nintro-line', 'nintro-type', 'nintro-tile']) {+ expect(block).toMatch(new RegExp(`\\.${cls}[^{]*\\{[^}]*animation:`))+ expect(reduced).toContain(`.neuron-intro .${cls}`)+ }+ expect(reduced).toMatch(/animation: none/)+ })+})++describe('coordinates', () => {+ it('reads a pasted recipe, prepares what is missing, and Undo brings the old sliders back', async () => {+ vectors.push(CHEERFUL)+ useNeuronStore.setState({ profiles: { 'qwen-1': { cheerful: 0.2 } } })+ render(createElement(NeuronView))+ await screen.findByTestId('neuron-slider-cheerful')+ fireEvent.click(screen.getByTestId('neuron-way-coords'))+ const input = await screen.findByTestId('neuron-coords-input')+ const link = 'locallyuncensored://neuron?v=1&model=Qwen2.5-0.5B-Instruct&c=%40cheerful%2B0.50+%40detailed-0.40&o=' ++ encodeURIComponent(JSON.stringify([{ n: 'Pirate', s: 0.5, m: ['Talk like a pirate.'], l: ['Talk plainly.'] }]))+ fireEvent.change(input, { target: { value: link } })+ const lines = screen.getAllByTestId('neuron-coords-line').map((l) => l.textContent)+ expect(lines[0]).toMatch(/@cheerful\+0\.50.*Ready$/)+ expect(lines[1]).toMatch(/@detailed-0\.40.*Will be prepared$/)+ expect(lines[2]).toMatch(/Pirate.*Will be prepared$/)+ expect(screen.getByTestId('neuron-coords-preview').textContent).toMatch(/That is the model you picked/)+ fireEvent.click(screen.getByTestId('neuron-coords-use'))+ const profile = useNeuronStore.getState().profiles['qwen-1']+ expect(profile.cheerful).toBe(0.5)+ expect(profile.detailed).toBe(-0.4)+ const ownId = Object.keys(profile).find((k) => k.startsWith('own-pirate-'))!+ expect(profile[ownId]).toBe(0.5)+ // The first job starts; the next waits until it has ended.+ await waitFor(() => expect(buildPreset).toHaveBeenCalledWith('/models/qwen.gguf', 'detailed'))+ expect(buildOwn).not.toHaveBeenCalled()+ await waitFor(() => expect(buildOwn).toHaveBeenCalledWith('/models/qwen.gguf', 'Pirate', ['Talk like a pirate.'], ['Talk plainly.'], ownId))+ fireEvent.click(screen.getByTestId('neuron-coords-undo'))+ expect(useNeuronStore.getState().profiles['qwen-1']).toEqual({ cheerful: 0.2 })+ })++ it('refuses a bad recipe in words and lets nothing through', async () => {+ render(createElement(NeuronView))+ fireEvent.click(await screen.findByTestId('neuron-way-coords'))+ fireEvent.change(await screen.findByTestId('neuron-coords-input'), { target: { value: 'locallyuncensored://neuron?v=1&c=L1N2%2B0.5&url=https://evil.example' } })+ expect(screen.getByTestId('neuron-coords-error').textContent).toMatch(/never has/)+ expect(screen.queryByTestId('neuron-coords-use')).toBeNull()+ })++ it('names what it cannot do yet: single neurons and other models', async () => {+ render(createElement(NeuronView))+ fireEvent.click(await screen.findByTestId('neuron-way-coords'))+ fireEvent.change(await screen.findByTestId('neuron-coords-input'), { target: { value: 'Qwen3.5-4B: L13N7956-1.0 L14N8949+1.0' } })+ expect(screen.getByTestId('neuron-coords-other-model').textContent).toMatch(/one exact model/)+ expect(screen.getAllByTestId('neuron-coords-line')[0].textContent).toMatch(/not in this build yet/)+ expect((screen.getByTestId('neuron-coords-use') as HTMLButtonElement).disabled).toBe(true)+ })+})++describe('sharing', () => {+ it('shows the mix as coordinates and copies line and link', async () => {+ vectors.push(CHEERFUL)+ useNeuronStore.setState({ profiles: { 'qwen-1': { cheerful: 0.6 } } })+ const writeText = vi.fn(async (_t: string) => {})+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })+ render(createElement(NeuronView))+ const line = await screen.findByTestId('neuron-share-line')+ await waitFor(() => expect(line.textContent).toBe('Qwen2.5 0.5B Instruct · @cheerful+0.60'))+ fireEvent.click(screen.getByTestId('neuron-share-copy'))+ await waitFor(() => expect(writeText).toHaveBeenCalled())+ expect(writeText.mock.calls[0][0]).toBe('LU neurons · Qwen2.5 0.5B Instruct · @cheerful+0.60\nlocallyuncensored://neuron?v=1&model=Qwen2.5+0.5B+Instruct&c=%40cheerful%2B0.60')+ })+})diff --git a/src/components/neuron/panels.tsx b/src/components/neuron/panels.tsxnew file mode 100644index 00000000..1ea20120--- /dev/null+++ b/src/components/neuron/panels.tsx@@ -0,0 +1,411 @@+// The contents of the Neurons steps (N2, 3.0.9): the ways to make a slider+// (from examples, features, coordinates), before/after, and sharing. The+// work behind them is P11's (api/neuron, Rust); these only lay it out.++import { useMemo, useState } from 'react'+import { ArrowRight, Check, ClipboardCopy, Link2, Loader2, Search, Undo2 } from 'lucide-react'+import { Hinweis } from '../ui/Hinweis'+import { HINWEIS_TEXT } from '../../lib/hinweis'+import { ICON_SM } from '../ui/icon-size'+import { openExternal } from '../../api/backend'+import { neuronCompare, neuronSaeSearch, type CompareResult, type FeatureHit, type NeuronInfo, type NeuronVector } from '../../api/neuron'+import type { BundledModel } from '../../api/engine'+import { sameEntries, type entriesFor } from '../../lib/neuron'+import {+ coordsLine, entryCode, modelFit, parseRecipe, recipeText, recipeLink,+ type ModelFit, type Recipe, type RecipeEntry,+} from '../../lib/neuron-recipe'+import { SliderRow, signedValue } from './parts'+import type { BuiltinEngineTuning } from '../../types/settings'++const fieldBase = 't-body rounded-md border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-white/[0.04] px-2.5 py-1.5 text-gray-900 dark:text-white placeholder:text-gray-400'+const field = `w-full ${fieldBase}`++/** What the engine piece for single neurons adds to the model's info+ * (AN-P11-N2.md). Absent until that piece is in. */+export type NeuronInfoPlus = NeuronInfo & { mlpNeurons?: boolean; nFf?: number }++// ── From examples ─────────────────────────────────────────────────────++export function OwnSliderForm({ disabled, onCompute }: { disabled: boolean; onCompute: (name: string, more: string[], less: string[]) => void }) {+ const [open, setOpen] = useState(false)+ const [name, setName] = useState('')+ const [more, setMore] = useState('')+ const [less, setLess] = useState('')+ const lines = (t: string) => t.split('\n').map((l) => l.trim()).filter(Boolean)+ if (!open) {+ return (+ <button type="button" disabled={disabled} onClick={() => setOpen(true)} data-testid="neuron-own-new" className="lu-tonal">+ + New slider from examples+ </button>+ )+ }+ const ok = name.trim() && lines(more).length > 0 && lines(less).length > 0+ return (+ <div className="space-y-3 rounded-lg border border-gray-200 dark:border-white/[0.08] p-3" data-testid="neuron-own-form">+ <label className="block t-body text-gray-700 dark:text-gray-200">+ <span className="block mb-1 font-medium">1. Name the trait</span>+ <input className={field} placeholder="e.g. Pirate" value={name} maxLength={40} onChange={(e) => setName(e.target.value)} data-testid="neuron-own-name" />+ </label>+ <div>+ <p className="t-body font-medium text-gray-700 dark:text-gray-200 mb-1">2. Write a few lines for each side</p>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <label className="block t-micro text-gray-600 dark:text-gray-300">More like this (one per line)+ <textarea rows={4} className={`${field} mt-1`} placeholder={'Talk like a pirate.\nSay arr and matey.'} value={more} onChange={(e) => setMore(e.target.value)} data-testid="neuron-own-more" />+ </label>+ <label className="block t-micro text-gray-600 dark:text-gray-300">Less like this (one per line)+ <textarea rows={4} className={`${field} mt-1`} placeholder={'Talk in plain modern English.'} value={less} onChange={(e) => setLess(e.target.value)} data-testid="neuron-own-less" />+ </label>+ </div>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1`}>Tip: keep both sides alike except for the trait. Three to ten lines each are plenty.</p>+ </div>+ <div className="flex gap-2">+ <button type="button" disabled={disabled || !ok} onClick={() => { onCompute(name.trim(), lines(more), lines(less)); setOpen(false); setName(''); setMore(''); setLess('') }} data-testid="neuron-own-compute" className="lu-control lu-primary">+ 3. Compute slider+ </button>+ <button type="button" onClick={() => setOpen(false)} className="lu-control">Cancel</button>+ </div>+ </div>+ )+}++// ── Features ──────────────────────────────────────────────────────────++interface FeaturePanelProps {+ info: NeuronInfo+ modelPath: string+ vectors: NeuronVector[]+ strengths: Record<string, number>+ disabled: boolean+ onDownload: () => void+ onAdd: (hit: FeatureHit) => void+ onChange: (id: string, v: number) => void+ onDelete: (id: string) => void+ onError: (e: string) => void+}++export function FeaturePanel({ info, modelPath, vectors, strengths, disabled, onDownload, onAdd, onChange, onDelete, onError }: FeaturePanelProps) {+ const sae = info.sae!+ const [query, setQuery] = useState('')+ const [hits, setHits] = useState<FeatureHit[] | null>(null)+ const [searching, setSearching] = useState(false)+ const search = async () => {+ if (!query.trim()) return+ setSearching(true)+ try {+ setHits((await neuronSaeSearch(modelPath, query)).hits)+ } catch (e) {+ onError(String(e))+ } finally {+ setSearching(false)+ }+ }+ return (+ <div data-testid="neuron-features" className="space-y-3">+ <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>+ {sae.title}. License {sae.license}.{' '}+ <button type="button" className="underline" onClick={() => void openExternal(sae.source)}>Source</button>+ {!sae.instruct && ' This file does not look like the instruction-tuned model the features were trained on; they may act weaker.'}+ </p>+ {!sae.downloaded ? (+ <button type="button" disabled={disabled} onClick={onDownload} data-testid="neuron-sae-download" className="lu-tonal">+ Download feature data ({Math.round(sae.bytes / 1e6)} MB)+ </button>+ ) : (+ <>+ <form className="flex gap-2" onSubmit={(e) => { e.preventDefault(); void search() }}>+ <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search a word, e.g. ocean, love, or #1234" aria-label="Search features" data-testid="neuron-feature-query" className={`${field} flex-1`} />+ <button type="submit" disabled={searching} data-testid="neuron-feature-search" className="lu-control lu-control--outline" aria-label="Search">+ {searching ? <Loader2 size={ICON_SM} className="animate-spin" /> : <Search size={ICON_SM} />}+ </button>+ </form>+ {hits && hits.length === 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>No feature pushes that word. Try another word or a feature number (#1234).</p>}+ {hits && hits.length > 0 && (+ <ul className="max-h-56 overflow-y-auto scrollbar-thin divide-y divide-gray-100 dark:divide-white/[0.05] rounded-lg border border-gray-200 dark:border-white/[0.06]" data-testid="neuron-feature-hits">+ {hits.map((h) => (+ <li key={h.feature} className="grid grid-cols-[4.5rem_1fr_auto] items-center gap-2 px-3 py-1.5 t-body">+ <span className="tabular-nums t-mono text-gray-500">#{h.feature}</span>+ <span className="truncate text-gray-700 dark:text-gray-200" title={h.label}>{h.label}</span>+ <button type="button" disabled={disabled || vectors.some((v) => v.feature === h.feature)} onClick={() => onAdd(h)} className="lu-tonal">Add</button>+ </li>+ ))}+ </ul>+ )}+ {vectors.length > 0 && (+ <div className="space-y-2">+ {vectors.map((v) => (+ <SliderRow key={v.id} id={v.id} left="Less" right={v.name} value={strengths[v.id] ?? 0} computed disabled={disabled} onChange={(x) => onChange(v.id, x)} onDelete={() => onDelete(v.id)} />+ ))}+ </div>+ )}+ </>+ )}+ </div>+ )+}++// ── Coordinates ───────────────────────────────────────────────────────++export type EntryState =+ | { state: 'ready' }+ | { state: 'prepare' }+ | { state: 'blocked'; why: string }++/** Whether a recipe line can run on this model, and if not, why. */+export function entryState(e: RecipeEntry, info: NeuronInfoPlus, vectorIds: ReadonlySet<string>, ids: { feature: (n: number) => string; neuron: (l: number, n: number) => string; own: (e: Extract<RecipeEntry, { kind: 'own' }>) => string }): EntryState {+ switch (e.kind) {+ case 'preset':+ if (vectorIds.has(e.id)) return { state: 'ready' }+ return info.generator ? { state: 'prepare' } : { state: 'blocked', why: 'This install is missing its vector tool.' }+ case 'own':+ if (vectorIds.has(ids.own(e))) return { state: 'ready' }+ return info.generator ? { state: 'prepare' } : { state: 'blocked', why: 'This install is missing its vector tool.' }+ case 'feature':+ if (!info.sae) return { state: 'blocked', why: 'This model has no feature data (only Gemma 3 270M IT and 1B IT have).' }+ if (e.feature >= info.sae.width) return { state: 'blocked', why: `This model's features go up to #${info.sae.width - 1}.` }+ if (vectorIds.has(ids.feature(e.feature))) return { state: 'ready' }+ return info.sae.downloaded ? { state: 'prepare' } : { state: 'blocked', why: 'Download the feature data first (Features tab).' }+ case 'neuron':+ if (e.layer >= info.facts.nLayer) return { state: 'blocked', why: `This model has ${info.facts.nLayer} layers (0–${info.facts.nLayer - 1}).` }+ if (info.nFf && e.neuron >= info.nFf) return { state: 'blocked', why: `Layers of this model have ${info.nFf} neurons.` }+ if (vectorIds.has(ids.neuron(e.layer, e.neuron))) return { state: 'ready' }+ if (!info.mlpNeurons) return { state: 'blocked', why: 'Pushing single neurons needs an LU Engine piece that is not in this build yet. You can still read and pass on the line.' }+ return { state: 'prepare' }+ }+}++function describe(e: RecipeEntry, presetName: (id: string) => string): string {+ switch (e.kind) {+ case 'preset': return `Ready-made slider ${presetName(e.id)} at ${signedValue(e.strength)}`+ case 'feature': return `Feature #${e.feature} at ${signedValue(e.strength)}`+ case 'neuron': return `Layer ${e.layer}, neuron ${e.neuron}, pushed ${e.dose < 0 ? 'down' : 'up'} by ${Math.abs(e.dose).toFixed(2)}`+ case 'own': return `Your-own slider “${e.name}” at ${signedValue(e.strength)}, from ${e.more.length} + ${e.less.length} example lines`+ }+}++const KIND_LABEL: Record<RecipeEntry['kind'], string> = { preset: 'Ready-made', feature: 'Feature', neuron: 'Neuron', own: 'From examples' }++export const COORD_EXAMPLES = [+ { label: 'Cheerful and brief', text: '@cheerful+0.50 @detailed-0.40' },+ { label: 'Calm and formal', text: '@cheerful-0.30 @casual-0.50' },+ { label: 'A shared neuron (Qwen3.5-4B)', text: 'Qwen3.5-4B: L13N7956-1.0 L14N8949+1.0' },+]++export function CoordinatesPanel({ presets, modelNames, states, onUse, disabled }: {+ presets: Array<{ id: string; left: string; right: string }>+ modelNames: Array<string | null | undefined>+ states: (e: RecipeEntry) => EntryState+ onUse: (recipe: Recipe) => void+ disabled: boolean+}) {+ const [text, setText] = useState('')+ const [anyway, setAnyway] = useState(false)+ const presetIds = useMemo(() => new Set(presets.map((p) => p.id)), [presets])+ const parsed = useMemo(() => (text.trim() ? parseRecipe(text, presetIds) : null), [text, presetIds])+ const fit: ModelFit = parsed?.ok ? modelFit(parsed.recipe.model, ...modelNames) : 'unknown'+ const modelBound = parsed?.ok && parsed.recipe.entries.some((e) => e.kind === 'neuron' || e.kind === 'feature')+ const presetName = (id: string) => {+ const p = presets.find((x) => x.id === id)+ return p ? `${p.left} ↔ ${p.right}` : id+ }+ const usable = parsed?.ok ? parsed.recipe.entries.filter((e) => states(e).state !== 'blocked') : []+ const blockedByModel = fit === 'other' && modelBound && !anyway+ return (+ <div className="space-y-3" data-testid="neuron-coords">+ <label className="block t-body text-gray-700 dark:text-gray-200">+ <span className="block mb-1 font-medium">Paste coordinates or an LU link</span>+ <textarea+ rows={3}+ value={text}+ onChange={(e) => { setText(e.target.value); setAnyway(false) }}+ placeholder={'Qwen3.5-4B: L13N7956-1.0 L14N8949+1.0\n@cheerful+0.5 F11690+0.8\nlocallyuncensored://neuron?v=1&…'}+ spellCheck={false}+ className={`${field} t-mono`}+ data-testid="neuron-coords-input"+ />+ </label>+ <div className="flex flex-wrap items-center gap-1.5">+ <span className={`t-micro ${HINWEIS_TEXT.ruhig} mr-1`}>Try:</span>+ {COORD_EXAMPLES.map((x) => (+ <button key={x.text} type="button" onClick={() => setText(x.text)} className="lu-control lu-control--outline t-micro" title={x.text}>{x.label}</button>+ ))}+ </div>++ {parsed && !parsed.ok && <Hinweis ton="fehler"><span data-testid="neuron-coords-error">{parsed.error}</span></Hinweis>}++ {parsed?.ok && (+ <div className="space-y-2" data-testid="neuron-coords-preview">+ <p className="t-body text-gray-700 dark:text-gray-200">+ {parsed.recipe.model ? <>Made on <span className="font-medium">{parsed.recipe.model}</span>. </> : null}+ {fit === 'same' && <span className="text-emerald-600 dark:text-emerald-400">That is the model you picked.</span>}+ {fit === 'other' && <span className="font-medium text-gray-900 dark:text-white" data-testid="neuron-coords-other-model">You picked another model.{modelBound ? ' Neuron and feature numbers belong to one exact model; on another they point at something unrelated.' : ' Ready-made and own sliders are computed fresh for yours, so they still work.'}</span>}+ </p>+ <ul className="divide-y divide-gray-100 dark:divide-white/[0.05] rounded-lg border border-gray-200 dark:border-white/[0.06]">+ {parsed.recipe.entries.map((e) => {+ const st = states(e)+ return (+ <li key={entryCode(e)} className="grid grid-cols-[6.5rem_1fr_auto] items-start gap-3 px-3 py-2" data-testid="neuron-coords-line">+ <span className="t-label text-gray-500 pt-1">{KIND_LABEL[e.kind]}</span>+ <div className="min-w-0">+ <p className="t-mono text-gray-900 dark:text-white truncate">{entryCode(e)}</p>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>{describe(e, presetName)}</p>+ {st.state === 'blocked' && <p className="t-micro text-gray-700 dark:text-gray-200 mt-0.5">{st.why}</p>}+ </div>+ <span className={`t-micro pt-1 ${st.state === 'ready' ? 'text-emerald-600 dark:text-emerald-400' : st.state === 'prepare' ? 'text-lu-accent' : HINWEIS_TEXT.ruhig}`}>+ {st.state === 'ready' ? 'Ready' : st.state === 'prepare' ? 'Will be prepared' : 'Not usable'}+ </span>+ </li>+ )+ })}+ </ul>+ {parsed.notes.map((n) => <p key={n} className={`t-micro ${HINWEIS_TEXT.ruhig}`}>{n}</p>)}+ {fit === 'other' && modelBound && (+ <label className="flex items-center gap-2 t-body text-gray-700 dark:text-gray-200">+ <input type="checkbox" checked={anyway} onChange={(e) => setAnyway(e.target.checked)} className="accent-lu-accent" data-testid="neuron-coords-anyway" />+ Use the numbers on my model anyway+ </label>+ )}+ <div className="flex flex-wrap items-center gap-2 pt-1">+ <button+ type="button"+ disabled={disabled || usable.length === 0 || blockedByModel}+ onClick={() => onUse({ model: parsed.recipe.model, entries: usable })}+ data-testid="neuron-coords-use"+ className="lu-control lu-primary"+ >+ {usable.length === 0 ? 'Nothing usable on this model' : usable.length === parsed.recipe.entries.length ? 'Use these values' : `Use the ${usable.length} usable values`} <ArrowRight size={ICON_SM} />+ </button>+ <span className={`t-micro ${HINWEIS_TEXT.ruhig}`}>Replaces your current sliders. You can undo.</span>+ </div>+ </div>+ )}++ <details className="pt-1">+ <summary className={`t-micro ${HINWEIS_TEXT.ruhig} cursor-pointer`}>How coordinates are written</summary>+ <ul className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1.5 space-y-1 list-disc pl-4`}>+ <li><span className="t-mono">L13N7956-1.0</span>: layer 13, MLP neuron 7956, pushed down by 1 (the form shared on neuronary.org and neuron-explorer since October 2026; <span className="t-mono">13:7956:-1.0</span> and <span className="t-mono">L13 N7956 −1.0</span> mean the same). Valid only for the exact model it was found on.</li>+ <li><span className="t-mono">@cheerful+0.5</span>: one of LU’s ready-made sliders. Works on any model, because LU computes it for yours.</li>+ <li><span className="t-mono">F11690+0.8</span>: feature 11690 of the model’s sparse autoencoder (Gemma Scope 2).</li>+ <li>An LU link also carries your own sliders as their example lines. LU reads only numbers and example sentences from a recipe, never files, addresses or commands.</li>+ </ul>+ </details>+ </div>+ )+}++// ── Before and after ──────────────────────────────────────────────────++export function ComparePanel({ modelPath, entries, disabled, model, tuning, onError, onDone }: {+ modelPath: string+ entries: ReturnType<typeof entriesFor>+ disabled: boolean+ model: BundledModel | undefined+ tuning: (m: BundledModel | undefined) => Promise<BuiltinEngineTuning | undefined>+ onError: (e: string) => void+ onDone?: () => void+}) {+ const [question, setQuestion] = useState('Write two sentences about rain.')+ const [seed, setSeed] = useState(42)+ const [busy, setBusy] = useState(false)+ const [result, setResult] = useState<(CompareResult & { entries: typeof entries }) | null>(null)+ const run = async () => {+ setBusy(true)+ try {+ const r = await neuronCompare(modelPath, question, seed, entries, await tuning(model))+ setResult({ ...r, entries })+ onDone?.()+ } catch (e) {+ onError(String(e))+ } finally {+ setBusy(false)+ }+ }+ const stale = result && !sameEntries(result.entries, entries)+ return (+ <div data-testid="neuron-compare" className="space-y-3">+ <div className="grid grid-cols-[1fr_auto_auto] items-end gap-2">+ <label className="block t-body text-gray-700 dark:text-gray-200 min-w-0">+ <span className="block mb-1 font-medium">Question</span>+ <input value={question} onChange={(e) => setQuestion(e.target.value)} data-testid="neuron-compare-question" className={field} />+ </label>+ <label className="block t-body text-gray-700 dark:text-gray-200">+ <span className="block mb-1 font-medium">Seed</span>+ <input type="number" value={seed} onChange={(e) => setSeed(Math.max(0, Math.floor(Number(e.target.value) || 0)))} className={`${fieldBase} w-20`} />+ </label>+ <button type="button" disabled={disabled || busy || !question.trim()} onClick={() => void run()} data-testid="neuron-compare-run" className="lu-control lu-primary h-[34px]">+ {busy && <Loader2 size={ICON_SM} className="animate-spin" />} Compare+ </button>+ </div>+ {entries.length === 0 && !result && <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>All sliders are at 0, so both answers will be the same. Move a slider in step 2 first.</p>}+ {result && (+ <>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3" data-testid="neuron-compare-result">+ <div className="rounded-lg border border-gray-200 dark:border-white/[0.08] p-3">+ <p className="t-label text-gray-500 mb-1.5">Before · sliders off</p>+ <p className="t-body text-gray-800 dark:text-gray-100 whitespace-pre-wrap" data-testid="neuron-compare-before">{result.before}</p>+ </div>+ <div className="rounded-lg border border-lu-accent/40 bg-lu-accent/[0.05] p-3">+ <p className="t-label text-lu-accent mb-1.5">After · {result.entries.map((e) => `${e.id} ${signedValue(e.strength)}`).join(', ') || 'all at 0'}</p>+ <p className="t-body text-gray-800 dark:text-gray-100 whitespace-pre-wrap" data-testid="neuron-compare-after">{result.after}</p>+ </div>+ </div>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-compare-same">+ {result.same ? 'Identical answers.' : 'The answers differ.'}{stale ? ' The sliders changed since; compare again.' : ''}+ </p>+ </>+ )}+ <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>Same question, same seed, temperature 0: once with the sliders off, once on. The engine restarts twice.</p>+ </div>+ )+}++// ── Share ─────────────────────────────────────────────────────────────++async function copy(text: string): Promise<boolean> {+ try {+ await navigator.clipboard.writeText(text)+ return true+ } catch {+ return false+ }+}++export function SharePanel({ recipe, skipped, onUndo }: { recipe: Recipe; skipped: string[]; onUndo?: () => void }) {+ const [copied, setCopied] = useState<'' | 'text' | 'link' | 'fail'>('')+ const line = coordsLine(recipe)+ const hasAny = recipe.entries.length > 0+ const flash = (k: 'text' | 'link', ok: boolean) => {+ setCopied(ok ? k : 'fail')+ window.setTimeout(() => setCopied(''), 1800)+ }+ return (+ <div className="space-y-2" data-testid="neuron-share">+ {hasAny ? (+ <>+ <p className="t-body text-gray-700 dark:text-gray-200">Your mix as coordinates. Others paste it under <span className="font-medium">Coordinates</span>.</p>+ <pre className="t-mono whitespace-pre-wrap break-all rounded-lg bg-gray-100 dark:bg-white/[0.05] px-3 py-2 text-gray-900 dark:text-white" data-testid="neuron-share-line">+ {[recipe.model, line || null].filter(Boolean).join(' · ')}+ {recipe.entries.some((e) => e.kind === 'own') ? `${line ? ' ' : ''}+ ${recipe.entries.filter((e) => e.kind === 'own').length} own slider(s) in the link` : ''}+ </pre>+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" className="lu-control lu-control--outline" data-testid="neuron-share-copy" onClick={() => void copy(recipeText(recipe)).then((ok) => flash('text', ok))}>+ {copied === 'text' ? <Check size={ICON_SM} /> : <ClipboardCopy size={ICON_SM} />} Copy coordinates+ </button>+ <button type="button" className="lu-control lu-control--outline" data-testid="neuron-share-link" onClick={() => void copy(recipeLink(recipe)).then((ok) => flash('link', ok))}>+ {copied === 'link' ? <Check size={ICON_SM} /> : <Link2 size={ICON_SM} />} Copy link+ </button>+ {copied === 'fail' && <span className="t-micro text-red-600 dark:text-red-400">The clipboard refused. Select the line above and copy it by hand.</span>}+ </div>+ {skipped.length > 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>Not in the recipe: {skipped.join(', ')}.</p>}+ </>+ ) : (+ <p className={`t-body ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-share-empty">Move a slider first. Your mix then shows here as a short line to copy.</p>+ )}+ {onUndo && (+ <button type="button" className="lu-control" onClick={onUndo} data-testid="neuron-coords-undo">+ <Undo2 size={ICON_SM} /> Undo the recipe+ </button>+ )}+ </div>+ )+}diff --git a/src/components/neuron/parts.tsx b/src/components/neuron/parts.tsxnew file mode 100644index 00000000..ebd02ab2--- /dev/null+++ b/src/components/neuron/parts.tsx@@ -0,0 +1,208 @@+// The building blocks of the Neurons page (N2, 3.0.9). David, 31.10.2026:+// "text left, sliders in the middle, then left again: no structure, one+// cannot see what to do". So every part of the page is one of these: a+// numbered step card whose content starts on the same left edge, and slider+// rows that read the same way everywhere (both ends on one line, the slider+// under them across the whole card).++import { Check, Loader2, Trash2 } from 'lucide-react'+import type { ReactNode } from 'react'+import { Hinweis } from '../ui/Hinweis'+import { HINWEIS_TEXT } from '../../lib/hinweis'+import { ICON_SM } from '../ui/icon-size'+import { jobProgressText, jobShare } from '../../lib/neuron'+import type { NeuronJob } from '../../api/neuron'++/** One step of the page: number, title, one line on what it is for, then+ * its content. A done step shows a check instead of its number. */+export function StepCard({ n, title, lead, done, aside, children, testId }: {+ n: number+ title: string+ lead: ReactNode+ done?: boolean+ aside?: ReactNode+ children: ReactNode+ testId?: string+}) {+ return (+ <section className="relative pl-10 pb-6" data-testid={testId} aria-labelledby={`neuron-step-${n}`}>+ {/* The line that ties the steps together, behind the numbers. */}+ <span aria-hidden className="absolute left-[13px] top-7 bottom-0 w-px bg-gray-200 dark:bg-white/[0.08] neuron-step-line" />+ <span+ aria-hidden+ className={`absolute left-0 top-0 w-7 h-7 rounded-full flex items-center justify-center t-control tabular-nums ${done ? 'bg-lu-accent text-white' : 'border border-gray-300 dark:border-white/20 text-gray-600 dark:text-gray-300 bg-white dark:bg-[#1a1a1a]'}`}+ data-step-done={done ? 'true' : 'false'}+ >+ {done ? <Check size={ICON_SM} /> : n}+ </span>+ <div className="flex items-start justify-between gap-3 min-h-7">+ <div className="min-w-0 pt-0.5">+ <h2 id={`neuron-step-${n}`} className="t-title text-gray-900 dark:text-white">{title}</h2>+ <p className={`t-body ${HINWEIS_TEXT.ruhig} mt-0.5`}>{lead}</p>+ </div>+ {aside && <div className="flex-none flex items-center gap-2">{aside}</div>}+ </div>+ <div className="mt-3 rounded-xl border border-gray-200 dark:border-white/[0.08] bg-white/60 dark:bg-white/[0.02] p-4">+ {children}+ </div>+ </section>+ )+}++export interface SliderRowProps {+ id: string+ left: string+ right: string+ value: number+ computed: boolean+ disabled?: boolean+ /** A short tag above the ends: "Ready-made", "Your slider", "Feature #…". */+ tag?: string+ onChange: (v: number) => void+ onCompute?: () => void+ onDelete?: () => void+}++export function signedValue(v: number): string {+ if (v === 0) return '0'+ return `${v > 0 ? '+' : '−'}${Math.abs(v).toFixed(2)}`+}++/** A slider as one card row: both ends and the value on one line, the+ * slider under it across the whole row. Not computed yet: the same line,+ * and in place of the slider the button that prepares it. */+export function SliderRow({ id, left, right, value, computed, disabled, tag, onChange, onCompute, onDelete }: SliderRowProps) {+ const on = computed && value !== 0+ return (+ <div+ className={`rounded-lg px-3 py-2.5 border ${on ? 'border-lu-accent/40 bg-lu-accent/[0.06]' : 'border-gray-200 dark:border-white/[0.06]'}`}+ data-testid={`neuron-slider-${id}`}+ >+ <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2">+ <span className="t-body text-gray-700 dark:text-gray-200 truncate" title={left}>{left}</span>+ <span className={`t-control tabular-nums px-1.5 py-0.5 rounded ${on ? 'text-lu-accent' : HINWEIS_TEXT.ruhig}`} data-testid={`neuron-value-${id}`}>+ {computed ? signedValue(value) : tag ?? ''}+ </span>+ <span className="flex items-center justify-end gap-1 min-w-0">+ <span className="t-body text-gray-700 dark:text-gray-200 truncate text-right" title={right}>{right}</span>+ {onDelete && (+ <button type="button" onClick={onDelete} aria-label={`Delete ${right}`} className="p-0.5 text-gray-400 hover:text-red-500 flex-none">+ <Trash2 size={ICON_SM} />+ </button>+ )}+ </span>+ </div>+ {computed ? (+ <input+ type="range"+ min={-1}+ max={1}+ step={0.05}+ value={value}+ disabled={disabled}+ aria-label={`${left} to ${right}`}+ aria-valuetext={signedValue(value)}+ onChange={(e) => onChange(Number(e.target.value))}+ onDoubleClick={() => onChange(0)}+ className="neuron-range w-full mt-1.5 accent-lu-accent"+ />+ ) : (+ <div className="mt-1.5 flex items-center gap-2">+ <button+ type="button"+ disabled={disabled}+ onClick={onCompute}+ data-testid={`neuron-compute-${id}`}+ className="lu-tonal"+ >+ Prepare for this model+ </button>+ <span className={`t-micro ${HINWEIS_TEXT.ruhig}`}>Once per model, seconds to a few minutes.</span>+ </div>+ )}+ </div>+ )+}++/** The ways to make a slider, as tabs. */+export function WayTabs<T extends string>({ ways, current, onPick }: {+ ways: Array<{ id: T; label: string; count?: number }>+ current: T+ onPick: (id: T) => void+}) {+ return (+ <div role="tablist" aria-label="Ways to tweak" className="flex flex-wrap gap-1 p-1 rounded-lg bg-gray-100 dark:bg-white/[0.04] mb-4">+ {ways.map((w) => (+ <button+ key={w.id}+ type="button"+ role="tab"+ id={`neuron-way-tab-${w.id}`}+ aria-selected={current === w.id}+ aria-controls={`neuron-way-${w.id}`}+ data-testid={`neuron-way-${w.id}`}+ onClick={() => onPick(w.id)}+ className={`flex-1 min-w-[7rem] t-control px-2.5 py-1.5 rounded-md transition-colors ${current === w.id ? 'bg-white dark:bg-white/[0.10] text-gray-900 dark:text-white shadow-sm' : 'text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white'}`}+ >+ {w.label}{w.count ? <span className="ml-1 tabular-nums text-lu-accent">{w.count}</span> : null}+ </button>+ ))}+ </div>+ )+}++/** The first line inside a way: what it is, in one sentence, and for whom. */+export function WayIntro({ icon, title, children }: { icon: ReactNode; title: string; children: ReactNode }) {+ return (+ <div className="flex items-start gap-3 mb-4">+ <span aria-hidden className="flex-none w-8 h-8 rounded-lg bg-lu-accent/10 text-lu-accent flex items-center justify-center">{icon}</span>+ <div className="min-w-0">+ <p className="t-body font-medium text-gray-900 dark:text-white">{title}</p>+ <p className={`t-body ${HINWEIS_TEXT.ruhig}`}>{children}</p>+ </div>+ </div>+ )+}++export function ScopeButton({ on, onClick, children }: { on: boolean; onClick: () => void; children: ReactNode }) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={on}+ onClick={onClick}+ className={`t-control px-2.5 py-1.5 rounded-md border ${on ? 'border-lu-accent/50 bg-lu-accent/10 text-gray-900 dark:text-white' : 'border-gray-200 dark:border-white/[0.08] text-gray-600 dark:text-gray-300'}`}+ >+ {children}+ </button>+ )+}++export function JobPanel({ job, onStop, onDismiss }: { job: NeuronJob; onStop: () => void; onDismiss: () => void }) {+ const share = jobShare(job)+ if (job.status === 'running') {+ return (+ <div className="space-y-1.5 mb-4 rounded-lg border border-lu-accent/30 bg-lu-accent/[0.05] px-3 py-2.5" data-testid="neuron-job" aria-live="polite">+ <p className="flex items-center gap-1.5 t-body text-gray-800 dark:text-gray-100">+ <Loader2 size={ICON_SM} className="animate-spin" /> {job.title}: {job.phaseLabel || 'starting…'}+ </p>+ <div className="h-1 rounded-full bg-gray-200 dark:bg-white/[0.08] overflow-hidden">+ <div className="h-full rounded-full bg-lu-accent transition-[width]" style={{ width: share == null ? '0%' : `${Math.round(share * 100)}%` }} />+ </div>+ <div className="flex items-center justify-between gap-2">+ <p className={`t-micro font-mono ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-job-progress">{jobProgressText(job)}</p>+ <button type="button" onClick={onStop} className="t-micro text-red-600 dark:text-red-400 hover:underline">Stop</button>+ </div>+ {job.logs.length > 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig} truncate`}>{job.logs[job.logs.length - 1]}</p>}+ </div>+ )+ }+ const strength = job.logs.find((l) => l.includes('full strength'))?.trim()+ return (+ <div className="mb-4" data-testid="neuron-job-ended">+ {job.status === 'done' && <Hinweis onDismiss={onDismiss}>{job.title}: done{job.elapsedSecs ? ` in ${job.elapsedSecs} s` : ''}.{strength ? ` ${strength}.` : ''}</Hinweis>}+ {job.status === 'failed' && <Hinweis ton="fehler" onDismiss={onDismiss}>{job.title} failed: {job.error}</Hinweis>}+ {job.status === 'cancelled' && <Hinweis onDismiss={onDismiss}>{job.title}: stopped.</Hinweis>}+ </div>+ )+}diff --git a/src/components/ui/command-actions.ts b/src/components/ui/command-actions.tsindex c474a53a..751e25c1 100644--- a/src/components/ui/command-actions.ts+++ b/src/components/ui/command-actions.ts@@ -14,6 +14,7 @@import type { ShortcutId } from '../../hooks/useKeyboardShortcuts'import type { View } from '../../stores/uiStore'+import { useNeuronIntroRequest } from '../../stores/neuronIntroStore'// Das Blattmodul und nicht die Sammelstelle `api/providers`: diese Datei laeuft// im Test ohne DOM und soll dabei keine Provider-Klassen und keinen Store// mitziehen. `model-name.ts` ist reine Zeichenkettenarbeit ohne Laufzeit-Import.@@ -126,6 +127,8 @@ export function buildCommands(ctx: CommandContext): Command[] {out.push({ id: 'view-voice', label: 'Voice', group: GROUP_VIEW, run: () => ctx.setView('voice') })out.push({ id: 'view-benchmark', label: 'Benchmark', group: GROUP_VIEW, run: () => ctx.setView('benchmark') })out.push({ id: 'view-neuron', label: 'Neuron tweaker', group: GROUP_VIEW, run: () => ctx.setView('neuron') })+ // N2 (3.0.9): the Neurons introduction again, after its one showing.+ out.push({ id: 'neuron-intro', label: 'Neurons: how it works', group: GROUP_VIEW, run: () => { ctx.setView('neuron'); useNeuronIntroRequest.getState().show() } })out.push({ id: 'view-models', label: 'Models', group: GROUP_VIEW, run: () => ctx.setView('models') })}out.push({ id: 'view-settings', label: 'Settings', group: GROUP_VIEW, run: () => ctx.setView('settings') })diff --git a/src/index.css b/src/index.cssindex a4555da2..bd9849a9 100644--- a/src/index.css+++ b/src/index.css@@ -2830,3 +2830,130 @@ html[data-computer-surface]:not([data-computer-surface='window']) #root {@media (prefers-reduced-motion: reduce) {.lu-develop { animation: none; }}++/* ──────────────────────────────────────────────────────────────────+ Neurons introduction (N2, 3.0.9). Calm loops of 3–6 s, nothing that+ blinks. Colours from the house tokens: the accent for what the user+ adds, the greys of the page for the model. With reduced motion every+ drawing stands still in its finished state.+ ───────────────────────────────────────────────────────────────── */+.neuron-intro .nintro-label { font-size: 10px; font-weight: 600; letter-spacing: 0.04em; }+.neuron-intro .nintro-code { font-size: 12px; font-family: ui-monospace, 'JetBrains Mono', 'SF Mono', Menlo, monospace; fill: #111827; }+.dark .neuron-intro .nintro-code { fill: #f3f4f6; }+.neuron-intro .nintro-muted-text { fill: #6b7280; }+.dark .neuron-intro .nintro-muted-text { fill: #9ca3af; }+.neuron-intro .nintro-accent-text { fill: var(--color-lu-accent); }+.neuron-intro .nintro-accent-stroke { stroke: var(--color-lu-accent); }+.neuron-intro .nintro-accent-fill { fill: var(--color-lu-accent); }+.neuron-intro .nintro-accent-fill-soft { fill: color-mix(in srgb, var(--color-lu-accent) 16%, transparent); }+.neuron-intro .nintro-layer { fill: #e5e7eb; }+.dark .neuron-intro .nintro-layer { fill: rgba(255, 255, 255, 0.10); }+.neuron-intro .nintro-layer--hit { animation: lu-nintro-hit 3s ease-in-out infinite; }+.neuron-intro .nintro-token { fill: #9ca3af; animation: lu-nintro-rise 2.1s ease-in infinite; }+.neuron-intro .nintro-push { animation: lu-nintro-push 3s ease-in-out infinite; }+.neuron-intro .nintro-track { stroke: #d1d5db; }+.dark .neuron-intro .nintro-track { stroke: rgba(255, 255, 255, 0.16); }+.neuron-intro .nintro-knob-fill { fill: #ffffff; stroke: #9ca3af; stroke-width: 1.5; }+.dark .neuron-intro .nintro-knob-fill { fill: #2a2a2a; stroke: #6b7280; }+.neuron-intro .nintro-knob { animation: lu-nintro-knob 4.2s ease-in-out infinite; }+.neuron-intro .nintro-card { fill: #ffffff; stroke: #e5e7eb; stroke-width: 1; }+.dark .neuron-intro .nintro-card { fill: rgba(255, 255, 255, 0.04); stroke: rgba(255, 255, 255, 0.10); }+.neuron-intro .nintro-card--accent { fill: color-mix(in srgb, var(--color-lu-accent) 8%, transparent); stroke: color-mix(in srgb, var(--color-lu-accent) 45%, transparent); }+.neuron-intro .nintro-line { fill: #d1d5db; transform-box: fill-box; transform-origin: left center; animation: lu-nintro-write 4.4s ease-out infinite; }+.dark .neuron-intro .nintro-line { fill: rgba(255, 255, 255, 0.18); }+.neuron-intro .nintro-line--accent,+.dark .neuron-intro .nintro-line--accent { fill: var(--color-lu-accent); }+.neuron-intro .nintro-type { clip-path: inset(0 100% 0 0); animation: lu-nintro-type 5s steps(26, end) infinite; }+.neuron-intro .nintro-glow { opacity: 0; animation: lu-nintro-glow 5s ease-in-out infinite; }+.neuron-intro .nintro-dash { stroke-dashoffset: 40; animation: lu-nintro-dash 5s linear infinite; }+.neuron-intro .nintro-arrive { opacity: 0; animation: lu-nintro-arrive 5s ease-out infinite; }+.neuron-intro .nintro-tile { opacity: 0; animation: lu-nintro-tile 0.5s ease-out forwards; }++@keyframes lu-nintro-rise {+ 0% { transform: translateY(0); opacity: 0; }+ 15% { opacity: 1; }+ 85% { opacity: 1; }+ 100% { transform: translateY(-150px); opacity: 0; }+}+@keyframes lu-nintro-hit {+ 0%, 30%, 100% { fill: #e5e7eb; }+ 50%, 70% { fill: color-mix(in srgb, var(--color-lu-accent) 55%, transparent); }+}+.dark .neuron-intro .nintro-layer--hit { animation-name: lu-nintro-hit-dark; }+@keyframes lu-nintro-hit-dark {+ 0%, 30%, 100% { fill: rgba(255, 255, 255, 0.10); }+ 50%, 70% { fill: color-mix(in srgb, var(--color-lu-accent) 60%, transparent); }+}+@keyframes lu-nintro-push {+ 0%, 20% { transform: translateX(14px); opacity: 0.2; }+ 50%, 80% { transform: translateX(0); opacity: 1; }+ 100% { transform: translateX(14px); opacity: 0.2; }+}+@keyframes lu-nintro-knob {+ 0%, 100% { transform: translateY(0); }+ 45%, 70% { transform: translateY(var(--nintro-to, 0px)); }+}+@keyframes lu-nintro-write {+ 0% { transform: scaleX(0); }+ 30%, 85% { transform: scaleX(1); }+ 100% { transform: scaleX(1); opacity: 0; }+}+@keyframes lu-nintro-type {+ 0% { clip-path: inset(0 100% 0 0); }+ 45%, 100% { clip-path: inset(0 0 0 0); }+}+@keyframes lu-nintro-glow {+ 0%, 45% { opacity: 0; }+ 55%, 80% { opacity: 1; }+ 100% { opacity: 0; }+}+@keyframes lu-nintro-dash {+ 0%, 55% { stroke-dashoffset: 40; opacity: 0; }+ 60% { opacity: 1; }+ 100% { stroke-dashoffset: 0; opacity: 1; }+}+@keyframes lu-nintro-arrive {+ 0%, 70% { opacity: 0; }+ 80%, 100% { opacity: 1; }+}+@keyframes lu-nintro-tile {+ from { opacity: 0; transform: translateY(6px); }+ to { opacity: 1; transform: none; }+}++@media (prefers-reduced-motion: reduce) {+ .neuron-intro .nintro-layer--hit,+ .neuron-intro .nintro-token,+ .neuron-intro .nintro-push,+ .neuron-intro .nintro-knob,+ .neuron-intro .nintro-line,+ .neuron-intro .nintro-type,+ .neuron-intro .nintro-glow,+ .neuron-intro .nintro-dash,+ .neuron-intro .nintro-arrive,+ .neuron-intro .nintro-tile { animation: none; }+ .neuron-intro .nintro-token { opacity: 0; }+ .neuron-intro .nintro-type { clip-path: none; }+ .neuron-intro .nintro-glow,+ .neuron-intro .nintro-arrive,+ .neuron-intro .nintro-tile,+ .neuron-intro .nintro-dash { opacity: 1; }+ .neuron-intro .nintro-knob { transform: translateY(var(--nintro-to, 0px)); }+}++/* Neurons slider (N2): the house range (track and knob above), with a+ mark at 0 so "unchanged" can be seen, and a taller hit area. */+input[type="range"].neuron-range,+.light input[type="range"].neuron-range {+ height: 18px;+ cursor: pointer;+ background:+ linear-gradient(to right, transparent calc(50% - 1px), rgba(0, 0, 0, 0.35) calc(50% - 1px), rgba(0, 0, 0, 0.35) calc(50% + 1px), transparent calc(50% + 1px)) center / 100% 12px no-repeat,+ linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)) center / 100% 4px no-repeat;+}+.dark input[type="range"].neuron-range {+ background:+ linear-gradient(to right, transparent calc(50% - 1px), rgba(255, 255, 255, 0.35) calc(50% - 1px), rgba(255, 255, 255, 0.35) calc(50% + 1px), transparent calc(50% + 1px)) center / 100% 12px no-repeat,+ linear-gradient(rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.1)) center / 100% 4px no-repeat;+}+input[type="range"].neuron-range:disabled { cursor: not-allowed; opacity: 0.5; }diff --git a/src/lib/__tests__/neuron-recipe.test.ts b/src/lib/__tests__/neuron-recipe.test.tsnew file mode 100644index 00000000..af75ffee--- /dev/null+++ b/src/lib/__tests__/neuron-recipe.test.ts@@ -0,0 +1,157 @@+/**+ * N2 (3.0.9): neuron recipes, the "coordinates" people share. LU reads the+ * codes in use (neuronary "L13N7956-1.0", gguf-neuron-explorer "14:8949:+1.0",+ * "L9 N9009 +0.7"), its own sliders and links, and refuses everything else+ * with a reason: a recipe carries numbers and example sentences, nothing+ * that could run.+ *+ * Run: npx vitest run src/lib/__tests__/neuron-recipe.test.ts+ */+import { describe, it, expect } from 'vitest'+import {+ coordsLine, featureVectorId, modelFit, neuronVectorId, normalizeModelName, parseRecipe, recipeLink, recipeOwnId, recipeText,+ type Recipe,+} from '../neuron-recipe'++const PRESETS = new Set(['creative', 'detailed', 'casual', 'cheerful', 'refusals'])+const ok = (s: string) => {+ const r = parseRecipe(s, PRESETS)+ if (!r.ok) throw new Error(r.error)+ return r+}+const bad = (s: string) => {+ const r = parseRecipe(s, PRESETS)+ if (r.ok) throw new Error(`accepted: ${s}`)+ return r.error+}++describe('reading coordinates people share', () => {+ it('reads the neuronary form with its model', () => {+ const r = ok('Qwen3.5-4B: L13N7956-1.0 L14N8949+1.0')+ expect(r.recipe.model).toBe('Qwen3.5-4B')+ expect(r.recipe.entries).toEqual([+ { kind: 'neuron', layer: 13, neuron: 7956, dose: -1 },+ { kind: 'neuron', layer: 14, neuron: 8949, dose: 1 },+ ])+ })++ it('reads the colon form and the spaced form', () => {+ expect(ok('14:8949:+1.0').recipe.entries).toEqual([{ kind: 'neuron', layer: 14, neuron: 8949, dose: 1 }])+ expect(ok('L9 N9009 +0.7, L26 N6173 +0.3').recipe.entries).toEqual([+ { kind: 'neuron', layer: 9, neuron: 9009, dose: 0.7 },+ { kind: 'neuron', layer: 26, neuron: 6173, dose: 0.3 },+ ])+ expect(ok('L22 N8295 −0.4').recipe.entries).toEqual([{ kind: 'neuron', layer: 22, neuron: 8295, dose: -0.4 }])+ })++ it('reads a negative ready slider, whose id may hold dashes', () => {+ expect(ok('@detailed-0.40 @cheerful+0.5').recipe.entries).toEqual([+ { kind: 'preset', id: 'detailed', strength: -0.4 },+ { kind: 'preset', id: 'cheerful', strength: 0.5 },+ ])+ expect(parseRecipe('@more-refusals-0.3', new Set(['more-refusals'])).ok).toBe(true)+ expect(bad('@cheerful0.5')).toMatch(/not a coordinate/)+ })++ it('reads LU sliders and features', () => {+ expect(ok('@cheerful+0.6 F11690+0.8').recipe.entries).toEqual([+ { kind: 'preset', id: 'cheerful', strength: 0.6 },+ { kind: 'feature', feature: 11690, strength: 0.8 },+ ])+ })++ it('keeps the last value of a coordinate given twice, and says so', () => {+ const r = ok('L1N2+0.5 L1N2-0.5')+ expect(r.recipe.entries).toEqual([{ kind: 'neuron', layer: 1, neuron: 2, dose: -0.5 }])+ expect(r.notes.join(' ')).toMatch(/twice/)+ })+})++describe('refusing what does not fit', () => {+ it('refuses what other programs do that LU cannot', () => {+ expect(bad('L12E12N1234+0.6')).toMatch(/mixture-of-experts/)+ expect(bad('22:2742:x4')).toMatch(/gain/)+ expect(bad('21:H7:x0')).toMatch(/gain/)+ expect(bad('30:dir:yandere:+0.3')).toMatch(/direction file/)+ })++ it('refuses unknown sliders, wild numbers and garbage', () => {+ expect(bad('@pirate+0.5')).toMatch(/no ready slider/)+ expect(bad('@cheerful+1.5')).toMatch(/outside/)+ expect(bad('L1N2+3.5')).toMatch(/outside/)+ expect(bad('L999N2+0.5')).toMatch(/too large/)+ expect(bad('rm -rf /')).toMatch(/not a coordinate/)+ expect(bad('')).toMatch(/Paste/)+ expect(bad('L1N2+0.5 '.repeat(2000))).toMatch(/Too long/)+ expect(bad(Array.from({ length: 30 }, (_, i) => `L1N${i}+0.1`).join(' '))).toMatch(/at most 24/)+ })++ it('refuses hidden characters and foreign addresses', () => {+ expect(bad('L1N2+0.5')).toMatch(/hidden/)+ expect(bad('L1N2+0.5\u0007')).toMatch(/hidden/)+ expect(bad('https://example.com/evil.gguf')).toMatch(/no other web addresses/)+ expect(bad('file:///etc/passwd')).toMatch(/no other web addresses/)+ })+})++describe('LU links', () => {+ const recipe: Recipe = {+ model: 'Qwen2.5-0.5B-Instruct',+ entries: [+ { kind: 'preset', id: 'cheerful', strength: 0.6 },+ { kind: 'neuron', layer: 13, neuron: 7956, dose: -1 },+ { kind: 'own', name: 'Pirate', more: ['Talk like a pirate.', 'Say arr.'], less: ['Talk plainly.'], strength: 0.5 },+ ],+ }++ it('goes out and comes back unchanged, own sliders included', () => {+ const link = recipeLink(recipe)+ expect(link.startsWith('locallyuncensored://neuron?v=1&')).toBe(true)+ const back = ok(link)+ expect(back.recipe).toEqual(recipe)+ // The copy line is readable and carries the same link.+ const text = recipeText(recipe)+ expect(text.split('\n')[0]).toBe('LU neurons · Qwen2.5-0.5B-Instruct · @cheerful+0.60 L13N7956-1.00')+ expect(ok(text).recipe).toEqual(recipe)+ expect(coordsLine(recipe)).toBe('@cheerful+0.60 L13N7956-1.00')+ })++ it('reads the copy line alone, without the link', () => {+ const r = ok('LU neurons · Qwen2.5-0.5B-Instruct · @cheerful+0.60 L13N7956-1.00')+ expect(r.recipe.model).toBe('Qwen2.5-0.5B-Instruct')+ expect(r.recipe.entries).toHaveLength(2)+ })++ it('refuses links with anything a neuron link never has', () => {+ expect(bad('locallyuncensored://neuron?v=1&c=L1N2%2B0.5&url=https://x')).toMatch(/never has/)+ expect(bad('locallyuncensored://neuron?v=1&c=L1N2%2B0.5&c=L1N3%2B0.5')).toMatch(/twice/)+ expect(bad('locallyuncensored://open-model?repo=a/b')).toMatch(/not an LU neuron link/)+ expect(bad('locallyuncensored://neuron/../x?v=1&c=L1N2%2B0.5')).toMatch(/not an LU neuron link/)+ expect(bad('locallyuncensored://neuron?v=2&c=L1N2%2B0.5')).toMatch(/newer LU/)+ expect(bad('locallyuncensored://neuron?v=1&o=%5B%7B%22n%22%3A%22x%22%2C%22s%22%3A0.5%2C%22m%22%3A%5B%22a%22%5D%2C%22l%22%3A%5B%22b%22%5D%2C%22cmd%22%3A%22rm%22%7D%5D')).toMatch(/fields LU does not read/)+ expect(bad('locallyuncensored://neuron?v=1&o=not-json')).toMatch(/damaged/)+ expect(bad('locallyuncensored://neuron?v=1&o=' + encodeURIComponent(JSON.stringify([{ n: 'x', s: 0.5, m: ['a\nb'], l: ['c'] }])))).toMatch(/example lines/)+ })+})++describe('model names and ids', () => {+ it('sees the same model in a repo name and a file name', () => {+ expect(normalizeModelName('Qwen/Qwen3.5-4B')).toBe('qwen354b')+ expect(normalizeModelName('qwen3.5-4b-q8_0.gguf')).toBe('qwen354b')+ expect(modelFit('Qwen/Qwen3.5-4B', 'Qwen3.5 4B', 'qwen3.5-4b-q8_0')).toBe('same')+ expect(modelFit('Qwen/Qwen3.5-4B', 'Qwen2.5 0.5B Instruct', 'qwen2.5-0.5b-instruct-q8_0')).toBe('other')+ expect(modelFit(null, 'x')).toBe('unknown')+ })++ it('gives an own slider from a recipe the same id every time, one Rust accepts', () => {+ const e = { kind: 'own' as const, name: 'Pirate talk!', more: ['a'], less: ['b'], strength: 0.5 }+ const id = recipeOwnId(e)+ expect(id).toBe(recipeOwnId({ ...e, strength: -1 }))+ expect(id).not.toBe(recipeOwnId({ ...e, more: ['c'] }))+ expect(id).toMatch(/^own-pirate-talk-r[0-9a-f]+$/)+ expect(id.length).toBeLessThanOrEqual(48)+ expect(featureVectorId('gemma-scope-2-270m-it-l9', 11690)).toBe('f-g270m-11690')+ expect(featureVectorId('gemma-scope-2-1b-it-l13', 5)).toBe('f-g1b-5')+ expect(neuronVectorId(13, 7956)).toBe('n-L13-N7956')+ })+})diff --git a/src/lib/neuron-recipe.ts b/src/lib/neuron-recipe.tsnew file mode 100644index 00000000..eb79ee26--- /dev/null+++ b/src/lib/neuron-recipe.ts@@ -0,0 +1,372 @@+// Neuron recipes (3.0.9, N2): what people share as "coordinates", read and+// written by LU.+//+// Since late October 2026 people pass single MLP neurons around as short+// codes, "L13N7956-1.0 L14N8949+1.0" (neuronary.org, neuron-explorer),+// "14:8949:+1.0" (gguf-neuron-explorer) or "L9 N9009 +0.7". LU reads those,+// and writes its own sliders the same way:+//+// @cheerful+0.60 a ready slider, by its id+// F11690+0.80 a feature of the model's sparse autoencoder+// L13N7956-1.00 layer 13, MLP neuron 7956, dose −1+// own sliders only in the link, as their example lines+//+// One line to copy: "LU neurons · <model> · <coordinates>", and a link+// "locallyuncensored://neuron?v=1&model=…&c=…&o=…" that also carries own+// sliders. A recipe holds numbers and example sentences, nothing else: no+// path, no address, no command. Everything is checked strictly; whatever+// does not fit is refused with the reason, never guessed.++export type RecipeEntry =+ | { kind: 'preset'; id: string; strength: number }+ | { kind: 'feature'; feature: number; strength: number }+ | { kind: 'neuron'; layer: number; neuron: number; dose: number }+ | { kind: 'own'; name: string; more: string[]; less: string[]; strength: number }++export interface Recipe {+ /** The model the recipe was made on, as its maker named it. */+ model: string | null+ entries: RecipeEntry[]+}++export type RecipeParse =+ | { ok: true; recipe: Recipe; notes: string[] }+ | { ok: false; error: string }++export const RECIPE_SCHEME = 'locallyuncensored'+export const RECIPE_HOST = 'neuron'+export const RECIPE_MAX_CHARS = 8000+export const RECIPE_MAX_ENTRIES = 24+/** Neuron doses are in median residual norms (the neuronary unit); shared+ * recipes stay within about ±1.2, and ±3 already wrecks any model. */+export const NEURON_MAX_DOSE = 3+const MAX_LAYER = 511+const MAX_INDEX = 1 << 20+const OWN_MAX_LINES = 40+const OWN_MAX_LINE = 300+const OWN_MAX_NAME = 40+const MODEL_MAX = 120++const NUM = '([-+−]?\\d{1,2}(?:\\.\\d{1,4})?)'+// A slider id may hold dashes, so its value needs its sign: "@detailed-0.4"+// is detailed at −0.4, not a slider called "detailed-".+const SIGNED = '([-+−]\\d{1,2}(?:\\.\\d{1,4})?)'+const RE_PRESET = new RegExp(`^@([a-z][a-z0-9-]{0,31}?)${SIGNED}$`)+const RE_FEATURE = new RegExp(`^F(\\d{1,7})${NUM}$`, 'i')+const RE_NEURON = new RegExp(`^L(\\d{1,3})N(\\d{1,7})${NUM}$`, 'i')+const RE_COLON = new RegExp(`^(\\d{1,3}):(\\d{1,7}):${NUM}$`)+const RE_MODEL = /^[\p{L}\p{N} ._\-/:()+]+$/u++function num(s: string): number {+ return Number(s.replace('−', '-'))+}++/** Control characters other than line breaks and tabs: never in a recipe. */+function hasControl(s: string): boolean {+ // eslint-disable-next-line no-control-regex+ return /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f--]/.test(s)+}++function short(s: string): string {+ return s.length > 24 ? `${s.slice(0, 24)}…` : s+}++/** Tokens like "L9", "N9009", "+0.7" written apart are glued back together,+ * so "L9 N9009 +0.7" reads as one coordinate. */+function glue(tokens: string[]): string[] {+ const out: string[] = []+ for (let i = 0; i < tokens.length; i++) {+ const t = tokens[i]+ if (/^L\d{1,3}$/i.test(t) && /^N\d{1,7}$/i.test(tokens[i + 1] ?? '') && /^[-+−]?\d/.test(tokens[i + 2] ?? '')) {+ out.push(`${t}${tokens[i + 1]}${tokens[i + 2]}`)+ i += 2+ } else if (/^L\d{1,3}N\d{1,7}$/i.test(t) && /^[-+−]\d/.test(tokens[i + 1] ?? '')) {+ out.push(`${t}${tokens[i + 1]}`)+ i += 1+ } else out.push(t)+ }+ return out+}++/** Why a code that looks like a coordinate is not one LU can use. */+function unsupported(t: string): string | null {+ if (/^L\d+E\d+N\d+/i.test(t) || /^\d+:E\d+:/i.test(t)) return `“${short(t)}” is a neuron inside a mixture-of-experts layer. LU can only push neurons of dense layers.`+ if (/^\d+:\d+:x/i.test(t) || /^\d+:H\d+/i.test(t)) return `“${short(t)}” scales a neuron or head (gain). LU only adds directions, so it cannot apply this one.`+ if (/^\d+:dir:/i.test(t)) return `“${short(t)}” names a direction file from another program. Make it in LU from examples instead.`+ return null+}++function checkStrength(t: string, v: number, max: number): string | null {+ if (!Number.isFinite(v)) return `“${short(t)}” has no valid number.`+ if (Math.abs(v) > max) return `“${short(t)}”: ${v} is outside −${max} … +${max}.`+ return null+}++/** One coordinate token, or the reason it is refused. */+export function parseToken(raw: string, presetIds: ReadonlySet<string>): RecipeEntry | string {+ const t = raw.trim().replace(/,$/, '')+ let m = RE_PRESET.exec(t)+ if (m) {+ if (!presetIds.has(m[1])) return `“${short(t)}”: LU has no ready slider called “${m[1]}”.`+ const s = num(m[2])+ return checkStrength(t, s, 1) ?? { kind: 'preset', id: m[1], strength: s }+ }+ m = RE_FEATURE.exec(t)+ if (m) {+ const f = Number(m[1])+ if (f >= MAX_INDEX) return `“${short(t)}”: feature number too large.`+ const s = num(m[2])+ return checkStrength(t, s, 1) ?? { kind: 'feature', feature: f, strength: s }+ }+ m = RE_NEURON.exec(t) ?? RE_COLON.exec(t)+ if (m) {+ const layer = Number(m[1])+ const neuron = Number(m[2])+ if (layer > MAX_LAYER || neuron >= MAX_INDEX) return `“${short(t)}”: layer or neuron number too large.`+ const d = num(m[3])+ return checkStrength(t, d, NEURON_MAX_DOSE) ?? { kind: 'neuron', layer, neuron, dose: d }+ }+ return unsupported(t) ?? `“${short(t)}” is not a coordinate LU knows. Examples: L14N8949+1.0, @cheerful+0.5, F11690+0.8.`+}++function cleanLines(v: unknown): string[] | null {+ if (!Array.isArray(v) || v.length === 0 || v.length > OWN_MAX_LINES) return null+ const out: string[] = []+ for (const l of v) {+ if (typeof l !== 'string') return null+ const s = l.trim()+ if (!s || s.length > OWN_MAX_LINE || hasControl(s) || /[\r\n]/.test(s)) return null+ out.push(s)+ }+ return out+}++/** Own sliders from the link's `o` parameter: a JSON list of+ * {n: name, s: strength, m: [more…], l: [less…]}. */+function parseOwn(json: string): RecipeEntry[] | string {+ let data: unknown+ try {+ data = JSON.parse(json)+ } catch {+ return 'The own sliders in this link are damaged.'+ }+ if (!Array.isArray(data) || data.length > 8) return 'The own sliders in this link are damaged.'+ const out: RecipeEntry[] = []+ for (const d of data) {+ if (!d || typeof d !== 'object' || Array.isArray(d)) return 'The own sliders in this link are damaged.'+ const keys = Object.keys(d)+ if (keys.some((k) => !['n', 's', 'm', 'l'].includes(k))) return 'The own sliders in this link carry fields LU does not read.'+ const { n, s, m, l } = d as Record<string, unknown>+ if (typeof n !== 'string' || !n.trim() || n.trim().length > OWN_MAX_NAME || hasControl(n)) return 'An own slider in this link has no usable name.'+ if (typeof s !== 'number' || !Number.isFinite(s) || Math.abs(s) > 1) return `Own slider “${short(n)}”: strength outside −1 … +1.`+ const more = cleanLines(m)+ const less = cleanLines(l)+ if (!more || !less) return `Own slider “${short(n)}”: needs 1–${OWN_MAX_LINES} example lines on each side, each up to ${OWN_MAX_LINE} characters.`+ out.push({ kind: 'own', name: n.trim(), more, less, strength: s })+ }+ return out+}++function entryKey(e: RecipeEntry): string {+ switch (e.kind) {+ case 'preset': return `p:${e.id}`+ case 'feature': return `f:${e.feature}`+ case 'neuron': return `n:${e.layer}:${e.neuron}`+ case 'own': return `o:${e.name.toLowerCase()}`+ }+}++function finish(model: string | null, entries: RecipeEntry[]): RecipeParse {+ if (entries.length === 0) return { ok: false, error: 'No coordinates found. Paste a line like “L14N8949+1.0 @cheerful+0.5”, or an LU link.' }+ const notes: string[] = []+ const byKey = new Map<string, RecipeEntry>()+ for (const e of entries) {+ const k = entryKey(e)+ if (byKey.has(k)) notes.push(`${k.startsWith('n:') ? 'A neuron' : 'A slider'} appears twice; the last value counts.`)+ byKey.set(k, e)+ }+ if (byKey.size > RECIPE_MAX_ENTRIES) return { ok: false, error: `More than ${RECIPE_MAX_ENTRIES} coordinates. LU takes at most ${RECIPE_MAX_ENTRIES} at once.` }+ if (model !== null && (model.length > MODEL_MAX || !RE_MODEL.test(model))) return { ok: false, error: 'The model name in this recipe has characters LU does not accept.' }+ return { ok: true, recipe: { model, entries: [...byKey.values()] }, notes: [...new Set(notes)] }+}++function parseCoords(text: string, presetIds: ReadonlySet<string>): RecipeEntry[] | string {+ const tokens = glue(text.split(/[\s,;]+/).filter(Boolean))+ const out: RecipeEntry[] = []+ for (const t of tokens) {+ const e = parseToken(t, presetIds)+ if (typeof e === 'string') return e+ out.push(e)+ }+ return out+}++function parseLink(link: string, presetIds: ReadonlySet<string>): RecipeParse {+ let url: URL+ try {+ url = new URL(link)+ } catch {+ return { ok: false, error: 'This link is damaged.' }+ }+ if (url.protocol !== `${RECIPE_SCHEME}:`) return { ok: false, error: 'Only LU neuron links are read here.' }+ // `locallyuncensored://neuron?…`: the host is "neuron" (some engines put+ // it into the path for unknown schemes).+ const host = url.host || url.pathname.replace(/^\/\//, '').split('/')[0]+ const rest = url.host ? url.pathname : url.pathname.replace(/^\/\/[^/?]*/, '')+ if (host !== RECIPE_HOST || (rest && rest !== '/') || url.hash || url.username || url.password || url.port) {+ return { ok: false, error: 'This is not an LU neuron link.' }+ }+ const seen = new Set<string>()+ for (const k of url.searchParams.keys()) {+ if (!['v', 'model', 'c', 'o'].includes(k)) return { ok: false, error: `The link carries “${short(k)}”, which a neuron link never has. Nothing was read.` }+ if (seen.has(k)) return { ok: false, error: `The link carries “${k}” twice. Nothing was read.` }+ seen.add(k)+ }+ if (url.searchParams.get('v') !== '1') return { ok: false, error: 'This link is from a newer LU. Update LU to read it.' }+ const model = url.searchParams.get('model')+ const entries: RecipeEntry[] = []+ const c = url.searchParams.get('c')+ if (c) {+ if (hasControl(c)) return { ok: false, error: 'The link has hidden characters. Nothing was read.' }+ const coords = parseCoords(c, presetIds)+ if (typeof coords === 'string') return { ok: false, error: coords }+ entries.push(...coords)+ }+ const o = url.searchParams.get('o')+ if (o) {+ const own = parseOwn(o)+ if (typeof own === 'string') return { ok: false, error: own }+ entries.push(...own)+ }+ return finish(model?.trim() || null, entries)+}++/**+ * Reads what someone pasted: an LU link, LU's own copy line, or plain+ * coordinates from elsewhere ("Qwen3.5-4B: L13N7956-1.0 L14N8949+1.0").+ */+export function parseRecipe(input: string, presetIds: ReadonlySet<string>): RecipeParse {+ const text = input.trim()+ if (!text) return { ok: false, error: 'Paste coordinates or an LU neuron link first.' }+ if (text.length > RECIPE_MAX_CHARS) return { ok: false, error: `Too long: LU reads recipes up to ${RECIPE_MAX_CHARS} characters.` }+ if (hasControl(text)) return { ok: false, error: 'The text has hidden characters. Nothing was read.' }++ // A link anywhere in the text wins: LU's copy puts it on the second line.+ const link = /locallyuncensored:\/\/\S+/i.exec(text)+ if (link) return parseLink(link[0], presetIds)+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) return { ok: false, error: 'LU reads only its own neuron links and plain coordinates, no other web addresses.' }++ // "LU neurons · Model · coords", "Model: coords" or just coords.+ let model: string | null = null+ let coords = text+ const parts = text.split(/\s+[·|]\s+/)+ if (parts.length > 1) {+ const kept = parts.filter((p) => !/^LU neurons$/i.test(p.trim()))+ if (kept.length >= 2) {+ model = kept[0].trim()+ coords = kept.slice(1).join(' ')+ } else coords = kept.join(' ')+ } else {+ const colon = /^([^:]{2,120}):\s+(.+)$/s.exec(text)+ if (colon && !/^\d+$/.test(colon[1].trim()) && typeof parseToken(colon[1].trim().split(/\s+/)[0], presetIds) === 'string') {+ model = colon[1].trim()+ coords = colon[2]+ }+ }+ const entries = parseCoords(coords, presetIds)+ if (typeof entries === 'string') return { ok: false, error: entries }+ return finish(model, entries)+}++function signed(v: number): string {+ return `${v < 0 ? '-' : '+'}${Math.abs(v).toFixed(2)}`+}++export function entryCode(e: RecipeEntry): string {+ switch (e.kind) {+ case 'preset': return `@${e.id}${signed(e.strength)}`+ case 'feature': return `F${e.feature}${signed(e.strength)}`+ case 'neuron': return `L${e.layer}N${e.neuron}${signed(e.dose)}`+ case 'own': return `“${e.name}” ${signed(e.strength)}`+ }+}++/** The coordinates as one line, own sliders left out (they travel in the+ * link). */+export function coordsLine(recipe: Recipe): string {+ return recipe.entries.filter((e) => e.kind !== 'own').map(entryCode).join(' ')+}++/** The model name a recipe carries: plain, without characters a reader+ * would refuse. */+export function recipeModelName(name: string): string {+ return name.replace(/[^\p{L}\p{N} ._\-/()+]/gu, '').trim().slice(0, MODEL_MAX)+}++export function recipeLink(recipe: Recipe): string {+ const p = new URLSearchParams()+ p.set('v', '1')+ if (recipe.model) p.set('model', recipeModelName(recipe.model))+ const c = coordsLine(recipe)+ if (c) p.set('c', c)+ const own = recipe.entries.filter((e): e is Extract<RecipeEntry, { kind: 'own' }> => e.kind === 'own')+ if (own.length) p.set('o', JSON.stringify(own.map((e) => ({ n: e.name, s: e.strength, m: e.more, l: e.less }))))+ return `${RECIPE_SCHEME}://${RECIPE_HOST}?${p.toString()}`+}++/** What "Copy" puts on the clipboard: a line people can read and type, and+ * under it the link that carries everything. */+export function recipeText(recipe: Recipe): string {+ const head = ['LU neurons', recipe.model ? recipeModelName(recipe.model) : null, coordsLine(recipe) || null].filter(Boolean).join(' · ')+ return `${head}\n${recipeLink(recipe)}`+}++/** Model names compared loosely: "Qwen/Qwen3.5-4B" and+ * "qwen3.5-4b-instruct-q8_0.gguf" are the same model. */+export function normalizeModelName(name: string): string {+ return name+ .toLowerCase()+ .replace(/^.*\//, '')+ .replace(/\.gguf$/, '')+ .replace(/-gguf$/, '')+ .replace(/[-_.](?:i?q\d[\w]*|f16|bf16|f32|ud[-_]\w+)$/i, '')+ .replace(/[^a-z0-9]/g, '')+}++export type ModelFit = 'same' | 'other' | 'unknown'++export function modelFit(recipeModel: string | null, ...ours: Array<string | null | undefined>): ModelFit {+ if (!recipeModel) return 'unknown'+ const want = normalizeModelName(recipeModel)+ if (!want) return 'unknown'+ for (const o of ours) {+ if (!o) continue+ const have = normalizeModelName(o)+ if (have && (have === want || have.startsWith(want) || want.startsWith(have))) return 'same'+ }+ return 'other'+}++/** A stable id for an own slider brought in by a recipe, so the same recipe+ * brought in twice lands on the same slider. Same shape as Rust's own ids+ * ("own-<name>-<tag>"). */+export function recipeOwnId(e: Extract<RecipeEntry, { kind: 'own' }>): string {+ const base = e.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24)+ let h = 0x811c9dc5+ for (const ch of `${e.name}\u0001${e.more.join('\n')}\u0002${e.less.join('\n')}`) {+ h ^= ch.codePointAt(0)!+ h = Math.imul(h, 0x01000193) >>> 0+ }+ const tag = `r${(h & 0xfffff).toString(16)}`+ return base ? `own-${base}-${tag}` : `own-${tag}`+}++/** The id Rust gives a feature slider (commands/neuron/mod.rs feature_id). */+export function featureVectorId(saeId: string, feature: number): string {+ return `f-${saeId.includes('270m') ? 'g270m' : 'g1b'}-${feature}`+}++/** The id the engine piece gives a single-neuron slider (AN-P11-N2.md). */+export function neuronVectorId(layer: number, neuron: number): string {+ return `n-L${layer}-N${neuron}`+}diff --git a/src/stores/neuronIntroStore.ts b/src/stores/neuronIntroStore.tsnew file mode 100644index 00000000..611fe6f0--- /dev/null+++ b/src/stores/neuronIntroStore.ts@@ -0,0 +1,12 @@+import { create } from 'zustand'++/**+ * Asks the Neurons page to show its introduction again (N2, 3.0.9): from the+ * page's "How it works" button and from the command palette. Not saved;+ * only "seen" is (neuronStore).+ */+export const useNeuronIntroRequest = create<{ open: boolean; show: () => void; hide: () => void }>((set) => ({+ open: false,+ show: () => set({ open: true }),+ hide: () => set({ open: false }),+}))diff --git a/src/stores/neuronStore.ts b/src/stores/neuronStore.tsindex 63239a53..fe6c98b7 100644--- a/src/stores/neuronStore.ts+++ b/src/stores/neuronStore.ts@@ -22,6 +22,9 @@ interface NeuronState {removeProfile: (key: string) => voidremoveSlider: (modelKey: string, id: string) => voidsetScope: (modelKey: string, scope: 'model' | 'persona') => void+ /** The introduction was shown once (N2): it comes back only on request. */+ introSeen: boolean+ setIntroSeen: (seen: boolean) => void}export const useNeuronStore = create<NeuronState>()(@@ -50,6 +53,8 @@ export const useNeuronStore = create<NeuronState>()(return { profiles: next }}),setScope: (modelKey, scope) => set((s) => ({ scopeByModel: { ...s.scopeByModel, [modelKey]: scope } })),+ introSeen: false,+ setIntroSeen: (seen) => set({ introSeen: seen }),}),{ name: 'lu-neuron-tweaker', storage: safeJSONStorage() },),