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.

fix(agentic-ide): wait for writable Codex terminals

rubenluetke10-beep86873d227e03
diff --git a/jarvis/agentic_ide/fleet_actions.py b/jarvis/agentic_ide/fleet_actions.py
index ffe9340fcf..72e62b9004 100644
--- a/jarvis/agentic_ide/fleet_actions.py
+++ b/jarvis/agentic_ide/fleet_actions.py
@@ -13,7 +13,7 @@ _INPUT_MARKERS = ("›", "❯", ">")
log = logging.getLogger(__name__)
-def _ready_for_prompt(term: Any) -> bool:
+def ready_for_prompt(term: Any) -> bool:
"""Is this pane far enough along to be typed into?
Every CLI observed so far swallows a prompt that arrives while it is still
@@ -37,29 +37,59 @@ def _ready_for_prompt(term: Any) -> bool:
return True
transcript = getattr(term, "transcript", None)
if transcript is None:
- return True
+ return False
try:
- lines = transcript.tail(30)
+ # Read the visible bottom of the current screen when it is available.
+ # Transcript history can contain old prompt sigils from the conversation
+ # being resumed; treating one of those as the new input box is the same
+ # early-write bug with a more convincing false positive.
+ screen = getattr(transcript, "screen", None)
+ display = getattr(screen, "display", None)
+ lines = display()[-10:] if callable(display) else transcript.tail(10)
except Exception: # noqa: BLE001 - a test double may expose no real buffer
- return True
+ return False
markers = (spec.input_markers if spec else ()) or _INPUT_MARKERS
+ if spec is not None and spec.requires_visible_input_cursor:
+ # Codex renders the same sigil when its composer is disabled, but its
+ # Ratatui frame hides the cursor in that state. The visible cursor is
+ # placed back on the editable row only when key events are accepted.
+ try:
+ visible_cursor = getattr(screen, "visible_cursor", None)
+ row_text = getattr(screen, "row_text", None)
+ if visible_cursor is None or not callable(row_text):
+ return False
+ row, column = visible_cursor
+ line = row_text(row)
+ except Exception: # noqa: BLE001 - malformed extensions fail closed
+ return False
+ stripped = line.lstrip()
+ for marker in markers:
+ if stripped.startswith(marker):
+ marker_column = len(line) - len(stripped)
+ return column > marker_column
+ return False
return any(line.strip().startswith(markers) for line in lines)
+def _ready_for_prompt(term: Any) -> bool:
+ """Backward-compatible private name for older callers and extensions."""
+ return ready_for_prompt(term)
+
+
async def wait_for_prompt_ready(
session: Any,
names: Sequence[str],
*,
timeout_s: float = READY_TIMEOUT_S,
) -> tuple[str, ...]:
- """Wait for newly mounted Codex panes to display their real input line."""
+ """Wait for newly mounted panes to display their real input line."""
wanted = tuple(dict.fromkeys(name for name in names if name))
deadline = time.monotonic() + max(0.0, timeout_s)
while True:
ready = tuple(
name
for name in wanted
- if (term := session.find(name)) is not None and _ready_for_prompt(term)
+ if (term := session.find(name)) is not None and ready_for_prompt(term)
)
if len(ready) == len(wanted) or time.monotonic() >= deadline:
return ready
@@ -108,6 +138,7 @@ __all__ = [
"READY_POLL_S",
"READY_TIMEOUT_S",
"close_agent_terminals",
+ "ready_for_prompt",
"terminals_closed_event",
"wait_for_prompt_ready",
]
diff --git a/jarvis/agentic_ide/interrupted.py b/jarvis/agentic_ide/interrupted.py
index 35dbfc7bfb..782e3c39c8 100644
--- a/jarvis/agentic_ide/interrupted.py
+++ b/jarvis/agentic_ide/interrupted.py
@@ -66,6 +66,7 @@ from typing import TYPE_CHECKING, Any
from loguru import logger
from .activity import read_activity, shows_question
+from .fleet_actions import ready_for_prompt
from .recap import condense
from .session import SessionError, accepts_prompts
@@ -156,8 +157,8 @@ class ContinueReport:
continued: list[str]
unconfirmed: list[str]
failed: list[tuple[str, str]]
- #: Panes whose agent had not started yet. The instruction is held and
- #: delivered when it comes up — a promise, not a refusal and not a send.
+ #: Panes whose process or input line is still starting. The instruction is
+ #: held and delivered when it becomes writable — a promise, not a refusal.
queued: list[str] = field(default_factory=list)
@property
@@ -206,9 +207,12 @@ def _starting(term: Terminal) -> bool:
Cold starts are staggered on purpose (``COLD_START_LIMIT``), so a workspace
of a dozen panes has most of them in this state for the first few seconds
- after it appears — the exact window somebody presses "Continue" in.
+ after it appears. A spawned process also stays here until its TUI exposes a
+ real input line; process existence alone is not prompt readiness.
"""
- return term.status == "pending"
+ return term.status == "pending" or (
+ term.status == "live" and bool(term.pty_id) and not ready_for_prompt(term)
+ )
def _describe(session: Session, term: Terminal) -> InterruptedPane:
@@ -312,7 +316,9 @@ def _selected(
return chosen, rejected
-def _claim(registry: Registry, pane: InterruptedPane) -> Terminal | None:
+def _claim(
+ registry: Registry, pane: InterruptedPane
+) -> tuple[Session, Terminal] | None:
"""Take a pane off the waiting list BEFORE anything is sent to it.
**The bug this fixes.** Typing a prompt and verifying it takes seconds — the
@@ -326,23 +332,26 @@ def _claim(registry: Registry, pane: InterruptedPane) -> Terminal | None:
caller puts the flag back when the send fails, and the pane returns to the
list rather than being silently dropped.
"""
- found = registry.find_terminal(pane.name)
- if found is None:
+ session = registry.get(pane.workspace_id)
+ if session is None:
+ return None
+ term = session.find(pane.key)
+ if term is None:
return None
- term = found[1]
if not term.continuation_pending:
# Somebody got here first — another press, or the user typing into the
# pane themselves between the scan and now.
return None
term.continuation_pending = False
- return term
+ return session, term
-def _release(registry: Registry, name: str) -> None:
+def _release(registry: Registry, pane: InterruptedPane) -> None:
"""Put a pane back on the waiting list after its nudge failed to go."""
- found = registry.find_terminal(name)
- if found is not None:
- found[1].continuation_pending = True
+ session = registry.get(pane.workspace_id)
+ term = session.find(pane.key) if session is not None else None
+ if term is not None:
+ term.continuation_pending = True
async def continue_panes(
@@ -366,8 +375,8 @@ async def continue_panes(
**A pane still starting is queued, not skipped.** Cold starts are staggered
(``COLD_START_LIMIT``), so most of a big workspace is still coming up in the
seconds after it appears — the very window this button is pressed in. Those
- panes are marked and continued by :meth:`Registry.attach` the moment their
- agent exists, and reported as ``queued`` rather than as done or refused.
+ panes are marked and continued when their agent's input line is writable,
+ and reported as ``queued`` rather than as done or refused.
**Pressing twice cannot send twice.** Every pane is claimed off the waiting
list synchronously before a single byte is typed (see :func:`_claim`), and
@@ -383,20 +392,25 @@ async def continue_panes(
for pane in chosen:
if not pane.continuable:
continue
- term = _claim(registry, pane)
- if term is None:
+ claimed = _claim(registry, pane)
+ if claimed is None:
# Already claimed by a press that is still in flight. Not a failure
# and not a second send — the first one is doing the work.
continue
+ owner, term = claimed
if pane.starting:
- term.continue_when_ready = True
+ registry.defer_continue(owner, term, text)
queued.append(pane.name)
else:
runnable.append(pane)
async def _send(pane: InterruptedPane) -> tuple[InterruptedPane, Any]:
try:
- return pane, await registry.send_prompt(pane.name, text)
+ return pane, await registry.send_prompt(
+ pane.name,
+ text,
+ workspace_id=pane.workspace_id,
+ )
except SessionError as exc:
return pane, exc
except Exception as exc: # noqa: BLE001 - one pane must not fail the batch
@@ -408,7 +422,7 @@ async def continue_panes(
for pane, outcome in await asyncio.gather(*(_send(pane) for pane in runnable)):
if isinstance(outcome, Exception):
# Nothing reached the agent, so this one is still waiting.
- _release(registry, pane.name)
+ _release(registry, pane)
failed.append((pane.name, str(outcome) or outcome.__class__.__name__))
elif getattr(outcome, "submitted", None) is True:
continued.append(pane.name)
diff --git a/jarvis/agentic_ide/screen.py b/jarvis/agentic_ide/screen.py
index 6fceccbd98..cce97268d6 100644
--- a/jarvis/agentic_ide/screen.py
+++ b/jarvis/agentic_ide/screen.py
@@ -20,10 +20,12 @@ Scope is deliberately narrow — the sequences TUIs actually use for layout:
* index / reverse index (IND, RI, NEL) and scroll up / down (SU, SD),
* a scroll region (DECSTBM), because status bars depend on it.
-Everything else — colours (SGR), cursor visibility, bracketed paste, mouse
-reporting, alternate screen switches — is parsed and ignored, which is correct:
-it changes appearance, not content. Unknown sequences are skipped rather than
-printed, so a future escape code cannot leak garbage into the transcript.
+Everything else — colours (SGR), bracketed paste, mouse reporting, alternate
+screen switches — is parsed and ignored, which is correct: it changes
+appearance, not content. Cursor visibility is the one appearance bit retained:
+coding TUIs use it to distinguish a writable composer from a disabled one.
+Unknown sequences are skipped rather than printed, so a future escape code
+cannot leak garbage into the transcript.
Not a goal: a conformant emulator. There is no support for double-width glyphs,
character sets, or wide-character alignment. A row is a list of single-cell
@@ -56,6 +58,7 @@ class ScreenBuffer:
"_grid",
"_cursor_row",
"_cursor_col",
+ "_cursor_visible",
"_scrollback",
"_pending",
"_scroll_top",
@@ -69,6 +72,7 @@ class ScreenBuffer:
self._grid: list[list[str]] = [self._blank_row() for _ in range(self.rows)]
self._cursor_row = 0
self._cursor_col = 0
+ self._cursor_visible = True
self._scrollback: deque[str] = deque(maxlen=scrollback)
# Bytes of an escape sequence split across two PTY reads.
self._pending = ""
@@ -236,8 +240,12 @@ class ScreenBuffer:
private = raw.startswith("?")
if private:
- # DEC private modes: cursor visibility, alternate screen, mouse
- # reporting, bracketed paste. None of them change content.
+ # Cursor visibility is semantic for prompt delivery: Ratatui hides
+ # it when a composer's input is disabled and puts it back on the
+ # input row only when key events can be consumed. Other private
+ # modes affect presentation or input routing, not screen content.
+ if final in "hl" and "25" in raw[1:].split(";"):
+ self._cursor_visible = final == "h"
return length
params = [int(p) if p.isdigit() else 0 for p in raw.split(";")] if raw else []
@@ -349,6 +357,19 @@ class ScreenBuffer:
rows.pop()
return rows
+ @property
+ def visible_cursor(self) -> tuple[int, int] | None:
+ """Current ``(row, column)`` when the application exposes its cursor."""
+ if not self._cursor_visible:
+ return None
+ return self._cursor_row, self._cursor_col
+
+ def row_text(self, row: int) -> str:
+ """One visible grid row, or an empty string outside the screen."""
+ if row < 0 or row >= self.rows:
+ return ""
+ return "".join(self._grid[row]).rstrip()
+
def history(self) -> list[str]:
"""Rows that have scrolled off the top, oldest first."""
return list(self._scrollback)
@@ -356,6 +377,7 @@ class ScreenBuffer:
def reset(self) -> None:
self._grid = [self._blank_row() for _ in range(self.rows)]
self._cursor_row = self._cursor_col = 0
+ self._cursor_visible = True
self._scrollback.clear()
self._pending = ""
self._scroll_top = 0
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 8f564ffbf9..1a88fba0c5 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -344,15 +344,6 @@ COLD_START_LIMIT = max(2, (os.cpu_count() or 4) // 4)
# enough to stagger, short enough that nobody watches a spinner for it.
COLD_START_SETTLE_S = 1.2
-# How long a deferred "carry on" waits after its pane's process appears.
-#
-# The process existing is not the same as its prompt box being on screen: a
-# coding CLI spends a second or two loading, and text typed into that window is
-# swallowed whole rather than queued (measured on a real Codex — see
-# `_await_arrival`). Long enough to clear that boot burst, short enough that
-# nobody watches a pane sit there.
-CONTINUE_AFTER_START_S = 2.5
-
# How long the nudged window size is held before it is put back (see
# ``_nudge_repaint``). A PTY carries one size, not a queue of them: set twice
# within the same event-loop tick, the agent may only ever observe the second
@@ -975,8 +966,12 @@ class Terminal:
# Sending only to the ones that happen to be up already is what made the
# button look like it skipped terminals; refusing them would be the same
# answer worn differently. So the wish is REMEMBERED here and spent by
- # `attach` the moment that pane's agent exists.
+ # `attach` once that pane's agent exposes a writable input line.
continue_when_ready: bool = False
+ # The exact nudge paired with ``continue_when_ready``. Usually the one-word
+ # default, but the REST contract accepts custom wording and a queued pane
+ # must not silently replace it while waiting for its cold-start slot.
+ continue_prompt: str = ""
# Has this pane's screen been observed STANDING STILL since its current
# process started?
#
@@ -1535,6 +1530,11 @@ class Registry:
# it is first awaited on, and the registry is also built in tests that
# run each case on a loop of its own.
self._cold_start: asyncio.Semaphore | None = None
+ # Some CLIs serialize badly on one account-scoped runtime store even
+ # when the machine has ample CPU. Their registry entry supplies the
+ # limit; separate accounts get separate gates, and CLIs with no limit
+ # never touch this path.
+ self._agent_cold_starts: dict[tuple[str, str], asyncio.Semaphore] = {}
# ---------------------------------------------------------------- state
@property
@@ -2403,6 +2403,32 @@ class Registry:
else:
gate.release()
+ async def _acquire_agent_cold_start(
+ self, term: Terminal
+ ) -> asyncio.Semaphore | None:
+ """Take this CLI/account's boot slot when its registry entry needs one.
+
+ The machine-wide gate protects CPU and process count. This narrower gate
+ protects a vendor runtime store: Codex resumes that are fast alone can
+ block one another for minutes when they initialize against the same
+ account database concurrently. The caller releases the slot only after
+ the pane's actual input line appears (or the readiness timeout expires).
+ """
+ spec = workspace_agents.get_agent(term.agent)
+ if not term.resumed:
+ return None
+ limit = max(0, spec.resume_start_limit if spec is not None else 0)
+ if limit == 0:
+ return None
+ key = (term.agent, term.account or "")
+ gate = self._agent_cold_starts.get(key)
+ if gate is None:
+ # No await between lookup and assignment: concurrent mounts cannot
+ # create two independent gates for one account.
+ gate = self._agent_cold_starts[key] = asyncio.Semaphore(limit)
+ await gate.acquire()
+ return gate
+
async def attach(
self,
key: str,
@@ -2674,7 +2700,14 @@ class Registry:
# resume and came back empty is not reported as waiting to be nudged.
# A valid conversation may already be finished or waiting for input.
# Offer a nudge only when the previous live pane was observed working.
- term.continuation_pending = term.resumed and term.resume_continuation_needed
+ # A Continue claimed while this pane was still pending stays claimed:
+ # raising the flag again during attach would let a second click enqueue
+ # the same nudge while the first is waiting for the input line.
+ term.continuation_pending = (
+ term.resumed
+ and term.resume_continuation_needed
+ and not term.continue_when_ready
+ )
if not term.resumed:
term.resume_continuation_needed = False
@@ -2684,6 +2717,10 @@ class Registry:
term.process_generation += 1
term.idle_seen = False
term.transcript.resize(cols, rows)
+ # Readiness belongs to this process. Keeping the dead process's screen
+ # here leaves old prompt sigils visible to the readiness probe and makes
+ # a freshly spawned CLI look writable before it has emitted one byte.
+ term.transcript.clear()
# A fresh process draws a fresh screen: anything the previous one left
# in the replay buffer belongs to a terminal that no longer exists, and
# replaying it to the next viewer would show output from a dead agent.
@@ -2780,32 +2817,42 @@ class Registry:
self._prepare_spawn, term, session.folder
)
- # One of a few starts at a time (see COLD_START_LIMIT).
- async with self._cold_start_slot():
- try:
- pty_session = await manager.spawn(
- shell_argv=argv,
- shell_id=f"agentic-ide:{term.key}",
- cwd=session.folder,
- cols=cols,
- rows=rows,
- on_output=_output,
- on_closed=_closed,
- env=env,
- # In the READER THREAD, not here: a CLI asking its terminal
- # for the device type or the screen colours reads the answer
- # within milliseconds of asking, and this event loop is at
- # its busiest while panes are starting — which is exactly
- # when the question is asked. Answered from the pump, the
- # reply was measured 203-234 ms late under a 300 ms stall
- # and landed in the CLI's prompt as junk the user never
- # typed. Off the loop it is immediate.
- on_probe=term.queries.feed,
- )
- except Exception as exc: # noqa: BLE001 - surfaced to the pane
- term.status = "error"
- term.error = str(exc)
- raise SessionError(str(exc)) from exc
+ # The provider/account gate is acquired BEFORE the machine-wide gate.
+ # A Codex pane waiting on shared state must never occupy a CPU slot that
+ # an unrelated Claude/OpenCode pane could use immediately.
+ agent_start_gate = await self._acquire_agent_cold_start(term)
+ spawn_succeeded = False
+ try:
+ # One of a few starts at a time (see COLD_START_LIMIT).
+ async with self._cold_start_slot():
+ try:
+ pty_session = await manager.spawn(
+ shell_argv=argv,
+ shell_id=f"agentic-ide:{term.key}",
+ cwd=session.folder,
+ cols=cols,
+ rows=rows,
+ on_output=_output,
+ on_closed=_closed,
+ env=env,
+ # In the READER THREAD, not here: a CLI asking its terminal
+ # for the device type or the screen colours reads the answer
+ # within milliseconds of asking, and this event loop is at
+ # its busiest while panes are starting — which is exactly
+ # when the question is asked. Answered from the pump, the
+ # reply was measured 203-234 ms late under a 300 ms stall
+ # and landed in the CLI's prompt as junk the user never
+ # typed. Off the loop it is immediate.
+ on_probe=term.queries.feed,
+ )
+ except Exception as exc: # noqa: BLE001 - surfaced to the pane
+ term.status = "error"
+ term.error = str(exc)
+ raise SessionError(str(exc)) from exc
+ spawn_succeeded = True
+ finally:
+ if not spawn_succeeded and agent_start_gate is not None:
+ agent_start_gate.release()
term.pty_id = pty_session.terminal_id
term.status = "live"
@@ -2836,6 +2883,27 @@ class Registry:
# And this process has not stood still yet, whatever the previous one
# did. Everything it is about to draw is a CLI painting itself, not an
# agent working — see the field.
+ if agent_start_gate is not None:
+ from . import fleet_actions
+
+ try:
+ ready = await fleet_actions.wait_for_prompt_ready(
+ session,
+ [term.name],
+ timeout_s=fleet_actions.READY_TIMEOUT_S,
+ )
+ if term.name not in ready:
+ # Never strand the remaining panes behind a CLI that stopped
+ # on login, trust, or an unknown future startup screen. Prompt
+ # delivery still waits independently and therefore stays safe.
+ logger.warning(
+ "Agentic IDE: {} did not expose an input line before its "
+ "cold-start slot expired; admitting the next {} pane",
+ term.name,
+ term.display_name,
+ )
+ finally:
+ agent_start_gate.release()
if term.resume is None and can_resume(term.agent):
# A CLI that cannot be told its session id (Codex): find out which
# one it just created, shortly from now.
@@ -2843,34 +2911,50 @@ class Registry:
if term.continue_when_ready:
# Somebody pressed "Continue" while this pane was still waiting for
# a cold-start slot. The wish outlives the wait — see
- # `continue_when_ready` — and is spent HERE, once the agent exists
- # and can be typed into. As a task, because the pane's socket is
- # waiting on this call: the nudge itself watches the pane's screen
- # for a few seconds, and holding the attach open for that would
- # leave the terminal blank while it ran.
- term.continue_when_ready = False
- self._schedule_continue(session, term)
+ # `continue_when_ready` — and is spent HERE. As a task, because the
+ # submit itself verifies the pane's screen for a few seconds and the
+ # viewer should not wait for that receipt before attaching.
+ self.defer_continue(session, term, term.continue_prompt)
await self._persist()
return term
- def _schedule_continue(self, session: Session, term: Terminal) -> None:
+ def defer_continue(self, session: Session, term: Terminal, prompt: str = "") -> None:
+ """Remember a Continue nudge and schedule it once this pane is live.
+
+ A pending pane carries the request into :meth:`attach`. A live pane may
+ still be booting, so it enters the same background path immediately and
+ :meth:`send_prompt` waits for the actual input line. There is one route
+ for both states and therefore no fixed-delay race.
+ """
+ from .interrupted import CONTINUE_PROMPT
+
+ term.continue_when_ready = True
+ term.continue_prompt = (prompt or CONTINUE_PROMPT).strip() or CONTINUE_PROMPT
+ if term.status != "live" or not term.pty_id:
+ return
+ queued_prompt = term.continue_prompt
+ term.continue_when_ready = False
+ term.continue_prompt = ""
+ self._schedule_continue(session, term, queued_prompt)
+
+ def _schedule_continue(self, session: Session, term: Terminal, prompt: str) -> None:
"""Send the deferred "carry on" to a pane that has just come up.
Kept on the session's own task set, like the conversation-id lookups, so
closing that workspace cancels it rather than leaving a nudge in flight
for a pane that no longer exists.
"""
- from .interrupted import CONTINUE_PROMPT
-
async def _nudge() -> None:
try:
- # The agent's CLI needs a moment after its process exists before
- # its prompt box is on screen; typing into the boot sequence is
- # how a paste gets swallowed whole (see `_await_arrival`, which
- # then waits for text that never appears).
- await asyncio.sleep(CONTINUE_AFTER_START_S)
- await self.send_prompt(term.name, CONTINUE_PROMPT)
+ await self.send_prompt(
+ term.name,
+ prompt,
+ workspace_id=session.id,
+ )
except SessionError as exc:
+ # No bytes were written when readiness timed out or the pane
+ # stopped. Put the offer back instead of losing the user's click.
+ term.continuation_pending = True
logger.warning(
"Agentic IDE: {} came up but could not be continued: {}", term.name, exc
)
@@ -3830,7 +3914,9 @@ class Registry:
next_slot[term.column] = term.slot + 1
# --------------------------------------------------------------- prompt
- async def send_prompt(self, wanted: str, text: str) -> Terminal:
+ async def send_prompt(
+ self, wanted: str, text: str, *, workspace_id: str | None = None
+ ) -> Terminal:
"""Type ``text`` into a terminal, press Enter, and CONFIRM it was sent.
Typing and hoping is not enough, which a live failure proved on
@@ -3856,11 +3942,20 @@ class Registry:
the single-line form that has always worked. The worst case is
therefore the old behaviour, never a lost instruction.
- Raises ``SessionError`` when the terminal is unknown, not running, or the
- prompt sanitizes down to nothing. A prompt that was typed but refused to
- submit is NOT an error — the text is in the box and the caller is told.
+ ``workspace_id`` pins background work such as a deferred Continue to the
+ pane it came from; without it, the front workspace keeps the established
+ call-sign resolution rules.
+
+ Raises ``SessionError`` when the terminal is unknown, not running, still
+ booting after the readiness window, or the prompt sanitizes down to
+ nothing. A prompt that was typed but refused to submit is NOT an error —
+ the text is in the box and the caller is told.
"""
- found = self.find_terminal(wanted)
+ found = (
+ self._locate(wanted, workspace_id)
+ if workspace_id is not None
+ else self.find_terminal(wanted)
+ )
if found is None:
raise self._unknown_terminal(wanted)
owner, term = found
@@ -3882,6 +3977,29 @@ class Registry:
if not payload:
raise SessionError("The prompt was empty after cleanup.")
+ # A spawned PTY is not necessarily an interactive CLI yet. Codex in
+ # particular can spend tens of seconds opening plugins and MCP servers,
+ # and a paste written during that phase is swallowed rather than queued.
+ # Waiting on the real input line is capability-gated, so the measured
+ # stable fast path (Claude) remains immediate and new CLIs fail safe.
+ from . import fleet_actions
+
+ ready = await fleet_actions.wait_for_prompt_ready(
+ owner,
+ [term.name],
+ timeout_s=fleet_actions.READY_TIMEOUT_S,
+ )
+ if term.name not in ready:
+ if term.status != "live" or not term.pty_id:
+ raise SessionError(
+ f"{term.name} stopped while it was starting (status: {term.status}) — "
+ "nothing was sent."
+ )
+ raise SessionError(
+ f"{term.name} is still starting — its input line never appeared, "
+ "so nothing was sent."
+ )
+
manager = self._manager()
multiline = "\n" in payload
diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.py
index 6d0d8bd71c..e4077a08e7 100644
--- a/jarvis/workspace/agents.py
+++ b/jarvis/workspace/agents.py
@@ -236,6 +236,16 @@ class WorkspaceAgent:
#: The prompt sigils this CLI's input line starts with. Empty means "the
#: shared default set", which covers every TUI observed so far.
input_markers: tuple[str, ...] = ()
+ #: True when readiness requires the terminal cursor to be visible on the
+ #: input-marker row. Ratatui CLIs can draw the same marker while disabling
+ #: keyboard input; cursor visibility is the stable distinction.
+ requires_visible_input_cursor: bool = False
+ #: Maximum resumed panes of this CLI and account that may still be starting.
+ #: Zero means no provider-specific limit beyond the shared machine gate.
+ #: Use this when parallel starts contend on one vendor runtime store; the
+ #: slot is held until the pane exposes its real input line, not merely until
+ #: its process exists.
+ resume_start_limit: int = 0
#: TUI furniture to strip before a transcript is summarised — banners,
#: status bars, key hints. Additive to the shared set.
chrome_fragments: tuple[str, ...] = ()
@@ -531,6 +541,13 @@ _AGENTS: dict[str, WorkspaceAgent] = {
kind="node",
),
instruction_filename="AGENTS.md",
+ input_markers=("›", "»"),
+ requires_visible_input_cursor=True,
+ # Two simultaneous resumes against Codex's shared SQLite/runtime store
+ # were measured beyond 90 s while one resume initialized substantially
+ # faster. Serialize only this shared-store boot phase. Claude and every
+ # unrelated CLI keep the normal parallel path.
+ resume_start_limit=1,
spoken_aliases=("codex", "kodex", "codecs", "codeks"),
),
"opencode": make_cli_agent(
diff --git a/tests/unit/agentic_ide/test_cold_start_gate.py b/tests/unit/agentic_ide/test_cold_start_gate.py
index a81f5e54c3..817e5d8498 100644
--- a/tests/unit/agentic_ide/test_cold_start_gate.py
+++ b/tests/unit/agentic_ide/test_cold_start_gate.py
@@ -25,6 +25,7 @@ from pathlib import Path
import pytest
+from jarvis.agentic_ide import fleet_actions
from jarvis.agentic_ide import session as ide
from tests.fakes.fake_pty_manager import FakePtyManager
@@ -95,6 +96,52 @@ async def test_a_full_workspace_starts_in_waves(
assert pool.peak <= 3, f"{pool.peak} agents were starting at once"
+async def test_codex_shared_store_starts_are_serial_until_the_input_line(
+ pool: CountingPtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A process existing does not release Codex's account-scoped boot slot."""
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ monkeypatch.setattr(fleet_actions, "READY_POLL_S", 0.01)
+ monkeypatch.setattr(fleet_actions, "READY_TIMEOUT_S", 1.0)
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(
+ str(tmp_path),
+ [
+ {"agent": "codex", "name": "Cody"},
+ {"agent": "codex", "name": "Cole"},
+ ],
+ )
+ monkeypatch.setattr(ide, "has_conversation", lambda *_args, **_kwargs: True)
+ for index, term in enumerate(session.terminals):
+ term.resume = ide.ResumeHandle(
+ kind="codex_rollout", id=f"resume-{index}", captured_at=0.0
+ )
+
+ mounting = asyncio.create_task(_attach_all(registry, session))
+ for _ in range(50):
+ if len(pool.spawns) == 1:
+ break
+ await asyncio.sleep(0.01)
+ assert len(pool.spawns) == 1
+ first = next(term for term in session.terminals if term.status == "live")
+ await pool.emit(
+ first.pty_id,
+ "\x1b[2J\x1b[H\u203a Ask Codex anything\x1b[1;3H\x1b[?25h",
+ )
+
+ for _ in range(50):
+ if len(pool.spawns) == 2:
+ break
+ await asyncio.sleep(0.01)
+ assert len(pool.spawns) == 2, "the next pane starts as soon as the first is writable"
+ second = next(term for term in session.terminals if term is not first)
+ await pool.emit(
+ second.pty_id,
+ "\x1b[2J\x1b[H\u203a Ask Codex anything\x1b[1;3H\x1b[?25h",
+ )
+ await asyncio.wait_for(mounting, timeout=1.0)
+
+
async def test_rejoining_a_running_agent_never_waits_for_a_starting_one(
pool: CountingPtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/unit/agentic_ide/test_fleet_actions.py b/tests/unit/agentic_ide/test_fleet_actions.py
index e7ca043663..965471051e 100644
--- a/tests/unit/agentic_ide/test_fleet_actions.py
+++ b/tests/unit/agentic_ide/test_fleet_actions.py
@@ -8,14 +8,7 @@ from jarvis.agentic_ide.fleet_actions import (
close_agent_terminals,
wait_for_prompt_ready,
)
-
-
-class _Transcript:
- def __init__(self, lines: list[str]) -> None:
- self._lines = lines
-
- def tail(self, _count: int) -> list[str]:
- return self._lines
+from jarvis.agentic_ide.transcript import Transcript
@dataclass
@@ -24,7 +17,7 @@ class _Term:
agent: str
status: str = "live"
pty_id: str | None = "pty"
- transcript: _Transcript = field(default_factory=lambda: _Transcript([]))
+ transcript: Transcript = field(default_factory=Transcript)
class _Session:
@@ -45,7 +38,18 @@ async def test_codex_waits_for_its_input_line_but_claude_does_not() -> None:
"Clara",
)
- codex.transcript = _Transcript(["OpenAI Codex", "› "])
+ codex.transcript.feed(
+ "\x1b[2J\x1b[HOpenAI Codex\r\n"
+ "› Input disabled.\x1b[2;3H\x1b[?25l"
+ )
+ assert await wait_for_prompt_ready(session, ["Cody", "Clara"], timeout_s=0) == (
+ "Clara",
+ )
+
+ codex.transcript.feed(
+ "\x1b[2J\x1b[HOpenAI Codex\r\n"
+ "› Ask Codex anything\x1b[2;3H\x1b[?25h"
+ )
assert await wait_for_prompt_ready(session, ["Cody", "Clara"], timeout_s=0) == (
"Cody",
"Clara",
diff --git a/tests/unit/agentic_ide/test_interrupted.py b/tests/unit/agentic_ide/test_interrupted.py
index 249ced54b5..2823ba24e9 100644
--- a/tests/unit/agentic_ide/test_interrupted.py
+++ b/tests/unit/agentic_ide/test_interrupted.py
@@ -20,7 +20,13 @@ from typing import Any
import pytest
-from jarvis.agentic_ide import activity, interrupted, notifications, resume_store
+from jarvis.agentic_ide import (
+ activity,
+ fleet_actions,
+ interrupted,
+ notifications,
+ resume_store,
+)
from jarvis.agentic_ide import session as session_mod
from jarvis.agentic_ide.agent_sessions import ResumeHandle
from jarvis.agentic_ide.session import Registry
@@ -51,9 +57,8 @@ def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Regis
monkeypatch.setattr(session_mod, "_SUBMIT_RETRY_AFTER_S", 0.02)
monkeypatch.setattr(session_mod, "_ARRIVAL_POLL_S", 0.01)
monkeypatch.setattr(session_mod, "_ARRIVAL_WINDOW_S", 0.04)
- # A deferred continue waits for the CLI's boot burst to clear before typing.
- # Real length, no value to a test that owns a fake terminal.
- monkeypatch.setattr(session_mod, "CONTINUE_AFTER_START_S", 0.01)
+ monkeypatch.setattr(fleet_actions, "READY_POLL_S", 0.01)
+ monkeypatch.setattr(fleet_actions, "READY_TIMEOUT_S", 0.12)
return Registry(pty_manager=fake_pty)
@@ -73,6 +78,7 @@ async def _restarted_pane(
name: str = "Alex",
conversation: str = "conv-1",
continuation_needed: bool = True,
+ agent: str = "claude",
):
"""A pane whose agent was spawned onto a conversation that already exists.
@@ -80,10 +86,11 @@ async def _restarted_pane(
point, the CLI's own history really holds the conversation, and attaching
launches the agent with ``--resume``.
"""
- session = await registry.start(str(folder), [{"agent": "claude", "name": name}])
- existing_conversation(conversation)
+ session = await registry.start(str(folder), [{"agent": agent, "name": name}])
+ existing_conversation(conversation, agent=agent)
+ kind = "codex_rollout" if agent == "codex" else "claude_session"
session.terminals[0].resume = ResumeHandle(
- kind="claude_session", id=conversation, captured_at=1.0
+ kind=kind, id=conversation, captured_at=0.0 if agent == "codex" else 1.0
)
session.terminals[0].resume_continuation_needed = continuation_needed
term = await registry.attach(name, 100, 30, _noop, _noop_exit)
@@ -409,6 +416,60 @@ async def test_a_pane_still_starting_is_continued_when_it_comes_up(
assert interrupted.scan(registry) == []
+async def test_continue_queues_a_live_codex_until_its_input_line_appears(
+ registry: Registry,
+ fake_pty: FakePtyManager,
+ tmp_path: Path,
+ existing_conversation: Any,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The pending claim survives spawn and the whole live-but-booting phase."""
+ monkeypatch.setattr(fleet_actions, "READY_TIMEOUT_S", 1.0)
+ fake_pty.tui_echo = True
+ session = await registry.start(
+ str(tmp_path), [{"agent": "codex", "name": "Cody"}]
+ )
+ existing_conversation("conv-codex", agent="codex")
+ term = session.terminals[0]
+ term.resume = ResumeHandle(kind="codex_rollout", id="conv-codex", captured_at=0.0)
+ term.resume_continuation_needed = True
+ term.continuation_pending = True
+
+ report = await interrupted.continue_panes(registry)
+
+ assert report.queued == ["Cody"]
+ assert report.continued == []
+ assert fake_pty.typed == []
+
+ mounting = asyncio.create_task(
+ registry.attach("Cody", 100, 30, _noop, _noop_exit)
+ )
+ for _ in range(50):
+ if term.status == "live":
+ break
+ await asyncio.sleep(0.01)
+ assert term.status == "live"
+ second_press = await interrupted.continue_panes(registry)
+ assert second_press.to_dict() == {
+ "ok": True,
+ "continued": [],
+ "queued": [],
+ "unconfirmed": [],
+ "failed": [],
+ }
+
+ await fake_pty.emit(
+ term.pty_id,
+ "\x1b[2J\x1b[H\u203a Ask Codex anything\x1b[1;3H\x1b[?25h",
+ )
+ await asyncio.wait_for(mounting, timeout=1.0)
+ await _settle(session)
+
+ assert fake_pty.typed.count(interrupted.CONTINUE_PROMPT) == 1
+ assert term.submitted is True
+ assert interrupted.scan(registry) == []
+
+
async def test_a_restored_pane_is_listed_before_its_agent_starts(
registry: Registry, tmp_path: Path, existing_conversation: Any
) -> None:
diff --git a/tests/unit/agentic_ide/test_new_cli_providers.py b/tests/unit/agentic_ide/test_new_cli_providers.py
index 6427290b72..f4be243ffa 100644
--- a/tests/unit/agentic_ide/test_new_cli_providers.py
+++ b/tests/unit/agentic_ide/test_new_cli_providers.py
@@ -450,17 +450,42 @@ def test_a_dropped_file_is_written_the_way_each_cli_reads_it() -> None:
class _Pane:
- def __init__(self, agent: str, lines: tuple[str, ...] = ()) -> None:
+ def __init__(
+ self,
+ agent: str,
+ lines: tuple[str, ...] = (),
+ *,
+ cursor_visible: bool = True,
+ ) -> None:
self.agent = agent
self.status = "live"
self.pty_id = "pty-1"
self._lines = lines
+ self._cursor_visible = cursor_visible
@property
def transcript(self) -> Any:
lines = self._lines
+ cursor_visible = self._cursor_visible
class _T:
+ class _Screen:
+ @staticmethod
+ def display() -> tuple[str, ...]:
+ return lines
+
+ @property
+ def visible_cursor(self) -> tuple[int, int] | None:
+ if not cursor_visible or not lines:
+ return None
+ return len(lines) - 1, len(lines[-1])
+
+ @staticmethod
+ def row_text(row: int) -> str:
+ return lines[row] if 0 <= row < len(lines) else ""
+
+ screen = _Screen()
+
@staticmethod
def tail(_n: int) -> tuple[str, ...]:
return lines
@@ -478,5 +503,10 @@ def test_a_booting_pane_of_a_new_cli_is_not_prompted_yet() -> None:
assert _ready_for_prompt(_Pane("opencode", ("Loading...",))) is False
assert _ready_for_prompt(_Pane("opencode", ("> ",))) is True
assert _ready_for_prompt(_Pane("kimi", ("starting",))) is False
+ assert _ready_for_prompt(
+ _Pane("codex", ("› Input disabled.",), cursor_visible=False)
+ ) is False
+ assert _ready_for_prompt(_Pane("codex", ("› Ask Codex anything",))) is True
+ assert _ready_for_prompt(_Pane("codex", ("» Ask Codex anything",))) is True
# The one measured exception keeps its fast path.
assert _ready_for_prompt(_Pane("claude", ("anything",))) is True
diff --git a/tests/unit/agentic_ide/test_prompt_submit.py b/tests/unit/agentic_ide/test_prompt_submit.py
index 7bff50ad08..188ed51905 100644
--- a/tests/unit/agentic_ide/test_prompt_submit.py
+++ b/tests/unit/agentic_ide/test_prompt_submit.py
@@ -17,6 +17,7 @@ from pathlib import Path
import pytest
+from jarvis.agentic_ide import fleet_actions
from jarvis.agentic_ide import session as session_mod
from jarvis.agentic_ide.session import (
PASTE_END,
@@ -130,6 +131,8 @@ def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Regis
monkeypatch.setattr(session_mod, "_SUBMIT_RETRY_AFTER_S", 0.02)
monkeypatch.setattr(session_mod, "_ARRIVAL_POLL_S", 0.01)
monkeypatch.setattr(session_mod, "_ARRIVAL_WINDOW_S", 0.04)
+ monkeypatch.setattr(fleet_actions, "READY_POLL_S", 0.01)
+ monkeypatch.setattr(fleet_actions, "READY_TIMEOUT_S", 0.08)
return Registry(pty_manager=fake_pty)
@@ -150,6 +153,51 @@ async def _live(registry: Registry, tmp_path: Path):
return await registry.attach("Alex", 100, 30, _noop, _noop_exit)
+async def _live_codex(registry: Registry, tmp_path: Path):
+ session = await registry.start(
+ str(tmp_path), [{"agent": "codex", "name": "Cody"}]
+ )
+ # A dead process's input marker must not make the replacement process look
+ # ready. The attach path owns clearing this generation's screen evidence.
+ session.terminals[0].transcript.feed("\u203a old prompt\r\n")
+ return await registry.attach("Cody", 100, 30, _noop, _noop_exit)
+
+
+async def test_a_booting_codex_is_not_typed_into_until_its_input_line_exists(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ fake_pty.tui_echo = True
+ term = await _live_codex(registry, tmp_path)
+ await fake_pty.emit(
+ term.pty_id,
+ "\x1b[2J\x1b[H\u203a Input disabled.\x1b[1;3H\x1b[?25l",
+ )
+
+ sending = asyncio.create_task(registry.send_prompt("Cody", "review the pipeline"))
+ await asyncio.sleep(0.03)
+ assert fake_pty.typed == [], "boot-time keystrokes are swallowed by Codex"
+
+ await fake_pty.emit(
+ term.pty_id,
+ "\x1b[2J\x1b[H\u203a Ask Codex anything\x1b[1;3H\x1b[?25h",
+ )
+ delivered = await sending
+
+ assert fake_pty.typed[:2] == ["review the pipeline", "\r"]
+ assert delivered.submitted is True
+
+
+async def test_a_codex_that_never_becomes_ready_receives_no_partial_prompt(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await _live_codex(registry, tmp_path)
+
+ with pytest.raises(SessionError, match="input line never appeared"):
+ await registry.send_prompt("Cody", "review the pipeline")
+
+ assert fake_pty.typed == []
+
+
async def test_a_trailing_reference_gets_a_closing_space(
registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
) -> None:
diff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.py
index 82c9be993a..e968ad0db0 100644
--- a/tests/unit/agentic_ide/test_resume_session.py
+++ b/tests/unit/agentic_ide/test_resume_session.py
@@ -926,7 +926,7 @@ async def test_a_conversation_that_starts_late_is_still_found(
"""
fake_pty.tui_echo = True
await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])
- await registry.attach("Cody", 80, 24, _noop, _noop_exit)
+ term = await registry.attach("Cody", 80, 24, _noop, _noop_exit)
await _settle()
assert registry.session.find("Cody").resume is None, "nothing exists to find yet"
assert late_cli.calls, "the pane still looks right after starting"
@@ -934,6 +934,10 @@ async def test_a_conversation_that_starts_late_is_still_found(
# The pane is given its first instruction, which is what makes the CLI write
# its session file.
late_cli.spoken_to = True
+ await fake_pty.emit(
+ term.pty_id,
+ "\x1b[2J\x1b[H› Ask Codex anything\x1b[1;3H\x1b[?25h",
+ )
await registry.send_prompt("Cody", "review the pipeline")
await _settle()
diff --git a/tests/unit/agentic_ide/test_transcript.py b/tests/unit/agentic_ide/test_transcript.py
index d64790fdcf..f4f8d670ec 100644
--- a/tests/unit/agentic_ide/test_transcript.py
+++ b/tests/unit/agentic_ide/test_transcript.py
@@ -40,6 +40,21 @@ def test_absolute_cursor_positioning_is_honoured() -> None:
assert t.tail() == ["first line", "third line"]
+def test_screen_tracks_the_visible_cursor_used_by_tui_input_gates() -> None:
+ screen = ScreenBuffer(cols=40, rows=10)
+ screen.feed("\x1b[3;1H› Ask Codex anything\x1b[3;3H\x1b[?25l")
+
+ assert screen.visible_cursor is None
+
+ screen.feed("\x1b[?25h")
+
+ assert screen.visible_cursor == (2, 2)
+ assert screen.row_text(2).startswith("› ")
+
+ screen.reset()
+ assert screen.visible_cursor == (0, 0)
+
+
def test_erase_line_removes_stale_content() -> None:
"""A repainted row must not leave the longer previous text behind."""
t = Transcript()
diff --git a/tests/unit/workspace/test_agents.py b/tests/unit/workspace/test_agents.py
index 31058b9b59..9987432724 100644
--- a/tests/unit/workspace/test_agents.py
+++ b/tests/unit/workspace/test_agents.py
@@ -96,6 +96,10 @@ def test_install_commands_are_runnable_or_honestly_absent() -> None:
def test_launch_command_is_bare_binary() -> None:
assert get_agent("claude").launch_command == "claude"
assert get_agent("codex").launch_command == "codex"
+ assert get_agent("codex").resume_start_limit == 1
+ assert get_agent("claude").resume_start_limit == 0
+ assert get_agent("codex").input_markers == ("›", "»")
+ assert get_agent("codex").requires_visible_input_cursor is True
assert get_agent("opencode").launch_command == "opencode"
# The profile runs the borrowed binary, not a command named after itself.
assert get_agent("glm").launch_command == "claude"