Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/staged/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions apps/staged/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ rand = "0.10"
hex = "0.4"
subtle = "2.6"
time = "0.3"
# Usage-limit resets printed in an IANA zone ("resets 4:10pm
# (Australia/Melbourne)"). Already in the lock; the system tzdb is read on
# macOS and Linux, and a bundled copy is used on Windows.
jiff = "0.2"
pikchr = "0.1.4"

# Pikchr preview MCP tool: render Pikchr source to SVG (same C engine as the
Expand Down
2 changes: 1 addition & 1 deletion apps/staged/src-tauri/src/rate_limit_scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1268,7 +1268,7 @@ fn metadata_for_state(state: &RateLimitAutoRecovery) -> serde_json::Value {
/// rows written before normalization existed — is accepted here as epoch
/// seconds or millis, split by magnitude: epoch seconds passed 10^11 around
/// year 5138, while millis crossed it in 1973.
fn parse_reset_timestamp_millis(value: &str) -> Option<i64> {
pub(crate) fn parse_reset_timestamp_millis(value: &str) -> Option<i64> {
let value = value.trim();
if let Ok(epoch) = value.parse::<i64>() {
if epoch <= 0 {
Expand Down
98 changes: 75 additions & 23 deletions apps/staged/src-tauri/src/session_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ pub(crate) mod reconcile;
mod run_end;
mod second_directory;
mod startup_restart;
mod usage_limit_reset;

pub(crate) use disconnect::may_still_run_on_workstation;
pub(crate) mod remote_note_watchdog;
Expand Down Expand Up @@ -6406,12 +6407,19 @@ fn rate_limit_recovery_details(
// read here in order of preference:
//
// 1. `data.rateLimit` on the failed prompt's error: the failing
// turn's latest info, and the only copy a turn refused before its
// first model response gets, which is every message sent while
// already over the limit and every refused auto-resume.
// turn's latest info, which the bridge attaches only when the SDK
// sent a `rate_limit_event` during the turn.
// 2. `_meta["_claude/rateLimit"]` on a `usage_update`, which the
// bridge sends only once the turn has usage to report.
//
// A turn refused by a freshly started agent process has neither: the
// CLI turns the prompt away from its own saved limit state without
// calling the API, so no `rate_limit_event` is sent and the error is
// a bare `{ errorKind: "rate_limit" }`. Every message sent to an idle
// session while over the limit and every refused auto-resume starts
// such a process. For those the reset is read from the message text
// below instead.
//
// Each field is taken from the first place that has it. Info that
// does not say a limit was reached is skipped in both places (see
// `rate_limit_info_reports_a_reached_limit`).
Expand Down Expand Up @@ -6454,13 +6462,54 @@ fn rate_limit_recovery_details(
error_kind = data.and_then(|data| string_field(data, &["errorKind", "kind", "type"]));
}

let usage_limit_message = usage_limit_message(error, provider_metadata);

// The reset a usage-limit message prints (`resets 4:10pm
// (Australia/Melbourne)`) stands in for a structured reset that is
// missing, or already past when the printed one is still ahead: a stale
// `rejected` info would otherwise send the pause to the minute-scale
// backoff. A structured reset still ahead always wins, and the parsed
// one goes through the same allowance check below.
//
// A printed reset that replaces a stale structured one also drops the
// limit type that came with it: that info describes a window that has
// since reset, and naming its kind (`five_hour`) beside the printed
// reset of another (`weekly limit · resets Dec 8 at 2am`) would put the
// wrong limit in the pause copy and the auto-resume prompt. The kind then
// falls back to the wording below.
let printed_reset_millis = usage_limit_message.as_deref().and_then(|message| {
usage_limit_reset::reset_millis_from_usage_limit_message(message, now_millis)
});
let replaces_stale_reset = details.resets_at.is_some();
let use_printed_reset = match details.resets_at.as_deref() {
None => true,
Some(structured) => {
crate::rate_limit_scheduler::parse_reset_timestamp_millis(structured)
.is_some_and(|millis| millis <= now_millis)
&& printed_reset_millis.is_some_and(|millis| millis > now_millis)
}
};
if let Some(resets_at) = printed_reset_millis
.filter(|_| use_printed_reset)
.and_then(|millis| epoch_to_rfc3339_utc(millis, now_millis))
{
details.resets_at = Some(resets_at);
if replaces_stale_reset {
limit_type = None;
}
}

// The kind is the limit type the bridge reported. Failing that, a
// message worded as a reached usage limit names one (`USAGE_LIMIT_KIND`),
// which is what tells a subscription limit from an API 429 when neither
// a type nor a reset arrives. Then a bare `status`, the error's own
// kind, and last the error text.
details.kind = limit_type
.or_else(|| usage_limit_kind_from_message(error, provider_metadata))
.or_else(|| {
usage_limit_message
.as_ref()
.map(|_| crate::rate_limit_scheduler::USAGE_LIMIT_KIND.to_string())
})
.or(status)
.or(error_kind)
.or_else(|| {
Expand Down Expand Up @@ -6521,20 +6570,21 @@ fn rate_limit_info_reports_a_reached_limit(rate_limit: &serde_json::Value) -> bo
})
}

/// [`USAGE_LIMIT_KIND`](crate::rate_limit_scheduler::USAGE_LIMIT_KIND) when
/// the failed prompt's message is worded as a reached subscription usage
/// limit, for a failure that reported no limit type.
/// The failed prompt's message when it is worded as a reached subscription
/// usage limit. It names the kind
/// ([`USAGE_LIMIT_KIND`](crate::rate_limit_scheduler::USAGE_LIMIT_KIND)) of
/// a failure that reported no limit type, and its printed reset stands in
/// for one that reported no reset.
///
/// A subscription limit and an API rate limit can arrive with the same
/// structured kind (`rate_limit`) and no reset: a Claude bridge older than
/// claude-agent-acp #1610 sends nothing else for a turn refused before its
/// first model response, and Codex sends text alone. They need different
/// waits (hours against seconds), and the wording is what is left to tell
/// them apart. This does not read the reset out of the text.
/// structured kind (`rate_limit`) and no reset: claude-agent-acp sends
/// nothing else for a turn a freshly started agent process refuses, and
/// Codex sends text alone. They need different waits (hours against
/// seconds), and the wording is what is left to tell them apart.
///
/// A structured kind other than `rate_limit` stands: an `overloaded`
/// failure is never a usage limit, whatever its text says.
fn usage_limit_kind_from_message(
fn usage_limit_message(
error: &str,
provider_metadata: Option<&serde_json::Value>,
) -> Option<String> {
Expand All @@ -6556,8 +6606,7 @@ fn usage_limit_kind_from_message(
.map(str::to_string)
.or_else(|| innermost_error_sentence(error))
.unwrap_or_else(|| error.to_string());
has_usage_limit_wording(&message.to_lowercase())
.then(|| crate::rate_limit_scheduler::USAGE_LIMIT_KIND.to_string())
has_usage_limit_wording(&message.to_lowercase()).then_some(message)
}

/// Whether lowercased error text is worded as a subscription usage limit
Expand Down Expand Up @@ -11879,20 +11928,23 @@ draft file (its path is in your instructions), counting from the first non-blank
}

#[test]
fn rate_limit_recovery_details_has_no_reset_for_a_bare_error_kind() {
// A turn refused before its first usage by a bridge that sends no
// `rateLimit` (before claude-agent-acp #1610, or with no
// `rate_limit_event` in the turn): there is nothing structured to
// read, and the reset in the message text is not parsed. The
// message's wording still names it a usage limit, which is what
// keeps it off the backoff of an API `rate_limit`.
fn rate_limit_recovery_details_reads_the_printed_reset_of_a_bare_error_kind() {
// A turn refused by a freshly started agent process: the SDK sent
// no `rate_limit_event`, so the bridge sends no `rateLimit` and
// there is nothing structured to read. The message's wording names
// it a usage limit, which keeps it off the backoff of an API
// `rate_limit`, and the reset it prints is the one waited for.
let metadata = claude_limit_metadata(None, None);
let error = "Prompt failed: You've hit your session limit · resets 3:45pm (UTC)";
assert!(is_rate_limit_error(error, Some(&metadata)));

let details = rate_limit_recovery_details(error, Some(&metadata), RESET_TEST_NOW_MILLIS);

assert_eq!(details.resets_at, None);
// The end of the printed minute.
assert_eq!(
details.resets_at.as_deref(),
Some("2026-06-24T15:46:00.000Z")
);
assert_eq!(details.kind.as_deref(), Some("usage_limit"));
}

Expand Down
131 changes: 119 additions & 12 deletions apps/staged/src-tauri/src/session_runner/failed_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ mod tests {
/// auto-resume. The bridge sends no `usage_update` for such a turn, so
/// the row holds the prompt error alone. `rate_limit` is the error's
/// `data.rateLimit`, which a bridge older than claude-agent-acp #1610
/// does not send.
/// does not send, and no bridge sends for a turn a freshly started agent
/// process refuses.
fn session_refused_before_usage(rate_limit: Option<serde_json::Value>) -> Session {
let mut metadata = prompt_error_metadata("rate_limit", LIMIT_MESSAGE);
if let Some(rate_limit) = rate_limit {
Expand Down Expand Up @@ -374,11 +375,12 @@ mod tests {

const MINUTE_MS: i64 = 60_000;

/// The subscription case with no structured reset: a bridge older than
/// claude-agent-acp #1610 sends the error kind and the message, nothing
/// else. The wording names it a usage limit.
/// The subscription case with no structured reset: a turn a freshly
/// started agent process refuses gets the error kind and the message,
/// nothing else. The wording names it a usage limit, and the reset it
/// prints stands in for the missing one.
#[test]
fn a_turn_refused_before_usage_with_no_reset_is_named_a_usage_limit() {
fn a_turn_refused_before_usage_with_no_structured_reset_takes_the_one_in_its_message() {
let session = session_refused_before_usage(None);

let decision = decide_failed_run(
Expand All @@ -393,26 +395,131 @@ mod tests {
assert_eq!(
decision.recovery,
Some(RateLimitRecovery {
resets_at: None,
resets_at: Some("2026-11-12T11:01:00.000Z".to_string()),
kind: Some("usage_limit".to_string()),
})
);
}

/// And it is parked on the slow schedule, not the minute-scale backoff
/// that used to spend its attempts long before the limit reset.
/// And it is parked for that reset, as a structured one would be, not
/// on the slow schedule that retried 40–50 minutes after it.
#[test]
fn a_usage_limit_with_no_reset_parks_the_row_on_the_slow_schedule() {
fn a_bare_usage_limit_with_a_printed_reset_parks_the_row_for_it() {
let store = Store::in_memory().unwrap();
let session = session_refused_before_usage(None).with_agent("agent-1");

let bookkeeping = park_failed_run(&store, &session, LIMIT_MESSAGE);

let parked = store.get_session(&session.id).unwrap().unwrap();
assert_eq!(parked.rate_limit_kind.as_deref(), Some("usage_limit"));
assert_eq!(
parked.rate_limit_resets_at.as_deref(),
Some("2026-11-12T11:01:00.000Z")
);
assert_eq!(bookkeeping.attempt, 1);
assert_eq!(bookkeeping.reason.as_deref(), Some("usage_limit_backoff"));
assert_eq!(bookkeeping.reason.as_deref(), Some("reset_at"));
let retry_at = bookkeeping.next_retry_at.expect("a retry is scheduled");
let waits = (NOW_MS + 40 * MINUTE_MS)..=(NOW_MS + 50 * MINUTE_MS);
assert!(waits.contains(&retry_at), "{}", retry_at - NOW_MS);
// The printed 11am is taken as its minute's end, 11:01.
let reset_at = LIMIT_RESETS_AT_SECS * 1_000 + MINUTE_MS;
assert!(
(reset_at..=reset_at + 6 * MINUTE_MS).contains(&retry_at),
"the retry follows the end of the printed minute: {}",
retry_at - reset_at
);
}

/// A refused auto-resume starts a new agent process too, so its error is
/// as bare as the first. Here the session window reopened but the weekly
/// one closed: the retry is parked for the weekly reset its message
/// prints, on the same retry budget.
#[test]
fn a_refused_auto_resume_with_a_bare_error_waits_for_the_reset_in_its_message() {
const WEEKLY_BARE_MESSAGE: &str =
"Internal error: You've hit your weekly limit · resets Nov 14 at 2am (UTC)";
let store = Store::in_memory().unwrap();
let session = session_refused_before_usage(None).with_agent("agent-1");
let first = park_failed_run(&store, &session, LIMIT_MESSAGE);
let retry_now = first.next_retry_at.expect("a retry is scheduled");

// The scheduler's claim keeps the bookkeeping; the resumed turn's
// prompt error replaces the last one.
let parked = store.get_session(&session.id).unwrap().unwrap();
let mut metadata = parked.provider_metadata.clone().unwrap();
metadata["acp"]["promptError"] =
prompt_error_metadata("rate_limit", WEEKLY_BARE_MESSAGE)["acp"]["promptError"].clone();
assert!(store
.transition_to_running_with_provider_metadata(&session.id, Some(&metadata))
.unwrap());
let row = store.get_session(&session.id).unwrap().unwrap();

let decision = decide_failed_run(
Some(&row),
None,
&driver_error(WEEKLY_BARE_MESSAGE),
true,
retry_now,
);
let recovery = decision.recovery.expect("the refused resume pauses");
assert_eq!(
recovery,
RateLimitRecovery {
resets_at: Some("2026-11-14T02:01:00.000Z".to_string()),
kind: Some("usage_limit".to_string()),
}
);
assert!(crate::rate_limit_scheduler::pause_for_rate_limit(
&store,
None,
&session.id,
Some(WEEKLY_BARE_MESSAGE),
recovery.resets_at.as_deref(),
recovery.kind.as_deref(),
retry_now,
)
.unwrap());

let reparked = store.get_session(&session.id).unwrap().unwrap();
let bookkeeping = crate::rate_limit_scheduler::auto_recovery_from_metadata(
reparked.provider_metadata.as_ref(),
)
.expect("the pause writes retry bookkeeping");
assert_eq!(bookkeeping.attempt, 2);
assert_eq!(bookkeeping.reason.as_deref(), Some("reset_at"));
// 2026-11-14T02:01:00Z, the end of the printed minute.
let reset_at = 1_794_621_660_000;
let retry_at = bookkeeping.next_retry_at.expect("a retry is scheduled");
assert!(
(reset_at..=reset_at + 6 * MINUTE_MS).contains(&retry_at),
"the retry follows the weekly reset: {}",
retry_at - reset_at
);
}

/// A usage limit whose message prints no reset this can read is parked
/// on the slow schedule, not the minute-scale backoff that used to spend
/// its attempts long before the limit reset.
#[test]
fn a_usage_limit_with_no_reset_parks_the_row_on_the_slow_schedule() {
for message in [
"Internal error: You've hit your session limit",
"Internal error: You've hit your session limit · resets 11am (Nowhere/Special)",
] {
let store = Store::in_memory().unwrap();
let mut session = session_refused_before_usage(None).with_agent("agent-1");
session.provider_metadata.as_mut().unwrap()["acp"]["promptError"]["message"] =
json!(message);

let bookkeeping = park_failed_run(&store, &session, message);

let parked = store.get_session(&session.id).unwrap().unwrap();
assert_eq!(parked.rate_limit_kind.as_deref(), Some("usage_limit"));
assert_eq!(parked.rate_limit_resets_at, None, "{message}");
assert_eq!(bookkeeping.attempt, 1);
assert_eq!(bookkeeping.reason.as_deref(), Some("usage_limit_backoff"));
let retry_at = bookkeeping.next_retry_at.expect("a retry is scheduled");
let waits = (NOW_MS + 40 * MINUTE_MS)..=(NOW_MS + 50 * MINUTE_MS);
assert!(waits.contains(&retry_at), "{}", retry_at - NOW_MS);
}
}

/// 2026-11-18T08:00:00Z in epoch seconds, six days after [`NOW_MS`].
Expand Down
Loading