Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): stop a pane's scrollbar claiming you are halfway up
Ruben Lütkecd5cd6a335f7
diff --git a/jarvis/terminal/shells.py b/jarvis/terminal/shells.pyindex 91e3290c72..88724701a1 100644--- a/jarvis/terminal/shells.py+++ b/jarvis/terminal/shells.py@@ -140,6 +140,19 @@ 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.tsxindex 20391de8b7..a5fba39000 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx@@ -21,10 +21,19 @@ 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@@ -44,6 +53,8 @@ vi.mock("./AgenticTerminal", () => ({maximized,splitDisabled,restartToken,+ recap,+ recapDetail,onRestart,agents,onToggleMaximize,@@ -54,6 +65,8 @@ vi.mock("./AgenticTerminal", () => ({maximized?: boolean;splitDisabled?: boolean;restartToken?: number;+ recap?: string;+ recapDetail?: string;onRestart?: () => void;agents?: Array<{ name: string }>;onToggleMaximize?: () => void;@@ -65,6 +78,8 @@ 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}>@@ -186,6 +201,24 @@ 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(() => {@@ -270,6 +303,50 @@ 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."),@@ -473,18 +550,32 @@ describe("selecting several terminals", () => {expect(screen.getByText("Selected: 0")).toBeTruthy();});- it("right-clicking a pane enters selection mode and marks it immediately", () => {+ it("never enters selection mode on a right-click", () => {renderGrid();- fireEvent.contextMenu(screen.getByTestId("pane-cell-Nova"));+ // 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"));+ expect(reached).toBe(true);expect(screen.getByTestId("terminal-selection-toggle").getAttribute("aria-pressed"),- ).toBe("true");+ ).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);expect(screen.getByTestId("select-terminal-Nova").getAttribute("aria-pressed"),- ).toBe("true");- expect(screen.getByText("Selected: 1")).toBeTruthy();+ ).toBe("false");+ expect(screen.getByText("Selected: 0")).toBeTruthy();});it("select all marks every terminal with one click", () => {@@ -556,7 +647,8 @@ describe("selecting several terminals", () => {it("keeps every selected terminal open when confirmation is cancelled", async () => {renderGrid();- fireEvent.contextMenu(screen.getByTestId("pane-cell-Mika"));+ fireEvent.click(screen.getByTestId("terminal-selection-toggle"));+ fireEvent.click(screen.getByTestId("select-terminal-Mika"));fireEvent.click(screen.getByTestId("close-selected-terminals"));fireEvent.click(screen.getByRole("button", { name: "Keep them open" }));@@ -681,7 +773,9 @@ describe("the prompt bar composes before it sends", () => {type("run the tests");await waitFor(() => expect(screen.getByTestId("prompt-preview")).toBeTruthy());- expect(api.composePrompt).toHaveBeenCalledWith("Mika", "run the tests");+ // 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.promptTerminal).not.toHaveBeenCalled();});@@ -693,7 +787,13 @@ 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."),+ 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: [] },+ ),);});@@ -705,7 +805,9 @@ 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"),+ expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests", {+ attachments: [],+ }),);});@@ -729,11 +831,159 @@ describe("the prompt bar composes before it sends", () => {type("run the tests");await waitFor(() =>- expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests"),+ expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests", {+ attachments: [],+ }),);});});+/*+ * 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.*@@ -850,3 +1100,61 @@ 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.tsxindex 1cf1a287db..cff7c3deec 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -16,8 +16,11 @@ import {Brain,Check,ChevronUp,+ FileText,FolderGit2,+ Image as ImageIcon,ListChecks,+ Loader2,Minus,Moon,Plus,@@ -48,14 +51,29 @@ 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 {@@ -70,11 +88,30 @@ 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.*@@ -139,6 +176,21 @@ 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,@@ -161,6 +213,8 @@ export function AgenticGrid({maxTerminals = 12,agents,onSessionChanged,+ accounts = [],+ onStateChanged,}: AgenticGridProps) {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -186,8 +240,15 @@ export function AgenticGrid({setFontSizeState(next);writeStored(FONT_KEY, String(next));}, []);- const [target, setTarget] = useState(session.terminals[0]?.name ?? "");+ const [target, setTarget] = useState(+ session.terminals.find(takesPrompts)?.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@@ -237,16 +298,44 @@ export function AgenticGrid({});}, []);- 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;- });- }, []);+ /*+ * 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]);// A terminal can disappear because another client closed it. Keep the local// selection honest instead of leaving an invisible name selected.@@ -363,7 +452,10 @@ 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));- if (added) setTarget(added.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);} catch (e) {pushToast("error", (e as Error).message);} finally {@@ -378,7 +470,7 @@ export function AgenticGrid({setPendingClose(null);if (maximized === name) setMaximized(null);onSessionChanged?.(next);- if (target === name) setTarget(next.terminals[0]?.name ?? "");+ if (target === name) setTarget(next.terminals.find(takesPrompts)?.name ?? "");} catch (e) {pushToast("error", (e as Error).message);} finally {@@ -396,7 +488,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[0]?.name ?? "");+ setTarget(result.session.terminals.find(takesPrompts)?.name ?? "");}if (result.failed.length === 0) setSelectionMode(false);else {@@ -419,14 +511,78 @@ 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) => {+ const deliver = async (text: string, carry: DropAttachment[] = []) => {setSending(true);try {- const result = await promptTerminal(target, text);+ const result = await promptTerminal(target, text, { attachments: carry });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) {@@ -458,16 +614,18 @@ export function AgenticGrid({if (!text || !target) return;setSending(true);try {- const composed = await composePrompt(target, text);+ const composed = await composePrompt(target, text, attachments);if (composed.composed && composed.composed !== text) {setPreviewSource(text);setPreview(composed);return;}- await deliver(text);+ // 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);} catch (e) {pushToast("warning", `Could not prepare the prompt: ${(e as Error).message}`);- await deliver(text);+ await deliver(text, attachments);} finally {setSending(false);}@@ -565,6 +723,14 @@ 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}+ />+<buttonref={selectionToggleRef}type="button"@@ -709,11 +875,6 @@ 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" }@@ -727,6 +888,13 @@ 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@@ -742,7 +910,9 @@ export function AgenticGrid({maximized={isMaximized}splitDisabled={atLimit || busy || working}agents={agents}- onFocus={() => setTarget(term.name)}+ onFocus={() => {+ if (takesPrompts(term)) setTarget(term.name);+ }}onStatus={(status, detail) => setStatus(term.name, status, detail)}onToggleMaximize={() =>setMaximized((current) => (current === term.name ? null : term.name))@@ -770,10 +940,14 @@ 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",@@ -882,13 +1056,38 @@ export function AgenticGrid({<divdata-testid="agentic-composer"style={{ height: composerHeight }}- className="flex shrink-0 flex-col overflow-hidden px-4 py-3"+ {...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",+ )}>+ {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>- {session.terminals.map((term) => {+ {/* 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) => {const state = statuses[term.name];return (<button@@ -909,6 +1108,13 @@ 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@@ -916,10 +1122,15 @@ 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)}+ onSendVerbatim={() => void deliver(previewSource, attachments)}onCancel={() => {- // Give the user their own words back rather than dropping them.+ // 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.setPrompt(previewSource);setPreview(null);setPreviewSource("");@@ -973,6 +1184,86 @@ 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/PaneScrollbar.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsxindex df22c4d191..f9aca64125 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx@@ -141,7 +141,26 @@ describe("PaneScrollbar", () => {const bar = screen.getByTestId("pane-scrollbar-Dana");expect(bar.dataset.mode).toBe("app");- expect(screen.getByTestId("pane-scrollbar-thumb-Dana")).toBeTruthy();++ // And it must not look like a position while it is at it. A short thumb+ // centred in the track was read as "you are halfway up" by a pane sitting+ // at the live end of Claude Code's transcript — so the grip spans the+ // track, and only its marking sits in the middle.+ const thumb = screen.getByTestId("pane-scrollbar-thumb-Dana");+ expect(thumb.style.top).toBe("0px");+ expect(thumb.style.height).toBe("300px");+ expect(screen.getByTestId("pane-scrollbar-grip-Dana")).toBeTruthy();+ });++ it("draws no grip marking where the thumb's position IS the answer", () => {+ render(<Harness term={fakeTerminal({ length: 1000 })} />);++ reachForTheBar();++ expect(screen.getByTestId("pane-scrollbar-Dana").dataset.mode).toBe(+ "scrollback",+ );+ expect(screen.queryByTestId("pane-scrollbar-grip-Dana")).toBeNull();});it("hands wheel turns over the bar to the CLI that owns the screen", () => {diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsxindex 67b5bfcc3f..c10c046c0e 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx@@ -12,9 +12,9 @@* 2. **It only worked for half the CLIs.** Why, and what this does about it,* is in ./paneScroll — in short: Claude Code runs on the alternate screen* with mouse tracking, so the terminal holds no scrollback to drag through- * and the wheel belongs to the CLI. That pane gets a grip which relays wheel- * notches to Claude Code instead of a thumb that would be lying about a- * position it cannot know.+ * and the wheel belongs to the CLI. That pane gets a full-track grip which+ * relays wheel notches to Claude Code, rather than a short thumb whose very+ * shape would claim a position nobody can know.** The bar is an overlay, not a layout box: xterm reserves a gutter on the right* for the scrollbar it thinks it has, and the bar sits in that gutter, so@@ -31,6 +31,7 @@ import type { Terminal } from "@xterm/xterm";import { cn } from "@/lib/utils";import type { TerminalAppearance } from "./terminalThemes";import {+ GRIP_MARKER_PX,IDLE_STATE,jogNotches,lineForThumbTop,@@ -281,8 +282,13 @@ export function PaneScrollbar({const rect = track.getBoundingClientRect();const geometry = thumbGeometry(current, rect.height);if (!geometry) return;- const down = event.clientY - rect.top > geometry.topPx;const pages = Math.max(1, current.rows - 1);+ // In `app` mode the grip covers the whole track, so this is all but+ // unreachable — and where it is, aiming at the track's own middle is the+ // only meaningful "up or down": the grip's position holds no answer.+ const pivot =+ current.mode === "app" ? rect.height / 2 : geometry.topPx;+ const down = event.clientY - rect.top > pivot;if (current.mode === "app") relay(down ? pages : -pages);else term.scrollLines?.(down ? pages : -pages);},@@ -351,9 +357,29 @@ export function PaneScrollbar({style={{top: geometry.topPx,height: geometry.heightPx,- background: `rgb(var(--jarvis-yellow) / ${strength})`,+ // A full-track bar is the shape for "no position to report", so it+ // is drawn faintly — the bright part is the marking on it, which+ // is a handle rather than a claim. See ./paneScroll.+ background: `rgb(var(--jarvis-yellow) / ${+ geometry.markerPx === undefined ? strength : dragging ? 0.24 : 0.14+ })`,}}- />+ >+ {geometry.markerPx !== undefined && (+ <div+ data-testid={`pane-scrollbar-grip-${name}`}+ className={cn(+ "pointer-events-none absolute left-0 w-full rounded-full",+ dragging ? undefined : "transition-[top] duration-150",+ )}+ style={{+ top: geometry.markerPx,+ height: Math.min(GRIP_MARKER_PX, geometry.heightPx),+ background: `rgb(var(--jarvis-yellow) / ${strength})`,+ }}+ />+ )}+ </div>)}</div>);diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.tsindex f9ed4c4084..3d5d807c0d 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import type { Terminal } from "@xterm/xterm";import {- GRIP_PX,+ GRIP_MARKER_PX,GRIP_TRAVEL_PX,JOG_STEP_PX,MIN_THUMB_PX,@@ -85,7 +85,11 @@ describe("readScrollState", () => {expect(state.mode).toBe("app");// No leftover position from the frozen viewport: the grip encodes none.expect(state.top).toBe(0);- expect(thumbGeometry(state, 400)).toEqual({ topPx: 178, heightPx: GRIP_PX });+ expect(thumbGeometry(state, 400)).toEqual({+ topPx: 0,+ heightPx: 400,+ markerPx: 189,+ });});it("stays away from a full-screen app that did not take the mouse", () => {@@ -125,24 +129,52 @@ describe("thumbGeometry", () => {expect(geometry!.topPx + geometry!.heightPx).toBe(400);});- it("centres a fixed grip in app mode — it encodes no position", () => {+ /*+ * The bug this shape exists to prevent: a fixed 44px grip centred in the+ * track was read — by the only grammar scrollbars have — as "you are halfway+ * up", while the pane sat at the live end of Claude Code's transcript. A bar+ * that spans the track cannot be read that way in either direction.+ */+ it("spans the whole track in app mode — no length of it means a position", () => {const state = readScrollState(fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),);- expect(thumbGeometry(state, 300)).toEqual({ topPx: 128, heightPx: GRIP_PX });+ expect(thumbGeometry(state, 300)).toEqual({+ topPx: 0,+ heightPx: 300,+ markerPx: 139,+ });+ });++ it("lets the app-mode marking follow a drag, within its travel", () => {+ const state = readScrollState(+ fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),+ );++ const dragged = thumbGeometry(state, 300, 40);+ // The bar itself never moves — only its marking, as drag feedback.+ expect(dragged?.topPx).toBe(0);+ expect(dragged?.heightPx).toBe(300);+ expect(dragged?.markerPx).toBe(179);+ // A long drag keeps relaying wheel notches, but the marking stops moving:+ // running it to the track's end would restore the very "you are here" read+ // the full-track bar is here to refuse.+ expect(thumbGeometry(state, 300, 9000)?.markerPx).toBe(+ 139 + GRIP_TRAVEL_PX,+ );});- it("lets the app-mode grip follow a drag, within its travel", () => {+ it("keeps the app-mode marking inside a track shorter than itself", () => {const state = readScrollState(fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),);- expect(thumbGeometry(state, 300, 40)?.topPx).toBe(168);- // A long drag keeps relaying wheel notches, but the grip stops moving —- // it would otherwise sit at the bottom of the track claiming to be at the- // end of a history whose length nobody knows.- expect(thumbGeometry(state, 300, 9000)?.topPx).toBe(128 + GRIP_TRAVEL_PX);+ expect(thumbGeometry(state, GRIP_MARKER_PX - 8)).toEqual({+ topPx: 0,+ heightPx: GRIP_MARKER_PX - 8,+ markerPx: 0,+ });});it("draws nothing when there is nothing to scroll", () => {diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.tsindex fdafb3dbc6..2c3b1aa57b 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts@@ -46,11 +46,27 @@* shell). The thumb is proportional and exact, and dragging it moves the* viewport.* * `app` — the application took the mouse, so it holds the history (Claude- * Code). There is no honest position to draw, so the bar becomes a centred- * grip: dragging it relays wheel notches to the CLI, which scrolls itself. It- * springs back rather than pretending to know where it is.+ * Code). There is no honest position to draw, so the bar becomes a full-track+ * grip: dragging it relays wheel notches to the CLI, which scrolls itself.* * `none` — nothing to scroll (a fresh pane, or a full-screen app that does* not take the mouse). The bar stays away instead of drawing a dead track.+ *+ * ## A short bar in the middle of a track IS a position claim+ *+ * `app` mode first drew a fixed 44px grip centred in the track, on the reasoning+ * that a grip which never moves cannot be lying. It was — just in a language the+ * code was not reading. Every scrollbar anyone has ever used says "you are here"+ * with exactly that shape, so a pane parked at the live end of Claude Code's+ * transcript showed a thumb halfway up its track and was read, correctly by the+ * only grammar available, as "you are halfway up". Abstaining from a claim is+ * not the same as saying nothing when the shape you abstain with is the shape+ * the claim is made in.+ *+ * So the grip now fills the track end to end — the universal "there is no+ * position here" — carrying a small marking that shows it can be grabbed and+ * follows a drag for feedback. The bar occupies the whole track in either+ * direction, which is the one arrangement no scrollbar has ever used to mean+ * "somewhere in the middle".*/import type { Terminal } from "@xterm/xterm";@@ -70,6 +86,14 @@ export interface PaneScrollState {export interface ThumbGeometry {topPx: number;heightPx: number;+ /**+ * `app` mode only: where the grip's marking sits inside the bar. The bar+ * itself spans the whole track and says nothing about position, so this is+ * drag feedback and a "you can grab this" hint, never a location in a+ * history. Absent in `scrollback` mode, where the bar's own position is the+ * information.+ */+ markerPx?: number;}export const IDLE_STATE: PaneScrollState = {@@ -82,10 +106,10 @@ export const IDLE_STATE: PaneScrollState = {/** A thumb shorter than this is impossible to grab in a tall pane. */export const MIN_THUMB_PX = 26;-/** Height of the `app`-mode grip. Fixed: it encodes no position. */-export const GRIP_PX = 44;+/** Height of the marking on the `app`-mode grip. Encodes no position. */+export const GRIP_MARKER_PX = 22;-/** How far the `app`-mode grip may travel from centre while dragged. */+/** How far the `app`-mode marking may travel from centre while dragged. */export const GRIP_TRAVEL_PX = 60;/** Drag distance that relays one wheel notch in `app` mode. */@@ -133,8 +157,9 @@ export function appTakesWheel(term: Terminal | null): boolean {/*** Where to draw the thumb inside a track of `trackPx`, or null for no bar.*- * In `app` mode `offsetPx` is the live drag offset, so the grip follows the- * pointer while it is held and returns to the middle when it is let go.+ * In `app` mode `offsetPx` is the live drag offset: the bar stays put — it+ * spans the whole track — and its marking follows the pointer while it is held,+ * returning to the middle when it is let go.*/export function thumbGeometry(state: PaneScrollState,@@ -144,12 +169,13 @@ export function thumbGeometry(if (trackPx <= 0) return null;if (state.mode === "app") {- const heightPx = Math.min(GRIP_PX, trackPx);- const centre = (trackPx - heightPx) / 2;+ const markerHeight = Math.min(GRIP_MARKER_PX, trackPx);+ const centre = (trackPx - markerHeight) / 2;const travel = clamp(offsetPx, -GRIP_TRAVEL_PX, GRIP_TRAVEL_PX);return {- heightPx,- topPx: Math.round(clamp(centre + travel, 0, trackPx - heightPx)),+ topPx: 0,+ heightPx: trackPx,+ markerPx: Math.round(clamp(centre + travel, 0, trackPx - markerHeight)),};}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 502aab0fa5..2a146f760a 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 zum Auswählen anklicken. Ein Rechtsklick wählt ein Fenster sofort aus.",+ "hint": "Terminal-Fenster auswählen. Zuerst einschalten, dann die gewünschten Fenster anklicken.","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.jsonindex 87771e13f4..13380fa457 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. Right-click any pane to select it immediately.",+ "hint": "Select terminal panes. Turn this on first, then click the panes you want.","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.jsonindex dd311f62c5..ad956ea9c2 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": "Haz clic en los paneles para seleccionarlos. Haz clic derecho en cualquier panel para seleccionarlo inmediatamente.",+ "hint": "Selecciona paneles de terminal. Actívalo primero y luego haz clic en los paneles que quieras.","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.pyindex ea8bbe7ce0..0c9dfb0cfd 100644--- a/jarvis/ui/web/workspace_routes.py+++ b/jarvis/ui/web/workspace_routes.py@@ -63,7 +63,11 @@ class LaunchRequest(BaseModel):@router.get("/agents", response_model=AgentsResponse)async def get_agents() -> AgentsResponse:- infos = await detect_agents()+ # 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]return AgentsResponse(cwd=str(repo_root()),terminal_available=pty_available(),diff --git a/jarvis/workspace/__init__.py b/jarvis/workspace/__init__.pyindex 04d782571e..2759256693 100644--- a/jarvis/workspace/__init__.py+++ b/jarvis/workspace/__init__.py@@ -21,25 +21,41 @@ from __future__ import annotationsfrom .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.pyindex 506c2e4d89..efbe4ab950 100644--- a/jarvis/workspace/agents.py+++ b/jarvis/workspace/agents.py@@ -1,14 +1,30 @@-"""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+"""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(``jarvis/clis/catalog/seed_catalog.json``) — see ``__init__`` for why.-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).+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."""from __future__ import annotations@@ -17,7 +33,7 @@ from dataclasses import dataclassfrom jarvis.clis.prober import CliStatusProberfrom jarvis.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfig-from jarvis.terminal.shells import discover_shells+from jarvis.terminal.shells import default_shelllog = logging.getLogger(__name__)@@ -25,70 +41,133 @@ 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:- """An agent the workspace launcher can detect, install, and launch."""+ """One thing a workspace terminal can run.- name: str- display_name: str- 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+ ``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".-def _make_spec(- name: str, display_name: str, binary: str, npm_package: str, homepage: str-) -> CliSpec:- return CliSpec(+ ``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.+ """++ 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(name=name,display_name=display_name,- description=f"{display_name} coding-agent CLI.",+ description=description or 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, recommended="npm"),+ install=InstallMethods(npm_package=npm_package or None, 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": 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",+ "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",),- "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",+ 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.",),}-AGENT_NAMES: tuple[str, ...] = tuple(_AGENTS.keys())++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 agentdef list_agents() -> list[WorkspaceAgent]:+ """Every registered entry, in registration order."""return list(_AGENTS.values())@@ -96,10 +175,37 @@ 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:+ if agent is None or agent.spec is None:return Nonepkg = agent.spec.install.npm_packagereturn f"npm install -g {pkg}" if pkg else None@@ -107,7 +213,7 @@ def install_command(name: str) -> str | None:@dataclass(slots=True)class AgentInfo:- """Runtime status of one agent, returned by the /agents endpoint."""+ """Runtime status of one entry, returned by the /agents endpoints."""name: strdisplay_name: str@@ -115,14 +221,39 @@ class AgentInfo:version: str | Noneinstall_command: str | Nonelaunch_command: str+ kind: str = "cli"+ description: str = ""async def detect_agents(prober: CliStatusProber | None = None) -> list[AgentInfo]:- """Probe both agents and return their install status."""+ """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.+ """prober = prober or CliStatusProber()- statuses = await prober.probe_all([a.spec for a in _AGENTS.values()])+ 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()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,+ )+ )+ continuest = statuses.get(agent.name)out.append(AgentInfo(@@ -131,7 +262,9 @@ async def detect_agents(prober: CliStatusProber | None = None) -> list[AgentInfoinstalled=bool(st and st.installed),version=st.version if st else None,install_command=install_command(agent.name),- launch_command=agent.launch_command,+ launch_command=agent.launch_command or "",+ kind=agent.kind,+ description=agent.description,))return out@@ -140,10 +273,9 @@ async def detect_agents(prober: CliStatusProber | None = None) -> list[AgentInfodef _build_pty_argv(command: str) -> tuple[str, ...] | None:"""Wrap a command in the platform's default shell so it runs inside a PTYand the shell stays open afterwards (the user can re-run / keep typing)."""- shells = discover_shells()- if not shells:+ shell = default_shell() # pwsh>powershell>cmd / $SHELL first+ if shell is None:return None- shell = shells[0] # preference order: pwsh>powershell>cmd / $SHELL firstpath = shell.argv[0]if shell.id in ("pwsh", "powershell"):return (path, "-NoLogo", "-NoExit", "-Command", command)@@ -153,11 +285,29 @@ 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 launches the agent in a shell (trust pre-seeded)."""+ """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.+ """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)@@ -173,7 +323,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 betterthan spawning OS terminal windows."""- if not discover_shells():+ if default_shell() is None:return Falsetry:from jarvis.terminal.backend import make_pty_backend@@ -185,13 +335,20 @@ def pty_available() -> bool:__all__ = ["AGENT_NAMES",- "WorkspaceAgent",+ "PLAIN_TERMINAL","AgentInfo",- "list_agents",- "get_agent",- "install_command",- "detect_agents",+ "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",]diff --git a/jarvis/workspace/trust.py b/jarvis/workspace/trust.pyindex 1da09d8200..7f045d226e 100644--- a/jarvis/workspace/trust.py+++ b/jarvis/workspace/trust.py@@ -55,11 +55,24 @@ 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 upstreamresults.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/workspace/test_agents.py b/tests/unit/workspace/test_agents.pyindex 5ea640584a..1f8cf09a47 100644--- a/tests/unit/workspace/test_agents.py+++ b/tests/unit/workspace/test_agents.py@@ -1,4 +1,7 @@-"""Agent specs + detection (with a fake prober — no real CLIs invoked)."""+"""The workspace registry: specs, detection, and what each entry launches.++Detection runs against a fake prober — no real CLI is ever invoked.+"""from __future__ import annotationsimport pytest@@ -6,22 +9,48 @@ import pytestfrom jarvis.clis.spec import CliSpec, CliStatusfrom 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_only_claude_and_codex() -> None:+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.assert set(AGENT_NAMES) == {"claude", "codex"}-def test_specs_are_valid_clispecs() -> None:+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:for agent in list_agents():+ if not agent.is_coding_agent:+ continueassert isinstance(agent.spec, CliSpec)assert agent.spec.binary_name in ("claude", "codex")assert agent.spec.check_command[-1] == "--version"@@ -47,10 +76,25 @@ 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 Noneassert 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 Nonedef test_pty_available_is_true_on_a_host_with_a_shell() -> None:@@ -79,3 +123,64 @@ async def test_detect_reports_installed_and_version() -> None:assert infos["claude"].version == "2.1.195"assert infos["codex"].installed is Falseassert 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"))