AI-native design editor. Open-source Figma alternative.
feat(ai): add guided AI setup for providers, coding agents, and Pi (#916)
Danila Poyarkov8bf71bd92f76
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54947c8cb..ca6859c6f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -33,6 +33,8 @@### Added+- Set up AI in a few steps with guided setup. On first launch OpenPencil asks what AI should help with and what you already use: a coding agent on this computer (Claude Code, Codex, Gemini CLI, or Pi, in the desktop app), an API account (Anthropic, OpenAI, Google AI, OpenRouter, DeepSeek, Z.ai, or MiniMax), or a local or company server such as Ollama or LM Studio. Sign in to OpenRouter from the browser or the desktop app instead of pasting a key. In the desktop app, setup checks whether the agent, its OpenPencil adapter, OpenPencil's MCP server, and Pi's Harness companion are installed and match the app, installs or updates them with one click through npm, and links a [setup guide](https://openpencil.dev/programmable/coding-agents) or copies a prompt that asks the agent to set itself up. Setup tests each connection, proposes a model for each role that you can change, and keeps anything configured by hand. Skip it to start designing, or run it again from **Settings → AI & agents**.+- Print the installed version of OpenPencil's MCP server and Harness companion with `openpencil-mcp-http --version`, `openpencil-mcp --version`, and `openpencil-harness --version`. The desktop app asks it to check that they match the app on every platform, including npm `.cmd` shims on Windows and version managers such as Volta and mise.- Make main components behave like real controls and try them in preview. The Behaviour section turns a component or component set into a Button, Text field, Textarea, Number field, Toggle, Switch, Checkbox, Radio, Radio group, Toggle group, Slider, Progress, Tabs, Collapsible, or Accordion, after Reka UI's primitives: its values bind to the component's variant, boolean, and text properties, a slider or number field keeps its own number range, its parts are its slots (a group's items slot holds its radios, toggles, or collapsibles), and a variant property can draw its default, hover, pressed, focus, and disabled states. Rows are named for the control, and an empty row creates what it needs: a text layer and text property, Off and On variants, a slot in every variant, or a variant for each interaction state, turning a lone component into a component set when it needs variants. View > Preview (⌥⌘↩) runs each top-level layer holding controls as live Reka UI components over the canvas, drawn by the component's variants: real inputs with the browser's caret, selection, and paste, keyboard focus and navigation, and layout that grows as collapsibles open, all without changing the document, its history, or what collaborators see; Esc or the pill returns to editing.- Build controls from scripts, tools, and design JSX. Scripts run by `eval`, `openpencil eval`, and app automation get an `openpencil` global next to `figma`, in the Figma API's style: `openpencil.setBehaviour(set, { kind: 'switch', values: { value: 'State' }, parts: { thumb: 'Thumb' }, states: 'Interaction' })` or `.bindValue()` and `.bindPart()` by property and slot names, `getBehaviour`, `behaviourKinds`, and `createSlot`. MCP and AI chat get `set_behaviour`, `get_behaviour`, and `create_slot`. Design JSX writes controls with Reka UI's element names, such as `<Switch.Root modelValue="State">` with `<Switch.Thumb>`, `<TextField.Input>`, and `<Tabs.List>`, and exports components with behaviours the same way.- Open a `.fig`, `.pen`, or other supported document by dragging it onto the window, where it opens in a new tab as File → Open does. Images and SVG files dropped on the canvas are still placed, and other files report that they can't be opened instead of being ignored.@@ -73,6 +75,8 @@### Changed+- Run Pi with the providers you signed in to in the Pi CLI and Pi's default model, so an AI Gateway key and a model ID are optional. The Pi model editor shows whether the Harness companion and MCP server are installed and match the app, and a chat whose Harness companion is missing, or whose companion or MCP server does not match the app, says what to fix and offers guided setup instead of failing with a generic error, and the message and its attachments stay in the composer.+- Point Codex install instructions at `@agentclientprotocol/codex-acp`, which replaces `@zed-industries/codex-acp` and provides the same `codex-acp` command.- The desktop app shows an available update in a Software Update window with formatted, scrollable release notes, a link to the full notes, and download progress you can cancel, instead of a system dialog that showed raw Markdown and could grow taller than the screen (#743). On macOS and Linux the update installs first and you choose when to restart; restarting, and on Windows installing, first asks about unsaved documents as Quit does.- `openpencil eval` prints the value of a script's last expression, as the `eval` tool and app automation already do, so `-c 'figma.currentPage.children.length'` prints the count without a `return`.- In scripts, children of groups and booleans report `x`, `y`, and `relativeTransform` in their container's space, as in Figma, and a group refits whenever a script moves, resizes, rotates, adds, or removes one of its children; a group left without children is removed. The canvas and the plugin API share the refit.@@ -115,6 +119,7 @@- Release a document's memory when its tab closes. Every closed tab kept its scene, canvas, and editor panels alive until reload, so memory grew with each document opened and closed. Menus and shortcuts now also follow the active document, so Undo and Redo are offered according to its history rather than the first document opened.- Put a deleted variable back in its place in its collection when the deletion is undone, instead of at the end.- Start Pi chats with OpenPencil's MCP tools when the Harness companion runs on Node 22.15 or later; the companion now installs the dependency Pi's MCP adapter needs and loads its TypeScript sources. A reopened Pi session starts fresh instead of failing to resume its in-memory sandbox, and npm output from Pi no longer mixes into the companion's protocol.+- Keep a chat message in the composer when the chat cannot start, instead of discarding it.- Import HTML and CSS with the right shadow and border colors. A shadow whose color follows its lengths, as CSS usually writes it, and a `border` with a color function such as `rgb(226, 232, 240)` came in black. Every layer of a `box-shadow` list now imports, `inset` ones as inner shadows, and lengths in `%`, `em`, or `vh` are no longer read as pixels.- Accept a CSS `box-shadow` list in design JSX's `shadow` prop: the color may come first, a fourth length sets the spread, several layers add several shadows, and `inset` makes an inner shadow. A color before the lengths or a spread made the shadow black.- Read `repeat()` and `minmax()` in design JSX grid tracks, such as `columns="repeat(7, 1fr)"`, which collapsed the grid to near-zero columns. A track the grid cannot express sizes to its content instead of to 0.@@ -176,6 +181,8 @@- Load the Bold, Medium, and other styles of macOS system fonts packaged as font collections, such as Menlo, Helvetica Neue, and Avenir Next, instead of reporting them as substituted or drawing a different style (#746).- Load the Medium, Semibold, Bold, and other styles of installed variable fonts such as SF Pro on macOS instead of reporting them as substituted (#752).- Ship the MIT license text in every published npm package, and add READMEs for `@open-pencil/core`, `@open-pencil/cli`, and `@open-pencil/mcp` on npm.+- Draw unchecked checkboxes in the Publish library dialog as empty boxes instead of filled squares, which were nearly black in the light theme.+- Show a saved AI key the browser can no longer read as Unavailable on its model in Settings, instead of a "Browser credential operation failed" error each time Settings or the app opens.- Reject malformed vector network JSON in the AI and MCP `path_set` tool with an error instead of storing it on the node, where later path tools failed on it.- Keep image bytes when the CLI reads a component library revision back from its catalog, instead of restoring every image empty.- Work with pages other than the one on screen through MCP, `eval`, and the CLI against the running app without switching to them: `openpencil export --page` and `--page-id` export that page instead of the selection, `export_image` and `openpencil export --node` export layers from any page instead of failing with "Raster export selection must stay on a single page", and a `.fig` page that has not been shown yet gets its layers, fonts, and layout before a command reads or changes it.diff --git a/README.md b/README.mdindex e211be5e2..0d4a3a34d 100644--- a/README.md+++ b/README.md@@ -140,7 +140,7 @@ Not every provider works in the browser, and not every model streams tool callsUse Claude Code, Codex, or Gemini CLI directly in the chat panel. The agent connects to the editor's MCP server and uses all 100+ design tools. Requires the desktop app and the agent CLI installed locally.-Pi works too: install `@open-pencil/harness` globally, then add a **Pi** model profile in **Settings → AI & agents**.+Pi works too: choose it in guided setup (**Settings → AI & agents → Run guided setup**), which installs the `@open-pencil/harness` companion with one click and uses the providers you signed in to in Pi. The companion needs Node.js 22.15 or later; see [Coding agents](packages/docs/programmable/coding-agents.md#pi).**Setup (Claude Code):**diff --git a/bun.lock b/bun.lockindex ec177432c..0650aec8f 100644--- a/bun.lock+++ b/bun.lock@@ -104,6 +104,7 @@"@figma/plugin-typings": "^1.140.0","@hono/node-server": "^1.19.17","@iconify-json/lucide": "^1.2.139",+ "@lobehub/icons-static-svg": "^1.95.1","@modelcontextprotocol/client": "^2.0.0","@open-pencil/brand-tools": "workspace:*","@open-pencil/mcp": "workspace:*",@@ -1391,6 +1392,8 @@"@loaderkit/resolve": ["@loaderkit/[email protected]", "", { "dependencies": { "@braidai/lang": "^1.0.0" } }, "sha512-G8FdIoF5CypfwmD9rl8BXod5HDn8JqB0CCNBXDTaRZ+yRYhARrrSToX1zg1zy9jX3zLqigsELwhT4gNtkdQAUg=="],+ "@lobehub/icons-static-svg": ["@lobehub/[email protected]", "", {}, "sha512-Hw7EPPgVnC4NZLXBfTNJG6hyQgqECfUPC11VVXodPSr1aebKcFxDZlSpxhWwYNdCc6bhxps/x5TtXoPmfKH2ag=="],+"@marijn/find-cluster-break": ["@marijn/[email protected]", "", {}, "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA=="],"@mariozechner/clipboard": ["@mariozechner/[email protected]", "", { "optionalDependencies": { "@mariozechner/clipboard-darwin-arm64": "0.3.9", "@mariozechner/clipboard-darwin-universal": "0.3.9", "@mariozechner/clipboard-darwin-x64": "0.3.9", "@mariozechner/clipboard-linux-arm64-gnu": "0.3.9", "@mariozechner/clipboard-linux-arm64-musl": "0.3.9", "@mariozechner/clipboard-linux-riscv64-gnu": "0.3.9", "@mariozechner/clipboard-linux-x64-gnu": "0.3.9", "@mariozechner/clipboard-linux-x64-musl": "0.3.9", "@mariozechner/clipboard-win32-arm64-msvc": "0.3.9", "@mariozechner/clipboard-win32-x64-msvc": "0.3.9" } }, "sha512-ABnA53mdfkGZwOFUdZNv2S0CWGO/EIuPj8Vv9xmBFmSYg/qFc7ihO6q5FcQjvoE67kZpWkEc4AhD6B/os04yuA=="],diff --git a/desktop/capabilities/default.json b/desktop/capabilities/default.jsonindex b3251c235..8dda85f65 100644--- a/desktop/capabilities/default.json+++ b/desktop/capabilities/default.json@@ -78,6 +78,7 @@{"identifier": "fs:allow-read-text-file","allow": [+ { "path": "$HOME/.pi/agent/settings.json" },{ "path": "$HOME/Library/Application Support/OpenPencil/mcp.json" },{ "path": "$LOCALDATA/OpenPencil/mcp.json" },{ "path": "$RUNTIME/openpencil/mcp.json" },@@ -97,6 +98,7 @@{"identifier": "fs:allow-exists","allow": [+ { "path": "$HOME/.pi/agent/auth.json" },{ "path": "$HOME/Library/Application Support/OpenPencil/mcp.json" },{ "path": "$LOCALDATA/OpenPencil/mcp.json" },{ "path": "$RUNTIME/openpencil/mcp.json" },@@ -128,11 +130,37 @@{ "name": "claude-agent-acp", "cmd": "claude-agent-acp", "args": false },{ "name": "codex-acp", "cmd": "codex-acp", "args": false },{ "name": "gemini", "cmd": "gemini", "args": ["--acp"] },+ {+ "name": "npm",+ "cmd": "npm",+ "args": [+ "install",+ "--global",+ {+ "validator": "^(@agentclientprotocol/(claude-agent-acp|codex-acp)|@open-pencil/(mcp|harness)@[0-9]+\\.[0-9]+\\.[0-9]+)$"+ },+ "--registry=https://registry.npmjs.org"+ ]+ },{ "name": "openpencil-mcp-http", "cmd": "openpencil-mcp-http", "args": false },{ "name": "openpencil-harness", "cmd": "openpencil-harness", "args": false },{ "name": "cmd-claude-agent-acp", "cmd": "cmd", "args": ["/c", "claude-agent-acp"] },{ "name": "cmd-codex-acp", "cmd": "cmd", "args": ["/c", "codex-acp"] },{ "name": "cmd-gemini", "cmd": "cmd", "args": ["/c", "gemini", "--acp"] },+ {+ "name": "cmd-npm",+ "cmd": "cmd",+ "args": [+ "/c",+ "npm",+ "install",+ "--global",+ {+ "validator": "^(@agentclientprotocol/(claude-agent-acp|codex-acp)|@open-pencil/(mcp|harness)@[0-9]+\\.[0-9]+\\.[0-9]+)$"+ },+ "--registry=https://registry.npmjs.org"+ ]+ },{ "name": "cmd-openpencil-mcp-http", "cmd": "cmd", "args": ["/c", "openpencil-mcp-http"] },{ "name": "cmd-openpencil-harness", "cmd": "cmd", "args": ["/c", "openpencil-harness"] }]diff --git a/desktop/src/agents.rs b/desktop/src/agents.rsnew file mode 100644index 000000000..a066e040b--- /dev/null+++ b/desktop/src/agents.rs@@ -0,0 +1,208 @@+use std::collections::BTreeMap;+use std::io::Read;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++// Only inspect known executables. Discovery never launches an agent or reads credentials;+// it runs only OpenPencil's own companions, and only to ask their version.+const EXECUTABLES: &[&str] = &[+ "claude",+ "claude-agent-acp",+ "codex",+ "codex-acp",+ "gemini",+ "openpencil-mcp-http",+ "openpencil-harness",+ "npm",+];++// OpenPencil's own companions, whose installed version must match the app.+const PACKAGES: &[(&str, &str)] = &[+ ("openpencil-mcp-http", "@open-pencil/mcp"),+ ("openpencil-harness", "@open-pencil/harness"),+];++#[derive(serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentLookup {+ executables: BTreeMap<String, Option<String>>,+ /// Versions OpenPencil's companions report for `--version`; `None` when one predates it.+ versions: BTreeMap<String, Option<String>>,+ search_path: String,+}++/// Long enough for a cold Node start, short enough that a companion which ignores the flags+/// and keeps running cannot hold up setup.+const VERSION_TIMEOUT: Duration = Duration::from_secs(5);++/// The version line a companion prints for `--version`, or `None` for anything else.+fn parse_version(output: &str) -> Option<String> {+ let line = output.lines().next()?.trim();+ let mut core = line.split(['-', '+']).next()?.split('.');+ let numeric = (0..3).all(|_| {+ core.next()+ .is_some_and(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))+ });+ (numeric && core.next().is_none()).then(|| line.to_owned())+}++/// Asks one of OpenPencil's own companions for its version. Asking the program reports what+/// actually runs, through npm and bun shims, `.cmd` wrappers on Windows, and version managers.+/// `--help` follows so that a release older than `--version` prints its help and exits; it has+/// no version line, which reads as outdated.+fn companion_version(executable: &Path, search_path: &str, timeout: Duration) -> Option<String> {+ let mut command = Command::new(executable);+ command+ .args(["--version", "--help"])+ .env("PATH", search_path)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null());+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;+ command.creation_flags(CREATE_NO_WINDOW);+ }+ let mut child = command.spawn().ok()?;+ let deadline = Instant::now() + timeout;+ while child.try_wait().ok()?.is_none() {+ if Instant::now() >= deadline {+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ std::thread::sleep(Duration::from_millis(25));+ }+ let mut output = String::new();+ child.stdout.take()?.read_to_string(&mut output).ok()?;+ parse_version(&output)+}++fn lookup_with(+ search_path: String,+ resolve: impl Fn(&str) -> Option<PathBuf>,+ version: impl Fn(&Path) -> Option<String>,+) -> AgentLookup {+ let resolved: BTreeMap<&str, Option<PathBuf>> = EXECUTABLES+ .iter()+ .map(|command| (*command, resolve(command)))+ .collect();+ AgentLookup {+ executables: resolved+ .iter()+ .map(|(command, path)| {+ (+ (*command).to_owned(),+ path.as_ref()+ .map(|path| path.to_string_lossy().into_owned()),+ )+ })+ .collect(),+ versions: PACKAGES+ .iter()+ .map(|(command, package)| {+ let path = resolved.get(command).cloned().flatten();+ ((*package).to_owned(), path.and_then(|path| version(&path)))+ })+ .collect(),+ search_path,+ }+}++#[tauri::command]+pub async fn agent_lookup() -> Result<AgentLookup, String> {+ tauri::async_runtime::spawn_blocking(|| {+ let current = std::env::var("PATH").unwrap_or_default();+ let search_path = crate::augment_path(¤t, &crate::mcp_candidate_dirs());+ let cwd = std::env::current_dir().unwrap_or_else(|_| Path::new("/").to_path_buf());+ lookup_with(+ search_path.clone(),+ |command| which::which_in(command, Some(&search_path), &cwd).ok(),+ |executable| companion_version(executable, &search_path, VERSION_TIMEOUT),+ )+ })+ .await+ .map_err(|_| "Could not discover local agents.".to_owned())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reports_the_adapter_missing_when_only_the_agent_cli_is_installed() {+ let result = lookup_with(+ "/agents/bin".to_owned(),+ |command| match command {+ "claude" | "npm" | "openpencil-mcp-http" => {+ Some(PathBuf::from("/agents/bin").join(command))+ }+ _ => None,+ },+ |_| Some("0.15.1".to_owned()),+ );+ assert_eq!(+ result.executables["claude"],+ Some("/agents/bin/claude".to_owned())+ );+ assert_eq!(result.executables["claude-agent-acp"], None);+ assert_eq!(+ result.versions["@open-pencil/mcp"],+ Some("0.15.1".to_owned())+ );+ assert_eq!(result.versions["@open-pencil/harness"], None);+ }++ #[test]+ fn reads_only_a_version_line() {+ assert_eq!(parse_version("0.15.1\n"), Some("0.15.1".to_owned()));+ assert_eq!(+ parse_version("1.0.0-beta.2\n"),+ Some("1.0.0-beta.2".to_owned())+ );+ // A release older than `--version` prints its help instead.+ assert_eq!(+ parse_version("openpencil-mcp-http\n\nStart the server."),+ None+ );+ assert_eq!(parse_version("1.2\n"), None);+ assert_eq!(parse_version(""), None);+ }++ #[cfg(unix)]+ fn script(name: &str, body: &str) -> PathBuf {+ use std::os::unix::fs::PermissionsExt;+ let dir = std::env::temp_dir().join(format!("openpencil-agents-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join(name);+ std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ path+ }++ #[cfg(unix)]+ #[test]+ fn asks_a_companion_for_its_version() {+ let current = script("current", "echo 0.15.1");+ let path = std::env::var("PATH").unwrap_or_default();+ assert_eq!(+ companion_version(¤t, &path, VERSION_TIMEOUT),+ Some("0.15.1".to_owned())+ );+ }++ #[cfg(unix)]+ #[test]+ fn stops_a_companion_that_ignores_the_flags() {+ let stuck = script("stuck", "sleep 30");+ let path = std::env::var("PATH").unwrap_or_default();+ let started = Instant::now();+ assert_eq!(+ companion_version(&stuck, &path, Duration::from_millis(200)),+ None+ );+ assert!(started.elapsed() < Duration::from_secs(5));+ }+}diff --git a/desktop/src/deep_link.rs b/desktop/src/deep_link.rsindex 7882ea2b4..23b920c4f 100644--- a/desktop/src/deep_link.rs+++ b/desktop/src/deep_link.rs@@ -18,6 +18,7 @@ pub struct DeepLinkJoin {pub enum DeepLink {Open(DeepLinkOpen),Join(DeepLinkJoin),+ OAuth(OAuthCallback),}#[derive(Debug, PartialEq, Eq)]@@ -28,6 +29,7 @@ pub enum DeepLinkError {ParentSegment,BadExtension,BadRoom,+ BadOAuthProvider,}/// Room IDs are 32 lowercase base36 characters (`ROOM_ID_LENGTH` and `ROOM_ID_CHARS` in@@ -46,6 +48,9 @@ pub fn parse_deep_link(url: &Url) -> Result<DeepLink, DeepLinkError> {match url.host_str().unwrap_or("") {"open" => parse_open_url(url).map(DeepLink::Open),"join" => parse_join_url(url).map(DeepLink::Join),+ "oauth" => parse_oauth_url(url)+ .map(DeepLink::OAuth)+ .ok_or(DeepLinkError::BadOAuthProvider),action => Err(DeepLinkError::UnknownAction(action.to_string())),}}@@ -60,6 +65,31 @@ fn parse_join_url(url: &Url) -> Result<DeepLinkJoin, DeepLinkError> {Ok(DeepLinkJoin { room })}+/// An OAuth redirect relayed by the web app's callback page: `openpencil://oauth/<provider>?…`.+/// The query goes to the webview untouched; the attempt that started sign-in checks its state.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct OAuthCallback {+ pub provider: String,+ pub query: String,+}++pub fn parse_oauth_url(url: &Url) -> Option<OAuthCallback> {+ if url.host_str() != Some("oauth") {+ return None;+ }+ let provider = url.path().strip_prefix('/')?;+ if provider.is_empty() || !provider.bytes().all(|byte| byte.is_ascii_lowercase()) {+ return None;+ }+ Some(OAuthCallback {+ provider: provider.to_owned(),+ query: url+ .query()+ .map(|query| format!("?{query}"))+ .unwrap_or_default(),+ })+}+pub fn parse_open_url(url: &Url) -> Result<DeepLinkOpen, DeepLinkError> {let action = url.host_str().unwrap_or("");if action != "open" {@@ -171,6 +201,28 @@ fn path_ends_with_segments(candidate: &Path, suffix: &str) -> bool {mod tests {use super::*;+ fn oauth(url: &str) -> Option<OAuthCallback> {+ parse_oauth_url(&Url::parse(url).unwrap())+ }++ #[test]+ fn passes_an_oauth_redirect_through_with_its_provider() {+ assert_eq!(+ oauth("openpencil://oauth/openrouter?code=abc&state=xyz"),+ Some(OAuthCallback {+ provider: "openrouter".to_owned(),+ query: "?code=abc&state=xyz".to_owned(),+ })+ );+ }++ #[test]+ fn refuses_an_oauth_link_without_a_plain_provider() {+ assert_eq!(oauth("openpencil://oauth?code=abc"), None);+ assert_eq!(oauth("openpencil://oauth/open/router?code=abc"), None);+ assert_eq!(oauth("openpencil://open?file=a.pen"), None);+ }+fn parse(s: &str) -> Result<DeepLinkOpen, DeepLinkError> {parse_open_url(&Url::parse(s).unwrap())}diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex 9dbc3744b..866b78f87 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -1,3 +1,4 @@+mod agents;mod credentials;mod deep_link;mod fig_container;@@ -9,8 +10,8 @@ mod menu_events;mod window;use credentials::{- credential_access_paused, credential_retry_access, credential_read, credential_remove, credential_status, credential_store_availability,- credential_write,+ credential_access_paused, credential_read, credential_remove, credential_retry_access,+ credential_status, credential_store_availability, credential_write,};use deep_link::path_matches_suffix;use fig_container::build_fig_file;@@ -265,6 +266,13 @@ fn queue_deep_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, urls: Vec<url:deep_link: true,}),Ok(deep_link::DeepLink::Join(join)) => rooms.push(join.room),+ // The sign-in that opened the browser is waiting; it checks the state itself.+ Ok(deep_link::DeepLink::OAuth(callback)) => {+ let _ = app.emit("oauth-callback", callback);+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_focus();+ }+ }Err(error) => eprintln!("[deep-link] refused {url}: {error:?}"),}}@@ -331,6 +339,7 @@ pub fn run() {.manage(PendingOpen(Mutex::new(Vec::new()))).manage(PendingRooms(Mutex::new(Vec::new()))).invoke_handler(tauri::generate_handler![+ agents::agent_lookup,build_fig_file,credential_read,credential_access_paused,diff --git a/package.json b/package.jsonindex 3e6659208..2a219dd25 100644--- a/package.json+++ b/package.json@@ -199,6 +199,7 @@"@figma/plugin-typings": "^1.140.0","@hono/node-server": "^1.19.17","@iconify-json/lucide": "^1.2.139",+ "@lobehub/icons-static-svg": "^1.95.1","@modelcontextprotocol/client": "^2.0.0","@open-pencil/brand-tools": "workspace:*","@open-pencil/mcp": "workspace:*",diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 8d0997c18..328485f49 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -179,6 +179,12 @@ export interface ACPAgentDef {name: stringcommand: stringargs: string[]+ /** The agent's own CLI, when the ACP program is a separate adapter for it. */+ cliCommand?: string+ /** npm package that provides `command` when it is an adapter. */+ adapterPackage?: string+ /** The vendor's installation guide for the agent itself. */+ setupURL?: stringinstallCommand?: string}@@ -188,6 +194,9 @@ export const ACP_AGENTS: ACPAgentDef[] = [name: 'Claude Code',command: 'claude-agent-acp',args: [],+ cliCommand: 'claude',+ adapterPackage: '@agentclientprotocol/claude-agent-acp',+ setupURL: 'https://code.claude.com/docs/en/setup',installCommand: 'npm i -g @agentclientprotocol/claude-agent-acp'},{@@ -195,13 +204,17 @@ export const ACP_AGENTS: ACPAgentDef[] = [name: 'Codex',command: 'codex-acp',args: [],- installCommand: 'npm i -g @zed-industries/codex-acp'+ cliCommand: 'codex',+ adapterPackage: '@agentclientprotocol/codex-acp',+ setupURL: 'https://developers.openai.com/codex/cli',+ installCommand: 'npm i -g @agentclientprotocol/codex-acp'},{id: 'gemini-cli',name: 'Gemini CLI',command: 'gemini',args: ['--acp'],+ setupURL: 'https://geminicli.com/docs/get-started/installation/',installCommand: 'npm i -g @google/gemini-cli'}]@@ -246,7 +259,7 @@ export const AI_PROVIDERS: AIProviderDef[] = [{id: HARNESS_PROVIDER_ID,name: 'Pi',- keyPlaceholder: 'Provider API key',+ keyPlaceholder: 'AI Gateway key (optional)',keyURL: '',defaultModel: '',supportsCustomModel: true,diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsindex e6fcd38ea..70ce3e930 100644--- a/packages/docs/.vitepress/sidebars.ts+++ b/packages/docs/.vitepress/sidebars.ts@@ -74,6 +74,7 @@ export const programmableSidebar = ({ text: labels.aiChat, link: `${prefix}/programmable/ai-chat` },...(!prefix? [+ { text: 'Coding agents', link: '/programmable/coding-agents' },{text: 'BYOK Compatibility',link: '/programmable/byok-provider-compatibility',diff --git a/packages/docs/de/programmable/ai-chat.md b/packages/docs/de/programmable/ai-chat.mdindex ed31f43d3..1c7b0e847 100644--- a/packages/docs/de/programmable/ai-chat.md+++ b/packages/docs/de/programmable/ai-chat.md@@ -9,6 +9,8 @@ description: Integrierter AI-Assistent mit mehr als 90 Werkzeugen zum Erstellen## Einrichtung+Beim ersten Start fragt die geführte Einrichtung, wobei die KI helfen soll und was bereits vorhanden ist: ein Coding-Agent wie Claude Code, Codex oder Gemini CLI in der Desktop-App, ein API-Konto oder ein lokaler bzw. Firmenserver. Sie verbindet diesen Zugang und weist ihn den Rollen **Design agent** und **Vision** zu; manuell Eingerichtetes bleibt erhalten. Bei OpenRouter genügt eine Anmeldung statt eines eingefügten API-Schlüssels. Sie lässt sich überspringen und jederzeit über **Einstellungen → KI und Agenten → Geführte Einrichtung starten** erneut ausführen. Modelle manuell einrichten:+1. AI-Chat öffnen.2. Einstellungssymbol wählen.3. Modell hinzufügen und Anbieter, Modellkennung, Zugangsdaten und Fähigkeiten konfigurieren.diff --git a/packages/docs/es/programmable/ai-chat.md b/packages/docs/es/programmable/ai-chat.mdindex 48401e2d7..98b8de277 100644--- a/packages/docs/es/programmable/ai-chat.md+++ b/packages/docs/es/programmable/ai-chat.md@@ -9,6 +9,8 @@ Pulsa <kbd>⌘</kbd><kbd>J</kbd> o <kbd>Ctrl</kbd><kbd>J</kbd>. El asistente pue## Configurar modelos+La primera vez que abres OpenPencil, la configuración guiada pregunta en qué debe ayudarte la IA y qué usas ya: un agente de programación como Claude Code, Codex o Gemini CLI en la aplicación de escritorio, una cuenta de API o un servidor local o de la empresa. Conecta ese acceso y lo asigna a los roles **Design agent** y **Vision**, sin tocar lo que configuraste a mano. Con OpenRouter puedes iniciar sesión en lugar de pegar una clave de API. Puedes omitirla y volver a ejecutarla desde **Ajustes → IA y agentes → Iniciar la configuración guiada**. Para configurar los modelos a mano:+1. Abre el chat.2. Selecciona el icono de ajustes.3. Añade un perfil y configura conexión, identificador del modelo, credenciales y capacidades.diff --git a/packages/docs/fr/programmable/ai-chat.md b/packages/docs/fr/programmable/ai-chat.mdindex 4f6aa7295..7a6273eda 100644--- a/packages/docs/fr/programmable/ai-chat.md+++ b/packages/docs/fr/programmable/ai-chat.md@@ -9,6 +9,8 @@ Appuyez sur <kbd>⌘</kbd><kbd>J</kbd> ou <kbd>Ctrl</kbd><kbd>J</kbd>. L’assis## Configurer les modèles+Au premier lancement, la configuration guidée demande pour quoi l’IA doit vous aider et ce que vous utilisez déjà : un agent de code comme Claude Code, Codex ou Gemini CLI dans l’application de bureau, un compte API, ou un serveur local ou d’entreprise. Elle connecte cet accès et l’attribue aux rôles **Design agent** et **Vision**, sans toucher à ce que vous avez configuré à la main. Avec OpenRouter, il suffit de se connecter au lieu de coller une clé API. Vous pouvez la passer et la relancer depuis **Réglages → IA et agents → Lancer la configuration guidée**. Pour configurer les modèles à la main :+1. Ouvrez le chat.2. Sélectionnez l’icône des réglages.3. Ajoutez un profil et configurez la connexion, l’identifiant du modèle, les identifiants d’accès et les capacités.diff --git a/packages/docs/it/programmable/ai-chat.md b/packages/docs/it/programmable/ai-chat.mdindex d211984a5..2135797ed 100644--- a/packages/docs/it/programmable/ai-chat.md+++ b/packages/docs/it/programmable/ai-chat.md@@ -9,6 +9,8 @@ Premi <kbd>⌘</kbd><kbd>J</kbd> o <kbd>Ctrl</kbd><kbd>J</kbd>. L’assistente p## Configurare i modelli+Al primo avvio, la configurazione guidata chiede in cosa deve aiutarti l’IA e cosa usi già: un agente di programmazione come Claude Code, Codex o Gemini CLI nell’app desktop, un account API o un server locale o aziendale. Collega quell’accesso e lo assegna ai ruoli **Design agent** e **Vision**, lasciando invariato ciò che hai configurato a mano. Con OpenRouter puoi accedere invece di incollare una chiave API. Puoi saltarla e riavviarla da **Impostazioni → IA e agenti → Avvia la configurazione guidata**. Per configurare i modelli a mano:+1. Apri la chat.2. Seleziona l’icona delle impostazioni.3. Aggiungi un profilo e configura connessione, identificatore del modello, credenziali e capacità.diff --git a/packages/docs/pl/programmable/ai-chat.md b/packages/docs/pl/programmable/ai-chat.mdindex 87a4d0405..862c070f5 100644--- a/packages/docs/pl/programmable/ai-chat.md+++ b/packages/docs/pl/programmable/ai-chat.md@@ -9,6 +9,8 @@ Naciśnij <kbd>⌘</kbd><kbd>J</kbd> albo <kbd>Ctrl</kbd> + <kbd>J</kbd>. Asyste## Konfiguracja+Przy pierwszym uruchomieniu konfiguracja z przewodnikiem pyta, w czym ma pomagać AI i z czego już korzystasz: z agenta programistycznego, takiego jak Claude Code, Codex lub Gemini CLI w aplikacji na komputer, z konta API albo z serwera lokalnego lub firmowego. Łączy ten dostęp i przypisuje go do ról **Design agent** i **Vision**, nie zmieniając ręcznej konfiguracji. W przypadku OpenRouter wystarczy się zalogować zamiast wklejać klucz API. Możesz ją pominąć i uruchomić ponownie w **Ustawienia → AI i agenci → Uruchom konfigurację z przewodnikiem**. Aby skonfigurować modele ręcznie:+1. Otwórz panel czatu AI.2. Kliknij ikonę ustawień.3. Dodaj model i skonfiguruj dostawcę, identyfikator modelu, dane uwierzytelniające oraz możliwości.diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.mdindex 1016e4c9a..fffc5b2e6 100644--- a/packages/docs/programmable/ai-chat.md+++ b/packages/docs/programmable/ai-chat.md@@ -9,6 +9,8 @@ Press <kbd>⌘</kbd><kbd>J</kbd> (<kbd>Ctrl</kbd> + <kbd>J</kbd>) to open the AI## Setup+The first time you open OpenPencil, guided setup asks what AI should help with and what you already use: a [coding agent](./coding-agents) such as Claude Code, Codex, Gemini CLI, or Pi in the desktop app, an API account, or a local or company server. It connects that access and assigns it to the **Design agent** and **Vision** roles, keeping anything you configured by hand. With OpenRouter you can sign in instead of pasting an API key. Skip it to start designing, and run it again from **Settings → AI & agents → Run guided setup**. To configure models by hand:+1. Open the AI chat panel (<kbd>⌘</kbd><kbd>J</kbd>)2. Click the settings icon3. Add a model and configure its provider, model ID, credentials, and capabilitiesdiff --git a/packages/docs/programmable/coding-agents.md b/packages/docs/programmable/coding-agents.mdnew file mode 100644index 000000000..0719c09ef--- /dev/null+++ b/packages/docs/programmable/coding-agents.md@@ -0,0 +1,66 @@+# Coding agents++The OpenPencil desktop app can use a coding agent you already have — Claude Code, Codex, Gemini CLI, or [Pi](#pi) — as its design agent. The agent runs on your computer with your own subscription and chooses its own model; OpenPencil starts it when you send a message, through the [Agent Client Protocol](https://agentclientprotocol.com/) or, for Pi, its Harness companion, and gives it the canvas tools through OpenPencil's local [MCP server](./mcp-server).++Coding agents need the desktop app; the browser cannot start programs on your computer. They take only the **Design agent** role. Visual review, plan reviews, and fast background work need an API model, which guided setup can add for you.++## What you need++1. The [OpenPencil desktop app](https://github.com/open-pencil/open-pencil/releases/latest).+2. The agent's ACP program, installed globally (see each agent below).+3. OpenPencil's MCP server, installed globally. Use the version that matches your app:++ ```sh+ npm install -g @open-pencil/mcp+ ```++4. The agent signed in to your account with its own command-line tool.++Then open **Settings → AI & agents → Run guided setup**, choose the agent under **Coding agents on this computer**, and check that both the agent and the MCP server show as installed. **Check again** looks again after you install something.++### Let your agent set itself up++If you already use one of these agents in a terminal, guided setup can do the typing for you: press **Copy setup prompt** on the agent's card and paste the prompt into the agent. It asks the agent to install its ACP program and the MCP server, confirm both are on your `PATH`, and make sure you are signed in.++## Claude Code++```sh+npm install -g @agentclientprotocol/claude-agent-acp+```++Sign in by running `claude` and using `/login`. The ACP program uses the same account as Claude Code.++## Codex++```sh+npm install -g @agentclientprotocol/codex-acp+```++Sign in with `codex login`.++## Gemini CLI++```sh+npm install -g @google/gemini-cli+```++Gemini CLI speaks ACP itself, so there is no separate program. Run `gemini` once and choose a sign-in method.++## Pi++Pi runs through OpenPencil's Harness companion instead of ACP. It needs Node.js 22.15 or later, or Bun. Guided setup installs the companion with one click; to install it yourself, use the version that matches your app:++```sh+npm install -g @open-pencil/harness+```++OpenPencil uses the providers you signed in to in Pi and Pi's default model, so there is no key to paste. Sign in by running `pi` and using `/login`, and pick a default model with `/model`. To use another model in OpenPencil, enter it as `provider/model` in the Pi model's settings. An [AI Gateway](https://vercel.com/ai-gateway) key is optional; when you save one, Pi uses the gateway instead of your Pi sign-ins.++OpenPencil reads only Pi's `settings.json` for the default model; your credentials stay with Pi. Your Pi extensions, themes, and prompt templates are not loaded into OpenPencil's sessions. Pi keeps a conversation's context while it runs; after Pi or OpenPencil restarts, the conversation continues in a fresh Pi session, because Pi's workspace lives in memory.++## Troubleshooting++- **Shown as not found after installing.** Apps started from the Dock or Start menu do not see every folder your terminal adds to `PATH`. OpenPencil also looks in common global folders for npm, Bun, Volta, mise, and Homebrew; if your package manager installs elsewhere, add that folder to your login shell's `PATH` and restart OpenPencil.+- **Shown as update needed.** The MCP server or Pi's companion does not match the app version. Press the update button, or run the command guided setup shows with the package manager that installed it, then press **Check again**. A chat that needs it says so and offers **Run guided setup**.+- **The agent starts but cannot edit the canvas.** The MCP server is missing or not running. Install the matching `@open-pencil/mcp` version and restart OpenPencil.+- **The agent asks you to sign in.** Sign in with the agent's own command-line tool as described above, then send your message again.diff --git a/packages/docs/ru/programmable/ai-chat.md b/packages/docs/ru/programmable/ai-chat.mdindex faf691859..440c1be13 100644--- a/packages/docs/ru/programmable/ai-chat.md+++ b/packages/docs/ru/programmable/ai-chat.md@@ -9,6 +9,8 @@ description: Встроенный помощник с более чем 90 ин## Настройка+При первом запуске пошаговая настройка спрашивает, с чем должен помогать ИИ и чем вы уже пользуетесь: агентом для программирования вроде Claude Code, Codex или Gemini CLI в настольном приложении, аккаунтом API или локальным либо корпоративным сервером. Она подключает этот доступ и назначает его ролям **Design agent** и **Vision**, не меняя то, что вы настроили вручную. Для OpenRouter достаточно войти в аккаунт вместо вставки ключа API. Её можно пропустить и запустить снова в **Настройки → ИИ и агенты → Пройти пошаговую настройку**. Чтобы настроить модели вручную:+1. Откройте панель чата.2. Нажмите значок настроек.3. Добавьте модель и настройте поставщика, идентификатор модели, учётные данные и возможности.diff --git a/packages/harness/src/stdio.ts b/packages/harness/src/stdio.tsindex 0299e1b9e..f69d9dbce 100644--- a/packages/harness/src/stdio.ts+++ b/packages/harness/src/stdio.ts@@ -13,6 +13,14 @@ import { HarnessSessionService } from '#harness/service'import { FileResumeStateStore } from '#harness/session-store'import { loadTypeScriptDependencies } from '#harness/typescript-dependencies'+import packageJSON from '../package.json' with { type: 'json' }++// The app reads this to check that the companion matches it, before anything else starts.+if (process.argv.includes('--version')) {+ process.stdout.write(`${packageJSON.version}\n`)+ process.exit(0)+}+const writeProtocol = reserveProtocolOutput()loadTypeScriptDependencies()diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex ee6eda3a2..40a3324f0 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -1,9 +1,14 @@#!/usr/bin/env nodeimport { resolveMCPRoot } from '#mcp/root'-import { startServer } from '#mcp/server'+import { MCP_VERSION, startServer } from '#mcp/server'import { readToolPolicyFromEnv } from '#mcp/tool/policy'import { resolveCORSOrigins } from '#mcp/transport/origins'+if (process.argv.includes('--version')) {+ process.stdout.write(`${MCP_VERSION}\n`)+ process.exit(0)+}+if (process.argv.includes('--help') || process.argv.includes('-h')) {process.stdout.write(`openpencil-mcp-http\n\n` +@@ -11,7 +16,8 @@ if (process.argv.includes('--help') || process.argv.includes('-h')) {`On macOS/Linux, the server listens on a Unix domain socket by default\n` +`with optional TCP for browser clients. On Windows, only TCP is available.\n\n` +`Options:\n` +- ` --help, -h Show this help message\n\n` ++ ` --help, -h Show this help message\n` ++ ` --version Print the version\n\n` +`Environment variables:\n` +` PORT TCP port (default: 7600, set to 0 to disable TCP)\n` +` OPENPENCIL_MCP_SOCKET Override Unix socket path (recorded in the discovery file)\n` +diff --git a/packages/mcp/src/stdio.ts b/packages/mcp/src/stdio.tsindex 389d331c9..cf259f90c 100644--- a/packages/mcp/src/stdio.ts+++ b/packages/mcp/src/stdio.ts@@ -9,6 +9,11 @@ import type { ToolPolicy } from '#mcp/tool/metadata'import { parseDisabledTools } from '#mcp/tool/policy'import { readDiscoveryFile } from '#mcp/transport/discovery'+if (process.argv.includes('--version')) {+ process.stdout.write(`${MCP_VERSION}\n`)+ process.exit(0)+}+if (process.argv.includes('--help') || process.argv.includes('-h')) {process.stdout.write(`openpencil-mcp\n\n` +@@ -18,7 +23,8 @@ if (process.argv.includes('--help') || process.argv.includes('-h')) {`The MCP server is started by the OpenPencil\n` +`desktop app; this bridge only forwards stdio JSON-RPC to it.\n\n` +`Options:\n` +- ` --help, -h Show this help message\n\n` ++ ` --help, -h Show this help message\n` ++ ` --version Print the version\n\n` +`Environment variables:\n` +` OPENPENCIL_MCP_SOCKET Override socket path (auto-discovered from discovery file when unset)\n` +` OPENPENCIL_MCP_AUTH_TOKEN Bearer token for RPC auth\n` +diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex ce4aa661d..a4436157b 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -136,6 +136,11 @@"chatOutputLimit": "Das Modell hat beim Schlussfolgern das Ausgabetoken-Limit erreicht. Erhöhe die maximalen Ausgabetoken oder verringere den Schlussfolgerungsaufwand.","chatRequestFailed": "Die Modellanfrage ist fehlgeschlagen. Prüfe die Anbietereinstellungen und versuche es erneut.","visionModelUnavailable": "Wähle in den Einstellungen ein Vision-Modell aus, bevor du Bilder anhängst.",+ "chatPiCompanionMissing": "Pi braucht den Harness-Begleiter. Starte die geführte Einrichtung, um ihn zu installieren.",+ "chatPiCompanionOutdated": "Der Harness-Begleiter passt nicht zu dieser OpenPencil-Version. Starte die geführte Einrichtung, um ihn zu aktualisieren.",+ "chatMCPOutdated": "Der MCP-Server von OpenPencil passt nicht zu dieser OpenPencil-Version. Starte die geführte Einrichtung, um ihn zu aktualisieren.",+ "chatPiSignIn": "Pi ist bei keinem Anbieter angemeldet. Starte pi im Terminal und gib /login ein oder füge einen AI-Gateway-Schlüssel hinzu.",+ "chatPiModel": "Pi hat kein Modell. Starte pi im Terminal und gib /model ein oder wähle eines in den Einstellungen.","completions": "Completions","responses": "Responses","connectProvider": "Verbinde einen KI-Anbieter, um den Chat zu starten.",@@ -177,6 +182,95 @@"reasoningExpanded": "Standardmäßig ausgeklappt","jumpToLatest": "Zum neuesten Beitrag","maxAgentStepsCustom": "Eigener Wert…",+ "aiSetupWelcomeTitle": "Willkommen bei OpenPencil",+ "aiSetupWelcomeDescription": "Erstelle und bearbeite Designs auf einer offenen Arbeitsfläche. Importiere Figma-Dateien und mach sie zu deinen eigenen.",+ "aiSetupWelcomeAITitle": "Mit KI gestalten",+ "aiSetupWelcomeAIDescription": "Verbinde die KI, die du bereits nutzt, um die Arbeitsfläche zu bearbeiten und Designs zu prüfen. Du kannst das später in den Einstellungen ändern.",+ "aiSetupStart": "KI einrichten",+ "aiSetupSkip": "Mit dem Gestalten beginnen",+ "aiSetupProgress": "Schritt {current} von {total}",+ "aiSetupAdvanced": "Erweiterte Einstellungen",+ "aiSetupContinue": "Weiter",+ "aiSetupGoalsTitle": "Wobei soll die KI helfen?",+ "aiSetupGoalDesign": "Designs erstellen und bearbeiten",+ "aiSetupGoalDesignDescription": "Beschreibe eine Änderung und lass die KI die Arbeitsfläche bearbeiten.",+ "aiSetupGoalVision": "Designs visuell prüfen",+ "aiSetupGoalVisionDescription": "Lass die KI deine Designs ansehen, um Abstände, Ausrichtung und Hierarchie zu prüfen.",+ "aiSetupAccessTitle": "Was nutzt du bereits?",+ "aiSetupAccessDescription": "Wähle alles aus, was du hast. Wenn du noch nichts hast, mach einfach weiter.",+ "aiSetupAccessAgents": "Coding-Agenten auf diesem Computer",+ "aiSetupAccessAgentsDescription": "Nutze dein bestehendes Abo. Der Agent wählt sein Modell selbst.",+ "aiSetupAccessAgentsDesktop": "Coding-Agenten sind in der Desktop-App von OpenPencil verfügbar.",+ "aiSetupAccessAPI": "API-Konten",+ "aiSetupAccessServer": "Lokales Modell oder Firmenserver",+ "aiSetupAccessServerDescription": "Jeder Server, der die OpenAI-API spricht, etwa Ollama oder LM Studio.",+ "aiSetupConnectTitle": "KI verbinden",+ "aiSetupNothingDescription": "Geh zurück, um etwas anderes zu wählen, oder richte die KI in den erweiterten Einstellungen ein.",+ "aiSetupAgentDescription": "OpenPencil startet {agent}, sobald du eine Nachricht sendest. Melde dich vorher mit dessen eigenem Kommandozeilen-Tool an.",+ "aiSetupAgentInstall": "Falls es noch nicht installiert ist, führe Folgendes aus:",+ "aiSetupMeteredNote": "OpenRouter bietet Modelle mehrerer Anbieter mit einem Konto und einem Schlüssel.",+ "aiSetupReviewTitle": "Einrichtung prüfen",+ "aiSetupAgentModel": "Vom Agenten gewähltes Modell",+ "aiSetupFinish": "Einrichtung abschließen",+ "aiSetupSavedTitle": "Die KI ist bereit",+ "aiSetupSavedDescription": "Du kannst Modelle und Rollen jederzeit in den Einstellungen ändern.",+ "aiSetupRun": "Geführte Einrichtung starten",+ "aiSetupServerKeyHint": "Wenn dein Server keine Schlüssel prüft, gib einen beliebigen Wert ein.",+ "aiSetupAlreadyConnected": "Alles, was du ausgewählt hast, ist bereits verbunden.",+ "aiSetupOpenRouterSignIn": "Mit OpenRouter anmelden",+ "aiSetupOpenRouterWaiting": "Schließe die Anmeldung bei OpenRouter in deinem Browser ab.",+ "aiSetupOpenRouterReopen": "Erneut öffnen",+ "aiSetupOpenRouterOrKey": "Oder einen API-Schlüssel einfügen",+ "aiSetupOpenRouterBlocked": "Dein Browser hat das Anmeldefenster blockiert. Erlaube Pop-ups für OpenPencil und versuche es erneut.",+ "aiSetupOpenRouterCancelled": "Die Anmeldung wurde abgebrochen.",+ "aiSetupOpenRouterExpired": "Die Anmeldung hat zu lange gedauert. Versuche es erneut.",+ "aiSetupOpenRouterFailed": "Die Anmeldung bei OpenRouter ist fehlgeschlagen. Versuche es erneut oder füge einen API-Schlüssel ein.",+ "aiSetupOpenRouterSignedInTitle": "Bei OpenRouter angemeldet",+ "aiSetupSavedKeyHint": "Leer lassen, um den gespeicherten Schlüssel zu behalten.",+ "aiSetupOpenRouterKeyLabel": "· Schlüssel „{label}“",+ "aiSetupOpenRouterVerifying": "Dein OpenRouter-Schlüssel wird geprüft…",+ "aiSetupOpenRouterNoCredits": "Dieses OpenRouter-Konto hat noch kein Guthaben. Lade bei OpenRouter Guthaben auf, um kostenpflichtige Modelle wie das empfohlene zu nutzen.",+ "aiSetupOpenRouterChange": "Anderes Konto verwenden",+ "aiSetupUseRecommended": "Empfohlene Einrichtung verwenden",+ "aiSetupRolesDescription": "Wähle für jede Art von Arbeit ein Modell. Wir haben aus deinen Verbindungen empfohlene ausgewählt; alles andere, was du eingerichtet hast, bleibt unverändert.",+ "aiSetupGapDesign": "Nichts von deiner Auswahl kann Designs erstellen und bearbeiten.",+ "aiSetupGapVision": "Nichts von deiner Auswahl kann Bilder prüfen, daher bliebe die visuelle Prüfung aus.",+ "aiSetupGapContinue": "Du kannst ohne fortfahren und es später in den Einstellungen hinzufügen.",+ "aiSetupGapAddOpenRouter": "OpenRouter hinzufügen (nutzungsbasiert)",+ "aiSetupGapRemoveOpenRouter": "OpenRouter nicht verwenden",+ "aiSetupServerVision": "Dieses Modell kann Bilder lesen",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter übernimmt, was deine übrige Auswahl nicht abdeckt, und rechnet pro Anfrage ab.",+ "aiSetupAccessMore": "Weitere Anbieter",+ "aiSetupServerOther": "Anderer Server",+ "aiSetupAgentChecking": "Dieser Computer wird geprüft…",+ "aiSetupAgentInstalled": "installiert",+ "aiSetupAgentNotFound": "nicht gefunden",+ "aiSetupAgentMCP": "OpenPencil-MCP-Server",+ "aiSetupAgentMCPInstall": "Coding-Agenten greifen über den MCP-Server von OpenPencil auf die Arbeitsfläche zu. Installiere ihn mit:",+ "aiSetupAgentPromptHint": "Nutzt du schon {agent} oder einen anderen Coding-Agenten? Kopiere den Einrichtungs-Prompt und füge ihn dort ein; er installiert, was OpenPencil braucht.",+ "aiSetupAgentCopyPrompt": "Einrichtungs-Prompt kopieren",+ "aiSetupAgentCheckAgain": "Erneut prüfen",+ "aiSetupAgentGuide": "Einrichtungsanleitung",+ "aiSetupPiDescription": "OpenPencil führt Pi über seinen Harness-Begleiter aus und nutzt die Anbieter, bei denen du dich in Pi angemeldet hast.",+ "aiSetupPiCompanion": "Harness-Begleiter",+ "aiSetupPiInstallCompanion": "Begleiter installieren",+ "aiSetupPiUpdateCompanion": "Begleiter aktualisieren",+ "aiSetupPiModel": "Standardmodell von Pi: {model}",+ "aiSetupPiNoModel": "Kein Standardmodell in Pi festgelegt",+ "piModelHint": "Ein Pi-Modell wie provider/model. Leer lassen, um das Standardmodell von Pi zu verwenden.",+ "aiSetupPiSignIn": "Um dich bei einem Anbieter anzumelden oder ein Standardmodell zu wählen, starte pi im Terminal und gib /login oder /model ein.",+ "aiSetupGetDesktop": "Desktop-App herunterladen",+ "aiSetupAgentNeedsAdapter": "installiert · OpenPencil-Adapter fehlt",+ "aiSetupAgentInstallAdapter": "Adapter installieren",+ "aiSetupAgentInstallMCP": "MCP-Server installieren",+ "aiSetupAgentUpdateMCP": "MCP-Server aktualisieren",+ "aiSetupAgentOutdated": "Update nötig",+ "aiSetupAgentInstalling": "Wird installiert…",+ "aiSetupAgentGetCLI": "{agent} installieren",+ "aiSetupAgentNeedsNpm": "Zum Installieren wird npm benötigt, das mit Node.js geliefert wird. Installiere Node.js und prüfe dann erneut.",+ "aiSetupAgentInstallFailed": "Die Installation wurde nicht abgeschlossen. Prüfe deine Verbindung oder führe den Befehl selbst aus.",+ "aiSetupAgentMCPStartFailed": "Der MCP-Server ist installiert, startet aber nicht. Starte OpenPencil neu und prüfe dann erneut.",+ "aiSetupAgentLookupFailed": "Dieser Computer konnte nicht geprüft werden. Versuche es erneut.","chatAgentWorkingOn": "{agent} arbeitet an „{page}“","chatGoToPage": "Zur Seite"}diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 8748e025c..5ddcc9be2 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -142,6 +142,11 @@"chatOutputLimit": "El modelo agotó los tokens de salida mientras razonaba. Aumenta los tokens máximos de salida o reduce el esfuerzo de razonamiento.","chatRequestFailed": "La solicitud al modelo falló. Comprueba la configuración del proveedor e inténtalo de nuevo.","visionModelUnavailable": "Elige un modelo de visión en Ajustes antes de adjuntar imágenes.",+ "chatPiCompanionMissing": "Pi necesita el complemento Harness. Ejecuta la configuración guiada para instalarlo.",+ "chatPiCompanionOutdated": "El complemento Harness no coincide con esta versión de OpenPencil. Ejecuta la configuración guiada para actualizarlo.",+ "chatMCPOutdated": "El servidor MCP de OpenPencil no coincide con esta versión de OpenPencil. Ejecuta la configuración guiada para actualizarlo.",+ "chatPiSignIn": "Pi no ha iniciado sesión en ningún proveedor. Ejecuta pi en una terminal y escribe /login, o añade una clave de AI Gateway.",+ "chatPiModel": "Pi no tiene ningún modelo. Ejecuta pi en una terminal y escribe /model, o elige uno en Ajustes.","completions": "Completions","responses": "Responses","connectProvider": "Conecta un proveedor de IA para empezar a chatear.",@@ -177,6 +182,95 @@"reasoningExpanded": "Expandido por defecto","jumpToLatest": "Ir al último mensaje","maxAgentStepsCustom": "Personalizado…",+ "aiSetupWelcomeTitle": "Te damos la bienvenida a OpenPencil",+ "aiSetupWelcomeDescription": "Crea y edita diseños en un lienzo abierto. Importa archivos de Figma y hazlos tuyos.",+ "aiSetupWelcomeAITitle": "Diseña con IA",+ "aiSetupWelcomeAIDescription": "Conecta la IA que ya usas para editar el lienzo y revisar diseños. Puedes cambiarlo más tarde en Ajustes.",+ "aiSetupStart": "Configurar IA",+ "aiSetupSkip": "Empezar a diseñar",+ "aiSetupProgress": "Paso {current} de {total}",+ "aiSetupAdvanced": "Ajustes avanzados",+ "aiSetupContinue": "Continuar",+ "aiSetupGoalsTitle": "¿En qué debe ayudarte la IA?",+ "aiSetupGoalDesign": "Crear y editar diseños",+ "aiSetupGoalDesignDescription": "Describe un cambio y deja que la IA edite el lienzo.",+ "aiSetupGoalVision": "Revisar diseños visualmente",+ "aiSetupGoalVisionDescription": "Deja que la IA mire tus diseños para revisar espaciado, alineación y jerarquía.",+ "aiSetupAccessTitle": "¿Qué usas ya?",+ "aiSetupAccessDescription": "Selecciona todo lo que tengas. Si aún no tienes nada, continúa.",+ "aiSetupAccessAgents": "Agentes de programación en este equipo",+ "aiSetupAccessAgentsDescription": "Usa tu suscripción actual. El agente elige su propio modelo.",+ "aiSetupAccessAgentsDesktop": "Los agentes de programación están disponibles en la aplicación de escritorio de OpenPencil.",+ "aiSetupAccessAPI": "Cuentas de API",+ "aiSetupAccessServer": "Modelo local o servidor de la empresa",+ "aiSetupAccessServerDescription": "Cualquier servidor compatible con la API de OpenAI, como Ollama o LM Studio.",+ "aiSetupConnectTitle": "Conecta tu IA",+ "aiSetupNothingDescription": "Vuelve atrás para elegir otro acceso o configura la IA en los ajustes avanzados.",+ "aiSetupAgentDescription": "OpenPencil inicia {agent} cuando envías un mensaje. Antes, inicia sesión con su propia herramienta de línea de comandos.",+ "aiSetupAgentInstall": "Si aún no está instalado, ejecuta:",+ "aiSetupMeteredNote": "OpenRouter te da modelos de varios proveedores con una sola cuenta y una sola clave.",+ "aiSetupReviewTitle": "Revisa tu configuración",+ "aiSetupAgentModel": "Modelo elegido por el agente",+ "aiSetupFinish": "Terminar la configuración",+ "aiSetupSavedTitle": "La IA está lista",+ "aiSetupSavedDescription": "Puedes cambiar los modelos y los roles en cualquier momento en Ajustes.",+ "aiSetupRun": "Iniciar la configuración guiada",+ "aiSetupServerKeyHint": "Si tu servidor no comprueba claves, escribe cualquier valor.",+ "aiSetupAlreadyConnected": "Todo lo que seleccionaste ya está conectado.",+ "aiSetupOpenRouterSignIn": "Iniciar sesión con OpenRouter",+ "aiSetupOpenRouterWaiting": "Termina de iniciar sesión en OpenRouter en tu navegador.",+ "aiSetupOpenRouterReopen": "Abrir de nuevo",+ "aiSetupOpenRouterOrKey": "O pega una clave de API",+ "aiSetupOpenRouterBlocked": "Tu navegador bloqueó la ventana de inicio de sesión. Permite ventanas emergentes para OpenPencil y vuelve a intentarlo.",+ "aiSetupOpenRouterCancelled": "Se canceló el inicio de sesión.",+ "aiSetupOpenRouterExpired": "El inicio de sesión tardó demasiado. Vuelve a intentarlo.",+ "aiSetupOpenRouterFailed": "No se pudo iniciar sesión en OpenRouter. Vuelve a intentarlo o pega una clave de API.",+ "aiSetupOpenRouterSignedInTitle": "Sesión iniciada en OpenRouter",+ "aiSetupSavedKeyHint": "Déjalo en blanco para conservar la clave guardada.",+ "aiSetupOpenRouterKeyLabel": "· clave «{label}»",+ "aiSetupOpenRouterVerifying": "Comprobando tu clave de OpenRouter…",+ "aiSetupOpenRouterNoCredits": "Esta cuenta de OpenRouter aún no tiene créditos. Añade créditos en OpenRouter para usar modelos de pago como el recomendado.",+ "aiSetupOpenRouterChange": "Usar otra cuenta",+ "aiSetupUseRecommended": "Usar la configuración recomendada",+ "aiSetupRolesDescription": "Elige un modelo para cada tipo de trabajo. Elegimos los recomendados entre lo que conectaste; todo lo demás que configuraste se mantiene igual.",+ "aiSetupGapDesign": "Nada de lo que elegiste puede crear y editar diseños.",+ "aiSetupGapVision": "Nada de lo que elegiste puede revisar imágenes, así que la revisión visual quedaría desactivada.",+ "aiSetupGapContinue": "Puedes continuar sin ello y añadirlo más tarde en Ajustes.",+ "aiSetupGapAddOpenRouter": "Añadir OpenRouter (pago por uso)",+ "aiSetupGapRemoveOpenRouter": "No usar OpenRouter",+ "aiSetupServerVision": "Este modelo puede leer imágenes",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter cubrirá lo que no cubre el resto de tu elección, con cobro por solicitud.",+ "aiSetupAccessMore": "Más proveedores",+ "aiSetupServerOther": "Otro servidor",+ "aiSetupAgentChecking": "Comprobando este equipo…",+ "aiSetupAgentInstalled": "instalado",+ "aiSetupAgentNotFound": "no encontrado",+ "aiSetupAgentMCP": "Servidor MCP de OpenPencil",+ "aiSetupAgentMCPInstall": "Los agentes de programación acceden al lienzo a través del servidor MCP de OpenPencil. Instálalo con:",+ "aiSetupAgentPromptHint": "¿Ya usas {agent} u otro agente de programación? Copia el prompt de configuración y pégalo allí; instalará lo que OpenPencil necesita.",+ "aiSetupAgentCopyPrompt": "Copiar prompt de configuración",+ "aiSetupAgentCheckAgain": "Comprobar de nuevo",+ "aiSetupAgentGuide": "Guía de configuración",+ "aiSetupPiDescription": "OpenPencil ejecuta Pi mediante su complemento Harness y usa los proveedores en los que iniciaste sesión en Pi.",+ "aiSetupPiCompanion": "Complemento Harness",+ "aiSetupPiInstallCompanion": "Instalar complemento",+ "aiSetupPiUpdateCompanion": "Actualizar complemento",+ "aiSetupPiModel": "Modelo predeterminado de Pi: {model}",+ "aiSetupPiNoModel": "Pi no tiene un modelo predeterminado",+ "piModelHint": "Un modelo de Pi como provider/model. Déjalo vacío para usar el modelo predeterminado de Pi.",+ "aiSetupPiSignIn": "Para iniciar sesión en un proveedor o elegir un modelo predeterminado, ejecuta pi en una terminal y escribe /login o /model.",+ "aiSetupGetDesktop": "Descargar la aplicación de escritorio",+ "aiSetupAgentNeedsAdapter": "instalado · falta el adaptador de OpenPencil",+ "aiSetupAgentInstallAdapter": "Instalar adaptador",+ "aiSetupAgentInstallMCP": "Instalar servidor MCP",+ "aiSetupAgentUpdateMCP": "Actualizar servidor MCP",+ "aiSetupAgentOutdated": "requiere actualización",+ "aiSetupAgentInstalling": "Instalando…",+ "aiSetupAgentGetCLI": "Instalar {agent}",+ "aiSetupAgentNeedsNpm": "Para instalar hace falta npm, que viene con Node.js. Instala Node.js y vuelve a comprobar.",+ "aiSetupAgentInstallFailed": "La instalación no terminó. Revisa tu conexión o ejecuta el comando tú mismo.",+ "aiSetupAgentMCPStartFailed": "El servidor MCP está instalado pero no se inició. Reinicia OpenPencil y vuelve a comprobar.",+ "aiSetupAgentLookupFailed": "No se pudo comprobar este equipo. Vuelve a intentarlo.","chatAgentWorkingOn": "{agent} está trabajando en «{page}»","chatGoToPage": "Ir a la página"}diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex aa3a8f87a..0a11d4084 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -136,6 +136,11 @@"chatOutputLimit": "Le modèle a épuisé ses jetons de sortie pendant le raisonnement. Augmentez le nombre maximal de jetons de sortie ou réduisez l’effort de raisonnement.","chatRequestFailed": "La requête au modèle a échoué. Vérifiez les paramètres du fournisseur et réessayez.","visionModelUnavailable": "Choisissez un modèle Vision dans les paramètres avant de joindre des images.",+ "chatPiCompanionMissing": "Pi a besoin du compagnon Harness. Lancez la configuration guidée pour l’installer.",+ "chatPiCompanionOutdated": "Le compagnon Harness ne correspond pas à cette version d’OpenPencil. Lancez la configuration guidée pour le mettre à jour.",+ "chatMCPOutdated": "Le serveur MCP d’OpenPencil ne correspond pas à cette version d’OpenPencil. Lancez la configuration guidée pour le mettre à jour.",+ "chatPiSignIn": "Pi n’est connecté à aucun fournisseur. Lancez pi dans un terminal et tapez /login, ou ajoutez une clé AI Gateway.",+ "chatPiModel": "Pi n’a aucun modèle. Lancez pi dans un terminal et tapez /model, ou choisissez-en un dans les réglages.","completions": "Completions","responses": "Responses","connectProvider": "Connectez un fournisseur d’IA pour commencer à discuter.",@@ -177,6 +182,95 @@"reasoningExpanded": "Déplié par défaut","jumpToLatest": "Aller au dernier message","maxAgentStepsCustom": "Personnalisé…",+ "aiSetupWelcomeTitle": "Bienvenue dans OpenPencil",+ "aiSetupWelcomeDescription": "Créez et modifiez des designs sur un canevas ouvert. Importez des fichiers Figma et appropriez-vous-les.",+ "aiSetupWelcomeAITitle": "Concevez avec l’IA",+ "aiSetupWelcomeAIDescription": "Connectez l’IA que vous utilisez déjà pour modifier le canevas et relire vos designs. Vous pourrez la changer plus tard dans les réglages.",+ "aiSetupStart": "Configurer l’IA",+ "aiSetupSkip": "Commencer à concevoir",+ "aiSetupProgress": "Étape {current} sur {total}",+ "aiSetupAdvanced": "Réglages avancés",+ "aiSetupContinue": "Continuer",+ "aiSetupGoalsTitle": "Pour quoi l’IA doit-elle vous aider ?",+ "aiSetupGoalDesign": "Créer et modifier des designs",+ "aiSetupGoalDesignDescription": "Décrivez une modification et laissez l’IA modifier le canevas.",+ "aiSetupGoalVision": "Relire les designs visuellement",+ "aiSetupGoalVisionDescription": "Laissez l’IA regarder vos designs pour vérifier l’espacement, l’alignement et la hiérarchie.",+ "aiSetupAccessTitle": "Qu’utilisez-vous déjà ?",+ "aiSetupAccessDescription": "Sélectionnez tout ce que vous avez. Si vous n’avez encore rien, continuez.",+ "aiSetupAccessAgents": "Agents de code sur cet ordinateur",+ "aiSetupAccessAgentsDescription": "Utilisez votre abonnement existant. L’agent choisit son propre modèle.",+ "aiSetupAccessAgentsDesktop": "Les agents de code sont disponibles dans l’application de bureau OpenPencil.",+ "aiSetupAccessAPI": "Comptes API",+ "aiSetupAccessServer": "Modèle local ou serveur d’entreprise",+ "aiSetupAccessServerDescription": "Tout serveur compatible avec l’API OpenAI, comme Ollama ou LM Studio.",+ "aiSetupConnectTitle": "Connectez votre IA",+ "aiSetupNothingDescription": "Revenez en arrière pour choisir un autre accès, ou configurez l’IA dans les réglages avancés.",+ "aiSetupAgentDescription": "OpenPencil lance {agent} quand vous envoyez un message. Connectez-vous d’abord avec son propre outil en ligne de commande.",+ "aiSetupAgentInstall": "S’il n’est pas encore installé, exécutez :",+ "aiSetupMeteredNote": "OpenRouter donne accès aux modèles de plusieurs fournisseurs avec un seul compte et une seule clé.",+ "aiSetupReviewTitle": "Vérifiez votre configuration",+ "aiSetupAgentModel": "Modèle choisi par l’agent",+ "aiSetupFinish": "Terminer la configuration",+ "aiSetupSavedTitle": "L’IA est prête",+ "aiSetupSavedDescription": "Vous pouvez changer les modèles et les rôles à tout moment dans les réglages.",+ "aiSetupRun": "Lancer la configuration guidée",+ "aiSetupServerKeyHint": "Si votre serveur ne vérifie pas les clés, saisissez n’importe quelle valeur.",+ "aiSetupAlreadyConnected": "Tout ce que vous avez sélectionné est déjà connecté.",+ "aiSetupOpenRouterSignIn": "Se connecter avec OpenRouter",+ "aiSetupOpenRouterWaiting": "Terminez la connexion à OpenRouter dans votre navigateur.",+ "aiSetupOpenRouterReopen": "Rouvrir",+ "aiSetupOpenRouterOrKey": "Ou collez une clé API",+ "aiSetupOpenRouterBlocked": "Votre navigateur a bloqué la fenêtre de connexion. Autorisez les fenêtres contextuelles pour OpenPencil, puis réessayez.",+ "aiSetupOpenRouterCancelled": "La connexion a été annulée.",+ "aiSetupOpenRouterExpired": "La connexion a pris trop de temps. Réessayez.",+ "aiSetupOpenRouterFailed": "Impossible de se connecter à OpenRouter. Réessayez ou collez une clé API.",+ "aiSetupOpenRouterSignedInTitle": "Connecté à OpenRouter",+ "aiSetupSavedKeyHint": "Laissez vide pour conserver la clé enregistrée.",+ "aiSetupOpenRouterKeyLabel": "· clé « {label} »",+ "aiSetupOpenRouterVerifying": "Vérification de votre clé OpenRouter…",+ "aiSetupOpenRouterNoCredits": "Ce compte OpenRouter n’a pas encore de crédits. Ajoutez des crédits sur OpenRouter pour utiliser des modèles payants comme celui recommandé.",+ "aiSetupOpenRouterChange": "Utiliser un autre compte",+ "aiSetupUseRecommended": "Utiliser la configuration recommandée",+ "aiSetupRolesDescription": "Choisissez un modèle pour chaque type de travail. Nous avons choisi ceux recommandés parmi ce que vous avez connecté ; tout le reste de votre configuration reste inchangé.",+ "aiSetupGapDesign": "Rien de ce que vous avez choisi ne peut créer et modifier des designs.",+ "aiSetupGapVision": "Rien de ce que vous avez choisi ne peut analyser d’images : la relecture visuelle resterait désactivée.",+ "aiSetupGapContinue": "Vous pouvez continuer sans et l’ajouter plus tard dans les réglages.",+ "aiSetupGapAddOpenRouter": "Ajouter OpenRouter (à l’usage)",+ "aiSetupGapRemoveOpenRouter": "Ne pas utiliser OpenRouter",+ "aiSetupServerVision": "Ce modèle peut lire des images",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter couvrira ce que vos autres choix ne couvrent pas, facturé à la requête.",+ "aiSetupAccessMore": "Autres fournisseurs",+ "aiSetupServerOther": "Autre serveur",+ "aiSetupAgentChecking": "Vérification de cet ordinateur…",+ "aiSetupAgentInstalled": "installé",+ "aiSetupAgentNotFound": "introuvable",+ "aiSetupAgentMCP": "Serveur MCP d’OpenPencil",+ "aiSetupAgentMCPInstall": "Les agents de code accèdent au canevas via le serveur MCP d’OpenPencil. Installez-le avec :",+ "aiSetupAgentPromptHint": "Vous utilisez déjà {agent} ou un autre agent de code ? Copiez le prompt de configuration et collez-le dedans ; il installe ce dont OpenPencil a besoin.",+ "aiSetupAgentCopyPrompt": "Copier le prompt de configuration",+ "aiSetupAgentCheckAgain": "Vérifier à nouveau",+ "aiSetupAgentGuide": "Guide de configuration",+ "aiSetupPiDescription": "OpenPencil exécute Pi via son compagnon Harness et utilise les fournisseurs auxquels vous êtes connecté dans Pi.",+ "aiSetupPiCompanion": "Compagnon Harness",+ "aiSetupPiInstallCompanion": "Installer le compagnon",+ "aiSetupPiUpdateCompanion": "Mettre à jour le compagnon",+ "aiSetupPiModel": "Modèle par défaut de Pi : {model}",+ "aiSetupPiNoModel": "Aucun modèle par défaut défini dans Pi",+ "piModelHint": "Un modèle Pi comme provider/model. Laissez vide pour utiliser le modèle par défaut de Pi.",+ "aiSetupPiSignIn": "Pour vous connecter à un fournisseur ou choisir un modèle par défaut, lancez pi dans un terminal et tapez /login ou /model.",+ "aiSetupGetDesktop": "Télécharger l’application de bureau",+ "aiSetupAgentNeedsAdapter": "installé · adaptateur OpenPencil manquant",+ "aiSetupAgentInstallAdapter": "Installer l’adaptateur",+ "aiSetupAgentInstallMCP": "Installer le serveur MCP",+ "aiSetupAgentUpdateMCP": "Mettre à jour le serveur MCP",+ "aiSetupAgentOutdated": "mise à jour requise",+ "aiSetupAgentInstalling": "Installation…",+ "aiSetupAgentGetCLI": "Installer {agent}",+ "aiSetupAgentNeedsNpm": "L’installation nécessite npm, fourni avec Node.js. Installez Node.js, puis vérifiez à nouveau.",+ "aiSetupAgentInstallFailed": "L’installation n’a pas abouti. Vérifiez votre connexion ou exécutez la commande vous-même.",+ "aiSetupAgentMCPStartFailed": "Le serveur MCP est installé mais n’a pas démarré. Redémarrez OpenPencil, puis vérifiez à nouveau.",+ "aiSetupAgentLookupFailed": "Impossible de vérifier cet ordinateur. Réessayez.","chatAgentWorkingOn": "{agent} travaille sur « {page} »","chatGoToPage": "Aller à la page"}diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex eb6accdad..88fa0b292 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -142,6 +142,11 @@"chatOutputLimit": "Il modello ha esaurito i token di output durante il ragionamento. Aumenta i token di output massimi o riduci lo sforzo di ragionamento.","chatRequestFailed": "La richiesta al modello non è riuscita. Controlla le impostazioni del provider e riprova.","visionModelUnavailable": "Scegli un modello Vision nelle Impostazioni prima di allegare immagini.",+ "chatPiCompanionMissing": "Pi richiede il companion Harness. Avvia la configurazione guidata per installarlo.",+ "chatPiCompanionOutdated": "Il companion Harness non corrisponde a questa versione di OpenPencil. Avvia la configurazione guidata per aggiornarlo.",+ "chatMCPOutdated": "Il server MCP di OpenPencil non corrisponde a questa versione di OpenPencil. Avvia la configurazione guidata per aggiornarlo.",+ "chatPiSignIn": "Pi non ha effettuato l’accesso a nessun provider. Esegui pi in un terminale e digita /login, oppure aggiungi una chiave AI Gateway.",+ "chatPiModel": "Pi non ha un modello. Esegui pi in un terminale e digita /model, oppure scegline uno nelle Impostazioni.","completions": "Completions","responses": "Responses","connectProvider": "Collega un provider AI per iniziare a chattare.",@@ -177,6 +182,95 @@"reasoningExpanded": "Espanso per impostazione predefinita","jumpToLatest": "Vai all’ultimo messaggio","maxAgentStepsCustom": "Personalizzato…",+ "aiSetupWelcomeTitle": "Benvenuto in OpenPencil",+ "aiSetupWelcomeDescription": "Crea e modifica design su una tela aperta. Importa file Figma e falli tuoi.",+ "aiSetupWelcomeAITitle": "Progetta con l’IA",+ "aiSetupWelcomeAIDescription": "Collega l’IA che usi già per modificare la tela e rivedere i design. Puoi cambiarla in seguito nelle Impostazioni.",+ "aiSetupStart": "Configura l’IA",+ "aiSetupSkip": "Inizia a progettare",+ "aiSetupProgress": "Passo {current} di {total}",+ "aiSetupAdvanced": "Impostazioni avanzate",+ "aiSetupContinue": "Continua",+ "aiSetupGoalsTitle": "In cosa deve aiutarti l’IA?",+ "aiSetupGoalDesign": "Creare e modificare design",+ "aiSetupGoalDesignDescription": "Descrivi una modifica e lascia che l’IA modifichi la tela.",+ "aiSetupGoalVision": "Rivedere i design visivamente",+ "aiSetupGoalVisionDescription": "Lascia che l’IA guardi i tuoi design per controllare spaziatura, allineamento e gerarchia.",+ "aiSetupAccessTitle": "Cosa usi già?",+ "aiSetupAccessDescription": "Seleziona tutto ciò che hai. Se non hai ancora nulla, continua.",+ "aiSetupAccessAgents": "Agenti di programmazione su questo computer",+ "aiSetupAccessAgentsDescription": "Usa il tuo abbonamento attuale. L’agente sceglie il proprio modello.",+ "aiSetupAccessAgentsDesktop": "Gli agenti di programmazione sono disponibili nell’app desktop di OpenPencil.",+ "aiSetupAccessAPI": "Account API",+ "aiSetupAccessServer": "Modello locale o server aziendale",+ "aiSetupAccessServerDescription": "Qualsiasi server compatibile con l’API di OpenAI, come Ollama o LM Studio.",+ "aiSetupConnectTitle": "Collega la tua IA",+ "aiSetupNothingDescription": "Torna indietro per scegliere un altro accesso o configura l’IA nelle impostazioni avanzate.",+ "aiSetupAgentDescription": "OpenPencil avvia {agent} quando invii un messaggio. Prima accedi con il suo strumento da riga di comando.",+ "aiSetupAgentInstall": "Se non è ancora installato, esegui:",+ "aiSetupMeteredNote": "OpenRouter offre modelli di più fornitori con un solo account e una sola chiave.",+ "aiSetupReviewTitle": "Controlla la configurazione",+ "aiSetupAgentModel": "Modello scelto dall’agente",+ "aiSetupFinish": "Completa la configurazione",+ "aiSetupSavedTitle": "L’IA è pronta",+ "aiSetupSavedDescription": "Puoi cambiare modelli e ruoli in qualsiasi momento nelle Impostazioni.",+ "aiSetupRun": "Avvia la configurazione guidata",+ "aiSetupServerKeyHint": "Se il server non verifica le chiavi, inserisci un valore qualsiasi.",+ "aiSetupAlreadyConnected": "Tutto ciò che hai selezionato è già collegato.",+ "aiSetupOpenRouterSignIn": "Accedi con OpenRouter",+ "aiSetupOpenRouterWaiting": "Completa l’accesso a OpenRouter nel browser.",+ "aiSetupOpenRouterReopen": "Apri di nuovo",+ "aiSetupOpenRouterOrKey": "Oppure incolla una chiave API",+ "aiSetupOpenRouterBlocked": "Il browser ha bloccato la finestra di accesso. Consenti i pop-up per OpenPencil e riprova.",+ "aiSetupOpenRouterCancelled": "L’accesso è stato annullato.",+ "aiSetupOpenRouterExpired": "L’accesso ha richiesto troppo tempo. Riprova.",+ "aiSetupOpenRouterFailed": "Impossibile accedere a OpenRouter. Riprova o incolla una chiave API.",+ "aiSetupOpenRouterSignedInTitle": "Accesso a OpenRouter eseguito",+ "aiSetupSavedKeyHint": "Lascia vuoto per mantenere la chiave salvata.",+ "aiSetupOpenRouterKeyLabel": "· chiave «{label}»",+ "aiSetupOpenRouterVerifying": "Verifica della chiave OpenRouter…",+ "aiSetupOpenRouterNoCredits": "Questo account OpenRouter non ha ancora crediti. Aggiungi crediti su OpenRouter per usare modelli a pagamento come quello consigliato.",+ "aiSetupOpenRouterChange": "Usa un altro account",+ "aiSetupUseRecommended": "Usa la configurazione consigliata",+ "aiSetupRolesDescription": "Scegli un modello per ogni tipo di lavoro. Abbiamo scelto quelli consigliati tra ciò che hai collegato; tutto il resto che hai configurato resta invariato.",+ "aiSetupGapDesign": "Nulla di ciò che hai scelto può creare e modificare design.",+ "aiSetupGapVision": "Nulla di ciò che hai scelto può esaminare immagini, quindi la revisione visiva resterebbe disattivata.",+ "aiSetupGapContinue": "Puoi continuare senza e aggiungerlo in seguito nelle Impostazioni.",+ "aiSetupGapAddOpenRouter": "Aggiungi OpenRouter (a consumo)",+ "aiSetupGapRemoveOpenRouter": "Non usare OpenRouter",+ "aiSetupServerVision": "Questo modello può leggere immagini",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter coprirà ciò che le altre scelte non coprono, con addebito per richiesta.",+ "aiSetupAccessMore": "Altri fornitori",+ "aiSetupServerOther": "Altro server",+ "aiSetupAgentChecking": "Controllo di questo computer…",+ "aiSetupAgentInstalled": "installato",+ "aiSetupAgentNotFound": "non trovato",+ "aiSetupAgentMCP": "Server MCP di OpenPencil",+ "aiSetupAgentMCPInstall": "Gli agenti di programmazione accedono alla tela tramite il server MCP di OpenPencil. Installalo con:",+ "aiSetupAgentPromptHint": "Usi già {agent} o un altro agente di programmazione? Copia il prompt di configurazione e incollalo lì: installerà ciò che serve a OpenPencil.",+ "aiSetupAgentCopyPrompt": "Copia il prompt di configurazione",+ "aiSetupAgentCheckAgain": "Controlla di nuovo",+ "aiSetupAgentGuide": "Guida alla configurazione",+ "aiSetupPiDescription": "OpenPencil esegue Pi tramite il suo companion Harness e usa i provider a cui hai effettuato l’accesso in Pi.",+ "aiSetupPiCompanion": "Companion Harness",+ "aiSetupPiInstallCompanion": "Installa companion",+ "aiSetupPiUpdateCompanion": "Aggiorna companion",+ "aiSetupPiModel": "Modello predefinito di Pi: {model}",+ "aiSetupPiNoModel": "Nessun modello predefinito impostato in Pi",+ "piModelHint": "Un modello Pi come provider/model. Lascia vuoto per usare il modello predefinito di Pi.",+ "aiSetupPiSignIn": "Per accedere a un provider o scegliere un modello predefinito, esegui pi in un terminale e digita /login o /model.",+ "aiSetupGetDesktop": "Scarica l’app desktop",+ "aiSetupAgentNeedsAdapter": "installato · manca l’adattatore OpenPencil",+ "aiSetupAgentInstallAdapter": "Installa adattatore",+ "aiSetupAgentInstallMCP": "Installa server MCP",+ "aiSetupAgentUpdateMCP": "Aggiorna server MCP",+ "aiSetupAgentOutdated": "aggiornamento necessario",+ "aiSetupAgentInstalling": "Installazione…",+ "aiSetupAgentGetCLI": "Installa {agent}",+ "aiSetupAgentNeedsNpm": "Per installare serve npm, incluso in Node.js. Installa Node.js e poi controlla di nuovo.",+ "aiSetupAgentInstallFailed": "L’installazione non è stata completata. Controlla la connessione o esegui il comando manualmente.",+ "aiSetupAgentMCPStartFailed": "Il server MCP è installato ma non si è avviato. Riavvia OpenPencil e controlla di nuovo.",+ "aiSetupAgentLookupFailed": "Impossibile controllare questo computer. Riprova.","chatAgentWorkingOn": "{agent} sta lavorando su «{page}»","chatGoToPage": "Vai alla pagina"}diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex d4153b130..5d8a95950 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -142,6 +142,11 @@"chatOutputLimit": "推論中にモデルの出力トークンが上限に達しました。最大出力トークンを増やすか、推論の強度を下げてください。","chatRequestFailed": "モデルへのリクエストに失敗しました。プロバイダー設定を確認して再試行してください。","visionModelUnavailable": "画像を添付する前に、設定でビジョンモデルを選択してください。",+ "chatPiCompanionMissing": "Pi には Harness コンパニオンが必要です。ガイド付きセットアップを実行してインストールしてください。",+ "chatPiCompanionOutdated": "Harness コンパニオンがこのバージョンの OpenPencil と一致しません。ガイド付きセットアップを実行して更新してください。",+ "chatMCPOutdated": "OpenPencil の MCP サーバーがこのバージョンの OpenPencil と一致しません。ガイド付きセットアップを実行して更新してください。",+ "chatPiSignIn": "Pi はどのプロバイダーにもサインインしていません。ターミナルで pi を実行して /login と入力するか、AI Gateway キーを追加してください。",+ "chatPiModel": "Pi に使用するモデルがありません。ターミナルで pi を実行して /model と入力するか、設定で選択してください。","completions": "入力補完","responses": "応答","connectProvider": "チャットを始めるには、AIプロバイダーを接続してください。",@@ -177,6 +182,95 @@"reasoningExpanded": "既定で展開","jumpToLatest": "最新へ移動","maxAgentStepsCustom": "カスタム…",+ "aiSetupWelcomeTitle": "OpenPencil へようこそ",+ "aiSetupWelcomeDescription": "オープンなキャンバスでデザインを作成・編集できます。Figma ファイルを読み込んで自由に使えます。",+ "aiSetupWelcomeAITitle": "AI でデザインする",+ "aiSetupWelcomeAIDescription": "普段使っている AI を接続して、キャンバスの編集やデザインのレビューに使えます。あとから設定で変更できます。",+ "aiSetupStart": "AI を設定",+ "aiSetupSkip": "デザインを始める",+ "aiSetupProgress": "ステップ {current}/{total}",+ "aiSetupAdvanced": "詳細設定",+ "aiSetupContinue": "続ける",+ "aiSetupGoalsTitle": "AI に何を手伝ってほしいですか?",+ "aiSetupGoalDesign": "デザインの作成と編集",+ "aiSetupGoalDesignDescription": "変更内容を伝えると、AI がキャンバスを編集します。",+ "aiSetupGoalVision": "デザインを見てレビュー",+ "aiSetupGoalVisionDescription": "AI がデザインを見て、余白・整列・階層をチェックします。",+ "aiSetupAccessTitle": "すでに使っているものは?",+ "aiSetupAccessDescription": "持っているものをすべて選んでください。まだ何もなければ、そのまま続けてください。",+ "aiSetupAccessAgents": "このコンピューターのコーディングエージェント",+ "aiSetupAccessAgentsDescription": "既存のサブスクリプションを使います。モデルはエージェントが選びます。",+ "aiSetupAccessAgentsDesktop": "コーディングエージェントは OpenPencil デスクトップアプリで利用できます。",+ "aiSetupAccessAPI": "API アカウント",+ "aiSetupAccessServer": "ローカルモデルまたは社内サーバー",+ "aiSetupAccessServerDescription": "Ollama や LM Studio など、OpenAI API 互換のサーバー。",+ "aiSetupConnectTitle": "AI を接続",+ "aiSetupNothingDescription": "戻って別のものを選ぶか、詳細設定で AI を設定してください。",+ "aiSetupAgentDescription": "メッセージを送ると OpenPencil が {agent} を起動します。先にエージェント自身のコマンドラインツールでサインインしてください。",+ "aiSetupAgentInstall": "まだインストールしていない場合は、次を実行してください:",+ "aiSetupMeteredNote": "OpenRouter なら、1 つのアカウントと 1 つのキーで複数ベンダーのモデルを使えます。",+ "aiSetupReviewTitle": "設定を確認",+ "aiSetupAgentModel": "モデルはエージェントが選択",+ "aiSetupFinish": "設定を完了",+ "aiSetupSavedTitle": "AI の準備ができました",+ "aiSetupSavedDescription": "モデルと役割はいつでも設定で変更できます。",+ "aiSetupRun": "ガイド付き設定を開始",+ "aiSetupServerKeyHint": "サーバーがキーを確認しない場合は、任意の値を入力してください。",+ "aiSetupAlreadyConnected": "選んだものはすべて接続済みです。",+ "aiSetupOpenRouterSignIn": "OpenRouter でサインイン",+ "aiSetupOpenRouterWaiting": "ブラウザで OpenRouter へのサインインを完了してください。",+ "aiSetupOpenRouterReopen": "もう一度開く",+ "aiSetupOpenRouterOrKey": "または API キーを貼り付け",+ "aiSetupOpenRouterBlocked": "ブラウザがサインイン用のウィンドウをブロックしました。OpenPencil のポップアップを許可してから、もう一度お試しください。",+ "aiSetupOpenRouterCancelled": "サインインはキャンセルされました。",+ "aiSetupOpenRouterExpired": "サインインに時間がかかりすぎました。もう一度お試しください。",+ "aiSetupOpenRouterFailed": "OpenRouter にサインインできませんでした。もう一度試すか、API キーを貼り付けてください。",+ "aiSetupOpenRouterSignedInTitle": "OpenRouter にサインインしました",+ "aiSetupSavedKeyHint": "保存済みのキーを使う場合は空欄のままにしてください。",+ "aiSetupOpenRouterKeyLabel": "・キー「{label}」",+ "aiSetupOpenRouterVerifying": "OpenRouter のキーを確認しています…",+ "aiSetupOpenRouterNoCredits": "この OpenRouter アカウントにはまだクレジットがありません。推奨モデルなどの有料モデルを使うには、OpenRouter でクレジットを追加してください。",+ "aiSetupOpenRouterChange": "別のアカウントを使う",+ "aiSetupUseRecommended": "推奨の設定を使う",+ "aiSetupRolesDescription": "作業の種類ごとにモデルを選んでください。接続したものから推奨モデルを選んであります。ほかに設定した内容はそのまま残ります。",+ "aiSetupGapDesign": "選んだものではデザインの作成と編集ができません。",+ "aiSetupGapVision": "選んだものでは画像を確認できないため、ビジュアルレビューはオフのままになります。",+ "aiSetupGapContinue": "このまま続けて、あとから設定で追加することもできます。",+ "aiSetupGapAddOpenRouter": "OpenRouter を追加(従量課金)",+ "aiSetupGapRemoveOpenRouter": "OpenRouter を使わない",+ "aiSetupServerVision": "このモデルは画像を読み取れます",+ "aiSetupGapCoveredByOpenRouter": "ほかの選択で対応できない部分は OpenRouter が担当し、リクエストごとに課金されます。",+ "aiSetupAccessMore": "その他のプロバイダー",+ "aiSetupServerOther": "その他のサーバー",+ "aiSetupAgentChecking": "このコンピューターを確認しています…",+ "aiSetupAgentInstalled": "インストール済み",+ "aiSetupAgentNotFound": "見つかりません",+ "aiSetupAgentMCP": "OpenPencil MCP サーバー",+ "aiSetupAgentMCPInstall": "コーディングエージェントは OpenPencil の MCP サーバー経由でキャンバスを操作します。次のコマンドでインストールしてください:",+ "aiSetupAgentPromptHint": "{agent} などのコーディングエージェントをすでに使っていますか?セットアップ用プロンプトをコピーして貼り付けると、OpenPencil に必要なものをインストールします。",+ "aiSetupAgentCopyPrompt": "セットアップ用プロンプトをコピー",+ "aiSetupAgentCheckAgain": "もう一度確認",+ "aiSetupAgentGuide": "セットアップガイド",+ "aiSetupPiDescription": "OpenPencil は Harness コンパニオンを通じて Pi を実行し、Pi でサインインしたプロバイダーを使います。",+ "aiSetupPiCompanion": "Harness コンパニオン",+ "aiSetupPiInstallCompanion": "コンパニオンをインストール",+ "aiSetupPiUpdateCompanion": "コンパニオンを更新",+ "aiSetupPiModel": "Pi のデフォルトモデル: {model}",+ "aiSetupPiNoModel": "Pi にデフォルトモデルが設定されていません",+ "piModelHint": "provider/model 形式の Pi モデル。空欄にすると Pi のデフォルトモデルを使います。",+ "aiSetupPiSignIn": "プロバイダーにサインインするかデフォルトモデルを選ぶには、ターミナルで pi を実行して /login または /model と入力します。",+ "aiSetupGetDesktop": "デスクトップアプリを入手",+ "aiSetupAgentNeedsAdapter": "インストール済み・OpenPencil アダプターがありません",+ "aiSetupAgentInstallAdapter": "アダプターをインストール",+ "aiSetupAgentInstallMCP": "MCP サーバーをインストール",+ "aiSetupAgentUpdateMCP": "MCP サーバーを更新",+ "aiSetupAgentOutdated": "更新が必要",+ "aiSetupAgentInstalling": "インストールしています…",+ "aiSetupAgentGetCLI": "{agent} をインストール",+ "aiSetupAgentNeedsNpm": "インストールには Node.js に含まれる npm が必要です。Node.js をインストールしてから、もう一度確認してください。",+ "aiSetupAgentInstallFailed": "インストールが完了しませんでした。接続を確認するか、コマンドを自分で実行してください。",+ "aiSetupAgentMCPStartFailed": "MCP サーバーはインストール済みですが起動しませんでした。OpenPencil を再起動してから、もう一度確認してください。",+ "aiSetupAgentLookupFailed": "このコンピューターを確認できませんでした。もう一度お試しください。","chatAgentWorkingOn": "{agent}が「{page}」で作業中","chatGoToPage": "ページへ移動"}diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 059cb205a..4e68a39f0 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -136,6 +136,11 @@"chatOutputLimit": "Model wyczerpał limit tokenów wyjściowych podczas rozumowania. Zwiększ maksymalną liczbę tokenów wyjściowych lub zmniejsz poziom rozumowania.","chatRequestFailed": "Żądanie do modelu nie powiodło się. Sprawdź ustawienia dostawcy i spróbuj ponownie.","visionModelUnavailable": "Przed dołączeniem obrazów wybierz model Vision w Ustawieniach.",+ "chatPiCompanionMissing": "Pi potrzebuje programu towarzyszącego Harness. Uruchom konfigurację z przewodnikiem, aby go zainstalować.",+ "chatPiCompanionOutdated": "Program towarzyszący Harness nie pasuje do tej wersji OpenPencil. Uruchom konfigurację z przewodnikiem, aby go zaktualizować.",+ "chatMCPOutdated": "Serwer MCP OpenPencil nie pasuje do tej wersji OpenPencil. Uruchom konfigurację z przewodnikiem, aby go zaktualizować.",+ "chatPiSignIn": "Pi nie jest zalogowany do żadnego dostawcy. Uruchom pi w terminalu i wpisz /login albo dodaj klucz AI Gateway.",+ "chatPiModel": "Pi nie ma modelu. Uruchom pi w terminalu i wpisz /model albo wybierz model w Ustawieniach.","completions": "Completions","responses": "Responses","connectProvider": "Połącz dostawcę AI, aby rozpocząć czat.",@@ -177,6 +182,95 @@"reasoningExpanded": "Domyślnie rozwinięte","jumpToLatest": "Przejdź do najnowszej wiadomości","maxAgentStepsCustom": "Własna wartość…",+ "aiSetupWelcomeTitle": "Witamy w OpenPencil",+ "aiSetupWelcomeDescription": "Twórz i edytuj projekty na otwartym płótnie. Importuj pliki Figma i dostosuj je do siebie.",+ "aiSetupWelcomeAITitle": "Projektuj z AI",+ "aiSetupWelcomeAIDescription": "Połącz AI, z którego już korzystasz, aby edytować płótno i przeglądać projekty. Możesz to później zmienić w ustawieniach.",+ "aiSetupStart": "Skonfiguruj AI",+ "aiSetupSkip": "Zacznij projektować",+ "aiSetupProgress": "Krok {current} z {total}",+ "aiSetupAdvanced": "Ustawienia zaawansowane",+ "aiSetupContinue": "Dalej",+ "aiSetupGoalsTitle": "W czym ma pomagać AI?",+ "aiSetupGoalDesign": "Tworzenie i edycja projektów",+ "aiSetupGoalDesignDescription": "Opisz zmianę, a AI zmodyfikuje płótno.",+ "aiSetupGoalVision": "Wizualny przegląd projektów",+ "aiSetupGoalVisionDescription": "Pozwól AI obejrzeć projekty i sprawdzić odstępy, wyrównanie i hierarchię.",+ "aiSetupAccessTitle": "Z czego już korzystasz?",+ "aiSetupAccessDescription": "Zaznacz wszystko, co masz. Jeśli nie masz jeszcze nic, przejdź dalej.",+ "aiSetupAccessAgents": "Agenci programistyczni na tym komputerze",+ "aiSetupAccessAgentsDescription": "Korzystaj z obecnej subskrypcji. Agent sam wybiera model.",+ "aiSetupAccessAgentsDesktop": "Agenci programistyczni są dostępni w aplikacji OpenPencil na komputer.",+ "aiSetupAccessAPI": "Konta API",+ "aiSetupAccessServer": "Model lokalny lub serwer firmowy",+ "aiSetupAccessServerDescription": "Dowolny serwer zgodny z API OpenAI, np. Ollama lub LM Studio.",+ "aiSetupConnectTitle": "Połącz AI",+ "aiSetupNothingDescription": "Wróć, aby wybrać inny dostęp, albo skonfiguruj AI w ustawieniach zaawansowanych.",+ "aiSetupAgentDescription": "OpenPencil uruchamia {agent}, gdy wyślesz wiadomość. Najpierw zaloguj się za pomocą jego narzędzia wiersza poleceń.",+ "aiSetupAgentInstall": "Jeśli nie jest jeszcze zainstalowany, uruchom:",+ "aiSetupMeteredNote": "OpenRouter daje dostęp do modeli wielu dostawców z jednym kontem i jednym kluczem.",+ "aiSetupReviewTitle": "Sprawdź konfigurację",+ "aiSetupAgentModel": "Model wybrany przez agenta",+ "aiSetupFinish": "Zakończ konfigurację",+ "aiSetupSavedTitle": "AI jest gotowe",+ "aiSetupSavedDescription": "Modele i role możesz zmienić w dowolnej chwili w ustawieniach.",+ "aiSetupRun": "Uruchom konfigurację z przewodnikiem",+ "aiSetupServerKeyHint": "Jeśli serwer nie sprawdza kluczy, wpisz dowolną wartość.",+ "aiSetupAlreadyConnected": "Wszystko, co wybrano, jest już połączone.",+ "aiSetupOpenRouterSignIn": "Zaloguj się przez OpenRouter",+ "aiSetupOpenRouterWaiting": "Dokończ logowanie do OpenRouter w przeglądarce.",+ "aiSetupOpenRouterReopen": "Otwórz ponownie",+ "aiSetupOpenRouterOrKey": "Lub wklej klucz API",+ "aiSetupOpenRouterBlocked": "Przeglądarka zablokowała okno logowania. Zezwól na wyskakujące okna dla OpenPencil i spróbuj ponownie.",+ "aiSetupOpenRouterCancelled": "Logowanie zostało anulowane.",+ "aiSetupOpenRouterExpired": "Logowanie trwało zbyt długo. Spróbuj ponownie.",+ "aiSetupOpenRouterFailed": "Nie udało się zalogować do OpenRouter. Spróbuj ponownie lub wklej klucz API.",+ "aiSetupOpenRouterSignedInTitle": "Zalogowano do OpenRouter",+ "aiSetupSavedKeyHint": "Pozostaw puste, aby zachować zapisany klucz.",+ "aiSetupOpenRouterKeyLabel": "· klucz „{label}”",+ "aiSetupOpenRouterVerifying": "Sprawdzanie klucza OpenRouter…",+ "aiSetupOpenRouterNoCredits": "To konto OpenRouter nie ma jeszcze środków. Doładuj je w OpenRouter, aby korzystać z płatnych modeli, takich jak polecany.",+ "aiSetupOpenRouterChange": "Użyj innego konta",+ "aiSetupUseRecommended": "Użyj polecanej konfiguracji",+ "aiSetupRolesDescription": "Wybierz model dla każdego rodzaju pracy. Spośród połączonych usług wybraliśmy polecane; pozostała konfiguracja się nie zmieni.",+ "aiSetupGapDesign": "Żadna z wybranych opcji nie tworzy ani nie edytuje projektów.",+ "aiSetupGapVision": "Żadna z wybranych opcji nie analizuje obrazów, więc przegląd wizualny pozostanie wyłączony.",+ "aiSetupGapContinue": "Możesz kontynuować bez tego i dodać to później w ustawieniach.",+ "aiSetupGapAddOpenRouter": "Dodaj OpenRouter (płatność za użycie)",+ "aiSetupGapRemoveOpenRouter": "Nie używaj OpenRouter",+ "aiSetupServerVision": "Ten model potrafi odczytywać obrazy",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter obsłuży to, czego nie obejmują pozostałe wybory, z opłatą za każde zapytanie.",+ "aiSetupAccessMore": "Więcej dostawców",+ "aiSetupServerOther": "Inny serwer",+ "aiSetupAgentChecking": "Sprawdzanie tego komputera…",+ "aiSetupAgentInstalled": "zainstalowany",+ "aiSetupAgentNotFound": "nie znaleziono",+ "aiSetupAgentMCP": "Serwer MCP OpenPencil",+ "aiSetupAgentMCPInstall": "Agenci programistyczni korzystają z płótna przez serwer MCP OpenPencil. Zainstaluj go poleceniem:",+ "aiSetupAgentPromptHint": "Korzystasz już z {agent} lub innego agenta programistycznego? Skopiuj prompt konfiguracji i wklej go tam — zainstaluje to, czego potrzebuje OpenPencil.",+ "aiSetupAgentCopyPrompt": "Kopiuj prompt konfiguracji",+ "aiSetupAgentCheckAgain": "Sprawdź ponownie",+ "aiSetupAgentGuide": "Przewodnik konfiguracji",+ "aiSetupPiDescription": "OpenPencil uruchamia Pi przez towarzyszący program Harness i korzysta z dostawców, do których zalogowano się w Pi.",+ "aiSetupPiCompanion": "Program towarzyszący Harness",+ "aiSetupPiInstallCompanion": "Zainstaluj program towarzyszący",+ "aiSetupPiUpdateCompanion": "Zaktualizuj program towarzyszący",+ "aiSetupPiModel": "Domyślny model Pi: {model}",+ "aiSetupPiNoModel": "W Pi nie ustawiono domyślnego modelu",+ "piModelHint": "Model Pi, np. provider/model. Pozostaw puste, aby użyć domyślnego modelu Pi.",+ "aiSetupPiSignIn": "Aby zalogować się do dostawcy lub wybrać domyślny model, uruchom pi w terminalu i wpisz /login lub /model.",+ "aiSetupGetDesktop": "Pobierz aplikację na komputer",+ "aiSetupAgentNeedsAdapter": "zainstalowany · brak adaptera OpenPencil",+ "aiSetupAgentInstallAdapter": "Zainstaluj adapter",+ "aiSetupAgentInstallMCP": "Zainstaluj serwer MCP",+ "aiSetupAgentUpdateMCP": "Zaktualizuj serwer MCP",+ "aiSetupAgentOutdated": "wymaga aktualizacji",+ "aiSetupAgentInstalling": "Instalowanie…",+ "aiSetupAgentGetCLI": "Zainstaluj {agent}",+ "aiSetupAgentNeedsNpm": "Instalacja wymaga npm, który jest częścią Node.js. Zainstaluj Node.js i sprawdź ponownie.",+ "aiSetupAgentInstallFailed": "Instalacja nie została ukończona. Sprawdź połączenie lub uruchom polecenie samodzielnie.",+ "aiSetupAgentMCPStartFailed": "Serwer MCP jest zainstalowany, ale się nie uruchomił. Uruchom ponownie OpenPencil i sprawdź jeszcze raz.",+ "aiSetupAgentLookupFailed": "Nie udało się sprawdzić tego komputera. Spróbuj ponownie.","chatAgentWorkingOn": "{agent} pracuje nad „{page}”","chatGoToPage": "Przejdź do strony"}diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex e34c2ba1a..d865ae360 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -136,6 +136,11 @@"chatOutputLimit": "Модель исчерпала лимит выходных токенов во время рассуждения. Увеличьте максимум выходных токенов или снизьте глубину рассуждения.","chatRequestFailed": "Запрос к модели завершился ошибкой. Проверьте настройки провайдера и повторите попытку.","visionModelUnavailable": "Перед добавлением изображений выберите модель для зрения в настройках.",+ "chatPiCompanionMissing": "Pi нужен компаньон Harness. Запустите пошаговую настройку, чтобы установить его.",+ "chatPiCompanionOutdated": "Компаньон Harness не подходит к этой версии OpenPencil. Запустите пошаговую настройку, чтобы обновить его.",+ "chatMCPOutdated": "MCP-сервер OpenPencil не подходит к этой версии OpenPencil. Запустите пошаговую настройку, чтобы обновить его.",+ "chatPiSignIn": "Pi не вошёл ни в одного провайдера. Запустите pi в терминале и введите /login или добавьте ключ AI Gateway.",+ "chatPiModel": "У Pi нет модели. Запустите pi в терминале и введите /model или выберите модель в настройках.","completions": "Completions","responses": "Responses","connectProvider": "Подключите AI-провайдера, чтобы начать чат.",@@ -177,6 +182,95 @@"reasoningExpanded": "Развёрнуто по умолчанию","jumpToLatest": "К последнему сообщению","maxAgentStepsCustom": "Своё значение…",+ "aiSetupWelcomeTitle": "Добро пожаловать в OpenPencil",+ "aiSetupWelcomeDescription": "Создавайте и редактируйте дизайн на открытом холсте. Импортируйте файлы Figma и распоряжайтесь ими как своими.",+ "aiSetupWelcomeAITitle": "Дизайн с ИИ",+ "aiSetupWelcomeAIDescription": "Подключите ИИ, которым вы уже пользуетесь, чтобы редактировать холст и проверять дизайн. Это можно изменить позже в настройках.",+ "aiSetupStart": "Настроить ИИ",+ "aiSetupSkip": "Начать работу",+ "aiSetupProgress": "Шаг {current} из {total}",+ "aiSetupAdvanced": "Расширенные настройки",+ "aiSetupContinue": "Далее",+ "aiSetupGoalsTitle": "С чем должен помогать ИИ?",+ "aiSetupGoalDesign": "Создавать и редактировать дизайн",+ "aiSetupGoalDesignDescription": "Опишите изменение, и ИИ отредактирует холст.",+ "aiSetupGoalVision": "Проверять дизайн визуально",+ "aiSetupGoalVisionDescription": "ИИ посмотрит на дизайн и проверит отступы, выравнивание и иерархию.",+ "aiSetupAccessTitle": "Чем вы уже пользуетесь?",+ "aiSetupAccessDescription": "Отметьте всё, что у вас есть. Если пока ничего нет, просто продолжайте.",+ "aiSetupAccessAgents": "Агенты для программирования на этом компьютере",+ "aiSetupAccessAgentsDescription": "Используется ваша подписка. Модель выбирает сам агент.",+ "aiSetupAccessAgentsDesktop": "Агенты для программирования доступны в настольном приложении OpenPencil.",+ "aiSetupAccessAPI": "Аккаунты API",+ "aiSetupAccessServer": "Локальная модель или сервер компании",+ "aiSetupAccessServerDescription": "Любой сервер с API, совместимым с OpenAI, например Ollama или LM Studio.",+ "aiSetupConnectTitle": "Подключите ИИ",+ "aiSetupNothingDescription": "Вернитесь и выберите другой доступ или настройте ИИ в расширенных настройках.",+ "aiSetupAgentDescription": "OpenPencil запускает {agent}, когда вы отправляете сообщение. Сначала войдите в аккаунт через его собственную консольную утилиту.",+ "aiSetupAgentInstall": "Если он ещё не установлен, выполните:",+ "aiSetupMeteredNote": "OpenRouter даёт доступ к моделям разных компаний с одним аккаунтом и одним ключом.",+ "aiSetupReviewTitle": "Проверьте настройку",+ "aiSetupAgentModel": "Модель выбирает агент",+ "aiSetupFinish": "Завершить настройку",+ "aiSetupSavedTitle": "ИИ готов к работе",+ "aiSetupSavedDescription": "Модели и роли можно изменить в любой момент в настройках.",+ "aiSetupRun": "Пройти пошаговую настройку",+ "aiSetupServerKeyHint": "Если сервер не проверяет ключи, введите любое значение.",+ "aiSetupAlreadyConnected": "Всё выбранное уже подключено.",+ "aiSetupOpenRouterSignIn": "Войти через OpenRouter",+ "aiSetupOpenRouterWaiting": "Завершите вход в OpenRouter в браузере.",+ "aiSetupOpenRouterReopen": "Открыть снова",+ "aiSetupOpenRouterOrKey": "Или вставьте ключ API",+ "aiSetupOpenRouterBlocked": "Браузер заблокировал окно входа. Разрешите всплывающие окна для OpenPencil и попробуйте снова.",+ "aiSetupOpenRouterCancelled": "Вход отменён.",+ "aiSetupOpenRouterExpired": "Вход занял слишком много времени. Попробуйте снова.",+ "aiSetupOpenRouterFailed": "Не удалось войти в OpenRouter. Попробуйте снова или вставьте ключ API.",+ "aiSetupOpenRouterSignedInTitle": "Вход в OpenRouter выполнен",+ "aiSetupSavedKeyHint": "Оставьте поле пустым, чтобы использовать сохранённый ключ.",+ "aiSetupOpenRouterKeyLabel": "· ключ «{label}»",+ "aiSetupOpenRouterVerifying": "Проверяем ключ OpenRouter…",+ "aiSetupOpenRouterNoCredits": "На этом аккаунте OpenRouter пока нет кредитов. Пополните баланс в OpenRouter, чтобы пользоваться платными моделями, например рекомендованной.",+ "aiSetupOpenRouterChange": "Использовать другой аккаунт",+ "aiSetupUseRecommended": "Использовать рекомендуемую настройку",+ "aiSetupRolesDescription": "Выберите модель для каждого вида работы. Мы подобрали рекомендуемые из подключённого; остальные ваши настройки не изменятся.",+ "aiSetupGapDesign": "Ничто из выбранного не умеет создавать и редактировать дизайн.",+ "aiSetupGapVision": "Ничто из выбранного не умеет анализировать изображения, поэтому визуальная проверка останется выключенной.",+ "aiSetupGapContinue": "Можно продолжить без этого и добавить позже в настройках.",+ "aiSetupGapAddOpenRouter": "Добавить OpenRouter (оплата за использование)",+ "aiSetupGapRemoveOpenRouter": "Не использовать OpenRouter",+ "aiSetupServerVision": "Эта модель умеет читать изображения",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter возьмёт на себя то, что не покрывает остальной выбор, с оплатой за каждый запрос.",+ "aiSetupAccessMore": "Другие провайдеры",+ "aiSetupServerOther": "Другой сервер",+ "aiSetupAgentChecking": "Проверяем этот компьютер…",+ "aiSetupAgentInstalled": "установлен",+ "aiSetupAgentNotFound": "не найден",+ "aiSetupAgentMCP": "MCP-сервер OpenPencil",+ "aiSetupAgentMCPInstall": "Агенты для программирования работают с холстом через MCP-сервер OpenPencil. Установите его командой:",+ "aiSetupAgentPromptHint": "Уже пользуетесь {agent} или другим агентом для программирования? Скопируйте промпт настройки и вставьте его туда — он установит всё нужное OpenPencil.",+ "aiSetupAgentCopyPrompt": "Скопировать промпт настройки",+ "aiSetupAgentCheckAgain": "Проверить снова",+ "aiSetupAgentGuide": "Руководство по настройке",+ "aiSetupPiDescription": "OpenPencil запускает Pi через компаньон Harness и использует провайдеров, в которые вы вошли в Pi.",+ "aiSetupPiCompanion": "Компаньон Harness",+ "aiSetupPiInstallCompanion": "Установить компаньон",+ "aiSetupPiUpdateCompanion": "Обновить компаньон",+ "aiSetupPiModel": "Модель Pi по умолчанию: {model}",+ "aiSetupPiNoModel": "В Pi не выбрана модель по умолчанию",+ "piModelHint": "Модель Pi вида provider/model. Оставьте пустым, чтобы использовать модель Pi по умолчанию.",+ "aiSetupPiSignIn": "Чтобы войти в провайдера или выбрать модель по умолчанию, запустите pi в терминале и введите /login или /model.",+ "aiSetupGetDesktop": "Скачать настольное приложение",+ "aiSetupAgentNeedsAdapter": "установлен · нет адаптера OpenPencil",+ "aiSetupAgentInstallAdapter": "Установить адаптер",+ "aiSetupAgentInstallMCP": "Установить MCP-сервер",+ "aiSetupAgentUpdateMCP": "Обновить сервер MCP",+ "aiSetupAgentOutdated": "нужно обновить",+ "aiSetupAgentInstalling": "Устанавливаем…",+ "aiSetupAgentGetCLI": "Установить {agent}",+ "aiSetupAgentNeedsNpm": "Для установки нужен npm, который входит в Node.js. Установите Node.js и проверьте снова.",+ "aiSetupAgentInstallFailed": "Установка не завершилась. Проверьте подключение или выполните команду вручную.",+ "aiSetupAgentMCPStartFailed": "MCP-сервер установлен, но не запустился. Перезапустите OpenPencil и проверьте снова.",+ "aiSetupAgentLookupFailed": "Не удалось проверить этот компьютер. Попробуйте снова.","chatAgentWorkingOn": "{agent} работает над «{page}»","chatGoToPage": "Перейти к странице"}diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex a6946a270..47cd58fdd 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -142,6 +142,11 @@"chatOutputLimit": "模型在推理时耗尽了输出词元。请提高最大输出词元数或降低推理强度。","chatRequestFailed": "模型请求失败。请检查提供商设置后重试。","visionModelUnavailable": "附加图片前,请在设置中选择视觉模型。",+ "chatPiCompanionMissing": "Pi 需要 Harness 配套程序。运行引导式设置来安装它。",+ "chatPiCompanionOutdated": "Harness 配套程序与此版本的 OpenPencil 不匹配。运行引导式设置来更新它。",+ "chatMCPOutdated": "OpenPencil 的 MCP 服务器与此版本的 OpenPencil 不匹配。运行引导式设置来更新它。",+ "chatPiSignIn": "Pi 尚未登录任何提供商。请在终端中运行 pi 并输入 /login,或添加 AI Gateway 密钥。",+ "chatPiModel": "Pi 没有可用的模型。请在终端中运行 pi 并输入 /model,或在设置中选择一个。","completions": "Completions","responses": "Responses","connectProvider": "连接 AI 提供商以开始聊天。",@@ -177,6 +182,95 @@"reasoningExpanded": "默认展开","jumpToLatest": "跳转到最新消息","maxAgentStepsCustom": "自定义…",+ "aiSetupWelcomeTitle": "欢迎使用 OpenPencil",+ "aiSetupWelcomeDescription": "在开放的画布上创建和编辑设计。导入 Figma 文件,随心使用。",+ "aiSetupWelcomeAITitle": "用 AI 设计",+ "aiSetupWelcomeAIDescription": "连接你已在使用的 AI,用来编辑画布和审查设计。之后可以在设置中更改。",+ "aiSetupStart": "设置 AI",+ "aiSetupSkip": "开始设计",+ "aiSetupProgress": "第 {current} 步,共 {total} 步",+ "aiSetupAdvanced": "高级设置",+ "aiSetupContinue": "继续",+ "aiSetupGoalsTitle": "希望 AI 帮你做什么?",+ "aiSetupGoalDesign": "创建和编辑设计",+ "aiSetupGoalDesignDescription": "描述你想要的修改,让 AI 编辑画布。",+ "aiSetupGoalVision": "可视化审查设计",+ "aiSetupGoalVisionDescription": "让 AI 查看你的设计,检查间距、对齐和层级。",+ "aiSetupAccessTitle": "你已经在用哪些服务?",+ "aiSetupAccessDescription": "选择你拥有的全部服务。如果还没有,直接继续即可。",+ "aiSetupAccessAgents": "这台电脑上的编程智能体",+ "aiSetupAccessAgentsDescription": "使用你现有的订阅,模型由智能体自行选择。",+ "aiSetupAccessAgentsDesktop": "编程智能体可在 OpenPencil 桌面应用中使用。",+ "aiSetupAccessAPI": "API 账户",+ "aiSetupAccessServer": "本地模型或公司服务器",+ "aiSetupAccessServerDescription": "任何兼容 OpenAI API 的服务器,例如 Ollama 或 LM Studio。",+ "aiSetupConnectTitle": "连接你的 AI",+ "aiSetupNothingDescription": "返回选择其他服务,或在高级设置中配置 AI。",+ "aiSetupAgentDescription": "发送消息时,OpenPencil 会启动 {agent}。请先使用它自带的命令行工具登录。",+ "aiSetupAgentInstall": "如果尚未安装,请运行:",+ "aiSetupMeteredNote": "OpenRouter 让你用一个账户和一个密钥使用多家厂商的模型。",+ "aiSetupReviewTitle": "检查你的设置",+ "aiSetupAgentModel": "模型由智能体选择",+ "aiSetupFinish": "完成设置",+ "aiSetupSavedTitle": "AI 已就绪",+ "aiSetupSavedDescription": "你可以随时在设置中更改模型和角色。",+ "aiSetupRun": "运行引导式设置",+ "aiSetupServerKeyHint": "如果你的服务器不校验密钥,可以输入任意值。",+ "aiSetupAlreadyConnected": "你选择的服务都已连接。",+ "aiSetupOpenRouterSignIn": "使用 OpenRouter 登录",+ "aiSetupOpenRouterWaiting": "请在浏览器中完成 OpenRouter 登录。",+ "aiSetupOpenRouterReopen": "再次打开",+ "aiSetupOpenRouterOrKey": "或粘贴 API 密钥",+ "aiSetupOpenRouterBlocked": "浏览器拦截了登录窗口。请允许 OpenPencil 弹出窗口后重试。",+ "aiSetupOpenRouterCancelled": "登录已取消。",+ "aiSetupOpenRouterExpired": "登录耗时过长,请重试。",+ "aiSetupOpenRouterFailed": "无法登录 OpenRouter。请重试或粘贴 API 密钥。",+ "aiSetupOpenRouterSignedInTitle": "已登录 OpenRouter",+ "aiSetupSavedKeyHint": "留空即可继续使用已保存的密钥。",+ "aiSetupOpenRouterKeyLabel": "· 密钥“{label}”",+ "aiSetupOpenRouterVerifying": "正在检查你的 OpenRouter 密钥…",+ "aiSetupOpenRouterNoCredits": "这个 OpenRouter 账户还没有额度。请在 OpenRouter 充值后再使用推荐模型等付费模型。",+ "aiSetupOpenRouterChange": "使用其他账户",+ "aiSetupUseRecommended": "使用推荐设置",+ "aiSetupRolesDescription": "为每类工作选择模型。我们已从你连接的服务中选好推荐模型,其他已配置的内容保持不变。",+ "aiSetupGapDesign": "你选择的服务都无法创建和编辑设计。",+ "aiSetupGapVision": "你选择的服务都无法查看图片,因此可视化审查将保持关闭。",+ "aiSetupGapContinue": "你可以先继续,之后在设置中添加。",+ "aiSetupGapAddOpenRouter": "添加 OpenRouter(按量付费)",+ "aiSetupGapRemoveOpenRouter": "不使用 OpenRouter",+ "aiSetupServerVision": "此模型可以读取图片",+ "aiSetupGapCoveredByOpenRouter": "OpenRouter 会覆盖你其他选择无法完成的部分,按请求计费。",+ "aiSetupAccessMore": "更多服务商",+ "aiSetupServerOther": "其他服务器",+ "aiSetupAgentChecking": "正在检查这台电脑…",+ "aiSetupAgentInstalled": "已安装",+ "aiSetupAgentNotFound": "未找到",+ "aiSetupAgentMCP": "OpenPencil MCP 服务器",+ "aiSetupAgentMCPInstall": "编程智能体通过 OpenPencil 的 MCP 服务器操作画布。使用以下命令安装:",+ "aiSetupAgentPromptHint": "已经在用 {agent} 或其他编程智能体?复制设置提示词并粘贴进去,它会安装 OpenPencil 所需的内容。",+ "aiSetupAgentCopyPrompt": "复制设置提示词",+ "aiSetupAgentCheckAgain": "重新检查",+ "aiSetupAgentGuide": "设置指南",+ "aiSetupPiDescription": "OpenPencil 通过 Harness 配套程序运行 Pi,并使用你在 Pi 中登录的提供商。",+ "aiSetupPiCompanion": "Harness 配套程序",+ "aiSetupPiInstallCompanion": "安装配套程序",+ "aiSetupPiUpdateCompanion": "更新配套程序",+ "aiSetupPiModel": "Pi 的默认模型:{model}",+ "aiSetupPiNoModel": "Pi 中未设置默认模型",+ "piModelHint": "Pi 模型,例如 provider/model。留空则使用 Pi 的默认模型。",+ "aiSetupPiSignIn": "要登录提供商或选择默认模型,请在终端中运行 pi 并输入 /login 或 /model。",+ "aiSetupGetDesktop": "获取桌面应用",+ "aiSetupAgentNeedsAdapter": "已安装 · 缺少 OpenPencil 适配器",+ "aiSetupAgentInstallAdapter": "安装适配器",+ "aiSetupAgentInstallMCP": "安装 MCP 服务器",+ "aiSetupAgentUpdateMCP": "更新 MCP 服务器",+ "aiSetupAgentOutdated": "需要更新",+ "aiSetupAgentInstalling": "正在安装…",+ "aiSetupAgentGetCLI": "安装 {agent}",+ "aiSetupAgentNeedsNpm": "安装需要 Node.js 自带的 npm。请先安装 Node.js,然后重新检查。",+ "aiSetupAgentInstallFailed": "安装未完成。请检查网络连接,或自行运行该命令。",+ "aiSetupAgentMCPStartFailed": "MCP 服务器已安装但未能启动。请重启 OpenPencil,然后重新检查。",+ "aiSetupAgentLookupFailed": "无法检查这台电脑,请重试。","chatAgentWorkingOn": "{agent} 正在处理“{page}”","chatGoToPage": "转到页面"}diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex 0d885d7af..45931a5f0 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -192,8 +192,126 @@ export const aiMessageDefaults = {chatRequestFailed: 'The model request failed. Check the provider settings and try again.',openProviderSettingsAction: 'Open settings',visionModelUnavailable: 'Choose a Vision model in Settings before attaching images.',+ chatPiCompanionMissing: 'Pi needs the Harness companion. Run guided setup to install it.',+ chatPiCompanionOutdated:+ 'The Harness companion doesn’t match this version of OpenPencil. Run guided setup to update it.',+ chatMCPOutdated:+ 'OpenPencil’s MCP server doesn’t match this version of OpenPencil. Run guided setup to update it.',+ chatPiSignIn:+ 'Pi isn’t signed in to a provider. Run pi in a terminal and type /login, or add an AI Gateway key.',+ chatPiModel:+ 'Pi has no model to use. Run pi in a terminal and type /model, or choose one in Settings.',completions: 'Completions',- responses: 'Responses'+ responses: 'Responses',+ aiSetupWelcomeTitle: 'Welcome to OpenPencil',+ aiSetupWelcomeDescription:+ 'Create and edit designs on an open canvas. Import Figma files and make them your own.',+ aiSetupWelcomeAITitle: 'Design with AI',+ aiSetupWelcomeAIDescription:+ 'Connect the AI you already use to edit the canvas and review designs. You can change it later in Settings.',+ aiSetupStart: 'Set up AI',+ aiSetupSkip: 'Start designing',+ aiSetupProgress: params('Step {current} of {total}'),+ aiSetupAdvanced: 'Advanced settings',+ aiSetupContinue: 'Continue',+ aiSetupGoalsTitle: 'What should AI help with?',+ aiSetupGoalDesign: 'Create and edit designs',+ aiSetupGoalDesignDescription: 'Describe a change and let AI edit the canvas.',+ aiSetupGoalVision: 'Review designs visually',+ aiSetupGoalVisionDescription:+ 'Let AI look at your designs to check spacing, alignment, and hierarchy.',+ aiSetupAccessTitle: 'What do you already use?',+ aiSetupAccessDescription: 'Select everything you have. If you have nothing yet, continue.',+ aiSetupAccessAgents: 'Coding agents on this computer',+ aiSetupAccessAgentsDescription:+ 'Use your existing subscription. The agent chooses its own model.',+ aiSetupAccessAgentsDesktop: 'Coding agents are available in the OpenPencil desktop app.',+ aiSetupAccessAPI: 'API accounts',+ aiSetupAccessServer: 'Local model or company server',+ aiSetupAccessMore: 'More providers',+ aiSetupServerOther: 'Other server',+ aiSetupAccessServerDescription:+ 'Any server that speaks the OpenAI API, such as Ollama or LM Studio.',+ aiSetupConnectTitle: 'Connect your AI',+ aiSetupNothingDescription: 'Go back to choose other access, or set up AI in advanced settings.',+ aiSetupAgentDescription: params(+ 'OpenPencil starts {agent} when you send a message. Sign in with its own command-line tool first.'+ ),+ aiSetupAgentInstall: 'If it is not installed yet, run:',+ aiSetupAgentChecking: 'Checking this computer…',+ aiSetupAgentInstalled: 'installed',+ aiSetupAgentNotFound: 'not found',+ aiSetupAgentMCP: 'OpenPencil MCP server',+ aiSetupAgentMCPInstall:+ 'Coding agents reach the canvas through OpenPencil’s MCP server. Install it with:',+ aiSetupAgentPromptHint: params(+ 'Already using {agent} or another coding agent? Copy the setup prompt and paste it there; it installs what OpenPencil needs.'+ ),+ aiSetupAgentNeedsAdapter: 'installed · OpenPencil adapter missing',+ aiSetupAgentInstallAdapter: 'Install adapter',+ aiSetupAgentInstallMCP: 'Install MCP server',+ aiSetupAgentUpdateMCP: 'Update MCP server',+ aiSetupAgentOutdated: 'update needed',+ aiSetupAgentInstalling: 'Installing…',+ aiSetupAgentGetCLI: params('Install {agent}'),+ aiSetupAgentNeedsNpm:+ 'Installing needs npm, which comes with Node.js. Install Node.js, then check again.',+ aiSetupAgentInstallFailed:+ 'The installation didn’t finish. Check your connection, or run the command yourself.',+ aiSetupAgentMCPStartFailed:+ 'The MCP server is installed but didn’t start. Restart OpenPencil, then check again.',+ aiSetupAgentLookupFailed: 'Couldn’t check this computer. Try again.',+ aiSetupAgentCopyPrompt: 'Copy setup prompt',+ aiSetupAgentCheckAgain: 'Check again',+ aiSetupAgentGuide: 'Setup guide',+ aiSetupPiDescription:+ 'OpenPencil runs Pi through its Harness companion and uses the providers you signed in to in Pi.',+ aiSetupPiCompanion: 'Harness companion',+ aiSetupPiInstallCompanion: 'Install companion',+ aiSetupPiUpdateCompanion: 'Update companion',+ aiSetupPiModel: params('Pi’s default model: {model}'),+ aiSetupPiNoModel: 'No default model set in Pi',+ piModelHint: 'A Pi model such as provider/model. Leave empty to use Pi’s default model.',+ aiSetupPiSignIn:+ 'To sign in to a provider or pick a default model, run pi in a terminal and type /login or /model.',+ aiSetupGetDesktop: 'Get the desktop app',+ aiSetupMeteredNote:+ 'OpenRouter gives you models from several vendors with one account and one key.',+ aiSetupReviewTitle: 'Review your setup',+ aiSetupAgentModel: 'Model chosen by the agent',+ aiSetupFinish: 'Finish setup',+ aiSetupSavedTitle: 'AI is ready',+ aiSetupSavedDescription: 'You can change models and roles anytime in Settings.',+ aiSetupRun: 'Run guided setup',+ aiSetupServerKeyHint: 'If your server does not check keys, enter any value.',+ aiSetupGapDesign: 'Nothing you selected can create and edit designs.',+ aiSetupGapVision: 'Nothing you selected can review images, so visual review would stay off.',+ aiSetupGapContinue: 'You can continue without it and add it later in Settings.',+ aiSetupGapAddOpenRouter: 'Add OpenRouter (pay as you go)',+ aiSetupGapRemoveOpenRouter: 'Don’t use OpenRouter',+ aiSetupGapCoveredByOpenRouter:+ 'OpenRouter will cover what your other choices can’t, billed per request.',+ aiSetupServerVision: 'This model can read images',+ aiSetupSavedKeyHint: 'Leave blank to keep the saved key.',+ aiSetupAlreadyConnected: 'Everything you selected is already connected.',+ aiSetupOpenRouterSignIn: 'Sign in with OpenRouter',+ aiSetupOpenRouterWaiting: 'Finish signing in to OpenRouter in your browser.',+ aiSetupOpenRouterReopen: 'Open again',+ aiSetupOpenRouterOrKey: 'Or paste an API key',+ aiSetupOpenRouterBlocked:+ 'Your browser blocked the sign-in window. Allow pop-ups for OpenPencil and try again.',+ aiSetupOpenRouterCancelled: 'Sign-in was cancelled.',+ aiSetupOpenRouterExpired: 'Sign-in took too long. Try again.',+ aiSetupOpenRouterFailed: 'Couldn’t sign in to OpenRouter. Try again or paste an API key.',+ aiSetupOpenRouterSignedInTitle: 'Signed in to OpenRouter',+ aiSetupOpenRouterKeyLabel: params('· key “{label}”'),+ aiSetupOpenRouterVerifying: 'Checking your OpenRouter key…',+ aiSetupOpenRouterNoCredits:+ 'This OpenRouter account has no credits yet. Add credits on OpenRouter to use paid models such as the recommended one.',+ aiSetupOpenRouterChange: 'Use a different account',+ aiSetupUseRecommended: 'Use recommended setup',+ aiSetupRolesDescription:+ 'Choose a model for each kind of work. We picked recommended ones from what you connected; anything else you configured stays as it is.'} as constexport const aiMessages = i18n('ai', aiMessageDefaults)diff --git a/playwright.config.ts b/playwright.config.tsindex 0bf43d76d..8cb38ead0 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -36,6 +36,21 @@ const appDefaults = {},use: {baseURL: origin,+ // Tests start past the first-run AI setup offer; its own spec clears this.+ storageState: {+ cookies: [],+ origins: [+ {+ origin,+ localStorage: [+ {+ name: 'open-pencil:preferences:v1',+ value: JSON.stringify({ version: 1, onboarding: { aiSetup: 'done' } })+ }+ ]+ }+ ]+ },testIdAttribute: 'data-test-id',viewport: { width: 1280, height: 800 },deviceScaleFactor: 2,diff --git a/public/oauth/openrouter-desktop.html b/public/oauth/openrouter-desktop.htmlnew file mode 100644index 000000000..832b3fab7--- /dev/null+++ b/public/oauth/openrouter-desktop.html@@ -0,0 +1,14 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="robots" content="noindex" />+ <title>OpenPencil</title>+ <script src="/oauth/openrouter-desktop.js" defer></script>+ </head>+ <body style="font: 14px system-ui, sans-serif; margin: 3rem auto; max-width: 28rem; text-align: center">+ <p>Returning to OpenPencil…</p>+ <p><a id="return" href="openpencil://oauth/openrouter">Open OpenPencil</a></p>+ </body>+</html>diff --git a/public/oauth/openrouter-desktop.js b/public/oauth/openrouter-desktop.jsnew file mode 100644index 000000000..605a4c85f--- /dev/null+++ b/public/oauth/openrouter-desktop.js@@ -0,0 +1,5 @@+// Hands OpenRouter's redirect to the desktop app, which validates the state and exchanges the+// code for a key. The code is useless without the verifier, which never leaves the app.+const target = `openpencil://oauth/openrouter${window.location.search}`+document.getElementById('return')?.setAttribute('href', target)+window.location.replace(target)diff --git a/public/oauth/openrouter.html b/public/oauth/openrouter.htmlnew file mode 100644index 000000000..d02e55635--- /dev/null+++ b/public/oauth/openrouter.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="robots" content="noindex" />+ <title>OpenPencil</title>+ <script src="/oauth/openrouter.js" defer></script>+ </head>+ <body style="font: 14px system-ui, sans-serif; margin: 3rem auto; max-width: 28rem; text-align: center">+ <p>You can close this window and return to OpenPencil.</p>+ </body>+</html>diff --git a/public/oauth/openrouter.js b/public/oauth/openrouter.jsnew file mode 100644index 000000000..9d052bb12--- /dev/null+++ b/public/oauth/openrouter.js@@ -0,0 +1,6 @@+// Relays OpenRouter's redirect to the editor that started sign-in, which validates the state,+// exchanges the code for a key, and closes this window.+const channel = new BroadcastChannel('open-pencil:openrouter-oauth')+channel.postMessage(window.location.search)+channel.close()+window.close()diff --git a/src/App.vue b/src/App.vueindex 516ceca9d..3ff19893c 100644--- a/src/App.vue+++ b/src/App.vue@@ -20,6 +20,7 @@ import UnsavedChangesDialog from '@/components/document/UnsavedChangesDialog.vueimport PublishLibraryDialog from '@/components/libraries/PublishLibraryDialog.vue'import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpdateReviewDialog.vue'import RecoveryDialog from '@/components/recovery/RecoveryDialog.vue'+import AISetupDialog from '@/components/settings/ai-setup/AISetupDialog.vue'import SettingsDialog from '@/components/settings/SettingsDialog.vue'import AppShell from '@/components/shell/AppShell.vue'import Toaster from '@/components/shell/Toaster.vue'@@ -56,6 +57,7 @@ onMounted(() => {<RouterView /></AppShell><SettingsDialog />+ <AISetupDialog /><RecoveryDialog /><UnsavedChangesDialog /><PublishLibraryDialog />diff --git a/src/app/ai/acp/setup-prompt.ts b/src/app/ai/acp/setup-prompt.tsnew file mode 100644index 000000000..45d2983f2--- /dev/null+++ b/src/app/ai/acp/setup-prompt.ts@@ -0,0 +1,46 @@+import dedent from 'dedent'++import { ACP_AGENTS, type ACPAgentID } from '@open-pencil/core/constants'++import { MCP_INSTALL_TARGET } from '@/app/automation/mcp/failure'++/** Installs OpenPencil's MCP server at the version that matches the app. */+export const MCP_INSTALL_COMMAND = `npm i -g ${MCP_INSTALL_TARGET}`++/** The public guide for connecting a coding agent, one section per agent. */+export const CODING_AGENTS_GUIDE_URL = 'https://openpencil.dev/programmable/coding-agents'++const SIGN_IN: Record<ACPAgentID, string> = {+ 'claude-code':+ 'Make sure I am signed in to Claude Code: run `claude` and use `/login` if it asks me to sign in.',+ codex: 'Make sure I am signed in to Codex: run `codex login` if I am not.',+ 'gemini-cli': 'Make sure I am signed in to Gemini CLI: run `gemini` and choose a sign-in method.'+}++export function codingAgentGuideURL(agentID: ACPAgentID): string {+ return `${CODING_AGENTS_GUIDE_URL}#${agentID}`+}++/**+ * Markdown to paste into a coding agent the person already uses, asking it to install what+ * OpenPencil needs to start it. Written for the agent, so it stays in English.+ */+export function codingAgentSetupPrompt(agentID: ACPAgentID): string {+ const agent = ACP_AGENTS.find((candidate) => candidate.id === agentID)+ if (!agent) return ''+ const install = agent.installCommand ?? `Install ${agent.name}`+ return dedent`+ Help me connect ${agent.name} to OpenPencil, an open-source design editor. OpenPencil starts ${agent.name} through the Agent Client Protocol and gives it canvas tools through OpenPencil's local MCP server, so both need to be installed on this computer.++ Please do this for me:++ 1. If \`${agent.command}\` is not on my PATH, install it: \`${install}\`+ 2. If \`openpencil-mcp-http\` is not on my PATH, install OpenPencil's MCP server: \`${MCP_INSTALL_COMMAND}\`+ 3. Confirm both commands are found, for example with \`which ${agent.command}\` and \`which openpencil-mcp-http\` (\`where\` on Windows). If a global npm folder is missing from my PATH, tell me how to add it.+ 4. ${SIGN_IN[agentID]}++ Then tell me what you installed and anything I still need to do myself. I will press "Check again" in OpenPencil's AI setup afterwards.++ Setup guide: ${codingAgentGuideURL(agentID)}+ `+}diff --git a/src/app/ai/agents/companions.ts b/src/app/ai/agents/companions.tsnew file mode 100644index 000000000..0fc70f53e--- /dev/null+++ b/src/app/ai/agents/companions.ts@@ -0,0 +1,28 @@+import { APP_VERSION } from '@/app/runtime/version'++function majorMinor(version: string): string | null {+ const match = /^(\d+)\.(\d+)/.exec(version)+ return match ? `${match[1]}.${match[2]}` : null+}++/**+ * Whether an installed OpenPencil companion (MCP server, Harness) is too old or new for this app.+ * Companions must match the app's major.minor version. One that reports no version predates+ * `--version`, which the desktop app asks every installed companion, so it is outdated too.+ */+export function isOutdatedCompanion(+ version: string | null | undefined,+ appVersion: string = APP_VERSION+): boolean {+ if (!version) return true+ return majorMinor(version) !== majorMinor(appVersion)+}++const BUN_GLOBAL_BIN = /[\\/]\.bun[\\/]/++/** The command that replaces a global package with the package manager that installed it. */+export function globalInstallCommand(target: string, executablePath?: string | null): string {+ return executablePath && BUN_GLOBAL_BIN.test(executablePath)+ ? `bun add -g ${target}`+ : `npm i -g ${target}`+}diff --git a/src/app/ai/agents/discovery.ts b/src/app/ai/agents/discovery.tsnew file mode 100644index 000000000..81d30b554--- /dev/null+++ b/src/app/ai/agents/discovery.ts@@ -0,0 +1,221 @@+import { computed, ref, shallowRef } from 'vue'++import {+ ACP_AGENTS,+ IS_TAURI,+ type ACPAgentDef,+ type ACPAgentID+} from '@open-pencil/core/constants'++import {+ HARNESS_EXECUTABLE,+ HARNESS_INSTALL_TARGET,+ HARNESS_PACKAGE+} from '@/app/ai/harness/companion'+import { MCP_INSTALL_TARGET, MCP_PACKAGE_NAME } from '@/app/automation/mcp/failure'++import { globalInstallCommand, isOutdatedCompanion } from './companions'+import {+ installAgentAdapter,+ installCanvasBridge,+ installHarnessCompanion,+ lookupAgents,+ type AgentLookup+} from './native'++const MCP_EXECUTABLE = 'openpencil-mcp-http'++export type DetectedAgent = {+ definition: ACPAgentDef+ cliPath: string | null+ adapterPath: string | null+ status: 'available' | 'needs-adapter' | 'not-installed'+}++export function detectedAgents(lookup: AgentLookup): DetectedAgent[] {+ return ACP_AGENTS.map((definition) => {+ const cliPath = lookup.executables[definition.cliCommand ?? definition.command] ?? null+ const adapterPath = lookup.executables[definition.command] ?? null+ const unavailableStatus = cliPath ? 'needs-adapter' : 'not-installed'+ return {+ definition,+ cliPath,+ adapterPath,+ status: adapterPath ? 'available' : unavailableStatus+ }+ })+}++export function createAgentDiscovery(options: {+ enabled: boolean+ lookup: () => Promise<AgentLookup>+ install: (agent: ACPAgentDef, searchPath: string) => Promise<void>+ installBridge?: (searchPath: string) => Promise<void>+ restartBridge?: () => Promise<void>+ installHarness?: (searchPath: string) => Promise<void>+}) {+ const snapshot = shallowRef<AgentLookup | null>(null)+ const scanning = ref(false)+ const installing = ref<ACPAgentID | 'canvas' | 'harness' | null>(null)+ const error = ref<+ 'lookup' | 'install' | 'npm' | 'canvas-install' | 'canvas-start' | 'harness-install' | null+ >(null)+ let pending: Promise<void> | null = null+ const agents = computed(() => (snapshot.value ? detectedAgents(snapshot.value) : []))+ const availableAgents = computed(() =>+ agents.value.filter((agent) => agent.status === 'available')+ )+ const npmAvailable = computed(() => Boolean(snapshot.value?.executables.npm))+ // Checks read through functions so they see the snapshot of a rescan that just finished.+ function hasBridge(): boolean {+ return Boolean(snapshot.value?.executables[MCP_EXECUTABLE])+ }+ /** An installed MCP server whose version does not match the app. */+ function bridgeOutdated(): boolean {+ return hasBridge() && isOutdatedCompanion(snapshot.value?.versions[MCP_PACKAGE_NAME])+ }+ function hasHarness(): boolean {+ return Boolean(snapshot.value?.executables[HARNESS_EXECUTABLE])+ }+ function harnessOutdated(): boolean {+ return hasHarness() && isOutdatedCompanion(snapshot.value?.versions[HARNESS_PACKAGE])+ }+ const canvasBridgeAvailable = computed(hasBridge)+ const canvasBridgeOutdated = computed(bridgeOutdated)+ /** The Harness companion that runs Pi. */+ const harnessAvailable = computed(hasHarness)+ const harnessOutdatedVersion = computed(harnessOutdated)+ /** Commands to install or update a companion by hand, for the package manager that has it. */+ const canvasBridgeCommand = computed(() =>+ globalInstallCommand(MCP_INSTALL_TARGET, snapshot.value?.executables[MCP_EXECUTABLE])+ )+ const harnessCommand = computed(() =>+ globalInstallCommand(HARNESS_INSTALL_TARGET, snapshot.value?.executables[HARNESS_EXECUTABLE])+ )++ function refresh(force = false): Promise<void> {+ if (!options.enabled) return Promise.resolve()+ if (pending) return force ? pending.then(() => refresh()) : pending+ scanning.value = true+ error.value = null+ pending = options+ .lookup()+ .then((result) => {+ snapshot.value = result+ return undefined+ })+ .catch(() => {+ error.value = 'lookup'+ })+ .finally(() => {+ scanning.value = false+ pending = null+ })+ return pending+ }++ async function install(id: ACPAgentID): Promise<void> {+ if (!options.enabled || installing.value) return+ const agent = agents.value.find((candidate) => candidate.definition.id === id)+ if (!agent?.definition.adapterPackage || agent.status !== 'needs-adapter') return+ if (!snapshot.value || !npmAvailable.value) {+ error.value = 'npm'+ return+ }+ installing.value = id+ error.value = null+ try {+ await options.install(agent.definition, snapshot.value.searchPath)+ await refresh(true)+ if (+ agents.value.find((candidate) => candidate.definition.id === id)?.status !== 'available'+ ) {+ error.value = 'install'+ }+ } catch {+ error.value = 'install'+ } finally {+ installing.value = null+ }+ }++ async function setupCanvasBridge(): Promise<void> {+ if (!options.enabled || installing.value || !snapshot.value) return+ let installed = hasBridge() && !bridgeOutdated()+ if (!installed && !npmAvailable.value) {+ error.value = 'npm'+ return+ }+ installing.value = 'canvas'+ error.value = null+ try {+ if (!installed) {+ if (!options.installBridge) throw new Error('Canvas bridge setup is unavailable.')+ await options.installBridge(snapshot.value.searchPath)+ await refresh(true)+ if (!hasBridge() || bridgeOutdated())+ throw new Error('A matching MCP server was not found.')+ installed = true+ }+ await options.restartBridge?.()+ } catch {+ error.value = installed ? 'canvas-start' : 'canvas-install'+ } finally {+ installing.value = null+ }+ }++ async function setupHarness(): Promise<void> {+ if (!options.enabled || installing.value || !snapshot.value) return+ if (hasHarness() && !harnessOutdated()) return+ if (!npmAvailable.value) {+ error.value = 'npm'+ return+ }+ installing.value = 'harness'+ error.value = null+ try {+ if (!options.installHarness) throw new Error('Harness companion setup is unavailable.')+ await options.installHarness(snapshot.value.searchPath)+ await refresh(true)+ if (!hasHarness() || harnessOutdated()) error.value = 'harness-install'+ } catch {+ error.value = 'harness-install'+ } finally {+ installing.value = null+ }+ }++ return {+ supported: options.enabled,+ agents,+ availableAgents,+ scanning,+ installing,+ error,+ npmAvailable,+ canvasBridgeAvailable,+ canvasBridgeOutdated,+ canvasBridgeCommand,+ harnessAvailable,+ harnessOutdated: harnessOutdatedVersion,+ harnessCommand,+ setupCanvasBridge,+ setupHarness,+ refresh,+ install+ }+}++export const agentDiscovery = createAgentDiscovery({+ enabled: IS_TAURI,+ lookup: lookupAgents,+ install: installAgentAdapter,+ installBridge: installCanvasBridge,+ installHarness: installHarnessCompanion,+ async restartBridge() {+ const { restartMCPRuntime } = await import('@/app/automation/mcp/runtime')+ const result = await restartMCPRuntime()+ if (!result.ok) throw result.error+ }+})diff --git a/src/app/ai/agents/native.ts b/src/app/ai/agents/native.tsnew file mode 100644index 000000000..4e5fd373f--- /dev/null+++ b/src/app/ai/agents/native.ts@@ -0,0 +1,79 @@+import * as v from 'valibot'++import type { ACPAgentDef } from '@open-pencil/core/constants'++import { HARNESS_INSTALL_TARGET } from '@/app/ai/harness/companion'+import { MCP_INSTALL_TARGET } from '@/app/automation/mcp/failure'+import { resolvePlatformCommand } from '@/app/tauri/command'++const lookupSchema = v.object({+ executables: v.record(v.string(), v.nullable(v.string())),+ /** Versions of OpenPencil's own companions, keyed by package name. */+ versions: v.record(v.string(), v.nullable(v.string())),+ searchPath: v.string()+})++export type AgentLookup = v.InferOutput<typeof lookupSchema>++export async function lookupAgents(): Promise<AgentLookup> {+ const { invoke } = await import('@tauri-apps/api/core')+ return v.parse(lookupSchema, await invoke<unknown>('agent_lookup'))+}++const INSTALL_TIMEOUT_MS = 120_000++export async function installAgentAdapter(agent: ACPAgentDef, searchPath: string): Promise<void> {+ if (!agent.adapterPackage) throw new Error('This agent does not need an adapter.')+ return installPackage(agent.adapterPackage, searchPath)+}++export async function installCanvasBridge(searchPath: string): Promise<void> {+ await installPackage(MCP_INSTALL_TARGET, searchPath)+}++export async function installHarnessCompanion(searchPath: string): Promise<void> {+ await installPackage(HARNESS_INSTALL_TARGET, searchPath)+}++/** The npm arguments that install a package globally; the desktop shell scope pins them. */+export function npmInstallArgs(packageName: string): string[] {+ // These are public packages; a user's private project registry may not mirror them.+ return ['install', '--global', packageName, '--registry=https://registry.npmjs.org']+}++async function installPackage(packageName: string, searchPath: string): Promise<void> {+ const { Command } = await import('@tauri-apps/plugin-shell')+ const resolved = resolvePlatformCommand('npm', npmInstallArgs(packageName))+ const command = Command.create(resolved.command, resolved.args, {+ env: { PATH: searchPath }+ })+ let child: Awaited<ReturnType<typeof command.spawn>> | undefined+ let timer: ReturnType<typeof setTimeout> | undefined+ let closed = false+ let finished = false+ async function killIfRunning() {+ if (!closed) await child?.kill().catch(() => undefined)+ }+ try {+ await new Promise<void>((resolve, reject) => {+ command.on('close', ({ code }) => {+ closed = true+ if (code === 0) resolve()+ else reject(new Error('Adapter installation failed.'))+ })+ command.on('error', () => reject(new Error('Adapter installation failed.')))+ timer = setTimeout(() => {+ reject(new Error('Adapter installation timed out.'))+ }, INSTALL_TIMEOUT_MS)+ void command.spawn().then((spawned) => {+ child = spawned+ if (finished) void killIfRunning()+ return undefined+ }, reject)+ })+ } finally {+ finished = true+ clearTimeout(timer)+ await killIfRunning()+ }+}diff --git a/src/app/ai/agents/readiness.ts b/src/app/ai/agents/readiness.tsnew file mode 100644index 000000000..c9f6c2c22--- /dev/null+++ b/src/app/ai/agents/readiness.ts@@ -0,0 +1,47 @@+import { agentDiscovery } from './discovery'++/** What an agent chat needs before it can start, each fixed by guided setup. */+export type AgentSetupProblem =+ | 'companion-missing'+ | 'companion-outdated'+ | 'mcp-outdated'+ | 'pi-sign-in'+ | 'pi-model'++/** A chat that cannot start until setup is finished; the chat names the fix. */+export class AgentSetupError extends Error {+ constructor(readonly problem: AgentSetupProblem) {+ super(`Agent setup is incomplete: ${problem}`)+ this.name = 'AgentSetupError'+ }+}++type AgentDiscovery = Pick<+ typeof agentDiscovery,+ | 'supported'+ | 'refresh'+ | 'error'+ | 'harnessAvailable'+ | 'harnessOutdated'+ | 'canvasBridgeOutdated'+>++/**+ * Checks the companions an agent chat starts, so a missing or mismatched one fails with a fix+ * instead of an opaque process error. A failed lookup does not block the chat.+ */+export async function assertAgentReady(+ agent: 'acp' | 'pi',+ discovery: AgentDiscovery = agentDiscovery+): Promise<void> {+ if (!discovery.supported) return+ await discovery.refresh(true)+ if (discovery.error.value === 'lookup') return+ if (agent === 'pi' && !discovery.harnessAvailable.value) {+ throw new AgentSetupError('companion-missing')+ }+ if (agent === 'pi' && discovery.harnessOutdated.value) {+ throw new AgentSetupError('companion-outdated')+ }+ if (discovery.canvasBridgeOutdated.value) throw new AgentSetupError('mcp-outdated')+}diff --git a/src/app/ai/attachment/presentation/store.ts b/src/app/ai/attachment/presentation/store.tsindex ac7648e1e..b5571e5df 100644--- a/src/app/ai/attachment/presentation/store.ts+++ b/src/app/ai/attachment/presentation/store.ts@@ -15,6 +15,10 @@ export function setMessageAttachments(attachments.set(messageId, nextAttachments)}+export function deleteMessageAttachments(messageId: string): void {+ attachments.delete(messageId)+}+export function clearMessageAttachments(): void {attachments.clear()}diff --git a/src/app/ai/chat/storage.ts b/src/app/ai/chat/storage.tsindex d3921b1c9..08e5cadf9 100644--- a/src/app/ai/chat/storage.ts+++ b/src/app/ai/chat/storage.ts@@ -41,7 +41,8 @@ export const isAgentProvider = computed(() => isACPProvider.value || isHarnessPrexport const isConfigured = computed(() => {if (isACPProvider.value) return IS_TAURI- if (isHarnessProvider.value) return IS_TAURI && apiKeyStatus.value === 'configured'+ // Pi can use the CLI's own sign-in, so a key is optional.+ if (isHarnessProvider.value) return IS_TAURIif (apiKeyStatus.value !== 'configured') return falseconst needsBaseURL =providerID.value === 'openai-compatible' || providerID.value === 'anthropic-compatible'@@ -49,7 +50,10 @@ export const isConfigured = computed(() => {})async function refreshStatus(reference: CredentialRef): Promise<CredentialStatus> {- const status = await appCredentialServices.manager.status(reference)+ // A key the store cannot read is reported as unavailable rather than rejecting startup.+ const status = await appCredentialServices.manager+ .status(reference)+ .catch((): CredentialStatus => 'unavailable')return status === 'missing' && hasLegacyCredential(reference) ? 'configured' : status}diff --git a/src/app/ai/chat/submission/errors.ts b/src/app/ai/chat/submission/errors.tsnew file mode 100644index 000000000..473bdf2dc--- /dev/null+++ b/src/app/ai/chat/submission/errors.ts@@ -0,0 +1,39 @@+import type { Ref } from 'vue'++import { AgentSetupError, type AgentSetupProblem } from '@/app/ai/agents/readiness'+import { VisionModelUnavailableError } from '@/app/ai/attachment/image/analyze'++export interface SubmissionMessages {+ openSettings: string+ requestFailed: string+ visionUnavailable: string+ runSetup: string+ agentSetup: Record<AgentSetupProblem, string>+}++export interface SubmissionErrorOptions {+ messages: Ref<SubmissionMessages>+ reportError: (message: string, action?: { label: string; run: () => void }) => void+ openModelSettings: () => void+ openSetup: () => void+}++/** Explains why a message could not be sent, with the fix when there is one. */+export function reportSubmissionError(options: SubmissionErrorOptions, error: unknown): void {+ console.error('Chat error:', error)+ if (error instanceof AgentSetupError) {+ options.reportError(options.messages.value.agentSetup[error.problem], {+ label: options.messages.value.runSetup,+ run: options.openSetup+ })+ return+ }+ if (error instanceof VisionModelUnavailableError) {+ options.reportError(options.messages.value.visionUnavailable, {+ label: options.messages.value.openSettings,+ run: options.openModelSettings+ })+ return+ }+ options.reportError(options.messages.value.requestFailed)+}diff --git a/src/app/ai/chat/submission/images.ts b/src/app/ai/chat/submission/images.tsnew file mode 100644index 000000000..8990f817f--- /dev/null+++ b/src/app/ai/chat/submission/images.ts@@ -0,0 +1,15 @@+import { analyzeAttachedImages } from '@/app/ai/attachment/image/analyze'+import { prepareImageAttachment } from '@/app/ai/attachment/image/prepare'+import type { ImageAttachmentDraft } from '@/app/ai/attachment/image/types'+import type { EditorStore } from '@/app/editor/active-store'++/** Prepares a message's images for the model and what the vision model found in them. */+export async function prepareSubmittedImages(+ editor: EditorStore,+ text: string,+ images: ImageAttachmentDraft[]+) {+ const prepared = await Promise.all(images.map((image) => prepareImageAttachment(image.file)))+ const findings = await analyzeAttachedImages(editor, text, prepared)+ return { prepared, findings }+}diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.tsindex 1c335b3ef..d329bc0e2 100644--- a/src/app/ai/chat/submission/use.ts+++ b/src/app/ai/chat/submission/use.ts@@ -1,39 +1,31 @@import { computed, markRaw, ref, type Ref } from 'vue'-import {- analyzeAttachedImages,- designMessageWithImageFindings,- VisionModelUnavailableError-} from '@/app/ai/attachment/image/analyze'-import { prepareImageAttachment, revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'+import { designMessageWithImageFindings } from '@/app/ai/attachment/image/analyze'+import { revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'import {imageDraftPresentations,preparedImagePresentations} from '@/app/ai/attachment/image/presentation'import { snapshotNode } from '@/app/ai/attachment/node/snapshot'-import { setMessageAttachments } from '@/app/ai/attachment/presentation/store'+import {+ deleteMessageAttachments,+ setMessageAttachments+} from '@/app/ai/attachment/presentation/store'import { setVisibleMessageText } from '@/app/ai/chat/presentation'+import { reportSubmissionError, type SubmissionErrorOptions } from '@/app/ai/chat/submission/errors'+import { prepareSubmittedImages } from '@/app/ai/chat/submission/images'import { useRevertRecords } from '@/app/ai/chat/submission/reverts'import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'import { recordTurn, restoreTurn, revertTurn } from '@/app/ai/chat/turns'import { runUndoEntries } from '@/app/ai/tools'import type { EditorStore } from '@/app/editor/active-store'-interface SubmissionMessages {- openSettings: string- requestFailed: string- visionUnavailable: string-}--interface SubmissionOptions {+interface SubmissionOptions extends SubmissionErrorOptions {chat: Ref<ChatInstance | null>ensureChat: () => Promise<ChatInstance | null>flush?: () => Promise<void>clearFailure: () => voidgetEditor: () => EditorStore- messages: Ref<SubmissionMessages>- reportError: (message: string, action?: { label: string; run: () => void }) => void- openModelSettings: () => void}export function useChatSubmission(options: SubmissionOptions) {@@ -69,8 +61,13 @@ export function useChatSubmission(options: SubmissionOptions) {recordTurn(reply, editor, runUndoEntries(editor))}- async function sendText(currentChat: ChatInstance, submission: ChatSubmission): Promise<void> {+ async function sendText(+ currentChat: ChatInstance,+ submission: ChatSubmission,+ dispatch: () => void+ ): Promise<void> {const previousIds = new Set(currentChat.messages.map((message) => message.id))+ dispatch()await withTurn(currentChat, () =>currentChat.sendMessage({ text: submission.modelText }).catch(() => undefined))@@ -80,10 +77,15 @@ export function useChatSubmission(options: SubmissionOptions) {if (message) setVisibleMessageText(message.id, submission.displayText)}+ /**+ * Shows the message at once and sends it once its images are prepared. A failure before it+ * is sent takes the message back out, so the composer can restore the draft.+ */async function sendAttachments(currentChat: ChatInstance,submission: ChatSubmission,- version: number+ version: number,+ dispatch: () => void): Promise<void> {const messageId = crypto.randomUUID()const editor = options.getEditor()@@ -97,19 +99,30 @@ export function useChatSubmission(options: SubmissionOptions) {setVisibleMessageText(messageId, submission.displayText)const draftImages = imageDraftPresentations(messageId, submission.images)setMessageAttachments(messageId, [...nodeAttachments, ...draftImages])- for (const image of submission.images) revokeImagePreviewURL(image.previewURL)+ // The message previews its images from their files; the composer's previews go once sent.+ const send = () => {+ dispatch()+ for (const image of submission.images) revokeImagePreviewURL(image.previewURL)+ }if (submission.images.length === 0) {+ send()await withTurn(currentChat, () =>currentChat.sendMessage({ messageId, text: submission.modelText }).catch(() => undefined))return}- const preparedImages = await Promise.all(- submission.images.map((image) => prepareImageAttachment(image.file))- )- const findings = await analyzeAttachedImages(editor, submission.modelText, preparedImages)+ const images = await prepareSubmittedImages(+ editor,+ submission.modelText,+ submission.images+ ).catch((error: unknown) => {+ currentChat.messages = currentChat.messages.filter((message) => message.id !== messageId)+ deleteMessageAttachments(messageId)+ throw error+ })+ const { prepared: preparedImages, findings } = imagesif (version !== operationVersion || options.chat.value !== currentChat) returnconst normalizedImages = preparedImagePresentations(@@ -118,6 +131,7 @@ export function useChatSubmission(options: SubmissionOptions) {preparedImages)setMessageAttachments(messageId, [...nodeAttachments, ...normalizedImages])+ send()await withTurn(currentChat, () =>currentChat.sendMessage({@@ -132,51 +146,48 @@ export function useChatSubmission(options: SubmissionOptions) {)}- function reportSubmissionError(error: unknown): void {- console.error('Chat error:', error)- if (error instanceof VisionModelUnavailableError) {- options.reportError(options.messages.value.visionUnavailable, {- label: options.messages.value.openSettings,- run: options.openModelSettings- })- return- }- options.reportError(options.messages.value.requestFailed)- }-- async function submit(submission: ChatSubmission): Promise<void> {+ /**+ * Resolves to false when the message never reached the chat. The composer then takes the+ * submission back, attachments included, so their previews stay alive until it decides.+ */+ async function submit(submission: ChatSubmission): Promise<boolean> {const status = options.chat.value?.status ?? 'ready'if (status === 'streaming' || status === 'submitted' || isPreparingAttachments.value) {- for (const image of submission.images) revokeImagePreviewURL(image.previewURL)if (submission.images.length > 0) options.reportError(options.messages.value.requestFailed)- return+ return false}const version = ++operationVersion+ // Whether the message was sent: after that, a failure must not hand it back.+ let sent = false+ const dispatch = () => {+ sent = true+ }isPreparingAttachments.value = submission.images.length > 0options.clearFailure()try {const currentChat = await options.ensureChat()if (currentChat && version === operationVersion) options.chat.value = markRaw(currentChat)if (!currentChat || version !== operationVersion) {- for (const image of submission.images) revokeImagePreviewURL(image.previewURL)if (submission.images.length > 0) options.reportError(options.messages.value.requestFailed)- return+ return false}const note = reverts.note(submission.modelText, currentChat.messages)const noted = { ...submission, modelText: note.text }const previousIds = new Set(currentChat.messages.map((message) => message.id))if (submission.images.length === 0 && submission.nodes.length === 0) {- await sendText(currentChat, noted)+ await sendText(currentChat, noted, dispatch)} else {- await sendAttachments(currentChat, noted, version)+ await sendAttachments(currentChat, noted, version, dispatch)}const request = currentChat.messages.find((message) => message.role === 'user' && !previousIds.has(message.id))if (request) reverts.reported(currentChat, note.reverts, request.id)+ return true} catch (error) {- reportSubmissionError(error)+ reportSubmissionError(options, error)+ return sent} finally {await options.flush?.().catch(() => undefined)if (version === operationVersion) isPreparingAttachments.value = falsediff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.tsindex 5391d1929..d23005c47 100644--- a/src/app/ai/chat/transports.ts+++ b/src/app/ai/chat/transports.ts@@ -14,6 +14,7 @@ import { ref } from 'vue'import { ACP_AGENTS } from '@open-pencil/core/constants'import type { ACPAgentID, AIProviderID } from '@open-pencil/core/constants'+import { AgentSetupError, assertAgentReady } from '@/app/ai/agents/readiness'import { classifyAIChatError, type AIChatFailure } from '@/app/ai/chat/failure'import { resolveLanguageModelID } from '@/app/ai/chat/model'import { reasoningCallSettings, type AIProviderOptions } from '@/app/ai/chat/reasoning'@@ -252,6 +253,7 @@ export function createChatSessionManager({async function createActiveACPTransport() {await destroyAgentTransports()+ await assertAgentReady('acp')const transport = await createACPTransport(providerID.value)acpTransportInstance = transportreturn transport as ChatTransport<UIMessage>@@ -261,13 +263,22 @@ export function createChatSessionManager({await destroyAgentTransports()const runtime = await createAIModelRuntime('design')if (runtime?.kind !== 'harness') throw new Error('The Design agent is not configured for Pi')- const [{ HarnessChatTransport }, { buildPiMCPServers }] = await Promise.all([+ await assertAgentReady('pi')+ const [{ HarnessChatTransport }, { buildPiMCPServers }, { readPiAccount }] = await Promise.all([import('@/app/ai/harness/transport'),- import('@/app/integrations/mcp')+ import('@/app/integrations/mcp'),+ import('@/app/ai/harness/pi-settings')])+ // A saved key is an AI Gateway key; without one, Pi uses the CLI's own sign-in.const apiKey = await resolveModelConnectionAPIKey(runtime.role.connection.id)- if (!apiKey) throw new Error('Credential is unavailable for the Pi agent')- const model = runtime.role.profile.customModelID || runtime.role.profile.modelID+ const account = apiKey ? null : await readPiAccount()+ const model =+ runtime.role.profile.customModelID ||+ runtime.role.profile.modelID ||+ account?.defaultModel ||+ ''+ if (!apiKey && !account?.signedIn) throw new AgentSetupError('pi-sign-in')+ if (!model) throw new AgentSetupError('pi-model')const transport = new HarnessChatTransport(sessionId,{@@ -283,7 +294,9 @@ export function createChatSessionManager({instructions: SYSTEM_PROMPT,mcpServers: await buildPiMCPServers()},- { OPENPENCIL_HARNESS_API_KEY: apiKey }+ apiKey+ ? { OPENPENCIL_HARNESS_API_KEY: apiKey }+ : { OPENPENCIL_HARNESS_AGENT_DIR: account?.agentDir ?? '' })harnessTransportInstance = transportreturn transport as ChatTransport<UIMessage>diff --git a/src/app/ai/harness/companion.ts b/src/app/ai/harness/companion.tsnew file mode 100644index 000000000..0bffe1cc8--- /dev/null+++ b/src/app/ai/harness/companion.ts@@ -0,0 +1,6 @@+import { APP_VERSION } from '@/app/runtime/version'++/** The Harness companion runs Pi; it is installed separately and must match the app version. */+export const HARNESS_EXECUTABLE = 'openpencil-harness'+export const HARNESS_PACKAGE = '@open-pencil/harness'+export const HARNESS_INSTALL_TARGET = `${HARNESS_PACKAGE}@${APP_VERSION}`diff --git a/src/app/ai/harness/pi-settings.ts b/src/app/ai/harness/pi-settings.tsnew file mode 100644index 000000000..4d5dce8b1--- /dev/null+++ b/src/app/ai/harness/pi-settings.ts@@ -0,0 +1,42 @@+import * as v from 'valibot'++/** The settings Pi's CLI keeps next to its sign-ins; only non-secret fields are read. */+const piSettingsSchema = v.object({+ defaultModel: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1)))+})++export interface PiAccount {+ /** Pi's agent folder; the Harness companion reuses the sign-ins stored there. */+ agentDir: string+ /** Pi's default model, used when an OpenPencil Pi profile names none. */+ defaultModel: string | null+ /** Pi keeps sign-ins in `auth.json`; only whether it exists is checked, never its contents. */+ signedIn: boolean+}++/** Reads the default model from Pi's `settings.json`; never touches `auth.json`. */+export function parsePiSettings(text: string): string | null {+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), piSettingsSchema), text)+ return parsed.success ? (parsed.output.defaultModel ?? null) : null+}++/**+ * Finds the Pi CLI's agent folder (`~/.pi/agent`), its default model, and whether anyone signed+ * in there, on the desktop. Null where there is no home folder to look in.+ */+export async function readPiAccount(): Promise<PiAccount | null> {+ const [{ homeDir, join }, { exists, readTextFile }] = await Promise.all([+ import('@tauri-apps/api/path'),+ import('@tauri-apps/plugin-fs')+ ])+ const home = await homeDir().catch(() => '')+ if (!home) return null+ const agentDir = await join(home, '.pi', 'agent')+ // The desktop capability allows reading only settings.json from Pi's folder, and checking+ // only that auth.json exists.+ const [settings, signedIn] = await Promise.all([+ readTextFile(await join(agentDir, 'settings.json')).catch(() => null),+ exists(await join(agentDir, 'auth.json')).catch(() => false)+ ])+ return { agentDir, defaultModel: settings ? parsePiSettings(settings) : null, signedIn }+}diff --git a/src/app/ai/models/provider-name.ts b/src/app/ai/models/provider-name.tsnew file mode 100644index 000000000..70a754a3d--- /dev/null+++ b/src/app/ai/models/provider-name.ts@@ -0,0 +1,11 @@+import { ACP_AGENTS, AI_PROVIDERS, HARNESS_PROVIDER_ID } from '@open-pencil/core/constants'++/** Display name for a provider, agent, or the Pi harness. */+export function modelProviderName(providerID: string): string {+ if (providerID === HARNESS_PROVIDER_ID) return 'Pi'+ if (providerID.startsWith('acp:')) {+ const agentID = providerID.slice('acp:'.length)+ return ACP_AGENTS.find((agent) => agent.id === agentID)?.name ?? providerID+ }+ return AI_PROVIDERS.find((provider) => provider.id === providerID)?.name ?? providerID+}diff --git a/src/app/ai/models/runtime.ts b/src/app/ai/models/runtime.tsindex 24d5f4fdf..c25865d10 100644--- a/src/app/ai/models/runtime.ts+++ b/src/app/ai/models/runtime.ts@@ -1,4 +1,5 @@import type { LanguageModel } from 'ai'+import { ref } from 'vue'import { createLanguageModel } from '@/app/ai/chat/model'import { modelConnection, resolveAIModelRole } from '@/app/ai/models/store'@@ -40,13 +41,20 @@ export async function modelConnectionCredentialStatus(return appCredentialServices.manager.status(modelConnectionCredentialRef(connection))}+/** Changes whenever a model connection's key is saved or cleared, so status views can refresh. */+export const modelCredentialRevision = ref(0)+export async function setModelConnectionAPIKey(connectionId: string, value: string): Promise<void> {const connection = modelConnection(connectionId)if (!connection || connection.providerID.startsWith('acp:')) returnconst reference = modelConnectionCredentialRef(connection)const key = value.trim()- if (key) await appCredentialServices.manager.set(reference, key)- else await appCredentialServices.manager.clear(reference)+ try {+ if (key) await appCredentialServices.manager.set(reference, key)+ else await appCredentialServices.manager.clear(reference)+ } finally {+ modelCredentialRevision.value+++ }}export async function resolveModelConnectionAPIKey(connectionId: string): Promise<string | null> {diff --git a/src/app/ai/models/settings/onboarding/agents.ts b/src/app/ai/models/settings/onboarding/agents.tsnew file mode 100644index 000000000..df63921d5--- /dev/null+++ b/src/app/ai/models/settings/onboarding/agents.ts@@ -0,0 +1,119 @@+import { ref } from 'vue'++import { agentDiscovery, type DetectedAgent } from '@/app/ai/agents/discovery'+import { readPiAccount } from '@/app/ai/harness/pi-settings'++import type { OnboardingAccess } from './plan'++type AgentDiscovery = typeof agentDiscovery++/** What guided setup knows about one coding agent and the MCP server it needs. */+export interface AgentSetupState {+ /** False where agents cannot run, so only manual instructions apply. */+ supported: boolean+ scanning: boolean+ detected: DetectedAgent | null+ /** OpenPencil's MCP server, through which agents reach the canvas. */+ bridge: boolean+ /** The installed MCP server does not match this app's version. */+ bridgeOutdated: boolean+ /** Installs or updates the MCP server by hand. */+ bridgeCommand: string+ /** npm, which one-click installation runs. */+ npm: boolean+ installingAgent: boolean+ installingBridge: boolean+ error: AgentDiscovery['error']['value']+}++/** What guided setup knows about Pi: the Harness companion that runs it and Pi's own settings. */+export interface PiSetupState {+ supported: boolean+ scanning: boolean+ /** The `openpencil-harness` companion that runs Pi. */+ companion: boolean+ companionOutdated: boolean+ companionCommand: string+ bridge: boolean+ bridgeOutdated: boolean+ bridgeCommand: string+ npm: boolean+ installingCompanion: boolean+ installingBridge: boolean+ /** The default model set in Pi, used unless OpenPencil names another. */+ defaultModel: string | null+ error: AgentDiscovery['error']['value']+}++/** Coding agent setup in guided setup, backed by the desktop agent discovery. */+export function useOnboardingAgents(+ discovery: AgentDiscovery = agentDiscovery,+ readPi: typeof readPiAccount = readPiAccount+) {+ const piDefaultModel = ref<string | null>(null)+ const readingPi = ref(false)++ function agentID(providerID: OnboardingAccess) {+ return providerID.startsWith('acp:') ? providerID.slice('acp:'.length) : null+ }++ function agentSetup(providerID: OnboardingAccess): AgentSetupState {+ const id = agentID(providerID)+ return {+ supported: discovery.supported,+ scanning: discovery.scanning.value,+ detected: discovery.agents.value.find((agent) => agent.definition.id === id) ?? null,+ bridge: discovery.canvasBridgeAvailable.value,+ bridgeOutdated: discovery.canvasBridgeOutdated.value,+ bridgeCommand: discovery.canvasBridgeCommand.value,+ npm: discovery.npmAvailable.value,+ installingAgent: discovery.installing.value === id,+ installingBridge: discovery.installing.value === 'canvas',+ error: discovery.error.value+ }+ }++ function piSetup(providerID: OnboardingAccess): PiSetupState | undefined {+ if (providerID !== 'harness:pi') return undefined+ return {+ supported: discovery.supported,+ scanning: discovery.scanning.value || readingPi.value,+ companion: discovery.harnessAvailable.value,+ companionOutdated: discovery.harnessOutdated.value,+ companionCommand: discovery.harnessCommand.value,+ bridge: discovery.canvasBridgeAvailable.value,+ bridgeOutdated: discovery.canvasBridgeOutdated.value,+ bridgeCommand: discovery.canvasBridgeCommand.value,+ npm: discovery.npmAvailable.value,+ installingCompanion: discovery.installing.value === 'harness',+ installingBridge: discovery.installing.value === 'canvas',+ defaultModel: piDefaultModel.value,+ error: discovery.error.value+ }+ }++ function installAgent(providerID: OnboardingAccess): Promise<void> {+ if (providerID === 'harness:pi') return discovery.setupHarness()+ const detected = agentSetup(providerID).detected+ return detected ? discovery.install(detected.definition.id) : Promise.resolve()+ }++ async function refreshAgents(): Promise<void> {+ if (!discovery.supported) return+ readingPi.value = true+ try {+ const [, account] = await Promise.all([discovery.refresh(true), readPi().catch(() => null)])+ piDefaultModel.value = account?.defaultModel ?? null+ } finally {+ readingPi.value = false+ }+ }++ return {+ agentSetup,+ piSetup,+ installAgent,+ refreshAgents,+ setupCanvasBridge: () => discovery.setupCanvasBridge()+ }+}diff --git a/src/app/ai/models/settings/onboarding/apply.ts b/src/app/ai/models/settings/onboarding/apply.tsnew file mode 100644index 000000000..57dc36d4c--- /dev/null+++ b/src/app/ai/models/settings/onboarding/apply.ts@@ -0,0 +1,191 @@+import { AI_PROVIDERS } from '@open-pencil/core/constants'++import type {+ AIModelConnection,+ AIModelProfile,+ AIModelProfileId,+ AIModelSettings+} from '@/app/ai/models/types'++import {+ isOnboardingAccess,+ isOnboardingAgent,+ ONBOARDING_SERVER_PROVIDER,+ type OnboardingAccess,+ type OnboardingPlan,+ type PlannedModel+} from './plan'++const DEFAULT_MAX_OUTPUT_TOKENS = 16_384+/** The profile a fresh install starts with before anything is configured. */+const PLACEHOLDER_PROFILE_ID = 'model-default'++/** Details entered while connecting; only a server needs an address and its own model ID. */+export interface OnboardingConnectionDetails {+ customBaseURL: string+ customModelID: string+}++export interface ApplyOnboardingInput {+ settings: AIModelSettings+ /** The final model for every role; a `null` design keeps the current design model. */+ plan: OnboardingPlan+ details: Partial<Record<OnboardingAccess, OnboardingConnectionDetails>>+ createId: () => string+}++export interface ApplyOnboardingResult {+ settings: AIModelSettings+ /** Connection used for each planned provider, so the caller can store its API key. */+ connectionIds: Partial<Record<OnboardingAccess, string>>+}++function effectiveModelID(profile: Pick<AIModelProfile, 'modelID' | 'customModelID'>): string {+ return profile.customModelID || profile.modelID+}++function recommendedMaxOutputTokens(providerID: string, modelID: string): number {+ const provider = AI_PROVIDERS.find((definition) => definition.id === providerID)+ const model = provider?.models.find((candidate) => candidate.id === modelID)+ return model?.recommendedMaxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS+}++function isPlaceholder(settings: AIModelSettings, profile: AIModelProfile): boolean {+ if (profile.id !== PLACEHOLDER_PROFILE_ID || effectiveModelID(profile)) return false+ const connection = settings.connections.find((candidate) => candidate.id === profile.connectionId)+ return connection?.providerID === ONBOARDING_SERVER_PROVIDER && !connection.customBaseURL+}++function isUnusedPlaceholder(settings: AIModelSettings, profile: AIModelProfile): boolean {+ return (+ isPlaceholder(settings, profile) && !Object.values(settings.assignments).includes(profile.id)+ )+}++/** True while the settings hold only the empty profile a fresh install starts with. */+export function isUnconfiguredModelSettings(settings: AIModelSettings): boolean {+ return settings.models.length === 1 && isPlaceholder(settings, settings.models[0])+}++function isAgentConnection(+ settings: AIModelSettings,+ profile: AIModelProfile | undefined+): boolean {+ const connection = settings.connections.find(+ (candidate) => candidate.id === profile?.connectionId+ )+ return !connection || isOnboardingAgent(connection.providerID)+}++/**+ * Clears assignments the model settings would reject: agents only take the design role, and+ * vision needs a model that accepts images, whether assigned directly or through the design model.+ */+function enforceRoleRules(settings: AIModelSettings): void {+ const profileOf = (id: string | null) => settings.models.find((profile) => profile.id === id)+ const design = profileOf(settings.assignments.design)+ for (const role of ['review', 'fast', 'vision'] as const) {+ const assignment = settings.assignments[role]+ if (assignment === null) continue+ const profile = assignment === 'design' ? design : profileOf(assignment)+ if (!profile) continue+ if (+ isAgentConnection(settings, profile) ||+ (role === 'vision' && !profile.capabilities.includes('vision'))+ ) {+ settings.assignments[role] = null+ }+ }+}++function removeUnusedPlaceholder(settings: AIModelSettings): void {+ const placeholder = settings.models.find((profile) => isUnusedPlaceholder(settings, profile))+ if (!placeholder) return+ settings.models = settings.models.filter((profile) => profile !== placeholder)+ if (!settings.models.some((profile) => profile.connectionId === placeholder.connectionId)) {+ settings.connections = settings.connections.filter(+ (connection) => connection.id !== placeholder.connectionId+ )+ }+}++/**+ * Merges a confirmed onboarding plan into the current settings. Matching connections and+ * profiles are reused, and anything configured in the advanced settings is kept.+ */+export function applyOnboardingPlan({+ settings: current,+ plan,+ details,+ createId+}: ApplyOnboardingInput): ApplyOnboardingResult {+ const settings = structuredClone(current)+ const connectionIds: ApplyOnboardingResult['connectionIds'] = {}++ function connectionFor(providerID: OnboardingAccess): AIModelConnection {+ const customBaseURL = details[providerID]?.customBaseURL.trim() ?? ''+ const existing = settings.connections.find(+ (connection) =>+ connection.providerID === providerID && connection.customBaseURL === customBaseURL+ )+ const connection = existing ?? {+ id: `connection-${createId()}`,+ providerID,+ customBaseURL,+ customAPIType: 'completions' as const,+ credentialProfileId: ''+ }+ if (!existing) {+ connection.credentialProfileId = connection.id+ settings.connections.push(connection)+ }+ connectionIds[providerID] = connection.id+ return connection+ }++ function profileFor(model: PlannedModel): AIModelProfileId | null {+ if (model.profileId) {+ return settings.models.some((profile) => profile.id === model.profileId)+ ? model.profileId+ : null+ }+ if (!isOnboardingAccess(model.providerID)) return null+ const connection = connectionFor(model.providerID)+ const customModelID = details[model.providerID]?.customModelID.trim() ?? ''+ const wanted = customModelID || model.modelID+ // Reuse only a profile that can do everything the plan relies on.+ const existing = settings.models.find(+ (profile) =>+ profile.connectionId === connection.id &&+ effectiveModelID(profile) === wanted &&+ model.capabilities.every((capability) => profile.capabilities.includes(capability))+ )+ if (existing) return existing.id+ const profile: AIModelProfile = {+ id: `model-${createId()}`,+ name: customModelID || model.name,+ connectionId: connection.id,+ modelID: model.modelID,+ customModelID,+ maxOutputTokens: recommendedMaxOutputTokens(model.providerID, model.modelID),+ thinkingLevel: 'default',+ capabilities: [...model.capabilities]+ }+ settings.models.push(profile)+ return profile.id+ }++ if (plan.design) {+ settings.assignments.design = profileFor(plan.design) ?? settings.assignments.design+ }+ for (const role of ['vision', 'review', 'fast'] as const) {+ const choice = plan[role]+ settings.assignments[role] =+ choice === null || choice === 'design' ? choice : profileFor(choice)+ }++ enforceRoleRules(settings)+ removeUnusedPlaceholder(settings)++ return { settings, connectionIds }+}diff --git a/src/app/ai/models/settings/onboarding/connections.ts b/src/app/ai/models/settings/onboarding/connections.tsnew file mode 100644index 000000000..5dba90316--- /dev/null+++ b/src/app/ai/models/settings/onboarding/connections.ts@@ -0,0 +1,186 @@+import { tryOnScopeDispose } from '@vueuse/core'+import { reactive } from 'vue'++import {+ testProviderConnection,+ type ProviderConnectionTestFailureReason+} from '@/app/ai/chat/connection-test'+import {+ aiModelSettings,+ modelConnectionCredentialStatus,+ resolveModelConnectionAPIKey,+ type AIModelConnection+} from '@/app/ai/models'+import type { OpenRouterKeyInfo } from '@/app/ai/providers/openrouter/key'+import type { CredentialStatus } from '@/app/settings/credentials/types'++import {+ isOnboardingAgent,+ ONBOARDING_SERVER_PROVIDER,+ type OnboardingAccess,+ type PlannedModel+} from './plan'++export type ConnectionTestStatus = 'idle' | 'testing' | 'success' | 'error'++export interface OnboardingConnectionState {+ /** A newly entered key; kept only until it is saved or setup closes. */+ apiKey: string+ customBaseURL: string+ customModelID: string+ test: ConnectionTestStatus+ reason: ProviderConnectionTestFailureReason | null+ /** Set once a key from signing in has been checked with the provider. */+ account: OpenRouterKeyInfo | null+}++/** Local servers with a well-known OpenAI-compatible address. */+export const ONBOARDING_SERVER_PRESETS = [+ { id: 'ollama', name: 'Ollama', baseURL: 'http://localhost:11434/v1' },+ { id: 'lmstudio', name: 'LM Studio', baseURL: 'http://localhost:1234/v1' }+] as const++/** Details the person edits while connecting. */+export type OnboardingConnectionPatch = Partial<+ Pick<OnboardingConnectionState, 'apiKey' | 'customBaseURL' | 'customModelID'>+>++/**+ * The configured connection onboarding would reuse: the provider's connection without an+ * address, or for a server the one at the given address (any server when none is given).+ */+export function existingOnboardingConnection(+ providerID: OnboardingAccess,+ customBaseURL?: string+): AIModelConnection | null {+ const server = providerID === ONBOARDING_SERVER_PROVIDER+ return (+ aiModelSettings.value.connections.find(+ (connection) =>+ connection.providerID === providerID &&+ (server+ ? Boolean(connection.customBaseURL) &&+ (customBaseURL === undefined || connection.customBaseURL === customBaseURL.trim())+ : !connection.customBaseURL)+ ) ?? null+ )+}++interface OnboardingConnectionsOptions {+ plannedModel: (providerID: OnboardingAccess) => PlannedModel | null+}++/** Connection details, saved-key status, and connection tests for the providers being set up. */+export function useOnboardingConnections({ plannedModel }: OnboardingConnectionsOptions) {+ const states = reactive<Partial<Record<OnboardingAccess, OnboardingConnectionState>>>({})+ const keyStatuses = reactive<Record<string, CredentialStatus>>({})+ const testVersions = new Map<OnboardingAccess, number>()+ let disposed = false++ tryOnScopeDispose(() => {+ disposed = true+ clearKeys()+ })++ function clearKeys(): void {+ for (const state of Object.values(states)) state.apiKey = ''+ }++ async function loadKeyStatus(connectionId: string): Promise<void> {+ try {+ const status = await modelConnectionCredentialStatus(connectionId)+ if (!disposed) keyStatuses[connectionId] = status+ } catch {+ if (!disposed) keyStatuses[connectionId] = 'unavailable'+ }+ }++ function connection(providerID: OnboardingAccess): OnboardingConnectionState {+ const current = states[providerID]+ if (current) return current+ const existing = existingOnboardingConnection(providerID)+ const serverProfile =+ providerID === ONBOARDING_SERVER_PROVIDER && existing+ ? aiModelSettings.value.models.find((profile) => profile.connectionId === existing.id)+ : undefined+ states[providerID] = {+ apiKey: '',+ customBaseURL: existing?.customBaseURL ?? '',+ customModelID: serverProfile?.customModelID ?? '',+ test: 'idle',+ reason: null,+ account: null+ }+ return states[providerID]+ }++ /** The configured connection matching what is entered now, whose saved key may be used. */+ function savedConnection(providerID: OnboardingAccess): AIModelConnection | null {+ if (isOnboardingAgent(providerID)) return null+ const saved = existingOnboardingConnection(providerID, connection(providerID).customBaseURL)+ if (saved && !(saved.id in keyStatuses)) {+ keyStatuses[saved.id] = 'missing'+ void loadKeyStatus(saved.id)+ }+ return saved+ }++ function hasSavedKey(providerID: OnboardingAccess): boolean {+ const saved = savedConnection(providerID)+ return Boolean(saved && keyStatuses[saved.id] === 'configured')+ }++ function ready(providerID: OnboardingAccess): boolean {+ if (isOnboardingAgent(providerID)) return true+ const state = connection(providerID)+ if (state.test === 'success' || state.account) return true+ return (+ providerID !== ONBOARDING_SERVER_PROVIDER && hasSavedKey(providerID) && !state.apiKey.trim()+ )+ }++ /** Invalidates a finished or running test after the details it checked change. */+ function resetTest(providerID: OnboardingAccess): void {+ testVersions.set(providerID, (testVersions.get(providerID) ?? 0) + 1)+ const state = connection(providerID)+ state.test = 'idle'+ state.reason = null+ }++ async function testConnection(providerID: OnboardingAccess): Promise<void> {+ const request = (testVersions.get(providerID) ?? 0) + 1+ testVersions.set(providerID, request)+ const state = connection(providerID)+ const current = () => !disposed && testVersions.get(providerID) === request+ state.test = 'testing'+ state.reason = null+ try {+ const saved = savedConnection(providerID)+ const savedKey =+ !state.apiKey.trim() && saved ? await resolveModelConnectionAPIKey(saved.id) : null+ if (!current()) return+ const result = await testProviderConnection({+ providerID,+ apiKey: state.apiKey.trim() || savedKey || '',+ modelID: plannedModel(providerID)?.modelID ?? '',+ customModelID: state.customModelID.trim(),+ customBaseURL: state.customBaseURL.trim(),+ customAPIType: saved?.customAPIType ?? 'completions'+ })+ if (!current()) return+ state.test = result.ok ? 'success' : 'error'+ state.reason = result.ok ? null : result.reason+ } catch {+ if (!current()) return+ state.test = 'error'+ state.reason = 'unknown'+ }+ }++ /** Records a key that setup stored, so the connection shows as saved without a reload. */+ function markKeySaved(connectionId: string): void {+ keyStatuses[connectionId] = 'configured'+ }++ return { connection, hasSavedKey, ready, resetTest, testConnection, clearKeys, markKeySaved }+}diff --git a/src/app/ai/models/settings/onboarding/current.ts b/src/app/ai/models/settings/onboarding/current.tsnew file mode 100644index 000000000..2ed5c8823--- /dev/null+++ b/src/app/ai/models/settings/onboarding/current.ts@@ -0,0 +1,44 @@+import type { AIModelRoleAssignment, AIModelSettings } from '@/app/ai/models/types'++import { isUnconfiguredModelSettings } from './apply'+import type { CurrentOnboardingModels, PlannedModel, PlannedRole } from './plan'++function configuredModel(+ settings: AIModelSettings,+ assignment: AIModelRoleAssignment+): PlannedModel | null {+ const profile =+ assignment && assignment !== 'design'+ ? settings.models.find((candidate) => candidate.id === assignment)+ : undefined+ const connection = settings.connections.find(+ (candidate) => candidate.id === profile?.connectionId+ )+ if (!profile || !connection) return null+ return {+ providerID: connection.providerID,+ modelID: profile.customModelID || profile.modelID,+ name: profile.name,+ capabilities: [...profile.capabilities],+ profileId: profile.id+ }+}++function configuredRole(settings: AIModelSettings, assignment: AIModelRoleAssignment): PlannedRole {+ return assignment === 'design' ? 'design' : configuredModel(settings, assignment)+}++/** What each role uses now, so guided setup keeps models configured by hand. */+export function currentOnboardingModels(settings: AIModelSettings): CurrentOnboardingModels {+ if (isUnconfiguredModelSettings(settings)) {+ return { configured: false, design: null, vision: null, review: null, fast: null }+ }+ const { design, vision, review, fast } = settings.assignments+ return {+ configured: true,+ design: configuredModel(settings, design),+ vision: configuredRole(settings, vision),+ review: configuredRole(settings, review),+ fast: configuredRole(settings, fast)+ }+}diff --git a/src/app/ai/models/settings/onboarding/dialog.ts b/src/app/ai/models/settings/onboarding/dialog.tsnew file mode 100644index 000000000..b989de4d9--- /dev/null+++ b/src/app/ai/models/settings/onboarding/dialog.ts@@ -0,0 +1,35 @@+import { ref } from 'vue'++import { aiModelSettings } from '@/app/ai/models/store'+import { appPreferences, updateAISetupState } from '@/app/settings/preferences/store'++import { isUnconfiguredModelSettings } from './apply'++/** `welcome` introduces OpenPencil first; `guided` starts at the setup questions. */+export type AISetupEntry = 'welcome' | 'guided'++export const aiSetupDialogOpen = ref(false)+export const aiSetupEntry = ref<AISetupEntry>('guided')++export function openAISetup(entry: AISetupEntry = 'guided'): void {+ aiSetupEntry.value = entry+ aiSetupDialogOpen.value = true+}++/** Closing guided setup in any way counts as done, so the welcome is offered only once. */+export function closeAISetup(): void {+ aiSetupDialogOpen.value = false+ updateAISetupState('done')+}++/** Offers the welcome to a fresh install; anyone who already configured AI never sees it. */+export function offerAISetupOnFirstRun(): void {+ // The native test binary starts every run with an empty data store.+ if (import.meta.env.MODE === 'native-test') return+ if (appPreferences.value.onboarding.aiSetup === 'done') return+ if (!isUnconfiguredModelSettings(aiModelSettings.value)) {+ updateAISetupState('done')+ return+ }+ openAISetup('welcome')+}diff --git a/src/app/ai/models/settings/onboarding/plan.ts b/src/app/ai/models/settings/onboarding/plan.tsnew file mode 100644index 000000000..5040f0eca--- /dev/null+++ b/src/app/ai/models/settings/onboarding/plan.ts@@ -0,0 +1,354 @@+import { AI_PROVIDERS, type AIProviderID, type ModelOption } from '@open-pencil/core/constants'++import { modelProviderName } from '@/app/ai/models/provider-name'+import type { AIModelCapability, AIModelProfileId, AIModelRole } from '@/app/ai/models/types'++/** Roles onboarding asks about; review and fast stay in the advanced settings. */+export const ONBOARDING_GOALS = ['design', 'vision'] as const+export type OnboardingGoal = (typeof ONBOARDING_GOALS)[number]++/** Coding agents that run on this computer and bring their own subscription and model. */+export const ONBOARDING_AGENTS = [+ 'acp:claude-code',+ 'acp:codex',+ 'acp:gemini-cli',+ 'harness:pi'+] as const+/** API accounts, in the order onboarding prefers them when several are available. */+export const ONBOARDING_API_PROVIDERS = ['anthropic', 'openai', 'google', 'openrouter'] as const+/** Further API accounts the catalog supports, offered behind "More providers". */+export const ONBOARDING_MORE_API_PROVIDERS = ['deepseek', 'zai', 'minimax'] as const+/** A local model server or a company proxy that speaks the OpenAI API. */+export const ONBOARDING_SERVER_PROVIDER = 'openai-compatible'+/** One account for models from several vendors, recommended when no API account exists yet. */+export const ONBOARDING_METERED_PROVIDER = 'openrouter'++export type OnboardingAccess =+ | (typeof ONBOARDING_AGENTS)[number]+ | (typeof ONBOARDING_API_PROVIDERS)[number]+ | (typeof ONBOARDING_MORE_API_PROVIDERS)[number]+ | typeof ONBOARDING_SERVER_PROVIDER++const ONBOARDING_ACCESS = new Set<string>([+ ...ONBOARDING_AGENTS,+ ...ONBOARDING_API_PROVIDERS,+ ...ONBOARDING_MORE_API_PROVIDERS,+ ONBOARDING_SERVER_PROVIDER+])++export function isOnboardingAccess(providerID: string): providerID is OnboardingAccess {+ return ONBOARDING_ACCESS.has(providerID)+}++export type OnboardingSpending = 'existing' | 'metered'++export interface OnboardingAnswers {+ goals: OnboardingGoal[]+ access: OnboardingAccess[]+ /** `metered` lets setup add OpenRouter for goals nothing selected covers. */+ spending: OnboardingSpending+ /** The person says their server's model can read images. */+ serverVision?: boolean+}++export interface PlannedModel {+ providerID: AIProviderID+ /** Catalog model ID; empty when the connection supplies its own model (server, agent). */+ modelID: string+ name: string+ capabilities: AIModelCapability[]+ /** Set when the plan keeps a model that is already configured. */+ profileId?: AIModelProfileId+}++/** A model for a role, the design model (`'design'`), or nothing. */+export type PlannedRole = PlannedModel | 'design' | null++/** Roles in the order setup shows them. */+export const ONBOARDING_ROLES = [+ 'design',+ 'vision',+ 'review',+ 'fast'+] as const satisfies readonly AIModelRole[]++export interface OnboardingPlan {+ /** `null` keeps the design model that is configured now. */+ design: PlannedModel | null+ vision: PlannedRole+ review: PlannedRole+ fast: PlannedRole+ /** Providers to connect before the plan can be applied, in the order they are used. */+ connections: OnboardingAccess[]+}++/** The models currently assigned to each role. */+export interface CurrentOnboardingModels {+ /** False for a fresh install, whose empty roles are not choices to keep. */+ configured: boolean+ design: PlannedModel | null+ vision: PlannedRole+ review: PlannedRole+ fast: PlannedRole+}++export interface PlanOptions {+ /** Agents run as local processes, so only the desktop app can use them. */+ agentsAvailable: boolean+ current?: CurrentOnboardingModels+}++const NO_CURRENT: CurrentOnboardingModels = {+ configured: false,+ design: null,+ vision: null,+ review: null,+ fast: null+}++/** ACP agents and Pi, which run on this computer and choose their own model. */+export function isOnboardingAgent(providerID: string): boolean {+ return providerID.startsWith('acp:') || providerID === 'harness:pi'+}++function isAgentModel(model: PlannedModel | null): boolean {+ return Boolean(model && isOnboardingAgent(model.providerID))+}++function catalogModels(providerID: AIProviderID): ModelOption[] {+ return AI_PROVIDERS.find((definition) => definition.id === providerID)?.models ?? []+}++function fromCatalog(providerID: AIProviderID, model: ModelOption): PlannedModel {+ return {+ providerID,+ modelID: model.id,+ name: model.name,+ capabilities: model.capabilities ? [...model.capabilities] : ['tools']+ }+}++function plannedModel(providerID: OnboardingAccess, serverVision = false): PlannedModel {+ if (providerID === ONBOARDING_SERVER_PROVIDER) {+ return {+ providerID,+ modelID: '',+ name: modelProviderName(providerID),+ capabilities: serverVision ? ['tools', 'vision'] : ['tools']+ }+ }+ if (isOnboardingAgent(providerID)) {+ return { providerID, modelID: '', name: modelProviderName(providerID), capabilities: ['tools'] }+ }+ const defaultID = AI_PROVIDERS.find((definition) => definition.id === providerID)?.defaultModel+ const model = catalogModels(providerID).find((candidate) => candidate.id === defaultID)+ return model+ ? fromCatalog(providerID, model)+ : { providerID, modelID: '', name: modelProviderName(providerID), capabilities: ['tools'] }+}++/** The provider's model tagged as fast, for low-cost background work. */+function fastModel(providerID: AIProviderID): PlannedModel | null {+ const model = catalogModels(providerID).find(+ (candidate) => candidate.tag === 'Fast' && candidate.capabilities?.includes('tools')+ )+ return model ? fromCatalog(providerID, model) : null+}++function hasVision(model: PlannedModel): boolean {+ return model.capabilities.includes('vision')+}++function availableAccess(answers: OnboardingAnswers, options: PlanOptions): OnboardingAccess[] {+ return answers.access.filter((access) => options.agentsAvailable || !isOnboardingAgent(access))+}++/** A configured model stays while its access is still selected or onboarding cannot offer it. */+function keepable(model: PlannedModel | null, access: OnboardingAccess[]): model is PlannedModel {+ if (!model) return false+ return !isOnboardingAccess(model.providerID) || access.includes(model.providerID)+}++/** Whether a role may follow the design model: agents cannot, and vision needs image input. */+export function canFollowDesign(role: AIModelRole, design: PlannedModel | null): boolean {+ if (!design || isAgentModel(design)) return false+ return role !== 'vision' || hasVision(design)+}++function planDesign(+ answers: OnboardingAnswers,+ access: OnboardingAccess[],+ current: PlannedModel | null+) {+ if (keepable(current, access)) return current+ const preferred: OnboardingAccess[] = [+ ...ONBOARDING_AGENTS,+ ...ONBOARDING_API_PROVIDERS,+ ...ONBOARDING_MORE_API_PROVIDERS,+ ONBOARDING_SERVER_PROVIDER+ ]+ const existing = preferred.find((providerID) => access.includes(providerID))+ if (existing) return plannedModel(existing, answers.serverVision)+ return answers.spending === 'metered' ? plannedModel(ONBOARDING_METERED_PROVIDER) : null+}++function planVision(+ answers: OnboardingAnswers,+ design: PlannedModel | null,+ access: OnboardingAccess[],+ current: PlannedRole+): PlannedRole {+ if (current !== null && current !== 'design' && keepable(current, access)) return current+ if (canFollowDesign('vision', design)) return 'design'+ // A local server that reads images is preferred over a paid account.+ const candidates: OnboardingAccess[] = [+ ONBOARDING_SERVER_PROVIDER,+ ...ONBOARDING_API_PROVIDERS,+ ...ONBOARDING_MORE_API_PROVIDERS+ ]+ const existing = candidates+ .filter((providerID) => access.includes(providerID))+ .map((providerID) => plannedModel(providerID, answers.serverVision))+ .find(hasVision)+ if (existing) return existing+ const metered = plannedModel(ONBOARDING_METERED_PROVIDER)+ if (answers.spending === 'metered' && hasVision(metered)) return metered+ // Nothing new covers visual review, so a configured vision model stays as it is; inheriting+ // from a design model that cannot accept images is not possible.+ return current === 'design' ? null : current+}++/**+ * Review and fast work are never asked about, so a configured choice stays, including none,+ * unless it follows a design model it can no longer follow.+ */+function keepRole(+ current: CurrentOnboardingModels,+ role: 'review' | 'fast',+ design: PlannedModel | null+) {+ const choice = current[role]+ if (!current.configured) return false+ if (choice === 'design') return canFollowDesign(role, design)+ return !isAgentModel(choice)+}++/** Review follows the design model, or uses the API model chosen for vision behind an agent. */+function planReview(+ design: PlannedModel | null,+ vision: PlannedRole,+ current: CurrentOnboardingModels+): PlannedRole {+ if (keepRole(current, 'review', design)) return current.review+ if (canFollowDesign('review', design)) return 'design'+ return vision !== 'design' && vision?.capabilities.includes('tools') ? vision : null+}++/** Fast work uses the provider's fast model when it has one, otherwise the design model. */+function planFast(+ design: PlannedModel | null,+ vision: PlannedRole,+ current: CurrentOnboardingModels+): PlannedRole {+ if (keepRole(current, 'fast', design)) return current.fast+ const apiVision = vision === 'design' ? null : vision+ const base = canFollowDesign('fast', design) ? design : apiVision+ const fast = base ? fastModel(base.providerID) : null+ if (fast && fast.modelID !== base?.modelID) return fast+ if (canFollowDesign('fast', design)) return 'design'+ return base+}++function roleModels(plan: Omit<OnboardingPlan, 'connections'>): PlannedModel[] {+ return [plan.design, plan.vision, plan.review, plan.fast].filter(+ (model): model is PlannedModel => model !== null && model !== 'design'+ )+}++/**+ * Proposes a model for each role, preferring what is already configured and then access the+ * person already has. Agents choose their own model and cannot take the other roles, so those+ * fall back to an API model. Roles the person did not ask about keep their configuration.+ */+export function planOnboarding(answers: OnboardingAnswers, options: PlanOptions): OnboardingPlan {+ const access = availableAccess(answers, options)+ const current = options.current ?? NO_CURRENT+ const design = answers.goals.includes('design')+ ? planDesign(answers, access, current.design)+ : current.design+ const vision = answers.goals.includes('vision')+ ? planVision(answers, design, access, current.vision)+ : current.vision+ const roles = {+ design,+ vision,+ review: planReview(design, vision, current),+ fast: planFast(design, vision, current)+ }+ return { ...roles, connections: planConnections(roles) }+}++/** Providers the planned models need connected, skipping models that are already configured. */+export function planConnections(roles: Omit<OnboardingPlan, 'connections'>): OnboardingAccess[] {+ const providers = roleModels(roles)+ .filter((model) => !model.profileId)+ .map((model) => model.providerID)+ .filter(isOnboardingAccess)+ return [...new Set(providers)]+}++/** Whether every role the person asked about has a model. */+export function coversGoals(plan: OnboardingPlan, goals: OnboardingGoal[]): boolean {+ return goals.every((goal) => plan[goal] !== null)+}++/** Requested goals that the access the person selected cannot cover without OpenRouter. */+export function uncoveredGoals(answers: OnboardingAnswers, options: PlanOptions): OnboardingGoal[] {+ const plan = planOnboarding({ ...answers, spending: 'existing' }, options)+ return answers.goals.filter((goal) => plan[goal] === null)+}++export const SAME_AS_DESIGN = '__design__'+export const NO_MODEL = '__none__'++/** A stable key for a role choice, used as the value of the role's picker. */+export function roleChoiceKey(choice: PlannedRole): string {+ if (choice === 'design') return SAME_AS_DESIGN+ if (choice === null) return NO_MODEL+ return choice.profileId ?? `${choice.providerID}::${choice.modelID}`+}++/**+ * Choices for a role: configured models, every suitable catalog model of a connected provider,+ * an agent or server for the design role, and for the other roles the design model or nothing.+ */+export function roleOptions(+ role: AIModelRole,+ plan: OnboardingPlan,+ configured: PlannedModel[]+): PlannedRole[] {+ const needs: AIModelCapability = role === 'vision' ? 'vision' : 'tools'+ // Planned models come first so a provider whose catalog lists no capabilities still offers one.+ const candidates: PlannedModel[] = [...configured, ...roleModels(plan)]+ for (const providerID of plan.connections) {+ if (isOnboardingAgent(providerID) || providerID === ONBOARDING_SERVER_PROVIDER) {+ candidates.push(+ roleModels(plan).find((model) => model.providerID === providerID) ??+ plannedModel(providerID)+ )+ } else {+ candidates.push(+ ...catalogModels(providerID)+ .filter((model) => model.capabilities)+ .map((model) => fromCatalog(providerID, model))+ )+ }+ }+ const suitable = candidates.filter(+ (model) => model.capabilities.includes(needs) && (role === 'design' || !isAgentModel(model))+ )+ const unique = new Map(suitable.map((model) => [roleChoiceKey(model), model]))+ const models = [...unique.values()]+ if (role === 'design') return models+ return [...(canFollowDesign(role, plan.design) ? (['design'] as const) : []), null, ...models]+}diff --git a/src/app/ai/models/settings/onboarding/roles.ts b/src/app/ai/models/settings/onboarding/roles.tsnew file mode 100644index 000000000..b3cdf3803--- /dev/null+++ b/src/app/ai/models/settings/onboarding/roles.ts@@ -0,0 +1,62 @@+import { computed, ref, type ComputedRef } from 'vue'++import type { AIModelRole } from '@/app/ai/models/types'++import {+ ONBOARDING_ROLES,+ planConnections,+ roleChoiceKey,+ roleOptions,+ type OnboardingPlan,+ type PlannedModel,+ type PlannedRole+} from './plan'++/** The person's model choices per role on top of the recommended plan. */+export function useOnboardingRoles(+ recommended: ComputedRef<OnboardingPlan>,+ configured: PlannedModel[]+) {+ const choices = ref<Partial<Record<AIModelRole, string>>>({})++ function options(role: AIModelRole): PlannedRole[] {+ return roleOptions(role, recommended.value, configured)+ }++ function chosen(role: AIModelRole): PlannedRole {+ const key = choices.value[role]+ const option =+ key === undefined+ ? undefined+ : options(role).find((candidate) => roleChoiceKey(candidate) === key)+ return option === undefined ? recommended.value[role] : option+ }++ /** The recommended plan with the person's choices applied; choices that no longer fit are dropped. */+ const plan = computed<OnboardingPlan>(() => {+ const design = chosen('design')+ const roles = {+ design: design === 'design' ? null : design,+ vision: chosen('vision'),+ review: chosen('review'),+ fast: chosen('fast')+ }+ return { ...roles, connections: planConnections(roles) }+ })++ const isRecommended = computed(() =>+ ONBOARDING_ROLES.every(+ (role) => roleChoiceKey(plan.value[role]) === roleChoiceKey(recommended.value[role])+ )+ )++ function choose(role: AIModelRole, key: string): void {+ choices.value = { ...choices.value, [role]: key }+ }++ function useRecommended(): void {+ choices.value = {}+ }++ return { plan, options, choose, useRecommended, isRecommended }+}diff --git a/src/app/ai/models/settings/onboarding/sign-in.ts b/src/app/ai/models/settings/onboarding/sign-in.tsnew file mode 100644index 000000000..230dbfa32--- /dev/null+++ b/src/app/ai/models/settings/onboarding/sign-in.ts@@ -0,0 +1,96 @@+import { tryOnScopeDispose } from '@vueuse/core'+import { reactive } from 'vue'++import { fetchOpenRouterKeyInfo } from '@/app/ai/providers/openrouter/key'+import {+ signInWithOpenRouter,+ type OpenRouterSignIn,+ type OpenRouterSignInFailure,+ type OpenRouterSignInOptions+} from '@/app/ai/providers/openrouter/sign-in'++import type { OnboardingConnectionState } from './connections'+import type { OnboardingAccess } from './plan'++export type OnboardingSignInStatus = 'idle' | 'waiting' | 'verifying' | OpenRouterSignInFailure++interface OnboardingSignInOptions {+ connection: (providerID: OnboardingAccess) => OnboardingConnectionState+ resetTest: (providerID: OnboardingAccess) => void+}++/** Provider sign-in that fills the API key, then tests it like a pasted key. */+export function useOnboardingSignIn({ connection, resetTest }: OnboardingSignInOptions) {+ const statuses = reactive<Partial<Record<OnboardingAccess, OnboardingSignInStatus>>>({})+ const attempts = new Map<+ OnboardingAccess,+ { controller: AbortController; sign: OpenRouterSignIn }+ >()++ tryOnScopeDispose(() => {+ for (const { controller } of attempts.values()) controller.abort()+ attempts.clear()+ })++ function signInStatus(providerID: OnboardingAccess): OnboardingSignInStatus {+ return statuses[providerID] ?? 'idle'+ }++ async function complete(providerID: OnboardingAccess, sign: OpenRouterSignIn): Promise<void> {+ const current = () => attempts.get(providerID)?.sign === sign+ const result = await sign.result+ if (!current()) return+ if (!result.ok) {+ attempts.delete(providerID)+ statuses[providerID] = result.reason+ return+ }+ // The key is checked with OpenRouter directly, which costs nothing and needs no credits.+ statuses[providerID] = 'verifying'+ const account = await fetchOpenRouterKeyInfo(result.key).catch(() => null)+ if (!current()) return+ attempts.delete(providerID)+ if (!account) {+ statuses[providerID] = 'failed'+ return+ }+ resetTest(providerID)+ Object.assign(connection(providerID), { apiKey: result.key, account })+ statuses[providerID] = 'idle'+ }++ /** Forgets a signed-in key so another account can sign in or a key can be pasted. */+ function signOut(providerID: OnboardingAccess): void {+ cancelSignIn(providerID)+ Object.assign(connection(providerID), { apiKey: '', account: null })+ resetTest(providerID)+ statuses[providerID] = 'idle'+ }++ /** Call directly from the click that starts sign-in, so the browser allows its popup. */+ function signIn(+ providerID: OnboardingAccess,+ labels: Pick<OpenRouterSignInOptions, 'keyLabel'>+ ): void {+ if (providerID !== 'openrouter') return+ attempts.get(providerID)?.controller.abort()+ const controller = new AbortController()+ const sign = signInWithOpenRouter({ ...labels, signal: controller.signal })+ attempts.set(providerID, { controller, sign })+ statuses[providerID] = 'waiting'+ void complete(providerID, sign)+ }++ function reopenSignIn(providerID: OnboardingAccess): void {+ attempts.get(providerID)?.sign.reopen()+ }++ /** Stops an attempt, including one whose key is still being checked. */+ function cancelSignIn(providerID: OnboardingAccess): void {+ attempts.get(providerID)?.controller.abort()+ attempts.delete(providerID)+ statuses[providerID] = 'idle'+ }++ return { signInStatus, signIn, reopenSignIn, cancelSignIn, signOut }+}diff --git a/src/app/ai/models/settings/onboarding/use.ts b/src/app/ai/models/settings/onboarding/use.tsnew file mode 100644index 000000000..0c2f6ce90--- /dev/null+++ b/src/app/ai/models/settings/onboarding/use.ts@@ -0,0 +1,172 @@+import { computed, reactive, ref, watch } from 'vue'++import { IS_TAURI } from '@open-pencil/core/constants'++import { refreshAIProviderStatus } from '@/app/ai/chat/storage'+import {+ aiModelSettings,+ modelSettingsSnapshot,+ replaceAIModelSettings,+ setModelConnectionAPIKey+} from '@/app/ai/models'+import type { SettingsSaveResult } from '@/app/settings/save-result'++import { useOnboardingAgents } from './agents'+import { applyOnboardingPlan } from './apply'+import { existingOnboardingConnection, useOnboardingConnections } from './connections'+import { currentOnboardingModels } from './current'+import {+ isOnboardingAccess,+ planOnboarding,+ type OnboardingAccess,+ type OnboardingAnswers,+ type PlannedModel,+ uncoveredGoals+} from './plan'+import { useOnboardingRoles } from './roles'+import { useOnboardingSignIn } from './sign-in'++export const AI_SETUP_STEPS = ['goals', 'access', 'connect', 'review'] as const+export type AISetupStep = (typeof AI_SETUP_STEPS)[number]++/** Starts from what is already configured, so running setup again adjusts instead of resets. */+function initialAnswers(): OnboardingAnswers {+ const access = aiModelSettings.value.connections+ .map((connection) => connection.providerID)+ .filter(isOnboardingAccess)+ .filter((providerID) => existingOnboardingConnection(providerID))+ return {+ goals: aiModelSettings.value.assignments.vision === null ? ['design'] : ['design', 'vision'],+ access: [...new Set(access)],+ spending: 'existing'+ }+}++interface AIOnboardingOptions {+ /** Agents run as local processes, so only the desktop app offers them. */+ agentsAvailable?: boolean+}++export function useAIOnboarding({ agentsAvailable = IS_TAURI }: AIOnboardingOptions = {}) {+ const answers = reactive<OnboardingAnswers>(initialAnswers())+ const current = currentOnboardingModels(aiModelSettings.value)+ const configured = [current.design, current.vision, current.review, current.fast].filter(+ (model): model is PlannedModel => model !== null && model !== 'design'+ )+ const step = ref<AISetupStep>('goals')+ const busy = ref(false)+ const saveResult = ref<SettingsSaveResult | null>(null)++ const recommended = computed(() => planOnboarding(answers, { agentsAvailable, current }))+ const roles = useOnboardingRoles(recommended, configured)+ const { plan } = roles+ /** Requested goals nothing selected covers; setup offers OpenRouter for them. */+ const gaps = computed(() => uncoveredGoals(answers, { agentsAvailable, current }))+ /** Setup can finish once there is a design model, planned or already configured. */+ const hasDesign = computed(() => recommended.value.design !== null || current.design !== null)++ function plannedModel(providerID: OnboardingAccess): PlannedModel | null {+ const { design, vision, review, fast } = recommended.value+ return (+ [design, vision, review, fast].find(+ (model): model is PlannedModel =>+ model !== null && model !== 'design' && model.providerID === providerID+ ) ?? null+ )+ }++ const connections = useOnboardingConnections({ plannedModel })+ const { connection, ready, markKeySaved } = connections+ const signIn = useOnboardingSignIn(connections)+ const agents = useOnboardingAgents()+ // Look for installed agents when they are about to be connected, and again on return.+ watch(step, (current) => {+ if (current === 'connect') void agents.refreshAgents()+ })++ const canContinue = computed(() => {+ if (step.value === 'goals') return answers.goals.length > 0+ if (step.value === 'connect') {+ return hasDesign.value && recommended.value.connections.every(ready)+ }+ return true+ })++ function next(): void {+ const index = AI_SETUP_STEPS.indexOf(step.value)+ if (canContinue.value && index < AI_SETUP_STEPS.length - 1) {+ step.value = AI_SETUP_STEPS[index + 1]+ }+ }++ /** Returns false on the first step, where going back leaves setup. */+ function back(): boolean {+ const index = AI_SETUP_STEPS.indexOf(step.value)+ if (index <= 0) return false+ step.value = AI_SETUP_STEPS[index - 1]+ return true+ }++ async function apply(): Promise<SettingsSaveResult> {+ if (busy.value) return 'failed'+ busy.value = true+ saveResult.value = null+ let persisted = false+ try {+ // Copied first: closing setup clears entered keys while the saves below are pending.+ const keys = plan.value.connections.map(+ (providerID) => [providerID, connection(providerID).apiKey.trim()] as const+ )+ const details = Object.fromEntries(+ plan.value.connections.map((providerID) => {+ const { customBaseURL, customModelID } = connection(providerID)+ return [providerID, { customBaseURL, customModelID }]+ })+ )+ const { settings, connectionIds } = applyOnboardingPlan({+ settings: modelSettingsSnapshot(),+ plan: plan.value,+ details,+ createId: () => crypto.randomUUID()+ })+ replaceAIModelSettings(settings)+ // Applying again is idempotent, so a retry after a credential failure adds nothing.+ persisted = true+ for (const [providerID, key] of keys) {+ const connectionId = connectionIds[providerID]+ if (!key || !connectionId) continue+ await setModelConnectionAPIKey(connectionId, key)+ connection(providerID).apiKey = ''+ markKeySaved(connectionId)+ }+ await refreshAIProviderStatus()+ saveResult.value = 'saved'+ } catch {+ saveResult.value = persisted ? 'partial' : 'failed'+ } finally {+ busy.value = false+ }+ return saveResult.value+ }++ return {+ agentsAvailable,+ answers,+ step,+ recommended,+ plan,+ roles,+ gaps,+ hasDesign,+ busy,+ saveResult,+ canContinue,+ plannedModel,+ ...connections,+ ...signIn,+ ...agents,+ next,+ back,+ apply+ }+}diff --git a/src/app/ai/models/settings/profile-editor/schema.ts b/src/app/ai/models/settings/profile-editor/schema.tsindex 2a0257a5e..d3e6e6dfd 100644--- a/src/app/ai/models/settings/profile-editor/schema.ts+++ b/src/app/ai/models/settings/profile-editor/schema.ts@@ -23,8 +23,9 @@ export function modelProfileSchema(messages: ModelProfileValidationMessages) {const modelField = context.customModel ? 'customModelID' : 'modelID'- const requiresModel = context.providerKind !== 'acp'+ // Agents choose their own model, and Pi falls back to the default model set in Pi.const requiresAPI = context.providerKind === 'api'+ const requiresModel = requiresAPIreturn v.pipe(v.object({name: context.intent === 'save' ? requiredSetting(messages.requiredField) : v.string(),diff --git a/src/app/ai/models/settings/use.ts b/src/app/ai/models/settings/use.tsindex 97f009a5d..98d61ae9b 100644--- a/src/app/ai/models/settings/use.ts+++ b/src/app/ai/models/settings/use.ts@@ -1,9 +1,15 @@import { tryOnScopeDispose } from '@vueuse/core'import { computed, ref, watch } from 'vue'-import { ACP_AGENTS, AI_PROVIDERS } from '@open-pencil/core/constants'+import { AI_PROVIDERS } from '@open-pencil/core/constants'-import { aiModelSettings, modelConnection, modelConnectionCredentialStatus } from '@/app/ai/models'+import {+ aiModelSettings,+ modelConnection,+ modelConnectionCredentialStatus,+ modelCredentialRevision+} from '@/app/ai/models'+import { modelProviderName } from '@/app/ai/models/provider-name'import type { CredentialStatus } from '@/app/settings/credentials/types'export function useModelSettings() {@@ -16,15 +22,6 @@ export function useModelSettings() {const statusByConnection = ref<Record<string, CredentialStatus>>({})- function providerName(providerID: string): string {- if (providerID === 'harness:pi') return 'Pi'- if (providerID.startsWith('acp:')) {- const agentID = providerID.slice('acp:'.length)- return ACP_AGENTS.find((agent) => agent.id === agentID)?.name ?? providerID- }- return AI_PROVIDERS.find((provider) => provider.id === providerID)?.name ?? providerID- }-const profiles = computed(() =>aiModelSettings.value.models.map((profile) => {const connection = modelConnection(profile.connectionId)@@ -35,7 +32,7 @@ export function useModelSettings() {return {...profile,providerID: connection?.providerID ?? '',- providerName: providerName(connection?.providerID ?? ''),+ providerName: modelProviderName(connection?.providerID ?? ''),modelName}})@@ -44,16 +41,22 @@ export function useModelSettings() {async function refreshStatuses(): Promise<void> {const request = ++versionconst entries = await Promise.all(- aiModelSettings.value.connections.map(- async (connection) =>- [connection.id, await modelConnectionCredentialStatus(connection.id)] as const- )+ aiModelSettings.value.connections.map(async (connection) => {+ // One unreadable credential marks its own row instead of failing the whole list.+ const status: CredentialStatus = await modelConnectionCredentialStatus(connection.id).catch(+ () => 'unavailable'+ )+ return [connection.id, status] as const+ }))if (!disposed && request === version) statusByConnection.value = Object.fromEntries(entries)}watch(- () => aiModelSettings.value.connections.map((connection) => connection.id),+ () => [+ aiModelSettings.value.connections.map((connection) => connection.id),+ modelCredentialRevision.value+ ],() => void refreshStatuses(),{ immediate: true })diff --git a/src/app/ai/models/store.ts b/src/app/ai/models/store.tsindex 544e713c7..ea115f976 100644--- a/src/app/ai/models/store.ts+++ b/src/app/ai/models/store.ts@@ -375,7 +375,12 @@ export function saveModelProfileDraft(draft: AIModelProfileDraft): AIModelProfilconst provider = AI_PROVIDERS.find((definition) => definition.id === draft.providerID)const effectiveModel = draft.customModelID.trim() || draft.modelID.trim()if (!draft.name.trim()) throw new Error('Model name is required')- if (!draft.providerID.startsWith('acp:') && !effectiveModel) {+ // Agents choose their own model, and Pi falls back to its own default model.+ if (+ !draft.providerID.startsWith('acp:') &&+ draft.providerID !== 'harness:pi' &&+ !effectiveModel+ ) {throw new Error('Model ID is required')}if (diff --git a/src/app/ai/providers/openrouter/key.ts b/src/app/ai/providers/openrouter/key.tsnew file mode 100644index 000000000..8bf8cb990--- /dev/null+++ b/src/app/ai/providers/openrouter/key.ts@@ -0,0 +1,39 @@+import * as v from 'valibot'++/** Describes the key it is called with, without using credits. */+export const OPENROUTER_KEY_INFO_URL = 'https://openrouter.ai/api/v1/key'++export interface OpenRouterKeyInfo {+ label: string+ /** The account has never bought credits, so only free models will answer. */+ freeTier: boolean+}++export class OpenRouterKeyError extends Error {+ constructor(readonly status: number) {+ super(`OpenRouter rejected the key with status ${status}`)+ this.name = 'OpenRouterKeyError'+ }+}++/** Only the fields setup shows; anything missing reads as an unnamed key on the free tier. */+const keyInfoSchema = v.object({+ data: v.object({+ label: v.fallback(v.string(), ''),+ is_free_tier: v.fallback(v.boolean(), false)+ })+})++/** Checks that OpenRouter accepts a key and reports what it belongs to. */+export async function fetchOpenRouterKeyInfo(+ key: string,+ fetchImpl: typeof fetch = fetch+): Promise<OpenRouterKeyInfo> {+ const response = await fetchImpl(OPENROUTER_KEY_INFO_URL, {+ headers: { authorization: `Bearer ${key}` }+ })+ if (!response.ok) throw new OpenRouterKeyError(response.status)+ const parsed = v.safeParse(keyInfoSchema, await response.json())+ const data = parsed.success ? parsed.output.data : { label: '', is_free_tier: false }+ return { label: data.label, freeTier: data.is_free_tier }+}diff --git a/src/app/ai/providers/openrouter/oauth.ts b/src/app/ai/providers/openrouter/oauth.tsnew file mode 100644index 000000000..0a78c9e84--- /dev/null+++ b/src/app/ai/providers/openrouter/oauth.ts@@ -0,0 +1,81 @@+import { fromUint8Array } from 'js-base64'+import * as v from 'valibot'++/** OpenRouter's OAuth PKCE flow: https://openrouter.ai/docs/guides/overview/auth/oauth */+export const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth'+export const OPENROUTER_KEYS_URL = 'https://openrouter.ai/api/v1/auth/keys'+/** Authorization codes expire after ten minutes. */+export const OPENROUTER_CODE_LIFETIME_MS = 10 * 60 * 1000++export interface OpenRouterPKCE {+ verifier: string+ challenge: string+ state: string+}++export type OpenRouterCallback =+ | { ok: true; code: string }+ | { ok: false; reason: 'cancelled' | 'mismatch' }++export class OpenRouterKeyExchangeError extends Error {+ constructor(readonly status: number) {+ super(`OpenRouter key exchange failed with status ${status}`)+ this.name = 'OpenRouterKeyExchangeError'+ }+}++function randomToken(bytes: number): string {+ return fromUint8Array(crypto.getRandomValues(new Uint8Array(bytes)), true)+}++/** The S256 challenge for a verifier: the base64url SHA-256 digest, without padding. */+export async function pkceChallenge(verifier: string): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))+ return fromUint8Array(new Uint8Array(digest), true)+}++export async function createOpenRouterPKCE(): Promise<OpenRouterPKCE> {+ const verifier = randomToken(48)+ return { verifier, challenge: await pkceChallenge(verifier), state: randomToken(16) }+}++export function openRouterAuthorizationURL(+ callbackURL: string,+ pkce: OpenRouterPKCE,+ keyLabel: string+): string {+ const url = new URL(OPENROUTER_AUTH_URL)+ url.searchParams.set('callback_url', callbackURL)+ url.searchParams.set('code_challenge', pkce.challenge)+ url.searchParams.set('code_challenge_method', 'S256')+ url.searchParams.set('state', pkce.state)+ url.searchParams.set('key_label', keyLabel)+ return url.toString()+}++/** Reads the redirect OpenRouter sends back, rejecting one that belongs to another attempt. */+export function parseOpenRouterCallback(query: string, expectedState: string): OpenRouterCallback {+ const params = new URLSearchParams(query)+ if (params.get('state') !== expectedState) return { ok: false, reason: 'mismatch' }+ const code = params.get('code')+ return code ? { ok: true, code } : { ok: false, reason: 'cancelled' }+}++const keyExchangeSchema = v.object({ key: v.pipe(v.string(), v.minLength(1)) })++/** Trades an authorization code for an API key; OpenRouter allows this from a browser. */+export async function exchangeOpenRouterCode(+ code: string,+ verifier: string,+ fetchImpl: typeof fetch = fetch+): Promise<string> {+ const response = await fetchImpl(OPENROUTER_KEYS_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: 'S256' })+ })+ if (!response.ok) throw new OpenRouterKeyExchangeError(response.status)+ const parsed = v.safeParse(keyExchangeSchema, await response.json())+ if (!parsed.success) throw new OpenRouterKeyExchangeError(response.status)+ return parsed.output.key+}diff --git a/src/app/ai/providers/openrouter/sign-in.ts b/src/app/ai/providers/openrouter/sign-in.tsnew file mode 100644index 000000000..3fddda5d3--- /dev/null+++ b/src/app/ai/providers/openrouter/sign-in.ts@@ -0,0 +1,176 @@+import * as v from 'valibot'++import { IS_TAURI } from '@open-pencil/core/constants'++import { createDeferred } from '@/app/runtime/deferred'+import { openExternalLink } from '@/app/shell/ui'+import { WEB_APP_ORIGIN } from '@/constants'++import {+ createOpenRouterPKCE,+ exchangeOpenRouterCode,+ openRouterAuthorizationURL,+ OPENROUTER_CODE_LIFETIME_MS,+ parseOpenRouterCallback,+ type OpenRouterPKCE+} from './oauth'++/** Served from `public/`; it relays the redirect to the editor over this channel. */+export const OPENROUTER_CALLBACK_PATH = '/oauth/openrouter.html'+export const OPENROUTER_CALLBACK_CHANNEL = 'open-pencil:openrouter-oauth'+/** Served from `public/` on the web app; it hands the redirect to the desktop app's deep link. */+export const OPENROUTER_DESKTOP_CALLBACK_PATH = '/oauth/openrouter-desktop.html'+/** Emitted by the desktop shell for an `openpencil://oauth/<provider>?…` link. */+const OAUTH_CALLBACK_EVENT = 'oauth-callback'+const POPUP_NAME = 'open-pencil-openrouter'+const POPUP_FEATURES = 'popup,width=520,height=720'++export type OpenRouterSignInFailure = 'cancelled' | 'blocked' | 'expired' | 'failed'+export type OpenRouterSignInResult =+ | { ok: true; key: string }+ | { ok: false; reason: OpenRouterSignInFailure }++export interface OpenRouterSignInOptions {+ signal: AbortSignal+ /** Prefills the name of the key OpenRouter creates. */+ keyLabel: string+}++/** What the desktop shell forwards from an `openpencil://oauth/<provider>?…` link. */+const oauthCallbackSchema = v.object({ provider: v.string(), query: v.string() })++export interface OpenRouterSignIn {+ /** Opens the OpenRouter sign-in page again for the same attempt. */+ reopen: () => void+ result: Promise<OpenRouterSignInResult>+}++class SignInAbortedError extends Error {+ constructor() {+ super('OpenRouter sign-in was cancelled')+ this.name = 'SignInAbortedError'+ }+}++async function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {+ if (signal.aborted) throw new SignInAbortedError()+ const aborted = createDeferred<never>()+ const abort = () => aborted.reject(new SignInAbortedError())+ signal.addEventListener('abort', abort, { once: true })+ try {+ return await Promise.race([promise, aborted.promise])+ } finally {+ signal.removeEventListener('abort', abort)+ }+}++async function finish(+ query: string | null,+ pkce: OpenRouterPKCE,+ signal: AbortSignal+): Promise<OpenRouterSignInResult> {+ if (query === null) return { ok: false, reason: 'expired' }+ const callback = parseOpenRouterCallback(query, pkce.state)+ if (!callback.ok)+ return { ok: false, reason: callback.reason === 'cancelled' ? 'cancelled' : 'failed' }+ return {+ ok: true,+ key: await abortable(exchangeOpenRouterCode(callback.code, pkce.verifier), signal)+ }+}++function settle(run: () => Promise<OpenRouterSignInResult>): Promise<OpenRouterSignInResult> {+ return run().catch((error: unknown) => ({+ ok: false as const,+ reason: error instanceof SignInAbortedError ? ('cancelled' as const) : ('failed' as const)+ }))+}++/** Waits for the callback page in this origin to relay the redirect query. */+function browserCallback(signal: AbortSignal): Promise<string | null> {+ const channel = new BroadcastChannel(OPENROUTER_CALLBACK_CHANNEL)+ let timer: ReturnType<typeof setTimeout> | undefined+ const received = new Promise<string | null>((resolve) => {+ timer = setTimeout(() => resolve(null), OPENROUTER_CODE_LIFETIME_MS)+ channel.addEventListener('message', (event: MessageEvent<unknown>) => {+ if (typeof event.data === 'string') resolve(event.data)+ })+ })+ return abortable(received, signal).finally(() => {+ clearTimeout(timer)+ channel.close()+ })+}++/**+ * Opens OpenRouter in a popup that returns to this origin. Must be called from the click that+ * starts sign-in, before anything is awaited, or the browser blocks the popup.+ */+function browserSignIn({ signal, keyLabel }: OpenRouterSignInOptions): OpenRouterSignIn {+ let popup = window.open('', POPUP_NAME, POPUP_FEATURES)+ let authorizationURL = ''+ const reopen = () => {+ if (authorizationURL) popup = window.open(authorizationURL, POPUP_NAME, POPUP_FEATURES) ?? popup+ }+ const result = settle(async () => {+ if (!popup) return { ok: false, reason: 'blocked' }+ const pkce = await createOpenRouterPKCE()+ const callbackURL = new URL(OPENROUTER_CALLBACK_PATH, window.location.origin).href+ authorizationURL = openRouterAuthorizationURL(callbackURL, pkce, keyLabel)+ popup.location.href = authorizationURL+ try {+ return await finish(await browserCallback(signal), pkce, signal)+ } finally {+ popup.close()+ }+ })+ return { reopen, result }+}++/**+ * Listens for the `openpencil://oauth/openrouter` link the hosted callback page opens; the+ * desktop shell forwards its query as an `oauth-callback` event.+ */+async function listenForDesktopCallback() {+ const { listen } = await import('@tauri-apps/api/event')+ const received = createDeferred<string | null>()+ const timer = setTimeout(() => received.resolve(null), OPENROUTER_CODE_LIFETIME_MS)+ const unlisten = await listen<unknown>(OAUTH_CALLBACK_EVENT, (event) => {+ const callback = v.safeParse(oauthCallbackSchema, event.payload)+ if (callback.success && callback.output.provider === 'openrouter') {+ received.resolve(callback.output.query)+ }+ })+ return {+ query: (signal: AbortSignal) => abortable(received.promise, signal),+ stop: () => {+ clearTimeout(timer)+ unlisten()+ }+ }+}++/** Opens OpenRouter in the system browser, which returns to the app through a deep link. */+function desktopSignIn({ signal, keyLabel }: OpenRouterSignInOptions): OpenRouterSignIn {+ let authorizationURL = ''+ const reopen = () => {+ if (authorizationURL) void openExternalLink(authorizationURL)+ }+ const result = settle(async () => {+ const [pkce, callback] = await Promise.all([createOpenRouterPKCE(), listenForDesktopCallback()])+ try {+ const callbackURL = new URL(OPENROUTER_DESKTOP_CALLBACK_PATH, WEB_APP_ORIGIN).href+ authorizationURL = openRouterAuthorizationURL(callbackURL, pkce, keyLabel)+ await openExternalLink(authorizationURL)+ return await finish(await callback.query(signal), pkce, signal)+ } finally {+ callback.stop()+ }+ })+ return { reopen, result }+}++/** Signs in to OpenRouter with OAuth PKCE and returns a new API key for this app. */+export function signInWithOpenRouter(options: OpenRouterSignInOptions): OpenRouterSignIn {+ return IS_TAURI ? desktopSignIn(options) : browserSignIn(options)+}diff --git a/src/app/automation/mcp/failure.ts b/src/app/automation/mcp/failure.tsindex e0ca174b5..11c1442d3 100644--- a/src/app/automation/mcp/failure.ts+++ b/src/app/automation/mcp/failure.ts@@ -1,3 +1,5 @@+import { APP_VERSION } from '@/app/runtime/version'+/*** Name of the entry point installed by `@open-pencil/mcp`.*@@ -6,9 +8,6 @@*/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}`diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.tsindex f6708ca68..69398bb55 100644--- a/src/app/automation/mcp/spawn.ts+++ b/src/app/automation/mcp/spawn.ts@@ -11,6 +11,7 @@ import {} from '@open-pencil/mcp/tools'import { randomHex } from '@open-pencil/scene-graph/random'+import { APP_VERSION } from '@/app/runtime/version'import { decodeTauriStderr } from '@/app/shell/ui'import { resolvePlatformCommand } from '@/app/tauri/command'import { isTauri } from '@/app/tauri/env'@@ -51,8 +52,6 @@ const DEV_AUTOMATION_AUTH_TOKEN =import.meta.env.DEV && typeof __OPENPENCIL_LOCAL_AUTOMATION_TOKEN__ === 'string'? __OPENPENCIL_LOCAL_AUTOMATION_TOKEN__: null-const APP_VERSION =- typeof __OPENPENCIL_APP_VERSION__ === 'string' ? __OPENPENCIL_APP_VERSION__ : '0.0.0-test'const noop = () => undefinedconst MAX_STARTUP_STDERR_LENGTH = 8_192const MCP_EXECUTABLE = 'openpencil-mcp-http'diff --git a/src/app/runtime/version.ts b/src/app/runtime/version.tsnew file mode 100644index 000000000..fe3d9bcf5--- /dev/null+++ b/src/app/runtime/version.ts@@ -0,0 +1,3 @@+/** The app's release version; tests and tools that run app code without the Vite define get a placeholder. */+export const APP_VERSION =+ typeof __OPENPENCIL_APP_VERSION__ === 'string' ? __OPENPENCIL_APP_VERSION__ : '0.0.0-test'diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex 1d134171b..470e871cb 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -28,6 +28,9 @@ export interface DesignCheckPreferences {disabledRules: string[]}+/** Whether guided AI setup was offered and finished or skipped. */+export type AISetupState = 'pending' | 'done'+export interface AppPreferences {appearance: { animations: AnimationPreference }chat: {@@ -46,6 +49,9 @@ export interface AppPreferences {canvasMode: CanvasRenderingMode}designCheck: DesignCheckPreferences+ onboarding: {+ aiSetup: AISetupState+ }}export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {@@ -61,7 +67,8 @@ export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {snapping: { ...DEFAULT_SNAPPING_PREFERENCES }},rendering: { canvasMode: 'retained' },- designCheck: { showOnCanvas: true, preset: 'recommended', disabledRules: [] }+ designCheck: { showOnCanvas: true, preset: 'recommended', disabledRules: [] },+ onboarding: { aiSetup: 'pending' }}const STORAGE_KEY = 'open-pencil:preferences:v1'@@ -83,6 +90,7 @@ interface StoredAppPreferences {editing?: { snapping?: StoredSnappingPreferences }rendering?: { canvasMode?: unknown }designCheck?: { showOnCanvas?: unknown; preset?: unknown; disabledRules?: unknown }+ onboarding?: { aiSetup?: unknown }}function isStoredAppPreferences(value: unknown): value is StoredAppPreferences {@@ -153,7 +161,10 @@ function normalizePreferences(value: unknown): AppPreferences {rendering: {canvasMode: stored?.rendering?.canvasMode === 'tiled' ? 'tiled' : 'retained'},- designCheck: normalizeDesignCheckPreferences(stored?.designCheck)+ designCheck: normalizeDesignCheckPreferences(stored?.designCheck),+ onboarding: {+ aiSetup: stored?.onboarding?.aiSetup === 'done' ? 'done' : 'pending'+ }}}@@ -173,6 +184,10 @@ export function updateRecoveryEnabled(enabled: boolean): void {appPreferences.value = preferences}+export function updateAISetupState(aiSetup: AISetupState): void {+ appPreferences.value = { ...appPreferences.value, onboarding: { aiSetup } }+}+export function updateCanvasRenderingMode(canvasMode: CanvasRenderingMode): void {appPreferences.value = {...appPreferences.value,diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vueindex 3d6f12480..fe8525df5 100644--- a/src/components/ChatPanel.vue+++ b/src/components/ChatPanel.vue@@ -1,14 +1,17 @@<script setup lang="ts">import type { Chat } from '@ai-sdk/vue'import type { UIMessage } from 'ai'-import { computed, shallowRef, watch } from 'vue'+import { computed, shallowRef, useTemplateRef, watch } from 'vue'import { useI18n } from '@open-pencil/vue'+import { revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'import { chatDocumentId } from '@/app/ai/chat/history/document'import { useChatRunLocation } from '@/app/ai/chat/run-location'+import type { ChatSubmission } from '@/app/ai/chat/submission/types'import { useChatSubmission } from '@/app/ai/chat/submission/use'import { useAIChat } from '@/app/ai/chat/use'+import { openAISetup } from '@/app/ai/models/settings/onboarding/dialog'import { didHitStepLimit } from '@/app/ai/tools'import { getActiveEditorStore } from '@/app/editor/active-store'import { openSettingsDialog } from '@/app/settings/dialog'@@ -35,13 +38,33 @@ const submission = useChatSubmission({messages: computed(() => ({openSettings: ai.value.openProviderSettingsAction,requestFailed: ai.value.chatRequestFailed,- visionUnavailable: ai.value.visionModelUnavailable+ visionUnavailable: ai.value.visionModelUnavailable,+ runSetup: ai.value.aiSetupRun,+ agentSetup: {+ 'companion-missing': ai.value.chatPiCompanionMissing,+ 'companion-outdated': ai.value.chatPiCompanionOutdated,+ 'mcp-outdated': ai.value.chatMCPOutdated,+ 'pi-sign-in': ai.value.chatPiSignIn,+ 'pi-model': ai.value.chatPiModel+ }})),reportError: toast.error,- openModelSettings: () => openSettingsDialog('ai')+ openModelSettings: () => openSettingsDialog('ai'),+ openSetup: () => openAISetup()})+const chatInput = useTemplateRef<{ restoreDraft: (submission: ChatSubmission) => void }>(+ 'chatInput'+)let viewGeneration = 0++/** Puts an unsent message back only in the conversation it was written in. */+async function submitMessage(message: ChatSubmission) {+ const generation = viewGeneration+ if (await submission.submit(message)) return+ if (generation === viewGeneration) chatInput.value?.restoreDraft(message)+ else for (const image of message.images) revokeImagePreviewURL(image.previewURL)+}// Restoring local history must not open a provider connection or read credentials.void history.initialize().catch(() => {toast.error(ai.value.chatHistoryFailed)@@ -222,9 +245,10 @@ function handleStop() {/><ChatInputv-if="isConfigured && !agentHistoryReadOnly && !history.readOnly.value"+ ref="chatInput":status="status":disabled="submission.busy.value || history.busy.value"- @submit="submission.submit"+ @submit="submitMessage"@stop="handleStop"@error="toast.error"/>diff --git a/src/components/chat/ChatComposer.vue b/src/components/chat/ChatComposer.vueindex 2e054719f..b6df09331 100644--- a/src/components/chat/ChatComposer.vue+++ b/src/components/chat/ChatComposer.vue@@ -35,6 +35,17 @@ function handleSubmit(event: Event) {input.value = ''triggerResize()}+/**+ * Puts back a message that could not be sent, unless something new was typed meanwhile.+ * Returns whether it did.+ */+function restoreDraft(text: string): boolean {+ if (input.value.trim()) return false+ input.value = text+ triggerResize()+ return true+}+defineExpose({ restoreDraft })</script><template><TooltipProvider>diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vueindex 68789a6b8..98cd147db 100644--- a/src/components/chat/ChatInput.vue+++ b/src/components/chat/ChatInput.vue@@ -1,9 +1,10 @@<script setup lang="ts">-import { computed } from 'vue'+import { computed, useTemplateRef } from 'vue'import { ACP_AGENTS } from '@open-pencil/core/constants'import { useI18n, useSelectionState } from '@open-pencil/vue'+import { revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'import { MAX_IMAGE_ATTACHMENTS } from '@/app/ai/attachment/image/types'import type { ChatSubmission } from '@/app/ai/chat/submission/types'import { useAIChat } from '@/app/ai/chat/use'@@ -47,9 +48,19 @@ const {removeNode: removeReferencedNode,toggleSelection: toggleCurrentSelection,handlePaste,- takeSubmission+ takeSubmission,+ restoreSubmission} = attachments+const composer = useTemplateRef<{ restoreDraft: (text: string) => boolean }>('composer')++/** Puts back an unsent message with its attachments; releases them if newer text replaced it. */+function restoreDraft(submission: ChatSubmission): void {+ if (composer.value?.restoreDraft(submission.displayText)) restoreSubmission(submission)+ else for (const image of submission.images) revokeImagePreviewURL(image.previewURL)+}+defineExpose({ restoreDraft })+const isStreaming = computed(() => disabled || status === 'streaming' || status === 'submitted')const isAgentProvider = computed(() => providerID.value.startsWith('acp:') || providerID.value === 'harness:pi'@@ -81,6 +92,7 @@ const selectedProfileName = computed(<template><ChatComposer+ ref="composer":status="status":disabled="disabled"@submit="emit('submit', takeSubmission($event))"diff --git a/src/components/chat/input/useAttachments.ts b/src/components/chat/input/useAttachments.tsindex 3652e36bf..837c01063 100644--- a/src/components/chat/input/useAttachments.ts+++ b/src/components/chat/input/useAttachments.ts@@ -1,4 +1,5 @@import { useFileDialog } from '@vueuse/core'+import { uniq } from 'es-toolkit'import { computed, onBeforeUnmount, ref, type Ref } from 'vue'import type { Editor } from '@open-pencil/core/editor'@@ -114,6 +115,12 @@ export function useAttachmentDrafts(options: AttachmentDraftOptions) {}}+ /** Takes back a submission that was not sent, ahead of anything attached since. */+ function restoreSubmission(submission: ChatSubmission): void {+ images.value = [...submission.images, ...images.value]+ nodeIds.value = uniq([...submission.nodes.map((node) => node.id), ...nodeIds.value])+ }+function clear(): void {for (const image of images.value) revokeImagePreviewURL(image.previewURL)images.value = []@@ -137,6 +144,7 @@ export function useAttachmentDrafts(options: AttachmentDraftOptions) {removeNode,toggleSelection,handlePaste,- takeSubmission+ takeSubmission,+ restoreSubmission}}diff --git a/src/components/settings/ai-setup/AISetupAccess.vue b/src/components/settings/ai-setup/AISetupAccess.vuenew file mode 100644index 000000000..3b4f119f3--- /dev/null+++ b/src/components/settings/ai-setup/AISetupAccess.vue@@ -0,0 +1,109 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'+import { ref } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { modelProviderName } from '@/app/ai/models/provider-name'+import {+ ONBOARDING_AGENTS,+ ONBOARDING_API_PROVIDERS,+ ONBOARDING_MORE_API_PROVIDERS,+ ONBOARDING_SERVER_PROVIDER,+ type OnboardingAccess+} from '@/app/ai/models/settings/onboarding/plan'+import SettingsLink from '@/components/settings/layout/SettingsLink.vue'+import ProviderLogo from '@/components/settings/provider/ProviderLogo.vue'+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'+import { DESKTOP_DOWNLOAD_URL } from '@/constants'+import theme from '@/theme/settings/ai-setup/flow'++import SetupChoice from './SetupChoice.vue'++const { agentsAvailable } = defineProps<{ agentsAvailable: boolean }>()+const access = defineModel<OnboardingAccess[]>({ required: true })+const { ai } = useI18n()+const styles = tv(theme)()+const moreOpen = ref(+ ONBOARDING_MORE_API_PROVIDERS.some((provider) => access.value.includes(provider))+)++function toggle(providerID: OnboardingAccess, checked: boolean): void {+ access.value = checked+ ? [...access.value, providerID]+ : access.value.filter((candidate) => candidate !== providerID)+}+</script>++<template>+ <section :class="styles.group()">+ <h3 :class="styles.groupHeading()">{{ ai.aiSetupAccessAgents }}</h3>+ <template v-if="agentsAvailable">+ <p :class="styles.help()">{{ ai.aiSetupAccessAgentsDescription }}</p>+ <SetupChoice+ v-for="agent in ONBOARDING_AGENTS"+ :key="agent"+ :label="modelProviderName(agent)"+ >+ <AppCheckbox+ :model-value="access.includes(agent)"+ :ariaLabel="modelProviderName(agent)"+ @update:model-value="toggle(agent, $event)"+ />+ <template #icon><ProviderLogo :provider="agent" /></template>+ </SetupChoice>+ </template>+ <AppAlert v-else :heading="ai.aiSetupAccessAgentsDesktop">+ <template #actions>+ <SettingsLink :href="DESKTOP_DOWNLOAD_URL">{{ ai.aiSetupGetDesktop }}</SettingsLink>+ </template>+ </AppAlert>+ </section>+ <section :class="styles.group()">+ <h3 :class="styles.groupHeading()">{{ ai.aiSetupAccessAPI }}</h3>+ <SetupChoice+ v-for="provider in ONBOARDING_API_PROVIDERS"+ :key="provider"+ :label="modelProviderName(provider)"+ >+ <AppCheckbox+ :model-value="access.includes(provider)"+ :ariaLabel="modelProviderName(provider)"+ @update:model-value="toggle(provider, $event)"+ />+ <template #icon><ProviderLogo :provider="provider" /></template>+ </SetupChoice>+ <AppCollapsible+ v-model:open="moreOpen"+ :label="ai.aiSetupAccessMore"+ :ui="{ trigger: styles.moreTrigger() }"+ >+ <div :class="styles.moreGroup()">+ <SetupChoice+ v-for="provider in ONBOARDING_MORE_API_PROVIDERS"+ :key="provider"+ :label="modelProviderName(provider)"+ >+ <AppCheckbox+ :model-value="access.includes(provider)"+ :ariaLabel="modelProviderName(provider)"+ @update:model-value="toggle(provider, $event)"+ />+ <template #icon><ProviderLogo :provider="provider" /></template>+ </SetupChoice>+ </div>+ </AppCollapsible>+ </section>+ <section :class="styles.group()">+ <SetupChoice :label="ai.aiSetupAccessServer" :description="ai.aiSetupAccessServerDescription">+ <AppCheckbox+ :model-value="access.includes(ONBOARDING_SERVER_PROVIDER)"+ :ariaLabel="ai.aiSetupAccessServer"+ @update:model-value="toggle(ONBOARDING_SERVER_PROVIDER, $event)"+ />+ <template #icon><ProviderLogo :provider="ONBOARDING_SERVER_PROVIDER" /></template>+ </SetupChoice>+ </section>+</template>diff --git a/src/components/settings/ai-setup/AISetupAgent.vue b/src/components/settings/ai-setup/AISetupAgent.vuenew file mode 100644index 000000000..77707d369--- /dev/null+++ b/src/components/settings/ai-setup/AISetupAgent.vue@@ -0,0 +1,163 @@+<script setup lang="ts">+import { useClipboard } from '@vueuse/core'+import { tv } from 'tailwind-variants'+import { computed } from 'vue'++import type { ACPAgentDef } from '@open-pencil/core/constants'+import { useI18n } from '@open-pencil/vue'++import {+ codingAgentGuideURL,+ codingAgentSetupPrompt,+ MCP_INSTALL_COMMAND+} from '@/app/ai/acp/setup-prompt'+import type { AgentSetupState } from '@/app/ai/models/settings/onboarding/agents'+import SettingsLink from '@/components/settings/layout/SettingsLink.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import { NODE_DOWNLOAD_URL } from '@/constants'+import theme from '@/theme/settings/ai-setup/flow'++import SetupInstallItem from './SetupInstallItem.vue'++const { agent, setup } = defineProps<{ agent: ACPAgentDef; setup: AgentSetupState }>()+const emit = defineEmits<{ check: []; installAgent: []; installBridge: [] }>()+const { ai, common } = useI18n()+const styles = tv(theme)()+const { copy, copied, text } = useClipboard({ copiedDuring: 1500 })++const detected = computed(() => setup.detected)+const prompt = computed(() => codingAgentSetupPrompt(agent.id))+const busy = computed(() => setup.installingAgent || setup.installingBridge)+const bridgeReady = computed(() => setup.bridge && !setup.bridgeOutdated)+/** Manual commands are for where one-click installation cannot help. */+const manualAgentCommand = computed(() => {+ if (!agent.installCommand || detected.value?.status === 'available') return null+ if (!setup.supported || !setup.npm || setup.error === 'install') {+ return agent.installCommand+ }+ return agent.adapterPackage ? null : agent.installCommand+})+const manualBridgeCommand = computed(() => {+ if (!setup.supported) return MCP_INSTALL_COMMAND+ return !bridgeReady.value && (!setup.npm || setup.error === 'canvas-install')+ ? setup.bridgeCommand+ : null+})+const needsNpm = computed(+ () =>+ !setup.npm &&+ (detected.value?.status === 'needs-adapter' || (setup.detected !== null && !bridgeReady.value))+)+const agentAction = computed(() => {+ if (detected.value?.status !== 'needs-adapter' || !setup.npm) return undefined+ return setup.installingAgent+ ? ai.value.aiSetupAgentInstalling+ : ai.value.aiSetupAgentInstallAdapter+})+const bridgeState = computed(() => {+ if (setup.bridgeOutdated) return ai.value.aiSetupAgentOutdated+ return setup.bridge ? ai.value.aiSetupAgentInstalled : ai.value.aiSetupAgentNotFound+})+const bridgeAction = computed(() => {+ if (bridgeReady.value || !setup.npm) return undefined+ if (setup.installingBridge) return ai.value.aiSetupAgentInstalling+ return setup.bridgeOutdated ? ai.value.aiSetupAgentUpdateMCP : ai.value.aiSetupAgentInstallMCP+})+const errorMessage = computed(() => {+ if (setup.error === 'npm' || needsNpm.value) return ai.value.aiSetupAgentNeedsNpm+ if (setup.error === 'install' || setup.error === 'canvas-install') {+ return ai.value.aiSetupAgentInstallFailed+ }+ if (setup.error === 'canvas-start') return ai.value.aiSetupAgentMCPStartFailed+ if (setup.error === 'lookup') return ai.value.aiSetupAgentLookupFailed+ return null+})++function agentState(): string {+ if (detected.value?.status === 'available') return ai.value.aiSetupAgentInstalled+ if (detected.value?.status === 'needs-adapter') return ai.value.aiSetupAgentNeedsAdapter+ return ai.value.aiSetupAgentNotFound+}++function copiedLabel(value: string, label: string): string {+ return copied.value && text.value === value ? common.value.copied : label+}+</script>++<template>+ <p :class="styles.help()">{{ ai.aiSetupAgentDescription({ agent: agent.name }) }}</p>++ <template v-if="setup.supported">+ <p v-if="setup.scanning && !detected" role="status" :class="styles.signInStatus()">+ <icon-lucide-loader-2 :class="styles.spinner()" aria-hidden="true" />+ {{ ai.aiSetupAgentChecking }}+ </p>+ <ul v-else-if="detected" :class="styles.installList()">+ <SetupInstallItem+ :ready="detected.status === 'available'"+ :action="agentAction"+ :loading="setup.installingAgent"+ :disabled="busy"+ @action="emit('installAgent')"+ >+ {{ agent.name }} · {{ agentState() }}+ <template v-if="detected.status === 'not-installed' && agent.setupURL" #action>+ <SettingsLink :href="agent.setupURL">+ {{ ai.aiSetupAgentGetCLI({ agent: agent.name }) }}+ </SettingsLink>+ </template>+ </SetupInstallItem>+ <SetupInstallItem+ :ready="bridgeReady"+ :action="bridgeAction"+ :loading="setup.installingBridge"+ :disabled="busy"+ @action="emit('installBridge')"+ >+ {{ ai.aiSetupAgentMCP }} · {{ bridgeState }}+ </SetupInstallItem>+ </ul>+ <AppAlert v-if="errorMessage" tone="warning" :heading="errorMessage">+ <template v-if="setup.error === 'npm' || needsNpm" #actions>+ <SettingsLink :href="NODE_DOWNLOAD_URL">Node.js</SettingsLink>+ </template>+ </AppAlert>+ </template>++ <template v-if="manualAgentCommand">+ <p :class="styles.help()">{{ ai.aiSetupAgentInstall }}</p>+ <div :class="styles.command()">+ <code>{{ manualAgentCommand }}</code>+ <AppButton size="xs" @click="copy(manualAgentCommand)">+ {{ copiedLabel(manualAgentCommand, common.copy) }}+ </AppButton>+ </div>+ </template>+ <template v-if="manualBridgeCommand">+ <p :class="styles.help()">{{ ai.aiSetupAgentMCPInstall }}</p>+ <div :class="styles.command()">+ <code>{{ manualBridgeCommand }}</code>+ <AppButton size="xs" @click="copy(manualBridgeCommand)">+ {{ copiedLabel(manualBridgeCommand, common.copy) }}+ </AppButton>+ </div>+ </template>++ <p :class="styles.help()">{{ ai.aiSetupAgentPromptHint({ agent: agent.name }) }}</p>+ <div :class="styles.signInActions()">+ <AppButton size="xs" variant="outline" @click="copy(prompt)">+ <template #leading><icon-lucide-clipboard-copy class="size-3" /></template>+ {{ copiedLabel(prompt, ai.aiSetupAgentCopyPrompt) }}+ </AppButton>+ <AppButton+ v-if="setup.supported"+ size="xs"+ :disabled="busy || setup.scanning"+ @click="emit('check')"+ >+ {{ ai.aiSetupAgentCheckAgain }}+ </AppButton>+ <SettingsLink :href="codingAgentGuideURL(agent.id)">{{ ai.aiSetupAgentGuide }}</SettingsLink>+ </div>+</template>diff --git a/src/components/settings/ai-setup/AISetupConnection.stories.ts b/src/components/settings/ai-setup/AISetupConnection.stories.tsnew file mode 100644index 000000000..b9cf0aec2--- /dev/null+++ b/src/components/settings/ai-setup/AISetupConnection.stories.ts@@ -0,0 +1,235 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, within } from 'storybook/test'++import { ACP_AGENTS, type ACPAgentID } from '@open-pencil/core/constants'++import type { DetectedAgent } from '@/app/ai/agents/discovery'+import type { AgentSetupState, PiSetupState } from '@/app/ai/models/settings/onboarding/agents'++import AISetupConnection from './AISetupConnection.vue'++interface Args {+ providerID:+ | 'openrouter'+ | 'anthropic'+ | 'openai-compatible'+ | 'acp:claude-code'+ | 'acp:codex'+ | 'harness:pi'+ signInStatus: 'idle' | 'waiting' | 'verifying' | 'blocked' | 'cancelled' | 'expired' | 'failed'+ account: { label: string; freeTier: boolean } | null+ agentSetup?: AgentSetupState+ piSetup?: PiSetupState+ hasSavedKey: boolean+ recommended: boolean+}++function detected(id: ACPAgentID, status: DetectedAgent['status']): DetectedAgent {+ const definition = ACP_AGENTS.find((agent) => agent.id === id) ?? ACP_AGENTS[0]+ return { definition, cliPath: null, adapterPath: null, status }+}++function agentSetup(overrides: Partial<AgentSetupState>): AgentSetupState {+ return {+ supported: true,+ scanning: false,+ detected: null,+ bridge: false,+ bridgeOutdated: false,+ bridgeCommand: 'npm i -g @open-pencil/[email protected]',+ npm: true,+ installingAgent: false,+ installingBridge: false,+ error: null,+ ...overrides+ }+}++function piSetup(overrides: Partial<PiSetupState>): PiSetupState {+ return {+ supported: true,+ scanning: false,+ companion: false,+ companionOutdated: false,+ companionCommand: 'npm i -g @open-pencil/[email protected]',+ bridge: false,+ bridgeOutdated: false,+ bridgeCommand: 'npm i -g @open-pencil/[email protected]',+ npm: true,+ installingCompanion: false,+ installingBridge: false,+ defaultModel: null,+ error: null,+ ...overrides+ }+}++const meta = {+ title: 'Settings/AI Setup/Connection',+ args: {+ providerID: 'openrouter',+ signInStatus: 'idle',+ hasSavedKey: false,+ recommended: true,+ account: null+ },+ render: (args) => ({+ components: { AISetupConnection },+ setup: () => ({+ args,+ state: {+ apiKey: args.account ? 'sk-or-story' : '',+ customBaseURL: '',+ customModelID: '',+ test: 'idle',+ reason: null,+ account: args.account+ }+ }),+ template:+ '<div class="w-[30rem] max-w-full"><AISetupConnection v-bind="args" :state="state" /></div>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const OpenRouterSignIn: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('button', { name: 'Sign in with OpenRouter' })).toBeVisible()+ await expect(canvas.getByLabelText('API Key')).toBeVisible()+ }+}+export const OpenRouterWaiting: Story = {+ args: { signInStatus: 'waiting' },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('status')).toBeVisible()+ await expect(canvas.queryByRole('button', { name: 'Sign in with OpenRouter' })).toBeNull()+ }+}+export const OpenRouterVerifying: Story = { args: { signInStatus: 'verifying' } }+export const OpenRouterSignedIn: Story = {+ args: { account: { label: 'OpenPencil', freeTier: false } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('status')).toHaveTextContent('Signed in to OpenRouter')+ await expect(canvas.queryByLabelText('API Key')).toBeNull()+ await expect(canvas.queryByRole('button', { name: 'Test connection' })).toBeNull()+ }+}+export const OpenRouterSignedInWithoutCredits: Story = {+ args: { account: { label: 'OpenPencil', freeTier: true } }+}+export const OpenRouterPopupBlocked: Story = { args: { signInStatus: 'blocked' } }+export const OpenRouterFailed: Story = { args: { signInStatus: 'failed' } }+export const OpenRouterExpired: Story = { args: { signInStatus: 'expired' } }+export const SavedAPIKey: Story = {+ args: { providerID: 'anthropic', hasSavedKey: true, recommended: false }+}+export const LocalServer: Story = { args: { providerID: 'openai-compatible', recommended: false } }+export const CodingAgentInBrowser: Story = {+ args: {+ providerID: 'acp:claude-code',+ recommended: false,+ agentSetup: agentSetup({ supported: false })+ }+}+export const CodingAgentChecking: Story = {+ args: { providerID: 'acp:codex', recommended: false, agentSetup: agentSetup({ scanning: true }) }+}+export const CodingAgentInstalled: Story = {+ args: {+ providerID: 'acp:claude-code',+ recommended: false,+ agentSetup: agentSetup({ detected: detected('claude-code', 'available'), bridge: true })+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.queryByRole('button', { name: 'Install adapter' })).toBeNull()+ await expect(canvas.queryByText(/npm i -g/)).toBeNull()+ await expect(canvas.getByRole('button', { name: 'Check again' })).toBeVisible()+ }+}+export const CodingAgentNeedsAdapter: Story = {+ args: {+ providerID: 'acp:codex',+ recommended: false,+ agentSetup: agentSetup({ detected: detected('codex', 'needs-adapter') })+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('button', { name: 'Install adapter' })).toBeVisible()+ await expect(canvas.getByRole('button', { name: 'Install MCP server' })).toBeVisible()+ await expect(canvas.getByRole('link', { name: /Setup guide/ })).toHaveAttribute(+ 'href',+ 'https://openpencil.dev/programmable/coding-agents#codex'+ )+ }+}+export const CodingAgentNeedsNpm: Story = {+ args: {+ providerID: 'acp:claude-code',+ recommended: false,+ agentSetup: agentSetup({ detected: detected('claude-code', 'needs-adapter'), npm: false })+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByText('npm i -g @agentclientprotocol/claude-agent-acp')).toBeVisible()+ await expect(canvas.queryByRole('button', { name: 'Install adapter' })).toBeNull()+ await expect(canvas.getByText(/npm i -g @open-pencil\/mcp@/)).toBeVisible()+ }+}+export const PiNeedsCompanion: Story = {+ args: {+ providerID: 'harness:pi',+ recommended: false,+ piSetup: piSetup({ defaultModel: 'openai-codex/gpt-5.6' })+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('button', { name: 'Install companion' })).toBeVisible()+ await expect(canvas.getByText(/openai-codex\/gpt-5\.6/)).toBeVisible()+ await expect(canvas.queryByLabelText('API Key')).toBeNull()+ }+}+export const PiReady: Story = {+ args: {+ providerID: 'harness:pi',+ recommended: false,+ piSetup: piSetup({ companion: true, bridge: true, defaultModel: 'openai-codex/gpt-5.6' })+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.queryByRole('button', { name: 'Install companion' })).toBeNull()+ await expect(canvas.queryByText(/npm i -g/)).toBeNull()+ }+}+export const PiNeedsNpm: Story = {+ args: { providerID: 'harness:pi', recommended: false, piSetup: piSetup({ npm: false }) },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByText(/npm i -g @open-pencil\/harness@/)).toBeVisible()+ }+}+export const PiOutdatedMCPFromBun: Story = {+ args: {+ providerID: 'harness:pi',+ recommended: false,+ piSetup: piSetup({+ companion: true,+ bridge: true,+ bridgeOutdated: true,+ bridgeCommand: 'bun add -g @open-pencil/[email protected]',+ defaultModel: 'openai-codex/gpt-5.6',+ error: 'canvas-install'+ })+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByText(/OpenPencil MCP server · update needed/)).toBeVisible()+ await expect(canvas.getByRole('button', { name: 'Update MCP server' })).toBeVisible()+ await expect(canvas.getByText('bun add -g @open-pencil/[email protected]')).toBeVisible()+ }+}diff --git a/src/components/settings/ai-setup/AISetupConnection.vue b/src/components/settings/ai-setup/AISetupConnection.vuenew file mode 100644index 000000000..d8dec4711--- /dev/null+++ b/src/components/settings/ai-setup/AISetupConnection.vue@@ -0,0 +1,259 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'+import { computed } from 'vue'++import { ACP_AGENTS, AI_PROVIDERS } from '@open-pencil/core/constants'+import { useI18n } from '@open-pencil/vue'++import { modelProviderName } from '@/app/ai/models/provider-name'+import type { AgentSetupState, PiSetupState } from '@/app/ai/models/settings/onboarding/agents'+import {+ ONBOARDING_SERVER_PRESETS,+ type OnboardingConnectionPatch,+ type OnboardingConnectionState+} from '@/app/ai/models/settings/onboarding/connections'+import {+ isOnboardingAgent,+ ONBOARDING_SERVER_PROVIDER,+ type OnboardingAccess+} from '@/app/ai/models/settings/onboarding/plan'+import type { OnboardingSignInStatus } from '@/app/ai/models/settings/onboarding/sign-in'+import ProviderConnectionTestButton from '@/components/chat/ProviderConnectionTestButton.vue'+import ProviderLogo from '@/components/settings/provider/ProviderLogo.vue'+import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'+import ProviderSettingsInput from '@/components/settings/provider/ProviderSettingsInput.vue'+import ProviderSettingsKeyField from '@/components/settings/provider/ProviderSettingsKeyField.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'+import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'+import theme from '@/theme/settings/ai-setup/flow'++import AISetupAgent from './AISetupAgent.vue'+import AISetupPi from './AISetupPi.vue'+import SetupChoice from './SetupChoice.vue'++const {+ providerID,+ state,+ hasSavedKey = false,+ agentSetup,+ piSetup,+ serverVision = false,+ signInStatus = 'idle',+ recommended = false,+ disabled = false+} = defineProps<{+ providerID: OnboardingAccess+ state: OnboardingConnectionState+ /** A key saved for the connection that matches what is entered now. */+ hasSavedKey?: boolean+ /** Whether a coding agent and the MCP server it needs are installed. */+ agentSetup?: AgentSetupState+ /** Whether Pi's companion and the MCP server are installed, and Pi's default model. */+ piSetup?: PiSetupState+ /** The person says the server's model can read images. */+ serverVision?: boolean+ /** Progress of signing in with the provider, for providers that support it. */+ signInStatus?: OnboardingSignInStatus+ /** Suggested for pay-as-you-go rather than chosen by the person. */+ recommended?: boolean+ disabled?: boolean+}>()+const emit = defineEmits<{+ update: [patch: OnboardingConnectionPatch]+ test: []+ signIn: []+ reopenSignIn: []+ cancelSignIn: []+ signOut: []+ serverVision: [value: boolean]+ checkAgent: []+ installAgent: []+ installBridge: []+}>()+const { ai, common, credentials } = useI18n()+const styles = tv(theme)()++const name = computed(() =>+ providerID === ONBOARDING_SERVER_PROVIDER+ ? ai.value.aiSetupAccessServer+ : modelProviderName(providerID)+)+const agent = computed(() =>+ isOnboardingAgent(providerID)+ ? ACP_AGENTS.find((candidate) => `acp:${candidate.id}` === providerID)+ : undefined+)+const provider = computed(() => AI_PROVIDERS.find((candidate) => candidate.id === providerID))+const server = computed(() => providerID === ONBOARDING_SERVER_PROVIDER)+const supportsSignIn = computed(() => providerID === 'openrouter')+const signInFailure = computed(() => {+ if (signInStatus === 'blocked') return ai.value.aiSetupOpenRouterBlocked+ if (signInStatus === 'cancelled') return ai.value.aiSetupOpenRouterCancelled+ if (signInStatus === 'expired') return ai.value.aiSetupOpenRouterExpired+ if (signInStatus === 'failed') return ai.value.aiSetupOpenRouterFailed+ return null+})+const serverPreset = computed(+ () =>+ ONBOARDING_SERVER_PRESETS.find((preset) => preset.baseURL === state.customBaseURL.trim())?.id ??+ 'custom'+)+const serverPresetOptions = computed(() => [+ ...ONBOARDING_SERVER_PRESETS.map((preset) => ({ value: preset.id, label: preset.name })),+ { value: 'custom', label: ai.value.aiSetupServerOther }+])++function choosePreset(id: string): void {+ const preset = ONBOARDING_SERVER_PRESETS.find((candidate) => candidate.id === id)+ emit('update', { customBaseURL: preset?.baseURL ?? '' })+}++const keyHint = computed(() => {+ if (hasSavedKey) return ai.value.aiSetupSavedKeyHint+ return server.value ? ai.value.aiSetupServerKeyHint : undefined+})+</script>++<template>+ <section :class="styles.connection()" :data-provider="providerID">+ <h3 :class="styles.connectionHeading()">+ <ProviderLogo :provider="serverPreset === 'custom' ? providerID : serverPreset" />+ {{ name }}+ </h3>++ <AISetupAgent+ v-if="agent && agentSetup"+ :agent="agent"+ :setup="agentSetup"+ @check="emit('checkAgent')"+ @install-agent="emit('installAgent')"+ @install-bridge="emit('installBridge')"+ />+ <AISetupPi+ v-else-if="piSetup"+ :setup="piSetup"+ @check="emit('checkAgent')"+ @install-companion="emit('installAgent')"+ @install-bridge="emit('installBridge')"+ />++ <template v-else>+ <p v-if="recommended" :class="styles.help()">{{ ai.aiSetupMeteredNote }}</p>+ <div v-if="state.account" :class="styles.signIn()" data-slot="signed-in">+ <p role="status" :class="styles.signInStatus()">+ <icon-lucide-circle-check :class="styles.signedInIcon()" aria-hidden="true" />+ <span>+ {{ ai.aiSetupOpenRouterSignedInTitle }}+ <span v-if="state.account.label" :class="styles.signInDetail()">+ {{ ai.aiSetupOpenRouterKeyLabel({ label: state.account.label }) }}+ </span>+ </span>+ </p>+ <AppButton size="xs" @click="emit('signOut')">{{ ai.aiSetupOpenRouterChange }}</AppButton>+ </div>+ <AppAlert+ v-if="state.account?.freeTier"+ tone="warning"+ :heading="ai.aiSetupOpenRouterNoCredits"+ />+ <template v-if="supportsSignIn && !state.account">+ <div+ v-if="signInStatus === 'waiting' || signInStatus === 'verifying'"+ :class="styles.signIn()"+ >+ <p role="status" :class="styles.signInStatus()">+ <icon-lucide-loader-2 :class="styles.spinner()" aria-hidden="true" />+ {{+ signInStatus === 'waiting'+ ? ai.aiSetupOpenRouterWaiting+ : ai.aiSetupOpenRouterVerifying+ }}+ </p>+ <div :class="styles.signInActions()">+ <AppButton+ v-if="signInStatus === 'waiting'"+ size="xs"+ variant="outline"+ @click="emit('reopenSignIn')"+ >+ {{ ai.aiSetupOpenRouterReopen }}+ </AppButton>+ <AppButton size="xs" @click="emit('cancelSignIn')">{{ common.cancel }}</AppButton>+ </div>+ </div>+ <AppButton+ v-else+ class="self-start"+ color="primary"+ variant="solid"+ :disabled="disabled"+ @click="emit('signIn')"+ >+ {{ ai.aiSetupOpenRouterSignIn }}+ </AppButton>+ <AppAlert v-if="signInFailure" tone="warning" :heading="signInFailure" />+ <p :class="styles.groupHeading()">{{ ai.aiSetupOpenRouterOrKey }}</p>+ </template>+ <template v-if="server">+ <SegmentedControl+ :model-value="serverPreset"+ :options="serverPresetOptions"+ :label="ai.aiSetupAccessServer"+ @update:model-value="choosePreset"+ >+ <template #option="{ option }">+ <span class="flex items-center gap-1.5">+ <ProviderLogo :provider="option.value === 'custom' ? providerID : option.value" />+ {{ option.label }}+ </span>+ </template>+ </SegmentedControl>+ <ProviderSettingsField v-slot="{ control }" :label="ai.baseURL">+ <ProviderSettingsInput+ v-bind="control"+ :model-value="state.customBaseURL"+ :aria-label="ai.baseURL"+ :placeholder="ai.baseURLPlaceholder"+ @update:model-value="emit('update', { customBaseURL: String($event) })"+ />+ </ProviderSettingsField>+ <ProviderSettingsField v-slot="{ control }" :label="ai.modelID">+ <ProviderSettingsInput+ v-bind="control"+ :model-value="state.customModelID"+ :aria-label="ai.modelID"+ @update:model-value="emit('update', { customModelID: String($event) })"+ />+ </ProviderSettingsField>+ <SetupChoice :label="ai.aiSetupServerVision">+ <AppCheckbox+ :model-value="serverVision"+ :ariaLabel="ai.aiSetupServerVision"+ @update:model-value="emit('serverVision', $event)"+ />+ </SetupChoice>+ </template>+ <ProviderSettingsKeyField+ v-if="!state.account"+ :model-value="state.apiKey"+ :label="ai.apiKey"+ :saved="false"+ :hint="keyHint"+ kind="api"+ :placeholder="hasSavedKey ? credentials.savedReplace : (provider?.keyPlaceholder ?? '')"+ :key-u-r-l="provider?.keyURL"+ :key-u-r-l-label="credentials.getAPIKey"+ @update:model-value="emit('update', { apiKey: $event })"+ />+ <ProviderConnectionTestButton+ v-if="!state.account"+ :status="state.test"+ :reason="state.reason"+ :disabled="disabled"+ @test="emit('test')"+ />+ </template>+ </section>+</template>diff --git a/src/components/settings/ai-setup/AISetupDialog.vue b/src/components/settings/ai-setup/AISetupDialog.vuenew file mode 100644index 000000000..361a0799a--- /dev/null+++ b/src/components/settings/ai-setup/AISetupDialog.vue@@ -0,0 +1,31 @@+<script setup lang="ts">+import {+ aiSetupDialogOpen,+ aiSetupEntry,+ closeAISetup+} from '@/app/ai/models/settings/onboarding/dialog'+import { openSettingsDialog } from '@/app/settings/dialog'+import { AppDialogRoot } from '@/components/ui/dialog'++import AISetupFlow from './AISetupFlow.vue'++function onOpenChange(open: boolean): void {+ if (!open) closeAISetup()+}++function openAdvancedSettings(): void {+ closeAISetup()+ openSettingsDialog('ai')+}+</script>++<template>+ <AppDialogRoot+ :open="aiSetupDialogOpen"+ size="md"+ data-test-id="ai-setup-dialog"+ @update:open="onOpenChange"+ >+ <AISetupFlow :entry="aiSetupEntry" @close="closeAISetup" @advanced="openAdvancedSettings" />+ </AppDialogRoot>+</template>diff --git a/src/components/settings/ai-setup/AISetupFlow.stories.ts b/src/components/settings/ai-setup/AISetupFlow.stories.tsnew file mode 100644index 000000000..f09cd00b4--- /dev/null+++ b/src/components/settings/ai-setup/AISetupFlow.stories.ts@@ -0,0 +1,149 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'++import {+ aiModelSettings,+ modelSettingsSnapshot,+ replaceAIModelSettings,+ type AIModelSettings+} from '@/app/ai/models'+import { AppDialogRoot } from '@/components/ui/dialog'++import AISetupFlow from './AISetupFlow.vue'++interface Args {+ entry: 'welcome' | 'guided'+ agentsAvailable: boolean+}++const freshInstall: AIModelSettings = {+ version: 1,+ connections: [+ {+ id: 'connection-default',+ providerID: 'openai-compatible',+ customBaseURL: '',+ customAPIType: 'completions',+ credentialProfileId: 'default'+ }+ ],+ models: [+ {+ id: 'model-default',+ name: 'Design model',+ connectionId: 'connection-default',+ modelID: '',+ customModelID: '',+ maxOutputTokens: 16_384,+ thinkingLevel: 'default',+ capabilities: ['tools']+ }+ ],+ assignments: { design: 'model-default', review: 'design', fast: 'design', vision: null }+}++const meta = {+ title: 'Settings/AI Setup/Guided setup',+ args: { entry: 'guided', agentsAvailable: false },+ parameters: {+ docs: {+ description: {+ component:+ 'Skippable guided setup over the same model settings that Settings → AI edits directly. Each story starts from fresh-install settings and restores the previous ones afterwards.'+ }+ }+ },+ beforeEach: () => {+ const previous = modelSettingsSnapshot()+ replaceAIModelSettings(freshInstall)+ return () => replaceAIModelSettings(previous)+ },+ render: (args) => ({+ components: { AppDialogRoot, AISetupFlow },+ setup: () => ({ args }),+ template: '<AppDialogRoot :open="true" size="md"><AISetupFlow v-bind="args" /></AppDialogRoot>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++const page = () => within(document.body)++async function choose(name: string | RegExp) {+ await userEvent.click(page().getByRole('checkbox', { name }))+}++async function next() {+ await userEvent.click(page().getByRole('button', { name: 'Continue' }))+}++export const Welcome: Story = { args: { entry: 'welcome' } }+export const Goals: Story = {}+export const AccessInBrowser: Story = {+ play: async () => {+ await next()+ await expect(page().getByRole('checkbox', { name: 'OpenRouter' })).toBeVisible()+ await expect(page().queryByRole('checkbox', { name: 'Claude Code' })).toBeNull()+ }+}+export const AccessOnDesktop: Story = {+ args: { agentsAvailable: true },+ play: async () => {+ await next()+ await expect(page().getByRole('checkbox', { name: 'Claude Code' })).toBeVisible()+ }+}++export const ConnectAgentAndFinish: Story = {+ args: { agentsAvailable: true },+ play: async () => {+ await next()+ await choose('Codex')+ await next()+ // Codex covers the design goal, so there is no pay-as-you-go question.+ await expect(page().getByRole('heading', { name: 'Connect your AI' })).toBeVisible()+ await expect(page().getByText('npm i -g @agentclientprotocol/codex-acp')).toBeVisible()+ await next()+ await expect(page().getByText('Codex · Model chosen by the agent')).toBeVisible()+ await userEvent.click(page().getByRole('button', { name: 'Finish setup' }))+ await expect(page().getByRole('heading', { name: 'AI is ready' })).toBeVisible()+ await expect(aiModelSettings.value.models.map((profile) => profile.name)).toEqual(['Codex'])+ }+}++export const RecommendOpenRouter: Story = {+ play: async () => {+ await choose(/Review designs visually/)+ await next()+ await next()+ await userEvent.click(page().getByRole('button', { name: 'Add OpenRouter (pay as you go)' }))+ await expect(page().getByRole('button', { name: 'Sign in with OpenRouter' })).toBeVisible()+ await expect(page().getByRole('button', { name: 'Continue' })).toBeDisabled()+ }+}++export const NothingCovered: Story = {+ play: async () => {+ await next()+ await next()+ await expect(page().getByRole('button', { name: 'Continue' })).toBeDisabled()+ await expect(+ page().getByRole('button', { name: 'Add OpenRouter (pay as you go)' })+ ).toBeVisible()+ }+}++export const ServerWithoutVision: Story = {+ play: async () => {+ await choose(/Review designs visually/)+ await next()+ await choose('Local model or company server')+ await next()+ const addOpenRouter = () =>+ page().queryByRole('button', { name: 'Add OpenRouter (pay as you go)' })+ await expect(addOpenRouter()).toBeVisible()+ await choose('This model can read images')+ await expect(addOpenRouter()).toBeNull()+ }+}diff --git a/src/components/settings/ai-setup/AISetupFlow.vue b/src/components/settings/ai-setup/AISetupFlow.vuenew file mode 100644index 000000000..b739d1ad4--- /dev/null+++ b/src/components/settings/ai-setup/AISetupFlow.vue@@ -0,0 +1,257 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'+import { computed, ref } from 'vue'++import { IS_TAURI } from '@open-pencil/core/constants'+import { useI18n } from '@open-pencil/vue'++import type { OnboardingConnectionPatch } from '@/app/ai/models/settings/onboarding/connections'+import type { AISetupEntry } from '@/app/ai/models/settings/onboarding/dialog'+import {+ ONBOARDING_GOALS,+ type OnboardingAccess,+ type OnboardingGoal+} from '@/app/ai/models/settings/onboarding/plan'+import { AI_SETUP_STEPS, useAIOnboarding } from '@/app/ai/models/settings/onboarding/use'+import SettingsSaveFeedback from '@/components/settings/layout/SettingsSaveFeedback.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import { AppDialogBody, AppDialogFooter, AppDialogHeader } from '@/components/ui/dialog'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'+import theme from '@/theme/settings/ai-setup/flow'++import AISetupAccess from './AISetupAccess.vue'+import AISetupConnection from './AISetupConnection.vue'+import AISetupReview from './AISetupReview.vue'+import AISetupRoles from './AISetupRoles.vue'+import SetupChoice from './SetupChoice.vue'++const { entry, agentsAvailable = IS_TAURI } = defineProps<{+ entry: AISetupEntry+ agentsAvailable?: boolean+}>()+const emit = defineEmits<{ close: []; advanced: [] }>()+const { ai, common } = useI18n()+const styles = tv(theme)()++const onboarding = useAIOnboarding({ agentsAvailable })+const { answers, step, recommended, plan, roles, gaps, hasDesign, busy, saveResult, canContinue } =+ onboarding+const { isRecommended } = roles+const phase = ref<'welcome' | 'wizard' | 'saved'>(entry === 'welcome' ? 'welcome' : 'wizard')++const goals = computed(() => [+ {+ id: 'design' as const,+ label: ai.value.aiSetupGoalDesign,+ description: ai.value.aiSetupGoalDesignDescription+ },+ {+ id: 'vision' as const,+ label: ai.value.aiSetupGoalVision,+ description: ai.value.aiSetupGoalVisionDescription+ }+])+const header = computed(() => {+ if (phase.value === 'welcome') {+ return {+ heading: ai.value.aiSetupWelcomeTitle,+ description: ai.value.aiSetupWelcomeDescription+ }+ }+ if (phase.value === 'saved') {+ return { heading: ai.value.aiSetupSavedTitle, description: ai.value.aiSetupSavedDescription }+ }+ const headings = {+ goals: ai.value.aiSetupGoalsTitle,+ access: ai.value.aiSetupAccessTitle,+ connect: ai.value.aiSetupConnectTitle,+ review: ai.value.aiSetupReviewTitle+ }+ return {+ heading: headings[step.value],+ description: ai.value.aiSetupProgress({+ current: AI_SETUP_STEPS.indexOf(step.value) + 1,+ total: AI_SETUP_STEPS.length+ })+ }+})++function toggleGoal(goal: OnboardingGoal, checked: boolean): void {+ answers.goals = ONBOARDING_GOALS.filter((candidate) =>+ candidate === goal ? checked : answers.goals.includes(candidate)+ )+}++function updateConnection(providerID: OnboardingAccess, patch: OnboardingConnectionPatch): void {+ Object.assign(onboarding.connection(providerID), patch)+ onboarding.resetTest(providerID)+}++/** Runs in the click handler, so the browser allows the sign-in popup. */+function signIn(providerID: OnboardingAccess): void {+ onboarding.signIn(providerID, { keyLabel: 'OpenPencil' })+}++function back(): void {+ if (onboarding.back()) return+ if (entry === 'welcome') phase.value = 'welcome'+ else emit('close')+}++async function finish(): Promise<void> {+ if ((await onboarding.apply()) === 'saved') phase.value = 'saved'+}+</script>++<template>+ <AppDialogHeader+ :heading="header.heading"+ :description="header.description"+ :close-label="common.close"+ >+ <template #actions>+ <AppButton v-if="phase === 'wizard'" size="xs" class="mr-1 ml-auto" @click="emit('advanced')">+ {{ ai.aiSetupAdvanced }}+ </AppButton>+ </template>+ </AppDialogHeader>++ <AppDialogBody>+ <div :class="styles.body()" :data-ai-setup-step="phase === 'wizard' ? step : phase">+ <section v-if="phase === 'welcome'" :class="styles.intro()">+ <h3 :class="styles.introHeading()">{{ ai.aiSetupWelcomeAITitle }}</h3>+ <p :class="styles.introText()">{{ ai.aiSetupWelcomeAIDescription }}</p>+ </section>++ <template v-else-if="phase === 'saved'">+ <AISetupReview :plan="plan" />+ </template>++ <template v-else-if="step === 'goals'">+ <SetupChoice+ v-for="goal in goals"+ :key="goal.id"+ :label="goal.label"+ :description="goal.description"+ >+ <AppCheckbox+ :model-value="answers.goals.includes(goal.id)"+ :ariaLabel="goal.label"+ @update:model-value="toggleGoal(goal.id, $event)"+ />+ </SetupChoice>+ </template>++ <template v-else-if="step === 'access'">+ <p :class="styles.help()">{{ ai.aiSetupAccessDescription }}</p>+ <AISetupAccess v-model="answers.access" :agents-available="agentsAvailable" />+ </template>++ <template v-else-if="step === 'connect'">+ <AppAlert+ v-if="gaps.length && answers.spending === 'metered'"+ :heading="ai.aiSetupGapCoveredByOpenRouter"+ data-slot="setup-gap"+ >+ <template #actions>+ <AppButton size="xs" @click="answers.spending = 'existing'">+ {{ ai.aiSetupGapRemoveOpenRouter }}+ </AppButton>+ </template>+ </AppAlert>+ <AppAlert+ v-else-if="gaps.length"+ :tone="hasDesign ? 'info' : 'warning'"+ :heading="gaps.includes('design') ? ai.aiSetupGapDesign : ai.aiSetupGapVision"+ :description="hasDesign ? ai.aiSetupGapContinue : ai.aiSetupNothingDescription"+ data-slot="setup-gap"+ >+ <template #actions>+ <AppButton size="xs" variant="outline" @click="answers.spending = 'metered'">+ {{ ai.aiSetupGapAddOpenRouter }}+ </AppButton>+ </template>+ </AppAlert>+ <AppAlert+ v-if="hasDesign && !recommended.connections.length"+ tone="success"+ :heading="ai.aiSetupAlreadyConnected"+ />+ <AISetupConnection+ v-for="providerID in recommended.connections"+ :key="providerID"+ :provider-i-d="providerID"+ :state="onboarding.connection(providerID)"+ :has-saved-key="onboarding.hasSavedKey(providerID)"+ :sign-in-status="onboarding.signInStatus(providerID)"+ :server-vision="answers.serverVision ?? false"+ :agent-setup="onboarding.agentSetup(providerID)"+ :pi-setup="onboarding.piSetup(providerID)"+ :recommended="!answers.access.includes(providerID)"+ :disabled="busy"+ @update="updateConnection(providerID, $event)"+ @test="onboarding.testConnection(providerID)"+ @sign-in="signIn(providerID)"+ @reopen-sign-in="onboarding.reopenSignIn(providerID)"+ @cancel-sign-in="onboarding.cancelSignIn(providerID)"+ @sign-out="onboarding.signOut(providerID)"+ @server-vision="answers.serverVision = $event"+ @check-agent="onboarding.refreshAgents()"+ @install-agent="onboarding.installAgent(providerID)"+ @install-bridge="onboarding.setupCanvasBridge()"+ />+ </template>++ <template v-else>+ <p :class="styles.help()">{{ ai.aiSetupRolesDescription }}</p>+ <AISetupRoles+ :plan="plan"+ :options="roles.options"+ :is-recommended="isRecommended"+ @choose="roles.choose"+ @use-recommended="roles.useRecommended"+ />+ <SettingsSaveFeedback+ :result="saveResult"+ :error="saveResult === 'saved' ? null : saveResult"+ />+ </template>+ </div>+ </AppDialogBody>++ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <template v-if="phase === 'welcome'">+ <AppButton variant="outline" @click="emit('close')">{{ ai.aiSetupSkip }}</AppButton>+ <AppButton color="primary" variant="solid" @click="phase = 'wizard'">+ {{ ai.aiSetupStart }}+ </AppButton>+ </template>+ <template v-else-if="phase === 'saved'">+ <AppButton class="ml-auto" color="primary" variant="solid" @click="emit('close')">+ {{ common.done }}+ </AppButton>+ </template>+ <template v-else>+ <AppButton :disabled="busy" @click="back">{{ common.back }}</AppButton>+ <AppButton+ v-if="step === 'review'"+ color="primary"+ variant="solid"+ :disabled="busy"+ @click="finish"+ >+ {{ ai.aiSetupFinish }}+ </AppButton>+ <AppButton+ v-else+ color="primary"+ variant="solid"+ :disabled="!canContinue"+ @click="onboarding.next()"+ >+ {{ ai.aiSetupContinue }}+ </AppButton>+ </template>+ </AppDialogFooter>+</template>diff --git a/src/components/settings/ai-setup/AISetupPi.vue b/src/components/settings/ai-setup/AISetupPi.vuenew file mode 100644index 000000000..0aaabf9b1--- /dev/null+++ b/src/components/settings/ai-setup/AISetupPi.vue@@ -0,0 +1,142 @@+<script setup lang="ts">+import { useClipboard } from '@vueuse/core'+import { tv } from 'tailwind-variants'+import { computed, ref, watch } from 'vue'++import { useI18n } from '@open-pencil/vue'++import type { PiSetupState } from '@/app/ai/models/settings/onboarding/agents'+import SettingsLink from '@/components/settings/layout/SettingsLink.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import { NODE_DOWNLOAD_URL } from '@/constants'+import theme from '@/theme/settings/ai-setup/flow'++import SetupInstallItem from './SetupInstallItem.vue'++const { setup } = defineProps<{ setup: PiSetupState }>()+const emit = defineEmits<{ check: []; installCompanion: []; installBridge: [] }>()+const { ai, common } = useI18n()+const styles = tv(theme)()+const { copy, copied, text } = useClipboard({ copiedDuring: 1500 })++/** Keeps showing results during a later check instead of flashing back to a spinner. */+const checked = ref(false)+watch(+ () => setup.scanning,+ (scanning) => {+ if (!scanning) checked.value = true+ },+ { immediate: true }+)++const busy = computed(() => setup.installingCompanion || setup.installingBridge)+const companionReady = computed(() => setup.companion && !setup.companionOutdated)+const bridgeReady = computed(() => setup.bridge && !setup.bridgeOutdated)+const needsNpm = computed(+ () => checked.value && !setup.npm && (!companionReady.value || !bridgeReady.value)+)+/** Manual commands are for where one-click installation cannot help. */+const manualCommands = computed(() => {+ const manual = !setup.npm || setup.error === 'harness-install' || setup.error === 'canvas-install'+ if (!manual) return []+ return [+ ...(companionReady.value ? [] : [setup.companionCommand]),+ ...(bridgeReady.value ? [] : [setup.bridgeCommand])+ ]+})+const errorMessage = computed(() => {+ if (setup.error === 'npm' || needsNpm.value) return ai.value.aiSetupAgentNeedsNpm+ if (setup.error === 'harness-install' || setup.error === 'canvas-install') {+ return ai.value.aiSetupAgentInstallFailed+ }+ if (setup.error === 'canvas-start') return ai.value.aiSetupAgentMCPStartFailed+ if (setup.error === 'lookup') return ai.value.aiSetupAgentLookupFailed+ return null+})++function state(installed: boolean, outdated: boolean): string {+ if (outdated) return ai.value.aiSetupAgentOutdated+ return installed ? ai.value.aiSetupAgentInstalled : ai.value.aiSetupAgentNotFound+}++/** The button that installs or updates a companion, while one-click installation can help. */+function actionLabel(+ ready: boolean,+ installing: boolean,+ outdated: boolean,+ labels: { install: string; update: string }+): string | undefined {+ if (ready || !setup.npm) return undefined+ if (installing) return ai.value.aiSetupAgentInstalling+ return outdated ? labels.update : labels.install+}++function copiedLabel(value: string): string {+ return copied.value && text.value === value ? common.value.copied : common.value.copy+}+</script>++<template>+ <p :class="styles.help()">{{ ai.aiSetupPiDescription }}</p>++ <p v-if="setup.scanning && !checked" role="status" :class="styles.signInStatus()">+ <icon-lucide-loader-2 :class="styles.spinner()" aria-hidden="true" />+ {{ ai.aiSetupAgentChecking }}+ </p>+ <ul v-else :class="styles.installList()">+ <SetupInstallItem+ :ready="companionReady"+ :action="+ actionLabel(companionReady, setup.installingCompanion, setup.companionOutdated, {+ install: ai.aiSetupPiInstallCompanion,+ update: ai.aiSetupPiUpdateCompanion+ })+ "+ :loading="setup.installingCompanion"+ :disabled="busy"+ @action="emit('installCompanion')"+ >+ {{ ai.aiSetupPiCompanion }} · {{ state(setup.companion, setup.companionOutdated) }}+ </SetupInstallItem>+ <SetupInstallItem+ :ready="bridgeReady"+ :action="+ actionLabel(bridgeReady, setup.installingBridge, setup.bridgeOutdated, {+ install: ai.aiSetupAgentInstallMCP,+ update: ai.aiSetupAgentUpdateMCP+ })+ "+ :loading="setup.installingBridge"+ :disabled="busy"+ @action="emit('installBridge')"+ >+ {{ ai.aiSetupAgentMCP }} · {{ state(setup.bridge, setup.bridgeOutdated) }}+ </SetupInstallItem>+ <SetupInstallItem :ready="Boolean(setup.defaultModel)">+ {{+ setup.defaultModel ? ai.aiSetupPiModel({ model: setup.defaultModel }) : ai.aiSetupPiNoModel+ }}+ </SetupInstallItem>+ </ul>+ <AppAlert v-if="errorMessage" tone="warning" :heading="errorMessage">+ <template v-if="setup.error === 'npm' || needsNpm" #actions>+ <SettingsLink :href="NODE_DOWNLOAD_URL">Node.js</SettingsLink>+ </template>+ </AppAlert>++ <template v-if="manualCommands.length">+ <p :class="styles.help()">{{ ai.aiSetupAgentInstall }}</p>+ <div v-for="command in manualCommands" :key="command" :class="styles.command()">+ <code>{{ command }}</code>+ <AppButton size="xs" @click="copy(command)">{{ copiedLabel(command) }}</AppButton>+ </div>+ </template>++ <p :class="styles.help()">{{ ai.aiSetupPiSignIn }}</p>+ <div :class="styles.signInActions()">+ <AppButton size="xs" :disabled="busy || setup.scanning" @click="emit('check')">+ {{ ai.aiSetupAgentCheckAgain }}+ </AppButton>+ </div>+</template>diff --git a/src/components/settings/ai-setup/AISetupReview.vue b/src/components/settings/ai-setup/AISetupReview.vuenew file mode 100644index 000000000..12cbf9e33--- /dev/null+++ b/src/components/settings/ai-setup/AISetupReview.vue@@ -0,0 +1,22 @@+<script setup lang="ts">+import { ONBOARDING_ROLES, type OnboardingPlan } from '@/app/ai/models/settings/onboarding/plan'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsRow from '@/components/settings/layout/SettingsRow.vue'++import { useRoleLabels } from './role-label'++const { plan } = defineProps<{ plan: OnboardingPlan }>()+const { choiceLabel, roleLabel } = useRoleLabels()+</script>++<template>+ <SettingsGroup>+ <SettingsRow+ v-for="role in ONBOARDING_ROLES"+ :key="role"+ :label="roleLabel(role).label"+ :description="choiceLabel(plan[role])"+ :data-model-role="role"+ />+ </SettingsGroup>+</template>diff --git a/src/components/settings/ai-setup/AISetupRoles.stories.ts b/src/components/settings/ai-setup/AISetupRoles.stories.tsnew file mode 100644index 000000000..4a0ca7443--- /dev/null+++ b/src/components/settings/ai-setup/AISetupRoles.stories.ts@@ -0,0 +1,45 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, within } from 'storybook/test'++import { planOnboarding, roleOptions } from '@/app/ai/models/settings/onboarding/plan'+import type { AIModelRole } from '@/app/ai/models/types'++import AISetupRoles from './AISetupRoles.vue'++interface Args {+ isRecommended: boolean+}++const plan = planOnboarding(+ { goals: ['design', 'vision'], access: ['openrouter'], spending: 'existing' },+ { agentsAvailable: false }+)++const meta = {+ title: 'Settings/AI Setup/Roles',+ args: { isRecommended: true },+ render: (args) => ({+ components: { AISetupRoles },+ setup: () => ({+ args,+ plan,+ options: (role: AIModelRole) => roleOptions(role, plan, [])+ }),+ template:+ '<div class="flex w-[34rem] max-w-full flex-col gap-3"><AISetupRoles v-bind="args" :plan="plan" :options="options" /></div>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const RecommendedOpenRouter: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByRole('combobox', { name: 'Fast tasks' })).not.toHaveTextContent(+ 'Same as Design'+ )+ await expect(canvas.queryByRole('button', { name: 'Use recommended setup' })).toBeNull()+ }+}+export const ChangedFromRecommended: Story = { args: { isRecommended: false } }diff --git a/src/components/settings/ai-setup/AISetupRoles.vue b/src/components/settings/ai-setup/AISetupRoles.vuenew file mode 100644index 000000000..94298ad29--- /dev/null+++ b/src/components/settings/ai-setup/AISetupRoles.vue@@ -0,0 +1,57 @@+<script setup lang="ts">+import { useI18n } from '@open-pencil/vue'++import {+ ONBOARDING_ROLES,+ roleChoiceKey,+ type OnboardingPlan,+ type PlannedRole+} from '@/app/ai/models/settings/onboarding/plan'+import type { AIModelRole } from '@/app/ai/models/types'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsRow from '@/components/settings/layout/SettingsRow.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'++import { useRoleLabels } from './role-label'++const { plan, options, isRecommended } = defineProps<{+ plan: OnboardingPlan+ options: (role: AIModelRole) => PlannedRole[]+ isRecommended: boolean+}>()+const emit = defineEmits<{ choose: [role: AIModelRole, key: string]; useRecommended: [] }>()+const { ai } = useI18n()+const { choiceLabel, roleLabel } = useRoleLabels()++function selectOptions(role: AIModelRole) {+ return options(role).map((option) => ({+ value: roleChoiceKey(option),+ label: choiceLabel(option)+ }))+}+</script>++<template>+ <SettingsGroup>+ <SettingsRow+ v-for="role in ONBOARDING_ROLES"+ :key="role"+ class="max-sm:flex-col max-sm:items-stretch"+ :label="roleLabel(role).label"+ :description="roleLabel(role).description"+ :data-model-role="role"+ >+ <AppSelect+ class="w-full sm:w-64"+ :model-value="roleChoiceKey(plan[role])"+ :options="selectOptions(role)"+ :label="roleLabel(role).label"+ @update:model-value="emit('choose', role, String($event))"+ />+ </SettingsRow>+ </SettingsGroup>+ <AppButton v-if="!isRecommended" class="self-start" @click="emit('useRecommended')">+ {{ ai.aiSetupUseRecommended }}+ </AppButton>+</template>diff --git a/src/components/settings/ai-setup/SetupChoice.vue b/src/components/settings/ai-setup/SetupChoice.vuenew file mode 100644index 000000000..42e2a257e--- /dev/null+++ b/src/components/settings/ai-setup/SetupChoice.vue@@ -0,0 +1,19 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'++import theme from '@/theme/settings/ai-setup/flow'++const { label, description } = defineProps<{ label: string; description?: string }>()+const styles = tv(theme)()+</script>++<template>+ <label :class="styles.choice()">+ <slot />+ <slot name="icon" />+ <span+ ><span class="font-medium">{{ label }}</span+ ><span v-if="description" class="mt-1 block text-muted">{{ description }}</span></span+ >+ </label>+</template>diff --git a/src/components/settings/ai-setup/SetupInstallItem.vue b/src/components/settings/ai-setup/SetupInstallItem.vuenew file mode 100644index 000000000..d41d3bd34--- /dev/null+++ b/src/components/settings/ai-setup/SetupInstallItem.vue@@ -0,0 +1,43 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'++import AppButton from '@/components/ui/button/AppButton.vue'+import theme from '@/theme/settings/ai-setup/flow'++/** One thing guided setup checks on this computer, with an optional one-click fix. */+const {+ ready,+ action,+ loading = false,+ disabled = false+} = defineProps<{+ /** Installed and usable as it is. */+ ready: boolean+ /** Label of the button that installs or updates it; no button when absent. */+ action?: string+ loading?: boolean+ disabled?: boolean+}>()+const emit = defineEmits<{ action: [] }>()+const styles = tv(theme)()+</script>++<template>+ <li :class="styles.installItem()" :data-status="ready ? 'available' : 'missing'">+ <icon-lucide-circle-check v-if="ready" :class="styles.signedInIcon()" aria-hidden="true" />+ <icon-lucide-circle-dashed v-else :class="styles.missingIcon()" aria-hidden="true" />+ <span class="flex-1"><slot /></span>+ <slot name="action">+ <AppButton+ v-if="action"+ size="xs"+ variant="outline"+ :disabled="disabled"+ :loading="loading"+ @click="emit('action')"+ >+ {{ action }}+ </AppButton>+ </slot>+ </li>+</template>diff --git a/src/components/settings/ai-setup/role-label.ts b/src/components/settings/ai-setup/role-label.tsnew file mode 100644index 000000000..adc884146--- /dev/null+++ b/src/components/settings/ai-setup/role-label.ts@@ -0,0 +1,31 @@+import { useI18n } from '@open-pencil/vue'++import { modelProviderName } from '@/app/ai/models/provider-name'+import { isOnboardingAgent, type PlannedRole } from '@/app/ai/models/settings/onboarding/plan'+import type { AIModelRole } from '@/app/ai/models/types'++/** Labels for the roles and the choices guided setup offers for them. */+export function useRoleLabels() {+ const { ai } = useI18n()++ function choiceLabel(choice: PlannedRole): string {+ if (choice === 'design') return ai.value.modelRoleUseDesign+ if (choice === null) return ai.value.noModel+ const provider = modelProviderName(choice.providerID)+ if (isOnboardingAgent(choice.providerID)) return `${provider} · ${ai.value.aiSetupAgentModel}`+ return choice.modelID && choice.name !== provider ? `${choice.name} · ${provider}` : provider+ }++ function roleLabel(role: AIModelRole): { label: string; description: string } {+ const roles = {+ design: [ai.value.modelRoleDesign, ai.value.modelRoleDesignDescription],+ vision: [ai.value.modelRoleVision, ai.value.modelRoleVisionDescription],+ review: [ai.value.modelRoleReview, ai.value.modelRoleReviewDescription],+ fast: [ai.value.modelRoleFast, ai.value.modelRoleFastDescription]+ } as const+ const [label, description] = roles[role]+ return { label, description }+ }++ return { choiceLabel, roleLabel }+}diff --git a/src/components/settings/models/ModelsPanel.vue b/src/components/settings/models/ModelsPanel.vueindex 30816f17e..106dbfdda 100644--- a/src/components/settings/models/ModelsPanel.vue+++ b/src/components/settings/models/ModelsPanel.vue@@ -1,8 +1,10 @@<script setup lang="ts">import { ref, onUnmounted } from 'vue'+import { HARNESS_PROVIDER_ID } from '@open-pencil/core/constants'import { useI18n } from '@open-pencil/vue'+import { openAISetup } from '@/app/ai/models/settings/onboarding/dialog'import { useModelSettings } from '@/app/ai/models/settings/use'import SettingsPage from '@/components/settings/layout/SettingsPage.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'@@ -30,8 +32,12 @@ function editModel(profileId: string): void {}function statusLabel(connectionId: string, providerID: string): string {- if (providerID.startsWith('acp:')) return ai.value.modelAgentConnectionconst status = statusByConnection.value[connectionId]+ if (providerID.startsWith('acp:')) return ai.value.modelAgentConnection+ // Pi uses its own sign-ins unless an AI Gateway key is saved.+ if (providerID === HARNESS_PROVIDER_ID && status !== 'configured') {+ return ai.value.modelAgentConnection+ }if (status === 'configured') return collaboration.value.connectedif (status === 'locked' || status === 'unavailable') return common.value.unavailablereturn ai.value.modelNeedsCredential@@ -130,6 +136,17 @@ const { profiles, statusByConnection, refreshStatuses } = useModelSettings()</template></AppActionRow></div>+ <AppButton+ color="primary"+ variant="link"+ size="xs"+ class="self-start"+ data-test-id="settings-run-ai-setup"+ @click="openAISetup()"+ >+ <template #leading><icon-lucide-sparkles class="size-3" /></template>+ {{ ai.aiSetupRun }}+ </AppButton></SettingsSection><SettingsSection>diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vueindex 69e4b34f6..0262f1752 100644--- a/src/components/settings/models/ProfileEditor.vue+++ b/src/components/settings/models/ProfileEditor.vue@@ -1,14 +1,16 @@<script setup lang="ts">-import { computed, ref, useTemplateRef } from 'vue'+import { computed, ref, useTemplateRef, watch } from 'vue'import type { AIProviderID } from '@open-pencil/core/constants'import { useI18n } from '@open-pencil/vue'+import { useOnboardingAgents } from '@/app/ai/models/settings/onboarding/agents'import { useModelProfileFeedback } from '@/app/ai/models/settings/profile-editor/feedback'import { useModelProfileEditor } from '@/app/ai/models/settings/profile-editor/use'import { thinkingLevelOptions as buildThinkingLevelOptions } from '@/app/ai/models/thinking'import { useSettingsFormGuard } from '@/app/settings/navigation/use'import ProviderConnectionTestButton from '@/components/chat/ProviderConnectionTestButton.vue'+import AISetupPi from '@/components/settings/ai-setup/AISetupPi.vue'import { focusInvalidField } from '@/components/settings/layout/focus'import SettingsPage from '@/components/settings/layout/SettingsPage.vue'import SettingsSaveFeedback from '@/components/settings/layout/SettingsSaveFeedback.vue'@@ -56,6 +58,16 @@ const {clearKey,testConnection: runConnectionTest} = profile+const piAgents = useOnboardingAgents()+const piSetup = computed(() => {+ const setup = isHarness.value ? piAgents.piSetup('harness:pi') : undefined+ // Pi runs only in the desktop app, where its companion can be checked.+ return setup?.supported ? setup : undefined+})+const customModelPlaceholder = computed(() =>+ isHarness.value ? (piSetup.value?.defaultModel ?? 'provider/model') : 'e.g. llama-3.3-70b'+)+watch(isHarness, (harness) => harness && piAgents.refreshAgents(), { immediate: true })const feedback = useModelProfileFeedback(profile, keyInput, settings)const { errors: fieldErrors } = feedbackconst busy = computed(() => saving.value || connectionTestStatus.value === 'testing')@@ -133,6 +145,15 @@ async function remove() {/></ProviderSettingsField>+ <div v-if="piSetup" class="flex flex-col gap-2" data-test-id="settings-pi-setup">+ <AISetupPi+ :setup="piSetup"+ @check="piAgents.refreshAgents()"+ @install-companion="piAgents.installAgent('harness:pi')"+ @install-bridge="piAgents.setupCanvasBridge()"+ />+ </div>+<template v-if="!isACP"><div class="flex items-center gap-2 pt-1"><p class="text-[10px] font-medium uppercase tracking-wide text-muted">@@ -142,7 +163,7 @@ async function remove() {</div><ProviderSettingsField- v-if="modelOptions.length"+ v-if="modelOptions.length && !isHarness"v-slot="{ control }":label="ai.modelID":error="fieldErrors.modelID"@@ -164,7 +185,7 @@ async function remove() {v-if="providerDef.supportsCustomModel && selectedModelValue === CUSTOM_MODEL_VALUE"v-slot="{ control }":label="ai.customModelID"- :hint="settings.modelIDHint"+ :hint="isHarness ? ai.piModelHint : settings.modelIDHint":error="fieldErrors.customModelID"@blur="feedback.blur('customModelID')">@@ -173,7 +194,7 @@ async function remove() {v-model="draft.customModelID":aria-label="ai.customModelID"data-test-id="provider-settings-custom-model"- placeholder="e.g. llama-3.3-70b"+ :placeholder="customModelPlaceholder"/></ProviderSettingsField>diff --git a/src/components/settings/provider/ProviderLogo.vue b/src/components/settings/provider/ProviderLogo.vuenew file mode 100644index 000000000..350e22094--- /dev/null+++ b/src/components/settings/provider/ProviderLogo.vue@@ -0,0 +1,43 @@+<script setup lang="ts">+import type { Component } from 'vue'+import { computed } from 'vue'+import IconAnthropic from '~icons/ai/anthropic'+import IconClaudeCode from '~icons/ai/claudecode'+import IconCodex from '~icons/ai/codex'+import IconDeepSeek from '~icons/ai/deepseek'+import IconGemini from '~icons/ai/gemini'+import IconGeminiCLI from '~icons/ai/geminicli'+import IconLMStudio from '~icons/ai/lmstudio'+import IconMiniMax from '~icons/ai/minimax'+import IconOllama from '~icons/ai/ollama'+import IconOpenAI from '~icons/ai/openai'+import IconOpenRouter from '~icons/ai/openrouter'+import IconZai from '~icons/ai/zai'+import IconBot from '~icons/lucide/bot'+import IconServer from '~icons/lucide/server'++/** A provider, agent, or server preset such as `ollama`. */+const { provider } = defineProps<{ provider: string }>()++const LOGOS: Record<string, Component> = {+ anthropic: IconAnthropic,+ openai: IconOpenAI,+ google: IconGemini,+ openrouter: IconOpenRouter,+ deepseek: IconDeepSeek,+ zai: IconZai,+ minimax: IconMiniMax,+ ollama: IconOllama,+ lmstudio: IconLMStudio,+ 'acp:claude-code': IconClaudeCode,+ 'acp:codex': IconCodex,+ 'acp:gemini-cli': IconGeminiCLI,+ 'harness:pi': IconBot+}++const logo = computed(() => LOGOS[provider] ?? IconServer)+</script>++<template>+ <component :is="logo" class="size-4 shrink-0" aria-hidden="true" data-slot="provider-logo" />+</template>diff --git a/src/components/ui/toggle/AppCheckbox.vue b/src/components/ui/toggle/AppCheckbox.vueindex 618ffeabd..c2e8e63a4 100644--- a/src/components/ui/toggle/AppCheckbox.vue+++ b/src/components/ui/toggle/AppCheckbox.vue@@ -19,7 +19,7 @@ const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>():model-value="modelValue":aria-label="ariaLabel":disabled="disabled"- class="flex size-4 shrink-0 items-center justify-center rounded border border-border bg-surface text-white outline-none data-[state=checked]:border-accent data-[state=checked]:bg-accent data-[state=indeterminate]:border-accent data-[state=indeterminate]:bg-accent focus-visible:ring-2 focus-visible:ring-accent/40 disabled:opacity-50"+ class="flex size-4 shrink-0 items-center justify-center rounded border border-border bg-panel-field text-white outline-none transition-colors hover:border-accent/60 data-[state=checked]:border-accent data-[state=checked]:bg-accent data-[state=indeterminate]:border-accent data-[state=indeterminate]:bg-accent focus-visible:ring-2 focus-visible:ring-accent/40 disabled:opacity-50"@update:model-value="(value) => emit('update:modelValue', value === true)"><CheckboxIndicator class="flex items-center justify-center">diff --git a/src/components/ui/toggle/AppRadioGroup.stories.ts b/src/components/ui/toggle/AppRadioGroup.stories.tsnew file mode 100644index 000000000..25a22b59f--- /dev/null+++ b/src/components/ui/toggle/AppRadioGroup.stories.ts@@ -0,0 +1,69 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, waitFor, within } from 'storybook/test'+import { ref } from 'vue'++import AppRadioGroup from './AppRadioGroup.vue'+import type { AppRadioOption } from './radio'++interface Args {+ label: string+ options: AppRadioOption<string>[]+ orientation?: 'vertical' | 'horizontal'+}++const options: AppRadioOption<string>[] = [+ { value: 'existing', label: 'Use my existing accounts only' },+ {+ value: 'metered',+ label: 'Include pay-as-you-go options',+ description: 'Requests are billed to the API account you connect.'+ },+ { value: 'later', label: 'Decide later', disabled: true }+]++const meta = {+ title: 'Design System/Inputs/Radio group',+ args: { label: 'Spending', options },+ render: (args) => ({+ components: { AppRadioGroup },+ setup: () => ({ args, value: ref('existing') }),+ template:+ '<div class="w-80 max-w-full"><AppRadioGroup v-bind="args" v-model="value" /><p class="mt-3 text-xs text-muted">Selected: {{ value }}</p></div>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>+export const Vertical: Story = {}+export const Horizontal: Story = {+ args: {+ orientation: 'horizontal',+ options: options.map(({ value, label }) => ({ value, label }))+ }+}+export const KeyboardSelection: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const existing = canvas.getByRole('radio', { name: 'Use my existing accounts only' })+ const metered = canvas.getByRole('radio', { name: 'Include pay-as-you-go options' })+ await expect(metered).toHaveAccessibleDescription(+ 'Requests are billed to the API account you connect.'+ )+ await expect(existing).toBeChecked()+ await userEvent.click(existing)+ // Reka checks the newly focused radio only while the arrow key is still held, as in a browser.+ async function pressArrow(key: string) {+ await userEvent.keyboard(`{${key}>}`)+ await waitFor(() => expect(canvasElement.ownerDocument.activeElement).toBeChecked())+ await userEvent.keyboard(`{/${key}}`)+ }+ await pressArrow('ArrowDown')+ await expect(metered).toBeChecked()+ await expect(canvas.getByText('Selected: metered')).toBeVisible()+ await pressArrow('ArrowRight')+ await expect(existing).toBeChecked()+ await pressArrow('ArrowLeft')+ await expect(metered).toBeChecked()+ await expect(canvas.getByRole('radio', { name: 'Decide later' })).toBeDisabled()+ }+}diff --git a/src/components/ui/toggle/AppRadioGroup.vue b/src/components/ui/toggle/AppRadioGroup.vuenew file mode 100644index 000000000..2520ddab2--- /dev/null+++ b/src/components/ui/toggle/AppRadioGroup.vue@@ -0,0 +1,68 @@+<script setup lang="ts" generic="T extends string | number">+import { RadioGroupIndicator, RadioGroupItem, RadioGroupRoot } from 'reka-ui'+import { tv } from 'tailwind-variants'+import { useId } from 'vue'++import theme from '@/theme/toggle/radio'++import type { AppRadioGroupUI, AppRadioOption } from './radio'++const {+ label,+ labelledby,+ options,+ orientation,+ disabled = false,+ ui+} = defineProps<{+ label?: string+ labelledby?: string+ options: AppRadioOption<T>[]+ orientation?: 'vertical' | 'horizontal'+ disabled?: boolean+ ui?: AppRadioGroupUI+}>()+const modelValue = defineModel<T>({ required: true })+const styles = tv(theme)()+const id = useId()+</script>++<template>+ <RadioGroupRoot+ v-model="modelValue"+ :aria-label="labelledby ? undefined : label"+ :aria-labelledby="labelledby"+ :orientation="orientation"+ :disabled="disabled"+ :class="styles.root({ class: ui?.root })"+ >+ <label+ v-for="(option, index) in options"+ :key="option.value"+ :class="styles.option({ class: ui?.option })"+ data-slot="radio-option"+ >+ <RadioGroupItem+ :value="option.value"+ :disabled="option.disabled"+ :aria-labelledby="`${id}-${index}-label`"+ :aria-describedby="option.description ? `${id}-${index}-description` : undefined"+ :class="styles.item({ class: ui?.item })"+ >+ <RadioGroupIndicator :class="styles.indicator({ class: ui?.indicator })" />+ </RadioGroupItem>+ <span :class="styles.text({ class: ui?.text })">+ <span :id="`${id}-${index}-label`" :class="styles.label({ class: ui?.label })">{{+ option.label+ }}</span>+ <span+ v-if="option.description"+ :id="`${id}-${index}-description`"+ :class="styles.description({ class: ui?.description })"+ >+ {{ option.description }}+ </span>+ </span>+ </label>+ </RadioGroupRoot>+</template>diff --git a/src/components/ui/toggle/radio.ts b/src/components/ui/toggle/radio.tsnew file mode 100644index 000000000..f2e3f964d--- /dev/null+++ b/src/components/ui/toggle/radio.ts@@ -0,0 +1,11 @@+import type { ComponentUI } from '@/components/ui/types'+import type { RadioGroupTheme } from '@/theme/toggle/radio'++export type AppRadioGroupUI = ComponentUI<RadioGroupTheme>++export interface AppRadioOption<TValue extends string | number> {+ value: TValue+ label: string+ description?: string+ disabled?: boolean+}diff --git a/src/constants.ts b/src/constants.tsindex ef156f727..5b29e71b3 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -80,10 +80,7 @@ export const ROOM_STATUS_TICK_MS = 500export const WEB_APP_ORIGIN = 'https://app.openpencil.dev'/** Where the desktop app's installers are published. */export const DESKTOP_DOWNLOAD_URL = 'https://github.com/open-pencil/open-pencil/releases/latest'--/** The running app's version, from `package.json` at build time. */-export const APP_VERSION =- typeof __OPENPENCIL_APP_VERSION__ === 'string' ? __OPENPENCIL_APP_VERSION__ : ''+export const NODE_DOWNLOAD_URL = 'https://nodejs.org/en/download'/** The published release page, with its full notes, for a desktop version. */export function releaseNotesURL(version: string): string {diff --git a/src/theme/settings/ai-setup/flow.ts b/src/theme/settings/ai-setup/flow.tsnew file mode 100644index 000000000..6ab84f931--- /dev/null+++ b/src/theme/settings/ai-setup/flow.ts@@ -0,0 +1,31 @@+import { motionStyles } from '@/theme/motion/styles'++export default {+ slots: {+ body: 'flex flex-col gap-3 text-xs text-surface',+ help: 'text-xs leading-relaxed text-muted',+ intro: 'rounded-lg border border-accent/25 bg-accent/5 p-4',+ introHeading: 'text-sm font-semibold text-surface',+ introText: 'mt-2 text-xs leading-relaxed text-muted',+ group: 'flex flex-col gap-2',+ groupHeading: 'text-[11px] font-semibold text-muted',+ // Reads as a group heading; the gap below lives inside the animated content.+ moreTrigger: 'py-1.5 text-[11px] font-semibold text-muted transition-colors hover:text-surface',+ moreGroup: 'flex flex-col gap-2 pt-1',+ choice:+ 'flex cursor-pointer items-start gap-3 rounded-md border border-border px-3 py-3 transition-colors hover:bg-hover has-[[data-state=checked]]:border-accent has-[[data-state=checked]]:bg-accent/5 focus-within:ring-2 focus-within:ring-accent/50',+ connection: 'flex flex-col gap-3 rounded-md border border-border p-3',+ connectionHeading: 'flex items-center gap-2 text-xs font-semibold text-surface',+ signIn: 'flex flex-wrap items-center justify-between gap-2 rounded bg-input px-3 py-2',+ signInStatus: 'flex items-center gap-2 text-xs text-surface',+ signInActions: 'flex items-center gap-2',+ signInDetail: 'ml-1 text-muted',+ signedInIcon: 'size-3.5 shrink-0 text-success',+ missingIcon: 'size-3.5 shrink-0 text-muted',+ installList: 'flex flex-col gap-1.5',+ installItem: 'flex items-center gap-2 text-xs text-surface',+ spinner: `size-3.5 shrink-0 ${motionStyles.spinner}`,+ command:+ 'flex items-center justify-between gap-2 rounded bg-input px-2.5 py-1.5 font-mono text-[11px] text-surface'+ }+}diff --git a/src/theme/toggle/radio.ts b/src/theme/toggle/radio.tsnew file mode 100644index 000000000..79a45a523--- /dev/null+++ b/src/theme/toggle/radio.ts@@ -0,0 +1,15 @@+const radioGroupTheme = {+ slots: {+ root: 'flex flex-col gap-2 data-[orientation=horizontal]:flex-row data-[orientation=horizontal]:flex-wrap',+ option:+ 'flex cursor-pointer items-start gap-2 text-xs text-surface has-[[data-disabled]]:cursor-not-allowed has-[[data-disabled]]:opacity-50',+ item: 'mt-px flex size-4 shrink-0 items-center justify-center rounded-full border border-border bg-panel-field outline-none transition-colors hover:border-accent/60 focus-visible:ring-2 focus-visible:ring-accent/40 data-[state=checked]:border-accent data-[state=checked]:bg-accent data-[disabled]:pointer-events-none',+ indicator: 'size-1.5 rounded-full bg-white',+ text: 'flex min-w-0 flex-col',+ label: 'font-medium',+ description: 'mt-1 text-muted'+ }+}++export type RadioGroupTheme = typeof radioGroupTheme+export default radioGroupThemediff --git a/src/views/UpdaterView.vue b/src/views/UpdaterView.vueindex 465222176..74a888f15 100644--- a/src/views/UpdaterView.vue+++ b/src/views/UpdaterView.vue@@ -4,11 +4,11 @@ import { computed, onMounted, onScopeDispose } from 'vue'import { useI18n } from '@open-pencil/vue'+import { APP_VERSION } from '@/app/runtime/version'import { animationsEnabled } from '@/app/shell/motion'import { useAppTheme } from '@/app/shell/theme'import { createTauriUpdaterBackend, createUpdaterSession } from '@/app/shell/updater/session'import UpdatePrompt from '@/components/updater/UpdatePrompt.vue'-import { APP_VERSION } from '@/constants'const { updates, locale } = useI18n()diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex d275b1925..f807c1cec 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -6,6 +6,7 @@ import { useRoute, useRouter } from 'vue-router'import { useI18n } from '@open-pencil/vue'+import { offerAISetupOnFirstRun } from '@/app/ai/models/settings/onboarding/dialog'import { startMCPRuntime, stopMCPRuntime } from '@/app/automation/mcp/runtime'import { startWebMCP } from '@/app/automation/webmcp/runtime'import { exposeCollaborationActions } from '@/app/browser-bridge'@@ -74,6 +75,10 @@ function openFirstTab(): Tab {}}+if (createdInitialTab && route.path === '/' && !appRuntimeConfig.test && !route.meta.demo) {+ offerAISetupOnFirstRun()+}+useHead({ title: route.meta.demo ? 'Demo' : undefined })useKeyboard()useEditorMenu()diff --git a/tests/AGENTS.md b/tests/AGENTS.mdindex aee131079..c26f27dc4 100644--- a/tests/AGENTS.md+++ b/tests/AGENTS.md@@ -13,6 +13,7 @@## Writing specs- Test contracts and observable behavior, not source text. Specs use domain drivers and probes, not scattered Window/store traversal or unrestricted evaluator wrappers.+- Assert state and outcomes, never copy, prompts, or constants: a test must not fail on rewording, a catalog update, or a list it restates. Name controls by role to reach them, assert what they do, and never recompute an expected value with the rule under test (`tests/app/ai/models/settings/onboarding/plan.test.ts`).- Locate behavior by accessible role and name, then label, then visible text. Scope repeated controls to a named region. Use scoped `data-slot` anatomy or semantic attributes (`data-property`, `data-command`, `data-node-id`) when needed; reserve `data-test-id` for integration boundaries and never add test-hook props or compound IDs.- Prefer test-runner-owned fixtures and request/route counters over browser globals. For in-page performance instrumentation, return a scoped `JSHandle` from `evaluateHandle()`, restore patched methods and listeners, and dispose the handle in `finally`; handles do not survive navigation. Assert transient DOM state with locators before the interaction ends.- Do not create a catch-all test Window interface or ad-hoc counter properties on `window`. Native-test declarations live in `tests/helpers/tauri/native-global.d.ts`; never expand production Window declarations for fixtures.@@ -26,6 +27,7 @@- Use the canonical `playwright.config.ts`; do not create task-specific config copies or server runners. Playwright owns Vite; the Vite automation plugin owns MCP startup and cleanup; browser fixtures own interactions, not server processes.- Test scripts select their server; direct Playwright commands start both servers unless `OPENPENCIL_TEST_SERVER=app|storybook|all` is set. Managed runs start the intended checkout; server reuse is opt-in for local development only, never for baseline comparisons or CI. Isolate the app URL, MCP endpoint, CORS origin, socket, and discovery path together.+- App projects start with the first-run AI setup offer already dismissed through the shared `storageState` in `playwright.config.ts`. A spec that overrides `storageState` and loads without `?test` must keep that preference unless it tests the offer (`tests/e2e/settings/ai-setup-first-run.spec.ts`).- Pixel-affecting renderer changes need committed canvas snapshots (`packages/core/AGENTS.md`, Renderer). Update only the justified affected snapshot and rerun without update mode.## Native WebViewdiff --git a/tests/app/ai/agents/companions.test.ts b/tests/app/ai/agents/companions.test.tsnew file mode 100644index 000000000..3f8c9f454--- /dev/null+++ b/tests/app/ai/agents/companions.test.ts@@ -0,0 +1,30 @@+import { describe, expect, test } from 'bun:test'++import { globalInstallCommand, isOutdatedCompanion } from '@/app/ai/agents/companions'++describe('isOutdatedCompanion', () => {+ test('requires the app’s major and minor version', () => {+ expect(isOutdatedCompanion('0.15.0', '0.15.1')).toBe(false)+ expect(isOutdatedCompanion('0.12.0', '0.15.1')).toBe(true)+ expect(isOutdatedCompanion('1.15.1', '0.15.1')).toBe(true)+ })++ test('treats an installed companion without a version as outdated', () => {+ expect(isOutdatedCompanion(null, '0.15.1')).toBe(true)+ })+})++describe('globalInstallCommand', () => {+ test('uses the package manager that installed the program', () => {+ expect(globalInstallCommand('@open-pencil/[email protected]', '/Users/me/.bun/bin/x')).toBe(+ 'bun add -g @open-pencil/[email protected]'+ )+ expect(globalInstallCommand('@open-pencil/[email protected]', 'C:\\Users\\me\\.bun\\bin\\x.exe')).toBe(+ 'bun add -g @open-pencil/[email protected]'+ )+ expect(globalInstallCommand('@open-pencil/[email protected]', '/usr/local/bin/x')).toBe(+ 'npm i -g @open-pencil/[email protected]'+ )+ expect(globalInstallCommand('@open-pencil/[email protected]')).toBe('npm i -g @open-pencil/[email protected]')+ })+})diff --git a/tests/app/ai/agents/discovery.test.ts b/tests/app/ai/agents/discovery.test.tsnew file mode 100644index 000000000..5782ee93d--- /dev/null+++ b/tests/app/ai/agents/discovery.test.ts@@ -0,0 +1,280 @@+import { describe, expect, test, mock } from 'bun:test'++import type { ACPAgentDef } from '@open-pencil/core/constants'++import { createAgentDiscovery, detectedAgents } from '@/app/ai/agents/discovery'+import type { AgentLookup } from '@/app/ai/agents/native'+import { createDeferred } from '@/app/runtime/deferred'++// Installed companions report the version of the app under test, as matching ones do.+const COMPANION_PACKAGES: Record<string, string> = {+ 'openpencil-mcp-http': '@open-pencil/mcp',+ 'openpencil-harness': '@open-pencil/harness'+}++function lookup(...commands: string[]): AgentLookup {+ return {+ searchPath: '/test/bin',+ versions: Object.fromEntries(+ commands.flatMap((command) => {+ const name = COMPANION_PACKAGES[command]+ return name ? [[name, '0.0.0']] : []+ })+ ),+ executables: Object.fromEntries(commands.map((command) => [command, `/test/bin/${command}`]))+ }+}++describe('local agent discovery', () => {+ test('installs the canvas companion once, discovers it, and restarts the bridge', async () => {+ let installed = false+ const pending = createDeferred<undefined>()+ const installBridge = mock(async () => {+ await pending.promise+ installed = true+ })+ const restartBridge = mock(async () => undefined)+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('gemini', 'npm', ...(installed ? ['openpencil-mcp-http'] : [])),+ install: async () => undefined,+ installBridge,+ restartBridge+ })+ await discovery.refresh()+ expect(installBridge).not.toHaveBeenCalled()+ const setup = discovery.setupCanvasBridge()+ await discovery.setupCanvasBridge()+ expect(installBridge).toHaveBeenCalledTimes(1)+ pending.resolve(undefined)+ await setup+ expect(discovery.canvasBridgeAvailable.value).toBe(true)+ expect(restartBridge).toHaveBeenCalledTimes(1)+ expect(discovery.error.value).toBeNull()+ })++ test('retries bridge startup without reinstalling a successfully installed companion', async () => {+ const installBridge = mock(async () => undefined)+ const restartBridge = mock(async (): Promise<void> => {+ throw new Error('Cannot start')+ })+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('gemini', 'openpencil-mcp-http'),+ install: async () => undefined,+ installBridge,+ restartBridge+ })+ await discovery.refresh()+ await discovery.setupCanvasBridge()+ expect(discovery.error.value).toBe('canvas-start')+ restartBridge.mockImplementation(async () => undefined)+ await discovery.setupCanvasBridge()+ expect(installBridge).not.toHaveBeenCalled()+ expect(discovery.error.value).toBeNull()+ })+ test('distinguishes native CLIs, adapters, and absent agents without starting them', () => {+ const agents = detectedAgents(lookup('claude', 'codex-acp'))+ expect(agents.map((agent) => [agent.definition.id, agent.status])).toEqual([+ ['claude-code', 'needs-adapter'],+ ['codex', 'available'],+ ['gemini-cli', 'not-installed']+ ])+ })++ test('browser discovery performs no native operations', async () => {+ const scan = mock(async () => lookup('gemini'))+ const install = mock(async () => undefined)+ const discovery = createAgentDiscovery({ enabled: false, lookup: scan, install })+ await discovery.refresh()+ await discovery.install('claude-code')+ expect(scan).not.toHaveBeenCalled()+ expect(install).not.toHaveBeenCalled()+ expect(discovery.agents.value).toEqual([])+ })++ test('deduplicates concurrent scans and notices removals on refresh', async () => {+ const pending = createDeferred<AgentLookup>()+ const scan = mock(() => pending.promise)+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: scan,+ install: async () => undefined+ })+ const first = discovery.refresh()+ const second = discovery.refresh()+ expect(scan).toHaveBeenCalledTimes(1)+ pending.resolve(lookup('gemini', 'codex-acp'))+ await Promise.all([first, second])+ expect(discovery.availableAgents.value).toHaveLength(2)+ scan.mockImplementation(async () => lookup())+ await discovery.refresh()+ expect(discovery.availableAgents.value).toHaveLength(0)+ })++ test('installs only on request, blocks duplicate installs, and rescans afterward', async () => {+ let installed = false+ const pending = createDeferred<undefined>()+ const install = mock(async (_agent: ACPAgentDef, _searchPath: string) => {+ await pending.promise+ installed = true+ })+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('claude', 'npm', ...(installed ? ['claude-agent-acp'] : [])),+ install+ })+ await discovery.refresh()+ expect(install).not.toHaveBeenCalled()+ const operation = discovery.install('claude-code')+ await discovery.install('claude-code')+ expect(install).toHaveBeenCalledTimes(1)+ expect(install.mock.calls[0]).toEqual([+ expect.objectContaining({ adapterPackage: '@agentclientprotocol/claude-agent-acp' }),+ '/test/bin'+ ])+ pending.resolve(undefined)+ await operation+ expect(discovery.availableAgents.value[0]?.definition.id).toBe('claude-code')+ expect(discovery.installing.value).toBeNull()+ expect(discovery.error.value).toBeNull()+ })++ test('failed installation remains retryable and does not publish raw errors', async () => {+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('codex', 'npm'),+ install: async () => {+ throw new Error('private npm backend error')+ }+ })+ await discovery.refresh()+ await discovery.install('codex')+ expect(discovery.error.value).toBe('install')+ expect(discovery.installing.value).toBeNull()+ expect(discovery.availableAgents.value).toEqual([])+ })++ test('requires npm for adapter setup but not for native ACP agents', async () => {+ const install = mock(async () => undefined)+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('claude', 'gemini'),+ install+ })+ await discovery.refresh()+ await discovery.install('claude-code')+ expect(discovery.error.value).toBe('npm')+ expect(install).not.toHaveBeenCalled()+ expect(discovery.availableAgents.value[0]?.definition.id).toBe('gemini-cli')+ })++ test('a failed scan preserves the last successful discovery and allows retry', async () => {+ const scan = mock(async () => lookup('gemini'))+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: scan,+ install: async () => undefined+ })+ await discovery.refresh()+ scan.mockImplementation(async () => {+ throw new Error('unavailable')+ })+ await discovery.refresh()+ expect(discovery.error.value).toBe('lookup')+ expect(discovery.scanning.value).toBe(false)+ expect(discovery.availableAgents.value[0]?.definition.id).toBe('gemini-cli')+ scan.mockImplementation(async () => lookup('gemini', 'codex-acp'))+ await discovery.refresh()+ expect(discovery.error.value).toBeNull()+ expect(discovery.availableAgents.value).toHaveLength(2)+ })+})++describe('Harness companion setup', () => {+ test('installs the companion once and rescans', async () => {+ let installed = false+ const installHarness = mock(async () => {+ installed = true+ })+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('npm', ...(installed ? ['openpencil-harness'] : [])),+ install: async () => undefined,+ installHarness+ })+ await discovery.refresh()+ expect(discovery.harnessAvailable.value).toBe(false)+ await discovery.setupHarness()+ expect(installHarness).toHaveBeenCalledWith('/test/bin')+ expect(discovery.harnessAvailable.value).toBe(true)+ expect(discovery.error.value).toBeNull()+ })++ test('updates a companion whose version does not match the app', async () => {+ let version = '0.12.0'+ const installHarness = mock(async () => {+ version = '0.0.1'+ })+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => ({+ ...lookup('npm', 'openpencil-harness'),+ versions: { '@open-pencil/harness': version }+ }),+ install: async () => undefined,+ installHarness+ })+ await discovery.refresh()+ expect(discovery.harnessOutdated.value).toBe(true)+ await discovery.setupHarness()+ expect(installHarness).toHaveBeenCalledTimes(1)+ expect(discovery.harnessOutdated.value).toBe(false)+ expect(discovery.error.value).toBeNull()+ })++ test('reports an update that left the old MCP server first on the path', async () => {+ const installBridge = mock(async () => undefined)+ const restartBridge = mock(async () => undefined)+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => ({+ searchPath: '/test/bin',+ executables: { npm: '/test/bin/npm', 'openpencil-mcp-http': '/home/me/.bun/bin/mcp' },+ versions: { '@open-pencil/mcp': '0.12.0' }+ }),+ install: async () => undefined,+ installBridge,+ restartBridge+ })+ await discovery.refresh()+ expect(discovery.canvasBridgeCommand.value).toStartWith('bun add -g @open-pencil/mcp@')+ await discovery.setupCanvasBridge()+ expect(installBridge).toHaveBeenCalledTimes(1)+ expect(restartBridge).not.toHaveBeenCalled()+ expect(discovery.error.value).toBe('canvas-install')+ })++ test('needs npm and reports a failed install without raw errors', async () => {+ const withoutNpm = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup(),+ install: async () => undefined,+ installHarness: async () => undefined+ })+ await withoutNpm.refresh()+ await withoutNpm.setupHarness()+ expect(withoutNpm.error.value).toBe('npm')+ const failing = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('npm'),+ install: async () => undefined,+ installHarness: async () => {+ throw new Error('private npm details')+ }+ })+ await failing.refresh()+ await failing.setupHarness()+ expect(failing.error.value).toBe('harness-install')+ })+})diff --git a/tests/app/ai/agents/native.test.ts b/tests/app/ai/agents/native.test.tsnew file mode 100644index 000000000..07e8b91ed--- /dev/null+++ b/tests/app/ai/agents/native.test.ts@@ -0,0 +1,96 @@+import { afterEach, expect, test } from 'bun:test'++import type { Channel } from '@tauri-apps/api/core'++import { ACP_AGENTS } from '@open-pencil/core/constants'++import { installAgentAdapter, lookupAgents } from '@/app/ai/agents/native'+import { createDeferred } from '@/app/runtime/deferred'++import { expectDefined } from '#tests/helpers/assert'+import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'++afterEach(clearTauriMocks)++test('validates native discovery responses', async () => {+ await mockTauriIPC((command) => {+ expect(command).toBe('agent_lookup')+ return {+ executables: { claude: '/bin/claude', npm: null },+ versions: { '@open-pencil/mcp': '0.15.1' },+ searchPath: '/bin'+ }+ })+ const lookup = await lookupAgents()+ expect(lookup.executables.claude).toBe('/bin/claude')+ expect(lookup.versions['@open-pencil/mcp']).toBe('0.15.1')+ await mockTauriIPC(() => ({ executables: { claude: true }, versions: {}, searchPath: '/bin' }))+ await expect(lookupAgents()).rejects.toThrow()+})++test.each([0, 1])('installs the selected adapter and handles exit code %i', async (code) => {+ const commands: string[] = []+ await mockTauriIPC((command, args) => {+ commands.push(command)+ expect(command).toBe('plugin:shell|spawn')+ const spawn = args as {+ program: string+ args: string[]+ options: { env: { PATH: string } }+ onEvent: Channel+ }+ expect(spawn.program).toBe('npm')+ expect(spawn.args).toEqual([+ 'install',+ '--global',+ '@agentclientprotocol/codex-acp',+ '--registry=https://registry.npmjs.org'+ ])+ expect(spawn.options.env.PATH).toBe('/agents/bin')+ queueMicrotask(() =>+ spawn.onEvent.onmessage({ event: 'Terminated', payload: { code, signal: null } })+ )+ return 42+ })+ const codex = expectDefined(+ ACP_AGENTS.find((agent) => agent.id === 'codex'),+ 'Codex'+ )+ const installation = installAgentAdapter(codex, '/agents/bin')+ if (code === 0) await installation+ else await expect(installation).rejects.toThrow('Adapter installation failed.')+ expect(commands).toEqual(['plugin:shell|spawn'])+})++test('rejects native agents before attempting an adapter install', async () => {+ const gemini = expectDefined(+ ACP_AGENTS.find((agent) => agent.id === 'gemini-cli'),+ 'Gemini CLI'+ )+ await expect(installAgentAdapter(gemini, '/bin')).rejects.toThrow(+ 'This agent does not need an adapter.'+ )+})++test('cleans up an installer that reports an error before its process handle arrives', async () => {+ const spawned = createDeferred<number>()+ const killed = createDeferred<undefined>()+ await mockTauriIPC((command, args) => {+ if (command === 'plugin:shell|kill') {+ expect(args).toMatchObject({ pid: 42 })+ killed.resolve(undefined)+ return+ }+ expect(command).toBe('plugin:shell|spawn')+ const { onEvent } = args as { onEvent: Channel }+ queueMicrotask(() => onEvent.onmessage({ event: 'Error', payload: 'private npm details' }))+ return spawned.promise+ })+ const codex = expectDefined(+ ACP_AGENTS.find((agent) => agent.id === 'codex'),+ 'Codex'+ )+ await expect(installAgentAdapter(codex, '/bin')).rejects.toThrow('Adapter installation failed.')+ spawned.resolve(42)+ await killed.promise+})diff --git a/tests/app/ai/agents/readiness.test.ts b/tests/app/ai/agents/readiness.test.tsnew file mode 100644index 000000000..aca41eafb--- /dev/null+++ b/tests/app/ai/agents/readiness.test.ts@@ -0,0 +1,62 @@+import { describe, expect, test } from 'bun:test'++import { createAgentDiscovery } from '@/app/ai/agents/discovery'+import type { AgentLookup } from '@/app/ai/agents/native'+import { AgentSetupError, assertAgentReady } from '@/app/ai/agents/readiness'++function discovery(lookup: () => Promise<AgentLookup>, enabled = true) {+ return createAgentDiscovery({ enabled, lookup, install: async () => undefined })+}++function installed(versions: AgentLookup['versions'] = {}, ...commands: string[]) {+ return async (): Promise<AgentLookup> => ({+ searchPath: '/test/bin',+ versions,+ executables: Object.fromEntries(commands.map((command) => [command, `/test/bin/${command}`]))+ })+}++async function problem(agent: 'acp' | 'pi', lookup: () => Promise<AgentLookup>) {+ try {+ await assertAgentReady(agent, discovery(lookup))+ return null+ } catch (error) {+ if (error instanceof AgentSetupError) return error.problem+ throw error+ }+}++describe('assertAgentReady', () => {+ test('lets a chat start when its companions match the app', async () => {+ const lookup = installed(+ { '@open-pencil/harness': '0.0.2', '@open-pencil/mcp': '0.0.2' },+ 'openpencil-harness',+ 'openpencil-mcp-http'+ )+ expect(await problem('pi', lookup)).toBeNull()+ expect(await problem('acp', lookup)).toBeNull()+ })++ test('names the missing or mismatched companion', async () => {+ expect(await problem('pi', installed({}, 'openpencil-mcp-http'))).toBe('companion-missing')+ expect(+ await problem('pi', installed({ '@open-pencil/harness': '0.12.0' }, 'openpencil-harness'))+ ).toBe('companion-outdated')+ expect(+ await problem('acp', installed({ '@open-pencil/mcp': '0.12.0' }, 'openpencil-mcp-http'))+ ).toBe('mcp-outdated')+ })++ test('only Pi needs the Harness companion', async () => {+ expect(await problem('acp', installed())).toBeNull()+ })++ test('does not block a chat when the computer cannot be checked', async () => {+ expect(+ await problem('pi', async () => {+ throw new Error('lookup failed')+ })+ ).toBeNull()+ await assertAgentReady('pi', discovery(installed(), false))+ })+})diff --git a/tests/app/ai/chat/submission/use.test.ts b/tests/app/ai/chat/submission/use.test.tsnew file mode 100644index 000000000..7878b3279--- /dev/null+++ b/tests/app/ai/chat/submission/use.test.ts@@ -0,0 +1,100 @@+import { describe, expect, mock, spyOn, test } from 'bun:test'++import type { Chat } from '@ai-sdk/vue'+import type { UIMessage } from 'ai'+import { ref, shallowRef } from 'vue'++import { AgentSetupError } from '@/app/ai/agents/readiness'+import { useChatSubmission } from '@/app/ai/chat/submission/use'+import type { EditorStore } from '@/app/editor/active-store'++import { asDouble } from '#tests/helpers/doubles'++const messages = ref({+ openSettings: 'Open settings',+ requestFailed: 'Request failed',+ visionUnavailable: 'Vision unavailable',+ runSetup: 'Run guided setup',+ agentSetup: {+ 'companion-missing': 'Companion missing',+ 'companion-outdated': 'Companion outdated',+ 'mcp-outdated': 'MCP outdated',+ 'pi-sign-in': 'Pi sign-in',+ 'pi-model': 'Pi model'+ }+})++function submission(ensureChat: () => Promise<Chat<UIMessage> | null>) {+ const reportError = mock(() => undefined)+ const openSetup = mock(() => undefined)+ const chat = useChatSubmission({+ chat: shallowRef<Chat<UIMessage> | null>(null),+ ensureChat,+ clearFailure: () => undefined,+ getEditor: () => ({}) as EditorStore,+ messages,+ reportError,+ openModelSettings: () => undefined,+ openSetup+ })+ return { chat, reportError, openSetup }+}++const message = { modelText: 'Draw a card', displayText: 'Draw a card', images: [], nodes: [] }++describe('useChatSubmission', () => {+ test('reports an unsent message so the composer can keep it', async () => {+ const { chat } = submission(async () => null)+ expect(await chat.submit(message)).toBe(false)+ })++ test('names the setup problem that stopped an agent chat and offers guided setup', async () => {+ const { chat, reportError, openSetup } = submission(async () => {+ throw new AgentSetupError('mcp-outdated')+ })+ expect(await chat.submit(message)).toBe(false)+ expect(reportError).toHaveBeenCalledWith('MCP outdated', {+ label: 'Run guided setup',+ run: openSetup+ })+ })++ test('keeps the previews of an unsent message for the composer to take back', async () => {+ const revoke = spyOn(URL, 'revokeObjectURL')+ try {+ const { chat } = submission(async () => null)+ const image = { file: new File(['png'], 'card.png'), previewURL: 'blob:card' }+ expect(await chat.submit({ ...message, images: [image] })).toBe(false)+ expect(revoke).not.toHaveBeenCalled()+ } finally {+ revoke.mockRestore()+ }+ })++ test('hands back a message that failed before reaching the chat', async () => {+ const target = fakeChat()+ const { chat } = submission(async () => target)+ // The editor stand-in cannot snapshot the referenced layer, which fails before sending.+ const node = { id: '1:2', name: 'Card', type: 'FRAME' as const }+ expect(await chat.submit({ ...message, nodes: [node] })).toBe(false)+ expect(target.messages).toEqual([])+ })++ test('takes back a message whose images could not be prepared', async () => {+ const revoke = spyOn(URL, 'revokeObjectURL')+ try {+ const target = fakeChat()+ const { chat } = submission(async () => target)+ const image = { file: new File(['not an image'], 'card.png'), previewURL: 'blob:card' }+ expect(await chat.submit({ ...message, images: [image] })).toBe(false)+ expect(target.messages).toEqual([])+ expect(revoke).not.toHaveBeenCalled()+ } finally {+ revoke.mockRestore()+ }+ })+})++function fakeChat(sendMessage: () => Promise<void> = async () => undefined): Chat<UIMessage> {+ return asDouble<Chat<UIMessage>>({ messages: [], status: 'ready', sendMessage })+}diff --git a/tests/app/ai/chat/turns.test.ts b/tests/app/ai/chat/turns.test.tsindex 03254f7e5..a8d05a7f9 100644--- a/tests/app/ai/chat/turns.test.ts+++ b/tests/app/ai/chat/turns.test.ts@@ -104,9 +104,22 @@ function submission(chat: ReturnType<typeof fakeChat>) {ensureChat: async () => chat,clearFailure: () => undefined,getEditor: () => store,- messages: shallowRef({ openSettings: '', requestFailed: '', visionUnavailable: '' }),+ messages: shallowRef({+ openSettings: '',+ requestFailed: '',+ visionUnavailable: '',+ runSetup: '',+ agentSetup: {+ 'companion-missing': '',+ 'companion-outdated': '',+ 'mcp-outdated': '',+ 'pi-sign-in': '',+ 'pi-model': ''+ }+ }),reportError: () => undefined,openModelSettings: () => undefined,+ openSetup: () => undefined,// Like the history's flush, this snapshots the messages synchronously, so a message that// cannot be cloned throws here instead of becoming a rejected promise.flush: () => {diff --git a/tests/app/ai/harness/pi-settings.test.ts b/tests/app/ai/harness/pi-settings.test.tsnew file mode 100644index 000000000..392123e5b--- /dev/null+++ b/tests/app/ai/harness/pi-settings.test.ts@@ -0,0 +1,20 @@+import { describe, expect, test } from 'bun:test'++import { parsePiSettings } from '@/app/ai/harness/pi-settings'++describe('parsePiSettings', () => {+ test('reads the default model', () => {+ expect(+ parsePiSettings(+ JSON.stringify({ defaultProvider: 'openai-codex', defaultModel: 'openai-codex/gpt-5.6' })+ )+ ).toBe('openai-codex/gpt-5.6')+ })++ test('ignores missing, empty, or malformed settings', () => {+ expect(parsePiSettings('{}')).toBeNull()+ expect(parsePiSettings(JSON.stringify({ defaultModel: ' ' }))).toBeNull()+ expect(parsePiSettings(JSON.stringify({ defaultModel: 42 }))).toBeNull()+ expect(parsePiSettings('not json')).toBeNull()+ })+})diff --git a/tests/app/ai/models/settings/onboarding/agents.test.ts b/tests/app/ai/models/settings/onboarding/agents.test.tsnew file mode 100644index 000000000..bb63455c6--- /dev/null+++ b/tests/app/ai/models/settings/onboarding/agents.test.ts@@ -0,0 +1,43 @@+import { describe, expect, mock, test } from 'bun:test'++import { createAgentDiscovery } from '@/app/ai/agents/discovery'+import type { AgentLookup } from '@/app/ai/agents/native'+import { useOnboardingAgents } from '@/app/ai/models/settings/onboarding/agents'++function lookup(...commands: string[]): AgentLookup {+ return {+ searchPath: '/test/bin',+ versions: {},+ executables: Object.fromEntries(commands.map((command) => [command, `/test/bin/${command}`]))+ }+}++describe('useOnboardingAgents', () => {+ test('installs the Harness companion for Pi and reads Pi’s default model', async () => {+ let installed = false+ const installHarness = mock(async () => {+ installed = true+ })+ const discovery = createAgentDiscovery({+ enabled: true,+ lookup: async () => lookup('npm', ...(installed ? ['openpencil-harness'] : [])),+ install: async () => undefined,+ installHarness+ })+ const agents = useOnboardingAgents(discovery, async () => ({+ agentDir: '/home/test/.pi/agent',+ defaultModel: 'openai-codex/gpt-5.6',+ signedIn: true+ }))+ await agents.refreshAgents()+ expect(agents.piSetup('harness:pi')).toMatchObject({+ companion: false,+ npm: true,+ defaultModel: 'openai-codex/gpt-5.6'+ })+ await agents.installAgent('harness:pi')+ expect(installHarness).toHaveBeenCalledTimes(1)+ expect(agents.piSetup('harness:pi')?.companion).toBe(true)+ expect(agents.piSetup('acp:codex')).toBeUndefined()+ })+})diff --git a/tests/app/ai/models/settings/onboarding/apply.test.ts b/tests/app/ai/models/settings/onboarding/apply.test.tsnew file mode 100644index 000000000..e941ce4ad--- /dev/null+++ b/tests/app/ai/models/settings/onboarding/apply.test.ts@@ -0,0 +1,294 @@+import { describe, expect, test } from 'bun:test'++import { parseAIModelSettings, type AIModelSettings } from '@/app/ai/models'+import {+ applyOnboardingPlan,+ isUnconfiguredModelSettings+} from '@/app/ai/models/settings/onboarding/apply'+import { currentOnboardingModels } from '@/app/ai/models/settings/onboarding/current'+import { planOnboarding, type OnboardingAnswers } from '@/app/ai/models/settings/onboarding/plan'++import { defaultModel, isFastToolModel } from '#tests/helpers/ai/model-catalog'++function freshInstall(): AIModelSettings {+ return {+ version: 1,+ connections: [+ {+ id: 'connection-default',+ providerID: 'openai-compatible',+ customBaseURL: '',+ customAPIType: 'completions',+ credentialProfileId: 'default'+ }+ ],+ models: [+ {+ id: 'model-default',+ name: 'Design model',+ connectionId: 'connection-default',+ modelID: '',+ customModelID: '',+ maxOutputTokens: 16_384,+ thinkingLevel: 'default',+ capabilities: ['tools']+ }+ ],+ assignments: { design: 'model-default', review: 'design', fast: 'design', vision: null }+ }+}++function configured(): AIModelSettings {+ return {+ version: 1,+ connections: [+ {+ id: 'connection-anthropic',+ providerID: 'anthropic',+ customBaseURL: '',+ customAPIType: 'completions',+ credentialProfileId: 'connection-anthropic'+ }+ ],+ models: [+ {+ id: 'model-opus',+ name: 'Claude Opus 5',+ connectionId: 'connection-anthropic',+ modelID: 'claude-opus-5',+ customModelID: '',+ maxOutputTokens: 32_000,+ thinkingLevel: 'high',+ capabilities: ['tools', 'vision']+ }+ ],+ assignments: { design: 'model-opus', review: 'model-opus', fast: null, vision: 'design' }+ }+}++function sequentialIds() {+ let next = 0+ return () => `id-${++next}`+}++function apply(+ settings: AIModelSettings,+ answers: OnboardingAnswers,+ details: Parameters<typeof applyOnboardingPlan>[0]['details'] = {}+) {+ return applyOnboardingPlan({+ settings,+ plan: planOnboarding(answers, {+ agentsAvailable: true,+ current: currentOnboardingModels(settings)+ }),+ details,+ createId: sequentialIds()+ })+}++describe('applyOnboardingPlan', () => {+ test('replaces the empty fresh-install profile with the planned models', () => {+ const { settings, connectionIds } = apply(freshInstall(), {+ goals: ['design', 'vision'],+ access: ['openrouter'],+ spending: 'existing'+ })+ expect(settings.models).toEqual([+ expect.objectContaining({+ id: 'model-id-2',+ connectionId: 'connection-id-1',+ modelID: defaultModel('openrouter'),+ capabilities: ['tools', 'vision']+ }),+ expect.objectContaining({ id: 'model-id-3', connectionId: 'connection-id-1' })+ ])+ expect(isFastToolModel('openrouter', settings.models[1]?.modelID ?? '')).toBe(true)+ expect(settings.connections.map((connection) => connection.id)).toEqual(['connection-id-1'])+ expect(settings.assignments).toEqual({+ design: 'model-id-2',+ review: 'design',+ fast: 'model-id-3',+ vision: 'design'+ })+ expect(connectionIds).toEqual({ openrouter: 'connection-id-1' })+ })++ test('produces settings the store accepts unchanged', () => {+ const { settings } = apply(freshInstall(), {+ goals: ['design', 'vision'],+ access: ['acp:claude-code', 'google'],+ spending: 'existing'+ })+ expect(parseAIModelSettings(settings)).toEqual(settings)+ })++ test('clears roles an agent cannot take when design moves to an agent', () => {+ const { settings } = apply(freshInstall(), {+ goals: ['design'],+ access: ['acp:codex'],+ spending: 'existing'+ })+ expect(settings.assignments).toMatchObject({ review: null, fast: null, vision: null })+ expect(parseAIModelSettings(settings)?.assignments).toEqual(settings.assignments)+ })++ test('reuses a matching connection and profile and keeps advanced settings', () => {+ const before = configured()+ before.models.push({+ id: 'model-sonnet',+ name: 'Claude Sonnet 5',+ connectionId: 'connection-anthropic',+ modelID: 'claude-sonnet-5',+ customModelID: '',+ maxOutputTokens: 64_000,+ thinkingLevel: 'low',+ capabilities: ['tools', 'vision']+ })+ before.assignments = { design: 'model-sonnet', review: 'model-opus', fast: null, vision: null }+ const { settings, connectionIds } = apply(before, {+ goals: ['design'],+ access: ['anthropic'],+ spending: 'existing'+ })+ expect(settings.connections).toEqual(before.connections)+ expect(settings.models).toEqual(before.models)+ // Review and fast work are never asked about, so an explicit none stays none.+ expect(settings.assignments).toEqual(before.assignments)+ expect(connectionIds).toEqual({})++ const again = apply(settings, {+ goals: ['design'],+ access: ['anthropic'],+ spending: 'existing'+ })+ expect(again.settings).toEqual(settings)+ })++ test('reuses a catalog profile it would otherwise create', () => {+ const before = freshInstall()+ before.connections.push({+ id: 'connection-anthropic',+ providerID: 'anthropic',+ customBaseURL: '',+ customAPIType: 'completions',+ credentialProfileId: 'connection-anthropic'+ })+ before.models.push({+ id: 'model-sonnet',+ name: 'Sonnet',+ connectionId: 'connection-anthropic',+ modelID: defaultModel('anthropic'),+ customModelID: '',+ maxOutputTokens: 64_000,+ thinkingLevel: 'low',+ capabilities: ['tools', 'vision']+ })+ const { settings, connectionIds } = apply(before, {+ goals: ['design'],+ access: ['anthropic'],+ spending: 'existing'+ })+ expect(settings.assignments.design).toBe('model-sonnet')+ expect(settings.models.find((profile) => profile.id === 'model-sonnet')).toMatchObject({+ maxOutputTokens: 64_000,+ thinkingLevel: 'low'+ })+ expect(connectionIds).toEqual({ anthropic: 'connection-anthropic' })+ })++ test('keeps a working vision route for roles that were not asked about', () => {+ const before = configured()+ const { settings } = apply(before, {+ goals: ['vision'],+ access: ['openai'],+ spending: 'existing'+ })+ expect(settings.assignments).toEqual(before.assignments)+ expect(settings.models).toEqual(before.models)+ })++ test('stores the server address and model the person entered', () => {+ const { settings } = apply(+ freshInstall(),+ { goals: ['design'], access: ['openai-compatible'], spending: 'existing' },+ {+ 'openai-compatible': {+ customBaseURL: ' http://localhost:11434/v1 ',+ customModelID: 'qwen3-coder:30b'+ }+ }+ )+ expect(settings.connections).toEqual([+ expect.objectContaining({+ providerID: 'openai-compatible',+ customBaseURL: 'http://localhost:11434/v1'+ })+ ])+ expect(settings.models).toEqual([+ expect.objectContaining({ name: 'qwen3-coder:30b', customModelID: 'qwen3-coder:30b' })+ ])+ })+})++describe('isUnconfiguredModelSettings', () => {+ test('recognizes only the empty fresh-install settings', () => {+ expect(isUnconfiguredModelSettings(freshInstall())).toBe(true)+ expect(isUnconfiguredModelSettings(configured())).toBe(false)+ const server = freshInstall()+ server.connections[0].customBaseURL = 'http://localhost:11434/v1'+ expect(isUnconfiguredModelSettings(server)).toBe(false)+ })+})++describe('applyOnboardingPlan with configured models', () => {+ test('keeps a configured profile with its own settings', () => {+ const before = configured()+ const { settings } = apply(before, {+ goals: ['design'],+ access: ['anthropic'],+ spending: 'existing'+ })+ expect(settings).toEqual(before)+ })++ test('does not give the vision role to a matching profile without image input', () => {+ const before = configured()+ before.models.push({+ id: 'model-gpt-text',+ name: 'GPT-5.6 text',+ connectionId: 'connection-openai',+ modelID: '',+ customModelID: 'gpt-5.6',+ maxOutputTokens: 16_384,+ thinkingLevel: 'default',+ capabilities: ['tools']+ })+ before.connections.push({+ id: 'connection-openai',+ providerID: 'openai',+ customBaseURL: '',+ customAPIType: 'completions',+ credentialProfileId: 'connection-openai'+ })+ // Opus cannot review images here, so vision has to come from OpenAI.+ before.models[0].capabilities = ['tools']+ before.assignments.vision = null+ const { settings } = apply(before, {+ goals: ['vision'],+ access: ['openai'],+ spending: 'existing'+ })+ const vision = settings.models.find((profile) => profile.id === settings.assignments.vision)+ expect(vision?.id).not.toBe('model-gpt-text')+ expect(vision?.capabilities).toContain('vision')+ })++ test('clears an explicit vision assignment to a profile without image input', () => {+ const before = configured()+ before.models[0].capabilities = ['tools']+ before.assignments.vision = 'model-opus'+ const { settings } = apply(before, { goals: ['design'], access: [], spending: 'existing' })+ expect(settings.assignments.vision).toBeNull()+ })+})diff --git a/tests/app/ai/models/settings/onboarding/connections.test.ts b/tests/app/ai/models/settings/onboarding/connections.test.tsnew file mode 100644index 000000000..2a435cd6d--- /dev/null+++ b/tests/app/ai/models/settings/onboarding/connections.test.ts@@ -0,0 +1,65 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'++import {+ modelSettingsSnapshot,+ replaceAIModelSettings,+ type AIModelSettings+} from '@/app/ai/models'+import { existingOnboardingConnection } from '@/app/ai/models/settings/onboarding/connections'++let original: AIModelSettings++beforeEach(() => {+ original = modelSettingsSnapshot()+ replaceAIModelSettings({+ version: 1,+ connections: [+ {+ id: 'connection-proxy',+ providerID: 'openai-compatible',+ customBaseURL: 'https://proxy.example/v1',+ customAPIType: 'responses',+ credentialProfileId: 'connection-proxy'+ },+ {+ id: 'connection-openai',+ providerID: 'openai',+ customBaseURL: '',+ customAPIType: 'completions',+ credentialProfileId: 'connection-openai'+ }+ ],+ models: [+ {+ id: 'model-proxy',+ name: 'Proxy',+ connectionId: 'connection-proxy',+ modelID: '',+ customModelID: 'team/design',+ maxOutputTokens: 16_384,+ thinkingLevel: 'default',+ capabilities: ['tools']+ }+ ],+ assignments: { design: 'model-proxy', review: null, fast: null, vision: null }+ })+})++afterEach(() => replaceAIModelSettings(original))++describe('existingOnboardingConnection', () => {+ test('matches a server only at the address being entered', () => {+ expect(existingOnboardingConnection('openai-compatible')?.id).toBe('connection-proxy')+ expect(+ existingOnboardingConnection('openai-compatible', ' https://proxy.example/v1 ')?.id+ ).toBe('connection-proxy')+ expect(existingOnboardingConnection('openai-compatible', 'http://localhost:11434/v1')).toBe(+ null+ )+ })++ test('matches an API account only without a custom address', () => {+ expect(existingOnboardingConnection('openai')?.id).toBe('connection-openai')+ expect(existingOnboardingConnection('anthropic')).toBeNull()+ })+})diff --git a/tests/app/ai/models/settings/onboarding/plan.test.ts b/tests/app/ai/models/settings/onboarding/plan.test.tsnew file mode 100644index 000000000..029af8595--- /dev/null+++ b/tests/app/ai/models/settings/onboarding/plan.test.ts@@ -0,0 +1,278 @@+import { describe, expect, test } from 'bun:test'++import {+ uncoveredGoals,+ planOnboarding,+ roleChoiceKey,+ roleOptions,+ type OnboardingAnswers,+ type OnboardingPlan+} from '@/app/ai/models/settings/onboarding/plan'++import { defaultModel, isFastToolModel } from '#tests/helpers/ai/model-catalog'++const desktop = { agentsAvailable: true }+const browser = { agentsAvailable: false }++function answers(overrides: Partial<OnboardingAnswers>): OnboardingAnswers {+ return { goals: ['design'], access: [], spending: 'existing', ...overrides }+}++function plannedModelID(choice: OnboardingPlan['fast']): string {+ return typeof choice === 'object' && choice !== null ? choice.modelID : ''+}++describe('planOnboarding', () => {+ test('uses an agent the person already has for design', () => {+ const plan = planOnboarding(answers({ access: ['acp:codex'] }), desktop)+ expect(plan.design).toMatchObject({ providerID: 'acp:codex', modelID: '' })+ expect(plan.connections).toEqual(['acp:codex'])+ })++ test('runs design on Pi and takes the other roles from an API account', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['harness:pi', 'openai'] }),+ desktop+ )+ expect(plan.design).toMatchObject({ providerID: 'harness:pi', modelID: '' })+ expect(plan.vision).toMatchObject({ providerID: 'openai' })+ expect(plan.review).not.toBe('design')+ expect(plan.connections).toEqual(['harness:pi', 'openai'])+ })++ test('ignores agents outside the desktop app', () => {+ const plan = planOnboarding(answers({ access: ['acp:claude-code', 'openai'] }), browser)+ expect(plan.design).toMatchObject({ providerID: 'openai', modelID: defaultModel('openai') })+ })++ test('reuses a vision-capable design model for visual review', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['anthropic'] }),+ desktop+ )+ expect(plan.design).toMatchObject({+ providerID: 'anthropic',+ modelID: defaultModel('anthropic')+ })+ expect(plan.vision).toBe('design')+ expect(plan.connections).toEqual(['anthropic'])+ })++ test('takes visual review from an API account when design runs on an agent', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['acp:claude-code', 'google'] }),+ desktop+ )+ expect(plan.design).toMatchObject({ providerID: 'acp:claude-code' })+ expect(plan.vision).toMatchObject({ providerID: 'google', modelID: defaultModel('google') })+ expect(plan.connections).toEqual(['acp:claude-code', 'google'])+ })++ test('leaves visual review unassigned without pay-as-you-go access', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['acp:codex'] }),+ desktop+ )+ expect(plan.vision).toBeNull()+ expect(plan.connections).toEqual(['acp:codex'])+ })++ test('recommends OpenRouter when pay-as-you-go is allowed and nothing else covers a role', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['acp:codex'], spending: 'metered' }),+ desktop+ )+ expect(plan.vision).toMatchObject({ providerID: 'openrouter' })+ expect(planOnboarding(answers({ spending: 'metered' }), browser).design).toMatchObject({+ providerID: 'openrouter',+ modelID: defaultModel('openrouter')+ })+ })++ test('proposes nothing when no access is selected and spending is not allowed', () => {+ const plan = planOnboarding(answers({ goals: ['design', 'vision'] }), desktop)+ expect(plan).toEqual({ design: null, vision: null, review: null, fast: null, connections: [] })+ })++ test('uses a server with a model it names itself and no assumed vision', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['openai-compatible'] }),+ desktop+ )+ expect(plan.design).toMatchObject({ providerID: 'openai-compatible', modelID: '' })+ expect(plan.vision).toBeNull()+ })++ test('plans only the roles that were asked for', () => {+ const plan = planOnboarding(answers({ goals: ['vision'], access: ['openai'] }), desktop)+ expect(plan.design).toBeNull()+ expect(plan.vision).toMatchObject({ providerID: 'openai' })+ })+})++describe('planOnboarding with configured models', () => {+ const opus = {+ providerID: 'anthropic' as const,+ modelID: 'claude-opus-5',+ name: 'Claude Opus 5',+ capabilities: ['tools' as const, 'vision' as const],+ profileId: 'model-opus' as const+ }+ const zai = {+ providerID: 'zai' as const,+ modelID: 'glm-5v-turbo',+ name: 'GLM-5V-Turbo',+ capabilities: ['tools' as const, 'vision' as const],+ profileId: 'model-glm' as const+ }++ test('keeps a configured design model while its access is still selected', () => {+ const plan = planOnboarding(answers({ access: ['anthropic'] }), {+ ...desktop,+ current: { configured: true, design: opus, vision: null, review: null, fast: null }+ })+ expect(plan.design).toBe(opus)+ expect(plan.connections).toEqual([])+ })++ test('replaces a configured design model whose access was deselected', () => {+ const plan = planOnboarding(answers({ access: ['openai'] }), {+ ...desktop,+ current: { configured: true, design: opus, vision: null, review: null, fast: null }+ })+ expect(plan.design).toMatchObject({ providerID: 'openai' })+ expect(plan.design?.profileId).toBeUndefined()+ })++ test('keeps models from providers onboarding does not offer', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['openai-compatible'] }),+ {+ ...desktop,+ current: { configured: true, design: null, vision: zai, review: null, fast: null }+ }+ )+ expect(plan.vision).toBe(zai)+ expect(plan.connections).toEqual(['openai-compatible'])+ })++ test('keeps a configured vision model when nothing new covers visual review', () => {+ const plan = planOnboarding(answers({ goals: ['design', 'vision'], access: ['acp:codex'] }), {+ ...desktop,+ current: {+ configured: true,+ design: null,+ vision: { ...opus, profileId: 'model-opus' },+ review: null,+ fast: null+ }+ })+ expect(plan.design).toMatchObject({ providerID: 'acp:codex' })+ expect(plan.vision).toMatchObject({ profileId: 'model-opus' })+ })+})++describe('planOnboarding for review and fast work', () => {+ test('gives fast work the provider model tagged as fast', () => {+ const plan = planOnboarding(answers({ access: ['openrouter'] }), desktop)+ expect(plan.review).toBe('design')+ expect(plan.fast).toMatchObject({ providerID: 'openrouter' })+ expect(isFastToolModel('openrouter', plannedModelID(plan.fast))).toBe(true)+ })++ test('follows the design model when its provider has no separate fast model', () => {+ expect(planOnboarding(answers({ access: ['anthropic'] }), desktop).fast).toBe('design')+ })++ test('uses the API vision model for review and fast work behind an agent', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['acp:codex', 'openai'] }),+ desktop+ )+ expect(plan.vision).toMatchObject({ providerID: 'openai', modelID: defaultModel('openai') })+ expect(plan.review).toMatchObject({ providerID: 'openai', modelID: defaultModel('openai') })+ expect(plan.fast).toMatchObject({ providerID: 'openai' })+ expect(isFastToolModel('openai', plannedModelID(plan.fast))).toBe(true)+ expect(planOnboarding(answers({ access: ['acp:codex'] }), desktop)).toMatchObject({+ review: null,+ fast: null+ })+ })++ test('keeps configured review and fast choices, including none', () => {+ const plan = planOnboarding(answers({ access: ['openrouter'] }), {+ ...desktop,+ current: { configured: true, design: null, vision: null, review: null, fast: 'design' }+ })+ expect(plan.review).toBeNull()+ expect(plan.fast).toBe('design')+ })+})++describe('roleOptions', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['acp:claude-code', 'openrouter'] }),+ desktop+ )++ test('offers an agent only for the design role', () => {+ expect(roleOptions('design', plan, []).map(roleChoiceKey)).toContain('acp:claude-code::')+ expect(roleOptions('review', plan, []).map(roleChoiceKey)).not.toContain('acp:claude-code::')+ })++ test('offers only image-capable models for vision and none instead of an agent design', () => {+ const vision = roleOptions('vision', plan, [])+ expect(vision).toContain(null)+ expect(vision).not.toContain('design')+ for (const option of vision) {+ if (option && option !== 'design') expect(option.capabilities).toContain('vision')+ }+ })++ test('offers same as design when the design model can take the role', () => {+ const api = planOnboarding(answers({ access: ['openrouter'] }), desktop)+ expect(roleOptions('fast', api, []).slice(0, 2)).toEqual(['design', null])+ })+})++describe('uncoveredGoals', () => {+ test('lists requested goals the selected access cannot cover', () => {+ expect(+ uncoveredGoals(answers({ goals: ['design', 'vision'], access: ['acp:codex'] }), desktop)+ ).toEqual(['vision'])+ expect(uncoveredGoals(answers({ goals: ['design'] }), desktop)).toEqual(['design'])+ })++ test('ignores the pay-as-you-go choice, which is how setup offers to fill the gap', () => {+ const metered = answers({+ goals: ['design', 'vision'],+ access: ['acp:codex'],+ spending: 'metered'+ })+ expect(uncoveredGoals(metered, desktop)).toEqual(['vision'])+ expect(planOnboarding(metered, desktop).vision).toMatchObject({ providerID: 'openrouter' })+ })+})++describe('server vision', () => {+ test('covers visual review with a server whose model reads images', () => {+ const plan = planOnboarding(+ answers({ goals: ['design', 'vision'], access: ['openai-compatible'], serverVision: true }),+ desktop+ )+ expect(plan.design).toMatchObject({ capabilities: ['tools', 'vision'] })+ expect(plan.vision).toBe('design')+ })++ test('prefers the local server for vision behind an agent', () => {+ const plan = planOnboarding(+ answers({+ goals: ['design', 'vision'],+ access: ['acp:codex', 'openai', 'openai-compatible'],+ serverVision: true+ }),+ desktop+ )+ expect(plan.vision).toMatchObject({ providerID: 'openai-compatible' })+ })+})diff --git a/tests/app/ai/providers/openrouter/key.test.ts b/tests/app/ai/providers/openrouter/key.test.tsnew file mode 100644index 000000000..88ee3268d--- /dev/null+++ b/tests/app/ai/providers/openrouter/key.test.ts@@ -0,0 +1,36 @@+import { describe, expect, test } from 'bun:test'++import {+ fetchOpenRouterKeyInfo,+ OPENROUTER_KEY_INFO_URL,+ OpenRouterKeyError+} from '@/app/ai/providers/openrouter/key'++import { fetchStub } from '#tests/helpers/fetch'++describe('fetchOpenRouterKeyInfo', () => {+ test('reports the key label and free tier with the key as a bearer token', async () => {+ const requests: { url: string; authorization: string | null }[] = []+ const fetchImpl = fetchStub(async (input, init) => {+ const url = String(input)+ requests.push({ url, authorization: new Headers(init?.headers).get('authorization') })+ return Response.json({ data: { label: 'OpenPencil', is_free_tier: true, usage: 0 } })+ })+ expect(await fetchOpenRouterKeyInfo('sk-or-v1-test', fetchImpl)).toEqual({+ label: 'OpenPencil',+ freeTier: true+ })+ expect(requests).toEqual([+ { url: OPENROUTER_KEY_INFO_URL, authorization: 'Bearer sk-or-v1-test' }+ ])+ })++ test('rejects a key OpenRouter does not accept', async () => {+ const rejected = fetchStub(async () =>+ Response.json({ error: { code: 401, message: 'Invalid credentials' } }, { status: 401 })+ )+ await expect(fetchOpenRouterKeyInfo('sk-or-bad', rejected)).rejects.toBeInstanceOf(+ OpenRouterKeyError+ )+ })+})diff --git a/tests/app/ai/providers/openrouter/oauth.test.ts b/tests/app/ai/providers/openrouter/oauth.test.tsnew file mode 100644index 000000000..6e7d5cf34--- /dev/null+++ b/tests/app/ai/providers/openrouter/oauth.test.ts@@ -0,0 +1,76 @@+import { describe, expect, test } from 'bun:test'++import {+ exchangeOpenRouterCode,+ openRouterAuthorizationURL,+ OpenRouterKeyExchangeError,+ OPENROUTER_KEYS_URL,+ parseOpenRouterCallback,+ pkceChallenge+} from '@/app/ai/providers/openrouter/oauth'++import { fetchStub } from '#tests/helpers/fetch'++describe('OpenRouter OAuth PKCE', () => {+ test('derives the S256 challenge from the RFC 7636 example verifier', async () => {+ expect(await pkceChallenge('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')).toBe(+ 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'+ )+ })++ test('builds the authorization URL with the challenge, state, and key label', () => {+ const url = new URL(+ openRouterAuthorizationURL(+ 'http://localhost:4123/callback',+ { verifier: 'v', challenge: 'c', state: 's' },+ 'OpenPencil'+ )+ )+ expect(url.origin + url.pathname).toBe('https://openrouter.ai/auth')+ expect(Object.fromEntries(url.searchParams)).toEqual({+ callback_url: 'http://localhost:4123/callback',+ code_challenge: 'c',+ code_challenge_method: 'S256',+ state: 's',+ key_label: 'OpenPencil'+ })+ })++ test('accepts only the callback for the current attempt', () => {+ expect(parseOpenRouterCallback('?code=abc&state=s1', 's1')).toEqual({ ok: true, code: 'abc' })+ expect(parseOpenRouterCallback('?code=abc&state=other', 's1')).toEqual({+ ok: false,+ reason: 'mismatch'+ })+ expect(parseOpenRouterCallback('?state=s1', 's1')).toEqual({ ok: false, reason: 'cancelled' })+ })++ test('exchanges the code and verifier for a key', async () => {+ const requests: { url: string; body: unknown }[] = []+ const fetchImpl = fetchStub(async (input, init) => {+ const url = String(input)+ requests.push({ url, body: JSON.parse(String(init?.body)) })+ return Response.json({ key: 'sk-or-v1-test' })+ })+ expect(await exchangeOpenRouterCode('abc', 'verifier', fetchImpl)).toBe('sk-or-v1-test')+ expect(requests).toEqual([+ {+ url: OPENROUTER_KEYS_URL,+ body: { code: 'abc', code_verifier: 'verifier', code_challenge_method: 'S256' }+ }+ ])+ })++ test('reports a rejected or empty exchange', async () => {+ const rejected = fetchStub(async () =>+ Response.json({ error: { message: 'Invalid code' } }, { status: 400 })+ )+ await expect(exchangeOpenRouterCode('abc', 'v', rejected)).rejects.toBeInstanceOf(+ OpenRouterKeyExchangeError+ )+ const empty = fetchStub(async () => Response.json({}))+ await expect(exchangeOpenRouterCode('abc', 'v', empty)).rejects.toBeInstanceOf(+ OpenRouterKeyExchangeError+ )+ })+})diff --git a/tests/e2e/native/agents.spec.ts b/tests/e2e/native/agents.spec.tsnew file mode 100644index 000000000..2dc3c81fa--- /dev/null+++ b/tests/e2e/native/agents.spec.ts@@ -0,0 +1,27 @@+import { strict as assert } from 'node:assert'++import { invokeNative } from '#tests/helpers/tauri/invoke'++interface AgentLookup {+ executables: Record<string, string | null>+ versions: Record<string, string | null>+ searchPath: string+}++describe('native agent discovery', () => {+ it('answers agent discovery through the desktop shell', async () => {+ await browser.waitUntil(+ async () => browser.execute(() => Boolean(window.openPencil?.getStore?.())),+ { timeout: 30_000, timeoutMsg: 'OpenPencil editor did not initialize' }+ )+ const lookup = await invokeNative<AgentLookup>('agent_lookup')+ assert.ok(Object.keys(lookup.executables).length > 0)+ for (const path of Object.values(lookup.executables)) {+ assert.ok(path === null || path.length > 0)+ }+ for (const version of Object.values(lookup.versions)) {+ assert.ok(version === null || /^\d+\.\d+\.\d+/.test(version))+ }+ assert.ok(lookup.searchPath.length > 0)+ })+})diff --git a/tests/e2e/settings/ai-setup-first-run.spec.ts b/tests/e2e/settings/ai-setup-first-run.spec.tsnew file mode 100644index 000000000..edd811fbc--- /dev/null+++ b/tests/e2e/settings/ai-setup-first-run.spec.ts@@ -0,0 +1,73 @@+import { expect, test } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++// `?test` suppresses the first-run offer, so these load the app as a person would, with none+// of the stored preferences the other browser tests start from.+test.use({ storageState: { cookies: [], origins: [] } })++test('a fresh install offers guided AI setup once and remembers skipping it', async ({ page }) => {+ await page.goto('/')+ // The offer is made while the workspace starts, so it is open once the canvas is ready.+ await new CanvasHelper(page).waitForInit()+ const setup = page.getByTestId('ai-setup-dialog')+ await expect(setup.getByRole('heading', { name: 'Welcome to OpenPencil' })).toBeVisible()+ await setup.getByRole('button', { name: 'Start designing' }).click()+ await expect(setup).toHaveCount(0)++ await page.reload()+ await new CanvasHelper(page).waitForInit()+ await expect(setup).toHaveCount(0)+})++const CONFIGURED_MODEL_SETTINGS = {+ version: 1,+ connections: [+ {+ id: 'connection-anthropic',+ providerID: 'anthropic',+ customBaseURL: '',+ customAPIType: 'completions',+ credentialProfileId: 'connection-anthropic'+ }+ ],+ models: [+ {+ id: 'model-sonnet',+ name: 'Claude Sonnet 5',+ connectionId: 'connection-anthropic',+ modelID: 'claude-sonnet-5',+ customModelID: '',+ capabilities: ['tools', 'vision']+ }+ ],+ assignments: { design: 'model-sonnet', review: 'design', fast: 'design', vision: 'design' }+}++test.describe('an install with a configured model', () => {+ test.use({+ storageState: async ({ baseURL }, use) => {+ if (!baseURL) throw new Error('Browser test baseURL is required')+ await use({+ cookies: [],+ origins: [+ {+ origin: new URL(baseURL).origin,+ localStorage: [+ {+ name: 'open-pencil:ai-model-settings',+ value: JSON.stringify(CONFIGURED_MODEL_SETTINGS)+ }+ ]+ }+ ]+ })+ }+ })++ test('never sees the first-run offer', async ({ page }) => {+ await page.goto('/')+ await new CanvasHelper(page).waitForInit()+ await expect(page.getByTestId('ai-setup-dialog')).toHaveCount(0)+ })+})diff --git a/tests/e2e/settings/ai-setup.spec.ts b/tests/e2e/settings/ai-setup.spec.tsnew file mode 100644index 000000000..0bc637647--- /dev/null+++ b/tests/e2e/settings/ai-setup.spec.ts@@ -0,0 +1,181 @@+import { expect, test, type BrowserContext, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++const SERVER_URL = 'http://ai-setup.test/v1'+const CORS_HEADERS = {+ 'access-control-allow-origin': '*',+ 'access-control-allow-headers': '*',+ 'access-control-allow-methods': 'POST, OPTIONS'+}++async function openGuidedSetup(page: Page) {+ await page.goto('/?test')+ await new CanvasHelper(page).waitForInit()+ await page.getByTestId('app-settings-trigger').click()+ await page.getByTestId('settings-section-ai').click()+ await page.getByTestId('settings-run-ai-setup').click()+ const setup = page.getByTestId('ai-setup-dialog')+ await expect(setup.getByRole('heading', { name: 'What should AI help with?' })).toBeVisible()+ return setup+}++/** Answers the connection test like an OpenAI-compatible server would. */+async function serveCompatibleModel(page: Page) {+ await page.route(`${SERVER_URL}/**`, async (route) => {+ if (route.request().method() === 'OPTIONS') {+ await route.fulfill({ status: 204, headers: CORS_HEADERS })+ return+ }+ await route.fulfill({+ headers: CORS_HEADERS,+ json: {+ id: 'chatcmpl-ai-setup',+ object: 'chat.completion',+ created: 0,+ model: 'qwen3-coder:30b',+ choices: [+ { index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }+ ],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }+ }+ })+ })+}++test('guided setup opens from AI settings and hands off to advanced settings', async ({ page }) => {+ const setup = await openGuidedSetup(page)+ await setup.getByRole('button', { name: 'Advanced settings' }).click()+ await expect(setup).toHaveCount(0)+ await expect(page.getByTestId('settings-add-model')).toBeVisible()+})++test('guided setup connects a local server and saves it as the design model', async ({ page }) => {+ await serveCompatibleModel(page)+ const setup = await openGuidedSetup(page)+ const next = setup.getByRole('button', { name: 'Continue' })+ await next.click()+ await setup.getByRole('checkbox', { name: 'Local model or company server' }).click()+ await next.click()++ // The server covers the design goal, so setup skips the pay-as-you-go question.+ await expect(setup.getByRole('heading', { name: 'Connect your AI' })).toBeVisible()+ await expect(next).toBeDisabled()+ await setup.getByRole('textbox', { name: 'Base URL' }).fill(SERVER_URL)+ await setup.getByRole('textbox', { name: 'Model ID' }).fill('qwen3-coder:30b')+ // The runtime needs a stored key even for servers that ignore it.+ await setup.getByLabel('API Key').fill('local-server-key')+ await setup.getByRole('button', { name: 'Test connection' }).click()+ await expect(next).toBeEnabled()+ await next.click()++ await setup.getByRole('button', { name: 'Finish setup' }).click()+ await expect(setup.getByRole('heading', { name: 'AI is ready' })).toBeVisible()+ await setup.getByRole('button', { name: 'Done' }).click()++ const models = page.getByTestId('settings-model-list')+ const model = models.locator('[data-model-id]', { hasText: 'qwen3-coder:30b' })+ await expect(model).toBeVisible()+ // The saved key shows without reopening Settings.+ await expect(model.getByText('Connected', { exact: true })).toBeVisible()+ await expect(models.getByText('Design model', { exact: true })).toHaveCount(0)+})++/** Stands in for OpenRouter: sign-in redirects back with a code, which exchanges for a key. */+async function serveOpenRouter(context: BrowserContext) {+ const exchanges: unknown[] = []+ const keyChecks: (string | undefined)[] = []+ await context.route('https://openrouter.ai/auth?**', async (route) => {+ await route.fulfill({+ contentType: 'text/html',+ body: `<script>+ const params = new URLSearchParams(location.search)+ const callback = new URL(params.get('callback_url'))+ callback.searchParams.set('code', 'e2e-code')+ callback.searchParams.set('state', params.get('state'))+ location.replace(callback.href)+ </script>`+ })+ })+ await context.route('https://openrouter.ai/api/v1/**', async (route) => {+ const request = route.request()+ if (request.method() === 'OPTIONS') {+ await route.fulfill({ status: 204, headers: CORS_HEADERS })+ return+ }+ if (request.url().endsWith('/auth/keys')) {+ exchanges.push(request.postDataJSON())+ await route.fulfill({ headers: CORS_HEADERS, json: { key: 'sk-or-e2e-key' } })+ return+ }+ if (request.url().endsWith('/api/v1/key')) {+ keyChecks.push(request.headers().authorization)+ await route.fulfill({+ headers: CORS_HEADERS,+ json: { data: { label: 'OpenPencil', is_free_tier: false } }+ })+ return+ }+ await route.fulfill({+ headers: CORS_HEADERS,+ json: {+ id: 'gen-ai-setup',+ object: 'chat.completion',+ created: 0,+ model: 'anthropic/claude-sonnet-5',+ choices: [+ { index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }+ ],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }+ }+ })+ })+ return { exchanges, keyChecks }+}++test('guided setup signs in with OpenRouter without pasting a key', async ({ page, context }) => {+ const { exchanges, keyChecks } = await serveOpenRouter(context)+ const setup = await openGuidedSetup(page)+ const next = setup.getByRole('button', { name: 'Continue' })+ await next.click()+ await next.click()+ await setup.getByRole('button', { name: 'Add OpenRouter (pay as you go)' }).click()++ await expect(next).toBeDisabled()+ const popup = page.waitForEvent('popup')+ await setup.getByRole('button', { name: 'Sign in with OpenRouter' }).click()+ await (await popup).waitForEvent('close')+ // Setup checks the key with OpenRouter itself instead of asking for a connection test.+ await expect(+ setup.getByRole('status').filter({ hasText: 'Signed in to OpenRouter' })+ ).toBeVisible()+ await expect(setup.getByLabel('API Key')).toHaveCount(0)+ await expect(next).toBeEnabled()+ expect(exchanges).toEqual([+ { code: 'e2e-code', code_verifier: expect.any(String), code_challenge_method: 'S256' }+ ])+ expect(keyChecks).toEqual(['Bearer sk-or-e2e-key'])++ await next.click()+ // Role choices read "<model> · <provider>"; the catalog decides which models those are.+ const design = setup.getByRole('combobox', { name: 'Design agent' })+ const fast = setup.getByRole('combobox', { name: 'Fast tasks' })+ const designModel = (await design.textContent())?.split(' · ')[0]?.trim() ?? ''+ const recommendedFast = (await fast.textContent())?.trim() ?? ''+ expect(recommendedFast).not.toMatch(/Same as Design/)+ await fast.click()+ await page.getByRole('option', { name: 'Same as Design' }).click()+ await expect(fast).toHaveText(/Same as Design/)+ await setup.getByRole('button', { name: 'Use recommended setup' }).click()+ await expect(fast).toHaveText(recommendedFast)+ const fastModel = recommendedFast.split(' · ')[0]?.trim() ?? ''+ await setup.getByRole('button', { name: 'Finish setup' }).click()+ await expect(setup.getByRole('heading', { name: 'AI is ready' })).toBeVisible()+ await setup.getByRole('button', { name: 'Done' }).click()++ const models = page.getByTestId('settings-model-list')+ for (const name of [designModel, fastModel]) {+ const model = models.locator('[data-model-id]', { hasText: name })+ await expect(model.getByText('Connected', { exact: true })).toBeVisible()+ }+})diff --git a/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-dark-openpencil-darwin.png b/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-dark-openpencil-darwin.pngindex 26bc75ed6..81fef5268 100644Binary files a/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-dark-openpencil-darwin.png and b/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-dark-openpencil-darwin.png differdiff --git a/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-light-openpencil-darwin.png b/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-light-openpencil-darwin.pngindex f30b0f9ce..8785d71e4 100644Binary files a/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-light-openpencil-darwin.png and b/tests/e2e/settings/mobile.spec.ts-snapshots/mobile-settings-models-light-openpencil-darwin.png differdiff --git a/tests/e2e/settings/model-status.spec.ts b/tests/e2e/settings/model-status.spec.tsnew file mode 100644index 000000000..c6f1f3fcb--- /dev/null+++ b/tests/e2e/settings/model-status.spec.ts@@ -0,0 +1,31 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++async function openModels(page: Page) {+ await page.goto('/?test')+ await new CanvasHelper(page).waitForInit()+ await page.getByTestId('app-settings-trigger').click()+ await page.getByTestId('settings-section-ai').click()+}++test('an unreadable saved key marks its model row instead of failing Settings', async ({+ page+}) => {+ await openModels(page)+ await page.locator('[data-model-id]').first().click()+ await page.getByTestId('settings-model-provider').click()+ await page.getByRole('option', { name: 'OpenRouter' }).click()+ await page.getByTestId('provider-settings-api-key').fill('sk-or-unreadable')+ await page.getByRole('button', { name: 'Save model' }).click()+ await expect(page.getByTestId('settings-model-list')).toContainText('Connected')++ // A stored key that can no longer be decrypted, as after browser data from an older session.+ await page.addInitScript(() => {+ crypto.subtle.decrypt = () => Promise.reject(new DOMException('', 'OperationError'))+ })+ await openModels(page)+ const row = page.getByTestId('settings-model-list').locator('[data-model-id]').first()+ await expect(row).toContainText('Unavailable')+ await expect(page.getByText('Browser credential operation failed')).toHaveCount(0)+})diff --git a/tests/engine/app/settings/model-schema.test.ts b/tests/engine/app/settings/model-schema.test.tsindex 833a532c9..1b0595105 100644--- a/tests/engine/app/settings/model-schema.test.ts+++ b/tests/engine/app/settings/model-schema.test.ts@@ -55,3 +55,10 @@ test('independent field errors survive a failed tool-support rule', () => {modelID: ['Tools required']})})++test('Pi may leave the model empty to use the default model set in Pi', () => {+ expect(errors({ providerKind: 'harness' }, { ...values, modelID: '' })).toEqual({})+ expect(errors({ providerKind: 'harness', intent: 'test' }, { ...values, modelID: '' })).toEqual(+ {}+ )+})diff --git a/tests/engine/tauri/command.test.ts b/tests/engine/tauri/command.test.tsindex d09b44474..86a78996b 100644--- a/tests/engine/tauri/command.test.ts+++ b/tests/engine/tauri/command.test.ts@@ -5,6 +5,9 @@ import * as v from 'valibot'import { ACP_AGENTS } from '@open-pencil/core/constants'+import { npmInstallArgs } from '@/app/ai/agents/native'+import { HARNESS_PACKAGE } from '@/app/ai/harness/companion'+import { MCP_PACKAGE_NAME } from '@/app/automation/mcp/failure'import { resolvePlatformCommand } from '@/app/tauri/command'import { repoPath } from '#tests/helpers/paths'@@ -80,12 +83,37 @@ function spawnScope() {return typeof spawn === 'string' ? [] : (spawn?.allow ?? [])}+/** The arguments a scope entry lets through for `args`, the way the shell plugin builds them. */+function allowedArgs(scope: boolean | unknown[] | undefined, args: string[]): unknown[] | null {+ if (scope === false) return []+ if (!Array.isArray(scope)) return null+ return scope.map((allowed, index) => {+ if (typeof allowed === 'string') return allowed+ const validator = v.parse(v.object({ validator: v.string() }), allowed).validator+ const value = args[index] ?? ''+ return new RegExp(validator).test(value) ? value : { rejected: value }+ })+}++const rootPackage = v.parse(+ v.pipe(v.string(), v.parseJson(), v.object({ version: v.string() })),+ readFileSync(repoPath('package.json'), 'utf8')+)+describe('shell scope', () => {// Every program the app starts, with the arguments it starts it with.+ // npm installs only these packages; a build pins the companions to the app's version, which+ // tests stand in for with a placeholder the scope rightly refuses.+ const installs = [+ ...ACP_AGENTS.flatMap((agent) => (agent.adapterPackage ? [agent.adapterPackage] : [])),+ `${MCP_PACKAGE_NAME}@${rootPackage.version}`,+ `${HARNESS_PACKAGE}@${rootPackage.version}`+ ]const spawns: [string, string[]][] = [...ACP_AGENTS.map((agent): [string, string[]] => [agent.command, agent.args]),['openpencil-mcp-http', []],- ['openpencil-harness', []]+ ['openpencil-harness', []],+ ...installs.map((target): [string, string[]] => ['npm', npmInstallArgs(target)])]for (const userAgent of [WINDOWS_UA, MAC_UA]) {@@ -94,7 +122,7 @@ describe('shell scope', () => {const resolved = resolvePlatformCommand(name, args, userAgent)const entry = spawnScope().find((candidate) => candidate.name === resolved.command)expect(entry?.cmd).toBe(userAgent === WINDOWS_UA ? 'cmd' : name)- expect(entry?.args === false ? [] : entry?.args).toEqual(resolved.args)+ expect(allowedArgs(entry?.args, resolved.args)).toEqual(resolved.args)})}}@@ -110,6 +138,19 @@ describe('shell scope', () => {).toEqual([...new Set(expected)].sort())})+ test('lets npm install nothing but those packages', () => {+ const validators = spawnScope().flatMap((entry) =>+ Array.isArray(entry.args) ? entry.args.filter((arg) => typeof arg !== 'string') : []+ )+ expect(validators.length).toBeGreaterThan(0)+ for (const validator of validators) {+ const pattern = new RegExp(v.parse(v.object({ validator: v.string() }), validator).validator)+ for (const target of ['left-pad', '@open-pencil/[email protected] & calc', '@open-pencil/mcp']) {+ expect(pattern.test(target)).toBe(false)+ }+ }+ })+test('lets no program take arbitrary arguments', () => {expect(spawnScope().filter((entry) => entry.args === true)).toEqual([])})diff --git a/tests/helpers/ai/model-catalog.ts b/tests/helpers/ai/model-catalog.tsnew file mode 100644index 000000000..08be98d3f--- /dev/null+++ b/tests/helpers/ai/model-catalog.ts@@ -0,0 +1,14 @@+import { AI_PROVIDERS } from '@open-pencil/core/constants'++/** The catalog's default model, so onboarding tests follow catalog updates. */+export function defaultModel(providerID: string): string {+ return AI_PROVIDERS.find((provider) => provider.id === providerID)?.defaultModel ?? ''+}++/** Whether the catalog offers `modelID` as a fast model that can call tools. */+export function isFastToolModel(providerID: string, modelID: string): boolean {+ const model = AI_PROVIDERS.find((provider) => provider.id === providerID)?.models.find(+ (candidate) => candidate.id === modelID+ )+ return model?.tag === 'Fast' && model.capabilities?.includes('tools') === true+}diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 15a24f660..acff2350f 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -1,3 +1,43 @@+ja:ai.aiSetupAccessAPI+ja:ai.aiSetupAccessAgentsDesktop+ja:ai.aiSetupAccessServerDescription+ja:ai.aiSetupAgentDescription+ja:ai.aiSetupAgentInstallMCP+ja:ai.aiSetupAgentMCP+ja:ai.aiSetupAgentMCPInstall+ja:ai.aiSetupAgentMCPStartFailed+ja:ai.aiSetupAgentNeedsAdapter+ja:ai.aiSetupAgentNeedsNpm+ja:ai.aiSetupAgentPromptHint+ja:ai.aiSetupConnectTitle+ja:ai.aiSetupGapAddOpenRouter+ja:ai.aiSetupGapCoveredByOpenRouter+ja:ai.aiSetupGapRemoveOpenRouter+ja:ai.aiSetupGoalDesignDescription+ja:ai.aiSetupGoalVisionDescription+ja:ai.aiSetupGoalsTitle+ja:ai.aiSetupMeteredNote+ja:ai.aiSetupNothingDescription+ja:ai.aiSetupOpenRouterBlocked+ja:ai.aiSetupOpenRouterFailed+ja:ai.aiSetupOpenRouterNoCredits+ja:ai.aiSetupOpenRouterOrKey+ja:ai.aiSetupOpenRouterSignIn+ja:ai.aiSetupOpenRouterSignedInTitle+ja:ai.aiSetupOpenRouterVerifying+ja:ai.aiSetupOpenRouterWaiting+ja:ai.aiSetupSavedTitle+ja:ai.aiSetupStart+ja:ai.aiSetupWelcomeAIDescription+ja:ai.aiSetupWelcomeAITitle+ja:ai.aiSetupWelcomeDescription+ja:ai.aiSetupWelcomeTitle+ja:ai.aiSetupPiDescription+ja:ai.aiSetupPiCompanion+ja:ai.aiSetupPiModel+ja:ai.aiSetupPiNoModel+ja:ai.aiSetupPiSignIn+ja:ai.aiSetupAgentUpdateMCPja:ai.apiKeyja:ai.apiTypeja:ai.baseURL@@ -22,6 +62,12 @@ ja:ai.modelIDja:ai.modelIDPlaceholderja:ai.modelRoleDesignDescriptionja:ai.provider+ja:ai.chatPiCompanionMissing+ja:ai.chatPiCompanionOutdated+ja:ai.chatMCPOutdated+ja:ai.chatPiSignIn+ja:ai.chatPiModel+ja:ai.piModelHintja:ai.changePreviewHintja:automation.addServerConnectionja:automation.aiToolAccessDescription@@ -144,6 +190,46 @@ ja:updates.restartFailedja:updates.restartToFinishja:updates.unavailableja:updates.upToDate+zh-cn:ai.aiSetupAccessAPI+zh-cn:ai.aiSetupAccessAgentsDesktop+zh-cn:ai.aiSetupAccessServerDescription+zh-cn:ai.aiSetupAgentDescription+zh-cn:ai.aiSetupAgentInstallMCP+zh-cn:ai.aiSetupAgentMCP+zh-cn:ai.aiSetupAgentMCPInstall+zh-cn:ai.aiSetupAgentMCPStartFailed+zh-cn:ai.aiSetupAgentNeedsAdapter+zh-cn:ai.aiSetupAgentNeedsNpm+zh-cn:ai.aiSetupAgentPromptHint+zh-cn:ai.aiSetupConnectTitle+zh-cn:ai.aiSetupGapAddOpenRouter+zh-cn:ai.aiSetupGapCoveredByOpenRouter+zh-cn:ai.aiSetupGapRemoveOpenRouter+zh-cn:ai.aiSetupGoalDesignDescription+zh-cn:ai.aiSetupGoalVisionDescription+zh-cn:ai.aiSetupGoalsTitle+zh-cn:ai.aiSetupMeteredNote+zh-cn:ai.aiSetupNothingDescription+zh-cn:ai.aiSetupOpenRouterBlocked+zh-cn:ai.aiSetupOpenRouterFailed+zh-cn:ai.aiSetupOpenRouterNoCredits+zh-cn:ai.aiSetupOpenRouterOrKey+zh-cn:ai.aiSetupOpenRouterSignIn+zh-cn:ai.aiSetupOpenRouterSignedInTitle+zh-cn:ai.aiSetupOpenRouterVerifying+zh-cn:ai.aiSetupOpenRouterWaiting+zh-cn:ai.aiSetupSavedTitle+zh-cn:ai.aiSetupStart+zh-cn:ai.aiSetupWelcomeAIDescription+zh-cn:ai.aiSetupWelcomeAITitle+zh-cn:ai.aiSetupWelcomeDescription+zh-cn:ai.aiSetupWelcomeTitle+zh-cn:ai.aiSetupPiDescription+zh-cn:ai.aiSetupPiCompanion+zh-cn:ai.aiSetupPiModel+zh-cn:ai.aiSetupPiNoModel+zh-cn:ai.aiSetupPiSignIn+zh-cn:ai.aiSetupAgentUpdateMCPja:variables.copyAsCSSja:variables.copyAsTailwindThemezh-cn:ai.apiKey@@ -170,6 +256,12 @@ zh-cn:ai.modelIDzh-cn:ai.modelIDPlaceholderzh-cn:ai.modelRoleDesignDescriptionzh-cn:ai.provider+zh-cn:ai.chatPiCompanionMissing+zh-cn:ai.chatPiCompanionOutdated+zh-cn:ai.chatMCPOutdated+zh-cn:ai.chatPiSignIn+zh-cn:ai.chatPiModel+zh-cn:ai.piModelHintzh-cn:ai.changePreviewHintzh-cn:automation.addServerConnectionzh-cn:automation.aiToolAccessDescriptiondiff --git a/vite.config.ts b/vite.config.tsindex e61515c71..705811309 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -19,6 +19,7 @@ import {openPencilAutomationPlugin} from './vite/automation'import { copyCanvasKitAssetsPlugin } from './vite/canvaskit-assets'+import { aiIconCollection } from './vite/icons'import { openPencilPwaPlugin } from './vite/pwa'import { rawMarkdownPlugin } from './vite/raw-markdown'import { createDevServerOptions } from './vite/server'@@ -46,8 +47,8 @@ export default defineConfig(async ({ command }) => {rawMarkdownPlugin(),copyCanvasKitAssetsPlugin(),tailwindcss(),- Icons({ compiler: 'vue3' }),- Components({ resolvers: [IconsResolver({ prefix: 'icon' })] }),+ Icons({ compiler: 'vue3', customCollections: { ai: aiIconCollection() } }),+ Components({ resolvers: [IconsResolver({ prefix: 'icon', customCollections: ['ai'] })] }),openPencilAutomationPlugin(command, host),vue(),openPencilPwaPlugin()diff --git a/vite/icons.ts b/vite/icons.tsnew file mode 100644index 000000000..37c5dee06--- /dev/null+++ b/vite/icons.ts@@ -0,0 +1,15 @@+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++import { FileSystemIconLoader } from 'unplugin-icons/loaders'++/**+ * Monochrome provider and agent logos from LobeHub, used as `<icon-ai-openai />` or+ * `~icons/ai/openai`. They draw with `currentColor` on a 24px grid, like Lucide.+ */+export function aiIconCollection() {+ const manifest = fileURLToPath(import.meta.resolve('@lobehub/icons-static-svg/package.json'))+ const icons = join(dirname(manifest), 'icons')+ // Titles would add tooltips and duplicate the accessible name of the label beside the logo.+ return FileSystemIconLoader(icons, (svg) => svg.replace(/<title>.*?<\/title>/, ''))+}diff --git a/vite/pwa.ts b/vite/pwa.tsindex b9d5ada49..c798bd3af 100644--- a/vite/pwa.ts+++ b/vite/pwa.ts@@ -7,7 +7,9 @@ export function openPencilPwaPlugin() {workbox: {maximumFileSizeToCacheInBytes: 12 * 1024 * 1024,globPatterns: ['**/*.{js,css,html,wasm,png,svg,ico,ttf,webmanifest}'],- navigateFallback: '/index.html'+ navigateFallback: '/index.html',+ // OAuth callbacks are standalone pages that relay a redirect, not app routes.+ navigateFallbackDenylist: [/^\/oauth\//]},manifest: {name: 'OpenPencil',