fix(agents): load an imported session's history when its task opens (#7816)

An imported (or forked) session showed no history when its background load failed or the app quit before it finished, because the history was only loaded with the first message. A task holding a recorded session but no history now loads it when its entries are first shown, once per run. A failed background load no longer makes the next message silently start a new session; only a failed message, which the user sees, does.

Co-authored-by: janoskranczler <[email protected]>
Цей коміт міститься в:
János Kranczlerтаjanoskranczler authored and GitHub committed 2026-12-03 22:10:51 +08:00
1 джерело 45dd96cdeb
коміт cd57b7f053
2 files changed
+134 -23

No files matched your search

+61 -23
Переглянути файл
@@ -160,6 +160,8 @@ const FLUSH_DELAY: Duration = Duration::from_millis(40);
const SAVE_DELAY: Duration = Duration::from_millis(250);
/// Updates that arrive this late after `session/load` returns are still replayed history.
const REPLAY_GRACE: Duration = Duration::from_millis(300);
/// Agents whose recorded sessions can become tasks (import, fork).
const RECORDED_SESSION_AGENTS: [&str; 3] = ["claude", "codex", "copilot"];
/// Notifications are delivered on their own thread: the last `session/update`s of a turn
/// can trail its `session/prompt` response by this much.
const TURN_GRACE: Duration = Duration::from_millis(100);
@@ -1027,6 +1029,8 @@ struct Task {
/// The task has a session but none of its history (an imported session): the next load's
/// replay becomes the task's history instead of being dropped.
adopting_replay: AtomicBool,
/// A background load of the recorded session started in this run (see `load_recorded_session`).
recorded_load_started: AtomicBool,
/// The saved session failed to load and the user was told: the next start opens a new one.
start_fresh: AtomicBool,
/// The current turn is being cancelled to send the first queued message right away.
@@ -1564,9 +1568,13 @@ impl AgentManager {
self.tasks.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no agent task {id}")))
}
/// The entries of the task's conversation, or of its subagent `subagent`'s.
/// The entries of the task's conversation, or of its subagent `subagent`'s. A task that
/// holds a recorded session without its history starts loading it.
pub fn entries(&self, id: &str, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
let task = self.task(id)?;
if subagent.is_none() && task.awaits_recorded_history() {
task.load_recorded_session(self.shared.shutdown_epoch());
}
let s = task.state.lock();
let timeline =
s.history.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
@@ -1605,7 +1613,7 @@ impl AgentManager {
/// Imports an external session as a task, loading it in the background to show its history (#312).
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex" | "copilot") {
if !RECORDED_SESSION_AGENTS.contains(&provider) {
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
}
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
@@ -1681,13 +1689,7 @@ impl AgentManager {
};
handle.emit_task();
handle.persist();
// Loading the session replays its history into the task, so it shows before a first message.
self.shared.runtime.spawn(async move {
match handle.ensure_session(epoch).await {
Ok(_) => handle.release_when_idle(),
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
}
});
handle.load_recorded_session(epoch);
Ok(task)
}
@@ -1695,7 +1697,7 @@ impl AgentManager {
/// recording as the agent's own fork, under an id the host chooses. The session must
/// belong to this project and have been recorded in `cwd`.
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex" | "copilot") {
if !RECORDED_SESSION_AGENTS.contains(&provider) {
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
}
if !canonical_uuid(session_id) {
@@ -1784,13 +1786,7 @@ impl AgentManager {
};
handle.emit_task();
handle.persist();
// Loading the session replays its history into the task, so it shows before a first message.
self.shared.runtime.spawn(async move {
match handle.ensure_session(epoch).await {
Ok(_) => handle.release_when_idle(),
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
}
});
handle.load_recorded_session(epoch);
Ok(task)
}
@@ -3946,6 +3942,7 @@ impl Task {
next_permission: AtomicU32::new(1),
replaying: AtomicBool::new(false),
adopting_replay: AtomicBool::new(adopt),
recorded_load_started: AtomicBool::new(false),
start_fresh: AtomicBool::new(false),
send_now: AtomicBool::new(false),
cancel_pending: AtomicBool::new(false),
@@ -5448,7 +5445,39 @@ impl Task {
}
}
/// A task holding a recorded session but none of its history (an import whose load failed or
/// was cut short) that is idle and not yet loading it in this run.
fn awaits_recorded_history(&self) -> bool {
if self.recorded_load_started.load(Ordering::Acquire) || !self.adopts_replay() || self.live.lock().is_some() {
return false;
}
let s = self.state.lock();
!s.busy
&& s.session_id.is_some()
&& s.pending_native_fork.is_none()
&& RECORDED_SESSION_AGENTS.contains(&s.task.provider.as_str())
}
/// Opens the recorded session in the background, once per run: its replay shows the history
/// before a first message (#312).
fn load_recorded_session(self: &Arc<Self>, epoch: u64) {
if self.recorded_load_started.swap(true, Ordering::AcqRel) {
return;
}
let task = self.clone();
self.shared.runtime.spawn(async move {
match task.ensure_session_for(epoch, OpenFor::History).await {
Ok(_) => task.release_when_idle(),
Err(e) => tracing::warn!("agent task {}: loading its recorded session failed: {e}", task.id),
}
});
}
async fn ensure_session(self: &Arc<Self>, epoch: u64) -> Result<Live, String> {
self.ensure_session_for(epoch, OpenFor::Message).await
}
async fn ensure_session_for(self: &Arc<Self>, epoch: u64, open_for: OpenFor) -> Result<Live, String> {
let _guard = self.connecting.lock().await;
if self.shared.shut_down_since(epoch) {
return Err("The agent manager shut down.".into());
@@ -5458,9 +5487,9 @@ impl Task {
{
return Ok(live);
}
let (provider_id, cwd, saved, pending) = {
let (provider_id, saved, pending) = {
let s = self.state.lock();
(s.task.provider.clone(), s.task.cwd.0.clone(), s.session_id.clone(), s.pending_model.clone())
(s.task.provider.clone(), s.session_id.clone(), s.pending_model.clone())
};
let pending_model = pending.as_ref();
let raw_spec = self.shared.spec(&provider_id).ok_or_else(|| format!("unknown agent {provider_id}"))?;
@@ -5472,7 +5501,7 @@ impl Task {
raw_spec.clone()
};
let opened =
match self.open_session(&provider_id, primary_spec, &cwd, saved.clone(), pending_model, epoch).await {
match self.open_session(&provider_id, primary_spec, open_for, saved.clone(), pending_model, epoch).await {
Ok(live) => Ok(live),
Err(err) if can_fallback && err.allow_acp_fallback && !self.shared.shut_down_since(epoch) => {
tracing::warn!(
@@ -5482,7 +5511,7 @@ impl Task {
);
self.shared.mark_copilot_acp_fallback(&raw_spec);
let acp_spec = native::copilot::acp_fallback_spec(&raw_spec);
self.open_session(&provider_id, acp_spec, &cwd, saved, pending_model, epoch).await
self.open_session(&provider_id, acp_spec, open_for, saved, pending_model, epoch).await
}
Err(err) => Err(err),
};
@@ -5518,7 +5547,7 @@ impl Task {
self: &Arc<Self>,
provider_id: &str,
spec: provider::ProviderSpec,
_cwd: &Path,
open_for: OpenFor,
saved: Option<String>,
pending_model: Option<&PendingModel>,
epoch: u64,
@@ -5720,13 +5749,15 @@ impl Task {
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
// Warm-up, timeouts and writer conflicts can clear before the next attempt.
// Warm-up, timeouts and writer conflicts can clear before the next attempt,
// and only a message whose failure the user sees may give up the session.
let writer_conflict = spec.driver == provider::Driver::Codex
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"));
if acp::service_warming_up(&e)
|| matches!(e, RpcError::Timeout)
|| writer_conflict
|| pending_model.is_some()
|| open_for == OpenFor::History
{
return Err(SessionOpenError {
message: format!(
@@ -7530,6 +7561,13 @@ struct SessionOpenError {
allow_acp_fallback: bool,
}
/// Why a session opens: for a message, whose failure the user sees, or to show the recorded history.
#[derive(Clone, Copy, PartialEq, Eq)]
enum OpenFor {
Message,
History,
}
/// Registers an opening peer on `task.connecting_peer` so `kill()` can terminate it
/// mid-handshake, and kills it on early error return.
struct OpeningPeer<'a> {
+73
Переглянути файл
@@ -3642,6 +3642,79 @@ async fn imports_copilot_sessions_and_loads_their_history() {
mgr.shutdown();
}
fn session_calls(agent: &FakeAgent) -> Vec<String> {
agent.calls.lock().iter().filter(|c| c.starts_with("session/")).cloned().collect()
}
/// Imports a claude session whose load fails, which leaves what a quit during the load leaves
/// too: a task that holds the recorded session but no conversation.
async fn import_without_history(dir: &Path) -> String {
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INTERNAL_ERROR, "Claude Code exited".into())),
..Default::default()
});
let mgr = manager(dir, agent.clone());
let _down = ShutDown(&mgr);
plant_claude_session(&mgr, dir, NATIVE_SOURCE);
let id = mgr.import_session("claude", NATIVE_SOURCE).unwrap().id;
for _ in 0..300 {
if !session_calls(&agent).is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(session_calls(&agent), ["session/load"]);
assert_eq!(saved_task(&task_file(dir, &id)).unwrap().1, 0);
id
}
#[tokio::test(flavor = "multi_thread")]
async fn an_imported_task_without_its_history_loads_it_when_shown() {
let tmp = tempfile::tempdir().unwrap();
let id = import_without_history(tmp.path()).await;
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
for _ in 0..300 {
if !mgr.entries(&id, None).unwrap().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let entries = mgr.entries(&id, None).unwrap();
assert!(matches!(&entries[0], AgentEntry::User { text, .. } if text == "earlier question"), "{entries:?}");
assert_eq!(session_calls(&agent), ["session/load"], "loaded once, however often it is shown");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_failed_history_load_leaves_the_new_session_to_the_user() {
let tmp = tempfile::tempdir().unwrap();
let id = import_without_history(tmp.path()).await;
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INTERNAL_ERROR, "no conversation found".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
mgr.entries(&id, None).unwrap();
for _ in 0..300 {
if !session_calls(&agent).is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
mgr.entries(&id, None).unwrap();
assert_eq!(session_calls(&agent), ["session/load"], "tried once in this run");
mgr.prompt(&id, text("again"), false).await.unwrap();
wait_for(&mgr, &id, AgentStatus::Failed).await;
assert_eq!(session_calls(&agent), ["session/load", "session/load"], "no new session behind the user's back");
assert!(mgr.entries(&id, None).unwrap().iter().any(|e| matches!(e,
AgentEntry::Error { message } if message.contains("Send the message again"))));
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_codex_assigns() {
let tmp = tempfile::tempdir().unwrap();