Skip to content

Self-improving AI Employees for everyone

fix(agents): handle Gemini quotas and show retry progress

trohitg318f6ac69e5c
diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsx
index 6c32beb4..0e9889ca 100644
--- a/client/src/components/AIAgentNode.tsx
+++ b/client/src/components/AIAgentNode.tsx
@@ -21,6 +21,8 @@ const PHASE_CONFIG: Record<string, { icon: string; label: string; color: string
building_tools: { icon: '🔧', label: 'Building Tools', color: 'var(--warning)' },
building_graph: { icon: '🔗', label: 'Building Graph', color: 'var(--warning)' },
invoking_llm: { icon: '🧠', label: 'Thinking...', color: 'var(--node-trigger)' },
+ llm_step: { icon: '🧠', label: 'Thinking...', color: 'var(--node-trigger)' },
+ retry_wait: { icon: '⏳', label: 'Retrying automatically…', color: 'var(--warning)' },
executing_tool: { icon: '⚡', label: 'Using Tool', color: 'var(--node-trigger)' },
tool_completed: { icon: '✓', label: 'Tool Done', color: 'var(--success)' },
loading_skill: { icon: '📚', label: 'Loading Skill', color: 'var(--node-agent)' },
@@ -75,6 +77,9 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
const isExecuting = nodeStatus?.status === 'executing';
const currentPhase = nodeStatus?.data?.phase as string | undefined;
const phaseConfig = currentPhase ? PHASE_CONFIG[currentPhase] : null;
+ const retryMessage = isExecuting && currentPhase === 'retry_wait'
+ && typeof nodeStatus?.data?.retry_message === 'string'
+ ? `${nodeStatus.data.retry_message} Retrying automatically…` : undefined;
const activeSkills = (nodeStatus?.data?.active_skills as Array<{ name: string; state: string }> | undefined) ?? [];
const lastSkills = (nodeStatus?.data?.last_skills as Array<{ name: string; state: string }> | undefined) ?? [];
const currentSkill = activeSkills.find((skill) => skill.state === 'loading') ?? activeSkills[activeSkills.length - 1];
@@ -272,8 +277,10 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
lineHeight: '1.2', marginBottom: theme.spacing.lg, transition: 'color 0.3s ease',
overflowWrap: 'break-word', wordBreak: 'break-word', whiteSpace: 'normal',
textAlign: 'center',
- }} aria-label={capabilityLabel ? 'Current agent capability' : undefined} title={capabilityLabel}>
- {capabilityLabel || (isExecuting && phaseConfig ? phaseConfig.label : subtitle)}
+ }} role={retryMessage ? 'status' : undefined}
+ aria-label={!retryMessage && capabilityLabel ? 'Current agent capability' : undefined}
+ title={retryMessage || capabilityLabel}>
+ {retryMessage || capabilityLabel || (isExecuting && phaseConfig ? phaseConfig.label : subtitle)}
</div>
{/* Left inputs below the main one (Memory / Task / etc.) */}
diff --git a/client/src/components/__tests__/AIAgentNode.test.tsx b/client/src/components/__tests__/AIAgentNode.test.tsx
new file mode 100644
index 00000000..eac8ff4d
--- /dev/null
+++ b/client/src/components/__tests__/AIAgentNode.test.tsx
@@ -0,0 +1,44 @@
+import { act, render, screen } from '@testing-library/react';
+import { beforeEach, expect, it, vi } from 'vitest';
+import { ReactFlowProvider, type NodeProps } from 'reactflow';
+import type { NodeData } from '@/types/NodeTypes';
+import { useNodeStatusStore } from '@/stores/nodeStatusStore';
+
+vi.mock('@/hooks/useAppTheme', async () => {
+ const { theme } = await import('@/styles/theme');
+ return { useAppTheme: () => theme };
+});
+vi.mock('@/contexts/WebSocketContext', async () => {
+ const { useNodeStatusForId } = await import('@/stores/nodeStatusStore');
+ return { useNodeStatus: useNodeStatusForId };
+});
+vi.mock('@/lib/nodeSpec', () => ({ useNodeSpec: () => ({ handles: [], subtitle: 'Ready' }) }));
+vi.mock('@/components/ui/EditableNodeLabel', () => ({ default: () => <span>Agent</span> }));
+vi.mock('@/assets/icons', () => ({ NodeIcon: () => null }));
+
+import AIAgentNode from '../AIAgentNode';
+
+beforeEach(() => {
+ useNodeStatusStore.setState({ allStatuses: {}, currentWorkflowId: 'w1' });
+});
+
+it('shows provider retry ahead of a sticky tool label, then returns to normal progress', () => {
+ useNodeStatusStore.getState().setStatus('w1', 'agent', { status: 'executing', data: {
+ phase: 'retry_wait', retry_message: 'Gemini is temporarily unavailable.',
+ last_capability: { kind: 'tool', name: 'WriteTodos' }, iteration: 7, max_iterations: 100,
+ } });
+ const props: NodeProps<NodeData> = {
+ id: 'agent', type: 'aiAgent', data: {}, selected: false, isConnectable: true,
+ xPos: 0, yPos: 0, zIndex: 0, dragging: false,
+ };
+ render(<ReactFlowProvider><AIAgentNode {...props} /></ReactFlowProvider>);
+ expect(screen.getByRole('status')).toHaveTextContent('Gemini is temporarily unavailable. Retrying automatically…');
+ expect(screen.queryByText('tool WriteTodos')).not.toBeInTheDocument();
+ act(() => useNodeStatusStore.getState().setStatus('w1', 'agent', {
+ status: 'executing', data: { phase: 'llm_step' },
+ }));
+ expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();
+ expect(screen.getByText('Thinking...')).toBeInTheDocument();
+ act(() => useNodeStatusStore.getState().setStatus('w1', 'agent', { status: 'success' }));
+ expect(screen.getByText('Ready')).toBeInTheDocument();
+});
diff --git a/client/src/features/home/__tests__/talk.test.tsx b/client/src/features/home/__tests__/talk.test.tsx
index 7ead1120..ed4cc28b 100644
--- a/client/src/features/home/__tests__/talk.test.tsx
+++ b/client/src/features/home/__tests__/talk.test.tsx
@@ -129,6 +129,17 @@ describe('the thread', () => {
});
describe('sending', () => {
+ it('shows a retry on reopening Talk and clears it on the next attempt', async () => {
+ act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {
+ status: 'executing', data: { phase: 'retry_wait', retry_message: 'Gemini is temporarily unavailable.' },
+ }));
+ renderTalk(employee());
+ expect(await screen.findByRole('status')).toHaveTextContent('Gemini is temporarily unavailable. Retrying automatically…');
+ expect(screen.queryByText('No answer from Maya yet.')).not.toBeInTheDocument();
+ setAgentStatus('executing');
+ expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();
+ });
+
it('shows the node failure and hint without waiting for another model answer', async () => {
renderTalk(employee());
const box = await screen.findByRole('textbox', { name: 'Message Maya' });
@@ -285,6 +296,36 @@ describe('useReplyWait', () => {
vi.useRealTimers();
});
+ it('keeps waiting through provider backoff, then allows time for the next attempt', () => {
+ let messages: ThreadMessage[] = [];
+ const { result, rerender } = renderHook(() => useReplyWait('w1', AGENT, messages));
+ act(() => result.current.begin());
+ act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {
+ status: 'executing', data: { phase: 'retry_wait', retry_message: 'Gemini is rate-limiting requests.' },
+ }));
+ act(() => vi.advanceTimersByTime(REPLY_WAIT_MS * 2));
+ expect(result.current).toMatchObject({ waiting: true, unanswered: false, retryMessage: 'Gemini is rate-limiting requests.' });
+ setAgentStatus('executing');
+ act(() => vi.advanceTimersByTime(REPLY_WAIT_MS - 1));
+ expect(result.current).toMatchObject({ waiting: true, retryMessage: null });
+ messages = [reply];
+ rerender();
+ expect(result.current).toMatchObject({ waiting: false, unanswered: false, retryMessage: null });
+ });
+
+ it('replaces a temporary throttle with actionable quota failure', () => {
+ const { result } = renderHook(() => useReplyWait('w1', AGENT, []));
+ act(() => result.current.begin());
+ act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {
+ status: 'executing', data: { phase: 'retry_wait', retry_message: 'Waiting for Gemini.' },
+ }));
+ act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {
+ status: 'error', data: { error: 'Daily quota exhausted.', hint: 'Resume after quota resets.' },
+ }));
+ expect(result.current).toMatchObject({ waiting: false, unanswered: false, retryMessage: null,
+ failure: { error: 'Daily quota exhausted.', hint: 'Resume after quota resets.' } });
+ });
+
it('ignores an old failure when a new message begins', () => {
act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, { status: 'error', data: { error: 'Old failure' } }));
const { result } = renderHook(() => useReplyWait('w1', AGENT, []));
diff --git a/client/src/features/home/data/talk.ts b/client/src/features/home/data/talk.ts
index 4d09f5d6..942dc06a 100644
--- a/client/src/features/home/data/talk.ts
+++ b/client/src/features/home/data/talk.ts
@@ -34,7 +34,7 @@ import { parseEmployee, type EmployeeSummary } from './schemas';
export const THREAD_LIMIT = 200;
/** How long the talk agent has to pick a message up. */
export const PICKUP_WAIT_MS = 30_000;
-/** The longest "Working…" lasts, however long the agent works. */
+/** Time without fresh progress before "Working…" expires, excluding retry waits. */
export const REPLY_WAIT_MS = 180_000;
/** Once the agent stops, how long its answer has to reach the thread. */
export const SETTLE_WAIT_MS = 5_000;
@@ -209,6 +209,7 @@ export interface ReplyWait {
/** The last wait ended with no answer. */
unanswered: boolean;
failure: { error: string; hint?: string } | null;
+ retryMessage: string | null;
/** A message just went to the agent. */
begin: () => void;
/** It did not after all (refused, or waiting for Resume). */
@@ -230,6 +231,11 @@ export function useReplyWait(
),
);
const status = nodeStatus?.status;
+ const retryMessage = status === 'executing'
+ && nodeStatus?.data?.phase === 'retry_wait'
+ && (!wait || nodeStatus !== wait.initialStatus)
+ && typeof nodeStatus.data.retry_message === 'string'
+ ? nodeStatus.data.retry_message : null;
const replyId = latestReplyId(messages);
// An answer ends the wait. The agent working, then stopping, settles it.
@@ -254,18 +260,19 @@ export function useReplyWait(
}
}, [wait, status, nodeStatus, replyId]);
- // Never picked up, never finished, or finished with nothing to say.
+ // A known retry wait is active work. Resume the fallback timer when the
+ // next attempt starts, so backoff cannot consume the time to answer.
useEffect(() => {
- if (!wait) return;
+ if (!wait || retryMessage) return;
const left = wait.settling
? SETTLE_WAIT_MS
- : (wait.working ? REPLY_WAIT_MS : PICKUP_WAIT_MS) - (Date.now() - wait.since);
+ : wait.working ? REPLY_WAIT_MS : PICKUP_WAIT_MS - (Date.now() - wait.since);
const timer = window.setTimeout(() => {
setWait(null);
setUnanswered(true);
}, Math.max(0, left));
return () => window.clearTimeout(timer);
- }, [wait]);
+ }, [wait, nodeStatus, retryMessage]);
const begin = useCallback(() => {
const initialStatus = agentNodeId ? useNodeStatusStore.getState().allStatuses[workflowId]?.[agentNodeId] : undefined;
@@ -274,7 +281,7 @@ export function useReplyWait(
setFailure(null);
}, [messages, workflowId, agentNodeId]);
const cancel = useCallback(() => setWait(null), []);
- return { waiting: wait !== null, unanswered, failure, begin, cancel };
+ return { waiting: wait !== null, unanswered, failure, retryMessage, begin, cancel };
}
// ----- Turn on Talk, Apply -----
diff --git a/client/src/features/home/employee/EmployeeTalk.tsx b/client/src/features/home/employee/EmployeeTalk.tsx
index 8bc2497f..ac198bd2 100644
--- a/client/src/features/home/employee/EmployeeTalk.tsx
+++ b/client/src/features/home/employee/EmployeeTalk.tsx
@@ -164,7 +164,7 @@ function Conversation({ employee, control, drafts }: { employee: EmployeeSummary
const thread = useTalkThread(workflowId);
const messages = thread.data;
const send = useSendTalkMessage(workflowId);
- const { waiting, unanswered, failure, begin, cancel } = useReplyWait(workflowId, employee.talk.agent_node_id, messages);
+ const { waiting, unanswered, failure, retryMessage, begin, cancel } = useReplyWait(workflowId, employee.talk.agent_node_id, messages);
const mode = talkMode(employee.control);
const [draft, setDraft] = useState('');
const [queued, setQueued] = useState(false);
@@ -253,13 +253,15 @@ function Conversation({ employee, control, drafts }: { employee: EmployeeSummary
<MessageRow key={row.message.id} message={row.message} employee={employee} now={now} />
),
)}
- {waiting && (
+ {(waiting || retryMessage) && (
<div className="flex items-start gap-3">
<Avatar name={name} colorRole={employee.color_role} size="sm" />
- <p className={cn('m-0', BUBBLE, THEIRS, 'text-fg-muted')}>Working…</p>
+ <p role="status" className={cn('m-0', BUBBLE, THEIRS, 'text-fg-muted')}>
+ {retryMessage ? `${retryMessage} Retrying automatically…` : 'Working…'}
+ </p>
</div>
)}
- {unanswered && !waiting && !failureText && <p className={cn('m-0 text-xs text-fg-muted', PAST_AVATAR)}>No answer from {name} yet.</p>}
+ {unanswered && !waiting && !retryMessage && !failureText && <p className={cn('m-0 text-xs text-fg-muted', PAST_AVATAR)}>No answer from {name} yet.</p>}
</div>
{drafts}
</div>
diff --git a/docs-internal/native_llm_sdk.md b/docs-internal/native_llm_sdk.md
index 5c4b9b0e..dd95b802 100644
--- a/docs-internal/native_llm_sdk.md
+++ b/docs-internal/native_llm_sdk.md
@@ -262,6 +262,22 @@ also owns error translation: typed SDK exceptions (resolved lazily from
with a user-correctable message. There is no per-provider branch anywhere
in `ai.py`.
+Agent execution preserves typed `LLMError` metadata until the runtime boundary.
+For Gemini, `google.rpc.RetryInfo.retryDelay` in the SDK exception's `details`
+sets the minimum wait (the larger of it and `Retry-After`); native retries must
+not shorten this to their fallback backoff cap. Minute throttles and generic
+`RESOURCE_EXHAUSTED` capacity responses remain retryable. A `QuotaFailure`
+with a daily quota ID or an explicit zero quota, and depleted billing credits,
+pause for user action with safe recovery guidance. A 500 `INTERNAL` remains
+a transient server failure, not evidence of exhausted quota.
+
+Temporal owns retries for agent LLM steps (SDK and native retries are disabled).
+The activity publishes `retry_wait` with a safe message and scheduled delay to
+the workflow-scoped node status; each new attempt clears it with `llm_step`.
+Canvas and Talk show automatic retries, and Talk does not time out a reply
+while Temporal is waiting to retry. Status delivery is best effort and must
+never cause a successful model request to be repeated.
+
The legacy `factory.py` (`create_provider` / `is_native_provider` /
`NATIVE_PROVIDERS`) was **removed** — `ChatUnifier` + `registry.py` is the
only dispatch layer.
diff --git a/server/services/agent_runtime.py b/server/services/agent_runtime.py
index 4ca82dde..f7a062fc 100644
--- a/server/services/agent_runtime.py
+++ b/server/services/agent_runtime.py
@@ -153,9 +153,11 @@ async def run_native_llm_step(
delay = (
error.retry_after
if error.retry_after is not None
- else 0.25 * (2**attempt)
+ else min(0.25 * (2**attempt), 5.0)
)
- await asyncio.sleep(max(0.0, min(float(delay), 5.0)))
+ # A provider delay is a minimum, including Gemini RetryInfo.
+ # Cap only our fallback backoff, never the provider's hint.
+ await asyncio.sleep(max(0.0, float(delay)))
raise AssertionError("native LLM retry loop exhausted unexpectedly")
diff --git a/server/services/llm/protocol.py b/server/services/llm/protocol.py
index 5bb2b4f3..a167a428 100644
--- a/server/services/llm/protocol.py
+++ b/server/services/llm/protocol.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import base64
import json
import math
+import re
from dataclasses import dataclass, field
from enum import Enum
from typing import (
@@ -309,6 +310,7 @@ class LLMErrorCategory(str, Enum):
AUTHENTICATION = "authentication"
PERMISSION = "permission"
BILLING = "billing"
+ QUOTA = "quota"
RATE_LIMIT = "rate_limit"
INVALID_REQUEST = "invalid_request"
NOT_FOUND = "not_found"
@@ -406,6 +408,9 @@ class LLMError(Exception):
LLMErrorCategory.BILLING.value: (
f"{provider} blocked this request because a spending limit or available credits were exhausted."
),
+ LLMErrorCategory.QUOTA.value: (
+ f"{provider}'s daily quota is exhausted or this model has no available quota."
+ ),
LLMErrorCategory.RATE_LIMIT.value: (
f"{provider} is rate-limiting requests. "
"Retry after a short delay."
@@ -439,6 +444,7 @@ class LLMError(Exception):
"""Fixed recovery advice; never copy the provider's raw response."""
return {
LLMErrorCategory.BILLING: "Review the provider project's billing, spending cap, and credits. Resume after access is restored; repeating the request will not fix it.",
+ LLMErrorCategory.QUOTA: "Check the model's quota for your API project. Resume after the quota resets or is increased, or choose a model with available quota.",
LLMErrorCategory.AUTHENTICATION: "Update the provider credential in Settings > Connectors, then resume.",
LLMErrorCategory.PERMISSION: "Check the credential's project and model permissions, then resume after access is restored.",
LLMErrorCategory.NOT_FOUND: "Choose a model available to this provider and credential, then apply the change and resume.",
@@ -450,7 +456,7 @@ class LLMError(Exception):
@property
def requires_user_action(self) -> bool:
return not self.retryable and self.category in {
- LLMErrorCategory.BILLING, LLMErrorCategory.AUTHENTICATION,
+ LLMErrorCategory.BILLING, LLMErrorCategory.QUOTA, LLMErrorCategory.AUTHENTICATION,
LLMErrorCategory.PERMISSION, LLMErrorCategory.NOT_FOUND,
LLMErrorCategory.PROTOCOL,
}
@@ -488,6 +494,20 @@ class LLMError(Exception):
getattr(exc, "response", None), "retry-after"
)
retry_after = _optional_float(retry_after_value)
+ if retry_after is not None and (not math.isfinite(retry_after) or retry_after < 0):
+ retry_after = None
+ # google-genai stores the REST error envelope in ``details``, not
+ # ``body``. Google sends pacing as google.rpc.RetryInfo there, often
+ # without a Retry-After header. Never retry earlier than either hint.
+ for detail in _google_error_details(exc):
+ if detail.get("@type") != "type.googleapis.com/google.rpc.RetryInfo":
+ continue
+ raw_delay = detail.get("retryDelay")
+ if not isinstance(raw_delay, str) or not re.fullmatch(r"\d+(?:\.\d{1,9})?s", raw_delay):
+ continue
+ delay = _optional_float(raw_delay[:-1])
+ if delay is not None and math.isfinite(delay) and (retry_after is None or delay > retry_after):
+ retry_after, retry_after_value = delay, raw_delay
category = _classify_error(exc, status)
return cls(
message=str(exc),
@@ -727,6 +747,40 @@ def _header(response: Any, name: str) -> Optional[str]:
return None
+def _google_error_details(exc: BaseException) -> List[Mapping[str, Any]]:
+ """Read Google's typed details without exposing provider bodies publicly."""
+ body = getattr(exc, "details", None)
+ if not isinstance(body, Mapping):
+ body = getattr(exc, "body", None)
+ if not isinstance(body, Mapping):
+ return []
+ error = body.get("error", body)
+ details = error.get("details") if isinstance(error, Mapping) else None
+ return [item for item in details if isinstance(item, Mapping)] if isinstance(details, list) else []
+
+
+def _google_quota_exhausted(exc: BaseException) -> bool:
+ for detail in _google_error_details(exc):
+ if detail.get("@type") != "type.googleapis.com/google.rpc.QuotaFailure":
+ continue
+ violations = detail.get("violations")
+ if not isinstance(violations, list):
+ continue
+ for violation in violations:
+ if not isinstance(violation, Mapping):
+ continue
+ quota_id = re.sub(r"[^a-z]", "", str(violation.get("quotaId") or "").lower())
+ if "perday" in quota_id or _optional_int(violation.get("quotaValue")) == 0:
+ return True
+ # Some Gemini responses omit quotaValue but name the zero limit in the
+ # message. A bare RESOURCE_EXHAUSTED or "check quota" stays retryable:
+ # Vertex shared-capacity throttling uses exactly that generic response.
+ message = str(getattr(exc, "message", "") or "").lower()
+ return getattr(exc, "status", None) == "RESOURCE_EXHAUSTED" and bool(
+ re.search(r"quota exceeded for metric:[^\r\n]*\blimit:\s*0(?:[,\s]|$)", message)
+ )
+
+
def _classify_error(
exc: BaseException, status: Optional[int]
) -> LLMErrorCategory:
@@ -738,9 +792,12 @@ def _classify_error(
status == 402 or any(marker in message for marker in (
"spend cap breached", "insufficient_quota", "insufficient credits",
"credit balance is too low", "billing_hard_limit_reached",
+ "prepayment credits are depleted", "prepay credit balance is depleted",
))
):
return LLMErrorCategory.BILLING
+ if status == 429 and _google_quota_exhausted(exc):
+ return LLMErrorCategory.QUOTA
if status == 401 or "authentication" in name or "api key" in message:
return LLMErrorCategory.AUTHENTICATION
if status == 403 or "permission" in name:
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index 629751db..f2a1057c 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -156,7 +156,7 @@ async def _resolve_activity_api_key(payload: Dict[str, Any]) -> str:
return str(api_key)
-def _as_temporal_llm_error(error: Any):
+def _as_temporal_llm_error(error: Any, *, attempt: Optional[int] = None):
"""Translate a structured SDK failure at the Temporal boundary.
Raw provider messages can contain payload fragments or internal endpoint
@@ -197,6 +197,14 @@ def _as_temporal_llm_error(error: Any):
and retry_after > 0
else None
)
+ if details["retryable"] and next_retry_delay is None and attempt is not None:
+ from ._retry_policies import LLM_STEP_RETRY
+
+ next_retry_delay = min(
+ LLM_STEP_RETRY.maximum_interval,
+ LLM_STEP_RETRY.initial_interval
+ * LLM_STEP_RETRY.backoff_coefficient ** min(max(attempt - 1, 0), 20),
+ )
return ApplicationError(
safe_message,
details,
@@ -206,6 +214,48 @@ def _as_temporal_llm_error(error: Any):
)
+def _llm_activity_attempt() -> int:
+ try:
+ return activity.info().attempt
+ except RuntimeError: # direct unit invocation, outside a Temporal activity
+ return 1
+
+
+async def _publish_llm_attempt_status(
+ payload: Dict[str, Any], *, error: Any = None, delay: Optional[timedelta] = None,
+) -> None:
+ """Keep the existing node-status projection honest during activity backoff.
+
+ Retry waits happen inside Temporal, so the workflow cannot emit progress
+ until the activity completes. This is a best-effort UI projection only;
+ failure to broadcast must never repeat an otherwise successful model call.
+ """
+ conversation_key = payload.get("conversation_key")
+ if not isinstance(conversation_key, Mapping):
+ conversation_key = {}
+ workflow_id = payload.get("workflow_id") or conversation_key.get("workflow_id")
+ node_id = payload.get("node_id")
+ if not workflow_id or not node_id:
+ return
+ data = {
+ "agent_type": "temporal",
+ "phase": "retry_wait" if error else "llm_step",
+ **{key: payload[key] for key in ("iteration", "max_iterations") if key in payload},
+ }
+ if error is not None:
+ data.update({
+ "retry_message": error.user_message,
+ "retry_after": delay.total_seconds() if delay is not None else None,
+ "retry_attempt": _llm_activity_attempt() + 1,
+ })
+ try:
+ from services.status_broadcaster import get_status_broadcaster
+
+ await get_status_broadcaster().update_node_status(node_id, "executing", data, workflow_id=str(workflow_id))
+ except Exception: # noqa: BLE001 - optional status delivery never changes LLM execution
+ logger.warning("Could not publish LLM attempt status for node %s", node_id, exc_info=True)
+
+
def _native_tool_definition(tool: Any) -> Dict[str, Any]:
"""Serialize an AgentToolSpec (or legacy StructuredTool) for history."""
@@ -314,8 +364,8 @@ async def _execute_native_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
thinking=thinking,
tools=tool_defs,
context_management=payload.get("context_management"),
- # Temporal owns the one-shot retry contract. SDK retries could
- # otherwise re-bill a request after an ambiguous transport loss.
+ # Temporal owns retries; nested SDK retries would bypass
+ # quota classification and hide the wait from the UI.
sdk_max_retries=0,
explicit_max_retries=0,
# Keep structured metadata until this activity boundary,
@@ -325,7 +375,17 @@ async def _execute_native_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
detail=f"LLM step waiting: {payload.get('model')}",
)
except LLMError as error:
- raise _as_temporal_llm_error(error) from error
+ attempt = _llm_activity_attempt()
+ failure = _as_temporal_llm_error(error, attempt=attempt)
+ if error.retryable:
+ await _publish_llm_attempt_status(payload, error=error, delay=failure.next_retry_delay)
+ logger.warning(
+ "LLM retry scheduled: provider=%s category=%s attempt=%s delay_seconds=%s",
+ error.provider, error.category.value, attempt, failure.next_retry_delay.total_seconds(),
+ )
+ # The safe category and diagnostic fields are sufficient here. Raw
+ # SDK bodies in chained tracebacks can include prompts or credentials.
+ raise failure from None
assistant = response.assistant_message or Message(
role="assistant",
@@ -476,6 +536,7 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
)
activity.heartbeat(f"LLM step starting: {payload.get('model')}")
+ await _publish_llm_attempt_status(payload)
result = await _execute_native_llm_step(payload)
activity.heartbeat("LLM step: model returned")
return result
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index b478159a..7222d8de 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -869,7 +869,10 @@ class AgentWorkflow:
visible_tools = [t for t in tools if not t.get("llm_hidden")]
llm_payload = {
"node_id": payload["node_id"],
+ "workflow_id": agent_workflow_id,
"provider": payload["provider"],
+ "iteration": iteration,
+ "max_iterations": max_iterations,
"model": payload["model"],
"messages": messages,
"tools": [
diff --git a/server/tests/llm/test_gemini_errors.py b/server/tests/llm/test_gemini_errors.py
new file mode 100644
index 00000000..2572b077
--- /dev/null
+++ b/server/tests/llm/test_gemini_errors.py
@@ -0,0 +1,122 @@
+"""Gemini's real SDK error envelope must drive retry versus owner action."""
+
+from types import SimpleNamespace
+
+import pytest
+from google.genai.errors import ClientError, ServerError
+
+from services.llm.protocol import LLMError, LLMErrorCategory
+
+
+def gemini_error(*details, message="Resource exhausted", status=429):
+ error_type = ServerError if status >= 500 else ClientError
+ return error_type(status, {"error": {
+ "code": status,
+ "status": "INTERNAL" if status >= 500 else "RESOURCE_EXHAUSTED",
+ "message": message,
+ "details": list(details),
+ }})
+
+
+def retry_info(delay):
+ return {"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": delay}
+
+
+def quota_failure(*violations):
+ return {"@type": "type.googleapis.com/google.rpc.QuotaFailure", "violations": list(violations)}
+
+
+def test_logged_internal_error_is_transient_not_quota():
+ error = LLMError.from_exception("gemini", gemini_error(status=500, message="Internal error encountered."))
+ assert error.category == LLMErrorCategory.SERVER
+ assert error.status_code == 500
+ assert error.retryable
+ assert not error.requires_user_action
+ assert error.user_message == "Gemini is temporarily unavailable."
+
+
+def test_minute_quota_honors_fractional_retry_info():
+ error = LLMError.from_exception("gemini", gemini_error(
+ quota_failure({"quotaId": "GenerateRequestsPerMinutePerProjectPerModel"}),
+ retry_info("43.123456789s"),
+ ))
+ assert error.category == LLMErrorCategory.RATE_LIMIT
+ assert error.retryable
+ assert not error.requires_user_action
+ assert error.retry_after == pytest.approx(43.123456789)
+ assert error.retry_after_raw == "43.123456789s"
+
+
[email protected]("details", [(), (quota_failure(),), (quota_failure({"description": "Quota exceeded"}),)])
+def test_generic_resource_exhausted_does_not_imply_a_hard_quota(details):
+ error = LLMError.from_exception("gemini", gemini_error(*details))
+ assert error.category == LLMErrorCategory.RATE_LIMIT
+ assert error.retryable
+
+
[email protected]("violation", [
+ {"quotaId": "GenerateRequestsPerDayPerProjectPerModel-FreeTier"},
+ {"quotaId": "GenerateRequestsPerMinutePerProjectPerModel", "quotaValue": "0"},
+ {"quotaValue": 0},
+])
+def test_daily_or_zero_quota_requires_action_even_with_retry_info(violation):
+ error = LLMError.from_exception("gemini", gemini_error(
+ quota_failure({"quotaId": "GenerateRequestsPerMinutePerProjectPerModel"}, {
+ **violation, "subject": "private-project", "description": "secret details",
+ }),
+ retry_info("39s"),
+ ))
+ assert error.category == LLMErrorCategory.QUOTA
+ assert not error.retryable
+ assert error.requires_user_action
+ node_error = error.as_node_error().as_dict()
+ assert node_error["requires_user_action"]
+ assert "quota resets" in node_error["hint"]
+ assert "private-project" not in str(node_error)
+ assert "secret" not in str(node_error)
+
+
[email protected](("limit", "retryable"), [("0", False), ("10", True), ("0.5", True)])
+def test_message_fallback_only_treats_an_explicit_zero_limit_as_blocked(limit, retryable):
+ error = LLMError.from_exception("gemini", gemini_error(message=(
+ f"Quota exceeded for metric: generativelanguage.googleapis.com/generate_content_free_tier_requests, limit: {limit}, model: test"
+ )))
+ assert error.retryable is retryable
+
+
+def test_depleted_gemini_prepayment_is_billing_not_a_throttle():
+ error = LLMError.from_exception("gemini", gemini_error(message="Prepayment credits are depleted."))
+ assert error.category == LLMErrorCategory.BILLING
+ assert error.requires_user_action
+ assert not error.retryable
+
+
[email protected](("header", "body", "expected"), [("60", "20s", 60), ("5", "40s", 40)])
+def test_retry_wait_never_shortens_either_provider_hint(header, body, expected):
+ exc = gemini_error(retry_info(body), retry_info("1s"))
+ exc.response = SimpleNamespace(headers={"retry-after": header})
+ error = LLMError.from_exception("gemini", exc)
+ assert error.retry_after == expected
+
+
[email protected]("delay", [None, {}, 40, "-1s", "nans", "infs", "40", "1.1234567890s"])
+def test_malformed_retry_info_uses_normal_backoff(delay):
+ error = LLMError.from_exception("gemini", gemini_error(retry_info(delay)))
+ assert error.retry_after is None
+ assert error.retryable
+
+
[email protected]("header", ["nan", "inf", "-1"])
+def test_invalid_header_cannot_poison_a_valid_google_delay(header):
+ exc = gemini_error(retry_info("30s"))
+ exc.response = SimpleNamespace(headers={"retry-after": header})
+ assert LLMError.from_exception("gemini", exc).retry_after == 30
+
+
[email protected]("details", [None, "invalid", [{"violations": "invalid"}], [None]])
+def test_malformed_google_details_do_not_hide_the_original_error(details):
+ exc = gemini_error()
+ exc.details["error"]["details"] = details
+ error = LLMError.from_exception("gemini", exc)
+ assert error.category == LLMErrorCategory.RATE_LIMIT
+ assert error.retry_after is None
diff --git a/server/tests/services/test_native_agent_runtime.py b/server/tests/services/test_native_agent_runtime.py
index 8a95ee78..88d374ed 100644
--- a/server/tests/services/test_native_agent_runtime.py
+++ b/server/tests/services/test_native_agent_runtime.py
@@ -192,6 +192,37 @@ async def test_native_step_never_surfaces_raw_provider_error_text():
assert "Bearer secret" not in str(caught.value)
[email protected]("daily_quota", [False, True])
+async def test_native_gemini_retry_info_is_honored_and_hard_quota_never_retries(monkeypatch, daily_quota):
+ from google.genai.errors import ClientError
+
+ details = [{"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": "41.5s"}]
+ if daily_quota:
+ details.append({"@type": "type.googleapis.com/google.rpc.QuotaFailure", "violations": [
+ {"quotaId": "GenerateRequestsPerDayPerProjectPerModel"},
+ ]})
+ error = LLMError.from_exception("gemini", ClientError(429, {"error": {
+ "code": 429, "status": "RESOURCE_EXHAUSTED", "message": "Quota exceeded", "details": details,
+ }}))
+ unifier = SimpleNamespace(chat=AsyncMock(side_effect=[error, LLMResponse(content="recovered")]))
+ sleep = AsyncMock()
+ monkeypatch.setattr("services.agent_runtime.asyncio.sleep", sleep)
+ request = dict(provider="gemini", api_key="test", model="test-model",
+ messages=[Message(role="user", content="go")], temperature=0, max_tokens=100)
+ if daily_quota:
+ with pytest.raises(NodeUserError) as raised:
+ await run_native_llm_step(unifier, **request)
+ assert raised.value.requires_user_action
+ assert unifier.chat.await_count == 1
+ sleep.assert_not_awaited()
+ else:
+ result = await run_native_llm_step(unifier, **request)
+ assert result.content == "recovered"
+ assert unifier.chat.await_count == 2
+ sleep.assert_awaited_once_with(41.5)
+
+
@pytest.mark.asyncio
async def test_native_loop_replays_assistant_and_accumulates_usage():
first_message = Message(
diff --git a/server/tests/temporal/test_agent_llm_contract.py b/server/tests/temporal/test_agent_llm_contract.py
index 7bdbb7de..313d4176 100644
--- a/server/tests/temporal/test_agent_llm_contract.py
+++ b/server/tests/temporal/test_agent_llm_contract.py
@@ -89,12 +89,13 @@ def patched_workflow(monkeypatch):
class TestWorkflowLoopContract:
@pytest.mark.asyncio
@pytest.mark.parametrize("from_tool", [False, True])
- async def test_owner_action_error_stops_before_another_model_or_compaction(self, monkeypatch, patched_workflow, from_tool):
+ @pytest.mark.parametrize("category", ["billing", "quota"])
+ async def test_owner_action_error_stops_before_another_model_or_compaction(self, monkeypatch, patched_workflow, from_tool, category):
from services.llm.protocol import LLMError, LLMErrorCategory
from services.temporal.agent_activities import _as_temporal_llm_error
from services.temporal.agent_workflow import AgentWorkflow
- error = LLMError("secret provider body", "gemini", category=LLMErrorCategory.BILLING)
+ error = LLMError("secret provider body", "gemini", category=LLMErrorCategory(category))
prepared = _payload()
prepared["compaction_threshold"] = 1
calls = []
@@ -178,6 +179,9 @@ class TestWorkflowLoopContract:
assert "message_wire_version" not in llm_payload
assert "api_key" not in llm_payload
assert "tool_data" not in llm_payload
+ assert llm_payload["workflow_id"] == "graph-1"
+ assert llm_payload["iteration"] == 0
+ assert llm_payload["max_iterations"] == 2
assert llm_payload["tools"] == [_tool()["definition"]]
assert [m["role"] for m in llm_payload["messages"]] == [
"system",
diff --git a/server/tests/temporal/test_llm_retry_status.py b/server/tests/temporal/test_llm_retry_status.py
new file mode 100644
index 00000000..bc292e6d
--- /dev/null
+++ b/server/tests/temporal/test_llm_retry_status.py
@@ -0,0 +1,109 @@
+"""A provider outage stays visible until the next attempt; quota fails fast."""
+
+from dataclasses import replace
+from datetime import timedelta
+from unittest.mock import AsyncMock
+
+import pytest
+from google.genai.errors import ClientError, ServerError
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import ActivityEnvironment
+
+from services.llm.protocol import LLMError, LLMResponse, Message, message_to_wire
+from services.status_broadcaster import StatusBroadcaster
+from services.temporal.agent_activities import execute_llm_step
+
+
+def step(monkeypatch):
+ import core.container as container_module
+ import services.agent_runtime as runtime_module
+ import services.status_broadcaster as status_module
+
+ monkeypatch.setattr(container_module.container, "chat_unifier", object)
+ run = AsyncMock()
+ monkeypatch.setattr(runtime_module, "run_native_llm_step", run)
+ broadcaster = StatusBroadcaster()
+ broadcaster.broadcast = AsyncMock()
+ monkeypatch.setattr(status_module, "get_status_broadcaster", lambda: broadcaster)
+ payload = {
+ "workflow_id": "graph-7", "node_id": "agent-1", "provider": "gemini", "model": "test-model",
+ "api_key": "test", "messages": [message_to_wire(Message(role="user", content="go"))],
+ "iteration": 7, "max_iterations": 100,
+ }
+ return ActivityEnvironment(), run, broadcaster, payload
+
+
[email protected](("attempt", "delay"), [(1, 5), (2, 10), (8, 300), (100, 300)])
+async def test_internal_error_announces_backoff_then_clears_on_success(step, attempt, delay):
+ env, run, broadcaster, payload = step
+ env.info = replace(env.info, attempt=attempt)
+ error = LLMError.from_exception("gemini", ServerError(500, {"error": {
+ "code": 500, "status": "INTERNAL", "message": "Internal error encountered. secret",
+ }}))
+ run.side_effect = [error, LLMResponse(content="recovered")]
+ with pytest.raises(ApplicationError) as raised:
+ await env.run(execute_llm_step, payload)
+ failure = raised.value
+ assert failure.type == "LLMError.server"
+ assert not failure.non_retryable
+ assert failure.next_retry_delay == timedelta(seconds=delay)
+ assert failure.__suppress_context__
+ assert "secret" not in str(failure.details)
+ event = broadcaster.broadcast.await_args.args[0]
+ assert event["workflow_id"] == "graph-7"
+ assert event["data"]["status"] == "executing"
+ assert event["data"]["data"] == {
+ "agent_type": "temporal", "phase": "retry_wait", "iteration": 7, "max_iterations": 100,
+ "retry_message": "Gemini is temporarily unavailable.", "retry_after": delay,
+ "retry_attempt": attempt + 1,
+ }
+ env.info = replace(env.info, attempt=attempt + 1)
+ response = await env.run(execute_llm_step, payload)
+ assert response["content"] == "recovered"
+ status = broadcaster._status["nodes"]["agent-1"]
+ assert status["data"]["phase"] == "llm_step"
+ assert "retry_message" not in status["data"]
+ assert run.await_count == 2
+ assert all(call.kwargs["explicit_max_retries"] == 0 for call in run.await_args_list)
+ assert all(call.kwargs["sdk_max_retries"] == 0 for call in run.await_args_list)
+
+
[email protected]("daily", [False, True])
+async def test_google_retry_info_paces_throttles_but_cannot_override_a_daily_block(step, daily):
+ env, run, broadcaster, payload = step
+ quota_id = "GenerateRequestsPerDayPerProjectPerModel" if daily else "GenerateRequestsPerMinutePerProjectPerModel"
+ run.side_effect = LLMError.from_exception("gemini", ClientError(429, {"error": {
+ "code": 429, "status": "RESOURCE_EXHAUSTED", "message": "Quota exceeded: private project",
+ "details": [
+ {"@type": "type.googleapis.com/google.rpc.QuotaFailure", "violations": [{"quotaId": quota_id}]},
+ {"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": "45.5s"},
+ ],
+ }}))
+ with pytest.raises(ApplicationError) as raised:
+ await env.run(execute_llm_step, payload)
+ failure = raised.value
+ assert failure.non_retryable is daily
+ if daily:
+ assert failure.next_retry_delay is None
+ assert failure.type == "LLMError.quota"
+ assert failure.details[0]["requires_user_action"]
+ assert "quota resets" in failure.details[0]["hint"]
+ assert broadcaster.broadcast.await_count == 1 # attempt start only, never a retry promise
+ else:
+ assert failure.next_retry_delay == timedelta(seconds=45.5)
+ assert broadcaster._status["nodes"]["agent-1"]["data"]["retry_after"] == 45.5
+ assert "private project" not in str(failure.details)
+ assert run.await_count == 1
+
+
+async def test_status_failure_does_not_repeat_a_successful_model_call(step, monkeypatch):
+ env, run, broadcaster, payload = step
+ monkeypatch.setattr(broadcaster, "update_node_status", AsyncMock(side_effect=RuntimeError("socket closed")))
+ run.return_value = LLMResponse(content="done")
+ response = await env.run(execute_llm_step, payload)
+ assert response["content"] == "done"
+ run.assert_awaited_once()