Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai e7424f94ec fix(agents): report a session that fails to load instead of replacing it
When session/load failed for a task's saved session, the task silently
started a new session and stored its id over the old one: the agent lost
the conversation and nothing in the chat said so (OMP fails to load a
session saved with a model it cannot restore). The failure now shows in
the chat and keeps the saved session; sending the message again starts a
new session, as the error explains. An authentication failure during the
load shows the sign-in error and suggests no new session.

Fixes #4035
2026-11-18 08:42:16 +08:00
2 змінених файлів з 68 додано та 4 видалено

No files matched your search

+23 -2
Переглянути файл
@@ -423,6 +423,8 @@ struct Task {
next_permission: AtomicU32,
/// Set while `session/load` replays history we already have.
replaying: 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.
send_now: AtomicBool,
/// The user stopped the current turn. A stop that reaches the agent before it took the
@@ -1761,6 +1763,7 @@ impl Task {
permissions: Mutex::new(HashMap::new()),
next_permission: AtomicU32::new(1),
replaying: AtomicBool::new(false),
start_fresh: AtomicBool::new(false),
send_now: AtomicBool::new(false),
cancel_pending: AtomicBool::new(false),
turn_started: AtomicBool::new(false),
@@ -2369,7 +2372,8 @@ impl Task {
let mut tried_auth = false;
let mut session = None;
if let (Some(id), true) = (saved, can_load) {
let start_fresh = self.start_fresh.load(Ordering::Acquire);
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers);
params["sessionId"] = json!(&id);
@@ -2378,7 +2382,23 @@ impl Task {
self.replaying.store(false, Ordering::Release);
match loaded {
Ok(v) => session = Some((id, v)),
Err(e) => tracing::info!("agent task {}: session/load failed, starting a new session: {e}", self.id),
// Not silently: a new session would lose the conversation and replace the saved id.
Err(e) => {
tracing::info!("agent task {}: session/load failed: {e}", self.id);
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
self.start_fresh.store(true, Ordering::Release);
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
continue in a new session. The agent won't see the earlier conversation.",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
}
}
let resumed = session.is_some();
@@ -2483,6 +2503,7 @@ impl Task {
s.task.config = options;
s.task.capabilities = capabilities;
s.session_id = Some(session_id.clone());
self.start_fresh.store(false, Ordering::Release);
// The (re)started process runs nothing yet: whatever it reports next is all of it.
s.background_tasks = Vec::new();
s.task.background.clear();
+45 -2
Переглянути файл
@@ -39,6 +39,8 @@ struct FakeAgent {
authenticate_method: Option<String>,
authenticated: AtomicBool,
request_error: Option<(i64, String)>,
/// `session/load` fails with this, as OMP does for a session whose model it can't restore.
load_error: Option<(i64, String)>,
auth_methods: Vec<Value>,
/// Hold the late mode reply until the prompt's permission request is already waiting.
hold_late_mode: bool,
@@ -212,6 +214,7 @@ impl Handler for FakeAgent {
let outcome = if text == "too late" { "promptRequired" } else { "injected" };
Ok(json!({"outcome": outcome, "queue": "steering"}))
}
"session/load" if self.load_error.is_some() => Err(self.load_error.clone().unwrap()),
"session/load" => {
self.say(&session, "replayed history");
Ok(json!({}))
@@ -870,7 +873,7 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
["session/load", "authenticate", "authenticate github_oauth", "session/load", "session/prompt"],
);
// If `authenticate` fails during `session/load`, fallback to `session/new` does not try it again.
// If `authenticate` fails during `session/load`, the sign-in error stands: no new session replaces it.
mgr2.shutdown();
let agent3 = Arc::new(FakeAgent {
auth_on_load: true,
@@ -889,7 +892,7 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
.iter()
.filter(|c| c.starts_with("session/") || c.starts_with("authenticate"))
.collect::<Vec<_>>(),
["session/load", "authenticate", "session/new"],
["session/load", "authenticate"],
);
mgr3.shutdown();
}
@@ -1154,6 +1157,46 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
assert!(calls.contains(&"session/set_mode \"code\"".to_owned()), "{calls:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_again() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
mgr.shutdown();
// OMP: "Could not restore model …" for a session saved with a model it can't restore.
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INTERNAL_ERROR, "Could not restore model x".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
let calls = |agent: &FakeAgent| -> Vec<String> {
agent.calls.lock().iter().filter(|c| c.starts_with("session/")).cloned().collect()
};
assert_eq!(calls(&agent), ["session/load"], "no new session behind the user's back");
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.state.lock().session_id.as_deref(), Some(saved.as_str()));
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|e| matches!(e,
AgentEntry::Error { message } if message.contains("Could not restore model x") && message.contains("Send the message again"))));
// Sending again is the user's choice to continue without the earlier conversation.
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}