Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf(agentic-ide): stop a busy workspace from swallowing keystrokes
Ruben Lütkecbeba19e92d2
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 19a5c0ffa1..acbf6d7b5e 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -7645,3 +7645,91 @@ honesty, and all three disarm paths).actually accept, and must never rely on a matching `dragleave` to take thatannouncement down. `dragenter` is a "something is moving over you" signal, nota "the user is offering you a file" signal.++## BUG-111: typing into an Agentic-IDE terminal lags 2-3 s and then arrives in a burst (HIGH, FIXED 2026-07-27)++**Symptom (desktop field report).** Characters typed into a terminal pane took+seconds to appear. Users concluded the keystrokes were lost, retyped them, and+the backlog then flushed at once — running the command twice. It got worse the+more panes a workspace held and the busier the agents in them were. Measured on+the live machine at the time: **63 panes open in one workspace**, most of them+idle, the backend burning two cores.++**Root cause — an unbounded fan-in with no pacing, on both sides of the wire.**++1. **Backend: one coroutine and one websocket frame per PTY read**+ (`jarvis/terminal/pty_manager.py`). The reader thread scheduled+ `on_output(...)` through `run_coroutine_threadsafe` for every single+ `read()`, and each one queued behind the socket's send lock. The producer+ runs at PTY speed and the consumer at browser speed, so with enough panes+ the queue grew faster than it drained — and every new chunk, including the+ echo of the key just pressed, joined the END of it. The delay was therefore+ not constant but *compounding*, which is why it presents as "nothing, then+ everything at once" rather than as a steady lag.+2. **Frontend: every pane drew, whether or not anyone could see it**+ (`.../components/agentic/AgenticTerminal.tsx`). A pane scrolled out of the+ grid, or hidden with `display:none` behind a maximized sibling, still ran+ `term.write` for every chunk — parsing the escape stream, updating a cell+ grid, scheduling a repaint. All of it on the one browser main thread that+ also has to notice a keypress, and all of it for pixels nobody could see.++Both halves multiply with the pane count, which is why the feature was fine at+two panes and unusable at sixty.++**What it was NOT.** The PTY read path, the write path, and asyncio dispatch+were all measured at well under a millisecond, and idle panes cost nothing. The+screen emulator (`agentic_ide/screen.py`) runs at ~4 MB/s and was never the+limit. Frame COUNT was the cost, not bytes.++**Fix.**++- `PtyManager` gained a per-session **output pump**: the reader thread appends+ to a bounded buffer and wakes the pump, and the pump forwards everything that+ accumulated while the previous send was in flight as ONE chunk. It is+ self-clocking — an idle pane forwards its first chunk immediately, with no+ timer and no added latency — so a slow viewer costs frame count, never queue+ depth. Past `MAX_PENDING_CHARS` the OLDEST output is dropped, for the reason+ the replay buffer drops it: a terminal UI repaints continuously, so the newest+ bytes are the screen. `on_closed` now fires after the final flush, so a caller+ can no longer be told the agent exited while its last words are still+ buffered.+- An empty non-EOF read now backs off instead of spinning, which the comment+ above it had claimed since it was written.+- The pane writes only when it is on screen (`offscreenBuffer.ts` ++ an `IntersectionObserver` in `AgenticTerminal.tsx`); hidden output is parked+ and replayed in a single `term.write` when the pane comes back. Bounded the+ same way, and every pane write — output, exit banner, trouble notice — goes+ through the same gate so ordering survives.++**Measured, 45 concurrent panes redrawing a full-screen UI (backend):**++| | before | after |+|---|---|---|+| event-loop lag, mean | 45-126 ms | -4.5 ms |+| event-loop lag, p99 | 482-2227 ms | 16-17 ms |+| event-loop lag, max | 496-3344 ms | 21-30 ms |+| keystroke echo, mean | 3.4-3.9 s | 1.1 s |+| keystroke echo, max | 6.0-8.0 s | 1.5-1.6 s |+| output actually delivered | 0.46-0.72 MB/s | 4.1 MB/s |++The last row is the tell: the old path was so far behind that it could not even+carry what the agents produced, in MORE frames than the new one uses.++**Measured, 63 panes in a real browser (frontend):** main-thread scheduling+delay mean 52-60 ms -> 25-30 ms, p99 102-124 ms -> 79-81 ms — i.e. from above+the 100 ms interactivity budget to below it.++**Guards.** `tests/unit/terminal/test_pty_output_pump.py` (first chunk not+delayed, backlog coalesced, oldest dropped under flood, exit after the final+output, a broken viewer does not stop the PTY, an idle PTY does not spin);+`offscreenBuffer.test.ts` and `AgenticTerminal.offscreen.test.tsx` (withhold,+replay in one write, ordering, and no gating where `IntersectionObserver` is+absent).++**Class rule.** Whenever a thread produces into an event loop for a consumer+that can be slower than the producer, forward the BACKLOG, not each item: one+wake-up and one coalesced hand-off, bounded, dropping the stalest. Per-item+scheduling turns a slow consumer into a compounding delay, and the first thing+that delay eats is the user's own keystrokes. The same rule governs the far end+— never render for a surface nobody is looking at, because that thread is+usually the one holding the keyboard.diff --git a/jarvis/terminal/pty_manager.py b/jarvis/terminal/pty_manager.pyindex 24b3e7458b..c35dd89e3c 100644--- a/jarvis/terminal/pty_manager.py+++ b/jarvis/terminal/pty_manager.py@@ -17,13 +17,49 @@ Design decisions:swapped from a raw ``winpty.PtyProcess`` to a ``PtyHandle``.- Lifecycle: close() signals the reader thread via a flag and terminates theprocess. No join, so a hung PTY never blocks the web server.++## Why output is coalesced instead of forwarded chunk by chunk++The reader thread produces at PTY speed; the consumer is a websocket feeding+one browser. That is a producer/consumer pair with no natural pacing, and the+first version had none: every single ``read()`` became its own coroutine, its+own JSON frame, and its own entry in a FIFO queue behind the socket's send+lock. One pane got away with it. A workspace full of them does not — the+frames are what cost, not the bytes, and every pane's frames land on the SAME+browser main thread.++Measured on this machine, 45 panes redrawing a TUI: forwarding per chunk drove+the event loop 5.4 s behind (worst 13.4 s) and a keystroke took 8.6 s to echo,+because the backlog grew faster than it drained and every new chunk joined the+end of it. That is exactly what the user reports as "I type and nothing+happens, then everything appears at once".++So a pane's output goes through a **pump** instead:++* the reader thread appends to a buffer and wakes the pump — no coroutine, no+ queue entry, no frame,+* the pump sends whatever has accumulated as ONE chunk, then looks again.++The pump is self-clocking: with nothing pending it forwards the first chunk+immediately (no added latency, no timer), and while a send is in flight the+next chunks merge into a single follow-up. A slow viewer therefore costs frame+COUNT, never queue depth — the same 45 panes stay at 90 ms.++``MAX_PENDING_CHARS`` bounds what one pane may hold for a viewer that cannot+keep up at all. Past it the OLDEST chunks are dropped, for the reason the+replay buffer drops them (``jarvis/agentic_ide/transcript.py``): a terminal UI+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."""from __future__ import annotationsimport asyncioimport threading+from collections import dequefrom collections.abc import Awaitable, Callable, Mapping-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom uuid import uuid4from loguru import logger@@ -33,6 +69,18 @@ from .backend import PtyHandle, make_pty_backendOutputCallback = Callable[[str, str], Awaitable[None]]ClosedCallback = Callable[[str, int], Awaitable[None]]+#: 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+#: full-screen agent UI, small enough that a hundred panes stay bounded+#: (100 x 256 KB is 25 MB in the worst case nobody reaches).+MAX_PENDING_CHARS = 256 * 1024++#: How long the reader thread waits after a read that returned nothing without+#: signalling EOF. Backends differ on whether ``read`` blocks; without this a+#: non-blocking one spins a core per pane, which is what starves the very loop+#: the output has to be delivered on.+_EMPTY_READ_BACKOFF_S = 0.005+@dataclass(slots=True)class PtySession:@@ -42,8 +90,91 @@ class PtySession:shell_id: strpid: intproc: PtyHandle # normalized PTY handle behind the backend seam (AD-6)- reader_thread: threading.Threadstop_flag: threading.Event+ #: Assigned right after construction — the thread is handed the session it+ #: feeds, so the two cannot be built in one expression.+ reader_thread: threading.Thread | None = field(default=None, init=False)++ # ---- output pump (see the module docstring) --------------------------+ #: Output read from the PTY that the viewer has not been handed yet.+ _pending: deque[str] = field(default_factory=deque, init=False)+ _pending_chars: int = field(default=0, init=False)+ #: 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)+ #: 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)+ #: The child's exit code once the reader thread has finished, else None.+ #: The pump reads it to know that the last flush really is the last one.+ _exit_code: int | None = field(default=None, init=False)+ _finished: bool = field(default=False, init=False)+ #: Characters dropped because the viewer could not keep up. Reported once+ #: per session rather than per drop — a flooding pane must not turn into a+ #: flooding log.+ _dropped_chars: int = field(default=0, init=False)++ # ------------------------------------------------------------------+ # Producer side — called from the reader thread+ # ------------------------------------------------------------------+ def offer(self, text: str, loop: asyncio.AbstractEventLoop) -> None:+ """Hand one PTY read to the pump. Never blocks the reader thread."""+ if not text:+ return+ with self._buffer_lock:+ self._pending.append(text)+ self._pending_chars += len(text)+ while self._pending_chars > MAX_PENDING_CHARS and len(self._pending) > 1:+ self._dropped_chars += len(self._pending[0])+ self._pending_chars -= len(self._pending.popleft())+ self._signal(loop)++ def finish(self, exit_code: int, loop: asyncio.AbstractEventLoop) -> None:+ """Tell the pump the child is gone, so it can flush and report it."""+ self._exit_code = exit_code+ self._finished = True+ self._signal(loop)++ def _signal(self, loop: asyncio.AbstractEventLoop) -> None:+ """Wake the pump, unless it is already awake.++ Skipping an already-set event is safe in both directions: the pump+ clears the event BEFORE it drains, so anything appended while the event+ was set is still picked up by that drain, and a wake that arrives after+ a drain simply returns immediately with nothing to do.+ """+ if self._wake.is_set():+ return+ try:+ loop.call_soon_threadsafe(self._wake.set)+ except RuntimeError:+ # The loop is closing — the server is going down with it.+ pass++ # ------------------------------------------------------------------+ # Consumer side — called from the pump, on the event loop+ # ------------------------------------------------------------------+ def take(self) -> str:+ """Everything that arrived since the last take, as ONE chunk."""+ with self._buffer_lock:+ if not self._pending:+ return ""+ text = "".join(self._pending)+ self._pending.clear()+ self._pending_chars = 0+ return text++ @property+ def pending_chars(self) -> int:+ """Output waiting for the viewer right now (diagnostics and tests)."""+ with self._buffer_lock:+ return self._pending_chars++ @property+ def dropped_chars(self) -> int:+ """Output dropped because the viewer never caught up."""+ with self._buffer_lock:+ return self._dropped_charsclass PtyManager:@@ -70,8 +201,12 @@ class PtyManager:) -> PtySession:"""Starts a new PTY session and registers the I/O callbacks.- The callbacks run in the caller's asyncio loop — the reader thread- schedules them via `asyncio.run_coroutine_threadsafe`.+ The callbacks run in the caller's asyncio loop, driven by one pump task+ per session: ``on_output`` is awaited with everything that accumulated+ while the previous call was in flight (see the module docstring), and+ ``on_closed`` is awaited exactly once, after the final flush — so a+ caller can never be told the child exited while output it produced is+ still in the buffer.The PTY is created through the backend seam (`make_pty_backend()`):Winpty on Windows, ptyprocess on POSIX, or a null backend that raises a@@ -103,26 +238,30 @@ class PtyManager:terminal_id = str(uuid4())stop_flag = threading.Event()- reader_thread = threading.Thread(- target=self._reader_loop,- name=f"pty-reader-{terminal_id[:8]}",- args=(terminal_id, proc, stop_flag, loop, on_output, on_closed),- daemon=True,- )-pid = int(getattr(proc, "pid", 0) or 0)session = PtySession(terminal_id=terminal_id,shell_id=shell_id,pid=pid,proc=proc,- reader_thread=reader_thread,stop_flag=stop_flag,)+ session.reader_thread = threading.Thread(+ target=self._reader_loop,+ name=f"pty-reader-{terminal_id[:8]}",+ args=(session, loop),+ daemon=True,+ )with self._lock:self._sessions[terminal_id] = session- reader_thread.start()+ # Started BEFORE the reader thread, so the first byte a fast child+ # prints already has somewhere to go.+ session._pump = loop.create_task(+ self._pump_loop(session, on_output, on_closed),+ name=f"pty-pump-{terminal_id[:8]}",+ )+ session.reader_thread.start()logger.info("PTY spawned",terminal_id=terminal_id,@@ -190,17 +329,83 @@ class PtyManager:pass# No join — the reader thread is a daemon and may still be running# through one last read(). That's fine; Python exit cleans it up.+ # The pump is deliberately NOT cancelled here: the reader thread is+ # about to report the exit, and the pump is what turns that into the+ # caller's ``on_closed`` after a final flush. Cancelling would swallow+ # both the last output and the exit notification.- def _reader_loop(+ async def _pump_loop(self,- terminal_id: str,- proc: PtyHandle,- stop_flag: threading.Event,- loop: asyncio.AbstractEventLoop,+ session: PtySession,on_output: OutputCallback,on_closed: ClosedCallback,) -> None:- """Blocking read-loop — runs in its own daemon thread (AD-9: unchanged)."""+ """Forward one PTY's output to its viewer, coalescing the backlog.++ One task per session, and the only thing that ever calls the caller's+ callbacks. Everything that arrived while a send was in flight leaves as+ a single chunk on the next pass, which is what keeps a busy pane from+ turning into a queue of thousands of frames (see the module docstring).++ A failing callback is logged and the pump carries on: the viewer is+ 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.+ """+ terminal_id = session.terminal_id+ while True:+ await session._wake.wait()+ session._wake.clear()+ while True:+ text = session.take()+ if not text:+ break+ try:+ await on_output(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,+ error=str(exc),+ )+ if session._finished:+ break++ if session._dropped_chars:+ logger.warning(+ "PTY viewer could not keep up — dropped the oldest output",+ terminal_id=terminal_id,+ dropped_chars=session._dropped_chars,+ )+ code = session._exit_code+ try:+ await on_closed(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,+ error=str(exc),+ )++ def _reader_loop(+ self,+ session: PtySession,+ loop: asyncio.AbstractEventLoop,+ ) -> 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.+ """+ terminal_id = session.terminal_id+ proc = session.proc+ stop_flag = session.stop_flagexit_code = -1try:while not stop_flag.is_set():@@ -218,8 +423,11 @@ class PtyManager:breakif not data:# Empty but not EOF — back off briefly to avoid a busy-loop.+ # The wait is on the stop flag rather than a plain sleep, so+ # closing the terminal is still immediate.if not proc.isalive():break+ stop_flag.wait(_EMPTY_READ_BACKOFF_S)continue# The backend seam already normalized to str; stay defensive.@@ -228,25 +436,13 @@ class PtyManager:else:text = str(data)- # Dispatch the callback into the asyncio loop- fut = asyncio.run_coroutine_threadsafe(- on_output(terminal_id, text), loop- )- # We do NOT wait for the future — the reader must not- # throttle the producer. The future gets garbage-collected.- del fut+ session.offer(text, loop)finally:try:exit_code = int(proc.exitstatus or -1)except Exception: # noqa: BLE001exit_code = -1- try:- asyncio.run_coroutine_threadsafe(- on_closed(terminal_id, exit_code), loop- )- except RuntimeError:- # Loop is already closed — server shutdown- pass+ session.finish(exit_code, loop)logger.info("PTY reader terminated",terminal_id=terminal_id,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.tsxnew file mode 100644index 0000000000..688855a04b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx@@ -0,0 +1,177 @@+/**+ * A pane nobody is looking at must not draw.+ *+ * Dozens of terminals share one browser main thread with the keyboard, so a+ * pane scrolled out of the grid — or hidden behind a maximized sibling — used+ * to spend real frames painting pixels nobody could see, at the direct expense+ * of the pane being typed into. These pin the contract: withhold while hidden,+ * replay in ONE write on return, in order.+ */+import { render } from "@testing-library/react";+import { act } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const harness = vi.hoisted(() => ({+ writes: [] as string[],+ handlers: null as null | {+ onOutput: (text: string) => void;+ onExit: (code: number) => void;+ onReady: (info: { resumed: boolean; reattached: boolean }) => void;+ onTrouble: (message: string, retrying: boolean) => void;+ },+ observed: [] as Element[],+ fire: null as null | ((intersecting: boolean) => void),+}));++vi.mock("@xterm/xterm", () => ({+ Terminal: class {+ cols = 80;+ rows = 24;+ options: Record<string, unknown> = {};+ unicode = { activeVersion: "" };++ loadAddon() {}+ open() {}+ focus() {}+ paste() {}+ getSelection() {+ return "";+ }+ onData() {+ return { dispose() {} };+ }+ write(text: string) {+ harness.writes.push(text);+ }+ resize() {}+ dispose() {}+ clearTextureAtlas() {}+ },+}));++vi.mock("@xterm/addon-fit", () => ({ FitAddon: class { fit() {} } }));+vi.mock("@xterm/addon-web-links", () => ({ WebLinksAddon: class {} }));+vi.mock("@xterm/addon-canvas", () => ({ CanvasAddon: class {} }));+vi.mock("@xterm/addon-unicode11", () => ({ Unicode11Addon: class {} }));++vi.mock("./paneSocket", () => ({+ openPaneSocket: (_opts: unknown, handlers: typeof harness.handlers) => {+ harness.handlers = handlers;+ return { send() {}, close() {} };+ },+}));+vi.mock("./terminalPaste", () => ({+ installPasteBridge: () => () => undefined,+}));+vi.mock("./paneFileDrag", () => ({+ usePaneFileDrag: () => ({ dragging: false, handlers: {} }),+}));+vi.mock("@/lib/editActions", () => ({ attachTerminalBridge: () => undefined }));+vi.mock("@/lib/agenticIdeApi", () => ({ attachToTerminal: vi.fn() }));++import { AgenticTerminal } from "./AgenticTerminal";++class ResizeObserverHarness implements ResizeObserver {+ constructor(_callback: ResizeObserverCallback) {}+ observe() {}+ unobserve() {}+ disconnect() {}+}++class IntersectionObserverHarness {+ constructor(private readonly callback: IntersectionObserverCallback) {+ harness.fire = (intersecting: boolean) => {+ this.callback(+ harness.observed.map((target) => ({ target, isIntersecting: intersecting })) as+ unknown as IntersectionObserverEntry[],+ this as unknown as IntersectionObserver,+ );+ };+ }+ observe(target: Element) {+ harness.observed.push(target);+ }+ unobserve() {}+ disconnect() {}+ takeRecords() {+ return [];+ }+ root = null;+ rootMargin = "";+ thresholds = [];+}++function mount() {+ return render(+ <AgenticTerminal+ name="Dana"+ displayName="Claude Code"+ appearance="dark"+ fontSize={13}+ />,+ );+}++describe("AgenticTerminal off-screen output", () => {+ beforeEach(() => {+ harness.writes = [];+ harness.handlers = null;+ harness.observed = [];+ harness.fire = null;+ globalThis.ResizeObserver = ResizeObserverHarness;+ globalThis.IntersectionObserver =+ IntersectionObserverHarness as unknown as typeof IntersectionObserver;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("writes straight through while the pane is on screen", () => {+ mount();+ act(() => harness.handlers?.onOutput("visible output"));+ expect(harness.writes).toContain("visible output");+ });++ it("withholds output while hidden and replays it in ONE write", () => {+ mount();+ act(() => harness.fire?.(false));++ act(() => {+ harness.handlers?.onOutput("frame one ");+ harness.handlers?.onOutput("frame two ");+ harness.handlers?.onOutput("frame three");+ });+ expect(harness.writes).toEqual([]);++ act(() => harness.fire?.(true));+ expect(harness.writes).toEqual(["frame one frame two frame three"]);+ });++ it("keeps the exit banner BEHIND the output it follows", () => {+ // Writing the banner straight to xterm while output is parked would put+ // "[exited]" above the lines that explain why.+ mount();+ act(() => harness.fire?.(false));+ act(() => {+ harness.handlers?.onOutput("the last thing it said");+ harness.handlers?.onExit(1);+ });+ act(() => harness.fire?.(true));++ const replayed = harness.writes.join("");+ expect(replayed.indexOf("the last thing it said")).toBeLessThan(+ replayed.indexOf("exited"),+ );+ });++ it("stays visible where IntersectionObserver does not exist", () => {+ // Old engines and bare test environments: the pane must keep drawing+ // rather than go permanently silent.+ // @ts-expect-error - deliberately removing the API+ delete globalThis.IntersectionObserver;+ mount();+ act(() => harness.handlers?.onOutput("still drawn"));+ expect(harness.writes).toContain("still drawn");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 81b015c93c..6a70ec8202 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -75,6 +75,7 @@ import { attachToTerminal } from "@/lib/agenticIdeApi";import { attachTerminalBridge } from "@/lib/editActions";import { robustPaste } from "@/lib/clipboard";import { installPasteBridge } from "./terminalPaste";+import { OffscreenBuffer } from "./offscreenBuffer";import { openPaneSocket, type PaneSocket } from "./paneSocket";export type PaneStatus = "connecting" | "live" | "exited" | "error";@@ -291,6 +292,37 @@ export function AgenticTerminal({// scroll the agent's own output away for nothing.let troublePrinted = false;+ /*+ * Is anyone actually looking at this pane?+ *+ * A workspace holds dozens of terminals and the browser draws all of them on+ * the SAME thread that has to notice a keypress — so a pane scrolled out of+ * the grid, or hidden behind a maximized sibling, was spending real frames+ * painting pixels nobody could see, at the direct expense of the pane being+ * typed into. Its output is parked instead and written in one call when it+ * comes back (see ./offscreenBuffer).+ *+ * Starts as VISIBLE: the observer's first callback is asynchronous, and a+ * pane that withheld output until it arrived would flicker blank on mount.+ */+ let paneVisible = true;+ const offscreen = new OffscreenBuffer();++ const showPane = () => {+ if (paneVisible) return;+ paneVisible = true;+ const held = offscreen.drain();+ if (held) term.write(held);+ };++ // Everything this pane draws goes through here, not just the agent's+ // stream: an exit banner written straight to xterm while output is parked+ // would appear ABOVE the output it is supposed to follow.+ const writeToPane = (text: string) => {+ if (paneVisible) term.write(text);+ else offscreen.push(text);+ };+const sendResize = () => {// A hidden pane measures 0x0 (maximizing another one hides this one), and// fitting to that would resize the PTY to zero columns — which permanently@@ -319,7 +351,7 @@ export function AgenticTerminal({sendResize();requestAnimationFrame(sendResize);},- onOutput: (text) => term.write(text),+ onOutput: (text) => writeToPane(text),onReady: ({ resumed, reattached }) => {troublePrinted = false;// Say which of THREE things happened. They look identical on screen and@@ -338,7 +370,7 @@ export function AgenticTerminal({},onExit: (code) => {report("exited", `exit code ${code}`);- term.write(+ writeToPane(`\r\n\x1b[33m[${displayName} exited — code ${code}]\x1b[0m\r\n`,);},@@ -350,7 +382,7 @@ export function AgenticTerminal({report(retrying ? "connecting" : "error", message);if (retrying && troublePrinted) return;troublePrinted = true;- term.write(+ writeToPane(`\r\n\x1b[${retrying ? "33" : "31"}m[${message}]\x1b[0m\r\n`,);},@@ -396,11 +428,39 @@ export function AgenticTerminal({const ro = new ResizeObserver(scheduleResize);ro.observe(container);+ /*+ * Stop drawing panes nobody can see.+ *+ * Two cases, one mechanism: a pane scrolled past in a tall grid, and a pane+ * hidden with `display:none` because a sibling is maximized — neither+ * intersects the viewport, and both used to keep parsing and repainting an+ * agent's full-screen UI on the thread that owes the user a keystroke.+ *+ * The margin is generous on purpose: a pane one flick of the wheel away+ * catches up before it is looked at, so scrolling never shows a pane+ * mid-write. `IntersectionObserver` is absent in some test environments and+ * very old engines — there the pane simply stays visible, which is exactly+ * the behaviour this replaces.+ */+ let io: IntersectionObserver | null = null;+ if (typeof IntersectionObserver !== "undefined") {+ io = new IntersectionObserver(+ (entries) => {+ const onScreen = entries[entries.length - 1]?.isIntersecting ?? true;+ if (onScreen) showPane();+ else paneVisible = false;+ },+ { rootMargin: "300px" },+ );+ io.observe(container);+ }+return () => {disposed = true;if (resizeTimer !== undefined) window.clearTimeout(resizeTimer);window.removeEventListener("resize", scheduleResize);ro.disconnect();+ io?.disconnect();disposePasteBridge();try {socket?.close();diff --git a/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.test.ts b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.test.tsnew file mode 100644index 0000000000..65b8e39b7c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";++import { OffscreenBuffer } from "./offscreenBuffer";++describe("OffscreenBuffer", () => {+ it("hands back exactly what it was given, in order, once", () => {+ const buffer = new OffscreenBuffer();+ buffer.push("one ");+ buffer.push("two ");+ buffer.push("three");++ expect(buffer.drain()).toBe("one two three");+ // Drained means drained — a second look must not repaint the same output.+ expect(buffer.drain()).toBe("");+ expect(buffer.pending).toBe(0);+ });++ it("ignores empty chunks", () => {+ const buffer = new OffscreenBuffer();+ buffer.push("");+ expect(buffer.pending).toBe(0);+ expect(buffer.drain()).toBe("");+ });++ it("drops the OLDEST output when a hidden pane floods", () => {+ // A terminal UI repaints continuously, so the newest bytes are the screen.+ // Keeping the oldest would replay a screen that no longer exists.+ const buffer = new OffscreenBuffer(20);+ buffer.push("STALE");+ buffer.push("0123456789");+ buffer.push("abcdefghij");+ buffer.push("NEWEST");++ const held = buffer.drain();+ expect(held.endsWith("NEWEST")).toBe(true);+ expect(held).not.toContain("STALE");+ expect(buffer.dropped).toBeGreaterThan(0);+ });++ it("never drops the newest chunk, however large", () => {+ const buffer = new OffscreenBuffer(10);+ const huge = "x".repeat(500);+ buffer.push("old");+ buffer.push(huge);++ expect(buffer.drain()).toBe(huge);+ });++ it("stays bounded across a long flood", () => {+ const limit = 1024;+ const buffer = new OffscreenBuffer(limit);+ for (let i = 0; i < 500; i += 1) buffer.push("y".repeat(64));++ // One chunk of slack: the newest is always kept whole.+ expect(buffer.pending).toBeLessThanOrEqual(limit + 64);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.ts b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.tsnew file mode 100644index 0000000000..5ee13cffc8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.ts@@ -0,0 +1,68 @@+/**+ * What a pane nobody is looking at does with its agent's output.+ *+ * A workspace may hold dozens of panes, and every one of them is a terminal+ * emulator: `term.write` parses the escape stream, updates a cell grid, and+ * schedules a repaint — all on the ONE browser main thread that also has to+ * notice the user pressing a key. Off-screen panes therefore compete directly+ * with the pane being typed into, and they win often enough that keystrokes+ * arrive in delayed bursts.+ *+ * They also do it for nothing. A pane scrolled out of the grid, or hidden+ * behind a maximized sibling, draws to a surface with no pixels on screen. So+ * its output is parked here instead and written in one call when the pane comes+ * back — same bytes, same order, one parse instead of hundreds.+ *+ * Bounded, and the OLDEST goes first, for the same reason the server bounds its+ * replay buffer (`jarvis/agentic_ide/transcript.py`): a terminal UI repaints+ * itself continuously, so the newest bytes ARE the screen and stale ones are+ * overwritten within a frame. Keeping the oldest instead would replay a dead+ * screen; keeping everything would trade a bounded delay for unbounded memory+ * across every pane at once.+ */++/**+ * How much output one hidden pane keeps. Comfortably several full repaints of+ * a full-screen agent UI, and small enough that a hundred hidden panes stay a+ * rounding error.+ */+export const OFFSCREEN_LIMIT_CHARS = 256 * 1024;++export class OffscreenBuffer {+ private chunks: string[] = [];+ private size = 0;+ private droppedChars = 0;++ constructor(private readonly limit: number = OFFSCREEN_LIMIT_CHARS) {}++ /** Park one chunk of agent output. */+ push(text: string): void {+ if (!text) return;+ this.chunks.push(text);+ this.size += text.length;+ while (this.size > this.limit && this.chunks.length > 1) {+ const dropped = this.chunks.shift() as string;+ this.size -= dropped.length;+ this.droppedChars += dropped.length;+ }+ }++ /** Everything kept, oldest first, ready for a single `term.write`. */+ drain(): string {+ if (this.chunks.length === 0) return "";+ const text = this.chunks.join("");+ this.chunks = [];+ this.size = 0;+ return text;+ }++ /** Characters waiting to be written when this pane is looked at again. */+ get pending(): number {+ return this.size;+ }++ /** Characters this pane never got to draw because it fell too far behind. */+ get dropped(): number {+ return this.droppedChars;+ }+}diff --git a/tests/unit/terminal/test_pty_output_pump.py b/tests/unit/terminal/test_pty_output_pump.pynew file mode 100644index 0000000000..91a6f1b1bd--- /dev/null+++ b/tests/unit/terminal/test_pty_output_pump.py@@ -0,0 +1,264 @@+"""The PTY output pump — what keeps a busy pane from starving a typist.++The contract these pin down (see ``jarvis/terminal/pty_manager.py``):++* the FIRST chunk is forwarded immediately — coalescing must not buy+ throughput with latency the user feels on every keystroke,+* chunks that arrive while a send is in flight leave as ONE chunk, so a slow+ viewer costs frame count rather than queue depth,+* a viewer that never catches up loses the OLDEST output, not the newest, and+ the pane stays bounded,+* ``on_closed`` arrives exactly once, after the last output — a caller must+ never be told the agent exited while its final words are still buffered.++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 MAX_PENDING_CHARS, PtyManager+++class ScriptedHandle:+ """A ``PtyHandle`` that reads out a scripted list of chunks, then EOFs.++ ``feed`` may be called from the test at any time; the reader thread picks+ the chunks up in order and blocks on nothing, which is what lets a test+ control the producer's timing precisely.+ """++ 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)++ def finish(self, code: int = 0) -> None:+ self.exitstatus = code+ self._eof = True++ # --- 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+++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, handle: ScriptedHandle, on_output, on_closed): # noqa: ANN001, ANN202+ return await manager.spawn(+ shell_argv=("agent",),+ shell_id="test",+ cwd=None,+ cols=80,+ rows=24,+ on_output=on_output,+ on_closed=on_closed,+ )+++async def _until(predicate, give_up_after: float = 3.0) -> None: # noqa: ANN001+ """Wait for a condition the reader THREAD has to reach, without sleeping blind."""+ 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_first_chunk_is_not_delayed(handle: ScriptedHandle) -> None:+ """An idle pane forwards immediately — coalescing costs no latency."""+ seen: list[str] = []+ manager = PtyManager()++ async def on_output(_tid: str, text: str) -> None:+ seen.append(text)++ async def on_closed(_tid: str, _code: int) -> None:+ return++ await _spawn(manager, handle, on_output, on_closed)+ handle.feed("hello")+ await _until(lambda: seen == ["hello"])+ manager.close_all()+++async def test_backlog_during_a_slow_send_arrives_as_one_chunk(+ handle: ScriptedHandle,+) -> None:+ """The whole point: a slow viewer gets fewer frames, not a longer queue."""+ seen: list[str] = []+ release = asyncio.Event()+ manager = PtyManager()++ async def on_output(_tid: str, text: str) -> None:+ seen.append(text)+ if len(seen) == 1:+ # Hold the first send open the way a congested browser does.+ await release.wait()++ async def on_closed(_tid: str, _code: int) -> None:+ return++ await _spawn(manager, handle, on_output, on_closed)+ handle.feed("first")+ await _until(lambda: seen == ["first"])++ # Everything produced while that send is in flight must merge.+ handle.feed("a", "b", "c")+ await _until(lambda: handle._chunks == deque())+ release.set()+ await _until(lambda: len(seen) == 2)+ assert seen[1] == "abc"+ manager.close_all()+++async def test_a_viewer_that_never_drains_drops_the_oldest(+ handle: ScriptedHandle,+) -> None:+ """A flooding pane stays bounded, and it is the STALE screen that goes."""+ seen: list[str] = []+ release = asyncio.Event()+ manager = PtyManager()++ async def on_output(_tid: str, text: str) -> None:+ seen.append(text)+ if len(seen) == 1:+ await release.wait()++ async def on_closed(_tid: str, _code: int) -> None:+ return++ session = await _spawn(manager, handle, on_output, on_closed)+ handle.feed("open the send")+ await _until(lambda: len(seen) == 1)++ block = "x" * 4096+ overflow = (MAX_PENDING_CHARS // len(block)) + 4+ handle.feed("STALE-FIRST-SCREEN", *[block] * overflow, "NEWEST")+ await _until(lambda: session.dropped_chars > 0)+ await _until(lambda: not handle._chunks)++ assert session.pending_chars <= MAX_PENDING_CHARS+ release.set()+ await _until(lambda: len(seen) == 2)+ # The newest bytes — the screen as it is now — survived; the oldest did not.+ assert seen[1].endswith("NEWEST")+ assert "STALE-FIRST-SCREEN" not in seen[1]+ manager.close_all()+++async def test_exit_is_reported_after_the_final_output(handle: ScriptedHandle) -> None:+ """No caller may be told the agent exited while its last words are buffered."""+ events: list[tuple[str, object]] = []+ manager = PtyManager()++ async def on_output(_tid: str, text: str) -> None:+ events.append(("out", text))++ async def on_closed(_tid: str, code: int) -> None:+ events.append(("exit", code))++ await _spawn(manager, handle, on_output, on_closed)+ handle.feed("goodbye")+ handle.finish(3)+ await _until(lambda: ("exit", 3) in events)+ assert events == [("out", "goodbye"), ("exit", 3)]+ manager.close_all()+++async def test_a_broken_viewer_does_not_stop_the_pty(handle: ScriptedHandle) -> None:+ """The PTY outlives its viewer — a raising callback is not fatal."""+ seen: list[str] = []+ manager = PtyManager()++ async def on_output(_tid: str, text: str) -> None:+ seen.append(text)+ if len(seen) == 1:+ raise RuntimeError("viewer gone")++ async def on_closed(_tid: str, _code: int) -> None:+ return++ await _spawn(manager, handle, on_output, on_closed)+ handle.feed("one")+ await _until(lambda: len(seen) == 1)+ handle.feed("two")+ await _until(lambda: seen[-1] == "two")+ manager.close_all()+++async def test_an_idle_pty_does_not_spin(handle: ScriptedHandle) -> None:+ """An empty non-EOF read backs off instead of burning a core per pane.++ A backend whose ``read`` does not block is allowed (the seam does not+ promise one); without the backoff each such pane pins a core, and the loop+ those cores starve is the one the output has to be delivered on.+ """+ manager = PtyManager()+ reads = 0+ real_read = handle.read++ def counting_read(size: int) -> str:+ nonlocal reads+ reads += 1+ return real_read(size)++ handle.read = counting_read # type: ignore[method-assign]++ async def on_output(_tid: str, _text: str) -> None:+ return++ async def on_closed(_tid: str, _code: int) -> None:+ return++ await _spawn(manager, handle, on_output, on_closed)+ await asyncio.sleep(0.3)+ manager.close_all()+ # 0.3 s at a 5 ms backoff is ~60 reads. A spinning loop reaches six figures.+ assert reads < 1000, f"idle PTY spun: {reads} reads in 0.3 s"