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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 7ce59ab407 fix(agents): retry Cursor capacity errors with visible attempt counts 2026-12-02 17:50:15 +08:00
11 змінених файлів з 266 додано та 22 видалено

No files matched your search

+112 -17
Переглянути файл
@@ -154,6 +154,9 @@ 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);
const CURSOR_CAPACITY_MESSAGE: &str = "Error: RetriableError: [resource_exhausted] Error";
const CURSOR_RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(5), Duration::from_secs(15), Duration::from_secs(30)];
/// 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.
@@ -2815,6 +2818,7 @@ impl AgentManager {
let approval_drifted = intr.approval_mode != current_fp;
let eligible = first_reconcile
&& policy_allows
&& intr.reason != InterruptionReason::CursorCapacity
&& safe_session
&& !intr.was_waiting_for_input
&& !approval_drifted
@@ -3619,6 +3623,7 @@ impl AgentManager {
};
self.detach_sinks();
for task in tasks {
task.network_poke.notify_waiters();
let was_live = task.kill().is_some();
task.finish_shutdown(was_live, reason);
}
@@ -4204,6 +4209,7 @@ impl Task {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
});
}
if in_flight {
@@ -4443,12 +4449,13 @@ impl Task {
self.explicit_stop.store(false, Ordering::Release);
self.force_resume_now.store(false, Ordering::Release);
let mut network_resumes_this_turn: u32 = 0;
let mut capacity_retries = 0;
loop {
if self.shared.shut_down_since(epoch) {
return;
}
self.state.lock().active_scheduled_turn = scheduled.clone();
if recovery.is_none() {
if recovery.is_none() || recovery == Some(InterruptionReason::CursorCapacity) {
if let Err(err) = self.verify_worktree_cwd_confined() {
self.state.lock().active_scheduled_turn = None;
return self.fail(Failure::from(err.to_string()), epoch);
@@ -4469,7 +4476,9 @@ impl Task {
}
}
// The message shows before the checkout is recorded, which can take a while in a large repository.
if !self.show_prompt(&prompt, recovery.take(), epoch) {
let retry_attempt = (recovery == Some(InterruptionReason::CursorCapacity) && capacity_retries > 0)
.then_some(capacity_retries as u32);
if !self.show_prompt(&prompt, recovery.take(), retry_attempt, epoch) {
self.state.lock().active_scheduled_turn = None;
return;
}
@@ -4481,11 +4490,6 @@ impl Task {
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) {
return;
@@ -4494,13 +4498,41 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return;
}
// Cursor ACP ends the turn successfully even when its final response is a
// capacity error. Check after TURN_GRACE so trailing chunks have arrived.
if self.cursor_at_capacity(&result) {
if self.cancel_pending.load(Ordering::Acquire) || self.send_now.load(Ordering::Acquire) {
result = Ok("cancelled".into());
} else if let Some(&delay) = CURSOR_RETRY_DELAYS.get(capacity_retries) {
capacity_retries += 1;
if self.wait_for_cursor_retry(capacity_retries, delay, epoch).await {
let changed = self.state.lock().history.conversation.end_turn(Some(now_ms()));
self.mark_dirty(changed);
recovery = Some(InterruptionReason::CursorCapacity);
prompt = continuation_prompt_for(InterruptionReason::CursorCapacity);
continue;
}
if self.shared.shut_down_since(epoch) {
return;
}
result = Ok("cancelled".into());
} else {
self.settle_interrupted(InterruptionReason::CursorCapacity, 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);
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);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
if network_resumes_this_turn < MAX_NETWORK_RESUMES_PER_TURN {
@@ -4514,7 +4546,7 @@ impl Task {
result = Ok("cancelled".into());
}
NetworkWaitOutcome::Expired => {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
NetworkWaitOutcome::Recovered { forced } => {
@@ -4526,7 +4558,7 @@ impl Task {
recovery = Some(InterruptionReason::NetworkTimeout);
continue;
} else {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
}
@@ -4573,6 +4605,7 @@ impl Task {
}
self.emit_task();
network_resumes_this_turn = 0;
capacity_retries = 0;
prompt = queued.prompt;
scheduled = queued.scheduled;
recovery = None;
@@ -4699,9 +4732,53 @@ impl Task {
}
}
fn settle_network_timeout(self: &Arc<Self>, epoch: u64) {
fn cursor_at_capacity(&self, result: &Result<String, Failure>) -> bool {
let s = self.state.lock();
if s.task.provider != "cursor" {
return false;
}
matches!(result, Ok(stop) if stop == "end_turn")
&& matches!(
s.history.conversation.main.entries.last(),
Some(AgentEntry::Agent { text }) if text.trim() == CURSOR_CAPACITY_MESSAGE
)
}
async fn wait_for_cursor_retry(&self, attempt: usize, delay: Duration, epoch: u64) -> bool {
#[cfg(test)]
let delay = delay.min(Duration::from_millis(150));
let until = tokio::time::Instant::now() + delay;
self.set_retry(Some(AgentRetry {
attempt: attempt as u32,
max_retries: Some(CURSOR_RETRY_DELAYS.len() as u32),
retry_at_ms: now_ms() + delay.as_secs_f64() * 1000.0,
error: Some(CURSOR_CAPACITY_MESSAGE.into()),
deadline_ms: None,
}));
loop {
let notified = self.network_poke.notified();
if self.shared.shut_down_since(epoch)
|| self.cancel_pending.load(Ordering::Acquire)
|| self.explicit_stop.load(Ordering::Acquire)
|| self.send_now.load(Ordering::Acquire)
{
return false;
}
if tokio::time::Instant::now() >= until {
return true;
}
tokio::select! {
_ = tokio::time::sleep_until(until) => {}
_ = notified => {}
}
}
}
fn settle_interrupted(self: &Arc<Self>, reason: InterruptionReason, epoch: u64) {
self.cancel_permissions();
if let Some(live) = self.live.lock().take() {
if reason == InterruptionReason::NetworkTimeout
&& let Some(live) = self.live.lock().take()
{
live.peer.kill();
}
let mut file = self.file.lock();
@@ -4714,12 +4791,15 @@ impl Task {
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.active_scheduled_turn = None;
if reason == InterruptionReason::NetworkTimeout {
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,
reason,
at_ms: now,
was_waiting_for_input: false,
approval_mode,
@@ -4733,6 +4813,9 @@ impl Task {
self.mark_dirty(dirty);
self.emit_task();
self.emit_attention(AgentAttentionReason::Failed);
if reason == InterruptionReason::CursorCapacity {
self.release_when_idle();
}
}
/// Drops an idle resumable live session so the next turn reloads it.
@@ -4976,7 +5059,9 @@ impl Task {
let live = self.live.lock().clone().filter(|l| l.capabilities.steer && !l.peer.is_closed());
let running = {
let s = self.state.lock();
s.busy && s.task.status == AgentStatus::Running
// During Cursor backoff the ACP turn has already ended. Send Now must
// cancel the wait and dispatch the new prompt as a turn of its own.
s.busy && s.task.status == AgentStatus::Running && !(s.task.provider == "cursor" && s.task.retry.is_some())
};
let Some((live, method)) = live
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
@@ -5015,12 +5100,19 @@ impl Task {
done_ms: None,
steered: true,
recovery: None,
retry_attempt: None,
});
Ok(())
}
/// Adds the user's message to the conversation and shows the task starting.
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt, recovery: Option<InterruptionReason>, epoch: u64) -> bool {
fn show_prompt(
self: &Arc<Self>,
prompt: &AgentPrompt,
recovery: Option<InterruptionReason>,
retry_attempt: Option<u32>,
epoch: u64,
) -> bool {
let attachments = prompt
.files
.iter()
@@ -5044,6 +5136,7 @@ impl Task {
done_ms: None,
steered: false,
recovery,
retry_attempt,
});
s.change_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
i
@@ -6038,6 +6131,7 @@ impl Task {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
})
}
};
@@ -6733,6 +6827,7 @@ fn continuation_prompt_for(reason: InterruptionReason) -> AgentPrompt {
InterruptionReason::BackendStop => "the OpenIDEA backend stopped",
InterruptionReason::UnexpectedExit => "OpenIDEA exited unexpectedly",
InterruptionReason::NetworkTimeout => "the network connection dropped",
InterruptionReason::CursorCapacity => "Cursor reported a capacity limit",
};
AgentPrompt {
text: format!(
+4
Переглянути файл
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
BackendStop,
UnexpectedExit,
NetworkTimeout,
CursorCapacity,
}
impl From<AgentShutdownReason> for InterruptionReason {
@@ -641,6 +642,9 @@ pub enum AgentEntry {
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
#[serde(default)]
recovery: Option<InterruptionReason>,
/// One-based automatic retry number for this continuation.
#[serde(default)]
retry_attempt: Option<u32>,
},
Agent {
text: String,
+97
Переглянути файл
@@ -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)>>,
/// Number of prompts that stream Cursor's capacity diagnostic before returning end_turn.
capacity_errors: Mutex<u32>,
/// 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`.
@@ -297,6 +299,22 @@ impl Handler for FakeAgent {
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
{
let mut remaining = self.capacity_errors.lock();
if *remaining > 0 {
*remaining -= 1;
if text == "edit once" {
self.update(
&session,
json!({"sessionUpdate": "tool_call", "toolCallId": "edit",
"title": "Edit file", "kind": "edit", "status": "completed"}),
);
}
self.say(&session, "\n\nError: RetriableError: ");
self.say(&session, "[resource_exhausted] Error");
return Ok(json!({"stopReason": "end_turn"}));
}
}
if text.starts_with("The previous turn was interrupted because ") {
self.say(&session, "resumed cleanly");
return Ok(json!({"stopReason": "end_turn"}));
@@ -7263,6 +7281,85 @@ async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_pauses_after_three_continuations_and_resumes_on_request() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 4;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let snap = handle.state.lock().snapshot();
assert_eq!(snap.interrupted.unwrap().reason, InterruptionReason::CursorCapacity);
assert!(snap.retry.is_none());
let entries = mgr.entries(&task.id, None).unwrap();
let attempts: Vec<_> = entries
.iter()
.filter_map(|e| match e {
AgentEntry::User { retry_attempt, .. } => *retry_attempt,
_ => None,
})
.collect();
assert_eq!(attempts, [1, 2, 3]);
assert_eq!(entries.iter().filter(|e| matches!(e, AgentEntry::Tool { .. })).count(), 1);
assert_eq!(agent.prompts.lock().len(), 4);
mgr.resume(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(handle.state.lock().task.interrupted.is_none());
assert_eq!(agent.prompts.lock().len(), 5);
assert!(
agent
.prompts
.lock()
.iter()
.skip(1)
.all(|p| p[0]["text"].as_str().unwrap().contains("Inspect the current workspace"))
);
assert!(
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Agent { text }) if text == "resumed cleanly")
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_can_be_stopped_or_replaced_during_backoff() {
for send_now in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 1;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
let handle = mgr.task(&task.id).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while handle.state.lock().task.retry.is_none() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
let retry = handle.state.lock().task.retry.clone().unwrap();
assert_eq!((retry.attempt, retry.max_retries, retry.deadline_ms), (1, Some(3), None));
if !send_now {
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 1);
assert!(handle.state.lock().task.retry.is_none());
}
mgr.prompt(&task.id, text("again"), send_now).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 2);
assert_eq!(agent.prompts.lock()[1][0]["text"], "again");
}
}
#[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};
+2
Переглянути файл
@@ -646,6 +646,7 @@ mod tests {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0));
@@ -668,6 +669,7 @@ mod tests {
done_ms: None,
steered,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0, false));
+4 -2
Переглянути файл
@@ -3421,7 +3421,9 @@ doneMs?: number | null;
/** Sent into a running turn rather than starting one. */
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 } |
recovery?: InterruptionReason | null;
/** One-based automatic retry number for this continuation. */
retryAttempt?: number | 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. */
@@ -11227,7 +11229,7 @@ export type InterfaceMember = {
};
/** Why an in-flight turn stopped before completing. */
export type InterruptionReason = "windowClose" | "quit" | "restart" | "backendUpgrade" | "backendStop" | "unexpectedExit" | "networkTimeout";
export type InterruptionReason = "windowClose" | "quit" | "restart" | "backendUpgrade" | "backendStop" | "unexpectedExit" | "networkTimeout" | "cursorCapacity";
/** Optional parts of the invalidation; the symbol index is always rebuilt. */
export type InvalidateCachesOptions = {
+4
Переглянути файл
@@ -233,6 +233,8 @@ export function interruptionBannerText(reason: InterruptionReason, wasWaitingFor
return "Interrupted when the OpenIDEA backend stopped.";
case "unexpectedExit":
return "Interrupted when OpenIDEA exited unexpectedly.";
case "cursorCapacity":
return "Cursor is still at capacity. Automatic retries have stopped.";
case "networkTimeout":
return "Paused after the network retry window expired.";
}
@@ -252,6 +254,8 @@ export function recoveryDividerLabel(reason: InterruptionReason): string {
return "Resumed after backend stop";
case "unexpectedExit":
return "Resumed after unexpected exit";
case "cursorCapacity":
return "Retry after Cursor capacity limit";
case "networkTimeout":
return "Resumed after network drop";
}
+33
Переглянути файл
@@ -386,6 +386,39 @@ describe("inline Interrupted banner, Waiting for network banner, and RecoveryTur
await vi.waitFor(() => expect(backend.cancel).toHaveBeenCalledWith("n1"));
});
it("shows the retry number during backoff and offers Retry once Cursor is still at capacity", async () => {
const task = makeTask("cursor-retry", {
provider: "cursor",
status: "running",
retry: { attempt: 2, maxRetries: 3, retryAtMs: Date.now() + 15_000, error: null },
});
const view = render(<WorkingRow task={task} entries={[]} subagent={null} />);
expect(screen.getByText(/retrying in .*s \(attempt 2\/3\)/)).toBeVisible();
const paused = {
...task,
status: "ready" as const,
retry: null,
interrupted: { reason: "cursorCapacity" as const, atMs: Date.now() },
};
useAgents.setState({ tasks: new Map([[paused.id, paused]]) });
view.rerender(
<SessionComposer
task={paused}
focusRequest={0}
focusRoot={{ current: null }}
entries={[]}
head={null}
changes={null}
commits={[]}
onOpenChanges={() => {}}
onOpenSubagent={() => {}}
/>,
);
expect(screen.getByText("Cursor is still at capacity. Automatic retries have stopped.")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await vi.waitFor(() => expect(backend.resumeTask).toHaveBeenCalledWith(paused.id));
});
it("renders synthetic recovery User entries as a compact separator pill instead of a chat bubble", () => {
const t = makeTask("m1");
const drafts = { current: new Map() };
+2 -2
Переглянути файл
@@ -122,7 +122,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
<span className={styles.bannerMeta}>{age(intr.atMs ?? 0)}</span>
</span>
<div className={styles.bannerActions}>
<RecoveryWindowPicker task={task} />
{intr.reason !== "cursorCapacity" && <RecoveryWindowPicker task={task} />}
<Button
size="small"
variant="primary"
@@ -141,7 +141,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
.finally(() => setResuming(false));
}}
>
<T>Resume</T>
{intr.reason === "cursorCapacity" ? <T>Retry</T> : <T>Resume</T>}
</Button>
<IconButton
icon="close"
+2 -1
Переглянути файл
@@ -352,12 +352,13 @@ function UserMessage({
const [editWidth, setEditWidth] = useState<number | null>(null);
const bubbleRef = useRef<HTMLDivElement>(null);
if (entry.recovery) {
const attempt = entry.retryAttempt;
return (
<div className={styles.recoveryDivider} role="separator">
<span className={styles.recoveryRule} aria-hidden="true" />
<span className={styles.recoveryPill}>
<Icon name="agent-resume" size={12} />
<span>{tx(recoveryDividerLabel(entry.recovery))}</span>
<span>{attempt != null ? tx`Retry ${attempt}` : tx(recoveryDividerLabel(entry.recovery))}</span>
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
</span>
<span className={styles.recoveryRule} aria-hidden="true" />
+3
Переглянути файл
@@ -3448,6 +3448,9 @@
"Edit name patterns in Data Source Properties.": "Edit name patterns in Data Source Properties.",
"Update the remote OpenIDEA server to edit visibility from the tree.": "Update the remote OpenIDEA server to edit visibility from the tree.",
"Retry": "Retry",
"Retry {attempt}": "Retry {attempt}",
"Retry after Cursor capacity limit": "Retry after Cursor capacity limit",
"Cursor is still at capacity. Automatic retries have stopped.": "Cursor is still at capacity. Automatic retries have stopped.",
"Choose File…": "Choose File…",
"Choose Directory Archive…": "Choose Directory Archive…",
"This is a MySQL dump: restore it into a MySQL data source.": "This is a MySQL dump: restore it into a MySQL data source.",
+3
Переглянути файл
@@ -11457,6 +11457,9 @@
"Interrupted when the OpenIDEA backend upgraded.": "OpenIDEA 后端升级时被中断。",
"Interrupted when the OpenIDEA backend stopped.": "OpenIDEA 后端停止时被中断。",
"Interrupted when OpenIDEA exited unexpectedly.": "OpenIDEA 异常退出时被中断。",
"Cursor is still at capacity. Automatic retries have stopped.": "Cursor 仍然资源不足,自动重试已停止。",
"Retry {attempt}": "第 {attempt} 次重试",
"Retry after Cursor capacity limit": "Cursor 资源不足后重试",
"Paused after the network retry window expired.": "网络自动重试时间窗口到期后已暂停。",
"Resumed after window close": "窗口关闭后已恢复",
"Resumed after OpenIDEA quit": "OpenIDEA 退出后已恢复",