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): answer the agent's terminal questions off the event loop

Ruben Lütke747834fb4584
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index abd3303424..f853a0eeb6 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -2262,16 +2262,6 @@ class Registry:
# 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:
- # 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()
@@ -2339,6 +2329,15 @@ class Registry:
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"
diff --git a/jarvis/agentic_ide/terminal_input.py b/jarvis/agentic_ide/terminal_input.py
index 6a190ab9ff..fdd84cfe45 100644
--- a/jarvis/agentic_ide/terminal_input.py
+++ b/jarvis/agentic_ide/terminal_input.py
@@ -16,6 +16,17 @@ Two halves, and both are needed:
the reply is written before the CLI can finish waiting. No network is in that
path, which is the whole point — a faster browser would not have fixed this,
only made it rarer.
+
+ Being in the right PROCESS turned out not to be enough: routed through the
+ output pump it still had to wait for the event loop, and a workspace launch
+ is the busiest that loop ever gets — several panes spawning at once, which is
+ precisely when a starting CLI asks. Measured against a 300 ms stall the reply
+ came 203-234 ms late and landed in the prompt anyway. So ``feed`` is wired as
+ the PTY's ``on_probe`` (``jarvis/terminal/pty_manager.py``) and runs in the
+ READER THREAD, on the bytes as they come off the PTY: 0 ms under the same
+ load. It is therefore called from that thread and from nowhere else, which is
+ what keeps its ``_tail`` free of locking; ``appearance`` is assigned from the
+ loop, a lone attribute swap that a reader can only ever see whole.
* :func:`is_terminal_report_only` drops the browser's own copy of those replies
on the way in. Unconditionally, because once the backend answers, a report
arriving from a browser is by definition a duplicate. An earlier version
diff --git a/jarvis/terminal/pty_manager.py b/jarvis/terminal/pty_manager.py
index 36c6d3b9bb..0f4b860e64 100644
--- a/jarvis/terminal/pty_manager.py
+++ b/jarvis/terminal/pty_manager.py
@@ -66,6 +66,23 @@ repaints itself continuously, so the newest bytes are the screen and stale ones
are overwritten within a frame anyway. Dropping the newest instead would show a
viewer an old screen forever, and holding everything would trade a bounded
delay for an unbounded one plus unbounded memory.
+
+## Why one kind of output is answered before the pump ever sees it
+
+That pump is the right shape for a VIEWER and the wrong shape for a QUESTION.
+A coding CLI asks its terminal what it is and which colours it draws on while
+it starts, then reads the answer within milliseconds and gives up. Routed
+through the pump, the reply is scheduled behind whatever else the loop is doing
+— and a workspace launch is the busiest the loop ever gets, with several panes
+spawning at once. Measured here, a loop held for 300 ms delayed the answer by
+203-234 ms: the reply then arrives after the CLI stopped listening and its
+prompt editor has opened, where the bytes appear as a line of
+``11;rgb:1212/1414/1a1a`` the user never typed.
+
+``on_probe`` therefore runs in the READER THREAD, on the bytes as they come off
+the PTY, and whatever it returns is written straight back. Same measurement,
+same load: 0 ms. Nothing else moves off the pump — this is for replies that are
+useless once late, not for output a human reads.
"""
from __future__ import annotations
@@ -84,6 +101,11 @@ from .backend import PtyHandle, make_pty_backend
OutputCallback = Callable[[str, str], Awaitable[None]]
ClosedCallback = Callable[[str, int], Awaitable[None]]
+#: Called in the reader thread with each raw read; whatever it returns is
+#: written straight back to the PTY (empty for the overwhelming majority of
+#: output). Synchronous and cheap by contract — it runs on the path that drains
+#: the PTY, so anything slow here becomes back-pressure on the child.
+ProbeCallback = Callable[[str], str]
#: How much output one PTY may have waiting for its viewer before the oldest
#: is dropped. Generous enough to cover several full repaints of a busy
@@ -126,6 +148,11 @@ class PtySession:
#: Guards the two fields above — written by the reader thread, read by the
#: pump on the event loop.
_buffer_lock: threading.Lock = field(default_factory=threading.Lock, init=False)
+ #: Serializes writes INTO the child. Two threads reach the PTY: the event
+ #: loop carrying what the user typed, and the reader thread answering the
+ #: emulator queries (``on_probe``). Interleaving those would tear an escape
+ #: sequence in half, which a terminal cannot resynchronise from.
+ _write_lock: threading.Lock = field(default_factory=threading.Lock, init=False)
#: Set (from the loop, via ``call_soon_threadsafe``) when output is waiting.
_wake: asyncio.Event = field(default_factory=asyncio.Event, init=False)
_pump: asyncio.Task[None] | None = field(default=None, init=False)
@@ -178,6 +205,11 @@ class PtySession:
# ------------------------------------------------------------------
# Consumer side — called from the pump, on the event loop
# ------------------------------------------------------------------
+ def write(self, data: str) -> None:
+ """Write into the child, from whichever thread is holding the bytes."""
+ with self._write_lock:
+ self.proc.write(data)
+
def take(self) -> str:
"""Everything that arrived since the last take, as ONE chunk."""
with self._buffer_lock:
@@ -222,6 +254,7 @@ class PtyManager:
on_output: OutputCallback,
on_closed: ClosedCallback,
env: Mapping[str, str] | None = None,
+ on_probe: ProbeCallback | None = None,
) -> PtySession:
"""Starts a new PTY session and registers the I/O callbacks.
@@ -232,6 +265,13 @@ class PtyManager:
caller can never be told the child exited while output it produced is
still in the buffer.
+ ``on_probe`` is the exception, and runs in the READER THREAD instead:
+ it is handed each raw read and whatever it returns goes straight back
+ into the PTY. That is for answers a child stops waiting for within
+ milliseconds — the loop is at its busiest exactly while panes are
+ starting, which is when those questions get asked (module docstring).
+ The same output still reaches ``on_output`` afterwards, unchanged.
+
The PTY is created through the backend seam (`make_pty_backend()`):
Winpty on Windows, ptyprocess on POSIX, or a null backend that raises a
clear English RuntimeError when no PTY capability exists (AD-6). Any
@@ -287,7 +327,7 @@ class PtyManager:
session.reader_thread = threading.Thread(
target=self._reader_loop,
name=f"pty-reader-{terminal_id[:8]}",
- args=(session, loop),
+ args=(session, loop, on_probe),
daemon=True,
)
with self._lock:
@@ -316,7 +356,7 @@ class PtyManager:
if session is None:
return False
try:
- session.proc.write(data)
+ session.write(data)
return True
except Exception as exc: # noqa: BLE001
logger.warning("PTY write failed", terminal_id=terminal_id, error=str(exc))
@@ -523,13 +563,17 @@ class PtyManager:
self,
session: PtySession,
loop: asyncio.AbstractEventLoop,
+ on_probe: ProbeCallback | None = None,
) -> None:
"""Blocking read-loop — runs in its own daemon thread (AD-9: unchanged).
It hands every read straight to the session buffer and never touches
- the caller's callbacks: scheduling a coroutine per read is precisely the
- cost this module exists to avoid, and it is also what let a slow viewer
- build an unbounded queue.
+ the caller's async callbacks: scheduling a coroutine per read is
+ precisely the cost this module exists to avoid, and it is also what let
+ a slow viewer build an unbounded queue.
+
+ ``on_probe`` is the one thing answered from HERE rather than from the
+ pump, because its answer is worthless once late (module docstring).
"""
proc = session.proc
stop_flag = session.stop_flag
@@ -563,6 +607,30 @@ class PtyManager:
else:
text = str(data)
+ # BEFORE the buffer, so a question the child is holding its
+ # breath for is answered without waiting on the event loop.
+ # Never fatal: a probe that raises must not take the reader
+ # thread — and with it the pane's whole output — down with it.
+ if on_probe is not None:
+ try:
+ reply = on_probe(text)
+ except Exception as exc: # noqa: BLE001
+ logger.debug(
+ "PTY probe failed",
+ terminal_id=session.terminal_id,
+ error=str(exc),
+ )
+ else:
+ if reply:
+ try:
+ session.write(reply)
+ except Exception as exc: # noqa: BLE001
+ logger.debug(
+ "PTY probe reply could not be written",
+ terminal_id=session.terminal_id,
+ error=str(exc),
+ )
+
session.offer(text, loop)
finally:
try:
diff --git a/tests/fakes/fake_pty_manager.py b/tests/fakes/fake_pty_manager.py
index 56ad54a090..455b8d24f0 100644
--- a/tests/fakes/fake_pty_manager.py
+++ b/tests/fakes/fake_pty_manager.py
@@ -50,6 +50,10 @@ class FakePtyManager:
# Callbacks per live terminal, so a test can make an agent SPEAK (see
# ``emit``) rather than only observe what was typed at it.
_callbacks: dict[str, tuple[Any, Any]] = field(default_factory=dict)
+ # The synchronous probe the real manager runs in its reader thread, on the
+ # bytes as they come off the PTY. Kept apart from the callbacks above
+ # because it runs BEFORE them and its answer is a write, not a view.
+ _probes: dict[str, Any] = field(default_factory=dict)
async def spawn(
self,
@@ -61,6 +65,7 @@ class FakePtyManager:
on_output: Any,
on_closed: Any,
env: Any = None,
+ on_probe: Any = None,
) -> FakePtySession:
if self.spawn_error:
raise RuntimeError(self.spawn_error)
@@ -75,6 +80,7 @@ class FakePtyManager:
"rows": rows,
"on_output": on_output,
"on_closed": on_closed,
+ "on_probe": on_probe,
# The environment a pane was started with — how a test proves
# which subscription an agent actually runs on.
"env": dict(env) if env is not None else None,
@@ -82,6 +88,8 @@ class FakePtyManager:
)
self._live.add(terminal_id)
self._callbacks[terminal_id] = (on_output, on_closed)
+ if on_probe is not None:
+ self._probes[terminal_id] = on_probe
return FakePtySession(terminal_id=terminal_id, shell_id=shell_id)
def write(self, terminal_id: str, data: str) -> bool:
@@ -123,6 +131,7 @@ class FakePtyManager:
def close(self, terminal_id: str) -> bool:
self.closed.append(terminal_id)
self._callbacks.pop(terminal_id, None)
+ self._probes.pop(terminal_id, None)
return self._live.discard(terminal_id) is None and True
def has(self, terminal_id: str) -> bool:
@@ -141,13 +150,20 @@ class FakePtyManager:
async def emit(self, terminal_id: str | None, text: str) -> None:
"""Make the agent in this terminal print ``text``.
- The real reader thread calls the registry's output callback; this is the
- same call, so everything downstream of it — transcript, replay buffer,
- the viewer — is exercised exactly as it is in production.
+ Mirrors the real reader thread in ORDER as well as effect: the probe
+ sees the bytes first and anything it answers is written back before the
+ output callback runs, so a test cannot pass against a version that
+ answers from the pump. Everything downstream — transcript, replay
+ buffer, the viewer — is then exercised exactly as in production.
"""
callbacks = self._callbacks.get(terminal_id or "")
if callbacks is None:
raise AssertionError(f"no live terminal {terminal_id!r} to emit from")
+ probe = self._probes.get(terminal_id or "")
+ if probe is not None:
+ reply = probe(text)
+ if reply:
+ self.write(terminal_id or "", reply)
await callbacks[0](terminal_id, text)
async def die(self, terminal_id: str | None, code: int = 1) -> None:
diff --git a/tests/unit/terminal/test_pty_probe.py b/tests/unit/terminal/test_pty_probe.py
new file mode 100644
index 0000000000..d72e9d3438
--- /dev/null
+++ b/tests/unit/terminal/test_pty_probe.py
@@ -0,0 +1,234 @@
+"""Answering a child's question must not wait for the event loop.
+
+A coding CLI asks its terminal what it is and which colours it draws on while
+it starts, then reads the answer within milliseconds and gives up. A workspace
+launch is the busiest the event loop ever gets — several panes spawning at
+once — which is exactly when that question gets asked, so an answer routed
+through the output pump arrives after the CLI stopped listening and shows up in
+its prompt as a line of ``11;rgb:1212/1414/1a1a`` the user never typed.
+
+``on_probe`` therefore runs in the reader thread. What follows pins the
+PROPERTY that makes it work — the answer is written while the loop is not
+running at all — rather than the wiring, which could be satisfied by a version
+that is late again.
+
+The PTY is a fake handle, so this needs no pseudo-terminal (or coding agent) on
+the machine running the suite.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+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 reads out chunks the test feeds it, then EOFs.
+
+ ``written`` is what the child would have received on its stdin — which is
+ where a probe's answer has to end up.
+ """
+
+ def __init__(self) -> None:
+ self.pid = 4242
+ self.exitstatus: int | None = None
+ self._chunks: deque[str] = deque()
+ self._eof = False
+ self._alive = True
+ self.written: list[str] = []
+
+ # --- 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:
+ return None
+
+ 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._alive = False
+ self._eof = True
+ if self.exitstatus is None:
+ self.exitstatus = 0
+
+
+class ScriptedBackend:
+ def __init__(self, handle: ScriptedHandle) -> None:
+ self.handle = handle
+
+ def spawn(self, argv, cwd, cols, rows, env=None): # noqa: ANN001, ANN201
+ return self.handle
+
+
+#: What a CLI asks, and what the pane answers with.
+QUERY = "\x1b]11;?\x07"
+REPLY = "\x1b]11;rgb:1212/1414/1a1a\x07"
+
+#: Longer than a starting CLI waits for its answer, so a reply that needs the
+#: loop cannot sneak in inside the margin.
+LOOP_HELD_S = 0.3
+
+
+def handle(monkeypatch) -> ScriptedHandle: # noqa: ANN001
+ scripted = ScriptedHandle()
+ monkeypatch.setattr(pty_mod, "make_pty_backend", lambda: ScriptedBackend(scripted))
+ return scripted
+
+
+async def _spawn(manager: PtyManager, on_output=None, on_probe=None): # noqa: ANN001, ANN202
+ async def _ignore_output(_tid: str, _text: str) -> None:
+ return
+
+ async def _ignore_closed(_tid: str, _code: int) -> None:
+ return
+
+ return await manager.spawn(
+ shell_argv=("agent",),
+ shell_id="test",
+ cwd=None,
+ cols=80,
+ rows=24,
+ on_output=on_output or _ignore_output,
+ on_closed=_ignore_closed,
+ on_probe=on_probe,
+ )
+
+
+async def _until(predicate, give_up_after: float = 3.0) -> None: # noqa: ANN001
+ deadline = asyncio.get_running_loop().time() + give_up_after
+ while not predicate():
+ if asyncio.get_running_loop().time() > deadline:
+ raise AssertionError("condition not reached in time")
+ await asyncio.sleep(0.005)
+
+
+async def test_the_question_is_answered_while_the_loop_is_blocked(
+ handle: ScriptedHandle,
+) -> None:
+ """The regression: a busy launch must not make the answer late.
+
+ The loop is held for longer than a CLI waits, and the callback that proves
+ it never ran is checked alongside the reply — so this fails for a version
+ that answers correctly but from the pump.
+ """
+ manager = PtyManager()
+ loop_ran: list[bool] = []
+
+ await _spawn(manager, on_probe=lambda _text: REPLY)
+
+ asyncio.get_running_loop().call_soon(lambda: loop_ran.append(True))
+ handle.feed(QUERY)
+ # Blocking the loop IS the test — an await here would hand control back and
+ # let the very path this guards against answer in time.
+ time.sleep(LOOP_HELD_S) # noqa: ASYNC251
+
+ assert handle.written == [REPLY], "the child was left waiting for its answer"
+ assert loop_ran == [], "the loop ran, so this proves nothing about being off it"
+ manager.close_all()
+
+
+async def test_the_child_is_answered_with_what_the_probe_returns(
+ handle: ScriptedHandle,
+) -> None:
+ manager = PtyManager()
+
+ await _spawn(manager, on_probe=lambda text: REPLY if QUERY in text else "")
+
+ handle.feed("Welcome to the agent\r\n")
+ handle.feed(QUERY)
+ await _until(lambda: handle.written == [REPLY])
+ manager.close_all()
+
+
+async def test_output_still_reaches_the_viewer_unchanged(
+ handle: ScriptedHandle,
+) -> None:
+ """Probing is an extra read of the stream, never a filter on it."""
+ seen: list[str] = []
+ manager = PtyManager()
+
+ async def on_output(_tid: str, text: str) -> None:
+ seen.append(text)
+
+ await _spawn(manager, on_output=on_output, on_probe=lambda _text: REPLY)
+
+ handle.feed(QUERY)
+ await _until(lambda: seen == [QUERY])
+ manager.close_all()
+
+
+async def test_a_probe_that_says_nothing_writes_nothing(
+ handle: ScriptedHandle,
+) -> None:
+ """Ordinary output is the overwhelming majority; it must not be written back."""
+ seen: list[str] = []
+ manager = PtyManager()
+
+ async def on_output(_tid: str, text: str) -> None:
+ seen.append(text)
+
+ await _spawn(manager, on_output=on_output, on_probe=lambda _text: "")
+
+ handle.feed("compiling...\r\n")
+ # Once the viewer has it, the reader thread is demonstrably past the probe.
+ await _until(lambda: seen == ["compiling...\r\n"])
+ assert handle.written == []
+ manager.close_all()
+
+
+async def test_a_failing_probe_does_not_take_the_pane_down_with_it(
+ handle: ScriptedHandle,
+) -> None:
+ """The reader thread drains the PTY; losing it would freeze the whole pane."""
+ seen: list[str] = []
+ manager = PtyManager()
+
+ def exploding(_text: str) -> str:
+ raise RuntimeError("probe is broken")
+
+ async def on_output(_tid: str, text: str) -> None:
+ seen.append(text)
+
+ await _spawn(manager, on_output=on_output, on_probe=exploding)
+
+ handle.feed("first")
+ handle.feed("second")
+ await _until(lambda: "".join(seen) == "firstsecond")
+ manager.close_all()
+
+
+async def test_a_pane_without_a_probe_is_unaffected(handle: ScriptedHandle) -> None:
+ """Every other caller of spawn() passes nothing and must keep working."""
+ seen: list[str] = []
+ manager = PtyManager()
+
+ async def on_output(_tid: str, text: str) -> None:
+ seen.append(text)
+
+ await _spawn(manager, on_output=on_output)
+
+ handle.feed("hello")
+ await _until(lambda: seen == ["hello"])
+ assert handle.written == []
+ manager.close_all()