AI-native design editor. Open-source Figma alternative.
feat(settings): configure tool access, MCP failures, and step limits
Danila Poyarkov048a8fbbc128
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 729742124..595fe09b7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,15 +2,24 @@## Unreleased+### Added++- Configure built-in AI and local MCP tool access independently on a Tool access page, including optional extended AI tools, searchable read-only and side-effect groups, and per-target defaults (#584).+- Set the built-in AI's maximum steps per message in Chat settings, with consistent stopping and remaining-step warnings (#573).+- Choose a custom number for diagnostics retention or the AI step limit instead of only the offered presets.+### Changed- Export diagnostics from Settings only. AI requests and tool activity now carry conversation and request identifiers, while chat no longer offers a separate diagnostic log or includes transcript content.### Fixed+- Explain why the local MCP server did not start — a missing `@open-pencil/mcp` install, a denied command, an early exit, a rejected local connection, or an unreachable address — with translated guidance and collapsible technical details instead of one generic health failure.+- Find a globally installed `@open-pencil/mcp` when the desktop app is launched from the system shell, by searching the common global binary directories that a graphical launch omits from `PATH`.- Mark unsaved documents and ask whether to save before closing a tab, the desktop window, or the application, rather than relying on recovery alone.- Defer AI provider connections and system credential reads until you send a message or use a connected feature, so opening documents and browsing chat history no longer trigger unexpected credential prompts.- Point Homebrew installation instructions to the official `openpencil` cask and document separate CLI installation.+- Let the desktop app use an MCP server you started yourself by allowing the app's own origin by default, instead of requiring `OPENPENCIL_MCP_CORS_ORIGIN`.- Reach the custom model option in the model picker for providers with large model catalogs instead of requiring a search for it.## 0.15.0 — 2026-09-16diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex cd94fbd9f..5ebdf198f 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -46,9 +46,109 @@ fn set_recent_files(app: tauri::AppHandle, paths: Vec<String>) -> Result<(), Strinstall_app_menu(&app, &paths).map_err(|error| error.to_string())}+/// Name of the MCP entry point installed by `@open-pencil/mcp`.+const MCP_EXECUTABLE: &str = "openpencil-mcp-http";+/// Bound on the directories reported back to the settings diagnostics.+const MAX_REPORTED_SEARCH_DIRS: usize = 12;++/// Directories that commonly hold a globally installed Node/Bun CLI.+///+/// GUI launches inherit launchd's minimal `PATH`, so a package installed by+/// npm, Bun, Volta, or Homebrew can be invisible even though the user's shell+/// finds it. `fix_path_env::fix()` reads the login shell first; these entries+/// cover managers that only modify an interactive rc file.+fn mcp_candidate_dirs() -> Vec<PathBuf> {+ let mut dirs: Vec<PathBuf> = Vec::new();+ if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {+ dirs.push(home.join(".bun/bin"));+ dirs.push(home.join(".local/bin"));+ dirs.push(home.join(".npm-global/bin"));+ dirs.push(home.join(".volta/bin"));+ dirs.push(home.join("n/bin"));+ dirs.push(home.join(".local/share/mise/shims"));+ }+ #[cfg(target_os = "macos")]+ {+ dirs.push(PathBuf::from("/opt/homebrew/bin"));+ dirs.push(PathBuf::from("/usr/local/bin"));+ dirs.push(PathBuf::from("/opt/local/bin"));+ }+ #[cfg(target_os = "linux")]+ {+ dirs.push(PathBuf::from("/usr/local/bin"));+ dirs.push(PathBuf::from("/home/linuxbrew/.linuxbrew/bin"));+ }+ #[cfg(windows)]+ {+ if let Some(appdata) = std::env::var_os("APPDATA").map(PathBuf::from) {+ dirs.push(appdata.join("npm"));+ }+ }+ dirs+}++fn push_unique_dir(dirs: &mut Vec<String>, dir: String) {+ if !dirs.contains(&dir) {+ dirs.push(dir);+ }+}++/// Existing candidate directories, most specific first, for diagnostics.+fn mcp_search_dirs() -> Vec<PathBuf> {+ mcp_candidate_dirs()+ .into_iter()+ .filter(|dir| dir.is_dir())+ .collect()+}++/// Append candidate directories that the current process `PATH` is missing.+fn augment_path(path: &str, candidates: &[PathBuf]) -> String {+ let mut entries: Vec<PathBuf> = std::env::split_paths(path).collect();+ for candidate in candidates {+ if candidate.is_dir() && !entries.contains(candidate) {+ entries.push(candidate.clone());+ }+ }+ std::env::join_paths(entries)+ .map(|joined| joined.to_string_lossy().into_owned())+ .unwrap_or_else(|_| path.to_string())+}++/// Make globally installed CLIs visible to `which` and to spawned children.+fn augment_mcp_path() {+ let current = std::env::var("PATH").unwrap_or_default();+ let next = augment_path(¤t, &mcp_candidate_dirs());+ if next != current {+ std::env::set_var("PATH", next);+ }+}++#[derive(serde::Serialize)]+#[serde(rename_all = "camelCase")]+struct McpLookup {+ available: bool,+ path: Option<String>,+ /// Existing directories that were searched, for diagnostics.+ searched: Vec<String>,+}+#[tauri::command]-fn mcp_executable_available() -> bool {- which::which("openpencil-mcp-http").is_ok()+fn mcp_lookup() -> McpLookup {+ let resolved = which::which(MCP_EXECUTABLE).ok();+ let path = resolved.as_ref().map(|p| p.display().to_string());+ let mut searched: Vec<String> = Vec::new();+ if let Some(dir) = resolved.as_ref().and_then(|p| p.parent()) {+ push_unique_dir(&mut searched, dir.display().to_string());+ }+ for dir in mcp_search_dirs() {+ push_unique_dir(&mut searched, dir.display().to_string());+ }+ searched.truncate(MAX_REPORTED_SEARCH_DIRS);+ McpLookup {+ available: resolved.is_some(),+ path,+ searched,+ }}fn file_association_path(path: PathBuf) -> Option<PathBuf> {@@ -119,6 +219,7 @@ fn startup_open_paths() -> Vec<PathBuf> {#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {let _ = fix_path_env::fix();+ augment_mcp_path();let mut builder = tauri::Builder::default();@@ -148,7 +249,7 @@ pub fn run() {credential_status,credential_store_availability,credential_write,- mcp_executable_available,+ mcp_lookup,list_system_fonts,load_system_font,proxy_http_request,@@ -202,3 +303,54 @@ pub fn run() {_ => {}});}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn augment_path_appends_missing_candidates_once() {+ let current_dir = std::env::temp_dir();+ let appended_dir = std::env::temp_dir().join("open-pencil-appended");+ std::fs::create_dir_all(&appended_dir).expect("create candidate dir");++ let current =+ std::env::join_paths([PathBuf::from("/open-pencil-first"), current_dir.clone()])+ .expect("join path list");+ let candidates = vec![current_dir.clone(), appended_dir.clone()];+ let entries: Vec<PathBuf> =+ std::env::split_paths(&augment_path(¤t.to_string_lossy(), &candidates)).collect();++ // Existing entries keep their order and the missing candidate is+ // appended once, at the end.+ assert_eq!(+ entries,+ vec![+ PathBuf::from("/open-pencil-first"),+ current_dir,+ appended_dir.clone(),+ ]+ );++ let _ = std::fs::remove_dir(&appended_dir);+ }++ #[test]+ fn augment_path_ignores_candidates_that_do_not_exist() {+ let current =+ std::env::join_paths([PathBuf::from("/open-pencil-only")]).expect("join path list");+ let augmented = augment_path(+ ¤t.to_string_lossy(),+ &[PathBuf::from("/open-pencil-nonexistent")],+ );++ assert!(!augmented.contains("nonexistent"));+ }++ #[test]+ fn augment_path_keeps_an_existing_path_when_nothing_changes() {+ let current = std::env::var("PATH").unwrap_or_default();+ let augmented = augment_path(¤t, &[]);+ assert_eq!(augmented, current);+ }+}diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.mdindex f05a44dab..a4c327bba 100644--- a/packages/docs/programmable/ai-chat.md+++ b/packages/docs/programmable/ai-chat.md@@ -18,6 +18,22 @@ You can configure multiple reusable models and separately assign models for desiThe chat composer grows with multiline prompts and can pin the current canvas selection as explicit node context. Assistant messages show provider reasoning in collapsible sections and provide a per-response copy action. Image attachments remain available for visual references when a Vision model is configured. Streaming responses use a hardened Markdown renderer with Shiki-highlighted code blocks; unsafe link protocols and embedded data images are blocked.+## Step limit++In **Settings → AI & agents → Chat**, set **Maximum steps per message** to a whole number from 1 to 1,000. The default is 50. Press Enter or leave the field to save a valid value; invalid drafts do not replace the saved preference. Higher limits allow longer tool-driven tasks but can increase latency and provider cost.++The built-in AI captures this limit when each message starts. Stopping, remaining-step warnings, and the **Continue** action use that same budget. Changing it does not interrupt an ongoing request; the next message or continuation uses the new limit. A step is one model iteration and can include multiple tool calls. ACP and Pi agents manage their own limits.++## Tool access++Open **Settings → Tool access** to choose which tools direct AI model connections can use. Search by name or description, expand read-only or side-effect groups, and toggle individual tools or an entire group. Group switches affect all tools in that group, not only search results. **Restore defaults** restores the compact default tool set; extended tools such as `create_component` can be enabled individually.++Preferences are saved locally and apply to the next message, including in an existing conversation. They do not change an already-running request. Enabling many tools increases the schemas sent to the model.++The **Local MCP** segment has independent settings for clients connected to OpenPencil's MCP server, including ACP and Pi agents. Restart the server and reconnect stdio clients after changing those settings. Remote MCP connections, WebMCP access, and Pi's shell/filesystem permissions remain separate.++Tool toggles control which tools are offered, not which operations scripts may perform. An enabled `eval` or other script-capable tool can perform design operations whose dedicated tools are disabled; these switches are not a sandbox.+## Saved ConversationsUse **Conversation history** to return to a saved chat, start a **New chat**, or rename or delete a conversation. History and attachment previews are stored locally; **All chats** lets you browse transcripts from other documents.@@ -43,13 +59,13 @@ No backend, no subscription — your key talks directly to the provider. Browser## External MCP connections-Desktop ACP agents can also use trusted remote [Model Context Protocol](https://modelcontextprotocol.io/) servers. In **Settings → MCP**, under remote connections, add a named Streamable HTTP endpoint, optionally save a bearer token, and enable the connection. OpenPencil stores the token in the configured credential backend rather than ordinary settings and resolves it only when starting the ACP session.+Desktop ACP agents can also use trusted remote [Model Context Protocol](https://modelcontextprotocol.io/) servers. In **Settings → MCP**, under MCP connections, add a named Streamable HTTP endpoint, optionally save a bearer token, and enable the connection. OpenPencil stores the token in the configured credential backend rather than ordinary settings and resolves it only when starting the ACP session.Remote servers must use HTTPS. Loopback HTTP endpoints are accepted for local development. Review and trust a server before enabling it: its tools may read external data or perform actions with the credentials you provide. OpenPencil's built-in design MCP server remains attached automatically and does not need to be added here.## What It Can Do-The assistant has 90+ tools across these categories:+The configurable tool catalog covers these categories; the tools offered to a model depend on your Tool access settings:- **Create** — frames, shapes, text, components, pages. Renders JSX for complex layouts.- **Style** — fills, strokes, effects, opacity, corner radius, blend modes.@@ -64,7 +80,7 @@ The assistant has 90+ tools across these categories:## Visual Verification-The assistant can verify its work visually. After creating or modifying designs, it uses `export_image` to capture a screenshot and checks the result against the original request. This catches layout issues, missing elements, and color mismatches that text-only responses would miss.+The assistant can verify its work visually. When `export_image` is enabled, it can capture a screenshot after creating or modifying designs and checks the result against the original request. This catches layout issues, missing elements, and color mismatches that text-only responses would miss.## Example Promptsdiff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 98ac8f390..04f3675a0 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -11,9 +11,15 @@ Two transports: **stdio** for MCP clients, and **Streamable HTTP** for browser eTool definitions own native Valibot input schemas, execution/mutation metadata, capabilities, and optional interface exposure exclusions. Tools are included by default; `exposure: { mcp: false, ai: false, webmcp: false }` can exclude them independently from each adapter. Exposure does not bypass execution support or user permissions: WebMCP still requires supported execution and explicit Off, Inspect, or Edit access. AI and MCP consume the same schema through Standard Schema; WebMCP derives its JSON Schema from that input. Numeric strings are accepted consistently across adapters, while non-finite values are rejected. Programmatic integrations use MCP SDK v2; custom tools replace the former `params`/`ParamDef` contract with `input` and execution metadata.+## Tool access settings++Use **Settings → Tool access** (select **Local MCP**) to search and toggle the local server's tools, individually or by read-only/side-effect group. Group switches affect all group members, even during search. **Restore defaults** enables the configurable MCP tools again. Existing MCP preferences are preserved separately from the **Built-in AI** settings.++Restart the MCP server, then reconnect stdio clients, to apply changes. For an externally managed server, restart its owning process. The list reflects the tools discovered from the server; disabling a dedicated tool does not prevent an enabled script tool from performing the same operation. These switches are not a sandbox and do not configure remote MCP servers or WebMCP.+## Browser-native WebMCP (experimental) {#webmcp}-WebMCP is **off by default**. Open **Settings → MCP & automation → WebMCP** and choose **Inspect** for read-only access or **Edit** to also allow scoped, undoable changes. **Off** unregisters all browser tools; changing modes revokes the previous registrations immediately. This preference is independent of local MCP authentication, tool switches, and outbound connections.+WebMCP is **off by default**. Open **Settings → MCP → WebMCP** and choose **Inspect** for read-only access or **Edit** to also allow scoped, undoable changes. **Off** unregisters all browser tools; changing modes revokes the previous registrations immediately. This preference is independent of local MCP authentication, tool switches, and outbound connections.For local testing, use a Chrome version exposing `document.modelContext`, enable `chrome://flags/#enable-webmcp-testing`, and relaunch the browser. Open a document, enable access in Settings, and connect a WebMCP-capable browser agent or the [Model Context Tool Inspector](https://developer.chrome.com/docs/ai/webmcp). Settings shows browser support and registration status. See the [Chrome WebMCP guide](https://developer.chrome.com/docs/ai/webmcp) for current availability.@@ -124,7 +130,7 @@ Security defaults:- Authentication is enabled by default with a generated token stored in the private discovery file.- `eval` is disabled.- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to the current working directory) and reject symlink escapes.-- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin.+- Only the desktop app's own origin (`tauri://localhost` and its `http(s)://tauri.localhost` variants) is allowed by default, so a server you start yourself works from the app without extra configuration. Set `OPENPENCIL_MCP_CORS_ORIGIN` to a comma-separated list to allow other origins, such as a worktree dev server.Set `PORT=0` to disable TCP on macOS and Linux. Windows requires TCP. Set `OPENPENCIL_MCP_SOCKET` to override the Unix socket path, or `OPENPENCIL_MCP_DISCOVERY_PATH` to override the discovery file location. To provide a stable token, set `OPENPENCIL_MCP_AUTH_TOKEN`; an explicitly empty value disables authentication and should only be used with a trusted local socket.diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 519154833..ee6eda3a2 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -2,6 +2,7 @@import { resolveMCPRoot } from '#mcp/root'import { startServer } from '#mcp/server'import { readToolPolicyFromEnv } from '#mcp/tool/policy'+import { resolveCORSOrigins } from '#mcp/transport/origins'if (process.argv.includes('--help') || process.argv.includes('-h')) {process.stdout.write(@@ -21,7 +22,9 @@ if (process.argv.includes('--help') || process.argv.includes('-h')) {` OPENPENCIL_MCP_ROOT Allowed directory for file-scoped tools (default: home directory on Windows, current working directory elsewhere)\n` +` OPENPENCIL_MCP_EVAL Set to 1 to enable the eval tool\n` +` OPENPENCIL_MCP_DISABLED_TOOLS Comma-separated tool names to omit\n` +- ` OPENPENCIL_MCP_CORS_ORIGIN Allowed CORS origin\n` ++ ` OPENPENCIL_MCP_CORS_ORIGIN Allowed CORS origins, comma-separated.\n` ++ ` Defaults to the desktop app origin, since the app\n` ++ ` webview is the only view that calls this server.\n` +` OPENPENCIL_MCP_APP_TIMEOUT_MS If set, close the server and remove its discovery\n` +` file after no app is attached for this many ms. The\n` +` grace period starts at startup and after disconnects.\n` +@@ -94,7 +97,7 @@ const handle = await startServer({}return trimmed})(),- corsOrigin: process.env.OPENPENCIL_MCP_CORS_ORIGIN?.trim() || null,+ corsOrigin: resolveCORSOrigins(process.env.OPENPENCIL_MCP_CORS_ORIGIN),appAttachTimeoutMs})diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex 8d5ac6407..b69215d50 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -73,7 +73,7 @@ export interface ServerOptions {mcpRoot?: string | null/** Auth token for /mcp and /rpc endpoints. Auto-generated (32-hex) when omitted. Pass null explicitly to disable auth. */authToken?: string | null- corsOrigin?: string | null+ corsOrigin?: string | readonly string[] | null/*** If set, the server starts a grace-period timer while no app is attached.* The timer closes the server and removes its discovery file unless an app@@ -109,7 +109,7 @@ export interface ServerHandle {/** Set up Hono routes: /health, /rpc, /mcp */function createHonoApp(options: {authToken: string | null- corsOrigin: string | null+ corsOrigin: string | readonly string[] | nullbrowserRPC: ReturnType<typeof createBrowserRPCBridge>mcpSessions: ReturnType<typeof createMCPSessionManager>sendToBrowser: (msg: RPCJSONObject) => Promise<unknown>diff --git a/packages/mcp/src/transport/origins.ts b/packages/mcp/src/transport/origins.tsnew file mode 100644index 000000000..a0ec21e0a--- /dev/null+++ b/packages/mcp/src/transport/origins.ts@@ -0,0 +1,29 @@+/**+ * Origins allowed to call the local server from a view.+ *+ * The desktop app's webview always calls the server from its own origin, so a+ * manually started server must allow it without extra configuration. Browsers+ * set `Origin` themselves, and only the Tauri webview serves these origins, so+ * allowing them does not expose the server to arbitrary websites. Requests still+ * need the bearer token whenever authentication is enabled.+ */+export const DESKTOP_APP_ORIGINS = [+ 'tauri://localhost',+ 'http://tauri.localhost',+ 'https://tauri.localhost'+] as const++/** Parse a comma-separated override. Returns null when nothing usable is set. */+export function parseCORSOrigins(raw: string | undefined | null): string[] | null {+ if (raw == null) return null+ const origins = raw+ .split(',')+ .map((origin) => origin.trim())+ .filter((origin) => origin.length > 0)+ return origins.length > 0 ? origins : null+}++/** Explicit configuration wins; otherwise the desktop app origin is allowed. */+export function resolveCORSOrigins(raw: string | undefined): readonly string[] {+ return parseCORSOrigins(raw) ?? DESKTOP_APP_ORIGINS+}diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex 2751dbe2f..c0af50f9f 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "Maximale Schritte pro Nachricht",+ "maxAgentStepsHint": "Nur für die integrierte KI; ACP und Pi verwalten eigene Limits. Mit Enter oder beim Verlassen des Feldes gespeichert und ab der nächsten Nachricht angewendet. Höhere Limits können die Kosten erhöhen.",+ "maxAgentStepsRange": "Gib eine ganze Zahl von {min} bis {max} ein.","connectionTestSuccess": "Verbindung erfolgreich. Das Modell ist erreichbar.","connectionTestMissingAPIKey": "Gib vor dem Testen einen API-Schlüssel ein.","connectionTestMissingBaseURL": "Gib vor dem Testen eine Basis-URL ein.",@@ -144,5 +147,6 @@"reasoningCollapsed": "Standardmäßig eingeklappt","reasoningWhileThinking": "Beim Nachdenken ausklappen","reasoningExpanded": "Standardmäßig ausgeklappt",- "jumpToLatest": "Zum neuesten Beitrag"+ "jumpToLatest": "Zum neuesten Beitrag",+ "maxAgentStepsCustom": "Eigener Wert…"}diff --git a/packages/vue/src/i18n/locales/de/automation.json b/packages/vue/src/i18n/locales/de/automation.jsonindex eb6b964b5..8874f6510 100644--- a/packages/vue/src/i18n/locales/de/automation.json+++ b/packages/vue/src/i18n/locales/de/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "Designwerkzeuge für die integrierte KI und den lokalen MCP-Server getrennt konfigurieren.",+ "toolAccessTarget": "Werkzeugzugriff konfigurieren für",+ "builtInAI": "Integrierte KI",+ "localMCP": "Lokales MCP",+ "restoreToolDefaults": "Standard wiederherstellen",+ "aiToolAccessDescription": "Werkzeuge für direkte KI-Modellverbindungen auswählen. ACP- und Pi-Agenten verwenden stattdessen den MCP-Zugriff.",+ "mcpToolAccessDescription": "Werkzeuge auswählen, die der lokale Server verbundenen Agenten und Clients anbietet.",+ "aiToolsNotice": "Änderungen gelten ab der nächsten Nachricht. Werkzeugschalter sind keine Sandbox: Aktivierte Skriptwerkzeuge können weiterhin andere Designoperationen ausführen.","addConnection": "Verbindung hinzufügen","connectionName": "Verbindungsname","connections": "MCP-Verbindungen",@@ -30,7 +38,7 @@"tools": "Verfügbare Werkzeuge","toolsEnabled": "{enabled} von {total} aktiviert","enableAllTools": "Alle aktivieren",- "searchTools": "MCP-Werkzeuge suchen",+ "searchTools": "Werkzeuge suchen","readOnlyTools": "Nur-Lese-Werkzeuge","sideEffectTools": "Werkzeuge mit Nebenwirkungen","toolsRestartNotice": "MCP-Server neu starten und anschließend stdio-Clients neu verbinden, um Werkzeugänderungen anzuwenden.",@@ -57,5 +65,24 @@"noMatchingTools": "Keine Tools entsprechen deiner Suche.","connectionNameHint": "Verwende einen eindeutigen Namen mit höchstens 80 Zeichen. Der Name open-pencil ist reserviert.","connectionNameInvalid": "Wähle einen eindeutigen Namen mit höchstens 80 Zeichen, der nicht open-pencil lautet.",- "serverURLHint": "Verwende HTTPS. HTTP ist nur für localhost oder eine Loopback-Adresse erlaubt. Die URL darf keine Zugangsdaten enthalten."+ "serverURLHint": "Verwende HTTPS. HTTP ist nur für localhost oder eine Loopback-Adresse erlaubt. Die URL darf keine Zugangsdaten enthalten.",+ "mcpFailureNotInstalled": "MCP-Automatisierung ist nicht installiert",+ "mcpFailureNotInstalledHint": "{package} global mit dem Paketmanager installieren und OpenPencil neu starten.",+ "mcpFailurePermission": "OpenPencil kann den MCP-Server nicht starten",+ "mcpFailurePermissionHint": "Das System hat den Befehl abgelehnt. OpenPencil mit den Shell-Berechtigungen neu installieren oder den Server manuell starten.",+ "mcpFailureExited": "MCP-Server wurde beim Start beendet",+ "mcpFailureExitedHint": "Der Prozess endete, bevor er bereit war.",+ "mcpFailureTimeout": "MCP-Server hat nicht rechtzeitig geantwortet",+ "mcpFailureTimeoutHint": "Er wurde nicht innerhalb des Startzeitlimits bereit.",+ "mcpFailureRejected": "MCP-Server hat die lokale Verbindung abgelehnt",+ "mcpFailureRejectedHint": "MCP-Server neu starten, um ein neues Token auszugeben.",+ "mcpFailureMalformed": "MCP-Server hat unerwartet geantwortet",+ "mcpFailureMalformedHint": "App- und Serverversion passen möglicherweise nicht zusammen. Beide aktualisieren und OpenPencil neu starten.",+ "mcpFailureUnreachable": "MCP-Server ist nicht erreichbar",+ "mcpFailureUnreachableHint": "Unter {endpoint} antwortet nichts. Adresse freigeben und den Server starten.",+ "mcpFailureUnknown": "MCP-Server konnte nicht gestartet werden",+ "mcpFailureUnknownHint": "Erneut starten oder die technischen Details unten prüfen.",+ "mcpFailureDetails": "Details",+ "mcpFailureCopy": "Details kopieren",+ "mcpFailureCopied": "Technische Details kopiert."}diff --git a/packages/vue/src/i18n/locales/de/diagnostics.json b/packages/vue/src/i18n/locales/de/diagnostics.jsonindex 97f59c590..f56eb6ad4 100644--- a/packages/vue/src/i18n/locales/de/diagnostics.json+++ b/packages/vue/src/i18n/locales/de/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "Dadurch werden lokal gespeicherte Diagnosedaten von diesem Gerät entfernt.","cleared": "Diagnosedaten gelöscht.","copied": "Diagnosedaten in die Zwischenablage kopiert.",- "copyFailed": "Diagnosedaten konnten nicht in die Zwischenablage kopiert werden."+ "copyFailed": "Diagnosedaten konnten nicht in die Zwischenablage kopiert werden.",+ "retentionCustom": "Eigener Wert…",+ "retentionRange": "Gib eine ganze Zahl von {min} bis {max} ein."}diff --git a/packages/vue/src/i18n/locales/de/settings.json b/packages/vue/src/i18n/locales/de/settings.jsonindex e3e917f90..8171db742 100644--- a/packages/vue/src/i18n/locales/de/settings.json+++ b/packages/vue/src/i18n/locales/de/settings.json@@ -19,7 +19,8 @@"usage": "Nutzung","diagnostics": "Diagnose","media": "Medien",- "automation": "MCP & Automatisierung",+ "mcp": "MCP",+ "toolAccess": "Werkzeugzugriff","storage": "Cloud-Speicher","animations": "Animationen","animationsSystem": "Systemeinstellung",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 1fe1d61ed..016186e8b 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "Máximo de pasos por mensaje",+ "maxAgentStepsHint": "Solo para la IA integrada; ACP y Pi controlan sus propios límites. Se guarda al pulsar Enter o salir del campo y se aplica al siguiente mensaje. Un límite mayor puede aumentar el coste.",+ "maxAgentStepsRange": "Introduce un número entero entre {min} y {max}.","connectionTestSuccess": "Conexión correcta. Se puede acceder al modelo.","connectionTestMissingAPIKey": "Introduce una clave API antes de probar.","connectionTestMissingBaseURL": "Introduce una URL base antes de probar.",@@ -144,5 +147,6 @@"reasoningCollapsed": "Contraído por defecto","reasoningWhileThinking": "Expandir al razonar","reasoningExpanded": "Expandido por defecto",- "jumpToLatest": "Ir al último mensaje"+ "jumpToLatest": "Ir al último mensaje",+ "maxAgentStepsCustom": "Personalizado…"}diff --git a/packages/vue/src/i18n/locales/es/automation.json b/packages/vue/src/i18n/locales/es/automation.jsonindex a61a6836e..e092645e8 100644--- a/packages/vue/src/i18n/locales/es/automation.json+++ b/packages/vue/src/i18n/locales/es/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "Configura las herramientas de diseño por separado para la IA integrada y el servidor MCP local.",+ "toolAccessTarget": "Configurar el acceso a herramientas para",+ "builtInAI": "IA integrada",+ "localMCP": "MCP local",+ "restoreToolDefaults": "Restaurar valores predeterminados",+ "aiToolAccessDescription": "Elige herramientas para conexiones directas a modelos de IA. Los agentes ACP y Pi utilizan el acceso MCP.",+ "mcpToolAccessDescription": "Elige las herramientas que el servidor local ofrece a los agentes y clientes conectados.",+ "aiToolsNotice": "Los cambios se aplican al siguiente mensaje. Los interruptores no aíslan la ejecución: las herramientas de scripts habilitadas pueden realizar otras operaciones de diseño.","addConnection": "Añadir conexión","connectionName": "Nombre de la conexión","connections": "Conexiones MCP",@@ -30,7 +38,7 @@"tools": "Herramientas disponibles","toolsEnabled": "{enabled} de {total} activadas","enableAllTools": "Activar todas",- "searchTools": "Buscar herramientas MCP",+ "searchTools": "Buscar herramientas","readOnlyTools": "Herramientas de solo lectura","sideEffectTools": "Herramientas con efectos secundarios","toolsRestartNotice": "Reinicia el servidor MCP y vuelve a conectar los clientes stdio para aplicar los cambios.",@@ -57,5 +65,24 @@"noMatchingTools": "Ninguna herramienta coincide con tu búsqueda.","connectionNameHint": "Usa un nombre único de hasta 80 caracteres. El nombre open-pencil está reservado.","connectionNameInvalid": "Elige un nombre único de hasta 80 caracteres que no sea open-pencil.",- "serverURLHint": "Usa HTTPS. HTTP solo se permite para localhost o una dirección de bucle local. No incluyas credenciales en la URL."+ "serverURLHint": "Usa HTTPS. HTTP solo se permite para localhost o una dirección de bucle local. No incluyas credenciales en la URL.",+ "mcpFailureNotInstalled": "La automatización MCP no está instalada",+ "mcpFailureNotInstalledHint": "Instala {package} globalmente con tu gestor de paquetes y reinicia OpenPencil.",+ "mcpFailurePermission": "OpenPencil no puede iniciar el servidor MCP",+ "mcpFailurePermissionHint": "El sistema denegó el comando. Reinstala OpenPencil con sus permisos de shell o inicia el servidor manualmente.",+ "mcpFailureExited": "El servidor MCP se detuvo durante el inicio",+ "mcpFailureExitedHint": "El proceso terminó antes de estar listo.",+ "mcpFailureTimeout": "El servidor MCP no respondió a tiempo",+ "mcpFailureTimeoutHint": "No quedó listo dentro del tiempo de inicio.",+ "mcpFailureRejected": "El servidor MCP rechazó la conexión local",+ "mcpFailureRejectedHint": "Reinicia el servidor MCP para emitir un token nuevo.",+ "mcpFailureMalformed": "El servidor MCP devolvió una respuesta inesperada",+ "mcpFailureMalformedHint": "Es posible que las versiones de la app y del servidor no coincidan. Actualiza ambas y reinicia OpenPencil.",+ "mcpFailureUnreachable": "El servidor MCP no es accesible",+ "mcpFailureUnreachableHint": "Nada escucha en {endpoint}. Libera la dirección e inicia el servidor.",+ "mcpFailureUnknown": "No se pudo iniciar el servidor MCP",+ "mcpFailureUnknownHint": "Vuelve a iniciarlo o revisa los detalles técnicos de abajo.",+ "mcpFailureDetails": "Detalles",+ "mcpFailureCopy": "Copiar detalles",+ "mcpFailureCopied": "Detalles técnicos copiados."}diff --git a/packages/vue/src/i18n/locales/es/diagnostics.json b/packages/vue/src/i18n/locales/es/diagnostics.jsonindex 45dea9035..64506dc24 100644--- a/packages/vue/src/i18n/locales/es/diagnostics.json+++ b/packages/vue/src/i18n/locales/es/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "Esto elimina del dispositivo los eventos de diagnóstico almacenados localmente.","cleared": "Diagnóstico borrado.","copied": "Diagnóstico copiado al portapapeles.",- "copyFailed": "No se pudo copiar el diagnóstico al portapapeles."+ "copyFailed": "No se pudo copiar el diagnóstico al portapapeles.",+ "retentionCustom": "Personalizado…",+ "retentionRange": "Introduce un número entero entre {min} y {max}."}diff --git a/packages/vue/src/i18n/locales/es/settings.json b/packages/vue/src/i18n/locales/es/settings.jsonindex 3ff3d5272..50eb87858 100644--- a/packages/vue/src/i18n/locales/es/settings.json+++ b/packages/vue/src/i18n/locales/es/settings.json@@ -19,7 +19,8 @@"usage": "Uso","diagnostics": "Diagnóstico","media": "Multimedia",- "automation": "MCP y automatización",+ "mcp": "MCP",+ "toolAccess": "Acceso a herramientas","storage": "Almacenamiento en la nube","animations": "Animaciones","animationsSystem": "Seguir al sistema",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 4aadac145..77fe36076 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "Nombre maximal d’étapes par message",+ "maxAgentStepsHint": "Pour l’IA intégrée uniquement ; ACP et Pi gèrent leurs propres limites. Enregistré avec Entrée ou en quittant le champ, puis appliqué au prochain message. Une limite élevée peut augmenter le coût.",+ "maxAgentStepsRange": "Saisissez un nombre entier entre {min} et {max}.","connectionTestSuccess": "Connexion réussie. Le modèle est accessible.","connectionTestMissingAPIKey": "Saisissez une clé API avant le test.","connectionTestMissingBaseURL": "Saisissez une URL de base avant le test.",@@ -144,5 +147,6 @@"reasoningCollapsed": "Replié par défaut","reasoningWhileThinking": "Déplier pendant le raisonnement","reasoningExpanded": "Déplié par défaut",- "jumpToLatest": "Aller au dernier message"+ "jumpToLatest": "Aller au dernier message",+ "maxAgentStepsCustom": "Personnalisé…"}diff --git a/packages/vue/src/i18n/locales/fr/automation.json b/packages/vue/src/i18n/locales/fr/automation.jsonindex 70bb86dd0..35a5294ec 100644--- a/packages/vue/src/i18n/locales/fr/automation.json+++ b/packages/vue/src/i18n/locales/fr/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "Configurez séparément les outils de conception pour l’IA intégrée et le serveur MCP local.",+ "toolAccessTarget": "Configurer l’accès aux outils pour",+ "builtInAI": "IA intégrée",+ "localMCP": "MCP local",+ "restoreToolDefaults": "Rétablir les valeurs par défaut",+ "aiToolAccessDescription": "Choisissez les outils pour les connexions directes aux modèles d’IA. Les agents ACP et Pi utilisent l’accès MCP.",+ "mcpToolAccessDescription": "Choisissez les outils que le serveur local propose aux agents et clients connectés.",+ "aiToolsNotice": "Les modifications s’appliquent au prochain message. Les interrupteurs ne constituent pas un bac à sable : les outils de script activés peuvent effectuer d’autres opérations de conception.","addConnection": "Ajouter une connexion","connectionName": "Nom de la connexion","connections": "Connexions MCP",@@ -30,7 +38,7 @@"tools": "Outils disponibles","toolsEnabled": "{enabled} sur {total} activés","enableAllTools": "Tout activer",- "searchTools": "Rechercher des outils MCP",+ "searchTools": "Rechercher des outils","readOnlyTools": "Outils en lecture seule","sideEffectTools": "Outils avec effets secondaires","toolsRestartNotice": "Redémarrez le serveur MCP, puis reconnectez les clients stdio pour appliquer les modifications.",@@ -57,5 +65,24 @@"noMatchingTools": "Aucun outil ne correspond à votre recherche.","connectionNameHint": "Utilisez un nom unique de 80 caractères maximum. Le nom open-pencil est réservé.","connectionNameInvalid": "Choisissez un nom unique de 80 caractères maximum, différent de open-pencil.",- "serverURLHint": "Utilisez HTTPS. HTTP n’est autorisé que pour localhost ou une adresse de bouclage. N’incluez pas d’identifiants dans l’URL."+ "serverURLHint": "Utilisez HTTPS. HTTP n’est autorisé que pour localhost ou une adresse de bouclage. N’incluez pas d’identifiants dans l’URL.",+ "mcpFailureNotInstalled": "L’automatisation MCP n’est pas installée",+ "mcpFailureNotInstalledHint": "Installez {package} globalement avec votre gestionnaire de paquets, puis redémarrez OpenPencil.",+ "mcpFailurePermission": "OpenPencil ne peut pas démarrer le serveur MCP",+ "mcpFailurePermissionHint": "Le système a refusé la commande. Réinstallez OpenPencil avec ses permissions de shell ou démarrez le serveur manuellement.",+ "mcpFailureExited": "Le serveur MCP s’est arrêté au démarrage",+ "mcpFailureExitedHint": "Le processus s’est terminé avant d’être prêt.",+ "mcpFailureTimeout": "Le serveur MCP n’a pas répondu à temps",+ "mcpFailureTimeoutHint": "Il n’était pas prêt dans le délai de démarrage.",+ "mcpFailureRejected": "Le serveur MCP a refusé la connexion locale",+ "mcpFailureRejectedHint": "Redémarrez le serveur MCP pour émettre un nouveau jeton.",+ "mcpFailureMalformed": "Le serveur MCP a renvoyé une réponse inattendue",+ "mcpFailureMalformedHint": "Les versions de l’application et du serveur peuvent différer. Mettez à jour les deux et redémarrez OpenPencil.",+ "mcpFailureUnreachable": "Le serveur MCP est injoignable",+ "mcpFailureUnreachableHint": "Rien n’écoute sur {endpoint}. Libérez l’adresse puis démarrez le serveur.",+ "mcpFailureUnknown": "Le serveur MCP n’a pas pu démarrer",+ "mcpFailureUnknownHint": "Relancez-le ou consultez les détails techniques ci-dessous.",+ "mcpFailureDetails": "Détails",+ "mcpFailureCopy": "Copier les détails",+ "mcpFailureCopied": "Détails techniques copiés."}diff --git a/packages/vue/src/i18n/locales/fr/diagnostics.json b/packages/vue/src/i18n/locales/fr/diagnostics.jsonindex 258afbd6a..182edfb84 100644--- a/packages/vue/src/i18n/locales/fr/diagnostics.json+++ b/packages/vue/src/i18n/locales/fr/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "Cette action supprime de cet appareil les événements de diagnostic stockés localement.","cleared": "Diagnostics effacés.","copied": "Diagnostics copiés dans le presse-papiers.",- "copyFailed": "Impossible de copier les diagnostics dans le presse-papiers."+ "copyFailed": "Impossible de copier les diagnostics dans le presse-papiers.",+ "retentionCustom": "Personnalisé…",+ "retentionRange": "Saisissez un nombre entier entre {min} et {max}."}diff --git a/packages/vue/src/i18n/locales/fr/settings.json b/packages/vue/src/i18n/locales/fr/settings.jsonindex 3ce5cdce4..847c5229b 100644--- a/packages/vue/src/i18n/locales/fr/settings.json+++ b/packages/vue/src/i18n/locales/fr/settings.json@@ -19,7 +19,8 @@"usage": "Utilisation","diagnostics": "Diagnostics","media": "Médias",- "automation": "MCP et automatisation",+ "mcp": "MCP",+ "toolAccess": "Accès aux outils","storage": "Stockage cloud","animations": "Animations","animationsSystem": "Suivre le système",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex 8b5c7e1c5..810cc1a6e 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "Passaggi massimi per messaggio",+ "maxAgentStepsHint": "Solo per l’IA integrata; ACP e Pi gestiscono i propri limiti. Si salva premendo Invio o uscendo dal campo e si applica al messaggio successivo. Limiti più alti possono aumentare i costi.",+ "maxAgentStepsRange": "Inserisci un numero intero da {min} a {max}.","connectionTestSuccess": "Connessione riuscita. Il modello è raggiungibile.","connectionTestMissingAPIKey": "Inserisci una chiave API prima della verifica.","connectionTestMissingBaseURL": "Inserisci un URL di base prima della verifica.",@@ -144,5 +147,6 @@"reasoningCollapsed": "Compresso per impostazione predefinita","reasoningWhileThinking": "Espandi durante il ragionamento","reasoningExpanded": "Espanso per impostazione predefinita",- "jumpToLatest": "Vai all’ultimo messaggio"+ "jumpToLatest": "Vai all’ultimo messaggio",+ "maxAgentStepsCustom": "Personalizzato…"}diff --git a/packages/vue/src/i18n/locales/it/automation.json b/packages/vue/src/i18n/locales/it/automation.jsonindex afa4b37d0..49fc215f3 100644--- a/packages/vue/src/i18n/locales/it/automation.json+++ b/packages/vue/src/i18n/locales/it/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "Configura separatamente gli strumenti di progettazione per l’IA integrata e il server MCP locale.",+ "toolAccessTarget": "Configura l’accesso agli strumenti per",+ "builtInAI": "IA integrata",+ "localMCP": "MCP locale",+ "restoreToolDefaults": "Ripristina valori predefiniti",+ "aiToolAccessDescription": "Scegli gli strumenti per le connessioni dirette ai modelli IA. Gli agenti ACP e Pi utilizzano invece l’accesso MCP.",+ "mcpToolAccessDescription": "Scegli gli strumenti che il server locale offre agli agenti e ai client connessi.",+ "aiToolsNotice": "Le modifiche si applicano dal prossimo messaggio. Gli interruttori non isolano l’esecuzione: gli strumenti di script abilitati possono eseguire altre operazioni di progettazione.","addConnection": "Aggiungi connessione","connectionName": "Nome connessione","connections": "Connessioni MCP",@@ -30,7 +38,7 @@"tools": "Strumenti disponibili","toolsEnabled": "{enabled} di {total} abilitati","enableAllTools": "Abilita tutti",- "searchTools": "Cerca strumenti MCP",+ "searchTools": "Cerca strumenti","readOnlyTools": "Strumenti di sola lettura","sideEffectTools": "Strumenti con effetti collaterali","toolsRestartNotice": "Riavvia il server MCP, quindi riconnetti i client stdio per applicare le modifiche.",@@ -57,5 +65,24 @@"noMatchingTools": "Nessuno strumento corrisponde alla ricerca.","connectionNameHint": "Usa un nome univoco di massimo 80 caratteri. Il nome open-pencil è riservato.","connectionNameInvalid": "Scegli un nome univoco di massimo 80 caratteri, diverso da open-pencil.",- "serverURLHint": "Usa HTTPS. HTTP è consentito solo per localhost o un indirizzo di loopback. Non includere credenziali nell’URL."+ "serverURLHint": "Usa HTTPS. HTTP è consentito solo per localhost o un indirizzo di loopback. Non includere credenziali nell’URL.",+ "mcpFailureNotInstalled": "L’automazione MCP non è installata",+ "mcpFailureNotInstalledHint": "Installa {package} a livello globale con il gestore di pacchetti, poi riavvia OpenPencil.",+ "mcpFailurePermission": "OpenPencil non può avviare il server MCP",+ "mcpFailurePermissionHint": "Il sistema ha negato il comando. Reinstalla OpenPencil con i permessi di shell o avvia il server manualmente.",+ "mcpFailureExited": "Il server MCP si è arrestato durante l’avvio",+ "mcpFailureExitedHint": "Il processo è terminato prima di essere pronto.",+ "mcpFailureTimeout": "Il server MCP non ha risposto in tempo",+ "mcpFailureTimeoutHint": "Non è diventato pronto entro il tempo di avvio.",+ "mcpFailureRejected": "Il server MCP ha rifiutato la connessione locale",+ "mcpFailureRejectedHint": "Riavvia il server MCP per emettere un nuovo token.",+ "mcpFailureMalformed": "Il server MCP ha restituito una risposta inattesa",+ "mcpFailureMalformedHint": "Le versioni dell’app e del server potrebbero non coincidere. Aggiorna entrambe e riavvia OpenPencil.",+ "mcpFailureUnreachable": "Il server MCP non è raggiungibile",+ "mcpFailureUnreachableHint": "Nessuno risponde su {endpoint}. Libera l’indirizzo e avvia il server.",+ "mcpFailureUnknown": "Impossibile avviare il server MCP",+ "mcpFailureUnknownHint": "Avvialo di nuovo o controlla i dettagli tecnici qui sotto.",+ "mcpFailureDetails": "Dettagli",+ "mcpFailureCopy": "Copia dettagli",+ "mcpFailureCopied": "Dettagli tecnici copiati."}diff --git a/packages/vue/src/i18n/locales/it/diagnostics.json b/packages/vue/src/i18n/locales/it/diagnostics.jsonindex 527835af7..a3a89da21 100644--- a/packages/vue/src/i18n/locales/it/diagnostics.json+++ b/packages/vue/src/i18n/locales/it/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "Questa operazione rimuove da questo dispositivo gli eventi diagnostici archiviati localmente.","cleared": "Diagnostica cancellata.","copied": "Diagnostica copiata negli appunti.",- "copyFailed": "Impossibile copiare la diagnostica negli appunti."+ "copyFailed": "Impossibile copiare la diagnostica negli appunti.",+ "retentionCustom": "Personalizzato…",+ "retentionRange": "Inserisci un numero intero da {min} a {max}."}diff --git a/packages/vue/src/i18n/locales/it/settings.json b/packages/vue/src/i18n/locales/it/settings.jsonindex b93047ca3..d9a4b32aa 100644--- a/packages/vue/src/i18n/locales/it/settings.json+++ b/packages/vue/src/i18n/locales/it/settings.json@@ -19,7 +19,8 @@"usage": "Utilizzo","diagnostics": "Diagnostica","media": "Media",- "automation": "MCP e automazione",+ "mcp": "MCP",+ "toolAccess": "Accesso agli strumenti","storage": "Archiviazione cloud","animations": "Animazioni","animationsSystem": "Segui il sistema",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex 536a76cc4..c74f974a8 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "メッセージごとの最大ステップ数",+ "maxAgentStepsHint": "内蔵 AI のみが対象です。ACP と Pi は独自の上限を使用します。Enter キーまたは入力欄から移動したときに保存され、次のメッセージから適用されます。上限を増やすと費用が増える場合があります。",+ "maxAgentStepsRange": "{min} から {max} までの整数を入力してください。","connectionTestSuccess": "接続しました。モデルにアクセスできます。","connectionTestMissingAPIKey": "テストする前にAPIキーを入力してください。","connectionTestMissingBaseURL": "テストする前にベースURLを入力してください。",@@ -144,5 +147,6 @@"reasoningCollapsed": "既定で折りたたむ","reasoningWhileThinking": "思考中に展開","reasoningExpanded": "既定で展開",- "jumpToLatest": "最新へ移動"+ "jumpToLatest": "最新へ移動",+ "maxAgentStepsCustom": "カスタム…"}diff --git a/packages/vue/src/i18n/locales/ja/automation.json b/packages/vue/src/i18n/locales/ja/automation.jsonindex df8271f2e..74e2aac68 100644--- a/packages/vue/src/i18n/locales/ja/automation.json+++ b/packages/vue/src/i18n/locales/ja/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "内蔵 AI とローカル MCP サーバーのデザインツールを個別に設定します。",+ "toolAccessTarget": "ツールアクセスの設定対象",+ "builtInAI": "内蔵 AI",+ "localMCP": "ローカル MCP",+ "restoreToolDefaults": "既定値に戻す",+ "aiToolAccessDescription": "AI モデルへの直接接続で使うツールを選択します。ACP と Pi エージェントは MCP アクセスを使用します。",+ "mcpToolAccessDescription": "ローカルサーバーが接続中のエージェントやクライアントに公開するツールを選択します。",+ "aiToolsNotice": "変更は次のメッセージから適用されます。ツールの切り替えはサンドボックスではありません。有効なスクリプトツールは他のデザイン操作も実行できます。","addConnection": "接続を追加","connectionName": "接続名","connections": "MCP接続",@@ -30,7 +38,7 @@"tools": "利用可能なツール","toolsEnabled": "{total} 件中 {enabled} 件を有効化","enableAllTools": "すべて有効化",- "searchTools": "MCP ツールを検索",+ "searchTools": "ツールを検索","readOnlyTools": "読み取り専用ツール","sideEffectTools": "副作用のあるツール","toolsRestartNotice": "変更を反映するには MCP サーバーを再起動し、stdio クライアントを再接続してください。",@@ -57,5 +65,24 @@"noMatchingTools": "検索に一致するツールはありません。","connectionNameHint": "80 文字以内の重複しない名前を使用してください。open-pencil は予約済みです。","connectionNameInvalid": "open-pencil 以外の、80 文字以内で重複しない名前を選んでください。",- "serverURLHint": "HTTPS を使用してください。HTTP は localhost またはループバックアドレスでのみ使用できます。URL に認証情報を含めないでください。"+ "serverURLHint": "HTTPS を使用してください。HTTP は localhost またはループバックアドレスでのみ使用できます。URL に認証情報を含めないでください。",+ "mcpFailureNotInstalled": "MCP 自動化がインストールされていません",+ "mcpFailureNotInstalledHint": "パッケージマネージャーで {package} をグローバルにインストールし、OpenPencil を再起動してください。",+ "mcpFailurePermission": "OpenPencil が MCP サーバーを起動できません",+ "mcpFailurePermissionHint": "システムがコマンドを拒否しました。シェル権限を含めて OpenPencil を再インストールするか、サーバーを手動で起動してください。",+ "mcpFailureExited": "起動中に MCP サーバーが停止しました",+ "mcpFailureExitedHint": "準備完了になる前にプロセスが終了しました。",+ "mcpFailureTimeout": "MCP サーバーが時間内に応答しませんでした",+ "mcpFailureTimeoutHint": "起動タイムアウト内に準備完了になりませんでした。",+ "mcpFailureRejected": "MCP サーバーがローカル接続を拒否しました",+ "mcpFailureRejectedHint": "MCP サーバーを再起動して新しいトークンを発行してください。",+ "mcpFailureMalformed": "MCP サーバーが予期しない応答を返しました",+ "mcpFailureMalformedHint": "アプリとサーバーのバージョンが一致していない可能性があります。両方を更新して OpenPencil を再起動してください。",+ "mcpFailureUnreachable": "MCP サーバーに到達できません",+ "mcpFailureUnreachableHint": "{endpoint} で応答がありません。アドレスを解放してからサーバーを起動してください。",+ "mcpFailureUnknown": "MCP サーバーを起動できませんでした",+ "mcpFailureUnknownHint": "もう一度起動するか、以下の技術的な詳細を確認してください。",+ "mcpFailureDetails": "詳細",+ "mcpFailureCopy": "詳細をコピー",+ "mcpFailureCopied": "技術的な詳細をコピーしました。"}diff --git a/packages/vue/src/i18n/locales/ja/diagnostics.json b/packages/vue/src/i18n/locales/ja/diagnostics.jsonindex 134fb071b..9b48f3d71 100644--- a/packages/vue/src/i18n/locales/ja/diagnostics.json+++ b/packages/vue/src/i18n/locales/ja/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "このデバイスに保存されている診断イベントを削除します。","cleared": "診断データを消去しました。","copied": "診断データをクリップボードにコピーしました。",- "copyFailed": "診断データをクリップボードにコピーできませんでした。"+ "copyFailed": "診断データをクリップボードにコピーできませんでした。",+ "retentionCustom": "カスタム…",+ "retentionRange": "{min} から {max} までの整数を入力してください。"}diff --git a/packages/vue/src/i18n/locales/ja/settings.json b/packages/vue/src/i18n/locales/ja/settings.jsonindex 3b2d98a07..227fdf333 100644--- a/packages/vue/src/i18n/locales/ja/settings.json+++ b/packages/vue/src/i18n/locales/ja/settings.json@@ -19,7 +19,8 @@"usage": "使用状況","diagnostics": "診断","media": "メディア",- "automation": "MCP と自動化",+ "mcp": "MCP",+ "toolAccess": "ツールへのアクセス","storage": "クラウドストレージ","animations": "アニメーション","animationsSystem": "システム設定に従う",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 28e055944..ff6d44aee 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "Maksymalna liczba kroków na wiadomość",+ "maxAgentStepsHint": "Tylko dla wbudowanej AI; ACP i Pi zarządzają własnymi limitami. Zapis po naciśnięciu Enter lub opuszczeniu pola, obowiązuje od następnej wiadomości. Wyższe limity mogą zwiększyć koszt.",+ "maxAgentStepsRange": "Wpisz liczbę całkowitą od {min} do {max}.","connectionTestSuccess": "Połączono pomyślnie. Model jest dostępny.","connectionTestMissingAPIKey": "Wprowadź klucz API przed rozpoczęciem testu.","connectionTestMissingBaseURL": "Wprowadź bazowy adres URL przed rozpoczęciem testu.",@@ -144,5 +147,6 @@"reasoningCollapsed": "Domyślnie zwinięte","reasoningWhileThinking": "Rozwijaj podczas rozumowania","reasoningExpanded": "Domyślnie rozwinięte",- "jumpToLatest": "Przejdź do najnowszej wiadomości"+ "jumpToLatest": "Przejdź do najnowszej wiadomości",+ "maxAgentStepsCustom": "Własna wartość…"}diff --git a/packages/vue/src/i18n/locales/pl/automation.json b/packages/vue/src/i18n/locales/pl/automation.jsonindex 5dc059306..26f847da6 100644--- a/packages/vue/src/i18n/locales/pl/automation.json+++ b/packages/vue/src/i18n/locales/pl/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "Skonfiguruj narzędzia projektowe osobno dla wbudowanej AI i lokalnego serwera MCP.",+ "toolAccessTarget": "Skonfiguruj dostęp do narzędzi dla",+ "builtInAI": "Wbudowana AI",+ "localMCP": "Lokalny MCP",+ "restoreToolDefaults": "Przywróć domyślne",+ "aiToolAccessDescription": "Wybierz narzędzia dla bezpośrednich połączeń z modelami AI. Agenci ACP i Pi korzystają z dostępu MCP.",+ "mcpToolAccessDescription": "Wybierz narzędzia udostępniane przez lokalny serwer połączonym agentom i klientom.",+ "aiToolsNotice": "Zmiany obowiązują od następnej wiadomości. Przełączniki nie izolują wykonania: włączone narzędzia skryptowe mogą wykonywać inne operacje projektowe.","addConnection": "Dodaj połączenie","connectionName": "Nazwa połączenia","connections": "Połączenia MCP",@@ -30,7 +38,7 @@"tools": "Dostępne narzędzia","toolsEnabled": "Włączono {enabled} z {total}","enableAllTools": "Włącz wszystkie",- "searchTools": "Szukaj narzędzi MCP",+ "searchTools": "Szukaj narzędzi","readOnlyTools": "Narzędzia tylko do odczytu","sideEffectTools": "Narzędzia z efektami ubocznymi","toolsRestartNotice": "Uruchom serwer MCP ponownie, a następnie połącz ponownie klientów stdio, aby zastosować zmiany.",@@ -57,5 +65,24 @@"noMatchingTools": "Brak narzędzi pasujących do wyszukiwania.","connectionNameHint": "Użyj unikalnej nazwy o długości do 80 znaków. Nazwa open-pencil jest zarezerwowana.","connectionNameInvalid": "Wybierz unikalną nazwę o długości do 80 znaków, inną niż open-pencil.",- "serverURLHint": "Użyj HTTPS. HTTP jest dozwolone tylko dla localhost lub adresu pętli zwrotnej. Nie umieszczaj danych uwierzytelniających w adresie URL."+ "serverURLHint": "Użyj HTTPS. HTTP jest dozwolone tylko dla localhost lub adresu pętli zwrotnej. Nie umieszczaj danych uwierzytelniających w adresie URL.",+ "mcpFailureNotInstalled": "Automatyzacja MCP nie jest zainstalowana",+ "mcpFailureNotInstalledHint": "Zainstaluj {package} globalnie w menedżerze pakietów i uruchom ponownie OpenPencil.",+ "mcpFailurePermission": "OpenPencil nie może uruchomić serwera MCP",+ "mcpFailurePermissionHint": "System odrzucił polecenie. Zainstaluj ponownie OpenPencil z uprawnieniami powłoki lub uruchom serwer ręcznie.",+ "mcpFailureExited": "Serwer MCP zatrzymał się podczas uruchamiania",+ "mcpFailureExitedHint": "Proces zakończył się, zanim był gotowy.",+ "mcpFailureTimeout": "Serwer MCP nie odpowiedział na czas",+ "mcpFailureTimeoutHint": "Nie stał się gotowy w wyznaczonym czasie.",+ "mcpFailureRejected": "Serwer MCP odrzucił połączenie lokalne",+ "mcpFailureRejectedHint": "Uruchom ponownie serwer MCP, aby wystawić nowy token.",+ "mcpFailureMalformed": "Serwer MCP zwrócił nieoczekiwaną odpowiedź",+ "mcpFailureMalformedHint": "Wersje aplikacji i serwera mogą się różnić. Zaktualizuj obie i uruchom ponownie OpenPencil.",+ "mcpFailureUnreachable": "Serwer MCP jest nieosiągalny",+ "mcpFailureUnreachableHint": "Pod adresem {endpoint} nikt nie nasłuchuje. Zwolnij adres i uruchom serwer.",+ "mcpFailureUnknown": "Nie udało się uruchomić serwera MCP",+ "mcpFailureUnknownHint": "Uruchom go ponownie lub sprawdź szczegóły techniczne poniżej.",+ "mcpFailureDetails": "Szczegóły",+ "mcpFailureCopy": "Kopiuj szczegóły",+ "mcpFailureCopied": "Skopiowano szczegóły techniczne."}diff --git a/packages/vue/src/i18n/locales/pl/diagnostics.json b/packages/vue/src/i18n/locales/pl/diagnostics.jsonindex e1858a271..00673201d 100644--- a/packages/vue/src/i18n/locales/pl/diagnostics.json+++ b/packages/vue/src/i18n/locales/pl/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "Spowoduje to usunięcie lokalnie zapisanych zdarzeń diagnostycznych z tego urządzenia.","cleared": "Wyczyszczono dane diagnostyczne.","copied": "Skopiowano dane diagnostyczne do schowka.",- "copyFailed": "Nie można skopiować danych diagnostycznych do schowka."+ "copyFailed": "Nie można skopiować danych diagnostycznych do schowka.",+ "retentionCustom": "Własna wartość…",+ "retentionRange": "Wpisz liczbę całkowitą od {min} do {max}."}diff --git a/packages/vue/src/i18n/locales/pl/settings.json b/packages/vue/src/i18n/locales/pl/settings.jsonindex 8bfe476d4..21851380d 100644--- a/packages/vue/src/i18n/locales/pl/settings.json+++ b/packages/vue/src/i18n/locales/pl/settings.json@@ -19,7 +19,8 @@"usage": "Użycie","diagnostics": "Diagnostyka","media": "Media",- "automation": "MCP i automatyzacja",+ "mcp": "MCP",+ "toolAccess": "Dostęp do narzędzi","storage": "Przechowywanie w chmurze","animations": "Animacje","animationsSystem": "Zgodnie z systemem",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex 5c039a86d..bffbab8b9 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "Максимум шагов на сообщение",+ "maxAgentStepsHint": "Только для встроенного ИИ; ACP и Pi управляют своими лимитами. Сохраняется по Enter или при выходе из поля и применяется со следующего сообщения. Больший лимит может увеличить расходы.",+ "maxAgentStepsRange": "Введите целое число от {min} до {max}.","connectionTestSuccess": "Подключение установлено. Модель доступна.","connectionTestMissingAPIKey": "Введите API-ключ перед проверкой.","connectionTestMissingBaseURL": "Введите базовый URL перед проверкой.",@@ -144,5 +147,6 @@"reasoningCollapsed": "Свёрнуто по умолчанию","reasoningWhileThinking": "Разворачивать во время размышлений","reasoningExpanded": "Развёрнуто по умолчанию",- "jumpToLatest": "К последнему сообщению"+ "jumpToLatest": "К последнему сообщению",+ "maxAgentStepsCustom": "Своё значение…"}diff --git a/packages/vue/src/i18n/locales/ru/automation.json b/packages/vue/src/i18n/locales/ru/automation.jsonindex 4748f9cf7..74eb5caa9 100644--- a/packages/vue/src/i18n/locales/ru/automation.json+++ b/packages/vue/src/i18n/locales/ru/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "Настраивайте инструменты дизайна отдельно для встроенного ИИ и локального MCP-сервера.",+ "toolAccessTarget": "Настроить доступ к инструментам для",+ "builtInAI": "Встроенный ИИ",+ "localMCP": "Локальный MCP",+ "restoreToolDefaults": "Восстановить настройки",+ "aiToolAccessDescription": "Выберите инструменты для прямых подключений к моделям ИИ. Агенты ACP и Pi используют доступ через MCP.",+ "mcpToolAccessDescription": "Выберите инструменты, которые локальный сервер предоставляет подключённым агентам и клиентам.",+ "aiToolsNotice": "Изменения применяются со следующего сообщения. Переключатели не изолируют выполнение: включённые инструменты скриптов могут выполнять и другие операции с дизайном.","addConnection": "Добавить подключение","connectionName": "Название подключения","connections": "Подключения MCP",@@ -30,7 +38,7 @@"tools": "Доступные инструменты","toolsEnabled": "Включено {enabled} из {total}","enableAllTools": "Включить все",- "searchTools": "Поиск инструментов MCP",+ "searchTools": "Поиск инструментов","readOnlyTools": "Инструменты только для чтения","sideEffectTools": "Инструменты с побочными эффектами","toolsRestartNotice": "Перезапустите MCP-сервер, затем переподключите stdio-клиенты, чтобы применить изменения.",@@ -57,5 +65,24 @@"noMatchingTools": "По вашему запросу инструменты не найдены.","connectionNameHint": "Укажите уникальное название длиной до 80 символов. Название open-pencil зарезервировано.","connectionNameInvalid": "Выберите уникальное название длиной до 80 символов, отличное от open-pencil.",- "serverURLHint": "Используйте HTTPS. HTTP разрешён только для localhost или адреса обратной петли. Не включайте учётные данные в URL."+ "serverURLHint": "Используйте HTTPS. HTTP разрешён только для localhost или адреса обратной петли. Не включайте учётные данные в URL.",+ "mcpFailureNotInstalled": "Автоматизация MCP не установлена",+ "mcpFailureNotInstalledHint": "Установите {package} глобально через менеджер пакетов и перезапустите OpenPencil.",+ "mcpFailurePermission": "OpenPencil не может запустить MCP-сервер",+ "mcpFailurePermissionHint": "Система отклонила команду. Переустановите OpenPencil с правами оболочки или запустите сервер вручную.",+ "mcpFailureExited": "MCP-сервер остановился при запуске",+ "mcpFailureExitedHint": "Процесс завершился до готовности.",+ "mcpFailureTimeout": "MCP-сервер не ответил вовремя",+ "mcpFailureTimeoutHint": "Он не стал готовым за отведённое время.",+ "mcpFailureRejected": "MCP-сервер отклонил локальное подключение",+ "mcpFailureRejectedHint": "Перезапустите MCP-сервер, чтобы выпустить новый токен.",+ "mcpFailureMalformed": "MCP-сервер вернул неожиданный ответ",+ "mcpFailureMalformedHint": "Версии приложения и сервера могут не совпадать. Обновите оба и перезапустите OpenPencil.",+ "mcpFailureUnreachable": "MCP-сервер недоступен",+ "mcpFailureUnreachableHint": "По адресу {endpoint} никто не отвечает. Освободите адрес и запустите сервер.",+ "mcpFailureUnknown": "MCP-сервер не удалось запустить",+ "mcpFailureUnknownHint": "Запустите его снова или посмотрите технические подробности ниже.",+ "mcpFailureDetails": "Подробности",+ "mcpFailureCopy": "Копировать подробности",+ "mcpFailureCopied": "Технические подробности скопированы."}diff --git a/packages/vue/src/i18n/locales/ru/diagnostics.json b/packages/vue/src/i18n/locales/ru/diagnostics.jsonindex a67919dd3..5d342cee8 100644--- a/packages/vue/src/i18n/locales/ru/diagnostics.json+++ b/packages/vue/src/i18n/locales/ru/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "Локально сохранённые диагностические события будут удалены с этого устройства.","cleared": "Диагностические данные очищены.","copied": "Диагностические данные скопированы в буфер обмена.",- "copyFailed": "Не удалось скопировать диагностические данные в буфер обмена."+ "copyFailed": "Не удалось скопировать диагностические данные в буфер обмена.",+ "retentionCustom": "Своё значение…",+ "retentionRange": "Введите целое число от {min} до {max}."}diff --git a/packages/vue/src/i18n/locales/ru/settings.json b/packages/vue/src/i18n/locales/ru/settings.jsonindex 5aee3ca06..4f7736b29 100644--- a/packages/vue/src/i18n/locales/ru/settings.json+++ b/packages/vue/src/i18n/locales/ru/settings.json@@ -19,7 +19,8 @@"usage": "Использование","diagnostics": "Диагностика","media": "Медиа",- "automation": "MCP и автоматизация",+ "mcp": "MCP",+ "toolAccess": "Доступ к инструментам","storage": "Облачное хранилище","animations": "Анимации","animationsSystem": "Как в системе",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 6779ead82..4bf625263 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -1,4 +1,7 @@{+ "maxAgentSteps": "每条消息的最大步骤数",+ "maxAgentStepsHint": "仅适用于内置 AI;ACP 和 Pi 使用各自的限制。按 Enter 或离开输入框时保存,从下一条消息开始生效。提高上限可能增加费用。",+ "maxAgentStepsRange": "请输入 {min} 到 {max} 之间的整数。","connectionTestSuccess": "连接成功。模型可访问。","connectionTestMissingAPIKey": "请在测试前输入 API 密钥。","connectionTestMissingBaseURL": "请在测试前输入基础 URL。",@@ -144,5 +147,6 @@"reasoningCollapsed": "默认折叠","reasoningWhileThinking": "思考时展开","reasoningExpanded": "默认展开",- "jumpToLatest": "跳转到最新消息"+ "jumpToLatest": "跳转到最新消息",+ "maxAgentStepsCustom": "自定义…"}diff --git a/packages/vue/src/i18n/locales/zh-cn/automation.json b/packages/vue/src/i18n/locales/zh-cn/automation.jsonindex c3100ddda..62c5f4303 100644--- a/packages/vue/src/i18n/locales/zh-cn/automation.json+++ b/packages/vue/src/i18n/locales/zh-cn/automation.json@@ -1,4 +1,12 @@{+ "toolAccessDescription": "分别配置内置 AI 和本地 MCP 服务器的设计工具。",+ "toolAccessTarget": "配置工具访问权限的对象",+ "builtInAI": "内置 AI",+ "localMCP": "本地 MCP",+ "restoreToolDefaults": "恢复默认设置",+ "aiToolAccessDescription": "选择直接连接 AI 模型时可用的工具。ACP 和 Pi 智能体使用 MCP 访问权限。",+ "mcpToolAccessDescription": "选择本地服务器向已连接的智能体和客户端提供的工具。",+ "aiToolsNotice": "更改从下一条消息开始生效。工具开关不是沙箱:已启用的脚本工具仍可执行其他设计操作。","addConnection": "添加连接","connectionName": "连接名称","connections": "MCP 连接",@@ -30,7 +38,7 @@"tools": "可用工具","toolsEnabled": "已启用 {enabled}/{total}","enableAllTools": "全部启用",- "searchTools": "搜索 MCP 工具",+ "searchTools": "搜索工具","readOnlyTools": "只读工具","sideEffectTools": "有副作用的工具","toolsRestartNotice": "重启 MCP 服务器并重新连接 stdio 客户端以应用工具更改。",@@ -57,5 +65,24 @@"noMatchingTools": "没有与搜索匹配的工具。","connectionNameHint": "使用不超过 80 个字符的唯一名称。open-pencil 为保留名称。","connectionNameInvalid": "请选择不超过 80 个字符且不是 open-pencil 的唯一名称。",- "serverURLHint": "请使用 HTTPS。仅 localhost 或回环地址允许使用 HTTP。请勿在 URL 中包含凭据。"+ "serverURLHint": "请使用 HTTPS。仅 localhost 或回环地址允许使用 HTTP。请勿在 URL 中包含凭据。",+ "mcpFailureNotInstalled": "MCP 自动化未安装",+ "mcpFailureNotInstalledHint": "请使用包管理器全局安装 {package},然后重启 OpenPencil。",+ "mcpFailurePermission": "OpenPencil 无法启动 MCP 服务器",+ "mcpFailurePermissionHint": "系统拒绝了该命令。请重新安装 OpenPencil 以包含其命令行权限,或手动启动服务器。",+ "mcpFailureExited": "MCP 服务器在启动过程中停止",+ "mcpFailureExitedHint": "进程在就绪前已退出。",+ "mcpFailureTimeout": "MCP 服务器未及时响应",+ "mcpFailureTimeoutHint": "未在启动超时时间内就绪。",+ "mcpFailureRejected": "MCP 服务器拒绝了本地连接",+ "mcpFailureRejectedHint": "重启 MCP 服务器以签发新的令牌。",+ "mcpFailureMalformed": "MCP 服务器返回了意外的响应",+ "mcpFailureMalformedHint": "应用与服务器版本可能不一致。请同时更新并重启 OpenPencil。",+ "mcpFailureUnreachable": "无法访问 MCP 服务器",+ "mcpFailureUnreachableHint": "{endpoint} 上没有任何服务在监听。请释放该地址,然后启动服务器。",+ "mcpFailureUnknown": "无法启动 MCP 服务器",+ "mcpFailureUnknownHint": "请重新启动,或查看下方的技术细节。",+ "mcpFailureDetails": "详细信息",+ "mcpFailureCopy": "复制详细信息",+ "mcpFailureCopied": "已复制技术细节。"}diff --git a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json b/packages/vue/src/i18n/locales/zh-cn/diagnostics.jsonindex 4250cd101..b20cb1233 100644--- a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json+++ b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json@@ -30,5 +30,7 @@"clearDescription": "这会从此设备中删除本地保存的诊断事件。","cleared": "诊断数据已清除。","copied": "诊断数据已复制到剪贴板。",- "copyFailed": "无法将诊断数据复制到剪贴板。"+ "copyFailed": "无法将诊断数据复制到剪贴板。",+ "retentionCustom": "自定义…",+ "retentionRange": "请输入 {min} 到 {max} 之间的整数。"}diff --git a/packages/vue/src/i18n/locales/zh-cn/settings.json b/packages/vue/src/i18n/locales/zh-cn/settings.jsonindex 4b2fc148e..1b3f0b56b 100644--- a/packages/vue/src/i18n/locales/zh-cn/settings.json+++ b/packages/vue/src/i18n/locales/zh-cn/settings.json@@ -19,7 +19,8 @@"usage": "使用情况","diagnostics": "诊断","media": "媒体",- "automation": "MCP 与自动化",+ "mcp": "MCP",+ "toolAccess": "工具访问权限","storage": "云存储","animations": "动画","animationsSystem": "跟随系统",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex aba5bccd2..38ce13161 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -5,6 +5,11 @@ import { i18n } from '#vue/i18n/create'export const aiMessageDefaults = {jumpToLatest: 'Jump to latest',chatSettings: 'Chat',+ maxAgentSteps: 'Maximum steps per message',+ maxAgentStepsCustom: 'Custom…',+ maxAgentStepsHint:+ 'For built-in AI only; ACP and Pi control their own limits. Saved on Enter or when you leave the field, and applied to the next message. Higher limits can increase cost.',+ maxAgentStepsRange: params('Enter a whole number from {min} to {max}.'),reasoningDisplay: 'Reasoning display',reasoningCollapsed: 'Collapsed by default',reasoningWhileThinking: 'Expand while thinking',diff --git a/packages/vue/src/i18n/messages/automation.ts b/packages/vue/src/i18n/messages/automation.tsindex 307a5db3b..34417a34d 100644--- a/packages/vue/src/i18n/messages/automation.ts+++ b/packages/vue/src/i18n/messages/automation.ts@@ -3,6 +3,43 @@ import { params } from '@nanostores/i18n'import { i18n } from '#vue/i18n/create'export const automationMessageDefaults = {+ toolAccessDescription:+ 'Configure design tools independently for built-in AI and the local MCP server.',+ toolAccessTarget: 'Configure tool access for',+ builtInAI: 'Built-in AI',+ localMCP: 'Local MCP',+ restoreToolDefaults: 'Restore defaults',+ aiToolAccessDescription:+ 'Choose tools for direct AI model connections. ACP and Pi agents use MCP access instead.',+ mcpToolAccessDescription:+ 'Choose tools advertised by the local server to connected agents and clients.',+ aiToolsNotice:+ 'Changes apply to your next message. Tool switches are not a sandbox: enabled script tools can still perform other design operations.',+ mcpFailureNotInstalled: 'MCP automation is not installed',+ mcpFailureNotInstalledHint: params(+ 'Install {package} globally with your package manager, then restart OpenPencil.'+ ),+ mcpFailurePermission: 'OpenPencil cannot start the MCP server',+ mcpFailurePermissionHint:+ 'The system denied the command. Reinstall OpenPencil with its shell permissions, or start the server manually.',+ mcpFailureExited: 'MCP server stopped during startup',+ mcpFailureExitedHint: 'The process exited before it became ready.',+ mcpFailureTimeout: 'MCP server did not respond in time',+ mcpFailureTimeoutHint: 'It did not become ready within the startup timeout.',+ mcpFailureRejected: 'MCP server rejected the local connection',+ mcpFailureRejectedHint: 'Restart the MCP server to issue a new token.',+ mcpFailureMalformed: 'MCP server returned an unexpected response',+ mcpFailureMalformedHint:+ 'The configured version and the running server may not match. Update both and restart OpenPencil.',+ mcpFailureUnreachable: 'MCP server is not reachable',+ mcpFailureUnreachableHint: params(+ 'Nothing is listening at {endpoint}. Check that the address is free, then start the server.'+ ),+ mcpFailureUnknown: 'MCP server could not start',+ mcpFailureUnknownHint: 'Start it again, or check the diagnostic details below.',+ mcpFailureDetails: 'Details',+ mcpFailureCopy: 'Copy details',+ mcpFailureCopied: 'Diagnostic details copied.',localServer: 'Local server',webmcpDescription:'Let browser agents use this document directly, without a local MCP server or bearer token. Local server settings do not apply here.',@@ -55,7 +92,7 @@ export const automationMessageDefaults = {tools: 'Available tools',toolsEnabled: params('{enabled} of {total} enabled'),enableAllTools: 'Enable all',- searchTools: 'Search MCP tools',+ searchTools: 'Search tools',readOnlyTools: 'Read-only tools',sideEffectTools: 'Tools with side effects',toolsRestartNotice:diff --git a/packages/vue/src/i18n/messages/diagnostics.ts b/packages/vue/src/i18n/messages/diagnostics.tsindex 9bc070ab4..4f8a01692 100644--- a/packages/vue/src/i18n/messages/diagnostics.ts+++ b/packages/vue/src/i18n/messages/diagnostics.ts@@ -22,6 +22,8 @@ export const diagnosticsMessageDefaults = {mcpFailed: 'MCP connection failed',technicalEvent: 'Technical event',retention: 'Diagnostics retention',+ retentionCustom: 'Custom…',+ retentionRange: params('Enter a whole number from {min} to {max}.'),retentionDescription: 'Keep up to this many recent events locally.',description:'Store technical events locally to help troubleshoot OpenPencil. Prompts, design content, credentials, and API keys are excluded.',diff --git a/packages/vue/src/i18n/messages/settings.ts b/packages/vue/src/i18n/messages/settings.tsindex df77827b3..5afb1f6cc 100644--- a/packages/vue/src/i18n/messages/settings.ts+++ b/packages/vue/src/i18n/messages/settings.ts@@ -24,7 +24,8 @@ export const settingsMessageDefaults = {usage: 'Usage',diagnostics: 'Diagnostics',media: 'Media',- automation: 'MCP & automation',+ mcp: 'MCP',+ toolAccess: 'Tool access',edit: 'Edit',configured: 'Configured',notConfigured: 'Not configured',diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 402ee6196..d36aed5f4 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -207,12 +207,14 @@ The CLI defaults the filesystem root to the home directory on Windows and the cu### Browser-native WebMCP (experimental)-WebMCP is off by default. In **Settings → MCP & automation → WebMCP**, choose **Inspect** for read-only tools or **Edit** for scoped changes. These controls are independent of local MCP settings. Supporting browsers expose inspection and undoable existing-layer/property and variable edits directly from the OpenPencil workspace through `document.modelContext`, without an MCP server connection. Discover this browser surface separately: it excludes structural creation/deletion, arbitrary JS/JSX execution, external assets, filesystem operations, and credentials.+WebMCP is off by default. In **Settings → MCP → WebMCP**, choose **Inspect** for read-only tools or **Edit** for scoped changes. These controls are independent of local MCP settings. Supporting browsers expose inspection and undoable existing-layer/property and variable edits directly from the OpenPencil workspace through `document.modelContext`, without an MCP server connection. Discover this browser surface separately: it excludes structural creation/deletion, arbitrary JS/JSX execution, external assets, filesystem operations, and credentials.Calls capture the active document/page. Cancellation prevents an edit from starting but does not reverse an already committed edit; use editor undo instead. Atomic edits require at most 10,000 nodes and variables combined, including when these same tools run through app AI/MCP. See the [WebMCP guide](https://openpencil.dev/programmable/mcp-server#webmcp) for scope and browser requirements.## Tool discovery+Users configure local server tools in **Settings → Tool access** → **Local MCP**, independently from **Built-in AI** tool preferences. Local MCP changes require a server restart and stdio client reconnection; built-in AI changes apply to the next message. ACP and Pi agents use the MCP surface, not the direct-model AI tool selection. Tool switches are not a sandbox: enabled scripting tools can still perform operations whose dedicated tools are disabled.+Discover available tools and their arguments from the connected server or browser; availability varies by version and mode. Each tool's schema and execution/exposure metadata are authoritative. Numeric inputs accept numbers or numeric strings consistently, but reject non-finite values. Do not rely on a fixed tool count or a copied inventory.> Tool availability can depend on server mode. `open_file`, `save_file`, and disk-writing export paths are scoped to the effective filesystem root; set it explicitly with `OPENPENCIL_MCP_ROOT`.diff --git a/src/app/ai/chat/preferences.ts b/src/app/ai/chat/preferences.tsindex a6ba96f6f..e8055794b 100644--- a/src/app/ai/chat/preferences.ts+++ b/src/app/ai/chat/preferences.ts@@ -2,9 +2,24 @@ import { computed } from 'vue'import { appPreferences, type ReasoningDisplay } from '@/app/settings/preferences/store'+import { resolveAgentStepLimit } from './step-limit'++export const maxAgentSteps = computed({+ get: () => resolveAgentStepLimit(appPreferences.value.chat.maxAgentSteps),+ set: (value: number) => {+ appPreferences.value = {+ ...appPreferences.value,+ chat: { ...appPreferences.value.chat, maxAgentSteps: resolveAgentStepLimit(value) }+ }+ }+})+export const reasoningDisplay = computed({get: () => appPreferences.value.chat.reasoningDisplay,set: (reasoningDisplay: ReasoningDisplay) => {- appPreferences.value = { ...appPreferences.value, chat: { reasoningDisplay } }+ appPreferences.value = {+ ...appPreferences.value,+ chat: { ...appPreferences.value.chat, reasoningDisplay }+ }}})diff --git a/src/app/ai/chat/step-limit.ts b/src/app/ai/chat/step-limit.tsnew file mode 100644index 000000000..efb08989e--- /dev/null+++ b/src/app/ai/chat/step-limit.ts@@ -0,0 +1,17 @@+import * as v from 'valibot'++export const DEFAULT_AGENT_STEPS = 50+export const AGENT_STEP_LIMIT_MIN = 1+export const AGENT_STEP_LIMIT_MAX = 1000++export const agentStepLimitSchema = v.pipe(+ v.number(),+ v.integer(),+ v.minValue(AGENT_STEP_LIMIT_MIN),+ v.maxValue(AGENT_STEP_LIMIT_MAX)+)++export function resolveAgentStepLimit(value: unknown): number {+ const result = v.safeParse(agentStepLimitSchema, value)+ return result.success ? result.output : DEFAULT_AGENT_STEPS+}diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.tsindex 8ae29ddb2..d61dca572 100644--- a/src/app/ai/chat/transports.ts+++ b/src/app/ai/chat/transports.ts@@ -12,7 +12,9 @@ import { resolveLanguageModelID } from '@/app/ai/chat/model'import { buildReasoningProviderOptions, type AIProviderOptions } from '@/app/ai/chat/reasoning'import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'import { createAIModelRuntime, resolveModelConnectionAPIKey } from '@/app/ai/models'-import { MAX_AGENT_STEPS, createAITools, recordStep, resetRunSteps } from '@/app/ai/tools'+import { createAITools, recordStep, resetRunSteps } from '@/app/ai/tools'+import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'+import { aiToolOverrides } from '@/app/ai/tools/preferences'import {recordChatCompleted,recordChatFailed,@@ -22,6 +24,7 @@ import type { AIDiagnosticContext } from '@/app/diagnostics/events/ai'import type { getActiveEditorStore } from '@/app/editor/active-store'import { resumableTransport } from './history/continuation'+import { maxAgentSteps } from './preferences'type EditorStore = ReturnType<typeof getActiveEditorStore>@@ -98,13 +101,19 @@ export function createToolLoopTransport({model,instructions: SYSTEM_PROMPT,tools,- stopWhen: stepCountIs(MAX_AGENT_STEPS),maxOutputTokens,providerOptions,prepareCall: (options) => {- resetRunSteps(store)+ const stepLimit = maxAgentSteps.value+ const enabledNames = new Set(+ enabledAIToolDefinitions(aiToolOverrides.value).map((tool) => tool.name)+ )+ resetRunSteps(store, stepLimit)return {...options,+ stopWhen: stepCountIs(stepLimit),+ // Keep the full catalog for validating history; offer only enabled tools to this request.+ tools: Object.fromEntries(Object.entries(tools).filter(([name]) => enabledNames.has(name))),maxOutputTokens,providerOptions}diff --git a/src/app/ai/tools/catalog.ts b/src/app/ai/tools/catalog.tsnew file mode 100644index 000000000..5545975d7--- /dev/null+++ b/src/app/ai/tools/catalog.ts@@ -0,0 +1,27 @@+import { ALL_TOOLS, CORE_TOOLS, isToolExposed, toolChangesDocument } from '@open-pencil/core/tools'++import type { ToolAccessEntry } from '@/app/automation/tool-access/types'++/** Preserve the compact shipped tool set as defaults, not as an availability restriction. */+const defaultNames = new Set([+ ...CORE_TOOLS.map((tool) => tool.name),+ 'get_components',+ 'list_libraries',+ 'insert_library_component'+])++export const aiToolDefinitions = ALL_TOOLS.filter((tool) => isToolExposed(tool, 'ai'))++export const configurableAITools: ToolAccessEntry[] = aiToolDefinitions.map((tool) => ({+ name: tool.name,+ description: tool.description,+ effect: toolChangesDocument(tool) ? 'write' : 'read'+}))++export function isAIToolEnabled(name: string, overrides: Readonly<Record<string, boolean>>) {+ return overrides[name] ?? defaultNames.has(name)+}++export function enabledAIToolDefinitions(overrides: Readonly<Record<string, boolean>>) {+ return aiToolDefinitions.filter((tool) => isAIToolEnabled(tool.name, overrides))+}diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 0cca69030..cb05ec5ea 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -1,15 +1,10 @@import { tool } from 'ai'-import {- CORE_TOOLS,- EXTENDED_TOOLS,- registerComponentCatalog,- isAtomicTool,- toolsToAI-} from '@open-pencil/core/tools'+import { registerComponentCatalog, isAtomicTool, toolsToAI } from '@open-pencil/core/tools'import type { StepBudget } from '@open-pencil/core/tools'import type { SceneNode } from '@open-pencil/scene-graph'+import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'import { executeAtomicEditorTool } from '@/app/automation/execution/editor'import { recordToolCompleted, type AIDiagnosticContext } from '@/app/diagnostics/events/ai'@@ -18,17 +13,20 @@ import type { EditorStore } from '@/app/editor/active-store'import { ensureGraphFonts } from '@/app/editor/fonts'import { useLibraryService } from '@/app/libraries'-export const MAX_AGENT_STEPS = 50+import { aiToolDefinitions } from './catalog'class RunState {currentSteps = 0+ /** Captured for the message in progress; settings changes apply to the next one. */+ maxSteps = DEFAULT_AGENT_STEPS- resetSteps(): void {+ resetSteps(maxSteps: number): void {this.currentSteps = 0+ this.maxSteps = resolveAgentStepLimit(maxSteps)}hitLimit(): boolean {- return this.currentSteps >= MAX_AGENT_STEPS+ return this.currentSteps >= this.maxSteps}}@@ -47,8 +45,8 @@ export function recordStep(store?: EditorStore): void {getRunState(store).currentSteps++}-export function resetRunSteps(store?: EditorStore): void {- getRunState(store).resetSteps()+export function resetRunSteps(store: EditorStore, maxSteps: number): void {+ getRunState(store).resetSteps(maxSteps)}export function didHitStepLimit(store?: EditorStore): boolean {@@ -63,12 +61,7 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnostregisterComponentCatalog(store.graph, libraryService)return toolsToAI(- [- ...CORE_TOOLS,- ...EXTENDED_TOOLS.filter((def) =>- ['get_components', 'list_libraries', 'insert_library_component'].includes(def.name)- )- ],+ aiToolDefinitions,{getFigma: () => makeFigmaFromStore(store),executeTool: async (def, figma, args) => {@@ -122,7 +115,7 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost},getStepBudget: (): StepBudget => ({current: runState.currentSteps,- max: MAX_AGENT_STEPS+ max: runState.maxSteps})},{ tool }diff --git a/src/app/ai/tools/preferences.ts b/src/app/ai/tools/preferences.tsnew file mode 100644index 000000000..d1b647bae--- /dev/null+++ b/src/app/ai/tools/preferences.ts@@ -0,0 +1,38 @@+import { useLocalStorage } from '@vueuse/core'+import * as v from 'valibot'+import { computed } from 'vue'++import { configurableAITools, isAIToolEnabled } from './catalog'++const overridesSchema = v.record(v.string(), v.boolean())++export const aiToolOverrides = useLocalStorage<Record<string, boolean>>(+ 'open-pencil:ai:tool-access',+ {},+ {+ serializer: {+ read: (raw) => {+ try {+ const result = v.safeParse(overridesSchema, JSON.parse(raw))+ return result.success ? result.output : {}+ } catch {+ return {}+ }+ },+ write: JSON.stringify+ }+ }+)++export const disabledAITools = computed({+ get: () =>+ configurableAITools+ .filter((tool) => !isAIToolEnabled(tool.name, aiToolOverrides.value))+ .map((tool) => tool.name),+ set: (names: string[]) => {+ const disabled = new Set(names)+ aiToolOverrides.value = Object.fromEntries(+ configurableAITools.map((tool) => [tool.name, !disabled.has(tool.name)])+ )+ }+})diff --git a/src/app/automation/mcp/failure.ts b/src/app/automation/mcp/failure.tsnew file mode 100644index 000000000..e0ca174b5--- /dev/null+++ b/src/app/automation/mcp/failure.ts@@ -0,0 +1,69 @@+/**+ * Name of the entry point installed by `@open-pencil/mcp`.+ *+ * Kept here rather than in the spawner so Settings can render the install+ * instruction without importing the spawning code.+ */+export const MCP_PACKAGE_NAME = '@open-pencil/mcp'++const APP_VERSION =+ typeof __OPENPENCIL_APP_VERSION__ === 'string' ? __OPENPENCIL_APP_VERSION__ : '0.0.0-test'++/** Exact package spec a user should install to match this app. */+export const MCP_INSTALL_TARGET = `${MCP_PACKAGE_NAME}@${APP_VERSION}`++/**+ * Why the local MCP server is unavailable.+ *+ * Codes stay in the domain so Settings can render translated, actionable copy.+ * Messages and stderr are diagnostic detail, never the user-facing heading.+ */+export type MCPFailureCode =+ | 'not-installed'+ | 'permission-denied'+ | 'exited'+ | 'timeout'+ | 'rejected'+ | 'malformed'+ | 'unreachable'+ | 'unknown'++export interface MCPFailure {+ code: MCPFailureCode+ /** Technical detail such as captured stderr or an HTTP status. Never translated. */+ detail?: string+}++/** Maximum diagnostic detail length retained for display. */+export const MCP_FAILURE_DETAIL_LIMIT = 400++export function mcpFailure(code: MCPFailureCode, detail?: string): MCPFailure {+ const trimmed = detail?.trim()+ return trimmed ? { code, detail: trimmed.slice(0, MCP_FAILURE_DETAIL_LIMIT) } : { code }+}++/** A startup error that already knows its reason code. */+export class MCPStartupError extends Error {+ constructor(+ message: string,+ readonly failure: MCPFailure+ ) {+ super(message)+ this.name = 'MCPStartupError'+ }+}++const PERMISSION_PATTERN = /not allowed|permission denied|forbidden|acl/i++/** Spawn failures only expose text, so the reason is derived once, in one place. */+export function classifySpawnFailure(error: unknown): MCPFailure {+ const message = error instanceof Error ? error.message : String(error)+ if (error instanceof MCPStartupError) return error.failure+ if (PERMISSION_PATTERN.test(message)) return mcpFailure('permission-denied', message)+ return mcpFailure('unknown', message)+}++export function failureFromError(error: unknown): MCPFailure {+ if (error instanceof MCPStartupError) return error.failure+ return classifySpawnFailure(error)+}diff --git a/src/app/automation/mcp/runtime.ts b/src/app/automation/mcp/runtime.tsindex a37470ae7..e98a9e634 100644--- a/src/app/automation/mcp/runtime.ts+++ b/src/app/automation/mcp/runtime.ts@@ -4,11 +4,14 @@ import { connectAutomation } from '@/app/automation/bridge/server'import type { EditorStore } from '@/app/editor/active-store'import { isTauri } from '@/app/tauri/env'+import { mcpFailure, type MCPFailure } from './failure'import { setMCPToolDescriptors } from './preferences'import {type AutomationHealth,type AutomationServerHandle,readAutomationHealth,+ getAutomationHealthFailure,+ getAutomationStartupFailure,getMCPServerURL,spawnMCPIfNeeded} from './spawn'@@ -19,7 +22,8 @@ export interface MCPRuntimeState {status: MCPRuntimeStatusendpoint: stringversion: string | null- error: string | null+ /** Structured reason the server is unavailable; Settings renders translated copy. */+ failure: MCPFailure | nullchecking: booleanexternallyManaged: boolean}@@ -32,6 +36,33 @@ export interface MCPRuntimeDependencies {readHealth: (authToken?: string | null) => Promise<AutomationHealth | null>setToolDescriptors: (tools: NonNullable<AutomationHealth['tools']>) => voidspawn: () => Promise<AutomationServerHandle | null>+ /** Diagnostics for the most recent spawn/health attempt. */+ getStartupFailure: () => MCPFailure | null+ getHealthFailure: () => MCPFailure | null+}++/**+ * Turn a failed startup into the reason the user can act on. The spawn layer+ * records the real cause; without it every failure reads as one generic message.+ */+function describeStartupFailure(+ dependencies: MCPRuntimeDependencies,+ spawned: AutomationServerHandle | null+): MCPFailure {+ const startupFailure = dependencies.getStartupFailure()+ if (!spawned && startupFailure) return startupFailure++ const healthFailure = dependencies.getHealthFailure()+ if (healthFailure?.code === 'rejected' || healthFailure?.code === 'malformed') {+ return healthFailure+ }+ if (startupFailure) return startupFailure+ return mcpFailure('unreachable', getMCPServerURL())+}++/** Technical summary for logs; the UI renders translated copy from the code. */+function failureDetail(failure: MCPFailure): string {+ return failure.detail ? `${failure.code}: ${failure.detail}` : failure.code}function toError(error: unknown): Error {@@ -43,7 +74,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {status: 'idle',endpoint: getMCPServerURL(),version: null,- error: null,+ failure: null,checking: false,externallyManaged: false})@@ -66,7 +97,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {state.version = health.version ?? nulldependencies.setToolDescriptors(health.tools ?? [])state.status = 'running'- state.error = null+ state.failure = null}async function refreshOperation(): Promise<MCPRuntimeResult> {@@ -84,7 +115,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {} catch (error) {const runtimeError = toError(error)state.status = 'error'- state.error = runtimeError.message+ state.failure = mcpFailure('unreachable', runtimeError.message)return { ok: false, error: runtimeError }} finally {state.checking = false@@ -106,27 +137,38 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {async function startOperation(): Promise<MCPRuntimeResult> {state.status = 'starting'- state.error = null+ state.failure = nullstate.externallyManaged = false+ let failure: MCPFailure | null = null+ let thrown: Error | null = nulltry {server = await dependencies.spawn()const health = await dependencies.readHealth(server?.authToken)- if (!health) throw new Error('MCP server did not become healthy')- state.externallyManaged = server?.managed === false- if (activeStore && dependencies.canConnect()) {- disconnectAutomation = dependencies.connect(activeStore, server?.authToken ?? null)+ if (health) {+ state.externallyManaged = server?.managed === false+ if (activeStore && dependencies.canConnect()) {+ disconnectAutomation = dependencies.connect(activeStore, server?.authToken ?? null)+ }+ applyHealth(health)+ return { ok: true }}- applyHealth(health)- return { ok: true }+ failure = describeStartupFailure(dependencies, server)} catch (error) {- const runtimeError = toError(error)- const disconnectError = await disconnectCurrentServer()- state.status = 'error'- state.error = disconnectError- ? `${runtimeError.message}. Cleanup failed: ${disconnectError.message}`- : runtimeError.message- console.warn('[MCP]', runtimeError)- return { ok: false, error: runtimeError }+ thrown = toError(error)+ failure = describeStartupFailure(dependencies, server)+ }++ const disconnectError = await disconnectCurrentServer()+ const detail = failureDetail(failure)+ state.status = 'error'+ state.failure = failure+ if (thrown) console.warn('[MCP]', detail, thrown)+ else console.warn('[MCP]', detail)+ return {+ ok: false,+ error: disconnectError+ ? new Error(`${detail}. Cleanup failed: ${disconnectError.message}`)+ : new Error(detail)}}@@ -135,7 +177,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {if (releaseStore) activeStore = nullstate.status = disconnectError ? 'error' : 'stopped'state.version = null- state.error = disconnectError?.message ?? null+ state.failure = disconnectError ? mcpFailure('unknown', disconnectError.message) : nullstate.externallyManaged = falsedependencies.setToolDescriptors([])return disconnectError ? { ok: false, error: disconnectError } : { ok: true }@@ -156,7 +198,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {if (!activeStore) {const error = new Error('Editor is not ready')state.status = 'error'- state.error = error.message+ state.failure = nullreturn { ok: false, error } as MCPRuntimeResult}return startOperation()@@ -169,7 +211,9 @@ const appMCPRuntime = createMCPRuntimeService({canConnect: () => import.meta.env.DEV || isTauri(),readHealth: readAutomationHealth,setToolDescriptors: setMCPToolDescriptors,- spawn: spawnMCPIfNeeded+ spawn: spawnMCPIfNeeded,+ getStartupFailure: getAutomationStartupFailure,+ getHealthFailure: getAutomationHealthFailure})export const mcpRuntime = appMCPRuntime.statediff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.tsindex 5f03dc7af..363f4f5ef 100644--- a/src/app/automation/mcp/spawn.ts+++ b/src/app/automation/mcp/spawn.ts@@ -14,6 +14,13 @@ import { resolvePlatformCommand } from '@/app/tauri/command'import { isTauri } from '@/app/tauri/env'import { DEV_MCP_RESTART_PATH, type DevMCPConfiguration } from './dev-control'+import {+ classifySpawnFailure,+ mcpFailure,+ MCP_INSTALL_TARGET,+ MCPStartupError,+ type MCPFailure+} from './failure'import { disabledMCPTools, mcpAuthenticationEnabled, mcpRootDirectory } from './preferences'export interface AutomationHealth {@@ -47,6 +54,12 @@ const APP_VERSION =const noop = () => undefinedconst MAX_STARTUP_STDERR_LENGTH = 8_192const MCP_EXECUTABLE = 'openpencil-mcp-http'++interface MCPLookup {+ available: boolean+ path: string | null+ searched: string[]+}// While no app is attached, the spawned server waits this long for a register// or reconnect before closing itself and removing its discovery file. This// prevents a server that outlives a crashed/reloaded app from squatting the@@ -64,19 +77,43 @@ const DEFAULT_STARTUP_TIMING: MCPStartupTiming = { earlyExitMs: 250, healthPollMlet runtimeAutomationAuthToken: string | null = DEV_AUTOMATION_AUTH_TOKENlet runtimeAutomationStartupError: Error | null = null+let runtimeAutomationStartupFailure: MCPFailure | null = null+let runtimeAutomationHealthFailure: MCPFailure | null = null++/**+ * The startup failure recorded by the most recent spawn attempt. Settings uses+ * this so a missing install, a rejected shell command, or a server that exited+ * is reported instead of a single generic health message.+ */+export function getAutomationStartupError(): Error | null {+ return runtimeAutomationStartupError+}++export function getAutomationStartupFailure(): MCPFailure | null {+ return runtimeAutomationStartupFailure+}++/** Why the most recent health probe failed. */+export function getAutomationHealthFailure(): MCPFailure | null {+ return runtimeAutomationHealthFailure+}function toError(error: unknown): Error {return error instanceof Error ? error : new Error(String(error))}-function missingMCPError(): Error {- return new Error(- `MCP automation is not installed. Install @open-pencil/mcp@${APP_VERSION} globally with your package manager, then restart OpenPencil.`+function missingMCPError(searched: string[] = []): Error {+ return new MCPStartupError(+ `MCP automation is not installed. Install ${MCP_INSTALL_TARGET} globally with your package manager, then restart OpenPencil.`,+ searched.length > 0+ ? mcpFailure('not-installed', searched.join(', '))+ : mcpFailure('not-installed'))}function rememberStartupError(error: unknown): null {runtimeAutomationStartupError = toError(error)+ runtimeAutomationStartupFailure = classifySpawnFailure(error)return null}@@ -250,9 +287,24 @@ export async function readAutomationHealth(headers,signal: AbortSignal.timeout(1000)})- if (!res.ok) return null- return parseAutomationHealth(await res.json())+ if (!res.ok) {+ // A running server that refuses our token needs a new token; any other+ // status means we are not talking to the server we expect.+ const rejectsCredentials = res.status === 401 || res.status === 403+ runtimeAutomationHealthFailure = rejectsCredentials+ ? mcpFailure('rejected', `HTTP ${res.status}`)+ : mcpFailure('malformed', `HTTP ${res.status}`)+ return null+ }+ const health = parseAutomationHealth(await res.json())+ if (!health) {+ runtimeAutomationHealthFailure = mcpFailure('malformed', `HTTP ${res.status}`)+ return null+ }+ runtimeAutomationHealthFailure = null+ return health} catch {+ runtimeAutomationHealthFailure = mcpFailure('unreachable', DEV_AUTOMATION_HTTP_URL)return null}}@@ -365,17 +417,25 @@ async function configureDevMCP(): Promise<AutomationServerHandle> {body: JSON.stringify(configuration)})if (!response.ok) {- throw new Error(`Failed to configure development MCP server (${response.status})`)+ throw new MCPStartupError(+ `Failed to configure development MCP server (${response.status})`,+ mcpFailure('unknown', `HTTP ${response.status}`)+ )}const authToken = configuration.authenticationEnabled ? DEV_AUTOMATION_AUTH_TOKEN : nullconst health = await pollHealth(10, 250, authToken)- if (!health) throw new Error('Development MCP server did not become healthy')+ if (!health)+ throw new MCPStartupError(+ 'Development MCP server did not become healthy',+ mcpFailure('timeout', `${DEV_AUTOMATION_HTTP_URL}/health`)+ )runtimeAutomationAuthToken = authTokenreturn { disconnect: noop, authToken, managed: true }}async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationServerHandle | null> {runtimeAutomationStartupError = null+ runtimeAutomationStartupFailure = nullif (import.meta.env.DEV) return configureDevMCP()if (!isTauri()) return null@@ -385,8 +445,8 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSer}const { invoke } = await import('@tauri-apps/api/core')- const executableAvailable = await invoke<boolean>('mcp_executable_available')- if (!executableAvailable) return rememberStartupError(missingMCPError())+ const lookup = await invoke<MCPLookup>('mcp_lookup')+ if (!lookup.available) return rememberStartupError(missingMCPError(lookup.searched))const authToken = mcpAuthenticationEnabled.value ? randomHex(32) : null// Cache only after MCP startup is confirmed healthy.@@ -441,8 +501,14 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSerif (earlyExit) {const details = startupStderr.trim()return rememberStartupError(- new Error(- `MCP server exited before startup completed (code ${earlyExit.code ?? 'null'}, signal ${earlyExit.signal ?? 'null'})${details ? `: ${details}` : '.'}`+ new MCPStartupError(+ `MCP server exited before startup completed (code ${earlyExit.code ?? 'null'}, signal ${earlyExit.signal ?? 'null'})${details ? `: ${details}` : '.'}`,+ mcpFailure(+ 'exited',+ [`code=${earlyExit.code ?? 'null'}`, `signal=${earlyExit.signal ?? 'null'}`, details]+ .filter(Boolean)+ .join(' ')+ )))}@@ -457,6 +523,7 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSerspawnedToken = tokenruntimeAutomationAuthToken = tokenruntimeAutomationStartupError = null+ runtimeAutomationStartupFailure = nullreturn {disconnect: async () => {await child.kill().catch((e) => {@@ -482,8 +549,9 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSerruntimeAutomationAuthToken = null}return rememberStartupError(- new Error(- `MCP server did not become healthy within the startup timeout${startupStderr.trim() ? `: ${startupStderr.trim()}` : '.'}`+ new MCPStartupError(+ `MCP server did not become healthy within the startup timeout${startupStderr.trim() ? `: ${startupStderr.trim()}` : '.'}`,+ mcpFailure('timeout', startupStderr)))}diff --git a/src/app/automation/mcp/settings/tool-access.ts b/src/app/automation/tool-access/settings/list.tssimilarity index 53%rename from src/app/automation/mcp/settings/tool-access.tsrename to src/app/automation/tool-access/settings/list.tsindex 1f3208b7d..22f703f37 100644--- a/src/app/automation/mcp/settings/tool-access.ts+++ b/src/app/automation/tool-access/settings/list.ts@@ -1,9 +1,9 @@-import { computed, ref, type Ref } from 'vue'+import { computed, ref, watch, type Ref } from 'vue'-import type { ToolDescriptor, ToolEffect } from '@open-pencil/mcp/tools'+import type { ToolAccessEntry } from '../types'/** Tool access is derived from the catalog and one controlled disabled-name model. */-export function useMCPToolAccess(tools: Readonly<Ref<ToolDescriptor[]>>, disabled: Ref<string[]>) {+export function useToolAccess(tools: Readonly<Ref<ToolAccessEntry[]>>, disabled: Ref<string[]>) {const search = ref('')const disabledNames = computed(() => new Set(disabled.value))const enabledCount = computed(() => tools.value.filter(isEnabled).length)@@ -15,7 +15,7 @@ export function useMCPToolAccess(tools: Readonly<Ref<ToolDescriptor[]>>, disable)})- function isEnabled(tool: ToolDescriptor) {+ function isEnabled(tool: ToolAccessEntry) {return !disabledNames.value.has(tool.name)}@@ -28,7 +28,7 @@ export function useMCPToolAccess(tools: Readonly<Ref<ToolDescriptor[]>>, disabledisabled.value = [...next]}- function category(effect: ToolEffect) {+ function category(effect: ToolAccessEntry['effect']) {const members = computed(() => tools.value.filter((tool) => tool.effect === effect))const count = computed(() => members.value.filter(isEnabled).length)return {@@ -40,23 +40,41 @@ export function useMCPToolAccess(tools: Readonly<Ref<ToolDescriptor[]>>, disableenabled)}),- state: computed(() =>+ state: computed<'mixed' | 'idle'>(() =>count.value > 0 && count.value < members.value.length ? 'mixed' : 'idle')}}- const { enabled: inspectionEnabled, state: inspectionState } = category('read')- const { enabled: modificationEnabled, state: modificationState } = category('write')+ const inspection = category('read')+ const modification = category('write')+ const expanded = ref({ read: true, write: true })+ watch(search, () => {+ expanded.value = { read: true, write: true }+ })+ const categories = { read: inspection, write: modification }+ const groups = computed(() =>+ (['read', 'write'] as const).map((effect) => ({+ effect,+ enabled: categories[effect].enabled.value,+ state: categories[effect].state.value,+ tools: visibleTools.value.filter((tool) => tool.effect === effect)+ }))+ )return {search,visibleTools,enabledCount,- inspectionEnabled,- inspectionState,- modificationEnabled,- modificationState,+ groups,+ expanded,+ inspectionEnabled: inspection.enabled,+ inspectionState: inspection.state,+ modificationEnabled: modification.enabled,+ modificationState: modification.state,+ setGroupEnabled: (effect: ToolAccessEntry['effect'], enabled: boolean) => {+ categories[effect].enabled.value = enabled+ },isEnabled,setToolEnabled: (name: string, enabled: boolean) => setEnabled([name], enabled)}diff --git a/src/app/automation/tool-access/settings/use.ts b/src/app/automation/tool-access/settings/use.tsnew file mode 100644index 000000000..59636ce0d--- /dev/null+++ b/src/app/automation/tool-access/settings/use.ts@@ -0,0 +1,39 @@+import { computed, ref } from 'vue'++import { configurableAITools } from '@/app/ai/tools/catalog'+import { aiToolOverrides, disabledAITools } from '@/app/ai/tools/preferences'+import { configurableMCPTools, disabledMCPTools } from '@/app/automation/mcp/preferences'+import { openSettingsDialog } from '@/app/settings/dialog'++import type { ToolAccessTarget } from '../types'++const target = ref<ToolAccessTarget>('ai')++export function openToolAccessSettings(value: ToolAccessTarget) {+ target.value = value+ openSettingsDialog('tools')+}++export function useToolAccessSettings() {+ const tools = computed(() =>+ target.value === 'ai' ? configurableAITools : configurableMCPTools.value+ )+ const disabled = computed({+ get: () => (target.value === 'ai' ? disabledAITools.value : disabledMCPTools.value),+ set: (names: string[]) => {+ if (target.value === 'ai') disabledAITools.value = names+ else disabledMCPTools.value = names+ }+ })++ function selectTarget(value: string) {+ if (value === 'ai' || value === 'mcp') target.value = value+ }++ function reset() {+ if (target.value === 'ai') aiToolOverrides.value = {}+ else disabledMCPTools.value = []+ }++ return { target, tools, disabled, selectTarget, reset }+}diff --git a/src/app/automation/tool-access/types.ts b/src/app/automation/tool-access/types.tsnew file mode 100644index 000000000..debc7169b--- /dev/null+++ b/src/app/automation/tool-access/types.ts@@ -0,0 +1,15 @@+import type { ToolDescriptor } from '@open-pencil/mcp/tools'++/** The presentation contract shared by local AI and discovered MCP tools. */+export type ToolAccessEntry = Pick<ToolDescriptor, 'name' | 'description' | 'effect'>++export type ToolAccessTarget = 'ai' | 'mcp'++/** One catalog group as presented to the settings UI, including its translated label. */+export type ToolAccessGroup = {+ effect: ToolAccessEntry['effect']+ label: string+ enabled: boolean+ state: 'mixed' | 'idle'+ tools: ToolAccessEntry[]+}diff --git a/src/app/diagnostics/settings.ts b/src/app/diagnostics/settings.tsindex 74f5b5fe7..1d9a07547 100644--- a/src/app/diagnostics/settings.ts+++ b/src/app/diagnostics/settings.ts@@ -1,23 +1,42 @@import { useLocalStorage } from '@vueuse/core'import { computed, ref } from 'vue'-export type DiagnosticsRetention = 100 | 500 | 1000+/**+ * Number of most recent events kept locally. Bounded rather than a closed set+ * so retention can be tuned beyond the offered presets.+ */+export type DiagnosticsRetention = number++/** Offered directly in Settings; any value in range is accepted. */+export const diagnosticsRetentionPresets = [100, 500, 1000] as const++export const DIAGNOSTICS_RETENTION_DEFAULT: DiagnosticsRetention = 500+export const DIAGNOSTICS_RETENTION_MIN = 50+export const DIAGNOSTICS_RETENTION_MAX = 20_000++/** Clamp stored or entered values, falling back to the default when unusable. */+export function resolveDiagnosticsRetention(value: unknown): DiagnosticsRetention {+ // An empty or non-numeric stored value is unusable rather than a small number,+ // so it falls back to the default instead of clamping down to the minimum.+ const parsed =+ typeof value === 'string' ? (value.trim() === '' ? Number.NaN : Number(value)) : value+ if (typeof parsed !== 'number' || !Number.isFinite(parsed)) {+ return DIAGNOSTICS_RETENTION_DEFAULT+ }+ const whole = Math.round(parsed)+ return Math.min(Math.max(whole, DIAGNOSTICS_RETENTION_MIN), DIAGNOSTICS_RETENTION_MAX)+}const diagnosticsEnabled = useLocalStorage('open-pencil:diagnostics-enabled', true)const usageEnabled = useLocalStorage('open-pencil:usage-enabled', true)const diagnosticsRetention = useLocalStorage<DiagnosticsRetention>('open-pencil:diagnostics-retention',500,- { serializer: { read: (value) => normalizeRetention(value), write: String } }+ { serializer: { read: (value) => resolveDiagnosticsRetention(value), write: String } })const diagnosticsCount = ref(0)const diagnosticsSize = ref(0)-function normalizeRetention(value: string): DiagnosticsRetention {- const parsed = Number(value)- return parsed === 100 || parsed === 1000 ? parsed : 500-}-export function useDiagnosticsSettings() {return {diagnosticsEnabled,@@ -51,4 +70,4 @@ export async function pruneDiagnostics(retention: DiagnosticsRetention): Promiseawait diagnostics.prune(retention)}-export const diagnosticsRetentionOptions = computed(() => [100, 500, 1000] as const)+export const diagnosticsRetentionOptions = computed(() => diagnosticsRetentionPresets)diff --git a/src/app/settings/dialog.ts b/src/app/settings/dialog.tsindex 80f9d81dd..36c1bbcf2 100644--- a/src/app/settings/dialog.ts+++ b/src/app/settings/dialog.ts@@ -6,6 +6,7 @@ export type SettingsSection =| 'usage'| 'diagnostics'| 'mcp'+ | 'tools'| 'media'| 'storage'diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex 1fb016957..9006e71a3 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -2,6 +2,8 @@ import { useLocalStorage } from '@vueuse/core'import { DEFAULT_SNAPPING_PREFERENCES, type SnappingPreferences } from '@open-pencil/core/editor'+import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'+export type AnimationPreference = 'system' | 'off'export type ReasoningDisplay = 'collapsed' | 'while-thinking' | 'expanded'@@ -10,7 +12,7 @@ export type CanvasRenderingMode = 'retained' | 'tiled'export interface AppPreferences {appearance: { animations: AnimationPreference }- chat: { reasoningDisplay: ReasoningDisplay }+ chat: { reasoningDisplay: ReasoningDisplay; maxAgentSteps: number }version: 1recovery: {enabled: boolean@@ -25,7 +27,7 @@ export interface AppPreferences {export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {appearance: { animations: 'system' },- chat: { reasoningDisplay: 'collapsed' },+ chat: { reasoningDisplay: 'collapsed', maxAgentSteps: DEFAULT_AGENT_STEPS },version: 1,recovery: { enabled: true },editing: {@@ -48,7 +50,7 @@ interface StoredSnappingPreferences {interface StoredAppPreferences {appearance?: { animations?: unknown }- chat?: { reasoningDisplay?: unknown }+ chat?: { reasoningDisplay?: unknown; maxAgentSteps?: unknown }recovery?: { enabled?: unknown }editing?: { snapping?: StoredSnappingPreferences }rendering?: { canvasMode?: unknown }@@ -62,19 +64,23 @@ function normalizeAnimationPreference(value: unknown): AnimationPreference {return value === 'off' ? 'off' : 'system'}+function normalizeChatPreferences(chat: StoredAppPreferences['chat']): AppPreferences['chat'] {+ return {+ maxAgentSteps: resolveAgentStepLimit(chat?.maxAgentSteps),+ reasoningDisplay:+ chat?.reasoningDisplay === 'expanded' || chat?.reasoningDisplay === 'while-thinking'+ ? chat.reasoningDisplay+ : 'collapsed'+ }+}+function normalizePreferences(value: unknown): AppPreferences {const stored = isStoredAppPreferences(value) ? value : undefinedconst snapping = stored?.editing?.snappingreturn {appearance: { animations: normalizeAnimationPreference(stored?.appearance?.animations) },- chat: {- reasoningDisplay:- stored?.chat?.reasoningDisplay === 'expanded' ||- stored?.chat?.reasoningDisplay === 'while-thinking'- ? stored.chat.reasoningDisplay- : 'collapsed'- },+ chat: normalizeChatPreferences(stored?.chat),version: 1,recovery: {enabled: booleanOrDefault(stored?.recovery?.enabled, DEFAULT_APP_PREFERENCES.recovery.enabled)diff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vueindex 81dd68571..5bffb4f63 100644--- a/src/components/settings/SettingsDialog.vue+++ b/src/components/settings/SettingsDialog.vue@@ -20,6 +20,7 @@ import MCPWorkspacePanel from '@/components/settings/mcp/MCPWorkspacePanel.vue'import MediaSettingsPanel from '@/components/settings/media/MediaSettingsPanel.vue'import ModelsPanel from '@/components/settings/models/ModelsPanel.vue'import StorageSettingsPanel from '@/components/settings/storage/StorageSettingsPanel.vue'+import ToolAccessSettingsPanel from '@/components/settings/tool-access/ToolAccessSettingsPanel.vue'import UsageSettingsPanel from '@/components/settings/usage/UsageSettingsPanel.vue'import AppButton from '@/components/ui/button/AppButton.vue'import {@@ -46,7 +47,8 @@ const sections = computed({ value: 'ai', label: settings.value.aiAndAgents },{ value: 'usage', label: settings.value.usage },{ value: 'diagnostics', label: settings.value.diagnostics },- { value: 'mcp', label: settings.value.automation },+ { value: 'mcp', label: settings.value.mcp },+ { value: 'tools', label: settings.value.toolAccess },{ value: 'media', label: settings.value.media },{ value: 'storage', label: settings.value.storage }] satisfies { value: SettingsSection; label: string }[]@@ -115,7 +117,11 @@ function onOpenChange(open: boolean): void {</AppTabsTrigger><AppTabsTrigger value="mcp" data-test-id="settings-section-mcp"><template #leading><icon-lucide-plug class="size-3.5" /></template>- {{ settings.automation }}+ {{ settings.mcp }}+ </AppTabsTrigger>+ <AppTabsTrigger value="tools" data-test-id="settings-section-tools">+ <template #leading><icon-lucide-sliders-horizontal class="size-3.5" /></template>+ {{ settings.toolAccess }}</AppTabsTrigger><AppTabsTrigger value="media" data-test-id="settings-section-media"><template #leading><icon-lucide-image class="size-3.5" /></template>@@ -146,6 +152,9 @@ function onOpenChange(open: boolean): void {<AppTabsContent value="mcp" as-child><MCPWorkspacePanel /></AppTabsContent>+ <AppTabsContent value="tools" as-child>+ <ToolAccessSettingsPanel />+ </AppTabsContent><AppTabsContent value="media" as-child><MediaSettingsPanel /></AppTabsContent>diff --git a/src/components/settings/chat/ChatSettingsSection.vue b/src/components/settings/chat/ChatSettingsSection.vueindex 6dd5929e7..67b686788 100644--- a/src/components/settings/chat/ChatSettingsSection.vue+++ b/src/components/settings/chat/ChatSettingsSection.vue@@ -3,13 +3,21 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'-import { reasoningDisplay } from '@/app/ai/chat/preferences'+import { maxAgentSteps, reasoningDisplay } from '@/app/ai/chat/preferences'+import { AGENT_STEP_LIMIT_MIN, AGENT_STEP_LIMIT_MAX } from '@/app/ai/chat/step-limit'+import { openToolAccessSettings } from '@/app/automation/tool-access/settings/use'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsRow from '@/components/settings/layout/SettingsRow.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import PresetNumberField from '@/components/ui/input/PresetNumberField.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'-const { ai } = useI18n()+const { ai, settings } = useI18n()+const stepPresets = [25, 50, 100, 200]+const limitMessage = computed(() =>+ ai.value.maxAgentStepsRange({ min: AGENT_STEP_LIMIT_MIN, max: AGENT_STEP_LIMIT_MAX })+)const options = computed(() => [{ value: 'collapsed' as const, label: ai.value.reasoningCollapsed },{ value: 'while-thinking' as const, label: ai.value.reasoningWhileThinking },@@ -29,6 +37,28 @@ const options = computed(() => [:ui="{ trigger: 'w-full sm:w-52' }"/></SettingsRow>+ <SettingsRow+ :label="ai.maxAgentSteps"+ :description="ai.maxAgentStepsHint"+ class="max-sm:flex-col max-sm:items-stretch"+ >+ <PresetNumberField+ v-model:number="maxAgentSteps"+ :presets="stepPresets"+ :min="AGENT_STEP_LIMIT_MIN"+ :max="AGENT_STEP_LIMIT_MAX"+ :label="ai.maxAgentSteps"+ :custom-label="ai.maxAgentStepsCustom"+ :range-message="limitMessage"+ />+ </SettingsRow>+ </SettingsGroup>+ <SettingsGroup>+ <SettingsRow :label="settings.toolAccess">+ <AppButton size="xs" variant="outline" @click="openToolAccessSettings('ai')">{{+ settings.toolAccess+ }}</AppButton>+ </SettingsRow></SettingsGroup></SettingsSection></template>diff --git a/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue b/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vueindex c743d9f1c..f12169abc 100644--- a/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue+++ b/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue@@ -5,27 +5,24 @@ import { useI18n } from '@open-pencil/vue'import { diagnostics, summarizeDiagnosticEvent } from '@/app/diagnostics'import {- diagnosticsRetentionOptions,+ DIAGNOSTICS_RETENTION_MAX,+ DIAGNOSTICS_RETENTION_MIN,+ diagnosticsRetentionPresets,pruneDiagnostics,useDiagnosticsSettings} from '@/app/diagnostics/settings'import { useRecentDiagnostics } from '@/app/diagnostics/settings/recent'import { toast } from '@/app/shell/ui'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsRow from '@/components/settings/layout/SettingsRow.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import AppButton from '@/components/ui/button/AppButton.vue'import { AppConfirmationDialog } from '@/components/ui/dialog'-import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'+import PresetNumberField from '@/components/ui/input/PresetNumberField.vue'import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'const { common, diagnostics: diagnosticMessages } = useI18n()const clearOpen = ref(false)-const retentionOptions = computed(() =>- diagnosticsRetentionOptions.value.map((value) => ({- value: String(value),- label: String(value)- }))-)const {diagnosticsEnabled,@@ -40,18 +37,19 @@ const { recentEvents } = useRecentDiagnostics(refreshDiagnosticsStats)-const retentionValue = computed<string>({- get: () => String(diagnosticsRetention.value),+const retentionValue = computed({+ get: () => diagnosticsRetention.value,set: (value) => {- const parsed = Number(value)- if (parsed === 100 || parsed === 500 || parsed === 1000) {- diagnosticsRetention.value = parsed- void pruneDiagnostics(parsed)- void refreshDiagnosticsStats()- }+ diagnosticsRetention.value = value}})+/** Retention is a stored policy change, so pruning follows the committed value. */+async function commitRetention(value: number): Promise<void> {+ await pruneDiagnostics(value)+ await refreshDiagnosticsStats()+}+async function clearDiagnostics() {await diagnostics.clear()await refreshDiagnosticsStats()@@ -93,20 +91,27 @@ async function exportDiagnostics() {><AppSwitch v-model="usageEnabled" :label="diagnosticMessages.usageHistory" /></label>- <div class="flex items-center justify-between gap-4 px-3 py-2.5">- <span- ><span class="block text-xs text-surface">{{ diagnosticMessages.retention }}</span- ><span class="block text-[10px] text-muted">{{- diagnosticMessages.retentionDescription- }}</span></span- >- <SegmentedControl- v-model="retentionValue"- :options="retentionOptions"+ <SettingsRow+ :label="diagnosticMessages.retention"+ :description="diagnosticMessages.retentionDescription"+ class="max-sm:flex-col max-sm:items-stretch"+ >+ <PresetNumberField+ v-model:number="retentionValue"+ :presets="diagnosticsRetentionPresets"+ :min="DIAGNOSTICS_RETENTION_MIN"+ :max="DIAGNOSTICS_RETENTION_MAX":label="diagnosticMessages.retention"- required+ :custom-label="diagnosticMessages.retentionCustom"+ :range-message="+ diagnosticMessages.retentionRange({+ min: DIAGNOSTICS_RETENTION_MIN,+ max: DIAGNOSTICS_RETENTION_MAX+ })+ "+ @commit="commitRetention"/>- </div>+ </SettingsRow></SettingsGroup><SettingsGroup v-if="recentEvents.length"><divdiff --git a/src/components/settings/layout/SettingsDisclosure.vue b/src/components/settings/layout/SettingsDisclosure.vueindex 86fa05d3d..8448bfe73 100644--- a/src/components/settings/layout/SettingsDisclosure.vue+++ b/src/components/settings/layout/SettingsDisclosure.vue@@ -1,23 +1,13 @@<script setup lang="ts">-import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'--import { settingsDisclosureMotion } from '@/theme/settings/disclosure'+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'const open = defineModel<boolean>('open', { default: false })</script><template>- <CollapsibleRoot v-model:open="open">- <CollapsibleTrigger- class="group flex w-full items-center gap-2 py-3 text-left text-xs text-surface"- >- <icon-lucide-chevron-right- class="size-3.5 shrink-0 transition-transform group-data-[state=open]:rotate-90 motion-reduce:transition-none"- />- <slot name="label" />- </CollapsibleTrigger>- <CollapsibleContent :class="settingsDisclosureMotion">- <div class="pb-3"><slot /></div>- </CollapsibleContent>- </CollapsibleRoot>+ <AppCollapsible v-model:open="open" :ui="{ trigger: 'py-3' }">+ <template #label><slot name="label" /></template>+ <template v-if="$slots.actions" #actions><slot name="actions" /></template>+ <div class="pb-3"><slot /></div>+ </AppCollapsible></template>diff --git a/src/components/settings/mcp/MCPFailureAlert.stories.ts b/src/components/settings/mcp/MCPFailureAlert.stories.tsnew file mode 100644index 000000000..2f981242e--- /dev/null+++ b/src/components/settings/mcp/MCPFailureAlert.stories.ts@@ -0,0 +1,79 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'++import type { MCPFailure, MCPFailureCode } from '@/app/automation/mcp/failure'++import MCPFailureAlert from './MCPFailureAlert.vue'++/** One representative failure per reason, mirroring what each path records. */+const reasons: Record<MCPFailureCode, MCPFailure> = {+ 'not-installed': {+ code: 'not-installed',+ detail: '/opt/homebrew/bin, /usr/local/bin, /Users/you/.bun/bin'+ },+ 'permission-denied': {+ code: 'permission-denied',+ detail: 'shell command openpencil-mcp-http not allowed by ACL'+ },+ exited: {+ code: 'exited',+ detail: 'Error: listen EADDRINUSE: address already in use 127.0.0.1:7600'+ },+ timeout: { code: 'timeout', detail: 'no health response from http://127.0.0.1:7600/health' },+ rejected: { code: 'rejected', detail: 'HTTP 401' },+ malformed: { code: 'malformed', detail: 'HTTP 200' },+ unreachable: { code: 'unreachable', detail: 'http://127.0.0.1:7600/mcp' },+ unknown: { code: 'unknown', detail: 'Failed to fetch' }+}++const meta = {+ title: 'Settings/MCP/Failure alert',+ component: MCPFailureAlert,+ args: { failure: reasons.timeout, restarting: false, externallyManaged: false },+ render: (args) => ({+ components: { MCPFailureAlert },+ setup: () => ({ args }),+ template: `+ <div class="max-w-xl bg-panel p-4 text-surface">+ <MCPFailureAlert+ :failure="args.failure"+ :restarting="args.restarting"+ :externally-managed="args.externallyManaged"+ />+ </div>`+ })+} satisfies Meta<{ failure: MCPFailure; restarting: boolean; externallyManaged: boolean }>++export default meta+type Story = StoryObj<typeof meta>++export const StartupTimeout: Story = {}+export const NotInstalled: Story = { args: { failure: reasons['not-installed'] } }+export const RejectedToken: Story = { args: { failure: reasons.rejected } }+export const Unreachable: Story = { args: { failure: reasons.unreachable } }+export const InternallyManaged: Story = { args: { restarting: true } }+export const ExternallyManaged: Story = { args: { externallyManaged: true } }++/** Every reason side by side: copy, guidance, and whether detail is offered. */+export const AllReasons: Story = {+ render: () => ({+ components: { MCPFailureAlert },+ setup: () => ({ failures: Object.values(reasons) }),+ template: `+ <div class="flex max-w-xl flex-col gap-3 bg-panel p-4 text-surface">+ <MCPFailureAlert v-for="failure in failures" :key="failure.code" :failure="failure" />+ </div>`+ })+}++export const DetailsExpandOnDemand: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ // Collapsed payloads stay unmounted, so the alert announces only its summary.+ await expect(canvas.queryByTestId('settings-mcp-failure-detail')).toBeNull()+ const trigger = canvas.getByRole('button', { name: 'Details' })+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ await userEvent.click(trigger)+ await expect(canvas.getByTestId('settings-mcp-failure-detail')).toBeVisible()+ }+}diff --git a/src/components/settings/mcp/MCPFailureAlert.vue b/src/components/settings/mcp/MCPFailureAlert.vuenew file mode 100644index 000000000..b4a8f0040--- /dev/null+++ b/src/components/settings/mcp/MCPFailureAlert.vue@@ -0,0 +1,120 @@+<script setup lang="ts">+import { useClipboard } from '@vueuse/core'+import { computed, ref } from 'vue'++import { useAutomationMessages } from '@open-pencil/vue'++import {+ MCP_INSTALL_TARGET,+ type MCPFailure,+ type MCPFailureCode+} from '@/app/automation/mcp/failure'+import { toast } from '@/app/shell/ui'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'++const {+ failure,+ restarting = false,+ externallyManaged = false+} = defineProps<{+ failure: MCPFailure+ restarting?: boolean+ externallyManaged?: boolean+}>()+const emit = defineEmits<{ restart: [] }>()++const automation = useAutomationMessages()+const { copy } = useClipboard()+const detailsOpen = ref(false)++/** Translated copy for each reason; the technical detail stays secondary. */+const copy$ = computed(() => {+ const messages = automation.value+ const map: Record<MCPFailureCode, { heading: string; description: string }> = {+ 'not-installed': {+ heading: messages.mcpFailureNotInstalled,+ description: messages.mcpFailureNotInstalledHint({ package: MCP_INSTALL_TARGET })+ },+ 'permission-denied': {+ heading: messages.mcpFailurePermission,+ description: messages.mcpFailurePermissionHint+ },+ exited: { heading: messages.mcpFailureExited, description: messages.mcpFailureExitedHint },+ timeout: { heading: messages.mcpFailureTimeout, description: messages.mcpFailureTimeoutHint },+ rejected: {+ heading: messages.mcpFailureRejected,+ description: messages.mcpFailureRejectedHint+ },+ malformed: {+ heading: messages.mcpFailureMalformed,+ description: messages.mcpFailureMalformedHint+ },+ unreachable: {+ heading: messages.mcpFailureUnreachable,+ description: messages.mcpFailureUnreachableHint({+ endpoint: failure.detail ?? 'the local server'+ })+ },+ unknown: { heading: messages.mcpFailureUnknown, description: messages.mcpFailureUnknownHint }+ }+ return map[failure.code]+})++/**+ * Reasons whose cause already appears in the guidance, so repeating the same+ * value under Details would only add noise.+ */+const EXPLAINED_REASONS: ReadonlySet<MCPFailureCode> = new Set(['rejected', 'unreachable'])++const detail = computed(() =>+ EXPLAINED_REASONS.has(failure.code) ? null : failure.detail?.trim() || null+)++async function copyDetails(): Promise<void> {+ const payload = [`code=${failure.code}`, failure.detail ? `detail=${failure.detail}` : null]+ .filter(Boolean)+ .join('\n')+ // VueUse falls back to a legacy write and never rejects, so awaiting the write+ // is what keeps the confirmation honest.+ await copy(payload)+ toast.info(automation.value.mcpFailureCopied)+}+</script>++<template>+ <AppAlert+ tone="error"+ :heading="copy$.heading"+ :description="copy$.description"+ data-test-id="settings-mcp-failure"+ >+ <template v-if="detail" #details>+ <AppCollapsible+ v-model:open="detailsOpen"+ :label="automation.mcpFailureDetails"+ :ui="{ trigger: 'text-muted hover:text-surface', content: 'mt-1' }"+ data-test-id="settings-mcp-failure-details"+ >+ <pre+ class="max-h-40 overflow-auto rounded border border-border bg-input p-2 font-mono text-[11px] whitespace-pre-wrap text-muted"+ data-test-id="settings-mcp-failure-detail"+ >{{ detail }}</pre>+ </AppCollapsible>+ </template>+ <template #actions>+ <AppButton size="xs" variant="outline" @click="copyDetails">{{+ automation.mcpFailureCopy+ }}</AppButton>+ <AppButton+ size="xs"+ variant="outline"+ :disabled="externallyManaged"+ :loading="restarting"+ @click="emit('restart')"+ >{{ externallyManaged ? automation.externallyManaged : automation.restart }}</AppButton+ >+ </template>+ </AppAlert>+</template>diff --git a/src/components/settings/mcp/MCPSettingsPanel.vue b/src/components/settings/mcp/MCPSettingsPanel.vueindex c34957b18..1adccd411 100644--- a/src/components/settings/mcp/MCPSettingsPanel.vue+++ b/src/components/settings/mcp/MCPSettingsPanel.vue@@ -2,28 +2,23 @@import { useClipboard } from '@vueuse/core'import { computed } from 'vue'-import { useAutomationMessages, useCommonMessages } from '@open-pencil/vue'+import { useAutomationMessages, useCommonMessages, useSettingsMessages } from '@open-pencil/vue'-import {- configurableMCPTools,- disabledMCPTools,- mcpAuthenticationEnabled,- mcpRootDirectory-} from '@/app/automation/mcp/preferences'+import { mcpAuthenticationEnabled, mcpRootDirectory } from '@/app/automation/mcp/preferences'import { mcpRuntime } from '@/app/automation/mcp/runtime'import { useMCPSettings } from '@/app/automation/mcp/settings/use'+import { openToolAccessSettings } from '@/app/automation/tool-access/settings/use'import { isTauri } from '@/app/tauri/env'-import SettingsDisclosure from '@/components/settings/layout/SettingsDisclosure.vue'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsRow from '@/components/settings/layout/SettingsRow.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import AppButton from '@/components/ui/button/AppButton.vue'-import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'-import MCPToolAccessPanel from './MCPToolAccessPanel.vue'+import MCPFailureAlert from './MCPFailureAlert.vue'const automation = useAutomationMessages()+const settings = useSettingsMessages()const common = useCommonMessages()const { copy, copied } = useClipboard()const statusMessage = computed(@@ -98,20 +93,20 @@ const { restart, chooseRootDirectory } = useMCPSettings()</div></div></SettingsGroup>- <AppAlert v-if="mcpRuntime.error" tone="error" :heading="mcpRuntime.error" />- <SettingsDisclosure>- <template #label>{{ automation.tools }}</template>- <MCPToolAccessPanel v-model:disabled-tools="disabledMCPTools" :tools="configurableMCPTools">- <template #footer>- {{- mcpRuntime.externallyManaged- ? automation.externalRestartNotice- : automation.toolsRestartNotice- }}- </template>- </MCPToolAccessPanel>- </SettingsDisclosure>+ <MCPFailureAlert+ v-if="mcpRuntime.failure"+ :failure="mcpRuntime.failure"+ :restarting="mcpRuntime.status === 'starting' || mcpRuntime.checking"+ :externally-managed="mcpRuntime.externallyManaged"+ @restart="restart"+ /><div>+ <AppButton variant="link" @click="openToolAccessSettings('mcp')">{{+ settings.toolAccess+ }}</AppButton>+ </div>+ <!-- The failure alert carries its own restart action. -->+ <div v-if="!mcpRuntime.failure"><AppButtoncolor="primary"variant="solid"diff --git a/src/components/settings/mcp/MCPToolAccessPanel.stories.ts b/src/components/settings/mcp/MCPToolAccessPanel.stories.tsdeleted file mode 100644index 9a3887e1f..000000000--- a/src/components/settings/mcp/MCPToolAccessPanel.stories.ts+++ /dev/null@@ -1,57 +0,0 @@-import type { Meta, StoryObj } from '@storybook/vue3-vite'-import { expect, userEvent, within } from 'storybook/test'-import { ref } from 'vue'--import type { ToolDescriptor } from '@open-pencil/mcp/tools'-import { useAutomationMessages } from '@open-pencil/vue'--import MCPToolAccessPanel from './MCPToolAccessPanel.vue'--const tools: ToolDescriptor[] = Array.from({ length: 80 }, (_, index) => ({- name: `inspect_component_${index + 1}`,- description:- 'Inspect a component and its properties in the active document. Narrow the selection to inspect fewer layers.',- effect: 'read',- availability: 'default',- capabilities: ['document:read'],- enabled: true-}))-const meta = {- title: 'Settings/MCP/Tool access',- args: { tools, disabledTools: [], externallyManaged: false },- render: (args) => ({- components: { MCPToolAccessPanel },- setup: () => ({- args,- disabled: ref([...args.disabledTools]),- automation: useAutomationMessages()- }),- template: `- <div class="flex h-96 max-w-lg bg-panel">- <MCPToolAccessPanel :tools="args.tools" v-model:disabled-tools="disabled">- <template #footer>{{ args.externallyManaged ? automation.externalRestartNotice : automation.toolsRestartNotice }}</template>- </MCPToolAccessPanel>- </div>`- })-} satisfies Meta<{ tools: ToolDescriptor[]; disabledTools: string[]; externallyManaged: boolean }>-export default meta-type Story = StoryObj<typeof meta>-export const LongCatalog: Story = {}-export const MixedAccess: Story = { args: { disabledTools: ['inspect_component_1'] } }-export const EmptySearch: Story = {- play: async ({ canvasElement }) => {- const canvas = within(canvasElement)- await userEvent.type(canvas.getByRole('searchbox'), 'no-matching-tool')- await expect(canvas.getByText('No tools match your search.')).toBeVisible()- }-}-export const ExternallyManaged: Story = { args: { externallyManaged: true } }-export const ToggleAccess: Story = {- play: async ({ canvasElement }) => {- const canvas = within(canvasElement)- await userEvent.click(canvas.getByRole('switch', { name: 'inspect_component_1' }))- await expect(canvas.getByText('79 of 80 enabled')).toBeVisible()- await userEvent.click(canvas.getByRole('button', { name: 'Enable all' }))- await expect(canvas.getByText('80 of 80 enabled')).toBeVisible()- }-}diff --git a/src/components/settings/mcp/MCPToolAccessPanel.vue b/src/components/settings/mcp/MCPToolAccessPanel.vuedeleted file mode 100644index 83ab6bac2..000000000--- a/src/components/settings/mcp/MCPToolAccessPanel.vue+++ /dev/null@@ -1,96 +0,0 @@-<script setup lang="ts">-import { toRef } from 'vue'--import type { ToolDescriptor } from '@open-pencil/mcp/tools'-import { useAutomationMessages, useCommonMessages } from '@open-pencil/vue'--import { useMCPToolAccess } from '@/app/automation/mcp/settings/tool-access'-import SettingsRow from '@/components/settings/layout/SettingsRow.vue'-import AppButton from '@/components/ui/button/AppButton.vue'-import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'-import AppInput from '@/components/ui/input/AppInput.vue'-import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'--const { tools } = defineProps<{ tools: ToolDescriptor[] }>()-const disabledTools = defineModel<string[]>('disabledTools', { required: true })-const {- search,- visibleTools,- enabledCount,- inspectionEnabled,- inspectionState,- modificationEnabled,- modificationState,- isEnabled,- setToolEnabled-} = useMCPToolAccess(- toRef(() => tools),- disabledTools-)-const automation = useAutomationMessages()-const common = useCommonMessages()-</script>--<template>- <div class="flex flex-col" data-slot="mcp-tool-access">- <div class="flex shrink-0 items-center justify-between gap-3 border-b border-border p-3">- <div class="min-w-0 flex-1">- <h3 class="text-xs font-semibold text-surface">{{ automation.tools }}</h3>- <p class="mt-1 text-xs text-muted">- {{ automation.toolsEnabled({ enabled: enabledCount, total: tools.length }) }}- </p>- </div>- <AppButton v-if="disabledTools.length" size="xs" variant="link" @click="disabledTools = []">{{- automation.enableAllTools- }}</AppButton>- </div>- <div class="sticky top-0 z-10 border-b border-border bg-panel p-3">- <AppInput- v-model="search"- type="search"- :placeholder="common.search"- :aria-label="automation.searchTools"- data-test-id="settings-mcp-tool-search"- />- </div>- <div class="divide-y divide-border border-b border-border">- <SettingsRow :label="automation.readOnlyTools">- <AppSwitch- v-model="inspectionEnabled"- :state="inspectionState"- :label="automation.readOnlyTools"- data-test-id="settings-mcp-inspection-tools"- />- </SettingsRow>- <SettingsRow :label="automation.sideEffectTools">- <AppSwitch- v-model="modificationEnabled"- :state="modificationState"- :label="automation.sideEffectTools"- data-test-id="settings-mcp-modification-tools"- />- </SettingsRow>- </div>- <AppPlaceholder v-if="!visibleTools.length" :label="automation.noMatchingTools" fill />- <ul v-else class="divide-y divide-border">- <li v-for="tool in visibleTools" :key="tool.name" class="flex items-start gap-3 p-3">- <div class="min-w-0 flex-1">- <code class="break-all text-xs font-medium text-surface">{{ tool.name }}</code>- <p class="mt-1 text-xs leading-relaxed text-muted">{{ tool.description }}</p>- </div>- <AppSwitch- :model-value="isEnabled(tool)"- :label="tool.name"- :data-test-id="`settings-mcp-tool-${tool.name}`"- @update:model-value="setToolEnabled(tool.name, $event)"- />- </li>- </ul>- <p- v-if="$slots.footer"- class="shrink-0 border-t border-border p-3 text-xs leading-relaxed text-muted"- >- <slot name="footer" />- </p>- </div>-</template>diff --git a/src/components/settings/mcp/MCPWorkspacePanel.vue b/src/components/settings/mcp/MCPWorkspacePanel.vueindex 4a78362b0..c3f3691b4 100644--- a/src/components/settings/mcp/MCPWorkspacePanel.vue+++ b/src/components/settings/mcp/MCPWorkspacePanel.vue@@ -1,27 +1,17 @@<script setup lang="ts">-import { useSettingsMessages } from '@open-pencil/vue'-import { webmcpMode } from '@/app/automation/webmcp/preferences'import { webmcpRuntime } from '@/app/automation/webmcp/runtime'-import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import MCPConnectionsSection from './MCPConnectionsSection.vue'import MCPSettingsPanel from './MCPSettingsPanel.vue'import WebMCPSettingsPanel from './WebMCPSettingsPanel.vue'--const settings = useSettingsMessages()</script><template><div class="flex min-h-0 min-w-0 flex-1 flex-col" data-test-id="settings-mcp-panel"><MCPConnectionsSection>- <SettingsSection>- <template #title>{{ settings.automation }}</template>- <div class="flex flex-col gap-6">- <MCPSettingsPanel />- <WebMCPSettingsPanel v-model="webmcpMode" :state="webmcpRuntime" />- </div>- </SettingsSection>+ <MCPSettingsPanel />+ <WebMCPSettingsPanel v-model="webmcpMode" :state="webmcpRuntime" /></MCPConnectionsSection></div></template>diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vueindex 08d56897b..939e16e91 100644--- a/src/components/settings/models/ProfileEditor.vue+++ b/src/components/settings/models/ProfileEditor.vue@@ -1,5 +1,4 @@<script setup lang="ts">-import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'import { computed, ref, useTemplateRef } from 'vue'import type { AIProviderID } from '@open-pencil/core/constants'@@ -18,12 +17,12 @@ import ProviderSettingsField from '@/components/settings/provider/ProviderSettinimport ProviderSettingsInput from '@/components/settings/provider/ProviderSettingsInput.vue'import ProviderSettingsKeyField from '@/components/settings/provider/ProviderSettingsKeyField.vue'import AppButton from '@/components/ui/button/AppButton.vue'+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'import { AppConfirmationDialog } from '@/components/ui/dialog'import AppInput from '@/components/ui/input/AppInput.vue'import AppCombobox from '@/components/ui/select/AppCombobox.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'-import { settingsDisclosureMotion } from '@/theme/settings/disclosure'const { profileId } = defineProps<{ profileId?: string }>()const emit = defineEmits<{ done: []; deleted: [] }>()const { ai, common, credentials, settings } = useI18n()@@ -238,96 +237,91 @@ async function remove() {/></template>- <CollapsibleRoot+ <AppCollapsiblev-if="!isACP"v-model:open="advancedOpen"- class="rounded border border-border"+ :ui="{+ root: 'rounded border border-border',+ trigger: 'px-2.5 py-2 text-[11px] text-muted hover:text-surface',+ icon: 'size-3'+ }">- <CollapsibleTrigger- class="flex w-full items-center gap-2 px-2.5 py-2 text-left text-[11px] text-muted hover:text-surface"- >- <icon-lucide-chevron-right- class="size-3 transition-transform [[data-state=open]>&]:rotate-90"- />- {{ ai.advancedModelSettings }}- </CollapsibleTrigger>- <CollapsibleContent :class="settingsDisclosureMotion">- <div class="flex flex-col gap-3 border-t border-border p-2.5">- <div>- <p class="text-[11px] font-medium text-surface">{{ ai.modelCapabilities }}</p>- <p class="mt-0.5 text-[10px] text-muted">- {{ knownModel ? ai.modelCapabilitiesDetected : ai.modelCapabilitiesManual }}- </p>- </div>+ <template #label>{{ ai.advancedModelSettings }}</template>+ <div class="flex flex-col gap-3 border-t border-border p-2.5">+ <div>+ <p class="text-[11px] font-medium text-surface">{{ ai.modelCapabilities }}</p>+ <p class="mt-0.5 text-[10px] text-muted">+ {{ knownModel ? ai.modelCapabilitiesDetected : ai.modelCapabilitiesManual }}+ </p>+ </div>- <div class="flex flex-col gap-2">- <div class="flex items-center justify-between gap-3">- <span class="text-[11px] text-muted">{{ ai.modelCapabilityTools }}</span>- <span v-if="knownModel" class="text-[10px] text-surface">- {{- knownCapabilities.includes('tools') ? common.supported : common.unsupported- }}- </span>- <AppSwitch v-else v-model="toolsEnabled" :label="ai.modelCapabilityTools" />- </div>- <div class="flex items-center justify-between gap-3">- <span class="text-[11px] text-muted">{{ ai.modelCapabilityVision }}</span>- <span v-if="knownModel" class="text-[10px] text-surface">- {{- knownCapabilities.includes('vision') ? common.supported : common.unsupported- }}- </span>- <AppSwitch v-else v-model="visionEnabled" :label="ai.modelCapabilityVision" />- </div>+ <div class="flex flex-col gap-2">+ <div class="flex items-center justify-between gap-3">+ <span class="text-[11px] text-muted">{{ ai.modelCapabilityTools }}</span>+ <span v-if="knownModel" class="text-[10px] text-surface">+ {{+ knownCapabilities.includes('tools') ? common.supported : common.unsupported+ }}+ </span>+ <AppSwitch v-else v-model="toolsEnabled" :label="ai.modelCapabilityTools" /></div>+ <div class="flex items-center justify-between gap-3">+ <span class="text-[11px] text-muted">{{ ai.modelCapabilityVision }}</span>+ <span v-if="knownModel" class="text-[10px] text-surface">+ {{+ knownCapabilities.includes('vision') ? common.supported : common.unsupported+ }}+ </span>+ <AppSwitch v-else v-model="visionEnabled" :label="ai.modelCapabilityVision" />+ </div>+ </div>- <ProviderSettingsField v-if="isHarness" :label="ai.harnessThinkingLevel">- <AppSelect- v-model="draft.harnessThinkingLevel"- :label="ai.harnessThinkingLevel"- :options="[- { value: 'off', label: ai.harnessThinkingOff },- { value: 'minimal', label: ai.harnessThinkingMinimal },- { value: 'low', label: ai.harnessThinkingLow },- { value: 'medium', label: ai.harnessThinkingMedium },- { value: 'high', label: ai.harnessThinkingHigh },- { value: 'xhigh', label: ai.harnessThinkingExtraHigh }- ]"- />- </ProviderSettingsField>+ <ProviderSettingsField v-if="isHarness" :label="ai.harnessThinkingLevel">+ <AppSelect+ v-model="draft.harnessThinkingLevel"+ :label="ai.harnessThinkingLevel"+ :options="[+ { value: 'off', label: ai.harnessThinkingOff },+ { value: 'minimal', label: ai.harnessThinkingMinimal },+ { value: 'low', label: ai.harnessThinkingLow },+ { value: 'medium', label: ai.harnessThinkingMedium },+ { value: 'high', label: ai.harnessThinkingHigh },+ { value: 'xhigh', label: ai.harnessThinkingExtraHigh }+ ]"+ />+ </ProviderSettingsField>- <ProviderSettingsField v-if="isHarness" :label="ai.harnessToolPermissions">- <AppSelect- v-model="draft.harnessPermissionMode"- :label="ai.harnessToolPermissions"- :options="[- { value: 'allow-reads', label: ai.harnessPermissionReads },- { value: 'allow-edits', label: ai.harnessPermissionEdits },- { value: 'allow-all', label: ai.harnessPermissionAll }- ]"- />- </ProviderSettingsField>+ <ProviderSettingsField v-if="isHarness" :label="ai.harnessToolPermissions">+ <AppSelect+ v-model="draft.harnessPermissionMode"+ :label="ai.harnessToolPermissions"+ :options="[+ { value: 'allow-reads', label: ai.harnessPermissionReads },+ { value: 'allow-edits', label: ai.harnessPermissionEdits },+ { value: 'allow-all', label: ai.harnessPermissionAll }+ ]"+ />+ </ProviderSettingsField>- <ProviderSettingsField v-if="supportsReasoningEffort" :label="ai.reasoningEffort">- <ProviderSettingsInput- v-model="draft.reasoningEffort"- :aria-label="ai.reasoningEffort"- :placeholder="ai.reasoningEffortPlaceholder"- />- <p class="mt-1 text-[10px] text-muted">{{ ai.reasoningEffortDescription }}</p>- </ProviderSettingsField>+ <ProviderSettingsField v-if="supportsReasoningEffort" :label="ai.reasoningEffort">+ <ProviderSettingsInput+ v-model="draft.reasoningEffort"+ :aria-label="ai.reasoningEffort"+ :placeholder="ai.reasoningEffortPlaceholder"+ />+ <p class="mt-1 text-[10px] text-muted">{{ ai.reasoningEffortDescription }}</p>+ </ProviderSettingsField>- <div class="border-t border-border pt-2.5">- <p class="text-[11px] font-medium text-surface">{{ ai.outputLimit }}</p>- <p class="mt-0.5 text-[10px] text-muted">- {{ ai.outputLimitAutomatic }} ·- {{ outputTokenRecommendation.toLocaleString() }}- {{ common.tokens }}- </p>- </div>+ <div class="border-t border-border pt-2.5">+ <p class="text-[11px] font-medium text-surface">{{ ai.outputLimit }}</p>+ <p class="mt-0.5 text-[10px] text-muted">+ {{ ai.outputLimitAutomatic }} ·+ {{ outputTokenRecommendation.toLocaleString() }}+ {{ common.tokens }}+ </p></div>- </CollapsibleContent>- </CollapsibleRoot>+ </div>+ </AppCollapsible><SettingsSaveFeedback :error="saveError" :result="saveResult" /></fieldset>diff --git a/src/components/settings/tool-access/ToolAccessList.stories.ts b/src/components/settings/tool-access/ToolAccessList.stories.tsnew file mode 100644index 000000000..b31c43375--- /dev/null+++ b/src/components/settings/tool-access/ToolAccessList.stories.ts@@ -0,0 +1,79 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'+import { computed, ref } from 'vue'++import type { ToolAccessEntry, ToolAccessGroup } from '@/app/automation/tool-access/types'++import ToolAccessList from './ToolAccessList.vue'++const entries: ToolAccessEntry[] = Array.from({ length: 60 }, (_, index) => ({+ name: `inspect_component_${index + 1}`,+ description:+ 'Inspect a component and its properties in the active document. Narrow the selection to inspect fewer layers.',+ effect: 'read'+}))+const writeEntries: ToolAccessEntry[] = Array.from({ length: 20 }, (_, index) => ({+ name: `edit_component_${index + 1}`,+ description: 'Change a property on one or more components.',+ effect: 'write'+}))++const meta = {+ title: 'Settings/Tool access/List',+ args: {+ disabledTools: [] as string[],+ initiallyCollapsed: false,+ labels: ['Read-only', 'Changes']+ },+ render: (args) => ({+ components: { ToolAccessList },+ setup: () => {+ const disabled = ref([...args.disabledTools])+ const expanded = ref({ read: !args.initiallyCollapsed, write: false })+ const all = [...entries, ...writeEntries]+ const groups = computed<ToolAccessGroup[]>(() =>+ (['read', 'write'] as const).map((effect) => {+ const tools = all.filter((tool) => tool.effect === effect)+ const enabled = tools.filter((tool) => !disabled.value.includes(tool.name)).length+ return {+ effect,+ label: effect === 'read' ? args.labels[0] : args.labels[1],+ enabled: enabled > 0,+ state: enabled > 0 && enabled < tools.length ? 'mixed' : 'idle',+ tools+ }+ })+ )+ const isEnabled = (tool: ToolAccessEntry) => !disabled.value.includes(tool.name)+ return { args, disabled, expanded, groups, isEnabled }+ },+ template: `+ <div class="max-w-lg bg-panel p-3 text-surface">+ <ToolAccessList+ :groups="groups"+ :expanded="expanded"+ :is-enabled="isEnabled"+ @update:expanded="(effect, open) => (expanded = { ...expanded, [effect]: open })"+ @set-group="(effect, enabled) => (disabled = enabled+ ? disabled.filter((name) => !groups.find((g) => g.effect === effect).tools.some((t) => t.name === name))+ : [...disabled, ...groups.find((g) => g.effect === effect).tools.map((t) => t.name)])"+ @set-tool="(name, enabled) => (disabled = enabled ? disabled.filter((n) => n !== name) : [...disabled, name])"+ />+ </div>`+ })+} satisfies Meta<{ disabledTools: string[]; initiallyCollapsed: boolean; labels: [string, string] }>++export default meta+type Story = StoryObj<typeof meta>++export const LongCatalog: Story = {}+export const MixedAccess: Story = { args: { disabledTools: ['inspect_component_1'] } }+export const CollapsedGroup: Story = { args: { initiallyCollapsed: true } }+export const ToggleAccess: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('switch', { name: 'inspect_component_1' }))+ await userEvent.click(canvas.getByRole('button', { name: 'Changes' }))+ await expect(canvas.getByRole('switch', { name: 'edit_component_1' })).toBeVisible()+ }+}diff --git a/src/components/settings/tool-access/ToolAccessList.vue b/src/components/settings/tool-access/ToolAccessList.vuenew file mode 100644index 000000000..3acdab5d0--- /dev/null+++ b/src/components/settings/tool-access/ToolAccessList.vue@@ -0,0 +1,53 @@+<script setup lang="ts">+import type { ToolAccessEntry, ToolAccessGroup } from '@/app/automation/tool-access/types'+import SettingsDisclosure from '@/components/settings/layout/SettingsDisclosure.vue'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'++const { groups, expanded, isEnabled } = defineProps<{+ groups: ToolAccessGroup[]+ expanded: Record<ToolAccessEntry['effect'], boolean>+ isEnabled: (tool: ToolAccessEntry) => boolean+}>()++const emit = defineEmits<{+ 'update:expanded': [effect: ToolAccessEntry['effect'], open: boolean]+ 'set-group': [effect: ToolAccessEntry['effect'], enabled: boolean]+ 'set-tool': [name: string, enabled: boolean]+}>()+</script>++<template>+ <div data-slot="tool-access-list">+ <template v-for="group in groups" :key="group.effect">+ <SettingsDisclosure+ v-if="group.tools.length"+ :open="expanded[group.effect]"+ class="border-b border-border"+ @update:open="emit('update:expanded', group.effect, $event)"+ >+ <template #label>{{ group.label }}</template>+ <template #actions>+ <AppSwitch+ :model-value="group.enabled"+ :state="group.state"+ :label="group.label"+ @update:model-value="emit('set-group', group.effect, $event)"+ />+ </template>+ <ul class="divide-y divide-border">+ <li v-for="tool in group.tools" :key="tool.name" class="flex items-start gap-3 py-3">+ <div class="min-w-0 flex-1">+ <code class="break-all text-xs font-medium text-surface">{{ tool.name }}</code>+ <p class="mt-1 text-xs leading-relaxed text-muted">{{ tool.description }}</p>+ </div>+ <AppSwitch+ :model-value="isEnabled(tool)"+ :label="tool.name"+ @update:model-value="emit('set-tool', tool.name, $event)"+ />+ </li>+ </ul>+ </SettingsDisclosure>+ </template>+ </div>+</template>diff --git a/src/components/settings/tool-access/ToolAccessSettingsPanel.vue b/src/components/settings/tool-access/ToolAccessSettingsPanel.vuenew file mode 100644index 000000000..11319382f--- /dev/null+++ b/src/components/settings/tool-access/ToolAccessSettingsPanel.vue@@ -0,0 +1,108 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useAutomationMessages } from '@open-pencil/vue'++import { mcpRuntime } from '@/app/automation/mcp/runtime'+import { useMCPSettings } from '@/app/automation/mcp/settings/use'+import { useToolAccess } from '@/app/automation/tool-access/settings/list'+import { useToolAccessSettings } from '@/app/automation/tool-access/settings/use'+import type { ToolAccessGroup } from '@/app/automation/tool-access/types'+import AppButton from '@/components/ui/button/AppButton.vue'+import { AppDialogBody } from '@/components/ui/dialog'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'++import ToolAccessList from './ToolAccessList.vue'++const automation = useAutomationMessages()+const { target, tools, disabled, selectTarget, reset } = useToolAccessSettings()+const { search, enabledCount, groups, expanded, setGroupEnabled, isEnabled, setToolEnabled } =+ useToolAccess(tools, disabled)+const { restart } = useMCPSettings()++const targetOptions = computed(() => [+ { value: 'ai', label: automation.value.builtInAI },+ { value: 'mcp', label: automation.value.localMCP }+])+const labelledGroups = computed<ToolAccessGroup[]>(() =>+ groups.value.map((group) => ({+ ...group,+ label:+ group.effect === 'read' ? automation.value.readOnlyTools : automation.value.sideEffectTools+ }))+)+const hasMatches = computed(() => labelledGroups.value.some((group) => group.tools.length))+function setExpanded(effect: 'read' | 'write', open: boolean) {+ expanded.value = { ...expanded.value, [effect]: open }+}+</script>++<template>+ <div class="flex min-h-0 min-w-0 flex-1 flex-col" data-slot="tool-access">+ <div+ class="flex shrink-0 flex-wrap items-center gap-2 border-b border-border px-5 py-3 sm:px-6"+ data-slot="tool-access-toolbar"+ >+ <SegmentedControl+ :model-value="target"+ :options="targetOptions"+ :label="automation.toolAccessTarget"+ class="max-sm:w-full"+ @update:model-value="selectTarget"+ />+ <span class="text-xs text-muted">+ {{ automation.toolsEnabled({ enabled: enabledCount, total: tools.length }) }}+ </span>+ <AppButton size="xs" variant="link" @click="reset">{{+ automation.restoreToolDefaults+ }}</AppButton>+ <AppInput+ v-model="search"+ type="search"+ class="ml-auto min-w-40 flex-1 sm:max-w-60"+ :placeholder="automation.searchTools"+ :aria-label="automation.searchTools"+ />+ </div>+ <AppDialogBody :ui="{ body: 'p-5 sm:p-6' }">+ <p class="pb-3 text-xs leading-relaxed text-muted">+ {{+ target === 'ai' ? automation.aiToolAccessDescription : automation.mcpToolAccessDescription+ }}+ </p>+ <AppPlaceholder v-if="!hasMatches" :label="automation.noMatchingTools" />+ <ToolAccessList+ v-else+ :groups="labelledGroups"+ :expanded="expanded"+ :is-enabled="isEnabled"+ @update:expanded="setExpanded"+ @set-group="setGroupEnabled"+ @set-tool="setToolEnabled"+ />+ <p class="border-t border-border pt-3 text-xs leading-relaxed text-muted">+ {{+ target === 'ai'+ ? automation.aiToolsNotice+ : mcpRuntime.externallyManaged+ ? automation.externalRestartNotice+ : automation.toolsRestartNotice+ }}+ </p>+ <div v-if="target === 'mcp'" class="pt-2">+ <AppButton+ color="primary"+ variant="solid"+ :disabled="mcpRuntime.externallyManaged"+ :loading="mcpRuntime.status === 'starting' || mcpRuntime.checking"+ @click="restart"+ >{{+ mcpRuntime.externallyManaged ? automation.externallyManaged : automation.restart+ }}</AppButton+ >+ </div>+ </AppDialogBody>+ </div>+</template>diff --git a/src/components/ui/collapsible/AppCollapsible.stories.ts b/src/components/ui/collapsible/AppCollapsible.stories.tsnew file mode 100644index 000000000..35eb1688b--- /dev/null+++ b/src/components/ui/collapsible/AppCollapsible.stories.ts@@ -0,0 +1,62 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'+import { ref } from 'vue'++import AppButton from '@/components/ui/button/AppButton.vue'++import AppCollapsible from './AppCollapsible.vue'++const meta = {+ title: 'Design System/Disclosure/Collapsible',+ args: { label: 'Advanced settings' },+ render: (args) => ({+ components: { AppCollapsible, AppButton },+ setup: () => ({ args, open: ref(false) }),+ template: `+ <div class="max-w-md bg-panel p-4 text-surface">+ <AppCollapsible v-model:open="open" :label="args.label">+ <p class="pb-3 text-xs text-muted">Content inside the animated height wrapper.</p>+ </AppCollapsible>+ </div>`+ })+} satisfies Meta<{ label: string }>++export default meta+type Story = StoryObj<typeof meta>++export const Collapsed: Story = {}+export const OpenByDefault: Story = {+ render: (args) => ({+ components: { AppCollapsible },+ setup: () => ({ args, open: ref(true) }),+ template: `+ <div class="max-w-md bg-panel p-4 text-surface">+ <AppCollapsible v-model:open="open" :label="args.label">+ <p class="pb-3 text-xs text-muted">Visible on first render.</p>+ </AppCollapsible>+ </div>`+ })+}+export const WithActions: Story = {+ render: (args) => ({+ components: { AppCollapsible, AppButton },+ setup: () => ({ args, open: ref(false) }),+ template: `+ <div class="max-w-md bg-panel p-4 text-surface">+ <AppCollapsible v-model:open="open" :label="args.label">+ <template #actions><AppButton size="xs" variant="outline">Action</AppButton></template>+ <p class="pb-3 text-xs text-muted">Row action stays next to the trigger.</p>+ </AppCollapsible>+ </div>`+ })+}+export const Toggles: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const trigger = canvas.getByRole('button', { name: 'Advanced settings' })+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ await userEvent.click(trigger)+ await expect(trigger).toHaveAttribute('aria-expanded', 'true')+ await expect(canvas.getByText('Content inside the animated height wrapper.')).toBeVisible()+ }+}diff --git a/src/components/ui/collapsible/AppCollapsible.vue b/src/components/ui/collapsible/AppCollapsible.vuenew file mode 100644index 000000000..c1e6ad2a2--- /dev/null+++ b/src/components/ui/collapsible/AppCollapsible.vue@@ -0,0 +1,71 @@+<script lang="ts">+import type { HTMLAttributes, VNode } from 'vue'++import type { ComponentUI } from '@/components/ui/types'+import type { CollapsibleTheme } from '@/theme/collapsible/collapsible'++export type AppCollapsibleUI = ComponentUI<CollapsibleTheme>++export interface AppCollapsibleProps {+ label?: string+ class?: HTMLAttributes['class']+ ui?: AppCollapsibleUI+}++export interface AppCollapsibleSlots {+ default?(): VNode[]+ label?(): VNode[]+ actions?(): VNode[]+}+</script>++<script setup lang="ts">+import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'+import { computed, normalizeClass, useAttrs } from 'vue'++import { collapsible } from '@/theme/collapsible/collapsible'++const { ui, class: className } = defineProps<AppCollapsibleProps>()+defineSlots<AppCollapsibleSlots>()+defineOptions({ inheritAttrs: false })++const attrs = useAttrs()+const open = defineModel<boolean>('open', { default: false })+const styles = computed(() => collapsible())+</script>++<template>+ <CollapsibleRoot+ v-bind="attrs"+ v-model:open="open"+ data-slot="root"+ :class="styles.root({ class: [ui?.root, normalizeClass(className)] })"+ >+ <div :class="styles.header({ class: ui?.header })">+ <CollapsibleTrigger+ :aria-label="label"+ :class="styles.trigger({ class: ui?.trigger })"+ data-slot="trigger"+ >+ <icon-lucide-chevron-right+ :class="styles.icon({ class: ui?.icon })"+ data-slot="icon"+ aria-hidden="true"+ />+ <span :class="styles.label({ class: ui?.label })" data-slot="label">+ <slot name="label">{{ label }}</slot>+ </span>+ </CollapsibleTrigger>+ <div+ v-if="$slots.actions"+ :class="styles.actions({ class: ui?.actions })"+ data-slot="actions"+ >+ <slot name="actions" />+ </div>+ </div>+ <CollapsibleContent :class="styles.content({ class: ui?.content })" data-slot="content">+ <slot />+ </CollapsibleContent>+ </CollapsibleRoot>+</template>diff --git a/src/components/ui/feedback/AppAlert.vue b/src/components/ui/feedback/AppAlert.vueindex 7b1b0bb69..452fe746f 100644--- a/src/components/ui/feedback/AppAlert.vue+++ b/src/components/ui/feedback/AppAlert.vue@@ -14,6 +14,7 @@ const styles = computed(() => {content: theme.content({ class: ui?.content }),heading: theme.heading({ class: ui?.heading }),description: theme.description({ class: ui?.description }),+ details: theme.details({ class: ui?.details }),actions: theme.actions({ class: ui?.actions })}})@@ -49,6 +50,9 @@ const styles = computed(() => {><slot>{{ description }}</slot></div>+ <div v-if="slots.details" :class="styles.details" data-slot="alert-details">+ <slot name="details" />+ </div><div v-if="slots.actions" :class="styles.actions" data-slot="alert-actions"><slot name="actions" /></div>diff --git a/src/components/ui/input/PresetNumberField.stories.ts b/src/components/ui/input/PresetNumberField.stories.tsnew file mode 100644index 000000000..3148c73f8--- /dev/null+++ b/src/components/ui/input/PresetNumberField.stories.ts@@ -0,0 +1,150 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'+import { computed, ref } from 'vue'++import PresetNumberField from './PresetNumberField.vue'++const LABEL = 'Maximum steps per message'++const meta = {+ title: 'Design System/Inputs/Preset number',+ args: {+ presets: [25, 50, 100, 200],+ min: 1,+ max: 1000,+ label: 'Maximum steps per message',+ customLabel: 'Custom…',+ rangeMessage: 'Enter a whole number from 1 to 1000.',+ initial: 50+ },+ render: (args) => ({+ components: { PresetNumberField },+ setup: () => {+ const value = ref(args.initial)+ const shown = computed(() => `Committed value: ${value.value}`)+ return { args, value, shown }+ },+ template: `+ <div class="flex max-w-md flex-col gap-2 bg-panel p-4 text-surface">+ <PresetNumberField+ v-model:number="value"+ :presets="args.presets"+ :min="args.min"+ :max="args.max"+ :label="args.label"+ :custom-label="args.customLabel"+ :range-message="args.rangeMessage"+ />+ <p data-testid="committed" class="text-xs text-muted">{{ shown }}</p>+ </div>`+ })+} satisfies Meta<{+ presets: number[]+ min: number+ max: number+ label: string+ customLabel: string+ rangeMessage: string+ initial: number+}>++export default meta+type Story = StoryObj<typeof meta>++export const PresetSelected: Story = {}+export const CustomSelected: Story = { args: { initial: 137 } }+export const Disabled: Story = {+ render: (args) => ({+ components: { PresetNumberField },+ setup: () => ({ args, value: ref(args.initial) }),+ template: `+ <div class="max-w-md bg-panel p-4 text-surface">+ <PresetNumberField+ v-model:number="value"+ :presets="args.presets"+ :min="args.min"+ :max="args.max"+ :label="args.label"+ :custom-label="args.customLabel"+ :range-message="args.rangeMessage"+ disabled+ />+ </div>`+ })+}++/** Open the preset list and choose the escape hatch for this story's field. */+async function chooseCustom(canvasElement: HTMLElement) {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('combobox', { name: LABEL }))+ await userEvent.click(within(document.body).getByRole('option', { name: 'Custom…' }))+ // The revealed field is named after the control plus the custom option.+ return canvas.getByRole('spinbutton', { name: `${LABEL}: Custom…` })+}++/** Choosing the escape hatch reveals a field seeded from the current value. */+export const RevealsCustomField: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.queryByRole('spinbutton', { name: LABEL })).toBeNull()+ const field = await chooseCustom(canvasElement)+ await expect(field).toHaveValue(50)+ }+}++/** An out-of-range draft reports the range and leaves the committed value alone. */+export const RejectsOutOfRange: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const field = await chooseCustom(canvasElement)+ await userEvent.clear(field)+ await userEvent.type(field, '0')+ await userEvent.tab()+ await expect(field).toHaveAttribute('aria-invalid', 'true')+ await expect(canvas.getByText('Enter a whole number from 1 to 1000.')).toBeVisible()+ await expect(canvas.getByTestId('committed')).toHaveTextContent('Committed value: 50')+ }+}++/** A value replaced from outside the control switches to custom mode. */+export const FollowsExternalValue: Story = {+ render: (args) => ({+ components: { PresetNumberField },+ setup: () => {+ const value = ref(args.initial)+ return { args, value }+ },+ template: `+ <div class="flex max-w-md flex-col gap-2 bg-panel p-4 text-surface">+ <PresetNumberField+ v-model:number="value"+ :presets="args.presets"+ :min="args.min"+ :max="args.max"+ :label="args.label"+ :custom-label="args.customLabel"+ :range-message="args.rangeMessage"+ />+ <button type="button" @click="value = 137">Set externally</button>+ </div>`+ }),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.queryByRole('spinbutton')).toBeNull()+ await userEvent.click(canvas.getByRole('button', { name: 'Set externally' }))+ const field = canvas.getByRole('spinbutton', { name: `${LABEL}: Custom…` })+ await expect(field).toHaveValue(137)+ }+}++/** A valid custom value commits on Enter and is reported to the owner. */+export const CommitsCustomValue: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const field = await chooseCustom(canvasElement)+ await userEvent.clear(field)+ await userEvent.type(field, '137{Enter}')+ await expect(field).toHaveAttribute('aria-invalid', 'false')+ await expect(canvas.getByTestId('committed')).toHaveTextContent('Committed value: 137')+ }+}diff --git a/src/components/ui/input/PresetNumberField.vue b/src/components/ui/input/PresetNumberField.vuenew file mode 100644index 000000000..d28a3885b--- /dev/null+++ b/src/components/ui/input/PresetNumberField.vue@@ -0,0 +1,143 @@+<script lang="ts">+import type { HTMLAttributes } from 'vue'++import type { ComponentUI } from '@/components/ui/types'+import type { PresetNumberTheme } from '@/theme/input/preset-number'++export type PresetNumberUI = ComponentUI<PresetNumberTheme> & {+ /** Width overrides forwarded to the child controls. */+ select?: string+ field?: string+}++/** Sentinel option value; never a real number so it cannot collide with a preset. */+const CUSTOM_OPTION = 'custom'++export interface PresetNumberFieldProps {+ /** Values offered directly; the current value selects one of them when it matches. */+ presets: readonly number[]+ min: number+ max: number+ /** Accessible name shared by the preset select and the custom field. */+ label: string+ /** Translated label for the escape-hatch option. */+ customLabel: string+ /** Translated message shown when a custom value is outside the range. */+ rangeMessage: string+ disabled?: boolean+ class?: HTMLAttributes['class']+ ui?: PresetNumberUI+}+</script>++<script setup lang="ts">+import { computed, nextTick, normalizeClass, ref, useId, useTemplateRef, watch } from 'vue'++import AppInput from '@/components/ui/input/AppInput.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'+import { presetNumber, presetNumberSizes } from '@/theme/input/preset-number'++const {+ presets,+ min,+ max,+ label,+ customLabel,+ rangeMessage,+ disabled = false,+ ui,+ class: className+} = defineProps<PresetNumberFieldProps>()++const emit = defineEmits<{ commit: [value: number] }>()+defineOptions({ inheritAttrs: false })++const errorID = `${useId()}-range`++const value = defineModel<number>('number', { required: true })+const styles = computed(() => presetNumber())+const custom = ref(!presets.includes(value.value))+const draft = ref(String(value.value))+const invalid = ref(false)+const field = useTemplateRef<{ focus: (options?: FocusOptions) => void }>('field')++const selection = computed({+ get: () => (custom.value ? CUSTOM_OPTION : String(value.value)),+ set: (next: string) => {+ if (next === CUSTOM_OPTION) {+ custom.value = true+ invalid.value = false+ draft.value = String(value.value)+ void nextTick(() => field.value?.focus())+ return+ }+ const parsed = Number(next)+ if (!Number.isFinite(parsed)) return+ custom.value = false+ invalid.value = false+ value.value = parsed+ emit('commit', parsed)+ }+})++const options = computed(() => [+ ...presets.map((preset) => ({ value: String(preset), label: String(preset) })),+ { value: CUSTOM_OPTION, label: customLabel }+])++/** Selecting a preset again, or a value arriving from elsewhere, exits custom mode. */+watch(value, (next) => {+ // Follow the model in both directions: a non-preset value arriving from the+ // owner must reveal the field instead of leaving the select without a match.+ custom.value = !presets.includes(next)+ invalid.value = false+ draft.value = String(next)+})++function commitDraft(): void {+ const parsed = Number(draft.value)+ const valid = Number.isInteger(parsed) && parsed >= min && parsed <= max+ invalid.value = !valid+ if (!valid || parsed === value.value) return+ value.value = parsed+ emit('commit', parsed)+}+</script>++<template>+ <div+ v-bind="$attrs"+ :class="styles.root({ class: [ui?.root, normalizeClass(className)] })"+ data-slot="root"+ >+ <div :class="styles.row({ class: ui?.row })">+ <AppSelect+ v-model="selection"+ :options="options"+ :label="label"+ :disabled="disabled"+ :ui="{ trigger: ui?.select ?? presetNumberSizes.select }"+ />+ <AppInput+ v-if="custom"+ ref="field"+ v-model="draft"+ type="number"+ :min="min"+ :max="max"+ :step="1"+ :disabled="disabled"+ :aria-label="`${label}: ${customLabel}`"+ :aria-invalid="invalid"+ :aria-describedby="invalid ? errorID : undefined"+ :state="invalid ? 'invalid' : 'idle'"+ :class="ui?.field ?? presetNumberSizes.field"+ @enter="commitDraft"+ @blur="commitDraft"+ />+ </div>+ <p v-if="invalid" :id="errorID" :class="styles.error({ class: ui?.error })" role="alert">+ {{ rangeMessage }}+ </p>+ </div>+</template>diff --git a/src/theme/collapsible/collapsible.ts b/src/theme/collapsible/collapsible.tsnew file mode 100644index 000000000..e4a763f1b--- /dev/null+++ b/src/theme/collapsible/collapsible.ts@@ -0,0 +1,23 @@+import { tv } from 'tailwind-variants'++export const collapsibleTheme = {+ slots: {+ root: '',+ header: 'flex items-center gap-3',+ trigger:+ 'group flex min-w-0 flex-1 items-center gap-2 text-left text-xs text-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50',+ icon: 'size-3.5 shrink-0 transition-transform group-data-[state=open]:rotate-90 motion-reduce:transition-none',+ label: 'min-w-0',+ actions: 'shrink-0',+ // Padding and borders belong to the slot inside this wrapper so they cannot+ // snap while the measured height animates.+ content:+ 'overflow-hidden data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up duration-180 motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none'+ }+} as const++export const collapsible = tv(collapsibleTheme)++export type CollapsibleTheme = typeof collapsibleTheme++export default collapsibleThemediff --git a/src/theme/feedback/alert.ts b/src/theme/feedback/alert.tsindex 5248df5e1..5ebb7a362 100644--- a/src/theme/feedback/alert.ts+++ b/src/theme/feedback/alert.ts@@ -5,7 +5,8 @@ const alertTheme = {content: 'min-w-0 flex-1',heading: 'font-medium leading-relaxed',description: 'mt-1 leading-relaxed text-surface',- actions: 'mt-3 flex flex-wrap items-center gap-2'+ details: 'mt-2',+ actions: 'mt-2 flex flex-wrap items-center gap-2'},variants: {tone: {diff --git a/src/theme/input/preset-number.ts b/src/theme/input/preset-number.tsnew file mode 100644index 000000000..ff0a6c8d9--- /dev/null+++ b/src/theme/input/preset-number.ts@@ -0,0 +1,21 @@+import { tv } from 'tailwind-variants'++/** Control widths are plain strings so they can be forwarded to child UI props. */+export const presetNumberSizes = {+ select: 'w-full sm:w-44',+ field: 'w-full sm:w-32'+} as const++const presetNumberTheme = {+ slots: {+ root: 'flex flex-col gap-1',+ row: 'flex flex-wrap items-center gap-2',+ error: 'text-xs text-error'+ }+} as const++export const presetNumber = tv(presetNumberTheme)++export type PresetNumberTheme = typeof presetNumberTheme++export default presetNumberThemediff --git a/src/theme/settings/disclosure.ts b/src/theme/settings/disclosure.tsdeleted file mode 100644index ed01ac581..000000000--- a/src/theme/settings/disclosure.ts+++ /dev/null@@ -1,2 +0,0 @@-export const settingsDisclosureMotion =- 'overflow-hidden data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up duration-180 motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none'diff --git a/tests/e2e/settings/chat.spec.ts b/tests/e2e/settings/chat.spec.tsnew file mode 100644index 000000000..5a96762bd--- /dev/null+++ b/tests/e2e/settings/chat.spec.ts@@ -0,0 +1,65 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++async function openChatSettings(page: Page) {+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+,' : 'Control+,')+ await page.getByTestId('settings-section-ai').click()+}++async function reloadAndOpenChatSettings(page: Page) {+ await page.reload()+ await new CanvasHelper(page).waitForInit()+ await openChatSettings(page)+}++test('chat step limit validates, persists and preserves reasoning preferences', async ({+ page+}) => {+ await page.goto('/?test')+ await new CanvasHelper(page).waitForInit()+ await openChatSettings(page)+ // The control must sit in a row that names it; an accessible name alone left+ // it unlabeled in the panel.+ const row = page+ .locator('[data-slot="settings-row"]')+ .filter({ hasText: 'Maximum steps per message' })+ await expect(row).toContainText('For built-in AI only')+ const limit = row.getByRole('combobox', { name: 'Maximum steps per message' })+ await expect(limit).toHaveText('50')+ // The numeric field only appears behind the custom option.+ await expect(row.getByRole('spinbutton')).toHaveCount(0)+ await limit.click()+ await page.getByRole('option', { name: 'Custom…' }).click()++ const custom = row.getByRole('spinbutton', { name: /Maximum steps per message/ })+ for (const invalid of ['', '0', '1.5', '1001']) {+ await custom.fill(invalid)+ await custom.press('Enter')+ await expect(custom).toHaveAttribute('aria-invalid', 'true')+ await expect(custom).toHaveAccessibleDescription(/Enter a whole number from 1 to 1000/)+ }++ await custom.fill('137')+ await custom.press('Enter')+ await expect(custom).toHaveAttribute('aria-invalid', 'false')++ const reasoning = page.getByRole('combobox', { name: 'Reasoning display' })+ await reasoning.click()+ await page.getByRole('option', { name: 'Expanded by default', exact: true }).click()++ await reloadAndOpenChatSettings(page)+ // A value outside the presets keeps the custom option selected.+ await expect(limit).toHaveText('Custom…')+ await expect(row.getByRole('spinbutton', { name: /Maximum steps per message/ })).toHaveValue(+ '137'+ )+ await expect(reasoning).toHaveText('Expanded by default')++ // A preset commits without revealing the field, and an invalid draft is not saved.+ await limit.click()+ await page.getByRole('option', { name: '200', exact: true }).click()+ await expect(limit).toHaveText('200')+ await reloadAndOpenChatSettings(page)+ await expect(limit).toHaveText('200')+})diff --git a/tests/e2e/settings/credentials.spec.ts b/tests/e2e/settings/credentials.spec.tsindex faf95bf58..25f3e2e54 100644--- a/tests/e2e/settings/credentials.spec.ts+++ b/tests/e2e/settings/credentials.spec.ts@@ -133,29 +133,24 @@ test('MCP automation settings filter and persist tool availability', async ({ paawait expect(authentication).toHaveAttribute('data-state', 'unchecked')await authentication.click()- await page.getByRole('button', { name: 'Available tools', exact: true }).click()- const search = page.getByTestId('settings-mcp-tool-search')+ await page.getByRole('button', { name: 'Tool access', exact: true }).click()+ const search = page.getByRole('searchbox', { name: 'Search tools' })await search.fill('create_shape')await expect(search).toHaveValue('create_shape')- await expect(page.getByTestId('settings-mcp-tool-create_shape')).toBeVisible()- await expect(page.getByTestId('settings-mcp-tool-get_page_tree')).toBeHidden()+ const createShape = page.getByRole('switch', { name: 'create_shape', exact: true })+ await expect(createShape).toBeVisible()+ await expect(page.getByRole('switch', { name: 'get_page_tree', exact: true })).toBeHidden()- await page.getByTestId('settings-mcp-tool-create_shape').click()+ await createShape.click()await page.reload()await canvas.waitForInit()await page.getByTestId('app-settings-trigger').click()await page.getByTestId('settings-section-mcp').click()- await page.getByRole('button', { name: 'Available tools', exact: true }).click()- await expect(page.getByTestId('settings-mcp-tool-create_shape')).toHaveAttribute(- 'data-state',- 'unchecked'- )+ await page.getByRole('button', { name: 'Tool access', exact: true }).click()+ await expect(createShape).toHaveAttribute('data-state', 'unchecked')- await page.getByRole('button', { name: 'Enable all' }).click()- await expect(page.getByTestId('settings-mcp-tool-create_shape')).toHaveAttribute(- 'data-state',- 'checked'- )+ await page.getByRole('button', { name: 'Restore defaults' }).click()+ await expect(createShape).toHaveAttribute('data-state', 'checked')})test('model library keeps reusable profiles and role assignments', async ({ page }) => {diff --git a/tests/e2e/settings/diagnostics.spec.ts b/tests/e2e/settings/diagnostics.spec.tsindex 59dd3c0fd..c872aba46 100644--- a/tests/e2e/settings/diagnostics.spec.ts+++ b/tests/e2e/settings/diagnostics.spec.ts@@ -1,6 +1,9 @@+import type { Page } from '@playwright/test'+import type { DiagnosticEvent } from '@/app/diagnostics/types'-import { test, expect } from '#tests/helpers/chat/fixture'+import { CanvasHelper } from '#tests/helpers/canvas'+import { expect, test } from '#tests/helpers/chat/fixture'test('Settings exports correlated chat telemetry without conversation content', async ({configuredChat: chat,@@ -29,3 +32,53 @@ test('Settings exports correlated chat telemetry without conversation content',expect(text).not.toContain('Private conversation content')expect(text).not.toContain('A second request')})++async function openDiagnostics(page: Page) {+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+,' : 'Control+,')+ await page.getByTestId('settings-section-diagnostics').click()+}++async function reloadAndOpenDiagnostics(page: Page) {+ await page.reload()+ await new CanvasHelper(page).waitForInit()+ await openDiagnostics(page)+}++test('diagnostics retention offers presets and accepts a bounded custom value', async ({+ page+}) => {+ await page.goto('/?test')+ await new CanvasHelper(page).waitForInit()+ await openDiagnostics(page)+ const row = page+ .locator('[data-slot="settings-row"]')+ .filter({ hasText: 'Diagnostics retention' })+ await expect(row).toContainText('Keep up to this many recent events locally.')+ const retention = row.getByRole('combobox', { name: 'Diagnostics retention' })+ await expect(retention).toHaveText('500')++ // A custom value is validated against the supported range before it is kept.+ await retention.click()+ await page.getByRole('option', { name: 'Custom…' }).click()+ const custom = row.getByRole('spinbutton', { name: /Diagnostics retention/ })+ await custom.fill('10')+ await custom.press('Enter')+ await expect(custom).toHaveAttribute('aria-invalid', 'true')+ await expect(custom).toHaveAccessibleDescription(/Enter a whole number from 50 to 20000/)++ await custom.fill('750')+ await custom.press('Enter')+ await expect(custom).toHaveAttribute('aria-invalid', 'false')++ await reloadAndOpenDiagnostics(page)+ await expect(retention).toHaveText('Custom…')+ await expect(row.getByRole('spinbutton', { name: /Diagnostics retention/ })).toHaveValue('750')++ // Presets remain one click and persist without revealing the field.+ await retention.click()+ await page.getByRole('option', { name: '1000', exact: true }).click()+ await expect(retention).toHaveText('1000')+ await reloadAndOpenDiagnostics(page)+ await expect(retention).toHaveText('1000')+ await expect(row.getByRole('spinbutton')).toHaveCount(0)+})diff --git a/tests/e2e/settings/mcp-failure.spec.ts b/tests/e2e/settings/mcp-failure.spec.tsnew file mode 100644index 000000000..9ad3b22d8--- /dev/null+++ b/tests/e2e/settings/mcp-failure.spec.ts@@ -0,0 +1,59 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++async function openMCPPage(page: Page) {+ await page.goto('/?test')+ await new CanvasHelper(page).waitForInit()+ await page.getByTestId('app-settings-trigger').click()+ await page.getByTestId('settings-section-mcp').click()+}++test('MCP startup failures are explained and translated instead of one generic message', async ({+ page+}) => {+ // The health probe is the first thing to fail when the server cannot serve the app.+ await page.route('**/health', (route) => route.abort())+ await openMCPPage(page)++ // Starting the app already attempted the server; the alert carries its own+ // restart action instead of the standalone button.+ await expect(+ page.getByRole('alert', { name: 'MCP server did not respond in time' })+ ).toContainText('It did not become ready within the startup timeout.')+ await expect(+ page.getByTestId('settings-mcp-automation-panel').getByRole('alert')+ ).not.toContainText('did not become healthy')++ // The same reason renders from the catalog rather than the raw error text.+ await page.getByTestId('settings-section-general').click()+ await page.getByTestId('settings-language').click()+ await page.getByRole('option', { name: 'Русский', exact: true }).click()+ await page.getByTestId('settings-section-mcp').click()+ await expect(page.getByRole('alert', { name: 'MCP-сервер не ответил вовремя' })).toContainText(+ 'Он не стал готовым за отведённое время.'+ )+})++test('technical details stay collapsed inside the alert and can be copied', async ({ page }) => {+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])+ // An unreachable health endpoint keeps the failure stable while Settings mounts.+ await page.route('**/health', (route) => route.abort())+ const alert = page.getByTestId('settings-mcp-failure')+ await openMCPPage(page)+ await expect(alert).toBeVisible()++ // Collapsed content is unmounted, so the alert announces only summary copy.+ const details = page.getByRole('button', { name: 'Details', exact: true })+ await expect(details).toHaveAttribute('aria-expanded', 'false')+ await expect(page.getByTestId('settings-mcp-failure-detail')).toHaveCount(0)++ await details.click()+ await expect(details).toHaveAttribute('aria-expanded', 'true')+ await expect(page.getByTestId('settings-mcp-failure-detail')).toBeVisible()++ await page.getByRole('button', { name: 'Copy details' }).click()+ await expect(page.getByText('Diagnostic details copied.', { exact: true })).toBeVisible()+ const clipboard = await page.evaluate(() => navigator.clipboard.readText())+ expect(clipboard).toMatch(/code=(unreachable|timeout)/)+})diff --git a/tests/e2e/settings/mcp.spec.ts b/tests/e2e/settings/mcp.spec.tsindex 3efe516e2..99ec077c4 100644--- a/tests/e2e/settings/mcp.spec.ts+++ b/tests/e2e/settings/mcp.spec.ts@@ -5,7 +5,7 @@ import { CanvasHelper } from '#tests/helpers/canvas'async function selectMCPSection(page: Page, mobile: boolean) {if (mobile) {await page.getByRole('combobox', { name: 'Settings', exact: true }).click()- await page.getByRole('option', { name: 'MCP & automation', exact: true }).click()+ await page.getByRole('option', { name: 'MCP', exact: true }).click()} else {await page.getByTestId('settings-section-mcp').click()}@@ -25,11 +25,11 @@ for (const viewport of [await page.keyboard.press(process.platform === 'darwin' ? 'Meta+,' : 'Control+,')await selectMCPSection(page, viewport.width < 640)await expect(page.getByRole('heading', { name: 'Local server', exact: true })).toBeVisible()- await page.getByRole('button', { name: 'Available tools', exact: true }).click()- const search = page.getByRole('searchbox', { name: 'Search MCP tools' })+ await page.getByRole('button', { name: 'Tool access', exact: true }).click()+ const search = page.getByRole('searchbox', { name: 'Search tools' })await search.fill('no-such-mcp-tool')await expect(page.getByText('No tools match your search.', { exact: true })).toBeVisible()- await page.getByRole('button', { name: 'Available tools', exact: true }).click()+ await selectMCPSection(page, viewport.width < 640)const access = page.getByRole('combobox', { name: 'Browser agent access' })await expect(access).toHaveText('Off')await access.click()@@ -91,11 +91,11 @@ test('MCP connection forms validate, retain invalid drafts and reset dirty stateawait expect(name).toHaveValue('')await expect(name).toHaveAttribute('aria-invalid', 'false')await name.fill('Temporary')- await page.getByTestId('settings-section-general').click()+ await page.getByTestId('settings-section-tools').click()await expect(page.getByRole('alertdialog')).toBeVisible()await page.getByRole('button', { name: 'Keep editing', exact: true }).click()await name.fill('')- await page.getByTestId('settings-section-general').click()+ await page.getByTestId('settings-section-tools').click()await expect(page.getByRole('alertdialog')).toHaveCount(0)await selectMCPSection(page, false)await page.getByRole('button', { name: 'Add connection', exact: true }).click()diff --git a/tests/e2e/settings/polish.spec.ts b/tests/e2e/settings/polish.spec.tsindex 3041f99df..8c5abe261 100644--- a/tests/e2e/settings/polish.spec.ts+++ b/tests/e2e/settings/polish.spec.ts@@ -16,8 +16,10 @@ for (const reducedMotion of ['no-preference', 'reduce'] as const) {await page.emulateMedia({ reducedMotion })await openSettings(page)await expect(page.getByRole('dialog')).toHaveCSS('width', '840px')- await page.getByTestId('settings-section-mcp').click()- const trigger = page.getByRole('button', { name: 'Available tools', exact: true })+ await page.getByTestId('settings-section-tools').click()+ const trigger = page.getByRole('button', { name: 'Read-only tools', exact: true })+ await trigger.click()+ await expect(page.getByRole('switch', { name: 'get_selection', exact: true })).toBeHidden()const motion = await trigger.evaluate(async (button) => {if (!(button instanceof HTMLButtonElement)) throw new Error('Expected a disclosure button')button.click()@@ -41,9 +43,9 @@ for (const reducedMotion of ['no-preference', 'reduce'] as const) {expect(motion.closing).toBe(reducedMotion === 'reduce' ? 'none' : 'collapsible-up')expect(motion.expanded).toBeGreaterThan(0)await expect(trigger).toHaveAttribute('aria-expanded', 'true')- await expect(page.getByRole('searchbox', { name: 'Search MCP tools' })).toBeVisible()+ await expect(page.getByRole('switch', { name: 'get_selection', exact: true })).toBeVisible()await trigger.click()- await expect(page.getByRole('searchbox', { name: 'Search MCP tools' })).toBeHidden()+ await expect(page.getByRole('switch', { name: 'get_selection', exact: true })).toBeHidden()await expect(page.getByTestId('app-settings-done')).toBeVisible()})}diff --git a/tests/e2e/settings/tool-access.spec.ts b/tests/e2e/settings/tool-access.spec.tsnew file mode 100644index 000000000..3ccf6802c--- /dev/null+++ b/tests/e2e/settings/tool-access.spec.ts@@ -0,0 +1,44 @@+import { expect, test } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++for (const width of [1280, 390]) {+ test(`AI and MCP tool settings remain independent across reload at ${width}px`, async ({+ page+ }) => {+ await page.setViewportSize({ width, height: 900 })+ await page.goto('/?test')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()+ async function open() {+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+,' : 'Control+,')+ if (width < 640) {+ await page.getByRole('combobox', { name: 'Settings', exact: true }).click()+ await page.getByRole('option', { name: 'Tool access', exact: true }).click()+ } else await page.getByRole('tab', { name: 'Tool access', exact: true }).click()+ }+ await open()+ const search = page.getByRole('searchbox', { name: 'Search tools' })+ const create = page.getByRole('switch', { name: 'create_component', exact: true })+ await search.fill('create_component')+ await expect(create).toHaveAttribute('data-state', 'unchecked')+ await create.click()+ await page.getByRole('button', { name: 'Local MCP', exact: true }).click()+ await expect(search).toHaveValue('create_component')+ await expect(create).toHaveAttribute('data-state', 'checked')+ await create.click()+ await page.getByRole('button', { name: 'Built-in AI', exact: true }).click()+ await expect(create).toHaveAttribute('data-state', 'checked')+ await page.reload()+ await canvas.waitForInit()+ await open()+ await search.fill('create_component')+ await expect(create).toHaveAttribute('data-state', 'checked')+ await page.getByRole('button', { name: 'Restore defaults' }).click()+ await expect(create).toHaveAttribute('data-state', 'unchecked')+ await page.getByRole('button', { name: 'Local MCP', exact: true }).click()+ await expect(create).toHaveAttribute('data-state', 'unchecked')+ await page.getByRole('button', { name: 'Restore defaults' }).click()+ await expect(create).toHaveAttribute('data-state', 'checked')+ })+}diff --git a/tests/e2e/storybook/controls.spec.ts b/tests/e2e/storybook/controls.spec.tsindex d099e4413..b6f1086ba 100644--- a/tests/e2e/storybook/controls.spec.ts+++ b/tests/e2e/storybook/controls.spec.ts@@ -16,7 +16,11 @@ const stories = ['design-system-paint-fill-swatch--transparent','design-system-paint-fill-swatch--gradient','design-system-paint-fill-swatch--image-placeholder',- 'design-system-navigation-tabs--constrained-labels'+ 'design-system-navigation-tabs--constrained-labels',+ 'design-system-disclosure-collapsible--collapsed',+ 'design-system-inputs-preset-number--custom-selected',+ 'settings-tool-access-list--mixed-access',+ 'settings-mcp-failure-alert--all-reasons']for (const theme of ['light', 'dark']) {@@ -26,7 +30,16 @@ for (const theme of ['light', 'dark']) {page.on('pageerror', (error) => errors.push(error.message))await page.goto(`/iframe.html?id=${story}&viewMode=story&globals=theme:${theme}`)const root = page.locator('#storybook-root')- await expect(root.getByRole('button').or(root.getByRole('tab')).first()).toBeVisible()+ // Stories exercise different primitive families, so assert that an+ // interactive control rendered rather than one specific family.+ await expect(+ root+ .getByRole('button')+ .or(root.getByRole('tab'))+ .or(root.getByRole('combobox'))+ .or(root.getByRole('spinbutton'))+ .first()+ ).toBeVisible()await page.evaluate(() => document.fonts.ready)await expect(page.locator('html')).toHaveAttribute('data-theme', theme)// Keep theme coverage on a composed color matrix, not every story permutation.diff --git a/tests/engine/app/automation/mcp-runtime.test.ts b/tests/engine/app/automation/mcp-runtime.test.tsindex dfa39110a..cd3283c54 100644--- a/tests/engine/app/automation/mcp-runtime.test.ts+++ b/tests/engine/app/automation/mcp-runtime.test.ts@@ -26,6 +26,8 @@ function setup(overrides: Partial<MCPRuntimeDependencies> = {}) {},readHealth: async () => ({ status: 'ok', version: '0.14.0', tools: [descriptor()] }),setToolDescriptors: (tools) => catalogs.push(tools),+ getStartupFailure: () => null,+ getHealthFailure: () => null,spawn: async () => ({authToken: 'token',managed: true,@@ -81,10 +83,47 @@ describe('MCP runtime service', () => {expect(result.ok).toBe(false)expect(service.state.status).toBe('error')- expect(service.state.error).toContain('did not become healthy')+ expect(service.state.failure).toEqual({ code: 'unreachable', detail: expect.any(String) })expect(calls).toEqual(['disconnect-server'])})+ test('surfaces why the server could not start instead of a generic message', async () => {+ const { service } = setup({+ spawn: async () => null,+ readHealth: async () => null,+ getStartupFailure: () => ({ code: 'not-installed', detail: '@open-pencil/[email protected]' })+ })++ await service.start(getStore)++ expect(service.state.failure).toEqual({+ code: 'not-installed',+ detail: '@open-pencil/[email protected]'+ })+ })++ test('distinguishes a rejected token from a missing server', async () => {+ const { service } = setup({+ readHealth: async () => null,+ getHealthFailure: () => ({ code: 'rejected', detail: 'HTTP 401' })+ })++ await service.start(getStore)++ expect(service.state.failure).toEqual({ code: 'rejected', detail: 'HTTP 401' })+ })++ test('reports an unexpected health payload', async () => {+ const { service } = setup({+ readHealth: async () => null,+ getHealthFailure: () => ({ code: 'malformed', detail: 'HTTP 200' })+ })++ await service.start(getStore)++ expect(service.state.failure).toEqual({ code: 'malformed', detail: 'HTTP 200' })+ })+test('clears local runtime state even when server shutdown fails', async () => {const { catalogs, service } = setup({spawn: async () => ({diff --git a/tests/engine/app/chat/step-limit.test.ts b/tests/engine/app/chat/step-limit.test.tsnew file mode 100644index 000000000..ff95b9843--- /dev/null+++ b/tests/engine/app/chat/step-limit.test.ts@@ -0,0 +1,127 @@+import 'fake-indexeddb/auto'+import { expect, spyOn, test } from 'bun:test'++import { simulateReadableStream } from 'ai'+import { MockLanguageModelV4 } from 'ai/test'+import { toRaw } from 'vue'++import { FigmaAPI } from '@open-pencil/core/figma-api'++import { maxAgentSteps, reasoningDisplay } from '@/app/ai/chat/preferences'+import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'+import { createToolLoopTransport } from '@/app/ai/chat/transports'+import { didHitStepLimit } from '@/app/ai/tools'+import { aiToolOverrides } from '@/app/ai/tools/preferences'+import * as figmaFactory from '@/app/automation/bridge/figma-factory'+import { createEditorStore } from '@/app/editor/session/create'+import { appPreferences } from '@/app/settings/preferences/store'++test.each([undefined, null, '100', 0, -1, 1.5, 1001, Number.NaN, Infinity])(+ 'invalid stored step limit %p falls back to the default',+ (value) => {+ expect(resolveAgentStepLimit(value)).toBe(DEFAULT_AGENT_STEPS)+ }+)++test('step limit and reasoning updates preserve each other', () => {+ const previous = structuredClone(toRaw(appPreferences.value))+ try {+ maxAgentSteps.value = 200+ reasoningDisplay.value = 'expanded'+ expect(maxAgentSteps.value).toBe(200)+ maxAgentSteps.value = 1+ expect(reasoningDisplay.value).toBe('expanded')+ expect(maxAgentSteps.value).toBe(1)+ maxAgentSteps.value = 1000+ expect(maxAgentSteps.value).toBe(1000)+ } finally {+ appPreferences.value = previous+ }+})++test('stop condition, warnings and limit detection share the budget captured per message', async () => {+ const previousPreferences = structuredClone(toRaw(appPreferences.value))+ const previousTools = aiToolOverrides.value+ const store = createEditorStore()+ // Viewport DOM plumbing is outside this transport/budget contract.+ const factory = spyOn(figmaFactory, 'makeFigmaFromStore').mockImplementation(+ (editor) => new FigmaAPI(editor.graph)+ )+ let calls = 0+ const model = new MockLanguageModelV4({+ doStream: async () => {+ calls+++ // Changing Settings while streaming must only affect the next message.+ maxAgentSteps.value = 1+ return {+ stream: simulateReadableStream({+ initialDelayInMs: null,+ chunkDelayInMs: null,+ chunks: [+ {+ type: 'tool-call',+ toolCallId: `call-${calls}`,+ toolName: 'get_selection',+ input: '{}'+ },+ {+ type: 'finish',+ finishReason: { unified: 'tool-calls', raw: undefined },+ usage: {+ inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined },+ outputTokens: { total: 1, text: 1, reasoning: undefined }+ }+ }+ ]+ })+ }+ }+ })+ try {+ maxAgentSteps.value = 2+ aiToolOverrides.value = {}+ const transport = createToolLoopTransport({+ store,+ providerID: 'openai',+ model,+ effectiveModelID: 'test',+ maxOutputTokens: 100,+ reasoningEffort: ''+ })+ async function send() {+ const stream = await transport.sendMessages({+ trigger: 'submit-message',+ chatId: 'step-limit',+ messageId: undefined,+ messages: [{ id: 'user', role: 'user', parts: [{ type: 'text', text: 'Inspect' }] }]+ })+ const reader = stream.getReader()+ try {+ while (true) {+ const next = await reader.read()+ if (next.done) break+ expect(next.value.type).not.toBe('error')+ }+ } finally {+ reader.releaseLock()+ }+ }+ await send()+ expect(calls).toBe(2)+ expect(+ JSON.stringify(model.doStreamCalls[1]?.prompt.filter((message) => message.role === 'tool'))+ ).toContain('out of 2')+ expect(didHitStepLimit(store)).toBe(true)+ maxAgentSteps.value = 100+ expect(didHitStepLimit(store)).toBe(true)+ maxAgentSteps.value = 1+ await send()+ expect(calls).toBe(3)+ expect(didHitStepLimit(store)).toBe(true)+ } finally {+ appPreferences.value = previousPreferences+ aiToolOverrides.value = previousTools+ factory.mockRestore()+ store.dispose()+ }+})diff --git a/tests/engine/app/chat/tool-access.test.ts b/tests/engine/app/chat/tool-access.test.tsnew file mode 100644index 000000000..69ed2a0a4--- /dev/null+++ b/tests/engine/app/chat/tool-access.test.ts@@ -0,0 +1,95 @@+import 'fake-indexeddb/auto'+import { expect, test } from 'bun:test'++import { simulateReadableStream, type UIMessage } from 'ai'+import { MockLanguageModelV4 } from 'ai/test'++import { createToolLoopTransport } from '@/app/ai/chat/transports'+import { aiToolOverrides } from '@/app/ai/tools/preferences'+import { createEditorStore } from '@/app/editor/session/create'++test('a reused AI transport refreshes actual request tools for each message', async () => {+ const previous = aiToolOverrides.value+ const store = createEditorStore()+ const model = new MockLanguageModelV4({+ doStream: async () => ({+ stream: simulateReadableStream({+ initialDelayInMs: null,+ chunkDelayInMs: null,+ chunks: [+ { type: 'text-start', id: 'reply' },+ { type: 'text-delta', id: 'reply', delta: 'Done' },+ { type: 'text-end', id: 'reply' },+ {+ type: 'finish',+ finishReason: { unified: 'stop', raw: undefined },+ usage: {+ inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined },+ outputTokens: { total: 1, text: 1, reasoning: undefined }+ }+ }+ ]+ })+ })+ })+ try {+ aiToolOverrides.value = {}+ const transport = createToolLoopTransport({+ store,+ providerID: 'openai',+ model,+ effectiveModelID: 'test',+ maxOutputTokens: 100,+ reasoningEffort: ''+ })+ async function send(history: UIMessage[] = []) {+ const stream = await transport.sendMessages({+ trigger: 'submit-message',+ chatId: 'tool-access',+ messageId: undefined,+ messages: [+ ...history,+ { id: 'user', role: 'user', parts: [{ type: 'text', text: 'Hello' }] }+ ]+ })+ const reader = stream.getReader()+ try {+ while (true) {+ const next = await reader.read()+ if (next.done) break+ expect(next.value.type).not.toBe('error')+ }+ } finally {+ reader.releaseLock()+ }+ return model.doStreamCalls.at(-1)?.tools?.map((tool) => tool.name) ?? []+ }+ expect(await send()).not.toContain('create_component')+ aiToolOverrides.value = { create_component: true, get_components: false }+ const updated = await send()+ expect(updated).toContain('create_component')+ expect(updated).not.toContain('get_components')+ expect(model.doStreamCalls).toHaveLength(2)+ // History remains valid even if an extended tool is now disabled.+ const next = await send([+ {+ id: 'previous-result',+ role: 'assistant',+ parts: [+ {+ type: 'tool-get_current_page',+ toolCallId: 'previous-call',+ state: 'output-available',+ input: {},+ output: { id: 'page', name: 'Page 1' }+ }+ ]+ }+ ])+ expect(next).not.toContain('get_current_page')+ expect(model.doStreamCalls).toHaveLength(3)+ } finally {+ aiToolOverrides.value = previous+ store.dispose()+ }+})diff --git a/tests/engine/app/diagnostics/settings.test.ts b/tests/engine/app/diagnostics/settings.test.tsindex 307ee5ee6..5d2f32fdf 100644--- a/tests/engine/app/diagnostics/settings.test.ts+++ b/tests/engine/app/diagnostics/settings.test.ts@@ -1,40 +1,42 @@-import { expect, spyOn, test } from 'bun:test'+import { describe, expect, test } from 'bun:test'-import { effectScope } from 'vue'+import {+ DIAGNOSTICS_RETENTION_DEFAULT,+ DIAGNOSTICS_RETENTION_MAX,+ DIAGNOSTICS_RETENTION_MIN,+ diagnosticsRetentionPresets,+ resolveDiagnosticsRetention+} from '@/app/diagnostics/settings'-import { diagnostics, type DiagnosticEvent } from '@/app/diagnostics'-import { useRecentDiagnostics } from '@/app/diagnostics/settings/recent'+describe('diagnostics retention', () => {+ test('keeps offered presets', () => {+ for (const preset of diagnosticsRetentionPresets) {+ expect(resolveDiagnosticsRetention(preset)).toBe(preset)+ expect(resolveDiagnosticsRetention(String(preset))).toBe(preset)+ }+ })++ test('accepts custom values inside the supported range', () => {+ expect(resolveDiagnosticsRetention(750)).toBe(750)+ expect(resolveDiagnosticsRetention('1234')).toBe(1234)+ expect(resolveDiagnosticsRetention(DIAGNOSTICS_RETENTION_MIN)).toBe(DIAGNOSTICS_RETENTION_MIN)+ expect(resolveDiagnosticsRetention(DIAGNOSTICS_RETENTION_MAX)).toBe(DIAGNOSTICS_RETENTION_MAX)+ })++ test('clamps out-of-range values instead of storing them', () => {+ expect(resolveDiagnosticsRetention(0)).toBe(DIAGNOSTICS_RETENTION_MIN)+ expect(resolveDiagnosticsRetention(-100)).toBe(DIAGNOSTICS_RETENTION_MIN)+ expect(resolveDiagnosticsRetention(1_000_000)).toBe(DIAGNOSTICS_RETENTION_MAX)+ })++ test('falls back to the default for unusable stored values', () => {+ for (const value of [undefined, null, '', 'many', Number.NaN, Number.POSITIVE_INFINITY, {}]) {+ expect(resolveDiagnosticsRetention(value)).toBe(DIAGNOSTICS_RETENTION_DEFAULT)+ }+ })-test('recent diagnostics unsubscribes and ignores an outstanding refresh after disposal', async () => {- let resolveEvents: (events: DiagnosticEvent[]) => void = () => undefined- let unsubscribed = false- const listing = spyOn(diagnostics, 'list').mockImplementation(- () =>- new Promise((resolve) => {- resolveEvents = resolve- })- )- const subscription = spyOn(diagnostics, 'subscribe').mockImplementation(() => () => {- unsubscribed = true+ test('rounds fractional values', () => {+ expect(resolveDiagnosticsRetention(750.4)).toBe(750)+ expect(resolveDiagnosticsRetention(750.6)).toBe(751)})- const scope = effectScope()- try {- const state = scope.run(() =>- useRecentDiagnostics(- () => {- throw new Error('Disposed refresh must not project')- },- async () => undefined- )- )- scope.stop()- resolveEvents([])- await Promise.resolve()- expect(unsubscribed).toBe(true)- expect(state?.recentEvents.value).toEqual([])- } finally {- scope.stop()- listing.mockRestore()- subscription.mockRestore()- }})diff --git a/tests/engine/app/settings/ai-tool-access.test.ts b/tests/engine/app/settings/ai-tool-access.test.tsnew file mode 100644index 000000000..f3175144a--- /dev/null+++ b/tests/engine/app/settings/ai-tool-access.test.ts@@ -0,0 +1,70 @@+import { afterEach, expect, test } from 'bun:test'++import { ALL_TOOLS, CORE_TOOLS, isToolExposed } from '@open-pencil/core/tools'++import { configurableAITools, enabledAIToolDefinitions } from '@/app/ai/tools/catalog'+import { aiToolOverrides, disabledAITools } from '@/app/ai/tools/preferences'+import { configurableMCPTools, disabledMCPTools } from '@/app/automation/mcp/preferences'+import { useToolAccessSettings } from '@/app/automation/tool-access/settings/use'++const originalAI = aiToolOverrides.value+const originalMCP = disabledMCPTools.value+const originalCatalog = configurableMCPTools.value++afterEach(() => {+ aiToolOverrides.value = originalAI+ disabledMCPTools.value = originalMCP+ configurableMCPTools.value = originalCatalog+ useToolAccessSettings().selectTarget('ai')+})++test('AI catalog includes exposed extended tools while preserving compact defaults', () => {+ expect(configurableAITools.map((tool) => tool.name)).toEqual(+ ALL_TOOLS.filter((tool) => isToolExposed(tool, 'ai')).map((tool) => tool.name)+ )+ const defaults = enabledAIToolDefinitions({}).map((tool) => tool.name)+ for (const tool of CORE_TOOLS) {+ if (isToolExposed(tool, 'ai')) expect(defaults).toContain(tool.name)+ }+ expect(defaults).toContain('get_components')+ expect(defaults).toContain('list_libraries')+ expect(defaults).toContain('insert_library_component')+ expect(defaults).not.toContain('create_component')+ expect(enabledAIToolDefinitions({ create_component: true }).map((tool) => tool.name)).toContain(+ 'create_component'+ )+ expect(+ enabledAIToolDefinitions({ get_components: false }).map((tool) => tool.name)+ ).not.toContain('get_components')+ expect(enabledAIToolDefinitions({ unknown_tool: true }).map((tool) => tool.name)).not.toContain(+ 'unknown_tool'+ )+})++test('target switching, bulk changes and reset preserve independent permissions', () => {+ aiToolOverrides.value = {}+ disabledMCPTools.value = ['create_component']+ const access = useToolAccessSettings()+ access.selectTarget('ai')+ expect(access.disabled.value).toContain('create_component')+ access.disabled.value = access.disabled.value.filter((name) => name !== 'create_component')+ expect(disabledAITools.value).not.toContain('create_component')+ expect(disabledMCPTools.value).toEqual(['create_component'])+ access.selectTarget('mcp')+ access.reset()+ expect(disabledMCPTools.value).toEqual([])+ expect(disabledAITools.value).not.toContain('create_component')+ access.disabled.value = ['find_nodes']+ access.selectTarget('ai')+ access.reset()+ expect(aiToolOverrides.value).toEqual({})+ expect(disabledAITools.value).toContain('create_component')+ expect(disabledMCPTools.value).toEqual(['find_nodes'])+})++test('disabling all AI tools is preserved and does not change MCP access', () => {+ const access = useToolAccessSettings()+ access.selectTarget('ai')+ access.disabled.value = configurableAITools.map((tool) => tool.name)+ expect(enabledAIToolDefinitions(aiToolOverrides.value)).toEqual([])+})diff --git a/tests/engine/app/settings/mcp-tool-access.test.ts b/tests/engine/app/settings/mcp-tool-access.test.tsindex c703fbf47..965689456 100644--- a/tests/engine/app/settings/mcp-tool-access.test.ts+++ b/tests/engine/app/settings/mcp-tool-access.test.ts@@ -1,10 +1,10 @@import { expect, test } from 'bun:test'-import { ref } from 'vue'+import { effectScope, nextTick, ref } from 'vue'import type { ToolDescriptor } from '@open-pencil/mcp/tools'-import { useMCPToolAccess } from '@/app/automation/mcp/settings/tool-access'+import { useToolAccess } from '@/app/automation/tool-access/settings/list'function catalog() {return ref<ToolDescriptor[]>([@@ -38,7 +38,7 @@ function catalog() {test('tool counts and mixed states follow the controlled model and catalog', () => {const tools = catalog()const disabled = ref(['inspect_a', 'unavailable_tool'])- const access = useMCPToolAccess(tools, disabled)+ const access = useToolAccess(tools, disabled)expect(access.enabledCount.value).toBe(2)expect(access.inspectionEnabled.value).toBe(true)expect(access.inspectionState.value).toBe('mixed')@@ -60,7 +60,7 @@ test('tool counts and mixed states follow the controlled model and catalog', ()test('search filters presentation without changing category membership or access', () => {const tools = catalog()const disabled = ref<string[]>([])- const access = useMCPToolAccess(tools, disabled)+ const access = useToolAccess(tools, disabled)access.search.value = ' VARIABLES 'expect(access.visibleTools.value.map((tool) => tool.name)).toEqual(['inspect_b'])access.inspectionEnabled.value = false@@ -69,3 +69,24 @@ test('search filters presentation without changing category membership or accessaccess.search.value = 'no-match'expect(access.visibleTools.value).toEqual([])})++test('groups project filtered tools and search reopens collapsed groups', async () => {+ const scope = effectScope()+ try {+ const access = scope.run(() => useToolAccess(catalog(), ref<string[]>([])))+ if (!access) throw new Error('Missing tool-access scope')+ expect(access.groups.value.map((group) => [group.effect, group.tools.length])).toEqual([+ ['read', 2],+ ['write', 1]+ ])+ access.expanded.value = { read: false, write: false }+ access.search.value = 'variables'+ await nextTick()+ expect(access.expanded.value).toEqual({ read: true, write: true })+ expect(access.groups.value[0]?.tools.map((tool) => tool.name)).toEqual(['inspect_b'])+ access.setGroupEnabled('read', false)+ expect(access.enabledCount.value).toBe(1)+ } finally {+ scope.stop()+ }+})diff --git a/tests/engine/mcp/server/security.test.ts b/tests/engine/mcp/server/security.test.tsindex 72422858f..07ae52430 100644--- a/tests/engine/mcp/server/security.test.ts+++ b/tests/engine/mcp/server/security.test.ts@@ -11,6 +11,7 @@ import { SceneGraph } from '@open-pencil/scene-graph'import { startServer } from '#mcp/server'import type { DiscoveryInfo } from '#mcp/transport/discovery'+import { DESKTOP_APP_ORIGINS, parseCORSOrigins, resolveCORSOrigins } from '#mcp/transport/origins'import {connectMockBrowser,@@ -67,6 +68,62 @@ describe('MCP server CORS', () => {await handle.close()}})++ test('allows the desktop app origin when several origins are configured', async () => {+ const handle = await startServer({+ httpPort: 0,+ withTcp: true,+ socketPath: testSocketPath(),+ authToken: TEST_AUTH_TOKEN,+ corsOrigin: DESKTOP_APP_ORIGINS,+ enableEval: false,+ mcpRoot: null+ })+ const httpPort = handle.httpPort+ if (!httpPort) {+ await handle.close()+ throw new Error('withTcp: true did not produce an HTTP port')+ }++ try {+ const preflight = (origin: string) =>+ fetch(`http://127.0.0.1:${httpPort}/health`, {+ method: 'OPTIONS',+ headers: {+ origin,+ 'access-control-request-method': 'GET',+ 'access-control-request-headers': 'authorization'+ }+ })++ // The app webview calls the server from its own origin with no extra setup.+ for (const origin of DESKTOP_APP_ORIGINS) {+ const response = await preflight(origin)+ expect(response.headers.get('access-control-allow-origin')).toBe(origin)+ }+ // An unrelated site is not granted access.+ const foreign = await preflight('https://example.com')+ expect(foreign.headers.get('access-control-allow-origin')).toBeNull()+ } finally {+ await handle.close()+ }+ })+})++describe('MCP CORS origin configuration', () => {+ test('defaults to the desktop app origin when nothing is configured', () => {+ expect(resolveCORSOrigins(undefined)).toEqual(DESKTOP_APP_ORIGINS)+ expect(resolveCORSOrigins(' ')).toEqual(DESKTOP_APP_ORIGINS)+ expect(resolveCORSOrigins(',')).toEqual(DESKTOP_APP_ORIGINS)+ })++ test('accepts a comma-separated override', () => {+ expect(parseCORSOrigins('https://a.example, https://b.example')).toEqual([+ 'https://a.example',+ 'https://b.example'+ ])+ expect(resolveCORSOrigins('https://one.example')).toEqual(['https://one.example'])+ })})// ---------------------------------------------------------------------------diff --git a/tests/engine/tauri/mcp-spawn.test.ts b/tests/engine/tauri/mcp-spawn.test.tsindex 57dfe349f..b048789f2 100644--- a/tests/engine/tauri/mcp-spawn.test.ts+++ b/tests/engine/tauri/mcp-spawn.test.ts@@ -1,6 +1,12 @@import { afterEach, describe, expect, test, vi } from 'bun:test'-import { getAutomationAuthToken, spawnMCPIfNeeded } from '@/app/automation/mcp/spawn'+import {+ getAutomationAuthToken,+ getAutomationHealthFailure,+ getAutomationStartupFailure,+ readAutomationHealth,+ spawnMCPIfNeeded+} from '@/app/automation/mcp/spawn'import { clearTauriMocks, installTauriMockWindow, mockTauriIPC } from '#tests/helpers/tauri/mocks'@@ -23,6 +29,45 @@ afterEach(async () => {Reflect.deleteProperty(globalThis, 'location')})+describe('MCP health probe diagnostics', () => {+ test('records a rejected token separately from an unreachable server', async () => {+ installTauriMockWindow()+ const reject = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response('', { status: 401 }))++ await expect(readAutomationHealth('stale-token')).resolves.toBeNull()+ expect(getAutomationHealthFailure()).toEqual({ code: 'rejected', detail: 'HTTP 401' })++ reject.mockResolvedValue(new Response('', { status: 500 }))+ await expect(readAutomationHealth('stale-token')).resolves.toBeNull()+ expect(getAutomationHealthFailure()).toEqual({ code: 'malformed', detail: 'HTTP 500' })++ reject.mockRejectedValue(new Error('connection refused'))+ await expect(readAutomationHealth('stale-token')).resolves.toBeNull()+ expect(getAutomationHealthFailure()).toEqual({+ code: 'unreachable',+ detail: expect.any(String)+ })+ })++ test('records an unexpected health payload and clears the failure on success', async () => {+ installTauriMockWindow()+ const fetchMock = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response(JSON.stringify({ unexpected: true }), { status: 200 }))++ await expect(readAutomationHealth()).resolves.toBeNull()+ expect(getAutomationHealthFailure()).toEqual({ code: 'malformed', detail: 'HTTP 200' })++ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ status: 'ok', version: '0.0.0-test' }), { status: 200 })+ )+ await expect(readAutomationHealth()).resolves.toMatchObject({ status: 'ok' })+ expect(getAutomationHealthFailure()).toBeNull()+ })+})+describe('Tauri MCP spawning', () => {test('retains an early startup failure for MCP-dependent features', async () => {installTauriMockWindow()@@ -34,7 +79,8 @@ describe('Tauri MCP spawning', () => {vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('', { status: 404 }))await mockTauriIPC((cmd, args) => {- if (cmd === 'mcp_executable_available') return true+ if (cmd === 'mcp_lookup')+ return { available: true, path: '/mock/bin/openpencil-mcp-http', searched: ['/mock/bin'] }if (cmd === 'plugin:path|resolve_directory') return '/mock/home'if (cmd === 'plugin:fs|exists') return falseif (cmd === 'plugin:shell|spawn') {@@ -56,6 +102,10 @@ describe('Tauri MCP spawning', () => {expect(await spawnMCPIfNeeded()).toBeNull()expect(getAutomationAuthToken()).rejects.toThrow('MCP server exited before startup completed')+ expect(getAutomationStartupFailure()).toMatchObject({+ code: 'exited',+ detail: expect.stringContaining('code=')+ })})test('retains unexpected spawn errors for MCP-dependent features', async () => {@@ -68,7 +118,8 @@ describe('Tauri MCP spawning', () => {vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('', { status: 404 }))await mockTauriIPC((cmd) => {- if (cmd === 'mcp_executable_available') return true+ if (cmd === 'mcp_lookup')+ return { available: true, path: '/mock/bin/openpencil-mcp-http', searched: ['/mock/bin'] }if (cmd === 'plugin:path|resolve_directory') return '/mock/home'if (cmd === 'plugin:fs|exists') return falseif (cmd === 'plugin:shell|spawn') throw new Error('shell permission denied')@@ -77,6 +128,7 @@ describe('Tauri MCP spawning', () => {expect(await spawnMCPIfNeeded()).toBeNull()expect(getAutomationAuthToken()).rejects.toThrow('shell permission denied')+ expect(getAutomationStartupFailure()).toMatchObject({ code: 'permission-denied' })})test('retains a language-independent missing executable diagnostic', async () => {@@ -91,12 +143,18 @@ describe('Tauri MCP spawning', () => {await mockTauriIPC((cmd) => {if (cmd === 'plugin:path|resolve_directory') return '/mock/home'if (cmd === 'plugin:fs|exists') return false- if (cmd === 'mcp_executable_available') return false+ if (cmd === 'mcp_lookup')+ return { available: false, path: null, searched: ['/usr/local/bin', '/mock/home/.bun/bin'] }return null})expect(await spawnMCPIfNeeded()).toBeNull()expect(getAutomationAuthToken()).rejects.toThrow('MCP automation is not installed')+ expect(getAutomationStartupFailure()).toMatchObject({+ code: 'not-installed',+ // The searched directories let a report show where the app looked.+ detail: expect.stringContaining('/mock/home/.bun/bin')+ })})test('spawns MCP server with shell plugin when health check is missing', async () => {@@ -126,7 +184,8 @@ describe('Tauri MCP spawning', () => {const calls: Array<{ cmd: string; args: unknown }> = []await mockTauriIPC((cmd, args) => {calls.push({ cmd, args })- if (cmd === 'mcp_executable_available') return true+ if (cmd === 'mcp_lookup')+ return { available: true, path: '/mock/bin/openpencil-mcp-http', searched: ['/mock/bin'] }if (cmd === 'plugin:shell|spawn') {expect(args).toMatchObject({program: 'openpencil-mcp-http',diff --git a/tools/i18n/mixed-script-baseline.txt b/tools/i18n/mixed-script-baseline.txtindex 4ff04cfda..770896ea4 100644--- a/tools/i18n/mixed-script-baseline.txt+++ b/tools/i18n/mixed-script-baseline.txt@@ -5,6 +5,7 @@ ja:ai.baseURLPlaceholderja:ai.chatAuthenticationFailedja:ai.chatForbiddenja:ai.chatNetworkFailed+ja:ai.connectProviderja:ai.connectionTestAPITypeMismatchja:ai.connectionTestAuthFailedja:ai.connectionTestBrowserNetworkFailed@@ -14,46 +15,62 @@ ja:ai.connectionTestMissingBaseURLja:ai.connectionTestMissingModelja:ai.connectionTestModelNotFoundja:ai.connectionTestNetworkFailed-ja:ai.connectProviderja:ai.customModelIDja:ai.getProviderAPIKey+ja:ai.maxAgentStepsHintja:ai.modelIDja:ai.modelIDPlaceholderja:ai.modelRoleDesignDescriptionja:ai.providerja:ai.reasoningEffortPlaceholder-ja:automation.webmcpDescription-ja:automation.webmcpSetup-ja:automation.webmcpUnsupportedja:automation.addServerConnection+ja:automation.aiToolAccessDescriptionja:automation.authenticationDescriptionja:automation.bearerAuthenticationja:automation.bearerTokenja:automation.bearerTokenPlaceholderja:automation.bearerTokenRequired+ja:automation.builtInAI+ja:automation.connectionEditorDescriptionja:automation.connectionNameHintja:automation.connectionNameInvalid-ja:automation.serverURLHint-ja:automation.connectionEditorDescriptionja:automation.connectionsja:automation.connectionsDescriptionja:automation.deleteConnectionDescriptionja:automation.descriptionja:automation.editConnectionja:automation.enableConnection+ja:automation.localMCP+ja:automation.mcpFailureExited+ja:automation.mcpFailureMalformed+ja:automation.mcpFailureMalformedHint+ja:automation.mcpFailureNotInstalled+ja:automation.mcpFailureNotInstalledHint+ja:automation.mcpFailurePermission+ja:automation.mcpFailurePermissionHint+ja:automation.mcpFailureRejected+ja:automation.mcpFailureRejectedHint+ja:automation.mcpFailureTimeout+ja:automation.mcpFailureUnknown+ja:automation.mcpFailureUnreachableja:automation.noConnectionsja:automation.restartja:automation.rootDirectoryja:automation.rootDirectoryDescription-ja:automation.searchToolsja:automation.serverURL+ja:automation.serverURLHint+ja:automation.toolAccessDescriptionja:automation.toolsRestartNotice+ja:automation.webmcpDescription+ja:automation.webmcpSetup+ja:automation.webmcpUnsupportedja:code.copyJSXReferenceja:code.editorHTMLCSSLabelja:collaboration.pasteRoomLinkOrIdja:commands.paletteDescriptionja:credentials.apiKeyja:credentials.getAPIKey+ja:credentials.rememberDeviceja:diagnostics.acpFailedja:diagnostics.chatCompletedja:diagnostics.chatFailed@@ -75,8 +92,8 @@ ja:files.useChromeja:fonts.downloadFallbackPacksDescriptionja:media.getPexelsAPIKeyja:media.getUnsplashAccessKey-ja:media.pexelsAlternativeOptionalja:media.pexelsAPIKey+ja:media.pexelsAlternativeOptionalja:media.stockPhotoToolOptionalja:media.unsplashAccessKeyja:media.vectorizationDescription@@ -103,11 +120,10 @@ ja:recovery.dialogDescriptionja:rendering.reloadRequiredja:rendering.settingsDescriptionja:rendering.urlOverride+ja:settings.aiAndAgents+ja:settings.baseURLHintja:settings.invalidURLja:settings.modelIDHint-ja:settings.baseURLHint-ja:settings.aiAndAgents-ja:settings.automationja:settings.temporaryDisableSnappingHintja:storage.accessKeyIDja:storage.copyCors@@ -125,6 +141,7 @@ zh-cn:ai.baseURLPlaceholderzh-cn:ai.chatAuthenticationFailedzh-cn:ai.chatForbiddenzh-cn:ai.chatNetworkFailed+zh-cn:ai.connectProviderzh-cn:ai.connectionTestAPITypeMismatchzh-cn:ai.connectionTestAuthFailedzh-cn:ai.connectionTestBrowserNetworkFailed@@ -134,46 +151,62 @@ zh-cn:ai.connectionTestMissingBaseURLzh-cn:ai.connectionTestMissingModelzh-cn:ai.connectionTestModelNotFoundzh-cn:ai.connectionTestNetworkFailed-zh-cn:ai.connectProviderzh-cn:ai.customModelIDzh-cn:ai.getProviderAPIKey+zh-cn:ai.maxAgentStepsHintzh-cn:ai.modelIDzh-cn:ai.modelIDPlaceholderzh-cn:ai.modelRoleDesignDescriptionzh-cn:ai.providerzh-cn:ai.reasoningEffortPlaceholder-zh-cn:automation.webmcpDescription-zh-cn:automation.webmcpSetup-zh-cn:automation.webmcpUnsupportedzh-cn:automation.addServerConnection+zh-cn:automation.aiToolAccessDescriptionzh-cn:automation.authenticationDescriptionzh-cn:automation.bearerAuthenticationzh-cn:automation.bearerTokenzh-cn:automation.bearerTokenPlaceholderzh-cn:automation.bearerTokenRequired+zh-cn:automation.builtInAI+zh-cn:automation.connectionEditorDescriptionzh-cn:automation.connectionNameHintzh-cn:automation.connectionNameInvalid-zh-cn:automation.serverURLHint-zh-cn:automation.connectionEditorDescriptionzh-cn:automation.connectionszh-cn:automation.connectionsDescriptionzh-cn:automation.deleteConnectionDescriptionzh-cn:automation.descriptionzh-cn:automation.editConnectionzh-cn:automation.enableConnection+zh-cn:automation.localMCP+zh-cn:automation.mcpFailureExited+zh-cn:automation.mcpFailureMalformed+zh-cn:automation.mcpFailureMalformedHint+zh-cn:automation.mcpFailureNotInstalled+zh-cn:automation.mcpFailureNotInstalledHint+zh-cn:automation.mcpFailurePermission+zh-cn:automation.mcpFailurePermissionHint+zh-cn:automation.mcpFailureRejected+zh-cn:automation.mcpFailureRejectedHint+zh-cn:automation.mcpFailureTimeout+zh-cn:automation.mcpFailureUnknown+zh-cn:automation.mcpFailureUnreachablezh-cn:automation.noConnectionszh-cn:automation.restartzh-cn:automation.rootDirectoryzh-cn:automation.rootDirectoryDescription-zh-cn:automation.searchToolszh-cn:automation.serverURL+zh-cn:automation.serverURLHint+zh-cn:automation.toolAccessDescriptionzh-cn:automation.toolsRestartNotice+zh-cn:automation.webmcpDescription+zh-cn:automation.webmcpSetup+zh-cn:automation.webmcpUnsupportedzh-cn:code.copyJSXReferencezh-cn:code.editorHTMLCSSLabelzh-cn:collaboration.pasteRoomLinkOrIdzh-cn:commands.paletteDescriptionzh-cn:credentials.apiKeyzh-cn:credentials.getAPIKey+zh-cn:credentials.rememberDevicezh-cn:diagnostics.acpFailedzh-cn:diagnostics.chatCompletedzh-cn:diagnostics.chatFailed@@ -194,8 +227,8 @@ zh-cn:files.useChromezh-cn:fonts.downloadFallbackPacksDescriptionzh-cn:media.getPexelsAPIKeyzh-cn:media.getUnsplashAccessKey-zh-cn:media.pexelsAlternativeOptionalzh-cn:media.pexelsAPIKey+zh-cn:media.pexelsAlternativeOptionalzh-cn:media.stockPhotoToolOptionalzh-cn:media.unsplashAccessKeyzh-cn:media.vectorizationDescription@@ -221,10 +254,9 @@ zh-cn:recovery.dialogDescriptionzh-cn:rendering.reloadRequiredzh-cn:rendering.settingsDescriptionzh-cn:rendering.urlOverride-zh-cn:settings.invalidURL-zh-cn:settings.baseURLHintzh-cn:settings.aiAndAgents-zh-cn:settings.automation+zh-cn:settings.baseURLHint+zh-cn:settings.invalidURLzh-cn:settings.temporaryDisableSnappingHintzh-cn:storage.accessKeyIDzh-cn:storage.copyCors@@ -235,7 +267,3 @@ zh-cn:updates.downloadingzh-cn:updates.installedzh-cn:updates.unavailablezh-cn:updates.upToDate---ja:credentials.rememberDevice-zh-cn:credentials.rememberDevicediff --git a/tools/i18n/translation-baseline.txt b/tools/i18n/translation-baseline.txtindex 129828532..d350ec727 100644--- a/tools/i18n/translation-baseline.txt+++ b/tools/i18n/translation-baseline.txt@@ -1,3 +1,4 @@+de:ai.chatSettingsde:ai.completionsde:ai.harnessThinkingMinimalde:ai.modelAgentConnection@@ -5,6 +6,7 @@ de:ai.modelCapabilityVisionShortde:ai.modelNamede:ai.modelRoleVisionde:ai.responses+de:automation.mcpFailureDetailsde:automation.portde:automation.statusde:automation.version@@ -38,6 +40,7 @@ de:panels.positionde:panels.radialGradientde:panels.radiusde:panels.textCaseOriginal+de:settings.mcpde:storage.bucketde:storage.providerAmazonS3de:storage.providerBackblaze@@ -49,6 +52,7 @@ de:tools.polygonde:tools.textde:variableTypes.booleande:variableTypes.text+es:ai.chatSettingses:ai.completionses:ai.responseses:ai.toolError@@ -73,6 +77,7 @@ es:panels.textCaseOriginales:panels.variableses:rendering.experimentales:settings.general+es:settings.mcpes:storage.bucketes:storage.providerAmazonS3es:storage.providerBackblaze@@ -126,6 +131,7 @@ fr:panels.saturationfr:panels.variablesfr:settings.animationsfr:settings.diagnostics+fr:settings.mcpfr:settings.notificationsfr:storage.bucketfr:storage.providerAmazonS3@@ -135,6 +141,7 @@ fr:tools.ellipsefr:tools.rectanglefr:tools.sectionfr:variables.modes+it:ai.chatSettingsit:ai.completionsit:ai.responsesit:code.editorDesignLabel@@ -156,6 +163,7 @@ it:panels.framePresetCategorySocialMediait:panels.framePresetCategoryTabletit:panels.layoutit:rendering.settingsTitle+it:settings.mcpit:settings.mediait:storage.bucketit:storage.endpoint@@ -172,6 +180,7 @@ ja:panels.colorFormatHslja:panels.colorFormatOkhclja:panels.colorFormatRgbja:panels.framePresetCategoryFigmaCommunity+ja:settings.mcpja:storage.providerAmazonS3ja:storage.providerBackblazeja:storage.providerR2@@ -196,6 +205,7 @@ pl:panels.designpl:panels.framePresetCategoryFigmaCommunitypl:panels.framePresetCategoryTabletpl:panels.kerning+pl:settings.mcppl:settings.mediapl:storage.providerAmazonS3pl:storage.providerBackblaze@@ -213,6 +223,7 @@ ru:panels.colorFormatHslru:panels.colorFormatOkhclru:panels.colorFormatRgbru:panels.framePresetCategoryFigmaCommunity+ru:settings.mcpru:storage.providerAmazonS3ru:storage.providerBackblazeru:storage.providerR2@@ -229,10 +240,7 @@ zh-cn:panels.colorFormatOkhclzh-cn:panels.colorFormatRgbzh-cn:panels.framePresetCategoryFigmaCommunityzh-cn:panels.maskTypeAlpha+zh-cn:settings.mcpzh-cn:storage.providerAmazonS3zh-cn:storage.providerBackblazezh-cn:storage.providerR2--de:ai.chatSettings-es:ai.chatSettings-it:ai.chatSettings