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.

refactor(agent): tell the model which OS it is on instead of shipping two tools

purple2bd2701c50c4
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 3819c05b..5e12814d 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -1843,6 +1843,11 @@ button{-webkit-appearance:none;appearance:none}
.chat-welcome-logo{font-size:1.25rem;font-weight:700;letter-spacing:0.06em;color:var(--primary);margin-top:-2px;opacity:0.95}
.chat-welcome-tag{font-size:0.58rem;letter-spacing:0.22em;text-transform:uppercase;color:var(--text-secondary);opacity:0.75}
.chat-messages{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:14px 14px 8px;display:flex;flex-direction:column;gap:2px}
+.plan-strip{position:sticky;top:0;z-index:2;margin:-4px -4px 8px;padding:6px 8px;border:1px solid rgba(59,130,246,.22);border-radius:8px;background:rgba(24,24,27,.94);backdrop-filter:blur(6px)}
+.plan-head{font-size:9px;letter-spacing:.12em;color:#6b7280;margin-bottom:3px}
+.plan-item{font-size:11px;line-height:1.45;color:#9ca3af}
+.plan-item.plan-completed{color:#4b5563;text-decoration:line-through}
+.plan-item.plan-in_progress{color:#e5e7eb;font-weight:600}
.msg-group{display:flex;flex-direction:column;margin-bottom:12px}
.msg-group.user{align-items:flex-end}
.msg-group.bot{align-items:flex-start}
@@ -2072,7 +2077,7 @@ button{-webkit-appearance:none;appearance:none}
// with live Thought/Action/Observation cards streamed into the chat.
// The old "you can't run tools" text was from v2.3.3 before the mobile
// bridge could actually execute them.
- var CODEX_PROMPT = 'You are the Coding Agent, an autonomous coding agent inside LU. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. Empty assistant messages are a FAILURE.\n\n2. DO NOT stop after the first tool. Real coding tasks take 3-15 tool calls. Stopping after one file_read or one shell_execute without producing the requested artefact = FAILURE. "I have called one tool, that is enough" is NOT a valid stop reason.\n\n3. NEVER say "Now I will create X" / "Next I\'ll write Y" as plain prose and then stop. Do the next step RIGHT NOW as a concrete tool call.\n\n4. When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call. Plan in tool-call form, not prose-then-stop.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk, OR (b) you are stuck and genuinely need user input.\n\n=== WORKFLOW ===\n\n1. Understand the task.\n2. Explore (file_list, file_read, file_search) when you need to know existing layout.\n3. Plan changes (in your head, not as a stop point).\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_execute / code_execute / file_read).\n6. Only THEN write a short summary of what you did.\n\n=== FILE & DIRECTORY RULES ===\n\n- file_write AUTOMATICALLY creates any missing parent directories. Never call shell_execute with `mkdir`, `New-Item -ItemType Directory`, `md`, or `os.makedirs` to set up a folder before writing — just file_write the target path directly.\n- All relative paths resolve to the current chat workspace folder. Always pass relative paths (e.g. `client/public/index.html`) — do not hard-code absolute drive paths.\n- shell_execute runs inside the workspace folder by default. Do not `cd` into a parent or sibling folder; prefer relative commands.\n- On Windows, the shell is PowerShell. Quote arguments with spaces. Use forward slashes in paths inside commands. Avoid `mkdir -p` (PowerShell mkdir does not accept -p) — again, just use file_write.\n\n=== GENERAL ===\n\n- Always read a file before modifying it.\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool.\n- If a command fails, diagnose and retry with corrected arguments — do not introduce yourself again.\n- After 2-3 failures of the same approach, switch strategy (e.g. file_write instead of shell mkdir) instead of repeating.\n- Be concise in text. All real work happens in tool calls.\n- Respond in the same language the user used in their message.';
+ var CODEX_PROMPT = 'You are the Coding Agent, an autonomous coding agent inside LU. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. Empty assistant messages are a FAILURE.\n\n2. DO NOT stop after the first tool. Real coding tasks take 3-15 tool calls. Stopping after one file_read or one shell_execute without producing the requested artefact = FAILURE. "I have called one tool, that is enough" is NOT a valid stop reason.\n\n3. NEVER say "Now I will create X" / "Next I\'ll write Y" as plain prose and then stop. Do the next step RIGHT NOW as a concrete tool call.\n\n4. When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call. Plan in tool-call form, not prose-then-stop.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk, OR (b) you are stuck and genuinely need user input.\n\n=== WORKFLOW ===\n\n1. Understand the task.\n2. If the task needs more than about three tool calls, call todo_write with the WHOLE plan before you start. The user sees that list live on their phone. It is how they follow a long run on a small screen. Call it again after each step with the complete list, the finished item completed and the next one in_progress. Never mark an item completed before it actually succeeded.\n3. Explore (file_list, file_read, file_search) when you need to know existing layout.\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_execute / code_execute / file_read).\n6. Only THEN write a short summary of what you did.\n\n=== FILE & DIRECTORY RULES ===\n\n- file_write AUTOMATICALLY creates any missing parent directories. Never call shell_execute with `mkdir`, `New-Item -ItemType Directory`, `md`, or `os.makedirs` to set up a folder before writing — just file_write the target path directly.\n- All relative paths resolve to the current chat workspace folder. Always pass relative paths (e.g. `client/public/index.html`) — do not hard-code absolute drive paths.\n- shell_execute runs inside the workspace folder by default. Do not `cd` into a parent or sibling folder; prefer relative commands.\n- On Windows, the shell is PowerShell. Quote arguments with spaces. Use forward slashes in paths inside commands. Avoid `mkdir -p` (PowerShell mkdir does not accept -p) — again, just use file_write.\n\n=== GENERAL ===\n\n- Always read a file before modifying it.\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool.\n- If a command fails, diagnose and retry with corrected arguments — do not introduce yourself again.\n- After 2-3 failures of the same approach, switch strategy (e.g. file_write instead of shell mkdir) instead of repeating.\n- Be concise in text. All real work happens in tool calls.\n- Respond in the same language the user used in their message.';
// ── Thinking-compatible prefixes (parity with desktop) ──
// Keep in sync with THINKING_COMPATIBLE in src/lib/model-compatibility.ts.
@@ -2179,6 +2184,8 @@ button{-webkit-appearance:none;appearance:none}
// same model behaviour follows us onto mobile. Tests in
// src/api/__tests__/tool-description-parity.test.ts pin this parity.
var AGENT_TOOLS = [
+ {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.',
+ parameters:[{name:'todos',type:'array',description:'The complete plan, in order. Replaces the previous list.',required:true}]},
{name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. PREFER web_fetch on promising URLs for full content — snippets are teasers, not answers. DO NOT call more than 3x per turn with similar queries; refine the query instead of re-searching. For current date/time, use get_current_time — do NOT web_search for it.',
parameters:[{name:'query',type:'string',description:'The search query string',required:true},
{name:'maxResults',type:'number',description:'Maximum results to return (default: 5, max: 20)',required:false}]},
@@ -2200,7 +2207,7 @@ button{-webkit-appearance:none;appearance:none}
parameters:[{name:'path',type:'string',description:'Directory to search in (recursive by default)',required:true},
{name:'pattern',type:'string',description:'Regex pattern to search for',required:true},
{name:'maxResults',type:'number',description:'Maximum matching files (default: 50)',required:false}]},
- {name:'shell_execute', description:'Run a shell command. PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`, get_current_time over `date`. Use shell_execute for git, npm, cargo, docker, package managers, or platform utilities without a dedicated tool. NEVER use to permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). Default timeout 120 s; set higher only for known long-running builds.',
+ {name:'shell_execute', description:'Run a shell command. PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`, get_current_time over `date`. Use shell_execute for git, npm, cargo, docker, package managers, or platform utilities without a dedicated tool. This is also how you open things on the desktop: a folder, a file, or an application. The system prompt states which OS this is and gives the exact command. NEVER use to permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). Default timeout 120 s; set higher only for known long-running builds.',
parameters:[{name:'command',type:'string',description:'The full command to execute',required:true},
{name:'cwd',type:'string',description:'Working directory (optional, absolute preferred)',required:false},
{name:'timeout',type:'number',description:'Timeout in milliseconds (default: 120000)',required:false},
@@ -2456,6 +2463,13 @@ button{-webkit-appearance:none;appearance:none}
// (missing arg, permission, underlying tool error). We surface those
// as clean observations instead of "HTTP 500: ..." red errors.
function runAgentTool(tool, args){
+ // todo_write never leaves the browser: it writes the plan strip and nothing
+ // else. Sending it to the desktop bridge would need a Rust dispatcher and a
+ // permission gate for something that touches no file and no process, and it
+ // would put a network round trip in front of a UI update.
+ if(tool === 'todo_write'){
+ return Promise.resolve(applyTodoWrite(args && args.todos));
+ }
return fetch('/remote-api/agent-tool',{
method:'POST',
headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},
@@ -3038,6 +3052,52 @@ button{-webkit-appearance:none;appearance:none}
row.innerHTML = html;
}
+ // ── Plan strip (todo_write) ───────────────────────────────────
+ // Mirrors the desktop PlanBar. On a phone this matters more than on the
+ // desktop: the screen is small, the transcript scrolls away in three tool
+ // calls, and the whole reason to watch a run from a phone is to know where it
+ // is. Per chat, in memory only — a plan outlives neither the run nor a reload.
+ var todosByChat = {};
+
+ function applyTodoWrite(raw){
+ var key = currentChatId || '';
+ var out = [];
+ if(Object.prototype.toString.call(raw) === '[object Array]'){
+ for(var i=0;i<raw.length && out.length<40;i++){
+ var e = raw[i];
+ if(!e || typeof e !== 'object') continue;
+ var content = typeof e.content === 'string' ? e.content.trim() : '';
+ if(!content) continue;
+ // Anything unrecognised counts as not started: a typo must never mark
+ // work done that was never done. Same rule as the desktop store.
+ var st = (e.status === 'completed' || e.status === 'in_progress') ? e.status : 'pending';
+ out.push({content: content.slice(0,200), status: st});
+ }
+ }
+ todosByChat[key] = out;
+ renderChat();
+ if(out.length === 0) return 'Plan cleared.';
+ var done = 0, current = null, lines = [];
+ for(var j=0;j<out.length;j++){
+ if(out[j].status === 'completed') done++;
+ if(out[j].status === 'in_progress' && !current) current = out[j].content;
+ lines.push((out[j].status==='completed'?'[x] ':out[j].status==='in_progress'?'[>] ':'[ ] ')+out[j].content);
+ }
+ return 'Plan updated ('+done+'/'+out.length+' done'+(current?', now: '+current:'')+').\n'+lines.join('\n');
+ }
+
+ function renderPlanStrip(){
+ var t = todosByChat[currentChatId || ''];
+ if(!t || !t.length) return '';
+ var done = 0, items = '';
+ for(var i=0;i<t.length;i++){
+ if(t[i].status === 'completed') done++;
+ var mark = t[i].status==='completed' ? '&#10003;' : t[i].status==='in_progress' ? '&#9654;' : '&#9675;';
+ items += '<div class="plan-item plan-'+t[i].status+'">'+mark+' '+H(t[i].content)+'</div>';
+ }
+ return '<div class="plan-strip"><div class="plan-head">PLAN '+done+'/'+t.length+'</div>'+items+'</div>';
+ }
+
function renderChat(){
var p = el('chat-area');
if(!p) return;
@@ -3055,6 +3115,7 @@ button{-webkit-appearance:none;appearance:none}
return;
}
var html = '<div class="chat-messages" id="chat-msgs">';
+ html += renderPlanStrip();
for(var i=0;i<msgs.length;i++){
var m = msgs[i];
// Skip hidden tool-call history (persisted for continue capability
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 0d6819aa..d3ec4274 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -332,196 +332,6 @@ 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 {
@@ -614,88 +424,4 @@ mod tests {
);
}
- // ── 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 ecdf6195..867de2e1 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -181,8 +181,6 @@ 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
deleted file mode 100644
index d906a8e9..00000000
--- a/src/api/__tests__/desktop-open-tools.test.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * 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 cd455690..b4ec1759 100644
--- a/src/api/__tests__/tool-description-parity.test.ts
+++ b/src/api/__tests__/tool-description-parity.test.ts
@@ -216,12 +216,6 @@ 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 3835c70d..7b6d1a8f 100644
--- a/src/api/__tests__/tool-registry.test.ts
+++ b/src/api/__tests__/tool-registry.test.ts
@@ -35,9 +35,13 @@ describe('AGENT_TOOL_DEFS', () => {
// v2.5.9 M1: file_edit (surgical SEARCH/REPLACE edit) (→ 30 tools).
// 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)
+ // 2.6.3 B1 (Morgan): opening a folder or starting a program is NOT a tool.
+ // desktop_open and app_launch existed here briefly and were removed on
+ // 2026-08-06: they only wrapped `open` / `explorer` / `xdg-open`, cost ~478
+ // tokens of every system prompt, and inherited the same confirm gate
+ // shell_execute already had, so they bought nothing. The capability lives
+ // in shell_execute plus the platform line from lib/host-platform.ts.
+ expect(AGENT_TOOL_DEFS).toHaveLength(31)
})
const expectedTools = [
@@ -106,11 +110,8 @@ 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([
- 'app_launch', 'code_execute', 'delegate_task', 'desktop_open',
+ 'code_execute', 'delegate_task',
'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',
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index a2bf4968..95386ca1 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -225,6 +225,7 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
'Run a shell command. PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. '
+ 'PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`, get_current_time over `date`. '
+ 'Use shell_execute for git, npm, cargo, docker, package managers, or platform utilities without a dedicated tool. '
+ + 'This is also how you open things on the desktop: a folder, a file, or an application. The system prompt states which OS this is and gives the exact command. '
+ 'NEVER use to permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). '
+ 'Default timeout 120 s; set higher only for known long-running builds.',
inputSchema: {
@@ -535,44 +536,15 @@ 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',
- },
+ // Opening a folder, a file or an application is deliberately NOT a tool. It
+ // is `open` / `Invoke-Item` / `xdg-open`, so a dedicated tool would only wrap
+ // a shell command, which is the anti-pattern Anthropic names in "Writing
+ // effective tools for AI agents", and which no comparable agent ships. The
+ // two tools that used to live here cost ~478 tokens of every system prompt on
+ // a registry that already overflows a 4k-context local model, and bought no
+ // safety, since shell_execute is behind the same confirmation gate. What the
+ // model actually lacked was knowing which OS it is on: see platformPromptLine
+ // in lib/host-platform.ts. Removed 2026-08-06.
// Image
{
@@ -1202,26 +1174,6 @@ 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
@@ -1608,8 +1560,6 @@ 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/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index a2dcdea6..19a66ae2 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -2,7 +2,7 @@ import { useRef, useState, useCallback } from 'react'
import { v4 as uuid } from 'uuid'
import { streamProviderTurn } from '../lib/provider-stream'
import { createHermesDisplayFilter } from '../lib/hermes-stream'
-import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, setChatArtifactMode, takeChatArtifacts } from '../api/agent-context'
+import { setActiveChatId, setActiveConversationId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, setChatArtifactMode, takeChatArtifacts } from '../api/agent-context'
import { isOllamaLocal } from '../api/backend'
import { requestGenerationCancel } from '../api/vram-handoff'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
@@ -37,7 +37,8 @@ import { buildExtractionPrompt, parseExtractionResponse } from '../lib/memory-ex
import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
import { WorkflowEngine } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
-import { selectRelevantToolsAsync } from '../lib/tool-selection'
+import { selectRelevantToolsAsync, ALWAYS_INCLUDE, SMALL_MODEL_MAX_TOOLS } from '../lib/tool-selection'
+import { renderToolRoster, renderToolNames } from '../lib/tool-roster'
import { MUTATING_TOOLS } from '../lib/mutating-tools'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
@@ -54,6 +55,7 @@ import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
import { finalStripThinkingTags } from '../lib/thinking-stripper'
+import { platformPromptLine } from '../lib/host-platform'
// ── Standalone memory extraction (usable outside React hooks) ──
@@ -371,6 +373,7 @@ export function useAgentChat() {
const convForSlug = useChatStore.getState().conversations.find((c) => c.id === convId)
const slug = chatWorkspaceSlug(convId, convForSlug?.title)
setActiveChatId(slug)
+ setActiveConversationId(convId)
// Multi-Repo Agent (B15) + workspace unification (B17): pin the
// resolved workspace so chatCtx() in builtin-tools.ts threads it
@@ -497,13 +500,23 @@ export function useAgentChat() {
// Chat-Tools mode uses a conversational prompt (NOT the autonomous-agent
// one) so plain chat keeps its normal voice and only reaches for a tool
// when the user actually needs it.
+ // The roster the prompt shows comes from the same filtered registry the
+ // request draws on, so the prompt can never advertise a tool a permission
+ // blocked or omit one that was added since (audit 2026-08-05).
+ const offeredTools = toolRegistry.getAvailableTools(permissions)
+ .filter((t) => toolMatchesCurated(t.name))
let agentSystemPrompt = strategy === 'hermes_xml'
? buildHermesToolPrompt(hermesToolDefs) + (systemPrompt ? `\n\n${systemPrompt}` : '')
: opts?.chatToolsMode
? buildChatToolsSystemPrompt(systemPrompt)
: settings.smallModelMode
- ? buildAgentSystemPromptLean(systemPrompt)
- : buildAgentSystemPrompt(systemPrompt)
+ // Lean names only what survives the 6-tool cap, which is exactly the
+ // always-included set; the rest is in the request's tool list.
+ ? buildAgentSystemPromptLean(
+ systemPrompt,
+ renderToolNames(offeredTools.filter((t) => ALWAYS_INCLUDE.includes(t.name))),
+ )
+ : buildAgentSystemPrompt(systemPrompt, renderToolRoster(offeredTools))
// Standing goal (/goal) — same section Code injects, so the objective
// survives a switch between the two surfaces.
agentSystemPrompt += renderGoalSection(useAgentGoalStore.getState().getGoal(convId))
@@ -743,7 +756,7 @@ export function useAgentChat() {
toolRegistry.getAll().filter((t) => toolMatchesCurated(t.name)),
permissions,
settings.smallModelMode
- ? { embed: (texts) => generateEmbeddings(texts), topN: 5, embeddingThreshold: 6, maxTools: 6 }
+ ? { embed: (texts) => generateEmbeddings(texts), topN: 5, embeddingThreshold: 6, maxTools: SMALL_MODEL_MAX_TOOLS }
: { embed: (texts) => generateEmbeddings(texts) }
)
const tools: ToolDefinition[] = relevantDefs.map(t => ({
@@ -1754,14 +1767,20 @@ export function extractMediaPrompt(text: string): string {
return stripped || p
}
-function buildAgentSystemPrompt(basePrompt: string): string {
+function buildAgentSystemPrompt(basePrompt: string, roster: string): string {
const agentInstructions = `You are an autonomous AI agent inside LU with full access to this computer. You execute tasks end-to-end by using tools, you do NOT just describe what to do.
+${platformPromptLine()}
+
Available tools:
-- Filesystem: file_read, file_write, file_list, file_search
-- Web: web_search, web_fetch
-- System: shell_execute, code_execute, system_info, screenshot, process_list, get_current_time
-- Creative: image_generate, video_generate (text-to-video, or animate a generated image via inputImage), run_workflow
+${roster}
+
+That list is what LU can do. Your request carries the subset that fits the task at hand, and on a local model it is a subset. Only ever call a tool that is in your tool list. Calling one that is not there fails as an unknown tool and wastes a step. If you need one that is missing, name it in your answer and carry on with what you have.
+
+PLAN FIRST (todo_write):
+- Any task that needs more than about three tool calls starts with todo_write: write the whole plan before the first step. The user sees that list live, it is how they know what you are doing.
+- After each step, call todo_write again with the COMPLETE list, flipping the finished item to completed and the next one to in_progress. Exactly one item is in_progress at a time.
+- Never mark an item completed before the work actually succeeded. Skip the plan entirely for a single-step request.
AUTONOMY CONTRACT (read carefully, this is the most important rule):
- When the user asks you to BUILD, CREATE, MAKE, or WRITE something (a file, a website, a script, a folder structure), you MUST execute it via tools, typically file_write.
@@ -1783,10 +1802,11 @@ Creative tools, image_generate, video_generate:
Other rules:
- You MUST use tools — NEVER answer from memory or guess file contents.
+- To CHANGE part of an existing file use file_edit (replace a UNIQUE old_string with new_string), never file_write: rewriting a large file to change three lines truncates it and costs a fortune in tokens. file_write is for creating a new file or fully replacing one.
- PATHS: use paths relative to your working directory (e.g. \`package.json\`, \`src/app.ts\`, \`.\` for the current folder). Never start a path with \`/\` or a drive letter (\`C:\\\`), that escapes your workspace and fails. To list the current folder, use file_list with path \`.\`.
- For filesystem READ tasks: file_list first if needed, then file_read.
- For web tasks: web_search → web_fetch on the best URL → answer based on real data. web_search returns ONLY short snippets, ALWAYS call web_fetch to read the page.
-- If you need to know the OS, paths, or hardware: call system_info once at the start.
+- The OS is stated above, so do not spend a call finding it out. For hardware or exact system paths: call system_info once at the start.
- Chain multiple tools as needed. If a tool fails, try a different approach.
- Be concise in text. All the work happens in tool calls.
- Respond in the same language the user uses.`
@@ -1802,13 +1822,17 @@ Other rules:
// small-model tool-calling (LongFuncEval, arXiv 2505.10570) and small models
// have a limited instruction-following budget. Keep only what a small model
// needs to ACT — same tool names + native call format as the full prompt.
-function buildAgentSystemPromptLean(basePrompt: string): string {
+function buildAgentSystemPromptLean(basePrompt: string, alwaysThere: string): string {
const lean = `You are an autonomous agent in LU with tools on this computer. Do tasks by CALLING tools, do not just describe them.
-Tools: file_read, file_write, file_list, file_search, web_search, web_fetch, shell_execute, code_execute, system_info, get_current_time, image_generate, video_generate.
+${platformPromptLine()}
+
+You always have: ${alwaysThere}. Your request carries the other tools that fit the task. Read their names there, do not guess.
Rules:
+- For a task of more than about three steps, call todo_write FIRST with the whole plan, then again after each step with the complete list (one item in_progress, finished ones completed). The user watches that list.
- To build/create/write something, CALL the tool (usually file_write), never paste a code block and say "save this".
+- To change an existing file use file_edit with a unique old_string, not file_write.
- PATHS: use relative paths (e.g. \`package.json\`, \`.\`). Never start with \`/\` or a drive letter, it escapes your workspace and fails.
- Emit the tool call as your FIRST output, no "Okay, let me…" preamble. Valid JSON, one at a time. Never guess file contents, file_read first.
- After each tool result, if a step remains, immediately call the next tool. Do not narrate "I will now…" and then stop.
diff --git a/src/lib/__tests__/host-platform.test.ts b/src/lib/__tests__/host-platform.test.ts
new file mode 100644
index 00000000..38731d90
--- /dev/null
+++ b/src/lib/__tests__/host-platform.test.ts
@@ -0,0 +1,118 @@
+/**
+ * The platform line that replaced the desktop_open and app_launch tools
+ * (removed 2026-08-06).
+ *
+ * Those two tools wrapped `open` / `explorer` / `xdg-open`, which is the
+ * anti-pattern Anthropic names outright, and which no comparable agent ships:
+ * Claude Code, Cline and the rest expose one shell tool. They cost ~478 tokens
+ * of every system prompt on a registry that already overflows a 4k-context
+ * local model, and they inherited the same confirm gate shell_execute already
+ * had, so they bought no safety either.
+ *
+ * The single real thing they gave a weak model was not having to guess between
+ * `open` and `explorer`. These tests pin the cheaper answer: say the OS once,
+ * in the prompt.
+ *
+ * Run: npx vitest run src/lib/__tests__/host-platform.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { hostPlatform, platformPromptLine, type HostPlatform } from '../host-platform'
+
+describe('hostPlatform', () => {
+ it('recognises the three platforms LU ships on', () => {
+ expect(hostPlatform({ platform: 'MacIntel', userAgent: 'Mozilla/5.0 (Macintosh)' })).toBe('macos')
+ expect(hostPlatform({ platform: 'Win32', userAgent: 'Mozilla/5.0 (Windows NT 10.0)' })).toBe('windows')
+ expect(hostPlatform({ platform: 'Linux x86_64', userAgent: 'Mozilla/5.0 (X11; Linux)' })).toBe('linux')
+ })
+
+ it('reads the user agent when platform is empty, which is what WKWebView does', () => {
+ expect(hostPlatform({ platform: '', userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X)' })).toBe('macos')
+ })
+
+ it('says unknown rather than guessing', () => {
+ expect(hostPlatform({})).toBe('unknown')
+ expect(hostPlatform({ platform: 'PlayStation 5' })).toBe('unknown')
+ })
+})
+
+describe('platformPromptLine', () => {
+ it('names the OS and the shell shell_execute will really use', () => {
+ expect(platformPromptLine('macos')).toMatch(/macOS/)
+ expect(platformPromptLine('macos')).toMatch(/bash/)
+ expect(platformPromptLine('windows')).toMatch(/Windows/)
+ expect(platformPromptLine('windows')).toMatch(/PowerShell/)
+ expect(platformPromptLine('linux')).toMatch(/Linux/)
+ })
+
+ it('gives the exact open command per platform, which is the whole point', () => {
+ expect(platformPromptLine('macos')).toContain('open <path>')
+ expect(platformPromptLine('windows')).toContain('Invoke-Item <path>')
+ expect(platformPromptLine('linux')).toContain('xdg-open <path>')
+ })
+
+ it('keeps the Windows reveal as one argument, comma included', () => {
+ // Passing "/select," and the path separately makes explorer ignore the path
+ // and open Documents. The prompt has to show the joined form.
+ expect(platformPromptLine('windows')).toContain('explorer "/select,<path>"')
+ expect(platformPromptLine('windows')).toMatch(/one argument/i)
+ })
+
+ it('tells the truth about Linux having no reveal', () => {
+ expect(platformPromptLine('linux')).toMatch(/no reveal/i)
+ expect(platformPromptLine('linux')).not.toContain('/select,')
+ })
+
+ it('names how to start an application everywhere it can', () => {
+ expect(platformPromptLine('macos')).toContain('open -a')
+ expect(platformPromptLine('windows')).toContain('Start-Process')
+ expect(platformPromptLine('linux')).toContain('gtk-launch')
+ })
+
+ it('invents nothing on an unknown platform', () => {
+ const line = platformPromptLine('unknown')
+ expect(line).toMatch(/unknown/i)
+ expect(line).toMatch(/system_info/)
+ // A wrong incantation is worse than none.
+ for (const cmd of ['open ', 'explorer', 'xdg-open', 'Invoke-Item', 'gtk-launch']) {
+ expect(line).not.toContain(cmd)
+ }
+ })
+
+ it('stays far cheaper than the tools it replaced', () => {
+ // The two tool definitions were ~1914 characters, roughly 478 tokens, in
+ // EVERY system prompt. The budget that matters is MythoMax at 4k. If this
+ // line ever grows past a few hundred characters the trade stops paying.
+ for (const p of ['macos', 'windows', 'linux', 'unknown'] as HostPlatform[]) {
+ expect(platformPromptLine(p).length).toBeLessThan(400)
+ }
+ })
+})
+
+describe('the tools really are gone', () => {
+ // A registry entry is cheap to add back by reflex. This states the decision
+ // where someone re-adding it would trip over it.
+ const src = resolve(__dirname, '..', '..')
+ const read = (...p: string[]) => readFileSync(resolve(src, ...p), 'utf8')
+
+ it('no tool definition or executor is left behind', () => {
+ const tools = read('api', 'mcp', 'builtin-tools.ts')
+ expect(tools).not.toMatch(/name: 'desktop_open'/)
+ expect(tools).not.toMatch(/name: 'app_launch'/)
+ expect(tools).not.toMatch(/executeDesktopOpen|executeAppLaunch/)
+ })
+
+ it('shell_execute is the documented way to open something', () => {
+ const tools = read('api', 'mcp', 'builtin-tools.ts')
+ expect(tools).toMatch(/This is also how you open things on the desktop/)
+ })
+
+ it('the agent prompt states the platform instead of spending a call on it', () => {
+ // There is no render harness in this repo, so the prompt is guarded at the
+ // source, like DownloadBadge-autoclose.test.ts does.
+ const agent = read('hooks', 'useAgentChat.ts')
+ expect(agent).toMatch(/platformPromptLine\(\)/)
+ expect(agent).toMatch(/The OS is stated above, so do not spend a call finding it out/)
+ })
+})
diff --git a/src/lib/host-platform.ts b/src/lib/host-platform.ts
new file mode 100644
index 00000000..be5edd6d
--- /dev/null
+++ b/src/lib/host-platform.ts
@@ -0,0 +1,61 @@
+// Which machine the agent is standing on, and the one line of prompt that says
+// so.
+//
+// This replaces the desktop_open and app_launch tools (removed 2026-08-06).
+// Those were wrappers around `open` / `explorer` / `xdg-open`, which is the
+// anti-pattern Anthropic names outright in "Writing effective tools for AI
+// agents": tools that merely wrap existing software functionality. No competitor
+// ships one either; Claude Code, Cline and the rest use a single shell tool.
+// They also cost ~478 tokens of every system prompt on a registry where the
+// full tool set already does not fit a 4k-context local model, so they hurt
+// exactly the models they were meant to help. And they bought no safety:
+// shell_execute sits behind the same confirmation gate.
+//
+// The one real thing they gave a weak model was not having to guess between
+// `open` and `explorer`. That is a prompt problem, and this is the fix: ~60
+// tokens that also spare the agent a system_info round trip and improve every
+// other shell task, not just opening a folder.
+
+export type HostPlatform = 'macos' | 'windows' | 'linux' | 'unknown'
+
+interface NavLike {
+ platform?: string
+ userAgent?: string
+}
+
+function currentNav(): NavLike {
+ return typeof navigator === 'undefined' ? {} : navigator
+}
+
+/** Injectable so every branch is testable from one machine. */
+export function hostPlatform(nav: NavLike = currentNav()): HostPlatform {
+ const plat = nav.platform || ''
+ const ua = nav.userAgent || ''
+ const both = `${plat} ${ua}`
+ if (/Mac|iPhone|iPad|iPod|Macintosh/.test(both)) return 'macos'
+ if (/Win/.test(both)) return 'windows'
+ if (/Linux|X11|CrOS/.test(both)) return 'linux'
+ return 'unknown'
+}
+
+/**
+ * The platform sentence for the agent system prompt.
+ *
+ * It names the OS, the shell shell_execute will actually use, and the three
+ * desktop verbs a model would otherwise guess at. Kept to one line per platform
+ * because the models that need it most are the ones with the least room.
+ */
+export function platformPromptLine(p: HostPlatform = hostPlatform()): string {
+ switch (p) {
+ case 'macos':
+ return 'This machine runs macOS and shell_execute runs bash. Open a file or folder with `open <path>`, reveal it in Finder with `open -R <path>`, start an application with `open -a "<App Name>"`.'
+ case 'windows':
+ return 'This machine runs Windows and shell_execute runs PowerShell. Open a file or folder with `Invoke-Item <path>`, reveal it in Explorer with `explorer "/select,<path>"` (one argument, the comma matters), start an application with `Start-Process "<App Name>"`.'
+ case 'linux':
+ return 'This machine runs Linux and shell_execute runs bash. Open a file or folder with `xdg-open <path>`, start an application with `gtk-launch <name>`. There is no reveal, so open the containing folder instead.'
+ default:
+ // Never invent a platform: a wrong incantation is worse than none, and
+ // system_info is still there for the agent that really needs to know.
+ return 'The operating system of this machine is unknown. Call system_info before running a platform-specific command.'
+ }
+}
diff --git a/src/lib/mutating-tools.ts b/src/lib/mutating-tools.ts
index 3fe1c23e..9d018d07 100644
--- a/src/lib/mutating-tools.ts
+++ b/src/lib/mutating-tools.ts
@@ -28,9 +28,4 @@ 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',
])