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
fix(agent): self-control tools load lazily; the list guards count them (C60)
purpled8d4a08c477c
diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.tsindex 222fa92a..f620d97c 100644--- a/src/api/__tests__/tool-registry.test.ts+++ b/src/api/__tests__/tool-registry.test.ts@@ -41,7 +41,13 @@ describe('AGENT_TOOL_DEFS', () => {// 3.0.8 (A11): +2, get_settings und set_setting. Sie stehen in keinem// Prompt, der nicht nach Einstellungen fragt: im Chat und in Agent nur// ueber SETTINGS_KEYWORDS, in Code hinter dem Tor (GATE_KEYWORDS).- expect(AGENT_TOOL_DEFS).toHaveLength(19)+ //+ // 3.1.0 (C60): +5, set_settings, lu_models, lu_service, lu_download und+ // lu_open_settings. LU bedient sich selbst; eine Aktion (Modell, Dienst,+ // Download) hat Nebenwirkungen und eine eigene Karte und passt deshalb+ // nicht in set_setting. Alle fuenf stehen hinter demselben Tor wie+ // get_settings und fahren nur auf einer Nachricht ueber LU selbst mit.+ expect(AGENT_TOOL_DEFS).toHaveLength(24)})const expectedTools = [@@ -95,8 +101,11 @@ describe('AGENT_TOOL_DEFS', () => {// 3.0.8 (A11): get_settings liest nur, set_setting fragt mit seiner// eigenen Karte (alt -> neu), auch im Bypass. Eine zweite Rueckfrage// davor fragte doppelt, wie bei create_order.+ // 3.1.0 (C60): die fuenf Selbststeuerungswerkzeuge aus demselben Grund+ // wie set_setting: jede Aenderung fragt mit ihrer eigenen Karte.expect(autoNames).toEqual([- 'check_tasks', 'get_settings', 'message_agent', 'set_setting', 'todo_write', 'web_fetch', 'web_search',+ 'check_tasks', 'get_settings', 'lu_download', 'lu_models', 'lu_open_settings', 'lu_service', 'message_agent',+ 'set_setting', 'set_settings', 'todo_write', 'web_fetch', 'web_search',])})diff --git a/src/api/mcp/__tests__/kein-argument-ungeprueft.test.ts b/src/api/mcp/__tests__/kein-argument-ungeprueft.test.tsindex c4841fa6..513a8f3b 100644--- a/src/api/mcp/__tests__/kein-argument-ungeprueft.test.ts+++ b/src/api/mcp/__tests__/kein-argument-ungeprueft.test.ts@@ -81,6 +81,12 @@ const PFLICHT: Record<string, Record<string, string>> = {message_agent: { task_id: 'task-1-abcdef', message: 'halte dich kurz' },// A11: ohne Schluessel keine Karte und keine Aenderung.set_setting: { key: 'theme' },+ // C60: die Aktionen sagen ohne ihre Pflichtangabe, was fehlt, und beruehren+ // dabei kein Backend.+ lu_models: { action: 'list' },+ lu_service: { service: 'comfyui', action: 'status' },+ lu_download: { action: 'status' },+ lu_open_settings: { area: 'keys' },}/**diff --git a/src/api/mcp/__tests__/mobile-tool-filter.test.ts b/src/api/mcp/__tests__/mobile-tool-filter.test.tsindex 00cd8a77..06035877 100644--- a/src/api/mcp/__tests__/mobile-tool-filter.test.ts+++ b/src/api/mcp/__tests__/mobile-tool-filter.test.ts@@ -45,7 +45,8 @@ function registryHere(): ToolRegistry {const GONE = ['shell_execute', 'pr_resume', 'screenshot', 'image_generate', 'video_generate']/** The settings tools of A11 (3.0.8): desktop only, see MOBILE_UNBUILT_TOOLS. */-const SETTINGS = ['get_settings', 'set_setting']+// A11 (3.0.8) and C60 (3.1.0): LU's own settings and actions, desktop only.+const SETTINGS = ['get_settings', 'set_setting', 'set_settings', 'lu_models', 'lu_service', 'lu_download', 'lu_open_settings']const STAYS = ['todo_write', 'web_search', 'web_fetch', 'file_read', 'file_write', 'file_edit', 'file_list','file_search', 'run_workflow', 'delegate_task', 'check_tasks', 'message_agent',@@ -66,12 +67,12 @@ describe('the catalog on a phone', () => {it('what the sub agent offers is what is registered, so it offers none of them either', () => {// api/agents/sub-agent.ts builds its tool list from toolRegistry.getAll()- // minus delegate_task and the settings tools (A11), and applies no device+ // minus delegate_task and the self-control tools (A11, C60), and applies no device// filter of its own.standOn('android')const offered = registryHere().getAll().map((t) => t.name).filter((n) => n !== 'delegate_task')for (const name of GONE) expect(offered).not.toContain(name)- expect(src('api/agents/sub-agent.ts')).toMatch(/toolRegistry\s*\.getAll\(\)\s*(\/\/[^\n]*\s*)?\.filter\(\(t\) => t\.name !== DELEGATE_TASK_TOOL_DEF\.name && !isSettingsToolName\(t\.name\)\)/)+ expect(src('api/agents/sub-agent.ts')).toMatch(/toolRegistry\s*\.getAll\(\)\s*(\/\/[^\n]*\s*)?\.filter\(\(t\) => t\.name !== DELEGATE_TASK_TOOL_DEF\.name && !isSelfControlToolName\(t\.name\)\)/)})it('the old names are no back door: all but the clock are unknown', async () => {diff --git a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts b/src/api/mcp/__tests__/tool-catalog-tokens.test.tsindex c90e6789..e6e70849 100644--- a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts+++ b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts@@ -130,8 +130,14 @@ const CODING_TOKEN_CEILING = 1730// 3.0.8 (A11): +762 Zeichen fuer get_settings und set_setting im VOLLEN// Katalog (18.370 -> 19.132). Der codierende Zug bleibt gleich: beide stehen// hinter dem Tor und fahren nur auf einer Nachricht ueber Einstellungen mit.-const FULL_CHAR_CEILING = 19170-const FULL_TOKEN_CEILING = 4090+// 3.1.0 (C60): +2.153 Zeichen fuer set_settings, lu_models, lu_service,+// lu_download und lu_open_settings im VOLLEN Katalog (19.170 -> 21.323). Der+// codierende Zug bleibt gleich: alle fuenf stehen hinter demselben Tor wie+// get_settings und fahren nur auf einer Nachricht ueber LU selbst mit. Die+// Beschreibungen sind auf einen Satz gekuerzt; die Token-Decke ist geschaetzt+// (Zeichen / 4 auf die alte Decke), der Tokenizer-Lauf ist hier uebersprungen.+const FULL_CHAR_CEILING = 21330+const FULL_TOKEN_CEILING = 4630describe('the coding step carries a catalog the diet actually shrank', () => {it('the gate really is what a plain coding turn gets', () => {diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 9775514e..3cdea301 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -8,7 +8,7 @@ import type {import type { ToolRegistry } from './tool-registry'import { reserveCreateTools } from './create-tools'import { registerSettingsTools } from './settings-tools'-import { registerSelfControlTools } from './self-control-tools'+import { registerSelfControlTools } from './self-control-defs'import { SETTINGS_TOOL_NAMES, SELF_CONTROL_ACTION_NAMES } from '../../lib/settings-tool-names'import { v4 as uuid } from 'uuid'import { backendCall, isTauri } from '../backend'diff --git a/src/api/mcp/self-control-defs.ts b/src/api/mcp/self-control-defs.tsnew file mode 100644index 00000000..187bde7d--- /dev/null+++ b/src/api/mcp/self-control-defs.ts@@ -0,0 +1,133 @@+// The self-control tools as the registry sees them (C60, 3.1.0): schemas, the+// mark an action leaves under its result, and the registration. Nothing heavy+// is imported here: the tool registry loads this with the app, and the stores,+// the engine and the downloader behind the tools would pull half the app, with+// code that runs at import time, into every module that only registers tools.+// The executors load on the first call (self-control-tools.ts, settings-tools.ts).++import type { MCPToolDefinition } from './types'+import type { ToolRegistry } from './tool-registry'+import {+ SET_SETTINGS, SET_SETTINGS_MAX, LU_MODELS, LU_SERVICE, LU_DOWNLOAD, LU_OPEN_SETTINGS,+} from '../../lib/settings-tool-names'++// ── Schemas ──────────────────────────────────────────────────────++// Defined here, not in settings-tools.ts: this module registers it, and a+// definition imported across the settings-tools ↔ stores ↔ mcp cycle can be+// undefined at registration time when settings-tools is loaded first.+const SET_SETTINGS_TOOL: MCPToolDefinition = {+ name: SET_SETTINGS,+ description: `Change up to ${SET_SETTINGS_MAX} LU app settings on one confirmation card, instead of several set_setting calls.`,+ brief: 'Change several LU app settings on one confirmation card.',+ inputSchema: {+ type: 'object',+ properties: {+ changes: {+ type: 'array',+ description: 'e.g. [{"key":"temperature","value":0.6}].',+ items: {+ type: 'object',+ properties: {+ key: { type: 'string', description: 'Key from get_settings.' },+ value: { type: ['string', 'number', 'boolean'], description: 'New value.' },+ },+ required: ['key', 'value'],+ },+ },+ },+ required: ['changes'],+ },+ category: 'system',+ source: 'builtin',+}+++const LU_MODELS_TOOL: MCPToolDefinition = {+ name: LU_MODELS,+ description: 'LU chat models: list, status, or switch (after the user confirms, when this answer is done).',+ brief: 'List LU chat models or switch the active chat model.',+ inputSchema: {+ type: 'object',+ properties: {+ action: { type: 'string', enum: ['list', 'status', 'switch'], description: 'What to do.' },+ name: { type: 'string', description: 'For switch: a model name from list.' },+ },+ required: ['action'],+ },+ category: 'system',+ source: 'builtin',+}++const LU_SERVICE_TOOL: MCPToolDefinition = {+ name: LU_SERVICE,+ description: 'Start, stop, restart or check a part of LU: comfyui, engine (LU Engine), local_api (this computer only), remote (phone, home network). The user confirms on a card.',+ brief: 'Start, stop or restart ComfyUI, LU Engine, the local API or the phone remote.',+ inputSchema: {+ type: 'object',+ properties: {+ service: { type: 'string', enum: ['comfyui', 'engine', 'local_api', 'remote'], description: 'Which part.' },+ action: { type: 'string', enum: ['status', 'start', 'stop', 'restart'], description: 'What to do.' },+ },+ required: ['service', 'action'],+ },+ category: 'system',+ source: 'builtin',+}++const LU_DOWNLOAD_TOOL: MCPToolDefinition = {+ name: LU_DOWNLOAD,+ description: 'Create models from the LU catalog: search, start (an id from search), status. '+ + 'start_link: a huggingface.co or civitai.com link the user pasted, into a ComfyUI model folder. The user confirms on a card.',+ brief: 'Search the LU model catalog and download a model, after the user confirms.',+ inputSchema: {+ type: 'object',+ properties: {+ action: { type: 'string', enum: ['search', 'start', 'status', 'start_link'], description: 'What to do.' },+ query: { type: 'string', description: 'Search words.' },+ id: { type: 'string', description: 'An id from search.' },+ url: { type: 'string', description: 'The link as the user sent it.' },+ folder: { type: 'string', description: 'Model folder, e.g. checkpoints, loras, vae.' },+ filename: { type: 'string', description: 'File name if the link lacks it.' },+ },+ required: ['action'],+ },+ category: 'system',+ source: 'builtin',+}++const LU_OPEN_SETTINGS_TOOL: MCPToolDefinition = {+ name: LU_OPEN_SETTINGS,+ description: 'Open LU Settings where the user changes what only they may (keys, looser permissions, paths, MCP). Changes nothing.',+ brief: 'Open LU Settings at a given area for the user.',+ inputSchema: {+ type: 'object',+ properties: {+ area: { type: 'string', description: 'e.g. keys, permissions, remote, local_api, mcp, comfyui, voice.' },+ },+ required: ['area'],+ },+ category: 'system',+ source: 'builtin',+}++export const SELF_CONTROL_TOOLS: MCPToolDefinition[] = [SET_SETTINGS_TOOL, LU_MODELS_TOOL, LU_SERVICE_TOOL, LU_DOWNLOAD_TOOL, LU_OPEN_SETTINGS_TOOL]++// ── Shared ───────────────────────────────────────────────────────++export { parseSelfControlAction, markOf, type SelfControlAction } from './self-control-mark'++++// ── Registration ─────────────────────────────────────────────────++const tools = () => import('./self-control-tools')+const settings = () => import('./settings-tools')++export function registerSelfControlTools(registry: ToolRegistry): void {+ registry.registerBuiltin(SET_SETTINGS_TOOL, async (a, run, signal) => (await settings()).executeSetSettings(a, run, signal))+ registry.registerBuiltin(LU_MODELS_TOOL, async (a, run, signal) => (await tools()).executeLuModels(a, run, signal))+ registry.registerBuiltin(LU_SERVICE_TOOL, async (a, run, signal) => (await tools()).executeLuService(a, run, signal))+ registry.registerBuiltin(LU_DOWNLOAD_TOOL, async (a, run, signal) => (await tools()).executeLuDownload(a, run, signal))+ registry.registerBuiltin(LU_OPEN_SETTINGS_TOOL, async (a) => (await tools()).executeLuOpenSettings(a))+}diff --git a/src/api/mcp/self-control-mark.ts b/src/api/mcp/self-control-mark.tsnew file mode 100644index 00000000..5b815703--- /dev/null+++ b/src/api/mcp/self-control-mark.ts@@ -0,0 +1,27 @@+// The mark an action of LU's self-control tools leaves under its tool result+// (C60), for the card that stays after the yes. Its own file so the card, the+// tools and the registration can share it without a cycle.++/** The line an action puts under its answer, for the card that stays. */+const ACTION_MARK = /<!-- lu-action (\{.*?\}) -->/++export interface SelfControlAction {+ kind: 'model' | 'service' | 'download'+ title: string+ /** For a model switch: the model before and after, for Undo. */+ from?: string | null+ to?: string | null+}++export function parseSelfControlAction(result: string | null | undefined): SelfControlAction | null {+ const m = typeof result === 'string' ? ACTION_MARK.exec(result) : null+ if (!m) return null+ try {+ const v = JSON.parse(m[1]) as Partial<SelfControlAction>+ return typeof v.kind === 'string' && typeof v.title === 'string' ? (v as SelfControlAction) : null+ } catch {+ return null+ }+}++export const markOf = (a: SelfControlAction) => `<!-- lu-action ${JSON.stringify(a)} -->`diff --git a/src/api/mcp/self-control-tools.ts b/src/api/mcp/self-control-tools.tsindex d5d6860b..4adf0b40 100644--- a/src/api/mcp/self-control-tools.ts+++ b/src/api/mcp/self-control-tools.ts@@ -19,168 +19,44 @@// the remote, delete anything, install a custom node, MCP server or plugin.import { v4 as uuid } from 'uuid'-import type { MCPToolDefinition, ToolArgs } from './types'-import type { ToolRegistry } from './tool-registry'+import type { ToolArgs } from './types'import { afterAgentRun, type AgentRunContext } from '../agent-context'-import {- SET_SETTINGS, SET_SETTINGS_MAX, LU_MODELS, LU_SERVICE, LU_DOWNLOAD, LU_OPEN_SETTINGS,-} from '../../lib/settings-tool-names'-import { executeSetSettings } from './settings-tools'import { useSettingsConfirmStore } from '../../stores/settingsConfirmStore'import { useSettingsAuditStore } from '../../stores/settingsAuditStore'import { useModelStore } from '../../stores/modelStore'import { useSettingsStore } from '../../stores/settingsStore'-import { useLocalApiStore } from '../../stores/localApiStore'-import { useRemoteStore } from '../../stores/remoteStore'-import { useDownloadStore } from '../../stores/downloadStore'import { useUIStore } from '../../stores/uiStore'import { backendCall, isTauri } from '../backend'-import { activateBuiltinModel, stopBundledEngine } from '../engine'-import { checkDownloadSpace, installBundleComplete, startChatLinkDownload } from '../discover'-import {- getAudioBundles, getImageBundles, getLipsyncBundles, getMotionBundles, getUpscaleBundles, getVideoBundles,- type ModelBundle,-} from '../model-bundles'import { getProviderIdFromModel } from '../providers/model-name'-import { isManagedBuiltinSlot } from '../builtin-ensure'import { checkSelfControl, noteCard, turnTextOf } from '../../lib/self-control-policy'import { taintLabel } from '../../lib/run-taint'-import { SETTINGS_AREAS, isArea, type SettingsArea } from '../../lib/settings-catalog'+import { isArea, type SettingsArea } from '../../lib/settings-catalog'import type { SettingsTab } from '../../lib/settings-reset'--// ── Schemas ──────────────────────────────────────────────────────--// Defined here, not in settings-tools.ts: this module registers it, and a-// definition imported across the settings-tools ↔ stores ↔ mcp cycle can be-// undefined at registration time when settings-tools is loaded first.-const SET_SETTINGS_TOOL: MCPToolDefinition = {- name: SET_SETTINGS,- description: `Change several LU app settings at once (up to ${SET_SETTINGS_MAX}) on one card; the user can untick each. `- + 'Use it instead of several set_setting calls.',- brief: 'Change several LU app settings on one confirmation card.',- inputSchema: {- type: 'object',- properties: {- changes: {- type: 'array',- description: 'The changes, e.g. [{"key":"temperature","value":0.6},{"key":"builtinEngine.ctx","value":16384}].',- items: {- type: 'object',- properties: {- key: { type: 'string' },- value: { type: ['string', 'number', 'boolean'] },- },- required: ['key', 'value'],- },- },- },- required: ['changes'],- },- category: 'system',- source: 'builtin',-}---const LU_MODELS_TOOL: MCPToolDefinition = {- name: LU_MODELS,- description: 'LU chat models. action list: installed chat models. status: the active one. '- + 'switch: change the chat model (name from list); it happens when this answer is done, after the user confirms.',- brief: 'List LU chat models or switch the active chat model.',- inputSchema: {- type: 'object',- properties: {- action: { type: 'string', enum: ['list', 'status', 'switch'], description: 'list, status or switch.' },- name: { type: 'string', description: 'For switch: the model name, or a unique part of it.' },- },- required: ['action'],- },- category: 'system',- source: 'builtin',-}--const LU_SERVICE_TOOL: MCPToolDefinition = {- name: LU_SERVICE,- description: 'Start, stop or restart a part of LU: comfyui, engine (LU Engine, e.g. after engine settings), '- + 'local_api (OpenAI-compatible API on this computer only), remote (phone access in the home network). '- + 'status needs no card; every other action waits for the user\'s card.',- brief: 'Start, stop or restart ComfyUI, LU Engine, the local API or the phone remote.',- inputSchema: {- type: 'object',- properties: {- service: { type: 'string', enum: ['comfyui', 'engine', 'local_api', 'remote'] },- action: { type: 'string', enum: ['status', 'start', 'stop', 'restart'] },- },- required: ['service', 'action'],- },- category: 'system',- source: 'builtin',-}--const LU_DOWNLOAD_TOOL: MCPToolDefinition = {- name: LU_DOWNLOAD,- description: 'Models from the LU catalog for Create (image, video, audio, upscale). action search: find by words. '- + 'start: download one by its id from search. status: running downloads. '- + 'start_link: a .safetensors or .gguf link to huggingface.co or civitai.com that the user pasted in their own message, into a ComfyUI model folder.',- brief: 'Search the LU model catalog and download a model, after the user confirms.',- inputSchema: {- type: 'object',- properties: {- action: { type: 'string', enum: ['search', 'start', 'status', 'start_link'] },- query: { type: 'string', description: 'For search.' },- id: { type: 'string', description: 'For start: the id search returned.' },- url: { type: 'string', description: 'For start_link: the link exactly as the user sent it.' },- folder: { type: 'string', description: 'For start_link: checkpoints, diffusion_models, unet, loras, vae, text_encoders, clip, clip_vision, upscale_models or controlnet.' },- filename: { type: 'string', description: 'For start_link: the file name, if the link does not end in it.' },- },- required: ['action'],- },- category: 'system',- source: 'builtin',-}--const LU_OPEN_SETTINGS_TOOL: MCPToolDefinition = {- name: LU_OPEN_SETTINGS,- description: 'Open LU\'s Settings at the place for an area, so the user can change what only they may change '- + '(keys, permissions looser, remote, paths, MCP). Changes nothing.',- brief: 'Open LU Settings at a given area for the user.',- inputSchema: {- type: 'object',- properties: {- area: { type: 'string', description: `An area (${Object.keys(SETTINGS_AREAS).join(', ')}) or one of keys, remote, local_api, mcp, comfyui, models.` },- },- required: ['area'],- },- category: 'system',- source: 'builtin',-}--export const SELF_CONTROL_TOOLS: MCPToolDefinition[] = [SET_SETTINGS_TOOL, LU_MODELS_TOOL, LU_SERVICE_TOOL, LU_DOWNLOAD_TOOL, LU_OPEN_SETTINGS_TOOL]--// ── Shared ───────────────────────────────────────────────────────--/** The line an action puts under its answer, for the card that stays. */-const ACTION_MARK = /<!-- lu-action (\{.*?\}) -->/--export interface SelfControlAction {- kind: 'model' | 'service' | 'download'- title: string- /** For a model switch: the model before and after, for Undo. */- from?: string | null- to?: string | null-}--export function parseSelfControlAction(result: string | null | undefined): SelfControlAction | null {- const m = typeof result === 'string' ? ACTION_MARK.exec(result) : null- if (!m) return null- try {- const v = JSON.parse(m[1]) as Partial<SelfControlAction>- return typeof v.kind === 'string' && typeof v.title === 'string' ? (v as SelfControlAction) : null- } catch {- return null+import type { ModelBundle } from '../model-bundles'++/**+ * The heavy parts load on first use, not with the tool registry: the engine,+ * the downloader and the bundle catalog pull half the app (and code that runs+ * at import time) into every module that only registers these tools.+ */+async function deps() {+ const [localApi, remote, downloads, engine, discover, bundles, ensure] = await Promise.all([+ import('../../stores/localApiStore'), import('../../stores/remoteStore'), import('../../stores/downloadStore'),+ import('../engine'), import('../discover'), import('../model-bundles'), import('../builtin-ensure'),+ ])+ return {+ useLocalApiStore: localApi.useLocalApiStore, useRemoteStore: remote.useRemoteStore, useDownloadStore: downloads.useDownloadStore,+ activateBuiltinModel: engine.activateBuiltinModel, stopBundledEngine: engine.stopBundledEngine,+ checkDownloadSpace: discover.checkDownloadSpace, installBundleComplete: discover.installBundleComplete,+ startChatLinkDownload: discover.startChatLinkDownload, bundles, isManagedBuiltinSlot: ensure.isManagedBuiltinSlot,}}-const markOf = (a: SelfControlAction) => `<!-- lu-action ${JSON.stringify(a)} -->`+// The schemas, the result mark and the registration live in+// self-control-defs.ts, which imports nothing heavy; this module is loaded on+// the first call.+import { markOf } from './self-control-mark'+export { parseSelfControlAction, type SelfControlAction } from './self-control-mark'const lower = (s: unknown) => String(s ?? '').toLowerCase()const has = (text: string, words: readonly string[]) => { const t = lower(text); return words.some((w) => t.includes(w)) }@@ -232,14 +108,14 @@ export async function executeLuModels(args: ToolArgs, run?: AgentRunContext, sigconst active = useModelStore.getState().activeModelif (action === 'list') {const list = chatModels()- if (list.length === 0) return 'No chat model is installed or listed yet.'+ if (list.length === 0) return 'No chat model is installed or listed.'const shown = list.slice(0, 30).map((m) => `${m.name === active ? '* ' : ' '}${m.name}`)return [`Chat models (* = active), ${list.length}:`, ...shown, ...(list.length > 30 ? [`(+${list.length - 30} more)`] : [])].join('\n')}if (action === 'status') {if (!active) return 'No chat model is selected.'const provider = getProviderIdFromModel(active)- const engine = provider === 'openai' && isManagedBuiltinSlot() ? 'LU Engine' : String(provider)+ const engine = provider === 'openai' && (await deps()).isManagedBuiltinSlot() ? 'LU Engine' : String(provider)return `Active chat model: ${active} (${engine}).`}if (action !== 'switch') return 'Error: action is list, status or switch.'@@ -270,10 +146,6 @@ export async function executeLuModels(args: ToolArgs, run?: AgentRunContext, sig+ `The user can undo it on the card.\n${markOf({ kind: 'model', title, from: active, to: target })}`}-/** Undo of a model switch from the card. */-export function undoModelSwitch(a: SelfControlAction): void {- if (a.kind === 'model' && a.from) useModelStore.getState().setActiveModel(a.from)-}// ── lu_service ───────────────────────────────────────────────────@@ -287,12 +159,13 @@ async function comfyRunning(): Promise<boolean | null> {try { return !!(await backendCall<{ running?: boolean }>('comfyui_status'))?.running } catch { return null }}-function luEngineActive(): boolean {+async function luEngineActive(): Promise<boolean> {const active = useModelStore.getState().activeModel- return !!active && getProviderIdFromModel(active) === 'openai' && isManagedBuiltinSlot()+ return !!active && getProviderIdFromModel(active) === 'openai' && (await deps()).isManagedBuiltinSlot()}export async function executeLuService(args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal): Promise<string> {+ const { useLocalApiStore, useRemoteStore, activateBuiltinModel, stopBundledEngine } = await deps()const service = lower(args?.service)const action = lower(args?.action)if (!['comfyui', 'engine', 'local_api', 'remote'].includes(service)) return 'Error: service is comfyui, engine, local_api or remote.'@@ -300,7 +173,7 @@ export async function executeLuService(args: ToolArgs, run?: AgentRunContext, siif (action === 'status') {if (service === 'comfyui') { const r = await comfyRunning(); return r === null ? 'ComfyUI: unknown here.' : `ComfyUI is ${r ? 'running' : 'stopped'}.` }- if (service === 'engine') return luEngineActive() ? `LU Engine serves the chat model ${useModelStore.getState().activeModel}.` : 'LU Engine does not serve the active chat model.'+ if (service === 'engine') return await luEngineActive() ? `LU Engine serves the chat model ${useModelStore.getState().activeModel}.` : 'LU Engine does not serve the active chat model.'if (service === 'local_api') { const s = useLocalApiStore.getState(); return `Local API is ${s.laeuft ? 'running' : 'stopped'}${s.lan ? ', LAN access is on' : ', this computer only'}.` }const r = useRemoteStore.getState()return `Phone remote is ${r.enabled ? 'on' : 'off'}${r.tunnelActive ? ', reachable from the internet' : ''}.`@@ -326,7 +199,7 @@ export async function executeLuService(args: ToolArgs, run?: AgentRunContext, si}if (service === 'engine') {- if (!luEngineActive()) return 'LU Engine does not serve the active chat model, so there is nothing to restart. Nothing changed.'+ if (!await luEngineActive()) return 'LU Engine does not serve the active chat model, so there is nothing to restart. Nothing changed.'if (action === 'start') return 'LU Engine starts by itself with the next message. Nothing changed.'const model = useModelStore.getState().activeModel as stringconst title = action === 'stop' ? 'Stop LU Engine' : 'Restart LU Engine with the current engine settings'@@ -364,7 +237,7 @@ export async function executeLuService(args: ToolArgs, run?: AgentRunContext, sireturn 'Refused: the local API is set to answer the network (LAN). With that on, only the user starts it, in Settings → Voice & Remote → Local API. Nothing changed. Tell the user so.'}if (!s.token) {- return 'Refused: the local API has no access token yet. The user creates one in Settings → Voice & Remote → Local API (lu_open_settings area local_api). Nothing changed.'+ return 'Refused: the local API has no access token. The user creates one in Settings → Voice & Remote → Local API (lu_open_settings area local_api). Nothing changed.'}const title = action === 'restart' ? 'Restart the local API' : 'Start the local API'const refused = await confirmAction(run, signal, {@@ -426,7 +299,8 @@ export async function executeLuService(args: ToolArgs, run?: AgentRunContext, siconst DOWNLOAD_WORDS = ['download', 'herunterlad', 'runterlad', 'herunter', 'install', 'hol ', 'besorg', 'get ']const LINK_FOLDERS = ['checkpoints', 'diffusion_models', 'unet', 'loras', 'vae', 'text_encoders', 'clip', 'clip_vision', 'upscale_models', 'controlnet']-function catalog(): { kind: string; b: ModelBundle }[] {+async function catalog(): Promise<{ kind: string; b: ModelBundle }[]> {+ const { getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, getUpscaleBundles } = (await deps()).bundlesconst out: { kind: string; b: ModelBundle }[] = []const add = (kind: string, list: ModelBundle[]) => { for (const b of list) out.push({ kind, b }) }add('image', getImageBundles()); add('video', getVideoBundles()); add('audio', getAudioBundles())@@ -434,9 +308,9 @@ function catalog(): { kind: string; b: ModelBundle }[] {return out}-function findBundle(id: string): { kind: string; b: ModelBundle }[] {+async function findBundle(id: string): Promise<{ kind: string; b: ModelBundle }[]> {const want = id.trim().toLowerCase()- const all = catalog()+ const all = await catalog()const exact = all.filter((x) => x.b.name.toLowerCase() === want)return exact.length ? exact : all.filter((x) => x.b.name.toLowerCase().includes(want))}@@ -449,10 +323,11 @@ function fileNameOfLink(url: string): string {}export async function executeLuDownload(args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal): Promise<string> {+ const { useDownloadStore, checkDownloadSpace, installBundleComplete, startChatLinkDownload } = await deps()const action = lower(args?.action)if (action === 'search') {const words = lower(args?.query).split(/[^a-z0-9.äöüß]+/).filter((w) => w.length >= 2)- const hits = catalog().filter(({ b }) => {+ const hits = (await catalog()).filter(({ b }) => {const hay = `${b.name} ${b.tags.join(' ')} ${b.description}`.toLowerCase()return words.length === 0 || words.every((w) => hay.includes(w))}).slice(0, 10)@@ -472,7 +347,7 @@ export async function executeLuDownload(args: ToolArgs, run?: AgentRunContext, sif (action === 'start') {const id = String(args?.id ?? '').trim()if (!id) return 'Error: id is missing. Call lu_download with action search first.'- const hits = findBundle(id)+ const hits = await findBundle(id)if (hits.length !== 1) {return hits.length === 0 ? `Error: no catalog entry "${id}". Call lu_download search. Nothing changed.`: `Error: "${id}" matches ${hits.length}: ${hits.slice(0, 5).map((h) => h.b.name).join(', ')}. Say which. Nothing changed.`@@ -550,6 +425,7 @@ const OPEN_AT: Record<string, SettingsTab> = {export async function executeLuOpenSettings(args: ToolArgs): Promise<string> {const area = lower(args?.area).trim().replace(/[\s-]+/g, '_')+ if (!area) return 'Error: area is missing, e.g. keys, permissions, remote, local_api, mcp, comfyui. Nothing opened.'const tab: SettingsTab = OPEN_AT[area] ?? (isArea(area) ? tabOfArea(area) : 'general')useUIStore.getState().openSettingsAt(area === 'comfyui' ? { tab, section: 'comfyui' } : { tab })return `Opened Settings → ${tab}. Nothing changed; the user changes it there.`@@ -562,12 +438,3 @@ function tabOfArea(a: SettingsArea): SettingsTab {return 'general'}-// ── Registration ─────────────────────────────────────────────────--export function registerSelfControlTools(registry: ToolRegistry): void {- registry.registerBuiltin(SET_SETTINGS_TOOL, (a, run, signal) => executeSetSettings(a, run, signal))- registry.registerBuiltin(LU_MODELS_TOOL, (a, run, signal) => executeLuModels(a, run, signal))- registry.registerBuiltin(LU_SERVICE_TOOL, (a, run, signal) => executeLuService(a, run, signal))- registry.registerBuiltin(LU_DOWNLOAD_TOOL, (a, run, signal) => executeLuDownload(a, run, signal))- registry.registerBuiltin(LU_OPEN_SETTINGS_TOOL, (a) => executeLuOpenSettings(a))-}diff --git a/src/api/mcp/settings-tools.ts b/src/api/mcp/settings-tools.tsindex 48d31f3f..e1092859 100644--- a/src/api/mcp/settings-tools.ts+++ b/src/api/mcp/settings-tools.ts@@ -22,15 +22,18 @@ import {} from '../../lib/settings-tool-names'import { useSettingsConfirmStore, type SettingChangeItem } from '../../stores/settingsConfirmStore'import { useSettingsAuditStore } from '../../stores/settingsAuditStore'-import { useModelStore } from '../../stores/modelStore'import {CATALOG, LOCK_RULES, SETTINGS_AREAS, areaOf, findEntry, isArea, isHiddenKey, lockedRule, normKey,sameValue, similarKeys, tabName, textNames, type CatalogEntry, type SettingsArea,} from '../../lib/settings-catalog'-import {- describeEntryNow, entryState, normalizeForStore, prepareEntry, readEntry, refuseValue, writeEntry,-} from '../../lib/settings-stores'-import { checkSelfControl, noteCard } from '../../lib/self-control-policy'+// The stores behind the catalog (Voice, Create, Memory …) load on first use:+// this module is imported by the tool registry, and those stores pull half the+// app, with code that runs at import time, into every module that only+// registers the tools (found by phone-file-results.test.ts).+const stores = () => import('../../lib/settings-stores')+// Same for the policy: it reads the chat store.+const policy = () => import('../../lib/self-control-policy')+type Stores = Awaited<ReturnType<typeof stores>>import { taintLabel } from '../../lib/run-taint'export { GET_SETTINGS, SET_SETTING, SET_SETTINGS, SET_SETTINGS_MAX, SETTINGS_TOOL_NAMES, isSettingsToolName, SETTINGS_PROMPT_LINE }@@ -85,20 +88,21 @@ function lockedReply(key: string): string | null {return `Refused: ${rule.what} is locked. Nothing changed. Only the user can change it, in ${rule.where}. Tell the user so.`}-function listed(entries: readonly CatalogEntry[], head: string): string {- const shown = entries.slice(0, GET_SETTINGS_MAX).map(describeEntryNow)+function listed(st: Stores, entries: readonly CatalogEntry[], head: string): string {+ const shown = entries.slice(0, GET_SETTINGS_MAX).map(st.describeEntryNow)const more = entries.length - shown.lengthreturn [head, ...shown, ...(more > 0 ? [`(+${more} more: narrow with query)`] : [])].join('\n')}export async function executeGetSettings(args: ToolArgs): Promise<string> {+ const st = await stores()const query = typeof args?.query === 'string' ? args.query.trim() : ''const areaArg = typeof args?.area === 'string' ? args.area.trim().toLowerCase() : ''const qArea = query.toLowerCase()const area: SettingsArea | null = isArea(areaArg) ? areaArg : isArea(qArea) ? qArea : nullif (area) {const inArea = CATALOG.filter((c) => areaOf(c) === area)- return listed(inArea, `LU settings, ${SETTINGS_AREAS[area].label} (key = value | allowed | what):`)+ return listed(st, inArea, `LU settings, ${SETTINGS_AREAS[area].label} (key = value | allowed | what):`)}if (!query) {// The map, not the territory: seventy lines would fill a small model's@@ -108,14 +112,14 @@ export async function executeGetSettings(args: ToolArgs): Promise<string> {return ['LU settings by area. Call get_settings with area or query for the keys:', ...counts, LOCKED_LINE].join('\n')}const exact = findEntry(query)- if (exact) return describeEntryNow(exact)+ if (exact) return st.describeEntryNow(exact)const q = normKey(query)const words = query.toLowerCase().split(/[^a-z0-9äöüß]+/).filter((w) => w.length >= 3)const hits = CATALOG.filter((c) => {const hay = `${c.key} ${c.label} ${c.help} ${(c.synonyms ?? []).join(' ')}`.toLowerCase()return (q.length >= 3 && normKey(hay).includes(q)) || words.some((w) => hay.includes(w))})- if (hits.length) return listed(hits, `LU settings matching "${query}":`)+ if (hits.length) return listed(st, hits, `LU settings matching "${query}":`)const locked = lockedReply(query)if (locked) return lockedreturn `No setting matches "${query}". Call get_settings with an area: ${AREA_NAMES}.`@@ -162,7 +166,7 @@ type Checked =/** Everything short of the card: known, not locked, a valid value, the safe* direction, a real change. */-async function checkOne(keyRaw: unknown, valueRaw: unknown): Promise<Checked> {+async function checkOne(st: Stores, keyRaw: unknown, valueRaw: unknown): Promise<Checked> {const key = typeof keyRaw === 'string' ? keyRaw.trim() : ''if (!key) return { ok: false, reply: 'Error: key is missing. Call get_settings for the keys. Nothing changed.' }const entry = findEntry(key)@@ -172,15 +176,15 @@ async function checkOne(keyRaw: unknown, valueRaw: unknown): Promise<Checked> {const near = isHiddenKey(key) ? [] : similarKeys(key)return { ok: false, reply: `Error: there is no setting "${key}". ${near.length ? `Closest: ${near.join(', ')}. ` : ''}Call get_settings. Nothing changed.` }}- await prepareEntry(entry)+ await st.prepareEntry(entry)const parsed = entry.parse(valueRaw)if (!parsed.ok) {return { ok: false, reply: `Error: ${entry.label} (${entry.key}) ${parsed.error}. Allowed: ${entry.allowed}. Nothing changed.` }}- const refused = refuseValue(entry, parsed.value)+ const refused = st.refuseValue(entry, parsed.value)if (refused) return { ok: false, reply: `Error: ${entry.label} ${String(parsed.value)}: ${refused}. Nothing changed.` }- const value = normalizeForStore(entry, parsed.value)- const before = readEntry(entry)+ const value = st.normalizeForStore(entry, parsed.value)+ const before = st.readEntry(entry)if (entry.safe && !entry.safe(value, before)) {return { ok: false, reply: `Refused: from the chat ${entry.label} can only be set to ${entry.allowed}. ${entry.safeWhy}. Nothing changed. The user can change it in ${tabName(entry.tab)}.` }}@@ -188,13 +192,13 @@ async function checkOne(keyRaw: unknown, valueRaw: unknown): Promise<Checked> {return { ok: true, entry, before, value, item: { key: entry.key, label: entry.label, from: entry.show(before), to: entry.show(value), note: noteFor(entry) } }}-function audit(run: AgentRunContext | undefined, row: {+function audit(run: AgentRunContext | undefined, model: string | null, row: {key: string; label: string; from: string; to: string; outcome: 'applied' | 'declined' | 'timeout' | 'refused' | 'failed';rawFrom?: unknown; rawTo?: unknown; why?: string; tainted?: string}): void {useSettingsAuditStore.getState().record({conversationId: run?.conversationId ?? null,- model: useModelStore.getState().activeModel ?? null,+ model,kind: 'setting',...row,})@@ -203,15 +207,19 @@ function audit(run: AgentRunContext | undefined, row: {const namesOf = (entry: CatalogEntry) => (text: string, strict: boolean) => textNames(entry, text, strict)export async function executeSetSetting(args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal): Promise<string> {+ if (typeof args?.key !== 'string' || !args.key.trim()) return 'Error: key is missing. Call get_settings for the keys. Nothing changed.'if (!run?.settingsCard) {return 'Error: settings can only be changed in a chat where the user sees the confirmation card. Nothing changed.'}- const c = await checkOne(args?.key, args?.value)+ const st = await stores()+ const { checkSelfControl, noteCard } = await policy()+ const model = st.activeModelName()+ const c = await checkOne(st, args?.key, args?.value)if (!c.ok) return c.replyconst { entry, before, value, item } = cconst verdict = checkSelfControl(run, { names: namesOf(entry), strong: entry.risk === 'strong', what: entry.label })if (!verdict.ok) {- audit(run, { ...item, outcome: 'refused', why: verdict.why })+ audit(run, model, { ...item, outcome: 'refused', why: verdict.why })return verdict.reply}noteCard(run)@@ -228,24 +236,24 @@ export async function executeSetSetting(args: ToolArgs, run?: AgentRunContext, staintedBy: verdict.taintedBy,}, signal ?? run.abortSignal)if (!answer.allow) {- audit(run, { ...item, outcome: answer.reason === 'timeout' ? 'timeout' : 'declined', tainted: verdict.taintedBy })+ audit(run, model, { ...item, outcome: answer.reason === 'timeout' ? 'timeout' : 'declined', tainted: verdict.taintedBy })return answer.reason === 'timeout'? `No answer on the card for 10 minutes, so no. ${entry.label} stays ${item.from}. Do not ask again unless the user asks.`: `The user declined. ${entry.label} stays ${item.from}. Do not ask again unless the user asks.`}// The value may have moved while the card was open (by hand, another chat).- const now = readEntry(entry)+ const now = st.readEntry(entry)if (!sameValue(now, before)) {- audit(run, { ...item, outcome: 'refused', why: 'moved' })+ audit(run, model, { ...item, outcome: 'refused', why: 'moved' })return `${entry.label} changed to ${entry.show(now)} while the card was open. Nothing applied. Ask the user again if it is still wanted.`}try {- writeEntry(entry, value)+ st.writeEntry(entry, value)} catch (e) {- audit(run, { ...item, outcome: 'failed', why: String(e) })+ audit(run, model, { ...item, outcome: 'failed', why: String(e) })return `Error: ${entry.label} could not be changed: ${String(e)}. Nothing changed.`}- audit(run, { ...item, outcome: 'applied', rawFrom: before, rawTo: value, tainted: verdict.taintedBy })+ audit(run, model, { ...item, outcome: 'applied', rawFrom: before, rawTo: value, tainted: verdict.taintedBy })return `Changed: ${entry.label} ${item.from} → ${item.to}.${item.note ? ` ${item.note}` : ''} The user can undo it on the card.\n${markOf({ key: entry.key, from: before, to: value })}`}@@ -256,15 +264,18 @@ export async function executeSetSettings(args: ToolArgs, run?: AgentRunContext,const raw = Array.isArray(args?.changes) ? (args.changes as unknown[]) : []if (raw.length === 0) return 'Error: changes is empty. Pass [{"key":…,"value":…}]. Nothing changed.'if (raw.length > SET_SETTINGS_MAX) return `Error: at most ${SET_SETTINGS_MAX} changes on one card. Nothing changed.`+ const st = await stores()+ const { checkSelfControl, noteCard } = await policy()+ const model = st.activeModelName()const lines: string[] = []const ok: Extract<Checked, { ok: true }>[] = []for (const r of raw) {const o = (r && typeof r === 'object' ? r : {}) as { key?: unknown; value?: unknown }- const c = await checkOne(o.key, o.value)+ const c = await checkOne(st, o.key, o.value)if (!c.ok) { lines.push(c.reply); continue }if (ok.some((x) => x.entry.key === c.entry.key)) { lines.push(`Error: ${c.entry.label} twice. The first one counts.`); continue }const v = checkSelfControl(run, { names: namesOf(c.entry), strong: c.entry.risk === 'strong', what: c.entry.label })- if (!v.ok) { audit(run, { ...c.item, outcome: 'refused', why: v.why }); lines.push(`${c.entry.label}: ${v.reply}`); continue }+ if (!v.ok) { audit(run, model, { ...c.item, outcome: 'refused', why: v.why }); lines.push(`${c.entry.label}: ${v.reply}`); continue }ok.push(c)}if (ok.length === 0) return lines.join('\n')@@ -281,7 +292,7 @@ export async function executeSetSettings(args: ToolArgs, run?: AgentRunContext,taintedBy,}, signal ?? run.abortSignal)if (!answer.allow) {- for (const c of ok) audit(run, { ...c.item, outcome: answer.reason === 'timeout' ? 'timeout' : 'declined', tainted: taintedBy })+ for (const c of ok) audit(run, model, { ...c.item, outcome: answer.reason === 'timeout' ? 'timeout' : 'declined', tainted: taintedBy })lines.push(answer.reason === 'timeout'? 'No answer on the card for 10 minutes, so no. Nothing changed. Do not ask again unless the user asks.': 'The user declined the card. Nothing changed. Do not ask again unless the user asks.')@@ -291,24 +302,24 @@ export async function executeSetSettings(args: ToolArgs, run?: AgentRunContext,const marks: string[] = []for (const c of ok) {if (!selected.has(c.entry.key)) {- audit(run, { ...c.item, outcome: 'declined', tainted: taintedBy })+ audit(run, model, { ...c.item, outcome: 'declined', tainted: taintedBy })lines.push(`Unticked by the user: ${c.entry.label} stays ${c.item.from}.`)continue}- const now = readEntry(c.entry)+ const now = st.readEntry(c.entry)if (!sameValue(now, c.before)) {- audit(run, { ...c.item, outcome: 'refused', why: 'moved' })+ audit(run, model, { ...c.item, outcome: 'refused', why: 'moved' })lines.push(`${c.entry.label} changed to ${c.entry.show(now)} while the card was open. Not applied.`)continue}try {- writeEntry(c.entry, c.value)+ st.writeEntry(c.entry, c.value)} catch (e) {- audit(run, { ...c.item, outcome: 'failed', why: String(e) })+ audit(run, model, { ...c.item, outcome: 'failed', why: String(e) })lines.push(`Error: ${c.entry.label} could not be changed: ${String(e)}.`)continue}- audit(run, { ...c.item, outcome: 'applied', rawFrom: c.before, rawTo: c.value, tainted: taintedBy })+ audit(run, model, { ...c.item, outcome: 'applied', rawFrom: c.before, rawTo: c.value, tainted: taintedBy })lines.push(`Changed: ${c.entry.label} ${c.item.from} → ${c.item.to}.${c.item.note ? ` ${c.item.note}` : ''}`)marks.push(markOf({ key: c.entry.key, from: c.before, to: c.value }))}@@ -316,32 +327,9 @@ export async function executeSetSettings(args: ToolArgs, run?: AgentRunContext,return lines.join('\n')}-/** Undo from the card: back to the value before, through the same catalog. */-export function undoSettingChange(change: SettingChange): boolean {- const entry = findEntry(change.key)- if (!entry) return false- writeEntry(entry, change.from)- useSettingsAuditStore.getState().record({- conversationId: null, model: null, kind: 'setting', key: entry.key, label: entry.label,- from: entry.show(change.to), to: entry.show(change.from), outcome: 'undone',- })- return true-}--/** Apply a change again (the card's "Apply again"). */-export function redoSettingChange(change: SettingChange): boolean {- const entry = findEntry(change.key)- if (!entry) return false- writeEntry(entry, change.to)- return true-}--/** Where the value stands now against the change on the card. */-export function settingChangeState(change: SettingChange): 'applied' | 'undone' | 'moved' {- const entry = findEntry(change.key)- if (!entry) return 'moved'- return entryState(entry, change.from, change.to)-}+// Undo, Apply again and the state of a change live with the stores+// (lib/settings-stores.ts: undoSettingChange, redoSettingChange,+// settingChangeState), so the card does not load this module's dependencies.export function registerSettingsTools(registry: ToolRegistry): void {registry.registerBuiltin(SETTINGS_TOOLS[0], (a) => executeGetSettings(a))diff --git a/src/components/chat/SettingChangeCard.tsx b/src/components/chat/SettingChangeCard.tsxindex cd915d2a..e0cf28b3 100644--- a/src/components/chat/SettingChangeCard.tsx+++ b/src/components/chat/SettingChangeCard.tsx@@ -1,10 +1,10 @@import { useState } from 'react'import { AlertTriangle, Check, RotateCcw, ShieldAlert, SlidersHorizontal, X, Zap } from 'lucide-react'import { useSettingsConfirmStore, type SettingChangeRequest } from '../../stores/settingsConfirmStore'-import { redoSettingChange, settingChangeState, undoSettingChange, type SettingChange } from '../../api/mcp/settings-tools'-import { undoModelSwitch, type SelfControlAction } from '../../api/mcp/self-control-tools'+import type { SettingChange } from '../../api/mcp/settings-tools'+import type { SelfControlAction } from '../../api/mcp/self-control-defs'import { findEntry } from '../../lib/settings-catalog'-import { useAnyEntryStore } from '../../lib/settings-stores'+import { redoSettingChange, settingChangeState, undoSettingChange, useAnyEntryStore } from '../../lib/settings-stores'import { useModelStore } from '../../stores/modelStore'const box = 'mt-1 mb-1.5 max-w-xl rounded-lg border border-gray-200 dark:border-white/[0.1] bg-gray-50 dark:bg-white/[0.03]'@@ -156,7 +156,7 @@ export function SelfControlDone({ action }: { action: SelfControlAction }) {<span className="t-body text-gray-900 dark:text-gray-100">{action.title}</span>{undoable && (<button type="button" data-testid="self-control-undo" className={btnNo}- onClick={(e) => { e.stopPropagation(); undoModelSwitch(action) }}>+ onClick={(e) => { e.stopPropagation(); if (action.from) useModelStore.getState().setActiveModel(action.from) }}><RotateCcw size={10} /> Back to {action.from}</button>)}diff --git a/src/components/chat/ToolCallBand.tsx b/src/components/chat/ToolCallBand.tsxindex be5d4644..73d1aa62 100644--- a/src/components/chat/ToolCallBand.tsx+++ b/src/components/chat/ToolCallBand.tsx@@ -1,6 +1,6 @@import { Fragment, useState, type ReactNode } from 'react'import { parseSettingChange } from '../../api/mcp/settings-tools'-import { parseSelfControlAction } from '../../api/mcp/self-control-tools'+import { parseSelfControlAction } from '../../api/mcp/self-control-defs'import { AnimatePresence, motion } from 'framer-motion'import { AlertCircle, Check, ChevronDown, Wrench } from 'lucide-react'import type { AgentBlock, AgentToolCall } from '../../types/agent-mode'diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 3c2e80e5..0314c465 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -16,7 +16,7 @@ import { ComputerChatPermission, useComputerChatAsk } from '../computer/Computerimport { SettingChangeAsk, SettingChangeDone, SelfControlDone } from './SettingChangeCard'import { useSettingsConfirmStore, pendingForCall } from '../../stores/settingsConfirmStore'import { parseSettingChanges } from '../../api/mcp/settings-tools'-import { parseSelfControlAction } from '../../api/mcp/self-control-tools'+import { parseSelfControlAction } from '../../api/mcp/self-control-defs'import { isSelfControlToolName } from '../../lib/settings-tool-names'import { useChatStore } from '../../stores/chatStore'import { commandIcon } from '../../lib/shell-command-classify'diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.tsindex a1eac43c..79ff2076 100644--- a/src/hooks/__tests__/codex-create-tool-gate.test.ts+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts@@ -75,7 +75,10 @@ describe('a plain coding turn does not carry the generators', () => {const after = names(gateCreateTools(codingCatalog(), 'fix the failing test in parser.ts'))// 3.0.8 (A11): neun, get_settings und set_setting fahren nur auf einer// Nachricht ueber Einstellungen mit.- expect(before.length - after.length).toBe(9)+ // 3.1.0 (C60): vierzehn, die fuenf Selbststeuerungswerkzeuge hinter+ // demselben Tor (set_settings, lu_models, lu_service, lu_download,+ // lu_open_settings).+ expect(before.length - after.length).toBe(14)expect(before.filter((n) => !after.includes(n)).sort()).toEqual([...GATE_OPENING_TOOLS].sort())})@@ -255,7 +258,9 @@ describe('a run that discovers halfway through that it needs a picture', () => {// NICHT aus GATE_KEYWORDS abgeleitet — sonst pruefte sie eine Karte gegen// sich selbst und waere fuer jeden kuenftigen Eintrag automatisch gruen.// 3.0.8 (A11): dazu die zwei Einstellungswerkzeuge.- const TOR = [...CREATE_TOOLS, 'pr_resume', 'delegate_task', 'check_tasks', 'message_agent', 'get_settings', 'set_setting']+ // 3.1.0 (C60): dazu die fuenf Selbststeuerungswerkzeuge.+ const TOR = [...CREATE_TOOLS, 'pr_resume', 'delegate_task', 'check_tasks', 'message_agent', 'get_settings', 'set_setting',+ 'set_settings', 'lu_models', 'lu_service', 'lu_download', 'lu_open_settings']for (const n of TOR) expect(isGatedTool(n), n).toBe(true)for (const n of ['file_read', 'file_edit', 'shell_execute', 'todo_write', 'web_search']) {expect(isGatedTool(n), n).toBe(false)diff --git a/src/lib/settings-stores.ts b/src/lib/settings-stores.tsindex a46fc26e..898a5202 100644--- a/src/lib/settings-stores.ts+++ b/src/lib/settings-stores.ts@@ -11,12 +11,14 @@ import { useVoiceStore } from '../stores/voiceStore'import { useCreateStore } from '../stores/createStore'import { useMemoryStore } from '../stores/memoryStore'import { usePermissionStore } from '../stores/permissionStore'+import { useModelStore } from '../stores/modelStore'+import { useSettingsAuditStore } from '../stores/settingsAuditStore'import { backendCall, isTauri } from '../api/backend'import { normalizeGpuRoles } from './gpu-roles'import type { GpuRef } from '../types/settings'import type { ToolCategory, PermissionLevel } from '../api/mcp/types'import {- patchFor, readValue, sameValue, setKnownGpuCards, storeOf, type CatalogEntry, type KnownGpuCard,+ findEntry, patchFor, readValue, sameValue, setKnownGpuCards, storeOf, type CatalogEntry, type KnownGpuCard,} from './settings-catalog'const field = (entry: CatalogEntry) => entry.key.slice(entry.key.indexOf('.') + 1)@@ -72,7 +74,7 @@ export function refuseValue(entry: CatalogEntry, value: unknown): string | nullconst hits = list.filter((m) => m.name.toLowerCase() === want || m.name.toLowerCase().includes(want))if (hits.length === 1) return nullconst names = list.slice(0, 8).map((m) => m.name).join(', ')- if (list.length === 0) return 'no model of this kind is installed (or Create has not listed them yet: open Create once)'+ if (list.length === 0) return 'no model of this kind is installed, or Create has not listed them: open Create once'return hits.length === 0 ? `not installed. Installed: ${names}` : `ambiguous, matches ${hits.length}: ${hits.slice(0, 5).map((m) => m.name).join(', ')}`}return null@@ -170,3 +172,38 @@ export function useAnyEntryStore(): number {const e = usePermissionStore((s) => s.globalPermissions)return [a, b, c, d, e].length}++/** The chat model that asks, for the log. */+export function activeModelName(): string | null {+ return useModelStore.getState().activeModel ?? null+}++/** One change as the mark under a tool result carries it (settings-tools.ts). */+export interface SettingChangeMark { key: string; from: unknown; to: unknown }++/** Undo from the card: back to the value before, through the same catalog. */+export function undoSettingChange(change: SettingChangeMark): boolean {+ const entry = findEntry(change.key)+ if (!entry) return false+ writeEntry(entry, change.from)+ useSettingsAuditStore.getState().record({+ conversationId: null, model: null, kind: 'setting', key: entry.key, label: entry.label,+ from: entry.show(change.to), to: entry.show(change.from), outcome: 'undone',+ })+ return true+}++/** Apply a change again (the card's "Apply again"). */+export function redoSettingChange(change: SettingChangeMark): boolean {+ const entry = findEntry(change.key)+ if (!entry) return false+ writeEntry(entry, change.to)+ return true+}++/** Where the value stands now against the change on the card. */+export function settingChangeState(change: SettingChangeMark): 'applied' | 'undone' | 'moved' {+ const entry = findEntry(change.key)+ if (!entry) return 'moved'+ return entryState(entry, change.from, change.to)+}diff --git a/src/lib/settings-tool-names.ts b/src/lib/settings-tool-names.tsindex 3716e335..37eb2bfd 100644--- a/src/lib/settings-tool-names.ts+++ b/src/lib/settings-tool-names.ts@@ -74,7 +74,10 @@ export function settingsGateWords(): string[] {const words = new Set<string>([...ACTION_WORDS.map((w) => w.toLowerCase()), ...catalogWords()])// Words that are everywhere in normal talk would open the gate on every// turn; they still count inside the intent check of a single setting.- for (const w of ['code', 'bild', 'image', 'video', 'size', 'such', 'search', 'wait', 'enter', 'design', 'hell', 'light', 'option', 'lade', 'load', 'starte', 'card', 'karte', 'cache', 'layer', 'block', 'allow', 'erlaub', 'merk', 'review', 'edits', 'command', 'befehl', 'agent', 'loop', 'werkzeug', 'clip', 'frames', 'batch', 'denk', 'think', 'budget', 'lokal', 'cloud', 'render', 'cpu', 'flash', 'idle', 'farbe', 'random', 'zufall', 'kreativ', 'creative', 'stell', 'install', 'record', 'confirm']) {+ for (const w of ['code', 'bild', 'image', 'video', 'size', 'such', 'search', 'wait', 'enter', 'design', 'hell', 'light', 'option', 'lade', 'load', 'starte', 'card', 'karte', 'cache', 'layer', 'block', 'allow', 'erlaub', 'merk', 'review', 'edits', 'command', 'befehl', 'agent', 'loop', 'werkzeug', 'clip', 'frames', 'batch', 'denk', 'think', 'budget', 'lokal', 'cloud', 'render', 'cpu', 'flash', 'idle', 'farbe', 'random', 'zufall', 'kreativ', 'creative', 'stell', 'install', 'record', 'confirm',+ // Talk about a search or a memory is not talk about LU's settings (the+ // phone's "Websuche: …" went to the settings tools instead of the search).+ 'websuche', 'wikipedia', 'duckduckgo', 'erinner', 'remember', 'memory', 'memories', 'gedächtnis', 'gedaechtnis']) {words.delete(w)}cachedGateWords = [...words]diff --git a/src/mobile/__tests__/pruefer-funde-r30.test.ts b/src/mobile/__tests__/pruefer-funde-r30.test.tsindex 0f350a36..0d92b4b8 100644--- a/src/mobile/__tests__/pruefer-funde-r30.test.ts+++ b/src/mobile/__tests__/pruefer-funde-r30.test.ts@@ -127,6 +127,8 @@ const ALLOWED: readonly Allowed[] = ['Three uncensored models that were missing', 'Voice is a new surface in the main navigation', 'Computer control is in beta: it is new and not proven in every app yet','Speech has a Microphone field', 'the Restart Now button closed the app on Linux', 'When Create runs on ComfyUI, Image, Edit and every video tab have a character chip', 'The Workflows view takes a workflow saved with Save or Export in ComfyUI', 'On your own machine the reference strip takes up to nine images', 'Use locally on the cloud character shelf saves a Z Image character', 'The reference strip in Edit has a Trained characters row', 'local character training has a second setting, Low VRAM', 'The Frames slider ran from 1 to 120 for every local video model', 'With a Wan 2.1 VACE model installed, Animate uses your picture', 'Import from other chatbots takes the .zip', 'Adding KoboldCpp while LM Studio or the LU Engine is on', 'Plugins has a new switch, REA', 'have a Check files button', 'KoboldCpp behind its Ollama API sends no context length', 'A size picked in the context picker is now saved for that model', 'LU estimated every text at four characters per token', 'LU counted a digit at a quarter of a token', 'Signed out, or with an account that cannot use them yet', 'The Mac parts of this release have not been clicked through'],'lib/chat-attachments.ts': ['[chat-attachments] attachment write failed'],+ // C60 (3.1.0): reached through the self-control tools (lu_service), which a phone never registers (MOBILE_UNBUILT_TOOLS).+ 'lib/local-api.ts': ['none yet'],},},{