diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 2d83171d6b..f19e360503 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -450,6 +450,31 @@ struct TaskFile { /// The user named the task: its agent's own title updates no longer replace it. #[serde(default, skip_serializing_if = "is_false")] title_renamed: bool, + /// Start the first session as a fork of a recorded native one (once). + #[serde(default, skip_serializing_if = "Option::is_none")] + pending_native_fork: Option, +} + +/// A session to start as a fork of the recorded one: its source, and the id the host +/// chooses for the fork (claude); codex assigns its own. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct ForkStart { + source: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + target: Option, +} + +/// A canonical lowercase UUID, the only session id shape either native agent writes. +fn canonical_uuid(value: &str) -> bool { + value.len() == 36 + && value.bytes().enumerate().all(|(index, byte)| { + if matches!(index, 8 | 13 | 18 | 23) { + byte == b'-' + } else { + byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte) + } + }) } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -502,6 +527,8 @@ struct TaskState { pending_rollback: u32, /// The user named the task; see `TaskFile::title_renamed`. title_renamed: bool, + /// See `TaskFile::pending_native_fork`: cleared once a session is established. + pending_native_fork: Option, /// A turn is running or about to (prompts arriving now are queued). busy: bool, /// Background tasks the agent reported as running (`run_in_background` commands and @@ -1023,6 +1050,92 @@ impl AgentManager { subagents: Vec::new(), pending_rollback: 0, title_renamed: true, + pending_native_fork: None, + }; + let handle = Task::restore(file, self.shared.clone()); + self.tasks.write().insert(task.id.clone(), handle.clone()); + handle.emit_task(); + handle.persist(); + Ok(task) + } + + /// Forks a recorded external session into a new task: its first turn continues the + /// recording as the agent's own fork, under an id the host chooses. The session must + /// belong to this project and have been recorded in `cwd`. + pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult { + if !matches!(provider, "claude" | "codex") { + return Err(IdeError::invalid(format!("cannot fork {provider} sessions"))); + } + if !canonical_uuid(session_id) { + return Err(IdeError::invalid("the recorded session has no canonical id")); + } + let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?; + if self.imported_session_ids().contains(session_id) { + return Err(IdeError::invalid("that session is already a task")); + } + let found = self + .external_sessions() + .into_iter() + .find(|s| s.provider == provider && s.session_id == session_id) + .ok_or_else(|| IdeError::not_found(format!("unknown {provider} session {session_id}")))?; + let recorded = found + .cwd + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .ok_or_else(|| IdeError::invalid("the recorded session has no working directory"))?; + let canonical = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if canonical(cwd) != canonical(&recorded) { + return Err(IdeError::invalid("the session was recorded in another directory")); + } + let root = self.shared.paths.project_root.clone(); + let config = self.shared.known_config(&spec.id); + let now = now_ms(); + let id = uuid::Uuid::new_v4().simple().to_string(); + // The host names the fork's session id for claude; codex assigns its own. + let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string()); + let task = AgentTask { + project_root: Some(IpcPath(root)), + id, + title: found.title, + provider: spec.id.clone(), + model: model_of(&config), + status: AgentStatus::Ready, + isolation: Isolation::Local, + cwd: IpcPath(recorded), + branch: None, + base: None, + base_commit: None, + error: None, + created_ms: now, + updated_ms: now, + config, + commands: self.shared.known_commands(&spec.id), + usage: None, + queue: Vec::new(), + capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(), + resets_ms: None, + retry: None, + background: Box::default(), + mcp_overrides: BTreeMap::new(), + skill_overrides: BTreeMap::new(), + stats: Box::default(), + }; + let file = TaskFile { + task: task.clone(), + session_id: target.clone(), + entries: Vec::new(), + wanted: Vec::new(), + pending_model: None, + pending_switch: None, + before: BTreeMap::new(), + saved: None, + touched: Some(BTreeSet::new()), + turn: None, + turns: Vec::new(), + subagents: Vec::new(), + pending_rollback: 0, + title_renamed: true, + pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target }), }; let handle = Task::restore(file, self.shared.clone()); self.tasks.write().insert(task.id.clone(), handle.clone()); @@ -1151,6 +1264,7 @@ impl AgentManager { subagents: Vec::new(), pending_rollback: 0, title_renamed: false, + pending_native_fork: None, }; let handle = Task::restore(file, self.shared.clone()); handle.state.lock().busy = !req.idle; @@ -1516,6 +1630,7 @@ impl AgentManager { subagents: s.conversation.saved_subagents(), pending_rollback: total - keep, title_renamed: s.title_renamed, + pending_native_fork: None, } }; // Copying may have started the source's agent: it stops again once idle. @@ -2420,6 +2535,7 @@ impl Task { turns, pending_rollback: file.pending_rollback, title_renamed: file.title_renamed, + pending_native_fork: file.pending_native_fork, busy: false, background_tasks: Vec::new(), shell_context: Vec::new(), @@ -2695,6 +2811,7 @@ impl Task { subagents: s.conversation.saved_subagents(), pending_rollback: s.pending_rollback, title_renamed: s.title_renamed, + pending_native_fork: s.pending_native_fork.clone(), } }; let bytes = serde_json::to_vec(©); @@ -3357,66 +3474,101 @@ impl Task { let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await; // Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`). let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned(); + let pending_native_fork = self.state.lock().pending_native_fork.clone(); let mut tried_auth = false; let mut session = None; - let start_fresh = self.start_fresh.load(Ordering::Acquire); - if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) { - return Err(SessionOpenError { - message: "The agent does not support resuming this session.".into(), - allow_acp_fallback: false, - }); - } - if let (Some(id), true, false) = (saved, can_load, start_fresh) { - // The replay goes before what this turn already showed (the user's message). - let shown = self.adopts_replay().then(|| self.take_entries()); - self.replaying.store(true, Ordering::Release); + if let Some(fork) = pending_native_fork { + if !capabilities.fork { + return Err(SessionOpenError { + message: "the agent can't continue a recorded session".into(), + allow_acp_fallback: false, + }); + } let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots); - params["sessionId"] = json!(&id); - let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await; - tokio::time::sleep(REPLAY_GRACE).await; - self.replaying.store(false, Ordering::Release); - if let Some(shown) = shown { - if loaded.is_ok() { - self.adopting_replay.store(false, Ordering::Release); - let changed = self.state.lock().conversation.end_turn(None); - self.mark_dirty(changed); - } else { - // A failed load may still have replayed part of it. - self.take_entries(); - } - for entry in shown { - self.push_entry(entry); + params["sessionId"] = json!(&fork.source); + if let Some(target) = &fork.target { + match params["_meta"].as_object_mut() { + Some(meta) => { + if let Some(openidea) = meta.entry("openidea").or_insert_with(|| json!({})).as_object_mut() { + openidea.insert("forkSessionId".into(), json!(target)); + } + } + None => params["_meta"] = json!({ "openidea": { "forkSessionId": target } }), } } - match loaded { - Ok(v) => session = Some((id, v)), - // Not silently: a new session would lose the conversation and replace the saved id. - Err(e) => { - tracing::info!("agent task {}: session/load failed: {e}", self.id); - if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) { - return Err(SessionOpenError { message, allow_acp_fallback: false }); + let reply = self + .request_with_auth(&peer, &init, &mut tried_auth, "session/fork", params) + .await + .map_err(|e| SessionOpenError { message: self.describe(e), allow_acp_fallback: false })?; + let id = reply + .get("sessionId") + .and_then(Value::as_str) + .ok_or_else(|| SessionOpenError { + message: "the agent returned no session".into(), + allow_acp_fallback: false, + })? + .to_owned(); + session = Some((id, reply)); + } else { + let start_fresh = self.start_fresh.load(Ordering::Acquire); + if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) { + return Err(SessionOpenError { + message: "The agent does not support resuming this session.".into(), + allow_acp_fallback: false, + }); + } + if let (Some(id), true, false) = (saved, can_load, start_fresh) { + // The replay goes before what this turn already showed (the user's message). + let shown = self.adopts_replay().then(|| self.take_entries()); + self.replaying.store(true, Ordering::Release); + let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots); + params["sessionId"] = json!(&id); + let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await; + tokio::time::sleep(REPLAY_GRACE).await; + self.replaying.store(false, Ordering::Release); + if let Some(shown) = shown { + if loaded.is_ok() { + self.adopting_replay.store(false, Ordering::Release); + let changed = self.state.lock().conversation.end_turn(None); + self.mark_dirty(changed); + } else { + // A failed load may still have replayed part of it. + self.take_entries(); } - if pending_model.is_some() { + for entry in shown { + self.push_entry(entry); + } + } + match loaded { + Ok(v) => session = Some((id, v)), + // Not silently: a new session would lose the conversation and replace the saved id. + Err(e) => { + tracing::info!("agent task {}: session/load failed: {e}", self.id); + if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) { + return Err(SessionOpenError { message, allow_acp_fallback: false }); + } + if pending_model.is_some() { + return Err(SessionOpenError { + message: format!( + "Couldn't reopen this conversation's {} session: {}", + spec.name, + self.describe(e) + ), + allow_acp_fallback: false, + }); + } + self.start_fresh.store(true, Ordering::Release); return Err(SessionOpenError { message: format!( - "Couldn't reopen this conversation's {} session: {}", + "Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \ + continue in a new session. The agent won't see the earlier conversation.", spec.name, self.describe(e) ), allow_acp_fallback: false, }); } - self.start_fresh.store(true, Ordering::Release); - return Err(SessionOpenError { - message: format!( - "Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \ - continue in a new session. The agent won't see the earlier conversation.", - spec.name, - self.describe(e) - ), - allow_acp_fallback: false, - }); } } } @@ -3604,6 +3756,8 @@ impl Task { s.pending_model = None; s.task.capabilities = capabilities; s.session_id = Some(session_id.clone()); + // The recorded session is forked (or the fork resumed): the one-shot intent is spent. + s.pending_native_fork = None; self.start_fresh.store(false, Ordering::Release); // The (re)started process runs nothing yet: whatever it reports next is all of it. s.background_tasks = Vec::new(); diff --git a/crates/ide-agent/src/native/claude/mod.rs b/crates/ide-agent/src/native/claude/mod.rs index 4abd90aa02..b3acae5e36 100644 --- a/crates/ide-agent/src/native/claude/mod.rs +++ b/crates/ide-agent/src/native/claude/mod.rs @@ -460,24 +460,43 @@ impl Shim { Ok(json!({ "configOptions": session.st.lock().settings.options() })) } "session/fork" => { - let source = self.session(¶ms)?; - let id = new_uuid(false); - let (start, settings) = { - let st = source.st.lock(); - let start = match &st.start { - Start::New { .. } if !st.pending && st.titled_or_prompted() => { - Start::Fork { from: source.id.clone(), id: id.clone(), at: None } - } - Start::New { .. } => Start::New { id: id.clone() }, - Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => { - Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() } - } - _ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None }, - }; - (start, st.settings.clone()) + let source_id = + params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?; + let source = self.sessions.lock().get(source_id).cloned(); + // The host names the fork's session id so the task knows it before the CLI + // starts; only a canonical UUID is accepted. + let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str); + if let Some(target) = requested + && !crate::canonical_uuid(target) + { + return Err(invalid("A fork session id must be a canonical UUID")); + } + let id = requested.map_or_else(|| new_uuid(false), str::to_owned); + if self.sessions.lock().contains_key(&id) { + return Err(invalid(format!("session {id} is already open"))); + } + let cwd = source.as_ref().map_or_else(|| self.cwd_of(¶ms), |session| session.cwd.clone()); + let (start, settings) = match &source { + Some(source) => { + let st = source.st.lock(); + let start = match &st.start { + Start::New { .. } if !st.pending && st.titled_or_prompted() => { + Start::Fork { from: source.id.clone(), id: id.clone(), at: None } + } + Start::New { .. } => Start::New { id: id.clone() }, + Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => { + Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() } + } + _ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None }, + }; + (start, st.settings.clone()) + } + // A recorded session is not open in this connection: the CLI forks it + // from its transcript on disk when the task's first prompt starts it. + None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()), }; self.save_pending(&id, Some(&start)); - let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms); + let session = self.add_session(&id, cwd, start, true, ¶ms); session.st.lock().settings = settings; let options = session.st.lock().settings.options(); Ok(json!({ "sessionId": id, "configOptions": options })) diff --git a/crates/ide-agent/src/native/claude/tests.rs b/crates/ide-agent/src/native/claude/tests.rs index b7a6f58519..0fac18931a 100644 --- a/crates/ide-agent/src/native/claude/tests.rs +++ b/crates/ide-agent/src/native/claude/tests.rs @@ -652,6 +652,84 @@ async fn replay_resume() { assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}"); } +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() { + /// Registering a fork must not start a process: its first prompt does. + struct NoLaunch; + impl Cli for NoLaunch { + fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result { + panic!("session/fork must not launch the CLI") + } + } + + let config = tempfile::tempdir().unwrap(); + let pending = tempfile::tempdir().unwrap(); + let h = Harness::connect( + Arc::new(NoLaunch), + config.path().to_path_buf(), + pending.path().to_path_buf(), + std::env::temp_dir(), + Vec::new(), + ) + .await; + let source = "11111111-1111-4111-8111-111111111111"; + let target = "22222222-2222-4222-8222-222222222222"; + let reply = h + .request( + "session/fork", + json!({ + "sessionId": source, + "cwd": h.cwd, + "mcpServers": [], + "_meta": { "openidea": { "forkSessionId": target } } + }), + ) + .await + .unwrap(); + assert_eq!(reply["sessionId"], target); + // The host chose this id for the fork: the next process must fork the recorded + // session under exactly it. + let saved: Value = + serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap(); + assert_eq!(saved, json!({ "fork": source, "id": target, "at": null })); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_rejects_a_requested_id_that_is_not_canonical() { + struct NoLaunch; + impl Cli for NoLaunch { + fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result { + panic!("no process") + } + } + + let config = tempfile::tempdir().unwrap(); + let pending = tempfile::tempdir().unwrap(); + let h = Harness::connect( + Arc::new(NoLaunch), + config.path().to_path_buf(), + pending.path().to_path_buf(), + std::env::temp_dir(), + Vec::new(), + ) + .await; + for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] { + let error = h + .request( + "session/fork", + json!({ + "sessionId": "11111111-1111-4111-8111-111111111111", + "cwd": h.cwd, + "mcpServers": [], + "_meta": { "openidea": { "forkSessionId": rejected } } + }), + ) + .await + .expect_err("only a canonical id may name the fork"); + assert!(error.to_string().contains("canonical"), "{rejected}: {error}"); + } +} + // ---------- recording ---------- /// Passes the real CLI's stdio through, keeping what went over it. diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 86c727970f..6ef9647be6 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -63,6 +63,8 @@ struct FakeAgent { session_steering: bool, /// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`. mcp_calls: Mutex)>>, + /// The params of every `session/fork`, in order. + forks: Mutex>, /// The content blocks of each `session/prompt`. prompts: Mutex>, } @@ -203,7 +205,11 @@ impl Handler for FakeAgent { "modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]}, "configOptions": options})) } - "session/fork" => Ok(json!({"sessionId": "s2"})), + "session/fork" => { + self.forks.lock().push(params.clone()); + let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str); + Ok(json!({ "sessionId": requested.unwrap_or("s2") })) + } "_openidea/stop_task" => { self.calls.lock().push(format!("{method} {}", params["taskId"])); Ok(json!({})) @@ -2773,6 +2779,128 @@ async fn forks_rollbacks_and_steering() { restored.shutdown(); } +const NATIVE_SOURCE: &str = "11111111-1111-4111-8111-111111111111"; +const NATIVE_TARGET: &str = "22222222-2222-4222-8222-222222222222"; + +/// Plants a recorded claude transcript for `session_id` under the project's escaped folder. +fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) { + let config = root.join("claude-config"); + mgr.set_builtin_env( + "claude", + [("CLAUDE_CONFIG_DIR".to_string(), config.to_string_lossy().into_owned())].into_iter().collect(), + ) + .unwrap(); + mgr.reload_providers(); + let escaped: String = + root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect(); + let transcript = config.join("projects").join(escaped).join(format!("{session_id}.jsonl")); + std::fs::create_dir_all(transcript.parent().unwrap()).unwrap(); + std::fs::write( + &transcript, + format!( + "{}\n", + json!({ + "type": "user", + "uuid": "u1", + "parentUuid": null, + "message": {"role": "user", "content": "fix the login bug"}, + "cwd": root.to_string_lossy(), + }) + ), + ) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE); + + let task = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap(); + assert_eq!(task.provider, "claude"); + assert_eq!(task.status, AgentStatus::Ready); + assert_eq!(task.isolation, Isolation::Local); + + mgr.prompt(&task.id, text("again"), true).await.unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + + let forks = agent.forks.lock().clone(); + assert_eq!(forks.len(), 1, "one fork start"); + assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE); + let target = forks[0]["_meta"]["openidea"]["forkSessionId"].as_str().unwrap(); + assert!(canonical_uuid(target), "the host chooses a canonical fork id: {target}"); + assert_ne!(target, NATIVE_SOURCE); + assert!( + !agent.calls.lock().iter().any(|call| call == "session/new" || call == "session/load"), + "the task forks the recorded session instead of starting or loading another" + ); + assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(target)); + mgr.shutdown(); +} + +/// Plants a recorded codex rollout for `session_id` under the home `.codex/sessions` tree. +fn plant_codex_session(root: &Path, session_id: &str) { + let dir = root.join(".codex").join("sessions").join("2026").join("11").join("23"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join(format!("rollout-{session_id}.jsonl")), + format!( + "{}\n{}\n", + json!({"type": "session_meta", "payload": {"id": session_id, "cwd": root.to_string_lossy()}}), + json!({"type": "event_msg", "payload": {"type": "user_message", "message": "fix the login bug"}}) + ), + ) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_uses_the_id_codex_assigns() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + plant_codex_session(tmp.path(), NATIVE_SOURCE); + + let task = mgr.fork_session("codex", NATIVE_SOURCE, tmp.path()).unwrap(); + assert_eq!(task.status, AgentStatus::Ready); + mgr.prompt(&task.id, text("again"), true).await.unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + + let forks = agent.forks.lock().clone(); + assert_eq!(forks.len(), 1); + assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE); + assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "codex names its own fork"); + assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2")); + mgr.shutdown(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_rejects_invalid_input_before_starting() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE); + + // Non-native provider, malformed id, unknown session, wrong directory. + let cases: [(&str, &str, &Path, ide_core::error::ErrorKind); 4] = [ + ("gemini", NATIVE_SOURCE, tmp.path(), ide_core::error::ErrorKind::InvalidInput), + ("claude", "not-a-uuid", tmp.path(), ide_core::error::ErrorKind::InvalidInput), + ("claude", NATIVE_TARGET, tmp.path(), ide_core::error::ErrorKind::NotFound), + ("claude", NATIVE_SOURCE, Path::new("/elsewhere"), ide_core::error::ErrorKind::InvalidInput), + ]; + for (index, (provider, id, cwd, kind)) in cases.into_iter().enumerate() { + let error = mgr.fork_session(provider, id, cwd).unwrap_err(); + assert_eq!(error.kind, kind, "case {index}: {error}"); + } + // A session already held by a task cannot be forked again. + mgr.import_session("claude", NATIVE_SOURCE).unwrap(); + let error = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput, "{error}"); + assert!(agent.calls.lock().is_empty(), "no process may start"); + mgr.shutdown(); +} + #[tokio::test(flavor = "multi_thread")] async fn usage_limits_and_late_settings() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-extension/src/capability.rs b/crates/ide-extension/src/capability.rs index 6f7f84fa5c..c7e311b133 100644 --- a/crates/ide-extension/src/capability.rs +++ b/crates/ide-extension/src/capability.rs @@ -62,6 +62,8 @@ pub enum Capability { /// Load the plugin's Java agent into the JVMs of Java run configurations. Never /// declared: it comes from `[[contributes.javaAgents]]`. JavaAgent, + /// Fork a recorded native agent session into a new task in the open project (API 1.18). + Agents, } /// How a grant is presented (plan 4.2). @@ -91,7 +93,8 @@ impl Capability { | Self::Secrets | Self::InputEvents | Self::Clipboard - | Self::ClipboardRead => Risk::Medium, + | Self::ClipboardRead + | Self::Agents => Risk::Medium, // A trusted project's own files name the programs the IDE starts (its settings, its // build scripts), so writing them is running code. Self::ProjectWrite @@ -149,6 +152,7 @@ impl Capability { Self::FsRead(path) => format!("Read files under {path}, outside the project"), Self::FsWrite(path) => format!("Change files under {path}, outside the project"), Self::JavaAgent => "Run code inside the Java applications you start".into(), + Self::Agents => "Fork a recorded agent session into a new task in the open project".into(), } } @@ -276,6 +280,7 @@ impl fmt::Display for Capability { Self::FsRead(p) => write!(f, "fs.read:{p}"), Self::FsWrite(p) => write!(f, "fs.write:{p}"), Self::JavaAgent => f.write_str("java.agent"), + Self::Agents => f.write_str("agents"), } } } @@ -355,6 +360,7 @@ impl FromStr for Capability { "clipboard" => Self::Clipboard, "clipboard.read" => Self::ClipboardRead, "java.agent" => Self::JavaAgent, + "agents" => Self::Agents, _ => return Err(format!("unknown capability {s:?}")), }) } diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs index ce3a0c8c04..b1d27c7ad4 100644 --- a/crates/ide-extension/src/manifest.rs +++ b/crates/ide-extension/src/manifest.rs @@ -369,6 +369,9 @@ impl Manifest { if matches!(cap, Capability::ClipboardRead) { self.needs_api(&format!("capability `{cap}`"), 11)?; } + if matches!(cap, Capability::Agents) { + self.needs_api(&format!("capability `{cap}`"), 18)?; + } if matches!(cap, Capability::JavaAgent) { return Err( "`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into() diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index ccbb286303..d171d4eaa2 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -281,6 +281,21 @@ pub async fn agent_import_session( blocking(move || agents.import_session(&provider, &session_id)).await } +/// Forks a recorded external session into a new task: its first turn continues the recording +/// as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded. +#[command(trust = trusted)] +pub async fn agent_fork_session( + host: &Host, + window: &str, + provider: String, + session_id: String, + cwd: String, +) -> IdeResult { + host.require_trust(window)?; + let agents = host.project(window)?.agents.clone(); + blocking(move || agents.fork_session(&provider, &session_id, std::path::Path::new(&cwd))).await +} + #[command(trust = trusted)] pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult { host.require_trust(window)?; @@ -1445,6 +1460,7 @@ ide_command::domain!( agent_entries, agent_external_sessions, agent_fork, + agent_fork_session, agent_grouped_changes, agent_hermes_profiles, agent_import_session, diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index 43fe9b4f37..53d4e7addd 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -68,6 +68,17 @@ pub trait PluginWorkspace: Send + Sync { fn problems(&self, _client: &str, _path: Option<&Path>) -> Result, HostError> { Ok(Vec::new()) } + /// Fork a recorded native agent session into a new task in the invoking + /// window's project, returning the new task id (API 1.18). + fn fork_agent_session( + &self, + _client: &str, + _agent: &str, + _session_id: &str, + _cwd: &Path, + ) -> Result { + Err(HostError::Failed("agent fork unavailable".into())) + } /// Roots of the open projects. fn projects(&self) -> Vec; @@ -1918,6 +1929,12 @@ impl HostApi for PluginApi { fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError> { self.set_file_icon_decorations(set, items) } + fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result { + self.shared + .workspace() + .ok_or_else(|| HostError::NotFound("window project".into()))? + .fork_agent_session(client, agent, session_id, cwd) + } fn console_rules(&self, rules: Vec) -> Result<(), HostError> { let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?; let mut all = self.shared.console_rules.lock(); @@ -3602,6 +3619,14 @@ impl PluginWorkspace for HostWorkspace { Ok(config) } + fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result { + let host = self.0.upgrade().ok_or(HostError::Cancelled)?; + let project = host.project(client).map_err(failed)?; + project.require_trust().map_err(failed)?; + // Scans the recorded transcripts on disk; plugin calls already run off the UI thread. + Ok(project.agents.fork_session(agent, session_id, cwd).map_err(failed)?.id) + } + fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option { client .and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path)) diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 107aabf767..f116140558 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -1391,6 +1391,65 @@ fn ungranted_capabilities_are_denied_not_trapped() { assert_eq!(f.workspace.text("src/notes.txt"), "one two three\nfour five\n"); } +/// A missing `agents` grant is an error the plugin can handle, not a trap. +#[test] +fn ungranted_agents_fork_is_denied_not_trapped() { + let f = fixture(Limits::default()); + f.install(&misbehave_pkg()); + let err = f + .host + .run_command("misbehave", "fork-session", Some("claude 11111111-2222-3333-4444-555555555555 /tmp"), f.inv()) + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err:?}"); + assert!(err.message.contains("agents"), "{err:?}"); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on"); + assert_eq!(info.stats.errors, 0, "a missing grant is not the plugin failing"); +} + +/// With the `agents` grant the call reaches the core fork over a real project: +/// an unknown session is the core's `not-found`, not a denial or a host stub. +#[tokio::test] +async fn granted_agents_fork_reaches_the_core() { + let f = fixture(Limits::default()); + // Hermetic: the core scans the home transcript folders; a real ~/.codex with + // thousands of rollouts would time the command out. + // SAFETY: set before the Host reads HOME; nextest isolates this test's process. + unsafe { std::env::set_var("HOME", f._tmp.path().join("home")) }; + let host = Arc::new(Host::new(HostConfig { + config_dir: f._tmp.path().join("config"), + data_dir: f._tmp.path().join("data"), + local_data_dir: f._tmp.path().join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(ide_core::NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + host.trust.decide(&f.project, true, false).unwrap(); + host.open_project("main", &f.project).unwrap(); + f.host.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host))))); + + // `misbehave` with the `agents` grant, which needs API 1.18. + let pkg = f._tmp.path().join("misbehave-agents"); + copy_dir(&misbehave_pkg(), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + let text = text + .replace("required = [\"project.read\"]", "required = [\"project.read\", \"agents\"]") + .replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\""); + std::fs::write(&manifest, text).unwrap(); + f.install(&pkg); + + let session = "11111111-2222-3333-4444-555555555555"; + let arg = format!("claude {session} {}", f.project.to_str().unwrap()); + let err = f.run("misbehave", "fork-session", Some(&arg)).unwrap_err(); + assert!(err.contains("unknown claude session"), "{err}"); + // Detached: the blocking close joins the LSP/index workers, which can stall under nextest. + host.close_project_detached("main"); +} + /// A trap drops the instance, which restarts on next use after a /// backoff that doubles; only consecutive crashes stop the plugin. #[test] @@ -1652,7 +1711,7 @@ fn idle_instances_are_reclaimed_and_schedules_reactivate() { assert_eq!(f.host.instances(), 0); let info = f.host.info_of("misbehave").unwrap(); assert_eq!((info.status, info.stats.reclaims), (PluginStatus::Inactive, 1)); - assert_eq!(f.command_titles("misbehave").len(), 24, "contributions stay"); + assert_eq!(f.command_titles("misbehave").len(), 25, "contributions stay"); assert_eq!(f.run("misbehave", "echo", Some("y")).unwrap().as_deref(), Some("y")); assert_eq!(f.host.info_of("misbehave").unwrap().stats.activations, 2); @@ -7669,7 +7728,7 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent "id = \"acme.mixed-skills\"\n\ name = \"Mixed Skills\"\n\ version = \"1.0.0\"\n\ - engines.openidea = \"^1.15\"\n\n\ + engines.openidea = \"^1.18\"\n\n\ [[contributes.skills]]\npath = \"skills/good-skill/SKILL.md\"\n\ [[contributes.skills]]\npath = \"../outside/SKILL.md\"\n\ [[contributes.skills]]\npath = \"skills/not-skill-md/README.md\"\n\ diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 63c7530618..4add874e2d 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -208,6 +208,9 @@ pub trait HostApi: Send + Sync { ) -> Result<(), HostError>; /// Replace all `(path, icon)` entries of a tree decoration set at once (API 1.8). fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError>; + /// Fork a recorded native agent session into a new task in the invoking + /// window's project, returning the new task id (API 1.18). + fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result; /// Trusted repository history. fn vcs_log( &self, diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index a9c24f0288..f89bc32e37 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -3321,6 +3321,19 @@ impl bindings::openidea::plugin::mcp::Host for StoreData { } } +impl bindings::openidea::plugin::agents::Host for StoreData { + fn fork_session(&mut self, agent: String, session_id: String, cwd: String) -> Fallible { + if let Err(e) = self.require(Capability::Agents) { + return Ok(Err(e)); + } + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + let client = self.invocation.client.clone().unwrap_or_default(); + Ok(self.host.fork_agent_session(&client, &agent, &session_id, Path::new(&cwd)).map_err(to_wit)) + } +} + pub(crate) mod mcp_bindings { wasmtime::component::bindgen!({ world: "mcp-tools", path: "../../wit", with: { diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm index c0094a2657..8e1f266d04 100644 Binary files a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources index 597183bb66..af4dba612c 100644 --- a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -1 +1 @@ -9857fa3a9b1d22d3b2c91a58fbf2c948267d87a6586ade7e0362fd6b6f4dd2ab +ba019d950ae83c45845a5cfcb2e890eca25c6f102b78f8cd3090f604c56aaf17 diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm index bac3d68b42..3d94a0cd2f 100644 Binary files a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources index 8994e660a7..54b54632dd 100644 --- a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources @@ -1 +1 @@ -ba19f794de91eeac3a2509a9495b443ab7b0c90404156d8e4049e5eae777ab66 +926ca24c9a08166e34fb8a6b2c6dd06a92cf3370dc01ff3054b533356314c84b diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm index 919674f6f4..cf7d311e23 100644 Binary files a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources index 9187f97fd7..8ab2d80a3a 100644 --- a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources @@ -1 +1 @@ -0692fd551f6cc80338f8f655ad2384f37aef5c9498a0396532afa0e54a25f477 +dd7e4dcc429bf44b839cabe682f36cb3951a3dcf535f500f90cb60ff749e31e6 diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index 121a726e92..26c0c9df14 100644 Binary files a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources index 8885e8bd5a..d23346bcfe 100644 --- a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources @@ -1 +1 @@ -6a25f9c9f9486468f1885cf81bccd90240014009ba3c507e478ce9b32468d594 +1acae0035935e9f6e7b52826e9731aeb15dafb5cfcc561a2b98dae10676f53f8 diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm index 799812ea3c..7b6a98f84e 100644 Binary files a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources index 02d1acbaa7..3be144049d 100644 --- a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources @@ -1 +1 @@ -84bb08e094ec85d49abe713df02ac03a47dc7dbb6d8dfc754491083e0d0c46f5 +d3b940a7899ed3a303b51c529d2771ec9ac20a22d996dbc9760dd118dc10dbc1 diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm index 5d1654a880..fbc089cea2 100644 Binary files a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources index f991d17fac..1ad5317fa6 100644 --- a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -958ef1f5cd54a9b4c6fb99ee8e02793ca70a81698620da9ddf2b1b3f25b535c8 +955e804453e7e8ea37a49ab7b65289d31fef1216eda4f1834e912375196adb17 diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm index 4cc96de874..a23d3e2e11 100644 Binary files a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources index da710a6b43..f9b0d140f1 100644 --- a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources @@ -1 +1 @@ -a846c18a1282242e25f0b61624c319fe10bdf322c224276a4a8edffd470ef940 +42caf6ccd73e3d622894416b0fd5007b8a1d773d6bf7e81c0ff4d0e97f888e43 diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm index 8bfa94d530..88508ec309 100644 Binary files a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources index 5c023cab04..d2c4a2c0bd 100644 --- a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources @@ -1 +1 @@ -35f393de3ed681d206885612ae085b69dfef81ff8baa701a737c1914ac1412fb +5795a3b4a25a7563c3a43ed0d414d3e520badd09066d5e5d2bcbc23ba4b8e1c8 diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index 9d31870223..4f9201d4a0 100644 Binary files a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources index f848f31bab..6cbdc5344b 100644 --- a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources @@ -1 +1 @@ -e75dad45fb2a6bb8823b8edfb41b29403ec77f8e6e533bad42d0ae0cb1d68286 +1e53f7713c294be551fa4641cfda5b2497d7a57a35116ca4dd29783e63a7a9f6 diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index e974866ef1..b2ac848817 100644 Binary files a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources index a67d8c6c02..7dd4d07137 100644 --- a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources @@ -1 +1 @@ -2cb47ff4fb3d401e95b742d78e026b872200dc503bf933ff9ce31d0557d69426 +650a8e88e4e6999e77159fb25516b5990f6ae7805167e89a8e3193d53fd57822 diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm index b0fb32d925..a2d5aed895 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources index 58069fc197..e38de5b999 100644 --- a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources @@ -1 +1 @@ -e121d0fd2cc841ebb911904ada80921d01af392ccaa295b2fe0b2e7f4f51c58c +6ee319bf6071871f7d9d0674b83be11d7b6f8ed2693572303f15d7e450a86b4b diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm index 879589a06e..5ae8c34e9d 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources index 5625531071..aaf01f8d98 100644 --- a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources @@ -1 +1 @@ -c0ebc0e6b8601044ab88eba4929c8c73ab1278d3401b6594df35407f1a93cc24 +61f41c0d8ce0bf2243c8cb3b2d2a84037a07958fb18d6ebb016abb08b469a80c diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm index edced1df7d..f4b5401720 100644 Binary files a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources index 0b73cace1f..fff8ec63ba 100644 --- a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources @@ -1 +1 @@ -cea7369e69efee782e6a7b62736832e90890cd7af089884f3ed6e144542e0589 +e5877e2978f8d36c1d8b684e84bfd21f9047b0153bed952e89299a69968029c0 diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm index c42eb35f92..2e4095733a 100644 Binary files a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources index 6e0c021d81..4b07f823c0 100644 --- a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources @@ -1 +1 @@ -f348c5ee1ce6d911ae53ea4aff185bdb6079729aee83561d3adb9d13eeb376fb +7fe7457184144c93b761b8fa26e45f1b8a55cc6753d91a7353bd67d7a5bd09a9 diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm index 0ecd31685f..d8139ad4cd 100644 Binary files a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources index 5b7654183c..3008d58a92 100644 --- a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources @@ -1 +1 @@ -5cd09b0da42f015faae666fbe210203b7ced9cf19d6ee542dadd236b7926b77b +19480e0dd6ae1e36aadabbda9ea49a34ee0aa37d4c7182c297b6d84c9b13991f diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm index 7a26f20b91..5ed2c0dd0a 100644 Binary files a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources index 79071ee779..b1d89bff3a 100644 --- a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources @@ -1 +1 @@ -ff2d1eac3fe4a2856e6310f36ed29d9a2ccffc8eeb41ded729dd01eadc244857 +7bd6651b0fd45032847868c341bc815b115ac678dcaaf26e752ae72ac1b0549f diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index f51f8612b6..1745c75f91 100644 Binary files a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources index a5970d9b7b..68f2538f36 100644 --- a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -1 +1 @@ -e37a64052eef340a8482d8129badc50f29e8949316a33e6172a64e1a00f0718c +9c99195f1c7efdb27f3715158559218db2f7db03325cc04af455b8f60653da24 diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm index f06f7815c4..dab2a7d4eb 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources index bd2903b852..18248e5f8d 100644 --- a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources @@ -1 +1 @@ -5f4dfb76c879bbbeb38f7c1b45c88818517743d742129a147e185bc7d2db7abc +875df930f71fa22112dbafddb6de460b9828d0aa10812ee1eeedc4052bc88061 diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index 513258d73c..94124fad39 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources index 39ae74f5f4..ce478afea8 100644 --- a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources @@ -1 +1 @@ -efe6d6c88d0bab2484f90cef6affe256c480297731ce585a5e3441e2648d9392 +d10b1225ab4228d3906e88e79ef346302a4db89aa4dd5a82da694cec408e5496 diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index d9df8ca705..b1707f93c9 100644 Binary files a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources index f168188647..1d578a0de4 100644 --- a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources @@ -1 +1 @@ -7b606308ee272adb1f659e7fd21069409b3bdbf12cd54b93232205bc8213f52a +12cb92d4b45279bbdc345dbdd4c8d4827abc5054d0324d35b85b648840d9c556 diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm index 883af0da38..d100882bbd 100644 Binary files a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources index f8a2750443..88ab3deeba 100644 --- a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources @@ -1 +1 @@ -6be054362a3c1f3545fdfba5c9b66d9eadcbeea3b160952068494c02bce3a4a1 +e8c1116c94c82ea4ed0fd7e33070bc878e88dcfe8f08632cd700bb3418b712cc diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index 1c3441e8cd..090ec5f17c 100644 Binary files a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources index 88e6589ae4..adc73f23f6 100644 --- a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -1 +1 @@ -3cd84b9876d2e5a5294877ac14d69b18319be3208c192f67b6c3848039c48a79 +9bd13ae90217e4355014512bce62de8b471a466484100abb7cc8b9197c008c93 diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm index 4cece283e6..eb269acd69 100644 Binary files a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources index e015b4112c..0dea9a9cc0 100644 --- a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources @@ -1 +1 @@ -e2c282bd0add6de51b6b275d16b950213fcdd24d1d882895b7d3099b0a7d569a +f3d78da579d47985908f8e7ce63793ff58b2d255992df97a0acdec1c56a039ee diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm index e7d54c1678..7326796891 100644 Binary files a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources index cec2040664..36397622fd 100644 --- a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources @@ -1 +1 @@ -84739ec73aa6b7b27d7a5062b78645d7342729806bc728f35a7b97c945c1a4fd +123a768fd0e531c6f8ce63648f10ddef2d309d01e5e8ac1386c16e45a9c0329b diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index 26517e1ac3..83a6c64407 100644 Binary files a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources index 1fee0dfded..750b026c52 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -1 +1 @@ -ad43fa07182ff3d90154fdd788599d60db5fe0ab736dad03c6ae2cc2a1055eff +6a57f349ba434cdc10ddbdd2fedb1578a18dcada080f6d8b9096a95174a2ab79 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml index 96de5c9ac6..b079823331 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml +++ b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml @@ -54,6 +54,10 @@ title = "projwrite" id = "insert" title = "insert" +[[contributes.commands]] +id = "fork-session" +title = "fork-session" + [[contributes.commands]] id = "cancel" title = "cancel" diff --git a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs index 7d7e351ce0..94e108e3c8 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs @@ -209,6 +209,16 @@ impl commands::Guest for Misbehave { let editor = ctx.editor().ok_or_else(|| failed("no editor"))?; editor.apply_edits(0, &[]).map(|_| None) } + // `agents.fork-session`: arg is "agent session-id cwd". Without the + // `agents` grant this is `denied`, not a trap. + "fork-session" => { + let arg = arg.unwrap_or_default(); + let mut parts = arg.splitn(3, ' '); + let agent = parts.next().unwrap_or_default(); + let session_id = parts.next().unwrap_or_default(); + let cwd = parts.next().unwrap_or_default(); + openidea::plugin::agents::fork_session(agent, session_id, cwd).map(Some) + } // The user gave up: not the plugin failing. "cancel" => Err(types::Error::Cancelled), // Event kinds are names: one this IDE doesn't know is refused. diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm index ffe2685eba..fb54043f60 100644 Binary files a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources index d99ed7cced..00e236c8f5 100644 --- a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources @@ -1 +1 @@ -639a93e98dd0fe3114ef7be3597ab559b69e4c54fdb5e96951cb19b894a020b9 +a689eca7666880c1096bf9bcaaba3d355a76666a7abe7524e5bb6f641a7d67fd diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm index 9c61334423..cdbbc6f1f5 100644 Binary files a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources index 56a9d34acd..fd11770a91 100644 --- a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources @@ -1 +1 @@ -20aa26598608efac79c941531d4b5cd26b4e71a9b09e261560bc086410eb5c83 +eff2b16fcdf47f7f0a204bb229438b585917c3be62fd9ea9a02898b415530d6e diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm index aa189f66dd..f1bda9f85b 100644 Binary files a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources index 9dceeb79e1..d15ae4a74f 100644 --- a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources @@ -1 +1 @@ -ca76bdb76b364ec445e06b893fdfb56cad1f05e4a1ff10affaa116b34c3160ec +97177d6d25b9a205c1cf1cf9bd8e50ad88a119e9876dddd786d72575d2cbae5c diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm index 87b51e0ed1..838cb13326 100644 Binary files a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources index cdbdb73022..8bcdda5395 100644 --- a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources @@ -1 +1 @@ -7307879ddca36b6a944bb3b5d3011916a3074e50d7f187aa258394c8c5123d91 +14559c777048bef5ec800dc6ea4e3f263268a6bd16000023c27f1f82a0d89ca6 diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm index d6f3575e07..8236dd0f69 100644 Binary files a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources index ca7d04bff1..39b9b9c290 100644 --- a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources @@ -1 +1 @@ -82a408bddf01af0e7a34a585a60d165e12ad5982e7843d6091a2f4e6fac15c55 +24060000f8040dbd6ba007b8da84e2800f93f3090aaafc0fb864ecc03266df82 diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm index a568005ba8..8ceef2294c 100644 Binary files a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources index 569b2112d8..6aa0060e0b 100644 --- a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources @@ -1 +1 @@ -04b1807c79763f6e2f74503d545007dbdb478f7aae010dd8330e768c1dc3a9ad +ce8e3742bdfa1e9f232b01af7569a72a2349c93e16866436d6a4d051a5aa9fdf diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 69799c2d11..4fdfa4c07c 100644 Binary files a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources index f62290414d..66ac11ba58 100644 --- a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources @@ -1 +1 @@ -53e4f47e38a8622e2ef0d03e4ed2369fb906e941d9e9734ed9d57fe5cbc5ead3 +687b349d2b55cbd0220fdd33cddf98d8bab735f5e6716d8b9a27029ab4973953 diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index 03edc05f7e..09fa423cbc 100644 Binary files a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources index 86fe4da29e..82acff9493 100644 --- a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources @@ -1 +1 @@ -d6bd0b261c6db62d04197c28b251a03acc5f32cb21c5133ac3aaeb3e37fe5eab +00ae790cecb1fd107e407d0c6a1e149713b2969af220de0267dbe9b55fc628ef diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index e2ae99203c..c0d8e54a72 100644 Binary files a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources index dc2da5e5aa..ef398eb053 100644 --- a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources @@ -1 +1 @@ -a7728793d40c78dc5ebfd74c013425358c888da87a2cce15a5e8c306ab5b6b30 +d1d5e658f86af183a9ce21d3ad6230ddd00a05b7c3bd447b9fabfa171aa92920 diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm index 8ca6fe86ce..237778b896 100644 Binary files a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources index 099402687b..f20a0cac4c 100644 --- a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources @@ -1 +1 @@ -1fca4a563944897ea1e55c49533c157f005e5efbc1aeabac65037cad1f05c2ba +213aa998dfcc309f8abd24f12a44db4ac12b676bb7d3567309378ef650e05602 diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm index b74dd56d6d..358c31ccf4 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources index 20919566a6..1c84a53bc7 100644 --- a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources @@ -1 +1 @@ -2be637ed5d3c72adf1a8b92aaea86602ab81ffaeeff99a719f6f67c244b82137 +ad698b8393a15b8af0065d97a73ade1cc98626ffe5ffd20cb1de6c06aef4611a diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm index ef266e6217..b03f6d7be9 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources index fe4453dfea..5578799a2c 100644 --- a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources @@ -1 +1 @@ -3a1aad965fa557b13e2aab2b714c68845d1890a6e98ab9155ccfc952ab2c64d5 +046020f3a6500bedba728a132353024201e7c59cbe5fa819dfe8b8aba3a87bab diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm index 16745710a9..50465ea59c 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources index a6ef4040a5..101e10bea7 100644 --- a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources @@ -1 +1 @@ -0ad7071e1674170ae360d873fda38656dbba6740514c7bfca642e7881cbd9c18 +8c0718c8d732965a6a87a68695a22c37c6ebdd26877019d47c8e2de3dfc7b10d diff --git a/docs/en/plugins/capabilities.mdx b/docs/en/plugins/capabilities.mdx index 236681bcec..1e45f13d9b 100644 --- a/docs/en/plugins/capabilities.mdx +++ b/docs/en/plugins/capabilities.mdx @@ -45,6 +45,7 @@ Later: | `events.input` | Medium | `action-performed` and `input-mode-changed` events (keystrokes and editor input) | 1.0 | | `clipboard` | Medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | 1.0 | | `clipboard.read` | Medium | `host::read_clipboard`: the clipboard's text and image, only in commands and view actions the user ran (event handlers and other unattended calls are denied) | 1.11 | +| `agents` | Medium | `host::fork_agent_session`: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project; trusted projects only | 1.18 | | `secrets` | Medium | `{{secret:}}` in request headers, `secret_is_set`, `secret_set`, `secret_delete` | 1.0 | | `net:` | Medium | `host::fetch` over HTTPS (and loopback HTTP) to that host; `*.example.com` matches subdomains | 1.0 | | `net:ask` | Medium | Ask the user at the first request to an HTTPS host that isn't declared | 1.5 | diff --git a/docs/en/plugins/versioning.mdx b/docs/en/plugins/versioning.mdx index ef8dbc49d4..a7935580bc 100644 --- a/docs/en/plugins/versioning.mdx +++ b/docs/en/plugins/versioning.mdx @@ -1,9 +1,9 @@ --- title: "API versions and compatibility" -description: "engines.openidea, the plugin API versions from 1.0 to 1.13, and the rules that keep released plugins loading in newer IDEs." +description: "engines.openidea, the plugin API versions from 1.0 to 1.18, and the rules that keep released plugins loading in newer IDEs." --- -The plugin API has one version number: the version of the WIT package in [`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) (`openidea:plugin@1.14.0` on `main`). The host's engine version and the SDK's `API_VERSION` always agree with it, and the SDK carries an identical copy of the WIT files. +The plugin API has one version number: the version of the WIT package in [`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) (`openidea:plugin@1.18.0` on `main`). The host's engine version and the SDK's `API_VERSION` always agree with it, and the SDK carries an identical copy of the WIT files. The plugin system is a preview. The compatibility rules below hold for released 1.x versions; what is still unreleased @@ -12,27 +12,27 @@ The plugin API has one version number: the version of the WIT package in [`wit/` ## Versions -| API | Shipped with | Highlights | -| ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | -| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | -| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | -| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | -| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | -| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:`), server commands routed to plugins, editor panels | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | -| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | -| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | -| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | -| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | -| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills//SKILL.md"`) for bundling agent skills in plugins | -| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | -| 1.18.0 | In development on `main` | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '' with " beside Run and Debug, the only launches that get that agent | +| API | Shipped with | Highlights | +| ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | +| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | +| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | +| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | +| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | +| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:<server>`), server commands routed to plugins, editor panels | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | +| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | +| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | +| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | +| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | +| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins | +| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | +| 1.18.0 | In development on `main` | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '<name>' with <title>" beside Run and Debug, the only launches that get that agent; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself | The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md). diff --git a/docs/zh/plugins/capabilities.mdx b/docs/zh/plugins/capabilities.mdx index caa596e459..dd0e684482 100644 --- a/docs/zh/plugins/capabilities.mdx +++ b/docs/zh/plugins/capabilities.mdx @@ -45,6 +45,7 @@ optional = ["net:api.example.com", "secrets"] | `events.input` | 中 | `action-performed` 和 `input-mode-changed` 事件(按键和编辑器输入) | 1.0 | | `clipboard` | 中 | `host::copy_to_clipboard`,以及插件 Web 视图中的剪贴板 API | 1.0 | | `clipboard.read` | 中 | `host::read_clipboard`:读取剪贴板的文本和图片,仅限用户运行的命令和视图操作(事件处理器等无人值守的调用会被拒绝) | 1.11 | +| `agents` | 中 | `host::fork_agent_session`:把录制的原生 agent 会话(`claude` 或 `codex`)派生为当前窗口项目中的新任务;仅限受信任项目 | 1.18 | | `secrets` | 中 | 请求头中的 `{{secret:<name>}}`、`secret_is_set`、`secret_set`、`secret_delete` | 1.0 | | `net:<host>` | 中 | `host::fetch` 通过 HTTPS(以及回环地址的 HTTP)访问该主机;`*.example.com` 匹配子域名 | 1.0 | | `net:ask` | 中 | 第一次请求未声明的 HTTPS 主机时询问用户 | 1.5 | diff --git a/docs/zh/plugins/versioning.mdx b/docs/zh/plugins/versioning.mdx index c46d3d0347..00088a2473 100644 --- a/docs/zh/plugins/versioning.mdx +++ b/docs/zh/plugins/versioning.mdx @@ -1,35 +1,35 @@ --- title: "API 版本与兼容" -description: "engines.openidea、插件 API 从 1.0 到 1.13 的各个版本,以及让已发布插件在新 IDE 中继续加载的规则。" +description: "engines.openidea、插件 API 从 1.0 到 1.18 的各个版本,以及让已发布插件在新 IDE 中继续加载的规则。" --- -插件 API 只有一个版本号:[`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) 中 WIT 包的版本(`main` 上是 `openidea:plugin@1.14.0`)。宿主的引擎版本和 SDK 的 `API_VERSION` 始终与它一致,SDK 里也带着一份完全相同的 WIT 文件。 +插件 API 只有一个版本号:[`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) 中 WIT 包的版本(`main` 上是 `openidea:plugin@1.18.0`)。宿主的引擎版本和 SDK 的 `API_VERSION` 始终与它一致,SDK 里也带着一份完全相同的 WIT 文件。 <Note>插件系统目前是预览版。下面的兼容规则适用于已发布的 1.x 版本;`main` 上尚未发布的内容在发布前仍可能变化。</Note> ## 版本历史 -| API | 随哪个版本发布 | 主要内容 | -| ------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | -| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | -| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | -| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | -| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | -| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | -| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | -| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | -| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | -| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | -| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 | -| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | -| 1.18.0 | `main` 上开发中 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理 | +| API | 随哪个版本发布 | 主要内容 | +| ------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | +| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | +| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | +| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | +| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | +| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | +| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | +| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | +| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | +| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | +| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 | +| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | +| 1.18.0 | `main` 上开发中 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude` 或 `codex`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 | 每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。 diff --git a/plugins/README.md b/plugins/README.md index 997ac9873e..b4c57a7e4d 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -377,6 +377,7 @@ machine. Users can revoke optional capabilities in Settings › Plugins. | `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` | | `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | | `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran | +| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only | `process:` capabilities are also derived from what the contributions start: a language's `language-servers` and `debugger` commands and a run detector's @@ -562,6 +563,11 @@ matching SDK. Plugins for 1.14 and earlier keep working. New in 1.15: sessions while the plugin is enabled; workspace and user skills take precedence on a name clash, and invalid entries report a plugin load warning rather than failing the plugin. +- [Forking agent sessions](#forking-agent-sessions-api-115): + `host::fork_agent_session` (`agents.fork-session`) continues a recorded native + agent session (`claude` or `codex`) as a new task in the invoking window's + project, returning the task id. Requires the `agents` capability; the host + validates the session and builds the fork invocation itself. ### API 1.14 @@ -897,93 +903,94 @@ then run `openidea-plugin check`. ### The API -| Rust SDK | WIT | Notes | -| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. | -| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. | -| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. | -| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). | -| `Project::document`, `apply_document_edits` | `editor.{document,apply-edits}-at` | API 1.6: versioned access to an explicitly named open project document from background events. Requires `project.read` and `editor.read`/`editor.write`; stale edits change nothing. | -| `WebSocket::{connect,send,drain,close}` | `net.websocket-*` | API 1.6: project-bound, bounded host-owned WSS transport with secret-filled headers, close state and event-driven wakeups. | -| `Project::{upsert_data_source,remove_data_source,data_sources,set_data_source_credential,connect_data_source}` | `database` | API 1.4: owned project sources; requires `database.sources` and trust. See _Database sources_. | -| `host::mcp_stdio_command()` | `mcp.stdio-command` | API 1.4: invoking project bridge argv, `None` while off. No URL/token. | -| `McpProvider::call(tool, arguments, ctx)` | export `mcp-provider.call` | API 1.4: declared tools under plugin grants and command budget. See _Plugin MCP tools_. | -| `host::open_editors()` | `editor.open-editors` | API 1.4: invoking window's path/language/dirty/active snapshots; requires `editor.read`. Commands/events of a window only. | -| `host::open_editor(path, selection)` | `editor.open` | API 1.4: open/select a project file (`project.read`), plugin-dir file, or install-directory file (read-only); same path rules as `views.open-location`. Commands/events of a window only. | -| `TextEditor::set_selections(ranges)`, `reveal(range)` | `editor.text-editor` | API 1.4: selections or scrolling in this window's already open editor; no capability. Commands/events only, UTF-16 coordinates. | -| `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. | -| `host::set_markdown_decorations` | `decorations.set-markdown` | API 1.16: the same sets with `markdown_hover` cards; shares set ids and limits with `set_decorations`. Requires `project.read`. | -| `host::set_styled_decorations` | `decorations.set-styled` | API 1.17: those items with their own `#rrggbb` / `#rrggbbaa` `colors`; `style` may be empty when colors are set; shares set ids and limits with `set_decorations`. Requires `project.read`. | -| `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. | -| `host::set_file_note` | `decorations.set-file-note` | API 1.7: a note after the name in the project tree (one line, at most 200 characters). Requires `project.read`. | -| `host::set_file_icon`, `set_file_icons` | `decorations.{set-file-icon,set-file-icons}` | API 1.8: assign one of the plugin's declared `[[contributes.fileIcons]]` icons to a file or plain folder by path (individually or up to 10,000 entries per set). Requires `project.read`. | -| `Project::search_text(query, limit)` | `workspace.project.search-text` | API 1.4: cancellable Find in Files with unsaved documents and project excludes, at most 10,000 matches. Requires `project.read`. | -| `host::problems(path)` | `diagnostics.problems` | API 1.4: project Problems reports grouped by file/source, optional file filter. Requires `project.read` and an invoking window. Empty for remote projects. | -| `Project::vcs_log(path, limit)` | `vcs.log` | API 1.4: newest first, at most 1000 commits, optional file history. Requires `vcs.read` and trust. | -| `Project::vcs_blame(path)` | `vcs.blame` | API 1.4: attribution including unsaved editor text. Requires `vcs.read` and trust. | -| `Project::build_dependencies(module)` | `build.dependencies` | API 1.10: the Maven / Gradle dependency graph the IDE resolved, flat, each module a root; nothing is resolved for the call. Requires `build.read` and trust. | -| `Project::vcs_diff(path, against)` | `vcs.diff` | API 1.4: disk working tree against HEAD/revision, optionally one file. None outside Git; fails above 4 MiB. Requires `vcs.read` and trust. | -| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. | -| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. | -| `Project::read_bytes(path)` | `workspace.project.read-bytes` | API 1.5: the exact bytes of a file inside the project (binary content is the point), at most 16 MiB, the file on disk. Same paths and `Error::NotFound` as `read_file`. | -| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). | -| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). | -| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). | -| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. | -| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. | -| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. | -| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. | -| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. | -| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. | -| `host::set_status_item_menu(id, item, menu)`, `set_window_status_item_menu` | `ui.set-{,window-}status-item-menu` | API 1.14: the item with a menu that a click opens instead of running its command; actions run declared commands with their argument. | -| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: requires high-risk `ide.commands` for IDE actions and other plugins; this plugin's own commands are exempt. Stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. | -| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. | -| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. | -| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. | -| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. | -| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. | -| `host::set_console_rules(rules)` | `ui.set-console-rules` | API 1.12: replaces the plugin's highlight rules for Run and Debug console output (regex, palette colours, styles, whole line or match); no capability. See _Console highlight rules_. | -| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). | -| `Project::notify(level, title, body, actions)` | `ui.notify-project` | API 1.5: balloon only in a window of that project (the most recently focused one), with or without an invoking window; see _Notifications with commands_. | -| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. | -| `host::read_clipboard()` → `ClipboardContent` | `ui.read-clipboard` | API 1.11: the clipboard's `text` and `image` (PNG bytes), `None` for what it doesn't hold. Needs `clipboard.read`; only in a command the user ran or a view action, else `denied`. See _Reading the clipboard_. | -| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. | -| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. | -| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. | -| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. | -| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. | -| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. | -| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | -| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. | -| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. | -| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. | -| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. | -| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; up to 16 MiB of stdout (fails if exceeded); killed when the call is cancelled or times out. | -| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. | -| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. | -| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. | -| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. | -| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | -| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. | -| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. | -| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. | -| `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. | -| `host::start_run_with_options(config, args, options)` | `run.start-with-options` | API 1.18: start an owned configuration with `RunStartOptions` (`debug` and optional per-launch `output_mode`); user-saved override wins over `options.output_mode`, which wins over plugin default. | -| `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. | -| `host::open_terminal_session_in(key, title, cmd, cwd)` | `views.open-terminal-session-in` | API 1.18: the same, started in `cwd`, a directory of the project relative to its root. | -| `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. | -| `host::open_content_tab(tab)` | `views.open-content-tab` | API 1.4: the shared content editor protocol, without a web view; actions arrive as `content-tab-action`. | -| `host::reply_content_tab(request_id, reply)` | `views.reply-content-tab` | API 1.4: reply to an owned action in the originating window. No capability; commands/events only. | -| `host::open_diff(diff, file_name)` | `views.open-diff` | API 1.7: two texts in the invoking window's diff viewer; `file_name` (at most 256 characters) picks the highlighting. Commands/events only; each side at most 8 MiB (earlier hosts: 1 MiB), a larger side fails with `Invalid("diff too large: …")`. | -| `host::open_file_diff(diff, file_name)` | `views.open-file-diff` | API 1.10: `open_diff` where a side may be `None` (the file doesn't exist there: added or deleted); the viewer shows the other side alone. Both `None` fails with `Invalid`. | -| `RunConfigurations::configurations(root)` | export `run-configurations.configurations` | API 1.4: optional `plugin-run-configurations` world; SDK registration `run_configurations`. Full project list, refreshed on configuration listing. | -| `LaunchConfigurations::launch_configurations(root)` | export `launch-configurations` | API 1.9: optional `plugin-launch-configurations` world; SDK registration `launch_configurations`. The same list with `env` and `debugger`; preferred over `run-configurations`. | -| `ExecutionConfigurations::execution_configurations(root)` | export `execution-configurations` | API 1.18: optional `plugin-execution-configurations` world; SDK registration `execution_configurations`. Adds a default `output_mode` (`Pipes` or `Pty`); preferred over `launch-configurations` and `run-configurations`. | -| `RunConfigurationCompletion::complete(project, config, field, text, caret)` | export `run-configuration-completion` | API 1.18: optional `plugin-run-configuration-completion` world; SDK registration `run_configuration_completion`. Completes the Arguments field (`field = "arguments"`) of the plugin's own configurations; items replace a UTF-16 range; 200 items, 300 ms. | -| `TestResults::parse(config, chunk)` | export `test-results.parse` | API 1.4: optional `plugin-test-results` world; SDK registration `test_results`. Bounded output batches for `framework = "plugin"`; failures use built-in parsers. | -| `TestResults::select_tests(config, tests)` | export `test-results.select-tests` | API 1.4: full replacement argv for test-tree name paths, or `None` when unsupported (the SDK default). Enables rerunning failed tests and running tree selections. | -| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. | -| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | +| Rust SDK | WIT | Notes | +| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. | +| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. | +| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. | +| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). | +| `Project::document`, `apply_document_edits` | `editor.{document,apply-edits}-at` | API 1.6: versioned access to an explicitly named open project document from background events. Requires `project.read` and `editor.read`/`editor.write`; stale edits change nothing. | +| `WebSocket::{connect,send,drain,close}` | `net.websocket-*` | API 1.6: project-bound, bounded host-owned WSS transport with secret-filled headers, close state and event-driven wakeups. | +| `Project::{upsert_data_source,remove_data_source,data_sources,set_data_source_credential,connect_data_source}` | `database` | API 1.4: owned project sources; requires `database.sources` and trust. See _Database sources_. | +| `host::mcp_stdio_command()` | `mcp.stdio-command` | API 1.4: invoking project bridge argv, `None` while off. No URL/token. | +| `McpProvider::call(tool, arguments, ctx)` | export `mcp-provider.call` | API 1.4: declared tools under plugin grants and command budget. See _Plugin MCP tools_. | +| `host::open_editors()` | `editor.open-editors` | API 1.4: invoking window's path/language/dirty/active snapshots; requires `editor.read`. Commands/events of a window only. | +| `host::open_editor(path, selection)` | `editor.open` | API 1.4: open/select a project file (`project.read`), plugin-dir file, or install-directory file (read-only); same path rules as `views.open-location`. Commands/events of a window only. | +| `TextEditor::set_selections(ranges)`, `reveal(range)` | `editor.text-editor` | API 1.4: selections or scrolling in this window's already open editor; no capability. Commands/events only, UTF-16 coordinates. | +| `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. | +| `host::set_markdown_decorations` | `decorations.set-markdown` | API 1.16: the same sets with `markdown_hover` cards; shares set ids and limits with `set_decorations`. Requires `project.read`. | +| `host::set_styled_decorations` | `decorations.set-styled` | API 1.17: those items with their own `#rrggbb` / `#rrggbbaa` `colors`; `style` may be empty when colors are set; shares set ids and limits with `set_decorations`. Requires `project.read`. | +| `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. | +| `host::set_file_note` | `decorations.set-file-note` | API 1.7: a note after the name in the project tree (one line, at most 200 characters). Requires `project.read`. | +| `host::set_file_icon`, `set_file_icons` | `decorations.{set-file-icon,set-file-icons}` | API 1.8: assign one of the plugin's declared `[[contributes.fileIcons]]` icons to a file or plain folder by path (individually or up to 10,000 entries per set). Requires `project.read`. | +| `Project::search_text(query, limit)` | `workspace.project.search-text` | API 1.4: cancellable Find in Files with unsaved documents and project excludes, at most 10,000 matches. Requires `project.read`. | +| `host::problems(path)` | `diagnostics.problems` | API 1.4: project Problems reports grouped by file/source, optional file filter. Requires `project.read` and an invoking window. Empty for remote projects. | +| `Project::vcs_log(path, limit)` | `vcs.log` | API 1.4: newest first, at most 1000 commits, optional file history. Requires `vcs.read` and trust. | +| `Project::vcs_blame(path)` | `vcs.blame` | API 1.4: attribution including unsaved editor text. Requires `vcs.read` and trust. | +| `Project::build_dependencies(module)` | `build.dependencies` | API 1.10: the Maven / Gradle dependency graph the IDE resolved, flat, each module a root; nothing is resolved for the call. Requires `build.read` and trust. | +| `Project::vcs_diff(path, against)` | `vcs.diff` | API 1.4: disk working tree against HEAD/revision, optionally one file. None outside Git; fails above 4 MiB. Requires `vcs.read` and trust. | +| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. | +| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. | +| `Project::read_bytes(path)` | `workspace.project.read-bytes` | API 1.5: the exact bytes of a file inside the project (binary content is the point), at most 16 MiB, the file on disk. Same paths and `Error::NotFound` as `read_file`. | +| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). | +| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). | +| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). | +| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. | +| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. | +| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. | +| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. | +| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. | +| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. | +| `host::set_status_item_menu(id, item, menu)`, `set_window_status_item_menu` | `ui.set-{,window-}status-item-menu` | API 1.14: the item with a menu that a click opens instead of running its command; actions run declared commands with their argument. | +| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: requires high-risk `ide.commands` for IDE actions and other plugins; this plugin's own commands are exempt. Stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. | +| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. | +| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. | +| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. | +| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. | +| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. | +| `host::set_console_rules(rules)` | `ui.set-console-rules` | API 1.12: replaces the plugin's highlight rules for Run and Debug console output (regex, palette colours, styles, whole line or match); no capability. See _Console highlight rules_. | +| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). | +| `Project::notify(level, title, body, actions)` | `ui.notify-project` | API 1.5: balloon only in a window of that project (the most recently focused one), with or without an invoking window; see _Notifications with commands_. | +| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. | +| `host::read_clipboard()` → `ClipboardContent` | `ui.read-clipboard` | API 1.11: the clipboard's `text` and `image` (PNG bytes), `None` for what it doesn't hold. Needs `clipboard.read`; only in a command the user ran or a view action, else `denied`. See _Reading the clipboard_. | +| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. | +| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. | +| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. | +| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. | +| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. | +| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. | +| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | +| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. | +| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. | +| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. | +| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. | +| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; up to 16 MiB of stdout (fails if exceeded); killed when the call is cancelled or times out. | +| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. | +| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. | +| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. | +| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. | +| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | +| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. | +| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. | +| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. | +| `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. | +| `host::start_run_with_options(config, args, options)` | `run.start-with-options` | API 1.18: start an owned configuration with `RunStartOptions` (`debug` and optional per-launch `output_mode`); user-saved override wins over `options.output_mode`, which wins over plugin default. | +| `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. | +| `host::open_terminal_session_in(key, title, cmd, cwd)` | `views.open-terminal-session-in` | API 1.18: the same, started in `cwd`, a directory of the project relative to its root. | +| `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. | +| `host::open_content_tab(tab)` | `views.open-content-tab` | API 1.4: the shared content editor protocol, without a web view; actions arrive as `content-tab-action`. | +| `host::reply_content_tab(request_id, reply)` | `views.reply-content-tab` | API 1.4: reply to an owned action in the originating window. No capability; commands/events only. | +| `host::open_diff(diff, file_name)` | `views.open-diff` | API 1.7: two texts in the invoking window's diff viewer; `file_name` (at most 256 characters) picks the highlighting. Commands/events only; each side at most 8 MiB (earlier hosts: 1 MiB), a larger side fails with `Invalid("diff too large: …")`. | +| `host::open_file_diff(diff, file_name)` | `views.open-file-diff` | API 1.10: `open_diff` where a side may be `None` (the file doesn't exist there: added or deleted); the viewer shows the other side alone. Both `None` fails with `Invalid`. | +| `RunConfigurations::configurations(root)` | export `run-configurations.configurations` | API 1.4: optional `plugin-run-configurations` world; SDK registration `run_configurations`. Full project list, refreshed on configuration listing. | +| `LaunchConfigurations::launch_configurations(root)` | export `launch-configurations` | API 1.9: optional `plugin-launch-configurations` world; SDK registration `launch_configurations`. The same list with `env` and `debugger`; preferred over `run-configurations`. | +| `ExecutionConfigurations::execution_configurations(root)` | export `execution-configurations` | API 1.18: optional `plugin-execution-configurations` world; SDK registration `execution_configurations`. Adds a default `output_mode` (`Pipes` or `Pty`); preferred over `launch-configurations` and `run-configurations`. | +| `RunConfigurationCompletion::complete(project, config, field, text, caret)` | export `run-configuration-completion` | API 1.18: optional `plugin-run-configuration-completion` world; SDK registration `run_configuration_completion`. Completes the Arguments field (`field = "arguments"`) of the plugin's own configurations; items replace a UTF-16 range; 200 items, 300 ms. | +| `TestResults::parse(config, chunk)` | export `test-results.parse` | API 1.4: optional `plugin-test-results` world; SDK registration `test_results`. Bounded output batches for `framework = "plugin"`; failures use built-in parsers. | +| `TestResults::select_tests(config, tests)` | export `test-results.select-tests` | API 1.4: full replacement argv for test-tree name paths, or `None` when unsupported (the SDK default). Enables rerunning failed tests and running tree selections. | +| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. | +| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | +| `host::fork_agent_session(agent, session_id, cwd)` → `String` | `agents.fork-session` | API 1.18: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project, returning the new task id. Requires the `agents` capability and project trust; the session must belong to the project and have been recorded in `cwd`. The host builds the fork invocation; claude forks under a host-chosen id, codex assigns its own. See _Forking agent sessions_. | `Project::symbols` reads the current in-memory index: results may be partial while indexing, and locations can lag unsaved edits. Normal saves and filesystem @@ -1251,6 +1258,23 @@ host::set_console_rules(&[ In tests, `MockHost::console_rules()` returns the last list set. The mock checks the count and pattern length only, not the complexity. +### Forking agent sessions (API 1.18) + +`host::fork_agent_session(agent, session_id, cwd)` (`agents.fork-session`) continues a +recorded native agent session as a new task in the invoking window's project, returning +the task id. `agent` is a native provider (`claude` or `codex`); `session_id` is the +recorded session's canonical UUID; `cwd` must be the directory the session was recorded +in. The host validates all three against its own session discovery (the same list Import +Sessions shows) and builds the agent's fork invocation itself, naming the fork's session id +for claude while codex assigns its own — a plugin never supplies CLI arguments. The new task +starts ready; its first turn continues the recording as the agent's own fork, leaving the +original session unchanged. + +Requires the `agents` capability (granted like other capabilities, listed separately with +its purpose) and a trusted project. Without the grant the call returns `error::denied`. +An unknown session, a malformed id, a session another task already holds, or a `cwd` that +does not match the recording is an invalid or not-found error, not a fork. + ### Database sources (API 1.4) Declare `database.sources` (medium risk). All five calls require it and a diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index f04eab0b6b..a66d6b4e4f 100644 Binary files a/plugins/official/ai-completion/dist/plugin.wasm and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources index 7732761d3e..90871b02f7 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -81f868bbdc6d1962a210d80c0bcc3d308aae4778074a7c0fc186f63c2ff61eac +4d117cb0757b72193decd8cd06e1667d52bf4bbabf3cf015bde1367b5219b708 diff --git a/plugins/official/blame-annotations/dist/plugin.wasm b/plugins/official/blame-annotations/dist/plugin.wasm index 12c6cdd570..607a20f455 100644 Binary files a/plugins/official/blame-annotations/dist/plugin.wasm and b/plugins/official/blame-annotations/dist/plugin.wasm differ diff --git a/plugins/official/blame-annotations/dist/plugin.wasm.sources b/plugins/official/blame-annotations/dist/plugin.wasm.sources index 0ae4703fa2..b30e2b6af0 100644 --- a/plugins/official/blame-annotations/dist/plugin.wasm.sources +++ b/plugins/official/blame-annotations/dist/plugin.wasm.sources @@ -1 +1 @@ -f7fe1f6c6dd7d0ca6d6d00822e9befb2be9dac290e43857fa34e25da58ea3404 +01670e76944a2bff7845f8e06ef548a380c57d927a83e5ebf134f26c3736b6fb diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index 562800618f..53d0edb9a3 100644 Binary files a/plugins/official/checkstyle/dist/plugin.wasm and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources index 01296cd7fb..8d5f576846 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -160dc378e930f137643b36a28a6eba4da6c1fa67e15348e82df93904a8cd6eeb +f5817cb75f4a4d9ba34074e6637572414d46ce2313e050ba81583af1ad5a639d diff --git a/plugins/official/container-runner/dist/plugin.wasm b/plugins/official/container-runner/dist/plugin.wasm index aa7ad34160..657173e8f1 100644 Binary files a/plugins/official/container-runner/dist/plugin.wasm and b/plugins/official/container-runner/dist/plugin.wasm differ diff --git a/plugins/official/container-runner/dist/plugin.wasm.sources b/plugins/official/container-runner/dist/plugin.wasm.sources index 97928d3c26..6089d40f2e 100644 --- a/plugins/official/container-runner/dist/plugin.wasm.sources +++ b/plugins/official/container-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -84c49b6c40314c5b8f4f366d51575abda6b3645d60010a2f6492bba9e18fa62a +ecdab1590c6f64b59ee7dfa7095ed8e2bfcccaa59ecf833f0a16bac6dd4a1ccf diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index 7383cd2824..74d953cd10 100644 Binary files a/plugins/official/csv-editor/dist/plugin.wasm and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources index b91558c6fe..d001358027 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -50d106a7b96c240652da5f25f0e2fc083a135c587879080687eb72a5b3d90769 +f67d34142192720ed748cb3fee8e198617232539f4f1381073c84fa8beda58e6 diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index 0a39487a5e..c5145b6675 100644 Binary files a/plugins/official/git-toolbox/dist/plugin.wasm and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources index 3109e56493..c6d1a298ee 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -6c3045316db235e129cc211040dd62ba4e3ed9bfc6c997aba61c5946929100b2 +fad90a072702f13b64e276a48eb2ea66bdaae1c043fe7cb074388ac260756611 diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index b3dac25449..572a14e231 100644 Binary files a/plugins/official/graphviz/dist/plugin.wasm and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources index 658f0d6c44..1334add745 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -006ecb56f6657044b54e8752c95fb3dbcaf98384124042f25298d27ab5c66773 +19020226d8ad23739f52e8f527a9ec43de31529e288d88687a90a906df265351 diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 49433dd242..cb96144569 100644 Binary files a/plugins/official/key-promoter/dist/plugin.wasm and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources index 06e0105112..e9c7206240 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -2c749192ea33f65d0396103371d3f8f21d4ce467268efb821705d806aa45973e +675472e967a2fa8e15155f939a5d734aa1892474506725e7b6ef1dd843990e88 diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index d09145f162..4e224d199e 100644 Binary files a/plugins/official/license-header/dist/plugin.wasm and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources index a87b7b1339..fa3d368e84 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -3d8838b8444bd7191d33d11b2e1e40b3f88b96b3bddd8ecf5e4936bac299437d +00f67f0116dfd51dd6e7597c06547bb5a6ac38462f8b1bf63c3863268b3684b7 diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index c04777256c..3072862329 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index 3699b68051..877c4e8dfc 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -2e788c8bd398ee5386e92e0ff8747e8470e12cb37eb6f8ca1cea9c9c79fc3366 +4eb13361d05380d220fc6db31280003b91696e37ebdcfa16160e86eb879be048 diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index e87f3e8c05..ddba2ed432 100644 Binary files a/plugins/official/regex-tester/dist/plugin.wasm and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources index 318f62ec55..e19e86f1d2 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -ba45d5376905a5602c1badb0ec94b351447b4eaf57cd0f19628b13ba59da961f +64f8783667f14707f51859c766d2e3beb691996e147e7cb8a87ceb9bf292dc4f diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index bf14886d13..8f582fa9d9 100644 Binary files a/plugins/official/solidity/dist/plugin.wasm and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources index fba71d026b..dbd2a9e489 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -5ec6de5a1d9a00e5f57fcf1ee6e6f04115061c08c4db6f9c1c7d83611caccc65 +b9864d2ea64473cbeeabf8b97d9dac551d8f3b84d5dba435c090119a020ce1b6 diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index 66abce39f2..c9c9154bd0 100644 Binary files a/plugins/official/string-tools/dist/plugin.wasm and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources index 33673ef829..2c22263186 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -4234fcfd105b5c6413372f4eca1bf707f912888d051ebed21f3959389c261def +9935722246fceecf99cd18ffc4d7b365ef060478f2cba0142f17b19374b31205 diff --git a/plugins/official/test-runner/dist/plugin.wasm b/plugins/official/test-runner/dist/plugin.wasm index 0b4352bb94..d45d6c590d 100644 Binary files a/plugins/official/test-runner/dist/plugin.wasm and b/plugins/official/test-runner/dist/plugin.wasm differ diff --git a/plugins/official/test-runner/dist/plugin.wasm.sources b/plugins/official/test-runner/dist/plugin.wasm.sources index f75d156f64..a487ff4930 100644 --- a/plugins/official/test-runner/dist/plugin.wasm.sources +++ b/plugins/official/test-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -70fbad5fc1d16069629e670fce2b4076113dd13cac3c794723d551dfdd500ce3 +a37ecea6b1e7baa012d45386a107078ada84671f8a51e01211e2fd45c761ae32 diff --git a/plugins/official/todo-finder/dist/plugin.wasm b/plugins/official/todo-finder/dist/plugin.wasm index 37b1f10407..4ad402abac 100644 Binary files a/plugins/official/todo-finder/dist/plugin.wasm and b/plugins/official/todo-finder/dist/plugin.wasm differ diff --git a/plugins/official/todo-finder/dist/plugin.wasm.sources b/plugins/official/todo-finder/dist/plugin.wasm.sources index 9a28a76459..d6d7389973 100644 --- a/plugins/official/todo-finder/dist/plugin.wasm.sources +++ b/plugins/official/todo-finder/dist/plugin.wasm.sources @@ -1 +1 @@ -d38a8314d156e1a4143cb1eb9dccb2fe01d3add4760570af4152f346307df297 +46437e4729fd25b9e1f19452ed97a907eef5f7b797033ff93efeaae47509debf diff --git a/sdk/rust/openidea-plugin/src/host.rs b/sdk/rust/openidea-plugin/src/host.rs index 6a08b9b41b..6970282c36 100644 --- a/sdk/rust/openidea-plugin/src/host.rs +++ b/sdk/rust/openidea-plugin/src/host.rs @@ -1096,6 +1096,10 @@ mod imp { Ok(list.into_iter().map(|c| crate::Contribution { plugin: c.plugin, data: c.data }).collect()) } + pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result<String, Error> { + wit::agents::fork_session(agent, session_id, cwd).map_err(error) + } + pub fn run_process( program: &str, args: &[String], @@ -2315,3 +2319,14 @@ pub fn mcp_stdio_command() -> Option<Vec<String>> { pub fn extension_contributions(point: &str) -> Result<Vec<crate::Contribution>, Error> { imp::extension_contributions(point) } + +/// Fork a recorded native agent session into a new task in the open project, +/// returning the new task id (API 1.18). Requires the `agents` capability and an +/// invoking window. The session must belong to that window's project and have +/// been recorded in `cwd`; the host builds the fork invocation and names the +/// fork's session id for claude (codex assigns its own). `agent` is a +/// native provider (`claude` or `codex`). The new task's first turn continues the +/// recording as the agent's own fork. Needs `engines.openidea = "^1.18"`. +pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result<String, Error> { + imp::fork_agent_session(agent, session_id, cwd) +} diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs index 9d9592fa12..3ff110fa21 100644 --- a/sdk/rust/openidea-plugin/src/mock.rs +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -206,6 +206,8 @@ struct State { run_remote_targets: BTreeSet<String>, configuration_runs: Vec<(String, String, Vec<String>, bool)>, configuration_run_options: Vec<(String, String, Vec<String>, crate::RunStartOptions, crate::OutputMode)>, + /// `(agent, session_id, cwd)` of each `fork_agent_session` call. + agent_forks: Vec<(String, String, String)>, log_tabs: Vec<MockLogTab>, locations: Vec<(String, u32, u32)>, settings: BTreeMap<String, String>, @@ -747,6 +749,10 @@ impl MockHost { ) -> Vec<(String, String, Vec<String>, crate::RunStartOptions, crate::OutputMode)> { self.state.borrow().configuration_run_options.clone() } + /// Recorded `fork_agent_session` calls as `(agent, session_id, cwd)` (API 1.18). + pub fn agent_forks(&self) -> Vec<(String, String, String)> { + self.state.borrow().agent_forks.clone() + } /// Makes the language server `server` run and answer `method` with `result` (JSON). /// A server with no answer set is not running: requests to it are not-found. pub fn set_language_server_response(&self, server: &str, method: &str, result: &str) { @@ -2791,6 +2797,14 @@ pub mod current { .ok_or_else(|| Error::NotFound(format!("no running plugin declares {point}"))) }) } + pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result<String, Error> { + with(|s| { + require(s, "agents")?; + let id = format!("mock-agent-task-{}", s.agent_forks.len()); + s.agent_forks.push((agent.into(), session_id.into(), cwd.into())); + Ok(id) + }) + } pub fn register_run_target(project: &ProjectRes, target: &crate::PluginRunTarget) -> Result<(), Error> { register_run_target_with_overrides(project, &target.clone().into()) diff --git a/sdk/rust/openidea-plugin/wit/agents.wit b/sdk/rust/openidea-plugin/wit/agents.wit new file mode 100644 index 0000000000..b833f3b91b --- /dev/null +++ b/sdk/rust/openidea-plugin/wit/agents.wit @@ -0,0 +1,14 @@ +package openidea:plugin@1.18.0; + +/// Forking recorded native agent sessions into new tasks (API 1.18). Requires +/// the `agents` capability. The session must belong to the invoking window's +/// project and have been recorded in `cwd`; the host builds the fork invocation +/// and names the fork's id for claude (codex assigns its own). +interface agents { + use types.{error}; + /// Fork the recorded session `session-id` of `agent` (a native provider, + /// `claude` or `codex`) into a new task in the open project, returning the + /// new task id. `cwd` must be where the session was recorded. The first + /// turn continues the recording as the agent's own fork. + fork-session: func(agent: string, session-id: string, cwd: string) -> result<string, error>; +} \ No newline at end of file diff --git a/sdk/rust/openidea-plugin/wit/plugin.wit b/sdk/rust/openidea-plugin/wit/plugin.wit index 8cc725b88d..ec2debc267 100644 --- a/sdk/rust/openidea-plugin/wit/plugin.wit +++ b/sdk/rust/openidea-plugin/wit/plugin.wit @@ -40,6 +40,7 @@ world plugin { import mcp; import settings; import extensions; + import agents; export lifecycle; export commands; diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index f2543fe1f6..172bb52dc0 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -18,6 +18,7 @@ agent_delete trusted project_host bin agent_entries always project_host bindings async agent_external_sessions trusted project_host bindings async agent_fork trusted project_host bindings async +agent_fork_session trusted project_host bindings async agent_grouped_changes trusted project_host bindings async agent_hermes_profiles trusted project_host bindings async agent_import_session trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index b797a03af1..b42559fbb2 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -64,6 +64,11 @@ export const commands = { agentExternalSessions: () => typedError<ExternalSession[], IdeError>(__TAURI_INVOKE("agent_external_sessions")), /** Copies the task's conversation into a new task, up to its first `turns` turns (all when `None`). */ agentFork: (task: string, turns: number | null) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })), + /** + * Forks a recorded external session into a new task: its first turn continues the recording + * as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded. + */ + agentForkSession: (provider: string, sessionId: string, cwd: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork_session", { provider, sessionId, cwd })), /** The task's uncommitted changes and the commits made since it started. */ agentGroupedChanges: (task: string) => typedError<AgentChanges, IdeError>(__TAURI_INVOKE("agent_grouped_changes", { task })), /** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */ diff --git a/src/features/agents/AgentsView.tsx b/src/features/agents/AgentsView.tsx index 786124c122..5ef61883d3 100644 --- a/src/features/agents/AgentsView.tsx +++ b/src/features/agents/AgentsView.tsx @@ -42,6 +42,7 @@ import { } from "./organize"; import { externalKey, + forkExternalSession, importExternalSession, moveTasksToGroup, moveTasksToStatusGroup, @@ -718,6 +719,21 @@ export function AgentsView() { > <T>Import</T> </button> + <button + type="button" + className={styles.link} + disabled={importing.has(key)} + title={tx("Fork into a new task")} + onClick={() => + void forkExternalSession( + s.provider, + s.sessionId, + s.cwd ?? useProject.getState().project?.root ?? "", + ).catch(() => {}) + } + > + <T>Fork</T> + </button> </div> ); })} diff --git a/src/features/agents/ImportSessionsDialog.tsx b/src/features/agents/ImportSessionsDialog.tsx index 278c0f3d93..3ac0684dfa 100644 --- a/src/features/agents/ImportSessionsDialog.tsx +++ b/src/features/agents/ImportSessionsDialog.tsx @@ -6,7 +6,14 @@ import { hasPrimaryModifier } from "@/platform/keymap"; import { relativePath, useProject } from "@/platform/project"; import { useTx } from "@/platform/i18n"; import { age, providerIcon } from "./model"; -import { externalKey, hideImportSessions, importExternalSessions, refreshExternalSessions, useAgents } from "./store"; +import { + externalKey, + forkExternalSessions, + hideImportSessions, + importExternalSessions, + refreshExternalSessions, + useAgents, +} from "./store"; import styles from "./Agents.module.css"; /** The backend lists at most this many sessions, newest first. */ @@ -62,7 +69,7 @@ function ImportSessionsDialog() { const [query, setQuery] = useState(""); // By key, so a filter or rescan never moves the selection onto another session. const [sel, setSel] = useState<Selection>({ leadKey: null, anchorKey: null, keys: null }); - const [progress, setProgress] = useState<{ done: number; total: number } | null>(null); + const [progress, setProgress] = useState<{ done: number; total: number; fork?: boolean } | null>(null); // The batch's rows, listed while it imports (they leave `external` one by one). const [frozen, setFrozen] = useState<Row[] | null>(null); const abort = useRef<AbortController | null>(null); @@ -112,25 +119,36 @@ function ImportSessionsDialog() { keys: new Set(view.map((r) => r.key)), }); }; - const importChosen = () => { + const runChosen = (fork: boolean) => { if (busy || !shown || !chosen.length) return; - const batch = chosen.map((r) => ({ provider: r.provider, sessionId: r.sessionId, title: r.title })); setFrozen(chosen); setSel({ leadKey: chosen[0]!.key, anchorKey: chosen[0]!.key, keys: new Set(chosen.map((r) => r.key)) }); - setProgress({ done: 0, total: batch.length }); + const total = chosen.length; + setProgress({ done: 0, total, fork }); const controller = new AbortController(); abort.current = controller; - void importExternalSessions( - batch, - (done) => live.current && setProgress({ done, total: batch.length }), - controller.signal, - ).finally(() => live.current && hideImportSessions()); + const progress = (done: number) => live.current && setProgress({ done, total, fork }); + const finish = () => live.current && hideImportSessions(); + if (fork) { + const batch = chosen.map((r) => ({ + provider: r.provider, + sessionId: r.sessionId, + cwd: r.cwd ?? root ?? "", + title: r.title, + })); + void forkExternalSessions(batch, progress, controller.signal).finally(finish); + } else { + const batch = chosen.map((r) => ({ provider: r.provider, sessionId: r.sessionId, title: r.title })); + void importExternalSessions(batch, progress, controller.signal).finally(finish); + } }; + const importChosen = () => runChosen(false); // Cancel, Esc and the close button stop a running batch after the import in flight. const close = () => { abort.current?.abort(); hideImportSessions(); }; + const forkChosen = () => runChosen(true); const onFilterKey = (e: KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); @@ -155,6 +173,7 @@ function ImportSessionsDialog() { }; const providerName = (id: string) => providers.find((p) => p.id === id)?.name ?? id; const importLabel = chosen.length > 1 ? tx`Import ${chosen.length}` : tx("Import"); + const forkLabel = chosen.length > 1 ? tx`Fork ${chosen.length}` : tx("Fork"); return ( <Dialog @@ -169,7 +188,9 @@ function ImportSessionsDialog() { </Button> {progress ? ( <span className={styles.chooserHint}> - {tx`Importing ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`} + {progress.fork + ? tx`Forking ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…` + : tx`Importing ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`} </span> ) : shown && external.length >= LISTED_MAX ? ( <span className={styles.chooserHint}> @@ -180,6 +201,7 @@ function ImportSessionsDialog() { } buttons={[ { label: "Cancel", role: "cancel" }, + { label: forkLabel, onClick: forkChosen, disabled: busy || !shown || !chosen.length }, { label: importLabel, role: "default", onClick: importChosen, disabled: busy || !shown || !chosen.length }, ]} > diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index 7523410924..ac1f3db591 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -15,6 +15,7 @@ import { ChangesTab } from "./session/ChangesTab"; import { acceptChanges, disconnect, + forkExternalSession, hideImportSessions, importExternalSessions, refreshChanges, @@ -56,6 +57,7 @@ const backend = vi.hoisted(() => ({ updatedMs: number; }>, imported: [] as Array<[string, string]>, + forked: [] as Array<[string, string, string]>, importError: null as string | null, importErrors: new Map<string, string>(), importWait: null as Promise<void> | null, @@ -157,6 +159,20 @@ vi.mock("@/platform/ipc", async (original) => ({ }, }; }, + agentForkSession: async (provider: string, sessionId: string, cwd: string) => { + backend.forked.push([provider, sessionId, cwd]); + const found = backend.external.find((e) => e.provider === provider && e.sessionId === sessionId); + if (!found) throw new Error("unknown session"); + return { + status: "ok", + data: { + ...task(`forked-${sessionId}`), + id: `forked-${sessionId}`, + title: found.title, + provider, + }, + }; + }, }, })); vi.mock("@tauri-apps/api/webview", () => ({ @@ -266,6 +282,7 @@ beforeEach(() => { // The flat list unless a test asks for the grouped view, so counts and selections stay as before. useChangesOptions.setState({ groupByCommit: false, scope: "task" }); backend.imported = []; + backend.forked = []; backend.importError = null; backend.importErrors = new Map(); backend.importWait = null; @@ -2614,6 +2631,19 @@ describe("batch import", () => { }); }); +describe("fork external session", () => { + it("forks a recorded session into a new task and opens it", async () => { + backend.external = [{ provider: "claude", sessionId: "a", title: "First", cwd: "/work/app", updatedMs: 0 }]; + useAgents.setState({ sessionLocation: "toolWindow", docked: null }); + await act(() => forkExternalSession("claude", "a", "/work/app")); + expect(backend.forked).toEqual([["claude", "a", "/work/app"]]); + expect(useAgents.getState().docked).toBe("forked-a"); + expect(useAgents.getState().tasks.has("forked-a")).toBe(true); + expect(useAgents.getState().external).toHaveLength(0); + expect(useAgents.getState().importing.size).toBe(0); + }); +}); + describe("import sessions dialog", () => { const sessions = [ { provider: "claude", sessionId: "abc", title: "Login fix", cwd: "/work/app", updatedMs: 0 }, diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 8e2201c54c..ff81e87888 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -1365,10 +1365,8 @@ function markImporting(keys: readonly string[], on: boolean) { }); } -async function importOne(provider: string, sessionId: string, open: boolean) { - const started = generation; - const task = await call(commands.agentImportSession(provider, sessionId)); - if (generation !== started) return task; +/** Records the task an external session became and opens it when asked; shared by import and fork. */ +function adoptSessionTask(provider: string, sessionId: string, task: AgentTask, open: boolean) { useAgents.setState((s) => ({ tasks: s.tasks.has(task.id) ? s.tasks : new Map(s.tasks).set(task.id, task), external: s.external.filter((e) => !(e.provider === provider && e.sessionId === sessionId)), @@ -1377,26 +1375,52 @@ async function importOne(provider: string, sessionId: string, open: boolean) { return task; } -/** Imports an external session as a task and opens it: its first turn loads it (#312). */ -export async function importExternalSession(provider: string, sessionId: string) { +async function importOne(provider: string, sessionId: string, open: boolean) { + const started = generation; + const task = await call(commands.agentImportSession(provider, sessionId)); + if (generation !== started) return task; + return adoptSessionTask(provider, sessionId, task, open); +} + +async function forkOne(provider: string, sessionId: string, cwd: string, open: boolean) { + const started = generation; + const task = await call(commands.agentForkSession(provider, sessionId, cwd)); + if (generation !== started) return task; + return adoptSessionTask(provider, sessionId, task, open); +} + +/** Guards a single external-session operation against a concurrent one on the same session. */ +async function runExternalOne(provider: string, sessionId: string, run: () => Promise<AgentTask>) { const key = externalKey(provider, sessionId); if (useAgents.getState().importing.has(key)) throw new Error(tx("Already importing")); markImporting([key], true); try { - return await importOne(provider, sessionId, true); + return await run(); } finally { markImporting([key], false); } } +/** Imports an external session as a task and opens it: its first turn loads it (#312). */ +export async function importExternalSession(provider: string, sessionId: string) { + return runExternalOne(provider, sessionId, () => importOne(provider, sessionId, true)); +} + +/** Forks a recorded session into a new task and opens it: its first turn continues the recording. */ +export async function forkExternalSession(provider: string, sessionId: string, cwd: string) { + return runExternalOne(provider, sessionId, () => forkOne(provider, sessionId, cwd, true)); +} + /** - * Imports sessions one after another, all marked pending from the start; only a single one opens. - * Sessions already being imported are skipped. Failures don't stop the rest and are reported - * together at the end. A project switch ends the batch; an abort ends it after the import in - * flight and frees the sessions it didn't reach. + * Runs external-session operations one after another, all marked pending from the start; only a + * single one opens. Sessions already pending are skipped. Failures don't stop the rest and are + * reported together at the end. A project switch ends the batch; an abort ends it after the + * operation in flight and frees the sessions it didn't reach. Shared by import and fork. */ -export async function importExternalSessions( - sessions: readonly { provider: string; sessionId: string; title: string }[], +async function runExternalBatch<T extends { provider: string; sessionId: string; title: string }>( + sessions: readonly T[], + runOne: (session: T, open: boolean) => Promise<unknown>, + failed: { one: string; many: string }, onProgress?: (done: number) => void, signal?: AbortSignal, ) { @@ -1414,8 +1438,8 @@ export async function importExternalSessions( break; } try { - // oxlint-disable-next-line no-await-in-loop -- imports are documented sequential: abort, generation and progress are checked between sessions - await importOne(s.provider, s.sessionId, batch.length === 1); + // oxlint-disable-next-line no-await-in-loop -- operations are documented sequential: abort, generation and progress are checked between sessions + await runOne(s, batch.length === 1); } catch (e) { failures.push(`${s.title}: ${e instanceof Error ? e.message : String(e)}`); } finally { @@ -1425,9 +1449,37 @@ export async function importExternalSessions( } if (generation !== started || !failures.length) return; // Not awaited, so the caller's dialog closes instead of waiting behind the message. - const title = - failures.length === 1 ? tx("A session could not be imported") : tx("Some sessions could not be imported"); - void showError(title, failures.join("\n")); + void showError(failures.length === 1 ? failed.one : failed.many, failures.join("\n")); +} + +/** Imports sessions one after another; the batch rules are {@link runExternalBatch}'s. */ +export async function importExternalSessions( + sessions: readonly { provider: string; sessionId: string; title: string }[], + onProgress?: (done: number) => void, + signal?: AbortSignal, +) { + await runExternalBatch( + sessions, + (s, open) => importOne(s.provider, s.sessionId, open), + { one: tx("A session could not be imported"), many: tx("Some sessions could not be imported") }, + onProgress, + signal, + ); +} + +/** Forks sessions one after another; the batch rules are {@link runExternalBatch}'s. */ +export async function forkExternalSessions( + sessions: readonly { provider: string; sessionId: string; cwd: string; title: string }[], + onProgress?: (done: number) => void, + signal?: AbortSignal, +) { + await runExternalBatch( + sessions, + (s, open) => forkOne(s.provider, s.sessionId, s.cwd, open), + { one: tx("A session could not be forked"), many: tx("Some sessions could not be forked") }, + onProgress, + signal, + ); } export function setIdeContext(on: boolean) { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index c713ba5298..a36eb4a7be 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -592,6 +592,11 @@ "Filter sessions": "Filter sessions", "Import {count}": "Import {count}", "Importing {done} of {total}…": "Importing {done} of {total}…", + "Fork {count}": "Fork {count}", + "Forking {done} of {total}…": "Forking {done} of {total}…", + "A session could not be forked": "A session could not be forked", + "Some sessions could not be forked": "Some sessions could not be forked", + "Fork into a new task": "Fork into a new task", "Only the 50 most recent sessions are shown.": "Only the 50 most recent sessions are shown.", "Some sessions could not be imported": "Some sessions could not be imported", "A session could not be imported": "A session could not be imported", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 198ec5ee4f..fdabebc8d8 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3339,6 +3339,11 @@ "Filter sessions": "过滤会话", "Import {count}": "导入 {count} 个", "Importing {done} of {total}…": "正在导入 {done}/{total}…", + "Fork {count}": "Fork {count} 个", + "Forking {done} of {total}…": "正在 Fork {done}/{total}…", + "A session could not be forked": "一个会话无法 Fork", + "Some sessions could not be forked": "部分会话无法 Fork", + "Fork into a new task": "Fork 为新任务", "Only the 50 most recent sessions are shown.": "仅显示最近的 50 个会话。", "Some sessions could not be imported": "部分会话无法导入", "A session could not be imported": "有一个会话无法导入", diff --git a/wit/agents.wit b/wit/agents.wit new file mode 100644 index 0000000000..b833f3b91b --- /dev/null +++ b/wit/agents.wit @@ -0,0 +1,14 @@ +package openidea:plugin@1.18.0; + +/// Forking recorded native agent sessions into new tasks (API 1.18). Requires +/// the `agents` capability. The session must belong to the invoking window's +/// project and have been recorded in `cwd`; the host builds the fork invocation +/// and names the fork's id for claude (codex assigns its own). +interface agents { + use types.{error}; + /// Fork the recorded session `session-id` of `agent` (a native provider, + /// `claude` or `codex`) into a new task in the open project, returning the + /// new task id. `cwd` must be where the session was recorded. The first + /// turn continues the recording as the agent's own fork. + fork-session: func(agent: string, session-id: string, cwd: string) -> result<string, error>; +} \ No newline at end of file diff --git a/wit/plugin.wit b/wit/plugin.wit index 8cc725b88d..ec2debc267 100644 --- a/wit/plugin.wit +++ b/wit/plugin.wit @@ -40,6 +40,7 @@ world plugin { import mcp; import settings; import extensions; + import agents; export lifecycle; export commands;