Skip to content

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.

feat(terminal): let two panes trade the agents running in them

Ruben Lütke825a30fa2e1e
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 50d088e853..4ccec97b17 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -77,6 +77,7 @@ from .folders import ProjectProfile, probe_project
from .names import default_names, normalize, resolve
from .transcript import ReplayBuffer, Transcript
+from .terminal_input import THEME_COLOURS, TerminalQueryResponder
if TYPE_CHECKING: # pragma: no cover - typing only
from jarvis.terminal.pty_manager import PtyManager
@@ -544,6 +545,13 @@ class Session:
restored_from: str = ""
def find(self, wanted: str) -> Terminal | None:
+ # Answers the emulator queries the agent's CLI asks on startup. It lives on
+ # the TERMINAL rather than on the viewer's socket for two reasons: the PTY
+ # outlives its viewers, and the replay handed to a re-joining viewer carries
+ # the original queries — answering those a second time would write the reply
+ # into a prompt the agent has long since opened, which is the corruption
+ # this exists to prevent. Only live output reaches it.
+ queries: TerminalQueryResponder = field(default_factory=TerminalQueryResponder)
"""Terminal by key, call-sign, or a spoken phrase containing one."""
if not wanted:
return None
@@ -1424,7 +1432,17 @@ class Registry:
# that is what makes switching workspaces safe — so a closure pinned to
# the viewer that happened to start the agent would keep writing into a
# dead socket forever, and the viewer that came later would see nothing.
- async def _output(_tid: str, text: str) -> None:
+ async def _output(tid: str, text: str) -> None:
+ # FIRST, before anything that could yield: a CLI asking its terminal
+ # for the device type or the screen colours reads the answer within
+ # milliseconds of asking. Answering here rather than in the browser
+ # keeps the whole exchange inside this process — a reply that has to
+ # cross two WebSocket hops arrives after the CLI stopped listening,
+ # and then appears as pasted-looking junk in its prompt. Addressed to
+ # `tid` rather than `term.pty_id`, which is assigned a moment later.
+ replies = term.queries.feed(text)
+ if replies:
+ manager.write(tid, replies)
term.transcript.feed(text)
term.replay.feed(text)
term.last_output_at = time.time()
@@ -1485,6 +1503,7 @@ class Registry:
except Exception as exc: # noqa: BLE001 - surfaced to the pane
term.status = "error"
term.error = str(exc)
+ appearance: str | None = None,
raise SessionError(str(exc)) from exc
term.pty_id = pty_session.terminal_id
@@ -1492,6 +1511,12 @@ class Registry:
term.error = ""
term.exit_code = None
term.started_at = time.time()
+ ``appearance`` is the light/dark ground the viewer draws this pane on.
+ It is answered to the agent's CLI when it asks for the screen colours,
+ so a CLI on a light pane picks a palette for paper rather than for
+ slate. Omitted (an internal re-attach), whatever the last viewer said
+ stands.
+
term.last_output_at = time.time()
if term.resume is None and can_resume(term.agent):
# A CLI that cannot be told its session id (Codex): find out which
@@ -1521,6 +1546,8 @@ class Registry:
await asyncio.sleep(delay)
if term not in owner.terminals or owner.id not in self._sessions:
return # the pane (or the workspace) is gone
+ if appearance in THEME_COLOURS:
+ term.queries.appearance = appearance
session = owner
if term.resume is not None:
return
diff --git a/jarvis/terminal/pty_manager.py b/jarvis/terminal/pty_manager.py
index c35dd89e3c..a0fcb81b80 100644
--- a/jarvis/terminal/pty_manager.py
+++ b/jarvis/terminal/pty_manager.py
@@ -86,6 +86,10 @@ _EMPTY_READ_BACKOFF_S = 0.005
class PtySession:
"""Holds state for a running PTY session."""
+ #: The id this process currently answers to. Not a constant: reordering a
+ #: workspace's panes swaps two routes (``PtyManager.swap_sessions``), and
+ #: this field is what a consumer sends its replies back through, so it has
+ #: to move with the route rather than with the process.
terminal_id: str
shell_id: str
pid: int
@@ -295,6 +299,63 @@ class PtyManager:
logger.warning("PTY resize failed", terminal_id=terminal_id, error=str(exc))
return False
+ def swap_sessions(self, id_a: str, id_b: str) -> bool:
+ """Exchange which running PTY each of two terminal ids addresses.
+
+ After this returns ``True``, everything that reaches a session through
+ its id — ``write``, ``resize``, ``close``, ``has`` — reaches the OTHER
+ process: ``write(id_a, ...)`` types into the child that was spawned for
+ ``id_b``. Nothing about either child changes; only the routing does,
+ which is what lets a workspace reorder its panes without restarting the
+ agents living in them.
+
+ Both ids must currently name a live session. If either does not, the
+ swap is refused and the pool is left exactly as it was — a half-applied
+ swap would leave one id pointing at a process the other still believes
+ it owns. Swapping an id with itself is a no-op and reports success.
+
+ Two things travel with the process and two do not, and the split is
+ deliberate:
+
+ * The session's own ``terminal_id`` DOES move, because it is what a
+ consumer routes its replies back through: the pump hands it to
+ ``on_output``, and the Agentic IDE answers a CLI's terminal queries by
+ writing to exactly that id. Left behind, an agent's "what colour is
+ your screen?" would be answered into its neighbour's prompt.
+ * The output callbacks do NOT move. They were registered by the viewer
+ that started this child and belong to it — the pump keeps delivering
+ this process's output to the surface already showing it. A caller that
+ wants the two panes to trade PICTURES as well as keystrokes swaps its
+ own viewer slots; this layer has no idea a viewer exists.
+
+ A reader that samples ``session.terminal_id`` at the same moment as a
+ swap may see one of the two ids briefly stale — the pool lock cannot
+ cover an attribute read it does not mediate. The consequence is bounded
+ to one terminal-query reply landing in the wrong pane in the instant a
+ user drags a tab, and never affects a keystroke, which routes through
+ the locked dictionary.
+ """
+ with self._lock:
+ session_a = self._sessions.get(id_a)
+ session_b = self._sessions.get(id_b)
+ if session_a is None or session_b is None:
+ logger.debug(
+ "PTY swap refused — unknown terminal",
+ terminal_id=id_a,
+ other_terminal_id=id_b,
+ a_known=session_a is not None,
+ b_known=session_b is not None,
+ )
+ return False
+ if id_a == id_b:
+ return True
+ self._sessions[id_a] = session_b
+ self._sessions[id_b] = session_a
+ session_a.terminal_id = id_b
+ session_b.terminal_id = id_a
+ logger.info("PTY sessions swapped", terminal_id=id_a, other_terminal_id=id_b)
+ return True
+
def close(self, terminal_id: str) -> bool:
with self._lock:
session = self._sessions.pop(terminal_id, None)
@@ -351,8 +412,12 @@ class PtyManager:
gone or broken, and neither is a reason to stop draining a PTY that is
still producing — the transcript on the other side keeps filling and the
next viewer replays it.
+
+ The id is read from the session on every pass rather than captured once,
+ because ``swap_sessions`` can rename this process's route while the pump
+ is running and the consumer routes its replies back through whatever id
+ it is handed.
"""
- terminal_id = session.terminal_id
while True:
await session._wake.wait()
session._wake.clear()
@@ -361,13 +426,13 @@ class PtyManager:
if not text:
break
try:
- await on_output(terminal_id, text)
+ await on_output(session.terminal_id, text)
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 - the PTY outlives its viewer
logger.debug(
"PTY output callback failed",
- terminal_id=terminal_id,
+ terminal_id=session.terminal_id,
error=str(exc),
)
if session._finished:
@@ -376,18 +441,18 @@ class PtyManager:
if session._dropped_chars:
logger.warning(
"PTY viewer could not keep up — dropped the oldest output",
- terminal_id=terminal_id,
+ terminal_id=session.terminal_id,
dropped_chars=session._dropped_chars,
)
code = session._exit_code
try:
- await on_closed(terminal_id, -1 if code is None else code)
+ await on_closed(session.terminal_id, -1 if code is None else code)
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 - the viewer may be gone
logger.debug(
"PTY close callback failed",
- terminal_id=terminal_id,
+ terminal_id=session.terminal_id,
error=str(exc),
)
@@ -403,7 +468,6 @@ class PtyManager:
cost this module exists to avoid, and it is also what let a slow viewer
build an unbounded queue.
"""
- terminal_id = session.terminal_id
proc = session.proc
stop_flag = session.stop_flag
exit_code = -1
@@ -417,7 +481,7 @@ class PtyManager:
# Process closed / pipe broken — normal end of life.
logger.debug(
"PTY read exception (process presumably dead)",
- terminal_id=terminal_id,
+ terminal_id=session.terminal_id,
error=str(exc),
)
break
@@ -445,6 +509,6 @@ class PtyManager:
session.finish(exit_code, loop)
logger.info(
"PTY reader terminated",
- terminal_id=terminal_id,
+ terminal_id=session.terminal_id,
exit_code=exit_code,
)
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index e39978f8af..e9827ca398 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -77,6 +77,7 @@ log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/agentic-ide", tags=["agentic-ide"])
# One system folder window at a time — see ``open_native_picker``.
+from jarvis.agentic_ide.terminal_input import is_terminal_report_only
_native_picker_lock = asyncio.Lock()
@@ -1504,7 +1505,13 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
try:
term = await registry.attach(
- name, cols, rows, on_output, on_exit, workspace_id=pane_workspace
+ name,
+ cols,
+ rows,
+ on_output,
+ on_exit,
+ workspace_id=pane_workspace,
+ appearance=appearance,
)
except SessionError as exc:
# The reason used to travel to the browser and nowhere else, where it
@@ -1551,7 +1558,22 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
continue
kind = msg.get("t")
if kind == "i":
- registry.write(term.key, str(msg.get("d", "")), pane_workspace)
+ data = str(msg.get("d", ""))
+ # A browser that answers the terminal's protocol queries itself
+ # is answering a question this process already answered, at PTY
+ # speed and correctly — so its copy is a duplicate whenever it
+ # arrives, and lands in whatever the agent has open by then.
+ # Current clients suppress those replies at the source; this
+ # holds the line for a stale cached bundle and for the replayed
+ # screen, which re-triggers a query from minutes ago. Nobody
+ # types these sequences, so no keystroke is at risk.
+ if is_terminal_report_only(data):
+ log.debug(
+ "Agentic IDE: dropped a terminal protocol reply echoed by the pane for %s",
+ term.name,
+ )
+ else:
+ registry.write(term.key, data, pane_workspace)
elif kind == "r":
registry.resize(
term.key,
@@ -1724,3 +1746,10 @@ async def set_prompt_writer(payload: PromptWriterRequest) -> PromptWriterState:
__all__ = ["router"]
+
+ The optional ``appearance`` parameter (``light`` / ``dark``) is the ground
+ this pane is drawn on. It is what the agent's CLI is told when it asks the
+ terminal for its colours — a question answered in the backend rather than
+ by xterm, so the reply cannot arrive after the CLI stopped waiting for it
+ (see ``jarvis.agentic_ide.terminal_input``).
+ appearance = (qp.get("appearance") or "").strip().lower() or None
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
index 688855a04b..0507277d0c 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
@@ -29,6 +29,13 @@ vi.mock("@xterm/xterm", () => ({
rows = 24;
options: Record<string, unknown> = {};
unicode = { activeVersion: "" };
+ // A pane takes over the terminal's protocol replies on mount, because the
+ // backend answers those instead (see ./terminalQueries). A stand-in without
+ // a parser is a terminal xterm never shipped.
+ parser = {
+ registerOscHandler: () => ({ dispose() {} }),
+ registerCsiHandler: () => ({ dispose() {} }),
+ };
loadAddon() {}
open() {}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index f26dde429e..c01da9cbad 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -76,6 +76,7 @@ import { attachTerminalBridge } from "@/lib/editActions";
import { robustPaste } from "@/lib/clipboard";
import { installPasteBridge } from "./terminalPaste";
import { OffscreenBuffer } from "./offscreenBuffer";
+import { installQuerySuppression } from "./terminalQueries";
import { PaneScrollbar } from "./PaneScrollbar";
import { openPaneSocket, type PaneSocket } from "./paneSocket";
@@ -216,8 +217,14 @@ export function AgenticTerminal({
// and the text under it accumulate different sub-pixel offsets and the
// frame visibly bends. Monospace legibility comes from the line height.
letterSpacing: 0,
+ // The ground this pane draws on, as of NOW — the socket tells the backend, so
+ // that the agent's CLI is answered with the colours it is actually drawing on
+ // when it asks. Read at connect time, hence a ref rather than the prop: the
+ // connect effect must not re-run when the user flips the theme.
+ const appearanceRef = useRef(appearance);
cursorBlink: true,
cursorStyle: "bar",
+ appearanceRef.current = appearance;
scrollback: 10000,
// Required by the Unicode 11 width provider below.
allowProposedApi: true,
@@ -255,6 +262,12 @@ export function AgenticTerminal({
// the mounted element. A failure here is not fatal — xterm falls back to
// the DOM renderer, which draws correctly, just less crisply.
try {
+ // Before anything is written to this terminal: the agent's CLI asks what
+ // its terminal is and which colours it draws on within milliseconds of
+ // starting, and an answer produced HERE has to cross the socket twice
+ // before reaching it — too late, and then visible as junk in its prompt.
+ // The backend answers those instead. See ./terminalQueries.
+ const disposeQuerySuppression = installQuerySuppression(term.parser);
term.loadAddon(new CanvasAddon());
} catch {
/* no canvas in this environment — the DOM renderer still works */
@@ -350,7 +363,13 @@ export function AgenticTerminal({
resizeRef.current = sendResize;
socket = openPaneSocket(
- { name, workspaceId, cols: term.cols || 80, rows: term.rows || 24 },
+ {
+ name,
+ workspaceId,
+ cols: term.cols || 80,
+ rows: term.rows || 24,
+ appearance: appearanceRef.current,
+ },
{
onOpen: () => {
report("connecting");
@@ -503,6 +522,7 @@ export function AgenticTerminal({
term.clearTextureAtlas?.();
// Changing the font size changes the COLUMN COUNT. Fitting locally without
// telling the terminal process leaves the agent formatting for the old
+ disposeQuerySuppression();
// width — it keeps wrapping at 100 columns in a pane that now holds 80, and
// every line breaks in the wrong place. The two must move together, so this
// goes through the same resize path the observer uses.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
index 88e103876b..f51d415c8f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts
@@ -62,6 +62,16 @@ export interface PaneSocketOptions {
* different folder.
*/
workspaceId?: string | null;
+ /**
+ * The ground this pane draws on — `"light"` or `"dark"`.
+ *
+ * Sent because the SERVER answers the agent's "what colour is your screen?"
+ * query, not this browser: the reply has to reach the CLI within a
+ * millisecond or two of it asking, and one produced here would arrive a full
+ * round trip late — as visible junk in the agent's prompt. The server can
+ * only answer correctly if it knows what the pane looks like.
+ */
+ appearance?: string | null;
}
export interface PaneSocketHandlers {
@@ -92,6 +102,7 @@ function paneUrl(opts: PaneSocketOptions, ticket: string | null): string {
rows: String(opts.rows),
});
if (opts.workspaceId) query.set("workspace", opts.workspaceId);
+ if (opts.appearance) query.set("appearance", opts.appearance);
if (ticket) query.set("ticket", ticket);
return `${proto}://${window.location.host}/api/agentic-ide/pty/${encodeURIComponent(
opts.name,
diff --git a/jarvis/ultrawiki/embeddings.py b/jarvis/ultrawiki/embeddings.py
index ec629bccc3..8be2ae8611 100644
--- a/jarvis/ultrawiki/embeddings.py
+++ b/jarvis/ultrawiki/embeddings.py
@@ -24,6 +24,7 @@ backend's own adapter.
from __future__ import annotations
import logging
+import re
from collections.abc import Callable, Iterator
from typing import Any
@@ -78,6 +79,48 @@ _GEMINI_KEY_CANDIDATES: tuple[tuple[str, str], ...] = (
)
+#: Body keys that may carry a provider's machine-readable failure code. Every
+#: supported backend answers an error as a JSON object with a short slug under
+#: one of these, usually nested in an ``error`` object. Nothing here names a
+#: provider or a model (AP-21) — it is the shape of an error body, not a brand.
+_ERROR_CODE_KEYS: tuple[str, ...] = ("code", "type", "status", "reason")
+
+#: A failure code is a SLUG, not prose. Anything longer or wordier is a human
+#: message, and a message can quote the submitted text straight back — which
+#: must never reach a log line or the ``last_error`` column of an item row.
+_CODE_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.\-]{0,63}$")
+
+
+def _error_code(response: httpx.Response) -> str:
+ """The provider's short failure code, or ``""`` when it did not send one.
+
+ Why this exists: an embeddings endpoint answers ``HTTP 429`` both for "you
+ are sending too fast, wait a moment" and for "this account is out of
+ credit, nothing changes until someone acts". For a backlog those are
+ opposite situations — the first clears itself, the second never does — and
+ the status code alone cannot tell them apart. The body's code slug can
+ (``rate_limit_exceeded`` vs ``insufficient_quota``), so the pipeline is
+ given the chance to see it and stop presenting a dead queue as a busy one.
+
+ Only a slug is ever returned, never the human-readable message beside it:
+ this string is logged and stored on the item, and a provider is free to
+ echo the submitted text back inside a message.
+ """
+ try:
+ body = response.json()
+ except (ValueError, TypeError):
+ return ""
+ scopes = [body] if isinstance(body, dict) else []
+ if scopes and isinstance(body.get("error"), dict):
+ scopes.insert(0, body["error"])
+ for scope in scopes:
+ for key in _ERROR_CODE_KEYS:
+ value = scope.get(key)
+ if isinstance(value, str) and _CODE_PATTERN.match(value.strip()):
+ return value.strip().lower()
+ return ""
+
+
def _chunks(texts: list[str], size: int) -> Iterator[list[str]]:
for start in range(0, len(texts), size):
yield texts[start : start + size]
@@ -123,9 +166,12 @@ class _HttpEmbedding:
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as exc:
+ # The code slug rides along so the pipeline can tell a wait-and-
+ # retry rejection from one that needs the user (see _error_code).
+ code = _error_code(exc.response)
raise EmbeddingError(
f"{self.name}: embedding request failed with "
- f"HTTP {exc.response.status_code}"
+ f"HTTP {exc.response.status_code}" + (f" ({code})" if code else "")
) from exc
except httpx.HTTPError as exc:
raise EmbeddingError(
diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.py
index d37f5ea38f..a5c7731d35 100644
--- a/jarvis/ultrawiki/pipeline.py
+++ b/jarvis/ultrawiki/pipeline.py
@@ -46,7 +46,7 @@ import json
import logging
import time
from collections.abc import Awaitable, Callable
-from datetime import datetime
+from datetime import UTC, datetime
from typing import Any
from jarvis.ultrawiki.types import DocType, ItemState
@@ -81,6 +81,26 @@ EMBED_COOLDOWN_S = 600.0
#: "this item is poisoned": rate limit, out of credit, service unavailable.
_RATE_LIMIT_MARKERS = ("HTTP 429", "HTTP 402", "HTTP 503")
+#: ...and the words that mark the subset which will NOT clear by waiting. A
+#: rate limit ends on its own; an exhausted quota or an unpaid bill ends only
+#: when someone adds credit or points the slot at another backend. Both keep
+#: retrying — a topped-up account has to resume by itself — but only this one
+#: is worth putting in front of the user, because patience is not the fix.
+#:
+#: Matched against the provider's own failure SLUG
+#: (:func:`jarvis.ultrawiki.embeddings._error_code`), never against a provider
+#: name or model id (AP-21): any backend with a billing state names it with one
+#: of these words, and one without simply never matches.
+_QUOTA_WORDS = (
+ "quota",
+ "billing",
+ "credit",
+ "payment",
+ "insufficient",
+ "exhausted",
+ "suspended",
+)
+
def _rate_limited_embed(exc: BaseException) -> bool:
"""True for an EmbeddingError carrying a rate/quota/unavailable status.
@@ -93,6 +113,19 @@ def _rate_limited_embed(exc: BaseException) -> bool:
message = str(exc)
return any(marker in message for marker in _RATE_LIMIT_MARKERS)
+
+def _embed_block_needs_attention(message: str) -> bool:
+ """Does this rejection require a human, or will it clear by itself?
+
+ ``HTTP 402`` (payment required) always does. ``HTTP 429`` does only when
+ the provider's code slug says the problem is the account rather than the
+ pace — otherwise it is an ordinary rate limit and the cooldown handles it.
+ """
+ lowered = message.lower()
+ if "http 402" in lowered:
+ return True
+ return "http 429" in lowered and any(word in lowered for word in _QUOTA_WORDS)
+
#: Media enrichment claims ONE item per pass, and only when every other stage
#: found nothing to do. Describing a picture costs a model call, and a photo
#: library is tens of thousands of them — so this lane is deliberately the
@@ -154,6 +187,13 @@ def _summary_text(
return "\n".join(parts)
+def _utc_now_iso() -> str:
+ """Wall-clock UTC stamp for the embed block. Deliberately NOT the
+ monotonic clock the cooldown uses: this one is shown to a person, and
+ "since 2026-07-26T18:14Z" is what makes a standstill legible."""
+ return datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
+
+
def _string_field(mapping: dict[str, Any], key: str) -> str:
return str(mapping.get(key) or "").strip()
@@ -203,6 +243,11 @@ class PipelineWorker:
#: monotonic deadline until which the embedding-dependent stages rest
#: after a rate/quota rejection (0.0 = no cooldown).
self._embed_cooldown_until = 0.0
+ #: The live provider-level embedding block, or ``None`` while vectors
+ #: are coming back. Survives the individual cooldown naps: what matters
+ #: to a reader is "this has been refused since yesterday evening", not
+ #: "the current ten-minute rest has four minutes left".
+ self._embed_block: dict[str, Any] | None = None
# -- public surface ------------------------------------------------------
@@ -210,6 +255,27 @@ class PipelineWorker:
"""Copy of the per-stage processed counters."""
return dict(self.processed)
+ def embed_block(self) -> dict[str, Any] | None:
+ """The live provider-level embedding block, or ``None``.
+
+ ``reason`` (the provider's honest answer), ``needs_attention`` (waiting
+ will not fix it), ``since`` (UTC ISO of the FIRST rejection in this
+ streak) and ``rejections`` (how many since).
+
+ The service reads this so ``/api/ultrawiki/status`` can report what the
+ worker already knows. Without it the two disagreed in the worst
+ possible direction: the embedding SLOT probe is a credential check by
+ contract (AP-21), so a key that exists but is out of quota probes
+ ``ready`` — and the overview kept saying "still filling up, you do not
+ have to wait" over a queue that had not advanced past keyword indexing
+ in fifteen hours, with "Nothing needs your attention" underneath
+ (observed live 2026-07-27). One concept, known in one layer, never
+ carried to the layer that speaks: the drift class of BUG-008 again.
+
+ A copy, so a status reader cannot mutate the worker's state.
+ """
+ return dict(self._embed_block) if self._embed_block is not None else None
+
async def run(self, cancel_event: asyncio.Event) -> None:
"""The worker loop: run passes until *cancel_event* is set.
@@ -276,10 +342,19 @@ class PipelineWorker:
"UltraWiki: mark_retry failed for item %s", item.get("id")
)
- def _note_stage_pause(self, stage: str, reason: str) -> None:
- """Log an honest 'stage paused' line once per reason change."""
- if self._pause_reasons.get(stage) != reason:
- self._pause_reasons[stage] = reason
+ def _note_stage_pause(self, stage: str, reason: str, *, key: str = "") -> None:
+ """Log an honest 'stage paused' line once per reason change.
+
+ *key* is what "the same reason" means for deduplication, defaulting to
+ the sentence itself. The cooldown reason carries a live countdown, so
+ deduplicating on the text logged the identical standstill every time
+ the remaining minute ticked over — 2 614 lines of it in one session's
+ log, which is precisely how a real, permanent block hides in plain
+ sight.
+ """
+ marker = key or reason
+ if self._pause_reasons.get(stage) != marker:
+ self._pause_reasons[stage] = marker
log.info("UltraWiki %s stage paused: %s", stage, reason)
def _clear_stage_pause(self, stage: str) -> None:
@@ -294,13 +369,53 @@ class PipelineWorker:
cooldown ends.
"""
self._embed_cooldown_until = time.monotonic() + EMBED_COOLDOWN_S
- log.warning(
- "UltraWiki embedding provider rejected with a rate/quota answer "
- "(%s) — resting the embed and distill stages for %.0f minutes "
- "instead of hammering it per item",
- exc,
- EMBED_COOLDOWN_S / 60.0,
- )
+ message = str(exc)
+ previous = self._embed_block or {}
+ first = bool(not previous)
+ self._embed_block = {
+ "reason": message,
+ "needs_attention": _embed_block_needs_attention(message),
+ # The streak's START, never the current nap's — a reader needs to
+ # know this has been refused since yesterday, not that the latest
+ # ten-minute rest began a moment ago.
+ "since": str(previous.get("since") or _utc_now_iso()),
+ "rejections": int(previous.get("rejections") or 0) + 1,
+ }
+ # Only the FIRST rejection of a streak warns. A permanent block would
+ # otherwise write a fresh warning every ten minutes forever, and a log
+ # that repeats itself is a log nobody reads.
+ if first:
+ log.warning(
+ "UltraWiki embedding provider rejected with a rate/quota answer "
+ "(%s) — resting the embed and distill stages for %.0f minutes "
+ "instead of hammering it per item%s",
+ exc,
+ EMBED_COOLDOWN_S / 60.0,
+ (
+ ". This will not clear by waiting: add credit to that "
+ "provider or choose another embedding backend"
+ if self._embed_block["needs_attention"]
+ else ""
+ ),
+ )
+
+ def _note_embed_success(self) -> None:
+ """A vector came back — whatever the provider was refusing is over.
+
+ Called on every successful embed call rather than only after a block,
+ so a topped-up account or a passing rate limit clears the standstill
+ report by itself. Nothing about recovery may require a restart.
+ """
+ block = self._embed_block
+ if block is not None:
+ log.info(
+ "UltraWiki embedding provider recovered after %d rejection(s) "
+ "since %s — the embed and distill stages resume",
+ int(block.get("rejections") or 0),
+ block.get("since"),
+ )
+ self._embed_block = None
+ self._embed_cooldown_until = 0.0
def _embed_cooldown_reason(self) -> str:
"""Honest pause reason while the cooldown runs, else ``""``."""
@@ -536,7 +651,8 @@ class PipelineWorker:
return 0
cooldown = self._embed_cooldown_reason()
if cooldown:
- self._note_stage_pause("embed", cooldown)
+ # A stable dedup key, because the sentence carries a countdown.
+ self._note_stage_pause("embed", cooldown, key="embed-cooldown")
return 0
self._clear_stage_pause("embed")
items = await self._store.claim_batch(
@@ -555,6 +671,7 @@ class PipelineWorker:
raise RuntimeError(
f"backend returned {len(vectors)} vectors for {len(texts)} texts"
)
+ self._note_embed_success()
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 — fall back to per-item embedding
@@ -611,6 +728,7 @@ class PipelineWorker:
f"backend returned {len(vectors)} vectors for "
f"{len(chunks)} passages"
)
+ self._note_embed_success()
await self._store_embedded(item, chunks, vectors, model)
except asyncio.CancelledError:
raise
@@ -675,7 +793,7 @@ class PipelineWorker:
if cooldown:
# The distilled summary must be embedded too, so this stage rests
# through the same provider cooldown as the embed pass.
- self._note_stage_pause("distill", cooldown)
+ self._note_stage_pause("distill", cooldown, key="embed-cooldown")
return 0
distill_ok, distill_reason = await self._distill_ready()
if not distill_ok:
@@ -779,6 +897,7 @@ class PipelineWorker:
vectors = await backend.embed([text], model=model)
if not vectors:
raise RuntimeError("backend returned no vector for the summary text")
+ self._note_embed_success()
await self._store.store_embedding(
doc_id, model=model, dim=len(vectors[0]), vector=vectors[0]
)
diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.py
index 91272c1d2d..9a2864e833 100644
--- a/jarvis/ultrawiki/service.py
+++ b/jarvis/ultrawiki/service.py
@@ -610,13 +610,31 @@ class UltraWikiService:
# Every slot probe walks credentials (keyring / .env) or an endpoint —
# all three go to a worker thread together, never on the event loop.
slots = await asyncio.to_thread(self._slot_statuses)
+ # What the WORKER has actually been told by the provider. The slot
+ # probe above is a credential check by contract (AP-21), so it cannot
+ # see a key that exists and is refused; only the worker can, and
+ # without carrying it here the status route reported a busy pipeline
+ # over a lane that had been dead for fifteen hours.
+ embed_block = (
+ self._pipeline.embed_block() if self._pipeline is not None else None
+ )
+ if embed_block:
+ embedding_slot = dict(slots.get("embedding") or {})
+ slots["embedding"] = {
+ **embedding_slot,
+ "ready": False,
+ "reason": str(embed_block.get("reason") or "")
+ or str(embedding_slot.get("reason") or ""),
+ "blocked_since": embed_block.get("since"),
+ "needs_attention": bool(embed_block.get("needs_attention")),
+ }
# ONE derivation of "how far along" for every surface that asks (the
# strip, the checklist, the overview). See jarvis/ultrawiki/progress.py
# for the screenshot that made a second derivation unacceptable.
counts_payload = _counts_dict(counts)
progress = build_progress(counts_payload)
state, reason = self._pipeline_state(
- progress, sources, slots, running=pipeline_running
+ progress, sources, slots, running=pipeline_running, embed_block=embed_block
)
return {
"enabled": self._uw_enabled(),
@@ -636,6 +654,14 @@ class UltraWikiService:
"state": state,
"reason": reason,
"processed": processed,
+ # Shipped separately from the sentence so a surface can style a
+ # standstill that needs the user differently from one that
+ # clears itself, without parsing prose.
+ "blocked": bool(embed_block),
+ "blocked_needs_attention": bool(
+ (embed_block or {}).get("needs_attention")
+ ),
+ "blocked_since": (embed_block or {}).get("since"),
},
"sources": sources,
"jobs": _list_job_snapshots(10),
@@ -658,15 +684,21 @@ class UltraWikiService:
slots: dict[str, Any],
*,
running: bool,
+ embed_block: dict[str, Any] | None = None,
) -> tuple[str, str]:
"""``(state, honest English reason)`` for the import-progress strip.
"Pipeline running" on a fresh activation with zero approved sources
read as "something is already pulling my data" — the exact opposite of
the consent contract. A live worker LOOP is not the same thing as work
- being done, so the strip states which of the four situations holds:
- nothing approved yet, nothing left to do, actually processing, or
- blocked on a slot. ``running`` is still reported separately.
+ being done, so the strip states which of the five situations holds:
+ nothing approved yet, nothing left to do, actually processing, blocked
+ on a slot, or — *embed_block* — refused by a provider that answers but
+ will not serve. ``running`` is still reported separately.
+
+ The last one has to be passed in because it cannot be derived here: a
+ slot probe is a credential check by contract (AP-21) and reports a
+ depleted key as ``ready``. Only the worker has been told otherwise.
Takes the shared progress model rather than raw counts: the backlog
this function reports and the backlog the checklist reports must be
@@ -709,6 +741,35 @@ class UltraWikiService:
distill_ready = bool((slots.get("distill") or {}).get("ready"))
distill_reason = str((slots.get("distill") or {}).get("reason") or "")
+ # A provider that is REFUSING outranks every other reading of the
+ # queue, including a keyword lane that is still moving. The lane that
+ # is standing still is the one carrying summaries and semantic search,
+ # and reporting "processing" because the free stage still ticks is how
+ # a fifteen-hour standstill kept rendering as a healthy import with
+ # "Nothing needs your attention" underneath it.
+ if embed_block and (pending_embed or pending_distill):
+ still_running = (
+ f" Keyword indexing is unaffected and still running "
+ f"({pending_keyword} item(s) to go), so new items keep "
+ "becoming findable by exact words."
+ if pending_keyword
+ else ""
+ )
+ advice = (
+ " Waiting will not clear this: add credit to that provider, or "
+ "switch the embedding backend in the UltraWiki settings."
+ if embed_block.get("needs_attention")
+ else " The pipeline retries on its own."
+ )
+ return "paused", (
+ f"{pending_embed + pending_distill} item(s) are waiting for the "
+ "embedding stage, which the provider is refusing: "
+ f"{embed_block.get('reason') or embed_reason}."
+ + advice
+ + still_running
+ + failed_note
+ )
+
if pending_keyword > 0:
blocked = ""
if pending_embed and not embed_ready:
diff --git a/tests/unit/terminal/test_pty_swap.py b/tests/unit/terminal/test_pty_swap.py
new file mode 100644
index 0000000000..a2727bb016
--- /dev/null
+++ b/tests/unit/terminal/test_pty_swap.py
@@ -0,0 +1,274 @@
+"""Swapping which PTY a terminal id addresses — what reordering panes costs.
+
+The contract these pin down (see ``PtyManager.swap_sessions``):
+
+* after a swap, EVERY id-addressed operation reaches the other process —
+ ``write``, ``resize`` and ``close`` must not disagree about who is who,
+* an id that names nothing refuses the swap and changes nothing, so a failed
+ reorder can never leave one pane typing into another pane's agent,
+* the session's own ``terminal_id`` moves with the route, because that is what
+ a consumer routes a reply back through,
+* the running children are untouched: a swap reorders a workspace, it does not
+ restart the agents in it.
+
+All OS legs: the PTY itself is a fake handle, so nothing here needs a real
+pseudo-terminal (or a coding agent) on the machine running the suite.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+
+import pytest
+
+import jarvis.terminal.pty_manager as pty_mod
+from jarvis.terminal.pty_manager import PtyManager
+
+
+class ScriptedHandle:
+ """A ``PtyHandle`` that records what was written and never blocks."""
+
+ def __init__(self, label: str) -> None:
+ self.label = label
+ self.pid = 4242
+ self.exitstatus: int | None = None
+ self._chunks: deque[str] = deque()
+ self._eof = False
+ self._alive = True
+ self.written: list[str] = []
+ self.sizes: list[tuple[int, int]] = []
+ self.terminated = False
+
+ # --- test-facing -------------------------------------------------
+ def feed(self, *chunks: str) -> None:
+ self._chunks.extend(chunks)
+
+ # --- PtyHandle ---------------------------------------------------
+ def write(self, data: str) -> None:
+ self.written.append(data)
+
+ def setwinsize(self, rows: int, cols: int) -> None:
+ self.sizes.append((rows, cols))
+
+ def read(self, size: int) -> str:
+ if self._chunks:
+ return self._chunks.popleft()
+ if self._eof:
+ self._alive = False
+ raise EOFError
+ return ""
+
+ def isalive(self) -> bool:
+ return self._alive
+
+ def terminate(self, force: bool) -> None:
+ self.terminated = True
+ self._alive = False
+ self._eof = True
+ if self.exitstatus is None:
+ self.exitstatus = 0
+
+
+class HandOutBackend:
+ """Hands out the queued handles in order, one per spawn."""
+
+ def __init__(self, handles: list[ScriptedHandle]) -> None:
+ self._handles = deque(handles)
+
+ def spawn(self, argv, cwd, cols, rows, env=None): # noqa: ANN001, ANN201
+ return self._handles.popleft()
+
+
+def handles(monkeypatch) -> tuple[ScriptedHandle, ScriptedHandle]: # noqa: ANN001
+ first, second = ScriptedHandle("A"), ScriptedHandle("B")
+ backend = HandOutBackend([first, second])
+ monkeypatch.setattr(pty_mod, "make_pty_backend", lambda: backend)
+ return first, second
+
+
+async def _spawn(manager: PtyManager, shell_id: str): # noqa: ANN202
+ async def _sink(_tid: str, _text: str) -> None:
+ return None
+
+ async def _closed(_tid: str, _code: int) -> None:
+ return None
+
+ return await manager.spawn(
+ shell_argv=("agent",),
+ shell_id=shell_id,
+ cwd=None,
+ cols=80,
+ rows=24,
+ on_output=_sink,
+ on_closed=_closed,
+ )
+
+
+async def _two(manager: PtyManager) -> tuple[str, str]:
+ a = await _spawn(manager, "pane-a")
+ b = await _spawn(manager, "pane-b")
+ return a.terminal_id, b.terminal_id
+
+
+async def test_write_follows_the_swap(handles: tuple[ScriptedHandle, ScriptedHandle]) -> None:
+ """Typing into a swapped id reaches the other pane's agent."""
+ handle_a, handle_b = handles
+ manager = PtyManager()
+ id_a, id_b = await _two(manager)
+
+ assert manager.swap_sessions(id_a, id_b) is True
+
+ assert manager.write(id_a, "to-b") is True
+ assert manager.write(id_b, "to-a") is True
+
+ assert handle_b.written == ["to-b"]
+ assert handle_a.written == ["to-a"]
+
+ manager.close_all()
+
+
+async def test_resize_and_close_agree_with_write(
+ handles: tuple[ScriptedHandle, ScriptedHandle],
+) -> None:
+ """Every id-addressed operation moves together — one that lagged behind
+ would resize one agent's screen and kill the other's process."""
+ handle_a, handle_b = handles
+ manager = PtyManager()
+ id_a, id_b = await _two(manager)
+ manager.swap_sessions(id_a, id_b)
+
+ assert manager.resize(id_a, 100, 30) is True
+ assert handle_b.sizes[-1] == (30, 100)
+ assert handle_a.sizes == []
+
+ assert manager.has(id_a) is True
+ assert manager.close(id_a) is True
+ assert handle_b.terminated is True
+ assert handle_a.terminated is False
+ # The surviving id still addresses the process it was swapped onto.
+ assert manager.has(id_a) is False
+ assert manager.write(id_b, "still here") is True
+ assert handle_a.written == ["still here"]
+
+ manager.close_all()
+
+
+async def test_the_session_id_travels_with_the_route(
+ handles: tuple[ScriptedHandle, ScriptedHandle],
+) -> None:
+ """A consumer answers a CLI by writing to the id it was handed, so the id
+ has to name the process that asked."""
+ handle_a, handle_b = handles
+ manager = PtyManager()
+ session_a = await _spawn(manager, "pane-a")
+ session_b = await _spawn(manager, "pane-b")
+ id_a, id_b = session_a.terminal_id, session_b.terminal_id
+
+ manager.swap_sessions(id_a, id_b)
+
+ assert session_a.terminal_id == id_b
+ assert session_b.terminal_id == id_a
+ # Round trip: replying to the id the pump reports reaches the same child.
+ manager.write(session_b.terminal_id, "reply")
+ assert handle_b.written == ["reply"]
+ assert handle_a.written == []
+
+ manager.close_all()
+
+
+async def test_the_pump_reports_the_swapped_id(
+ handles: tuple[ScriptedHandle, ScriptedHandle],
+) -> None:
+ """Output produced after a swap is announced under the id that now
+ addresses it — the pump must not keep using the one it started with."""
+ handle_a, _handle_b = handles
+ seen: list[tuple[str, str]] = []
+ ready = asyncio.Event()
+
+ async def on_output(tid: str, text: str) -> None:
+ seen.append((tid, text))
+ ready.set()
+
+ async def on_closed(_tid: str, _code: int) -> None:
+ return None
+
+ manager = PtyManager()
+ session_a = await manager.spawn(
+ shell_argv=("agent",),
+ shell_id="pane-a",
+ cwd=None,
+ cols=80,
+ rows=24,
+ on_output=on_output,
+ on_closed=on_closed,
+ )
+ session_b = await _spawn(manager, "pane-b")
+ id_a, id_b = session_a.terminal_id, session_b.terminal_id
+
+ manager.swap_sessions(id_a, id_b)
+ handle_a.feed("after the swap")
+ await asyncio.wait_for(ready.wait(), timeout=3.0)
+
+ assert seen == [(id_b, "after the swap")]
+ assert session_b.terminal_id == id_a # unrelated pane still consistent
+
+ manager.close_all()
+
+
+async def test_an_unknown_id_refuses_and_changes_nothing(
+ handles: tuple[ScriptedHandle, ScriptedHandle],
+) -> None:
+ """A half-applied swap would leave one id pointing at a process the other
+ still believes it owns, so a refusal has to be total."""
+ handle_a, handle_b = handles
+ manager = PtyManager()
+ id_a, id_b = await _two(manager)
+
+ assert manager.swap_sessions(id_a, "no-such-terminal") is False
+ assert manager.swap_sessions("no-such-terminal", id_b) is False
+ assert manager.swap_sessions("neither", "nor") is False
+
+ manager.write(id_a, "a")
+ manager.write(id_b, "b")
+ assert handle_a.written == ["a"]
+ assert handle_b.written == ["b"]
+
+ manager.close_all()
+
+
+async def test_swapping_an_id_with_itself_is_a_no_op(
+ handles: tuple[ScriptedHandle, ScriptedHandle],
+) -> None:
+ """Dropping a tab back where it came from is a successful reorder of
+ nothing, not a failure the UI has to explain."""
+ handle_a, _handle_b = handles
+ manager = PtyManager()
+ id_a, _id_b = await _two(manager)
+
+ assert manager.swap_sessions(id_a, id_a) is True
+ manager.write(id_a, "unchanged")
+ assert handle_a.written == ["unchanged"]
+
+ assert manager.swap_sessions("gone", "gone") is False
+
+ manager.close_all()
+
+
+async def test_a_swap_does_not_restart_anything(
+ handles: tuple[ScriptedHandle, ScriptedHandle],
+) -> None:
+ """The point of reordering panes is keeping the agents alive."""
+ handle_a, handle_b = handles
+ manager = PtyManager()
+ id_a, id_b = await _two(manager)
+
+ manager.swap_sessions(id_a, id_b)
+
+ assert handle_a.isalive() is True
+ assert handle_b.isalive() is True
+ assert handle_a.terminated is False
+ assert handle_b.terminated is False
+
+ manager.close_all()
diff --git a/tests/unit/ultrawiki/test_embeddings.py b/tests/unit/ultrawiki/test_embeddings.py
index 117ba53237..9a225b447b 100644
--- a/tests/unit/ultrawiki/test_embeddings.py
+++ b/tests/unit/ultrawiki/test_embeddings.py
@@ -362,3 +362,69 @@ def test_available_backends_uses_configured_ollama_endpoint(monkeypatch, no_secr
"reason": "",
"default_model": DEFAULT_MODELS["ollama"],
}
+
+
+# ---------------------------------------------------------------------------
+# The failure CODE beside the status (jarvis.ultrawiki.embeddings._error_code)
+# ---------------------------------------------------------------------------
+
+
+def test_an_exhausted_quota_is_distinguishable_from_a_rate_limit(fake_secrets):
+ """Both answer HTTP 429, and for a backlog they are opposites: one clears
+ itself, the other never does. Only the body's code slug can tell them
+ apart, so it has to survive into the error text the pipeline reads."""
+
+ def refuse(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 429,
+ json={
+ "error": {
+ "message": "You exceeded your current quota, please check "
+ "your plan and billing details.",
+ "type": "insufficient_quota",
+ "code": "insufficient_quota",
+ }
+ },
+ )
+
+ backend = OpenAIEmbedding(transport=httpx.MockTransport(refuse))
+ with pytest.raises(EmbeddingError) as excinfo:
+ import asyncio
+
+ asyncio.run(backend.embed(["hello"], model="text-embedding-3-small"))
+
+ message = str(excinfo.value)
+ assert "HTTP 429" in message
+ assert "insufficient_quota" in message
+
+
+def test_the_error_text_never_carries_the_providers_prose(fake_secrets):
+ """A message can quote the submitted text straight back, and this string
+ is logged and stored on the item row. Only a slug is ever taken."""
+
+ def refuse(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 400,
+ json={"error": {"message": "Invalid input: 'my private note text'"}},
+ )
+
+ backend = OpenAIEmbedding(transport=httpx.MockTransport(refuse))
+ with pytest.raises(EmbeddingError) as excinfo:
+ import asyncio
+
+ asyncio.run(backend.embed(["my private note text"], model="m"))
+
+ message = str(excinfo.value)
+ assert "HTTP 400" in message
+ assert "private note" not in message
+
+
+def test_a_body_without_a_code_still_yields_an_honest_error(fake_secrets):
+ def refuse(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(503, text="upstream unavailable")
+
+ backend = OpenAIEmbedding(transport=httpx.MockTransport(refuse))
+ with pytest.raises(EmbeddingError, match="HTTP 503"):
+ import asyncio
+
+ asyncio.run(backend.embed(["hello"], model="m"))
diff --git a/tests/unit/ultrawiki/test_pipeline.py b/tests/unit/ultrawiki/test_pipeline.py
index a1e297ade8..fd9c73e7f5 100644
--- a/tests/unit/ultrawiki/test_pipeline.py
+++ b/tests/unit/ultrawiki/test_pipeline.py
@@ -447,6 +447,131 @@ async def test_distill_pass_rests_through_the_embed_cooldown(store):
assert await worker._distill_pass() == 0 # noqa: SLF001
+async def test_an_exhausted_quota_is_reported_as_needing_a_human(store):
+ """The forensic case of 2026-07-27.
+
+ An OpenAI key with no credit answers ``HTTP 429 (insufficient_quota)``
+ forever. The cooldown handled it correctly and silently, so the worker
+ napped ten minutes at a time for fifteen hours while every surface above
+ reported a healthy import. The block is now visible, and it says whether
+ waiting is the fix.
+ """
+ from jarvis.ultrawiki.embeddings import EmbeddingError
+
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: FakeEmbeddingBackend(),
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ worker._begin_embed_cooldown( # noqa: SLF001 — drive the branch deliberately
+ EmbeddingError("fake: embedding request failed with HTTP 429 (insufficient_quota)")
+ )
+
+ block = worker.embed_block()
+ assert block is not None
+ assert block["needs_attention"] is True, "no amount of waiting adds credit"
+ assert "insufficient_quota" in block["reason"]
+ assert block["rejections"] == 1
+ assert block["since"].endswith("Z")
+
+
+async def test_an_ordinary_rate_limit_does_not_cry_for_help(store):
+ """The other half of the same 429: going too fast fixes itself, and a
+ surface that shouts about it teaches people to ignore the shouting."""
+ from jarvis.ultrawiki.embeddings import EmbeddingError
+
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: FakeEmbeddingBackend(),
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ worker._begin_embed_cooldown( # noqa: SLF001
+ EmbeddingError("fake: embedding request failed with HTTP 429 (rate_limit_exceeded)")
+ )
+
+ block = worker.embed_block()
+ assert block is not None
+ assert block["needs_attention"] is False
+
+
+async def test_the_block_dates_from_the_first_refusal_not_the_latest_nap(store):
+ """What a reader needs is "refused since yesterday evening", not "this
+ ten-minute rest started a moment ago"."""
+ from jarvis.ultrawiki.embeddings import EmbeddingError
+
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: FakeEmbeddingBackend(),
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ error = EmbeddingError("fake: embedding request failed with HTTP 429 (insufficient_quota)")
+ worker._begin_embed_cooldown(error) # noqa: SLF001
+ first_seen = worker.embed_block()["since"]
+ worker._begin_embed_cooldown(error) # noqa: SLF001
+ worker._begin_embed_cooldown(error) # noqa: SLF001
+
+ block = worker.embed_block()
+ assert block["since"] == first_seen, "the streak keeps its start"
+ assert block["rejections"] == 3
+
+
+async def test_a_vector_coming_back_clears_the_block_without_a_restart(store):
+ """Recovery is the provider's to announce, and it announces it by
+ answering. A topped-up account must resume on its own."""
+ from jarvis.ultrawiki.embeddings import EmbeddingError
+
+ await store.upsert_items("src1", [make_item(1)])
+ backend = FakeEmbeddingBackend()
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: backend,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ worker._begin_embed_cooldown( # noqa: SLF001
+ EmbeddingError("fake: embedding request failed with HTTP 429 (insufficient_quota)")
+ )
+ assert worker.embed_block() is not None
+
+ worker._embed_cooldown_until = 0.0 # noqa: SLF001 — cooldown elapsed
+ await worker._keyword_pass() # noqa: SLF001
+ await worker._embed_pass() # noqa: SLF001 — the provider answers again
+
+ assert worker.embed_block() is None
+ assert worker.processed_counts()["embed"] == 1
+
+
+async def test_a_standstill_is_logged_once_not_every_countdown_tick(store, caplog):
+ """The pause sentence carries a live countdown, so deduplicating on the
+ text logged the same standstill every time the minute changed — 2 614
+ identical lines in one session, which is how a real block hides."""
+ from jarvis.ultrawiki.embeddings import EmbeddingError
+
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: FakeEmbeddingBackend(),
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ worker._begin_embed_cooldown( # noqa: SLF001
+ EmbeddingError("fake: embedding request failed with HTTP 429 (insufficient_quota)")
+ )
+ with caplog.at_level("INFO", logger="jarvis.ultrawiki.pipeline"):
+ for _ in range(5):
+ await worker._embed_pass() # noqa: SLF001
+
+ paused = [r for r in caplog.records if "embed stage paused" in r.getMessage()]
+ assert len(paused) == 1, "one standstill, one line"
+
+
async def test_a_long_item_is_embedded_as_many_passages_not_truncated(store):
"""The change that makes full-depth ingestion mean anything.
diff --git a/tests/unit/ultrawiki/test_service.py b/tests/unit/ultrawiki/test_service.py
index 1d8e546d53..db43f6a252 100644
--- a/tests/unit/ultrawiki/test_service.py
+++ b/tests/unit/ultrawiki/test_service.py
@@ -506,6 +506,74 @@ async def test_pipeline_state_is_paused_when_the_embedding_slot_blocks(
assert status["slots"]["embedding"]["ready"] is False
+async def test_a_refusing_embedding_provider_is_reported_even_while_keywords_flow(
+ service, monkeypatch
+):
+ """The forensic case of 2026-07-27, end to end.
+
+ An OpenAI key with no credit answered ``HTTP 429 (insufficient_quota)``
+ for fifteen hours. The keyword lane needs no model, so it kept ticking —
+ and because it did, the strip reported "processing", the checklist said
+ "you do not have to wait", and the problem list said "Nothing needs your
+ attention" over a corpus where not one item had gained a summary since the
+ previous evening.
+
+ The slot probe cannot see this by contract: it is a CREDENTIAL check
+ (AP-21), and the key exists. Only the worker holds the provider's actual
+ answer, so the test that matters is that the answer reaches the payload.
+ """
+ from jarvis.ultrawiki.embeddings import EmbeddingError
+ from jarvis.ultrawiki.health import build_health
+
+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(6), [])})
+ source = await service.add_source("fake-conn", "Fake Source")
+ await service.approve_source(source["id"], auto_sync=False)
+ await wait_for_job(service, await service.start_sync(source["id"]))
+
+ # Half the corpus past the keyword gate, half still behind it — exactly
+ # the live shape, where the free stage still has work to show.
+ store = service._require_store()
+ for item in await store.claim_batch("keyword_indexed", limit=3):
+ await store.mark_stage_done(
+ item["id"],
+ "keyword_indexed",
+ fts_title=item["title"],
+ fts_body=item["body_raw"],
+ )
+
+ # A credential-ready slot, so nothing but the worker's knowledge can
+ # produce the honest verdict.
+ service._cfg.ultrawiki.embedding_provider = "fake-ready"
+ monkeypatch.setattr(
+ service,
+ "_embedding_slot_status",
+ lambda: {"provider": "fake-ready", "model": "m", "ready": True, "reason": ""},
+ )
+ service._pipeline._begin_embed_cooldown(
+ EmbeddingError("fake: embedding request failed with HTTP 429 (insufficient_quota)")
+ )
+
+ status = await service.status()
+
+ assert status["pipeline"]["state"] == "paused", "a refused lane is not progress"
+ assert status["pipeline"]["blocked"] is True
+ assert status["pipeline"]["blocked_needs_attention"] is True
+ reason = status["pipeline"]["reason"]
+ assert "insufficient_quota" in reason
+ assert "will not clear" in reason, "it has to say waiting is not the fix"
+ assert "Keyword indexing" in reason, "and what IS still moving"
+ # The slot stops claiming to be usable, whatever the credential says.
+ assert status["slots"]["embedding"]["ready"] is False
+ assert status["slots"]["embedding"]["needs_attention"] is True
+
+ # ...and the row that used to say "you do not have to wait" now asks.
+ processing = next(
+ c for c in build_health(status)["checks"] if c["id"] == "processing"
+ )
+ assert processing["state"] == "attention"
+ assert "insufficient_quota" in processing["detail"]
+
+
async def test_pipeline_state_is_processing_with_a_claimable_backlog(
service, monkeypatch
):