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): stop a pane pasting terminal replies into Codex

Ruben Lütke3e5a58ac0ef5
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index e2aa019b76..fe463a59cd 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -76,9 +76,9 @@ from .agent_sessions import (
)
from .folders import ProjectProfile, probe_project
from .names import default_names, normalize, resolve
+from .terminal_input import THEME_COLOURS, TerminalQueryResponder
from .transcript import ReplayBuffer, Transcript
-from .terminal_input import THEME_COLOURS, TerminalQueryResponder
if TYPE_CHECKING: # pragma: no cover - typing only
from jarvis.terminal.pty_manager import PtyManager
@@ -468,6 +468,13 @@ class Terminal:
# this pane is actually showing. Cleared on a fresh spawn, so what a viewer
# replays always belongs to the process it is now watching.
replay: ReplayBuffer = field(default_factory=ReplayBuffer)
+ # Answers the emulator queries the agent's CLI asks on startup. It lives on
+ # the TERMINAL rather than on the viewer's socket for two reasons: the PTY
+ # outlives its viewers, and the replay handed to a re-joining viewer carries
+ # the original queries — answering those a second time would write the reply
+ # into a prompt the agent has long since opened, which is the corruption
+ # this exists to prevent. Only live output reaches it.
+ queries: TerminalQueryResponder = field(default_factory=TerminalQueryResponder)
# Where this pane's output currently goes, or None while nobody is looking.
#
# A mutable slot rather than a closure captured at spawn time, and that is
@@ -565,13 +572,6 @@ class Session:
restored_from: str = ""
def find(self, wanted: str) -> Terminal | None:
- # Answers the emulator queries the agent's CLI asks on startup. It lives on
- # the TERMINAL rather than on the viewer's socket for two reasons: the PTY
- # outlives its viewers, and the replay handed to a re-joining viewer carries
- # the original queries — answering those a second time would write the reply
- # into a prompt the agent has long since opened, which is the corruption
- # this exists to prevent. Only live output reaches it.
- queries: TerminalQueryResponder = field(default_factory=TerminalQueryResponder)
"""Terminal by key, call-sign, or a spoken phrase containing one."""
if not wanted:
return None
@@ -1339,6 +1339,7 @@ class Registry:
on_output: Any,
on_exit: Any,
workspace_id: str | None = None,
+ appearance: str | None = None,
) -> Terminal:
"""Point a viewer at terminal ``key``, starting its agent if needed.
@@ -1346,6 +1347,12 @@ class Registry:
transcript is fed here, so it keeps filling even if the UI pane is
closed and reconnects later.
+ ``appearance`` is the light/dark ground the viewer draws this pane on.
+ It is answered to the agent's CLI when it asks for the screen colours,
+ so a CLI on a light pane picks a palette for paper rather than for
+ slate. Omitted (an internal re-attach), whatever the last viewer said
+ stands.
+
**A running agent is re-joined, never restarted.** A pane whose PTY is
still alive — the normal case after switching workspaces, reloading the
browser, or coming back to the section — hands its output to the new
@@ -1375,6 +1382,8 @@ class Registry:
raise SessionError("No Agentic-IDE session is running.")
raise SessionError(f"Unknown terminal: {key}")
session, term = found
+ if appearance in THEME_COLOURS:
+ term.queries.appearance = appearance
manager = self._manager()
if term.pty_id and manager.has(term.pty_id):
@@ -1530,7 +1539,6 @@ class Registry:
except Exception as exc: # noqa: BLE001 - surfaced to the pane
term.status = "error"
term.error = str(exc)
- appearance: str | None = None,
raise SessionError(str(exc)) from exc
term.pty_id = pty_session.terminal_id
@@ -1538,12 +1546,6 @@ class Registry:
term.error = ""
term.exit_code = None
term.started_at = time.time()
- ``appearance`` is the light/dark ground the viewer draws this pane on.
- It is answered to the agent's CLI when it asks for the screen colours,
- so a CLI on a light pane picks a palette for paper rather than for
- slate. Omitted (an internal re-attach), whatever the last viewer said
- stands.
-
term.last_output_at = time.time()
if term.resume is None and can_resume(term.agent):
# A CLI that cannot be told its session id (Codex): find out which
@@ -1573,8 +1575,6 @@ class Registry:
await asyncio.sleep(delay)
if term not in owner.terminals or owner.id not in self._sessions:
return # the pane (or the workspace) is gone
- if appearance in THEME_COLOURS:
- term.queries.appearance = appearance
session = owner
if term.resume is not None:
return
diff --git a/jarvis/agentic_ide/terminal_input.py b/jarvis/agentic_ide/terminal_input.py
new file mode 100644
index 0000000000..6a190ab9ff
--- /dev/null
+++ b/jarvis/agentic_ide/terminal_input.py
@@ -0,0 +1,127 @@
+"""Answer a pane's terminal-protocol queries here, where the PTY is.
+
+A coding CLI asks its terminal emulator what it is and which colours it draws
+on while it starts — device attributes (``ESC [ c``) and the foreground and
+background of the screen (``ESC ] 10;?`` / ``ESC ] 11;?``) — then reads the
+answer within milliseconds and gives up. In a web terminal that answer would
+otherwise be produced by xterm in the BROWSER, so it travels PTY → WebSocket →
+browser → WebSocket → PTY. Across a grid of panes that round trip regularly
+outlasts the CLI's own wait, and the reply lands after the prompt editor has
+opened, where bytes such as ``ESC ] 11;rgb:1212/1414/1a1a`` show up as a line
+of text the user never typed.
+
+Two halves, and both are needed:
+
+* :class:`TerminalQueryResponder` answers in the process that owns the PTY, so
+ 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.
+* :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
+ allowed them during a two-second window after a query, which could not work:
+ elapsed time cannot distinguish "the CLI is still reading" from "the CLI
+ stopped reading a millisecond ago", and a REPLAYED screen (a pane re-joining
+ a running agent is handed the raw stream that drew it) makes the browser
+ answer a query from minutes ago — corruption arriving on a path no timer
+ covers. Nobody types these sequences, so nothing legitimate is lost.
+
+The colours below mirror ``frontend/src/components/agentic/terminalThemes.ts``
+and are pinned to it by ``tests/unit/agentic_ide/test_terminal_input.py``: the
+CLI must be told the colours the pane actually draws with, or it picks a
+palette for the wrong ground.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+
+#: What a pane looks like when the client did not say — the app's own default.
+DEFAULT_APPEARANCE = "dark"
+
+#: (foreground, background) per appearance, mirroring ``terminalThemes.ts``.
+THEME_COLOURS: dict[str, tuple[str, str]] = {
+ "dark": ("#e8e8ec", "#12141a"),
+ "light": ("#2b2b33", "#fcfbf8"),
+}
+
+#: What xterm answers a primary device-attributes query with: a VT100 with the
+#: advanced video option. Kept identical to the browser's answer so that moving
+#: the reply here changes nothing a CLI can observe except when it arrives.
+DEVICE_ATTRIBUTES = "\x1b[?1;2c"
+
+#: Longest query worth remembering across a chunk boundary (``ESC ] 11 ; ? ST``
+#: is nine characters); a PTY read can split anywhere.
+_TAIL_KEEP = 32
+
+_QUERY_RE = re.compile(
+ r"\x1b\](?P<osc>10|11);\?(?P<terminator>\x07|\x1b\\)"
+ r"|\x1b\[0?(?P<da>c)"
+)
+
+_REPORT_RE = re.compile(
+ r"(?:"
+ r"\x1b\](?:10|11);rgb:[0-9a-fA-F/]+(?:\x07|\x1b\\)"
+ r"|\x1b\[[?=>]?[0-9;]*c"
+ r")"
+)
+
+
+def is_terminal_report_only(data: str) -> bool:
+ """True only when the entire input consists of known emulator replies."""
+ payload = data or ""
+ return bool(payload) and not _REPORT_RE.sub("", payload)
+
+
+def _rgb(colour: str) -> str:
+ """``#e8e8ec`` → ``rgb:e8e8/e8e8/ecec`` — the 16-bit form terminals use."""
+ raw = colour.lstrip("#").lower()
+ return "rgb:" + "/".join(raw[i : i + 2] * 2 for i in (0, 2, 4))
+
+
+@dataclass(slots=True)
+class TerminalQueryResponder:
+ """Turn the emulator queries in a PTY's output into replies for that PTY."""
+
+ appearance: str = DEFAULT_APPEARANCE
+ _tail: str = field(default="", repr=False)
+
+ def feed(self, data: str) -> str:
+ """Return what to write back for the queries contained in ``data``.
+
+ Empty for the overwhelming majority of output. Safe to call on every
+ chunk: a query split across two reads is still recognised, and a query
+ already answered from the retained tail is never answered twice.
+ """
+ if not data:
+ return ""
+ combined = self._tail + data
+ replies: list[str] = []
+ consumed = 0
+ for match in _QUERY_RE.finditer(combined):
+ replies.append(self._reply(match))
+ consumed = match.end()
+ # Keep only what could still be the beginning of a query: everything up
+ # to the last match is answered, and older bytes cannot grow into one.
+ self._tail = combined[max(consumed, len(combined) - _TAIL_KEEP) :]
+ return "".join(replies)
+
+ def _reply(self, match: re.Match[str]) -> str:
+ if match.group("da"):
+ return DEVICE_ATTRIBUTES
+ foreground, background = THEME_COLOURS.get(
+ self.appearance, THEME_COLOURS[DEFAULT_APPEARANCE]
+ )
+ which = match.group("osc")
+ colour = foreground if which == "10" else background
+ return f"\x1b]{which};{_rgb(colour)}{match.group('terminator')}"
+
+
+__all__ = [
+ "DEFAULT_APPEARANCE",
+ "DEVICE_ATTRIBUTES",
+ "THEME_COLOURS",
+ "TerminalQueryResponder",
+ "is_terminal_report_only",
+]
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index df138918b4..c311ca01f9 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -70,6 +70,7 @@ from jarvis.agentic_ide.session import (
terminals_added_event,
)
+from jarvis.agentic_ide.terminal_input import is_terminal_report_only
from .surface_security import credentials_valid, is_loopback_request
log = logging.getLogger(__name__)
@@ -77,7 +78,6 @@ log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/agentic-ide", tags=["agentic-ide"])
# One system folder window at a time — see ``open_native_picker``.
-from jarvis.agentic_ide.terminal_input import is_terminal_report_only
_native_picker_lock = asyncio.Lock()
@@ -1507,6 +1507,12 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
resolved against whichever workspace happens to be showing, and could land
in a pane in a different folder. Omitted, the front workspace answers (the
single-workspace case, and what older clients send).
+
+ The optional ``appearance`` parameter (``light`` / ``dark``) is the ground
+ this pane is drawn on. It is what the agent's CLI is told when it asks the
+ terminal for its colours — a question answered in the backend rather than
+ by xterm, so the reply cannot arrive after the CLI stopped waiting for it
+ (see ``jarvis.agentic_ide.terminal_input``).
"""
await ws.accept()
if not credentials_valid(ws.scope):
@@ -1525,6 +1531,7 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
cols = _safe_int(qp.get("cols"), 80)
rows = _safe_int(qp.get("rows"), 24)
workspace_id = (qp.get("workspace") or "").strip() or None
+ appearance = (qp.get("appearance") or "").strip().lower() or None
registry = get_registry()
send_lock = asyncio.Lock()
@@ -1794,10 +1801,3 @@ async def set_prompt_writer(payload: PromptWriterRequest) -> PromptWriterState:
__all__ = ["router"]
-
- The optional ``appearance`` parameter (``light`` / ``dark``) is the ground
- this pane is drawn on. It is what the agent's CLI is told when it asks the
- terminal for its colours — a question answered in the backend rather than
- by xterm, so the reply cannot arrive after the CLI stopped waiting for it
- (see ``jarvis.agentic_ide.terminal_input``).
- appearance = (qp.get("appearance") or "").strip().lower() or None
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index 1a1bb46f59..ebb49c3ea3 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -196,8 +196,14 @@ export function AgenticTerminal({
const onStatusRef = useRef(onStatus);
const onAttachErrorRef = useRef(onAttachError);
const initialRef = useRef({ appearance, fontSize });
+ // The ground this pane draws on, as of NOW — the socket tells the backend, so
+ // that the agent's CLI is answered with the colours it is actually drawing on
+ // when it asks. Read at connect time, hence a ref rather than the prop: the
+ // connect effect must not re-run when the user flips the theme.
+ const appearanceRef = useRef(appearance);
onStatusRef.current = onStatus;
onAttachErrorRef.current = onAttachError;
+ appearanceRef.current = appearance;
useEffect(() => {
const container = containerRef.current;
@@ -217,14 +223,8 @@ export function AgenticTerminal({
// and the text under it accumulate different sub-pixel offsets and the
// frame visibly bends. Monospace legibility comes from the line height.
letterSpacing: 0,
- // The ground this pane draws on, as of NOW — the socket tells the backend, so
- // that the agent's CLI is answered with the colours it is actually drawing on
- // when it asks. Read at connect time, hence a ref rather than the prop: the
- // connect effect must not re-run when the user flips the theme.
- const appearanceRef = useRef(appearance);
cursorBlink: true,
cursorStyle: "bar",
- appearanceRef.current = appearance;
scrollback: 10000,
// Required by the Unicode 11 width provider below.
allowProposedApi: true,
@@ -241,6 +241,12 @@ export function AgenticTerminal({
: undefined,
theme: themeFor(initialRef.current.appearance),
});
+ // Before anything is written to this terminal: the agent's CLI asks what
+ // its terminal is and which colours it draws on within milliseconds of
+ // starting, and an answer produced HERE has to cross the socket twice
+ // before reaching it — too late, and then visible as junk in its prompt.
+ // The backend answers those instead. See ./terminalQueries.
+ const disposeQuerySuppression = installQuerySuppression(term.parser);
const fit = new FitAddon();
term.loadAddon(fit);
term.loadAddon(new WebLinksAddon());
@@ -262,12 +268,6 @@ export function AgenticTerminal({
// the mounted element. A failure here is not fatal — xterm falls back to
// the DOM renderer, which draws correctly, just less crisply.
try {
- // Before anything is written to this terminal: the agent's CLI asks what
- // its terminal is and which colours it draws on within milliseconds of
- // starting, and an answer produced HERE has to cross the socket twice
- // before reaching it — too late, and then visible as junk in its prompt.
- // The backend answers those instead. See ./terminalQueries.
- const disposeQuerySuppression = installQuerySuppression(term.parser);
term.loadAddon(new CanvasAddon());
} catch {
/* no canvas in this environment — the DOM renderer still works */
@@ -501,6 +501,7 @@ export function AgenticTerminal({
ro.disconnect();
io?.disconnect();
disposePasteBridge();
+ disposeQuerySuppression();
try {
socket?.close();
} catch {
@@ -532,7 +533,6 @@ export function AgenticTerminal({
term.clearTextureAtlas?.();
// Changing the font size changes the COLUMN COUNT. Fitting locally without
// telling the terminal process leaves the agent formatting for the old
- disposeQuerySuppression();
// width — it keeps wrapping at 100 columns in a pane that now holds 80, and
// every line breaks in the wrong place. The two must move together, so this
// goes through the same resize path the observer uses.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalQueries.test.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalQueries.test.ts
new file mode 100644
index 0000000000..32dcd48f2d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalQueries.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ installQuerySuppression,
+ isColourQuery,
+ type TerminalQueryParser,
+} from "./terminalQueries";
+
+/** Records what was registered, so a test can run the handlers xterm would. */
+function fakeParser() {
+ const osc = new Map<number, (data: string) => boolean | Promise<boolean>>();
+ const csi: { id: { prefix?: string; final: string }; handled: boolean }[] = [];
+ const disposed: string[] = [];
+ const parser: TerminalQueryParser = {
+ registerOscHandler(ident, callback) {
+ osc.set(ident, callback);
+ return { dispose: () => disposed.push(`osc:${ident}`) };
+ },
+ registerCsiHandler(id, callback) {
+ csi.push({ id, handled: callback([0]) as boolean });
+ return { dispose: () => disposed.push(`csi:${id.final}`) };
+ },
+ };
+ return { parser, osc, csi, disposed };
+}
+
+describe("installQuerySuppression", () => {
+ it("stops this browser from answering the screen-colour queries", () => {
+ const { parser, osc } = fakeParser();
+ installQuerySuppression(parser);
+
+ // OSC 10 is the foreground, OSC 11 the background — the two a coding CLI
+ // asks for on startup. Answered here they arrive a round trip late, in the
+ // agent's prompt.
+ expect(osc.get(10)?.("?")).toBe(true);
+ expect(osc.get(11)?.("?")).toBe(true);
+ });
+
+ it("leaves a program that RECOLOURS the terminal working", () => {
+ const { parser, osc } = fakeParser();
+ installQuerySuppression(parser);
+
+ // Same sequence, no question mark: this sets the background rather than
+ // asking for it, and must fall through to xterm's own handler.
+ expect(osc.get(11)?.("#ff0000")).toBe(false);
+ });
+
+ it("stops this browser from answering the device-attributes query", () => {
+ const { parser, csi } = fakeParser();
+ installQuerySuppression(parser);
+
+ expect(csi).toHaveLength(1);
+ expect(csi[0].id.final).toBe("c");
+ // No prefix: the secondary form (ESC [ > c) keeps xterm's own answer, so
+ // nothing beyond the one query that misbehaves changes.
+ expect(csi[0].id.prefix).toBeUndefined();
+ expect(csi[0].handled).toBe(true);
+ });
+
+ it("restores xterm's own handling when the pane goes away", () => {
+ const { parser, disposed } = fakeParser();
+
+ installQuerySuppression(parser)();
+
+ expect(disposed).toEqual(["osc:10", "osc:11", "csi:c"]);
+ });
+
+ it("survives a terminal that was disposed first", () => {
+ const parser: TerminalQueryParser = {
+ registerOscHandler: () => ({
+ dispose: vi.fn(() => {
+ throw new Error("terminal is gone");
+ }),
+ }),
+ registerCsiHandler: () => ({ dispose: vi.fn() }),
+ };
+
+ expect(() => installQuerySuppression(parser)()).not.toThrow();
+ });
+});
+
+describe("isColourQuery", () => {
+ it("tells a question apart from an instruction", () => {
+ expect(isColourQuery("?")).toBe(true);
+ expect(isColourQuery("#12141a")).toBe(false);
+ expect(isColourQuery("rgb:1212/1414/1a1a")).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalQueries.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalQueries.ts
new file mode 100644
index 0000000000..e094915a3e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalQueries.ts
@@ -0,0 +1,64 @@
+/**
+ * Stop this pane from answering the agent's terminal-protocol queries.
+ *
+ * A coding CLI asks its terminal what it is (`ESC [ c`) and which colours it
+ * draws on (`ESC ] 10;?` and `ESC ] 11;?`) while it starts, and reads the
+ * answer within milliseconds. Left to itself xterm answers those here, in the
+ * browser — so the reply has to travel back over the WebSocket before it
+ * reaches the CLI. Across a grid of panes that round trip regularly outlasts
+ * the CLI's own wait, and the answer lands after the prompt editor has opened,
+ * where it appears as a pasted-looking line of `11;rgb:1212/1414/1a1a` the
+ * user never typed.
+ *
+ * The backend answers these instead, in the process that owns the PTY, where
+ * there is no network to be late (`jarvis/agentic_ide/terminal_input.py`). So
+ * the browser must stay quiet: a second answer is not harmless, it is exactly
+ * the junk being fixed, arriving one round trip later.
+ *
+ * Only QUERIES are suppressed. `ESC ] 10 ; <colour>` also SETS the foreground,
+ * and a program that recolours its terminal must keep working — those fall
+ * through to xterm's own handler untouched.
+ */
+
+/** The slice of xterm's parser this needs — kept small so it can be tested. */
+export interface TerminalQueryParser {
+ registerOscHandler(
+ ident: number,
+ callback: (data: string) => boolean | Promise<boolean>,
+ ): { dispose(): void };
+ registerCsiHandler(
+ id: { prefix?: string; intermediates?: string; final: string },
+ callback: (params: unknown) => boolean | Promise<boolean>,
+ ): { dispose(): void };
+}
+
+/** OSC 10 is the foreground colour, OSC 11 the background. */
+const COLOUR_QUERIES = [10, 11];
+
+/** True for `ESC ] 1x ; ?` — asking, as opposed to setting a colour. */
+export function isColourQuery(data: string): boolean {
+ return data.trim().startsWith("?");
+}
+
+/**
+ * Silence this terminal's protocol replies. Returns a disposer that restores
+ * xterm's own handling, so a pane can be torn down without leaking handlers.
+ */
+export function installQuerySuppression(parser: TerminalQueryParser): () => void {
+ const handlers = COLOUR_QUERIES.map((ident) =>
+ parser.registerOscHandler(ident, isColourQuery),
+ );
+ // Primary device attributes only — no prefix. The secondary form (`ESC [ > c`)
+ // has its own identifier and is left alone, so nothing beyond the one query
+ // that misbehaves changes behaviour.
+ handlers.push(parser.registerCsiHandler({ final: "c" }, () => true));
+ return () => {
+ for (const handler of handlers) {
+ try {
+ handler.dispose();
+ } catch {
+ /* the terminal is already gone */
+ }
+ }
+ };
+}
diff --git a/tests/unit/agentic_ide/test_terminal_input.py b/tests/unit/agentic_ide/test_terminal_input.py
new file mode 100644
index 0000000000..ddf34fbc72
--- /dev/null
+++ b/tests/unit/agentic_ide/test_terminal_input.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide.terminal_input import (
+ DEVICE_ATTRIBUTES,
+ THEME_COLOURS,
+ TerminalQueryResponder,
+ is_terminal_report_only,
+)
+
+#: What a CLI asks its terminal while starting: device attributes, then the
+#: foreground and background of the screen it is about to draw on.
+DA_QUERY = "\x1b[c"
+FG_QUERY = "\x1b]10;?\x1b\\"
+BG_QUERY = "\x1b]11;?\x07"
+
+#: The replies, as a browser's xterm would produce them a round trip later.
+REPORTS = "\x1b]10;rgb:e8e8/e8e8/ecec\x1b\\\x1b]11;rgb:1212/1414/1a1a\x1b\\\x1b[?1;2c"
+
+
+def test_a_startup_query_is_answered_from_the_pty_side() -> None:
+ responder = TerminalQueryResponder(appearance="dark")
+
+ replies = responder.feed(f"{DA_QUERY}{FG_QUERY}{BG_QUERY}")
+
+ assert replies == (
+ f"{DEVICE_ATTRIBUTES}\x1b]10;rgb:e8e8/e8e8/ecec\x1b\\\x1b]11;rgb:1212/1414/1a1a\x07"
+ )
+
+
+def test_the_answer_describes_the_ground_the_pane_actually_draws_on() -> None:
+ """A pane on paper must not report slate, or the CLI picks the wrong palette."""
+ light = TerminalQueryResponder(appearance="light").feed(BG_QUERY)
+
+ assert light == "\x1b]11;rgb:fcfc/fbfb/f8f8\x07"
+
+
+def test_an_unknown_appearance_falls_back_rather_than_failing() -> None:
+ responder = TerminalQueryResponder(appearance="solarized")
+
+ assert responder.feed(BG_QUERY) == "\x1b]11;rgb:1212/1414/1a1a\x07"
+
+
+def test_the_terminator_the_query_used_is_the_one_answered_with() -> None:
+ responder = TerminalQueryResponder()
+
+ assert responder.feed("\x1b]11;?\x1b\\").endswith("\x1b\\")
+ assert responder.feed("\x1b]11;?\x07").endswith("\x07")
+
+
+def test_a_query_split_across_two_pty_reads_is_still_answered() -> None:
+ responder = TerminalQueryResponder()
+
+ assert responder.feed("\x1b]11;") == ""
+ assert responder.feed("?\x07") == "\x1b]11;rgb:1212/1414/1a1a\x07"
+
+
+def test_an_answered_query_is_never_answered_twice() -> None:
+ """The retained tail must not re-match what it already replied to."""
+ responder = TerminalQueryResponder()
+ responder.feed(BG_QUERY)
+
+ assert responder.feed("Welcome to Codex\r\n") == ""
+
+
+def test_ordinary_output_is_not_mistaken_for_a_query() -> None:
+ responder = TerminalQueryResponder()
+
+ assert responder.feed("\x1b[32mdone\x1b[0m — 12 files changed\r\n") == ""
+
+
+def test_setting_a_colour_is_not_a_question() -> None:
+ """``ESC ] 11 ; <colour>`` recolours the terminal; nothing is being asked."""
+ responder = TerminalQueryResponder()
+
+ assert responder.feed("\x1b]11;#ff0000\x07") == ""
+
+
+def test_replies_echoed_by_a_browser_are_recognised_as_such() -> None:
+ assert is_terminal_report_only(REPORTS) is True
+
+
+def test_typing_is_never_mistaken_for_a_reply() -> None:
+ assert is_terminal_report_only("review this") is False
+ assert is_terminal_report_only(REPORTS + "review this") is False
+ assert is_terminal_report_only("") is False
+
+
+def test_a_cursor_position_report_still_reaches_the_agent() -> None:
+ """Only the two replies the backend produces itself are dropped."""
+ assert is_terminal_report_only("\x1b[12;40R") is False
+
+
+# --------------------------------------------------------------------------- #
+# Drift guard #
+# --------------------------------------------------------------------------- #
+_THEMES_TS = (
+ Path(__file__).resolve().parents[3]
+ / "jarvis"
+ / "ui"
+ / "web"
+ / "frontend"
+ / "src"
+ / "components"
+ / "agentic"
+ / "terminalThemes.ts"
+)
+
+
[email protected]("appearance", sorted(THEME_COLOURS))
+def test_the_answered_colours_match_the_theme_the_pane_is_drawn_with(
+ appearance: str,
+) -> None:
+ """Telling the CLI a colour the pane does not use is the same bug, quieter.
+
+ The palette lives in TypeScript because that is what paints the pane; the
+ backend answers the CLI's colour query from a copy. This pins the copy.
+ """
+ if not _THEMES_TS.exists(): # a source checkout without the frontend
+ pytest.skip("frontend sources are not present")
+ source = _THEMES_TS.read_text(encoding="utf-8")
+ block = re.search(
+ rf"{appearance.upper()}_TERMINAL_THEME: ITheme = \{{(.*?)\}};",
+ source,
+ re.DOTALL,
+ )
+ assert block is not None, f"no {appearance} theme found in terminalThemes.ts"
+ declared = dict(re.findall(r"(\w+): \"(#[0-9a-fA-F]{6})\"", block.group(1)))
+
+ assert THEME_COLOURS[appearance] == (
+ declared["foreground"].lower(),
+ declared["background"].lower(),
+ )
diff --git a/tests/unit/agentic_ide/test_terminal_queries.py b/tests/unit/agentic_ide/test_terminal_queries.py
new file mode 100644
index 0000000000..c8c652898a
--- /dev/null
+++ b/tests/unit/agentic_ide/test_terminal_queries.py
@@ -0,0 +1,106 @@
+"""A pane answers its agent's terminal queries here, not in the browser.
+
+The bug being pinned: a coding CLI asks its terminal for the device type and
+the screen colours while starting and reads the answer within milliseconds. Let
+xterm in the browser answer and the reply crosses the socket twice, arriving
+after the CLI's prompt editor has opened — where it shows up as a line of
+``11;rgb:...`` the user never typed. Reported against a grid of Codex panes,
+where the round trip is slowest and the symptom was constant.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import Registry
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+#: What a CLI asks on startup: device attributes, then the screen colours.
+STARTUP_QUERIES = "\x1b[c\x1b]11;?\x07"
+
+DARK_BACKGROUND_REPLY = "\x1b]11;rgb:1212/1414/1a1a\x07"
+LIGHT_BACKGROUND_REPLY = "\x1b]11;rgb:fcfc/fbfb/f8f8\x07"
+
+
+def fake_pty() -> FakePtyManager:
+ return FakePtyManager()
+
+
+def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ return Registry(pty_manager=fake_pty)
+
+
+async def _noop_output(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
+
+
+async def test_a_startup_query_is_answered_into_the_pty(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await registry.start(str(tmp_path), [{"agent": "codex"}])
+ term = await registry.attach("Alex", 80, 24, _noop_output, _noop_exit)
+
+ await fake_pty.emit(term.pty_id, STARTUP_QUERIES)
+
+ assert fake_pty.typed == [f"\x1b[?1;2c{DARK_BACKGROUND_REPLY}"]
+
+
+async def test_the_reply_describes_the_pane_the_viewer_is_looking_at(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await registry.start(str(tmp_path), [{"agent": "codex"}])
+ term = await registry.attach("Alex", 80, 24, _noop_output, _noop_exit, appearance="light")
+
+ await fake_pty.emit(term.pty_id, "\x1b]11;?\x07")
+
+ assert fake_pty.typed == [LIGHT_BACKGROUND_REPLY]
+
+
+async def test_a_replayed_screen_does_not_answer_its_own_old_queries(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The regression that timing alone could never have caught.
+
+ A pane re-joining a running agent is handed the raw stream that drew the
+ current screen — startup queries included. Answering those a second time
+ writes the reply into a prompt the agent opened minutes ago, which is the
+ corruption itself.
+ """
+ await registry.start(str(tmp_path), [{"agent": "codex"}])
+ term = await registry.attach("Alex", 80, 24, _noop_output, _noop_exit)
+ await fake_pty.emit(term.pty_id, STARTUP_QUERIES)
+ answered_once = list(fake_pty.typed)
+
+ replayed: list[str] = []
+
+ async def _collect(text: str) -> None:
+ replayed.append(text)
+
+ rejoined = await registry.attach("Alex", 80, 24, _collect, _noop_exit)
+
+ assert rejoined.reattached is True
+ # The viewer gets the queries back (they are part of the screen)...
+ assert any(STARTUP_QUERIES in chunk for chunk in replayed)
+ # ...and nothing further was typed at the agent because of it.
+ assert fake_pty.typed == answered_once
+
+
+async def test_ordinary_agent_output_types_nothing_at_the_agent(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await registry.start(str(tmp_path), [{"agent": "codex"}])
+ term = await registry.attach("Alex", 80, 24, _noop_output, _noop_exit)
+
+ await fake_pty.emit(term.pty_id, "\x1b[32mediting main.py\x1b[0m\r\n")
+
+ assert fake_pty.typed == []