Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
refactor(agent): drop the desktop agent loop, keep the CLI's
Akarshan Biswas8be2f1d72230
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 17cd71427..fcee4abef 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -24,6 +24,8 @@"log:default","core:webview:allow-create-webview-window","opener:allow-open-url",+ "opener:allow-open-path",+ "opener:allow-reveal-item-in-dir","store:default","vector-db:default","rag:default",@@ -65,6 +67,16 @@"url": "http://0.0.0.0:*"}]+ },+ {+ "identifier": "opener:allow-open-path",+ "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere; the same breadth the assetProtocol scope already has.",+ "windows": ["*"],+ "allow": [+ {+ "path": "**"+ }+ ]}]}diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.jsonindex 9259cdc71..e4dbeb7e1 100644--- a/src-tauri/capabilities/desktop.json+++ b/src-tauri/capabilities/desktop.json@@ -23,6 +23,8 @@"log:default","core:webview:allow-create-webview-window","opener:allow-open-url",+ "opener:allow-open-path",+ "opener:allow-reveal-item-in-dir","store:default","vector-db:default","rag:default",@@ -61,6 +63,16 @@"url": "http://0.0.0.0:*"}]+ },+ {+ "identifier": "opener:allow-open-path",+ "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere; the same breadth the assetProtocol scope already has.",+ "windows": ["*"],+ "allow": [+ {+ "path": "**"+ }+ ]}]}diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rsindex 745f90243..95983683e 100644--- a/src-tauri/src/core/agent/commands.rs+++ b/src-tauri/src/core/agent/commands.rs@@ -1,168 +1,21 @@-//! Tauri command surface for the shared agent loop. Lives in-crate (not a-//! separate plugin) because the loop depends on app-owned state-//! (`LlamacppState`, MLX sessions, provider configs, MCP). `agent_run` bridges-//! the loop's Tauri-free `mpsc` event stream onto a `tauri::ipc::Channel` and is-//! cancellable by `run_id` via `agent_cancel`.+//! Tauri command surface for the agent's project-scoped state: skills, the+//! skill hub, plugins, and the git branch shown in the workspace pill.+//!+//! The agent *loop* is no longer driven from here. The desktop runs it in the+//! renderer on the Vercel AI SDK (`web-app/src/lib/coworkRunner.ts`), calling+//! the tool plugin directly; `core::agent::r#loop` stays for the headless CLI+//! and the OpenAI-compatible API server, which still orchestrate in Rust.-use std::collections::HashMap;-use std::sync::Arc;--use tauri::ipc::Channel;-use tauri::{AppHandle, Manager, Runtime, State};-use tauri_plugin_llamacpp::state::LlamacppState;-use tokio::sync::{mpsc, oneshot, Mutex};--use crate::core::agent::events::StreamEvent;use crate::core::agent::git;use crate::core::agent::plugins;use crate::core::agent::project::{- agent_toml_path, ensure_project, load_agent_config, permissions_from,- set_skills_enabled_in_agent_toml,+ agent_toml_path, ensure_project, load_agent_config, set_skills_enabled_in_agent_toml,};-use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs};use crate::core::agent::skill_hub;use crate::core::agent::skills as agent_skills;-use crate::core::app::commands::get_jan_data_folder_path;-use crate::core::state::AppState;-use tauri_plugin_agent_tools::permissions::ToolPermissions;use tauri_plugin_agent_tools::skills::{self, SkillMeta};-use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use tauri_plugin_agent_tools::workspace;-/// Registry of in-flight agent runs keyed by client-supplied `run_id`, holding a-/// one-shot cancel sender per run. Managed via `app.manage(AgentRuns::default())`.-#[derive(Default)]-pub struct AgentRuns(pub Arc<Mutex<HashMap<String, oneshot::Sender<()>>>>);--/// Registry of in-flight permission prompts keyed by request_id, shared with the-/// agent loop so `agent_permission_respond` can resolve the awaiting tool call.-#[derive(Default)]-pub struct AgentPermissions(pub Arc<Mutex<HashMap<String, oneshot::Sender<PermissionDecision>>>>);--fn build_orchestration_args<R: Runtime>(- app_handle: &AppHandle<R>,- state: &AppState,-) -> OrchestrationArgs {- let llama_state: State<Arc<LlamacppState>> = app_handle.state();- let llama_state_arc = llama_state.inner().clone();-- // MLX is macOS-only; elsewhere the session map is permanently empty.- #[cfg(target_os = "macos")]- let mlx_sessions = {- let mlx_state: State<tauri_plugin_mlx::state::MlxState> = app_handle.state();- mlx_state.mlx_server_process.clone()- };- #[cfg(not(target_os = "macos"))]- let mlx_sessions: Arc<Mutex<HashMap<i32, crate::core::server::MlxBackendSession>>> =- Arc::new(Mutex::new(HashMap::new()));-- OrchestrationArgs {- client: crate::core::agent::upstream::agent_http_client(),- provider_configs: state.provider_configs.clone(),- llama_state: llama_state_arc,- mlx_sessions,- mcp_servers: state.mcp_servers.clone(),- mcp_settings: state.mcp_settings.clone(),- jan_data_folder: get_jan_data_folder_path(app_handle.clone())- .to_string_lossy()- .into_owned(),- permissions: ToolPermissions::allow_all(),- project_root: None,- permission_requests: Arc::new(Mutex::new(HashMap::new())),- ask_requests: None,- todo_registry: None,- system_prompt_override: None,- subagents_enabled: true,- max_parallel_subagents: crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,- auto_approve: false,- run_mode: crate::core::agent::plan::RunMode::Normal,- session_id: None,- sandbox: None,- }-}--/// Run the agent loop for one request, streaming `StreamEvent`s to `on_event`.-/// Resolves when the loop reaches a terminal state (or is cancelled); the-/// terminal `Done`/`Error` is also delivered over the channel.-#[tauri::command]-pub async fn agent_run<R: Runtime>(- app_handle: AppHandle<R>,- state: State<'_, AppState>,- runs: State<'_, AgentRuns>,- perms_registry: State<'_, AgentPermissions>,- run_id: String,- body: serde_json::Value,- on_event: Channel<StreamEvent>,-) -> Result<(), String> {- let mut args = build_orchestration_args(&app_handle, &state);- args.permission_requests = perms_registry.0.clone();-- // When a project is explicitly named, its agent.toml governs tool permissions.- // The project is auto-managed: scaffold a `.jan/agent/` on first use, then- // load it. A malformed config is still a hard error (never silently permissive).- if let Some(project) = body.get("project").and_then(|v| v.as_str()) {- let project_root = std::path::PathBuf::from(project);- ensure_project(&project_root)?;- let cfg = load_agent_config(&project_root)?;- args.permissions = permissions_from(&cfg);- args.project_root = Some(project_root);- }-- let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();- let forward = tokio::spawn(async move {- while let Some(ev) = rx.recv().await {- if on_event.send(ev).is_err() {- break;- }- }- });-- let (cancel_tx, cancel_rx) = oneshot::channel::<()>();- runs.0.lock().await.insert(run_id.clone(), cancel_tx);-- // Cancellation is a normal terminal state: emit one `cancelled` event and- // resolve Ok so the invoke promise does not also surface as an error.- let result = tokio::select! {- r = run_orchestration_streamed(&tx, &body, &args) => r,- _ = cancel_rx => {- let _ = tx.send(StreamEvent::Error {- code: "cancelled".to_string(),- message: "Agent run cancelled".to_string(),- });- Ok(serde_json::Value::Null)- }- };-- drop(tx);- let _ = forward.await;- runs.0.lock().await.remove(&run_id);-- result.map(|_| ())-}--/// Cancel an in-flight `agent_run` by `run_id`. No-op if the run already-/// finished or never existed.-#[tauri::command]-pub async fn agent_cancel(runs: State<'_, AgentRuns>, run_id: String) -> Result<(), String> {- if let Some(cancel_tx) = runs.0.lock().await.remove(&run_id) {- let _ = cancel_tx.send(());- }- Ok(())-}--/// Resolve an in-flight permission prompt emitted by the agent loop.-#[tauri::command]-pub async fn agent_permission_respond(- perms_registry: State<'_, AgentPermissions>,- request_id: String,- decision: PermissionDecision,-) -> Result<(), String> {- if let Some(tx) = perms_registry.0.lock().await.remove(&request_id) {- let _ = tx.send(decision);- }- Ok(())-}-/// Strip the internal `ERROR: ` prefix (an agent-tool-output convention) so the/// message reads cleanly in a UI toast.fn ui_error(e: String) -> String {@@ -234,10 +87,7 @@ pub async fn agent_skill_enabled_get(project: String) -> Result<Vec<String>, Str/// Set the project's enabled-skill whitelist. Empty = all skills enabled./// Persisted to `[skills].enabled` in agent.toml (format-preserving).#[tauri::command]-pub async fn agent_skill_enabled_set(- project: String,- enabled: Vec<String>,-) -> Result<(), String> {+pub async fn agent_skill_enabled_set(project: String, enabled: Vec<String>) -> Result<(), String> {let root = std::path::PathBuf::from(&project);ensure_project(&root)?;set_skills_enabled_in_agent_toml(&agent_toml_path(&root), &enabled).map_err(ui_error)diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 94ebd0fbe..f6b1c4b56 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -957,6 +957,9 @@ impl ToolInvoker for CompositeToolInvoker {&args,&self.project_root,Some(self.scratch_root.as_path()),+ // The CLI works *in* the project, so it has no separate+ // read-only root to attach.+ &[],&self.permissions,&snapshot,self.sandbox,diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex 6ee86b226..c22441f23 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -122,7 +122,12 @@ pub(crate) struct AgentSection {pub send_reasoning: Option<bool>,}+// `default`/`allow`/`deny`/`allow_write` are consumed by `permissions_from`,+// which only the CLI calls: the desktop's tool gate lives in the plugin. They+// stay parsed regardless so the desktop round-trips an `agent.toml` written by+// the CLI instead of silently dropping the user's policy on save.#[derive(Debug, Clone, Default, Deserialize)]+#[cfg_attr(not(feature = "cli"), allow(dead_code))]pub(crate) struct ToolsSection {#[serde(default)]pub default: Option<String>,@@ -261,6 +266,10 @@ pub(crate) fn enabled_skills(project_root: &Path) -> Vec<String> {}/// Build a `ToolPermissions` from the parsed `[tools]` section.+///+/// CLI-only: the desktop no longer runs the agent loop in Rust, so its tool+/// gating is the plugin's, not this one.+#[cfg_attr(not(feature = "cli"), allow(dead_code))]pub(crate) fn permissions_from(cfg: &AgentToml) -> ToolPermissions {let default = cfg.tools@@ -467,8 +476,7 @@ mod tests {/// The scaffold documents the key, so it has to stay parseable as written.#[test]fn scaffold_template_parses_with_allow_network_documented() {- let cfg: AgentToml =- toml::from_str(AGENT_TOML_TEMPLATE).expect("scaffold template parses");+ let cfg: AgentToml = toml::from_str(AGENT_TOML_TEMPLATE).expect("scaffold template parses");assert_eq!(cfg.tools.allow_network, None);assert!(AGENT_TOML_TEMPLATE.contains("allow_network"));}@@ -477,8 +485,10 @@ mod tests {fn ensure_errors_when_project_dir_missing() {// A mistyped --project (e.g. wrong case) must fail fast, not scaffold a// phantom project dir from nothing.- let root = std::env::temp_dir()- .join(format!("jan_agent_missing_{}", COUNTER.fetch_add(1, Ordering::SeqCst)));+ let root = std::env::temp_dir().join(format!(+ "jan_agent_missing_{}",+ COUNTER.fetch_add(1, Ordering::SeqCst)+ ));assert!(!root.exists());let err = ensure_project(&root).expect_err("must reject missing dir");assert!(err.contains("does not exist"), "err: {err}");@@ -565,12 +575,19 @@ mod tests {let root = unique_root("max_parallel");ensure_project(&root).expect("scaffold");let cfg = load_agent_config(&root).expect("load");- assert_eq!(cfg.agent.max_parallel_subagents, None, "template leaves it unset");+ assert_eq!(+ cfg.agent.max_parallel_subagents, None,+ "template leaves it unset"+ );// Explicit value round-trips through the /settings writer; unset removes.let path = agent_toml_path(&root);- set_agent_key(&path, "max_parallel_subagents", Some(toml_edit::value(4i64)))- .expect("write");+ set_agent_key(+ &path,+ "max_parallel_subagents",+ Some(toml_edit::value(4i64)),+ )+ .expect("write");let cfg = load_agent_config(&root).expect("load");assert_eq!(cfg.agent.max_parallel_subagents, Some(4));set_agent_key(&path, "max_parallel_subagents", None).expect("unset");@@ -589,8 +606,7 @@ mod tests {// Explicit value round-trips through the /settings writer; unset removes.let path = agent_toml_path(&root);- set_agent_key(&path, "show_reasoning", Some(toml_edit::value(true)))- .expect("write");+ set_agent_key(&path, "show_reasoning", Some(toml_edit::value(true))).expect("write");let cfg = load_agent_config(&root).expect("load");assert_eq!(cfg.agent.show_reasoning, Some(true));set_agent_key(&path, "show_reasoning", None).expect("unset");@@ -611,8 +627,7 @@ mod tests {assert_eq!(cfg.agent.send_reasoning, None, "template leaves it unset");let path = agent_toml_path(&root);- set_agent_key(&path, "send_reasoning", Some(toml_edit::value(false)))- .expect("write");+ set_agent_key(&path, "send_reasoning", Some(toml_edit::value(false))).expect("write");let cfg = load_agent_config(&root).expect("load");assert_eq!(cfg.agent.send_reasoning, Some(false));set_agent_key(&path, "send_reasoning", None).expect("unset");@@ -630,7 +645,10 @@ mod tests {set_agent_key(&path, "budget.max_tokens", Some(toml_edit::value(60i64))).expect("write");let raw = std::fs::read_to_string(&path).unwrap();- assert!(raw.contains("max_tokens = 60"), "written under [budget]: {raw}");+ assert!(+ raw.contains("max_tokens = 60"),+ "written under [budget]: {raw}"+ );set_agent_key(&path, "budget.max_tokens", None).expect("unset");let raw = std::fs::read_to_string(&path).unwrap();@@ -652,16 +670,14 @@ mod tests {#[cfg(feature = "cli")]#[test]fn scaffold_template_leaves_session_budget_unset() {- let cfg: AgentToml =- toml::from_str(AGENT_TOML_TEMPLATE).expect("scaffold template parses");+ let cfg: AgentToml = toml::from_str(AGENT_TOML_TEMPLATE).expect("scaffold template parses");assert_eq!(cfg.budget.max_tokens, None);}#[cfg(feature = "cli")]#[test]fn budget_max_tokens_parses_when_set() {- let cfg: AgentToml =- toml::from_str("[budget]\nmax_tokens = 200000\n").expect("parses");+ let cfg: AgentToml = toml::from_str("[budget]\nmax_tokens = 200000\n").expect("parses");assert_eq!(cfg.budget.max_tokens, Some(200_000));}diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rsindex 755aa0e78..aeb66d490 100644--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@ -349,30 +349,6 @@ pub fn open_app_directory<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {Ok(())}-#[tauri::command]-pub fn open_file_explorer(path: String) -> Result<(), String> {- let path = PathBuf::from(path);- let (program, arg): (&str, std::ffi::OsString) = if cfg!(target_os = "windows") {- // Normalize extended-length paths (\\?\...) for explorer compatibility.- let mut path_str = path.to_string_lossy().into_owned();- if let Some(stripped) = path_str.strip_prefix(r"\\?\UNC\") {- path_str = format!(r"\\{}", stripped);- } else if let Some(stripped) = path_str.strip_prefix(r"\\?\") {- path_str = stripped.to_string();- }- ("explorer", path_str.into())- } else if cfg!(target_os = "macos") {- ("open", path.into())- } else {- ("xdg-open", path.into())- };- std::process::Command::new(program)- .arg(arg)- .status()- .map_err(|e| format!("Failed to open file explorer: {e}"))?;- Ok(())-}-#[tauri::command]pub async fn read_logs<R: Runtime>(app: AppHandle<R>) -> Result<String, String> {let log_path = get_jan_data_folder_path(app).join("logs").join("app.log");diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex ef8044932..a26fd9d7f 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -70,7 +70,6 @@ macro_rules! invoke_commands_with_extras {// System commandscore::system::commands::relaunch,core::system::commands::open_app_directory,- core::system::commands::open_file_explorer,core::system::commands::factory_reset,core::system::commands::take_pending_webdata_reset,core::system::commands::read_logs,@@ -85,9 +84,6 @@ macro_rules! invoke_commands_with_extras {core::server::commands::stop_server,core::server::commands::get_server_status,// Agent commands- core::agent::commands::agent_run,- core::agent::commands::agent_cancel,- core::agent::commands::agent_permission_respond,core::agent::commands::agent_skill_list,core::agent::commands::agent_skill_read,core::agent::commands::agent_skill_write,@@ -331,8 +327,6 @@ pub fn run() {mcp_reconnect_notify: Arc::new(tokio::sync::Notify::new()),mcp_last_known_tools: Arc::new(Mutex::new(HashMap::new())),})- .manage(core::agent::commands::AgentRuns::default())- .manage(core::agent::commands::AgentPermissions::default()).setup(|app| {app.handle().plugin(tauri_plugin_log::Builder::default()