diff --git a/apps/staged/src-tauri/Cargo.lock b/apps/staged/src-tauri/Cargo.lock index 46da5cbcc..4b595079a 100644 --- a/apps/staged/src-tauri/Cargo.lock +++ b/apps/staged/src-tauri/Cargo.lock @@ -24,6 +24,7 @@ dependencies = [ "image", "imagesize", "include_dir", + "jiff", "libc", "log", "objc2", diff --git a/apps/staged/src-tauri/Cargo.toml b/apps/staged/src-tauri/Cargo.toml index 7771aa15d..c12698f19 100644 --- a/apps/staged/src-tauri/Cargo.toml +++ b/apps/staged/src-tauri/Cargo.toml @@ -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 diff --git a/apps/staged/src-tauri/src/rate_limit_scheduler.rs b/apps/staged/src-tauri/src/rate_limit_scheduler.rs index 92d8dbace..89734686c 100644 --- a/apps/staged/src-tauri/src/rate_limit_scheduler.rs +++ b/apps/staged/src-tauri/src/rate_limit_scheduler.rs @@ -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 { +pub(crate) fn parse_reset_timestamp_millis(value: &str) -> Option { let value = value.trim(); if let Ok(epoch) = value.parse::() { if epoch <= 0 { diff --git a/apps/staged/src-tauri/src/session_runner.rs b/apps/staged/src-tauri/src/session_runner.rs index 3f126eb5b..dd8fdc7eb 100644 --- a/apps/staged/src-tauri/src/session_runner.rs +++ b/apps/staged/src-tauri/src/session_runner.rs @@ -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; @@ -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`). @@ -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(|| { @@ -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 { @@ -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 @@ -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")); } diff --git a/apps/staged/src-tauri/src/session_runner/failed_run.rs b/apps/staged/src-tauri/src/session_runner/failed_run.rs index eea3a0755..8a42f2f95 100644 --- a/apps/staged/src-tauri/src/session_runner/failed_run.rs +++ b/apps/staged/src-tauri/src/session_runner/failed_run.rs @@ -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) -> Session { let mut metadata = prompt_error_metadata("rate_limit", LIMIT_MESSAGE); if let Some(rate_limit) = rate_limit { @@ -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( @@ -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`]. diff --git a/apps/staged/src-tauri/src/session_runner/tests/usage_limit_details.rs b/apps/staged/src-tauri/src/session_runner/tests/usage_limit_details.rs index 8a70c5a75..c3786252f 100644 --- a/apps/staged/src-tauri/src/session_runner/tests/usage_limit_details.rs +++ b/apps/staged/src-tauri/src/session_runner/tests/usage_limit_details.rs @@ -3,7 +3,7 @@ //! //! - a weekly limit, whose reset is days ahead; //! - a subscription usage limit that reports no reset and no limit type, -//! known only by its wording; +//! known only by its wording, and the reset its message prints; //! - an API 429 or an overloaded provider, which keep their own kind //! whatever rate-limit info the turn left behind, and wait for no reset //! more than 48 hours ahead; @@ -78,34 +78,248 @@ fn a_weekly_reset_days_ahead_is_kept() { #[test] fn a_weekly_limit_with_no_reset_keeps_its_limit_type() { // `resetsAt` is optional in `SDKRateLimitInfo`. The limit type the - // bridge names is more exact than the wording, so it stands. - let metadata = claude_limit_metadata( + // bridge names is more exact than the wording, so it stands; the reset + // the message prints fills in the one the info left out. + let mut metadata = claude_limit_metadata( Some(serde_json::json!({ "status": "rejected", "rateLimitType": "seven_day_opus" })), None, ); let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-24T15:46:00.000Z") + ); + assert_eq!(details.kind.as_deref(), Some("seven_day_opus")); + + // With no reset printed either, there is none. + metadata["acp"]["promptError"]["message"] = + serde_json::json!("Internal error: You've hit your Opus limit"); + let details = recovery("Prompt failed", Some(&metadata)); assert_eq!(details.resets_at, None); assert_eq!(details.kind.as_deref(), Some("seven_day_opus")); } #[test] fn the_wording_of_a_reached_usage_limit_names_the_kind() { + // With the reset each prints, where it prints one this reads, as the + // end of its printed minute. + for (message, resets_at) in [ + ( + "Internal error: You've hit your session limit · resets 3:45pm (UTC)", + Some("2026-06-24T15:46:00.000Z"), + ), + ( + "Internal error: You've hit your weekly limit · resets Jun 30, 7pm (UTC)", + Some("2026-06-30T19:01:00.000Z"), + ), + ( + "Internal error: You've hit your Opus limit · resets Jun 30, 7pm (UTC)", + Some("2026-06-30T19:01:00.000Z"), + ), + ("Internal error: You\u{2019}ve hit your session limit", None), + ("Internal error: You've reached your weekly limit", None), + ( + "Internal error: You're out of extra usage · resets 3:45pm (UTC)", + Some("2026-06-24T15:46:00.000Z"), + ), + ( + "Internal error: Claude usage limit reached. Your limit will reset at 3pm (UTC).", + None, + ), + ] { + let metadata = prompt_error("rate_limit", message); + let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!(details.resets_at.as_deref(), resets_at, "{message}"); + assert_eq!(details.kind.as_deref(), Some("usage_limit"), "{message}"); + } +} + +#[test] +fn the_printed_reset_of_a_bare_error_is_read_in_its_zone() { + // The two formats a freshly started Claude process refuses a prompt + // with, captured on 2026-12-03 (16:02:55 AEDT). Each reset is the end + // of its printed minute. + const NOW_MILLIS: i64 = 1_796_274_175_896; + for (message, resets_at) in [ + ( + "Internal error: You've hit your 5-hour limit · resets 4:10pm (Australia/Melbourne)", + "2026-12-03T05:11:00.000Z", + ), + ( + "Internal error: You've hit your weekly limit · resets Dec 4 at 2am (Australia/Melbourne)", + "2026-12-03T15:01:00.000Z", + ), + ] { + let metadata = prompt_error("rate_limit", message); + let details = rate_limit_recovery_details("Prompt failed", Some(&metadata), NOW_MILLIS); + assert_eq!(details.resets_at.as_deref(), Some(resets_at), "{message}"); + assert_eq!(details.kind.as_deref(), Some("usage_limit"), "{message}"); + } +} + +#[test] +fn a_structured_reset_wins_over_the_printed_one() { + // The message prints 5pm; the info the turn left behind says 15:45. + let message = "Internal error: You've hit your session limit · resets 5pm (UTC)"; + let reported = serde_json::json!({ + "status": "rejected", + "resetsAt": 1_782_315_900, + "rateLimitType": "five_hour", + }); + + // On the prompt error, and on the usage update alone. + for metadata in [ + claude_limit_metadata(Some(reported.clone()), None), + claude_limit_metadata(None, Some(reported.clone())), + ] { + let mut metadata = metadata; + metadata["acp"]["promptError"]["message"] = serde_json::json!(message); + let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-24T15:45:00.000Z") + ); + assert_eq!(details.kind.as_deref(), Some("five_hour")); + } + + // And a reset on the error's own data. + let mut metadata = prompt_error("rate_limit", message); + metadata["acp"]["promptError"]["data"]["resetsAt"] = serde_json::json!(1_782_315_900); + let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-24T15:45:00.000Z") + ); +} + +#[test] +fn a_structured_reset_already_past_gives_way_to_a_printed_one_ahead() { + // A stale `rejected` info whose reset (14:30) is half an hour past, + // with a message printing a reset still ahead (5pm). + let stale = serde_json::json!({ + "status": "rejected", + "resetsAt": 1_782_311_400, + "rateLimitType": "five_hour", + }); + let with_message = |message: &str| { + let mut metadata = claude_limit_metadata(Some(stale.clone()), None); + metadata["acp"]["promptError"]["message"] = serde_json::json!(message); + metadata + }; + + let metadata = with_message("Internal error: You've hit your session limit · resets 5pm (UTC)"); + let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-24T17:01:00.000Z") + ); + // The info's limit type went stale with its reset, so the kind is the + // wording's. + assert_eq!(details.kind.as_deref(), Some("usage_limit")); + + // A printed reset that has passed too, or none that can be read, leaves + // the structured one. for message in [ - "Internal error: You've hit your session limit · resets 3:45pm (UTC)", - "Internal error: You've hit your weekly limit · resets Jun 30, 7pm (UTC)", - "Internal error: You've hit your Opus limit · resets Jun 30, 7pm (UTC)", - "Internal error: You\u{2019}ve hit your session limit", - "Internal error: You've reached your weekly limit", - "Internal error: You're out of extra usage · resets 3:45pm (UTC)", - "Internal error: Claude usage limit reached. Your limit will reset at 3pm (UTC).", + "Internal error: You've hit your session limit · resets 2:30pm (UTC)", + "Internal error: You've hit your session limit · resets 5pm (Nowhere/Special)", + "Internal error: You've hit your session limit", + ] { + let metadata = with_message(message); + let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-24T14:30:00.000Z"), + "{message}" + ); + // Kept with its reset, the info's limit type stands too. + assert_eq!(details.kind.as_deref(), Some("five_hour"), "{message}"); + } +} + +#[test] +fn a_printed_reset_replacing_a_stale_one_does_not_take_the_stale_limit_type() { + // A stale five-hour info (its 14:30 reset half an hour past) beside a + // message printing the weekly reset: the reset is the printed one, and + // the kind must not name the five-hour window it no longer belongs to. + let stale = serde_json::json!({ + "status": "rejected", + "resetsAt": 1_782_311_400, + "rateLimitType": "five_hour", + }); + // On the prompt error, and on the usage update alone. + for metadata in [ + claude_limit_metadata(Some(stale.clone()), None), + claude_limit_metadata(None, Some(stale.clone())), + ] { + let mut metadata = metadata; + metadata["acp"]["promptError"]["message"] = serde_json::json!( + "Internal error: You've hit your weekly limit · resets Jun 30, 7pm (UTC)" + ); + let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-30T19:01:00.000Z") + ); + assert_eq!(details.kind.as_deref(), Some("usage_limit")); + } +} + +#[test] +fn the_grace_boundary_of_a_printed_reset_falls_back_safely() { + // 59 minutes after the printed 2pm (UTC), either form is still that + // reset, as the end of its minute; the scheduler sends it to the + // minute-scale backoff. + const WITHIN: i64 = RESET_TEST_NOW_MILLIS - 60_000; + // 61 minutes after it, either form rolls to its next occurrence, and + // both are dropped: the date a year ahead is past any allowance, and the + // time of day a day ahead is further than a session limit resets. + const BEYOND: i64 = RESET_TEST_NOW_MILLIS + 60_000; + for message in [ + "Internal error: You've hit your session limit · resets 2pm (UTC)", + "Internal error: You've hit your weekly limit · resets Jun 24 at 2pm (UTC)", + ] { + let metadata = prompt_error("rate_limit", message); + + let details = rate_limit_recovery_details("Prompt failed", Some(&metadata), WITHIN); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-24T14:01:00.000Z"), + "{message}" + ); + + let details = rate_limit_recovery_details("Prompt failed", Some(&metadata), BEYOND); + assert_eq!(details.resets_at, None, "{message}"); + assert_eq!(details.kind.as_deref(), Some("usage_limit"), "{message}"); + } +} + +#[test] +fn a_printed_reset_that_cannot_be_used_falls_back_to_none() { + for message in [ + // A zone the database does not know. + "Internal error: You've hit your session limit · resets 3:45pm (Nowhere/Special)", + // Not a time. + "Internal error: You've hit your session limit · resets soon (UTC)", + // A date two weeks past is next year's, far beyond any allowance. + "Internal error: You've hit your weekly limit · resets Jun 10 at 7pm (UTC)", ] { let metadata = prompt_error("rate_limit", message); let details = recovery("Prompt failed", Some(&metadata)); assert_eq!(details.resets_at, None, "{message}"); assert_eq!(details.kind.as_deref(), Some("usage_limit"), "{message}"); } + + // An overloaded provider is never a usage limit, so its text is not + // read for a reset either. + let metadata = prompt_error( + "overloaded", + "Internal error: You've hit your session limit · resets 3:45pm (UTC)", + ); + let details = recovery("Prompt failed", Some(&metadata)); + assert_eq!(details.resets_at, None); + assert_eq!(details.kind.as_deref(), Some("overloaded")); } #[test] @@ -116,7 +330,10 @@ fn a_bare_status_gives_way_to_the_wording() { let details = recovery("Prompt failed", Some(&metadata)); - assert_eq!(details.resets_at, None); + assert_eq!( + details.resets_at.as_deref(), + Some("2026-06-24T15:46:00.000Z") + ); assert_eq!(details.kind.as_deref(), Some("usage_limit")); } diff --git a/apps/staged/src-tauri/src/session_runner/usage_limit_reset.rs b/apps/staged/src-tauri/src/session_runner/usage_limit_reset.rs new file mode 100644 index 000000000..aa9ebe336 --- /dev/null +++ b/apps/staged/src-tauri/src/session_runner/usage_limit_reset.rs @@ -0,0 +1,543 @@ +//! The reset time a Claude usage-limit message prints, for a failure that +//! reported no structured one. +//! +//! A turn refused by a freshly started agent process never reaches the API, +//! so the SDK sends no `rate_limit_event` and the bridge has no +//! `rateLimit` to put on the error: the error is a bare +//! `{ errorKind: "rate_limit" }`. That is every message sent to an idle +//! session while over the limit and every refused auto-resume, since each +//! starts a new process. The CLI's message still names the reset, in the +//! account's zone: +//! +//! - `You've hit your 5-hour limit · resets 4:10pm (Australia/Melbourne)`: +//! a time of day, the next occurrence of it in that zone; +//! - `You've hit your weekly limit · resets Dec 3 at 2am (Australia/Melbourne)`: +//! a date and a time, with no year. +//! +//! The date may also be followed by a comma instead of `at` +//! (`resets Jun 30, 7pm (UTC)`). + +use std::sync::OnceLock; + +use jiff::civil::{Date, DateTime}; +use jiff::tz::TimeZone; +use jiff::Timestamp; + +/// How far in the past a printed reset may sit and still be read as that +/// reset rather than as its next occurrence. +/// +/// The CLI refuses a prompt only while its saved reset is ahead, so a +/// printed reset is in the past only by its truncation to the minute, clock +/// skew, or the time the error took to be handled. A just-passed reset +/// leaves the pause on the minute-scale backoff, since its window is due to +/// have reopened, where the next day's occurrence would park it for a day. +/// +/// A reset further past than this (the CLI's clock more than an hour behind +/// Staged's, say on a workstation, or its saved state stale) is rolled to +/// its next occurrence, and the two formats then fail differently: +/// +/// - a date (`Dec 3 at 2am`) rolls a year ahead, past any allowance, so the +/// reset is dropped and the pause takes the slow schedule a usage limit +/// with no reset gets (40–50 min); +/// - a time of day (`4:10pm`) rolls a day ahead, which is within the +/// allowance, and would park the pause for about 22 hours. So a time of +/// day more than [`TIME_OF_DAY_MAX_LEAD_MS`] ahead is dropped the same +/// way, unless the message names a long window (see +/// [`names_a_long_window`]). This fails closed: any wording not known to +/// be a weekly or model-specific limit (`5-hour`, `session`, a bare +/// `You've hit your limit`, a future rewording) is held to the five-hour +/// window, so a wording miss costs the slow schedule's extra attempts, +/// not a day. The cost runs the other way for a long window printed with a +/// time alone: a weekly limit cannot be told from its next-day occurrence +/// and keeps the day's wait, and one in a wording not recognised as long, +/// 6–24 hours ahead, takes the slow schedule instead of its reset. +/// +/// A wider grace would keep more of those past resets, but would also read +/// a time-of-day reset that is genuinely almost a day ahead as just passed. +const JUST_PASSED_GRACE_MS: i64 = 60 * 60_000; + +/// The furthest ahead a time-of-day reset is trusted unless the message +/// names a long window: the five-hour window, with an hour to spare for +/// clock skew and DST. Further than this it is taken for a past reset +/// rolled to the next day (see [`JUST_PASSED_GRACE_MS`]). +const TIME_OF_DAY_MAX_LEAD_MS: i64 = 6 * 60 * 60_000; + +/// A printed reset is truncated to the minute, so the real one can fall up +/// to a minute after it (`4:10pm` for 16:10:45). The reset is taken as the +/// end of its printed minute, so a retry scheduled just after it cannot land +/// before the window reopens; a CLI that rounds instead costs the wait at +/// most a minute. +const PRINTED_MINUTE_MS: i64 = 60_000; + +/// The reset `message` prints, as UTC millis, when it has one in either +/// format and names a zone the timezone database knows. +/// +/// That is the end of the printed minute (see [`PRINTED_MINUTE_MS`]) of the +/// instant [`printed_reset`] reads. A time of day more than +/// [`TIME_OF_DAY_MAX_LEAD_MS`] ahead gives `None` unless the message names a +/// long window, as does anything [`printed_reset`] cannot read. +/// The caller still checks the result against the allowance for the limit's +/// kind. +pub(super) fn reset_millis_from_usage_limit_message(message: &str, now_millis: i64) -> Option { + let printed = printed_reset(message, now_millis)?; + let reset_millis = printed.millis.checked_add(PRINTED_MINUTE_MS)?; + let implausibly_far = !printed.has_date + && !names_a_long_window(message) + && reset_millis.saturating_sub(now_millis) > TIME_OF_DAY_MAX_LEAD_MS; + (!implausibly_far).then_some(reset_millis) +} + +/// A reset as printed, to the minute. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct PrintedReset { + /// The instant the printed wall-clock time names, in UTC millis. + millis: i64, + /// Whether the message printed a date, not a time of day alone. + has_date: bool, +} + +/// The instant the reset in `message` names, when it has one in either +/// format and names a zone the timezone database knows. +/// +/// Of the instants the printed wall-clock time can mean (the day before, +/// that day or the day after for a time of day; the year before, that year +/// or the year after for a date), the earliest one no more than +/// [`JUST_PASSED_GRACE_MS`] in the past is taken: the next occurrence, or +/// one that has only just passed. A time that falls in a DST gap is moved +/// forward by the gap, and one that is repeated takes its first occurrence +/// (jiff's `compatible` disambiguation). +/// +/// `None` for text with no reset in these formats, an impossible time or +/// date, or an unknown zone. +fn printed_reset(message: &str, now_millis: i64) -> Option { + let captures = reset_pattern().captures(message)?; + let hour12: i8 = captures.name("hour")?.as_str().parse().ok()?; + let minute: i8 = captures + .name("minute") + .map_or(Some(0), |minute| minute.as_str().parse().ok())?; + if !(1..=12).contains(&hour12) || !(0..=59).contains(&minute) { + return None; + } + let pm = captures + .name("meridiem")? + .as_str() + .eq_ignore_ascii_case("pm"); + let hour = hour12 % 12 + if pm { 12 } else { 0 }; + let zone = TimeZone::get(captures.name("zone")?.as_str()).ok()?; + + let now = Timestamp::from_millisecond(now_millis).ok()?; + let today = now.to_zoned(zone.clone()).date(); + let has_date = captures.name("month").is_some() && captures.name("day").is_some(); + let candidate_dates: Vec = match (captures.name("month"), captures.name("day")) { + (Some(month), Some(day)) => { + let month = month_number(month.as_str())?; + let day: i8 = day.as_str().parse().ok()?; + [-1, 0, 1] + .into_iter() + .filter_map(|offset| Date::new(today.year().checked_add(offset)?, month, day).ok()) + .collect() + } + _ => [today.yesterday().ok(), Some(today), today.tomorrow().ok()] + .into_iter() + .flatten() + .collect(), + }; + + let earliest_accepted = now_millis.saturating_sub(JUST_PASSED_GRACE_MS); + candidate_dates + .into_iter() + .filter_map(|date| { + let wall_clock: DateTime = date.at(hour, minute, 0, 0); + wall_clock.to_zoned(zone.clone()).ok() + }) + .map(|zoned| zoned.timestamp().as_millisecond()) + .filter(|millis| *millis >= earliest_accepted) + .min() + .map(|millis| PrintedReset { millis, has_date }) +} + +/// Whether `message` names a limit whose window runs longer than a day, so +/// a time-of-day reset up to a day ahead is plausible: the weekly limit +/// (`You've hit your weekly limit`, `7-day`) or a model-specific one +/// (`... your Opus limit`, `... your Sonnet limit`), both seven-day windows. +/// +/// Anything else, a 5-hour or session limit or a wording not listed here, is +/// treated as the five-hour window (see [`JUST_PASSED_GRACE_MS`]). +fn names_a_long_window(message: &str) -> bool { + let message = message.to_lowercase(); + [ + "week", + "7-day", + "7 day", + "seven-day", + "seven day", + "opus", + "sonnet", + ] + .iter() + .any(|wording| message.contains(wording)) +} + +/// `resets`, then an optional ` ` followed by a comma or `at`, a +/// 12-hour time with optional minutes, and the IANA zone in parentheses. +fn reset_pattern() -> &'static regex::Regex { + static PATTERN: OnceLock = OnceLock::new(); + PATTERN.get_or_init(|| { + regex::Regex::new( + r"(?ix) + \bresets\s+ + (?: + (?Pjan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+ + (?P\d{1,2})(?:st|nd|rd|th)? + (?:\s*,\s*|\s+)(?:at\s+)? + )? + (?P\d{1,2})(?::(?P\d{2}))?\s*(?Pam|pm) + \s*\(\s*(?P[A-Za-z0-9_+\-/]+)\s*\)", + ) + .expect("the reset pattern compiles") + }) +} + +fn month_number(name: &str) -> Option { + let prefix = name.get(..3)?.to_ascii_lowercase(); + let index = [ + "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", + ] + .iter() + .position(|month| *month == prefix)?; + i8::try_from(index + 1).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A UTC instant in millis. + fn utc(text: &str) -> i64 { + text.parse::().unwrap().as_millisecond() + } + + fn rfc3339(millis: i64) -> String { + Timestamp::from_millisecond(millis).unwrap().to_string() + } + + /// The instant the reset `message` prints names at `now`, as an RFC3339 + /// UTC instant. + fn reset_at(message: &str, now: &str) -> Option { + printed_reset(message, utc(now)).map(|reset| rfc3339(reset.millis)) + } + + /// The reset `message` gives at `now` once rounded up and checked, as an + /// RFC3339 UTC instant. + fn rounded_reset_at(message: &str, now: &str) -> Option { + reset_millis_from_usage_limit_message(message, utc(now)).map(rfc3339) + } + + const MELBOURNE_LIMIT: &str = + "Internal error: You've hit your 5-hour limit · resets 4:10pm (Australia/Melbourne)"; + + #[test] + fn a_time_of_day_is_its_next_occurrence_in_the_zone() { + // 16:02:55 AEDT (UTC+11) on 2026-12-03, as in the support report. + assert_eq!( + reset_at(MELBOURNE_LIMIT, "2026-12-03T05:02:55Z").as_deref(), + Some("2026-12-03T05:10:00Z") + ); + } + + #[test] + fn a_time_of_day_without_minutes_is_on_the_hour() { + assert_eq!( + reset_at( + "You've hit your 5-hour limit · resets 4pm (Australia/Melbourne)", + "2026-12-03T02:00:00Z" + ) + .as_deref(), + Some("2026-12-03T05:00:00Z") + ); + } + + #[test] + fn twelve_am_is_midnight_and_twelve_pm_is_noon() { + let now = "2026-06-24T08:00:00Z"; + assert_eq!( + reset_at("resets 12pm (UTC)", now).as_deref(), + Some("2026-06-24T12:00:00Z") + ); + assert_eq!( + reset_at("resets 12:30pm (UTC)", now).as_deref(), + Some("2026-06-24T12:30:00Z") + ); + assert_eq!( + reset_at("resets 12am (UTC)", now).as_deref(), + Some("2026-06-25T00:00:00Z") + ); + assert_eq!( + reset_at("resets 12:10am (UTC)", now).as_deref(), + Some("2026-06-25T00:10:00Z") + ); + assert_eq!( + reset_at("resets 11:59am (UTC)", now).as_deref(), + Some("2026-06-24T11:59:00Z") + ); + assert_eq!( + reset_at("resets 1am (UTC)", "2026-06-24T00:30:00Z").as_deref(), + Some("2026-06-24T01:00:00Z") + ); + } + + #[test] + fn a_time_of_day_already_past_is_the_next_day() { + // 23:30 in Melbourne: a 12:10am reset is the next calendar day there. + assert_eq!( + reset_at( + "You've hit your 5-hour limit · resets 12:10am (Australia/Melbourne)", + "2026-12-03T12:30:00Z" + ) + .as_deref(), + Some("2026-12-03T13:10:00Z") + ); + // Well past today's 4:10pm: tomorrow's. + assert_eq!( + reset_at(MELBOURNE_LIMIT, "2026-12-03T08:00:00Z").as_deref(), + Some("2026-12-04T05:10:00Z") + ); + } + + #[test] + fn a_time_of_day_that_just_passed_stays_today() { + // Three minutes after the reset: the window is due to have reopened, + // not to reset again tomorrow. + assert_eq!( + reset_at(MELBOURNE_LIMIT, "2026-12-03T05:13:00Z").as_deref(), + Some("2026-12-03T05:10:00Z") + ); + } + + #[test] + fn the_grace_for_a_just_passed_reset_is_an_hour_for_either_form() { + // 4:10pm AEDT is 05:10Z. 59 minutes past it is still that reset; + // 61 minutes past it is the next occurrence. + const DATED: &str = + "You've hit your weekly limit · resets Dec 3 at 4:10pm (Australia/Melbourne)"; + let within = "2026-12-03T06:09:00Z"; + let beyond = "2026-12-03T06:11:00Z"; + + assert_eq!( + reset_at(MELBOURNE_LIMIT, within).as_deref(), + Some("2026-12-03T05:10:00Z") + ); + assert_eq!( + reset_at(MELBOURNE_LIMIT, beyond).as_deref(), + Some("2026-12-04T05:10:00Z") + ); + + assert_eq!( + reset_at(DATED, within).as_deref(), + Some("2026-12-03T05:10:00Z") + ); + assert_eq!( + reset_at(DATED, beyond).as_deref(), + Some("2027-12-03T05:10:00Z") + ); + } + + #[test] + fn a_reset_is_taken_as_the_end_of_its_printed_minute() { + // `4:10pm` may stand for 16:10:45: the retry must not land before + // that, so the reset is 16:11:00. + assert_eq!( + rounded_reset_at(MELBOURNE_LIMIT, "2026-12-03T05:02:55Z").as_deref(), + Some("2026-12-03T05:11:00Z") + ); + assert_eq!( + rounded_reset_at( + "You've hit your weekly limit · resets Dec 4 at 2am (Australia/Melbourne)", + "2026-12-03T05:02:55Z" + ) + .as_deref(), + Some("2026-12-03T15:01:00Z") + ); + // A just-passed reset is rounded too, and may land a moment ahead. + assert_eq!( + rounded_reset_at(MELBOURNE_LIMIT, "2026-12-03T05:10:30Z").as_deref(), + Some("2026-12-03T05:11:00Z") + ); + } + + #[test] + fn a_time_of_day_more_than_six_hours_ahead_is_dropped() { + // More than an hour past, today's 4:10pm rolls to tomorrow's. The + // five-hour window never resets that far ahead, so it is dropped + // rather than parking the pause for a day: for a 5-hour or session + // limit, and for any wording that does not name a long window. + let now = "2026-12-03T06:11:00Z"; + for message in [ + MELBOURNE_LIMIT, + "You've hit your session limit · resets 4:10pm (Australia/Melbourne)", + "You've hit your limit · resets 4:10pm (Australia/Melbourne)", + "You've hit your limit · resets 4pm (Australia/Melbourne)", + "You're out of extra usage · resets 4:10pm (Australia/Melbourne)", + ] { + assert_eq!(rounded_reset_at(message, now), None, "{message}"); + } + // Six hours ahead once rounded is kept; a minute more is not. + assert_eq!( + rounded_reset_at(MELBOURNE_LIMIT, "2026-12-02T23:11:00Z").as_deref(), + Some("2026-12-03T05:11:00Z") + ); + assert_eq!( + rounded_reset_at(MELBOURNE_LIMIT, "2026-12-02T23:10:00Z"), + None + ); + } + + #[test] + fn a_bare_limit_time_of_day_within_six_hours_is_kept() { + // The cap only drops a reset implausibly far ahead; a bare wording's + // reset an hour ahead is read as usual. + assert_eq!( + rounded_reset_at( + "You've hit your limit · resets 4pm (Australia/Melbourne)", + "2026-12-03T04:00:00Z" + ) + .as_deref(), + Some("2026-12-03T05:01:00Z") + ); + } + + #[test] + fn a_long_window_time_of_day_is_not_held_to_six_hours() { + let now = "2026-12-03T06:11:00Z"; + // A weekly or model-specific limit printed with a time alone keeps + // the next day's. + for message in [ + "You've hit your weekly limit · resets 4:10pm (Australia/Melbourne)", + "You've hit your Opus limit · resets 4:10pm (Australia/Melbourne)", + "You've hit your Sonnet limit · resets 4:10pm (Australia/Melbourne)", + ] { + assert_eq!( + rounded_reset_at(message, now).as_deref(), + Some("2026-12-04T05:11:00Z"), + "{message}" + ); + } + // A session limit printed with a date is not a rolled time of day. + assert_eq!( + rounded_reset_at( + "You've hit your session limit · resets Dec 4 at 4:10pm (Australia/Melbourne)", + now + ) + .as_deref(), + Some("2026-12-04T05:11:00Z") + ); + } + + #[test] + fn a_date_and_time_is_read_in_the_zone() { + assert_eq!( + reset_at( + "You've hit your weekly limit · resets Dec 3 at 2am (Australia/Melbourne)", + "2026-11-28T00:00:00Z" + ) + .as_deref(), + Some("2026-12-02T15:00:00Z") + ); + assert_eq!( + reset_at( + "You've hit your weekly limit · resets Dec 3 at 2:30pm (Australia/Melbourne)", + "2026-11-28T00:00:00Z" + ) + .as_deref(), + Some("2026-12-03T03:30:00Z") + ); + // The comma form, and a full month name. + assert_eq!( + reset_at( + "You've hit your weekly limit · resets Jun 30, 7pm (UTC)", + "2026-06-24T15:00:00Z" + ) + .as_deref(), + Some("2026-06-30T19:00:00Z") + ); + assert_eq!( + reset_at("resets June 30 at 7pm (UTC)", "2026-06-24T15:00:00Z").as_deref(), + Some("2026-06-30T19:00:00Z") + ); + } + + #[test] + fn a_date_takes_the_year_of_its_nearest_occurrence_across_new_year() { + // Late December: a January reset is next year's. + assert_eq!( + reset_at("resets Jan 2 at 2am (UTC)", "2026-12-30T10:00:00Z").as_deref(), + Some("2027-01-02T02:00:00Z") + ); + // Early January: a reset on Dec 31 that just passed is last year's, + // not the one almost a year ahead. + assert_eq!( + reset_at("resets Dec 31 at 11:30pm (UTC)", "2027-01-01T00:10:00Z").as_deref(), + Some("2026-12-31T23:30:00Z") + ); + // And one still ahead in the same December is this year's. + assert_eq!( + reset_at("resets Dec 31 at 11:30pm (UTC)", "2026-12-28T00:00:00Z").as_deref(), + Some("2026-12-31T23:30:00Z") + ); + } + + #[test] + fn a_time_in_a_dst_gap_moves_forward_by_the_gap() { + // Melbourne skipped 2am–3am on 2026-10-04 (AEST to AEDT). + assert_eq!( + reset_at( + "resets Oct 4 at 2:30am (Australia/Melbourne)", + "2026-10-01T00:00:00Z" + ) + .as_deref(), + Some("2026-10-03T16:30:00Z") + ); + // And repeated 2am–3am on 2026-04-05 (AEDT to AEST): the first one. + assert_eq!( + reset_at( + "resets Apr 5 at 2:30am (Australia/Melbourne)", + "2026-04-01T00:00:00Z" + ) + .as_deref(), + Some("2026-04-04T15:30:00Z") + ); + } + + #[test] + fn an_unknown_zone_gives_no_reset() { + assert_eq!( + reset_at( + "You've hit your 5-hour limit · resets 4:10pm (Mars/Olympus_Mons)", + "2026-12-03T05:02:55Z" + ), + None + ); + } + + #[test] + fn text_without_a_reset_in_these_formats_gives_none() { + let now = "2026-12-03T05:02:55Z"; + for message in [ + "", + "You've hit your 5-hour limit", + "You've hit your 5-hour limit · resets 4:10pm", + "You've hit your 5-hour limit · resets 16:10 (Australia/Melbourne)", + "You've hit your 5-hour limit · resets soon (Australia/Melbourne)", + "Claude usage limit reached. Your limit will reset at 3pm (UTC).", + "resets 13pm (UTC)", + "resets 0am (UTC)", + "resets 4:75pm (UTC)", + "resets Feb 30 at 2am (UTC)", + "resets Foo 3 at 2am (UTC)", + "presets 4pm (UTC)", + "\u{1F4A5} resets \u{00B7}\u{00B7} (\u{00B7})", + ] { + assert_eq!(reset_at(message, now), None, "{message}"); + } + } +}