Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(agent): the agent can open a folder and start a program

purplebd77b5c8aa46
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index e30c5abb..0d6819aa 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -332,6 +332,197 @@ pub fn get_current_time() -> Result<serde_json::Value, String> {
}))
}
+// ── Opening folders and launching apps (B1, Morgan 2026-08-03) ──────────────
+//
+// Morgan asked for an agent that can open a folder and start a program. The
+// deliberate limits, because this is a tool a MODEL calls, not a person:
+//
+// * `desktop_open` opens only what already EXISTS on disk. A path that does
+// not resolve is refused, which is what keeps this from doubling as a
+// protocol-handler primitive: `https://…`, `file://…` and `mailto:` are not
+// paths, so they never reach the opener. Web pages have web_fetch, and the
+// UI has its own openExternal with a URL allowlist.
+// * `app_launch` takes a name and nothing else. No arguments, by design: an
+// app plus attacker-chosen argv is a different and much larger surface than
+// "start Notepad", and nothing in Morgan's request needs it.
+// * Neither builds a shell string by concatenation. Every value goes in as
+// its own argv entry, so a path with a space, a quote or a semicolon is
+// data. The one platform path that cannot avoid a shell (the Windows
+// `cmd /C start` fallback) is reached only after the name has passed
+// `validate_app_name`.
+
+/// Characters that let a name break out of a Windows `cmd /C` line. An
+/// application is called "Google Chrome", never "foo & del".
+const APP_NAME_FORBIDDEN: &[char] = &['&', '|', ';', '<', '>', '^', '"', '\'', '`', '\n', '\r', '%', '!'];
+
+/// An app name has to be a name. Rejecting rather than escaping keeps the rule
+/// readable and the same on all three platforms.
+fn validate_app_name(name: &str) -> Result<(), String> {
+ let trimmed = name.trim();
+ if trimmed.is_empty() {
+ return Err("app_launch: no application name given".into());
+ }
+ if trimmed.len() > 256 {
+ return Err("app_launch: application name is too long".into());
+ }
+ if let Some(bad) = trimmed.chars().find(|c| APP_NAME_FORBIDDEN.contains(c)) {
+ return Err(format!(
+ "app_launch: refused, the name contains {bad:?}. Pass a plain application name such as \"Notepad\" or \"Google Chrome\"."
+ ));
+ }
+ Ok(())
+}
+
+/// Resolve and verify the target of `desktop_open`. Returns the existing path
+/// and whether it is a directory.
+fn resolve_existing(path: &str) -> Result<(std::path::PathBuf, bool), String> {
+ let trimmed = path.trim();
+ if trimmed.is_empty() {
+ return Err("desktop_open: no path given".into());
+ }
+ // A URL is not a path. Naming the case explicitly gives the model a usable
+ // error instead of "no such file or directory" on a string it thinks is fine.
+ if let Some(scheme) = trimmed.split("://").next().filter(|s| *s != trimmed) {
+ return Err(format!(
+ "desktop_open: {scheme}:// is a URL, not a path. This tool opens folders and files that exist on this machine."
+ ));
+ }
+ let p = std::path::PathBuf::from(trimmed);
+ let meta = std::fs::metadata(&p)
+ .map_err(|e| format!("desktop_open: cannot open {trimmed}: {e}"))?;
+ Ok((p, meta.is_dir()))
+}
+
+/// Open a folder or file in the desktop environment, or reveal it in the file
+/// manager with the item selected.
+#[tauri::command]
+pub fn desktop_open(path: String, reveal: Option<bool>) -> Result<serde_json::Value, String> {
+ let (target, is_dir) = resolve_existing(&path)?;
+ let reveal = reveal.unwrap_or(false);
+ let shown = target.to_string_lossy().to_string();
+ let mut cmd: std::process::Command;
+
+ #[cfg(target_os = "macos")]
+ {
+ cmd = std::process::Command::new("open");
+ if reveal {
+ cmd.arg("-R");
+ }
+ cmd.arg(&target);
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ cmd = std::process::Command::new("explorer");
+ if reveal {
+ // explorer takes this as ONE argument: `/select,C:\path`.
+ let mut sel = std::ffi::OsString::from("/select,");
+ sel.push(target.as_os_str());
+ cmd.arg(sel);
+ } else {
+ cmd.arg(&target);
+ }
+ }
+
+ #[cfg(all(unix, not(target_os = "macos")))]
+ {
+ // No portable "reveal" on Linux, so revealing a file opens the folder
+ // that holds it. Saying so beats silently doing something else.
+ let opened = if reveal && !is_dir {
+ target.parent().unwrap_or(&target).to_path_buf()
+ } else {
+ target.clone()
+ };
+ cmd = std::process::Command::new("xdg-open");
+ cmd.arg(&opened);
+ }
+
+ crate::process_util::suppress_window(&mut cmd);
+ let status = cmd
+ .status()
+ .map_err(|e| format!("desktop_open: could not start the file manager: {e}"))?;
+
+ // Windows Explorer reports a non-zero exit even when it did the right
+ // thing, so its code says nothing about success and is not checked.
+ #[cfg(not(target_os = "windows"))]
+ if !status.success() {
+ return Err(format!("desktop_open: the file manager refused {shown}"));
+ }
+ #[cfg(target_os = "windows")]
+ let _ = status;
+
+ Ok(serde_json::json!({
+ "path": shown,
+ "kind": if is_dir { "folder" } else { "file" },
+ "revealed": reveal,
+ }))
+}
+
+/// Launch an installed application by name. No arguments are forwarded.
+#[tauri::command]
+pub fn app_launch(name: String) -> Result<serde_json::Value, String> {
+ validate_app_name(&name)?;
+ let name = name.trim().to_string();
+
+ #[cfg(target_os = "macos")]
+ {
+ // `open -a` searches the launch services database, so "Chrome",
+ // "Google Chrome" and a full .app path all resolve.
+ let mut cmd = std::process::Command::new("open");
+ cmd.arg("-a").arg(&name);
+ let out = cmd
+ .output()
+ .map_err(|e| format!("app_launch: could not run open: {e}"))?;
+ if !out.status.success() {
+ let why = String::from_utf8_lossy(&out.stderr).trim().to_string();
+ return Err(format!(
+ "app_launch: could not start {name}. {}",
+ if why.is_empty() { "It may not be installed.".into() } else { why }
+ ));
+ }
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ {
+ // A name that is already an executable on PATH (or a full path to one)
+ // needs no shell at all, so that is tried first.
+ let mut direct = std::process::Command::new(&name);
+ crate::process_util::suppress_window(&mut direct);
+ if direct.spawn().is_ok() {
+ return Ok(serde_json::json!({ "launched": name }));
+ }
+
+ #[cfg(target_os = "windows")]
+ let mut cmd = {
+ // `start` is a cmd builtin, so this is the one path that needs a
+ // shell. The empty "" is start's title argument: without it start
+ // treats a quoted name AS the title and opens a console instead.
+ let mut c = std::process::Command::new("cmd");
+ c.args(["/C", "start", "", &name]);
+ c
+ };
+ #[cfg(all(unix, not(target_os = "macos")))]
+ let mut cmd = {
+ // Desktop entries are how Linux names applications.
+ let mut c = std::process::Command::new("gtk-launch");
+ c.arg(&name);
+ c
+ };
+
+ crate::process_util::suppress_window(&mut cmd);
+ let status = cmd
+ .status()
+ .map_err(|e| format!("app_launch: could not start {name}: {e}"))?;
+ if !status.success() {
+ return Err(format!(
+ "app_launch: could not start {name}. It may not be installed under that name."
+ ));
+ }
+ }
+
+ Ok(serde_json::json!({ "launched": name }))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -422,4 +613,89 @@ mod tests {
started.elapsed()
);
}
+
+ // ── B1: opening folders and launching apps ──────────────────
+
+ #[test]
+ fn an_ordinary_application_name_passes() {
+ for name in ["Notepad", "Google Chrome", "Visual Studio Code", "firefox", "calc.exe"] {
+ assert!(validate_app_name(name).is_ok(), "rejected a real name: {name}");
+ }
+ }
+
+ #[test]
+ fn a_name_that_could_break_out_of_a_command_line_is_refused() {
+ // The Windows fallback ends up in `cmd /C start`, so every character
+ // that means something to cmd has to be gone before we get there.
+ for name in [
+ "Notepad & del C:\\Windows\\*",
+ "foo | whoami",
+ "foo; rm -rf ~",
+ "foo > out.txt",
+ "foo`whoami`",
+ "foo\nshutdown",
+ "%USERPROFILE%",
+ "foo^&bar",
+ ] {
+ assert!(validate_app_name(name).is_err(), "let a payload through: {name}");
+ }
+ }
+
+ #[test]
+ fn an_empty_or_oversized_name_is_refused() {
+ assert!(validate_app_name("").is_err());
+ assert!(validate_app_name(" ").is_err());
+ assert!(validate_app_name(&"a".repeat(300)).is_err());
+ }
+
+ #[test]
+ fn a_url_is_not_a_path_and_says_so() {
+ // The rule that keeps desktop_open from becoming a way to make the
+ // machine follow a link the model chose.
+ for url in ["https://example.com", "file:///etc/passwd", "mailto:[email protected]"] {
+ let err = resolve_existing(url).unwrap_err();
+ assert!(
+ err.contains("URL") || err.contains("cannot open"),
+ "unhelpful error for {url}: {err}"
+ );
+ }
+ assert!(resolve_existing("https://example.com").unwrap_err().contains("URL"));
+ }
+
+ #[test]
+ fn a_path_that_does_not_exist_is_refused() {
+ let missing = std::env::temp_dir().join("lu-nope-4f1c9a2b").to_string_lossy().to_string();
+ assert!(resolve_existing(&missing).is_err());
+ assert!(resolve_existing("").is_err());
+ }
+
+ #[test]
+ fn an_existing_folder_resolves_and_is_reported_as_a_folder() {
+ let dir = std::env::temp_dir();
+ let (path, is_dir) = resolve_existing(&dir.to_string_lossy()).unwrap();
+ assert!(is_dir, "temp dir should be a directory");
+ assert!(path.exists());
+ }
+
+ #[test]
+ fn an_existing_file_resolves_and_is_reported_as_a_file() {
+ let f = std::env::temp_dir().join("lu-open-probe.txt");
+ std::fs::write(&f, b"probe").unwrap();
+ let (_, is_dir) = resolve_existing(&f.to_string_lossy()).unwrap();
+ assert!(!is_dir, "a regular file must not report as a folder");
+ let _ = std::fs::remove_file(&f);
+ }
+
+ #[test]
+ fn a_path_with_spaces_and_quotes_survives_resolution() {
+ // Nothing here concatenates a command line, so a hostile-looking name
+ // is just a name. This is the test that would fail the day someone
+ // rewrites the opener to build a shell string.
+ let dir = std::env::temp_dir().join("lu probe; rm -rf $HOME");
+ std::fs::create_dir_all(&dir).unwrap();
+ let (path, is_dir) = resolve_existing(&dir.to_string_lossy()).unwrap();
+ assert!(is_dir);
+ assert!(path.to_string_lossy().contains("rm -rf"));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 867de2e1..ecdf6195 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -181,6 +181,8 @@ fn main() {
commands::system::system_info,
commands::system::process_list,
commands::system::screenshot,
+ commands::system::desktop_open,
+ commands::system::app_launch,
commands::system::pick_folder,
commands::system::is_onboarding_done,
commands::system::set_onboarding_done,
diff --git a/src/api/__tests__/desktop-open-tools.test.ts b/src/api/__tests__/desktop-open-tools.test.ts
new file mode 100644
index 00000000..d906a8e9
--- /dev/null
+++ b/src/api/__tests__/desktop-open-tools.test.ts
@@ -0,0 +1,112 @@
+/**
+ * B1 (Morgan, promised for 2.6.3): the agent can open a folder and start a
+ * program.
+ *
+ * The whole point of these two tools is that they act on the user's actual
+ * desktop, so the interesting part is not that they work but what they refuse
+ * and how tightly they are scoped. The Rust side proves the refusals
+ * (src-tauri/src/commands/system.rs tests: URLs are not paths, a name that
+ * could break out of a Windows command line is rejected). This file proves the
+ * contract the MODEL sees: the arguments that reach the backend, the shape of
+ * the schema, and that neither tool quietly grew a way to pass arguments to a
+ * launched program.
+ *
+ * Run: npx vitest run src/api/__tests__/desktop-open-tools.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backendCall = vi.fn()
+vi.mock('../backend', () => ({
+ backendCall: (...args: any[]) => backendCall(...args),
+ fetchExternal: vi.fn(),
+}))
+
+const { toolRegistry } = await import('../mcp')
+
+const toolNamed = (n: string) => toolRegistry.getAll().find((t) => t.name === n)!
+const run = (n: string, args: Record<string, any>) => toolRegistry.execute(n, args)
+
+beforeEach(() => backendCall.mockReset())
+
+describe('desktop_open', () => {
+ it('is offered as a desktop tool with path required and reveal optional', () => {
+ const t = toolNamed('desktop_open')
+ expect(t.category).toBe('desktop')
+ expect(t.inputSchema.required).toEqual(['path'])
+ expect(t.inputSchema.properties.path.type).toBe('string')
+ expect(t.inputSchema.properties.reveal.type).toBe('boolean')
+ })
+
+ it('tells the model plainly that a link is not what this is for', () => {
+ // The model reaching for desktop_open on a URL is the mistake worth
+ // preventing in the prompt, not just in the backend.
+ const d = toolNamed('desktop_open').description
+ expect(d).toMatch(/https?:\/\//)
+ expect(d).toMatch(/web_fetch/)
+ })
+
+ it('passes the path through and defaults reveal to false', async () => {
+ backendCall.mockResolvedValue({ path: '/Users/x/Downloads', kind: 'folder', revealed: false })
+ const out = await run('desktop_open', { path: '/Users/x/Downloads' })
+ expect(backendCall).toHaveBeenCalledWith('desktop_open', {
+ path: '/Users/x/Downloads',
+ reveal: false,
+ })
+ expect(out).toBe('Folder opened: /Users/x/Downloads')
+ })
+
+ it('forwards reveal and says the item was revealed, not opened', async () => {
+ backendCall.mockResolvedValue({ path: '/Users/x/a.txt', kind: 'file', revealed: true })
+ const out = await run('desktop_open', { path: '/Users/x/a.txt', reveal: true })
+ expect(backendCall).toHaveBeenCalledWith('desktop_open', { path: '/Users/x/a.txt', reveal: true })
+ expect(out).toBe('File revealed in the file manager: /Users/x/a.txt')
+ })
+
+ it('only ever sends reveal as a real boolean', async () => {
+ // A prompt-transport model can hand over the STRING "true", and "false" is
+ // truthy in JavaScript. Anything that is not exactly true means false here.
+ backendCall.mockResolvedValue({ path: '/p', kind: 'folder', revealed: false })
+ await run('desktop_open', { path: '/p', reveal: 'false' as any })
+ expect(backendCall.mock.calls[0][1].reveal).toBe(false)
+ })
+
+ it('refuses an empty path without touching the backend', async () => {
+ const out = await run('desktop_open', { path: ' ' })
+ expect(out).toMatch(/needs a path/)
+ expect(backendCall).not.toHaveBeenCalled()
+ })
+})
+
+describe('app_launch', () => {
+ it('takes a name and nothing else, deliberately', () => {
+ // No args parameter. An application plus model-chosen argv is a much
+ // larger surface than "start Notepad", and shell_execute already exists
+ // for the case that genuinely needs arguments.
+ const t = toolNamed('app_launch')
+ expect(t.category).toBe('desktop')
+ expect(Object.keys(t.inputSchema.properties)).toEqual(['name'])
+ expect(t.inputSchema.required).toEqual(['name'])
+ expect(t.description).toMatch(/shell_execute/)
+ })
+
+ it('passes the trimmed name and reports what started', async () => {
+ backendCall.mockResolvedValue({ launched: 'Google Chrome' })
+ const out = await run('app_launch', { name: ' Google Chrome ' })
+ expect(backendCall).toHaveBeenCalledWith('app_launch', { name: 'Google Chrome' })
+ expect(out).toBe('Launched Google Chrome.')
+ })
+
+ it('refuses an empty name without touching the backend', async () => {
+ const out = await run('app_launch', { name: '' })
+ expect(out).toMatch(/needs an application name/)
+ expect(backendCall).not.toHaveBeenCalled()
+ })
+
+ it('never forwards anything the schema did not declare', async () => {
+ // If a model invents `args`, it must not reach the backend just because it
+ // was in the object.
+ backendCall.mockResolvedValue({ launched: 'Notepad' })
+ await run('app_launch', { name: 'Notepad', args: ['--evil'], cwd: '/' })
+ expect(backendCall).toHaveBeenCalledWith('app_launch', { name: 'Notepad' })
+ })
+})
diff --git a/src/api/__tests__/tool-description-parity.test.ts b/src/api/__tests__/tool-description-parity.test.ts
index 08aa80a5..cd455690 100644
--- a/src/api/__tests__/tool-description-parity.test.ts
+++ b/src/api/__tests__/tool-description-parity.test.ts
@@ -73,16 +73,61 @@ function evaluateStringLiteralExpression(expr: string): string {
return pieces.join('')
}
+/**
+ * Offset of the first `key:` that sits at the TOP level of the schema object,
+ * or -1. Depth-aware on purpose: `todo_write` (2026-08-05) is the first tool
+ * whose schema nests an object, and a plain `.match(/required:/)` grabbed the
+ * ITEM's `required: ['content','status']` instead of the schema's
+ * `required: ['todos']`. Every nested-schema tool after it would have hit the
+ * same wall.
+ */
+function topLevelKeyOffset(schemaExpr: string, key: string): number {
+ let depth = 0
+ for (let i = 0; i < schemaExpr.length; i++) {
+ const c = schemaExpr[i]
+ if (c === '{' || c === '[') depth++
+ else if (c === '}' || c === ']') depth--
+ // depth 1 == directly inside the schema object's braces
+ else if (depth === 1 && schemaExpr.startsWith(key + ':', i)) return i
+ }
+ return -1
+}
+
function extractRequiredArray(schemaExpr: string): string[] {
- const m = schemaExpr.match(/required:\s*\[([^\]]*)\]/)
+ const at = topLevelKeyOffset(schemaExpr, 'required')
+ if (at < 0) return []
+ const m = schemaExpr.slice(at).match(/required:\s*\[([^\]]*)\]/)
if (!m) return []
return [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1])
}
function extractPropertiesNames(schemaExpr: string): string[] {
- const propsBlock = schemaExpr.match(/properties:\s*\{([\s\S]*?)\}/)
- if (!propsBlock) return []
- return [...propsBlock[1].matchAll(/(\w+):\s*\{/g)].map((x) => x[1])
+ // Top-level `properties` only, and only its DIRECT keys — otherwise a nested
+ // object schema contributes its own field names to the parent's parameter
+ // list (todo_write would report `content` and `status` as its parameters).
+ const at = topLevelKeyOffset(schemaExpr, 'properties')
+ if (at < 0) return []
+ const open = schemaExpr.indexOf('{', at)
+ if (open < 0) return []
+ const names: string[] = []
+ let depth = 0
+ for (let i = open; i < schemaExpr.length; i++) {
+ const c = schemaExpr[i]
+ if (c === '{' || c === '[') {
+ depth++
+ continue
+ }
+ if (c === '}' || c === ']') {
+ depth--
+ if (depth === 0) break
+ continue
+ }
+ if (depth === 1) {
+ const m = /^(\w+):\s*\{/.exec(schemaExpr.slice(i))
+ if (m) names.push(m[1])
+ }
+ }
+ return names
}
// ─── Mobile extraction ───
@@ -171,6 +216,12 @@ const MOBILE_SKIP: ReadonlySet<string> = new Set<string>([
'shell_execute_background',
'shell_task_status', 'shell_task_kill', 'shell_task_list',
'video_generate',
+ // B1 (2.6.3): desktop_open and app_launch put a window on the DESKTOP
+ // screen. Driven from the phone, the user is by definition not looking at
+ // that screen, so the tool would appear to do nothing. remote.rs has no
+ // dispatcher for either, and adding one would mean the phone can open
+ // windows on an unattended machine.
+ 'desktop_open', 'app_launch',
])
describe('tool-description-parity — name sets', () => {
diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.ts
index e02c924f..3835c70d 100644
--- a/src/api/__tests__/tool-registry.test.ts
+++ b/src/api/__tests__/tool-registry.test.ts
@@ -25,7 +25,7 @@ const offeredDefNames = AGENT_TOOL_DEFS
// ── AGENT_TOOL_DEFS ─────────────────────────────────────────────
describe('AGENT_TOOL_DEFS', () => {
- it('contains exactly 30 tool definitions', () => {
+ it('contains exactly 33 tool definitions', () => {
// Phase 13 v2.4.0: delegate_task added as a builtin (→ 15 tools).
// v2.5.0 sprint A/B/C from uselu: +13 codex tools — shell_task_*,
// shell_execute_background, git_*, gh_pr_create, pr_resume,
@@ -33,10 +33,15 @@ describe('AGENT_TOOL_DEFS', () => {
// v2.5.0 Feature EE: video_generate (text-to-video via the VRAM hand-off
// orchestrator) added alongside image_generate (→ 29 tools).
// v2.5.9 M1: file_edit (surgical SEARCH/REPLACE edit) (→ 30 tools).
- expect(AGENT_TOOL_DEFS).toHaveLength(30)
+ // 2026-08-05 audit C4: todo_write — the plan the model keeps and the user
+ // sees above the composer (→ 31 tools).
+ // 2.6.3 B1 (Morgan): desktop_open and app_launch — open a folder, start a
+ // program (→ 33 tools).
+ expect(AGENT_TOOL_DEFS).toHaveLength(33)
})
const expectedTools = [
+ 'todo_write',
'web_search',
'web_fetch',
'file_read',
@@ -85,10 +90,13 @@ describe('AGENT_TOOL_DEFS', () => {
}
})
- it('auto-permission tools are get_current_time, process_list, system_info, web_fetch, web_search', () => {
+ it('auto-permission tools are the read-only probes plus todo_write', () => {
const autoTools = AGENT_TOOL_DEFS.filter((t) => t.permission === 'auto')
const autoNames = autoTools.map((t) => t.name).sort()
- expect(autoNames).toEqual(['get_current_time', 'process_list', 'system_info', 'web_fetch', 'web_search'])
+ // todo_write is category 'system' (auto) because it only writes the plan
+ // shown in the UI. Prompting for approval to write a to-do list would make
+ // the feature useless on a long unattended run.
+ expect(autoNames).toEqual(['get_current_time', 'process_list', 'system_info', 'todo_write', 'web_fetch', 'web_search'])
})
it('confirm-permission tools include file ops, code, shell, image, workflow, screenshot, delegate_task, sprint A/B/C tools', () => {
@@ -98,8 +106,12 @@ describe('AGENT_TOOL_DEFS', () => {
// v2.5.0 sprint A/B/C from uselu: codex tools default to confirm (writes,
// shell, git, gh, project_init, run_tests — all touch the user's machine).
// v2.5.0 Feature EE: video_generate (image category → confirm default).
+ // 2.6.3 B1: desktop_open and app_launch are desktop category, so they
+ // inherit confirm. That is the point — a tool that opens a window or
+ // starts a program asks first, exactly like screenshot does.
expect(confirmNames).toEqual([
- 'code_execute', 'delegate_task', 'file_edit', 'file_list', 'file_read', 'file_search',
+ 'app_launch', 'code_execute', 'delegate_task', 'desktop_open',
+ 'file_edit', 'file_list', 'file_read', 'file_search',
'file_write', 'gh_pr_create', 'git_commit', 'git_diff', 'git_log',
'git_push', 'git_status', 'image_generate', 'pr_resume', 'project_init',
'run_tests', 'run_workflow', 'screenshot', 'shell_execute',
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 7aff3965..dc684321 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -3,13 +3,14 @@
import type { MCPToolDefinition } from './types'
import type { ToolRegistry } from './tool-registry'
import { backendCall, fetchExternal } from '../backend'
-import { getActiveChatId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact } from '../agent-context'
+import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact } from '../agent-context'
import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
import { applyUniqueEdit } from '../../lib/surgical-edit'
import { sliceFileReadResult } from '../../lib/file-read-window'
+import { writeTodos, summarizeTodos } from '../../stores/todoStore'
import { isMlxImageHost, generateMlxImageDataUrl, listMlxImageModels, type MlxImageModel } from '../mlx-image'
import { getVideoStatus, listVideoModels, generateVideo as generateMlxVideo, getVideoProgress, cancelVideo, readVideoAsBlobUrl, type VideoModel } from '../mlx-video'
@@ -42,6 +43,40 @@ function chatCtx(): { chatId?: string; workingDirectory?: string } {
// every one of them is classified as mutating or read-only. It parses the file
// rather than importing it, because importing pulls in the tool-registry cycle.
const BUILTIN_TOOLS: MCPToolDefinition[] = [
+ // Planning
+ {
+ name: 'todo_write',
+ description:
+ 'Write the plan for a multi-step task and keep it up to date. The list is shown to the user live, so it is how they see what you are doing and how far along you are. '
+ + 'USE FIRST on any task that needs more than about three tool calls: write the whole plan before the first step. '
+ + 'Then call it again after each step to flip that item to completed and the next one to in_progress. '
+ + 'Send the COMPLETE list every time. It replaces the previous one, it does not merge. Exactly one item should be in_progress at a time. '
+ + 'DO NOT use it for a single-step request, and NEVER mark an item completed before the work actually succeeded.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ todos: {
+ type: 'array',
+ description: 'The complete plan, in order. Replaces the previous list.',
+ items: {
+ type: 'object',
+ properties: {
+ content: { type: 'string', description: 'What this step does, one short line' },
+ status: {
+ type: 'string',
+ enum: ['pending', 'in_progress', 'completed'],
+ description: 'pending = not started, in_progress = working on it now, completed = done and verified',
+ },
+ },
+ required: ['content', 'status'],
+ },
+ },
+ },
+ required: ['todos'],
+ },
+ category: 'system',
+ source: 'builtin',
+ },
// Web
{
name: 'web_search',
@@ -499,6 +534,44 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
category: 'desktop',
source: 'builtin',
},
+ {
+ name: 'desktop_open',
+ description:
+ 'Open a folder or file on this machine in the desktop file manager or its default application. '
+ + 'USE when the user says "open my Downloads folder", "show me that file", "open this in Finder/Explorer". '
+ + 'Set `reveal` to true to open the containing folder with the item selected instead of opening the item itself. '
+ + 'The path must already EXIST on this machine; a path that does not resolve is refused. '
+ + 'NOT for web pages or links of any kind (https://, file://, mailto:) — those are refused. Use web_fetch to read a page. '
+ + 'This shows something on the user\'s screen, so call it when they asked to see something, not to inspect a file yourself: use file_read or file_list for that.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Absolute path to an existing folder or file on this machine' },
+ reveal: { type: 'boolean', description: 'Open the containing folder with the item selected, instead of opening the item (default false)' },
+ },
+ required: ['path'],
+ },
+ category: 'desktop',
+ source: 'builtin',
+ },
+ {
+ name: 'app_launch',
+ description:
+ 'Start an installed desktop application by name. '
+ + 'USE for "open Chrome", "launch Notepad", "start Spotify". '
+ + 'Pass the application name as a person would say it ("Google Chrome", "Notepad", "Visual Studio Code"). '
+ + 'No arguments are passed to the application, deliberately — to run a command with arguments use shell_execute instead. '
+ + 'To open a document or folder rather than a program, use desktop_open.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Name of the installed application, e.g. "Google Chrome" or "Notepad"' },
+ },
+ required: ['name'],
+ },
+ category: 'desktop',
+ source: 'builtin',
+ },
// Image
{
@@ -1128,6 +1201,26 @@ async function executeScreenshot(): Promise<string> {
return JSON.stringify(data)
}
+async function executeDesktopOpen(args: Record<string, any>): Promise<string> {
+ const path = typeof args.path === 'string' ? args.path.trim() : ''
+ if (!path) return 'Error: desktop_open needs a path.'
+ const data = await backendCall<{ path: string; kind: string; revealed: boolean }>(
+ 'desktop_open',
+ { path, reveal: args.reveal === true },
+ )
+ const what = data.kind === 'folder' ? 'Folder' : 'File'
+ return data.revealed
+ ? `${what} revealed in the file manager: ${data.path}`
+ : `${what} opened: ${data.path}`
+}
+
+async function executeAppLaunch(args: Record<string, any>): Promise<string> {
+ const name = typeof args.name === 'string' ? args.name.trim() : ''
+ if (!name) return 'Error: app_launch needs an application name.'
+ const data = await backendCall<{ launched: string }>('app_launch', { name })
+ return `Launched ${data.launched}.`
+}
+
async function executeImageGenerate(args: Record<string, any>): Promise<string> {
// Feature EE (v2.5.0): the whole generation flow now goes through the VRAM
// hand-off orchestrator. It resolves the image model (args.model or first
@@ -1378,6 +1471,23 @@ async function executeVideoGenerateMlx(prompt: string, merged: Record<string, an
return 'Video generation timed out after 60 minutes; the generation was stopped.'
}
+async function executeTodoWrite(args: Record<string, any>): Promise<string> {
+ // Purely conversation state: no backend call, no permission gate, nothing
+ // that can fail on a machine. The one real failure is having no conversation
+ // to attach the plan to, which happens when a tool runs outside a loop.
+ // The CONVERSATION id, not getActiveChatId(): that one is a filesystem slug
+ // derived from id + title, and PlanBar reads the plan out of chatStore by the
+ // real id. Keying by the slug wrote the plan where nothing ever looks.
+ const convId = getActiveConversationId()
+ if (!convId) return 'Error: no active conversation to attach a plan to.'
+
+ const todos = writeTodos(convId, args.todos)
+ if (todos.length === 0 && Array.isArray(args.todos) && args.todos.length > 0) {
+ return 'Error: every item needs a non-empty `content` string. Nothing was written.'
+ }
+ return summarizeTodos(todos)
+}
+
async function executeGetCurrentTime(_args: Record<string, any>): Promise<string> {
try {
const data = await backendCall<{ unix: number; iso_local: string; iso_utc: string; timezone: string; timezone_offset: number }>(
@@ -1475,6 +1585,7 @@ function htmlToText(html: string): string {
// ── Registration ────────────────────────────────────────────────
const EXECUTOR_MAP: Record<string, (args: Record<string, any>) => Promise<string>> = {
+ todo_write: executeTodoWrite,
web_search: executeWebSearch,
web_fetch: executeWebFetch,
file_read: executeFileRead,
@@ -1500,6 +1611,8 @@ const EXECUTOR_MAP: Record<string, (args: Record<string, any>) => Promise<string
system_info: executeSystemInfo,
process_list: executeProcessList,
screenshot: executeScreenshot,
+ desktop_open: executeDesktopOpen,
+ app_launch: executeAppLaunch,
image_generate: executeImageGenerate,
video_generate: executeVideoGenerate,
run_workflow: executeRunWorkflow,
diff --git a/src/lib/mutating-tools.ts b/src/lib/mutating-tools.ts
index 9d018d07..3fe1c23e 100644
--- a/src/lib/mutating-tools.ts
+++ b/src/lib/mutating-tools.ts
@@ -28,4 +28,9 @@ export const MUTATING_TOOLS = new Set([
'run_workflow',
'delegate_task',
'screenshot',
+ // B1: both put something on the user's screen or start a process. Neither
+ // belongs in a turn the user asked to be read-only, for the same reason
+ // screenshot does not.
+ 'desktop_open',
+ 'app_launch',
])