дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 22:32:35 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
475b8f4786 | ||
|
|
18a3917fb9 |
No files matched your search
@@ -54,6 +54,21 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Canonical snapshot of approval-bearing config options (`mode`, `permissions`, `approval`)
|
||||
/// so auto-resume can refuse to run silently if permission policy drifted while closed.
|
||||
pub(crate) fn approval_fingerprint(config: &[AgentConfigOption]) -> Option<String> {
|
||||
let mut parts: Vec<String> = config
|
||||
.iter()
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("mode" | "permissions" | "approval")))
|
||||
.filter_map(|o| Some(format!("{}={}", o.id, o.current.as_deref()?)))
|
||||
.collect();
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
parts.sort();
|
||||
Some(parts.join(";"))
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -49,6 +49,74 @@ pub struct AgentCapabilities {
|
||||
pub context_usage: bool,
|
||||
}
|
||||
|
||||
/// Why `AgentManager` is shutting down its live tasks.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum AgentShutdownReason {
|
||||
WindowClose,
|
||||
#[default]
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
}
|
||||
|
||||
/// Why an in-flight turn stopped before completing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum InterruptionReason {
|
||||
WindowClose,
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
fn from(reason: AgentShutdownReason) -> Self {
|
||||
match reason {
|
||||
AgentShutdownReason::WindowClose => Self::WindowClose,
|
||||
AgentShutdownReason::Quit => Self::Quit,
|
||||
AgentShutdownReason::Restart => Self::Restart,
|
||||
AgentShutdownReason::BackendUpgrade => Self::BackendUpgrade,
|
||||
AgentShutdownReason::BackendStop => Self::BackendStop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovery metadata recorded when an active turn was interrupted before finishing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentInterrupted {
|
||||
pub reason: InterruptionReason,
|
||||
pub at_ms: f64,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub was_waiting_for_input: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approval_mode: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub auto_resume_once: bool,
|
||||
}
|
||||
|
||||
/// Summary returned when reconciling interrupted tasks for a connected project window.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentRecoveryReport {
|
||||
/// Unique identifier of this `AgentManager` process incarnation.
|
||||
pub instance_id: String,
|
||||
/// `true` on the first reconciliation of this `AgentManager` incarnation.
|
||||
pub first_reconcile: bool,
|
||||
/// Task IDs automatically resumed during this reconciliation.
|
||||
pub auto_resumed: Vec<String>,
|
||||
/// Task IDs remaining in `Interrupted` (`Ask to resume`).
|
||||
pub interrupted: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Isolation {
|
||||
@@ -117,6 +185,16 @@ pub struct AgentTask {
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub stats: Box<AgentSessionStats>,
|
||||
/// Set when the task's last active turn was interrupted (window close, restart, crash, or
|
||||
/// expired network retry window) and has not been resumed or dismissed yet.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub interrupted: Option<Box<AgentInterrupted>>,
|
||||
/// Persisted unseen reply / input / failure state across window closes and remote reattaches.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub unread: bool,
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -159,6 +237,9 @@ pub struct AgentRetry {
|
||||
/// When the next attempt starts (ms since the epoch).
|
||||
pub retry_at_ms: f64,
|
||||
pub error: Option<String>,
|
||||
/// Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub deadline_ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
|
||||
@@ -528,6 +609,9 @@ pub enum AgentEntry {
|
||||
/// Sent into a running turn rather than starting one.
|
||||
#[serde(default)]
|
||||
steered: bool,
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
|
||||
@@ -67,6 +67,8 @@ struct FakeAgent {
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
/// Queued errors returned on the next `session/prompt` calls before succeeding.
|
||||
prompt_errors: Mutex<VecDeque<(i64, String)>>,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -271,6 +273,9 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/prompt" => {
|
||||
self.prompts.lock().push(params.get("prompt").cloned().unwrap_or(Value::Null));
|
||||
if let Some(err) = self.prompt_errors.lock().pop_front() {
|
||||
return Err(err);
|
||||
}
|
||||
// `!` commands run since the last message come first; the message follows.
|
||||
let first = match params.pointer("/prompt/0/text").and_then(Value::as_str) {
|
||||
Some(t) if t.starts_with("<bash-input>") => 1,
|
||||
@@ -281,6 +286,10 @@ impl Handler for FakeAgent {
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
if text.starts_with("The previous turn was interrupted because ") {
|
||||
self.say(&session, "resumed cleanly");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text.starts_with("<send_user_message_question_reply>") {
|
||||
self.say(&session, "answer received");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -3616,7 +3625,7 @@ fn retry_updates_become_a_countdown() {
|
||||
json!({"sessionUpdate": RETRY_UPDATE, "attempt": 2, "maxRetries": 10, "retryDelayMs": 1500, "error": ""});
|
||||
assert_eq!(
|
||||
retry_of(&update, 1000.0),
|
||||
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None })
|
||||
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None, deadline_ms: None })
|
||||
);
|
||||
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
|
||||
}
|
||||
@@ -6300,3 +6309,477 @@ async fn workspace_roots_go_to_agents_that_take_them() {
|
||||
assert_eq!(mgr.shared.additional_directories(&takes, &worktree, Some(&api)), vec![web]);
|
||||
assert!(mgr.shared.additional_directories(&init(json!({})), &api, None).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_reasons_mark_only_in_flight_tasks_interrupted_and_keep_idle_tasks_clean() {
|
||||
for (shutdown_reason, expected) in [
|
||||
(AgentShutdownReason::WindowClose, InterruptionReason::WindowClose),
|
||||
(AgentShutdownReason::Quit, InterruptionReason::Quit),
|
||||
(AgentShutdownReason::Restart, InterruptionReason::Restart),
|
||||
(AgentShutdownReason::BackendUpgrade, InterruptionReason::BackendUpgrade),
|
||||
(AgentShutdownReason::BackendStop, InterruptionReason::BackendStop),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let idle = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &idle.id, AgentStatus::Ready).await;
|
||||
mgr.mark_read(&idle.id).unwrap();
|
||||
|
||||
let active = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &active.id, AgentStatus::Running).await;
|
||||
|
||||
mgr.shutdown_with(shutdown_reason);
|
||||
|
||||
let reopened = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let tasks = reopened.subscribe_as("", Arc::new(|_| {}));
|
||||
let restored_idle = tasks.iter().find(|t| t.id == idle.id).unwrap();
|
||||
assert_eq!(restored_idle.status, AgentStatus::Ready);
|
||||
assert!(restored_idle.interrupted.is_none(), "idle keepalive task must not become interrupted");
|
||||
assert!(!restored_idle.unread);
|
||||
|
||||
let restored_active = tasks.iter().find(|t| t.id == active.id).unwrap();
|
||||
assert_eq!(restored_active.status, AgentStatus::Ready);
|
||||
assert!(restored_active.unread);
|
||||
let intr = restored_active.interrupted.as_deref().expect("active task marked interrupted");
|
||||
assert_eq!(intr.reason, expected);
|
||||
assert!(!intr.was_waiting_for_input);
|
||||
reopened.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unexpected_exit_on_disk_tags_interrupted_lazily_without_rewriting_untouched_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = tmp.path().join("store");
|
||||
std::fs::create_dir_all(&store).unwrap();
|
||||
let crashed_running = json!({
|
||||
"task": {
|
||||
"id": "crash-run",
|
||||
"title": "Refactor auth",
|
||||
"provider": "claude",
|
||||
"model": "big",
|
||||
"status": "running",
|
||||
"isolation": "local",
|
||||
"cwd": tmp.path(),
|
||||
"branch": null,
|
||||
"base": null,
|
||||
"baseCommit": null,
|
||||
"error": null,
|
||||
"createdMs": 100.0,
|
||||
"updatedMs": 250.0,
|
||||
"config": [{"id": "mode", "name": "Mode", "category": "mode", "current": "ask", "via": "mode", "values": []}],
|
||||
"commands": [],
|
||||
"usage": null,
|
||||
"queue": [],
|
||||
"capabilities": {},
|
||||
"resetsMs": null,
|
||||
"retry": null
|
||||
},
|
||||
"sessionId": "s1",
|
||||
"entries": [
|
||||
{"type": "user", "text": "refactor", "attachments": [], "sentMs": 100.0, "doneMs": null, "steered": false},
|
||||
{"type": "tool", "id": "t1", "title": "cargo check", "kind": "execute", "status": "running", "locations": [], "output": null, "diffs": []}
|
||||
],
|
||||
"wanted": []
|
||||
});
|
||||
let crashed_input = json!({
|
||||
"task": {
|
||||
"id": "crash-input",
|
||||
"title": "Needs approval",
|
||||
"provider": "claude",
|
||||
"model": "big",
|
||||
"status": "needsInput",
|
||||
"isolation": "local",
|
||||
"cwd": tmp.path(),
|
||||
"branch": null,
|
||||
"base": null,
|
||||
"baseCommit": null,
|
||||
"error": null,
|
||||
"createdMs": 100.0,
|
||||
"updatedMs": 300.0,
|
||||
"config": [],
|
||||
"commands": [],
|
||||
"usage": null,
|
||||
"queue": [],
|
||||
"capabilities": {},
|
||||
"resetsMs": null,
|
||||
"retry": null
|
||||
},
|
||||
"sessionId": "s2",
|
||||
"entries": [],
|
||||
"wanted": []
|
||||
});
|
||||
let run_path = store.join("crash-run.json");
|
||||
let input_path = store.join("crash-input.json");
|
||||
let raw_run = serde_json::to_vec(&crashed_running).unwrap();
|
||||
std::fs::write(&run_path, &raw_run).unwrap();
|
||||
std::fs::write(&input_path, serde_json::to_vec(&crashed_input).unwrap()).unwrap();
|
||||
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
// Conversations stay lazy on disk during startup.
|
||||
assert!(!mgr.task("crash-run").unwrap().state.lock().history.is_loaded());
|
||||
let tasks = mgr.subscribe_as("", Arc::new(|_| {}));
|
||||
let r = tasks.iter().find(|t| t.id == "crash-run").unwrap();
|
||||
assert_eq!(r.status, AgentStatus::Ready);
|
||||
assert!(r.unread);
|
||||
assert_eq!(r.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
|
||||
assert!(!r.interrupted.as_ref().unwrap().was_waiting_for_input);
|
||||
assert_eq!(r.interrupted.as_ref().unwrap().approval_mode.as_deref(), Some("mode=ask"));
|
||||
|
||||
let inp = tasks.iter().find(|t| t.id == "crash-input").unwrap();
|
||||
assert_eq!(inp.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
|
||||
assert!(inp.interrupted.as_ref().unwrap().was_waiting_for_input);
|
||||
|
||||
// Shutting down without touching the task does not eagerly load or rewrite its conversation file.
|
||||
mgr.shutdown();
|
||||
assert_eq!(std::fs::read(&run_path).unwrap(), raw_run);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn manual_resume_appends_recovery_turn_drains_queue_and_dismiss_clears_state() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
// Queue a follow-up message before window close.
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
mgr.shutdown_with(AgentShutdownReason::WindowClose);
|
||||
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
let resumed = mgr2.resume_all_interrupted().unwrap();
|
||||
assert_eq!(resumed, vec![task.id.clone()]);
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr2.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(snap.queue.is_empty(), "queued message drained after continuation turn");
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(
|
||||
e,
|
||||
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::WindowClose), .. }
|
||||
)));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
|
||||
|
||||
// Dismissing an interrupted task clears its interrupted & unread state without sending a prompt.
|
||||
let task2 = mgr2
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr2, &task2.id, AgentStatus::Running).await;
|
||||
mgr2.shutdown_with(AgentShutdownReason::Quit);
|
||||
|
||||
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr3.dismiss_interrupted(&task2.id).unwrap();
|
||||
let snap2 = mgr3.task(&task2.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap2.interrupted.is_none());
|
||||
assert!(!snap2.unread);
|
||||
mgr3.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn interrupted_during_starting_before_session_new_resumes_original_prompt_without_duplicate() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let slow_agent = Arc::new(FakeAgent::default());
|
||||
slow_agent.hold_session_new.store(true, Ordering::Release);
|
||||
let mgr = manager(tmp.path(), slow_agent);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Starting).await;
|
||||
mgr.shutdown_with(AgentShutdownReason::Restart);
|
||||
|
||||
let fast_agent = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), fast_agent.clone());
|
||||
mgr2.resume(&task.id).unwrap();
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
let user_entries: Vec<_> = entries.iter().filter(|e| matches!(e, AgentEntry::User { .. })).collect();
|
||||
assert_eq!(user_entries.len(), 1, "original unsent prompt replayed without duplicating user entries");
|
||||
assert!(matches!(user_entries[0], AgentEntry::User { text, recovery: None, .. } if text == "again"));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
|
||||
mgr2.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_user_cancel_settles_to_plain_ready_without_interrupted_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(!snap.unread);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reconcile_interrupted_enforces_policies_one_shot_flag_and_all_safety_guardrails() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
|
||||
// 1. Ask policy leaves regular interrupted tasks waiting, except one-shot auto_resume_once.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Initialize git repo so worktree isolation works cleanly.
|
||||
std::process::Command::new("git").args(["init", "-b", "main"]).current_dir(tmp.path()).output().unwrap();
|
||||
std::fs::write(tmp.path().join("README.md"), "hi\n").unwrap();
|
||||
std::process::Command::new("git").args(["add", "."]).current_dir(tmp.path()).output().unwrap();
|
||||
std::process::Command::new("git")
|
||||
.args(["-c", "user.name=Test", "-c", "[email protected]", "commit", "-m", "init"])
|
||||
.current_dir(tmp.path())
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let wt_one_shot = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let wt_manual = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let needs_perm = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &wt_one_shot.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr, &wt_manual.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr, &needs_perm.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
// Arm one-shot auto-resume on BOTH wt_one_shot and needs_perm; needs_perm must STILL refuse auto-resume!
|
||||
mgr.set_auto_resume_once(&[wt_one_shot.id.clone(), needs_perm.id.clone()], true);
|
||||
mgr.shutdown_with(AgentShutdownReason::WindowClose);
|
||||
|
||||
let mgr2 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Ask)));
|
||||
let report = mgr2.reconcile_interrupted();
|
||||
assert!(report.first_reconcile);
|
||||
assert_eq!(report.auto_resumed, vec![wt_one_shot.id.clone()]);
|
||||
assert!(report.interrupted.contains(&wt_manual.id));
|
||||
assert!(report.interrupted.contains(&needs_perm.id), "NeedsInput task must never auto-resume");
|
||||
// Second call on the same AgentManager instance is idempotent.
|
||||
let second = mgr2.reconcile_interrupted();
|
||||
assert!(!second.first_reconcile);
|
||||
assert!(second.auto_resumed.is_empty());
|
||||
wait_for(&mgr2, &wt_one_shot.id, AgentStatus::Ready).await;
|
||||
mgr2.shutdown();
|
||||
|
||||
// 2. Shared Local checkout contention: two interrupted Local tasks sharing cwd refuse auto-resume
|
||||
// even under Window policy, while isolated Worktree tasks auto-resume.
|
||||
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let local_a = mgr3
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let local_b = mgr3
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr3, &local_a.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr3, &local_b.id, AgentStatus::Running).await;
|
||||
mgr3.shutdown_with(AgentShutdownReason::Restart);
|
||||
|
||||
let mgr4 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr4.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Restart)));
|
||||
let contention_report = mgr4.reconcile_interrupted();
|
||||
assert!(
|
||||
!contention_report.auto_resumed.contains(&local_a.id) && !contention_report.auto_resumed.contains(&local_b.id),
|
||||
"two local tasks sharing a checkout must not race via auto-resume"
|
||||
);
|
||||
assert!(contention_report.interrupted.contains(&local_a.id));
|
||||
assert!(contention_report.interrupted.contains(&local_b.id));
|
||||
|
||||
// 3. Permission-mode drift exclusion: changing approval config blocks silent auto-resume.
|
||||
mgr4.dismiss_interrupted(&local_b.id).unwrap();
|
||||
{
|
||||
let handle = mgr4.task(&local_a.id).unwrap();
|
||||
{
|
||||
let mut s = handle.state.lock();
|
||||
if let Some(mode) = s.task.config.iter_mut().find(|o| o.category.as_deref() == Some("mode")) {
|
||||
mode.current = Some("bypass".into());
|
||||
} else {
|
||||
s.task.config.push(AgentConfigOption {
|
||||
id: "mode".into(),
|
||||
name: "Mode".into(),
|
||||
description: None,
|
||||
category: Some("mode".into()),
|
||||
current: Some("bypass".into()),
|
||||
default_value: None,
|
||||
via: AgentConfigVia::Mode,
|
||||
values: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
handle.persist();
|
||||
}
|
||||
mgr4.shutdown();
|
||||
|
||||
let mgr5 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr5.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Window)));
|
||||
let drift_report = mgr5.reconcile_interrupted();
|
||||
assert!(!drift_report.auto_resumed.contains(&local_a.id), "drifted approval mode must not auto-resume silently");
|
||||
mgr5.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when_online() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "network error: connection reset by peer".into()));
|
||||
|
||||
let online = Arc::new(AtomicBool::new(false));
|
||||
let probe_calls = Arc::new(AtomicU32::new(0));
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.set_network_probe_delays(40, 80);
|
||||
mgr.set_network_probe({
|
||||
let online = online.clone();
|
||||
let probe_calls = probe_calls.clone();
|
||||
move |_| {
|
||||
probe_calls.fetch_add(1, Ordering::SeqCst);
|
||||
online.load(Ordering::SeqCst)
|
||||
}
|
||||
});
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Wait until the task enters `Waiting for network` (`retry.deadline_ms.is_some()`).
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
if snap.retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
|
||||
assert_eq!(snap.status, AgentStatus::Running);
|
||||
assert!(mgr.has_live_work(), "remote daemon must treat network-retry wait as live work");
|
||||
break;
|
||||
}
|
||||
assert!(tokio::time::Instant::now() < deadline, "did not enter network wait: {snap:?}");
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
|
||||
// Let several offline probes run: zero extra `session/prompt` calls may happen while offline.
|
||||
while probe_calls.load(Ordering::SeqCst) < 2 {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(agent.prompts.lock().len(), 1, "must not spend tokens or send prompts while offline");
|
||||
|
||||
// Restore connectivity and poke network (simulating browser `online` event).
|
||||
online.store(true, Ordering::SeqCst);
|
||||
mgr.poke_network();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(snap.retry.is_none());
|
||||
assert_eq!(agent.prompts.lock().len(), 2);
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(
|
||||
e,
|
||||
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::NetworkTimeout), .. }
|
||||
)));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
|
||||
// 1. Turning per-session recovery window to Off (`Some(0)`) during a network wait degrades immediately to Interrupted.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "ENOTFOUND api.anthropic.com".into()));
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
mgr.set_network_probe_delays(500, 1000);
|
||||
mgr.set_network_probe(|_| false);
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while !mgr.task(&task.id).unwrap().state.lock().snapshot().retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
|
||||
assert!(tokio::time::Instant::now() < deadline);
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
|
||||
mgr.set_recovery_window(&task.id, Some(0)).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert_eq!(snap.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
|
||||
|
||||
// 2. Global `NetworkRetryWindow::Off` skips waiting and immediately marks NetworkTimeout Interrupted.
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
agent2.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "503 Service Unavailable".into()));
|
||||
let mgr2 = manager(tmp.path(), agent2);
|
||||
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Off, ResumeInterruptedPolicy::Ask)));
|
||||
let task2 = mgr2
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr2, &task2.id, AgentStatus::Ready).await;
|
||||
let snap2 = mgr2.task(&task2.id).unwrap().state.lock().snapshot();
|
||||
assert_eq!(snap2.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
|
||||
|
||||
// 3. Non-network 401/400 errors fail fast to Failed without entering network retry.
|
||||
let agent3 = Arc::new(FakeAgent::default());
|
||||
agent3.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "400 Bad Request: invalid model parameter".into()));
|
||||
let mgr3 = manager(tmp.path(), agent3);
|
||||
let task3 = mgr3
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr3, &task3.id, AgentStatus::Failed).await;
|
||||
let snap3 = mgr3.task(&task3.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap3.interrupted.is_none());
|
||||
|
||||
mgr.shutdown();
|
||||
mgr2.shutdown();
|
||||
mgr3.shutdown();
|
||||
}
|
||||
@@ -645,6 +645,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -666,6 +667,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
|
||||
@@ -138,6 +138,19 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NewTaskApprovals)]
|
||||
pub new_task_approvals: NewTaskApprovals,
|
||||
/// How long an in-flight turn hit by a transient network outage waits and probes for
|
||||
/// connectivity before degrading to a manual Resume prompt.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NetworkRetryWindow)]
|
||||
pub network_retry_window: NetworkRetryWindow,
|
||||
/// What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
|
||||
/// User settings only.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ResumeInterruptedPolicy)]
|
||||
pub resume_interrupted: ResumeInterruptedPolicy,
|
||||
/// Warn before closing a local window whose project still has running agent tasks.
|
||||
/// User settings only.
|
||||
pub confirm_terminate_on_close: bool,
|
||||
/// Settings new tasks of an agent start with: agent id → option id → value.
|
||||
#[serde(deserialize_with = "agent_defaults")]
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, String>>)]
|
||||
@@ -177,6 +190,9 @@ impl Default for AgentSettings {
|
||||
send_with: SendKey::Enter,
|
||||
while_running: WhileRunning::Queue,
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
network_retry_window: NetworkRetryWindow::Hour1,
|
||||
resume_interrupted: ResumeInterruptedPolicy::Ask,
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
@@ -364,6 +380,49 @@ pub enum NewTaskApprovals {
|
||||
Ask,
|
||||
}
|
||||
|
||||
/// Default auto-retry window for transient network outages during an active agent turn.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub enum NetworkRetryWindow {
|
||||
#[serde(rename = "off")]
|
||||
Off,
|
||||
#[serde(rename = "15m")]
|
||||
Minutes15,
|
||||
#[default]
|
||||
#[serde(rename = "1h")]
|
||||
Hour1,
|
||||
#[serde(rename = "4h")]
|
||||
Hours4,
|
||||
#[serde(rename = "24h")]
|
||||
Hours24,
|
||||
}
|
||||
|
||||
impl NetworkRetryWindow {
|
||||
pub fn minutes(self) -> u32 {
|
||||
match self {
|
||||
Self::Off => 0,
|
||||
Self::Minutes15 => 15,
|
||||
Self::Hour1 => 60,
|
||||
Self::Hours4 => 240,
|
||||
Self::Hours24 => 1440,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How interrupted agent tasks are handled when a project reopens.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ResumeInterruptedPolicy {
|
||||
/// Show Interrupted markers, banner and balloon; wait for the user to click Resume.
|
||||
#[default]
|
||||
Ask,
|
||||
/// Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes.
|
||||
Restart,
|
||||
/// Auto-resume tasks interrupted by close, quit or restart within the session recovery window.
|
||||
Window,
|
||||
/// Settle quietly to Ready with no Interrupted markers or balloons.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// Which folders without an open window the MCP server still serves tools for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -406,8 +406,14 @@ pub async fn serve(
|
||||
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break Ok(()),
|
||||
_ = terminate.recv() => break Ok(()),
|
||||
_ = shutdown.cancelled() => {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendStop);
|
||||
break Ok(());
|
||||
}
|
||||
_ = terminate.recv() => {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
|
||||
break Ok(());
|
||||
}
|
||||
_ = async {
|
||||
match &active {
|
||||
Some(peer) => { peer.closed().await; }
|
||||
@@ -445,6 +451,7 @@ pub async fn serve(
|
||||
if busy {
|
||||
let _ = stream.write_u8(BUSY).await;
|
||||
} else if stream.write_u8(RETIRING).await.is_ok() {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
|
||||
retiring = Some(stream);
|
||||
break Ok(());
|
||||
}
|
||||
|
||||
@@ -155,6 +155,8 @@ pub struct Host {
|
||||
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
|
||||
/// Shutdowns of projects closed with [`Host::close_project_detached`].
|
||||
closing: parking_lot::Mutex<Vec<DetachedClose>>,
|
||||
/// Why this host's agents are shutting down when [`Host::shutdown`] runs.
|
||||
agent_shutdown_reason: parking_lot::Mutex<ide_agent::AgentShutdownReason>,
|
||||
/// One open at a time per window (see [`Host::opening`]).
|
||||
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
|
||||
}
|
||||
@@ -170,6 +172,7 @@ struct ShutdownWork {
|
||||
lsp: Option<Arc<ide_lsp::LspManager>>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
|
||||
agents: Vec<Arc<ide_agent::AgentManager>>,
|
||||
agent_reason: ide_agent::AgentShutdownReason,
|
||||
terminals: Option<ide_terminal::DetachedTerminals>,
|
||||
processes: Option<ide_run::DetachedProcessKills>,
|
||||
retired: Option<Arc<Project>>,
|
||||
@@ -273,6 +276,7 @@ impl Host {
|
||||
requests: Default::default(),
|
||||
project_requests: RwLock::default(),
|
||||
closing: Default::default(),
|
||||
agent_shutdown_reason: parking_lot::Mutex::new(ide_agent::AgentShutdownReason::Quit),
|
||||
open_locks: Default::default(),
|
||||
};
|
||||
host.apply_proxy();
|
||||
@@ -359,13 +363,18 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the shutdown reason reported on interrupted agent turns when [`Self::shutdown`] runs.
|
||||
pub fn set_agent_shutdown_reason(&self, reason: ide_agent::AgentShutdownReason) {
|
||||
*self.agent_shutdown_reason.lock() = reason;
|
||||
}
|
||||
|
||||
/// Closes `window`'s project and waits until its language servers, kernels and
|
||||
/// debug sessions have shut down. Never call this on the UI event-loop thread:
|
||||
/// the shutdown runs on the async runtime, whose workers may themselves be
|
||||
/// waiting for the event loop (IPC responses, window queries). Use
|
||||
/// [`Self::close_project_detached`] there.
|
||||
pub fn close_project(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
if let Some(shutdown) = self.begin_close(window, ide_agent::AgentShutdownReason::WindowClose) {
|
||||
self.wait_blocking(shutdown.handle);
|
||||
}
|
||||
}
|
||||
@@ -374,7 +383,12 @@ impl Host {
|
||||
/// the window; its workers finish shutting down in the background, and
|
||||
/// [`Self::shutdown_notebooks_on_exit`] waits for them before the process exits.
|
||||
pub fn close_project_detached(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
self.close_project_detached_with(window, ide_agent::AgentShutdownReason::WindowClose);
|
||||
}
|
||||
|
||||
/// Like [`Self::close_project_detached`], recording `reason` on any interrupted agent turn.
|
||||
pub fn close_project_detached_with(&self, window: &str, reason: ide_agent::AgentShutdownReason) {
|
||||
if let Some(shutdown) = self.begin_close(window, reason) {
|
||||
let mut closing = self.closing.lock();
|
||||
closing.retain(|entry| !entry.handle.is_finished());
|
||||
closing.push(shutdown);
|
||||
@@ -384,7 +398,7 @@ impl Host {
|
||||
/// Detaches the project from `window` synchronously so the caller (including the UI
|
||||
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
|
||||
/// background handle that stops its workers, agents, terminals and processes.
|
||||
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
|
||||
fn begin_close(&self, window: &str, agent_reason: ide_agent::AgentShutdownReason) -> Option<DetachedClose> {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
@@ -456,6 +470,7 @@ impl Host {
|
||||
// Debug sessions under the root belong to windows: a project served without one starts none.
|
||||
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
|
||||
agents: vec![project.agents.clone()],
|
||||
agent_reason,
|
||||
terminals: Some(terminals),
|
||||
processes: Some(processes),
|
||||
retired: Some(project),
|
||||
@@ -483,9 +498,10 @@ impl Host {
|
||||
}
|
||||
let agents = (!work.agents.is_empty()).then(|| {
|
||||
let agents = work.agents;
|
||||
let reason = work.agent_reason;
|
||||
std::thread::spawn(move || {
|
||||
for manager in agents {
|
||||
manager.shutdown();
|
||||
manager.shutdown_with(reason);
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -576,6 +592,10 @@ impl Host {
|
||||
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
|
||||
/// stuck on the event loop cannot keep the process from exiting.
|
||||
pub fn shutdown_notebooks_on_exit(&self) {
|
||||
self.shutdown_notebooks_on_exit_with(ide_agent::AgentShutdownReason::Quit);
|
||||
}
|
||||
|
||||
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
|
||||
let projects = self.projects();
|
||||
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
|
||||
if !projects.is_empty() {
|
||||
@@ -585,6 +605,7 @@ impl Host {
|
||||
lsp: None,
|
||||
debug: None,
|
||||
agents: projects.iter().map(|project| project.agents.clone()).collect(),
|
||||
agent_reason,
|
||||
terminals: None,
|
||||
processes: None,
|
||||
retired: None,
|
||||
@@ -673,7 +694,8 @@ impl Host {
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
let reason = *self.agent_shutdown_reason.lock();
|
||||
project.agents.shutdown_with(reason);
|
||||
}
|
||||
let stop_processes = async {
|
||||
for project in &projects {
|
||||
|
||||
@@ -7,10 +7,10 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy,
|
||||
AgentSkillState, AgentTask, CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest,
|
||||
LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
|
||||
McpTransport, NewAgentTask, RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -616,6 +616,74 @@ pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<St
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
}
|
||||
|
||||
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
|
||||
/// in the transient network outage retry loop).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_resume_task(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.resume(&task)).await
|
||||
}
|
||||
|
||||
/// Resumes all interrupted tasks in the project and returns their IDs.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_resume_all_interrupted(host: &Host, window: &str) -> IdeResult<Vec<String>> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.resume_all_interrupted()).await
|
||||
}
|
||||
|
||||
/// Clears a task's interrupted state without sending a continuation prompt.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.dismiss_interrupted(&task)).await
|
||||
}
|
||||
|
||||
/// Marks a task as read (`unread = false`) when viewed by the user.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.mark_read(&task)).await
|
||||
}
|
||||
|
||||
/// Overrides the recovery / network auto-retry window (`None` = global default,
|
||||
/// `Some(0)` = Off / Ask, `Some(minutes)` = override) for `task`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_set_recovery_window(host: &Host, window: &str, task: String, minutes: Option<u32>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.set_recovery_window(&task, minutes)).await
|
||||
}
|
||||
|
||||
/// Arms or clears the one-shot auto-resume flag on active/interrupted tasks before window close.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_set_auto_resume_once(host: &Host, window: &str, tasks: Vec<String>, enabled: bool) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || {
|
||||
agents.set_auto_resume_once(&tasks, enabled);
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Wakes any task waiting in the transient network outage loop so reachability is probed now.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_poke_network(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.project(window)?.agents.poke_network();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reconciles interrupted tasks once per `AgentManager` incarnation according to the user's
|
||||
/// recovery policy and safety guardrails.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult<AgentRecoveryReport> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || Ok(agents.reconcile_interrupted())).await
|
||||
}
|
||||
|
||||
/// Stops one of the task's background tasks.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
|
||||
@@ -1656,6 +1724,7 @@ ide_command::domain!(
|
||||
agent_copilot_auth_status,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
agent_dismiss_interrupted,
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
@@ -1665,6 +1734,7 @@ ide_command::domain!(
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mark_read,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
@@ -1674,25 +1744,31 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_poke_network,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
agent_reconcile_interrupted,
|
||||
agent_refresh_models,
|
||||
agent_registry_install,
|
||||
agent_registry_list,
|
||||
agent_registry_remove,
|
||||
agent_rename,
|
||||
agent_respond,
|
||||
agent_resume_all_interrupted,
|
||||
agent_resume_task,
|
||||
agent_rollback,
|
||||
agent_rollback_changes,
|
||||
agent_send_queued_now,
|
||||
agent_set_additional_args,
|
||||
agent_set_auto_resume_once,
|
||||
agent_set_command,
|
||||
agent_shell,
|
||||
agent_set_config,
|
||||
agent_set_env,
|
||||
agent_set_mcp_overrides,
|
||||
agent_set_recovery_window,
|
||||
agent_set_skill_overrides,
|
||||
agent_skills_browse,
|
||||
agent_skills_install,
|
||||
|
||||
@@ -838,6 +838,13 @@ impl Host {
|
||||
let settings = settings.clone();
|
||||
agents.set_new_task_approvals_hook(Arc::new(move || settings.effective().agents.new_task_approvals));
|
||||
}
|
||||
{
|
||||
let settings = settings.clone();
|
||||
agents.set_recovery_settings_hook(Arc::new(move || {
|
||||
let effective = settings.effective();
|
||||
(effective.agents.network_retry_window, effective.agents.resume_interrupted)
|
||||
}));
|
||||
}
|
||||
let approvals = self.mcp_approvals.clone();
|
||||
let secrets = self.agent_secrets.clone();
|
||||
let root = root.to_path_buf();
|
||||
|
||||
@@ -941,3 +941,156 @@ async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
|
||||
assert!(!guard.0.exists());
|
||||
assert!(compose_ids(true).await.is_empty(), "the stop command did not remove the compose service");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_daemon_preserves_agent_across_disconnect_and_records_backend_stop_for_resume() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let base = tmp.path().join("server");
|
||||
let project = home.join("demo");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let agents_dir = base.join("config/agents");
|
||||
std::fs::create_dir_all(&agents_dir).unwrap();
|
||||
|
||||
// Custom ACP agent: blocks on "hold" while disconnected, finishes immediately on continuation prompt.
|
||||
let agent_script = tmp.path().join("mock-acp-agent.sh");
|
||||
let script = r#"#!/bin/sh
|
||||
while IFS= read -r line; do
|
||||
id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')
|
||||
case "$line" in
|
||||
*'"initialize"'*)
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"
|
||||
;;
|
||||
*'"session/new"'*)
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"remote-s1"}}\n' "$id"
|
||||
;;
|
||||
*'"session/load"'*)
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
|
||||
;;
|
||||
*'"session/prompt"'*)
|
||||
case "$line" in
|
||||
*'"hold"'*)
|
||||
sleep 30
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
|
||||
;;
|
||||
*)
|
||||
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"remote-s1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"remote resumed"}}}}\n'
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
done
|
||||
"#;
|
||||
std::fs::write(&agent_script, script).unwrap();
|
||||
std::fs::set_permissions(&agent_script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::write(
|
||||
agents_dir.join("mock.toml"),
|
||||
format!("name = \"Mock Remote\"\ncommand = {:?}\nargs = []\n", agent_script.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let _guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
|
||||
|
||||
// 1. Connect first client, open project, and start a long-running agent task.
|
||||
let (first, _) = attach_client(&home, &base, "~/demo", 1);
|
||||
initialize(&first).await;
|
||||
invoke(&first, "open_project", json!({ "path": project })).await.unwrap();
|
||||
invoke(&first, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
|
||||
let _ =
|
||||
invoke(&first, "agent_subscribe", json!({ "onEvent": { "$channel": 1 }, "subscriber": "w1" })).await.unwrap();
|
||||
let report1 = invoke(&first, "agent_reconcile_interrupted", json!({})).await.unwrap();
|
||||
let instance1 = report1["instanceId"].as_str().unwrap().to_owned();
|
||||
|
||||
let created = invoke(
|
||||
&first,
|
||||
"agent_create",
|
||||
json!({
|
||||
"request": {
|
||||
"projectRoot": null,
|
||||
"prompt": { "text": "hold", "files": [], "images": [] },
|
||||
"provider": "mock",
|
||||
"config": [],
|
||||
"isolation": "local",
|
||||
"base": null,
|
||||
"mcpOverrides": {},
|
||||
"skillOverrides": {},
|
||||
"idle": false,
|
||||
"ephemeral": false,
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let task_id = created["id"].as_str().unwrap().to_owned();
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let tasks = invoke(&first, "agent_subscribe", json!({ "onEvent": { "$channel": 2 }, "subscriber": "w1" }))
|
||||
.await
|
||||
.unwrap();
|
||||
if tasks.as_array().unwrap().iter().any(|t| t["id"] == task_id && t["status"] == "running") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("remote agent task did not reach running");
|
||||
|
||||
// 2. Kill client relay (SSH disconnect / laptop sleep) and wait past the 1s idle timeout:
|
||||
// `has_live_work()` keeps the daemon and the agent turn alive!
|
||||
first.kill();
|
||||
first.exited().await;
|
||||
tokio::time::sleep(Duration::from_millis(1600)).await;
|
||||
|
||||
let (second, _) = attach_client(&home, &base, "~/demo", 1);
|
||||
initialize(&second).await;
|
||||
let tasks =
|
||||
invoke(&second, "agent_subscribe", json!({ "onEvent": { "$channel": 1 }, "subscriber": "w2" })).await.unwrap();
|
||||
let live_task = tasks.as_array().unwrap().iter().find(|t| t["id"] == task_id).unwrap();
|
||||
assert_eq!(live_task["status"], json!("running"), "SSH disconnect must not interrupt a remote daemon's agent");
|
||||
let report2 = invoke(&second, "agent_reconcile_interrupted", json!({})).await.unwrap();
|
||||
assert_eq!(report2["instanceId"].as_str(), Some(instance1.as_str()));
|
||||
assert_eq!(report2["firstReconcile"], json!(false));
|
||||
|
||||
// 3. Explicit Stop Remote Backend (`"shutdown"`) settles the active turn as `Interrupted (backendStop)`.
|
||||
shutdown(&second).await;
|
||||
|
||||
// 4. Reconnect (spawns fresh daemon): new `instanceId`, task is `Interrupted (backendStop)`, and 1-click Resume finishes!
|
||||
let (third, _) = attach_client(&home, &base, "~/demo", 5);
|
||||
initialize(&third).await;
|
||||
invoke(&third, "open_project", json!({ "path": project })).await.unwrap();
|
||||
let tasks3 =
|
||||
invoke(&third, "agent_subscribe", json!({ "onEvent": { "$channel": 1 }, "subscriber": "w3" })).await.unwrap();
|
||||
let stopped_task = tasks3.as_array().unwrap().iter().find(|t| t["id"] == task_id).unwrap();
|
||||
assert_eq!(stopped_task["status"], json!("ready"));
|
||||
assert_eq!(stopped_task["interrupted"]["reason"], json!("backendStop"));
|
||||
|
||||
let report3 = invoke(&third, "agent_reconcile_interrupted", json!({})).await.unwrap();
|
||||
assert_ne!(report3["instanceId"].as_str(), Some(instance1.as_str()));
|
||||
assert_eq!(report3["firstReconcile"], json!(true));
|
||||
assert_eq!(report3["interrupted"], json!([task_id]));
|
||||
|
||||
invoke(&third, "agent_resume_task", json!({ "task": task_id })).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let cur = invoke(&third, "agent_subscribe", json!({ "onEvent": { "$channel": 2 }, "subscriber": "w3" }))
|
||||
.await
|
||||
.unwrap();
|
||||
let t = cur.as_array().unwrap().iter().find(|t| t["id"] == task_id).unwrap();
|
||||
if t["status"] == "ready" && t.get("interrupted").is_none_or(Value::is_null) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("resumed remote task did not finish");
|
||||
|
||||
let entries = invoke(&third, "agent_entries", json!({ "task": task_id, "subagent": null })).await.unwrap();
|
||||
assert!(entries.as_array().unwrap().iter().any(|e| e["type"] == "agent" && e["text"] == "remote resumed"));
|
||||
shutdown(&third).await;
|
||||
}
|
||||
@@ -74,6 +74,8 @@ const USER_ONLY: &[&[&str]] = &[
|
||||
&["agentSecurity", "allowedCommands"],
|
||||
&["agents", "defaults"],
|
||||
&["agents", "newTaskApprovals"],
|
||||
&["agents", "resumeInterrupted"],
|
||||
&["agents", "confirmTerminateOnClose"],
|
||||
// OS notification centre: machine-local; projects must not enable/disable.
|
||||
&["notifications", "systemNotifications"],
|
||||
];
|
||||
@@ -1753,4 +1755,35 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(!settings.reload().notifications.system_notifications);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_recovery_policies_are_user_settings() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = tmp.path().join("config");
|
||||
let project = tmp.path().join("project");
|
||||
std::fs::create_dir_all(project.join(".openidea")).unwrap();
|
||||
std::fs::write(
|
||||
project.join(".openidea/settings.toml"),
|
||||
"[agents]\nresumeInterrupted = \"window\"\nconfirmTerminateOnClose = false\nnetworkRetryWindow = \"4h\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let settings = SettingsStore::load(&config, Some(&project));
|
||||
assert_eq!(settings.effective().agents.resume_interrupted, ResumeInterruptedPolicy::Ask);
|
||||
assert!(settings.effective().agents.confirm_terminate_on_close);
|
||||
assert_eq!(settings.effective().agents.network_retry_window, NetworkRetryWindow::Hours4);
|
||||
|
||||
// Project scope cannot force auto-resume or disable close warnings.
|
||||
assert!(settings.set(SettingsScope::Project, "agents.resumeInterrupted", json!("window")).is_err());
|
||||
assert!(settings.set(SettingsScope::Project, "agents.confirmTerminateOnClose", json!(false)).is_err());
|
||||
|
||||
// Global user scope updates USER_ONLY settings; project layer still overrides networkRetryWindow until cleared.
|
||||
let s = settings.set(SettingsScope::Global, "agents.resumeInterrupted", json!("restart")).unwrap();
|
||||
assert_eq!(s.agents.resume_interrupted, ResumeInterruptedPolicy::Restart);
|
||||
let s = settings.set(SettingsScope::Global, "agents.confirmTerminateOnClose", json!(false)).unwrap();
|
||||
assert!(!s.agents.confirm_terminate_on_close);
|
||||
let s = settings.set(SettingsScope::Project, "agents.networkRetryWindow", json!("15m")).unwrap();
|
||||
assert_eq!(s.agents.network_retry_window, NetworkRetryWindow::Minutes15);
|
||||
}
|
||||
}
|
||||
@@ -319,8 +319,13 @@ pub fn run() {
|
||||
let settings = ide_host::ops::project::settings_get(&state.host, window.label());
|
||||
w.keep_alive.store(settings.general.close_without_welcome, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
let reason = match window.try_state::<WindowsState>() {
|
||||
Some(w) if w.restart_requested() => ide_agent::AgentShutdownReason::Restart,
|
||||
Some(w) if w.quitting() => ide_agent::AgentShutdownReason::Quit,
|
||||
_ => ide_agent::AgentShutdownReason::WindowClose,
|
||||
};
|
||||
state.updates.forget_window(window.label());
|
||||
state.close_project(window.label());
|
||||
state.close_project_with(window.label(), reason);
|
||||
state.plugins.forget_client(window.label());
|
||||
}
|
||||
}
|
||||
@@ -365,15 +370,21 @@ pub fn run() {
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
#[cfg(target_os = "macos")]
|
||||
windows::flush_auxiliary_geometry(app);
|
||||
let restart = app.try_state::<WindowsState>().is_some_and(|w| w.restart_requested());
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
let reason = if restart {
|
||||
ide_agent::AgentShutdownReason::Restart
|
||||
} else {
|
||||
ide_agent::AgentShutdownReason::Quit
|
||||
};
|
||||
ide_db::stop_external_tunnels_on_exit();
|
||||
state.host.stop_processes_on_exit();
|
||||
state.host.mcp.stop(&state.host);
|
||||
state.host.clear_workspace_edit_history_on_exit();
|
||||
state.host.shutdown_notebooks_on_exit();
|
||||
state.host.shutdown_notebooks_on_exit_with(reason);
|
||||
}
|
||||
// Cleanup must finish before update/restart replaces this process.
|
||||
if app.try_state::<WindowsState>().is_some_and(|w| w.restart_requested()) {
|
||||
if restart {
|
||||
#[cfg(target_os = "macos")]
|
||||
relaunch::restart(&app.env());
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
|
||||
@@ -189,9 +189,13 @@ impl AppState {
|
||||
/// Called on the event-loop thread (window destruction, the `close_project`
|
||||
/// command), so it must not wait for the project's workers to shut down.
|
||||
pub fn close_project(&self, window: &str) {
|
||||
self.close_project_with(window, ide_agent::AgentShutdownReason::WindowClose);
|
||||
}
|
||||
|
||||
pub fn close_project_with(&self, window: &str, reason: ide_agent::AgentShutdownReason) {
|
||||
crate::system_notifications::clear_window(window);
|
||||
self.remote_dev.disconnect(window);
|
||||
self.host.close_project_detached(window);
|
||||
self.host.close_project_detached_with(window, reason);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ agent_custom_import trusted desktop bin
|
||||
agent_custom_remove trusted desktop bindings sync
|
||||
agent_custom_save trusted desktop bindings sync
|
||||
agent_delete trusted project_host bindings async
|
||||
agent_dismiss_interrupted always project_host bindings async
|
||||
agent_entries always project_host bindings async
|
||||
agent_external_sessions trusted project_host bindings async
|
||||
agent_fork trusted project_host bindings async
|
||||
@@ -25,6 +26,7 @@ agent_grouped_changes trusted project_host bin
|
||||
agent_hermes_profiles trusted project_host bindings async
|
||||
agent_import_session trusted project_host bindings async
|
||||
agent_login_spawn outside_restricted project_host bindings async
|
||||
agent_mark_read always project_host bindings async
|
||||
agent_mcp_discover_sources always project_host bindings async
|
||||
agent_mcp_import always project_host bindings sync
|
||||
agent_mcp_import_selected always project_host bindings async
|
||||
@@ -34,24 +36,30 @@ agent_mcp_save always project_host bin
|
||||
agent_mcp_save_json always project_host bindings sync
|
||||
agent_mcp_set_enabled always project_host bindings sync
|
||||
agent_mcp_test trusted project_host bindings async
|
||||
agent_poke_network always project_host bindings sync
|
||||
agent_preview_copilot_models trusted project_host bindings async
|
||||
agent_probe trusted project_host bindings async
|
||||
agent_prompt trusted project_host bindings async
|
||||
agent_providers trusted project_host bindings async
|
||||
agent_reconcile_interrupted trusted project_host bindings async
|
||||
agent_refresh_models trusted project_host bindings sync
|
||||
agent_registry_install always project_host bindings async
|
||||
agent_registry_list always project_host bindings async
|
||||
agent_registry_remove always project_host bindings async
|
||||
agent_rename trusted project_host bindings sync
|
||||
agent_respond trusted project_host bindings sync
|
||||
agent_resume_all_interrupted trusted project_host bindings async
|
||||
agent_resume_task trusted project_host bindings async
|
||||
agent_rollback trusted project_host bindings async
|
||||
agent_rollback_changes trusted project_host bindings async
|
||||
agent_send_queued_now trusted project_host bindings async
|
||||
agent_set_additional_args trusted project_host bindings sync
|
||||
agent_set_auto_resume_once trusted project_host bindings async
|
||||
agent_set_command trusted project_host bindings sync
|
||||
agent_set_config trusted project_host bindings async
|
||||
agent_set_env trusted project_host bindings sync
|
||||
agent_set_mcp_overrides always project_host bindings sync
|
||||
agent_set_recovery_window trusted project_host bindings async
|
||||
agent_set_skill_overrides always project_host bindings sync
|
||||
agent_shell trusted project_host bindings async
|
||||
agent_skills_browse always project_host bindings async
|
||||
|
||||
+145
-4
@@ -57,6 +57,8 @@ export const commands = {
|
||||
*/
|
||||
agentCustomSave: (input: CustomAgentInput) => typedError<null, IdeError>(__TAURI_INVOKE("agent_custom_save", { input })),
|
||||
agentDelete: (task: string, removeWorktree: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_delete", { task, removeWorktree })),
|
||||
/** Clears a task's interrupted state without sending a continuation prompt. */
|
||||
agentDismissInterrupted: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_dismiss_interrupted", { task })),
|
||||
/**
|
||||
* Entries of `task`'s conversation, or of its subagent `subagent`'s. On the blocking pool:
|
||||
* the first read of a saved conversation parses its task file, and a long one is cloned
|
||||
@@ -85,6 +87,8 @@ export const commands = {
|
||||
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
|
||||
/** Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code. */
|
||||
agentLoginSpawn: (id: string, cols: number, rows: number, onEvent: Channel<AgentLoginEvent>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("agent_login_spawn", { id, cols, rows, onEvent })),
|
||||
/** Marks a task as read (`unread = false`) when viewed by the user. */
|
||||
agentMarkRead: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_mark_read", { task })),
|
||||
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
|
||||
agentMcpDiscoverSources: () => typedError<McpExternalSource[], IdeError>(__TAURI_INVOKE("agent_mcp_discover_sources")),
|
||||
/** Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once. */
|
||||
@@ -106,6 +110,8 @@ export const commands = {
|
||||
agentMcpSetEnabled: (id: string, enabled: boolean) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_set_enabled", { id, enabled })),
|
||||
/** Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`). */
|
||||
agentMcpTest: (id: string) => typedError<McpProbeResult, IdeError>(__TAURI_INVOKE("agent_mcp_test", { id })),
|
||||
/** Wakes any task waiting in the transient network outage loop so reachability is probed now. */
|
||||
agentPokeNetwork: () => typedError<null, IdeError>(__TAURI_INVOKE("agent_poke_network")),
|
||||
/** Probes Copilot's model catalog for a staged GitHub account without persisting until Apply. */
|
||||
agentPreviewCopilotModels: (account: string, model: string | null) => typedError<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_preview_copilot_models", { account, model })),
|
||||
/**
|
||||
@@ -120,6 +126,11 @@ export const commands = {
|
||||
* blocking pool.
|
||||
*/
|
||||
agentProviders: () => typedError<AgentProvider_Serialize[], IdeError>(__TAURI_INVOKE("agent_providers")),
|
||||
/**
|
||||
* Reconciles interrupted tasks once per `AgentManager` incarnation according to the user's
|
||||
* recovery policy and safety guardrails.
|
||||
*/
|
||||
agentReconcileInterrupted: () => typedError<AgentRecoveryReport, IdeError>(__TAURI_INVOKE("agent_reconcile_interrupted")),
|
||||
/** Refreshes the model catalog; force bypasses freshness, not the cooldown. */
|
||||
agentRefreshModels: (provider: string, force: boolean, model: string | null) => typedError<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_refresh_models", { provider, force, model })),
|
||||
/**
|
||||
@@ -137,6 +148,13 @@ export const commands = {
|
||||
agentRename: (task: string, title: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rename", { task, title })),
|
||||
/** Answers a permission request; `option: null` cancels it. */
|
||||
agentRespond: (task: string, permission: number, option: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_respond", { task, permission, option })),
|
||||
/** Resumes all interrupted tasks in the project and returns their IDs. */
|
||||
agentResumeAllInterrupted: () => typedError<string[], IdeError>(__TAURI_INVOKE("agent_resume_all_interrupted")),
|
||||
/**
|
||||
* Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
|
||||
* in the transient network outage retry loop).
|
||||
*/
|
||||
agentResumeTask: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_resume_task", { task })),
|
||||
/**
|
||||
* Drops the task's turns after its first `turns`; returns the message of the first dropped one.
|
||||
* With `files`, the files those turns changed go back as they were before them.
|
||||
@@ -158,6 +176,8 @@ export const commands = {
|
||||
agentSendQueuedNow: (task: string, queued: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_send_queued_now", { task, queued })),
|
||||
/** Sets additional launch arguments for a built-in ACP agent; an empty list resets them. */
|
||||
agentSetAdditionalArgs: (id: string, args: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_additional_args", { id, args })),
|
||||
/** Arms or clears the one-shot auto-resume flag on active/interrupted tasks before window close. */
|
||||
agentSetAutoResumeOnce: (tasks: string[], enabled: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_auto_resume_once", { tasks, enabled })),
|
||||
/**
|
||||
* Overrides built-in agent `id`'s command with `command` (its agent file keeps the
|
||||
* built-in's driver and arguments), or returns it to auto-detection with `None`.
|
||||
@@ -172,6 +192,11 @@ export const commands = {
|
||||
agentSetEnv: (id: string, env: { [key in string]: string }) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_env", { id, env })),
|
||||
/** Updates per-session MCP server enable/disable overrides on `task`. */
|
||||
agentSetMcpOverrides: (task: string, overrides: { [key in string]: boolean }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_mcp_overrides", { task, overrides })),
|
||||
/**
|
||||
* Overrides the recovery / network auto-retry window (`None` = global default,
|
||||
* `Some(0)` = Off / Ask, `Some(minutes)` = override) for `task`.
|
||||
*/
|
||||
agentSetRecoveryWindow: (task: string, minutes: number | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_recovery_window", { task, minutes })),
|
||||
/** Updates per-session skill modes on `task`. */
|
||||
agentSetSkillOverrides: (task: string, overrides: { [key in string]: AgentSkillMode }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_skill_overrides", { task, overrides })),
|
||||
/**
|
||||
@@ -2946,7 +2971,9 @@ sentMs?: number | null;
|
||||
/** When the turn it started ended; `None` while it runs or when it was cut off. */
|
||||
doneMs?: number | null;
|
||||
/** Sent into a running turn rather than starting one. */
|
||||
steered?: boolean } | { type: "agent"; text: string } |
|
||||
steered?: boolean;
|
||||
/** Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn. */
|
||||
recovery?: InterruptionReason | null } | { type: "agent"; text: string } |
|
||||
/** A question that can be answered while the agent keeps working, or after the turn ends. */
|
||||
{ type: "question"; id: string; title: string; questions: AgentQuestion[];
|
||||
/** The submitted answers, or `Skipped`; `None` while unanswered. */
|
||||
@@ -3098,6 +3125,27 @@ export type AgentImage = {
|
||||
name: string | null,
|
||||
};
|
||||
|
||||
/** Recovery metadata recorded when an active turn was interrupted before finishing. */
|
||||
export type AgentInterrupted = AgentInterrupted_Serialize | AgentInterrupted_Deserialize;
|
||||
|
||||
/** Recovery metadata recorded when an active turn was interrupted before finishing. */
|
||||
export type AgentInterrupted_Deserialize = {
|
||||
reason: InterruptionReason,
|
||||
atMs: number | null,
|
||||
wasWaitingForInput?: boolean,
|
||||
approvalMode?: string | null,
|
||||
autoResumeOnce?: boolean,
|
||||
};
|
||||
|
||||
/** Recovery metadata recorded when an active turn was interrupted before finishing. */
|
||||
export type AgentInterrupted_Serialize = {
|
||||
reason: InterruptionReason,
|
||||
atMs: number | null,
|
||||
wasWaitingForInput?: boolean,
|
||||
approvalMode?: string | null,
|
||||
autoResumeOnce?: boolean,
|
||||
};
|
||||
|
||||
/** One usage-limit window of an agent's account. */
|
||||
export type AgentLimit = {
|
||||
/** The window as the agent names it: `five_hour`, `seven_day`, `seven_day_opus`… */
|
||||
@@ -3294,6 +3342,18 @@ export type AgentQueued = {
|
||||
prompt: AgentPrompt,
|
||||
};
|
||||
|
||||
/** Summary returned when reconciling interrupted tasks for a connected project window. */
|
||||
export type AgentRecoveryReport = {
|
||||
/** Unique identifier of this `AgentManager` process incarnation. */
|
||||
instanceId: string,
|
||||
/** `true` on the first reconciliation of this `AgentManager` incarnation. */
|
||||
firstReconcile: boolean,
|
||||
/** Task IDs automatically resumed during this reconciliation. */
|
||||
autoResumed: string[],
|
||||
/** Task IDs remaining in `Interrupted` (`Ask to resume`). */
|
||||
interrupted: string[],
|
||||
};
|
||||
|
||||
export type AgentRegistry = {
|
||||
agents: RegistryAgent[],
|
||||
/** Set when the registry could not be reached and the copy saved earlier is shown. */
|
||||
@@ -3301,12 +3361,28 @@ export type AgentRegistry = {
|
||||
};
|
||||
|
||||
/** An API request the agent is about to retry. */
|
||||
export type AgentRetry = {
|
||||
export type AgentRetry = AgentRetry_Serialize | AgentRetry_Deserialize;
|
||||
|
||||
/** An API request the agent is about to retry. */
|
||||
export type AgentRetry_Deserialize = {
|
||||
attempt: number,
|
||||
maxRetries: number | null,
|
||||
/** When the next attempt starts (ms since the epoch). */
|
||||
retryAtMs: number | null,
|
||||
error: string | null,
|
||||
/** Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`. */
|
||||
deadlineMs?: number | null,
|
||||
};
|
||||
|
||||
/** An API request the agent is about to retry. */
|
||||
export type AgentRetry_Serialize = {
|
||||
attempt: number,
|
||||
maxRetries: number | null,
|
||||
/** When the next attempt starts (ms since the epoch). */
|
||||
retryAtMs: number | null,
|
||||
error: string | null,
|
||||
/** Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`. */
|
||||
deadlineMs?: number | null,
|
||||
};
|
||||
|
||||
/** Tools › Agents: Command Execution Policy (whitelist and blacklist patterns). */
|
||||
@@ -3370,6 +3446,21 @@ export type AgentSettings_Deserialize = {
|
||||
* bypass permissions, Codex's full access) or in one that asks. User settings only.
|
||||
*/
|
||||
newTaskApprovals?: NewTaskApprovals,
|
||||
/**
|
||||
* How long an in-flight turn hit by a transient network outage waits and probes for
|
||||
* connectivity before degrading to a manual Resume prompt.
|
||||
*/
|
||||
networkRetryWindow?: NetworkRetryWindow,
|
||||
/**
|
||||
* What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
|
||||
* User settings only.
|
||||
*/
|
||||
resumeInterrupted?: ResumeInterruptedPolicy,
|
||||
/**
|
||||
* Warn before closing a local window whose project still has running agent tasks.
|
||||
* User settings only.
|
||||
*/
|
||||
confirmTerminateOnClose?: boolean,
|
||||
/** Settings new tasks of an agent start with: agent id → option id → value. */
|
||||
defaults?: { [key in string]: { [key in string]: string } },
|
||||
/**
|
||||
@@ -3427,6 +3518,21 @@ export type AgentSettings_Serialize = {
|
||||
* bypass permissions, Codex's full access) or in one that asks. User settings only.
|
||||
*/
|
||||
newTaskApprovals: NewTaskApprovals,
|
||||
/**
|
||||
* How long an in-flight turn hit by a transient network outage waits and probes for
|
||||
* connectivity before degrading to a manual Resume prompt.
|
||||
*/
|
||||
networkRetryWindow: NetworkRetryWindow,
|
||||
/**
|
||||
* What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
|
||||
* User settings only.
|
||||
*/
|
||||
resumeInterrupted: ResumeInterruptedPolicy,
|
||||
/**
|
||||
* Warn before closing a local window whose project still has running agent tasks.
|
||||
* User settings only.
|
||||
*/
|
||||
confirmTerminateOnClose: boolean,
|
||||
/** Settings new tasks of an agent start with: agent id → option id → value. */
|
||||
defaults: { [key in string]: { [key in string]: string } },
|
||||
/**
|
||||
@@ -3649,7 +3755,7 @@ export type AgentTask_Deserialize = {
|
||||
* The agent is retrying a failed API request (connection lost, overloaded…); cleared
|
||||
* by its next output or any status change.
|
||||
*/
|
||||
retry?: AgentRetry | null,
|
||||
retry?: AgentRetry_Deserialize | null,
|
||||
/** What the agent runs in the background (shells, subagents, monitors), oldest first. */
|
||||
background?: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
@@ -3658,6 +3764,15 @@ export type AgentTask_Deserialize = {
|
||||
skillOverrides?: { [key in string]: AgentSkillMode },
|
||||
/** Token counts of the last turn and context compressions, when the agent reports them. */
|
||||
stats?: AgentSessionStats,
|
||||
/**
|
||||
* Set when the task's last active turn was interrupted (window close, restart, crash, or
|
||||
* expired network retry window) and has not been resumed or dismissed yet.
|
||||
*/
|
||||
interrupted?: AgentInterrupted_Deserialize | null,
|
||||
/** Persisted unseen reply / input / failure state across window closes and remote reattaches. */
|
||||
unread?: boolean,
|
||||
/** Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global). */
|
||||
recoveryWindowMins?: number | null,
|
||||
};
|
||||
|
||||
export type AgentTask_Serialize = {
|
||||
@@ -3701,7 +3816,7 @@ export type AgentTask_Serialize = {
|
||||
* The agent is retrying a failed API request (connection lost, overloaded…); cleared
|
||||
* by its next output or any status change.
|
||||
*/
|
||||
retry: AgentRetry | null,
|
||||
retry: AgentRetry_Serialize | null,
|
||||
/** What the agent runs in the background (shells, subagents, monitors), oldest first. */
|
||||
background: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
@@ -3710,6 +3825,15 @@ export type AgentTask_Serialize = {
|
||||
skillOverrides?: { [key in string]: AgentSkillMode },
|
||||
/** Token counts of the last turn and context compressions, when the agent reports them. */
|
||||
stats: AgentSessionStats,
|
||||
/**
|
||||
* Set when the task's last active turn was interrupted (window close, restart, crash, or
|
||||
* expired network retry window) and has not been resumed or dismissed yet.
|
||||
*/
|
||||
interrupted?: AgentInterrupted_Serialize | null,
|
||||
/** Persisted unseen reply / input / failure state across window closes and remote reattaches. */
|
||||
unread?: boolean,
|
||||
/** Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global). */
|
||||
recoveryWindowMins?: number | null,
|
||||
};
|
||||
|
||||
/** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */
|
||||
@@ -9346,6 +9470,9 @@ export type InterfaceMember = {
|
||||
handleIdentifier: string,
|
||||
};
|
||||
|
||||
/** Why an in-flight turn stopped before completing. */
|
||||
export type InterruptionReason = "windowClose" | "quit" | "restart" | "backendUpgrade" | "backendStop" | "unexpectedExit" | "networkTimeout";
|
||||
|
||||
/** Optional parts of the invalidation; the symbol index is always rebuilt. */
|
||||
export type InvalidateCachesOptions = {
|
||||
/** Local History of every project. */
|
||||
@@ -11041,6 +11168,9 @@ export type NavigationResult = {
|
||||
targets: Location[],
|
||||
};
|
||||
|
||||
/** Default auto-retry window for transient network outages during an active agent turn. */
|
||||
export type NetworkRetryWindow = "off" | "15m" | "1h" | "4h" | "24h";
|
||||
|
||||
export type NewAgentTask = {
|
||||
/** Validated by the host; defaults to the window project root. */
|
||||
projectRoot?: IpcPath | null,
|
||||
@@ -13229,6 +13359,17 @@ export type ResolvedMapping = {
|
||||
deployment: string,
|
||||
};
|
||||
|
||||
/** How interrupted agent tasks are handled when a project reopens. */
|
||||
export type ResumeInterruptedPolicy =
|
||||
/** Show Interrupted markers, banner and balloon; wait for the user to click Resume. */
|
||||
"ask" |
|
||||
/** Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes. */
|
||||
"restart" |
|
||||
/** Auto-resume tasks interrupted by close, quit or restart within the session recovery window. */
|
||||
"window" |
|
||||
/** Settle quietly to Ready with no Interrupted markers or balloons. */
|
||||
"off";
|
||||
|
||||
export type ReviewEvent = "approve" | "requestChanges" | "comment";
|
||||
|
||||
/** A file changed across several commits: its content at `before` ↔ at `after`. */
|
||||
|
||||
@@ -171,6 +171,9 @@
|
||||
.ready {
|
||||
color: var(--success);
|
||||
}
|
||||
.interrupted {
|
||||
color: var(--warning);
|
||||
}
|
||||
.failed {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Status bar widget: tasks waiting for the user / running; opens the most urgent one. */
|
||||
import { Icon, Spinner, T } from "@/ui";
|
||||
import { isInterrupted } from "./model";
|
||||
import { openTask, useAgents } from "./store";
|
||||
import styles from "./Agents.module.css";
|
||||
|
||||
@@ -9,9 +10,11 @@ export function AgentsStatus() {
|
||||
const list = [...tasks.values()];
|
||||
const unseen = list.filter((t) => unread.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
const input = list.filter((t) => t.status === "needsInput");
|
||||
const interrupted = list.filter(isInterrupted).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
const running = list.filter((t) => t.status === "running" || t.status === "starting").length;
|
||||
if (!input.length && !running && !unseen.length) return null;
|
||||
const target = input[0] ?? unseen[0] ?? list.find((t) => t.status === "running" || t.status === "starting");
|
||||
if (!input.length && !interrupted.length && !running && !unseen.length) return null;
|
||||
const target =
|
||||
input[0] ?? interrupted[0] ?? unseen[0] ?? list.find((t) => t.status === "running" || t.status === "starting");
|
||||
return (
|
||||
<button type="button" className={styles.statusItem} onClick={() => target && openTask(target.id)}>
|
||||
{input.length > 0 && (
|
||||
@@ -20,6 +23,12 @@ export function AgentsStatus() {
|
||||
{input.length} <T>needs input</T>
|
||||
</span>
|
||||
)}
|
||||
{interrupted.length > 0 && (
|
||||
<span className={styles.statusPart}>
|
||||
<Icon name="pause" size={13} className={styles.interrupted} />
|
||||
{interrupted.length} <T>interrupted</T>
|
||||
</span>
|
||||
)}
|
||||
{running > 0 && (
|
||||
<span className={styles.statusPart}>
|
||||
<Spinner size={10} />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Agents tool window: tasks pinned above the user's groups, then by what they need from the user. */
|
||||
import { useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { AgentStatus as Status, AgentTask } from "@/bindings";
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import { EDITOR_TAB_MIME, maybeEditorService, type EditorInput } from "@/workbench/contributions";
|
||||
import {
|
||||
EmptyState,
|
||||
@@ -24,9 +24,12 @@ import {
|
||||
TASK_DRAG,
|
||||
age,
|
||||
branchLabel,
|
||||
groupStatus,
|
||||
interruptionBannerText,
|
||||
isInterrupted,
|
||||
isWaitingForNetwork,
|
||||
providerIcon,
|
||||
sessionKey,
|
||||
taskGroupStatus,
|
||||
type TaskGroup,
|
||||
} from "./model";
|
||||
import {
|
||||
@@ -132,8 +135,14 @@ const sessionPayloadTask = (payload: string): string | null => {
|
||||
}
|
||||
};
|
||||
|
||||
function TaskStatusIcon({ status }: { status: Status }) {
|
||||
switch (status) {
|
||||
function TaskStatusIcon({ task }: { task: AgentTask }) {
|
||||
if (isWaitingForNetwork(task)) {
|
||||
return <Icon name="clock" size={13} className={styles.interrupted} label="Waiting for network" />;
|
||||
}
|
||||
if (isInterrupted(task)) {
|
||||
return <Icon name="pause" size={13} className={styles.interrupted} label="Interrupted" />;
|
||||
}
|
||||
switch (task.status) {
|
||||
case "needsInput":
|
||||
return <Icon name="warning" size={13} label="Needs input" />;
|
||||
case "running":
|
||||
@@ -274,7 +283,7 @@ export function AgentsView() {
|
||||
}
|
||||
if (targetKey.startsWith("g:")) {
|
||||
if (sectionOfTask(source, organize) === targetKey) return null;
|
||||
if (statusSection(groupStatus(source.status)) !== targetKey) return null;
|
||||
if (statusSection(taskGroupStatus(source)) !== targetKey) return null;
|
||||
return {
|
||||
indicator: { kind: "section", key: targetKey } as DropIndicator,
|
||||
apply: () => moveTasksToStatusGroup([source.id]),
|
||||
@@ -415,7 +424,7 @@ export function AgentsView() {
|
||||
}
|
||||
return [];
|
||||
};
|
||||
const rowButton = (label: string, icon: "pin" | "archive", run: () => void) => (
|
||||
const rowButton = (label: string, icon: "pin" | "archive" | "resume", run: () => void) => (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.rowAction}
|
||||
@@ -574,9 +583,13 @@ export function AgentsView() {
|
||||
return <GroupRow label={n.group.name} count={n.tasks.length} />;
|
||||
case "group":
|
||||
return <GroupRow label={<T>{n.group.label}</T>} count={n.group.tasks.length} />;
|
||||
case "task":
|
||||
case "task": {
|
||||
const interrupted = isInterrupted(n.task);
|
||||
const tooltip = interrupted
|
||||
? tx(interruptionBannerText(n.task.interrupted!.reason, n.task.interrupted!.wasWaitingForInput))
|
||||
: (n.task.error ?? n.task.title);
|
||||
return (
|
||||
<span className={styles.row} title={n.task.error ?? n.task.title}>
|
||||
<span className={styles.row} title={tooltip}>
|
||||
<Icon name={providerIcon(n.task.provider)} size={16} label={providerName(n.task.provider)} />
|
||||
<span className={styles.title} data-unread={unread.has(n.task.id) || undefined}>
|
||||
{matches?.get(n.task.id)?.length ? (
|
||||
@@ -597,22 +610,25 @@ export function AgentsView() {
|
||||
<span className={styles.detail}>{branchLabel(n.task.branch)}</span>
|
||||
)}
|
||||
<span className={styles.rowActions}>
|
||||
{(interrupted || isWaitingForNetwork(n.task)) &&
|
||||
rowButton("Resume", "resume", () => void executeAction("agents.resumeTasks", [n.task.id]))}
|
||||
{pinned.has(n.task.id)
|
||||
? rowButton("Unpin", "pin", () => pinTasks([n.task.id], false))
|
||||
: rowButton("Pin", "pin", () => pinTasks([n.task.id], true))}
|
||||
{canArchive(n.task) &&
|
||||
rowButton("Archive", "archive", () => void executeAction("agents.archiveTasks", [n.task.id]))}
|
||||
</span>
|
||||
{/* Ready tasks say so by their group; the others show what they're doing, in a column
|
||||
{/* Plain Ready tasks say so by their group; interrupted and active tasks show their mark
|
||||
beside the age so the marks line up whatever the title length. */}
|
||||
{n.task.status !== "ready" && (
|
||||
{(n.task.status !== "ready" || interrupted) && (
|
||||
<span className={styles.status}>
|
||||
<TaskStatusIcon status={n.task.status} />
|
||||
<TaskStatusIcon task={n.task} />
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.age}>{age(n.task.updatedMs ?? 0)}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
}}
|
||||
empty={
|
||||
|
||||
@@ -149,12 +149,12 @@
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
|
||||
/* The archived-task notice: an editor notification banner above the conversation. */
|
||||
/* The archived / interrupted / waiting-for-network notice above the conversation. */
|
||||
.banner {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
align-items: center;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
min-height: 36px;
|
||||
padding: 9px 12px;
|
||||
@@ -162,6 +162,10 @@
|
||||
border-bottom: 1px solid var(--border-feedback-warning);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.bannerIcon {
|
||||
flex: none;
|
||||
color: var(--warning);
|
||||
}
|
||||
.bannerText {
|
||||
flex: 1 1 240px;
|
||||
min-width: 0;
|
||||
@@ -170,9 +174,42 @@
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.bannerMeta {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.bannerActions {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.bannerSpacer {
|
||||
flex: 1;
|
||||
}
|
||||
.recoveryDivider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin: var(--space-2) 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.recoveryRule {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
}
|
||||
.recoveryPill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
padding: 2px var(--space-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-elev);
|
||||
}
|
||||
|
||||
/* The conversation with its find bar. */
|
||||
.streamArea {
|
||||
|
||||
@@ -3,25 +3,30 @@
|
||||
* dot only while something waits for you (a finished reply not yet read, a question, an error).
|
||||
*/
|
||||
import { Badge, Spinner, tooltipAttrs } from "@/ui";
|
||||
import { isBusy, statusLabel } from "./model";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { isBusy, isInterrupted, isWaitingForNetwork, taskStatusLabel } from "./model";
|
||||
import { useAgents } from "./store";
|
||||
|
||||
export function TaskStatusMark({ task }: { task: string }) {
|
||||
const status = useAgents((s) => s.tasks.get(task)?.status);
|
||||
const tx = useTx();
|
||||
const current = useAgents((s) => s.tasks.get(task));
|
||||
const unread = useAgents((s) => s.unread.has(task));
|
||||
if (!status) return null;
|
||||
// Waiting for you is a dot, not a spinner: the task stops until you answer.
|
||||
const busy = isBusy(status) && status !== "needsInput";
|
||||
if (!current) return null;
|
||||
const { status } = current;
|
||||
const waitingNetwork = isWaitingForNetwork(current);
|
||||
const interrupted = isInterrupted(current);
|
||||
// Waiting for you (or waiting for network / interrupted) is a dot, not a spinner.
|
||||
const busy = isBusy(status) && status !== "needsInput" && !waitingNetwork;
|
||||
const tone =
|
||||
status === "failed" || status === "limited"
|
||||
? "danger"
|
||||
: status === "needsInput"
|
||||
: status === "needsInput" || waitingNetwork || interrupted
|
||||
? "warning"
|
||||
: status === "ready" && unread
|
||||
? "success"
|
||||
: null;
|
||||
if (!busy && !tone) return null;
|
||||
const label = statusLabel(status);
|
||||
const label = tx(taskStatusLabel(current));
|
||||
return (
|
||||
<span {...tooltipAttrs(label, undefined, true)} style={{ display: "inline-flex", alignItems: "center" }}>
|
||||
{busy ? (
|
||||
|
||||
@@ -26,6 +26,9 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
|
||||
sendWith: "enter",
|
||||
whileRunning: "queue",
|
||||
newTaskApprovals: "bypass",
|
||||
networkRetryWindow: "1h",
|
||||
resumeInterrupted: "ask",
|
||||
confirmTerminateOnClose: true,
|
||||
defaults: {},
|
||||
mcpServers: {},
|
||||
skills: {},
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
registerMenuGroup,
|
||||
registerMenuSlotItem,
|
||||
registerOverlay,
|
||||
registerRunningAgentTasksProvider,
|
||||
registerStatusItem,
|
||||
registerToolWindow,
|
||||
toolWindowService,
|
||||
@@ -35,6 +36,7 @@ import {
|
||||
SESSION_KIND,
|
||||
TASK_DRAG,
|
||||
TOOL_WINDOW,
|
||||
isInterrupted,
|
||||
providerIcon,
|
||||
} from "./model";
|
||||
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
|
||||
@@ -44,6 +46,7 @@ import { focusedSession, inputSession } from "./sessionFocus";
|
||||
import { cycleFocusedEffort } from "./effortFocus";
|
||||
import { clearAgentTabFontZoom } from "./fontZoom";
|
||||
import {
|
||||
activeAgentTasks,
|
||||
closeActiveTask,
|
||||
closeAndNewTask,
|
||||
connect,
|
||||
@@ -53,6 +56,8 @@ import {
|
||||
refreshProviders,
|
||||
refreshTaskModels,
|
||||
releaseClosedTaskCache,
|
||||
setAutoResumeOnce,
|
||||
trackNetworkOnline,
|
||||
trackPromptHistory,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
@@ -89,6 +94,11 @@ export function activate(): () => void {
|
||||
const disposers = [
|
||||
activateTaskWindows(),
|
||||
trackPromptHistory(),
|
||||
trackNetworkOnline(),
|
||||
registerRunningAgentTasksProvider({
|
||||
running: activeAgentTasks,
|
||||
setAutoResumeOnce,
|
||||
}),
|
||||
activateSettingsPages(),
|
||||
trackEditorCopies(),
|
||||
registerActions(copyAgentReferenceActions),
|
||||
@@ -137,7 +147,9 @@ export function activate(): () => void {
|
||||
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
|
||||
useBadge: () => {
|
||||
const n = useAgents(
|
||||
(s) => [...s.tasks.values()].filter((t) => t.status === "needsInput" || s.unread.has(t.id)).length,
|
||||
(s) =>
|
||||
[...s.tasks.values()].filter((t) => t.status === "needsInput" || isInterrupted(t) || s.unread.has(t.id))
|
||||
.length,
|
||||
);
|
||||
return n || null;
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Pure helpers: task grouping, entry updates, labels. */
|
||||
import type { AgentEntry, AgentStatus, AgentSubagentStatus, AgentTask } from "@/bindings";
|
||||
import type { AgentEntry, AgentStatus, AgentSubagentStatus, AgentTask, InterruptionReason } from "@/bindings";
|
||||
import { isIconName } from "@/ui/icons";
|
||||
|
||||
export const SESSION_KIND = "agent-session";
|
||||
@@ -80,8 +80,16 @@ export function providerIcon(provider: string): string {
|
||||
return isIconName(`agent-${id}`) ? `agent-${id}` : "toolwindow-agents";
|
||||
}
|
||||
|
||||
export const isBusy = (s: AgentStatus) => s === "running" || s === "starting" || s === "needsInput";
|
||||
|
||||
export const isInterrupted = (t: Pick<AgentTask, "status" | "interrupted"> | null | undefined) =>
|
||||
t?.status === "ready" && !!t.interrupted;
|
||||
|
||||
export const isWaitingForNetwork = (t: Pick<AgentTask, "status" | "retry"> | null | undefined) =>
|
||||
!!t && isBusy(t.status) && t.retry?.deadlineMs != null;
|
||||
|
||||
export interface TaskGroup {
|
||||
status: "needsInput" | "failed" | "limited" | "running" | "ready" | "archived";
|
||||
status: "needsInput" | "failed" | "limited" | "running" | "interrupted" | "ready" | "archived";
|
||||
label: string;
|
||||
tasks: AgentTask[];
|
||||
}
|
||||
@@ -92,32 +100,33 @@ const GROUPS: Array<[TaskGroup["status"], string, AgentStatus[]]> = [
|
||||
["failed", "Failed", ["failed"]],
|
||||
["limited", "Usage Limit", ["limited"]],
|
||||
["running", "Running", ["running", "starting"]],
|
||||
["interrupted", "Interrupted", []],
|
||||
["ready", "Ready to Review", ["ready"]],
|
||||
["archived", "Archived", ["archived"]],
|
||||
];
|
||||
|
||||
const ATTENTION_RANK = new Map<AgentStatus, number>(
|
||||
GROUPS.flatMap(([, , members], rank) => members.map((status): [AgentStatus, number] => [status, rank])),
|
||||
);
|
||||
|
||||
/** Where a task sits in the panel by status: what waits for the user comes first. */
|
||||
export const attentionRank = (status: AgentStatus) => ATTENTION_RANK.get(status) ?? GROUPS.length;
|
||||
const GROUP_RANK = new Map<TaskGroup["status"], number>(GROUPS.map(([status], rank) => [status, rank]));
|
||||
|
||||
/** The group a status is shown in (`starting` runs). */
|
||||
export const groupStatus = (status: AgentStatus): TaskGroup["status"] =>
|
||||
const groupStatus = (status: AgentStatus): TaskGroup["status"] =>
|
||||
GROUPS.find(([, , members]) => members.includes(status))?.[0] ?? "ready";
|
||||
|
||||
/** The group a task is shown in (`ready` with `interrupted` goes to `interrupted`). */
|
||||
export const taskGroupStatus = (task: Pick<AgentTask, "status" | "interrupted">): TaskGroup["status"] =>
|
||||
isInterrupted(task) ? "interrupted" : groupStatus(task.status);
|
||||
|
||||
export const taskAttentionRank = (task: Pick<AgentTask, "status" | "interrupted">): number =>
|
||||
GROUP_RANK.get(taskGroupStatus(task)) ?? GROUPS.length;
|
||||
|
||||
export function groupTasks(tasks: Iterable<AgentTask>): TaskGroup[] {
|
||||
const sorted = [...tasks].sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
return GROUPS.map(([status, label, members]) => ({
|
||||
return GROUPS.map(([status, label]) => ({
|
||||
status,
|
||||
label,
|
||||
tasks: sorted.filter((t) => members.includes(t.status)),
|
||||
tasks: sorted.filter((t) => taskGroupStatus(t) === status),
|
||||
})).filter((g) => g.tasks.length > 0);
|
||||
}
|
||||
|
||||
export const isBusy = (s: AgentStatus) => s === "running" || s === "starting" || s === "needsInput";
|
||||
|
||||
/** Whether `task` runs outside the project root (its own worktree, or an imported subfolder). */
|
||||
export const hasTaskTerminal = (task: AgentTask, projectRoot?: string | null) =>
|
||||
task.isolation === "worktree" || (!!projectRoot && task.cwd !== projectRoot);
|
||||
@@ -185,6 +194,51 @@ export function statusLabel(s: AgentStatus): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function taskStatusLabel(task: Pick<AgentTask, "status" | "interrupted" | "retry">): string {
|
||||
if (isWaitingForNetwork(task)) return "Waiting for network";
|
||||
if (isInterrupted(task)) return "Interrupted";
|
||||
return statusLabel(task.status);
|
||||
}
|
||||
|
||||
export function interruptionBannerText(reason: InterruptionReason, wasWaitingForInput = false): string {
|
||||
if (wasWaitingForInput) return "Interrupted while waiting for your approval.";
|
||||
switch (reason) {
|
||||
case "windowClose":
|
||||
return "Interrupted when the project window closed.";
|
||||
case "quit":
|
||||
return "Interrupted when OpenIDEA quit.";
|
||||
case "restart":
|
||||
return "Interrupted when OpenIDEA restarted.";
|
||||
case "backendUpgrade":
|
||||
return "Interrupted when the OpenIDEA backend upgraded.";
|
||||
case "backendStop":
|
||||
return "Interrupted when the OpenIDEA backend stopped.";
|
||||
case "unexpectedExit":
|
||||
return "Interrupted when OpenIDEA exited unexpectedly.";
|
||||
case "networkTimeout":
|
||||
return "Paused after the network retry window expired.";
|
||||
}
|
||||
}
|
||||
|
||||
export function recoveryDividerLabel(reason: InterruptionReason): string {
|
||||
switch (reason) {
|
||||
case "windowClose":
|
||||
return "Resumed after window close";
|
||||
case "quit":
|
||||
return "Resumed after OpenIDEA quit";
|
||||
case "restart":
|
||||
return "Resumed after OpenIDEA restart";
|
||||
case "backendUpgrade":
|
||||
return "Resumed after backend upgrade";
|
||||
case "backendStop":
|
||||
return "Resumed after backend stop";
|
||||
case "unexpectedExit":
|
||||
return "Resumed after unexpected exit";
|
||||
case "networkTimeout":
|
||||
return "Resumed after network drop";
|
||||
}
|
||||
}
|
||||
|
||||
/** Index of each turn-starting message in `entries`: its turn's number (messages steered into a running turn don't start one). */
|
||||
export function turnNumbers(entries: AgentEntry[]): Map<number, number> {
|
||||
const out = new Map<number, number>();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { parseRemoteLocation } from "@/platform/remote";
|
||||
import { attentionRank, groupStatus, groupTasks, type TaskGroup } from "./model";
|
||||
import { groupTasks, taskAttentionRank, taskGroupStatus, type TaskGroup } from "./model";
|
||||
|
||||
/** Section key of the pinned group, above every other group. */
|
||||
export const PINNED_SECTION = "pinned";
|
||||
@@ -20,6 +20,7 @@ const STATUS_SECTIONS = new Set<string>([
|
||||
"g:failed",
|
||||
"g:limited",
|
||||
"g:running",
|
||||
"g:interrupted",
|
||||
"g:ready",
|
||||
"g:archived",
|
||||
]);
|
||||
@@ -48,7 +49,7 @@ export function sectionOfTask(task: AgentTask, organize: TaskOrganize): string {
|
||||
if (organize.pinned.includes(task.id)) return PINNED_SECTION;
|
||||
const group = organize.groupOf[task.id];
|
||||
if (group && organize.groups.some((g) => g.id === group)) return customSection(group);
|
||||
return statusSection(groupStatus(task.status));
|
||||
return statusSection(taskGroupStatus(task));
|
||||
}
|
||||
|
||||
function isKnownSection(section: string, knownGroups: ReadonlySet<string>): boolean {
|
||||
@@ -212,7 +213,7 @@ export function groupMembers(tasks: Iterable<AgentTask>, organize: TaskOrganize,
|
||||
const pinned = new Set(organize.pinned);
|
||||
const sorted = [...tasks]
|
||||
.filter((t) => organize.groupOf[t.id] === group && !pinned.has(t.id))
|
||||
.sort((a, b) => attentionRank(a.status) - attentionRank(b.status) || (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
.sort((a, b) => taskAttentionRank(a) - taskAttentionRank(b) || (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
return applyOrder(sorted, organize.order?.[customSection(group)]);
|
||||
}
|
||||
|
||||
@@ -259,7 +260,7 @@ function placeId(
|
||||
export function canReorderTask(source: AgentTask, target: AgentTask, organize: TaskOrganize): boolean {
|
||||
if (source.id === target.id) return false;
|
||||
const targetSection = sectionOfTask(target, organize);
|
||||
if (targetSection.startsWith("g:")) return statusSection(groupStatus(source.status)) === targetSection;
|
||||
if (targetSection.startsWith("g:")) return statusSection(taskGroupStatus(source)) === targetSection;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,418 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { AgentEntry, AgentEvent, AgentRecoveryReport, AgentTask } from "@/bindings";
|
||||
import { disableRemote, enableRemote } from "@/platform/remote";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useContributions, type EditorInput, type OpenEditorTab } from "@/workbench/contributions";
|
||||
import { AgentsStatus } from "./AgentsStatus";
|
||||
import { AgentsView } from "./AgentsView";
|
||||
import { TaskStatusMark } from "./TaskStatusMark";
|
||||
import { activate } from "./index";
|
||||
import { groupTasks, isInterrupted, isWaitingForNetwork, taskGroupStatus } from "./model";
|
||||
import { EMPTY_ORGANIZE, groupMembers, sectionOfTask, statusGroups } from "./organize";
|
||||
import { SessionComposer } from "./session/SessionComposer";
|
||||
import { WorkingRow } from "./session/WorkingRow";
|
||||
import { Entry } from "./session/messages";
|
||||
import { connect, disconnect, markVisible, resetRecoveryState, trackNetworkOnline, useAgents } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
active: null as EditorInput | null,
|
||||
tabs: [] as OpenEditorTab[],
|
||||
channel: null as { onmessage: (event: AgentEvent) => void } | null,
|
||||
tasks: [] as AgentTask[],
|
||||
entries: [] as AgentEntry[],
|
||||
report: {
|
||||
instanceId: "inst-1",
|
||||
firstReconcile: true,
|
||||
autoResumed: [],
|
||||
interrupted: [],
|
||||
} as AgentRecoveryReport,
|
||||
notify: vi.fn(),
|
||||
expire: vi.fn(),
|
||||
openInput: vi.fn(),
|
||||
closeInput: vi.fn(),
|
||||
showToolWindow: vi.fn(),
|
||||
resumeTask: vi.fn(async (_task: string) => ({ status: "ok" as const, data: null })),
|
||||
resumeAll: vi.fn(async () => ({ status: "ok" as const, data: [] as string[] })),
|
||||
dismissInterrupted: vi.fn(async (_task: string) => ({ status: "ok" as const, data: null })),
|
||||
markRead: vi.fn(async (_task: string) => ({ status: "ok" as const, data: null })),
|
||||
setRecoveryWindow: vi.fn(async (_task: string, _minutes: number | null) => ({ status: "ok" as const, data: null })),
|
||||
pokeNetwork: vi.fn(async () => ({ status: "ok" as const, data: null })),
|
||||
cancel: vi.fn(async (_task: string) => ({ status: "ok" as const, data: null })),
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/webview", () => ({
|
||||
getCurrentWebview: () => ({
|
||||
onDragDropEvent: async () => () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const actual = await original<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
agentSubscribe: async (channel: typeof backend.channel) => {
|
||||
backend.channel = channel;
|
||||
return { status: "ok", data: backend.tasks };
|
||||
},
|
||||
agentProviders: async () => ({ status: "ok", data: [] }),
|
||||
agentChanges: async () => ({ status: "ok", data: [] }),
|
||||
agentGroupedChanges: async () => ({ status: "ok", data: { uncommitted: [], commits: [] } }),
|
||||
agentEntries: async () => ({ status: "ok", data: backend.entries }),
|
||||
agentCommands: async () => ({ status: "ok", data: [] }),
|
||||
vcsRemotes: async () => ({ status: "ok", data: [] }),
|
||||
agentReconcileInterrupted: async () => ({ status: "ok", data: backend.report }),
|
||||
agentResumeTask: (task: string) => backend.resumeTask(task),
|
||||
agentResumeAllInterrupted: () => backend.resumeAll(),
|
||||
agentDismissInterrupted: (task: string) => backend.dismissInterrupted(task),
|
||||
agentMarkRead: (task: string) => backend.markRead(task),
|
||||
agentSetRecoveryWindow: (task: string, minutes: number | null) => backend.setRecoveryWindow(task, minutes),
|
||||
agentPokeNetwork: () => backend.pokeNetwork(),
|
||||
agentCancel: (task: string) => backend.cancel(task),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
editorService: () => ({
|
||||
openInput: backend.openInput,
|
||||
closeInput: backend.closeInput,
|
||||
activeInput: () => backend.active,
|
||||
openTabs: () => backend.tabs,
|
||||
}),
|
||||
toolWindowService: () => ({ show: backend.showToolWindow }),
|
||||
notifications: () => ({ notify: backend.notify, expire: backend.expire }),
|
||||
}));
|
||||
|
||||
function makeTask(id: string, overrides: Partial<AgentTask> = {}): AgentTask {
|
||||
return {
|
||||
id,
|
||||
title: `Task ${id}`,
|
||||
status: "ready",
|
||||
provider: "claude",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/project",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 1000,
|
||||
updatedMs: 2000,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
|
||||
disconnect();
|
||||
resetRecoveryState();
|
||||
disableRemote();
|
||||
useProject.setState({ project: { root: "/project", name: "project", trusted: true } } as never);
|
||||
backend.tasks = [];
|
||||
backend.entries = [];
|
||||
backend.report = {
|
||||
instanceId: "inst-1",
|
||||
firstReconcile: true,
|
||||
autoResumed: [],
|
||||
interrupted: [],
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
disconnect();
|
||||
resetRecoveryState();
|
||||
disableRemote();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("interrupted task grouping and organization", () => {
|
||||
it("groups Interrupted above Ready to Review and sorts interrupted tasks ahead inside custom groups", () => {
|
||||
const ready = makeTask("ready-1", { updatedMs: 5000 });
|
||||
const intr = makeTask("intr-1", {
|
||||
updatedMs: 3000,
|
||||
interrupted: { reason: "windowClose", atMs: 3000 },
|
||||
});
|
||||
const running = makeTask("run-1", { status: "running", updatedMs: 1000 });
|
||||
|
||||
expect(isInterrupted(intr)).toBe(true);
|
||||
expect(isInterrupted(ready)).toBe(false);
|
||||
expect(taskGroupStatus(intr)).toBe("interrupted");
|
||||
expect(sectionOfTask(intr, EMPTY_ORGANIZE)).toBe("g:interrupted");
|
||||
|
||||
const groups = groupTasks([ready, intr, running]);
|
||||
expect(groups.map((g) => g.label)).toEqual(["Running", "Interrupted", "Ready to Review"]);
|
||||
expect(statusGroups([ready, intr], EMPTY_ORGANIZE).map((g) => g.status)).toEqual(["interrupted", "ready"]);
|
||||
|
||||
const custom = {
|
||||
groups: [{ id: "g1", name: "Backend" }],
|
||||
groupOf: { "ready-1": "g1", "intr-1": "g1" },
|
||||
pinned: [],
|
||||
};
|
||||
expect(groupMembers([ready, intr], custom, "g1").map((t) => t.id)).toEqual(["intr-1", "ready-1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sidebar, tab dot, and status bar indicators for closed chat tabs", () => {
|
||||
it("renders Interrupted section, pause mark, hover Resume button, tab warning dot, and status bar count", async () => {
|
||||
const intr = makeTask("t-intr", {
|
||||
title: "Migrate OAuth",
|
||||
unread: true,
|
||||
interrupted: { reason: "windowClose", atMs: Date.now() - 60_000 },
|
||||
});
|
||||
backend.tasks = [intr];
|
||||
backend.report = {
|
||||
instanceId: "inst-1",
|
||||
firstReconcile: false,
|
||||
autoResumed: [],
|
||||
interrupted: ["t-intr"],
|
||||
};
|
||||
await connect();
|
||||
expect(useAgents.getState().unread.has("t-intr")).toBe(true);
|
||||
|
||||
const dispose = activate();
|
||||
try {
|
||||
await vi.waitFor(() => expect(useAgents.getState().loaded).toBe(true));
|
||||
const useBadge = useContributions.getState().toolWindows.get("agents")!.useBadge!;
|
||||
function Badge() {
|
||||
return <span data-testid="sidebar-badge">{useBadge()}</span>;
|
||||
}
|
||||
render(
|
||||
<>
|
||||
<AgentsView />
|
||||
<AgentsStatus />
|
||||
<TaskStatusMark task="t-intr" />
|
||||
<Badge />
|
||||
</>,
|
||||
);
|
||||
|
||||
expect(screen.getAllByText("Interrupted").length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText("Migrate OAuth")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("sidebar-badge")).toHaveTextContent("1");
|
||||
expect(screen.getByRole("button", { name: /1 interrupted/i })).toBeInTheDocument();
|
||||
|
||||
// Viewing the task clears unread and syncs agentMarkRead, while badge stays 1 until resumed/dismissed.
|
||||
let hide!: () => void;
|
||||
act(() => {
|
||||
hide = markVisible("t-intr");
|
||||
});
|
||||
expect(backend.markRead).toHaveBeenCalledWith("t-intr");
|
||||
expect(screen.getByTestId("sidebar-badge")).toHaveTextContent("1");
|
||||
hide();
|
||||
|
||||
// Clicking hover Resume triggers agentResumeTask.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Resume" }));
|
||||
await vi.waitFor(() => expect(backend.resumeTask).toHaveBeenCalledWith("t-intr"));
|
||||
} finally {
|
||||
act(dispose);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("reopen balloons, remote daemon restart detection, and browser online wake", () => {
|
||||
it("surfaces interrupted & auto-resumed balloons on first reconcile and suppresses duplicates on client Wi-Fi reconnect", async () => {
|
||||
backend.tasks = [makeTask("t1", { interrupted: { reason: "restart", atMs: 1000 } })];
|
||||
backend.report = {
|
||||
instanceId: "daemon-1",
|
||||
firstReconcile: true,
|
||||
autoResumed: ["t-auto"],
|
||||
interrupted: ["t1"],
|
||||
};
|
||||
await connect();
|
||||
await vi.waitFor(() => expect(backend.notify).toHaveBeenCalledTimes(2));
|
||||
expect(backend.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Resuming 1 interrupted agent task" }),
|
||||
);
|
||||
expect(backend.notify).toHaveBeenCalledWith(expect.objectContaining({ title: "1 agent task was interrupted" }));
|
||||
|
||||
// Reconnecting to the SAME daemon instance (e.g. 30m Wi-Fi drop) shows zero duplicate balloons.
|
||||
backend.notify.mockClear();
|
||||
backend.report = {
|
||||
instanceId: "daemon-1",
|
||||
firstReconcile: false,
|
||||
autoResumed: [],
|
||||
interrupted: ["t1"],
|
||||
};
|
||||
await connect();
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(backend.notify).not.toHaveBeenCalled();
|
||||
|
||||
// Remote session: first attach records daemon-1, client Wi-Fi reconnect sees daemon-1 (silent),
|
||||
// then remote host reboot spawns daemon-2 and surfaces the remote restart balloon!
|
||||
enableRemote({
|
||||
target: { kind: "ssh", config: "prod" },
|
||||
root: "/project",
|
||||
host: "prod",
|
||||
os: "linux",
|
||||
commands: [],
|
||||
});
|
||||
backend.notify.mockClear();
|
||||
backend.report = {
|
||||
instanceId: "daemon-1",
|
||||
firstReconcile: false,
|
||||
autoResumed: [],
|
||||
interrupted: ["t1"],
|
||||
};
|
||||
await connect();
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(backend.notify).not.toHaveBeenCalled();
|
||||
|
||||
backend.report = {
|
||||
instanceId: "daemon-2",
|
||||
firstReconcile: true,
|
||||
autoResumed: [],
|
||||
interrupted: ["t1"],
|
||||
};
|
||||
await connect();
|
||||
await vi.waitFor(() =>
|
||||
expect(backend.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Remote host restarted — 1 agent task was interrupted" }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("pokes backend network probe immediately when browser online fires with a Waiting for network task", async () => {
|
||||
const waiting = makeTask("net-1", {
|
||||
status: "running",
|
||||
retry: {
|
||||
attempt: 2,
|
||||
maxRetries: null,
|
||||
retryAtMs: Date.now() + 30_000,
|
||||
error: "offline",
|
||||
deadlineMs: Date.now() + 3_600_000,
|
||||
},
|
||||
});
|
||||
expect(isWaitingForNetwork(waiting)).toBe(true);
|
||||
backend.tasks = [waiting];
|
||||
backend.report = { instanceId: "inst-1", firstReconcile: false, autoResumed: [], interrupted: [] };
|
||||
await connect();
|
||||
const off = trackNetworkOnline();
|
||||
try {
|
||||
window.dispatchEvent(new Event("online"));
|
||||
await vi.waitFor(() => expect(backend.pokeNetwork).toHaveBeenCalledOnce());
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("inline Interrupted banner, Waiting for network banner, and RecoveryTurnDivider pill", () => {
|
||||
it("renders InterruptedBanner with Resume, Dismiss, and per-session recovery window picker", async () => {
|
||||
const intr = makeTask("b1", {
|
||||
interrupted: { reason: "quit", atMs: Date.now() - 120_000 },
|
||||
recoveryWindowMins: 60,
|
||||
});
|
||||
useAgents.setState({ tasks: new Map([["b1", intr]]) });
|
||||
const focusRoot = { current: null };
|
||||
render(
|
||||
<SessionComposer
|
||||
task={intr}
|
||||
focusRequest={0}
|
||||
focusRoot={focusRoot}
|
||||
entries={[]}
|
||||
head={null}
|
||||
changes={null}
|
||||
commits={[]}
|
||||
onOpenChanges={() => {}}
|
||||
onOpenSubagent={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Interrupted when OpenIDEA quit\./)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Session recovery window" })).toHaveTextContent("1h window");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Resume" }));
|
||||
await vi.waitFor(() => expect(backend.resumeTask).toHaveBeenCalledWith("b1"));
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
|
||||
await vi.waitFor(() => expect(backend.dismissInterrupted).toHaveBeenCalledWith("b1"));
|
||||
});
|
||||
|
||||
it("renders WaitingForNetworkBanner + WorkingRow status and supports Resume Now and Stop", async () => {
|
||||
const now = Date.now();
|
||||
const netTask = makeTask("n1", {
|
||||
status: "running",
|
||||
retry: {
|
||||
attempt: 3,
|
||||
maxRetries: null,
|
||||
retryAtMs: now + 25_000,
|
||||
error: "ENOTFOUND api.anthropic.com",
|
||||
deadlineMs: now + 50 * 60_000,
|
||||
},
|
||||
});
|
||||
useAgents.setState({ tasks: new Map([["n1", netTask]]) });
|
||||
const focusRoot = { current: null };
|
||||
render(
|
||||
<>
|
||||
<WorkingRow task={netTask} entries={[]} subagent={null} />
|
||||
<SessionComposer
|
||||
task={netTask}
|
||||
focusRequest={0}
|
||||
focusRoot={focusRoot}
|
||||
entries={[]}
|
||||
head={null}
|
||||
changes={null}
|
||||
commits={[]}
|
||||
onOpenChanges={() => {}}
|
||||
onOpenSubagent={() => {}}
|
||||
/>
|
||||
</>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("Waiting for network connection…")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Connection lost — probing in/)).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Resume Now" }));
|
||||
await vi.waitFor(() => expect(backend.resumeTask).toHaveBeenCalledWith("n1"));
|
||||
|
||||
fireEvent.click(screen.getAllByRole("button", { name: "Stop" })[0]!);
|
||||
await vi.waitFor(() => expect(backend.cancel).toHaveBeenCalledWith("n1"));
|
||||
});
|
||||
|
||||
it("renders synthetic recovery User entries as a compact separator pill instead of a chat bubble", () => {
|
||||
const t = makeTask("m1");
|
||||
const drafts = { current: new Map() };
|
||||
const recoveryEntry: AgentEntry = {
|
||||
type: "user",
|
||||
text: "The previous turn was interrupted because the project window was closed.",
|
||||
attachments: [],
|
||||
images: [],
|
||||
sentMs: 1_700_000_000_000,
|
||||
doneMs: null,
|
||||
steered: false,
|
||||
recovery: "windowClose",
|
||||
};
|
||||
render(
|
||||
<Entry
|
||||
task={t}
|
||||
entry={recoveryEntry}
|
||||
turn={1}
|
||||
turnCount={2}
|
||||
working={false}
|
||||
drafts={drafts}
|
||||
onOpenSubagent={() => {}}
|
||||
onDiagramDrawn={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("separator")).toHaveTextContent("Resumed after window close");
|
||||
expect(screen.queryByText(/The previous turn was interrupted because/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { isErrorKind } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Icon, IconButton, T, type IconName } from "@/ui";
|
||||
import { Button, Icon, IconButton, Select, T, type IconName, type SelectOption } from "@/ui";
|
||||
import { notifications, useEditorShown } from "@/workbench/contributions";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
|
||||
@@ -16,19 +16,23 @@ import styles from "../Session.module.css";
|
||||
import { SessionAssets } from "../SessionAssets";
|
||||
import { SubmitButton } from "../SubmitButton";
|
||||
import { useAgentSettings } from "../agentSettings";
|
||||
import { canSend, emptyDraft } from "../composerModel";
|
||||
import { canSend, emptyDraft, retryParts } from "../composerModel";
|
||||
import { formatDuration } from "../conversation";
|
||||
import { useEffortFocus } from "../effortFocus";
|
||||
import { isBusy } from "../model";
|
||||
import { age, interruptionBannerText, isBusy, isInterrupted, isWaitingForNetwork } from "../model";
|
||||
import { asksInCard, type PermissionEntry } from "../permission";
|
||||
import {
|
||||
dismissInterruptedTask,
|
||||
stopTask,
|
||||
editQueued,
|
||||
refreshTaskModels,
|
||||
removeQueued,
|
||||
resumeTask,
|
||||
sendMessage,
|
||||
sendQueuedNow,
|
||||
setTaskConfig,
|
||||
setTaskMcpOverrides,
|
||||
setTaskRecoveryWindow,
|
||||
setTaskSkillOverrides,
|
||||
stopBackgroundTask,
|
||||
useAgentCommands,
|
||||
@@ -37,8 +41,126 @@ import {
|
||||
import { PermissionLine } from "./QuestionForm";
|
||||
import { SessionStatus } from "./SessionStatus";
|
||||
import { Elapsed } from "./WorkingRow";
|
||||
import { useNow } from "./shared";
|
||||
import { WorkingSubagents } from "./toolEntries";
|
||||
|
||||
const SESSION_WINDOW_OPTIONS: readonly SelectOption<string>[] = [
|
||||
{ value: "default", label: "Default window" },
|
||||
{ value: "0", label: "Off (ask)" },
|
||||
{ value: "15", label: "15m window" },
|
||||
{ value: "60", label: "1h window" },
|
||||
{ value: "240", label: "4h window" },
|
||||
{ value: "1440", label: "24h window" },
|
||||
];
|
||||
|
||||
function RecoveryWindowPicker({ task }: { task: AgentTask }) {
|
||||
const tx = useTx();
|
||||
const value = task.recoveryWindowMins == null ? "default" : String(task.recoveryWindowMins);
|
||||
return (
|
||||
<Select
|
||||
variant="chip"
|
||||
aria-label={tx("Session recovery window")}
|
||||
title="Auto-retry window on network drop"
|
||||
value={value}
|
||||
options={SESSION_WINDOW_OPTIONS}
|
||||
onChange={(next) => {
|
||||
const mins = next === "default" ? null : Number(next);
|
||||
void setTaskRecoveryWindow(task.id, mins).catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Couldn't change the setting"),
|
||||
body: String(e),
|
||||
}),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function InterruptedBanner({ task }: { task: AgentTask }) {
|
||||
const tx = useTx();
|
||||
const [resuming, setResuming] = useState(false);
|
||||
const intr = task.interrupted!;
|
||||
return (
|
||||
<div className={styles.banner} role="status">
|
||||
<Icon name="pause" size={14} className={styles.bannerIcon} />
|
||||
<span className={styles.bannerText}>
|
||||
{tx(interruptionBannerText(intr.reason, intr.wasWaitingForInput))}{" "}
|
||||
<span className={styles.bannerMeta}>{age(intr.atMs ?? 0)}</span>
|
||||
</span>
|
||||
<div className={styles.bannerActions}>
|
||||
<RecoveryWindowPicker task={task} />
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
icon="resume"
|
||||
disabled={resuming}
|
||||
onClick={() => {
|
||||
setResuming(true);
|
||||
void resumeTask(task.id)
|
||||
.catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Couldn't resume agent tasks"),
|
||||
body: String(e),
|
||||
}),
|
||||
)
|
||||
.finally(() => setResuming(false));
|
||||
}}
|
||||
>
|
||||
<T>Resume</T>
|
||||
</Button>
|
||||
<IconButton
|
||||
icon="close"
|
||||
size="small"
|
||||
title="Dismiss"
|
||||
onClick={() => void dismissInterruptedTask(task.id).catch(() => {})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WaitingForNetworkBanner({ task }: { task: AgentTask }) {
|
||||
const tx = useTx();
|
||||
const now = useNow(1000);
|
||||
const retry = task.retry!;
|
||||
const { wait } = retryParts(retry, now);
|
||||
const remaining = formatDuration(Math.max(0, (retry.deadlineMs ?? now) - now));
|
||||
return (
|
||||
<div className={styles.banner} role="status">
|
||||
<Icon name="clock" size={14} className={styles.bannerIcon} />
|
||||
<span className={styles.bannerText} title={retry.error ?? undefined}>
|
||||
{wait > 0
|
||||
? tx`Connection lost — probing in ${wait}s (auto-retry window: ${remaining})`
|
||||
: tx`Connection lost — checking connectivity (auto-retry window: ${remaining})`}
|
||||
</span>
|
||||
<div className={styles.bannerActions}>
|
||||
<RecoveryWindowPicker task={task} />
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
icon="resume"
|
||||
onClick={() =>
|
||||
void resumeTask(task.id).catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Couldn't resume agent tasks"),
|
||||
body: String(e),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<T>Resume Now</T>
|
||||
</Button>
|
||||
<Button size="small" icon="stop" onClick={() => void stopTask(task.id).catch(() => {})}>
|
||||
<T>Stop</T>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What needs the user or tells where the agent is, above the composer: an approval it
|
||||
* waits for (answered with 1, 2, 3… when the focus isn't in a text field), the plan,
|
||||
@@ -204,9 +326,9 @@ export function SessionComposer({
|
||||
const agentCommands = useAgentCommands(task.provider, task.id, task.commands);
|
||||
const busy = isBusy(task.status);
|
||||
const shellRunning = useAgents((s) => s.shellRunning.has(task.id));
|
||||
// ↑ recalls this conversation's messages, newest first.
|
||||
// ↑ recalls this conversation's messages, newest first (excluding synthetic recovery turns).
|
||||
const history = useMemo(
|
||||
() => (entries ?? []).flatMap((e) => (e.type === "user" && e.text ? [e.text] : [])).reverse(),
|
||||
() => (entries ?? []).flatMap((e) => (e.type === "user" && !e.recovery && e.text ? [e.text] : [])).reverse(),
|
||||
[entries],
|
||||
);
|
||||
// Only a running turn of an agent that takes messages mid-turn can be steered: otherwise
|
||||
@@ -272,6 +394,8 @@ export function SessionComposer({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{isInterrupted(task) && <InterruptedBanner task={task} />}
|
||||
{isWaitingForNetwork(task) && <WaitingForNetworkBanner task={task} />}
|
||||
<Tray task={task} entries={entries}>
|
||||
<WorkingSubagents entries={entries} onOpen={onOpenSubagent} />
|
||||
<BackgroundTasks task={task} />
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Spinner, T } from "@/ui";
|
||||
import styles from "../Session.module.css";
|
||||
import { retryParts } from "../composerModel";
|
||||
import { formatDuration } from "../conversation";
|
||||
import { subagentWorking, type SubagentEntry } from "../model";
|
||||
import { isWaitingForNetwork, subagentWorking, type SubagentEntry } from "../model";
|
||||
import { asksInCard } from "../permission";
|
||||
import { ACTIVITY_STATUS, activityOf } from "../workingStatus";
|
||||
import { useNow, type UserEntry } from "./shared";
|
||||
@@ -58,7 +58,11 @@ export function WorkingRow({
|
||||
return (
|
||||
<div className={styles.working} role="status">
|
||||
<Spinner size={12} />
|
||||
{task.retry ? (
|
||||
{isWaitingForNetwork(task) ? (
|
||||
<span className={styles.retrying}>
|
||||
<T>Waiting for network connection…</T>
|
||||
</span>
|
||||
) : task.retry ? (
|
||||
<Retrying retry={task.retry} />
|
||||
) : task.status === "starting" ? (
|
||||
<T>Starting the agent…</T>
|
||||
|
||||
@@ -17,7 +17,7 @@ import { useAgentSettings } from "../agentSettings";
|
||||
import { messageTokens, parseMention } from "../composerModel";
|
||||
import { formatDuration, formatSentAt, userMessageText } from "../conversation";
|
||||
import { isSignInErrorMessage, useAgentErrorText } from "../loginHint";
|
||||
import { isBusy, type ReplyTimes, type ReplyTurn } from "../model";
|
||||
import { isBusy, recoveryDividerLabel, type ReplyTimes, type ReplyTurn } from "../model";
|
||||
import { useRevealedText } from "../reveal";
|
||||
import { forkTask, refreshProviders, rerunFrom, resendMessage, useAgents } from "../store";
|
||||
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
|
||||
@@ -285,7 +285,21 @@ function UserMessage({
|
||||
turn: number | null;
|
||||
turnCount: number;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const [editing, setEditing] = useState(false);
|
||||
if (entry.recovery) {
|
||||
return (
|
||||
<div className={styles.recoveryDivider} role="separator">
|
||||
<span className={styles.recoveryRule} aria-hidden="true" />
|
||||
<span className={styles.recoveryPill}>
|
||||
<Icon name="resume" size={12} />
|
||||
<span>{tx(recoveryDividerLabel(entry.recovery))}</span>
|
||||
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
|
||||
</span>
|
||||
<span className={styles.recoveryRule} aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const failed = (title: string) => (e: unknown) => notifications().notify({ level: "error", title, body: String(e) });
|
||||
const fail = failed("Couldn't send the message");
|
||||
const archived = task.status === "archived";
|
||||
|
||||
@@ -29,7 +29,7 @@ import { clearAgentTaskFontZoom, resetAllAgentFontZoom } from "./fontZoom";
|
||||
import { clearDismissedAssets } from "./sessionAssetsModel";
|
||||
import { useSkillsCatalog, useSkillsCatalogSync } from "./skillsModel";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { projectLocation } from "@/platform/remote";
|
||||
import { isRemoteWindow, projectLocation } from "@/platform/remote";
|
||||
import { defaultTaskProject } from "./project";
|
||||
import { call, commands, isTauri, nextRequestId } from "@/platform/ipc";
|
||||
import { editorService, notifications, notifyTabTitlesChanged, toolWindowService } from "@/workbench/contributions";
|
||||
@@ -76,6 +76,8 @@ import {
|
||||
appendEntry,
|
||||
entriesKey,
|
||||
isBusy,
|
||||
isInterrupted,
|
||||
isWaitingForNetwork,
|
||||
sessionKey,
|
||||
upsertEntry,
|
||||
} from "./model";
|
||||
@@ -375,12 +377,15 @@ const visible = new Map<string, number>();
|
||||
const windowFocused = () => document.visibilityState !== "hidden" && document.hasFocus();
|
||||
const viewing = (task: string) => (visible.has(task) && windowFocused()) || taskWindowFocused(task);
|
||||
|
||||
function setUnread(task: string, value: boolean) {
|
||||
function setUnread(task: string, value: boolean, syncBackend = true) {
|
||||
const s = useAgents.getState();
|
||||
if (s.unread.has(task) === value) return;
|
||||
const unread = new Set(s.unread);
|
||||
if (value) unread.add(task);
|
||||
else unread.delete(task);
|
||||
else {
|
||||
unread.delete(task);
|
||||
if (syncBackend && isTauri()) void commands.agentMarkRead?.(task)?.catch(() => {});
|
||||
}
|
||||
useAgents.setState({ unread });
|
||||
}
|
||||
|
||||
@@ -576,10 +581,21 @@ export async function connect(): Promise<void> {
|
||||
}
|
||||
if (gen !== generation) return;
|
||||
const organizeRoot = projectLocation(useProject.getState().project?.root);
|
||||
const initialUnread = new Set<string>();
|
||||
for (const t of tasks) {
|
||||
if (t.unread && t.status !== "archived") {
|
||||
if (viewing(t.id)) {
|
||||
if (isTauri()) void commands.agentMarkRead?.(t.id)?.catch(() => {});
|
||||
} else {
|
||||
initialUnread.add(t.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
tasks: new Map(tasks.map((t) => [t.id, t])),
|
||||
unread: initialUnread,
|
||||
entries: new Map(),
|
||||
entryLoads: new Map(),
|
||||
changes: new Map(),
|
||||
@@ -590,6 +606,13 @@ export async function connect(): Promise<void> {
|
||||
organize: pruneOrganize(loadOrganize(organizeRoot), tasks),
|
||||
});
|
||||
notifyTabTitlesChanged();
|
||||
if (
|
||||
!auxiliaryWindow() &&
|
||||
useProject.getState().project?.trusted !== false &&
|
||||
typeof (commands as Partial<typeof commands>).agentReconcileInterrupted === "function"
|
||||
) {
|
||||
void reconcileInterruptedOnConnect(gen, organizeRoot);
|
||||
}
|
||||
// Restored tabs of tasks deleted meanwhile close, like editors of deleted files.
|
||||
const editors = editorService();
|
||||
for (const t of editors.openTabs?.() ?? []) {
|
||||
@@ -784,9 +807,18 @@ function onEvent(e: AgentEvent) {
|
||||
case "task": {
|
||||
const prev = s.tasks.get(e.task.id);
|
||||
useAgents.setState({ tasks: new Map(s.tasks).set(e.task.id, e.task) });
|
||||
if (prev && (prev.title !== e.task.title || prev.status !== e.task.status)) notifyTabTitlesChanged();
|
||||
if (
|
||||
prev &&
|
||||
(prev.title !== e.task.title ||
|
||||
prev.status !== e.task.status ||
|
||||
isInterrupted(prev) !== isInterrupted(e.task) ||
|
||||
isWaitingForNetwork(prev) !== isWaitingForNetwork(e.task))
|
||||
)
|
||||
notifyTabTitlesChanged();
|
||||
if (e.task.unread && !prev?.unread) markUnread(e.task.id);
|
||||
else if (prev?.unread && !e.task.unread && isBusy(e.task.status)) setUnread(e.task.id, false, false);
|
||||
if (e.task.status === "archived") {
|
||||
setUnread(e.task.id, false);
|
||||
setUnread(e.task.id, false, false);
|
||||
if (prev?.status !== "archived" && !isTaskOpenInUi(e.task.id)) dropTaskCache(e.task.id);
|
||||
}
|
||||
if (prev?.status !== e.task.status && !isBusy(e.task.status) && e.task.status !== "archived") {
|
||||
@@ -1567,6 +1599,130 @@ export async function stopTask(task: string): Promise<void> {
|
||||
if (isBusy(useAgents.getState().tasks.get(task)?.status ?? "ready")) await cancelTask(task);
|
||||
}
|
||||
|
||||
/** Resumes an interrupted task (or wakes a task waiting for network connectivity). */
|
||||
export async function resumeTask(task: string): Promise<void> {
|
||||
setUnread(task, false, false);
|
||||
await call(commands.agentResumeTask(task));
|
||||
}
|
||||
|
||||
/** Resumes every interrupted task in the open project. */
|
||||
export async function resumeAllInterrupted(): Promise<string[]> {
|
||||
return call(commands.agentResumeAllInterrupted());
|
||||
}
|
||||
|
||||
/** Dismisses the interrupted notice on `task`, keeping its conversation in Ready. */
|
||||
export async function dismissInterruptedTask(task: string): Promise<void> {
|
||||
setUnread(task, false, false);
|
||||
await call(commands.agentDismissInterrupted(task));
|
||||
}
|
||||
|
||||
/** Sets the per-session recovery / network retry window (`null` = default, `0` = off, `>0` = minutes). */
|
||||
export async function setTaskRecoveryWindow(task: string, minutes: number | null): Promise<void> {
|
||||
await call(commands.agentSetRecoveryWindow(task, minutes));
|
||||
}
|
||||
|
||||
/** Arms or clears the one-shot auto-resume flag on `tasks` before window close. */
|
||||
export async function setAutoResumeOnce(tasks: string[], enabled: boolean): Promise<void> {
|
||||
const fn = (commands as Partial<typeof commands>).agentSetAutoResumeOnce;
|
||||
if (!tasks.length || typeof fn !== "function") return;
|
||||
await call(fn(tasks, enabled));
|
||||
}
|
||||
|
||||
/** Active tasks in this project whose turn is currently in flight. */
|
||||
export function activeAgentTasks(): Array<{ id: string; title: string }> {
|
||||
return [...useAgents.getState().tasks.values()]
|
||||
.filter((t) => t.status !== "archived" && isBusy(t.status))
|
||||
.map((t) => ({ id: t.id, title: t.title }));
|
||||
}
|
||||
|
||||
const lastBackendInstanceByRoot = new Map<string, string>();
|
||||
|
||||
/** Test helper to clear cached backend instance ids between test cases. */
|
||||
export function resetRecoveryState() {
|
||||
lastBackendInstanceByRoot.clear();
|
||||
}
|
||||
|
||||
async function reconcileInterruptedOnConnect(gen: number, organizeRoot: string | null) {
|
||||
const report = await call(commands.agentReconcileInterrupted()).catch(() => null);
|
||||
if (!report || gen !== generation) return;
|
||||
const prevInstance = organizeRoot ? lastBackendInstanceByRoot.get(organizeRoot) : undefined;
|
||||
const backendRestarted = prevInstance !== undefined && prevInstance !== report.instanceId;
|
||||
if (organizeRoot) lastBackendInstanceByRoot.set(organizeRoot, report.instanceId);
|
||||
if (!report.firstReconcile && !backendRestarted) return;
|
||||
|
||||
if (report.autoResumed.length > 0) {
|
||||
const count = report.autoResumed.length;
|
||||
notifications().notify({
|
||||
key: "agent:recovery:resumed",
|
||||
group: "tools",
|
||||
level: "info",
|
||||
title: count === 1 ? tx("Resuming 1 interrupted agent task") : tx`Resuming ${count} interrupted agent tasks`,
|
||||
actions: [
|
||||
{ label: tx("View"), run: () => openTask(report.autoResumed[0]!) },
|
||||
{
|
||||
label: count === 1 ? tx("Stop") : tx("Stop All"),
|
||||
run: () => {
|
||||
for (const id of report.autoResumed) void stopTask(id).catch(() => {});
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (report.interrupted.length > 0) {
|
||||
const count = report.interrupted.length;
|
||||
const remoteRestart = backendRestarted && isRemoteWindow();
|
||||
const title = remoteRestart
|
||||
? count === 1
|
||||
? tx("Remote host restarted — 1 agent task was interrupted")
|
||||
: tx`Remote host restarted — ${count} agent tasks were interrupted`
|
||||
: count === 1
|
||||
? tx("1 agent task was interrupted")
|
||||
: tx`${count} agent tasks were interrupted`;
|
||||
notifications().notify({
|
||||
key: "agent:recovery:interrupted",
|
||||
group: "tools",
|
||||
level: "info",
|
||||
sticky: true,
|
||||
title,
|
||||
actions: [
|
||||
{
|
||||
label: count === 1 ? tx("Resume") : tx("Resume All"),
|
||||
run: () => {
|
||||
notifications().expire?.("agent:recovery:interrupted");
|
||||
void resumeAllInterrupted().catch((e: unknown) =>
|
||||
showError(tx("Couldn't resume agent tasks"), e instanceof Error ? e.message : String(e)),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: tx("Review"),
|
||||
run: () => {
|
||||
notifications().expire?.("agent:recovery:interrupted");
|
||||
openTask(report.interrupted[0]!);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Wakes backend network probes immediately when the browser regains connectivity. */
|
||||
export function trackNetworkOnline(): () => void {
|
||||
const onOnline = () => {
|
||||
const fn = (commands as Partial<typeof commands>).agentPokeNetwork;
|
||||
if (!isTauri() || typeof fn !== "function") return;
|
||||
for (const t of useAgents.getState().tasks.values()) {
|
||||
if (isWaitingForNetwork(t)) {
|
||||
void fn().catch(() => {});
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener("online", onOnline);
|
||||
return () => window.removeEventListener("online", onOnline);
|
||||
}
|
||||
|
||||
/** Sends the session composer's message: queued while the agent works, or with `now` interrupting it. */
|
||||
export async function sendMessage(task: string, now: boolean): Promise<void> {
|
||||
const composer = composerDraft(task);
|
||||
|
||||
@@ -4,15 +4,18 @@ import { tx } from "@/platform/i18n";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { confirm, showError, confirmChecked } from "@/workbench/messages";
|
||||
import { promptInput } from "@/workbench/inputDialogs";
|
||||
import { isBusy } from "./model";
|
||||
import { isBusy, isInterrupted, isWaitingForNetwork } from "./model";
|
||||
import { groupNameError, type OrganizeGroup } from "./organize";
|
||||
import {
|
||||
archiveTask,
|
||||
deleteTaskGroup,
|
||||
dismissInterruptedTask,
|
||||
moveTasksToGroup,
|
||||
newTaskGroup,
|
||||
pinTasks,
|
||||
renameTaskGroup,
|
||||
resumeAllInterrupted,
|
||||
resumeTask,
|
||||
taskGroups,
|
||||
unarchiveTask,
|
||||
deleteTask,
|
||||
@@ -329,6 +332,43 @@ export const taskActions: Action[] = [
|
||||
return forkTask(task.id, null).catch((e: unknown) => showError(tx("Couldn't fork the task"), String(e)));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "agents.resumeTasks",
|
||||
title: "Resume Interrupted Agent Tasks",
|
||||
category: "Agents",
|
||||
hidden: true,
|
||||
run: ({ arg }) =>
|
||||
runTasks(
|
||||
resolveTasks(arg).filter((task) => isInterrupted(task) || isWaitingForNetwork(task)),
|
||||
(task) => resumeTask(task.id),
|
||||
tx("Couldn't resume agent tasks"),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "agents.resumeAllInterrupted",
|
||||
title: "Resume All Interrupted Tasks",
|
||||
category: "Agents",
|
||||
icon: "resume",
|
||||
when: "projectOpen",
|
||||
keywords: ["resume", "continue", "interrupted", "recover"],
|
||||
run: async () => {
|
||||
await resumeAllInterrupted().catch((e: unknown) =>
|
||||
showError(tx("Couldn't resume agent tasks"), e instanceof Error ? e.message : String(e)),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "agents.dismissInterrupted",
|
||||
title: "Dismiss Interrupted State",
|
||||
category: "Agents",
|
||||
hidden: true,
|
||||
run: ({ arg }) =>
|
||||
runTasks(
|
||||
resolveTasks(arg).filter(isInterrupted),
|
||||
(task) => dismissInterruptedTask(task.id),
|
||||
tx("Couldn't update agent tasks"),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "agents.archiveTasks",
|
||||
title: "Archive Agent Tasks",
|
||||
@@ -440,9 +480,29 @@ export function taskMenu(tasks: AgentTask[], below: AgentTask[] = []): MenuItem[
|
||||
const task = tasks[0]!;
|
||||
const multiple = tasks.length > 1;
|
||||
const archived = tasks.filter((task) => task.status === "archived").length;
|
||||
const interrupted = tasks.filter(isInterrupted);
|
||||
const archivable = tasks.filter(canArchive).length;
|
||||
const archivableBelow = multiple ? [] : below.filter(canArchive);
|
||||
return [
|
||||
...(interrupted.length
|
||||
? ([
|
||||
{
|
||||
kind: "action",
|
||||
action: "agents.resumeTasks",
|
||||
label: multiple ? tx`Resume (${interrupted.length})` : "Resume",
|
||||
icon: "resume",
|
||||
arg: interrupted.map((t) => t.id),
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
action: "agents.dismissInterrupted",
|
||||
label: "Dismiss Interrupted State",
|
||||
icon: "close",
|
||||
arg: interrupted.map((t) => t.id),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
] satisfies MenuItem[])
|
||||
: []),
|
||||
...pinMenu(tasks),
|
||||
...(!multiple
|
||||
? ([
|
||||
|
||||
@@ -333,4 +333,70 @@ describe("quitting from outside the window", () => {
|
||||
expect(native.order).toEqual([]);
|
||||
expect(ipc.commands.appCancelQuit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("prompts for active local agent tasks, supports Close & Auto-Resume, and rolls back if save is cancelled", async () => {
|
||||
const armAutoResume = vi.fn(async () => {});
|
||||
const disableConfirmAgents = vi.fn(async () => {});
|
||||
deps.runningAgentTasks = async () => [{ id: "t1", title: "Refactor auth" }];
|
||||
deps.armAutoResumeAgents = armAutoResume;
|
||||
deps.disableConfirmTerminateAgents = disableConfirmAgents;
|
||||
|
||||
// 1. Choosing Close & Auto-Resume + Don't ask again, then cancelling Unsaved Changes rolls back armAutoResume!
|
||||
const responses = [
|
||||
{ button: "resumeOnReopen", checked: true },
|
||||
{ button: "cancel", checked: false },
|
||||
];
|
||||
deps.ask = vi.fn(async () => responses.shift() ?? { button: "cancel", checked: false });
|
||||
deps.prepareClose = async () => ({ dirty: 1, discard: vi.fn(), commit: vi.fn(), cancel: vi.fn() });
|
||||
const prevented1 = await close({ closeWithoutWelcome: true });
|
||||
expect(prevented1).toHaveBeenCalledOnce();
|
||||
expect(disableConfirmAgents).toHaveBeenCalledOnce();
|
||||
expect(armAutoResume).toHaveBeenNthCalledWith(1, ["t1"], true);
|
||||
expect(armAutoResume).toHaveBeenNthCalledWith(2, ["t1"], false);
|
||||
|
||||
// 2. Clean close with Close & Auto-Resume keeps armAutoResume armed.
|
||||
uninstall?.();
|
||||
armAutoResume.mockClear();
|
||||
deps.prepareClose = undefined;
|
||||
deps.ask = vi.fn(async () => ({ button: "resumeOnReopen", checked: false }));
|
||||
const prevented2 = await close({ closeWithoutWelcome: true });
|
||||
expect(prevented2).not.toHaveBeenCalled();
|
||||
expect(armAutoResume).toHaveBeenCalledTimes(1);
|
||||
expect(armAutoResume).toHaveBeenCalledWith(["t1"], true);
|
||||
});
|
||||
|
||||
it("skips the agent pause prompt when keeping a remote backend running, and prompts when stopping it", async () => {
|
||||
enableRemote({
|
||||
target: { kind: "ssh", config: "devbox" },
|
||||
root: "/srv/app",
|
||||
host: "devbox",
|
||||
os: "linux",
|
||||
commands: [],
|
||||
});
|
||||
const runningAgentTasks = vi.fn(async () => [{ id: "r1", title: "Remote build" }]);
|
||||
deps.runningAgentTasks = runningAgentTasks;
|
||||
|
||||
// Keep Backend Running: remote agents continue on the daemon, so no agent pause dialog is shown.
|
||||
deps.ask = vi.fn(async () => ({ button: "keep", checked: false }));
|
||||
await close({ closeWithoutWelcome: true });
|
||||
expect(runningAgentTasks).not.toHaveBeenCalled();
|
||||
|
||||
// Stop Backend: stopping the remote daemon interrupts remote agents, so the agent pause dialog is shown.
|
||||
uninstall?.();
|
||||
const prompts: PromptRequest[] = [];
|
||||
const answers = [
|
||||
{ button: "stop", checked: false },
|
||||
{ button: "pause", checked: false },
|
||||
];
|
||||
deps.ask = vi.fn(async (req) => {
|
||||
prompts.push(req);
|
||||
return answers.shift() ?? { button: "cancel", checked: false };
|
||||
});
|
||||
await close({ closeWithoutWelcome: true });
|
||||
expect(runningAgentTasks).toHaveBeenCalledOnce();
|
||||
expect(prompts.map((p) => p.title)).toEqual([
|
||||
"Close Remote Development Window",
|
||||
"Agent Task 'Remote build' Is Running",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -21,9 +21,12 @@ import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import {
|
||||
maybeEditorService,
|
||||
notifications,
|
||||
runningAgentTasks as liveAgentTasks,
|
||||
runningProcesses as liveProcesses,
|
||||
setAgentAutoResumeOnce,
|
||||
stopRunningProcesses,
|
||||
type EditorCloseSession,
|
||||
type RunningAgentTask,
|
||||
} from "@/workbench/contributions";
|
||||
import { beginTermination, endTermination } from "./termination";
|
||||
import { RemoteCloseMessage } from "./RemoteCloseMessage";
|
||||
@@ -43,6 +46,10 @@ export function confirmExitEnabled(settings: Settings | null | undefined): boole
|
||||
return settings?.general?.confirmExit === true;
|
||||
}
|
||||
|
||||
export function confirmTerminateAgentsEnabled(settings: Settings | null | undefined): boolean {
|
||||
return settings?.agents?.confirmTerminateOnClose !== false;
|
||||
}
|
||||
|
||||
/** Last window closes instead of showing Welcome. Only an explicit choice does. */
|
||||
export function closeWithoutWelcomeEnabled(settings: Settings | null | undefined): boolean {
|
||||
return settings?.general?.closeWithoutWelcome === true;
|
||||
@@ -70,6 +77,9 @@ export interface CloseInput {
|
||||
confirmTerminate: boolean;
|
||||
/** Running Run/Debug process names this close would terminate. */
|
||||
processes: readonly string[];
|
||||
confirmTerminateAgents?: boolean;
|
||||
/** Active AI agent tasks this close would pause. */
|
||||
agentTasks?: readonly RunningAgentTask[];
|
||||
dirty: number;
|
||||
project: string | null;
|
||||
}
|
||||
@@ -79,8 +89,13 @@ export interface CloseDeps {
|
||||
saveAll: () => Promise<void>;
|
||||
disableConfirmExit: () => Promise<void>;
|
||||
disableConfirmTerminate: () => Promise<void>;
|
||||
disableConfirmTerminateAgents?: () => Promise<void>;
|
||||
/** Running Run/Debug process names in this window. */
|
||||
runningProcesses: () => Promise<readonly string[]>;
|
||||
/** Active AI agent tasks in this window. */
|
||||
runningAgentTasks?: () => Promise<readonly RunningAgentTask[]>;
|
||||
/** Arms or clears one-shot auto-resume on `ids` for the next reopen. */
|
||||
armAutoResumeAgents?: (ids: string[], enabled: boolean) => Promise<void>;
|
||||
/** Stops them, gracefully first and SIGKILL when asked, as IDEA's close does. */
|
||||
terminate?: (kill: boolean) => Promise<void>;
|
||||
/** Resolves once no process of this window is left. */
|
||||
@@ -125,6 +140,33 @@ export async function decideClose(input: CloseInput, deps: CloseDeps): Promise<b
|
||||
// Terminated after the save question below, so cancelling that keeps the processes alive.
|
||||
terminateNames = names;
|
||||
}
|
||||
const activeAgents = input.agentTasks ?? [];
|
||||
let armedAgentIds: string[] = [];
|
||||
if (input.confirmTerminateAgents && activeAgents.length > 0) {
|
||||
const names = activeAgents.map((t) => t.title);
|
||||
const r = await deps.ask({
|
||||
title:
|
||||
activeAgents.length === 1
|
||||
? t("app.terminateAgents.titleOne", { name: names[0]! })
|
||||
: t("app.terminateAgents.titleMany", { count: activeAgents.length }),
|
||||
body:
|
||||
activeAgents.length === 1
|
||||
? t("app.terminateAgents.bodyOne", { name: names[0]! })
|
||||
: t("app.terminateAgents.bodyMany", { count: activeAgents.length, names: names.join(", ") }),
|
||||
buttons: [
|
||||
{ id: "resumeOnReopen", label: t("app.terminateAgents.resumeOnReopen") },
|
||||
{ id: "pause", label: t("app.terminateAgents.pause"), primary: true },
|
||||
],
|
||||
checkbox: t("app.terminateAgents.dontAsk"),
|
||||
icon: "warning",
|
||||
});
|
||||
if (r.button !== "pause" && r.button !== "resumeOnReopen") return false;
|
||||
if (r.checked) await deps.disableConfirmTerminateAgents?.().catch(() => {});
|
||||
if (r.button === "resumeOnReopen") {
|
||||
armedAgentIds = activeAgents.map((t) => t.id);
|
||||
await deps.armAutoResumeAgents?.(armedAgentIds, true).catch(() => {});
|
||||
}
|
||||
}
|
||||
let session: EditorCloseSession | undefined;
|
||||
let authorized = false;
|
||||
try {
|
||||
@@ -156,7 +198,10 @@ export async function decideClose(input: CloseInput, deps: CloseDeps): Promise<b
|
||||
deps.onSaveFailed(e);
|
||||
return false;
|
||||
} finally {
|
||||
if (!authorized) session?.cancel();
|
||||
if (!authorized) {
|
||||
session?.cancel();
|
||||
if (armedAgentIds.length > 0) void deps.armAutoResumeAgents?.(armedAgentIds, false).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,7 +219,13 @@ const defaultDeps: CloseDeps = {
|
||||
const r = await commands.settingsSet("global", "run.confirmTerminate", "false");
|
||||
if (r.status === "ok") useProject.setState({ settings: r.data });
|
||||
},
|
||||
disableConfirmTerminateAgents: async () => {
|
||||
const r = await commands.settingsSet("global", "agents.confirmTerminateOnClose", "false");
|
||||
if (r.status === "ok") useProject.setState({ settings: r.data });
|
||||
},
|
||||
runningProcesses: async () => (await liveProcesses()).map((p) => p.name),
|
||||
runningAgentTasks: () => liveAgentTasks(),
|
||||
armAutoResumeAgents: (ids, enabled) => setAgentAutoResumeOnce(ids, enabled),
|
||||
terminate: (kill) => stopRunningProcesses(kill),
|
||||
waitForProcesses: async () => {
|
||||
// oxlint-disable-next-line no-await-in-loop -- polling must finish one interval before checking processes again
|
||||
@@ -208,6 +259,10 @@ async function processNames(deps: CloseDeps): Promise<string[]> {
|
||||
return [...new Set(await deps.runningProcesses().catch(() => []))].filter(Boolean);
|
||||
}
|
||||
|
||||
async function agentTasksForClose(deps: CloseDeps): Promise<readonly RunningAgentTask[]> {
|
||||
return (await deps.runningAgentTasks?.().catch(() => [])) ?? [];
|
||||
}
|
||||
|
||||
let closing = false;
|
||||
|
||||
/**
|
||||
@@ -303,6 +358,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
stop = r.button === "stop";
|
||||
}
|
||||
const confirmTerminate = !remote.session && workflowSettings().run.confirmTerminate;
|
||||
const confirmTerminateAgents = (!remote.session || stop) && confirmTerminateAgentsEnabled(s.settings);
|
||||
const ok = await decideClose(
|
||||
{
|
||||
quitting,
|
||||
@@ -310,6 +366,8 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
confirmExit: !welcome && confirmExitEnabled(s.settings),
|
||||
confirmTerminate,
|
||||
processes: confirmTerminate ? await processNames(deps) : [],
|
||||
confirmTerminateAgents,
|
||||
agentTasks: confirmTerminateAgents ? await agentTasksForClose(deps) : [],
|
||||
dirty: dirtyCount(),
|
||||
project: s.project?.displayName || s.project?.name || null,
|
||||
},
|
||||
@@ -389,6 +447,7 @@ export async function confirmLeave(
|
||||
): Promise<boolean> {
|
||||
if (!(await closeDocumentWindows())) return false;
|
||||
const confirmTerminate = !isRemoteWindow() && workflowSettings().run.confirmTerminate;
|
||||
const confirmTerminateAgents = !isRemoteWindow() && confirmTerminateAgentsEnabled(useProject.getState().settings);
|
||||
// Untitled buffers follow the window into another project: they are neither counted nor
|
||||
// saved then (the window keeps them open). Closing to Welcome drops them, so they count.
|
||||
const untitled = new Set(keepUntitled ? (maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []) : []);
|
||||
@@ -405,6 +464,8 @@ export async function confirmLeave(
|
||||
confirmExit: false,
|
||||
confirmTerminate,
|
||||
processes: confirmTerminate ? await processNames(deps) : [],
|
||||
confirmTerminateAgents,
|
||||
agentTasks: confirmTerminateAgents ? await agentTasksForClose(deps) : [],
|
||||
dirty: dirtyCount() - untitled.size,
|
||||
project,
|
||||
},
|
||||
|
||||
@@ -27,7 +27,7 @@ vi.mock("@/workbench/messages", () => ({ confirm }));
|
||||
|
||||
import { getContext } from "@/platform/context";
|
||||
import { enableRemote, useRemote } from "@/platform/remote";
|
||||
import { installReconnect, reconnectNow, RETRY_DELAYS_MS } from "./reconnect";
|
||||
import { installReconnect, PASSIVE_RECONNECT_MS, reconnectNow, RETRY_DELAYS_MS } from "./reconnect";
|
||||
|
||||
const session: RemoteSession = {
|
||||
target: { kind: "ssh", config: "box" },
|
||||
@@ -151,3 +151,38 @@ it("ignores a lost connection of a window that is no longer remote", async () =>
|
||||
expect(useRemote.getState().lost).toBeNull();
|
||||
expect(reconnectRemote).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("auto-reconnects after a long Wi-Fi outage on browser online or passive poll unless dirty or taken over", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
uninstall();
|
||||
reconnectRemote.mockRejectedValue(new Error("Network down"));
|
||||
uninstall = installReconnect(async (ms) => {
|
||||
waits.push(ms);
|
||||
});
|
||||
lose();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(reconnectRemote).toHaveBeenCalledTimes(RETRY_DELAYS_MS.length);
|
||||
expect(notify).toHaveBeenCalledOnce();
|
||||
|
||||
// Unsaved edits block automatic passive reconnect on `online`.
|
||||
dirty.ids = [1];
|
||||
window.dispatchEvent(new Event("online"));
|
||||
expect(reconnectRemote).toHaveBeenCalledTimes(RETRY_DELAYS_MS.length);
|
||||
|
||||
// Clean state: passive 60s timer tries once, then `online` succeeds when Wi-Fi returns!
|
||||
dirty.ids = [];
|
||||
await vi.advanceTimersByTimeAsync(PASSIVE_RECONNECT_MS);
|
||||
expect(reconnectRemote).toHaveBeenCalledTimes(RETRY_DELAYS_MS.length + 1);
|
||||
|
||||
reconnectRemote.mockImplementationOnce(async () => {
|
||||
useRemote.setState({ lost: null, reconnecting: false });
|
||||
});
|
||||
window.dispatchEvent(new Event("online"));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(reconnectRemote).toHaveBeenCalledTimes(RETRY_DELAYS_MS.length + 2);
|
||||
expect(useRemote.getState().lost).toBeNull();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
@@ -11,6 +11,8 @@ import { confirm } from "@/workbench/messages";
|
||||
|
||||
/** Waits before each automatic attempt, as VS Code Remote and Gateway retry with back-off. */
|
||||
export const RETRY_DELAYS_MS = [2_000, 5_000, 15_000];
|
||||
/** Slow background reattach interval after initial fast retries fail (covers sleep / long Wi-Fi outages). */
|
||||
export const PASSIVE_RECONNECT_MS = 60_000;
|
||||
const KEY = "remote.connection";
|
||||
|
||||
let generation = 0;
|
||||
@@ -86,22 +88,62 @@ async function retry(host: string, run: number, wait: (ms: number) => Promise<vo
|
||||
export function installReconnect(
|
||||
wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
||||
): () => void {
|
||||
let passiveTimer: ReturnType<typeof setInterval> | undefined;
|
||||
const clearPassive = () => {
|
||||
if (passiveTimer !== undefined) {
|
||||
clearInterval(passiveTimer);
|
||||
passiveTimer = undefined;
|
||||
}
|
||||
};
|
||||
const tryPassiveReconnect = () => {
|
||||
const { lost, reconnecting, takenOver } = useRemote.getState();
|
||||
if (!lost || reconnecting || takenOver || unsaved() > 0) return;
|
||||
void reconnectRemote().then(
|
||||
() => notifications().expire?.(KEY),
|
||||
() => {},
|
||||
);
|
||||
};
|
||||
const offEvent = onIdeEvent("remoteConnectionLost", (e) => {
|
||||
const state = useRemote.getState();
|
||||
if (state.session?.host !== e.host || state.takenOver) return;
|
||||
const takenOver = e.takenOver === true;
|
||||
++generation;
|
||||
const run = ++generation;
|
||||
useRemote.setState({ lost: e.host, takenOver });
|
||||
if (!takenOver) void retry(e.host, generation, wait);
|
||||
if (!takenOver) {
|
||||
void retry(e.host, run, wait).then(() => {
|
||||
if (run === generation && useRemote.getState().lost === e.host && !useRemote.getState().takenOver) {
|
||||
clearPassive();
|
||||
passiveTimer = setInterval(tryPassiveReconnect, PASSIVE_RECONNECT_MS);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
const sync = (s: ReturnType<typeof useRemote.getState>, prev?: ReturnType<typeof useRemote.getState>) => {
|
||||
if (s.lost !== prev?.lost) setContext("remoteConnectionLost", s.lost !== null);
|
||||
if (s.lost && s.takenOver && (!prev?.takenOver || s.lost !== prev.lost)) notifyLost(s.lost, undefined, true);
|
||||
if (s.lost !== prev?.lost) {
|
||||
setContext("remoteConnectionLost", s.lost !== null);
|
||||
if (!s.lost) {
|
||||
clearPassive();
|
||||
notifications().expire?.(KEY);
|
||||
}
|
||||
}
|
||||
if (s.lost && s.takenOver && (!prev?.takenOver || s.lost !== prev.lost)) {
|
||||
clearPassive();
|
||||
notifyLost(s.lost, undefined, true);
|
||||
}
|
||||
};
|
||||
sync(useRemote.getState());
|
||||
const offState = useRemote.subscribe(sync);
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("online", tryPassiveReconnect);
|
||||
window.addEventListener("focus", tryPassiveReconnect);
|
||||
}
|
||||
return () => {
|
||||
generation++;
|
||||
clearPassive();
|
||||
if (typeof window !== "undefined") {
|
||||
window.removeEventListener("online", tryPassiveReconnect);
|
||||
window.removeEventListener("focus", tryPassiveReconnect);
|
||||
}
|
||||
offEvent();
|
||||
offState();
|
||||
};
|
||||
|
||||
@@ -16,6 +16,9 @@ describe("agent chat settings", () => {
|
||||
sendWith: "enter",
|
||||
whileRunning: "queue",
|
||||
newTaskApprovals: "bypass",
|
||||
networkRetryWindow: "1h",
|
||||
resumeInterrupted: "ask",
|
||||
confirmTerminateOnClose: true,
|
||||
chatUseUiFont: true,
|
||||
chatFontFamily: "Inter",
|
||||
chatFontFallback: "",
|
||||
@@ -53,6 +56,9 @@ describe("agent chat settings", () => {
|
||||
toolCalls: "nope",
|
||||
sendWith: "modEnter",
|
||||
newTaskApprovals: "ask",
|
||||
networkRetryWindow: "4h",
|
||||
resumeInterrupted: "window",
|
||||
confirmTerminateOnClose: false,
|
||||
defaults: { claude: { model: "opus", effort: 3 }, codex: "x" },
|
||||
},
|
||||
}).agents;
|
||||
@@ -61,8 +67,13 @@ describe("agent chat settings", () => {
|
||||
toolCalls: "grouped",
|
||||
sendWith: "modEnter",
|
||||
newTaskApprovals: "ask",
|
||||
networkRetryWindow: "4h",
|
||||
resumeInterrupted: "window",
|
||||
confirmTerminateOnClose: false,
|
||||
defaults: { claude: { model: "opus" }, codex: {} },
|
||||
});
|
||||
expect(validateSettings({ agents: { newTaskApprovals: "never" } }).agents.newTaskApprovals).toBe("bypass");
|
||||
expect(validateSettings({ agents: { networkRetryWindow: "99h" } }).agents.networkRetryWindow).toBe("1h");
|
||||
expect(validateSettings({ agents: { resumeInterrupted: "always" } }).agents.resumeInterrupted).toBe("ask");
|
||||
});
|
||||
});
|
||||
@@ -301,6 +301,9 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
sendWith: "enter",
|
||||
whileRunning: "queue",
|
||||
newTaskApprovals: "bypass",
|
||||
networkRetryWindow: "1h",
|
||||
resumeInterrupted: "ask",
|
||||
confirmTerminateOnClose: true,
|
||||
defaults: {},
|
||||
mcpServers: {},
|
||||
skills: {},
|
||||
@@ -534,6 +537,17 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
sendWith: oneOf(agents.sendWith, ["enter", "modEnter"] as const, d.agents.sendWith),
|
||||
whileRunning: oneOf(agents.whileRunning, ["queue", "steer"] as const, d.agents.whileRunning),
|
||||
newTaskApprovals: oneOf(agents.newTaskApprovals, ["bypass", "ask"] as const, d.agents.newTaskApprovals),
|
||||
networkRetryWindow: oneOf(
|
||||
agents.networkRetryWindow,
|
||||
["off", "15m", "1h", "4h", "24h"] as const,
|
||||
d.agents.networkRetryWindow,
|
||||
),
|
||||
resumeInterrupted: oneOf(
|
||||
agents.resumeInterrupted,
|
||||
["ask", "restart", "window", "off"] as const,
|
||||
d.agents.resumeInterrupted,
|
||||
),
|
||||
confirmTerminateOnClose: bool(agents.confirmTerminateOnClose, d.agents.confirmTerminateOnClose),
|
||||
defaults: agentDefaults(agents.defaults),
|
||||
mcpServers: agentMcpServers(agents.mcpServers),
|
||||
skills: agentSkillPolicies(agents.skills),
|
||||
|
||||
@@ -48,6 +48,19 @@ const NEW_TASK_APPROVAL_OPTIONS = [
|
||||
{ value: "bypass", label: "Without asking for approval" },
|
||||
{ value: "ask", label: "Asking for approval" },
|
||||
];
|
||||
const NETWORK_RETRY_WINDOW_OPTIONS = [
|
||||
{ value: "off", label: "Off (ask to resume)" },
|
||||
{ value: "15m", label: "15 minutes" },
|
||||
{ value: "1h", label: "1 hour" },
|
||||
{ value: "4h", label: "4 hours" },
|
||||
{ value: "24h", label: "24 hours" },
|
||||
];
|
||||
const RESUME_INTERRUPTED_OPTIONS = [
|
||||
{ value: "ask", label: "Ask to resume" },
|
||||
{ value: "restart", label: "Auto-resume after IDE update or restart" },
|
||||
{ value: "window", label: "Auto-resume within recovery window" },
|
||||
{ value: "off", label: "Never auto-resume" },
|
||||
];
|
||||
const TOOL_CALL_OPTIONS = [
|
||||
{ value: "grouped", label: "Grouped by what they did" },
|
||||
{ value: "each", label: "One per line" },
|
||||
@@ -916,6 +929,11 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
"approval",
|
||||
"permission",
|
||||
"bypass",
|
||||
"resume",
|
||||
"interrupted",
|
||||
"recovery",
|
||||
"network",
|
||||
"offline",
|
||||
"width",
|
||||
"font",
|
||||
],
|
||||
@@ -932,6 +950,30 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Session Recovery",
|
||||
options: [
|
||||
{
|
||||
kind: "select",
|
||||
key: "agents.networkRetryWindow",
|
||||
label: "Auto-retry window on network drop",
|
||||
options: NETWORK_RETRY_WINDOW_OPTIONS,
|
||||
hint: "While offline, active turns pause and automatically resume once connectivity returns within this window.",
|
||||
},
|
||||
{
|
||||
kind: "select",
|
||||
key: "agents.resumeInterrupted",
|
||||
label: "When reopening a project with interrupted tasks",
|
||||
options: RESUME_INTERRUPTED_OPTIONS,
|
||||
hint: "Tasks waiting for tool permission or sharing a local checkout always ask before resuming.",
|
||||
},
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "agents.confirmTerminateOnClose",
|
||||
label: "Confirm before closing window with running agent tasks",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Sending",
|
||||
options: [
|
||||
|
||||
@@ -124,6 +124,7 @@ export const CLIENT_SETTINGS_KEYS = [
|
||||
"agents.expandToolOutput",
|
||||
"agents.sendWith",
|
||||
"agents.whileRunning",
|
||||
"agents.confirmTerminateOnClose",
|
||||
] as const;
|
||||
|
||||
export function isClientSetting(key: string): boolean {
|
||||
|
||||
@@ -54,6 +54,13 @@
|
||||
"app.lightEdit.pickFolderTooltip": "Pick a folder to open as a project",
|
||||
"app.log.failed": "Cannot show the log",
|
||||
"app.project.opening": "Opening {name}…",
|
||||
"app.terminateAgents.bodyMany": "{count} agent tasks are still running ({names}). Closing pauses their turns so you can resume them later.",
|
||||
"app.terminateAgents.bodyOne": "Agent task '{name}' is still running. Closing pauses its turn so you can resume it later.",
|
||||
"app.terminateAgents.dontAsk": "Don't ask again",
|
||||
"app.terminateAgents.pause": "Pause & Close",
|
||||
"app.terminateAgents.resumeOnReopen": "Close & Auto-Resume",
|
||||
"app.terminateAgents.titleMany": "Agent Tasks Are Running",
|
||||
"app.terminateAgents.titleOne": "Agent Task '{name}' Is Running",
|
||||
"app.terminateProcesses.bodyMany": "Do you want to terminate these {count} processes: {names}?",
|
||||
"app.terminateProcesses.bodyOne": "Do you want to terminate the process '{name}'?",
|
||||
"app.terminateProcesses.dontAsk": "Don't ask again",
|
||||
|
||||
@@ -11190,5 +11190,62 @@
|
||||
"Re-run Failed Jobs": "重新运行失败的作业",
|
||||
"Re-run All Jobs": "重新运行所有作业",
|
||||
"Re-run Job": "重新运行作业",
|
||||
"Open Workflow Run in Browser": "在浏览器中打开工作流运行"
|
||||
"Open Workflow Run in Browser": "在浏览器中打开工作流运行",
|
||||
"interrupted": "已中断",
|
||||
"Waiting for network": "等待网络恢复",
|
||||
"Interrupted": "已中断",
|
||||
"Default window": "默认窗口",
|
||||
"Off (ask)": "关闭(询问)",
|
||||
"15m window": "15 分钟窗口",
|
||||
"1h window": "1 小时窗口",
|
||||
"4h window": "4 小时窗口",
|
||||
"24h window": "24 小时窗口",
|
||||
"Session recovery window": "会话恢复时间窗口",
|
||||
"Auto-retry window on network drop": "网络中断自动重试时间窗口",
|
||||
"Couldn't resume agent tasks": "无法恢复智能体任务",
|
||||
"Connection lost — probing in {wait}s (auto-retry window: {remaining})": "连接已断开 — {wait} 秒后探测网络(自动重试剩余窗口:{remaining})",
|
||||
"Connection lost — checking connectivity (auto-retry window: {remaining})": "连接已断开 — 正在检查网络连接(自动重试剩余窗口:{remaining})",
|
||||
"Resume Now": "立即恢复",
|
||||
"Waiting for network connection…": "正在等待网络连接恢复…",
|
||||
"Resuming 1 interrupted agent task": "正在恢复 1 个已中断的智能体任务",
|
||||
"Resuming {count} interrupted agent tasks": "正在恢复 {count} 个已中断的智能体任务",
|
||||
"Remote host restarted — 1 agent task was interrupted": "远程主机已重启 — 1 个智能体任务被中断",
|
||||
"Remote host restarted — {count} agent tasks were interrupted": "远程主机已重启 — {count} 个智能体任务被中断",
|
||||
"1 agent task was interrupted": "1 个智能体任务已中断",
|
||||
"{count} agent tasks were interrupted": "{count} 个智能体任务已中断",
|
||||
"Resume All": "全部恢复",
|
||||
"Resume Interrupted Agent Tasks": "恢复已中断的智能体任务",
|
||||
"Resume All Interrupted Tasks": "恢复所有已中断的任务",
|
||||
"Dismiss Interrupted State": "忽略中断状态",
|
||||
"Couldn't update agent tasks": "无法更新智能体任务",
|
||||
"Resume ({length})": "恢复 ({length})",
|
||||
"Off (ask to resume)": "关闭(手动确认恢复)",
|
||||
"15 minutes": "15 分钟",
|
||||
"1 hour": "1 小时",
|
||||
"4 hours": "4 小时",
|
||||
"24 hours": "24 小时",
|
||||
"Ask to resume": "询问后再恢复",
|
||||
"Auto-resume after IDE update or restart": "IDE 更新或重启后自动恢复",
|
||||
"Auto-resume within recovery window": "在恢复时间窗口内自动恢复",
|
||||
"Never auto-resume": "从不自动恢复",
|
||||
"Session Recovery": "会话恢复",
|
||||
"While offline, active turns pause and automatically resume once connectivity returns within this window.": "离线期间正在执行的轮次会暂停,并在该时间窗口内网络恢复后自动继续。",
|
||||
"When reopening a project with interrupted tasks": "重新打开包含已中断任务的项目时",
|
||||
"Tasks waiting for tool permission or sharing a local checkout always ask before resuming.": "正在等待工具权限或共享同一本地工作区的任务始终会在恢复前询问。",
|
||||
"Confirm before closing window with running agent tasks": "关闭仍有运行中智能体任务的窗口前进行确认",
|
||||
"Interrupted while waiting for your approval.": "等待你的授权确认时被中断。",
|
||||
"Interrupted when the project window closed.": "项目窗口关闭时被中断。",
|
||||
"Interrupted when OpenIDEA quit.": "OpenIDEA 退出时被中断。",
|
||||
"Interrupted when OpenIDEA restarted.": "OpenIDEA 重启时被中断。",
|
||||
"Interrupted when the OpenIDEA backend upgraded.": "OpenIDEA 后端升级时被中断。",
|
||||
"Interrupted when the OpenIDEA backend stopped.": "OpenIDEA 后端停止时被中断。",
|
||||
"Interrupted when OpenIDEA exited unexpectedly.": "OpenIDEA 异常退出时被中断。",
|
||||
"Paused after the network retry window expired.": "网络自动重试时间窗口到期后已暂停。",
|
||||
"Resumed after window close": "窗口关闭后已恢复",
|
||||
"Resumed after OpenIDEA quit": "OpenIDEA 退出后已恢复",
|
||||
"Resumed after OpenIDEA restart": "OpenIDEA 重启后已恢复",
|
||||
"Resumed after backend upgrade": "后端升级后已恢复",
|
||||
"Resumed after backend stop": "后端停止后已恢复",
|
||||
"Resumed after unexpected exit": "异常退出后已恢复",
|
||||
"Resumed after network drop": "网络恢复后已继续"
|
||||
}
|
||||
@@ -54,6 +54,13 @@
|
||||
"app.lightEdit.pickFolderTooltip": "选择一个文件夹作为工程打开",
|
||||
"app.log.failed": "无法显示日志",
|
||||
"app.project.opening": "正在打开 {name}…",
|
||||
"app.terminateAgents.bodyMany": "仍有 {count} 个智能体任务正在运行({names})。关闭窗口会暂停当前轮次,稍后可继续恢复。",
|
||||
"app.terminateAgents.bodyOne": "智能体任务“{name}”仍在运行。关闭窗口会暂停当前轮次,稍后可继续恢复。",
|
||||
"app.terminateAgents.dontAsk": "不再询问",
|
||||
"app.terminateAgents.pause": "暂停并关闭",
|
||||
"app.terminateAgents.resumeOnReopen": "关闭并在下次自动恢复",
|
||||
"app.terminateAgents.titleMany": "有智能体任务正在运行",
|
||||
"app.terminateAgents.titleOne": "智能体任务“{name}”正在运行",
|
||||
"app.terminateProcesses.bodyMany": "是否要终止这 {count} 个进程:{names}?",
|
||||
"app.terminateProcesses.bodyOne": "是否要终止进程“{name}”?",
|
||||
"app.terminateProcesses.dontAsk": "不再询问",
|
||||
|
||||
@@ -156,6 +156,8 @@ describe("remote client settings", () => {
|
||||
"tools.node",
|
||||
"languages.python.interpreter",
|
||||
"agents.newTaskApprovals",
|
||||
"agents.networkRetryWindow",
|
||||
"agents.resumeInterrupted",
|
||||
"agents.defaults",
|
||||
"agents.mcpServers",
|
||||
"keymapExtra",
|
||||
|
||||
@@ -2333,6 +2333,33 @@ export async function runningProcesses(): Promise<RunningProcess[]> {
|
||||
});
|
||||
}
|
||||
|
||||
export interface RunningAgentTask {
|
||||
id: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface RunningAgentTasksProvider {
|
||||
running(): RunningAgentTask[] | Promise<RunningAgentTask[]>;
|
||||
setAutoResumeOnce(ids: string[], enabled: boolean): Promise<void>;
|
||||
}
|
||||
|
||||
let runningAgentTasksProvider: RunningAgentTasksProvider | null = null;
|
||||
|
||||
export function registerRunningAgentTasksProvider(p: RunningAgentTasksProvider): () => void {
|
||||
runningAgentTasksProvider = p;
|
||||
return () => {
|
||||
if (runningAgentTasksProvider === p) runningAgentTasksProvider = null;
|
||||
};
|
||||
}
|
||||
|
||||
export async function runningAgentTasks(): Promise<RunningAgentTask[]> {
|
||||
return (await runningAgentTasksProvider?.running()) ?? [];
|
||||
}
|
||||
|
||||
export async function setAgentAutoResumeOnce(ids: string[], enabled: boolean): Promise<void> {
|
||||
await runningAgentTasksProvider?.setAutoResumeOnce(ids, enabled);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// "Get from Version Control" sources besides a plain URL (IDEA: GitHub, GitLab…),
|
||||
// listed in the Clone Repository dialog's sidebar.
|
||||
|
||||
Reference in new issue
Заблокувати користувача