From 439b7940a88b6adebb030e5816bc53a6d0b5a6fd Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Sat, 28 Nov 2026 23:15:42 -0800 Subject: [PATCH] feat(agents): recover and resume interrupted agent tasks (#6808) Agent turns cut off by a window close, quit, restart, backend stop or crash are recorded as interrupted (without changing the task status) and can be resumed from the task view, a notification or automatically on reopen. Closing a window with running tasks asks whether to pause them or arm a one-time auto-resume. Transient network failures hold the turn in Waiting for network and continue once connectivity returns within a configurable window. Auto-resume is refused when the turn was waiting for tool approval, the approval policy changed, several local tasks share a checkout, or a crash loop is detected. Recovery settings are user-only so project settings cannot force auto-resume. Closes #6758 Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-agent/src/config.rs | 15 + crates/ide-agent/src/lib.rs | 864 +++++++++++++++++- crates/ide-agent/src/model.rs | 84 ++ crates/ide-agent/src/tests.rs | 485 +++++++++- crates/ide-agent/src/timeline.rs | 2 + crates/ide-core/src/settings.rs | 59 ++ crates/ide-host/src/daemon.rs | 11 +- crates/ide-host/src/lib.rs | 32 +- crates/ide-host/src/ops/agent.rs | 84 +- crates/ide-host/src/project.rs | 7 + crates/ide-host/tests/remote_daemon.rs | 153 ++++ crates/ide-workspace/src/settings.rs | 33 + src-tauri/src/lib.rs | 17 +- src-tauri/src/state.rs | 6 +- src-tauri/tests/commands.snap | 8 + src/bindings.ts | 149 ++- src/features/agents/Agents.module.css | 3 + src/features/agents/AgentsStatus.tsx | 13 +- src/features/agents/AgentsView.tsx | 38 +- src/features/agents/Session.module.css | 41 +- src/features/agents/TaskStatusMark.tsx | 19 +- src/features/agents/agentSettings.ts | 3 + src/features/agents/index.ts | 14 +- src/features/agents/model.ts | 80 +- src/features/agents/organize.ts | 9 +- src/features/agents/recovery.test.tsx | 418 +++++++++ .../agents/session/SessionComposer.tsx | 134 ++- src/features/agents/session/WorkingRow.tsx | 8 +- src/features/agents/session/messages.tsx | 16 +- src/features/agents/store.ts | 166 +++- src/features/agents/taskActions.ts | 62 +- .../app/__tests__/windowClose.test.ts | 66 ++ src/features/app/closeGuard.ts | 63 +- src/features/remote-dev/reconnect.test.ts | 37 +- src/features/remote-dev/reconnect.ts | 50 +- .../settings/__tests__/agents.test.ts | 11 + src/features/settings/model/schema.ts | 14 + src/features/settings/pages/tools.tsx | 42 + src/platform/clientSettings.ts | 1 + src/platform/locales/en.json | 7 + src/platform/locales/text/zh.json | 59 +- src/platform/locales/zh.json | 7 + src/platform/remoteSettings.test.ts | 2 + src/workbench/contributions.ts | 27 + 44 files changed, 3315 insertions(+), 104 deletions(-) create mode 100644 src/features/agents/recovery.test.tsx diff --git a/crates/ide-agent/src/config.rs b/crates/ide-agent/src/config.rs index e995683ab0..ddada1ee76 100644 --- a/crates/ide-agent/src/config.rs +++ b/crates/ide-agent/src/config.rs @@ -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 { + let mut parts: Vec = 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 bool> { match category { diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index aa5ad870ae..a1444f9527 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -113,6 +113,20 @@ pub type WorkspaceRootsHook = Arc Vec + Send + Sync>; /// Returns the project's git executable (`None`: the default), which the tasks' git runs. pub type GitExecutableHook = Arc Option + Send + Sync>; +/// Returns the user's transient network retry window and cold-reopen recovery policy. +pub type RecoverySettingsHook = Arc< + dyn Fn() -> (ide_core::settings::NetworkRetryWindow, ide_core::settings::ResumeInterruptedPolicy) + Send + Sync, +>; + +type NetworkProbeFn = dyn Fn(&str) -> bool + Send + Sync; + +const NETWORK_PROBE_INITIAL_MS: u64 = 5_000; +const NETWORK_PROBE_MAX_MS: u64 = 60_000; +const MAX_NETWORK_RESUMES_PER_TURN: u32 = 2; +const MAX_AUTO_RESUMES_PER_WINDOW: usize = 3; +const AUTO_RESUME_SLIDING_WINDOW_MS: f64 = 5.0 * 60_000.0; +const MAX_CONCURRENT_AUTO_RESUMES: usize = 3; + /// Entry changes are batched for this long before they are sent. const FLUSH_DELAY: Duration = Duration::from_millis(40); /// A save asked for with `persist_soon` waits this long for others to join it. @@ -238,6 +252,12 @@ struct Shared { sinks: RwLock>, security: RwLock>, new_task_approvals: RwLock>, + recovery_settings: RwLock>, + network_probe_hook: RwLock>>, + network_probe_initial_ms: AtomicU64, + network_probe_max_ms: AtomicU64, + instance_id: String, + reconciled: AtomicBool, workspace_roots: RwLock>, git_executable: RwLock>, change_reads: Arc, @@ -309,6 +329,26 @@ impl Shared { self.shutdown_epoch.load(Ordering::Acquire) != epoch } + fn recovery_settings( + &self, + ) -> (ide_core::settings::NetworkRetryWindow, ide_core::settings::ResumeInterruptedPolicy) { + self.recovery_settings.read().as_ref().map(|hook| hook()).unwrap_or(( + ide_core::settings::NetworkRetryWindow::Hour1, + ide_core::settings::ResumeInterruptedPolicy::Ask, + )) + } + + async fn probe_network(&self, provider: &str) -> bool { + let hook = self.network_probe_hook.read().clone(); + let provider = provider.to_owned(); + tokio::task::spawn_blocking(move || match hook { + Some(hook) => hook(&provider), + None => default_network_probe(&provider), + }) + .await + .unwrap_or(false) + } + fn copilot_binary_key(&self, spec: &provider::ProviderSpec) -> CopilotBinaryKey { let resolved = spec.clone().resolve_for_launch(&self.paths.project_root); let executable = dunce::canonicalize(&resolved.command).unwrap_or_else(|_| PathBuf::from(&resolved.command)); @@ -766,6 +806,9 @@ struct TaskState { pending_native_fork: Option, /// A turn is running or about to (prompts arriving now are queued). busy: bool, + /// Prompt handed to a spawned `run()` before `show_prompt` has appended it to `entries`, + /// so a shutdown landing in between still preserves it. + pending_prompt: Option, /// Background tasks the agent reported as running (`run_in_background` commands and /// the like), as it sent them: unlike a turn they outlive it, so an idle release /// waits for the last one. A (re)started process runs nothing yet. @@ -778,6 +821,12 @@ struct TaskState { impl TaskState { fn change_status(&mut self, status: AgentStatus, error: Option) { self.task.retry = None; + if matches!(status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::Archived) { + self.task.interrupted = None; + self.task.unread = false; + } else if matches!(status, AgentStatus::Failed | AgentStatus::Limited | AgentStatus::NeedsInput) { + self.task.interrupted = None; + } self.task.status = status; self.task.error = error; self.task.updated_ms = now_ms(); @@ -868,6 +917,18 @@ struct Task { /// The user stopped the current turn. A stop that reaches the agent before it took the /// prompt can be ignored, so it is sent again once the turn shows signs of life. cancel_pending: AtomicBool, + /// Set when the user explicitly clicked Stop (rather than steering/shutting down), so an + /// active turn or network retry wait settles to plain `Ready` instead of `Failed`/`Interrupted`. + explicit_stop: AtomicBool, + /// One-shot flag armed from the Close/Quit guard dialog so `finish_shutdown` records + /// `auto_resume_once: true` on the interrupted task. + auto_resume_on_close: AtomicBool, + /// Wakes `wait_for_network` immediately for an explicit user "Resume Now". + force_resume_now: AtomicBool, + /// Notified on browser `online`, explicit Stop, Resume Now, or recovery window edits. + network_poke: tokio::sync::Notify, + /// Sliding-window timestamps of automatic resumes to guard against crash/retry loops. + auto_resume_times: Mutex>, /// The agent reported something for the current turn. turn_started: AtomicBool, /// Turns sent so far: an idle release scheduled before the latest one is void. @@ -908,6 +969,17 @@ impl AgentManager { self.shared.idle_release_ms.store(delay.as_millis() as u64, Ordering::Relaxed); } + #[cfg(test)] + fn set_network_probe(&self, probe: impl Fn(&str) -> bool + Send + Sync + 'static) { + *self.shared.network_probe_hook.write() = Some(Arc::new(probe)); + } + + #[cfg(test)] + fn set_network_probe_delays(&self, initial_ms: u64, max_ms: u64) { + self.shared.network_probe_initial_ms.store(initial_ms, Ordering::Relaxed); + self.shared.network_probe_max_ms.store(max_ms, Ordering::Relaxed); + } + /// Loads the project's saved tasks. Spawned work runs on `runtime`. pub fn new(paths: AgentPaths, runtime: tokio::runtime::Handle) -> Self { let connector: Connector = Arc::new(|spec, cwd, client, on_stderr| match spec.driver { @@ -931,6 +1003,12 @@ impl AgentManager { sinks: RwLock::new(HashMap::new()), security: RwLock::new(None), new_task_approvals: RwLock::new(None), + recovery_settings: RwLock::new(None), + network_probe_hook: RwLock::new(None), + network_probe_initial_ms: AtomicU64::new(NETWORK_PROBE_INITIAL_MS), + network_probe_max_ms: AtomicU64::new(NETWORK_PROBE_MAX_MS), + instance_id: uuid::Uuid::new_v4().simple().to_string(), + reconciled: AtomicBool::new(false), workspace_roots: RwLock::new(None), git_executable: RwLock::new(None), change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)), @@ -958,7 +1036,18 @@ impl AgentManager { Ok((mut f, entries)) => { // The agent process did not survive the restart: whatever was in flight is over. if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) { + let was_waiting_for_input = f.task.status == AgentStatus::NeedsInput; + let approval_mode = config::approval_fingerprint(&f.task.config); f.task.status = AgentStatus::Ready; + f.task.error = None; + f.task.unread = true; + f.task.interrupted = Some(Box::new(AgentInterrupted { + reason: InterruptionReason::UnexpectedExit, + at_ms: f.task.updated_ms, + was_waiting_for_input, + approval_mode, + auto_resume_once: false, + })); } f.task.retry = None; f.task.background.clear(); @@ -1009,6 +1098,16 @@ impl AgentManager { *self.shared.new_task_approvals.write() = Some(hook); } + /// Sets the callback that reads session recovery and transient network retry settings. + pub fn set_recovery_settings_hook(&self, hook: RecoverySettingsHook) { + *self.shared.recovery_settings.write() = Some(hook); + } + + /// Unique identifier for this `AgentManager` process incarnation. + pub fn instance_id(&self) -> &str { + &self.shared.instance_id + } + /// Sets the callback that lists the workspace roots offered to agents besides a task's own. pub fn set_workspace_roots_hook(&self, hook: WorkspaceRootsHook) { *self.shared.workspace_roots.write() = Some(hook); @@ -1343,6 +1442,9 @@ impl AgentManager { mcp_overrides: BTreeMap::new(), skill_overrides: BTreeMap::new(), stats: Box::default(), + interrupted: None, + unread: false, + recovery_window_mins: None, }; let file = TaskFile { task: task.clone(), @@ -1429,6 +1531,9 @@ impl AgentManager { mcp_overrides: BTreeMap::new(), skill_overrides: BTreeMap::new(), stats: Box::default(), + interrupted: None, + unread: false, + recovery_window_mins: None, }; let file = TaskFile { task: task.clone(), @@ -1564,6 +1669,9 @@ impl AgentManager { mcp_overrides: req.mcp_overrides, skill_overrides: req.skill_overrides, stats: Box::default(), + interrupted: None, + unread: false, + recovery_window_mins: None, }; let file = TaskFile { task: task.clone(), @@ -1584,7 +1692,13 @@ impl AgentManager { pending_native_fork: None, }; let handle = Task::restore(file, self.shared.clone()); - handle.state.lock().busy = !req.idle; + { + let mut s = handle.state.lock(); + s.busy = !req.idle; + if !req.idle { + s.pending_prompt = Some(prompt.clone()); + } + } let epoch = { let mut tasks = self.tasks.write(); let epoch = self.shared.shutdown_epoch(); @@ -1631,6 +1745,7 @@ impl AgentManager { } else { let epoch = self.shared.shutdown_epoch(); s.busy = true; + s.pending_prompt = Some(prompt.clone()); Some((prompt, epoch)) } }; @@ -1937,6 +2052,8 @@ impl AgentManager { retry: None, background: Box::default(), stats: Box::default(), + interrupted: None, + unread: false, ..s.task.clone() }; TaskFile { @@ -2162,7 +2279,7 @@ impl AgentManager { pub fn cancel(&self, id: &str, subagent: Option) -> IdeResult<()> { let task = self.task(id)?; match subagent { - None => task.cancel(), + None => task.cancel_explicit(), Some(sub) => { if let Some(live) = task.live.lock().clone() { let _ = live.peer.notify("session/cancel", json!({ "sessionId": sub })); @@ -2172,6 +2289,305 @@ impl AgentManager { Ok(()) } + /// Resumes an interrupted task with a continuation turn (or immediately wakes a task + /// waiting in the transient network outage loop). + pub fn resume(&self, id: &str) -> IdeResult<()> { + let task = self.task(id)?; + enum Action { + WakeNetwork, + Run { prompt: AgentPrompt, recovery: Option, truncated: bool, epoch: u64 }, + } + let action = { + let mut s = task.state.lock(); + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("the task is archived")); + } + if s.discovering_model.is_some() { + return Err(IdeError::unavailable("Model settings are still loading")); + } + if s.busy { + if s.task.retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) { + Action::WakeNetwork + } else { + return Err(IdeError::invalid("the agent is already running")); + } + } else { + let Some(interrupted) = s.task.interrupted.take() else { + return Err(IdeError::invalid("the task is not interrupted")); + }; + s.task.unread = false; + let unsent_initial = s.session_id.is_none() + && s.history.conversation.main.entries.len() == 1 + && matches!(&s.history.conversation.main.entries[0], AgentEntry::User { steered: false, .. }); + let (prompt, recovery, truncated) = if unsent_initial { + let popped = s.history.conversation.main.entries.pop(); + s.history.conversation.truncate(0); + s.history.turns.clear(); + match popped { + Some(AgentEntry::User { text, images, .. }) => { + (AgentPrompt { text, files: Vec::new(), images }, None, true) + } + _ => (continuation_prompt_for(interrupted.reason), Some(interrupted.reason), false), + } + } else { + (continuation_prompt_for(interrupted.reason), Some(interrupted.reason), false) + }; + let epoch = self.shared.shutdown_epoch(); + s.busy = true; + Action::Run { prompt, recovery, truncated, epoch } + } + }; + match action { + Action::WakeNetwork => { + task.force_resume_now.store(true, Ordering::Release); + task.network_poke.notify_waiters(); + } + Action::Run { prompt, recovery, truncated, epoch } => { + if truncated { + task.streamed.lock().clear(); + self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: 0 }); + } + self.shared.runtime.spawn(async move { task.run_with_recovery(prompt, recovery, epoch).await }); + } + } + Ok(()) + } + + /// Resumes every currently interrupted task and returns their IDs. + pub fn resume_all_interrupted(&self) -> IdeResult> { + let mut candidates: Vec<(String, f64)> = self + .tasks + .read() + .values() + .filter_map(|task| { + let s = task.state.lock(); + if s.task.status == AgentStatus::Archived || s.busy { + return None; + } + Some((task.id.clone(), s.task.interrupted.as_ref()?.at_ms)) + }) + .collect(); + candidates.sort_by(|a, b| b.1.total_cmp(&a.1)); + let mut resumed = Vec::new(); + for (id, _) in candidates { + if self.resume(&id).is_ok() { + resumed.push(id); + } + } + Ok(resumed) + } + + /// Clears a task's interrupted state without sending a continuation prompt. + pub fn dismiss_interrupted(&self, id: &str) -> IdeResult<()> { + let task = self.task(id)?; + let changed = { + let mut s = task.state.lock(); + let had_interrupted = s.task.interrupted.take().is_some(); + let had_unread = std::mem::replace(&mut s.task.unread, false); + had_interrupted || had_unread + }; + if changed { + task.persist(); + task.emit_task(); + } + Ok(()) + } + + /// Marks a task as read (`unread = false`) when the user opens or focuses it. + pub fn mark_read(&self, id: &str) -> IdeResult<()> { + let task = self.task(id)?; + let changed = { + let mut s = task.state.lock(); + std::mem::replace(&mut s.task.unread, false) + }; + if changed { + task.persist(); + task.emit_task(); + } + Ok(()) + } + + /// Overrides the recovery / network auto-retry window (`None` = global default, + /// `Some(0)` = Off / Ask, `Some(m)` = `m` minutes) for task `id`. + pub fn set_recovery_window(&self, id: &str, minutes: Option) -> IdeResult<()> { + if let Some(m) = minutes + && m > 7 * 24 * 60 + { + return Err(IdeError::invalid("recovery window exceeds maximum")); + } + let task = self.task(id)?; + let changed = { + let mut s = task.state.lock(); + if s.task.recovery_window_mins == minutes { + false + } else { + s.task.recovery_window_mins = minutes; + true + } + }; + if changed { + task.persist(); + task.emit_task(); + task.network_poke.notify_waiters(); + } + Ok(()) + } + + /// Arms or clears the one-shot auto-resume flag on active/interrupted tasks before + /// closing the project window or quitting OpenIDEA. + pub fn set_auto_resume_once(&self, ids: &[String], enabled: bool) { + for id in ids { + let Ok(task) = self.task(id) else { continue }; + task.auto_resume_on_close.store(enabled, Ordering::Release); + let changed = { + let mut s = task.state.lock(); + if let Some(intr) = s.task.interrupted.as_deref_mut() + && intr.auto_resume_once != enabled + { + intr.auto_resume_once = enabled && !intr.was_waiting_for_input; + true + } else { + false + } + }; + if changed { + task.persist(); + task.emit_task(); + } + } + } + + /// Wakes any task waiting in the transient network outage retry loop (e.g. when the + /// frontend receives a browser `online` event) so reachability is probed immediately. + pub fn poke_network(&self) { + let tasks: Vec> = self.tasks.read().values().cloned().collect(); + for task in tasks { + task.network_poke.notify_waiters(); + } + } + + /// Reconciles interrupted tasks once per `AgentManager` incarnation according to the + /// user's recovery policy and safety guardrails, returning what was auto-resumed vs left + /// waiting for manual confirmation. + pub fn reconcile_interrupted(&self) -> AgentRecoveryReport { + let first_reconcile = !self.shared.reconciled.swap(true, Ordering::AcqRel); + let (default_window, policy) = self.shared.recovery_settings(); + let now = now_ms(); + + struct ReconcileCandidate { + handle: Arc, + intr: AgentInterrupted, + isolation: Isolation, + cwd: PathBuf, + override_mins: Option, + safe_session: bool, + current_fp: Option, + } + + let handles: Vec> = self.tasks.read().values().cloned().collect(); + let mut active_local_cwds: HashSet = HashSet::new(); + let mut interrupted_local_counts: HashMap = HashMap::new(); + let mut candidates: Vec = Vec::new(); + + let canon = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + for handle in &handles { + let s = handle.state.lock(); + if s.task.status == AgentStatus::Archived { + continue; + } + let cwd = canon(&s.task.cwd.0); + if s.busy || matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput) + { + if s.task.isolation == Isolation::Local { + active_local_cwds.insert(cwd); + } + continue; + } + if let Some(intr) = s.task.interrupted.as_deref() { + if s.task.isolation == Isolation::Local { + *interrupted_local_counts.entry(cwd.clone()).or_insert(0) += 1; + } + let current_fp = config::approval_fingerprint(&s.task.config); + let safe_session = !s.ephemeral; + candidates.push(ReconcileCandidate { + handle: handle.clone(), + intr: intr.clone(), + isolation: s.task.isolation, + cwd, + override_mins: s.task.recovery_window_mins, + safe_session, + current_fp, + }); + } + } + + candidates.sort_by(|a, b| b.intr.at_ms.total_cmp(&a.intr.at_ms)); + + let mut auto_resumed = Vec::new(); + let mut remaining = Vec::new(); + + for ReconcileCandidate { handle, intr, isolation, cwd, override_mins, safe_session, current_fp } in candidates { + let window_mins = override_mins.unwrap_or_else(|| default_window.minutes()); + let within_window = window_mins > 0 && (now - intr.at_ms) <= (window_mins as f64) * 60_000.0; + let policy_allows = if intr.auto_resume_once { + true + } else { + match policy { + ide_core::settings::ResumeInterruptedPolicy::Off + | ide_core::settings::ResumeInterruptedPolicy::Ask => false, + ide_core::settings::ResumeInterruptedPolicy::Restart => { + matches!(intr.reason, InterruptionReason::Restart | InterruptionReason::BackendUpgrade) + } + ide_core::settings::ResumeInterruptedPolicy::Window => within_window, + } + }; + let local_conflict = isolation == Isolation::Local + && (active_local_cwds.contains(&cwd) || interrupted_local_counts.get(&cwd).copied().unwrap_or(0) > 1); + let approval_drifted = intr.approval_mode != current_fp; + let eligible = first_reconcile + && policy_allows + && safe_session + && !intr.was_waiting_for_input + && !approval_drifted + && !local_conflict + && auto_resumed.len() < MAX_CONCURRENT_AUTO_RESUMES + && handle.record_auto_resume_attempt(now); + + if eligible && self.resume(&handle.id).is_ok() { + if isolation == Isolation::Local { + active_local_cwds.insert(cwd); + } + auto_resumed.push(handle.id.clone()); + } else { + if first_reconcile && intr.auto_resume_once { + let cleared = { + let mut s = handle.state.lock(); + if let Some(cur) = s.task.interrupted.as_deref_mut() + && cur.auto_resume_once + { + cur.auto_resume_once = false; + true + } else { + false + } + }; + if cleared { + handle.persist(); + handle.emit_task(); + } + } + remaining.push(handle.id.clone()); + } + } + + AgentRecoveryReport { + instance_id: self.shared.instance_id.clone(), + first_reconcile, + auto_resumed, + interrupted: remaining, + } + } + pub async fn context_usage(&self, id: &str) -> IdeResult { let task = self.task(id)?; let live = task.live.lock().clone().ok_or_else(|| IdeError::unavailable("the agent session is offline"))?; @@ -2743,6 +3159,11 @@ impl AgentManager { /// Stops every agent (project closed or trust revoked). pub fn shutdown(&self) { + self.shutdown_with(AgentShutdownReason::default()); + } + + /// Stops every agent and records `reason` on any turn that was still in flight. + pub fn shutdown_with(&self, reason: AgentShutdownReason) { let tasks: Vec<_> = { let tasks = self.tasks.read(); self.shared.shutdown_epoch.fetch_add(1, Ordering::AcqRel); @@ -2751,7 +3172,7 @@ impl AgentManager { self.detach_sinks(); for task in tasks { let was_live = task.kill().is_some(); - task.finish_shutdown(was_live); + task.finish_shutdown(was_live, reason); } } } @@ -2881,6 +3302,7 @@ impl Task { ephemeral: file.ephemeral, pending_native_fork: file.pending_native_fork, busy: false, + pending_prompt: None, background_tasks: Vec::new(), shell_context: Vec::new(), }), @@ -2895,6 +3317,11 @@ impl Task { start_fresh: AtomicBool::new(false), send_now: AtomicBool::new(false), cancel_pending: AtomicBool::new(false), + explicit_stop: AtomicBool::new(false), + auto_resume_on_close: AtomicBool::new(false), + force_resume_now: AtomicBool::new(false), + network_poke: tokio::sync::Notify::new(), + auto_resume_times: Mutex::new(VecDeque::new()), turn_started: AtomicBool::new(false), turns: AtomicU64::new(0), idle_epoch: AtomicU64::new(0), @@ -3078,12 +3505,24 @@ impl Task { } /// Like [`Self::set_status`], but drops the update if `shutdown()` ran since `epoch`. - fn set_status_for_epoch(&self, status: AgentStatus, error: Option, epoch: u64) -> bool { + fn finish_status_for_epoch( + &self, + status: AgentStatus, + error: Option, + mark_unread: bool, + epoch: u64, + ) -> bool { let mut file = self.file.lock(); if self.shared.shut_down_since(epoch) { return false; } - self.state.lock().change_status(status, error); + { + let mut s = self.state.lock(); + s.change_status(status, error); + if mark_unread { + s.task.unread = true; + } + } // Saved first: whoever reacts to the status change finds it on disk. self.saves_asked.fetch_add(1, Ordering::AcqRel); self.save_locked(&mut file); @@ -3121,12 +3560,26 @@ impl Task { } /// After NeedsInput + optional auto-approve: notify only when the user must still answer. - fn emit_attention_if_input_pending(&self) { + fn emit_attention_if_input_pending(self: &Arc, epoch: u64) { // One lock at a time: `approve_pending` takes state then permissions, so holding the // permissions guard (a temporary that lives to the end of the statement) while taking // state could deadlock against it. let pending = !self.permissions.lock().is_empty(); - let waiting = pending && self.state.lock().task.status == AgentStatus::NeedsInput; + let (waiting, marked_unread) = { + let mut s = self.state.lock(); + let waiting = pending && s.task.status == AgentStatus::NeedsInput; + let marked_unread = if waiting && !s.task.unread { + s.task.unread = true; + true + } else { + false + }; + (waiting, marked_unread) + }; + if marked_unread { + self.persist_soon_for_epoch(epoch); + self.emit_task(); + } if waiting { self.emit_attention(AgentAttentionReason::Input); } @@ -3234,17 +3687,49 @@ impl Task { /// Settles any turn interrupted by `shutdown()` and flushes unsaved state without /// rewriting untouched or archived tasks. - fn finish_shutdown(&self, was_live: bool) { + fn finish_shutdown(&self, was_live: bool, reason: AgentShutdownReason) { let mut file = self.file.lock(); + let auto_resume_once = self.auto_resume_on_close.swap(false, Ordering::AcqRel); let settled = { let mut s = self.state.lock(); - let in_flight = s.busy - || matches!(s.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting); - if was_live || in_flight { + let archived = s.task.status == AgentStatus::Archived; + let in_flight = !archived + && (s.busy + || matches!(s.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting)); + if was_live || s.busy || in_flight { + let was_waiting_for_input = s.task.status == AgentStatus::NeedsInput; s.busy = false; - if matches!(s.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) { + if let Some(unsent) = s.pending_prompt.take() + && !archived + { + let attachments = unsent + .files + .iter() + .map(|f| file_name(&f.0)) + .chain(unsent.images.iter().map(|i| i.name.clone().unwrap_or_else(|| "image".into()))) + .collect(); + s.history.conversation.main.push(AgentEntry::User { + text: unsent.text, + attachments, + images: unsent.images, + sent_ms: Some(now_ms()), + done_ms: None, + steered: false, + recovery: None, + }); + } + if in_flight { + let approval_mode = config::approval_fingerprint(&s.task.config); s.task.status = AgentStatus::Ready; s.task.error = None; + s.task.unread = true; + s.task.interrupted = Some(Box::new(AgentInterrupted { + reason: reason.into(), + at_ms: now_ms(), + was_waiting_for_input, + approval_mode, + auto_resume_once: auto_resume_once && !was_waiting_for_input, + })); } s.task.retry = None; s.task.background.clear(); @@ -3259,6 +3744,7 @@ impl Task { }; if settled { self.cancel_pending.store(false, Ordering::Release); + self.explicit_stop.store(false, Ordering::Release); self.send_now.store(false, Ordering::Release); self.saves_asked.fetch_add(1, Ordering::AcqRel); } @@ -3344,23 +3830,39 @@ impl Task { /// Runs `prompt`, then the queued messages, until the queue is empty, a turn fails, or /// the user stops one. The caller set `busy`. - async fn run(self: Arc, mut prompt: AgentPrompt, epoch: u64) { + async fn run(self: Arc, prompt: AgentPrompt, epoch: u64) { + self.run_with_recovery(prompt, None, epoch).await; + } + + async fn run_with_recovery( + self: Arc, + mut prompt: AgentPrompt, + mut recovery: Option, + epoch: u64, + ) { + self.explicit_stop.store(false, Ordering::Release); + self.force_resume_now.store(false, Ordering::Release); + let mut network_resumes_this_turn: u32 = 0; loop { if self.shared.shut_down_since(epoch) { return; } // The message shows before the checkout is recorded, which can take a while in a large repository. - if !self.show_prompt(&prompt, epoch) { + if !self.show_prompt(&prompt, recovery.take(), epoch) { return; } self.checkout_before_turn(epoch).await; if self.shared.shut_down_since(epoch) { return; } - let result = self.turn(&prompt, epoch).await; + let mut result = self.turn(&prompt, epoch).await; if self.shared.shut_down_since(epoch) { return; } + let explicit_stop = self.explicit_stop.swap(false, Ordering::AcqRel); + if explicit_stop && result.is_err() { + result = Ok("cancelled".into()); + } self.cancel_pending.store(false, Ordering::Release); tokio::time::sleep(TURN_GRACE).await; if self.shared.shut_down_since(epoch) { @@ -3370,6 +3872,45 @@ impl Task { if self.shared.shut_down_since(epoch) { return; } + if let Err(ref failure) = result + && failure.network + && !explicit_stop + { + let window_mins = self.effective_recovery_window_mins(); + if window_mins == 0 { + self.settle_network_timeout(epoch); + return; + } + if network_resumes_this_turn < MAX_NETWORK_RESUMES_PER_TURN { + // Kill any broken child session before waiting for network to return. + if let Some(live) = self.live.lock().take() { + live.peer.kill(); + } + match self.wait_for_network(&failure.message, now_ms(), epoch).await { + NetworkWaitOutcome::ShutDown => return, + NetworkWaitOutcome::Cancelled => { + result = Ok("cancelled".into()); + } + NetworkWaitOutcome::Expired => { + self.settle_network_timeout(epoch); + return; + } + NetworkWaitOutcome::Recovered { forced } => { + if forced || self.record_auto_resume_attempt(now_ms()) { + let changed = self.state.lock().history.conversation.end_turn(Some(now_ms())); + self.mark_dirty(changed); + network_resumes_this_turn += 1; + prompt = continuation_prompt_for(InterruptionReason::NetworkTimeout); + recovery = Some(InterruptionReason::NetworkTimeout); + continue; + } else { + self.settle_network_timeout(epoch); + return; + } + } + } + } + } let send_now = self.send_now.swap(false, Ordering::AcqRel); let (changed, next, archived) = { let mut s = self.state.lock(); @@ -3408,13 +3949,16 @@ impl Task { return; } self.emit_task(); + network_resumes_this_turn = 0; prompt = queued.prompt; + recovery = None; } (None, Ok(stop)) => { - if !self.set_status_for_epoch(AgentStatus::Ready, None, epoch) { + let completed = stop != "cancelled"; + if !self.finish_status_for_epoch(AgentStatus::Ready, None, completed, epoch) { return; } - if stop != "cancelled" { + if completed { self.emit_attention(AgentAttentionReason::Finished); } if (self.mcp_reload_pending.swap(false, Ordering::AcqRel) @@ -3431,6 +3975,141 @@ impl Task { } } + fn effective_recovery_window_mins(&self) -> u32 { + let override_mins = self.state.lock().task.recovery_window_mins; + override_mins.unwrap_or_else(|| self.shared.recovery_settings().0.minutes()) + } + + fn record_auto_resume_attempt(&self, now: f64) -> bool { + let mut times = self.auto_resume_times.lock(); + while times.front().is_some_and(|&t| now - t > AUTO_RESUME_SLIDING_WINDOW_MS) { + times.pop_front(); + } + if times.len() >= MAX_AUTO_RESUMES_PER_WINDOW { + return false; + } + times.push_back(now); + true + } + + async fn wait_for_network(&self, error_msg: &str, outage_started_ms: f64, epoch: u64) -> NetworkWaitOutcome { + // Ensure status shows Running while holding the outage retry state. + { + let mut s = self.state.lock(); + if self.shared.shut_down_since(epoch) { + return NetworkWaitOutcome::ShutDown; + } + if s.task.status == AgentStatus::Starting { + s.task.status = AgentStatus::Running; + } + } + let provider = self.state.lock().task.provider.clone(); + let mut attempt: u32 = 1; + let mut delay_ms = self.shared.network_probe_initial_ms.load(Ordering::Relaxed).max(10); + let max_delay_ms = self.shared.network_probe_max_ms.load(Ordering::Relaxed).max(delay_ms); + + loop { + if self.shared.shut_down_since(epoch) { + return NetworkWaitOutcome::ShutDown; + } + if self.cancel_pending.load(Ordering::Acquire) + || self.explicit_stop.load(Ordering::Acquire) + || self.send_now.load(Ordering::Acquire) + { + self.set_retry(None); + return NetworkWaitOutcome::Cancelled; + } + if self.force_resume_now.swap(false, Ordering::AcqRel) { + self.set_retry(None); + return NetworkWaitOutcome::Recovered { forced: true }; + } + let window_mins = self.effective_recovery_window_mins(); + let deadline_ms = outage_started_ms + (window_mins as f64) * 60_000.0; + let now = now_ms(); + if window_mins == 0 || now >= deadline_ms { + self.set_retry(None); + return NetworkWaitOutcome::Expired; + } + let wait_ms = delay_ms.min((deadline_ms - now).ceil().max(1.0) as u64); + self.set_retry(Some(AgentRetry { + attempt, + max_retries: None, + retry_at_ms: now + wait_ms as f64, + error: Some(error_msg.to_owned()), + deadline_ms: Some(deadline_ms), + })); + + let notified = self.network_poke.notified(); + tokio::select! { + _ = tokio::time::sleep(Duration::from_millis(wait_ms)) => {} + _ = notified => {} + } + + if self.shared.shut_down_since(epoch) { + return NetworkWaitOutcome::ShutDown; + } + if self.cancel_pending.load(Ordering::Acquire) + || self.explicit_stop.load(Ordering::Acquire) + || self.send_now.load(Ordering::Acquire) + { + self.set_retry(None); + return NetworkWaitOutcome::Cancelled; + } + if self.force_resume_now.swap(false, Ordering::AcqRel) { + self.set_retry(None); + return NetworkWaitOutcome::Recovered { forced: true }; + } + let window_mins = self.effective_recovery_window_mins(); + let deadline_ms = outage_started_ms + (window_mins as f64) * 60_000.0; + if window_mins == 0 || now_ms() >= deadline_ms { + self.set_retry(None); + return NetworkWaitOutcome::Expired; + } + if self.shared.probe_network(&provider).await { + self.set_retry(None); + return NetworkWaitOutcome::Recovered { forced: false }; + } + attempt = attempt.saturating_add(1); + delay_ms = (delay_ms.saturating_mul(2)).min(max_delay_ms); + } + } + + fn settle_network_timeout(self: &Arc, epoch: u64) { + self.cancel_permissions(); + if let Some(live) = self.live.lock().take() { + live.peer.kill(); + } + let mut file = self.file.lock(); + if self.shared.shut_down_since(epoch) { + return; + } + let dirty = { + let mut s = self.state.lock(); + let now = now_ms(); + let dirty = s.history.conversation.settle(now); + let approval_mode = config::approval_fingerprint(&s.task.config); + s.busy = false; + s.task.background.clear(); + s.background_tasks.clear(); + s.change_status(AgentStatus::Ready, None); + s.task.unread = true; + s.task.interrupted = Some(Box::new(AgentInterrupted { + reason: InterruptionReason::NetworkTimeout, + at_ms: now, + was_waiting_for_input: false, + approval_mode, + auto_resume_once: false, + })); + dirty + }; + self.saves_asked.fetch_add(1, Ordering::AcqRel); + self.save_locked(&mut file); + drop(file); + self.mark_dirty(dirty); + self.emit_task(); + self.emit_attention(AgentAttentionReason::Failed); + } + /// Drops an idle resumable live session so the next turn reloads it. fn recycle_resumable_session(&self) { self.mcp_reload_pending.store(false, Ordering::Release); @@ -3648,6 +4327,7 @@ impl Task { let i = s.history.conversation.main.push(AgentEntry::Error { message: failure.message.clone() }); dirty.push((None, i)); s.task.background.clear(); + s.busy = false; match failure.limit { Some(resets) => { s.task.resets_ms = resets; @@ -3655,6 +4335,7 @@ impl Task { } None => s.change_status(AgentStatus::Failed, Some(failure.message)), } + s.task.unread = true; dirty }; self.saves_asked.fetch_add(1, Ordering::AcqRel); @@ -3708,12 +4389,13 @@ impl Task { sent_ms: Some(now_ms()), done_ms: None, steered: true, + recovery: None, }); Ok(()) } /// Adds the user's message to the conversation and shows the task starting. - fn show_prompt(self: &Arc, prompt: &AgentPrompt, epoch: u64) -> bool { + fn show_prompt(self: &Arc, prompt: &AgentPrompt, recovery: Option, epoch: u64) -> bool { let attachments = prompt .files .iter() @@ -3728,6 +4410,7 @@ impl Task { } let i = { let mut s = self.state.lock(); + s.pending_prompt = None; let i = s.history.conversation.main.push(AgentEntry::User { text: prompt.text.clone(), attachments, @@ -3735,6 +4418,7 @@ impl Task { sent_ms: Some(now_ms()), done_ms: None, steered: false, + recovery, }); s.change_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None); i @@ -3836,10 +4520,12 @@ impl Task { RpcError::Server { message, .. } if !message.is_empty() => message.clone(), _ => "The usage limit was reached.".into(), }; - return Failure { message, limit: Some(resets) }; + return Failure { message, limit: Some(resets), network: false }; } + let network = is_transient_network_error(&e); let guidance = self.live.lock().as_ref().map(|live| live.sign_in_message.clone()); - Failure::from(self.sign_in_error(&e, guidance.as_deref()).unwrap_or_else(|| self.describe(e))) + let message = self.sign_in_error(&e, guidance.as_deref()).unwrap_or_else(|| self.describe(e)); + Failure { message, limit: None, network } } fn sign_in_error(&self, e: &RpcError, guidance: Option<&str>) -> Option { @@ -4639,6 +5325,7 @@ impl Task { sent_ms: None, done_ms: None, steered: false, + recovery: None, }) } }; @@ -4761,7 +5448,7 @@ impl Task { self.mark_dirty([(None, entry)]); self.emit_task(); self.approve_pending(); - self.emit_attention_if_input_pending(); + self.emit_attention_if_input_pending(epoch); let answer = rx.recv().ok().flatten(); if self.shared.shut_down_since(epoch) { @@ -4867,7 +5554,7 @@ impl Task { }; self.mark_dirty([(None, entry)]); self.emit_task(); - self.emit_attention_if_input_pending(); + self.emit_attention_if_input_pending(epoch); let reply = rx.recv().ok().flatten(); let (response, chosen) = elicitation::answer(&form, reply.as_deref()); if self.shared.shut_down_since(epoch) { @@ -4931,11 +5618,19 @@ impl Task { } } + fn cancel_explicit(&self) { + if self.state.lock().busy { + self.explicit_stop.store(true, Ordering::Release); + } + self.cancel(); + } + fn cancel(&self) { // Also before the turn has started; nothing to stop when idle. if self.state.lock().busy { self.cancel_pending.store(true, Ordering::Release); } + self.network_poke.notify_waiters(); self.cancel_permissions(); if let Some(live) = self.live.lock().clone() { let _ = live.peer.notify("session/cancel", json!({ "sessionId": live.session })); @@ -5176,16 +5871,138 @@ fn upgrade_entry(entry: &mut Value) { } } +enum NetworkWaitOutcome { + Recovered { forced: bool }, + Expired, + Cancelled, + ShutDown, +} + /// Why a turn failed. struct Failure { message: String, /// The usage limit was reached: `Some(when it resets, if known)`. limit: Option>, + /// Failed due to a transient outbound network / transport error. + network: bool, } impl From for Failure { fn from(message: String) -> Self { - Self { message, limit: None } + let lower = message.to_lowercase(); + let network = is_transient_network_text(&lower); + Self { message, limit: None, network } + } +} + +fn is_transient_network_error(e: &RpcError) -> bool { + let RpcError::Server { code, message, data } = e else { return false }; + if acp::auth_required(*code, message) || usage_limit(e).is_some() { + return false; + } + if let Some(d) = data.as_ref() + && (d.pointer("/openidea/network").and_then(Value::as_bool) == Some(true) + || d.get("failureKind").and_then(Value::as_str) == Some("transport")) + { + return true; + } + let full = with_details(message.clone(), data.as_ref()).to_lowercase(); + is_transient_network_text(&full) +} + +fn is_transient_network_text(lower: &str) -> bool { + if ["400", "401", "403", "404", "422", "bad request", "unauthorized", "forbidden", "invalid model"] + .iter() + .any(|k| lower.contains(k)) + { + return false; + } + [ + "network error", + "network is unreachable", + "connection reset", + "connection refused", + "connection closed", + "connection timed out", + "tls handshake", + "enotfound", + "eai_again", + "econnreset", + "econnrefused", + "etimedout", + "ehostunreach", + "enetunreach", + "temporary failure in name resolution", + "failed to lookup address", + "failed to connect", + "transport error", + "502 bad gateway", + "503 service unavailable", + "504 gateway timeout", + ] + .iter() + .any(|k| lower.contains(k)) +} + +fn default_network_probe(provider: &str) -> bool { + use std::net::{TcpStream, ToSocketAddrs}; + + let timeout = Duration::from_secs(3); + for key in ["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy", "HTTP_PROXY", "http_proxy"] { + if let Ok(raw) = std::env::var(key) + && let Some(host_port) = proxy_host_port(&raw) + { + return tcp_reachable(&host_port, timeout); + } + } + let targets: &[&str] = match provider { + "copilot" => &["api.githubcopilot.com:443", "github.com:443"], + "claude" | "claude-acp" => &["api.anthropic.com:443"], + "codex" | "codex-acp" => &["api.openai.com:443"], + _ => &["github.com:443", "1.1.1.1:443"], + }; + fn tcp_reachable(target: &str, timeout: Duration) -> bool { + let Ok(addrs) = target.to_socket_addrs() else { return false }; + for addr in addrs.take(3) { + if TcpStream::connect_timeout(&addr, timeout).is_ok() { + return true; + } + } + false + } + targets.iter().any(|t| tcp_reachable(t, timeout)) +} + +fn proxy_host_port(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return None; + } + let without_scheme = trimmed.split_once("://").map_or(trimmed, |(_, rest)| rest); + let authority = without_scheme.split('/').next()?; + let host_port = authority.rsplit_once('@').map_or(authority, |(_, hp)| hp); + if host_port.is_empty() { + return None; + } + if host_port.contains(':') { Some(host_port.to_owned()) } else { Some(format!("{host_port}:80")) } +} + +fn continuation_prompt_for(reason: InterruptionReason) -> AgentPrompt { + let cause = match reason { + InterruptionReason::WindowClose => "the project window was closed", + InterruptionReason::Quit => "OpenIDEA quit", + InterruptionReason::Restart => "OpenIDEA restarted", + InterruptionReason::BackendUpgrade => "the OpenIDEA backend upgraded", + InterruptionReason::BackendStop => "the OpenIDEA backend stopped", + InterruptionReason::UnexpectedExit => "OpenIDEA exited unexpectedly", + InterruptionReason::NetworkTimeout => "the network connection dropped", + }; + AgentPrompt { + text: format!( + "The previous turn was interrupted because {cause}. Inspect the current workspace and git state before repeating any side-effecting commands, then continue from where you left off." + ), + files: Vec::new(), + images: Vec::new(), } } @@ -5342,6 +6159,7 @@ fn retry_of(update: &Value, now: f64) -> Option { max_retries: n("maxRetries").and_then(|m| u32::try_from(m).ok()), retry_at_ms: now + n("retryDelayMs").unwrap_or(0) as f64, error: update.get("error").and_then(Value::as_str).filter(|e| !e.is_empty()).map(str::to_owned), + deadline_ms: None, }) } diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index b96b7018bc..c618d87028 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -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 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, + #[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, + /// Task IDs remaining in `Interrupted` (`Ask to resume`). + pub interrupted: Vec, +} + +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, + /// 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>, + /// 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, } #[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, + /// 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, } /// 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, }, Agent { text: String, diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index ee18517d25..244e4f7240 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -67,6 +67,8 @@ struct FakeAgent { forks: Mutex>, /// The content blocks of each `session/prompt`. prompts: Mutex>, + /// Queued errors returned on the next `session/prompt` calls before succeeding. + prompt_errors: Mutex>, } 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("") => 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("") { 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", "user.email=test@example.com", "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(); +} diff --git a/crates/ide-agent/src/timeline.rs b/crates/ide-agent/src/timeline.rs index e4579790f6..28a601dfd7 100644 --- a/crates/ide-agent/src/timeline.rs +++ b/crates/ide-agent/src/timeline.rs @@ -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)); diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 65c5b18e1c..01983eeb0d 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -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>)] @@ -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")] diff --git a/crates/ide-host/src/daemon.rs b/crates/ide-host/src/daemon.rs index 461335e87d..c581f37f4a 100644 --- a/crates/ide-host/src/daemon.rs +++ b/crates/ide-host/src/daemon.rs @@ -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(()); } diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 994d90e2e0..678dfaab98 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -155,6 +155,8 @@ pub struct Host { project_requests: RwLock>>, /// Shutdowns of projects closed with [`Host::close_project_detached`]. closing: parking_lot::Mutex>, + /// Why this host's agents are shutting down when [`Host::shutdown`] runs. + agent_shutdown_reason: parking_lot::Mutex, /// One open at a time per window (see [`Host::opening`]). open_locks: parking_lot::Mutex>>>, } @@ -170,6 +172,7 @@ struct ShutdownWork { lsp: Option>, debug: Option<(Arc, String, Option)>, agents: Vec>, + agent_reason: ide_agent::AgentShutdownReason, terminals: Option, processes: Option, retired: Option>, @@ -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 { + fn begin_close(&self, window: &str, agent_reason: ide_agent::AgentShutdownReason) -> Option { 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 { diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index ccae8d46e3..582340af08 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -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 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> { + 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) -> 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, 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 { + 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, diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index a5839b2f4f..1288727e01 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -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(); diff --git a/crates/ide-host/tests/remote_daemon.rs b/crates/ide-host/tests/remote_daemon.rs index 55e43bec4b..1d34f82f4e 100644 --- a/crates/ide-host/tests/remote_daemon.rs +++ b/crates/ide-host/tests/remote_daemon.rs @@ -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; +} diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index 714b26ff69..aae94d37e7 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -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); + } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 69ada005d1..e3320a53dd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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::() { + 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::().is_some_and(|w| w.restart_requested()); if let Some(state) = app.try_state::() { + 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::().is_some_and(|w| w.restart_requested()) { + if restart { #[cfg(target_os = "macos")] relaunch::restart(&app.env()); #[cfg(not(target_os = "macos"))] diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index f00a6c832a..506584a67c 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -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); } } diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index f8b2a489d8..d1ee00e5ab 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -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 diff --git a/src/bindings.ts b/src/bindings.ts index 46a4e7d76d..9b7f14b87d 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -57,6 +57,8 @@ export const commands = { */ agentCustomSave: (input: CustomAgentInput) => typedError(__TAURI_INVOKE("agent_custom_save", { input })), agentDelete: (task: string, removeWorktree: boolean) => typedError(__TAURI_INVOKE("agent_delete", { task, removeWorktree })), + /** Clears a task's interrupted state without sending a continuation prompt. */ + agentDismissInterrupted: (task: string) => typedError(__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(__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) => typedError(__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(__TAURI_INVOKE("agent_mark_read", { task })), /** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */ agentMcpDiscoverSources: () => typedError(__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(__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(__TAURI_INVOKE("agent_mcp_test", { id })), + /** Wakes any task waiting in the transient network outage loop so reachability is probed now. */ + agentPokeNetwork: () => typedError(__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(__TAURI_INVOKE("agent_preview_copilot_models", { account, model })), /** @@ -120,6 +126,11 @@ export const commands = { * blocking pool. */ agentProviders: () => typedError(__TAURI_INVOKE("agent_providers")), + /** + * Reconciles interrupted tasks once per `AgentManager` incarnation according to the user's + * recovery policy and safety guardrails. + */ + agentReconcileInterrupted: () => typedError(__TAURI_INVOKE("agent_reconcile_interrupted")), /** Refreshes the model catalog; force bypasses freshness, not the cooldown. */ agentRefreshModels: (provider: string, force: boolean, model: string | null) => typedError(__TAURI_INVOKE("agent_refresh_models", { provider, force, model })), /** @@ -137,6 +148,13 @@ export const commands = { agentRename: (task: string, title: string) => typedError(__TAURI_INVOKE("agent_rename", { task, title })), /** Answers a permission request; `option: null` cancels it. */ agentRespond: (task: string, permission: number, option: string | null) => typedError(__TAURI_INVOKE("agent_respond", { task, permission, option })), + /** Resumes all interrupted tasks in the project and returns their IDs. */ + agentResumeAllInterrupted: () => typedError(__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(__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(__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(__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(__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(__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(__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(__TAURI_INVOKE("agent_set_recovery_window", { task, minutes })), /** Updates per-session skill modes on `task`. */ agentSetSkillOverrides: (task: string, overrides: { [key in string]: AgentSkillMode }) => typedError(__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`. */ diff --git a/src/features/agents/Agents.module.css b/src/features/agents/Agents.module.css index c6a376ab5a..d01d626236 100644 --- a/src/features/agents/Agents.module.css +++ b/src/features/agents/Agents.module.css @@ -171,6 +171,9 @@ .ready { color: var(--success); } +.interrupted { + color: var(--warning); +} .failed { color: var(--danger); } diff --git a/src/features/agents/AgentsStatus.tsx b/src/features/agents/AgentsStatus.tsx index b0a759c9f6..88f7db23f9 100644 --- a/src/features/agents/AgentsStatus.tsx +++ b/src/features/agents/AgentsStatus.tsx @@ -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 (