дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
fix(agents): retry opening a session while the agent finishes starting (#7350)
Opening a saved session while the agent was still starting failed with an internal error. The session open is now retried while the agent reports warming up, within a 30 s window that also bounds each attempt; a timeout or warm-up failure keeps the saved session id so Try again reopens the same conversation, and an auth request during any attempt runs the advertised authentication once. Closes #7348 Co-authored-by: xuejike <[email protected]>
Цей коміт міститься в:
1 джерело
2f799aede9
коміт
ff4e916561
4 files changed
+288
-25
No files matched your search
@@ -53,6 +53,24 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
|
||||
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
|
||||
}
|
||||
|
||||
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
|
||||
/// rejects session opens until the location's plugins and MCP servers finish activating
|
||||
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
|
||||
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
|
||||
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
|
||||
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
|
||||
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
|
||||
return false;
|
||||
};
|
||||
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
|
||||
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let lower = message.to_lowercase();
|
||||
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
|
||||
}
|
||||
|
||||
/// The capabilities this client offers, in v1 form.
|
||||
fn client_capabilities() -> Value {
|
||||
json!({
|
||||
|
||||
@@ -52,6 +52,40 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_warming_up_matches_opencode_startup_races_only() {
|
||||
for (code, message, data, expected) in [
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
true,
|
||||
),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: OpenCode server is unavailable",
|
||||
Some(json!({"errorName": "ServerUnavailable"})),
|
||||
true,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
false,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
|
||||
(codes::INTERNAL_ERROR, "boom", None, false),
|
||||
(AUTH_REQUIRED, "Authentication required", None, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
|
||||
expected,
|
||||
"code={code}, message={message:?}, data={data:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The messages of a fixture going `dir` (`in` or `out`).
|
||||
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
|
||||
fixture
|
||||
|
||||
@@ -154,6 +154,14 @@ const REPLAY_GRACE: Duration = Duration::from_millis(300);
|
||||
/// 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);
|
||||
/// A session open can arrive before the agent finishes activating its plugins and MCP
|
||||
/// servers (OpenCode: "Location plugins did not finish activating"). That is a transient
|
||||
/// startup race. The window bounds the session-open requests and the waits between them.
|
||||
const WARMUP_WINDOW: Duration = Duration::from_secs(30);
|
||||
/// First wait before retrying a session open the agent answered with "still starting up".
|
||||
const WARMUP_DELAY: Duration = Duration::from_millis(500);
|
||||
/// Backoff cap between those startup retries.
|
||||
const WARMUP_MAX_DELAY: Duration = Duration::from_secs(4);
|
||||
const STDERR_LINES: usize = 20;
|
||||
/// An agent idle this long after its turn is stopped when it can reload its session
|
||||
/// (`session/load`): the next message starts it again where it left off.
|
||||
@@ -5160,6 +5168,9 @@ impl Task {
|
||||
}
|
||||
|
||||
/// Runs `method` and, on an auth error, tries the agent's own ACP `authenticate` once before retrying.
|
||||
/// A session open that lands while the agent is still activating its plugins fails with a
|
||||
/// retryable "service unavailable" (see [`acp::service_warming_up`]); waits that out with
|
||||
/// backoff rather than failing the task over a startup race.
|
||||
async fn request_with_auth(
|
||||
&self,
|
||||
peer: &acp::Conn,
|
||||
@@ -5168,19 +5179,39 @@ impl Task {
|
||||
method: &str,
|
||||
params: Value,
|
||||
) -> Result<Value, RpcError> {
|
||||
let first = peer.request(method, params.clone(), None).await;
|
||||
if !*tried_auth
|
||||
&& let Err(RpcError::Server { code, ref message, .. }) = first
|
||||
&& acp::auth_required(code, message)
|
||||
&& let Some(method_id) = init.agent_auth_method()
|
||||
{
|
||||
*tried_auth = true;
|
||||
match peer.request::<_, Value>("authenticate", json!({ "methodId": method_id }), None).await {
|
||||
Ok(_) => return peer.request(method, params, None).await,
|
||||
Err(e) => tracing::debug!(task = %self.id, method_id, error = %e, "agent authenticate failed"),
|
||||
let mut deadline = tokio::time::Instant::now() + WARMUP_WINDOW;
|
||||
let mut delay = WARMUP_DELAY;
|
||||
loop {
|
||||
let result = tokio::time::timeout_at(deadline, peer.request(method, ¶ms, None))
|
||||
.await
|
||||
.unwrap_or(Err(RpcError::Timeout));
|
||||
let Err(error) = &result else {
|
||||
return result;
|
||||
};
|
||||
if !*tried_auth
|
||||
&& let RpcError::Server { code, message, .. } = error
|
||||
&& acp::auth_required(*code, message)
|
||||
&& let Some(method_id) = init.agent_auth_method()
|
||||
{
|
||||
*tried_auth = true;
|
||||
let auth = peer.request::<_, Value>("authenticate", json!({ "methodId": method_id }), None);
|
||||
match tokio::time::timeout(WARMUP_WINDOW, auth).await.unwrap_or(Err(RpcError::Timeout)) {
|
||||
Ok(_) => {
|
||||
deadline = tokio::time::Instant::now() + WARMUP_WINDOW;
|
||||
delay = WARMUP_DELAY;
|
||||
continue;
|
||||
}
|
||||
Err(e) => tracing::debug!(task = %self.id, method_id, error = %e, "agent authenticate failed"),
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if !acp::service_warming_up(error) || peer.is_closed() || tokio::time::Instant::now() + delay >= deadline {
|
||||
return result;
|
||||
}
|
||||
tracing::info!(task = %self.id, method, "agent still starting up; retrying session open in {delay:?}");
|
||||
tokio::time::sleep(delay).await;
|
||||
delay = (delay * 2).min(WARMUP_MAX_DELAY);
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
async fn ensure_session(self: &Arc<Self>, epoch: u64) -> Result<Live, String> {
|
||||
@@ -5440,9 +5471,13 @@ impl Task {
|
||||
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
return Err(SessionOpenError { message, allow_acp_fallback: false });
|
||||
}
|
||||
// A writer conflict is temporary: retrying must retain the original session ID.
|
||||
if spec.driver == provider::Driver::Codex
|
||||
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"))
|
||||
// Warm-up, timeouts and writer conflicts can clear before the next attempt.
|
||||
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()
|
||||
{
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
@@ -5453,16 +5488,6 @@ impl Task {
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
if pending_model.is_some() {
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
self.start_fresh.store(true, Ordering::Release);
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
@@ -5805,6 +5830,7 @@ impl Task {
|
||||
|
||||
/// A user-facing message for a failed request, with the agent's last stderr lines when it died.
|
||||
fn describe(&self, e: RpcError) -> String {
|
||||
let warming = acp::service_warming_up(&e);
|
||||
match e {
|
||||
RpcError::Closed => {
|
||||
let tail: Vec<String> = self.stderr.lock().iter().cloned().collect();
|
||||
@@ -5814,7 +5840,15 @@ impl Task {
|
||||
format!("The agent process exited:\n{}", tail.join("\n"))
|
||||
}
|
||||
}
|
||||
RpcError::Server { message, data, .. } => with_details(message, data.as_ref()),
|
||||
RpcError::Server { message, data, .. } => {
|
||||
let text = with_details(message, data.as_ref());
|
||||
if warming {
|
||||
format!("{text}\n\nThe agent hasn't finished starting up. Try again in a moment.")
|
||||
} else {
|
||||
text
|
||||
}
|
||||
}
|
||||
RpcError::Timeout => "The agent timed out. Try again in a moment.".into(),
|
||||
e => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +69,8 @@ struct FakeAgent {
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
/// Queued errors returned on the next `session/prompt` calls before succeeding.
|
||||
prompt_errors: Mutex<VecDeque<(i64, String)>>,
|
||||
/// Queued errors returned on the next session-open calls before succeeding.
|
||||
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
|
||||
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
|
||||
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
|
||||
}
|
||||
@@ -150,6 +152,12 @@ impl Handler for FakeAgent {
|
||||
let data = json!({"openidea": {"usageLimit": {"resetsAtMs": 1234.0}}});
|
||||
return Err((codes::INTERNAL_ERROR, "You've hit your usage limit".into(), Some(data)));
|
||||
}
|
||||
if matches!(method, "session/new" | "session/load" | "session/fork")
|
||||
&& let Some(err) = self.open_errors.lock().pop_front()
|
||||
{
|
||||
self.calls.lock().push(method.to_owned());
|
||||
return Err(err);
|
||||
}
|
||||
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
|
||||
}
|
||||
|
||||
@@ -2248,6 +2256,175 @@ async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn warming_up_error() -> (i64, String, Option<Value>) {
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure".to_owned(),
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_retries_while_the_agent_finishes_starting_up() {
|
||||
// OpenCode rejects session opens until its plugins and MCP servers finish activating.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent =
|
||||
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
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;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 2, "retried the startup race");
|
||||
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
|
||||
mgr.shutdown();
|
||||
|
||||
// The same race when reopening a saved session.
|
||||
let agent =
|
||||
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), 2, "retried the startup race");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(saved.as_str()));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
async fn wait_for_session_open_attempts(agent: &FakeAgent, method: &str, attempts: usize) {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while agent.calls.lock().iter().filter(|call| call.as_str() == method).count() < attempts {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("agent received the session-open requests");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_after_warmup_expires_loads_the_saved_session_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(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().unwrap();
|
||||
mgr.shutdown();
|
||||
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(std::iter::repeat_with(warming_up_error).take(16).collect()),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for_session_open_attempts(&agent, "session/load", 2).await;
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(WARMUP_WINDOW - WARMUP_DELAY * 2).await;
|
||||
tokio::time::resume();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
|
||||
entry, AgentEntry::Error { message } if message.contains("Try again") && !message.contains("new session")
|
||||
)));
|
||||
|
||||
agent.open_errors.lock().clear();
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|call| call == "session/new"));
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
assert_eq!(handle.live.lock().as_ref().unwrap().session, saved);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stalled_warmup_retry_times_out_and_closes_the_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
|
||||
hold_session_new: AtomicBool::new(true),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for_session_open_attempts(&agent, "session/new", 2).await;
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(WARMUP_WINDOW).await;
|
||||
tokio::time::resume();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
|
||||
entry, AgentEntry::Error { message } if message.contains("timed out")
|
||||
)));
|
||||
tokio::time::timeout(Duration::from_secs(5), agent.latest().closed())
|
||||
.await
|
||||
.expect("the timed-out connection closes");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_authenticates_after_a_warmup_reply() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
|
||||
auth_on_new: true,
|
||||
authenticate_method: Some("agent_login".into()),
|
||||
auth_methods: vec![json!({"id": "agent_login", "name": "Sign in"})],
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let calls = agent.calls.lock();
|
||||
let setup: Vec<_> = calls
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|call| call.starts_with("session/") || call.starts_with("authenticate"))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
setup,
|
||||
["session/new", "session/new", "authenticate", "authenticate agent_login", "session/new", "session/prompt"]
|
||||
);
|
||||
drop(calls);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_does_not_retry_unrelated_internal_errors() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure".into(),
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
)])),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 1, "no retry on a real failure");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn text(t: &str) -> AgentPrompt {
|
||||
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
|
||||
}
|
||||
|
||||
Reference in new issue
Заблокувати користувача