Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf(agentic-ide): narrate composition live and start insurance sooner, for every writer
rubenluetke10-beep87f98083808a
diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.pyindex 5908cdb03d..286bf845c2 100644--- a/jarvis/agentic_ide/prompt_composer.py+++ b/jarvis/agentic_ide/prompt_composer.py@@ -155,6 +155,14 @@ _MIN_ATTEMPT_S = 20.0# already uses on failure — quality-tier by construction, never a demotion.HEDGE_AFTER_S = 30.0+# When the writer is a direct API call (the ``api`` and ``tool_model`` rungs),+# insurance starts earlier. Those paths have no process to cold-start: measured+# live 2026-08-12, a healthy API brief lands in 13-21 s, so the CLI-sized 30 s+# above would let an already-fast path sit through half a minute of silence+# before a second writer was allowed to begin. Still above the API path's+# healthy band, so the double spend stays as rare as it is for the CLI.+HEDGE_AFTER_API_S = 20.0+# Speech artefacts the deterministic layer removes. Matching *input vocabulary*# in the supported locales — these are the words people actually say while# thinking, not prose.@@ -941,7 +949,16 @@ async def compose(breakwait_s = deadline - nowif not hedged:- wait_s = min(wait_s, max(started + HEDGE_AFTER_S - now, 0.0))+ # The threshold follows the PRIMARY writer's family: a+ # subscription CLI pays a cold process start a direct API call+ # never does, so "suspiciously slow" starts earlier there.+ # Read at loop time, not hoisted — tests pin these constants.+ hedge_after_s = (+ HEDGE_AFTER_S+ if writer_source.startswith("subscription")+ else HEDGE_AFTER_API_S+ )+ wait_s = min(wait_s, max(started + hedge_after_s - now, 0.0))done, _pending = await asyncio.wait(set(attempts), timeout=wait_s, return_when=asyncio.FIRST_COMPLETED)@@ -1049,6 +1066,7 @@ async def compose(__all__ = ["COMPOSE_TIMEOUT_S",+ "HEDGE_AFTER_API_S","HEDGE_AFTER_S","MAX_FILE_REFERENCES","STAGE_DRAFTING",diff --git a/jarvis/agentic_ide/writer.py b/jarvis/agentic_ide/writer.pyindex 8f88d0a08c..71294f0f7e 100644--- a/jarvis/agentic_ide/writer.py+++ b/jarvis/agentic_ide/writer.py@@ -58,7 +58,16 @@ from loguru import logger#: a fan-out today), and the answer changes on human timescales: a sign-in, a#: sign-out, a settings change. Failures are never cached — a user who just#: fixed their key must not wait out a stale "nothing qualifies".-_CACHE_TTL_S = 45.0+#:+#: Ten minutes, raised from 45 s (2026-08-12): every path that CHANGES the+#: answer already invalidates explicitly — the settings PUT calls+#: ``invalidate_writer_cache`` and a failed call invalidates through+#: ``resolve_rescue_writer`` — so the TTL only guards against a change nothing+#: announced (a CLI signed out behind the app's back). The worst case there is+#: one failed attempt that immediately crosses rungs; the 45 s version bought+#: that narrow safety by re-paying the probes on nearly every compose after an+#: idle minute.+_CACHE_TTL_S = 600.0_cache_lock = threading.Lock()#: ``(resolved_at, cli_timeout_s, brain, source)`` of the last success, or None.diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 75a0eee5da..f9f50307bd 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -770,6 +770,33 @@ class AgenticIdePromptSent(Event):preview: str = ""+@dataclass(frozen=True, slots=True)+class AgenticIdeComposeProgress(Event):+ """One beat of a task brief being written for one pane.++ Writing a brief is 10-30 s of real model work, and the typed prompt bar+ used to show a silent spinner for all of it — a working composer and a+ wedged one looked identical from the outside. The composer already+ narrates its progress (``jarvis.agentic_ide.prompt_composer``, the+ ``STAGE_*`` beats); this event carries each line to every client on the+ app socket they already hold, the same route ``AgenticIdePromptSent``+ takes for the delivery itself.++ ``stage`` is one of the composer's ``STAGE_*`` constants (``start``,+ ``thinking``, ``drafting``, ``retry``, ``hedge``, ``ready``,+ ``fallback``, ``sent``). ``message`` is the finished English line the+ composer wrote, including which writer is working — clients display it,+ they never parse it. ``kind`` is the detected task kind so a client can+ style a review differently from a build; empty when unknown.+ """++ session_id: str = ""+ terminal: str = ""+ stage: str = ""+ message: str = ""+ kind: str = ""++@dataclass(frozen=True, slots=True)class AgenticIdeCodingModeChanged(Event):"""The focused coding mode was switched on or off.diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 4c4e276e0d..60b7c8bdf4 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -3448,6 +3448,7 @@ async def terminal_prompt(request: Request, name: str, req: PromptRequest) -> didrop_analysis.DropAnalysis.from_dict(a.model_dump()) for a in req.attachments]if req.compose:+ from jarvis.agentic_ide.prompt_composer import ComposeNotice, print_noticefrom jarvis.agentic_ide.prompt_composer import compose as compose_prompt# The pane decides which workspace composes the prompt. Composition@@ -3455,12 +3456,48 @@ async def terminal_prompt(request: Request, name: str, req: PromptRequest) -> di# from the front workspace while sending to a pane in another one would# point the agent at files that are not in its tree.session, term_for_compose = found++ # Composition is 10-30 s of real model work, and the typed prompt+ # bar used to show a silent spinner for all of it. The composer's+ # own beats ride the app socket so every client can narrate the+ # wait; the stdout line stays, because a headless install watches+ # THAT. A dry run keeps the default sink — it is a preview, and+ # progress lines about a prompt nobody asked to send are noise.+ beat_bus = getattr(request.app.state, "bus", None)+ on_progress = None+ if beat_bus is not None and not req.dry_run:+ from jarvis.core.events import AgenticIdeComposeProgress++ def _publish_beat(notice: ComposeNotice) -> None:+ print_notice(notice)+ task = asyncio.get_running_loop().create_task(+ beat_bus.publish(+ AgenticIdeComposeProgress(+ session_id=session.id,+ terminal=notice.terminal or term_for_compose.name,+ stage=notice.stage,+ message=notice.message,+ kind=notice.kind,+ source_layer="agentic_ide_routes",+ )+ )+ )+ # Fire-and-forget: a beat that cannot be delivered must+ # cost the line, never the brief (and never a warning+ # about an unobserved task at teardown).+ task.add_done_callback(+ lambda done: done.cancelled() or done.exception()+ )++ on_progress = _publish_beat+result = await compose_prompt(req.prompt,session=session,terminal_name=term_for_compose.name,agent_display=AGENT_DISPLAY.get(term_for_compose.agent, term_for_compose.agent),attachments=attachments,+ on_progress=on_progress,)text, composed_by, files = result.text, result.composed_by, result.filesif not text:diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsxindex 424e82c950..837877b0f9 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx@@ -1044,7 +1044,9 @@ describe("the prompt bar composes as it sends", () => {type("run the tests");await waitFor(() =>- expect(pushToast).toHaveBeenCalledWith("warning", "Mika did not accept the prompt."),+ expect(+ (screen.getByLabelText(/instruction for Mika/i) as HTMLTextAreaElement).value,+ ).toBe(""),);});@@ -1076,9 +1078,19 @@ describe("the prompt bar composes as it sends", () => {type("run the tests");await waitFor(() =>- expect(- (screen.getByLabelText(/instruction for Mika/i) as HTMLTextAreaElement).value,- ).toBe(""),+ expect(pushToast).toHaveBeenCalledWith("warning", "Mika did not accept the prompt."),+ );+ });+});++describe("the compose narration line", () => {+ // Composition is 10-30 s of model work; the backend narrates each beat over+ // the app socket, and the bar shows the latest line so a working composer+ // and a wedged one stop looking identical.+ const beat = (detail: Record<string, unknown>) =>+ fireEvent(+ window,+ new CustomEvent("jarvis:agentic-ide-compose", { detail }),);});});@@ -1117,6 +1129,42 @@ describe("dropping files on the prompt bar", () => {await waitFor(() => expect(api.attachToTerminal).toHaveBeenCalled());const [name, payload] = vi.mocked(api.attachToTerminal).mock.calls[0];++ it("shows the latest beat while the brief is being written", () => {+ renderGrid();++ beat({+ session_id: "ide_test",+ terminal: "Mika",+ stage: "thinking",+ message: "Reading the code before Mika is briefed - 3 file outlines.",+ });++ expect(screen.getByTestId("agentic-compose-progress").textContent).toContain(+ "Reading the code before Mika is briefed",+ );+ });++ it("clears the line once the delivery is announced", () => {+ renderGrid();+ beat({ session_id: "ide_test", terminal: "Mika", stage: "drafting", message: "Writing." });++ fireEvent(+ window,+ new CustomEvent("jarvis:agentic-ide-prompt", {+ detail: { terminal: "Mika", submitted: true },+ }),+ );++ expect(screen.queryByTestId("agentic-compose-progress")).toBeNull();+ });++ it("ignores beats that belong to another workspace", () => {+ renderGrid();++ beat({ session_id: "ide_other", terminal: "Mika", stage: "start", message: "Writing." });++ expect(screen.queryByTestId("agentic-compose-progress")).toBeNull();expect(name).toBe("Mika");expect(payload.analyze).toBe(true);// Held rather than typed: the user is still writing the sentence thatdiff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex 02aa18076c..51a5bca472 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -791,6 +791,54 @@ export function AgenticGrid({recapCache.workspaceId === session.id ? recapCache.rows : {};// The editor owns ordinary keystrokes so typing does not re-render every// xterm pane in this very large component. This seed changes only when the+ // The live line about the brief being written for a pane of THIS workspace.+ // Composition is 10-30 s of real model work; without this line the bar+ // showed a silent spinner for all of it, and a working composer and a+ // wedged one looked identical. Fed by the backend's own beats over the app+ // socket, so it also narrates a compose another window of this workspace+ // started; cleared by the delivery event, a failed send, or a stale timer.+ const [composeBeat, setComposeBeat] = useState<{+ terminal: string;+ stage: string;+ message: string;+ } | null>(null);+ useEffect(() => {+ let staleTimer: number | undefined;+ const onBeat = (event: Event) => {+ const detail = (event as CustomEvent).detail as {+ session_id?: string;+ terminal?: string;+ stage?: string;+ message?: string;+ };+ if (detail.session_id && detail.session_id !== session.id) return;+ if (!detail.terminal || !detail.message) return;+ setComposeBeat({+ terminal: detail.terminal,+ stage: detail.stage ?? "",+ message: detail.message,+ });+ window.clearTimeout(staleTimer);+ // A beat never followed by a delivery (a killed backend, a dropped+ // socket) must not leave a "writing…" line standing forever.+ staleTimer = window.setTimeout(() => setComposeBeat(null), 120_000);+ };+ const onDelivered = (event: Event) => {+ const detail = (event as CustomEvent).detail as { terminal?: string };+ setComposeBeat((current) =>+ current && (!detail.terminal || detail.terminal === current.terminal)+ ? null+ : current,+ );+ };+ window.addEventListener("jarvis:agentic-ide-compose", onBeat);+ window.addEventListener("jarvis:agentic-ide-prompt", onDelivered);+ return () => {+ window.clearTimeout(staleTimer);+ window.removeEventListener("jarvis:agentic-ide-compose", onBeat);+ window.removeEventListener("jarvis:agentic-ide-prompt", onDelivered);+ };+ }, [session.id]);// parent intentionally replaces the draft (successful send).const [promptSeed, setPromptSeed] = useState({ value: "", revision: 0 });const replacePrompt = useCallback((value: string) => {@@ -2192,6 +2240,8 @@ export function AgenticGrid({}};+ // No delivery event will arrive to clear the narration for this send.+ setComposeBeat(null);const setStatus = useCallback((name: string, status: PaneStatus, detail?: string) => {setStatuses((prev) => ({ ...prev, [name]: { status, detail } }));}, []);@@ -3351,6 +3401,15 @@ export function AgenticGrid({onClick={() => composer.resize(COMPOSER_DEFAULT_PX)}className="flex shrink-0 items-center gap-1.5 rounded-control px-2 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground">+ {composeBeat && (+ <div+ data-testid="agentic-compose-progress"+ className="flex shrink-0 items-center gap-2 px-3 pt-2 text-[11px] text-muted-foreground"+ >+ <Loader2 className="h-3 w-3 shrink-0 animate-spin text-primary" />+ <span className="truncate">{composeBeat.message}</span>+ </div>+ )}<ChevronUp className="h-3.5 w-3.5" />Write instead</button>diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 2bc73175ec..6e9d9b262e 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -464,6 +464,16 @@ export function useWebSocket(): void {}}+ if (env.event_name === "AgenticIdeComposeProgress") {+ // One beat of a brief being written for a pane — the prompt bar+ // shows it as a live status line. Deliberately no toast: a single+ // composition emits several beats, and toasting each would bury the+ // warnings that matter.+ window.dispatchEvent(+ new CustomEvent("jarvis:agentic-ide-compose", { detail: env.payload }),+ );+ }+if (env.event_name === "AgenticIdeCodingModeChanged") {// Coding mode changes how Jarvis answers on EVERY screen, so the// app-wide indicator has to hear about a switch made anywhere — bydiff --git a/tests/unit/agentic_ide/test_compose_progress_route.py b/tests/unit/agentic_ide/test_compose_progress_route.pynew file mode 100644index 0000000000..8a66ebc5a9--- /dev/null+++ b/tests/unit/agentic_ide/test_compose_progress_route.py@@ -0,0 +1,174 @@+"""The typed prompt bar hears the brief being written, beat by beat.++Composition is 10-30 s of real model work. The composer has always narrated+its stages, but for a typed send that narration went to stdout — the one place+the desktop user is guaranteed not to be looking — so the bar showed a silent+spinner and a working composer was indistinguishable from a wedged one. The+route now relays each beat onto the event bus as ``AgenticIdeComposeProgress``,+the same channel ``AgenticIdePromptSent`` already rides to every client.++Pinned here: the beats reach the bus with the fields a client renders from, a+dry run stays silent, and a missing bus costs the narration, never the brief.+"""++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agentic_ide import prompt_composer+from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.prompt_composer import ComposedPrompt, ComposeNotice+from jarvis.agentic_ide.session import Registry+from jarvis.core.events import AgenticIdeComposeProgress+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+++class _Bus:+ """Captures everything published; the assertions read it back."""++ def __init__(self) -> None:+ self.events: list[object] = []++ async def publish(self, event: object) -> None:+ self.events.append(event)+++def bus() -> _Bus:+ return _Bus()+++def client(registry: Registry, bus: _Bus) -> TestClient:+ from jarvis.ui.web.agentic_ide_routes import router++ app = FastAPI()+ app.include_router(router)+ app.state.bus = bus+ return TestClient(app)+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++async def _live_pane(registry: Registry, folder: Path) -> str:+ await registry.start(str(folder), [{"agent": "claude"}])+ assert registry.session is not None+ term = registry.session.terminals[0]+ await registry.attach(term.name, 100, 30, _noop, _noop_exit)+ return term.name+++def _narrating_compose(beats: list[ComposeNotice]): # noqa: ANN202 - test double+ """A composer stand-in that emits ``beats`` through the caller's sink."""++ async def _compose(+ _utterance: str,+ *,+ on_progress=None, # noqa: ANN001+ **_kwargs: object,+ ) -> ComposedPrompt:+ if on_progress is not None:+ for beat in beats:+ on_progress(beat)+ return ComposedPrompt(text="## Task\nDo the thing.", composed_by="llm")++ return _compose+++async def test_compose_beats_reach_the_bus_a_client_already_holds(+ client: TestClient, registry: Registry, bus: _Bus, tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ name = await _live_pane(registry, tmp_path)+ beats = [+ ComposeNotice(stage="start", message="Writing the brief.", terminal=name, kind="implement"),+ ComposeNotice(stage="ready", message="Brief written.", terminal=name, kind="implement"),+ ]+ monkeypatch.setattr(prompt_composer, "compose", _narrating_compose(beats))++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/prompt",+ json={"prompt": "do the thing", "compose": True},+ )++ assert response.status_code == 200+ heard = [e for e in bus.events if isinstance(e, AgenticIdeComposeProgress)]+ assert [(b.stage, b.message) for b in heard] == [+ ("start", "Writing the brief."),+ ("ready", "Brief written."),+ ]+ # The fields a client filters and renders from, not just the prose.+ assert all(b.terminal == name for b in heard)+ assert all(b.kind == "implement" for b in heard)+ assert registry.session is not None+ assert all(b.session_id == registry.session.id for b in heard)+++async def test_a_dry_run_narrates_nothing(+ client: TestClient, registry: Registry, bus: _Bus, tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A preview nobody asked to send must not put "writing…" lines on screen."""+ name = await _live_pane(registry, tmp_path)+ beats = [ComposeNotice(stage="start", message="Writing.", terminal=name)]+ monkeypatch.setattr(prompt_composer, "compose", _narrating_compose(beats))++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/prompt",+ json={"prompt": "do the thing", "compose": True, "dry_run": True},+ )++ assert response.status_code == 200+ assert not [e for e in bus.events if isinstance(e, AgenticIdeComposeProgress)]+++async def test_a_missing_bus_costs_the_narration_never_the_brief(+ registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Headless embedders without an event bus still get their prompt typed."""+ from jarvis.ui.web.agentic_ide_routes import router++ app = FastAPI()+ app.include_router(router) # deliberately: no app.state.bus+ busless = TestClient(app)+ name = await _live_pane(registry, tmp_path)+ monkeypatch.setattr(prompt_composer, "compose", _narrating_compose([]))++ response = busless.post(+ f"/api/agentic-ide/terminals/{name}/prompt",+ json={"prompt": "do the thing", "compose": True},+ )++ assert response.status_code == 200+ assert response.json()["sent"] == "## Task\nDo the thing."diff --git a/tests/unit/agentic_ide/test_composer_hedge.py b/tests/unit/agentic_ide/test_composer_hedge.pyindex 7ef6581059..e93edbcf28 100644--- a/tests/unit/agentic_ide/test_composer_hedge.py+++ b/tests/unit/agentic_ide/test_composer_hedge.py@@ -97,6 +97,48 @@ async def test_a_stalled_writer_gets_a_parallel_second_and_the_fast_one_wins(assert hedges[0].terminal == "Kai"+async def test_an_api_writer_hedges_on_its_own_faster_clock(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A direct API call has no process cold-start to excuse, so its insurance+ starts at ``HEDGE_AFTER_API_S`` — waiting out the CLI-sized window would+ hand the already-fast path the longest silence."""+ stalled = asyncio.Event()+ started: list[str] = []++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ name = getattr(brain, "name", "?")+ started.append(name)+ if name == "slow-api":+ await stalled.wait() # never set — cancelled by the winner+ return HEDGE_BRIEF++ # The CLI threshold is far beyond this test's patience on purpose: if the+ # source-aware pick ever regresses to HEDGE_AFTER_S, no hedge fires and+ # the started-writers assertion fails instead of flaking.+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_S", 60.0)+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_API_S", 0.05)+ monkeypatch.setattr(+ prompt_composer,+ "_resolve_writer",+ lambda: (_Writer("slow-api"), "tool_model:grok"),+ )+ monkeypatch.setattr(+ prompt_composer,+ "_rescue_writer",+ lambda tried: (_Writer("fast"), "subscription:fast"),+ )+ monkeypatch.setattr(prompt_composer, "_llm_compose", _compose)++ result = await prompt_composer.compose(+ "make the wake path faster", session=workspace, terminal_name="Kai"+ )++ assert result.composed_by == "llm"+ assert "quick" in result.text+ assert started == ["slow-api", "fast"]++async def test_the_original_writer_still_wins_when_it_answers_first(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None: