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.

@ feat(agentic-ide): prove a delivered prompt on screen, not in the transcript

Ruben Lütke6e1aae13f9fb
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index cf84ae9b1b..6290128e17 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -88,7 +88,22 @@ import {
} from "./offscreenBuffer";
import { installQuerySuppression } from "./terminalQueries";
import { PaneScrollbar } from "./PaneScrollbar";
-import { openPaneSocket, type PaneSocket } from "./paneSocket";
+import {
+ openPaneSocket,
+ type PaneSocket,
+ type PromptDelivery,
+} from "./paneSocket";
+import { PromptReceipt } from "./PromptReceipt";
+
+/**
+ * How old a delivery may be and still raise its receipt on a fresh connection.
+ *
+ * Only applies to the receipt recovered from the HANDSHAKE — a prompt arriving
+ * live always shows one. Half an hour comfortably covers "I looked away and
+ * came back" while keeping a reopened workspace from re-announcing deliveries
+ * the user long since watched play out.
+ */
+const RECEIPT_MAX_AGE_MS = 30 * 60 * 1000;
export type PaneStatus = "connecting" | "live" | "exited" | "error";
@@ -308,6 +323,21 @@ export function AgenticTerminal({
* Reconnects therefore stay quiet: the replayed screen is already there.
*/
const [painted, setPainted] = useState(false);
+ /**
+ * The delivery this pane is currently showing a receipt for, if any.
+ *
+ * Held here rather than derived from the terminal's contents because the
+ * terminal is precisely what cannot be trusted to show it — see
+ * ./PromptReceipt for the four ways a delivered prompt fails to reach the
+ * screen. Fed from two independent sources so that neither being unavailable
+ * loses the proof: the socket's `prompt` frame (instant, lossy) and the
+ * pane's `last_prompt_at` in the workspace state (durable, one poll late).
+ */
+ const [receipt, setReceipt] = useState<PromptDelivery | null>(null);
+ /** The delivery the user has already waved away; never shown again. */
+ const [dismissedAt, setDismissedAt] = useState<number | null>(null);
+ /** Briefly true right after a delivery — draws the eye to the right pane. */
+ const [justDelivered, setJustDelivered] = useState(false);
// Latest callbacks/appearance without re-running the connect effect.
const onStatusRef = useRef(onStatus);
const onAttachErrorRef = useRef(onAttachError);
@@ -634,8 +664,57 @@ export function AgenticTerminal({
requestAnimationFrame(sendResize);
},
onOutput: (text) => writeToPane(text),
- onReady: ({ resumed, reattached }) => {
+ /**
+ * A prompt just landed in this pane — make that impossible to miss.
+ *
+ * Three things, and the order matters. The pane is un-parked FIRST:
+ * whatever the observer believes, output held back now is output the
+ * user will not see while they are looking straight at the receipt
+ * telling them it arrived. Then it is scrolled into the viewport,
+ * because a receipt drawn on a pane two screens down is no better than
+ * no receipt. Only then does it flash, which is the part that is merely
+ * nice.
+ *
+ * None of this depends on the agent echoing anything, which is the
+ * whole point: this path is what remains true when the terminal is a
+ * black rectangle.
+ */
+ onPrompt: (delivery) => {
+ if (disposed) return;
+ showPane();
+ setReceipt(delivery);
+ setJustDelivered(true);
+ window.setTimeout(() => setJustDelivered(false), 2_000);
+ try {
+ container.scrollIntoView({ block: "nearest", behavior: "smooth" });
+ } catch {
+ // Older engines take no options object; position is a nicety and
+ // the receipt is legible wherever the pane happens to sit.
+ container.scrollIntoView();
+ }
+ },
+ onReady: ({ resumed, reattached, lastPrompt }) => {
troubleShown = null;
+ // What this pane was told BEFORE this socket existed. A reload, a
+ // reconnect or a second window opened afterwards would otherwise
+ // show no receipt at all for a prompt that really was delivered —
+ // and that viewer is exactly the one with reason to doubt it.
+ //
+ // Bounded by age, because "durable" and "permanent" are different
+ // requirements. The receipt answers a question that is asked in the
+ // minutes after a delivery ("did that actually go?"); re-raising
+ // yesterday's every time a workspace is reopened would train the
+ // user to close it unread, which is how the next real one gets
+ // missed. Older deliveries stay readable on demand — the pane's
+ // state keeps them, and `GET /terminals/{name}/prompt` returns the
+ // text in full.
+ if (
+ lastPrompt?.at !== null &&
+ lastPrompt !== null &&
+ Date.now() - lastPrompt.at * 1000 < RECEIPT_MAX_AGE_MS
+ ) {
+ setReceipt(lastPrompt);
+ }
// Say which of THREE things happened. They look identical on screen and
// only differ when it matters: an agent that never stopped still holds
// everything, a resumed one re-read its history, and a fresh one will
@@ -967,6 +1046,12 @@ export function AgenticTerminal({
? "border-primary/60 shadow-[0_0_0_1px_hsl(var(--primary)/0.35),0_8px_24px_-12px_rgba(0,0,0,0.5)]"
: "shadow-[0_4px_16px_-10px_rgba(0,0,0,0.4)]",
dragging && "border-primary shadow-[0_0_0_2px_hsl(var(--primary)/0.5)]",
+ // A prompt just landed here. Two seconds of ring, for the one job the
+ // receipt below cannot do: telling the user WHICH pane out of eight to
+ // look at. Colour and shadow only — nothing moves, because a pane that
+ // jumps while an agent is drawing into it is worse than a quiet one.
+ justDelivered &&
+ "border-primary shadow-[0_0_0_2px_hsl(var(--primary)/0.6),0_0_28px_-4px_hsl(var(--primary)/0.55)]",
// Lifted out of the grid while it is being carried: the pane stays where
// it is (moving it under the cursor would tear down nothing but would
// reflow every other pane on every mouse move) and says so by fading.
@@ -1040,6 +1125,29 @@ export function AgenticTerminal({
every click and keystroke, so typing into a pane that is still
booting behaves exactly as it did before.
*/}
+ {/*
+ Proof that this pane was handed a prompt, drawn by the app rather
+ than read out of the agent's screen.
+
+ Sits INSIDE the terminal region so it points at the pane it is
+ talking about, and above the scrollbar overlay so a fleet of panes
+ cannot bury it. It is the answer to the failure this whole file keeps
+ circling: a delivery that really happened, on a pane that showed
+ nothing, told to a user who then had every reason to believe Jarvis
+ had invented it. See ./PromptReceipt.
+ */}
+ {receipt && receipt.at !== null && receipt.at !== dismissedAt && (
+ <PromptReceipt
+ key={receipt.at}
+ terminal={name}
+ workspaceId={workspaceId}
+ at={receipt.at}
+ preview={receipt.text}
+ chars={receipt.chars}
+ submitted={receipt.submitted}
+ onDismiss={() => setDismissedAt(receipt.at)}
+ />
+ )}
{!painted && visibleStatus === "connecting" && (
<div
data-testid={`agentic-pane-starting-${name}`}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PromptReceipt.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PromptReceipt.test.tsx
new file mode 100644
index 0000000000..ac03868212
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/PromptReceipt.test.tsx
@@ -0,0 +1,184 @@
+import { act, render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { PromptReceipt, agoLabel, RECEIPT_PROMINENT_MS } from "./PromptReceipt";
+
+/*
+ * The receipt exists because a delivered prompt is routinely invisible: the
+ * pane had parked its output, or its emulator had not painted, or its socket
+ * was reconnecting, or the CLI redrew its input box out of view. In every one
+ * of those the agent really was briefed and the user had no way to know it.
+ *
+ * So these tests pin the properties that make it PROOF rather than another
+ * claim: it shows real text from the prompt (not just the word "sent"), it can
+ * produce the whole brief on demand, it does not overstate a prompt that never
+ * started, and it does not disappear on its own.
+ */
+
+vi.mock("@/lib/agenticIdeApi", () => ({
+ fetchLastPrompt: vi.fn(),
+}));
+
+const { fetchLastPrompt } = await import("@/lib/agenticIdeApi");
+const fetchMock = fetchLastPrompt as unknown as ReturnType<typeof vi.fn>;
+
+const DELIVERED_AT = 1_700_000_000;
+
+const base = {
+ terminal: "Mika",
+ workspaceId: "ide_abc",
+ at: DELIVERED_AT,
+ preview: "## Task\nReview the ranking pipeline and report what you find.",
+ chars: 2_400,
+ submitted: true as boolean | null,
+ onDismiss: () => {},
+};
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ vi.setSystemTime(DELIVERED_AT * 1000 + 2_000);
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue({
+ name: "Mika",
+ text: "## Task\nReview the ranking pipeline and report what you find.\n\n## Key files\n- `@jarvis/rank.py`",
+ chars: 2_400,
+ at: DELIVERED_AT,
+ submitted: true,
+ prompts_sent: 1,
+ });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("PromptReceipt", () => {
+ it("shows actual text from the prompt, not merely that something was sent", () => {
+ // The whole complaint this answers is "it said it sent something and I
+ // could not see it". A receipt that only says "sent" repeats that.
+ render(<PromptReceipt {...base} />);
+
+ expect(screen.getByTestId("prompt-receipt").textContent).toContain(
+ "Review the ranking pipeline",
+ );
+ });
+
+ it("says when it happened, in clock time as well as relative", () => {
+ render(<PromptReceipt {...base} />);
+
+ const text = screen.getByTestId("prompt-receipt").textContent ?? "";
+ expect(text).toContain("just now");
+ // A clock reading is what can be checked against "I asked it right after
+ // the call" — a relative label alone cannot be.
+ expect(text).toMatch(/\d{1,2}:\d{2}/);
+ });
+
+ it("reads back the complete brief when it is opened", async () => {
+ render(<PromptReceipt {...base} />);
+
+ fireEvent.click(screen.getByTestId("prompt-receipt-toggle"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("prompt-receipt-body").textContent).toContain(
+ "jarvis/rank.py",
+ );
+ });
+ expect(fetchMock).toHaveBeenCalledWith("Mika", "ide_abc");
+ });
+
+ it("keeps showing the excerpt when the full prompt cannot be fetched", async () => {
+ // Degrades to "you can see the opening" rather than to an empty box: the
+ // delivery still happened and the excerpt is still evidence of it.
+ fetchMock.mockRejectedValue(new Error("backend restarting"));
+ render(<PromptReceipt {...base} />);
+
+ fireEvent.click(screen.getByTestId("prompt-receipt-toggle"));
+
+ await waitFor(() => {
+ const body = screen.getByTestId("prompt-receipt-body").textContent ?? "";
+ expect(body).toContain("Review the ranking pipeline");
+ expect(body).toContain("backend restarting");
+ });
+ });
+
+ it("does not claim a prompt started when it is still in the input box", () => {
+ // The case that most needs saying: this pane looks exactly like a working
+ // one, and only the user can push it over the line.
+ render(<PromptReceipt {...base} submitted={false} />);
+
+ const text = screen.getByTestId("prompt-receipt").textContent ?? "";
+ expect(text).toContain("not started");
+ expect(text).toContain("press Enter");
+ });
+
+ it("stays honest about an unconfirmed start rather than rounding up", () => {
+ render(<PromptReceipt {...base} submitted={null} />);
+
+ expect(screen.getByTestId("prompt-receipt").textContent).toContain(
+ "could not be confirmed",
+ );
+ });
+
+ it("stays on screen after its prominent spell instead of vanishing", () => {
+ // A toast that fades only reassures the user who was already watching —
+ // the one who never doubted it. Doubt arrives minutes later.
+ render(<PromptReceipt {...base} />);
+ expect(screen.getByTestId("prompt-receipt").dataset.prominent).toBe("true");
+
+ act(() => {
+ vi.advanceTimersByTime(RECEIPT_PROMINENT_MS + 500);
+ });
+
+ const receipt = screen.getByTestId("prompt-receipt");
+ expect(receipt).toBeTruthy();
+ expect(receipt.dataset.prominent).toBe("false");
+ expect(receipt.textContent).toContain("Review the ranking pipeline");
+ });
+
+ it("goes away only when the user says so", () => {
+ const onDismiss = vi.fn();
+ render(<PromptReceipt {...base} onDismiss={onDismiss} />);
+
+ fireEvent.click(screen.getByTestId("prompt-receipt-dismiss"));
+
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it("is announced to a screen reader, not only drawn", () => {
+ render(<PromptReceipt {...base} />);
+
+ const receipt = screen.getByTestId("prompt-receipt");
+ expect(receipt.getAttribute("role")).toBe("status");
+ expect(receipt.getAttribute("aria-live")).toBe("polite");
+ });
+
+ it("names the full length so an excerpt is never read as the whole brief", async () => {
+ render(<PromptReceipt {...base} />);
+
+ fireEvent.click(screen.getByTestId("prompt-receipt-toggle"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("prompt-receipt-body").textContent).toMatch(
+ /2[,.]400 characters/,
+ );
+ });
+ });
+});
+
+describe("agoLabel", () => {
+ it("reads as 'just now' only while it really is", () => {
+ expect(agoLabel(1_000, 1_000_000 + 3_000)).toBe("just now");
+ });
+
+ it("keeps up rather than freezing at 'just now'", () => {
+ const at = 1_000;
+ expect(agoLabel(at, at * 1000 + 30_000)).toBe("30s ago");
+ expect(agoLabel(at, at * 1000 + 4 * 60_000)).toBe("4 min ago");
+ expect(agoLabel(at, at * 1000 + 2 * 3_600_000)).toBe("2 hours ago");
+ });
+
+ it("never reports a delivery as being in the future", () => {
+ // Clock skew between the backend's stamp and the browser is ordinary; a
+ // receipt reading "-3s ago" would look like a bug in the proof itself.
+ expect(agoLabel(2_000, 1_000_000)).toBe("just now");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PromptReceipt.tsx b/jarvis/ui/web/frontend/src/components/agentic/PromptReceipt.tsx
new file mode 100644
index 0000000000..7496ee8fda
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/PromptReceipt.tsx
@@ -0,0 +1,264 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { AlertTriangle, Check, ChevronDown, HelpCircle, X } from "lucide-react";
+import { fetchLastPrompt } from "@/lib/agenticIdeApi";
+
+/**
+ * Visible proof that a pane was handed a prompt — drawn by the app, never by
+ * the agent's screen.
+ *
+ * ## Why this exists at all
+ *
+ * Jarvis composes a brief, types it into a pane and says so out loud. Until
+ * this component, the ONLY evidence the user had was the pane echoing the text
+ * back, and that evidence is missing in exactly the situations where somebody
+ * would want it:
+ *
+ * - the pane had parked its output while it was off screen, and un-parking
+ * depends on an `IntersectionObserver` reporting its way out of states it
+ * does not report (see ./offscreenBuffer);
+ * - the pane's socket was reconnecting, and a hidden window's timers are
+ * clamped, so "reconnecting" lasted minutes rather than half a second;
+ * - the emulator had not painted yet, so the pane was a black rectangle;
+ * - or the CLI simply redrew its input box somewhere the user was not looking.
+ *
+ * Every one of those has happened in production, and from the user's chair
+ * they are one single experience: **Jarvis claimed it sent the brief and the
+ * screen shows nothing.** The reasonable conclusion is that it did not, and no
+ * amount of "but the agent really did get it" repairs the trust that costs.
+ *
+ * So the receipt is deliberately built from a DIFFERENT source than the screen:
+ * the pane's own delivery record (`last_prompt_at`), pushed instantly over the
+ * socket and read again from the state on every mount, reconnect and poll. If
+ * the terminal is black, the socket is down and the observer is confused, the
+ * receipt still appears.
+ *
+ * ## Why it does not simply fade away
+ *
+ * A toast that vanishes after four seconds only reassures a user who was
+ * already watching — the one who never doubted it. The doubt belongs to
+ * whoever looked away, and it appears minutes later. So this stays: prominent
+ * while it is fresh, then shrinking to a quiet line that remains until the
+ * next prompt replaces it or the user dismisses it. Proof that expires is not
+ * proof.
+ */
+
+/** How long the receipt stays in its full, hard-to-miss form. */
+export const RECEIPT_PROMINENT_MS = 9_000;
+
+export interface PromptReceiptProps {
+ /** Call-sign of the pane this receipt belongs to. */
+ terminal: string;
+ /** Which workspace holds it — several can be open on the same call-signs. */
+ workspaceId?: string | null;
+ /** When the prompt was delivered (epoch SECONDS, as the backend stamps it). */
+ at: number;
+ /** Opening of the delivered text; the full brief is fetched on demand. */
+ preview: string;
+ /** Full length of the prompt, which `preview` is only the start of. */
+ chars: number;
+ /**
+ * Did the agent accept it and start?
+ *
+ * Three states, never rounded to two: `false` means the text is sitting in
+ * the pane's input box unsent, which looks exactly like a working agent and
+ * is the one case where the user has to act.
+ */
+ submitted: boolean | null;
+ onDismiss: () => void;
+}
+
+/** "just now" / "3 min ago" — short enough for a one-line receipt. */
+export function agoLabel(deliveredAt: number, now: number): string {
+ const seconds = Math.max(0, Math.round((now - deliveredAt * 1000) / 1000));
+ if (seconds < 10) return "just now";
+ if (seconds < 60) return `${seconds}s ago`;
+ const minutes = Math.round(seconds / 60);
+ if (minutes < 60) return `${minutes} min ago`;
+ const hours = Math.round(minutes / 60);
+ return hours === 1 ? "1 hour ago" : `${hours} hours ago`;
+}
+
+/** The clock time it landed — the detail that can be checked against a memory. */
+export function clockLabel(deliveredAt: number): string {
+ try {
+ return new Date(deliveredAt * 1000).toLocaleTimeString(undefined, {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+ } catch {
+ return "";
+ }
+}
+
+export function PromptReceipt({
+ terminal,
+ workspaceId,
+ at,
+ preview,
+ chars,
+ submitted,
+ onDismiss,
+}: PromptReceiptProps) {
+ const [prominent, setProminent] = useState(true);
+ const [open, setOpen] = useState(false);
+ const [full, setFull] = useState<string | null>(null);
+ const [loadError, setLoadError] = useState("");
+ const [now, setNow] = useState(() => Date.now());
+ const mounted = useRef(true);
+
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+
+ // A fresh delivery is prominent again: this component is keyed by `at` in the
+ // pane, but a re-render with a new timestamp must not leave a two-minute-old
+ // receipt in its quiet form while the user is being told something arrived.
+ useEffect(() => {
+ setProminent(true);
+ setOpen(false);
+ setFull(null);
+ setLoadError("");
+ const timer = window.setTimeout(() => setProminent(false), RECEIPT_PROMINENT_MS);
+ return () => window.clearTimeout(timer);
+ }, [at]);
+
+ // The relative label has to keep up on its own — nothing else re-renders this
+ // pane once the agent settles, and a receipt frozen at "just now" half an
+ // hour later is a small lie in a component whose entire job is not lying.
+ useEffect(() => {
+ const timer = window.setInterval(() => setNow(Date.now()), 15_000);
+ return () => window.clearInterval(timer);
+ }, []);
+
+ const loadFull = useCallback(async () => {
+ if (full !== null) return;
+ try {
+ const answer = await fetchLastPrompt(terminal, workspaceId ?? undefined);
+ if (!mounted.current) return;
+ setFull(answer.text);
+ setLoadError("");
+ } catch (err) {
+ if (!mounted.current) return;
+ // The excerpt is still on screen, so this degrades to "you can see the
+ // opening but not the rest" rather than to an empty box.
+ setLoadError(err instanceof Error ? err.message : "The full prompt could not be read.");
+ }
+ }, [full, terminal, workspaceId]);
+
+ const toggle = useCallback(() => {
+ setOpen((wasOpen) => {
+ if (!wasOpen) void loadFull();
+ return !wasOpen;
+ });
+ }, [loadFull]);
+
+ const verdict =
+ submitted === true
+ ? {
+ icon: <Check className="h-3.5 w-3.5 shrink-0 text-emerald-400" />,
+ label: "Prompt sent",
+ note: "the agent took it and started",
+ }
+ : submitted === false
+ ? {
+ icon: <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-amber-400" />,
+ label: "Prompt typed, not started",
+ note: "it is sitting in this pane's input box — press Enter here to run it",
+ }
+ : {
+ icon: <HelpCircle className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />,
+ label: "Prompt sent",
+ note: "it went to the pane; the agent's start could not be confirmed",
+ };
+
+ const clock = clockLabel(at);
+
+ return (
+ <div
+ className={`pointer-events-auto absolute inset-x-2 bottom-2 z-20 rounded-md border
+ backdrop-blur transition-all duration-500 ${
+ prominent
+ ? "border-primary/50 bg-card/95 shadow-lg"
+ : "border-border/60 bg-card/80"
+ }`}
+ // Announced rather than only drawn: the whole point is that the user
+ // finds out, and someone using a screen reader gets no help from a ring
+ // around a rectangle.
+ role="status"
+ aria-live="polite"
+ data-testid="prompt-receipt"
+ data-prominent={prominent ? "true" : "false"}
+ >
+ <div className="flex items-center gap-2 px-2 py-1.5">
+ {verdict.icon}
+ <button
+ type="button"
+ onClick={toggle}
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ aria-expanded={open}
+ data-testid="prompt-receipt-toggle"
+ title={`Read exactly what was sent to ${terminal}`}
+ >
+ <span className="shrink-0 text-[11px] font-medium text-foreground">
+ {verdict.label}
+ </span>
+ <span className="shrink-0 text-[11px] text-muted-foreground">
+ {agoLabel(at, now)}
+ {clock ? ` · ${clock}` : ""}
+ </span>
+ {/* The opening of the brief, on the line itself. Even closed, the
+ receipt shows a piece of the real text — a bare "sent" is another
+ claim, and claims are what the user already had. */}
+ <span className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground/80">
+ {preview}
+ </span>
+ <ChevronDown
+ className={`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${
+ open ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ <button
+ type="button"
+ onClick={onDismiss}
+ className="btn-ghost h-6 w-6 shrink-0 p-0"
+ aria-label={`Dismiss the delivery receipt for ${terminal}`}
+ data-testid="prompt-receipt-dismiss"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+
+ {prominent && !open && (
+ <p className="px-2 pb-1.5 text-[10px] leading-snug text-muted-foreground">
+ {verdict.note} · click to read what was sent
+ </p>
+ )}
+
+ {open && (
+ <div className="border-t border-border/60 px-2 py-2" data-testid="prompt-receipt-body">
+ <pre
+ className="max-h-56 overflow-y-auto whitespace-pre-wrap break-words rounded
+ bg-background/60 px-2 py-1.5 font-mono text-[11px] leading-relaxed
+ text-foreground"
+ >
+ {full ?? preview}
+ </pre>
+ <p className="mt-1.5 text-[10px] text-muted-foreground">
+ {full === null && !loadError
+ ? `Opening of ${chars.toLocaleString()} characters — reading the rest…`
+ : loadError
+ ? `Showing the opening only — ${loadError}`
+ : `${chars.toLocaleString()} characters, delivered to ${terminal}${
+ clock ? ` at ${clock}` : ""
+ }.`}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index b4df0314a9..6f958099d3 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -108,7 +108,23 @@ export interface TerminalState {
last_output_at: number | null;
idle_seconds: number | null;
prompts_sent: number;
+ /** The opening of the last delivered prompt — an excerpt, not the whole brief. */
last_prompt: string;
+ /** Its true length, so an excerpt is never presented as the whole thing. */
+ last_prompt_chars?: number;
+ /**
+ * When this pane was last handed a prompt (epoch seconds), null if never.
+ *
+ * The durable half of the delivery receipt. A pane proves a prompt arrived
+ * by echoing it, and that proof is absent in precisely the situations where
+ * it is needed — output parked while the pane was off screen, an emulator
+ * that never painted, a socket reconnecting, a CLI redrawing its input box
+ * out of view. This is read at mount and at every poll, so the receipt is
+ * still there for someone who looks a quarter of an hour later.
+ */
+ last_prompt_at?: number | null;
+ /** Did the last prompt start the agent, or is it still in the input box? */
+ submitted?: boolean | null;
lines_captured: number;
/** Which subscription this pane runs on (see agentAccountsApi). */
account?: string | null;
@@ -422,6 +438,39 @@ export function fetchTerminalRecaps(
return getJson<RecapsResponse>(`/api/agentic-ide/recaps${query}`);
}
+/** The exact prompt a pane was last sent, as `/terminals/{name}/prompt` reports it. */
+export interface LastPrompt {
+ name: string;
+ /** The brief as it was written into the pane, unabridged. */
+ text: string;
+ chars: number;
+ /** Epoch seconds; null when this pane has never been sent anything. */
+ at: number | null;
+ submitted: boolean | null;
+ prompts_sent: number;
+}
+
+/**
+ * Read back, word for word, what a pane was last told to do.
+ *
+ * The proof half of a delivery, and its own request on purpose: a composed
+ * brief runs to thousands of characters, so the workspace state carries only
+ * an excerpt, a length and a timestamp — enough to render the receipt. This is
+ * what a user gets when they open that receipt, and it is the only form of
+ * "I sent it" that can be checked rather than believed.
+ */
+export function fetchLastPrompt(
+ name: string,
+ workspaceId?: string,
+): Promise<LastPrompt> {
+ const query = workspaceId
+ ? `?workspace_id=${encodeURIComponent(workspaceId)}`
+ : "";
+ return getJson<LastPrompt>(
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/prompt${query}`,
+ );
+}
+
function recapUrl(name: string, workspaceId?: string, suffix = ""): string {
const query = workspaceId
? `?workspace_id=${encodeURIComponent(workspaceId)}`
diff --git a/tests/unit/agentic_ide/test_last_prompt_route.py b/tests/unit/agentic_ide/test_last_prompt_route.py
new file mode 100644
index 0000000000..9b8559aed5
--- /dev/null
+++ b/tests/unit/agentic_ide/test_last_prompt_route.py
@@ -0,0 +1,136 @@
+"""Reading back, word for word, what a pane was last told to do.
+
+The route exists because "I sent it" and "here is what I sent" are different
+claims, and only the second one can be checked by the person who has to trust
+it. Jarvis composes a brief, types it into a pane and says so — and the pane
+routinely shows nothing at that moment: output parked while it was off screen,
+an emulator that never painted, a socket reconnecting, a CLI redrawing its
+input box out of view. The user's honest reading of that is that nothing
+happened.
+
+It is also the CLI-first half (CLAUDE.md §5): the same proof has to be
+available from a terminal and a script, not only from the pane's own overlay.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import Registry
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
[email protected](autouse=True)
+def _isolated_recents(
+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.agentic_ide import recents
+
+ store = tmp_path_factory.mktemp("recents") / "recents.json"
+ monkeypatch.setattr(recents, "_store_path", lambda: store)
+
+
+def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ reg = Registry(pty_manager=FakePtyManager())
+ monkeypatch.setattr(session_mod, "get_registry", lambda: reg)
+ from jarvis.ui.web import agentic_ide_routes
+
+ monkeypatch.setattr(agentic_ide_routes, "get_registry", lambda: reg)
+ return reg
+
+
+def client(registry: Registry) -> TestClient:
+ from jarvis.ui.web.agentic_ide_routes import router
+
+ app = FastAPI()
+ app.include_router(router)
+ return TestClient(app)
+
+
+async def _noop(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
+
+
+async def _live_workspace(registry: Registry, folder: Path, count: int = 1) -> list[str]:
+ await registry.start(str(folder), [{"agent": "claude"} for _ in range(count)])
+ assert registry.session is not None
+ for term in list(registry.session.terminals):
+ await registry.attach(term.name, 100, 30, _noop, _noop_exit)
+ return [t.name for t in registry.session.terminals]
+
+
+async def test_it_returns_the_prompt_in_full_not_the_state_excerpt(
+ client: TestClient, registry: Registry, tmp_path: Path
+) -> None:
+ """The workspace state carries 200 characters; the proof carries all of it."""
+ [name] = await _live_workspace(registry, tmp_path)
+ brief = "## Task\n" + ("Review the ranking pipeline. " * 200)
+ await registry.send_prompt(name, brief)
+
+ response = client.get(f"/api/agentic-ide/terminals/{name}/prompt")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["name"] == name
+ assert body["text"].startswith("## Task")
+ assert body["chars"] == len(body["text"])
+ assert body["chars"] > 200
+ assert body["at"] is not None
+
+
+async def test_a_pane_that_was_never_prompted_answers_rather_than_404s(
+ client: TestClient, registry: Registry, tmp_path: Path
+) -> None:
+ """"Nothing was sent here" is an answer; a 404 would read as "no such pane"."""
+ [name] = await _live_workspace(registry, tmp_path)
+
+ body = client.get(f"/api/agentic-ide/terminals/{name}/prompt").json()
+
+ assert body["text"] == ""
+ assert body["at"] is None
+ assert body["prompts_sent"] == 0
+
+
+async def test_an_unknown_pane_is_a_404(client: TestClient) -> None:
+ assert client.get("/api/agentic-ide/terminals/Nobody/prompt").status_code == 404
+
+
+async def test_the_receipt_counts_every_prompt_that_pane_has_had(
+ client: TestClient, registry: Registry, tmp_path: Path
+) -> None:
+ [name] = await _live_workspace(registry, tmp_path)
+ await registry.send_prompt(name, "First instruction")
+ await registry.send_prompt(name, "Second instruction")
+
+ body = client.get(f"/api/agentic-ide/terminals/{name}/prompt").json()
+
+ assert body["prompts_sent"] == 2
+ # The LAST one, not an accumulation: the receipt answers "what is this pane
+ # working on now", and a concatenation of both would answer neither.
+ assert body["text"] == "Second instruction"
+
+
+async def test_the_workspace_state_carries_the_timestamp_the_receipt_is_built_from(
+ client: TestClient, registry: Registry, tmp_path: Path
+) -> None:
+ """Without this, a viewer that missed the live notice has no way back to it."""
+ [name] = await _live_workspace(registry, tmp_path)
+ await registry.send_prompt(name, "Look at the failing test")
+
+ state = client.get("/api/agentic-ide/state").json()
+ pane = next(t for t in state["session"]["terminals"] if t["name"] == name)
+
+ assert pane["last_prompt_at"] is not None
+ assert pane["last_prompt_chars"] == len("Look at the failing test")
diff --git a/tests/unit/agentic_ide/test_prompt_receipt.py b/tests/unit/agentic_ide/test_prompt_receipt.py
new file mode 100644
index 0000000000..15cda09923
--- /dev/null
+++ b/tests/unit/agentic_ide/test_prompt_receipt.py
@@ -0,0 +1,133 @@
+"""The delivery receipt: a pane records, and announces, that it was given a prompt.
+
+Guards the one guarantee that makes the receipt worth having — that it does NOT
+depend on the agent's screen. A prompt reaches a pane and the pane may show
+nothing at all: its output parked while it was off screen, its emulator never
+painted, its socket reconnecting, or the CLI redrawing its input box out of
+view. Every one of those has happened live, and each time the user was told the
+brief had been sent and had no way to check.
+
+So delivery is recorded in the pane's own state (durable, survives a viewer
+that was not there) and announced on a channel of its own (immediate, lossy).
+The tests below pin both halves, including the case the readback most needs to
+keep honest: a prompt that was typed but never submitted still produces a
+receipt, because that pane looks exactly like a working one.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.agentic_ide.session import Terminal, announce_prompt
+
+
+def pane(**kwargs: object) -> Terminal:
+ """A pane with the identity fields filled in and nothing else assumed."""
+ defaults: dict = {
+ "key": "t1",
+ "name": "T1",
+ "agent": "claude",
+ "display_name": "Claude Code",
+ "index": 0,
+ }
+ defaults.update(kwargs)
+ return Terminal(**defaults) # type: ignore[arg-type]
+
+
+def test_a_pane_that_was_never_prompted_says_so() -> None:
+ """No timestamp, rather than a zero that would render as 1 January 1970."""
+ term = pane()
+
+ assert term.last_prompt_at is None
+ assert term.to_dict()["last_prompt_at"] is None
+ assert term.to_dict()["last_prompt_chars"] == 0
+
+
+def test_the_state_carries_when_a_prompt_arrived_and_how_long_it_was() -> None:
+ """The durable half of the receipt: readable at any later mount or poll."""
+ term = pane(last_prompt="Refactor the parser" * 40, last_prompt_at=1_700_000_000.0)
+
+ state = term.to_dict()
+
+ assert state["last_prompt_at"] == 1_700_000_000.0
+ assert state["last_prompt_chars"] == len(term.last_prompt)
+ # The excerpt stays short on purpose — a composed brief runs to thousands of
+ # characters and this rides along in every state read.
+ assert len(state["last_prompt"]) == 200
+ assert state["last_prompt_chars"] > len(state["last_prompt"])
+
+
+async def test_every_attached_viewer_is_told_about_a_delivery() -> None:
+ """A pane open in two windows must not have one of them left in the dark."""
+ seen: list[dict] = []
+ other: list[dict] = []
+ term = pane(last_prompt="Write the tests first", last_prompt_at=12.0, prompts_sent=3)
+ term.prompt_viewers.extend(
+ [lambda notice: _record(seen, notice), lambda notice: _record(other, notice)]
+ )
+
+ await announce_prompt(term)
+
+ assert len(seen) == 1
+ assert len(other) == 1
+ assert seen[0]["name"] == "T1"
+ assert seen[0]["at"] == 12.0
+ assert seen[0]["chars"] == len("Write the tests first")
+ assert seen[0]["prompts_sent"] == 3
+
+
+async def test_the_notice_carries_an_excerpt_not_the_whole_brief() -> None:
+ """The socket is otherwise keystrokes; a 6 000-character brief has a URL."""
+ term = pane(last_prompt="x" * 4_000, last_prompt_at=1.0)
+ seen: list[dict] = []
+ term.prompt_viewers.append(lambda notice: _record(seen, notice))
+
+ await announce_prompt(term)
+
+ assert len(seen[0]["preview"]) == 200
+ assert seen[0]["chars"] == 4_000
+
+
[email protected]("submitted", [True, False, None])
+async def test_a_receipt_goes_out_for_every_outcome(submitted: bool | None) -> None:
+ """Including — above all — the prompt that never started.
+
+ A brief sitting unsent in an input box is indistinguishable on screen from
+ an agent hard at work, and it is the only case where the user has to do
+ something about it. Suppressing the receipt there would hide the one state
+ that cannot fix itself.
+ """
+ term = pane(last_prompt="Ship it", last_prompt_at=5.0, submitted=submitted)
+ seen: list[dict] = []
+ term.prompt_viewers.append(lambda notice: _record(seen, notice))
+
+ await announce_prompt(term)
+
+ assert seen[0]["submitted"] is submitted
+
+
+async def test_a_viewer_that_raises_does_not_cost_the_other_viewers() -> None:
+ """The delivery already happened; a broken channel may not unreport it."""
+ seen: list[dict] = []
+ term = pane(last_prompt="Carry on", last_prompt_at=7.0)
+
+ async def explode(_notice: dict) -> None:
+ raise RuntimeError("this viewer's socket died mid-send")
+
+ term.prompt_viewers.extend([explode, lambda notice: _record(seen, notice)])
+
+ await announce_prompt(term) # must not raise
+
+ assert len(seen) == 1
+
+
+async def test_announcing_with_nobody_attached_is_a_no_op() -> None:
+ """The state still carries it — the next viewer picks the receipt up there."""
+ term = pane(last_prompt="Nobody is watching", last_prompt_at=9.0)
+
+ await announce_prompt(term) # must not raise
+
+ assert term.last_prompt_at == 9.0
+
+
+async def _record(sink: list[dict], notice: dict) -> None:
+ sink.append(notice)