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 long-running pane coming back as empty space

Ruben Lütke83912a69c650
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 4ccec97b17..b49612bf83 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -153,6 +153,14 @@ RESUME_FAILED_WINDOW_S = 45.0
# nothing; two attempts cover a slow machine without turning into polling.
DISCOVERY_DELAYS_S = (4.0, 12.0)
+# How long the nudged window size is held before it is put back (see
+# ``_nudge_repaint``). A PTY carries one size, not a queue of them: set twice
+# within the same event-loop tick, the agent may only ever observe the second
+# value, see no change, and redraw nothing. Long enough that the two sizes are
+# distinct events for a process that polls or debounces its resize handler,
+# short enough that nobody sees a pane one row short.
+REPAINT_NUDGE_S = 0.08
+
# Bracketed paste. A TUI that has enabled it receives everything between these
# markers as ONE pasted block rather than as keystrokes, which is the only way
# a structured prompt survives the trip: a bare "\n" written to a PTY IS the
@@ -1374,6 +1382,13 @@ class Registry:
# this the pane comes back blank until the agent happens to
# repaint, which looks exactly like a dead terminal.
await on_output(replay)
+ if term.replay.truncated:
+ # The tail is all this pane has, and it no longer starts where
+ # the agent started drawing. Replaying it alone brings back the
+ # one row the agent rewrote last and empty space where its
+ # prompt box should be — see ReplayBuffer's docstring. Ask for
+ # a fresh paint instead of hoping one arrives.
+ await self._nudge_repaint(term, cols, rows)
logger.debug("Agentic IDE: {} re-joined a running agent", term.name)
return term
@@ -1587,6 +1602,37 @@ class Registry:
return False
return self._manager().write(term.pty_id, data)
+ async def _nudge_repaint(self, term: Terminal, cols: int, rows: int) -> None:
+ """Ask the agent in ``term`` to draw its whole interface again.
+
+ A terminal protocol has no "please repaint": the drawing side decides
+ what to redraw and when. A WINDOW SIZE CHANGE is the one event every
+ full-screen TUI answers by rebuilding its frame from scratch — and
+ unlike sending Ctrl+L it is not input, so it cannot land in the agent's
+ prompt, submit anything, or disturb the work in progress.
+
+ Height only, by one row, and put back immediately. Changing the WIDTH
+ would re-wrap the scrollback of an agent that has been running for an
+ hour — a visible mess in exchange for nothing, since the redraw is
+ triggered by the size CHANGING, not by which dimension changed.
+
+ Never fatal: a pane whose PTY refuses to resize is one whose screen
+ could not have been repaired anyway, and that must not cost the user
+ the reconnect itself.
+ """
+ pty_id = term.pty_id
+ if not pty_id:
+ return
+ manager = self._manager()
+ try:
+ # Two is the floor a TUI can still lay out; below it some redraw
+ # into a single row and never recover the frame.
+ manager.resize(pty_id, cols, max(rows - 1, 2))
+ await asyncio.sleep(REPAINT_NUDGE_S)
+ manager.resize(pty_id, cols, rows)
+ except Exception as exc: # noqa: BLE001 - a stale screen beats a failed reconnect
+ logger.debug("Agentic IDE: could not nudge {} into a repaint: {}", term.name, exc)
+
def resize(self, key: str, cols: int, rows: int, workspace_id: str | None = None) -> bool:
found = self._locate(key, workspace_id)
if found is None:
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
index 80f132e80d..eca551cdfa 100644
--- a/jarvis/agentic_ide/transcript.py
+++ b/jarvis/agentic_ide/transcript.py
@@ -39,6 +39,16 @@ _MISC_RE = re.compile(r"\x1b[<>=]")
# A row made only of these draws a frame or an animation; it carries no
# information for a model summarizing the session.
+# One COMPLETE escape sequence, anchored where a match is tried. Used to answer
+# "did this chunk stop in the middle of one?" — see :func:`_ends_mid_escape`.
+_ANY_ESC_RE = re.compile(
+ r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_]|[<>=])"
+)
+# The TAIL of a CSI sequence whose ESC was dropped: parameters, then optional
+# intermediates, then the final byte. The leading "[" is optional because the
+# split may have fallen either side of it.
+_CSI_TAIL_RE = re.compile(r"\[?[0-?]*[ -/]*[@-~]")
+
_DECORATION_CHARS = set("─│┌┐└┘├┤┬┴┼━┃╭╮╯╰═║╔╗╚╝╠╣╦╩╬▀▄█▌▐░▒▓▔▁·.-_=*#~ ")
_SPINNER_CHARS = set("|/\\-◐◓◑◒✻✽✢·✳✶⣿")
@@ -52,6 +62,18 @@ def strip_ansi(text: str) -> str:
return "".join(ch for ch in text if ch >= " " or ch in "\t\n\r")
+def _ends_mid_escape(text: str) -> bool:
+ """Does ``text`` stop INSIDE an escape sequence?
+
+ A PTY read ends wherever the kernel filled its buffer, so an escape can be
+ split across two chunks. The last ``ESC`` decides it: if what follows is a
+ complete sequence the chunk is self-contained, and if it is not, the rest is
+ at the front of the NEXT chunk.
+ """
+ esc = text.rfind("\x1b")
+ return esc >= 0 and _ANY_ESC_RE.match(text, esc) is None
+
+
def _is_decorative(ch: str) -> bool:
"""True for a glyph that only ever draws a frame or an animation.
@@ -151,15 +173,30 @@ class ReplayBuffer:
the stream that drew it. Cleaned-up text would come back as a wall of
prose where a framed, coloured interface used to be.
- Bounded by total characters, dropping whole chunks from the front. A TUI
- repaints itself constantly, so an old partial escape sequence at the very
- front is overwritten within a frame; cutting mid-sequence instead would
- leave the terminal in a broken colour/cursor state.
+ Bounded by total characters, dropping whole chunks from the front — and
+ ``truncated`` then says so, because **a cut stream does not repair
+ itself**. This buffer used to assume it did ("a TUI repaints itself
+ constantly"), and that assumption is what put empty rectangles in two panes
+ of a live workspace (reported 2026-07-27). A coding agent built on Ink
+ paints its interface ONCE and afterwards rewrites only the row that
+ changed, addressed by RELATIVE cursor moves — so a tail that lost its front
+ replays the spinner row the agent wrote last onto rows where the prompt box
+ it drew twenty minutes ago is simply missing. Nothing later redraws it.
+
+ Whoever replays a truncated buffer therefore has to ask the agent for a
+ fresh paint afterwards; :meth:`SessionRegistry.attach` does it with a
+ window-size change, the one request every TUI answers with a full redraw.
"""
limit: int = REPLAY_LIMIT_CHARS
_chunks: deque[str] = field(default_factory=deque, init=False)
_size: int = field(default=0, init=False)
+ #: Has anything been dropped since the last :meth:`clear`? Read by the
+ #: viewer path to decide whether the replay alone can be trusted.
+ truncated: bool = field(default=False, init=False)
+ #: Did the last dropped chunk stop inside an escape sequence? Then the rest
+ #: of that sequence is at the front of what remains.
+ _open_escape: bool = field(default=False, init=False)
def feed(self, chunk: str) -> None:
if not chunk:
@@ -167,15 +204,35 @@ class ReplayBuffer:
self._chunks.append(chunk)
self._size += len(chunk)
while self._size > self.limit and len(self._chunks) > 1:
- self._size -= len(self._chunks.popleft())
+ dropped = self._chunks.popleft()
+ self._size -= len(dropped)
+ self.truncated = True
+ self._open_escape = _ends_mid_escape(dropped)
def text(self) -> str:
- """Everything kept, oldest first — ready to be written to a terminal."""
- return "".join(self._chunks)
+ """Everything kept, oldest first — ready to be written to a terminal.
+
+ A truncated tail is repaired at its front before it goes out. Dropping
+ whole chunks can still leave the CONTINUATION of a sequence there — a
+ terminal handed ``[38;5;214m`` with no ``ESC`` prints it as visible text
+ in the middle of the agent's interface — so that remnant is skipped, and
+ an attribute reset makes the starting colour deterministic rather than
+ inherited from bytes that are gone.
+ """
+ text = "".join(self._chunks)
+ if not self.truncated or not text:
+ return text
+ if self._open_escape:
+ remnant = _CSI_TAIL_RE.match(text)
+ if remnant is not None:
+ text = text[remnant.end() :]
+ return "\x1b[0m" + text
def clear(self) -> None:
self._chunks.clear()
self._size = 0
+ self.truncated = False
+ self._open_escape = False
__all__ = [
diff --git a/jarvis/terminal/shells.py b/jarvis/terminal/shells.py
index 88724701a1..91e3290c72 100644
--- a/jarvis/terminal/shells.py
+++ b/jarvis/terminal/shells.py
@@ -140,19 +140,6 @@ def discover_shells() -> list[ShellInfo]:
return _unix_shells()
-def default_shell() -> ShellInfo | None:
- """The shell to use when nobody named one — ``None`` on a host with none.
-
- "First in preference order" is the whole rule: ``discover_shells()`` already
- returns pwsh before Windows PowerShell before cmd, and the user's ``$SHELL``
- before anything ``/etc/shells`` lists. Callers that only need *a* working
- shell (a plain terminal pane, wrapping a command in one) ask here instead of
- each re-deriving that order and drifting apart.
- """
- shells = discover_shells()
- return shells[0] if shells else None
-
-
def get_shell(shell_id: str) -> ShellInfo | None:
"""Looks up a shell by ID — None if not installed."""
for shell in discover_shells():
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index a5fba39000..20391de8b7 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -21,19 +21,10 @@ vi.mock("@/store/events", () => ({
vi.mock("@/lib/agenticIdeApi", () => ({
addTerminal: vi.fn(),
- attachToTerminal: vi.fn(),
closeTerminal: vi.fn(),
closeTerminals: vi.fn(),
composePrompt: vi.fn(),
- // Polled by the grid so the pane headers keep saying what their agents are
- // doing. Resolves empty by default; the recap tests give it real rows.
- fetchTerminalRecaps: vi.fn(async () => ({
- workspace_id: "ide_test",
- terminals: [],
- })),
promptTerminal: vi.fn(),
- // Reached from the toolbar's settings panel, which the grid always renders.
- setIdeActiveAccount: vi.fn(),
}));
// The grid follows the app theme for its terminal colours; these tests render
@@ -53,8 +44,6 @@ vi.mock("./AgenticTerminal", () => ({
maximized,
splitDisabled,
restartToken,
- recap,
- recapDetail,
onRestart,
agents,
onToggleMaximize,
@@ -65,8 +54,6 @@ vi.mock("./AgenticTerminal", () => ({
maximized?: boolean;
splitDisabled?: boolean;
restartToken?: number;
- recap?: string;
- recapDetail?: string;
onRestart?: () => void;
agents?: Array<{ name: string }>;
onToggleMaximize?: () => void;
@@ -78,8 +65,6 @@ vi.mock("./AgenticTerminal", () => ({
data-maximized={maximized ? "yes" : "no"}
data-agents={(agents ?? []).map((a) => a.name).join(",")}
data-restart-token={String(restartToken ?? 0)}
- data-recap={recap ?? ""}
- data-recap-detail={recapDetail ?? ""}
>
{name}
<button data-testid={`pane-maximize-${name}`} onClick={onToggleMaximize}>
@@ -201,24 +186,6 @@ beforeEach(() => {
files: [],
submitted: true,
});
- vi.mocked(api.attachToTerminal).mockResolvedValue({
- terminal: "Mika",
- references: ["@.jarvis/drops/shot.png"],
- files: ["shot.png"],
- copied: 1,
- submitted: false,
- delivered: false,
- analysis: [
- {
- name: "shot.png",
- reference: "@.jarvis/drops/shot.png",
- kind: "image",
- detail: "A login dialog whose submit button overflows its container.",
- described_by: "vision",
- note: "",
- },
- ],
- });
});
afterEach(() => {
@@ -303,50 +270,6 @@ describe("pane actions", () => {
);
});
- it("keeps a plain terminal out of the prompt bar's targets", () => {
- // A plain terminal is a shell prompt: Jarvis does not type into one, so
- // offering it as a target would promise a delivery that is always refused.
- const session = sessionWith([
- ["Mika", 0],
- ["Nova", 1],
- ]);
- session.terminals[1] = {
- ...session.terminals[1],
- agent: "shell",
- display_name: "Plain Terminal",
- accepts_prompts: false,
- };
- renderGrid(session);
-
- expect(screen.getByRole("button", { name: /^Mika/ })).toBeTruthy();
- expect(screen.queryByRole("button", { name: /^Nova live$/ })).toBeNull();
- // The agent pane, not the shell, is what the prompt goes to.
- expect(screen.getByPlaceholderText(/instruction for Mika/i)).toBeTruthy();
- });
-
- it("does not make a new plain terminal the prompt target", async () => {
- const next = sessionWith([
- ["Mika", 0],
- ["Aria", 1],
- ["Nova", 2],
- ]);
- next.terminals[1] = {
- ...next.terminals[1],
- agent: "shell",
- display_name: "Plain Terminal",
- accepts_prompts: false,
- };
- vi.mocked(api.addTerminal).mockResolvedValue(next);
- renderGrid();
-
- fireEvent.click(screen.getByTestId("pane-split-right-Mika"));
-
- await waitFor(() => expect(api.addTerminal).toHaveBeenCalled());
- // The prompt bar stays pointed at the agent it was on — a shell pane that
- // stole the target would silently swallow the next instruction.
- expect(screen.getByPlaceholderText(/instruction for Mika/i)).toBeTruthy();
- });
-
it("reports a refused split instead of pretending it worked", async () => {
vi.mocked(api.addTerminal).mockRejectedValue(
new Error("This workspace already has the maximum of 12 terminals."),
@@ -550,32 +473,18 @@ describe("selecting several terminals", () => {
expect(screen.getByText("Selected: 0")).toBeTruthy();
});
- it("never enters selection mode on a right-click", () => {
+ it("right-clicking a pane enters selection mode and marks it immediately", () => {
renderGrid();
- // The pane keeps the right button for the app-wide Cut/Copy/Paste menu, so
- // the event must also survive untouched rather than being swallowed here.
- const reached = fireEvent.contextMenu(screen.getByTestId("pane-cell-Nova"));
+ fireEvent.contextMenu(screen.getByTestId("pane-cell-Nova"));
- expect(reached).toBe(true);
expect(
screen.getByTestId("terminal-selection-toggle").getAttribute("aria-pressed"),
- ).toBe("false");
- expect(screen.queryByTestId("terminal-selection-actions")).toBeNull();
- expect(screen.queryByTestId("select-terminal-Nova")).toBeNull();
- });
-
- it("does nothing at all on a right-click while selection mode is on", () => {
- renderGrid();
- fireEvent.click(screen.getByTestId("terminal-selection-toggle"));
-
- const reached = fireEvent.contextMenu(screen.getByTestId("select-terminal-Nova"));
-
- expect(reached).toBe(false);
+ ).toBe("true");
expect(
screen.getByTestId("select-terminal-Nova").getAttribute("aria-pressed"),
- ).toBe("false");
- expect(screen.getByText("Selected: 0")).toBeTruthy();
+ ).toBe("true");
+ expect(screen.getByText("Selected: 1")).toBeTruthy();
});
it("select all marks every terminal with one click", () => {
@@ -647,8 +556,7 @@ describe("selecting several terminals", () => {
it("keeps every selected terminal open when confirmation is cancelled", async () => {
renderGrid();
- fireEvent.click(screen.getByTestId("terminal-selection-toggle"));
- fireEvent.click(screen.getByTestId("select-terminal-Mika"));
+ fireEvent.contextMenu(screen.getByTestId("pane-cell-Mika"));
fireEvent.click(screen.getByTestId("close-selected-terminals"));
fireEvent.click(screen.getByRole("button", { name: "Keep them open" }));
@@ -773,9 +681,7 @@ describe("the prompt bar composes before it sends", () => {
type("run the tests");
await waitFor(() => expect(screen.getByTestId("prompt-preview")).toBeTruthy());
- // The third argument is the dropped-file list — empty here, because this
- // instruction was typed with nothing attached.
- expect(api.composePrompt).toHaveBeenCalledWith("Mika", "run the tests", []);
+ expect(api.composePrompt).toHaveBeenCalledWith("Mika", "run the tests");
expect(api.promptTerminal).not.toHaveBeenCalled();
});
@@ -787,13 +693,7 @@ describe("the prompt bar composes before it sends", () => {
fireEvent.click(screen.getByTestId("prompt-preview-send"));
await waitFor(() =>
- expect(api.promptTerminal).toHaveBeenCalledWith(
- "Mika",
- "## Task\nRun the tests.",
- // Nothing carried alongside: the composed text already contains
- // whatever was dropped, so sending it again would duplicate it.
- { attachments: [] },
- ),
+ expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "## Task\nRun the tests."),
);
});
@@ -805,9 +705,7 @@ describe("the prompt bar composes before it sends", () => {
fireEvent.click(screen.getByTestId("prompt-preview-verbatim"));
await waitFor(() =>
- expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests", {
- attachments: [],
- }),
+ expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests"),
);
});
@@ -831,159 +729,11 @@ describe("the prompt bar composes before it sends", () => {
type("run the tests");
await waitFor(() =>
- expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests", {
- attachments: [],
- }),
+ expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests"),
);
});
});
-/*
- * Dropping a screenshot on the prompt bar.
- *
- * This is the gesture the whole feature exists for, and its failure mode is
- * quiet: a user drops a picture of a broken layout, types "fix this", and the
- * agent — which frequently cannot open an image at all — receives a path and a
- * pronoun. So what is pinned here is that the CONTENTS of the file reach the
- * composition, not merely that a drop was accepted.
- */
-describe("dropping files on the prompt bar", () => {
- /** A DataTransfer stand-in; jsdom cannot construct a real one. */
- function transfer(types: string[]) {
- return {
- types,
- files: [],
- items: [],
- dropEffect: "none",
- getData: (kind: string) =>
- kind === "text/uri-list" ? "file:///C:/work/shot.png" : "",
- } as unknown as DataTransfer;
- }
-
- const drop = (types: string[] = ["Files"]) =>
- fireEvent.drop(screen.getByTestId("agentic-composer"), {
- dataTransfer: transfer(types),
- });
-
- it("reads the dropped file instead of typing its path into the pane", async () => {
- renderGrid();
-
- drop();
-
- await waitFor(() => expect(api.attachToTerminal).toHaveBeenCalled());
- const [name, payload] = vi.mocked(api.attachToTerminal).mock.calls[0];
- expect(name).toBe("Mika");
- expect(payload.analyze).toBe(true);
- // Held rather than typed: the user is still writing the sentence that
- // explains the file, and it goes in with that sentence.
- expect(payload.deliver).toBe(false);
- expect(payload.paths).toEqual(["C:/work/shot.png"]);
- });
-
- it("shows what was read out of the file, not just its name", async () => {
- renderGrid();
-
- drop();
-
- await waitFor(() => expect(screen.getByTestId("agentic-attachments")).toBeTruthy());
- const strip = screen.getByTestId("agentic-attachments");
- expect(strip.textContent).toContain("shot.png");
- expect(strip.textContent).toContain("described");
- });
-
- it("carries the analysis into the composition", async () => {
- renderGrid();
- drop();
- await waitFor(() => expect(screen.getByTestId("agentic-attachments")).toBeTruthy());
-
- const box = screen.getByPlaceholderText(/instruction for Mika/i);
- fireEvent.change(box, { target: { value: "fix this" } });
- fireEvent.keyDown(box, { key: "Enter" });
-
- await waitFor(() => expect(api.composePrompt).toHaveBeenCalled());
- const attachments = vi.mocked(api.composePrompt).mock.calls[0][2];
- expect(attachments).toHaveLength(1);
- expect(attachments?.[0].detail).toContain("submit button overflows");
- });
-
- it("keeps the attachment when the user backs out of the rewrite", async () => {
- // Discarding a proposed wording is not a reason to lose the dropped file.
- renderGrid();
- drop();
- await waitFor(() => expect(screen.getByTestId("agentic-attachments")).toBeTruthy());
-
- const box = screen.getByPlaceholderText(/instruction for Mika/i);
- fireEvent.change(box, { target: { value: "fix this" } });
- fireEvent.keyDown(box, { key: "Enter" });
- await waitFor(() => expect(screen.getByTestId("prompt-preview")).toBeTruthy());
-
- fireEvent.click(screen.getByTestId("prompt-preview-cancel"));
-
- expect(screen.getByTestId("agentic-attachments").textContent).toContain("shot.png");
- });
-
- it("lets an attachment be taken back off", async () => {
- renderGrid();
- drop();
- await waitFor(() => expect(screen.getByTestId("agentic-attachments")).toBeTruthy());
-
- fireEvent.click(screen.getByTestId("agentic-attachment-remove-shot.png"));
-
- expect(screen.queryByTestId("agentic-attachment-shot.png")).toBeNull();
- });
-
- it("clears the attachments once they have been sent", async () => {
- renderGrid();
- drop();
- await waitFor(() => expect(screen.getByTestId("agentic-attachments")).toBeTruthy());
-
- const box = screen.getByPlaceholderText(/instruction for Mika/i);
- fireEvent.change(box, { target: { value: "fix this" } });
- fireEvent.keyDown(box, { key: "Enter" });
- await waitFor(() => expect(screen.getByTestId("prompt-preview")).toBeTruthy());
- fireEvent.click(screen.getByTestId("prompt-preview-send"));
-
- // Otherwise the next, unrelated instruction would silently carry the old
- // screenshot along with it.
- await waitFor(() => expect(screen.queryByTestId("agentic-attachments")).toBeNull());
- });
-
- it("ignores a drag carrying only selected text", async () => {
- renderGrid();
-
- drop(["text/plain"]);
-
- expect(api.attachToTerminal).not.toHaveBeenCalled();
- });
-
- it("reports an analysis that came back empty rather than pretending", async () => {
- vi.mocked(api.attachToTerminal).mockResolvedValue({
- terminal: "Mika",
- references: [],
- files: [],
- copied: 0,
- submitted: false,
- delivered: false,
- analysis: [],
- });
- renderGrid();
-
- drop();
-
- await waitFor(() => expect(pushToast).toHaveBeenCalled());
- expect(pushToast.mock.calls[0][0]).toBe("warning");
- });
-
- it("surfaces a failed attach instead of losing the drop silently", async () => {
- vi.mocked(api.attachToTerminal).mockRejectedValue(new Error("pane is gone"));
- renderGrid();
-
- drop();
-
- await waitFor(() => expect(pushToast).toHaveBeenCalledWith("error", "pane is gone"));
- });
-});
-
/*
* The seam between the terminals and the prompt bar.
*
@@ -1100,61 +850,3 @@ describe("a workspace with far more panes than the window fits", () => {
expect(screen.getAllByTestId(/^pane-cell-/)).toHaveLength(100);
});
});
-
-/*
- * The pane headers say what each session is doing, and that sentence goes stale
- * in seconds. So the grid polls for it — separately from the workspace state,
- * which changes only when a pane is opened, closed or moved.
- */
-describe("session recaps", () => {
- it("asks the backend what its own workspace's panes are doing", async () => {
- renderGrid();
-
- await waitFor(() =>
- expect(api.fetchTerminalRecaps).toHaveBeenCalledWith("ide_test"),
- );
- });
-
- it("hands each pane the recap that came back for it", async () => {
- vi.mocked(api.fetchTerminalRecaps).mockResolvedValue({
- workspace_id: "ide_test",
- terminals: [
- {
- key: "mika",
- name: "Mika",
- status: "live",
- recap: "Running pytest tests/unit/test_login.py",
- recap_detail:
- 'Last asked to: "Fix the failing login test". Working now: Running pytest.',
- },
- ],
- });
-
- renderGrid();
-
- await waitFor(() =>
- expect(screen.getByTestId("pane-Mika").dataset.recap).toBe(
- "Running pytest tests/unit/test_login.py",
- ),
- );
- expect(screen.getByTestId("pane-Mika").dataset.recapDetail).toContain(
- "Fix the failing login test",
- );
- });
-
- it("falls back to the recap the workspace state carried", async () => {
- // Nothing polled yet (and nothing ever will, here) — a pane must still open
- // with a sentence in its header rather than with a blank that fills in.
- vi.mocked(api.fetchTerminalRecaps).mockRejectedValue(new Error("offline"));
- const session = sessionWith([["Mika", 0]]);
- session.terminals[0].recap = "Waiting for its first instruction.";
-
- renderGrid(session);
-
- await waitFor(() =>
- expect(screen.getByTestId("pane-Mika").dataset.recap).toBe(
- "Waiting for its first instruction.",
- ),
- );
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index cff7c3deec..1cf1a287db 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -16,11 +16,8 @@ import {
Brain,
Check,
ChevronUp,
- FileText,
FolderGit2,
- Image as ImageIcon,
ListChecks,
- Loader2,
Minus,
Moon,
Plus,
@@ -51,29 +48,14 @@ import {
paneGrid,
} from "./layout";
import { PromptPreview } from "./PromptPreview";
-import { WorkspaceSettings } from "./WorkspaceSettings";
-import { usePaneFileDrag } from "./paneFileDrag";
-import {
- extractPaneDrop,
- extractPasteFiles,
- isEmptyPayload,
- nameClipboardFile,
- type PaneDropPayload,
-} from "./paneDrop";
import {
addTerminal,
- attachToTerminal,
closeTerminal,
closeTerminals,
composePrompt,
- fetchTerminalRecaps,
promptTerminal,
type ComposedPreview,
- type DropAttachment,
- type IdeAccountState,
- type IdeState,
type SessionState,
- type TerminalRecap,
} from "@/lib/agenticIdeApi";
interface AgenticGridProps {
@@ -88,30 +70,11 @@ interface AgenticGridProps {
agents?: SplitAgentChoice[];
/** Adding or closing a pane changes the workspace — the owner re-reads it. */
onSessionChanged?: (session: SessionState) => void;
- /**
- * Which subscription new terminals open on, per coding CLI. Drives the
- * settings panel; an empty list simply leaves it with nothing to show.
- */
- accounts?: IdeAccountState[];
- /** The settings panel changed the workspace state — the owner applies it. */
- onStateChanged?: (state: IdeState) => void;
}
const FONT_MIN = 10;
const FONT_MAX = 20;
-/**
- * How often the pane headers re-read what their agents are doing.
- *
- * A recap is a glanceable label, not a live log — five seconds is well below
- * the time it takes to look across a grid, and slow enough that a dozen panes
- * cost one cheap request per pane per minute. The read is deliberately the
- * small `/recaps` one rather than the full workspace state (see the API
- * client), and it is skipped entirely while the window is in the background:
- * nobody is glancing at a header they cannot see.
- */
-const RECAP_POLL_MS = 5000;
-
/*
* How tall the prompt bar is — dragged by its top edge, and remembered.
*
@@ -176,21 +139,6 @@ function writeStored(key: string, value: string): void {
}
}
-/**
- * May Jarvis type into this pane?
- *
- * False for a plain terminal: that pane is a live SHELL prompt, so a line typed
- * into it from the outside would not be read by an agent — it would run as a
- * command. The prompt bar therefore never offers one as a target, and clicking
- * one does not steal the target from the agent you were writing to.
- *
- * Undefined means a backend that predates the flag, where every pane was an
- * agent — so absent reads as "yes", never as "no".
- */
-function takesPrompts(term: { accepts_prompts?: boolean }): boolean {
- return term.accepts_prompts !== false;
-}
-
function storedAppearance(): TerminalAppearance | null {
return readStored(APPEARANCE_KEY, (raw) =>
raw === "light" || raw === "dark" ? raw : null,
@@ -213,8 +161,6 @@ export function AgenticGrid({
maxTerminals = 12,
agents,
onSessionChanged,
- accounts = [],
- onStateChanged,
}: AgenticGridProps) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
@@ -240,15 +186,8 @@ export function AgenticGrid({
setFontSizeState(next);
writeStored(FONT_KEY, String(next));
}, []);
- const [target, setTarget] = useState(
- session.terminals.find(takesPrompts)?.name ?? "",
- );
+ const [target, setTarget] = useState(session.terminals[0]?.name ?? "");
const [statuses, setStatuses] = useState<Record<string, { status: PaneStatus; detail?: string }>>({});
- // What each pane is doing, by call-sign, as the header shows it. Kept beside
- // the session rather than inside it because it changes on a completely
- // different clock: the layout changes when a pane is opened or closed, a
- // recap whenever an agent prints a line.
- const [recaps, setRecaps] = useState<Record<string, TerminalRecap>>({});
const [prompt, setPrompt] = useState("");
const [sending, setSending] = useState(false);
// The composed prompt waiting for the user's approval, and the wording they
@@ -298,44 +237,16 @@ export function AgenticGrid({
});
}, []);
- /*
- * Keep the pane headers current.
- *
- * Bound to the workspace ID, so switching tabs starts a fresh poll for the
- * workspace now on screen instead of continuing to describe the one behind
- * it. A failed read keeps whatever the headers already say: the backend
- * warming up, or a workspace closed in another window, is not a reason to
- * blank eight labels — and the recap is a convenience, never the pane.
- */
- useEffect(() => {
- let cancelled = false;
- const pull = async () => {
- if (typeof document !== "undefined" && document.hidden) return;
- try {
- const answer = await fetchTerminalRecaps(session.id);
- if (cancelled) return;
- setRecaps(
- Object.fromEntries(answer.terminals.map((term) => [term.name, term])),
- );
- } catch {
- /* keep the last recaps — a stale sentence beats an empty header */
- }
- };
- void pull();
- const timer = window.setInterval(() => void pull(), RECAP_POLL_MS);
- // A window coming back to the foreground has skipped every tick it spent
- // hidden, so its headers are as old as the time away. Catch up at once
- // rather than showing minute-old work for another five seconds.
- const onVisible = () => {
- if (!document.hidden) void pull();
- };
- document.addEventListener("visibilitychange", onVisible);
- return () => {
- cancelled = true;
- window.clearInterval(timer);
- document.removeEventListener("visibilitychange", onVisible);
- };
- }, [session.id]);
+ const markTerminal = useCallback((name: string) => {
+ setMaximized(null);
+ setSelectionMode(true);
+ setSelectedTerminals((current) => {
+ if (current.has(name)) return current;
+ const next = new Set(current);
+ next.add(name);
+ return next;
+ });
+ }, []);
// A terminal can disappear because another client closed it. Keep the local
// selection honest instead of leaving an invisible name selected.
@@ -452,10 +363,7 @@ export function AgenticGrid({
// A fresh pane should receive the next prompt — that is why it was opened.
const known = new Set(session.terminals.map((t) => t.name));
const added = next.terminals.find((t) => !known.has(t.name));
- // ...unless it is a plain terminal — that one is typed into by hand, and
- // stealing the target would silently redirect the next prompt into a pane
- // that refuses it.
- if (added && takesPrompts(added)) setTarget(added.name);
+ if (added) setTarget(added.name);
} catch (e) {
pushToast("error", (e as Error).message);
} finally {
@@ -470,7 +378,7 @@ export function AgenticGrid({
setPendingClose(null);
if (maximized === name) setMaximized(null);
onSessionChanged?.(next);
- if (target === name) setTarget(next.terminals.find(takesPrompts)?.name ?? "");
+ if (target === name) setTarget(next.terminals[0]?.name ?? "");
} catch (e) {
pushToast("error", (e as Error).message);
} finally {
@@ -488,7 +396,7 @@ export function AgenticGrid({
const remaining = new Set(result.session.terminals.map((term) => term.name));
if (maximized && !remaining.has(maximized)) setMaximized(null);
if (target && !remaining.has(target)) {
- setTarget(result.session.terminals.find(takesPrompts)?.name ?? "");
+ setTarget(result.session.terminals[0]?.name ?? "");
}
if (result.failed.length === 0) setSelectionMode(false);
else {
@@ -511,78 +419,14 @@ export function AgenticGrid({
setStatuses((prev) => ({ ...prev, [name]: { status, detail } }));
}, []);
- /*
- * Files dropped onto the PROMPT BAR, and what is in them.
- *
- * A drop on a pane and a drop here mean different things. The pane types a
- * path, which is right for "read this file" — the agent opens it. But a
- * screenshot is the case where that breaks down: several of the coding CLIs
- * cannot open an image at all, so the user drops a picture of a broken
- * layout, types "fix this", and the agent receives a path and a pronoun.
- *
- * So a drop here is READ first — described if it is an image, extracted if it
- * is a document — and the result rides along into the composition. The file
- * is still saved and still referenced; the description is the floor under it,
- * not a replacement for it.
- */
- const [attachments, setAttachments] = useState<DropAttachment[]>([]);
- const [analyzing, setAnalyzing] = useState(0);
-
- const attach = useCallback(
- async (payload: PaneDropPayload) => {
- if (isEmptyPayload(payload)) return;
- if (!target) {
- pushToast("warning", "Pick a terminal first — a dropped file belongs to one.");
- return;
- }
- setAnalyzing((n) => n + 1);
- try {
- const result = await attachToTerminal(target, {
- ...payload,
- analyze: true,
- // Held, not typed: the user is still writing the sentence that says
- // what to do with it, and it goes in with that sentence.
- deliver: false,
- });
- const found = result.analysis ?? [];
- if (found.length === 0) {
- pushToast("warning", "That drop carried nothing this prompt could use.");
- return;
- }
- setAttachments((prev) => [...prev, ...found]);
- } catch (e) {
- pushToast("error", (e as Error).message);
- } finally {
- setAnalyzing((n) => Math.max(0, n - 1));
- }
- },
- [target],
- );
-
- const { dragging, handlers: dragHandlers } = usePaneFileDrag(
- useCallback(
- (dt: DataTransfer) => {
- // Read BEFORE any await — a DataTransfer empties the moment this
- // handler returns (see ./paneDrop).
- void attach(extractPaneDrop(dt));
- },
- [attach],
- ),
- );
-
- const dropAttachment = useCallback((name: string) => {
- setAttachments((prev) => prev.filter((a) => a.name !== name));
- }, []);
-
/** Type `text` into `target` and report honestly if it was not accepted. */
- const deliver = async (text: string, carry: DropAttachment[] = []) => {
+ const deliver = async (text: string) => {
setSending(true);
try {
- const result = await promptTerminal(target, text, { attachments: carry });
+ const result = await promptTerminal(target, text);
setPreview(null);
setPreviewSource("");
setPrompt("");
- setAttachments([]);
// The text is typed either way — but if the agent did not accept it, say
// so instead of leaving the user to wonder why nothing happened.
if (result && result.submitted === false) {
@@ -614,18 +458,16 @@ export function AgenticGrid({
if (!text || !target) return;
setSending(true);
try {
- const composed = await composePrompt(target, text, attachments);
+ const composed = await composePrompt(target, text);
if (composed.composed && composed.composed !== text) {
setPreviewSource(text);
setPreview(composed);
return;
}
- // The composed text already contains the attachments, so it carries none
- // of its own; this branch did not compose, so they still have to travel.
- await deliver(text, attachments);
+ await deliver(text);
} catch (e) {
pushToast("warning", `Could not prepare the prompt: ${(e as Error).message}`);
- await deliver(text, attachments);
+ await deliver(text);
} finally {
setSending(false);
}
@@ -723,14 +565,6 @@ export function AgenticGrid({
</button>
</div>
- {/* Which subscription the next terminal spends, and the way to change
- it without leaving the workspace. */}
- <WorkspaceSettings
- accounts={accounts}
- onStateChanged={onStateChanged}
- busy={busy || working}
- />
-
<button
ref={selectionToggleRef}
type="button"
@@ -875,6 +709,11 @@ export function AgenticGrid({
"ring-2 ring-primary ring-offset-2 ring-offset-background",
maximized !== null && !isMaximized && "hidden",
)}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ markTerminal(term.name);
+ }}
style={
isMaximized
? { gridColumn: "1 / -1", gridRow: "1 / -1" }
@@ -888,13 +727,6 @@ export function AgenticGrid({
name={term.name}
workspaceId={session.id}
displayName={term.display_name}
- // The polled recap when one has arrived, the one the workspace
- // state carried until then — so a pane opens with a sentence in
- // its header rather than with a blank that fills in later.
- recap={recaps[term.name]?.recap ?? term.recap}
- recapDetail={
- recaps[term.name]?.recap_detail ?? term.recap_detail
- }
// Only the panes that are NOT on the default login carry a
// badge. Labelling every pane "Default Claude Code login" would
// be noise for the many; labelling the odd one out is the whole
@@ -910,9 +742,7 @@ export function AgenticGrid({
maximized={isMaximized}
splitDisabled={atLimit || busy || working}
agents={agents}
- onFocus={() => {
- if (takesPrompts(term)) setTarget(term.name);
- }}
+ onFocus={() => setTarget(term.name)}
onStatus={(status, detail) => setStatus(term.name, status, detail)}
onToggleMaximize={() =>
setMaximized((current) => (current === term.name ? null : term.name))
@@ -940,14 +770,10 @@ export function AgenticGrid({
)
}
onClick={() => toggleTerminalSelection(term.name)}
- // Selection mode owns the right mouse button and does nothing
- // with it. Marking a pane on right-click was too easy to
- // trigger by accident, and letting the event through would
- // open the app-wide Cut/Copy/Paste menu over an overlay that
- // has no text to copy. Left-click marks; right-click is inert.
onContextMenu={(event) => {
event.preventDefault();
event.stopPropagation();
+ markTerminal(term.name);
}}
className={cn(
"absolute inset-0 z-20 cursor-pointer rounded-xl transition-colors",
@@ -1056,38 +882,13 @@ export function AgenticGrid({
<div
data-testid="agentic-composer"
style={{ height: composerHeight }}
- {...dragHandlers}
- onPaste={(event) => {
- // Clipboard IMAGES only. Pasted text belongs to the textarea, and
- // intercepting it would break ordinary paste into the prompt.
- const images = extractPasteFiles(event.clipboardData).map((f) =>
- nameClipboardFile(f, target || "prompt"),
- );
- if (images.length === 0) return;
- event.preventDefault();
- void attach({ paths: [], files: images });
- }}
- className={cn(
- "relative flex shrink-0 flex-col overflow-hidden px-4 py-3 transition-colors",
- dragging && "bg-primary/5 ring-1 ring-inset ring-primary/50",
- )}
+ className="flex shrink-0 flex-col overflow-hidden px-4 py-3"
>
- {dragging && (
- <div
- data-testid="agentic-composer-dropzone"
- className="pointer-events-none absolute inset-2 z-10 flex items-center justify-center rounded-lg border-2 border-dashed border-primary/60 bg-background/80 text-xs font-medium text-primary"
- >
- Drop a screenshot or document — {target || "the agent"} gets what is in it
- </div>
- )}
<div className="mb-2 flex max-h-24 shrink-0 flex-wrap items-center gap-2 overflow-y-auto scrollbar-jarvis">
<span className="text-[11px] uppercase tracking-wider text-muted-foreground">
Send to
</span>
- {/* Agent panes only. A plain terminal is a shell prompt — it is
- typed into by hand, so listing it here would offer a target that
- refuses every instruction sent to it. */}
- {session.terminals.filter(takesPrompts).map((term) => {
+ {session.terminals.map((term) => {
const state = statuses[term.name];
return (
<button
@@ -1108,13 +909,6 @@ export function AgenticGrid({
);
})}
</div>
- {(attachments.length > 0 || analyzing > 0) && (
- <AttachmentStrip
- attachments={attachments}
- analyzing={analyzing}
- onRemove={dropAttachment}
- />
- )}
{preview && (
<div className="mb-2 shrink-0 overflow-y-auto scrollbar-jarvis">
<PromptPreview
@@ -1122,15 +916,10 @@ export function AgenticGrid({
composed={preview.composed}
files={preview.files}
composedBy={preview.composed_by}
- attachments={attachments}
- // The composed text already contains the attachments; the
- // verbatim path does not, so only that one carries them.
onSend={() => void deliver(preview.composed)}
- onSendVerbatim={() => void deliver(previewSource, attachments)}
+ onSendVerbatim={() => void deliver(previewSource)}
onCancel={() => {
- // Give the user their own words back rather than dropping
- // them. The attachments stay too — backing out of a rewrite
- // is not a reason to lose the file they dropped.
+ // Give the user their own words back rather than dropping them.
setPrompt(previewSource);
setPreview(null);
setPreviewSource("");
@@ -1184,86 +973,6 @@ export function AgenticGrid({
);
}
-/**
- * The files waiting to go in with the next prompt.
- *
- * Each chip says what was actually LEARNED from the file, not just that one was
- * attached. That distinction is the whole feature: "screenshot.png" tells the
- * user nothing about whether the agent will be able to see it, while "described"
- * and "not described" are the two outcomes they need to be able to tell apart
- * before they press Send — and the second one happens for real, on any install
- * whose providers cannot see images.
- */
-function AttachmentStrip({
- attachments,
- analyzing,
- onRemove,
-}: {
- attachments: DropAttachment[];
- analyzing: number;
- onRemove: (name: string) => void;
-}) {
- return (
- <div
- data-testid="agentic-attachments"
- className="mb-2 flex max-h-20 shrink-0 flex-wrap items-center gap-1.5 overflow-y-auto scrollbar-jarvis"
- >
- {attachments.map((item) => {
- const read = item.described_by !== "none" && item.detail.length > 0;
- return (
- <span
- key={item.name}
- data-testid={`agentic-attachment-${item.name}`}
- title={
- read
- ? `${item.detail.slice(0, 400)}${item.detail.length > 400 ? "…" : ""}`
- : item.note || "Attached as a file."
- }
- className={cn(
- "flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px]",
- read
- ? "border-primary/40 bg-primary/10 text-foreground"
- : "border-border text-muted-foreground",
- )}
- >
- {item.kind === "image" ? (
- <ImageIcon className="h-3 w-3 shrink-0" />
- ) : (
- <FileText className="h-3 w-3 shrink-0" />
- )}
- <span className="max-w-[12rem] truncate font-mono">{item.name}</span>
- <span className="shrink-0 text-[10px] text-muted-foreground">
- {read
- ? item.described_by === "vision"
- ? "described"
- : "text read"
- : "not described"}
- </span>
- <button
- type="button"
- aria-label={`Remove ${item.name}`}
- data-testid={`agentic-attachment-remove-${item.name}`}
- onClick={() => onRemove(item.name)}
- className="shrink-0 rounded text-muted-foreground hover:text-destructive"
- >
- <X className="h-3 w-3" />
- </button>
- </span>
- );
- })}
- {analyzing > 0 && (
- <span
- data-testid="agentic-attachment-working"
- className="flex items-center gap-1.5 rounded-md border border-dashed border-border px-2 py-1 text-[11px] text-muted-foreground"
- >
- <Loader2 className="h-3 w-3 animate-spin" />
- Reading {analyzing === 1 ? "the dropped file" : `${analyzing} dropped files`}…
- </span>
- )}
- </div>
- );
-}
-
function ConfirmSelectionClose({
names,
busy,
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
index 0507277d0c..efcffbad85 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.offscreen.test.tsx
@@ -155,6 +155,28 @@ describe("AgenticTerminal off-screen output", () => {
expect(harness.writes).toEqual(["frame one frame two frame three"]);
});
+ it("writes a flooded hidden pane out rather than losing its frame", () => {
+ // The bytes that DREW the agent's interface sit at the FRONT of the
+ // stream, and an Ink-based TUI never repaints it unprompted. A hidden pane
+ // that overflows must therefore hand what it holds to xterm — discarding
+ // the front is what left panes showing a spinner row over empty space
+ // (2026-07-27). Costly? One parse nobody paints. Correct? Always.
+ mount();
+ act(() => harness.fire?.(false));
+
+ const opening = "THE PROMPT BOX";
+ const flood = "z".repeat(16 * 1024);
+ act(() => {
+ harness.handlers?.onOutput(opening);
+ for (let i = 0; i < 40; i += 1) harness.handlers?.onOutput(flood);
+ });
+ act(() => harness.fire?.(true));
+
+ const replayed = harness.writes.join("");
+ expect(replayed.startsWith(opening)).toBe(true);
+ expect(replayed).toHaveLength(opening.length + 40 * flood.length);
+ });
+
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.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index c01da9cbad..1a1bb46f59 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -342,8 +342,18 @@ export function AgenticTerminal({
// 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);
+ if (paneVisible) {
+ term.write(text);
+ return;
+ }
+ offscreen.push(text);
+ // A pane that has parked all it may hold WRITES rather than forgets. An
+ // agent's TUI is drawn by relative cursor moves, so a stream that lost
+ // its front does not repair itself — the pane would come back showing
+ // the spinner row it rewrote last and blank rows where its prompt box
+ // belongs. Parsing into a surface nobody is painting is the cheap half
+ // of what parking avoids; a permanently broken screen is not.
+ if (offscreen.full) term.write(offscreen.drain());
};
const sendResize = () => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.test.ts b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.test.ts
index 65b8e39b7c..477a7be36e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.test.ts
@@ -22,36 +22,50 @@ describe("OffscreenBuffer", () => {
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.
+ it("keeps the OLDEST output when a hidden pane floods", () => {
+ // The front of the stream is what DREW the agent's interface; an Ink-based
+ // TUI never repaints it on its own. Dropping it is what left panes showing
+ // a spinner row over empty space (2026-07-27).
const buffer = new OffscreenBuffer(20);
- buffer.push("STALE");
+ buffer.push("FRAME");
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);
+ expect(held).toBe("FRAME0123456789abcdefghijNEWEST");
});
- it("never drops the newest chunk, however large", () => {
- const buffer = new OffscreenBuffer(10);
- const huge = "x".repeat(500);
- buffer.push("old");
- buffer.push(huge);
+ it("asks to be written out once it is holding its limit", () => {
+ const buffer = new OffscreenBuffer(20);
+ buffer.push("under the limit");
+ expect(buffer.full).toBe(false);
+
+ buffer.push("now well past it");
+ expect(buffer.full).toBe(true);
- expect(buffer.drain()).toBe(huge);
+ // Draining is what answers `full` — and it must clear the condition, or
+ // the pane would write on every single chunk from then on.
+ buffer.drain();
+ expect(buffer.full).toBe(false);
});
- it("stays bounded across a long flood", () => {
+ it("stays bounded when its user drains on full", () => {
+ // How the pane actually uses it: park, and write out whenever it is full.
+ // Memory stays capped WITHOUT anything being discarded.
const limit = 1024;
const buffer = new OffscreenBuffer(limit);
- for (let i = 0; i < 500; i += 1) buffer.push("y".repeat(64));
+ const written: string[] = [];
+ let high = 0;
+
+ for (let i = 0; i < 500; i += 1) {
+ buffer.push("y".repeat(64));
+ high = Math.max(high, buffer.pending);
+ if (buffer.full) written.push(buffer.drain());
+ }
+ written.push(buffer.drain());
- // One chunk of slack: the newest is always kept whole.
- expect(buffer.pending).toBeLessThanOrEqual(limit + 64);
+ expect(high).toBeLessThanOrEqual(limit + 64);
+ expect(written.join("").length).toBe(500 * 64);
});
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.ts b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.ts
index 5ee13cffc8..a0caf67e24 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/offscreenBuffer.ts
@@ -13,25 +13,37 @@
* 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.
+ * ## Why nothing is ever thrown away
+ *
+ * This buffer used to drop its oldest output once it grew past a limit, on the
+ * reasoning that a terminal UI repaints itself continuously and the newest
+ * bytes therefore ARE the screen. That reasoning is wrong, and it put empty
+ * rectangles in two panes of a live workspace (reported 2026-07-27): a coding
+ * agent built on Ink paints its interface ONCE and afterwards rewrites only the
+ * row that changed, addressed by RELATIVE cursor moves. A stream missing its
+ * front replays the spinner row the agent wrote last onto rows where the prompt
+ * box it drew twenty minutes ago is simply missing — and nothing later redraws
+ * it, so the pane stays broken until the agent is finished.
+ *
+ * So the limit still bounds MEMORY, but it is answered by writing rather than
+ * by discarding: {@link OffscreenBuffer.full} tells the pane to hand what it
+ * holds to xterm even though nobody is watching. That costs one parse on a
+ * surface the browser is not painting — which is the cheap half of the work
+ * this class exists to avoid, and far cheaper than a screen that never recovers.
*/
/**
- * 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.
+ * How much output one hidden pane parks before it stops holding and writes.
+ *
+ * Comfortably several full repaints of a full-screen agent UI, so an ordinary
+ * spell off screen is still one single write on return — 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) {}
@@ -40,11 +52,16 @@ export class OffscreenBuffer {
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;
- }
+ }
+
+ /**
+ * Has this pane parked as much as it may hold?
+ *
+ * True means "write what you are holding now" — not "discard it". See the
+ * module docstring for why the difference is the whole point.
+ */
+ get full(): boolean {
+ return this.size >= this.limit;
}
/** Everything kept, oldest first, ready for a single `term.write`. */
@@ -60,9 +77,4 @@ export class OffscreenBuffer {
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/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 2a146f760a..502aab0fa5 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -3347,7 +3347,7 @@
"selection": {
"start": "Terminals auswählen",
"finish": "Auswahl beenden",
- "hint": "Terminal-Fenster auswählen. Zuerst einschalten, dann die gewünschten Fenster anklicken.",
+ "hint": "Terminal-Fenster zum Auswählen anklicken. Ein Rechtsklick wählt ein Fenster sofort aus.",
"selected_count": "Ausgewählt: {0}",
"select_all": "Alle auswählen",
"clear_all": "Auswahl leeren",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 13380fa457..87771e13f4 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -3333,7 +3333,7 @@
"selection": {
"start": "Select terminals",
"finish": "Done selecting",
- "hint": "Select terminal panes. Turn this on first, then click the panes you want.",
+ "hint": "Select terminal panes. Right-click any pane to select it immediately.",
"selected_count": "Selected: {0}",
"select_all": "Select all",
"clear_all": "Clear selection",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index ad956ea9c2..dd311f62c5 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -3332,7 +3332,7 @@
"selection": {
"start": "Seleccionar terminales",
"finish": "Terminar selección",
- "hint": "Selecciona paneles de terminal. Actívalo primero y luego haz clic en los paneles que quieras.",
+ "hint": "Haz clic en los paneles para seleccionarlos. Haz clic derecho en cualquier panel para seleccionarlo inmediatamente.",
"selected_count": "Seleccionados: {0}",
"select_all": "Seleccionar todos",
"clear_all": "Borrar selección",
diff --git a/jarvis/ui/web/workspace_routes.py b/jarvis/ui/web/workspace_routes.py
index 0c9dfb0cfd..ea8bbe7ce0 100644
--- a/jarvis/ui/web/workspace_routes.py
+++ b/jarvis/ui/web/workspace_routes.py
@@ -63,11 +63,7 @@ class LaunchRequest(BaseModel):
@router.get("/agents", response_model=AgentsResponse)
async def get_agents() -> AgentsResponse:
- # Coding agents only. This grid plans terminals that EXTEND Jarvis, and its
- # split is validated against the same list — offering the plain-terminal
- # entry here would put a choice in front of the user that ``/launch`` then
- # rejects. A plain shell is offered where it belongs: the Agentic-IDE grid.
- infos = [i for i in await detect_agents() if i.name in AGENT_NAMES]
+ infos = await detect_agents()
return AgentsResponse(
cwd=str(repo_root()),
terminal_available=pty_available(),
diff --git a/jarvis/workspace/__init__.py b/jarvis/workspace/__init__.py
index 2759256693..04d782571e 100644
--- a/jarvis/workspace/__init__.py
+++ b/jarvis/workspace/__init__.py
@@ -21,41 +21,25 @@ from __future__ import annotations
from .agents import (
AGENT_NAMES,
- PLAIN_TERMINAL,
AgentInfo,
- WorkspaceAgent,
- agent_names,
build_agent_argv,
build_install_argv,
- coding_agent_names,
detect_agents,
get_agent,
list_agents,
- make_cli_agent,
- needs_trust,
- plain_terminal_argv,
pty_available,
- register_agent,
)
from .launcher import LAYOUT_CHOICES, LaunchPlan, Slot, plan_workspace, validate_split
__all__ = [
"AGENT_NAMES",
- "PLAIN_TERMINAL",
"AgentInfo",
- "WorkspaceAgent",
- "agent_names",
"build_agent_argv",
"build_install_argv",
- "coding_agent_names",
"detect_agents",
"get_agent",
"list_agents",
- "make_cli_agent",
- "needs_trust",
- "plain_terminal_argv",
"pty_available",
- "register_agent",
"LAYOUT_CHOICES",
"LaunchPlan",
"Slot",
diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.py
index efbe4ab950..506c2e4d89 100644
--- a/jarvis/workspace/agents.py
+++ b/jarvis/workspace/agents.py
@@ -1,30 +1,14 @@
-"""What a workspace terminal can RUN — a small, open registry.
-
-Two kinds of entry live here, and the difference is the whole design:
-
-* **A coding-agent CLI** (Claude Code, Codex, whatever is registered next) — a
- binary that has to be detected, may have to be installed, and is launched by
- name inside a shell.
-* **A plain terminal** — this machine's own shell and nothing else. Nothing to
- detect beyond "does this host have a shell", nothing to install, and no agent
- wrapped around it. It is what you want when the job is `git rebase -i`, not
- "ask an agent to do it".
-
-The registry is deliberately open (:func:`register_agent`): a new interactive
-CLI is a spec, not a code change spread across detection, launching and the UI.
-Everything downstream — the ``/agents`` endpoints, the pane split menu, the
-Agentic-IDE grid — reads this list rather than a hardcoded pair of names, so
-registering one entry is enough to make it offerable everywhere.
-
-CLI entries reuse ``CliSpec`` so the existing ``CliStatusProber`` can detect
-them, but they are deliberately NOT registered in the shared CLI catalog
+"""Local agent specs for the workspace launcher (Claude Code + Codex only).
+
+These reuse ``CliSpec`` so we can drive the existing ``CliStatusProber`` for
+detection, but they are deliberately NOT registered in the shared CLI catalog
(``jarvis/clis/catalog/seed_catalog.json``) — see ``__init__`` for why.
-Cross-platform: the shell entry resolves through
-:func:`jarvis.terminal.shells.default_shell`, which knows pwsh/PowerShell/cmd/
-Git Bash on Windows and ``$SHELL``/``/etc/shells`` elsewhere. On a host with no
-shell at all (a stripped container) the entry reports itself as not installed
-rather than handing the PTY an argv that cannot start.
+Each agent carries:
+- a detection spec (binary name + ``--version`` + a semver regex),
+- the install command shown/run when the binary is missing,
+- the bare launch command run inside the terminal (trust is pre-seeded
+ separately, so no flags are needed).
"""
from __future__ import annotations
@@ -33,7 +17,7 @@ from dataclasses import dataclass
from jarvis.clis.prober import CliStatusProber
from jarvis.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfig
-from jarvis.terminal.shells import default_shell
+from jarvis.terminal.shells import discover_shells
log = logging.getLogger(__name__)
@@ -41,133 +25,70 @@ log = logging.getLogger(__name__)
# "2.1.195 (Claude Code)" and "codex-cli 0.142.3".
_SEMVER_RE = r"(\d+\.\d+\.\d+)"
-# The registry key of the plain-shell entry. A name rather than a literal
-# everywhere, because several layers (the IDE session registry, the pane split
-# menu, the tests) have to agree on it.
-PLAIN_TERMINAL = "shell"
-
@dataclass(frozen=True, slots=True)
class WorkspaceAgent:
- """One thing a workspace terminal can run.
-
- ``kind`` decides how every question about it is answered:
-
- * ``"cli"`` — detect with ``spec``, install with ``spec.install``, launch
- ``launch_command`` inside a shell.
- * ``"shell"`` — no detection spec and no launch command; the terminal IS the
- host's shell, so "installed" means "this host has one".
-
- ``needs_trust`` says whether the folder has to be pre-marked as trusted for
- this entry before a pane opens (``jarvis.workspace.trust``). A shell has no
- trust dialog to skip, and neither does a CLI that never asks.
- """
+ """An agent the workspace launcher can detect, install, and launch."""
name: str
display_name: str
- kind: str = "cli"
- # Detection spec — CLI entries only.
- spec: CliSpec | None = None
- # The bare command run inside each terminal, for CLI entries. Trust is
- # pre-seeded by ``trust.py`` beforehand, so no permission/trust flags are
- # needed.
- launch_command: str | None = None
- needs_trust: bool = True
- # One line the UI can show under the name in a picker.
- description: str = ""
-
- @property
- def is_coding_agent(self) -> bool:
- """True for an entry that runs an agent rather than a bare shell."""
- return self.kind == "cli"
-
-
-def make_cli_agent(
- name: str,
- display_name: str,
- *,
- binary: str,
- npm_package: str = "",
- homepage: str = "",
- launch_command: str | None = None,
- description: str = "",
-) -> WorkspaceAgent:
- """Build a registrable entry for an interactive CLI.
-
- The convenience path for plugging in a new coding agent: give it a name, a
- binary and (optionally) the npm package that installs it, and detection,
- the install command and the launch argv all follow. A CLI installed some
- other way simply passes no package — it is then detected and launched, and
- reports "not installed" without offering an install command it does not
- have.
- """
- spec = CliSpec(
+ spec: CliSpec
+ # The bare command run inside each terminal. Trust is pre-seeded by
+ # ``trust.py`` beforehand, so no permission/trust flags are needed.
+ launch_command: str
+
+
+def _make_spec(
+ name: str, display_name: str, binary: str, npm_package: str, homepage: str
+) -> CliSpec:
+ return CliSpec(
name=name,
display_name=display_name,
- description=description or f"{display_name} coding-agent CLI.",
+ description=f"{display_name} coding-agent CLI.",
homepage=homepage,
binary_name=binary,
check_command=(binary, "--version"),
version_parse_regex=_SEMVER_RE,
- install=InstallMethods(npm_package=npm_package or None, recommended="npm"),
+ install=InstallMethods(npm_package=npm_package, recommended="npm"),
# We only care whether the binary is installed; the agent handles its
# own login interactively on first launch in the terminal.
auth=AuthConfig(type="none"),
risk=RiskConfig(default_tier="monitor"),
category="agent",
)
- return WorkspaceAgent(
- name=name,
- display_name=display_name,
- kind="cli",
- spec=spec,
- launch_command=launch_command or binary,
- description=description,
- )
_AGENTS: dict[str, WorkspaceAgent] = {
- "claude": make_cli_agent(
- "claude",
- "Claude Code",
- binary="claude",
- npm_package="@anthropic-ai/claude-code",
- homepage="https://claude.com/claude-code",
- ),
- "codex": make_cli_agent(
- "codex",
- "Codex",
- binary="codex",
- npm_package="@openai/codex",
- homepage="https://github.com/openai/codex",
+ "claude": WorkspaceAgent(
+ name="claude",
+ display_name="Claude Code",
+ spec=_make_spec(
+ "claude",
+ "Claude Code",
+ binary="claude",
+ npm_package="@anthropic-ai/claude-code",
+ homepage="https://claude.com/claude-code",
+ ),
+ launch_command="claude",
),
- PLAIN_TERMINAL: WorkspaceAgent(
- name=PLAIN_TERMINAL,
- display_name="Plain Terminal",
- kind="shell",
- needs_trust=False,
- description="This machine's own shell — no agent, just a prompt.",
+ "codex": WorkspaceAgent(
+ name="codex",
+ display_name="Codex",
+ spec=_make_spec(
+ "codex",
+ "Codex",
+ binary="codex",
+ npm_package="@openai/codex",
+ homepage="https://github.com/openai/codex",
+ ),
+ launch_command="codex",
),
}
-
-def register_agent(agent: WorkspaceAgent, *, replace: bool = False) -> WorkspaceAgent:
- """Add ``agent`` to the registry and return it.
-
- Refuses to overwrite an existing name unless ``replace`` is set: two
- different things answering to "codex" is the kind of collision that shows up
- as a pane running the wrong tool, which is worse than an early error.
- """
- if not agent.name:
- raise ValueError("A workspace agent needs a name.")
- if agent.name in _AGENTS and not replace:
- raise ValueError(f"A workspace agent called {agent.name!r} is already registered.")
- _AGENTS[agent.name] = agent
- return agent
+AGENT_NAMES: tuple[str, ...] = tuple(_AGENTS.keys())
def list_agents() -> list[WorkspaceAgent]:
- """Every registered entry, in registration order."""
return list(_AGENTS.values())
@@ -175,37 +96,10 @@ def get_agent(name: str) -> WorkspaceAgent | None:
return _AGENTS.get(name)
-def agent_names() -> tuple[str, ...]:
- """Every registered name, plain terminal included."""
- return tuple(_AGENTS)
-
-
-def coding_agent_names() -> tuple[str, ...]:
- """Only the entries that run a coding agent — no plain shell.
-
- The "Make It Yours" launcher plans a grid of agents that extend Jarvis, so
- it asks this rather than :func:`agent_names`.
- """
- return tuple(name for name, agent in _AGENTS.items() if agent.is_coding_agent)
-
-
-def needs_trust(name: str) -> bool:
- """Does opening this entry require pre-seeding folder trust?"""
- agent = _AGENTS.get(name)
- return bool(agent and agent.needs_trust)
-
-
-# Kept as a module constant for the many call sites that read it directly. It is
-# a snapshot of the CODING agents at import time, which is what every existing
-# reader means by "the agents" — a plain terminal is not one, and a dynamically
-# registered CLI is reachable through ``coding_agent_names()``.
-AGENT_NAMES: tuple[str, ...] = coding_agent_names()
-
-
def install_command(name: str) -> str | None:
"""The shell command that installs the agent (for display + terminal run)."""
agent = _AGENTS.get(name)
- if agent is None or agent.spec is None:
+ if agent is None:
return None
pkg = agent.spec.install.npm_package
return f"npm install -g {pkg}" if pkg else None
@@ -213,7 +107,7 @@ def install_command(name: str) -> str | None:
@dataclass(slots=True)
class AgentInfo:
- """Runtime status of one entry, returned by the /agents endpoints."""
+ """Runtime status of one agent, returned by the /agents endpoint."""
name: str
display_name: str
@@ -221,39 +115,14 @@ class AgentInfo:
version: str | None
install_command: str | None
launch_command: str
- kind: str = "cli"
- description: str = ""
async def detect_agents(prober: CliStatusProber | None = None) -> list[AgentInfo]:
- """Probe every registered entry and report what this machine can run.
-
- CLI entries go through the shared prober; the plain terminal answers from
- :func:`~jarvis.terminal.shells.default_shell`, because "is a shell
- installed" is not a question a ``--version`` probe can ask. Its reported
- version is the shell that would actually open ("PowerShell 7", "zsh"), which
- is the one thing a user picking it wants to know.
- """
+ """Probe both agents and return their install status."""
prober = prober or CliStatusProber()
- specs = [a.spec for a in _AGENTS.values() if a.spec is not None]
- statuses = await prober.probe_all(specs) if specs else {}
- shell = default_shell()
+ statuses = await prober.probe_all([a.spec for a in _AGENTS.values()])
out: list[AgentInfo] = []
for agent in _AGENTS.values():
- if agent.spec is None:
- out.append(
- AgentInfo(
- name=agent.name,
- display_name=agent.display_name,
- installed=shell is not None,
- version=shell.label if shell else None,
- install_command=None,
- launch_command="",
- kind=agent.kind,
- description=agent.description,
- )
- )
- continue
st = statuses.get(agent.name)
out.append(
AgentInfo(
@@ -262,9 +131,7 @@ async def detect_agents(prober: CliStatusProber | None = None) -> list[AgentInfo
installed=bool(st and st.installed),
version=st.version if st else None,
install_command=install_command(agent.name),
- launch_command=agent.launch_command or "",
- kind=agent.kind,
- description=agent.description,
+ launch_command=agent.launch_command,
)
)
return out
@@ -273,9 +140,10 @@ async def detect_agents(prober: CliStatusProber | None = None) -> list[AgentInfo
def _build_pty_argv(command: str) -> tuple[str, ...] | None:
"""Wrap a command in the platform's default shell so it runs inside a PTY
and the shell stays open afterwards (the user can re-run / keep typing)."""
- shell = default_shell() # pwsh>powershell>cmd / $SHELL first
- if shell is None:
+ shells = discover_shells()
+ if not shells:
return None
+ shell = shells[0] # preference order: pwsh>powershell>cmd / $SHELL first
path = shell.argv[0]
if shell.id in ("pwsh", "powershell"):
return (path, "-NoLogo", "-NoExit", "-Command", command)
@@ -285,29 +153,11 @@ def _build_pty_argv(command: str) -> tuple[str, ...] | None:
return (path, "-c", f"{command}; exec {path}")
-def plain_terminal_argv() -> tuple[str, ...] | None:
- """Full PTY argv for a plain shell session — no agent wrapped around it.
-
- The shell's OWN interactive argv, exactly as ``discover_shells()`` describes
- it, rather than the ``-Command``/``/k`` wrapper CLI entries need: there is no
- command to run first, and adding one would only cost the user a startup line
- they did not ask for.
- """
- shell = default_shell()
- return tuple(shell.argv) if shell is not None else None
-
-
def build_agent_argv(name: str) -> tuple[str, ...] | None:
- """Full PTY argv that opens this entry, or None when it cannot run here.
-
- A CLI is launched inside a shell (trust pre-seeded); the plain terminal IS
- the shell.
- """
+ """Full PTY argv that launches the agent in a shell (trust pre-seeded)."""
agent = _AGENTS.get(name)
if agent is None:
return None
- if agent.launch_command is None:
- return plain_terminal_argv()
return _build_pty_argv(agent.launch_command)
@@ -323,7 +173,7 @@ def pty_available() -> bool:
Works on a headless Linux VPS too — a PTY is a kernel feature, not a GUI —
which is why the in-app terminal grid fits the cloud-first doctrine better
than spawning OS terminal windows."""
- if default_shell() is None:
+ if not discover_shells():
return False
try:
from jarvis.terminal.backend import make_pty_backend
@@ -335,20 +185,13 @@ def pty_available() -> bool:
__all__ = [
"AGENT_NAMES",
- "PLAIN_TERMINAL",
- "AgentInfo",
"WorkspaceAgent",
- "agent_names",
- "build_agent_argv",
- "build_install_argv",
- "coding_agent_names",
- "detect_agents",
+ "AgentInfo",
+ "list_agents",
"get_agent",
"install_command",
- "list_agents",
- "make_cli_agent",
- "needs_trust",
- "plain_terminal_argv",
+ "detect_agents",
+ "build_agent_argv",
+ "build_install_argv",
"pty_available",
- "register_agent",
]
diff --git a/jarvis/workspace/trust.py b/jarvis/workspace/trust.py
index 7f045d226e..1da09d8200 100644
--- a/jarvis/workspace/trust.py
+++ b/jarvis/workspace/trust.py
@@ -55,24 +55,11 @@ def ensure_trusted(
results.append(_trust_claude(repo_root, claude_cfg))
elif name == "codex":
results.append(_trust_codex(repo_root, codex_home / "config.toml"))
- elif not _needs_trust(name):
- # A registered entry with no trust dialog to skip — a plain shell,
- # or a CLI that simply never asks. Nothing to write, and saying so
- # is not the same answer as "I do not know this agent".
- results.append(TrustResult(name, True, "noop", "nothing to pre-trust"))
else: # pragma: no cover - guarded upstream
results.append(TrustResult(name, False, "error", f"unknown agent: {name}"))
return results
-def _needs_trust(name: str) -> bool:
- """Does the registry know this entry, and does it want folder trust seeded?"""
- from .agents import get_agent
-
- agent = get_agent(name)
- return agent is None or agent.needs_trust
-
-
def _atomic_write_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.tmp-{os.getpid()}")
diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.py
index 72d5df8e43..fa480a5373 100644
--- a/tests/unit/agentic_ide/test_session.py
+++ b/tests/unit/agentic_ide/test_session.py
@@ -273,6 +273,59 @@ async def test_coming_back_rejoins_the_running_agent_and_replays_its_screen(
assert "building…" in "".join(seen), "the screen must come back with the pane"
+async def test_a_pane_whose_replay_lost_its_start_asks_the_agent_to_repaint(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """A truncated tail cannot rebuild a screen, so the agent is asked to.
+
+ An Ink-based TUI paints its interface once and afterwards rewrites only the
+ row that changed. Replaying a tail that lost its front therefore brings the
+ pane back showing one spinner row over empty space — which is exactly what
+ two live panes did (2026-07-27). A window-size change is the one event
+ every TUI answers with a full redraw, and unlike Ctrl+L it is not input.
+ """
+ session = await _open(registry, tmp_path, [{"agent": "claude"}])
+ term = session.terminals[0]
+ await registry.attach(term.name, 80, 24, _noop_output, _noop_exit)
+ pty = term.pty_id
+ # Overrun the replay budget without emitting a megabyte through the screen.
+ term.replay.limit = 64
+ await fake_pty.emit(pty, "the frame that drew the prompt box")
+ await fake_pty.emit(pty, "\x1b[Kspinner" * 10)
+ assert term.replay.truncated, "this test needs a tail that lost its front"
+ registry.detach(term.key, session.id)
+
+ fake_pty.resizes.clear()
+ await registry.attach(term.name, 100, 30, _noop_output, _noop_exit)
+
+ sizes = [(cols, rows) for tid, cols, rows in fake_pty.resizes if tid == pty]
+ assert (100, 29) in sizes, "the agent was never told its window changed"
+ assert sizes[-1] == (100, 30), "the pane must be left at the size it really is"
+
+
+async def test_an_intact_replay_leaves_the_agent_alone(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """No nudge when the tail is whole — it already rebuilds the screen.
+
+ The redraw is cheap but not free, and it is the common case that must stay
+ untouched: a pane that printed less than its replay budget comes back from
+ its own bytes.
+ """
+ session = await _open(registry, tmp_path, [{"agent": "claude"}])
+ term = session.terminals[0]
+ await registry.attach(term.name, 80, 24, _noop_output, _noop_exit)
+ pty = term.pty_id
+ await fake_pty.emit(pty, "\x1b[32mbuilding…\x1b[0m")
+ registry.detach(term.key, session.id)
+
+ fake_pty.resizes.clear()
+ await registry.attach(term.name, 100, 30, _noop_output, _noop_exit)
+
+ sizes = [(cols, rows) for tid, cols, rows in fake_pty.resizes if tid == pty]
+ assert sizes == [(100, 30)], "an intact replay must not cost a repaint"
+
+
async def test_closing_a_workspace_stops_only_its_own_agents(
registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
) -> None:
diff --git a/tests/unit/agentic_ide/test_transcript.py b/tests/unit/agentic_ide/test_transcript.py
index 0af73a367b..544d3fe9e5 100644
--- a/tests/unit/agentic_ide/test_transcript.py
+++ b/tests/unit/agentic_ide/test_transcript.py
@@ -6,7 +6,8 @@ is Alex doing?" gets answered from control codes and repainted frames.
"""
from __future__ import annotations
-from jarvis.agentic_ide.transcript import Transcript, is_noise, strip_ansi
+from jarvis.agentic_ide.screen import ScreenBuffer
+from jarvis.agentic_ide.transcript import ReplayBuffer, Transcript, is_noise, strip_ansi
def test_strip_ansi_removes_colour_and_cursor_sequences() -> None:
@@ -119,3 +120,95 @@ def test_is_noise_classifies_blank_and_decoration() -> None:
assert is_noise(" ")
assert is_noise("────────")
assert not is_noise("Running tests…")
+
+
+# --------------------------------------------------------------- replay buffer
+#
+# What a pane that comes back is handed. The property under test is not "the
+# bytes are kept" but "the pane can say whether they are ENOUGH" — a tail that
+# lost its front cannot rebuild a TUI drawn with relative cursor moves, and the
+# viewer has to know that to ask the agent for a fresh paint (2026-07-27).
+
+
+def test_replay_hands_back_the_stream_verbatim() -> None:
+ buffer = ReplayBuffer()
+ buffer.feed("\x1b[32mbuilding…\x1b[0m")
+ buffer.feed(" done\r\n")
+
+ assert buffer.text() == "\x1b[32mbuilding…\x1b[0m done\r\n"
+ assert buffer.truncated is False
+
+
+def test_replay_admits_when_it_dropped_the_start() -> None:
+ buffer = ReplayBuffer(limit=32)
+ buffer.feed("\x1b[Hthe frame that drew the prompt box")
+ assert buffer.truncated is False
+
+ buffer.feed("\x1b[Kspinner")
+ assert buffer.truncated is True, "a viewer must be able to tell it lost the start"
+
+
+def test_a_truncated_replay_starts_on_an_escape_boundary() -> None:
+ """PTY reads split anywhere — including mid-sequence.
+
+ Dropping whole chunks can still leave the CONTINUATION of a sequence at the
+ front, and a terminal handed ``[38;5;214m`` without its ``ESC`` prints it as
+ visible text in the middle of the agent's UI.
+ """
+ buffer = ReplayBuffer(limit=24)
+ buffer.feed("first chunk ending in \x1b")
+ buffer.feed("[38;5;214mstill orange, and then some more output")
+
+ replayed = buffer.text()
+ assert "[38;5;214m" not in strip_ansi(replayed), "a half sequence would be printed"
+ assert replayed.startswith("\x1b[0m"), "the starting attributes must be known"
+
+
+def test_clearing_a_replay_forgets_that_it_was_truncated() -> None:
+ # A fresh process draws a fresh screen: the new stream starts at its start.
+ buffer = ReplayBuffer(limit=8)
+ buffer.feed("aaaaaaaaaa")
+ buffer.feed("bbbbbbbbbb")
+ assert buffer.truncated is True
+
+ buffer.clear()
+ assert buffer.truncated is False
+ assert buffer.text() == ""
+
+
+def test_a_truncated_replay_alone_cannot_rebuild_the_screen() -> None:
+ """The reason the flag exists, spelled out as the failure it prevents.
+
+ An Ink-based TUI paints its interface once and afterwards rewrites only the
+ row that changed, addressed by relative cursor moves. Replaying a tail that
+ lost its front therefore reproduces the spinner row and NOTHING it was
+ drawn on top of — which is what put empty rectangles in two live panes.
+ """
+ opening = (
+ "Running 2 shell commands\r\n"
+ "\r\n"
+ "- Scurrying... (0m 01s)\r\n"
+ "\r\n"
+ "------------------------\r\n"
+ "> \r\n"
+ "------------------------\r\n"
+ " auto mode on\r\n"
+ )
+ # Every later frame: up six rows, erase that row, rewrite it, come back.
+ frames = [f"\x1b[6A\r\x1b[K- Scurrying... (0m {n:02d}s)\x1b[6B\r" for n in range(2, 60)]
+
+ buffer = ReplayBuffer(limit=len(opening) // 2)
+ buffer.feed(opening)
+ for frame in frames:
+ buffer.feed(frame)
+
+ screen = ScreenBuffer(40, 12)
+ screen.feed(buffer.text())
+ rows = [row.rstrip() for row in screen.display() if row.strip()]
+
+ assert any("Scurrying" in row for row in rows), "the last frame does arrive"
+ assert not any(">" in row for row in rows), (
+ "the prompt box is gone — which is why a truncated replay must be "
+ "followed by a repaint rather than trusted on its own"
+ )
+ assert buffer.truncated is True
diff --git a/tests/unit/workspace/test_agents.py b/tests/unit/workspace/test_agents.py
index 1f8cf09a47..5ea640584a 100644
--- a/tests/unit/workspace/test_agents.py
+++ b/tests/unit/workspace/test_agents.py
@@ -1,7 +1,4 @@
-"""The workspace registry: specs, detection, and what each entry launches.
-
-Detection runs against a fake prober — no real CLI is ever invoked.
-"""
+"""Agent specs + detection (with a fake prober — no real CLIs invoked)."""
from __future__ import annotations
import pytest
@@ -9,48 +6,22 @@ import pytest
from jarvis.clis.spec import CliSpec, CliStatus
from jarvis.workspace.agents import (
AGENT_NAMES,
- PLAIN_TERMINAL,
- WorkspaceAgent,
- agent_names,
build_agent_argv,
build_install_argv,
- coding_agent_names,
detect_agents,
get_agent,
install_command,
list_agents,
- make_cli_agent,
- needs_trust,
- plain_terminal_argv,
pty_available,
- register_agent,
)
-def test_coding_agents_are_claude_and_codex() -> None:
- assert set(coding_agent_names()) == {"claude", "codex"}
- # The historical constant keeps meaning "the coding agents": every existing
- # caller (the Make-It-Yours launcher, its PTY route) reads it that way.
+def test_only_claude_and_codex() -> None:
assert set(AGENT_NAMES) == {"claude", "codex"}
-def test_the_registry_also_holds_a_plain_terminal() -> None:
- assert PLAIN_TERMINAL in agent_names()
- shell = get_agent(PLAIN_TERMINAL)
- assert shell is not None
- assert shell.display_name == "Plain Terminal"
- # It is not an agent: nothing to detect, nothing to install, no trust
- # dialog to skip.
- assert shell.is_coding_agent is False
- assert shell.spec is None
- assert install_command(PLAIN_TERMINAL) is None
- assert needs_trust(PLAIN_TERMINAL) is False
-
-
-def test_cli_specs_are_valid_clispecs() -> None:
+def test_specs_are_valid_clispecs() -> None:
for agent in list_agents():
- if not agent.is_coding_agent:
- continue
assert isinstance(agent.spec, CliSpec)
assert agent.spec.binary_name in ("claude", "codex")
assert agent.spec.check_command[-1] == "--version"
@@ -76,25 +47,10 @@ def test_build_agent_argv_wraps_command_in_a_shell() -> None:
assert build_agent_argv("nope") is None
-def test_plain_terminal_launches_the_shell_itself() -> None:
- """No agent is wrapped around it — the shell IS the process."""
- argv = build_agent_argv(PLAIN_TERMINAL)
- assert argv == plain_terminal_argv()
- assert argv is not None
- # A discovered shell's own interactive argv, and NOT the "run this command
- # then stay open" wrapper a CLI entry gets.
- assert argv[0]
- assert "-Command" not in argv
- assert "/k" not in argv
- assert not any("claude" in part or "codex" in part for part in argv)
-
-
def test_build_install_argv_uses_install_command() -> None:
argv = build_install_argv("codex")
assert argv is not None
assert any("@openai/codex" in part for part in argv)
- # Nothing to install for a shell that is already there.
- assert build_install_argv(PLAIN_TERMINAL) is None
def test_pty_available_is_true_on_a_host_with_a_shell() -> None:
@@ -123,64 +79,3 @@ async def test_detect_reports_installed_and_version() -> None:
assert infos["claude"].version == "2.1.195"
assert infos["codex"].installed is False
assert infos["codex"].install_command == "npm install -g @openai/codex"
-
-
-async def test_detect_reports_the_plain_terminal_without_probing_it() -> None:
- """A shell cannot answer ``--version``, so it is never asked."""
- prober = FakeProber(
- {
- "claude": CliStatus(installed=False, version=None),
- "codex": CliStatus(installed=False, version=None),
- }
- )
- infos = {i.name: i for i in await detect_agents(prober)}
- shell = infos[PLAIN_TERMINAL]
- assert shell.kind == "shell"
- # Installed on any host with a shell — which every dev/CI machine is.
- assert shell.installed is True
- # Its "version" is the shell that would actually open.
- assert shell.version
- assert shell.install_command is None
-
-
-async def test_a_registered_cli_is_detected_and_launchable_like_the_built_ins() -> None:
- """Plugging in a new interactive CLI is one spec, not a code change."""
- entry = register_agent(
- make_cli_agent(
- "acme",
- "Acme Agent",
- binary="acme",
- npm_package="@acme/agent",
- homepage="https://example.invalid/acme",
- )
- )
- try:
- assert isinstance(entry, WorkspaceAgent)
- assert "acme" in agent_names()
- assert "acme" in coding_agent_names()
- assert install_command("acme") == "npm install -g @acme/agent"
- argv = build_agent_argv("acme")
- assert argv is not None and any("acme" in part for part in argv)
-
- prober = FakeProber(
- {
- "claude": CliStatus(installed=False, version=None),
- "codex": CliStatus(installed=False, version=None),
- "acme": CliStatus(installed=True, version="1.2.3"),
- }
- )
- infos = {i.name: i for i in await detect_agents(prober)}
- assert infos["acme"].installed is True
- assert infos["acme"].version == "1.2.3"
- finally:
- from jarvis.workspace import agents as registry
-
- registry._AGENTS.pop("acme", None)
-
-
-def test_registering_a_taken_name_is_refused() -> None:
- """Two things answering to one name is a pane running the wrong tool."""
- with pytest.raises(ValueError):
- register_agent(make_cli_agent("codex", "Impostor", binary="nope"))