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(neurons): Neurons as a plugin with its own window (3.1.0)
purple5a2484dd1c74
diff --git a/dev-server/remote-stubs.ts b/dev-server/remote-stubs.tsindex b639a7ef..2996f1d4 100644--- a/dev-server/remote-stubs.ts+++ b/dev-server/remote-stubs.ts@@ -103,7 +103,7 @@ export function registerRemoteStubs(routes: RouteMount): void {'/local-api/abliterate-plan', '/local-api/abliterate-start', '/local-api/abliterate-status','/local-api/abliterate-cancel', '/local-api/abliterate-dismiss', '/local-api/abliterate-runs','/local-api/abliterate-trash-copy',- '/local-api/neuron-presets', '/local-api/neuron-info', '/local-api/neuron-build', '/local-api/neuron-feature-add', '/local-api/neuron-mlp-add', '/local-api/neuron-delete', '/local-api/neuron-sae-download', '/local-api/neuron-sae-search', '/local-api/neuron-status', '/local-api/neuron-cancel', '/local-api/neuron-dismiss', '/local-api/neuron-apply', '/local-api/neuron-compare',+ '/local-api/neuron-presets', '/local-api/neuron-info', '/local-api/neuron-build', '/local-api/neuron-feature-add', '/local-api/neuron-mlp-add', '/local-api/neuron-delete', '/local-api/neuron-sae-download', '/local-api/neuron-sae-search', '/local-api/neuron-status', '/local-api/neuron-cancel', '/local-api/neuron-dismiss', '/local-api/neuron-apply', '/local-api/neuron-plugin-set', '/local-api/neuron-plugin-status', '/local-api/neuron-compare',]) {routes.use(path, (_req, res) => {res.writeHead(501, { 'Content-Type': 'application/json' })diff --git a/src-tauri/src/commands/neuron/mod.rs b/src-tauri/src/commands/neuron/mod.rsindex daa18752..75c0f55b 100644--- a/src-tauri/src/commands/neuron/mod.rs+++ b/src-tauri/src/commands/neuron/mod.rs@@ -130,8 +130,47 @@ pub(crate) fn mix_path_is_ours(root: &Path, path: &str) -> bool {&& p.is_file()}-/// The control vector the engine starts this model with, if any.+// ── the plugin switch ─────────────────────────────────────────────────────+//+// 3.1.0: Neurons is a plugin, off until the user turns it on under Plugins.+// While it is off no saved mix reaches the engine, for any model: sliders+// set in a 3.0.9 pre-release no longer steer unseen (D13). The switch lives+// here, as a file next to active.json, and not only in the app's settings,+// so an engine start that comes before the app has told Rust anything+// already starts plain.++const PLUGIN_ON_FILE: &str = "plugin-on";++static PLUGIN_ON: LazyLock<Mutex<Option<bool>>> = LazyLock::new(|| Mutex::new(None));++/// Whether the Neurons plugin is on (the marker file under `root`).+pub(crate) fn plugin_on_at(root: &Path) -> bool {+ root.join(PLUGIN_ON_FILE).is_file()+}++fn plugin_on() -> bool {+ let mut guard = PLUGIN_ON.lock().unwrap_or_else(|p| p.into_inner());+ *guard.get_or_insert_with(|| plugin_on_at(&root()))+}++/// Writes or removes the marker. Returns whether it is on afterwards.+pub(crate) fn set_plugin_on_at(root: &Path, on: bool) -> Result<bool, String> {+ let marker = root.join(PLUGIN_ON_FILE);+ if on {+ std::fs::create_dir_all(root).map_err(|e| crate::os_error::english(&e))?;+ std::fs::write(&marker, b"1").map_err(|e| crate::os_error::english(&e))?;+ } else if marker.exists() {+ std::fs::remove_file(&marker).map_err(|e| crate::os_error::english(&e))?;+ }+ Ok(plugin_on_at(root))+}++/// The control vector the engine starts this model with, if any. None while+/// the plugin is off.pub(crate) fn control_vector_for(model_path: &str) -> Option<String> {+ if !plugin_on() {+ return None;+ }let path = with_active(|m| m.get(model_path).cloned())?;if mix_path_is_ours(&root(), &path) {Some(path)@@ -1090,6 +1129,40 @@ pub async fn neuron_apply(app: tauri::AppHandle, model_path: String, entries: Ve.map_err(|e| crate::os_error::english(&e))?}+/// Turns the Neurons plugin on or off (3.1.0). When the engine runs a model,+/// it is started again so its control vector follows the switch; a start+/// that resolves to the same argv (no saved mix for that model) keeps the+/// running process.+#[tauri::command]+pub async fn neuron_plugin_set(app: tauri::AppHandle, enabled: bool, tuning: Option<crate::commands::engine::EngineTuning>) -> Result<Value, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let on = set_plugin_on_at(&root(), enabled)?;+ *PLUGIN_ON.lock().unwrap_or_else(|p| p.into_inner()) = Some(on);+ let held = {+ let state = app.state::<crate::state::AppState>();+ let guard = state.bundled_engine.lock().unwrap_or_else(|p| p.into_inner());+ guard.as_ref().map(|e| e.model_path.clone())+ };+ let mut out = json!({ "enabled": on, "restarted": false });+ if let Some(model_path) = held {+ if with_active(|m| m.contains_key(&model_path)) {+ let started = restart(&app, &model_path, tuning)?;+ out["restarted"] = json!(started["status"] != "already_running");+ }+ }+ tracing::info!(target: "neuron", enabled = on, restarted = %out["restarted"], "plugin switched");+ Ok(out)+ })+ .await+ .map_err(|e| crate::os_error::english(&e))?+}++/// Whether the plugin is on, for the app's first look.+#[tauri::command]+pub fn neuron_plugin_status() -> Value {+ json!({ "enabled": plugin_on() })+}+/// The same question to the same model with the sliders off and on, side by/// side: temperature 0 and a fixed seed, so a difference is the sliders'./// The engine is left with the sliders on (what the user set).@@ -1132,6 +1205,23 @@ pub async fn neuron_compare(#[cfg(test)]mod tests {+ /// 3.1.0: Neurons is a plugin. Off is the default (no marker), and the+ /// switch survives as a file, so an engine start before the app has+ /// spoken starts plain.+ #[test]+ fn the_plugin_switch_is_off_by_default_and_kept_as_a_file() {+ let dir = std::env::temp_dir().join(format!("lu-neuron-plugin-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ assert!(!super::plugin_on_at(&dir));+ assert!(super::set_plugin_on_at(&dir, true).unwrap());+ assert!(super::plugin_on_at(&dir));+ assert!(!super::set_plugin_on_at(&dir, false).unwrap());+ assert!(!super::plugin_on_at(&dir));+ // Off twice is fine.+ assert!(!super::set_plugin_on_at(&dir, false).unwrap());+ let _ = std::fs::remove_dir_all(&dir);+ }+/// T1 (3.0.9): an abort put the raw backtrace on the page.#[test]fn a_tool_failure_reads_as_one_sentence() {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 0661a099..6c4e0793 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -822,6 +822,10 @@ pub fn run() {#[cfg(desktop)]commands::neuron::neuron_apply,#[cfg(desktop)]+ commands::neuron::neuron_plugin_set,+ #[cfg(desktop)]+ commands::neuron::neuron_plugin_status,+ #[cfg(desktop)]commands::neuron::neuron_compare,// Whisper STTcommands::whisper::whisper_status,diff --git a/src/api/backend.ts b/src/api/backend.tsindex 5b728695..c0827776 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -688,6 +688,9 @@ export async function backendCall<T = unknown>(neuron_cancel: { path: "/local-api/neuron-cancel", method: "POST" },neuron_dismiss: { path: "/local-api/neuron-dismiss", method: "POST" },neuron_apply: { path: "/local-api/neuron-apply", method: "POST" },+ // 3.1.0: Neurons as a plugin, its on/off switch in Rust.+ neuron_plugin_set: { path: "/local-api/neuron-plugin-set", method: "POST" },+ neuron_plugin_status: { path: "/local-api/neuron-plugin-status" },neuron_compare: { path: "/local-api/neuron-compare", method: "POST" },abliterate_plan: { path: "/local-api/abliterate-plan", method: "POST" },abliterate_start: { path: "/local-api/abliterate-start", method: "POST" },diff --git a/src/api/neuron.ts b/src/api/neuron.tsindex 86ce9563..b00a5efa 100644--- a/src/api/neuron.ts+++ b/src/api/neuron.ts@@ -135,3 +135,10 @@ export const neuronApply = (modelPath: string, entries: NeuronEntry[], tuning?:export const neuronCompare = (modelPath: string, question: string, seed: number, entries: NeuronEntry[], tuning?: BuiltinEngineTuning) =>backendCall<CompareResult>('neuron_compare', { modelPath, question, seed, entries, tuning })++/** The Neurons plugin switch (3.1.0). Off: no saved mix reaches the engine,+ * for any model; the engine is started again when it runs a steered one. */+export const neuronPluginSet = (enabled: boolean, tuning?: BuiltinEngineTuning) =>+ backendCall<{ enabled: boolean; restarted: boolean }>('neuron_plugin_set', { enabled, tuning })++export const neuronPluginStatus = () => backendCall<{ enabled: boolean }>('neuron_plugin_status')diff --git a/src/components/__tests__/t1-a11y-names.test.tsx b/src/components/__tests__/t1-a11y-names.test.tsxindex 94ea5efe..8e64a236 100644--- a/src/components/__tests__/t1-a11y-names.test.tsx+++ b/src/components/__tests__/t1-a11y-names.test.tsx@@ -103,11 +103,11 @@ describe('5. Code mode trigger', () => {})})-describe('6. Neurons view', () => {- // NeuronView needs the bundled engine bridge to render its picker; its own+describe('6. Neurons window', () => {+ // The panel needs the bundled engine bridge to render its picker; its own// render test is the known flaky one, so this item is pinned on the source.it('ties the Model caption to the select', () => {- const src = readFileSync(resolve(here, '../neuron/NeuronView.tsx'), 'utf8')+ const src = readFileSync(resolve(here, '../neuron/NeuronPanel.tsx'), 'utf8')expect(src).toMatch(/<label[^>]*htmlFor="neuron-model"[^>]*>Model<\/label>/)expect(src).toMatch(/<select\s+id="neuron-model"/)})diff --git a/src/components/chat/NeuronPluginRow.tsx b/src/components/chat/NeuronPluginRow.tsxnew file mode 100644index 00000000..4c06f0b3--- /dev/null+++ b/src/components/chat/NeuronPluginRow.tsx@@ -0,0 +1,81 @@+// The Neurons row under Plugins (3.1.0). Neurons used to be a page of its+// own in the header; David, 08.11.2026: it belongs in the plugin section,+// on and off like the others, and it runs in one window with pop-ups. On+// opens that window right away; "Open" brings it back later. The sliders act+// inside the LU Engine itself, so Chat, Code and Agent and all their tools+// run as before, only with the model steered: nothing goes through MCP.++import { AudioLines, PanelRightOpen } from 'lucide-react'+import { useSettingsStore } from '../../stores/settingsStore'+import { useNeuronWindow } from '../../stores/neuronWindowStore'+import { HINWEIS_TEXT } from '../../lib/hinweis'++/** Why the switch is grey in Cloud mode. */+export const NEURONS_CLOUD_REASON = 'Cloud models take no sliders. Neurons steers models the LU Engine runs on this computer.'++/** The line under the switch while Neurons is on. */+export const NEURONS_ON_LINE = 'Your sliders steer the LU Engine model in Chat, Code and Agent. Tools work as before.'++export function NeuronPluginRow({ onOpenWindow }: { onOpenWindow?: () => void }) {+ const enabled = useSettingsStore((s) => s.settings.neuronsPluginEnabled === true)+ const cloud = useSettingsStore((s) => s.settings.appMode === 'cloud')+ const updateSettings = useSettingsStore((s) => s.updateSettings)+ const show = useNeuronWindow((s) => s.show)+ const hide = useNeuronWindow((s) => s.hide)+ const available = !cloud+ const on = enabled && available+ const open = () => { show(); onOpenWindow?.() }+ return (+ <div className="px-2.5" data-testid="plugins-neurons">+ <div className="w-full flex items-center justify-between py-1.5 gap-2">+ <div className="flex items-center gap-1.5 min-w-0">+ <AudioLines size={10} className={`shrink-0 ${on ? 'text-sky-400' : 'text-gray-400'}`} />+ <span className="shrink-0 t-micro font-medium text-gray-600 dark:text-gray-300">Neurons</span>+ <span className="t-micro text-gray-400 truncate">steer your local model</span>+ </div>+ <button+ onClick={(e) => {+ e.stopPropagation()+ if (!available) return+ updateSettings({ neuronsPluginEnabled: !enabled })+ if (enabled) hide()+ else open()+ }}+ disabled={!available}+ aria-pressed={on}+ aria-label="Neurons"+ data-testid="plugins-neurons-switch"+ title={!available ? NEURONS_CLOUD_REASON : on ? 'Turn off Neurons: the engine runs without sliders' : 'Neurons: turn traits of your local model up or down'}+ className={+ 'shrink-0 flex items-center w-7 h-3.5 rounded-full transition-colors '+ + (!available+ ? 'bg-gray-300/20 dark:bg-white/5 cursor-default justify-start'+ : on+ ? 'bg-sky-500/40 hover:bg-sky-500/55 justify-end'+ : 'bg-gray-300/30 dark:bg-white/10 hover:bg-gray-300/45 dark:hover:bg-white/15 justify-start')+ }+ >+ <span className={`w-3 h-3 rounded-full shadow-sm mx-px ${available ? 'bg-white' : 'bg-white/40'}`} />+ </button>+ </div>+ {!available && (+ <div data-testid="plugins-neurons-reason" className={`pb-1.5 t-micro leading-snug ${HINWEIS_TEXT.ruhig}`}>+ {NEURONS_CLOUD_REASON}+ </div>+ )}+ {on && (+ <div className="pb-1.5 flex items-start justify-between gap-2">+ <span data-testid="plugins-neurons-line" className={`t-micro leading-snug ${HINWEIS_TEXT.ruhig}`}>{NEURONS_ON_LINE}</span>+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); open() }}+ data-testid="plugins-neurons-open"+ className="shrink-0 inline-flex items-center gap-1 px-1.5 py-0.5 rounded t-micro text-sky-600 dark:text-sky-400 hover:bg-sky-500/10"+ >+ <PanelRightOpen size={9} /> Open+ </button>+ </div>+ )}+ </div>+ )+}diff --git a/src/components/chat/PluginsDropdown.tsx b/src/components/chat/PluginsDropdown.tsxindex 2267b899..d4da09ad 100644--- a/src/components/chat/PluginsDropdown.tsx+++ b/src/components/chat/PluginsDropdown.tsx@@ -15,6 +15,7 @@ import { BetaMark } from '../ui/BetaMark'import { isTauri } from '../../api/backend'import { createChatLive, createInChatOf, createSupport, servedWindowOf } from '../../lib/create/chat-switch'import { useCreateChatReleased } from '../../lib/create/chat-release'+import { NeuronPluginRow } from './NeuronPluginRow'/** Whether the Plugins menu carries REA: desktop app, Agent or Code only. */export function reaInPlugins(desktop: boolean, agentTools: boolean): boolean {@@ -140,7 +141,11 @@ export function PluginsDropdown({// only where its tools go: Agent and Code.const reaShown = reaInPlugins(isTauri(), agentTools)const reaOn = useSettingsStore((s) => s.settings.reaPluginEnabled === true) && reaShown- const anyPluginActive = !!(isCavemanActive || isPersonaActive || isGroupActive || createOn || reaOn)+ // Neurons (3.1.0): steers the local LU Engine, so the desktop app only, and+ // in every surface: Chat, Agent and Code all talk to the same engine.+ const neuronsShown = isTauri()+ const neuronsOn = useSettingsStore((s) => s.settings.neuronsPluginEnabled === true && s.settings.appMode !== 'cloud') && neuronsShown+ const anyPluginActive = !!(isCavemanActive || isPersonaActive || isGroupActive || createOn || reaOn || neuronsOn)return (<div className="relative">@@ -176,6 +181,7 @@ export function PluginsDropdown({<div className="flex gap-0.5">{createOn && <div data-testid="plugins-dot-create" className="w-1 h-1 rounded-full bg-lu-accent" />}{reaOn && <div data-testid="plugins-dot-rea" className="w-1 h-1 rounded-full bg-teal-400" />}+ {neuronsOn && <div data-testid="plugins-dot-neurons" className="w-1 h-1 rounded-full bg-sky-400" />}{/* Rosa, nicht mehr Bernstein: die vier Punkte sind Kategorien,keine Zustaende, und Gelb hat hier nie eine Warnung gemeint.Blau, Gruen und Violett waren schon vergeben, Rot gehoert@@ -240,6 +246,9 @@ export function PluginsDropdown({{/* ── REA, reverse engineering for the agents ────── */}{reaShown && <Suspense fallback={null}><ReaPluginRow /></Suspense>}+ {/* ── Neurons, the neuron tweaker (3.1.0) ─────────── */}+ {neuronsShown && <NeuronPluginRow onOpenWindow={() => setOpen(false)} />}+<div className="border-t border-gray-200 dark:border-white/[0.06] my-1" />{/* ── Caveman Mode Dropdown ───────────────────── */}diff --git a/src/components/chat/__tests__/plugins-menu-has-neurons.test.tsx b/src/components/chat/__tests__/plugins-menu-has-neurons.test.tsxnew file mode 100644index 00000000..3887279f--- /dev/null+++ b/src/components/chat/__tests__/plugins-menu-has-neurons.test.tsx@@ -0,0 +1,109 @@+/**+ * @vitest-environment jsdom+ *+ * The Neurons row under Plugins (3.1.0, David 08.11.2026): Neurons on and off+ * like the other plugins, its window opening as it turns on, and Rust's+ * switch following the row (useNeuronPluginSync) without restarting the+ * engine at a start of LU when nothing changed.+ *+ * Run: npx vitest run src/components/chat/__tests__/plugins-menu-has-neurons.test.tsx+ */+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'+import { cleanup, fireEvent, render, renderHook, screen, waitFor, act } from '@testing-library/react'++const pluginSet = vi.fn(async (enabled: boolean, _tuning?: unknown) => ({ enabled, restarted: false }))+const pluginStatus = vi.hoisted(() => ({ enabled: false }))+vi.mock('../../../api/neuron', () => ({+ neuronPluginSet: (e: boolean, t?: unknown) => pluginSet(e, t),+ neuronPluginStatus: async () => ({ ...pluginStatus }),+}))+vi.mock('../../../api/engine', () => ({ bundledEngineStatus: async () => ({ running: true, ctx: 8192 }) }))+vi.mock('../../../api/backend', async (orig) => ({ ...(await orig<object>()), isTauri: () => true }))++import { NeuronPluginRow, NEURONS_CLOUD_REASON, NEURONS_ON_LINE } from '../NeuronPluginRow'+import { PluginsDropdown } from '../PluginsDropdown'+import { useSettingsStore } from '../../../stores/settingsStore'+import { useNeuronWindow } from '../../../stores/neuronWindowStore'+import { useNeuronPluginSync } from '../../../hooks/useNeuronPlugin'++beforeEach(() => {+ pluginSet.mockClear()+ pluginStatus.enabled = false+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: false, appMode: 'local' })+ useNeuronWindow.setState({ open: false, collapsed: false, pos: null })+})+afterEach(() => cleanup())++describe('the Neurons row', () => {+ it('starts off; on opens the window, off closes it', () => {+ render(<NeuronPluginRow />)+ const sw = screen.getByTestId('plugins-neurons-switch')+ expect(sw.getAttribute('aria-pressed')).toBe('false')+ expect(screen.queryByTestId('plugins-neurons-open')).toBeNull()+ fireEvent.click(sw)+ expect(useSettingsStore.getState().settings.neuronsPluginEnabled).toBe(true)+ expect(useNeuronWindow.getState().open).toBe(true)+ expect(screen.getByTestId('plugins-neurons-line').textContent).toBe(NEURONS_ON_LINE)+ fireEvent.click(sw)+ expect(useSettingsStore.getState().settings.neuronsPluginEnabled).toBe(false)+ expect(useNeuronWindow.getState().open).toBe(false)+ })++ it('brings a closed window back with Open', () => {+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: true })+ const onOpen = vi.fn()+ render(<NeuronPluginRow onOpenWindow={onOpen} />)+ fireEvent.click(screen.getByTestId('plugins-neurons-open'))+ expect(useNeuronWindow.getState().open).toBe(true)+ expect(onOpen).toHaveBeenCalled()+ })++ it('is grey in Cloud mode, with the reason', () => {+ useSettingsStore.getState().updateSettings({ appMode: 'cloud', neuronsPluginEnabled: true })+ render(<NeuronPluginRow />)+ const sw = screen.getByTestId('plugins-neurons-switch') as HTMLButtonElement+ expect(sw.disabled).toBe(true)+ expect(sw.getAttribute('aria-pressed')).toBe('false')+ expect(screen.getByTestId('plugins-neurons-reason').textContent).toBe(NEURONS_CLOUD_REASON)+ })++ it('is in the Plugins menu of plain Chat, of Agent and of Code, with its dot while on', () => {+ for (const props of [{}, { agentTools: true }, { iconOnly: true, agentTools: true }]) {+ const { unmount } = render(<PluginsDropdown {...props} />)+ fireEvent.click(screen.getByRole('button', { expanded: false }))+ expect(screen.getByTestId('plugins-neurons')).toBeTruthy()+ unmount()+ }+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: true })+ render(<PluginsDropdown />)+ expect(screen.getByTestId('plugins-dot-neurons')).toBeTruthy()+ })+})++describe('Rust follows the row', () => {+ it('stays quiet at start when Rust already agrees, and speaks on a change', async () => {+ renderHook(() => useNeuronPluginSync())+ await new Promise((r) => setTimeout(r, 0))+ expect(pluginSet).not.toHaveBeenCalled()+ act(() => useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: true }))+ await waitFor(() => expect(pluginSet).toHaveBeenCalledTimes(1))+ expect(pluginSet.mock.calls[0][0]).toBe(true)+ act(() => useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: false }))+ await waitFor(() => expect(pluginSet).toHaveBeenCalledTimes(2))+ expect(pluginSet.mock.calls[1][0]).toBe(false)+ })++ it('turns Rust off at start when a 3.0.9 pre-release left it on', async () => {+ pluginStatus.enabled = true+ renderHook(() => useNeuronPluginSync())+ await waitFor(() => expect(pluginSet).toHaveBeenCalledWith(false, expect.anything()))+ })++ it('closes the window when the plugin goes off', async () => {+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: true })+ useNeuronWindow.setState({ open: true })+ renderHook(() => useNeuronPluginSync())+ act(() => useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: false }))+ expect(useNeuronWindow.getState().open).toBe(false)+ })+})diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 623aa5d1..6c5281a3 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -68,7 +68,8 @@ import { Titlebar } from './Titlebar'import { ChatRescueHint } from './ChatRescueHint'import { HfLinkInbox } from '../models/HfLinkInbox'import { useNeuronFollowsPersona } from '../../hooks/useNeuronFollowsPersona'-import { NEURONS_ENABLED } from '../../lib/features'+import { useNeuronPluginSync } from '../../hooks/useNeuronPlugin'+import { NeuronWindowHost } from '../neuron/NeuronWindowHost'// Aus der Komponente herausgezogen: `new Set(STORE_KEYS)` entstand bei jedem// Render neu und war damit die instabile Referenz, wegen der der Restore-Effekt@@ -130,7 +131,6 @@ const loadModelManager = () => import('../models/ModelManager').then((m) => ({ dconst loadBenchmarkView = () => import('../models/BenchmarkView').then((m) => ({ default: m.BenchmarkView }))const loadSettingsPage = () => import('../settings/SettingsPage').then((m) => ({ default: m.SettingsPage }))const loadCreateExperimental = () => import('../create/experimental/CreateExperimental').then((m) => ({ default: m.CreateExperimental }))-const loadNeuronView = () => import('../neuron/NeuronView').then((m) => ({ default: m.NeuronView }))const loadVoiceView = () => import('../voice/VoiceView').then((m) => ({ default: m.VoiceView }))const loadOnboarding = () => import('../onboarding/Onboarding').then((m) => ({ default: m.Onboarding }))@@ -186,6 +186,9 @@ export function AppShell() {useTraySync()useCloudOutageWatch()useNeuronFollowsPersona()+ // Neurons is a plugin (3.1.0): Rust's switch follows the Plugins row.+ useNeuronPluginSync()+ const neuronsOn = settings.neuronsPluginEnabled === true && settings.appMode !== 'cloud' && isTauri()// ── Global Local/Cloud mode (2.5.7) — appMode drives everything ──const appMode = settings.appMode@@ -1210,11 +1213,13 @@ export function AppShell() {{currentView === 'settings' && <LazyView load={loadSettingsPage} fallback={<SettingsSkeleton />} />}{currentView === 'create' && <LazyView load={loadCreateExperimental} fallback={<CreateSkeleton />} />}{currentView === 'voice' && <LazyView load={loadVoiceView} fallback={<VoiceSkeleton />} />}- {currentView === 'neuron' && NEURONS_ENABLED && <LazyView load={loadNeuronView} fallback={<BenchmarkSkeleton />} />}</main></div></div>+ {/* Neurons (3.1.0): its window floats over Chat, Code and Agent. */}+ {neuronsOn && currentView === 'chat' && <NeuronWindowHost />}+{/* Backend selection dialog (shown when multiple local backends detected) */}<BackendSelectoropen={showSelector}diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex ccd48722..252a8cba 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -53,8 +53,8 @@ const NAV_TARGETS: readonly NavTarget[] = [{ id: 'voice', label: 'Voice', view: 'voice', localOnly: true },{ id: 'compare', label: 'Compare', view: null },{ id: 'benchmark', label: 'Benchmark', view: 'benchmark', localOnly: true },- // The Neuron tweaker (3.0.9, P11) steers local LU Engine models only.- { id: 'neuron', label: 'Neurons', view: 'neuron', localOnly: true },+ // Neurons (P11, 3.0.9) left the header in 3.1.0: it is a plugin now, with+ // a window of its own (Plugins in the composer).{ id: 'models', label: 'Models', view: 'models', localOnly: true },{ id: 'settings', label: 'Settings', view: 'settings' },]diff --git a/src/components/layout/__tests__/die-kopfzeile-hat-eine-regel.test.ts b/src/components/layout/__tests__/die-kopfzeile-hat-eine-regel.test.tsindex 36bf2e58..19e6d09e 100644--- a/src/components/layout/__tests__/die-kopfzeile-hat-eine-regel.test.ts+++ b/src/components/layout/__tests__/die-kopfzeile-hat-eine-regel.test.ts@@ -208,8 +208,8 @@ describe('D-S47: die Kebab-Regel ist an der Anordnung ablesbar', () => {it('Voice is one of the targets Cloud hides, next to Benchmark and Models', () => {const local = [...CODE.matchAll(/\{ id: '(\w+)',[^}]*localOnly: true \}/g)].map((m) => m[1])- // The Neuron tweaker (3.0.9) steers local LU Engine models only.- expect(local.sort()).toEqual(['benchmark', 'models', 'neuron', 'voice'])+ // Neurons left the header in 3.1.0 (a plugin with its own window).+ expect(local.sort()).toEqual(['benchmark', 'models', 'voice'])})})diff --git a/src/components/layout/__tests__/lazy-view-boundaries.test.ts b/src/components/layout/__tests__/lazy-view-boundaries.test.tsindex b72615bc..cacb2156 100644--- a/src/components/layout/__tests__/lazy-view-boundaries.test.ts+++ b/src/components/layout/__tests__/lazy-view-boundaries.test.ts@@ -42,7 +42,6 @@ const LAZY_VIEWS = [['CreateExperimental', '../create/experimental/CreateExperimental'],['Onboarding', '../onboarding/Onboarding'],['VoiceView', '../voice/VoiceView'],- ['NeuronView', '../neuron/NeuronView'],] as constdescribe('der Boot-View bleibt statisch', () => {diff --git a/src/components/neuron/NeuronPanel.tsx b/src/components/neuron/NeuronPanel.tsxnew file mode 100644index 00000000..b157451c--- /dev/null+++ b/src/components/neuron/NeuronPanel.tsx@@ -0,0 +1,748 @@+// What the Neurons window holds (3.1.0). Neurons was a page in the header+// (P11, N2: four steps top to bottom); David, 08.11.2026: a plugin, one+// window with pop-ups, next to Chat, Code and Agent. So the window shows what+// one uses all the time (the model, the sliders, what is on) and everything+// else opens as a pop-up over it: adding a slider, before and after, keeping+// and sharing. The work behind it is unchanged (api/neuron, Rust).++import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import {+ ArrowLeftRight, ChevronsDownUp, ChevronsUpDown, CircleHelp, Download, FilePlus, FlaskConical, Hash,+ Loader2, Plus, RotateCcw, Share2, Sliders, Sparkles, X, AudioLines,+} 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 { addGgufFile, listBundledModels, isEmbeddingGgufName, type BundledModel } from '../../api/engine'+import {+ neuronApply, neuronBuildOwn, neuronBuildPreset, neuronCancel, neuronDelete, neuronDismiss,+ neuronFeatureAdd, neuronInfo, neuronMlpAdd, 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 { builtinModelMatches } from '../../lib/builtin-model-identity'+import {+ backendNote, effectiveStrengths, entriesFor, hasPersonaProfile,+ clampStrength, steeringPersona, strengthWarning, tweakedModelNote, buildTimeNote, warningText, type BackendKind, type Strengths,+} from '../../lib/neuron'+import { NEURON_MAX_DOSE, 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 { useDismissOnEscape } from '../../hooks/useDismissOnEscape'+import { restartTuning } from '../../hooks/useNeuronPlugin'+import { JobPanel, ScopeButton, SliderRow, TimeNote, TweakedNote, WayIntro, WayTabs, signedValue } from './parts'+import { ComparePanel, CoordinatesPanel, FeaturePanel, OwnSliderForm, SharePanel, entryState } from './panels'+import { NeuronIntroHost } from './NeuronIntro'+import { useNeuronIntroRequest } from '../../stores/neuronIntroStore'++const APPLY_DELAY_MS = 700++const NO_CHAT_MODEL = 'Neurons works on chat models the LU Engine runs. Download one, or use a GGUF file you already have. An embedding model (the one Document Chat uses) cannot be tweaked.'+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.'++/** Where the sliders act, said once in the window and once under Plugins. */+export const WHERE_IT_ACTS = 'Chat, Code and Agent'++type AddWay = 'own' | 'features' | 'coords'+export type NeuronPopup = null | 'add' | 'compare' | 'share' | 'limits'++/** Which program answers the chat's model right now. */+function chatBackend(activeModel: string | null, appMode: string | undefined): BackendKind {+ if (appMode === 'cloud') return 'cloud'+ if (!activeModel) return 'none'+ const provider = getProviderIdFromModel(activeModel)+ if (provider === 'ollama') return 'ollama'+ if (provider === 'openai' && isManagedBuiltinSlot()) return 'lu-engine'+ if (String(provider).includes('lmstudio')) return 'lmstudio'+ return 'other'+}++/** The window's own frame: dragging, folding, closing. */+export interface WindowChrome {+ onDragStart?: (e: React.PointerEvent) => void+ collapsed?: boolean+ onCollapse?: (collapsed: boolean) => void+ onClose?: () => void+}++export function NeuronPanel({ chrome = {} }: { chrome?: WindowChrome }) {+ const activeModel = useModelStore((s) => s.activeModel)+ const appMode = useSettingsStore((s) => s.settings.appMode)+ const activePersonaId = useSettingsStore((s) => s.activePersonaId)+ const personas = useSettingsStore((s) => s.personas)+ const personasOn = useSettingsStore((s) => s.settings.personasEnabled !== false)+ const conv = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId))+ const steering = steeringPersona(conv, personas, activePersonaId, personasOn)+ const personaId = steering.id ?? undefined+ const persona = personas.find((p) => p.id === personaId)+ const { profiles, scopeByModel, setStrength, setProfile, removeProfile, removeSlider, setScope } = useNeuronStore()++ const [models, setModels] = useState<BundledModel[]>([])+ const [modelsLoaded, setModelsLoaded] = useState(false)+ const [modelPath, setModelPath] = useState<string>('')+ // The info is kept with the model it was read for: after a switch the old+ // model's sliders must not reach the new one while its info is on the way.+ const [loadedInfo, setLoadedInfo] = useState<{ path: string; info: NeuronInfo } | null>(null)+ const [presets, setPresets] = useState<NeuronPreset[]>([])+ const [job, setJob] = useState<NeuronJob | null>(null)+ const [error, setError] = useState<string | null>(null)+ const [applyState, setApplyState] = useState<'idle' | 'applying' | 'applied'>('idle')+ const [lastApplied, setLastApplied] = useState<string>('')+ const [popup, setPopup] = useState<NeuronPopup>(null)+ const [addWay, setAddWay] = useState<AddWay>('own')+ // 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 pathRef = useRef(modelPath)+ pathRef.current = modelPath++ // Presets once; the models once and again after a GGUF file was added+ // from the empty state. The loaded model (or the chat's) preselected.+ const [modelsSeq, setModelsSeq] = useState(0)+ useEffect(() => {+ void neuronPresets().then(setPresets).catch(() => setPresets([]))+ }, [])+ useEffect(() => {+ void listBundledModels().then((all) => {+ // Chat models only: an embedding model (Document Chat's) has no chat+ // turn to steer, and the vector tool aborts on it.+ const list = all.filter((m) => !isEmbeddingGgufName(m.name))+ setModels(list)+ const loaded = list.find((m) => m.loaded)+ const chat = list.find((m) => activeModel && builtinModelMatches(m.path, activeModel) && activeModel.includes(m.name))+ setModelPath((cur) => cur || (chat ?? loaded ?? list[0])?.path || '')+ }).catch(() => setModels([])).finally(() => setModelsLoaded(true))+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [modelsSeq])++ const refreshInfo = useCallback(async (path: string) => {+ if (!path) return+ try {+ const read = await neuronInfo(path)+ if (path !== pathRef.current) return+ setLoadedInfo({ path, info: read })+ setError(null)+ } catch (e) {+ if (path !== pathRef.current) return+ setLoadedInfo(null)+ setError(String(e))+ }+ }, [])++ useEffect(() => { void refreshInfo(modelPath) }, [modelPath, refreshInfo])++ // Job polling while something runs (and once on mount, to pick up a job+ // that was started before the window opened).+ const pollRef = useRef<number | null>(null)+ const poll = useCallback(async () => {+ try {+ const j = await neuronStatus()+ setJob(j)+ if (j.status === 'running') {+ pollRef.current = window.setTimeout(() => void poll(), 1000)+ } else if (j.status === 'done') {+ await refreshInfo(j.modelPath || modelPath)+ }+ } catch { /* backend gone: nothing to show */ }+ }, [modelPath, refreshInfo])+ useEffect(() => {+ void poll()+ return () => { if (pollRef.current) window.clearTimeout(pollRef.current) }+ }, [poll])++ const modelKey = info?.modelKey ?? ''+ const scope = (personaId && scopeByModel[modelKey]) || 'model'+ const editKey = editingKey(modelKey, personaId, scope)+ const strengths = useMemo(() => {+ if (!modelKey) return {}+ return scope === 'persona' ? (profiles[editKey] ?? effectiveStrengths(profiles, modelKey, null)) : (profiles[editKey] ?? {})+ }, [profiles, editKey, modelKey, scope])+ const vectors = useMemo(() => info?.vectors ?? [], [info])+ const available = useMemo(() => new Set(vectors.map((v) => v.id)), [vectors])+ const effective = useMemo(() => modelKey ? effectiveStrengths(profiles, modelKey, personaId) : {}, [profiles, modelKey, personaId])+ const entries = useMemo(() => entriesFor(effective, available), [effective, available])+ const warning = warningText(strengthWarning(entries))+ const running = job?.status === 'running'++ // Apply after the sliders rest for a moment. A restart takes seconds, so+ // dragging must not cause one per pixel.+ useEffect(() => {+ if (!modelPath || !info) return+ const sig = `${modelPath}|${JSON.stringify(entries)}`+ if (sig === lastApplied) return+ const t = window.setTimeout(() => {+ void (async () => {+ setApplyState('applying')+ try {+ await neuronApply(modelPath, entries, await restartTuning(model))+ setLastApplied(sig)+ setApplyState('applied')+ await refreshInfo(modelPath)+ } catch (e) {+ setError(String(e))+ setApplyState('idle')+ }+ })()+ }, lastApplied === '' ? 0 : APPLY_DELAY_MS)+ return () => window.clearTimeout(t)+ }, [entries, modelPath, info, lastApplied, model, refreshInfo])++ const startJob = useCallback(async (start: () => Promise<unknown>) => {+ setError(null)+ try {+ await start()+ await poll()+ } 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:+ // they fell to 0 when the saved scope was already "persona").+ const move = (id: string, value: number) => {+ if (editKey in profiles) setStrength(editKey, id, value)+ else setProfile(editKey, { ...strengths, [id]: clampStrength(value, id) })+ }++ const reset = () => {+ if (!modelKey) return+ if (scope === 'persona') removeProfile(editKey)+ 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 states = useCallback((e: RecipeEntry) => {+ if (!info) return { state: 'blocked' as const, why: 'The model is still loading.' }+ return entryState(e, info, available, ids)+ }, [info, 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, neuronVectorId(e.layer, e.neuron))+ if (st.state === 'prepare') jobs.push(() => neuronMlpAdd(modelPath, e.layer, e.neuron))+ }+ }+ setProfile(editKey, next)+ setQueue(jobs)+ // The recipe is in: back to the sliders, where it shows.+ setPopup(null)+ }++ 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)++ // A model changed before (fine-tune, merge, heretic …): say so before+ // computing, and offer its original in Discover (David, 31.10.2026).+ const tweak = info ? tweakedModelNote(info.facts) : null+ // How long one slider takes, said before it starts: in the window for the+ // ready-made ones, in the Add pop-up for its ways.+ const presetsToPrepare = presets.some((p) => !vectors.some((x) => x.id === p.id))+ const presetTimeNote = info?.buildEstimate && info.generator && presetsToPrepare && !running ? buildTimeNote(info.buildEstimate) : null+ const addEstimate = addWay === 'own' ? info?.ownEstimate : addWay === 'coords' ? info?.buildEstimate : undefined+ const addTimeNote = addEstimate && info?.generator && !running ? buildTimeNote(addEstimate) : null+ const original = info?.facts.original ?? null+ const getOriginal = () => {+ if (!original) return+ useModelStore.getState().setCategoryFilter('text')+ useUIStore.getState().openDiscoverFor('builtin', original, { original: true })+ }++ 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+ }++ const status: StatusChip = applyState === 'applying'+ ? { kind: 'busy', text: 'Applying…' }+ : running+ ? { kind: 'busy', text: 'Preparing…' }+ : entries.length > 0 ? { kind: 'on', text: `${entries.length} on` } : { kind: 'off', text: 'Off' }++ const noModel = modelsLoaded && models.length === 0++ return (+ <div className="flex flex-col h-full min-h-0" data-testid="neuron-view">+ <TitleBar chrome={chrome} status={status} onIntro={showIntro} />+ {!chrome.collapsed && (+ <div className="relative flex-1 min-h-0 flex flex-col">+ {noModel ? (+ <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)}+ />+ ) : (+ <>+ <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-4 pt-3 pb-4 space-y-4" data-testid="neuron-body">+ <section data-testid="neuron-step-model" aria-label="Model to steer">+ <div className="flex items-center gap-2">+ <label className="t-micro font-medium text-gray-500 dark:text-gray-400 shrink-0" htmlFor="neuron-model">Model</label>+ <select+ id="neuron-model"+ data-testid="neuron-model"+ className="t-control flex-1 min-w-0 rounded-md border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-white/[0.04] px-2 py-1 text-gray-900 dark:text-white"+ 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>+ </div>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1`} data-testid="neuron-model-facts">+ {info ? `${info.facts.arch} · ${info.facts.nLayer} layers · sliders act on layers ${info.band[0]}–${info.band[1]}` : 'Reading the model…'}+ </p>+ {backend !== 'lu-engine' && <Hinweis className="mt-2">{backendNote(backend)}</Hinweis>}+ {steering.group && (+ <Hinweis className="mt-2"><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.</span></Hinweis>+ )}+ </section>++ <section data-testid="neuron-step-sliders" aria-label="Sliders">+ {error && <Hinweis ton="fehler" className="mb-3" onDismiss={() => setError(null)}>{error}</Hinweis>}+ {tweak && <TweakedNote title={tweak.title} text={tweak.text} original={tweak.original} onGetOriginal={getOriginal} />}+ {presetTimeNote && <TimeNote title={presetTimeNote.title} text={presetTimeNote.text} />}+ {job && job.status !== 'idle' && <JobPanel job={job} onStop={() => { setQueue([]); void neuronCancel().then(poll) }} onDismiss={() => void neuronDismiss().then(poll)} onGetOriginal={getOriginal} original={original} />}+ {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>+ )}++ <SectionHead title="Ready-made" hint="Five common traits. The first time, LU prepares each one for your model." />+ <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)}+ prepareHint={presetTimeNote ? 'Once per model. How long it takes is said above.' : undefined}+ />+ ))}+ </div>++ {(own.length > 0 || features.length > 0 || neurons.length > 0) && (+ <div className="mt-4" data-testid="neuron-yours">+ <SectionHead title="Yours" hint="Made from examples, features and coordinates. Delete one with the bin." />+ <div className="space-y-2">+ {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)} />+ ))}+ {features.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)} />+ ))}+ {neurons.map((v) => (+ <SliderRow key={v.id} id={v.id} left={v.left || 'Less'} right={v.name} value={strengths[v.id] ?? 0} max={NEURON_MAX_DOSE} computed disabled={running} onChange={(x) => move(v.id, x)} onDelete={() => deleteVector(v.id)} />+ ))}+ </div>+ </div>+ )}+ </section>+ </div>++ <MixBar+ entries={entries}+ labelOf={labelOf}+ warning={warning}+ applyState={applyState}+ onReset={reset}+ />++ <div className="flex items-center gap-1.5 px-3 py-2 border-t border-gray-200 dark:border-white/[0.06]" data-testid="neuron-actions">+ <button type="button" className="lu-control lu-primary" onClick={() => setPopup('add')} data-testid="neuron-add" disabled={!info}>+ <Plus size={ICON_SM} /> Add slider+ </button>+ <button type="button" className="lu-control lu-control--outline" onClick={() => setPopup('compare')} data-testid="neuron-open-compare" disabled={!info}>+ <ArrowLeftRight size={ICON_SM} /> Before / after+ </button>+ <button type="button" className="lu-control lu-control--outline" onClick={() => setPopup('share')} data-testid="neuron-open-share" disabled={!info}>+ <Share2 size={ICON_SM} /> Share+ </button>+ <button type="button" className="ml-auto lu-control lu-control--icon" onClick={() => setPopup('limits')} aria-label="What this can and cannot do" title="What this can and cannot do" data-testid="neuron-open-limits">+ <CircleHelp size={ICON_SM} />+ </button>+ </div>+ </>+ )}++ {popup === 'add' && (+ <Popup title="Add a slider" onClose={() => setPopup(null)} testId="neuron-popup-add">+ {addTimeNote && addWay !== 'features' && <TimeNote title={addTimeNote.title} text={addTimeNote.text} />}+ {job && job.status === 'running' && <JobPanel job={job} onStop={() => { setQueue([]); void neuronCancel().then(poll) }} onDismiss={() => void neuronDismiss().then(poll)} />}+ <WayTabs<AddWay>+ current={addWay}+ onPick={setAddWay}+ ways={[+ { 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-')) },+ ]}+ />+ <div role="tabpanel" id={`neuron-way-${addWay}`} aria-labelledby={`neuron-way-tab-${addWay}`}>+ {addWay === '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 (a control vector).+ </WayIntro>+ <OwnSliderForm startOpen disabled={running || !info?.generator || !modelPath} onCompute={(name, more, less) => { void startJob(() => neuronBuildOwn(modelPath, name, more, less)); setPopup(null) }} />+ </>+ )}+ {addWay === '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 as the model, or use the other ways.+ </p>+ )}+ </>+ )}+ {addWay === '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>+ {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>+ </Popup>+ )}++ {popup === 'compare' && (+ <Popup title="Before and after" onClose={() => setPopup(null)} testId="neuron-popup-compare">+ <p className={`t-body ${HINWEIS_TEXT.ruhig} mb-3`}>Ask one question and see the answer without and with your sliders.</p>+ <ComparePanel modelPath={modelPath} entries={entries} labelOf={labelOf} disabled={running || !modelPath} model={model} tuning={restartTuning} onError={setError} />+ </Popup>+ )}++ {popup === 'share' && (+ <Popup title="Keep and share" onClose={() => setPopup(null)} testId="neuron-popup-share">+ <p className={`t-body ${HINWEIS_TEXT.ruhig} mb-3`}>Your sliders stay for this model, also after a restart of LU. Every chat on this model uses them.</p>+ {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-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} />+ </Popup>+ )}++ {popup === 'limits' && (+ <Popup title="What this can and cannot do" onClose={() => setPopup(null)} testId="neuron-limits">+ <ul className={`t-body ${HINWEIS_TEXT.ruhig} list-disc pl-4 space-y-1.5`}>+ <li>Works with models in the LU Engine (llama.cpp control vectors), in {WHERE_IT_ACTS}. Tools keep working: the sliders act inside the model, not on the tools.</li>+ <li>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). Turning Neurons off under Plugins restarts it without them.</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).</li>+ <li>Small models (under 1B) show traits weakly; special ones like a pirate voice need a bigger model.</li>+ </ul>+ <button type="button" className="lu-control lu-control--outline mt-3" onClick={() => { setPopup(null); showIntro() }} data-testid="neuron-intro-open">+ <CircleHelp size={ICON_SM} /> Show the introduction+ </button>+ </Popup>+ )}+ </div>+ )}+ <NeuronIntroHost />+ </div>+ )+}++interface StatusChip { kind: 'off' | 'on' | 'busy'; text: string }++function TitleBar({ chrome, status, onIntro }: { chrome: WindowChrome; status: StatusChip; onIntro: () => void }) {+ return (+ <div+ className="flex items-center gap-2 pl-3 pr-1.5 h-10 shrink-0 border-b border-gray-200 dark:border-white/[0.06] select-none cursor-grab active:cursor-grabbing"+ onPointerDown={chrome.onDragStart}+ onDoubleClick={() => chrome.onCollapse?.(!chrome.collapsed)}+ data-testid="neuron-window-title"+ >+ <AudioLines size={14} className="text-sky-500 dark:text-sky-400 shrink-0" aria-hidden />+ <h2 className="t-control font-semibold text-gray-900 dark:text-white">Neurons</h2>+ <span+ data-testid="neuron-status"+ data-kind={status.kind}+ className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 t-micro tabular-nums ${+ status.kind === 'on'+ ? 'bg-sky-500/15 text-sky-700 dark:text-sky-300'+ : status.kind === 'busy'+ ? 'bg-gray-500/10 text-gray-300'+ : 'bg-gray-500/10 text-gray-500 dark:text-gray-400'+ }`}+ >+ {status.kind === 'busy' && <Loader2 size={10} className="animate-spin" />}+ {status.text}+ </span>+ <div className="ml-auto flex items-center gap-0.5" onPointerDown={(e) => e.stopPropagation()}>+ <button type="button" className="lu-control lu-control--icon" onClick={onIntro} aria-label="How Neurons works" title="How Neurons works" data-testid="neuron-help">+ <CircleHelp size={ICON_SM} />+ </button>+ {chrome.onCollapse && (+ <button+ type="button"+ className="lu-control lu-control--icon"+ onClick={() => chrome.onCollapse?.(!chrome.collapsed)}+ aria-label={chrome.collapsed ? 'Unfold the window' : 'Fold the window'}+ title={chrome.collapsed ? 'Unfold' : 'Fold to the title bar'}+ data-testid="neuron-window-fold"+ >+ {chrome.collapsed ? <ChevronsUpDown size={ICON_SM} /> : <ChevronsDownUp size={ICON_SM} />}+ </button>+ )}+ {chrome.onClose && (+ <button type="button" className="lu-control lu-control--icon" onClick={chrome.onClose} aria-label="Close Neurons" title="Close. The sliders stay on." data-testid="neuron-window-close">+ <X size={ICON_SM} />+ </button>+ )}+ </div>+ </div>+ )+}++function SectionHead({ title, hint }: { title: string; hint: string }) {+ return (+ <div className="mb-2">+ <p className="t-label text-gray-500 dark:text-gray-400">{title}</p>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>{hint}</p>+ </div>+ )+}++/** What is on right now, and whether it reached the engine. */+function MixBar({ entries, labelOf, warning, applyState, onReset }: {+ entries: Array<{ id: string; strength: number }>+ labelOf: (id: string) => string+ warning: string | null+ applyState: 'idle' | 'applying' | 'applied'+ onReset: () => void+}) {+ return (+ <div className="px-4 py-2.5 border-t border-gray-200 dark:border-white/[0.06] bg-gray-50/70 dark:bg-white/[0.02]" data-testid="neuron-mix">+ <div className="flex items-center justify-between gap-2">+ <p className="t-micro font-medium text-gray-200">On right now</p>+ <button type="button" data-testid="neuron-reset" onClick={onReset} disabled={entries.length === 0} className="lu-control lu-control--outline">+ <RotateCcw size={ICON_SM} /> Reset all+ </button>+ </div>+ {entries.length === 0 ? (+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1`}>Nothing. The model answers exactly as without Neurons.</p>+ ) : (+ <ul className="flex flex-wrap gap-1 mt-1.5">+ {entries.map((e) => (+ <li key={e.id} className="t-micro inline-flex items-center gap-1 rounded-full border border-sky-500/35 bg-sky-500/[0.08] px-2 py-0.5 text-gray-900 dark:text-white">+ {labelOf(e.id)} <span className="tabular-nums text-sky-700 dark:text-sky-300">{signedValue(e.strength)}</span>+ </li>+ ))}+ </ul>+ )}+ {warning && <Hinweis className="mt-2">{warning}</Hinweis>}+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1.5 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 ${WHERE_IT_ACTS}: ${entries.length} slider${entries.length > 1 ? 's' : ''}` : 'Off: the model runs unchanged'}</span>}+ </p>+ </div>+ )+}++/** A pop-up over the window's body: the window stays where it is, its title+ * bar and status stay visible. Escape or the cross closes it. */+function Popup({ title, onClose, testId, children }: { title: string; onClose: () => void; testId: string; children: React.ReactNode }) {+ useDismissOnEscape(true, onClose)+ const ref = useRef<HTMLDivElement>(null)+ useEffect(() => { ref.current?.focus() }, [])+ return (+ <div className="absolute inset-0 z-10 flex flex-col justify-end bg-black/25 dark:bg-black/45 neuron-popup-backdrop" onPointerDown={(e) => { if (e.target === e.currentTarget) onClose() }}>+ <div+ ref={ref}+ tabIndex={-1}+ role="dialog"+ aria-modal="true"+ aria-label={title}+ data-testid={testId}+ className="@container lu-elevated rounded-t-xl max-h-[92%] flex flex-col outline-none neuron-popup"+ >+ <div className="flex items-center justify-between gap-2 px-4 pt-3 pb-2 shrink-0">+ <h3 className="t-title text-gray-900 dark:text-white">{title}</h3>+ <button type="button" className="lu-control lu-control--icon" onClick={onClose} aria-label={`Close ${title}`} data-testid="neuron-popup-close">+ <X size={ICON_SM} />+ </button>+ </div>+ <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-4 pb-4">+ {children}+ </div>+ </div>+ </div>+ )+}++/** No LU Engine chat model yet: one centred state with the two ways to get+ * 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, onIntro, error, onDismissError }: {+ onDownload: () => void+ onAddFile: () => void+ onIntro: () => void+ error: string | null+ onDismissError: () => void+}) {+ return (+ <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-5 py-6">+ <div className="flex flex-col items-center text-center gap-3" data-testid="neuron-empty">+ <Sliders size={26} className="text-gray-400 dark:text-gray-500" aria-hidden />+ <h3 className="t-title text-gray-900 dark:text-white">No chat model for the LU Engine yet</h3>+ <p className="t-body text-gray-300" data-testid="neuron-no-chat-model">{NO_CHAT_MODEL}</p>+ <p className={`t-body ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-other-apps">{OTHER_APPS}</p>+ <div className="flex flex-wrap items-center justify-center gap-2 pt-1">+ <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. */}+ <div className="mt-2 w-full text-left rounded-lg border border-gray-200 dark:border-white/[0.06] px-4 py-3" data-testid="neuron-gguf-steps">+ <p className="t-body font-semibold text-gray-900 dark:text-white mb-1.5">Already have a GGUF file?</p>+ <ol className="t-body text-gray-300 space-y-1 list-decimal pl-5">+ {GGUF_STEPS.map((s) => <li key={s.from}>{s.text}</li>)}+ </ol>+ <button className="lu-control mt-2.5" onClick={onAddFile} data-testid="neuron-add-gguf" title="Use a GGUF file from your drive as a chat model on the LU Engine">+ <FilePlus size={ICON_SM} /> GGUF file+ </button>+ </div>+ {error && <Hinweis ton="fehler" className="mt-2 text-left" onDismiss={onDismissError}>{error}</Hinweis>}+ </div>+ </div>+ )+}diff --git a/src/components/neuron/NeuronView.tsx b/src/components/neuron/NeuronView.tsxdeleted file mode 100644index 132288af..00000000--- a/src/components/neuron/NeuronView.tsx+++ /dev/null@@ -1,638 +0,0 @@-import { useCallback, useEffect, useMemo, useRef, useState } from '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 { addGgufFile, listBundledModels, bundledEngineStatus, isEmbeddingGgufName, type BundledModel } from '../../api/engine'-import {- neuronApply, neuronBuildOwn, neuronBuildPreset, neuronCancel, neuronDelete, neuronDismiss,- neuronFeatureAdd, neuronInfo, neuronMlpAdd, 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,- clampStrength, steeringPersona, strengthWarning, tweakedModelNote, buildTimeNote, warningText, type BackendKind, type Strengths,-} from '../../lib/neuron'-import { NEURON_MAX_DOSE, 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, TimeNote, TweakedNote, WayIntro, WayTabs, signedValue } from './parts'-import { ComparePanel, CoordinatesPanel, FeaturePanel, OwnSliderForm, SharePanel, entryState } from './panels'-import { NeuronIntroHost } from './NeuronIntro'-import { useNeuronIntroRequest } from '../../stores/neuronIntroStore'--const APPLY_DELAY_MS = 700--const NO_CHAT_MODEL = 'The tweaker works on chat models the LU Engine runs. Download one, or use a GGUF file you already have. An embedding model (the one Document Chat uses) cannot be tweaked.'-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'- if (!activeModel) return 'none'- const provider = getProviderIdFromModel(activeModel)- if (provider === 'ollama') return 'ollama'- if (provider === 'openai' && isManagedBuiltinSlot()) return 'lu-engine'- if (String(provider).includes('lmstudio')) return 'lmstudio'- return 'other'-}--/** The tuning a restart uses: the user's, with the context the engine holds- * kept the way the chat's own restarts keep it (lib/builtin-ctx). */-async function restartTuning(model: BundledModel | undefined): Promise<BuiltinEngineTuning | undefined> {- const tuning = useSettingsStore.getState().settings.builtinEngine- try {- const status = await bundledEngineStatus()- const keep = preservedSwapCtx({- tuningCtx: tuning?.ctx,- tuningChosen: tuning?.ctxChosen,- currentCtx: status?.ctxRequested ?? status?.ctx,- ctxTrain: model?.ctx_train,- })- return keep ? { ...(tuning ?? {}), ctx: keep } as BuiltinEngineTuning : tuning- } catch {- return tuning- }-}--export function NeuronView() {- const activeModel = useModelStore((s) => s.activeModel)- const appMode = useSettingsStore((s) => s.settings.appMode)- const activePersonaId = useSettingsStore((s) => s.activePersonaId)- const personas = useSettingsStore((s) => s.personas)- const personasOn = useSettingsStore((s) => s.settings.personasEnabled !== false)- const conv = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId))- const steering = steeringPersona(conv, personas, activePersonaId, personasOn)- const personaId = steering.id ?? undefined- const persona = personas.find((p) => p.id === personaId)- const { profiles, scopeByModel, setStrength, setProfile, removeProfile, removeSlider, setScope } = useNeuronStore()-- const [models, setModels] = useState<BundledModel[]>([])- const [modelsLoaded, setModelsLoaded] = useState(false)- const [modelPath, setModelPath] = useState<string>('')- // The info is kept with the model it was read for: after a switch the old- // model's sliders must not reach the new one while its info is on the way.- const [loadedInfo, setLoadedInfo] = useState<{ path: string; info: NeuronInfo } | null>(null)- const [presets, setPresets] = useState<NeuronPreset[]>([])- const [job, setJob] = useState<NeuronJob | null>(null)- 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 pathRef = useRef(modelPath)- pathRef.current = modelPath-- // Presets once; the models once and again after a GGUF file was added- // from the empty state. The loaded model (or the chat's) preselected.- const [modelsSeq, setModelsSeq] = useState(0)- useEffect(() => {- void neuronPresets().then(setPresets).catch(() => setPresets([]))- }, [])- useEffect(() => {- void listBundledModels().then((all) => {- // Chat models only: an embedding model (Document Chat's) has no chat- // turn to steer, and the vector tool aborts on it.- const list = all.filter((m) => !isEmbeddingGgufName(m.name))- setModels(list)- const loaded = list.find((m) => m.loaded)- const chat = list.find((m) => activeModel && builtinModelMatches(m.path, activeModel) && activeModel.includes(m.name))- setModelPath((cur) => cur || (chat ?? loaded ?? list[0])?.path || '')- }).catch(() => setModels([])).finally(() => setModelsLoaded(true))- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [modelsSeq])-- const refreshInfo = useCallback(async (path: string) => {- if (!path) return- try {- const read = await neuronInfo(path)- if (path !== pathRef.current) return- setLoadedInfo({ path, info: read })- setError(null)- } catch (e) {- if (path !== pathRef.current) return- setLoadedInfo(null)- setError(String(e))- }- }, [])-- useEffect(() => { void refreshInfo(modelPath) }, [modelPath, refreshInfo])-- // Job polling while something runs (and once on mount, to pick up a job- // that was started before the view opened).- const pollRef = useRef<number | null>(null)- const poll = useCallback(async () => {- try {- const j = await neuronStatus()- setJob(j)- if (j.status === 'running') {- pollRef.current = window.setTimeout(() => void poll(), 1000)- } else if (j.status === 'done') {- await refreshInfo(j.modelPath || modelPath)- }- } catch { /* backend gone: nothing to show */ }- }, [modelPath, refreshInfo])- useEffect(() => {- void poll()- return () => { if (pollRef.current) window.clearTimeout(pollRef.current) }- }, [poll])-- const modelKey = info?.modelKey ?? ''- const scope = (personaId && scopeByModel[modelKey]) || 'model'- const editKey = editingKey(modelKey, personaId, scope)- const strengths = useMemo(() => {- if (!modelKey) return {}- return scope === 'persona' ? (profiles[editKey] ?? effectiveStrengths(profiles, modelKey, null)) : (profiles[editKey] ?? {})- }, [profiles, editKey, modelKey, scope])- const vectors = useMemo(() => info?.vectors ?? [], [info])- const available = useMemo(() => new Set(vectors.map((v) => v.id)), [vectors])- const effective = useMemo(() => modelKey ? effectiveStrengths(profiles, modelKey, personaId) : {}, [profiles, modelKey, personaId])- const entries = useMemo(() => entriesFor(effective, available), [effective, available])- const warning = warningText(strengthWarning(entries))- const running = job?.status === 'running'-- // Apply after the sliders rest for a moment. A restart takes seconds, so- // dragging must not cause one per pixel.- useEffect(() => {- if (!modelPath || !info) return- const sig = `${modelPath}|${JSON.stringify(entries)}`- if (sig === lastApplied) return- const t = window.setTimeout(() => {- void (async () => {- setApplyState('applying')- try {- await neuronApply(modelPath, entries, await restartTuning(model))- setLastApplied(sig)- setApplyState('applied')- await refreshInfo(modelPath)- } catch (e) {- setError(String(e))- setApplyState('idle')- }- })()- }, lastApplied === '' ? 0 : APPLY_DELAY_MS)- return () => window.clearTimeout(t)- }, [entries, modelPath, info, lastApplied, model, refreshInfo])-- const startJob = useCallback(async (start: () => Promise<unknown>) => {- setError(null)- try {- await start()- await poll()- } 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:- // they fell to 0 when the saved scope was already "persona").- const move = (id: string, value: number) => {- if (editKey in profiles) setStrength(editKey, id, value)- else setProfile(editKey, { ...strengths, [id]: clampStrength(value, id) })- }-- const reset = () => {- if (!modelKey) return- if (scope === 'persona') removeProfile(editKey)- 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 states = useCallback((e: RecipeEntry) => {- if (!info) return { state: 'blocked' as const, why: 'The model is still loading.' }- return entryState(e, info, available, ids)- }, [info, 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, neuronVectorId(e.layer, e.neuron))- if (st.state === 'prepare') jobs.push(() => neuronMlpAdd(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)-- // A model changed before (fine-tune, merge, heretic …): say so before- // computing, and offer its original in Discover (David, 31.10.2026).- const tweak = info ? tweakedModelNote(info.facts) : null- // How long one slider takes, said before it starts (P11 5b67ef9fe): on the- // ways that compute, while something there still needs it, not while a- // job runs (its own line counts down then).- const estimate = way === 'own' ? info?.ownEstimate : way === 'ready' || way === 'coords' ? info?.buildEstimate : undefined- const needsCompute = way === 'own' || presets.some((p) => !vectors.some((x) => x.id === p.id))- const timeNote = estimate && info?.generator && needsCompute && !running ? buildTimeNote(estimate) : null- const original = info?.facts.original ?? null- const getOriginal = () => {- if (!original) return- useModelStore.getState().setCategoryFilter('text')- useUIStore.getState().openDiscoverFor('builtin', original, { original: true })- }-- 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))- }- }}- 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 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-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>}- {tweak && <TweakedNote title={tweak.title} text={tweak.text} original={tweak.original} onGetOriginal={getOriginal} />}- {timeNote && <TimeNote title={timeNote.title} text={timeNote.text} />}- {job && job.status !== 'idle' && <JobPanel job={job} onStop={() => { setQueue([]); void neuronCancel().then(poll) }} onDismiss={() => void neuronDismiss().then(poll)} onGetOriginal={getOriginal} original={original} />}- {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>- )}-- <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-')) },- ]}- />-- <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)}- prepareHint={timeNote ? 'Once per model. How long it takes is said above.' : undefined}- />- ))}- </div>- </>- )}-- {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={v.left || 'Less'} right={v.name} value={strengths[v.id] ?? 0} max={NEURON_MAX_DOSE} 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>-- <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} labelOf={labelOf} 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-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>-- <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>- </details>- </Shell>- )-}--/** No LU Engine chat model yet: one centred state with the two ways to get- * 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, onIntro, error, onDismissError }: {- onDownload: () => void- onAddFile: () => void- onIntro: () => void- error: string | null- onDismissError: () => void-}) {- return (- <div className="h-full overflow-y-auto scrollbar-thin flex items-center justify-center px-6 py-8" data-testid="neuron-view">- <div className="max-w-md flex flex-col items-center text-center gap-3" data-testid="neuron-empty">- <Sliders size={28} className="text-gray-400 dark:text-gray-500" aria-hidden />- <h1 className="t-title text-gray-900 dark:text-white">No chat model for the LU Engine yet</h1>- <p className="t-body text-gray-300" data-testid="neuron-no-chat-model">{NO_CHAT_MODEL}</p>- <p className={`t-body ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-other-apps">{OTHER_APPS}</p>- <div className="flex flex-wrap items-center justify-center gap-2 pt-1">- <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. */}- <div className="mt-3 w-full text-left rounded-lg border border-gray-200 dark:border-white/[0.06] px-4 py-3" data-testid="neuron-gguf-steps">- <p className="t-body font-semibold text-gray-900 dark:text-white mb-1.5">Already have a GGUF file?</p>- <ol className="t-body text-gray-300 space-y-1 list-decimal pl-5">- {GGUF_STEPS.map((s) => <li key={s.from}>{s.text}</li>)}- </ol>- <button className="lu-control mt-2.5" onClick={onAddFile} data-testid="neuron-add-gguf" title="Use a GGUF file from your drive as a chat model on the LU Engine">- <FilePlus size={ICON_SM} /> GGUF file- </button>- </div>- {error && <Hinweis ton="fehler" className="mt-2 text-left" onDismiss={onDismissError}>{error}</Hinweis>}- </div>- </div>- )-}--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-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>- <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/NeuronWindow.tsx b/src/components/neuron/NeuronWindow.tsxnew file mode 100644index 00000000..cf784891--- /dev/null+++ b/src/components/neuron/NeuronWindow.tsx@@ -0,0 +1,81 @@+// The Neurons window (3.1.0): one floating window over Chat, Code and Agent,+// opened from the Neurons row under Plugins. It can be dragged by its title+// bar, folded to that bar while one chats, and closed; closing hides the+// window only, the sliders keep steering until the plugin is switched off.++import { useCallback, useEffect, useRef, useState } from 'react'+import { motion, useReducedMotion } from 'framer-motion'+import { NeuronPanel } from './NeuronPanel'+import {+ NEURON_WINDOW_GAP, NEURON_WINDOW_MAX_H, NEURON_WINDOW_W, clampWindowPos, defaultWindowPos, useNeuronWindow,+} from '../../stores/neuronWindowStore'++function viewport(): { vw: number; vh: number } {+ return { vw: window.innerWidth, vh: window.innerHeight }+}++export function NeuronWindow() {+ const open = useNeuronWindow((s) => s.open)+ const collapsed = useNeuronWindow((s) => s.collapsed)+ const saved = useNeuronWindow((s) => s.pos)+ const hide = useNeuronWindow((s) => s.hide)+ const setCollapsed = useNeuronWindow((s) => s.setCollapsed)+ const setPos = useNeuronWindow((s) => s.setPos)+ const reduced = useReducedMotion()++ const [{ vw, vh }, setView] = useState(viewport)+ useEffect(() => {+ const on = () => setView(viewport())+ window.addEventListener('resize', on)+ return () => window.removeEventListener('resize', on)+ }, [])++ const width = Math.min(NEURON_WINDOW_W, vw - 2 * NEURON_WINDOW_GAP)+ const pos = clampWindowPos(saved ?? defaultWindowPos(vw), vw, vh)+ const height = Math.min(NEURON_WINDOW_MAX_H, vh - pos.y - NEURON_WINDOW_GAP)++ // Drag by the title bar. The position follows the pointer while it moves+ // and is saved once, on release.+ const [drag, setDrag] = useState<{ x: number; y: number } | null>(null)+ const start = useRef<{ px: number; py: number; x: number; y: number } | null>(null)+ const onDragStart = useCallback((e: React.PointerEvent) => {+ if (e.button !== 0) return+ start.current = { px: e.clientX, py: e.clientY, x: pos.x, y: pos.y }+ ;(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId)+ const move = (ev: PointerEvent) => {+ const s = start.current+ if (!s) return+ setDrag(clampWindowPos({ x: s.x + ev.clientX - s.px, y: s.y + ev.clientY - s.py }, window.innerWidth, window.innerHeight))+ }+ const up = (ev: PointerEvent) => {+ const s = start.current+ start.current = null+ window.removeEventListener('pointermove', move)+ window.removeEventListener('pointerup', up)+ setDrag(null)+ if (s && (Math.abs(ev.clientX - s.px) > 2 || Math.abs(ev.clientY - s.py) > 2)) {+ setPos(clampWindowPos({ x: s.x + ev.clientX - s.px, y: s.y + ev.clientY - s.py }, window.innerWidth, window.innerHeight))+ }+ }+ window.addEventListener('pointermove', move)+ window.addEventListener('pointerup', up)+ }, [pos.x, pos.y, setPos])++ if (!open) return null+ const at = drag ?? pos+ return (+ <motion.div+ role="dialog"+ aria-label="Neurons"+ data-testid="neuron-window"+ data-collapsed={collapsed || undefined}+ initial={reduced ? false : { opacity: 0, y: 8, scale: 0.98 }}+ animate={{ opacity: 1, y: 0, scale: 1 }}+ transition={{ duration: 0.16, ease: 'easeOut' }}+ style={{ left: at.x, top: at.y, width, height: collapsed ? 'auto' : height }}+ className="fixed z-[45] lu-elevated rounded-xl overflow-hidden flex flex-col"+ >+ <NeuronPanel chrome={{ onDragStart, collapsed, onCollapse: setCollapsed, onClose: hide }} />+ </motion.div>+ )+}diff --git a/src/components/neuron/NeuronWindowHost.tsx b/src/components/neuron/NeuronWindowHost.tsxnew file mode 100644index 00000000..5950b7c0--- /dev/null+++ b/src/components/neuron/NeuronWindowHost.tsx@@ -0,0 +1,14 @@+import { Suspense, lazy } from 'react'++// Neurons' window (3.1.0) in a chunk of its own, loaded once the plugin is+// on. A floating window has no place to hold while it loads, so nothing+// stands there meanwhile (the views' skeletons are for <main>).+const NeuronWindow = lazy(() => import('./NeuronWindow').then((m) => ({ default: m.NeuronWindow })))++export function NeuronWindowHost() {+ return (+ <Suspense fallback={null}>+ <NeuronWindow />+ </Suspense>+ )+}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 8d8f8b9e..9f601455 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@@ -59,7 +59,7 @@ const slot = vi.hoisted(() => ({ managed: true }))const job = vi.hoisted(() => ({ status: 'idle', modelPath: '' }))vi.mock('../../../api/builtin-ensure', () => ({ isManagedBuiltinSlot: () => slot.managed }))-import { NeuronView } from '../NeuronView'+import { NeuronPanel as NeuronView } from '../NeuronPanel'import { useModelStore } from '../../../stores/modelStore'import { useNeuronStore } from '../../../stores/neuronStore'import { useSettingsStore } from '../../../stores/settingsStore'@@ -147,7 +147,7 @@ describe('Neuron tweaker view', () => {useSettingsStore.setState((s) => ({ personas: [{ id: 'coder', name: 'Coder', systemPrompt: 'Code.' } as Persona], activePersonaId: 'coder', settings: { ...s.settings, personasEnabled: true } }))render(createElement(NeuronView))const row = await screen.findByTestId('neuron-slider-creative')- await screen.findByText(/This model with/)+ await waitFor(() => expect(row.querySelector('input[type=range]')).toBeTruthy())fireEvent.change(row.querySelector('input[type=range]') as HTMLInputElement, { target: { value: '0.2' } })expect(useNeuronStore.getState().profiles['qwen-1::persona:coder']).toEqual({ creative: 0.2, cheerful: 0.4 })await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([{ id: 'cheerful', strength: 0.4 }, { id: 'creative', strength: 0.2 }]), { timeout: 3000 })@@ -174,16 +174,14 @@ describe('Neuron tweaker view', () => {})// David, 30.10.2026: the line sat at the top, "hingeklatscht". It is one- // state in the middle of the panel, both ways, with its text centred.- it('stands in the middle of the panel when there is no model', async () => {+ // state filling the window under its title bar, both ways, text centred.+ it('stands in the middle of the window when there is no model', async () => {disk.models = []render(createElement(NeuronView))const box = await screen.findByTestId('neuron-empty')const panel = screen.getByTestId('neuron-view')expect(panel.className).toMatch(/\bh-full\b/)expect(panel.className).toMatch(/\bflex\b/)- expect(panel.className).toMatch(/\bitems-center\b/)- expect(panel.className).toMatch(/\bjustify-center\b/)expect(box.className).toMatch(/\btext-center\b/)expect(box.className).toMatch(/\bitems-center\b/)})diff --git a/src/components/neuron/__tests__/neurons-for-beginners.test.tsx b/src/components/neuron/__tests__/neurons-for-beginners.test.tsxindex 815d0854..5314e53e 100644--- a/src/components/neuron/__tests__/neurons-for-beginners.test.tsx+++ b/src/components/neuron/__tests__/neurons-for-beginners.test.tsx@@ -2,7 +2,9 @@* @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+ * 3.1.0 (David, 08.11.2026): one window with pop-ups instead of a page. The+ * window holds the model, the sliders and what is on; adding a slider (the+ * ways as tabs), before/after and sharing open as pop-ups over it. 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.@@ -54,7 +56,8 @@ vi.mock('../../../api/engine', () => ({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 { NeuronPanel as NeuronView } from '../NeuronPanel'+import { useSettingsStore } from '../../../stores/settingsStore'import { useModelStore } from '../../../stores/modelStore'import { useUIStore } from '../../../stores/uiStore'import { useNeuronStore } from '../../../stores/neuronStore'@@ -80,27 +83,58 @@ beforeEach(() => {})afterEach(() => cleanup())-describe('Neurons for beginners: one page in steps', () => {- it('reads top to bottom in four numbered steps', async () => {+/** Opens a pop-up from the window's action row once the model is read. */+async function openPopup(id: 'neuron-add' | 'neuron-open-compare' | 'neuron-open-share') {+ const button = await screen.findByTestId(id) as HTMLButtonElement+ await waitFor(() => expect(button.disabled).toBe(false))+ fireEvent.click(button)+}++/** The Add pop-up on one of its ways. */+async function openWay(way: 'own' | 'features' | 'coords') {+ await openPopup('neuron-add')+ fireEvent.click(await screen.findByTestId(`neuron-way-${way}`))+}++describe('Neurons in one window with pop-ups', () => {+ it('keeps model, sliders and what is on in the window; the rest opens as a pop-up', 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')+ expect(screen.getByTestId('neuron-presets')).toBeTruthy()+ expect(screen.getByTestId('neuron-mix')).toBeTruthy()+ expect(screen.queryByRole('dialog')).toBeNull()+ await openPopup('neuron-add')+ const add = screen.getByTestId('neuron-popup-add')+ expect(add.getAttribute('role')).toBe('dialog')+ expect(add.getAttribute('aria-label')).toBe('Add a slider')+ // Escape closes the pop-up, the window stays.+ fireEvent.keyDown(document, { key: 'Escape' })+ await waitFor(() => expect(screen.queryByTestId('neuron-popup-add')).toBeNull())+ expect(screen.getByTestId('neuron-presets')).toBeTruthy()+ await openPopup('neuron-open-compare')+ expect(screen.getByTestId('neuron-popup-compare')).toBeTruthy()+ fireEvent.click(screen.getByTestId('neuron-popup-close'))+ await openPopup('neuron-open-share')+ expect(screen.getByTestId('neuron-popup-share')).toBeTruthy()})- it('shows the ways to make a slider as tabs, each with one line on what it is', async () => {+ it('shows the ways to add a slider as tabs in the Add pop-up, each with one line on what it is', async () => {render(createElement(NeuronView))+ await openPopup('neuron-add')const tabs = await screen.findAllByRole('tab')- expect(tabs.map((t) => t.textContent)).toEqual(['Ready-made', 'From examples', 'Features', 'Coordinates'])+ expect(tabs.map((t) => t.textContent)).toEqual(['From examples', 'Features', 'Coordinates'])+ expect(screen.getByText(/Your own slider, from examples/)).toBeTruthy()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('names the window status in its title bar', async () => {+ vectors.push(CHEERFUL)+ useNeuronStore.setState({ profiles: { 'qwen-1': { cheerful: 0.6 } } })+ render(createElement(NeuronView))+ await waitFor(() => expect(screen.getByTestId('neuron-status').textContent).toBe('1 on'))+ await waitFor(() => expect(screen.getByTestId('neuron-applied').textContent).toBe('Active in Chat, Code and Agent: 1 slider'))+ })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 } } })@@ -120,7 +154,7 @@ describe('Neurons for beginners: one page in steps', () => {// `.dark .text-gray-700` to gray-500 (index.css, contrast layer), which beats// a `dark:text-gray-200` next to it. The page uses the house's own greys.it('uses the greys the house does not dim', () => {- for (const f of ['NeuronView.tsx', 'parts.tsx', 'panels.tsx', 'NeuronIntro.tsx']) {+ for (const f of ['NeuronPanel.tsx', 'NeuronWindow.tsx', 'parts.tsx', 'panels.tsx', 'NeuronIntro.tsx']) {const src = readFileSync(resolve(__dirname, '..', f), 'utf8')expect(src, f).not.toMatch(/text-gray-[67]00 dark:text-gray-/)}@@ -137,19 +171,28 @@ describe('the introduction', () => {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])+ // Back from the window's own "How Neurons works".+ fireEvent.click(screen.getByTestId('neuron-help'))expect(await screen.findByTestId('neuron-intro')).toBeTruthy()expect(screen.getByTestId('neuron-intro-step').textContent).toBe('Step 1 of 5')})- // D13 (3.0.9): Neurons is hidden, so neither the view nor its introduction- // is in the command palette; both come back with lib/features.- it('is not in the command palette while Neurons is hidden', () => {- 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 })+ // 3.1.0: Neurons is a plugin. Its window and introduction are in the+ // command palette while the plugin is on, and nowhere while it is off.+ it('is in the command palette only while the plugin is on', () => {+ const ctx = { shortcuts: SHORTCUT_ACTIONS, keysFor: shortcutKeys, localViewsAvailable: true, setView: vi.fn(), openCompare: vi.fn(), toggleSidebar: vi.fn(), setActiveModel: vi.fn(), models: [], activeModel: null, quit: null }+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: false })+ let actions = buildCommands(ctx)expect(actions.find((a) => a.id === 'neuron-intro')).toBeUndefined()+ expect(actions.find((a) => a.id === 'neuron-window')).toBeUndefined()expect(actions.find((a) => a.id === 'view-neuron')).toBeUndefined()- expect(useNeuronIntroRequest.getState().open).toBe(false)+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: true })+ actions = buildCommands(ctx)+ expect(actions.find((a) => a.id === 'view-neuron')).toBeUndefined()+ actions.find((a) => a.id === 'neuron-intro')!.run()+ expect(useNeuronIntroRequest.getState().open).toBe(true)+ expect(ctx.setView).toHaveBeenCalledWith('chat')+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: false })})it('stands still with reduced motion', () => {@@ -176,7 +219,7 @@ describe('coordinates', () => {useNeuronStore.setState({ profiles: { 'qwen-1': { cheerful: 0.2 } } })render(createElement(NeuronView))await screen.findByTestId('neuron-slider-cheerful')- fireEvent.click(screen.getByTestId('neuron-way-coords'))+ await openWay('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.'] }]))@@ -196,13 +239,16 @@ describe('coordinates', () => {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))+ // The recipe is in: the pop-up closed; Undo waits under Share.+ expect(screen.queryByTestId('neuron-popup-add')).toBeNull()+ await openPopup('neuron-open-share')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'))+ await openWay('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()@@ -211,7 +257,7 @@ describe('coordinates', () => {it('says when the numbers belong to another model', async () => {Object.assign(facts, { mlpNeurons: true, nFf: 4864 })render(createElement(NeuronView))- fireEvent.click(await screen.findByTestId('neuron-way-coords'))+ await openWay('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/)// Neuron 7956 is past this model's 4864: nothing the box could unlock.@@ -224,7 +270,7 @@ describe('coordinates', () => {vectors.push(CHEERFUL)render(createElement(NeuronView))await screen.findByTestId('neuron-slider-cheerful')- fireEvent.click(screen.getByTestId('neuron-way-coords'))+ await openWay('coords')fireEvent.change(await screen.findByTestId('neuron-coords-input'), { target: { value: '@cheerful+0.4 L14N8949+1.0' } })expect(screen.getAllByTestId('neuron-coords-line')[1].textContent).toMatch(/experts \(MoE\).*Not usable$/)// FEHLER-N2 #1: one value, said as one.@@ -242,7 +288,7 @@ describe('single neurons', () => {it('prepares and sets the shared Qwen3.5-4B neurons, one after the other', async () => {render(createElement(NeuronView))- fireEvent.click(await screen.findByTestId('neuron-way-coords'))+ await openWay('coords')fireEvent.click(await screen.findByText('A shared neuron (Qwen3.5-4B)'))await waitFor(() => expect(screen.getAllByTestId('neuron-coords-line')).toHaveLength(2))expect(screen.getByTestId('neuron-coords-preview').textContent).toMatch(/That is the model you picked/)@@ -258,7 +304,7 @@ describe('single neurons', () => {it('keeps a dose above 1 and gives the neuron slider room to ±3', async () => {vectors.push({ id: 'n-L14-N8949', kind: 'neuron', name: 'L14 N8949', left: 'Less', right: 'More', unit: 31.5, builtAt: 1, more: [], less: [] })render(createElement(NeuronView))- fireEvent.click(await screen.findByTestId('neuron-way-coords'))+ await openWay('coords')fireEvent.change(await screen.findByTestId('neuron-coords-input'), { target: { value: 'L14N8949+1.5' } })expect(screen.getAllByTestId('neuron-coords-line')[0].textContent).toMatch(/Ready$/)fireEvent.click(screen.getByTestId('neuron-coords-use'))@@ -267,8 +313,7 @@ describe('single neurons', () => {expect([range.min, range.max, range.value]).toEqual(['-3', '3', '1.5'])expect(mlpAdd).not.toHaveBeenCalled()// The engine gets the dose, not one cut to 1 (AN-N2-P11.md).- await waitFor(() => expect(apply).toHaveBeenCalled())- expect(apply.mock.calls.at(-1)![1]).toEqual([{ id: 'n-L14-N8949', strength: 1.5 }])+ await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([{ id: 'n-L14-N8949', strength: 1.5 }]))fireEvent.change(range, { target: { value: '2.5' } })expect(useNeuronStore.getState().profiles['qwen-1']).toEqual({ 'n-L14-N8949': 2.5 })})@@ -278,6 +323,7 @@ describe('single neurons', () => {useNeuronStore.setState({ profiles: { 'qwen-1': { 'n-L13-N7956': -1 } } })render(createElement(NeuronView))await within(await screen.findByTestId('neuron-mix')).findByText('L13 N7956')+ await openPopup('neuron-open-compare')fireEvent.click(screen.getByTestId('neuron-compare-run'))const after = await screen.findByTestId('neuron-compare-after')expect(after.previousElementSibling!.textContent).toBe('After · L13 N7956 −1.00')@@ -285,7 +331,7 @@ describe('single neurons', () => {it('names the layers and neurons a model has before anything runs', async () => {render(createElement(NeuronView))- fireEvent.click(await screen.findByTestId('neuron-way-coords'))+ await openWay('coords')fireEvent.change(await screen.findByTestId('neuron-coords-input'), { target: { value: 'L0N5+1 L31N5+1 L13N9216+1' } })const lines = screen.getAllByTestId('neuron-coords-line').map((l) => l.textContent)expect(lines[0]).toMatch(/Single neurons work in layers 1 to 30 of this model\.Not usable$/)@@ -302,6 +348,7 @@ describe('sharing', () => {const writeText = vi.fn(async (_t: string) => {})Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })render(createElement(NeuronView))+ await openPopup('neuron-open-share')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'))@@ -323,7 +370,7 @@ describe('tweaked models', () => {expect(note.textContent).toMatch(/^Works best with original, untweaked models/)expect(note.textContent).toMatch(/fine-tune, merge, heretic, uncensored/)// Above the ways and their compute buttons, blocking nothing.- expect(note.compareDocumentPosition(screen.getByTestId('neuron-way-ready')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(note.compareDocumentPosition(screen.getByTestId('neuron-presets')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()expect((screen.getByTestId('neuron-compute-creative') as HTMLButtonElement).disabled).toBe(false)fireEvent.click(screen.getByTestId('neuron-get-original'))const ui = useUIStore.getState()@@ -360,12 +407,14 @@ describe('how long it takes', () => {expect(note.textContent).toMatch(/^This takes a while on this PC/)expect(note.textContent).toMatch(/Expect about 12–50 min for one slider\./)// Above the ways, next to the original note; the row points up to it.- expect(note.compareDocumentPosition(screen.getByTestId('neuron-way-ready')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(note.compareDocumentPosition(screen.getByTestId('neuron-presets')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()expect(within(screen.getByTestId('neuron-slider-creative')).getByText('Once per model. How long it takes is said above.')).toBeTruthy()- fireEvent.click(screen.getByTestId('neuron-way-own'))- expect(screen.getByTestId('neuron-time-note').textContent).toMatch(/25 min to 1 h 30 min.*last run on this PC/)+ // The Add pop-up says it for its own ways: from examples, coordinates.+ await openWay('own')+ const popup = screen.getByTestId('neuron-popup-add')+ expect(within(popup).getByTestId('neuron-time-note').textContent).toMatch(/25 min to 1 h 30 min.*last run on this PC/)fireEvent.click(screen.getByTestId('neuron-way-features'))- expect(screen.queryByTestId('neuron-time-note')).toBeNull()+ expect(within(popup).queryByTestId('neuron-time-note')).toBeNull()})it('says nothing where it is a moment, or nothing is left to compute', async () => {diff --git a/src/components/neuron/panels.tsx b/src/components/neuron/panels.tsxindex cbac2173..8ae7ef47 100644--- a/src/components/neuron/panels.tsx+++ b/src/components/neuron/panels.tsx@@ -26,8 +26,8 @@ const field = `w-full ${fieldBase}`// ── From examples ─────────────────────────────────────────────────────-export function OwnSliderForm({ disabled, onCompute }: { disabled: boolean; onCompute: (name: string, more: string[], less: string[]) => void }) {- const [open, setOpen] = useState(false)+export function OwnSliderForm({ disabled, onCompute, startOpen = false }: { disabled: boolean; onCompute: (name: string, more: string[], less: string[]) => void; startOpen?: boolean }) {+ const [open, setOpen] = useState(startOpen)const [name, setName] = useState('')const [more, setMore] = useState('')const [less, setLess] = useState('')@@ -48,7 +48,7 @@ export function OwnSliderForm({ disabled, onCompute }: { disabled: boolean; onCo</label><div><p className="t-body font-medium 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">+ <div className="grid grid-cols-1 @lg:grid-cols-2 gap-3"><label className="block t-micro 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>@@ -62,7 +62,7 @@ export function OwnSliderForm({ disabled, onCompute }: { disabled: boolean; onCo<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>+ {!startOpen && <button type="button" onClick={() => setOpen(false)} className="lu-control">Cancel</button>}</div></div>)@@ -347,10 +347,10 @@ export function ComparePanel({ modelPath, entries, labelOf, disabled, model, tun{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>}+ {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 first.</p>}{result && (<>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3" data-testid="neuron-compare-result">+ <div className="grid grid-cols-1 @lg: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-100 whitespace-pre-wrap" data-testid="neuron-compare-before">{result.before}</p>@@ -393,7 +393,7 @@ export function SharePanel({ recipe, skipped, onUndo }: { recipe: Recipe; skippe<div className="space-y-2" data-testid="neuron-share">{hasAny ? (<>- <p className="t-body text-gray-200">Your mix as coordinates. Others paste it under <span className="font-medium">Coordinates</span>.</p>+ <p className="t-body text-gray-200">Your mix as coordinates. Others paste it under <span className="font-medium">Add slider, 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` : ''}diff --git a/src/components/ui/command-actions.ts b/src/components/ui/command-actions.tsindex c2b8c7f0..62a1a8f2 100644--- a/src/components/ui/command-actions.ts+++ b/src/components/ui/command-actions.ts@@ -16,6 +16,8 @@ import type { ShortcutId } from '../../hooks/useKeyboardShortcuts'import type { View } from '../../stores/uiStore'import { useNeuronIntroRequest } from '../../stores/neuronIntroStore'import { NEURONS_ENABLED } from '../../lib/features'+import { useNeuronWindow } from '../../stores/neuronWindowStore'+import { useSettingsStore } from '../../stores/settingsStore'// 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.@@ -127,10 +129,12 @@ export function buildCommands(ctx: CommandContext): Command[] {if (ctx.localViewsAvailable) {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') })- if (NEURONS_ENABLED) {- out.push({ id: 'view-neuron', label: 'Neuron tweaker', group: GROUP_VIEW, run: () => ctx.setView('neuron') })+ // Neurons is a plugin (3.1.0): its window, once the plugin is on.+ if (NEURONS_ENABLED && useSettingsStore.getState().settings.neuronsPluginEnabled === true) {+ const openWindow = () => { ctx.setView('chat'); useNeuronWindow.getState().show() }+ out.push({ id: 'neuron-window', label: 'Neurons: open window', group: GROUP_VIEW, run: openWindow })// 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: 'neuron-intro', label: 'Neurons: how it works', group: GROUP_VIEW, run: () => { openWindow(); useNeuronIntroRequest.getState().show() } })}out.push({ id: 'view-models', label: 'Models', group: GROUP_VIEW, run: () => ctx.setView('models') })}diff --git a/src/hooks/useNeuronFollowsPersona.ts b/src/hooks/useNeuronFollowsPersona.tsindex 85fedd97..178ae95e 100644--- a/src/hooks/useNeuronFollowsPersona.ts+++ b/src/hooks/useNeuronFollowsPersona.ts@@ -4,7 +4,7 @@ import { neuronApply, neuronInfo } from '../api/neuron'import { entriesFor, effectiveStrengths, hasPersonaProfile, steeringPersona } from '../lib/neuron'import { useChatStore } from '../stores/chatStore'import { useNeuronStore } from '../stores/neuronStore'-import { NEURONS_ENABLED } from '../lib/features'+import { neuronsPluginOn } from './useNeuronPlugin'import { useSettingsStore } from '../stores/settingsStore'/**@@ -37,14 +37,14 @@ export function currentSteeringPersona(): { id: string | null; group: boolean }export function useNeuronFollowsPersona(): void {useEffect(() => {- // With Neurons hidden (lib/features) no slider may steer the engine unseen.- if (!NEURONS_ENABLED) returnlet prev = currentSteeringPersona().idconst check = () => {const next = currentSteeringPersona().idif (next === prev) returnconst was = prevprev = next+ // With the Neurons plugin off no slider may steer the engine unseen.+ if (!neuronsPluginOn()) returnvoid followPersona(was, next).catch(() => undefined)}const offSettings = useSettingsStore.subscribe(check)diff --git a/src/hooks/useNeuronPlugin.ts b/src/hooks/useNeuronPlugin.tsnew file mode 100644index 00000000..76dce41c--- /dev/null+++ b/src/hooks/useNeuronPlugin.ts@@ -0,0 +1,56 @@+import { useEffect, useRef } from 'react'+import { bundledEngineStatus, type BundledModel } from '../api/engine'+import { isTauri } from '../api/backend'+import { neuronPluginSet, neuronPluginStatus } from '../api/neuron'+import { preservedSwapCtx } from '../lib/builtin-ctx'+import { useSettingsStore } from '../stores/settingsStore'+import { useNeuronWindow } from '../stores/neuronWindowStore'+import type { BuiltinEngineTuning } from '../types/settings'++/** The tuning a restart uses: the user's, with the context the engine holds+ * kept the way the chat's own restarts keep it (lib/builtin-ctx). */+export async function restartTuning(model?: BundledModel): Promise<BuiltinEngineTuning | undefined> {+ const tuning = useSettingsStore.getState().settings.builtinEngine+ try {+ const status = await bundledEngineStatus()+ const keep = preservedSwapCtx({+ tuningCtx: tuning?.ctx,+ tuningChosen: tuning?.ctxChosen,+ currentCtx: status?.ctxRequested ?? status?.ctx,+ ctxTrain: model?.ctx_train,+ })+ return keep ? { ...(tuning ?? {}), ctx: keep } as BuiltinEngineTuning : tuning+ } catch {+ return tuning+ }+}++/** Whether the Neurons plugin is on in the settings (3.1.0). */+export function neuronsPluginOn(): boolean {+ return useSettingsStore.getState().settings.neuronsPluginEnabled === true+}++/**+ * Keeps Rust's Neurons switch (commands/neuron `plugin-on`) in step with the+ * Plugins row. Rust decides whether a saved mix reaches the engine; the app+ * only tells it. At start it asks first and speaks only on a difference, so+ * opening LU never restarts a running engine for nothing. Off also closes+ * the window.+ */+export function useNeuronPluginSync(): void {+ const enabled = useSettingsStore((s) => s.settings.neuronsPluginEnabled === true)+ const first = useRef(true)+ useEffect(() => {+ if (!enabled) useNeuronWindow.getState().hide()+ if (!isTauri()) return+ const initial = first.current+ first.current = false+ void (async () => {+ if (initial) {+ const now = await neuronPluginStatus().catch(() => null)+ if (now && now.enabled === enabled) return+ }+ await neuronPluginSet(enabled, await restartTuning())+ })().catch(() => undefined)+ }, [enabled])+}diff --git a/src/lib/__tests__/neurons-hidden-309.test.ts b/src/lib/__tests__/neurons-hidden-309.test.tsdeleted file mode 100644index b5772add..00000000--- a/src/lib/__tests__/neurons-hidden-309.test.ts+++ /dev/null@@ -1,71 +0,0 @@-// D13 (David, 04.11.2026): Neurons is hidden in 3.0.9, not removed. One-// switch (lib/features) closes every way in; these tests hold the switch and-// each entry it closes, so 3.1.0 turns it back on in one place.-import { describe, it, expect, vi, beforeEach } from 'vitest'-import { readFileSync } from 'node:fs'-import { resolve } from 'node:path'-import { NEURONS_ENABLED, visibleView } from '../features'-import { useUIStore } from '../../stores/uiStore'-import { buildCommands } from '../../components/ui/command-actions'-import { SHORTCUT_ACTIONS, shortcutKeys } from '../../hooks/useKeyboardShortcuts'-import { RELEASE_NOTES } from '../release-notes'-import { HOWTO } from '../howto'--const SRC = resolve(__dirname, '../..')-const read = (p: string) => readFileSync(resolve(SRC, p), 'utf-8')--describe('Neurons is hidden in 3.0.9', () => {- beforeEach(() => useUIStore.setState({ currentView: 'chat' }))-- it('the switch is off', () => {- expect(NEURONS_ENABLED).toBe(false)- })-- it('a hidden view falls back to Chat, the others stay', () => {- expect(visibleView('neuron')).toBe('chat')- for (const v of ['chat', 'models', 'settings', 'create', 'benchmark', 'voice'] as const) expect(visibleView(v)).toBe(v)- })-- it('a button or link that still asks for Neurons lands on Chat', () => {- useUIStore.getState().setView('models')- useUIStore.getState().setView('neuron')- expect(useUIStore.getState().currentView).toBe('chat')- })-- it('a saved UI state with "neuron" comes back as Chat', () => {- const merge = useUIStore.persist.getOptions().merge!- const merged = merge({ currentView: 'neuron', sidebarOpen: false }, useUIStore.getState()) as ReturnType<typeof useUIStore.getState>- expect(merged.currentView).toBe('chat')- expect(merged.sidebarOpen).toBe(false)- })-- it('the header has no Neurons tab', () => {- const header = read('components/layout/Header.tsx')- expect(header).toMatch(/\.filter\(\(t\) => t\.view === null \|\| visibleView\(t\.view\) === t\.view\)/)- })-- it('the command palette has neither the view nor the introduction', () => {- 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 })- expect(actions.filter((a) => /neuron/i.test(a.id + a.label))).toEqual([])- expect(actions.find((a) => a.id === 'view-models')).toBeDefined()- })-- it('the app never mounts the Neurons view', () => {- expect(read('components/layout/AppShell.tsx')).toContain("currentView === 'neuron' && NEURONS_ENABLED && <LazyView")- })-- it('the 3.0.9 release notes and the how-to lines do not name Neurons', () => {- const note = RELEASE_NOTES.find((n) => n.version === '3.0.9')!- expect(JSON.stringify(note)).not.toMatch(/neuron/i)- expect(JSON.stringify(HOWTO['gguf-file'])).not.toMatch(/neuron/i)- })-- it('Models and Discover name no Neuron tweaker while it is off', () => {- const discover = read('components/models/DiscoverModels.tsx')- for (const m of discover.matchAll(/Neuron (tweaker|sliders)/g)) {- const line = discover.slice(discover.lastIndexOf('\n', m.index!), discover.indexOf('\n', m.index!))- if (line.trim().startsWith('//') || line.trim().startsWith('*')) continue- expect(line).toContain('NEURONS_ENABLED')- }- })-})diff --git a/src/lib/__tests__/neurons-plugin-310.test.ts b/src/lib/__tests__/neurons-plugin-310.test.tsnew file mode 100644index 00000000..221383f1--- /dev/null+++ b/src/lib/__tests__/neurons-plugin-310.test.ts@@ -0,0 +1,105 @@+// 3.1.0 (David, 08.11.2026): Neurons is a plugin. It left the header and has+// no page; switched on under Plugins it opens one window over Chat, Code and+// Agent. Off, no slider steers the engine (Rust's switch, kept in step by+// useNeuronPluginSync). These tests hold each piece of that.+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { NEURONS_ENABLED, visibleView } from '../features'+import { useUIStore } from '../../stores/uiStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { buildCommands } from '../../components/ui/command-actions'+import { SHORTCUT_ACTIONS, shortcutKeys } from '../../hooks/useKeyboardShortcuts'+import { RELEASE_NOTES } from '../release-notes'+import { DEFAULT_SETTINGS } from '../constants'+import { clampWindowPos, defaultWindowPos, NEURON_WINDOW_W, useNeuronWindow } from '../../stores/neuronWindowStore'++const SRC = resolve(__dirname, '../..')+const read = (p: string) => readFileSync(resolve(SRC, p), 'utf-8')+const CTX = { shortcuts: SHORTCUT_ACTIONS, keysFor: shortcutKeys, localViewsAvailable: true, setView: vi.fn(), openCompare: vi.fn(), toggleSidebar: vi.fn(), setActiveModel: vi.fn(), models: [], activeModel: null, quit: null }++describe('Neurons is a plugin in 3.1.0', () => {+ beforeEach(() => {+ useUIStore.setState({ currentView: 'chat' })+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: false })+ useNeuronWindow.setState({ open: false, collapsed: false, pos: null })+ })++ it('exists, and is off until the user turns it on', () => {+ expect(NEURONS_ENABLED).toBe(true)+ expect(DEFAULT_SETTINGS.neuronsPluginEnabled).toBe(false)+ })++ it('has no page: a button, link or saved state that asks for it lands on Chat', () => {+ expect(visibleView('neuron')).toBe('chat')+ for (const v of ['chat', 'models', 'settings', 'create', 'benchmark', 'voice'] as const) expect(visibleView(v)).toBe(v)+ useUIStore.getState().setView('models')+ useUIStore.getState().setView('neuron')+ expect(useUIStore.getState().currentView).toBe('chat')+ const merge = useUIStore.persist.getOptions().merge!+ const merged = merge({ currentView: 'neuron', sidebarOpen: false }, useUIStore.getState()) as ReturnType<typeof useUIStore.getState>+ expect(merged.currentView).toBe('chat')+ })++ it('has no header tab', () => {+ expect(read('components/layout/Header.tsx')).not.toMatch(/id: 'neuron'/)+ })++ it('sits in the Plugins menu of Chat, Agent and Code, in the desktop app', () => {+ const menu = read('components/chat/PluginsDropdown.tsx')+ expect(menu).toMatch(/const neuronsShown = isTauri\(\)/)+ expect(menu).toMatch(/\{neuronsShown && <NeuronPluginRow /)+ // The same menu is the composer's (Chat, Agent) and the Code header's.+ expect(read('components/chat/ChatView.tsx')).toMatch(/<PluginsDropdown openUpward/)+ expect(read('components/chat/CodexView.tsx')).toMatch(/<PluginsDropdown iconOnly/)+ })++ it('mounts its window only while the plugin is on, over the chat surfaces', () => {+ const shell = read('components/layout/AppShell.tsx')+ expect(shell).toMatch(/const neuronsOn = settings\.neuronsPluginEnabled === true && settings\.appMode !== 'cloud' && isTauri\(\)/)+ expect(shell).toContain("{neuronsOn && currentView === 'chat' && <NeuronWindowHost />}")+ // The window itself comes in a chunk of its own.+ expect(read('components/neuron/NeuronWindowHost.tsx')).toContain("lazy(() => import('./NeuronWindow')")+ expect(shell).toContain('useNeuronPluginSync()')+ expect(shell).not.toMatch(/NeuronView/)+ })++ it('is in the command palette only while it is on, as its window', () => {+ expect(buildCommands(CTX).filter((a) => /neuron/i.test(a.id + a.label))).toEqual([])+ useSettingsStore.getState().updateSettings({ neuronsPluginEnabled: true })+ const actions = buildCommands(CTX)+ const open = actions.find((a) => a.id === 'neuron-window')!+ expect(open.label).toBe('Neurons: open window')+ open.run()+ expect(useNeuronWindow.getState().open).toBe(true)+ expect(actions.find((a) => a.id === 'view-neuron')).toBeUndefined()+ })++ it('keeps a persona switch from steering while it is off', () => {+ const src = read('hooks/useNeuronFollowsPersona.ts')+ expect(src).toMatch(/if \(!neuronsPluginOn\(\)\) return/)+ })++ it('keeps the 3.0.9 release notes free of Neurons', () => {+ const note = RELEASE_NOTES.find((n) => n.version === '3.0.9')!+ expect(JSON.stringify(note)).not.toMatch(/neuron/i)+ })+})++describe('the Neurons window stays on screen', () => {+ it('starts on the right, under the header', () => {+ expect(defaultWindowPos(1440)).toEqual({ x: 1440 - NEURON_WINDOW_W - 16, y: 64 })+ })++ it('keeps its title bar reachable after a drag or a smaller window', () => {+ expect(clampWindowPos({ x: -200, y: -50 }, 1200, 800)).toEqual({ x: 12, y: 12 })+ expect(clampWindowPos({ x: 5000, y: 5000 }, 1200, 800)).toEqual({ x: 1200 - NEURON_WINDOW_W - 12, y: 800 - 48 - 12 })+ // Narrower than the window: it sits at the gap, never off the left edge.+ expect(clampWindowPos({ x: 300, y: 100 }, 360, 700).x).toBe(12)+ })++ it('remembers where it stood and whether it was folded, not whether it was open', () => {+ const part = useNeuronWindow.persist.getOptions().partialize!({ ...useNeuronWindow.getState(), open: true, collapsed: true, pos: { x: 10, y: 20 } })+ expect(part).toEqual({ collapsed: true, pos: { x: 10, y: 20 } })+ })+})diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex f45e501e..99fab263 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -32,6 +32,7 @@ export const DEFAULT_SETTINGS: Settings = {enterKey: 'send',// REA plugin (3.0.7): a local MCP server, off until the user turns it on.reaPluginEnabled: false,+ neuronsPluginEnabled: false,// Reasoning effort (2.6.8). 'high' is not a taste, it is the rung this// client has always sent for thinking ON. Any other default would move every// existing customer's token bill on update without them touching anything.diff --git a/src/lib/features.ts b/src/lib/features.tsindex 1843bb7d..87cdb00d 100644--- a/src/lib/features.ts+++ b/src/lib/features.ts@@ -1,16 +1,18 @@/**- * Neurons (the Neuron tweaker, P11) is hidden in 3.0.9 (David, 04.11.2026):- * the tool gets reworked for 3.1.0. This one switch hides every way in- * (header tab, command palette, hints in Models and Discover, how-to lines,- * release notes, the introduction) and keeps persona sliders from steering- * the engine unseen. Backend, engine and saved sliders stay as they are.+ * Neurons (the neuron tweaker, P11) was hidden in 3.0.9 (David, 04.11.2026)+ * and comes back in 3.1.0 as a plugin (David, 08.11.2026): switched on under+ * Plugins, it works in one window over Chat, Code and Agent. It has no page+ * and no header tab any more; `NEURONS_ENABLED` says only that the feature+ * exists, so texts (Discover, how-to) may name it. Whether it steers is the+ * user's switch (settings.neuronsPluginEnabled, Rust's `plugin-on`).*/-export const NEURONS_ENABLED = false+export const NEURONS_ENABLED = true-/** The view to show for `view`: a hidden view falls back to Chat, so a- * stale button, link or saved state never lands on a page that is off.- * Generic over the view name instead of importing `View`: uiStore imports- * this file, and the type import back made an import cycle (`npm run cycles`). */+/** The view to show for `view`. Neurons has no page any more: an old button,+ * link or saved state that asks for it lands on Chat, where its window+ * lives. Generic over the view name instead of importing `View`: uiStore+ * imports this file, and the type import back made an import cycle+ * (`npm run cycles`). */export function visibleView<V extends string>(view: V): V | 'chat' {- return view === 'neuron' && !NEURONS_ENABLED ? 'chat' : view+ return view === 'neuron' ? 'chat' : view}diff --git a/src/lib/release-notes.ts b/src/lib/release-notes.tsindex 06e9819d..f8c713cb 100644--- a/src/lib/release-notes.ts+++ b/src/lib/release-notes.ts@@ -15,7 +15,6 @@*/import { CLOUD_PITCH, CLOUD_REFUSAL_LINE, CLOUD_SUBSCRIBER_LINE, cloudSalesLines } from './cloud-pitch'-import { NEURONS_ENABLED } from './features'/*** The two model numbers the 3.0.0 sheet quotes, in one place and read, never@@ -136,19 +135,14 @@ export interface ReleaseNote {// oder auf einer Karte lief, sagt die Zeile selbst knapp.const NOTE_309: ReleaseNote = {version: '3.0.9',- headline: NEURONS_ENABLED- ? 'Group chats send every speaker the context you picked, Neurons puts sliders on a local model, Animate takes an end image, and Create takes reference pictures.'- : 'Group chats send every speaker the context you picked, Animate takes an end image, and Create takes reference pictures.',+ // As shipped: Neurons was hidden in 3.0.9 and comes back as a plugin in+ // 3.1.0, so this note stays without it.+ headline: 'Group chats send every speaker the context you picked, Animate takes an end image, and Create takes reference pictures.',lines: [{title: 'Group chat: every speaker gets the context you picked.',detail: 'Local speakers get their chosen window minus room for the answer, no longer about half of it, and a grey line names messages that were not sent. One speaker can be regenerated on its own, and the speaking order can be changed with arrows or by dragging (GitHub #199, #200, #201).',},- // Neurons is off in 3.0.9 (lib/features); the line comes back with it.- ...(NEURONS_ENABLED ? [{- title: 'Neurons: sliders that steer a local LU Engine model.',- detail: 'Ready made sliders such as Serious to Cheerful or Fewer refusals, sliders from your own examples, and a before and after on the same question. LU measures how far each slider can push on your model; for small models that takes under a minute, and before a longer run Neurons says how long it will take and shows its progress. Ollama and LM Studio cannot take these sliders.',- }] : []),{title: 'End images and reference pictures in Animate and Create.',detail: 'Animate takes an end image for Wan 2.2 A14B, Wan 2.1 FLF2V and MiniMax H3, and up to nine reference pictures with MiniMax H3. Create takes reference pictures for Krea 2, Qwen-Image 2.1 and FLUX.2. A video shows a preview while it renders. The local end image and the preview ran on an RTX 3060; the reference pictures ran in automated tests only.',diff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.tsindex cde6f8f8..8333862c 100644--- a/src/lib/settings-catalog.ts+++ b/src/lib/settings-catalog.ts@@ -307,7 +307,7 @@ export const LOCK_RULES: readonly LockRule[] = [},{category: 'plugins', what: 'Plugins, MCP servers and custom nodes', where: 'Settings → Agent (MCP) and Plugins in the composer',- names: ['reaPluginEnabled', 'createEnabled', 'mcpServers', 'customNodes', 'plugins'],+ names: ['reaPluginEnabled', 'neuronsPluginEnabled', 'createEnabled', 'mcpServers', 'customNodes', 'plugins'],pattern: /plugin|mcp|customnode|extension|install|rea$/,},{diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.tsindex aac15859..1cc04ecd 100644--- a/src/lib/store-backup.ts+++ b/src/lib/store-backup.ts@@ -41,6 +41,8 @@ export const STORE_KEYS = ['lu-cloud-outage',// Neuron tweaker slider values per model and persona (3.0.9, P11).'lu-neuron-tweaker',+ // Where the Neurons window stood and whether it was folded (3.1.0).+ 'lu-neuron-window','locally-uncensored-agent-goal',// Computer control: the switch and the always allowed apps.'locally-uncensored-computer',diff --git a/src/stores/neuronWindowStore.ts b/src/stores/neuronWindowStore.tsnew file mode 100644index 00000000..ae3dfda9--- /dev/null+++ b/src/stores/neuronWindowStore.ts@@ -0,0 +1,70 @@+import { create } from 'zustand'+import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'++/**+ * The Neurons window (3.1.0): Neurons is a plugin now, not a page. Its+ * window floats over Chat, Code and Agent, so the sliders sit next to the+ * conversation they change. Whether it is open is not saved (a start of LU+ * opens nothing by itself); where it stood and whether it was folded are.+ */+export interface NeuronWindowPos {+ x: number+ y: number+}++interface NeuronWindowState {+ open: boolean+ /** Folded to its title bar, so the chat under it is free. */+ collapsed: boolean+ /** Top-left corner in CSS pixels; null = the default place (right side). */+ pos: NeuronWindowPos | null+ show: () => void+ hide: () => void+ toggle: () => void+ setCollapsed: (collapsed: boolean) => void+ setPos: (pos: NeuronWindowPos | null) => void+}++export const useNeuronWindow = create<NeuronWindowState>()(+ persist(+ (set) => ({+ open: false,+ collapsed: false,+ pos: null,+ show: () => set({ open: true, collapsed: false }),+ hide: () => set({ open: false }),+ toggle: () => set((s) => ({ open: !s.open, collapsed: false })),+ setCollapsed: (collapsed) => set({ collapsed }),+ setPos: (pos) => set({ pos }),+ }),+ {+ name: 'lu-neuron-window',+ storage: safeJSONStorage(),+ partialize: (s) => ({ collapsed: s.collapsed, pos: s.pos }),+ },+ ),+)++/** Window size: fixed width, as tall as fits. */+export const NEURON_WINDOW_W = 440+export const NEURON_WINDOW_MAX_H = 760+/** Room kept free around the window. */+export const NEURON_WINDOW_GAP = 12++/** Keeps the window's corner on screen, title bar always reachable. */+export function clampWindowPos(pos: NeuronWindowPos, vw: number, vh: number, w = NEURON_WINDOW_W): NeuronWindowPos {+ const width = Math.min(w, vw - 2 * NEURON_WINDOW_GAP)+ const maxX = Math.max(NEURON_WINDOW_GAP, vw - width - NEURON_WINDOW_GAP)+ const maxY = Math.max(NEURON_WINDOW_GAP, vh - 48 - NEURON_WINDOW_GAP)+ return {+ x: Math.round(Math.min(maxX, Math.max(NEURON_WINDOW_GAP, pos.x))),+ y: Math.round(Math.min(maxY, Math.max(NEURON_WINDOW_GAP, pos.y))),+ }+}++/** The default place: right side, under the header. */+export function defaultWindowPos(vw: number, w = NEURON_WINDOW_W): NeuronWindowPos {+ const width = Math.min(w, vw - 2 * NEURON_WINDOW_GAP)+ return { x: Math.max(NEURON_WINDOW_GAP, vw - width - 16), y: 64 }+}diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 82492544..46740d13 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -228,6 +228,8 @@ export const useSettingsStore = create<SettingsState>()(}// REA plugin (3.0.7): only a real true starts a process.state.settings.reaPluginEnabled = state.settings.reaPluginEnabled === true+ // Neurons plugin (3.1.0): only a real true lets sliders steer.+ state.settings.neuronsPluginEnabled = state.settings.neuronsPluginEnabled === true// 3.0.8 (A2): background generations are on unless switched off, and// the card per service is read defensively, a hand-edited profile// must not send a half pick to the backend.diff --git a/src/types/settings.ts b/src/types/settings.tsindex 5098f640..772e8669 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -98,6 +98,10 @@ export interface Settings {/** REA, the reverse engineering plugin of the agents (lib/plugins/rea.ts):* on starts its local MCP server. Default off. */reaPluginEnabled: boolean+ /** Neurons, the neuron tweaker as a plugin (3.1.0, components/neuron):+ * on lets saved sliders steer the LU Engine in Chat, Code and Agent and+ * offers its window. Default off; off starts the engine without sliders. */+ neuronsPluginEnabled?: boolean/*** How hard a reasoning model should think (2.6.8). One global rung, the same* way thinkingEnabled is one global switch, and it reaches Chat, Agent mode