Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agents): say a spent usage allowance, a full context window and a restart as what they are (#968)
Ruben Lütke880c91a444f4
diff --git a/dodaios/agent_chat/runner_acp.py b/dodaios/agent_chat/runner_acp.pyindex 1e359bdc35..0e7c8cde72 100644--- a/dodaios/agent_chat/runner_acp.py+++ b/dodaios/agent_chat/runner_acp.py@@ -389,5 +389,6 @@ def _plan(acp=acp,after_turn=release,provider_failure=failure,+ failure_probe=getattr(launch, "failure_probe", None),proc=launch.proc,)diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.pyindex 431614d3ce..66c1b75c46 100644--- a/dodaios/agent_chat/runner_cli.py+++ b/dodaios/agent_chat/runner_cli.py@@ -568,6 +568,9 @@ class CliPlan:after_turn: Callable[[], None] | None = None#: The local gateway knows failures that a runtime may render as prose.provider_failure: Future[str] | None = None+ #: Why a turn that ended without an answer failed, from the runtime's own+ #: log (``RuntimeLaunch.failure_probe``), given the turn's wall-clock start.+ failure_probe: Callable[[float], str] | None = None#: A process that is already running (an agent runtime's warm process,#: ``agent_runtimes.warm.Lease``): driven instead of spawning ``argv``.#: Its owner contains it, so the turn adds no process tree of its own.@@ -4374,6 +4377,16 @@ async def _drive_cli(if swallowed := gateway.last_failure(plan.provider_failure):status, error_text = "error", swallowed+ elif plan.failure_probe is not None:+ # The runtime ended a failed run like a finished one (no HTTP+ # error ever reached the gateway): its own log says why.+ try:+ probed = await asyncio.to_thread(plan.failure_probe, started_at)+ except Exception: # noqa: BLE001 — a probe never decides more than the reason+ log.debug("agent chat %s: failure probe failed", handle.turn_id, exc_info=True)+ probed = ""+ if probed:+ status, error_text = "error", probedusage = dict(state.usage)cost_usd = getattr(state, "cost_usd", None)diff --git a/dodaios/agent_chat/task_recovery.py b/dodaios/agent_chat/task_recovery.pyindex b90d0d98ed..582ecee67e 100644--- a/dodaios/agent_chat/task_recovery.py+++ b/dodaios/agent_chat/task_recovery.py@@ -38,6 +38,7 @@ _TERMINAL = ("quota","credit balance","http 429",+ "usage limit","rate limit","rate-limited",)diff --git a/dodaios/agent_runtimes/base.py b/dodaios/agent_runtimes/base.pyindex be36fc19fa..97e5c98f27 100644--- a/dodaios/agent_runtimes/base.py+++ b/dodaios/agent_runtimes/base.py@@ -202,6 +202,11 @@ class RuntimeLaunch:#: Replies the runtime itself posts as the assistant's message when a turn#: fails before any model call (``acp.AcpTurn.failure_replies``).failure_replies: tuple[re.Pattern[str], ...] = ()+ #: Why a turn that started at the given wall-clock time (``time.time()``)+ #: ended without an answer, from the runtime's own log ("" = unknown).+ #: For a runtime that ends a failed run like a finished one over ACP+ #: (OpenClaw after a context overflow it could not recover from).+ failure_probe: Callable[[float], str] | None = Noneclass AgentRuntimeDriver(Protocol):diff --git a/dodaios/agent_runtimes/gateway.py b/dodaios/agent_runtimes/gateway.pyindex f056152d1a..85e4efadf4 100644--- a/dodaios/agent_runtimes/gateway.py+++ b/dodaios/agent_runtimes/gateway.py@@ -113,7 +113,10 @@ _FAILURES: dict[Grant, Future[str]] = {}#: answer, the runner reports this instead of a silent empty turn._LAST_FAILURES: weakref.WeakKeyDictionary[Future[str], str] = weakref.WeakKeyDictionary()_TURN_EFFORTS: dict[Grant, str] = {}-_COOLDOWNS: OrderedDict[tuple[str, str, str], float] = OrderedDict()+#: Per (provider, account, model): until when calls are refused, why+#: (``rate_limited`` / ``usage_limit``) and whether the provider named that+#: time (a usage limit's reset is only told when it did).+_COOLDOWNS: OrderedDict[tuple[str, str, str], tuple[float, str, bool]] = OrderedDict()_DEFAULT_COOLDOWN_S: Final = 30.0#: Gemini's thought signature per tool call id: the OpenAI wire shape has no@@ -529,9 +532,27 @@ def whole_seconds(seconds: float) -> int:return max(0, math.ceil(round(seconds, 3)))-def _limited(provider: str, seconds: float) -> GatewayError:+def _limited(+ provider: str, seconds: float, *, code: str = "rate_limited", known: bool = True,+) -> GatewayError:+ if code == "usage_limit":+ # A spent allowance: no "try again in 30 s" — it is back when it+ # resets, which is only told when the provider said when.+ from dodaios.agent_runtimes.provider_errors import usage_limit_message++ return GatewayError(+ usage_limit_message(provider, seconds if known else None),+ status=429,+ code="usage_limit",+ retry_after=seconds,+ )+ from dodaios.agent_runtimes.provider_errors import provider_label++ # Named by label ("The ChatGPT subscription", not "openai-codex"): the chat+ # reads a stored "openai-codex returned HTTP 429" as a spent allowance.return GatewayError(- f"{provider} returned HTTP 429 (rate limit). Try again in {whole_seconds(seconds)} s, "+ f"{provider_label(provider)} returned HTTP 429 (rate limit). "+ f"Try again in {whole_seconds(seconds)} s, ""or choose another connected model in the agent's settings. ""No fallback provider was called.",status=429,@@ -544,11 +565,12 @@ def check_cooldown(provider: str, model: str, account_id: str = "") -> None:"""Reject early, without spawning a runtime or spending another model call."""key = (provider, account_id, model)with _LOCK:- remaining = _COOLDOWNS.get(key, 0.0) - time.monotonic()+ until, code, known = _COOLDOWNS.get(key, (0.0, "rate_limited", True))+ remaining = until - time.monotonic()if remaining <= 0:_COOLDOWNS.pop(key, None)if remaining > 0:- raise _limited(provider, remaining)+ raise _limited(provider, remaining, code=code, known=known)def _report_failure(@@ -558,17 +580,22 @@ def _report_failure(signal: Future[str] | None,) -> GatewayError:if failure.status == 429:- seconds = failure.retry_after if failure.retry_after is not None else _DEFAULT_COOLDOWN_S+ code = "usage_limit" if failure.code == "usage_limit" else "rate_limited"+ known = failure.retry_after is not None+ seconds = failure.retry_after if known else _DEFAULT_COOLDOWN_Skey = (grant.provider, grant.account_id, model)with _LOCK:now = time.monotonic()- until = max(_COOLDOWNS.get(key, 0.0), now + seconds)- seconds = until - now- _COOLDOWNS[key] = until+ before, before_code, before_known = _COOLDOWNS.get(key, (0.0, code, known))+ if before > now + seconds:+ seconds, known = before - now, before_known+ code = "usage_limit" if "usage_limit" in (code, before_code) else code+ until = now + seconds+ _COOLDOWNS[key] = (until, code, known)_COOLDOWNS.move_to_end(key)while len(_COOLDOWNS) > 512:_COOLDOWNS.popitem(last=False)- failure = _limited(grant.provider, seconds)+ failure = _limited(grant.provider, seconds, code=code, known=known)from dodaios.agent_runtimes.provider_errors import is_terminalif signal is not None and not is_terminal(failure.code):@@ -1108,7 +1135,9 @@ def _failure(provider: str, exc: Exception, model: str = "") -> GatewayError:refusal.message,status=refusal.status,code=refusal.code,- retry_after=_retry_after(exc) if refusal.code == "rate_limited" else None,+ retry_after=(+ _retry_after(exc) if refusal.code in ("rate_limited", "usage_limit") else None+ ),)diff --git a/dodaios/agent_runtimes/openclaw.py b/dodaios/agent_runtimes/openclaw.pyindex f57f228e91..9277c88cfc 100644--- a/dodaios/agent_runtimes/openclaw.py+++ b/dodaios/agent_runtimes/openclaw.py@@ -176,12 +176,85 @@ FAILURE_REPLIES: Final[tuple[re.Pattern[str], ...]] = (re.compile(r"^(Thinking level \"[^\"]*\" is not supported for \S+\. Use one of: .*)$"),)+#: What a turn that failed inside the Gateway reads as. OpenClaw's ACP bridge+#: ends an errored run like a finished one (``stopReason: end_turn``, no+#: text), so the reason is only in the Gateway's log.+CONTEXT_FULL_REASON: Final[str] = (+ "The conversation no longer fits this model's context window (context window "+ "exceeded). Start a fresh chat, or pick a model with a larger context window."+)+_RUN_FAILED: Final[re.Pattern[str]] = re.compile(r"\bisError=true\b.*?\brawError=(.+)$")+_OVERFLOW_GIVEN_UP: Final[tuple[str, ...]] = (+ "exhausted provider overflow recovery",+ "kind=context_overflow",+)+_OVERFLOW_WORDS: Final[tuple[str, ...]] = (+ "context window exceeded",+ "context overflow",+ "context length exceeded",+ "prompt too large",+)+#: How much of the end of the Gateway's log a failed turn reads.+_PROBE_TAIL_BYTES: Final[int] = 512 * 1024+_SECRET_SHAPES: Final[re.Pattern[str]] = re.compile(+ r"(sk-[A-Za-z0-9_\-]{6,}|AIza[0-9A-Za-z_\-]{10,}|[Bb]earer\s+[A-Za-z0-9._\-]{10,}"+ r"|eyJ[A-Za-z0-9._\-]{20,})"+)+_INSTALL_URL_PS1: Final[str] = "https://openclaw.ai/install.ps1"_INSTALL_URL_SH: Final[str] = "https://openclaw.ai/install.sh"#: OpenClaw's user-space installer: a private Node.js under ``--prefix``, no sudo._INSTALL_CLI_URL_SH: Final[str] = "https://openclaw.ai/install-cli.sh"+def run_failure(log_path: Path, since: float) -> str:+ """Why the Gateway's run for a turn started at ``since`` failed ("" = no failure logged).++ Reads the end of the Gateway's log: only lines stamped at or after the+ turn's start count. A context overflow the Gateway could not compact away+ reads as :data:`CONTEXT_FULL_REASON`; any other failed run as its own+ short reason, bounded and with key-shaped text masked.+ """+ import datetime as _dt++ try:+ with log_path.open("rb") as handle:+ handle.seek(0, os.SEEK_END)+ size = handle.tell()+ handle.seek(max(0, size - _PROBE_TAIL_BYTES))+ text = handle.read().decode("utf-8", errors="replace")+ except OSError: # no readable Gateway log: the caller keeps its generic reason+ return ""+ overflow = False+ failed = ""+ for line in text.splitlines():+ stamp, _, rest = line.partition(" ")+ try:+ at = _dt.datetime.fromisoformat(stamp).timestamp()+ except ValueError: # continuation line without a timestamp: not a turn event+ continue+ if at < since - 1.0:+ continue+ lowered = rest.lower()+ if any(marker in rest for marker in _OVERFLOW_GIVEN_UP):+ overflow = True+ continue+ match = _RUN_FAILED.search(rest)+ if match:+ raw = match.group(1).strip()+ if any(word in lowered for word in _OVERFLOW_WORDS):+ overflow = True+ failed = raw+ if overflow:+ return CONTEXT_FULL_REASON+ if not failed:+ return ""+ reason = _SECRET_SHAPES.sub("[redacted]", " ".join(failed.split()))+ if len(reason) > 240:+ reason = reason[:240].rstrip() + "…"+ return f"OpenClaw ended the run with an error: {reason}"++# ------------------------------------------------------------------ install@@ -809,6 +882,7 @@ class OpenClawRuntime:},prompt_meta=prompt_meta(turn),failure_replies=FAILURE_REPLIES,+ failure_probe=lambda since: run_failure(home / "gateway.log", since),)return launch, gatewaydiff --git a/dodaios/agent_runtimes/provider_errors.py b/dodaios/agent_runtimes/provider_errors.pyindex ecd60af31c..3f9f98b316 100644--- a/dodaios/agent_runtimes/provider_errors.py+++ b/dodaios/agent_runtimes/provider_errors.py@@ -8,6 +8,10 @@ here: it runs through the official Claude CLI, ``model_map``):* **No credits / no quota** on a key -> 402 ``billing`` (a runtime does notretry it; Hermes classifies 402 as billing and stops).+* **Usage limit reached** (a plan's allowance, such as a subscription's or a+ daily quota, is used up until it resets) -> 429 ``usage_limit``: never+ "try again in 30 s", but when the allowance resets, if known, and another+ connected model to use until then.* **Provider not reachable** (a local model server that is not running, nonetwork) -> 503 ``provider_unreachable``.* **Context too long** -> 400 ``context_length_exceeded`` with the words@@ -60,6 +64,26 @@ _BILLING_PHRASES: Final[tuple[str, ...]] = ("limit: 0,",)+#: Codes and wording of a plan's spent allowance (a subscription's usage+#: limit, a daily request quota): it comes back when the allowance resets,+#: not after a short wait. Matched on a 429 or a status-less error only.+_USAGE_LIMIT_CODES: Final[frozenset[str]] = frozenset(+ {+ "usage_limit_reached",+ "usage_limit_exceeded",+ "subscription_sharing_usage_limit_exceeded",+ }+)+_USAGE_LIMIT_PHRASES: Final[tuple[str, ...]] = (+ "usage limit",+ "usage_limit",+ "allowance resets",+ "requests per day",+ "perday",+ "daily limit",+ "daily quota",+)+#: Transport failures, by class name across the SDKs (openai, anthropic,#: httpx): the name is the stable capability signal, a class import is not.#: A connect failure means nothing answered; it is checked before the@@ -130,6 +154,7 @@ TERMINAL_CODES: Final[frozenset[str]] = frozenset("invalid_tool_schema","tools_unsupported","rate_limited",+ "usage_limit","incomplete",})@@ -216,6 +241,34 @@ def _label(provider: str) -> str:return _LABELS.get(provider, provider)+def provider_label(provider: str) -> str:+ """How ``provider`` is named in a message a person reads."""+ return _label(provider)+++def usage_limit_message(provider: str, reset_in: float | None = None) -> str:+ """A spent allowance in words a person can act on.++ ``reset_in`` is the seconds until the allowance resets when the provider+ said so; the reset is then named as a UTC time (``resets at+ 2026-10-27T15:04:00Z``), which the chat shows in the person's own clock.+ Never a short "try again in N s": waiting a moment does not help.+ """+ import datetime as _dt++ head = (+ f"{_label(provider)} reached its usage limit: the plan's allowance is used up "+ "until it resets"+ )+ if reset_in is not None and reset_in > 0:+ at = _dt.datetime.now(_dt.UTC) + _dt.timedelta(seconds=reset_in)+ head += f" (it resets at {at.strftime('%Y-%m-%dT%H:%M:%SZ')})"+ return (+ f"{head}. Until then, choose another connected model in the agent's settings. "+ "No fallback provider was called."+ )++def _class_names(exc: BaseException) -> set[str]:return {cls.__name__ for err in _chain(exc) for cls in type(err).__mro__}@@ -237,6 +290,10 @@ def classify(provider: str, exc: BaseException, model: str = "") -> Refusal | No"will not help. Top it up with the provider, or choose another connected ""model in the agent's settings.",)+ if status in (429, None) and (+ codes & _USAGE_LIMIT_CODES or any(phrase in text for phrase in _USAGE_LIMIT_PHRASES)+ ):+ return Refusal(429, "usage_limit", usage_limit_message(provider))if (status in (400, 413, 422) or status is None) and (codes & _OVERFLOW_CODES or any(phrase in text for phrase in _OVERFLOW_PHRASES)):@@ -311,7 +368,7 @@ def gateway_refusal(provider: str, exc: BaseException, model: str = "") -> Refusreturn foundstatus = _status(exc)if status == 429:- return Refusal(429, "rate_limited", f"{provider} returned HTTP 429 (rate limit).")+ return Refusal(429, "rate_limited", f"{_label(provider)} returned HTTP 429 (rate limit).")if status in (401, 403):return Refusal(401,diff --git a/dodaios/live/subscription_reasoning.py b/dodaios/live/subscription_reasoning.pyindex 212b0f46c5..badff2232b 100644--- a/dodaios/live/subscription_reasoning.py+++ b/dodaios/live/subscription_reasoning.py@@ -73,9 +73,15 @@ def _failure(code = str(error.get("code") or "")if not _SAFE_CODE.fullmatch(code):code = "subscription_unavailable"- if status == 429 or code in {+ if code == "rate_limit_exceeded":+ # A short burst limit, not the plan's allowance: a wait fixes it.+ status = 429+ message = (+ "The selected ChatGPT subscription is receiving too many requests "+ "right now (rate limit). Try again shortly."+ )+ elif status == 429 or code in {"usage_limit_reached",- "rate_limit_exceeded","subscription_sharing_usage_limit_exceeded",}:status = 429@@ -83,6 +89,7 @@ def _failure("The selected ChatGPT subscription reached a usage limit. ""Try again after its allowance resets.")+ retry_after = retry_after or _reset_after(error)elif status in (401, 403):message = ("ChatGPT subscription access was rejected. "@@ -108,6 +115,24 @@ def _failure(return SubscriptionReasoningError(message, code=code, status=status, retry_after=retry_after)+def _reset_after(error: dict[str, Any]) -> str | None:+ """Seconds until a spent allowance resets, from the backend's own fields.++ The usage-limit body names the reset as ``resets_in_seconds`` or as the+ epoch second ``resets_at``; nothing else of the body is read.+ """+ import time++ for field_name, relative in (("resets_in_seconds", True), ("resets_at", False)):+ raw = error.get(field_name)+ if isinstance(raw, bool) or not isinstance(raw, (int, float)):+ continue+ seconds = float(raw) if relative else float(raw) - time.time()+ if 0 <= seconds < 400 * 86400:+ return str(int(seconds))+ return None++#: Key- and token-shaped strings masked in a logged backend failure._SECRET = re.compile(r"(sk-[A-Za-z0-9_\-]{6,}|[Bb]earer\s+[A-Za-z0-9._\-]{10,}|eyJ[A-Za-z0-9._\-]{20,})"@@ -182,7 +207,7 @@ async def _http_failure(response: Any) -> SubscriptionReasoningError:failure = _failure(response.status_code, payload)# Preserve throttling instructions for gateway backoff without copying any# other headers. Existing consumers may read this optional exception field.- failure.retry_after = response.headers.get("retry-after")+ failure.retry_after = response.headers.get("retry-after") or failure.retry_afterlog.info("ChatGPT subscription request rejected: status=%s category=%s",failure.status,diff --git a/dodaios/ui/web/frontend/src/components/agentchat/turnError.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/turnError.test.tsindex 0548620178..89f198be79 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/turnError.test.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/turnError.test.ts@@ -4,7 +4,7 @@ import en from "@/i18n/locales/en.json";import es from "@/i18n/locales/es.json";import pt from "@/i18n/locales/pt.json";import zh from "@/i18n/locales/zh.json";-import { turnErrorText } from "./turnError";+import { resetTimeLabel, turnErrorText } from "./turnError";const CODES = ["mandated_tool_unfulfilled",@@ -29,3 +29,57 @@ describe("turnErrorText", () => {}});});++describe("turnErrorText for a spent allowance and a full context window", () => {+ const t = (key: string) => (key === "thread_turn.errors.usage_limit_until" ? "T:until {time}" : `T:${key}`);++ it("says the plan's allowance is used up, never a short wait", () => {+ const gateway = "The ChatGPT subscription reached its usage limit: the plan's allowance is used up until it resets. Until then, choose another connected model in the agent's settings. No fallback provider was called.";+ expect(turnErrorText(gateway, t)).toBe("T:thread_turn.errors.usage_limit");+ // A turn stored before the gateway told the two apart.+ expect(turnErrorText("openai-codex returned HTTP 429 (rate limit). Try again in 30 s, or choose another connected model in the agent's settings. No fallback provider was called.", t))+ .toBe("T:thread_turn.errors.usage_limit");+ });++ it("names the reset time when the gateway knows it", () => {+ const text = turnErrorText("OpenAI reached its usage limit: the plan's allowance is used up until it resets (it resets at 2026-10-27T15:04:00Z). Until then …", t);+ expect(text).toMatch(/^T:until .+/);+ expect(text).not.toContain("{time}");+ });++ it("keeps a real short rate limit as sent", () => {+ const limited = "openai returned HTTP 429 (rate limit). Try again in 30 s, or choose another connected model in the agent's settings.";+ expect(turnErrorText(limited, t)).toBe(limited);+ const subscription = "The ChatGPT subscription returned HTTP 429 (rate limit). Try again in 30 s, or choose another connected model in the agent's settings. No fallback provider was called.";+ expect(turnErrorText(subscription, t)).toBe(subscription);+ });++ it("explains a conversation that no longer fits the model's context window", () => {+ for (const reason of [+ "The conversation no longer fits this model's context window (context window exceeded). Start a fresh chat, or pick a model with a larger context window.",+ "Context length exceeded: the conversation is longer than qwen3.5:9b's context window on Ollama. Compress or shorten the conversation and send it again.",+ "Context window exceeded: estimated input 184592 leaves only 1 output tokens within the 65536-token context.",+ ]) expect(turnErrorText(reason, t)).toBe("T:thread_turn.errors.context_window");+ });++ it("has the new sentences in every UI language", () => {+ for (const locale of [en, de, es, pt, zh]) {+ const errors = (locale as { thread_turn: { errors: Record<string, string> } }).thread_turn.errors;+ expect(errors.usage_limit?.length).toBeGreaterThan(10);+ expect(errors.usage_limit_until).toContain("{time}");+ expect(errors.context_window?.length).toBeGreaterThan(10);+ expect(errors.usage_limit).not.toMatch(/30 ?s/);+ }+ });+});++describe("resetTimeLabel", () => {+ it("shows only the time on the same day and the day too otherwise", () => {+ const now = new Date("2026-10-27T10:00:00Z");+ const same = resetTimeLabel(new Date(now.getTime() + 60 * 60 * 1000).toISOString(), now);+ const later = resetTimeLabel(new Date(now.getTime() + 3 * 86400 * 1000).toISOString(), now);+ expect(same).toBeTruthy();+ expect(later && later.length).toBeGreaterThan(same!.length);+ expect(resetTimeLabel("not a date", now)).toBeNull();+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/turnError.ts b/dodaios/ui/web/frontend/src/components/agentchat/turnError.tsindex d8f5f5f320..64dea8c9c4 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/turnError.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/turnError.ts@@ -1,3 +1,5 @@+import { fill } from "@/i18n";+/** Backend turn-failure codes the chat shows as a sentence, not a raw identifier. */const TURN_ERROR_CODES = new Set(["mandated_tool_unfulfilled",@@ -6,11 +8,61 @@ const TURN_ERROR_CODES = new Set(["delegation_continuation_limit",]);-/** The text to show for a failed turn: a known code translated, anything else as sent. */+/**+ * A plan's allowance is used up (a subscription's usage limit, a daily+ * quota). Not a short rate limit: waiting a few seconds never helps. The+ * last pattern is the wording turns stored before the gateway told the+ * subscription's usage limit apart from a rate limit.+ */+const USAGE_LIMIT = [+ /usage limit/i,+ /usage_limit/i,+ /allowance (?:is )?used up/i,+ /allowance resets/i,+ /^openai-codex returned HTTP 429\b/i,+];++/** The conversation is longer than the model's context window, in any runtime's words. */+const CONTEXT_FULL = [+ /context window exceeded/i,+ /no longer fits this model's context window/i,+ /context[ _]length[ _]exceeded/i,+ /context overflow/i,+ /prompt is too long/i,+ /exceeds the model's context/i,+];++/** The UTC reset time the gateway names ("resets at 2026-10-27T15:04:00Z"). */+const RESET_AT = /resets at (\d{4}-\d\d-\d\dT\d\d:\d\d(?::\d\d)?Z)/;++/** A reset time in the person's own clock; the day too when it is not today. */+export function resetTimeLabel(iso: string, now: Date = new Date()): string | null {+ const at = new Date(iso);+ if (Number.isNaN(at.getTime())) return null;+ const sameDay = at.toDateString() === now.toDateString();+ return at.toLocaleString(undefined, sameDay+ ? { hour: "2-digit", minute: "2-digit" }+ : { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });+}++/**+ * The text to show for a failed turn: a known code translated, a spent+ * usage allowance or a full context window as an actionable sentence in the+ * person's language, anything else as sent.+ */export function turnErrorText(error: string | null | undefined,t: (key: string) => string,): string | null {if (!error) return null;- return TURN_ERROR_CODES.has(error) ? t(`thread_turn.errors.${error}`) : error;+ if (TURN_ERROR_CODES.has(error)) return t(`thread_turn.errors.${error}`);+ if (USAGE_LIMIT.some((pattern) => pattern.test(error))) {+ const reset = RESET_AT.exec(error);+ const time = reset ? resetTimeLabel(reset[1]) : null;+ return time+ ? fill(t("thread_turn.errors.usage_limit_until"), { time })+ : t("thread_turn.errors.usage_limit");+ }+ if (CONTEXT_FULL.some((pattern) => pattern.test(error))) return t("thread_turn.errors.context_window");+ return error;}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/turnFailure.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/turnFailure.test.tsxindex bc4101a096..f8f71f908c 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/turnFailure.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/turnFailure.test.tsx@@ -75,3 +75,15 @@ describe("retryOf", () => {expect(retryOf([user("hi"), turn("error", REASON), user("again", "u2")], send)).toBeNull();});});++describe("a turn a runtime ended with an error but no HTTP failure", () => {+ it("is the red failed-turn card with a readable reason and Retry, not a grey 'no answer' line", () => {+ let retried = 0;+ const reason = "The conversation no longer fits this model's context window (context window exceeded). Start a fresh chat, or pick a model with a larger context window.";+ draw(turn("error", reason), () => { retried += 1; });+ expect(screen.getByTestId("turn-failure-reason").textContent).toContain("context window");+ expect(screen.queryByText("Finished without an answer")).toBeNull();+ fireEvent.click(screen.getByTestId("turn-retry"));+ expect(retried).toBe(1);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsxindex 65267144e0..6007b37a88 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx@@ -83,7 +83,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c{error && <p role="alert" className="text-[11px] text-destructive">{error}</p>}</form>}<ul className="-mx-1 min-h-0 flex-1 space-y-0.5 overflow-y-auto px-1">- {live.error && <li role="alert" className="text-[12px] text-destructive">{t("tasks_view.load_error")}</li>}+ {live.error && !live.data && <li role="alert" className="text-[12px] text-destructive">{t("tasks_view.load_error")}</li>}{rows.length === 0 && live.isPending && <li className="text-[12px] text-muted-foreground">{t("society.profile_card.loading")}</li>}{rows.length === 0 && !live.isPending && !live.error && <li className="rounded-xl border border-dashed border-border px-3 py-4 text-center"><Sparkles size={16} aria-hidden className="mx-auto mb-1.5 text-faint-foreground" />diff --git a/dodaios/ui/web/frontend/src/components/society/data.ts b/dodaios/ui/web/frontend/src/components/society/data.tsindex 8e20bd95be..6555a73ace 100644--- a/dodaios/ui/web/frontend/src/components/society/data.ts+++ b/dodaios/ui/web/frontend/src/components/society/data.ts@@ -3,10 +3,10 @@* reads agents through the hooks in this file and nothing else.** Source of truth is `/api/society` (dodaios/ui/web/society_routes.py, rows- * typed in lib/societyApi.ts). When the backend is unreachable or has no- * agents yet, the clearly-labeled sample roster stands in and the rail says- * so — nothing else in the society components may know where agents come- * from.+ * typed in lib/societyApi.ts). A failed fetch (the backend restarting, a+ * dropped connection) never swaps in sample rows: the last known roster+ * stays on screen, or the rail keeps loading until the backend answers —+ * nothing else in the society components may know where agents come from.** The enums here mirror the roster schema (MASTERPLAN §3.1, agent-definition.md* §2); the const arrays in lib/societyApi.ts are pinned to the Python enums by@@ -27,7 +27,7 @@ import { useEventStore } from "@/store/events";import { translate } from "@/i18n";import { PALETTE_PRESETS, resolvePalette, type FigureRecipe } from "./figures/figureRecipe";-import { localizeSampleRoster, SAMPLE_ROSTER } from "./mockRoster";+import { SAMPLE_ROSTER } from "./mockRoster";import { beginRetirement, retirementRunning, retirementStageMounted } from "./world/retireStore";import { announceSpawn } from "./world/spawnStore";@@ -323,23 +323,27 @@ export function rowToAgent(row: SocietyAgentRow): SocietyAgent {const ROSTER_QUERY_KEY = ["society", "roster"] as const;const CAPABILITIES_QUERY_KEY = ["society", "capabilities"] as const;-async function fetchSocietyRoster(): Promise<RosterData> {- try {- const res = await fetch("/api/society/agents");- if (res.ok) {- const body = (await res.json()) as { agents?: SocietyAgentRow[] };- const rows = body.agents ?? [];- if (rows.length > 0) {- return { agents: rows.map(rowToAgent), sample: false };- }- }- } catch {- // Unreachable backend: the sample roster below says so on the rail.+/**+ * The roster as the backend has it. A failure throws, so the query keeps the+ * last roster it had (and retries) instead of showing anything made up; an+ * empty answer right after a non-empty one is a backend still starting, not+ * an empty society, and is treated the same way.+ */+export async function fetchSocietyRoster(previous?: RosterData): Promise<RosterData> {+ const res = await fetch("/api/society/agents");+ if (!res.ok) throw new Error(`GET /api/society/agents answered ${res.status}`);+ const body = (await res.json()) as { agents?: SocietyAgentRow[] };+ const rows = body.agents ?? [];+ if (rows.length === 0 && previous && !previous.sample && previous.agents.length > 0) {+ throw new Error("GET /api/society/agents answered an empty roster while starting");}- const rows = [...localizeSampleRoster()].filter((a) => !RETIRED_SAMPLE.has(a.agentId));- return { agents: rows, sample: true };+ return { agents: rows.map(rowToAgent), sample: false };}+/** Retry a failed roster fetch calmly (1 s, 2 s, 4 s … at most 10 s apart) until the backend is back. */+const ROSTER_RETRY = import.meta.env.MODE === "test" ? false : true;+const rosterRetryDelay = (attempt: number) => Math.min(1_000 * 2 ** attempt, 10_000);+/*** Apply a change to the cached roster right away, then refresh it in the* background. A create or a retirement shows on the rail the moment the@@ -370,7 +374,11 @@ const WARM_FRESH_MS = 2_000;export async function warmSocietyLists(client: QueryClient): Promise<void> {// A refetch mid-ceremony would delete the figure being carried to the mine.if (retirementRunning()) return;- const rosterQuery = { queryKey: ROSTER_QUERY_KEY, queryFn: fetchSocietyRoster, staleTime: WARM_FRESH_MS };+ const rosterQuery = {+ queryKey: ROSTER_QUERY_KEY,+ queryFn: () => fetchSocietyRoster(client.getQueryData<RosterData>(ROSTER_QUERY_KEY)),+ staleTime: WARM_FRESH_MS,+ };const teams = () => client.prefetchQuery({ ...societyChatGroupsQuery, staleTime: WARM_FRESH_MS });// The sample roster has no teams; a roster known to be real asks for both at once.const known = client.getQueryData<RosterData>(ROSTER_QUERY_KEY);@@ -378,8 +386,10 @@ export async function warmSocietyLists(client: QueryClient): Promise<void> {await Promise.all([client.prefetchQuery(rosterQuery), teams()]);return;}- const roster = await client.fetchQuery(rosterQuery);- if (!roster.sample) await teams();+ // A warm-up never waits on a backend that is down: the view's own query retries.+ await client.prefetchQuery(rosterQuery);+ const roster = client.getQueryData<RosterData>(ROSTER_QUERY_KEY);+ if (roster && !roster.sample) await teams();}/**@@ -395,11 +405,14 @@ export function withLeadName(data: RosterData, assistantName: string): RosterDat}export function useSocietyRoster(enabled = true) {+ const client = useQueryClient();const assistantName = useEventStore((s) => s.assistantName) ?? "";const select = useCallback((data: RosterData) => withLeadName(data, assistantName), [assistantName]);return useQuery({queryKey: ROSTER_QUERY_KEY,- queryFn: fetchSocietyRoster,+ queryFn: () => fetchSocietyRoster(client.getQueryData<RosterData>(ROSTER_QUERY_KEY)),+ retry: ROSTER_RETRY,+ retryDelay: rosterRetryDelay,enabled,select,staleTime: 15_000,diff --git a/dodaios/ui/web/frontend/src/components/society/mockRoster.ts b/dodaios/ui/web/frontend/src/components/society/mockRoster.tsindex 7556f18539..527205852e 100644--- a/dodaios/ui/web/frontend/src/components/society/mockRoster.ts+++ b/dodaios/ui/web/frontend/src/components/society/mockRoster.ts@@ -1,10 +1,11 @@/**- * Sample roster — stands in for society.db until the M1 backend is bound.+ * Sample roster — fixture rows for tests and previews. The running app never+ * shows them: a failed or empty roster fetch keeps the last real roster, or+ * the rail keeps loading (`data.ts`, `fetchSocietyRoster`).** Every value is deliberately static sample data (fixed timestamps, no chat- * sessions) and the roster rail shows a "sample data" badge, so the preview- * never pretends to be live state (the loading-states rule: an empty or- * mocked surface must say so, not invent numbers).+ * sessions), and a surface that shows it says "sample data", so it never+ * pretends to be live state.** The first row is the demo of the lead: Jarvis as the society's chief* executive — a human figure in a dark suit who owns the whole team anddiff --git a/dodaios/ui/web/frontend/src/components/society/rosterFetch.test.ts b/dodaios/ui/web/frontend/src/components/society/rosterFetch.test.tsnew file mode 100644index 0000000000..5c7e2bf4b0--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/rosterFetch.test.ts@@ -0,0 +1,54 @@+import { afterEach, describe, expect, test, vi } from "vitest";+import type { SocietyAgentRow } from "@/lib/societyApi";+import { fetchSocietyRoster, type RosterData } from "./data";+import { SAMPLE_ROSTER } from "./mockRoster";++const ROW = {+ agent_id: "agent-1", name: "Lumi", title: "", description: "", tier: "specialist",+ parent_agent_id: null, state: "active", avatar: null, checkpoint: "home", provider: "openai",+ model: "", effort: "", account_id: "", grant_mode: "all", grants: [], focus: [], denies: [],+ skills: null, workspace_dir: "", wiki_namespace: "", knowledge_scope: "shared",+ permission_ceiling: "ask", approval_mode: "bypass",+ approval_rules: { require_approval: [], always_allow: [] }, daily_budget_usd: 0,+ max_concurrent_runs: 1, browser_mode: "own", browser_allowed_domains: [], computer_id: null,+ runtime: "openclaw", session_id: "society:agent-1", created_ms: 0, updated_ms: 0,+ stats: { runs: 0, total_cost_usd: 0, last_active_ms: null },+} as unknown as SocietyAgentRow;++function answer(status: number, agents: SocietyAgentRow[] = []) {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ agents }), { status })));+}++afterEach(() => vi.unstubAllGlobals());++const sampleIds = new Set(SAMPLE_ROSTER.map((agent) => agent.agentId));++describe("fetchSocietyRoster never makes up a roster", () => {+ test("a backend that is down or restarting is an error, not sample rows", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => { throw new TypeError("Failed to fetch"); }));+ await expect(fetchSocietyRoster()).rejects.toThrow();+ answer(503);+ await expect(fetchSocietyRoster()).rejects.toThrow(/503/);+ });++ test("the real rows come through", async () => {+ answer(200, [ROW]);+ const roster = await fetchSocietyRoster();+ expect(roster.sample).toBe(false);+ expect(roster.agents.map((agent) => agent.agentId)).toEqual(["agent-1"]);+ });++ test("an empty roster is empty, never the sample agents", async () => {+ answer(200, []);+ const roster = await fetchSocietyRoster();+ expect(roster).toEqual({ agents: [], sample: false });+ expect(roster.agents.some((agent) => sampleIds.has(agent.agentId))).toBe(false);+ });++ test("an empty answer right after a real roster keeps the last known one (the query keeps it on error)", async () => {+ answer(200, [ROW]);+ const previous: RosterData = await fetchSocietyRoster();+ answer(200, []);+ await expect(fetchSocietyRoster(previous)).rejects.toThrow(/empty roster/);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/world/WorldStage.tsx b/dodaios/ui/web/frontend/src/components/society/world/WorldStage.tsxindex 9c7ed55410..3e62b74a15 100644--- a/dodaios/ui/web/frontend/src/components/society/world/WorldStage.tsx+++ b/dodaios/ui/web/frontend/src/components/society/world/WorldStage.tsx@@ -97,7 +97,7 @@ export function WorldStage({ onOpenAgents, onSelectAgent, onSelectPlace }: Worldconst shadows = useWorldSettings((s) => s.shadows);const roster = useSocietyRoster();const agents = roster.data?.agents ?? [];- const sample = roster.data?.sample ?? true;+ const sample = roster.data?.sample === true;const [selected, setSelected] = useState<string | null>(null);const [openHub, setOpenHub] = useState<KitPlace | null>(null);const [questOpen, setQuestOpen] = useState(false);diff --git a/dodaios/ui/web/frontend/src/hooks/useSocietyWarmup.test.tsx b/dodaios/ui/web/frontend/src/hooks/useSocietyWarmup.test.tsxindex c2b22422dd..cd71e8df86 100644--- a/dodaios/ui/web/frontend/src/hooks/useSocietyWarmup.test.tsx+++ b/dodaios/ui/web/frontend/src/hooks/useSocietyWarmup.test.tsx@@ -81,12 +81,16 @@ describe("useSocietyWarmup", () => {expect(count(TEAMS_URL)).toBe(1);});- it("leaves the teams alone while only the sample roster is known", async () => {- agents = [];+ it("leaves the teams alone, and makes up no roster, while the backend is down", async () => {+ vi.stubGlobal("fetch", async (url: string) => {+ calls.push(url);+ return new Response("restarting", { status: 503 });+ });renderHook(() => useSocietyWarmup(), { wrapper });- await waitFor(() => expect(client.getQueryData<RosterData>(ROSTER_KEY)?.sample).toBe(true));+ await waitFor(() => expect(count(ROSTER_URL)).toBe(1));await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });+ expect(client.getQueryData<RosterData>(ROSTER_KEY)).toBeUndefined();expect(count(TEAMS_URL)).toBe(0);});diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex 3a2213e5ad..e5a7e3046f 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -7675,7 +7675,10 @@"mandated_tool_unfulfilled": "Der nötige Schritt ist nicht gelaufen, deshalb konnte ich nicht verlässlich antworten. Bitte versuch es noch einmal.","unbacked_action_claim": "Ich konnte nicht bestätigen, dass die Aktion wirklich passiert ist, deshalb habe ich es nicht behauptet. Bitte versuch es noch einmal.","guarded_response": "Die Antwort wurde zurückgehalten, weil sie sich nicht prüfen ließ. Bitte versuch es noch einmal.",- "delegation_continuation_limit": "Die delegierte Arbeit hat zu viele Runden gebraucht und wurde gestoppt. Bitte frag noch einmal."+ "delegation_continuation_limit": "Die delegierte Arbeit hat zu viele Runden gebraucht und wurde gestoppt. Bitte frag noch einmal.",+ "usage_limit": "Das Kontingent dieses Modells ist aufgebraucht, bis es sich zurücksetzt. Wähle in den Einstellungen des Agenten ein anderes verbundenes Modell, um weiterzumachen.",+ "usage_limit_until": "Das Kontingent dieses Modells ist aufgebraucht, bis es sich um {time} zurücksetzt. Wähle in den Einstellungen des Agenten ein anderes verbundenes Modell, um weiterzumachen.",+ "context_window": "Das Gespräch passt nicht mehr in das Kontextfenster dieses Modells. Starte einen neuen Chat oder wähle ein Modell mit größerem Kontextfenster."}},"work_trace": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 03f348a984..7188909d7f 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -7675,7 +7675,10 @@"mandated_tool_unfulfilled": "The required step did not run, so I could not answer reliably. Please try again.","unbacked_action_claim": "I could not confirm that the action really happened, so I did not claim it. Please try again.","guarded_response": "The answer was held back because it could not be verified. Please try again.",- "delegation_continuation_limit": "The delegated work took too many rounds and was stopped. Please ask again."+ "delegation_continuation_limit": "The delegated work took too many rounds and was stopped. Please ask again.",+ "usage_limit": "This model's plan has used up its usage allowance until it resets. Pick another connected model in the agent's settings to keep going.",+ "usage_limit_until": "This model's plan has used up its usage allowance until it resets at {time}. Pick another connected model in the agent's settings to keep going.",+ "context_window": "The conversation no longer fits this model's context window. Start a fresh chat, or pick a model with a larger context window."}},"work_trace": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex 6de3d232be..4a1f31a4c2 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -7675,7 +7675,10 @@"mandated_tool_unfulfilled": "El paso necesario no se ejecutó, así que no pude responder con fiabilidad. Inténtalo de nuevo.","unbacked_action_claim": "No pude confirmar que la acción ocurriera de verdad, así que no lo afirmé. Inténtalo de nuevo.","guarded_response": "La respuesta se retuvo porque no se pudo verificar. Inténtalo de nuevo.",- "delegation_continuation_limit": "El trabajo delegado necesitó demasiadas rondas y se detuvo. Vuelve a preguntar."+ "delegation_continuation_limit": "El trabajo delegado necesitó demasiadas rondas y se detuvo. Vuelve a preguntar.",+ "usage_limit": "El plan de este modelo ha agotado su cuota de uso hasta que se restablezca. Elige otro modelo conectado en la configuración del agente para continuar.",+ "usage_limit_until": "El plan de este modelo ha agotado su cuota de uso hasta que se restablezca a las {time}. Elige otro modelo conectado en la configuración del agente para continuar.",+ "context_window": "La conversación ya no cabe en la ventana de contexto de este modelo. Empieza un chat nuevo o elige un modelo con una ventana de contexto más grande."}},"work_trace": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex 0d82a98e4c..4ce2a3be9c 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -7675,7 +7675,10 @@"mandated_tool_unfulfilled": "O passo necessário não foi executado, por isso não consegui responder com fiabilidade. Tenta novamente.","unbacked_action_claim": "Não consegui confirmar que a ação aconteceu mesmo, por isso não o afirmei. Tenta novamente.","guarded_response": "A resposta foi retida porque não foi possível verificá-la. Tenta novamente.",- "delegation_continuation_limit": "O trabalho delegado precisou de demasiadas rondas e foi parado. Volta a perguntar."+ "delegation_continuation_limit": "O trabalho delegado precisou de demasiadas rondas e foi parado. Volta a perguntar.",+ "usage_limit": "O plano deste modelo esgotou a cota de uso até ela ser renovada. Escolha outro modelo conectado nas configurações do agente para continuar.",+ "usage_limit_until": "O plano deste modelo esgotou a cota de uso até ela ser renovada às {time}. Escolha outro modelo conectado nas configurações do agente para continuar.",+ "context_window": "A conversa não cabe mais na janela de contexto deste modelo. Comece um chat novo ou escolha um modelo com uma janela de contexto maior."}},"work_trace": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 5e6172158a..0d555a6a15 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -7675,7 +7675,10 @@"mandated_tool_unfulfilled": "必要的步骤没有运行,所以我无法可靠地回答。请再试一次。","unbacked_action_claim": "我无法确认该操作确实已完成,所以没有这样声称。请再试一次。","guarded_response": "由于无法验证,该回答已被拦截。请再试一次。",- "delegation_continuation_limit": "委派的工作轮次过多,已被停止。请重新提问。"+ "delegation_continuation_limit": "委派的工作轮次过多,已被停止。请重新提问。",+ "usage_limit": "此模型的套餐用量已用完,需等待额度重置。请在智能体设置中选择另一个已连接的模型以继续。",+ "usage_limit_until": "此模型的套餐用量已用完,将在 {time} 重置。请在智能体设置中选择另一个已连接的模型以继续。",+ "context_window": "对话已超出此模型的上下文窗口。请开始新的聊天,或选择上下文窗口更大的模型。"}},"work_trace": {diff --git a/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx b/dodaios/ui/web/frontend/src/views/society/SocietyView.tsxindex e516be5d1c..9fcd485d3e 100644--- a/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx+++ b/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx@@ -66,7 +66,8 @@ export function SocietyView() {const [worldVisited, setWorldVisited] = useState(false);const roster = useSocietyRoster();const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);- const sample = roster.data?.sample ?? true;+ // Only rows that really are sample rows say so; a roster still loading is not one.+ const sample = roster.data?.sample === true;const groupsQuery = useSocietyChatGroups(!sample);const groups = useMemo(() => groupsQuery.data ?? [], [groupsQuery.data]);const teamsPending = !sample && !chatGroupsKnown(groupsQuery);diff --git a/tests/unit/agent_runtimes/test_acp_runner.py b/tests/unit/agent_runtimes/test_acp_runner.pyindex b99fe9914f..367d84c186 100644--- a/tests/unit/agent_runtimes/test_acp_runner.py+++ b/tests/unit/agent_runtimes/test_acp_runner.py@@ -56,6 +56,7 @@ def _turn(released: list[int] | None = None,cancel_on_delta: bool = False,provider_failure: Any = None,+ failure_probe: Any = None,) -> tuple[str | None, list[dict[str, Any]], list[tuple[str, str]], list[str | None]]:resumes: list[str | None] = []@@ -81,6 +82,7 @@ def _turn(),after_turn=(lambda: released.append(1)) if released is not None else None,provider_failure=provider_failure,+ failure_probe=failure_probe,)monkeypatch.setattr(runner_acp, "plan_runtime_turn", fake_plan)@@ -588,6 +590,48 @@ def test_a_silent_turn_without_a_gateway_failure_stays_done(monkeypatch, tmp_patassert _finished(events)["status"] == "done"+def test_a_silent_turn_the_runtime_logged_as_failed_is_an_error_with_its_reason(+ monkeypatch, tmp_path+):+ """OpenClaw ends a run that failed inside its Gateway (a context overflow it+ could not compact away) like a finished one; its own log says why."""+ from concurrent.futures import Future++ from dodaios.agent_runtimes.openclaw import CONTEXT_FULL_REASON++ asked: list[float] = []++ def probe(since: float) -> str:+ asked.append(since)+ return CONTEXT_FULL_REASON++ events = _turn(+ monkeypatch, tmp_path, "SILENT", provider_failure=Future(), failure_probe=probe+ )[1]+ finished = _finished(events)+ assert (finished["status"], finished["error"]) == ("error", CONTEXT_FULL_REASON)+ assert len(asked) == 1 and asked[0] > 0+++def test_the_failure_probe_never_turns_an_answer_into_an_error(monkeypatch, tmp_path):+ from concurrent.futures import Future++ events = _turn(+ monkeypatch, tmp_path, "hello", provider_failure=Future(),+ failure_probe=lambda since: "should not be read",+ )[1]+ assert _finished(events)["status"] == "done"+++def test_a_silent_turn_with_nothing_logged_stays_done(monkeypatch, tmp_path):+ from concurrent.futures import Future++ events = _turn(+ monkeypatch, tmp_path, "SILENT", provider_failure=Future(), failure_probe=lambda since: ""+ )[1]+ assert _finished(events)["status"] == "done"++def test_an_answer_after_a_retried_failure_stays_done(monkeypatch, tmp_path):from concurrent.futures import Futurediff --git a/tests/unit/agent_runtimes/test_runtime_gateway.py b/tests/unit/agent_runtimes/test_runtime_gateway.pyindex 6384c4a7b1..e1a2ce9751 100644--- a/tests/unit/agent_runtimes/test_runtime_gateway.py+++ b/tests/unit/agent_runtimes/test_runtime_gateway.py@@ -439,7 +439,8 @@ def test_subscription_limit_never_uses_the_api_path(fake, guarded, monkeypatch):signal = gateway.watch_failure(token)answer = _post(guarded, token, {"model": "m", "input": "hello"})assert answer.status_code == 429 and answer.headers["Retry-After"] == "120"- assert "openai-codex" in signal.result(timeout=1)+ assert "ChatGPT subscription" in signal.result(timeout=1)+ assert "usage limit" in signal.result() and "Try again in" not in signal.result()_post(guarded, token, {"model": "m", "input": "hello"})assert len(fake.calls) == 1gateway.check_cooldown("openai-codex", "m", "account-b")diff --git a/tests/unit/agent_runtimes/test_usage_limit_and_run_failures.py b/tests/unit/agent_runtimes/test_usage_limit_and_run_failures.pynew file mode 100644index 0000000000..a1f336abb7--- /dev/null+++ b/tests/unit/agent_runtimes/test_usage_limit_and_run_failures.py@@ -0,0 +1,210 @@+"""A spent plan allowance and a run that failed inside the runtime read as what they are.++Live 2026-10-27: a ChatGPT subscription at its usage limit showed "HTTP 429+(rate limit). Try again in 30 s", and an OpenClaw turn on Ollama whose+conversation outgrew the model's context window showed a grey "Finished+without an answer".+"""++from __future__ import annotations++import datetime as dt+import re+from pathlib import Path+from typing import Any++import pytest++from dodaios.agent_chat.task_recovery import blocks_automatic_recovery+from dodaios.agent_runtimes import gateway, provider_errors+from dodaios.agent_runtimes.openclaw import CONTEXT_FULL_REASON, run_failure+from dodaios.live import subscription_reasoning as sr+from dodaios.live.subscription_reasoning import SubscriptionReasoningError+++class ProviderStatusError(Exception):+ def __init__(self, status: int, body: Any = None, message: str = "Error") -> None:+ super().__init__(message)+ self.status_code = status+ self.body = body++[email protected](autouse=True)+def _clean_cooldowns():+ with gateway._LOCK:+ gateway._COOLDOWNS.clear()+ yield+ with gateway._LOCK:+ gateway._COOLDOWNS.clear()+++# ------------------------------------------------------------ classification+++def test_the_subscription_usage_limit_is_a_usage_limit_not_a_rate_limit() -> None:+ exc = sr._failure(429, {"error": {"code": "usage_limit_reached"}})+ refusal = provider_errors.gateway_refusal("openai-codex", exc)+ assert (refusal.status, refusal.code) == (429, "usage_limit")+ assert "usage limit" in refusal.message and "allowance" in refusal.message+ assert "another connected model" in refusal.message+ assert not re.search(r"\d+ s\b", refusal.message)+ assert provider_errors.is_terminal("usage_limit")+++def test_a_short_subscription_rate_limit_stays_a_rate_limit() -> None:+ exc = sr._failure(429, {"error": {"code": "rate_limit_exceeded"}})+ assert "usage limit" not in str(exc)+ assert provider_errors.gateway_refusal("openai-codex", exc).code == "rate_limited"+++def test_a_short_subscription_rate_limit_never_reads_like_a_stored_usage_limit() -> None:+ # The chat reads a stored "openai-codex returned HTTP 429 ..." (written before+ # the two were told apart) as a spent allowance; new rate limits are named by label.+ limited = gateway._limited("openai-codex", 30.0)+ assert limited.code == "rate_limited"+ assert not str(limited).startswith("openai-codex returned HTTP 429")+ assert str(limited).startswith("The ChatGPT subscription returned HTTP 429 (rate limit).")+ assert "30 s" in str(limited)+++def test_a_daily_quota_on_a_key_is_a_usage_limit() -> None:+ body = {+ "error": {+ "message": "Quota exceeded for metric: "+ "GenerateRequestsPerDayPerProjectPerModel-FreeTier"+ }+ }+ refusal = provider_errors.classify("gemini", ProviderStatusError(429, body))+ assert refusal is not None and refusal.code == "usage_limit"+ assert "GenerateRequests" not in refusal.message # never the provider's body+++def test_an_ordinary_rate_limit_is_still_unclassified() -> None:+ body = {"error": {"type": "rate_limit_error", "message": "Error"}}+ assert provider_errors.classify("claude-api", ProviderStatusError(429, body)) is None+++def test_the_reset_is_read_from_the_usage_limit_body() -> None:+ assert sr._failure(+ 429, {"error": {"code": "usage_limit_reached", "resets_in_seconds": 5400}}+ ).retry_after == "5400"+ soon = dt.datetime.now(dt.UTC).timestamp() + 600+ reset = sr._failure(429, {"error": {"type": "usage_limit_reached", "resets_at": soon}})+ assert reset.retry_after is not None and 590 <= int(reset.retry_after) <= 600+ assert sr._failure(429, {"error": {"resets_in_seconds": True}}).retry_after is None+++def test_the_message_names_the_reset_time_only_when_known() -> None:+ known = provider_errors.usage_limit_message("openai-codex", 3600)+ stamp = re.search(r"resets at (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ)", known)+ assert stamp is not None+ at = dt.datetime.strptime(stamp.group(1), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.UTC)+ assert abs((at - dt.datetime.now(dt.UTC)).total_seconds() - 3600) < 60+ assert "resets at" not in provider_errors.usage_limit_message("openai-codex")+++def test_a_usage_limit_ends_the_turn_without_an_automatic_continuation() -> None:+ assert blocks_automatic_recovery(provider_errors.usage_limit_message("openai-codex"))+++# ------------------------------------------------------------ gateway cooldown+++def _grant(provider: str = "openai-codex") -> gateway.Grant:+ return gateway.Grant(agent_id="agent-1", provider=provider, account_id="acct")+++def test_the_gateway_reports_a_usage_limit_without_a_30_second_wait() -> None:+ exc = SubscriptionReasoningError(+ "The selected ChatGPT subscription reached a usage limit. "+ "Try again after its allowance resets.",+ code="usage_limit_reached",+ status=429,+ )+ failure = gateway._report_failure(+ _grant(), "m", gateway._subscription_failure(_grant(), exc), None+ )+ assert (failure.status, failure.code) == (429, "usage_limit")+ assert "Try again in" not in str(failure) and "30 s" not in str(failure)+ assert "resets at" not in str(failure) # the provider named no reset time+ # The next call is refused early with the same words, not as a rate limit.+ with pytest.raises(gateway.GatewayError) as again:+ gateway.check_cooldown("openai-codex", "m", "acct")+ assert again.value.code == "usage_limit" and "Try again in" not in str(again.value)+++def test_a_known_reset_is_named_and_kept_by_the_cooldown() -> None:+ exc = SubscriptionReasoningError(+ "reached a usage limit", code="usage_limit_reached", status=429, retry_after="7200"+ )+ failure = gateway._report_failure(+ _grant(), "m", gateway._subscription_failure(_grant(), exc), None+ )+ assert failure.code == "usage_limit" and "resets at" in str(failure)+ assert failure.retry_after == pytest.approx(7200, abs=1)+ with pytest.raises(gateway.GatewayError) as again:+ gateway.check_cooldown("openai-codex", "m", "acct")+ assert "resets at" in str(again.value)+++def test_a_rate_limit_still_says_when_to_try_again() -> None:+ failure = gateway._report_failure(+ _grant("openai"), "m", gateway._failure("openai", ProviderStatusError(429)), None+ )+ assert failure.code == "rate_limited" and "Try again in 30 s" in str(failure)+++# ------------------------------------------------------------ OpenClaw's log+++def _log(tmp_path: Path, lines: list[str]) -> Path:+ path = tmp_path / "gateway.log"+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")+ return path+++_START = dt.datetime.fromisoformat("2026-10-27T12:35:15+01:00").timestamp()+_OVERFLOW_RUN = [+ "2026-10-27T12:30:00.000+01:00 [agent/embedded] embedded run agent end: runId=old "+ "isError=true model=m provider=jarvis error=x rawError=An older turn's failure",+ "2026-10-27T12:35:25.546+01:00 [agent/embedded] embedded run agent end: runId=r1 "+ "isError=true model=qwen3.5:9b provider=jarvis error=Agent run failed. rawError=Context "+ "window exceeded: estimated input 184592 leaves only 1 output tokens within the "+ "65536-token context.",+ "2026-10-27T12:35:25.624+01:00 [agent/embedded] context overflow detected (attempt 1/3); "+ "attempting auto-compaction for jarvis/qwen3.5:9b",+ "2026-10-27T12:38:25.830+01:00 [agent/embedded] [context-overflow-recovery] exhausted "+ "provider overflow recovery for jarvis/qwen3.5:9b; livenessState=blocked "+ "suggestedAction=reset_or_new kind=context_overflow",+ "2026-10-27T12:38:26.319+01:00 [diagnostic] message dispatch completed: outcome=error",+]+++def test_a_context_overflow_the_gateway_gave_up_on_reads_as_a_full_context(tmp_path) -> None:+ assert run_failure(_log(tmp_path, _OVERFLOW_RUN), _START) == CONTEXT_FULL_REASON+++def test_only_lines_of_this_turn_count(tmp_path) -> None:+ path = _log(tmp_path, _OVERFLOW_RUN)+ assert run_failure(path, _START + 3600) == ""+ assert run_failure(tmp_path / "missing.log", _START) == ""+++def test_another_failed_run_says_its_own_short_reason_without_secrets(tmp_path) -> None:+ path = _log(+ tmp_path,+ [+ "2026-10-27T12:35:25.546+01:00 [agent/embedded] embedded run agent end: runId=r1 "+ "isError=true model=m provider=jarvis error=failed rawError=Tool loop aborted "+ "with key sk-abcdef1234567890 " + "x" * 400,+ ],+ )+ reason = run_failure(path, _START)+ assert reason.startswith("OpenClaw ended the run with an error: Tool loop aborted")+ assert "sk-abcdef" not in reason and "[redacted]" in reason+ assert len(reason) < 320+++def test_an_overflow_the_run_never_got_past_is_the_reason(tmp_path) -> None:+ """Only consulted for a turn that ended without an answer."""+ assert run_failure(_log(tmp_path, _OVERFLOW_RUN[:2]), _START) == CONTEXT_FULL_REASON