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
feat(agentic-ide): let every coding agent ask and have its plan approved in a thread
rubenluetke10-beep32aa1a36685b
diff --git a/docs/agentic-ide-threads.md b/docs/agentic-ide-threads.mdindex e11651d12e..670d0ee519 100644--- a/docs/agentic-ide-threads.md+++ b/docs/agentic-ide-threads.md@@ -52,6 +52,24 @@ for an approval and a blue dot for news since it was last opened.- Changes, files, git and terminals live in the IDE's side panel, as in thegrid layout.+## Questions, approvals and plans++Every coding agent gets the same cards at the top of the composer+(`jarvis/agent_chat/turn_prompts.py`):++| Moment | Claude Code, GLM | Every other CLI (Codex, Antigravity, Grok Build, OpenCode, Kimi, Cursor, DeepSeek Harness) |+|---|---|---|+| The agent has a question | Its own `AskUserQuestion` opens the question card mid-turn; the answers go back on the control protocol and it keeps working | It ends its reply with a `jarvis-ask` block (the protocol rides in front of every prompt); the card opens when the turn ends and the answers are the next message |+| The plan is ready | `ExitPlanMode` opens a plan card with the plan itself; **Build it** switches the thread to the runner's build mode and the same turn starts building | A turn that finished in plan mode opens a plan card; **Build it** switches the thread to the runner's build mode and sends the go-ahead |+| A tool needs permission | The approval card (Approve, Always allow, Decline) | The CLI cannot ask from a headless run: the access mode decides, as each mode's description says |++The question card offers the agent's options (its recommendation first), a+typed answer, and Skip, which leaves the open questions to the agent's+recommendations. **Keep planning** closes a plan card so the person can type+what to change. A card nobody answered closes when the person sends another+message instead. Cards are rebuilt from the session's event log, so they+survive reopening the thread and restarting the app.+## PlatformsNothing in the thread layout is OS-specific: paths are compareddiff --git a/jarvis/agent_chat/events.py b/jarvis/agent_chat/events.pyindex c45548a064..d474e95e8a 100644--- a/jarvis/agent_chat/events.py+++ b/jarvis/agent_chat/events.py@@ -27,6 +27,13 @@ Kinds (``payload`` keys in brackets):``tool_result`` [turn_id, call_id, output, is_error, duration_ms]``approval_required`` [turn_id, approval_id, call_id, name, input, summary]``approval_resolved`` [turn_id, approval_id, decision] decision: allow | deny+``question_required`` [turn_id, question_id, asker, questions, deferred?] — a question+ card; ``deferred`` = an end-of-turn card (turn_prompts)+ whose answers go to the agent as the next message+``question_progress`` [turn_id, question_id, answers]+``question_resolved`` [turn_id, question_id, answers]+``plan_ready`` [turn_id, build_mode] — a coding agent's plan card+``plan_resolved`` [turn_id, decision] decision: build | keep``turn_finished`` [turn_id, status, duration_ms, usage, error, cost_usd]status: done | cancelled | error``session_updated`` [title?, provider?, model?, effort?, cwd?, permission_mode?]diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex 2bbfa8ac95..fbfef67b39 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -74,7 +74,14 @@ from jarvis.agent_chat.approval_bridge import approval_reffrom jarvis.agent_chat.cli_catalog import CatalogCache, catalog_key, discover_codex_modelsfrom jarvis.agent_chat.effort import ORDER, normalize_effort, snap_to_ladderfrom jarvis.agent_chat.events import make_event-from jarvis.agent_chat.permissions import normalize_permission+from jarvis.agent_chat.permissions import default_permission, normalize_permission+from jarvis.agent_chat.questions import (+ CANCELLED,+ UNATTENDED,+ TooManyQuestions,+ parse_questions,+ recommended_answer,+)from jarvis.agent_chat.runner_api import TurnHandlefrom jarvis.agent_chat.tool_context import register_turn, unregister_turnfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS@@ -210,25 +217,64 @@ def grok_argv_prefix() -> list[str]:return [binary]+def _is_batch(binary: str) -> bool:+ return binary.lower().endswith((".cmd", ".bat"))+++def _behind_shim(binary: str, agent: str) -> list[str]:+ """``binary``, or what its Windows ``.cmd`` shim would have launched.++ These CLIs take the prompt on argv, and through an npm shim argv passes+ ``cmd.exe``: a line break ends the command there, so a multi-line message+ reached the agent cut after its first line. The package layout the+ workspace registry declares (``WinShim``) launches the real program+ instead; an install laid out differently keeps the shim, and+ :func:`_argv_prompt` keeps the whole message on one line for it.+ """+ if not _is_batch(binary):+ return [binary]+ try:+ from jarvis.workspace import agents as workspace_agents++ spec = workspace_agents.get_agent(agent)+ direct = workspace_agents.behind_win_shim(spec, binary) if spec is not None else None+ except Exception: # noqa: BLE001 — the shim still runs; only line breaks are at risk+ log.warning("agent chat: could not look behind the %s shim", agent, exc_info=True)+ direct = None+ return list(direct) if direct else [binary]+++def _argv_prompt(prefix: list[str], prompt: str) -> str:+ """The prompt as one argv value that survives ``prefix``.++ A batch file still in front (an unknown install layout) would drop every+ line after the first, so the lines are joined with spaces instead: the+ agent loses the layout, never the words.+ """+ if prefix and _is_batch(prefix[0]):+ return " ".join(line.strip() for line in prompt.splitlines() if line.strip())+ return prompt++def opencode_argv_prefix() -> list[str]:binary = _which(*CLI_BINARIES["opencode-cli"])if not binary:raise CliUnavailable("OpenCode (opencode) is not installed or not on PATH.")- return [binary]+ return _behind_shim(binary, "opencode")def kimi_argv_prefix() -> list[str]:binary = _which(*CLI_BINARIES["kimi-cli"])if not binary:raise CliUnavailable("Kimi Code (kimi) is not installed or not on PATH.")- return [binary]+ return _behind_shim(binary, "kimi")def dsh_argv_prefix() -> list[str]:binary = _which(*CLI_BINARIES["dsh-cli"])if not binary:raise CliUnavailable("DeepSeek Harness (dsh) is not installed or not on PATH.")- return [binary]+ return _behind_shim(binary, "deepseek-harness")def cursor_argv_prefix() -> list[str]:@@ -615,7 +661,7 @@ def plan_grok(else:sid = str(uuid.uuid4())argv += ["--session-id", sid]- argv += ["-p", prompt]+ argv += ["-p", _argv_prompt(argv, prompt)]env = jarvis_harness.apply_env(_account_env("grok-build"))env.setdefault("PYTHONIOENCODING", "utf-8")return CliPlan(argv, env, None, "claude", sid)@@ -1125,7 +1171,7 @@ def plan_opencode(argv += ["--variant", effort]if resume:argv += ["--session", resume]- argv += ["--", prompt]+ argv += ["--", _argv_prompt(argv, prompt)]env = _registry_env("opencode", _account_env("opencode"))return CliPlan(argv, env, None, "opencode", resume)@@ -1165,16 +1211,15 @@ def plan_kimi(if model:argv += ["--model", model]# Print mode is autonomous by Kimi's own design (a headless run has nobody- # to ask); the flag only says so out loud. Plan is an instruction, not a- # sandbox — the ladder's sentence says as much.- if mode == "auto":- argv += ["--auto"]+ # to ask), and Kimi Code refuses ``--auto``, ``--yolo`` and ``--plan`` next+ # to ``--prompt`` ("Cannot combine --prompt with --auto", 0.29). Plan is+ # therefore an instruction, not a sandbox — the ladder's sentence says so.if resume:# Long form on purpose: the two Kimi generations disagree on the short# flag (``agent_sessions``).argv += ["--session", resume]text = _PLAN_PREAMBLE + prompt if mode == "plan" else prompt- argv += ["--prompt", text]+ argv += ["--prompt", _argv_prompt(argv, text)]env = _registry_env("kimi", _account_env("kimi"))return CliPlan(argv, env, None, "kimi", resume, discover=None if resume else _kimi_session_after@@ -1198,7 +1243,8 @@ def plan_dsh(back is text, and the chat shows it as the answer."""prompt = _with_identity(prompt, identity, None, compact=True)- argv = [*dsh_argv_prefix(), "--profile", "headless", prompt]+ prefix = dsh_argv_prefix()+ argv = [*prefix, "--profile", "headless", _argv_prompt(prefix, prompt)]env = _registry_env("deepseek-harness", _account_env("deepseek-harness"))return CliPlan(argv, env, None, "text", None)@@ -1239,7 +1285,7 @@ def plan_cursor(argv += ["--force"]if resume:argv += ["--resume", resume]- argv.append(prompt)+ argv.append(_argv_prompt(argv, prompt))env = _registry_env("cursor", _account_env("cursor"))return CliPlan(argv, env, None, "cursor", resume)@@ -2800,6 +2846,17 @@ async def run_cli_turn(else lambda _name, _args: False,),)+ from jarvis.agent_chat.surface_kits import kit_for+ from jarvis.agent_chat.turn_prompts import ASK_PROTOCOL++ if (+ runner not in _CLAUDE_CODE_RUNNERS+ and kit_for(session.surface).turn_prompts+ and not user_text.lstrip().startswith("/")+ ):+ # No mid-turn channel to ask on: the agent asks at the end of its turn+ # and the chat shows the block as a question card (turn_prompts).+ user_text = ASK_PROTOCOL + user_texttool_context = register_turn(session.session_id) if identity else Nonetry:outcome = await _run_cli_once(@@ -3144,10 +3201,14 @@ async def _run_cli_once(subtype = str(req.get("subtype") or "")decision = "deny"message = "Not supported by this chat."+ tool_name = ""if subtype == "can_use_tool":tool_name = str(req.get("tool_name") or req.get("display_name") or "tool")tool_input = req.get("input") if isinstance(req.get("input"), dict) else {}call_id = str(req.get("tool_use_id") or uuid.uuid4().hex)+ if tool_name == "AskUserQuestion":+ await _respond(request_id, await _claude_question(tool_input))+ returnsummary = str(req.get("description") or "") or _claude_request_summary(tool_name, tool_input)@@ -3181,14 +3242,76 @@ async def _run_cli_once(# A Jarvis tool the CLI just asked about will hit the executor's# own gate over MCP in a moment; the person has answered once.bridge.note_cli_approval(chat_ref, tool_name)+ if tool_name == "ExitPlanMode":+ build = await _leave_plan_mode()+ if build:+ body["updatedPermissions"] = [+ {"type": "setMode", "mode": build, "destination": "session"}+ ]else:body = {"behavior": "deny", "message": message}+ await _respond(request_id, body)++ async def _respond(request_id: str, body: dict[str, Any]) -> None:frame = {"type": "control_response","response": {"subtype": "success", "request_id": request_id, "response": body},}await _write_stdin(json.dumps(frame, ensure_ascii=False) + "\n")+ async def _claude_question(tool_input: dict[str, Any]) -> dict[str, Any]:+ """Claude Code's own ``AskUserQuestion``, answered on the chat's question card.++ The answers go back the way the CLI reads them: ``updatedInput`` keeps+ the questions and adds ``answers`` keyed by each question's text.+ """+ raw = tool_input.get("questions")+ rows = raw if isinstance(raw, list) else []+ try:+ specs = parse_questions({"questions": rows})+ except ValueError as exc:+ return {+ "behavior": "deny",+ "message": f"Invalid questions ({exc}). Ask 1-4 questions with 2-4 options each.",+ }+ ask = getattr(handle.control_service, "ask_questions", None)+ if not callable(ask):+ return {+ "behavior": "deny",+ "message": "Nobody can answer here. Decide yourself and state your assumptions.",+ }+ try:+ answers = await ask(session.session_id, specs)+ except (TooManyQuestions, RuntimeError) as exc:+ # The turn already used its cards (or has none to show): the+ # agent's own first options stand, exactly as on an unanswered card.+ log.info("agent chat %s: question not shown (%s)", handle.turn_id, exc)+ answers = [recommended_answer(spec, UNATTENDED) for spec in specs]+ if any(a.source == CANCELLED for a in answers):+ return {"behavior": "deny", "message": "The turn was stopped."}+ picked = {+ str(row.get("question") or ""): a.answer for row, a in zip(rows, answers, strict=True)+ }+ return {"behavior": "allow", "updatedInput": {**tool_input, "answers": picked}}++ async def _leave_plan_mode() -> str:+ """The build mode an approved plan continues in, or "" to leave it to the CLI.++ Coding threads only (``turn_prompts``): the session leaves plan mode+ for the runner's default, so the next message builds too and the+ composer's access pick shows it.+ """+ from jarvis.agent_chat.surface_kits import kit_for++ if not kit_for(session.surface).turn_prompts:+ return ""+ build = default_permission(runner)+ store = getattr(handle.control_service, "store", None)+ if store is not None and build != session.permission_mode:+ store.update_session(session.session_id, permission_mode=build)+ await handle.emit(make_event("session_updated", {"permission_mode": build}))+ return build+async def _feed_stdin() -> None:if proc.stdin is None:returndiff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex 1abd025d07..edd4ffe084 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -32,11 +32,12 @@ from pathlib import Pathfrom typing import Any, Finalfrom jarvis.agent_chat import attachments as chat_attachments+from jarvis.agent_chat import turn_promptsfrom jarvis.agent_chat.approval_bridge import ChatApprovalBridgefrom jarvis.agent_chat.catalog import PROVIDER_ROWS, api_seat, offers, provider_rowfrom jarvis.agent_chat.effort import normalize_effortfrom jarvis.agent_chat.events import make_event-from jarvis.agent_chat.permissions import ladder_key, normalize_permission+from jarvis.agent_chat.permissions import default_permission, ladder_key, normalize_permissionfrom jarvis.agent_chat.questions import (CANCELLED,MAX_ASKS_PER_TURN,@@ -970,6 +971,16 @@ class AgentChatService:if fut is not None and not fut.done():fut.set_result("cancel")self._cancel_questions(session_id)+ if (+ kit.turn_prompts+ and origin.direct_user+ and control_runner is None+ and not native_goal+ ):+ try:+ await self._open_turn_prompts(session_id, turn_id, runner)+ except Exception: # noqa: BLE001 — a missing card leaves the reply readable+ log.exception("agent chat: end-of-turn card failed for %s", turn_id)if hasattr(self, "_controls"):await self._controls.turn_completed(session_id, turn_id, origin.user_text, origin.direct_user, read_only@@ -1511,6 +1522,167 @@ class AgentChatService:open_q.wake.set()questions.pop(qid, None)+ # ------------------------------------------------------------ end-of-turn cards++ #: How far back a finished turn's reply is looked for. The question block+ #: ends the reply, so the newest events always hold it.+ _TURN_PROMPT_TAIL: Final[int] = 2000++ def _turn_prompt_lock(self) -> asyncio.Lock:+ # Lazily: a service built without __init__ (test doubles) still works.+ lock: asyncio.Lock | None = getattr(self, "_prompt_lock", None)+ if lock is None:+ lock = asyncio.Lock()+ self._prompt_lock = lock+ return lock++ async def _open_turn_prompts(self, session_id: str, turn_id: str, runner: str) -> None:+ """After a coding agent's turn: its question card, else its plan card.++ A reply ending in a ``jarvis-ask`` block opens a deferred question+ card; a finished turn while the session is still in plan mode opens a+ plan card. Nothing waits on either — the answer is the next message.+ """+ events = self.store.list_events(session_id, tail=self._TURN_PROMPT_TAIL)+ status, text = turn_prompts.turn_reply(events, turn_id)+ if status != "done":+ return+ specs = turn_prompts.parse_ask_block(text)+ if specs:+ await self._emit(+ session_id,+ make_event(+ "question_required",+ {+ "turn_id": turn_id,+ "question_id": uuid.uuid4().hex,+ "asker": "",+ "questions": [spec.to_payload() for spec in specs],+ "deferred": True,+ },+ ),+ )+ return+ session = self.store.get_session(session_id)+ if session is None or session.permission_mode != "plan" or not text.strip():+ return+ build = default_permission(ladder_key(session.surface, runner))+ if build == "plan":+ return+ await self._emit(+ session_id,+ make_event("plan_ready", {"turn_id": turn_id, "build_mode": build}),+ )++ async def answer_turn_question(+ self,+ session_id: str,+ question_id: str,+ *,+ index: int = 0,+ option_index: int | None = None,+ text: str | None = None,+ ) -> bool:+ """The person's answer to one question of an end-of-turn card.++ False for an unknown, closed or already answered question; raises+ ``ValueError`` for an answer that does not fit. The last answer closes+ the card and sends the answers to the agent as the next message.+ """+ async with self._turn_prompt_lock():+ card = turn_prompts.open_ask(self.store.list_events(session_id), question_id)+ if card is None:+ return False+ try:+ answers = turn_prompts.answer(+ card, index, option_index=option_index, text=text+ )+ except IndexError:+ return False+ if any(a is None for a in answers):+ await self._emit(+ session_id,+ make_event(+ "question_progress",+ {+ "turn_id": card.turn_id,+ "question_id": question_id,+ "answers": [a.to_payload() if a else None for a in answers],+ },+ ),+ )+ return True+ final = [a for a in answers if a is not None]+ await self._resolve_turn_question(session_id, card, final)+ await self._send_turn_answer(session_id, card, final)+ return True++ async def skip_turn_question(self, session_id: str, question_id: str) -> bool:+ """The person closed an end-of-turn card: the agent's recommendations stand."""+ async with self._turn_prompt_lock():+ card = turn_prompts.open_ask(self.store.list_events(session_id), question_id)+ if card is None:+ return False+ final = turn_prompts.skipped(card)+ await self._resolve_turn_question(session_id, card, final)+ await self._send_turn_answer(session_id, card, final)+ return True++ async def _resolve_turn_question(+ self, session_id: str, card: turn_prompts.OpenAsk, answers: list[QuestionAnswer]+ ) -> None:+ await self._emit(+ session_id,+ make_event(+ "question_resolved",+ {+ "turn_id": card.turn_id,+ "question_id": card.question_id,+ "answers": [a.to_payload() for a in answers],+ },+ ),+ )++ async def _send_turn_answer(+ self, session_id: str, card: turn_prompts.OpenAsk, answers: list[QuestionAnswer]+ ) -> None:+ await self.send(+ session_id,+ turn_prompts.answers_prompt(card.specs, answers),+ display_text=turn_prompts.answers_display(card.specs, answers),+ )++ async def resolve_turn_plan(self, session_id: str, turn_id: str, decision: str) -> bool:+ """The person's answer to a plan card: ``build`` or ``keep``.++ ``build`` moves the session to the build mode the card offered and+ sends the go-ahead as the next message; ``keep`` only closes the card,+ so the person can tell the agent what to change. False when the card+ is not open (any more).+ """+ if decision not in turn_prompts.PLAN_DECISIONS:+ raise ValueError(f"decision must be one of {turn_prompts.PLAN_DECISIONS}")+ async with self._turn_prompt_lock():+ card = turn_prompts.open_plan(self.store.list_events(session_id), turn_id)+ if card is None:+ return False+ await self._emit(+ session_id,+ make_event("plan_resolved", {"turn_id": turn_id, "decision": decision}),+ )+ if decision == turn_prompts.PLAN_KEEP:+ return True+ session = self.store.get_session(session_id)+ build = card.build_mode+ if session is not None and build and session.permission_mode != build:+ self.store.update_session(session_id, permission_mode=build)+ await self._emit(+ session_id,+ make_event("session_updated", {"permission_mode": build}),+ )+ await self.send(session_id, turn_prompts.PLAN_GO_AHEAD)+ return True+__all__ = ["AgentChatService",diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.pyindex 3e31c85c63..a751b9a6ff 100644--- a/jarvis/agent_chat/surface_kits.py+++ b/jarvis/agent_chat/surface_kits.py@@ -108,6 +108,10 @@ class SurfaceKit:session_always_allow: SessionAlwaysAllow | None = Noneturn_completed: Callable[[Any, ChatCompletion], Awaitable[None]] | None = Nonehistory_start: Callable[[Any], int] | None = None+ #: End-of-turn cards for coding agents (``turn_prompts``): a ``jarvis-ask``+ #: block becomes a question card and a finished plan-mode turn a plan card,+ #: so every CLI can ask and have its plan approved, not only Claude Code.+ turn_prompts: bool = Falsedef _chat_workspace() -> Path:@@ -218,7 +222,7 @@ def _only_local_models(tools: dict[str, Tool]) -> dict[str, Tool]:# ── the table ─────────────────────────────────────────────────────────────_KITS: Final[dict[str, SurfaceKit]] = {- "agent": SurfaceKit(surface="agent"),+ "agent": SurfaceKit(surface="agent", turn_prompts=True),"jarvis": SurfaceKit(surface="jarvis",brain_runner=True,diff --git a/jarvis/agent_chat/turn_prompts.py b/jarvis/agent_chat/turn_prompts.pynew file mode 100644index 0000000000..eeee53904c--- /dev/null+++ b/jarvis/agent_chat/turn_prompts.py@@ -0,0 +1,272 @@+"""What a coding agent asks the person at the end of its turn — for every CLI.++Claude Code (and GLM, which runs its binary) can stop mid-turn and ask: its+control protocol hands Jarvis ``AskUserQuestion`` and ``ExitPlanMode``, and the+chat's cards answer them on stdin (``runner_cli``). Every other coding CLI —+Codex, Antigravity, Grok Build, OpenCode, Kimi, Cursor, DeepSeek Harness — runs+headless here, with no channel to ask on. Two end-of-turn prompts give all of+them the same two moments, without any vendor cooperation:++* **Questions.** The agent is told (:data:`ASK_PROTOCOL`, in front of every+ prompt) to end its reply with one fenced ``jarvis-ask`` block when a decision+ genuinely belongs to the person, and to stop there. When the turn finished,+ the service turns that block into the chat's ordinary question card+ (``question_required`` with ``deferred: true``). Nothing waits on it: the+ answers go back to the agent as the next message, and its vendor session+ resumes with the context it had.+* **Plan approval.** A turn that finished while the session is in plan mode+ gets a ``plan_ready`` card. *Build* switches the session to the runner's+ build mode and sends the go-ahead as the next message; *Keep planning* just+ closes the card. Claude's own ``ExitPlanMode`` still asks mid-turn; when it+ is approved the session leaves plan mode, so no second card follows.++Both cards are event-sourced. A card is open while its event has no closing+event and no later turn started — a reopened chat, or an app restart, answers+the same card the person sees.+"""++from __future__ import annotations++import json+import re+from collections.abc import Iterable, Sequence+from dataclasses import dataclass+from typing import Any, Final++from jarvis.agent_chat.questions import (+ PERSON,+ SKIPPED,+ QuestionAnswer,+ QuestionSpec,+ answer_from,+ parse_questions,+ recommended_answer,+)++#: The fence language of an end-of-turn question block. The frontend hides+#: these blocks from the rendered reply (``ASK_FENCE`` in+#: ``src/components/agentchat/askFence.ts``) — a parity test keeps both equal.+ASK_FENCE: Final[str] = "jarvis-ask"++#: In front of every prompt of a CLI that cannot ask mid-turn.+ASK_PROTOCOL: Final[str] = (+ "QUESTIONS FOR THE PERSON: decide everything you reasonably can yourself. "+ "Only when a decision genuinely belongs to the person (their taste, priorities, "+ "money, accounts, or an irreversible trade-off you cannot infer), end your reply "+ f"with exactly one fenced code block whose language is {ASK_FENCE}, containing "+ 'JSON like {"questions": [{"question": "Which database?", "options": '+ '[{"label": "SQLite", "description": "One file, no server"}, {"label": "Postgres", '+ '"description": "A server to run"}], "recommendation_reason": "Why the first '+ 'option wins"}]}. Ask 1-4 questions, each with 2-4 options, your recommendation '+ "first. Then stop and wait: the person answers in a card and their answers arrive "+ "as the next message. Never ask for permission to do what you were asked.\n\n"+)++#: What the agent is told when the person approved its plan.+PLAN_GO_AHEAD: Final[str] = (+ "The plan is approved. Implement it now, step by step, and report what you changed."+)++#: The answers to a plan card.+PLAN_BUILD: Final[str] = "build"+PLAN_KEEP: Final[str] = "keep"+PLAN_DECISIONS: Final[tuple[str, ...]] = (PLAN_BUILD, PLAN_KEEP)++_FENCE_RE: Final[re.Pattern[str]] = re.compile(+ r"```[ \t]*" + re.escape(ASK_FENCE) + r"[ \t]*\r?\n(?P<body>.*?)\r?\n?```",+ re.DOTALL,+)+++def parse_ask_block(text: str) -> tuple[QuestionSpec, ...] | None:+ """The questions of the reply's last ``jarvis-ask`` block, or ``None``.++ A block that is not valid JSON, or whose questions do not validate, is no+ question at all: the reply still reads as text and the person answers it in+ the composer, exactly as before this card existed.+ """+ matches = list(_FENCE_RE.finditer(text or ""))+ if not matches:+ return None+ try:+ payload = json.loads(matches[-1].group("body"))+ except ValueError:+ return None+ if isinstance(payload, list):+ payload = {"questions": payload}+ if not isinstance(payload, dict):+ return None+ try:+ return parse_questions(payload)+ except ValueError:+ return None+++def turn_reply(events: Iterable[dict[str, Any]], turn_id: str) -> tuple[str, str]:+ """``(status, text)`` of a finished turn: its ``turn_finished`` status and+ every finished text block it wrote, joined. ``("", ...)`` while unfinished."""+ status = ""+ parts: list[str] = []+ for event in events:+ payload = event.get("payload") or {}+ if payload.get("turn_id") != turn_id:+ continue+ kind = event.get("kind")+ if kind == "assistant_text":+ text = str(payload.get("text") or "")+ if text.strip():+ parts.append(text)+ elif kind == "turn_finished":+ status = str(payload.get("status") or "")+ return status, "\n\n".join(parts)+++@dataclass(frozen=True, slots=True)+class OpenAsk:+ """An end-of-turn question card that still waits for the person."""++ question_id: str+ turn_id: str+ specs: tuple[QuestionSpec, ...]+ answers: tuple[QuestionAnswer | None, ...]+++@dataclass(frozen=True, slots=True)+class OpenPlan:+ """A plan card that still waits for the person."""++ turn_id: str+ build_mode: str+++def _answers_from(raw: Any, count: int) -> list[QuestionAnswer | None]:+ rows = raw if isinstance(raw, list) else []+ out: list[QuestionAnswer | None] = []+ for index in range(count):+ row = rows[index] if index < len(rows) else None+ if not isinstance(row, dict):+ out.append(None)+ continue+ option = row.get("option_index")+ out.append(+ QuestionAnswer(+ str(row.get("answer") or ""),+ option if isinstance(option, int) else None,+ str(row.get("source") or PERSON),+ )+ )+ return out+++def open_ask(events: Sequence[dict[str, Any]], question_id: str) -> OpenAsk | None:+ """The deferred card ``question_id`` if it is still open, else ``None``."""+ found: OpenAsk | None = None+ answers: list[QuestionAnswer | None] = []+ for event in events:+ kind = event.get("kind")+ payload = event.get("payload") or {}+ if found is None:+ if (+ kind == "question_required"+ and payload.get("deferred")+ and payload.get("question_id") == question_id+ ):+ try:+ specs = parse_questions({"questions": payload.get("questions") or []})+ except ValueError:+ return None+ found = OpenAsk(question_id, str(payload.get("turn_id") or ""), specs, ())+ answers = [None] * len(specs)+ continue+ if kind == "turn_started":+ return None # the person moved on; the card closed with it+ if payload.get("question_id") != question_id:+ continue+ if kind == "question_resolved":+ return None+ if kind == "question_progress":+ answers = _answers_from(payload.get("answers"), len(found.specs))+ if found is None:+ return None+ return OpenAsk(found.question_id, found.turn_id, found.specs, tuple(answers))+++def open_plan(events: Sequence[dict[str, Any]], turn_id: str) -> OpenPlan | None:+ """The plan card of ``turn_id`` if it is still open, else ``None``."""+ found: OpenPlan | None = None+ for event in events:+ kind = event.get("kind")+ payload = event.get("payload") or {}+ if found is None:+ if kind == "plan_ready" and payload.get("turn_id") == turn_id:+ found = OpenPlan(turn_id, str(payload.get("build_mode") or ""))+ continue+ if kind == "turn_started":+ return None+ if kind == "plan_resolved" and payload.get("turn_id") == turn_id:+ return None+ return found+++def answer(+ card: OpenAsk, index: int, *, option_index: int | None, text: str | None+) -> list[QuestionAnswer | None]:+ """The card's answers with question ``index`` answered by the person.++ Raises ``ValueError`` for an answer that does not fit, ``IndexError`` for a+ question that does not exist or was already answered.+ """+ if not 0 <= index < len(card.specs) or card.answers[index] is not None:+ raise IndexError(index)+ answers = list(card.answers)+ answers[index] = answer_from(card.specs[index], option_index=option_index, text=text)+ return answers+++def skipped(card: OpenAsk) -> list[QuestionAnswer]:+ """Every open question left to the agent's recommendation."""+ return [+ a if a is not None else recommended_answer(spec, SKIPPED)+ for spec, a in zip(card.specs, card.answers, strict=True)+ ]+++def answers_prompt(specs: Sequence[QuestionSpec], answers: Sequence[QuestionAnswer]) -> str:+ """The next message the agent receives once the card closed."""+ lines = ["Answers to your questions:"]+ for spec, picked in zip(specs, answers, strict=True):+ if picked.source == SKIPPED:+ lines.append(+ f"- {spec.question} -> left to you; go with your recommendation ({picked.answer})."+ )+ else:+ lines.append(f"- {spec.question} -> {picked.answer}")+ lines.append("Continue with these answers.")+ return "\n".join(lines)+++def answers_display(specs: Sequence[QuestionSpec], answers: Sequence[QuestionAnswer]) -> str:+ """What the timeline shows as the person's message: the picks, in their words."""+ return "\n".join(+ f"{spec.question} — {picked.answer}" for spec, picked in zip(specs, answers, strict=True)+ )+++__all__ = [+ "ASK_FENCE",+ "ASK_PROTOCOL",+ "PLAN_BUILD",+ "PLAN_DECISIONS",+ "PLAN_GO_AHEAD",+ "PLAN_KEEP",+ "OpenAsk",+ "OpenPlan",+ "answer",+ "answers_display",+ "answers_prompt",+ "open_ask",+ "open_plan",+ "parse_ask_block",+ "skipped",+ "turn_reply",+]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex e3efaa168d..dd1f750bc9 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -918,25 +918,9 @@ def _behind_win_shim(spec: workspace_agents.WorkspaceAgent, shim: str) -> tuple[``cmd /c <shim>`` works and stays the fallback, but it wedges a secondprocess between the pane and the agent, which costs clean signal delivery- and a clean exit. When the entry declares where the real thing sits inside- the installed package we skip the shim entirely.-- Two shapes exist and the entry says which: a Node script that needs- ``node.exe`` in front of it, and a native executable that is simply run.- ``None`` whenever the declared path is not actually there — an install- laid out differently than expected must fall back, never fail.+ and a clean exit (:func:`jarvis.workspace.agents.behind_win_shim`)."""- if spec.win_shim is None:- return None- target = Path(shim).resolve().parent.joinpath(*spec.win_shim.relative_path)- if not target.is_file():- return None- if spec.win_shim.kind == "exe":- return (str(target),)- from jarvis.core.path_augment import resolve_node_executable-- node = resolve_node_executable()- return (node, str(target)) if node else None+ return workspace_agents.behind_win_shim(spec, shim)@dataclass(slots=True)diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex cd25756408..3135eb135d 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -16,6 +16,8 @@ Prefix ``/api/agent-chat``:POST /sessions/{id}/questions/{qid} {index, option_index} or {index, text} -> answerone question of an agent's cardPOST /sessions/{id}/questions/{qid}/skip close the card: recommendations apply+ POST /sessions/{id}/plan {turn_id, decision: build | keep} -> answer+ a coding agent's plan cardWS /sessions/{id}/ws?after=<seq> snapshot, then live eventsPOST /attachments drop/paste/pick files for the next messagePOST /pick-folder the system folder dialog (desktop only)@@ -269,6 +271,13 @@ class QuestionAnswerBody(BaseModel):text: str | None = None+class PlanBody(BaseModel):+ #: The turn whose plan card this answers.+ turn_id: str+ #: ``build`` (switch to the build mode and go) or ``keep`` (keep planning).+ decision: str++class PickFolderBody(BaseModel):start: str | None = None@@ -1117,8 +1126,20 @@ async def answer_question(option_index=body.option_index,text=body.text,)+ if not ok:+ # Not a card a running turn waits on: an end-of-turn card, whose+ # answers go to the agent as the next message.+ ok = await svc.answer_turn_question(+ session_id,+ question_id,+ index=body.index,+ option_index=body.option_index,+ text=body.text,+ )except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc+ except SessionBusy as exc:+ raise HTTPException(status_code=409, detail="session is busy") from excif not ok:raise HTTPException(status_code=404, detail="no such open question")return {"ok": True, "question_id": question_id}@@ -1130,11 +1151,34 @@ async def answer_question()async def skip_question(session_id: str, question_id: str, request: Request) -> dict[str, Any]:svc = _service(request)- if not svc.skip_question(session_id, question_id):+ try:+ ok = svc.skip_question(session_id, question_id) or await svc.skip_turn_question(+ session_id, question_id+ )+ except SessionBusy as exc:+ raise HTTPException(status_code=409, detail="session is busy") from exc+ if not ok:raise HTTPException(status_code=404, detail="no such open question")return {"ok": True, "question_id": question_id}+ "/sessions/{session_id}/plan",+ summary="Answer a coding agent's plan card: build it, or keep planning",+)+async def resolve_plan(session_id: str, body: PlanBody, request: Request) -> dict[str, Any]:+ svc = _service(request)+ try:+ ok = await svc.resolve_turn_plan(session_id, body.turn_id, body.decision)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except SessionBusy as exc:+ raise HTTPException(status_code=409, detail="session is busy") from exc+ if not ok:+ raise HTTPException(status_code=404, detail="no such open plan")+ return {"ok": True, "turn_id": body.turn_id, "decision": body.decision}++# ------------------------------------------------------------------ attachmentsdiff --git a/jarvis/ui/web/frontend/src/components/agentchat/askFence.ts b/jarvis/ui/web/frontend/src/components/agentchat/askFence.tsnew file mode 100644index 0000000000..d1134485e8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/askFence.ts@@ -0,0 +1,19 @@+/**+ * A coding agent's end-of-turn question block (jarvis/agent_chat/turn_prompts.py).+ *+ * A CLI with no way to ask mid-turn ends its reply with one fenced block in+ * this language; the server turns it into the chat's question card. The reply+ * shows without it — the card already asks — including while the block is+ * still streaming in. The fence name is pinned to the server's by a parity+ * test (tests/unit/agent_chat/test_turn_prompts.py).+ */+export const ASK_FENCE = "jarvis-ask";++const COMPLETE = new RegExp("```[ \\t]*" + ASK_FENCE + "[ \\t]*\\r?\\n[\\s\\S]*?```", "g");+const STREAMING = new RegExp("```[ \\t]*" + ASK_FENCE + "[\\s\\S]*$");++/** The reply without its question blocks, finished or still arriving. */+export function hideAskBlocks(text: string): string {+ if (!text.includes(ASK_FENCE)) return text;+ return text.replace(COMPLETE, "").replace(STREAMING, "").replace(/\n{3,}/g, "\n\n").trimEnd();+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.tsindex b61703c835..e5ab114eb4 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts@@ -1,5 +1,6 @@import type { AgentChatEvent, InternalMessage } from "@/lib/agentChatApi";import type { ChatControlState } from "@/lib/chatControlApi";+import { hideAskBlocks } from "./askFence";import { readToolChoices, type ToolChoice } from "./toolChoices";/**@@ -21,7 +22,10 @@ import { readToolChoices, type ToolChoice } from "./toolChoices";export interface TextBlock {kind: "text";id: string;+ /** What the reply shows: the agent's text without an end-of-turn question block. */text: string;+ /** The text as the agent wrote it, kept only when a question block was hidden from it. */+ raw?: string;}export interface ReasoningBlock {@@ -82,13 +86,31 @@ export interface QuestionState {expiresMs: number | null;/** The card no longer takes answers (resolved, or the turn ended). */closed: boolean;+ /**+ * An end-of-turn card (jarvis/agent_chat/turn_prompts.py): the agent already+ * stopped, and the answers go to it as the next message. It stays open after+ * its turn ended and closes when the person starts another turn instead.+ */+ deferred?: boolean;}/** The tool an agent asks its question with — bare or behind an MCP prefix. */export const QUESTION_TOOL = "society_ask_user";+/** Claude Code's own question tool, answered on the same card. */+export const CLAUDE_QUESTION_TOOL = "AskUserQuestion";export function isQuestionTool(name: string): boolean {- return name === QUESTION_TOOL || name.endsWith(`__${QUESTION_TOOL}`);+ return name === QUESTION_TOOL || name.endsWith(`__${QUESTION_TOOL}`) || name === CLAUDE_QUESTION_TOOL;+}++/**+ * A coding agent's plan card (jarvis/agent_chat/turn_prompts.py): the turn+ * finished in plan mode. `decision` is `build`, `keep`, `superseded` (the+ * person started another turn instead) or `null` while it waits.+ */+export interface PlanState {+ buildMode: string;+ decision: string | null;}export interface ToolBlock {@@ -161,6 +183,8 @@ export interface TurnItem {liveUsage: Record<string, number> | null;costUsd: number | null;error: string | null;+ /** The plan card of a turn that finished in plan mode. */+ plan?: PlanState;}export interface ErrorItem {@@ -334,6 +358,46 @@ function updateQuestion(}/** Attach a question to its tool row: the open ask call, else a row of its own. */+/** A text block whose question block, if any, is hidden behind its card. */+function textBlock(id: string, raw: string): TextBlock {+ const text = hideAskBlocks(raw);+ return text === raw ? { kind: "text", id, text } : { kind: "text", id, text, raw };+}++/**+ * A new turn settles the cards the last one left waiting: an end-of-turn+ * question nobody answered and a plan nobody approved. The person moved on —+ * the server no longer takes answers for them either.+ */+function settleWaitingCards(items: TimelineItem[]): TimelineItem[] {+ let changed = false;+ const next = items.map((item) => {+ if (item.type !== "turn") return item;+ const openPlan = item.plan && item.plan.decision === null;+ const openAsk = item.blocks.some((b) => b.kind === "tool" && b.question?.deferred && !b.question.closed);+ if (!openPlan && !openAsk) return item;+ changed = true;+ return {+ ...item,+ ...(openPlan && item.plan ? { plan: { ...item.plan, decision: "superseded" } } : {}),+ blocks: openAsk+ ? item.blocks.map((b) =>+ b.kind === "tool" && b.question?.deferred && !b.question.closed+ ? {+ ...b,+ question: {+ ...b.question,+ closed: true,+ answers: b.question.answers.map((a) => a ?? { text: "", optionIndex: null, source: "closed" }),+ },+ }+ : b)+ : item.blocks,+ };+ });+ return changed ? next : items;+}+function withQuestion(turn: TurnItem, question: QuestionState, tsMs: number): TurnItem {let index = -1;for (let i = turn.blocks.length - 1; i >= 0; i -= 1) {@@ -439,7 +503,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {return {...base,items: [- ...base.items,+ ...settleWaitingCards(base.items),{type: "turn",id: turnId,@@ -467,7 +531,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {upsertBlock<TextBlock>(closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "text" && b.id === id,- (ex) => ({ kind: "text", id, text: (ex?.text ?? "") + delta }),+ (ex) => textBlock(id, (ex?.raw ?? ex?.text ?? "") + delta),),);}@@ -479,7 +543,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {upsertBlock<TextBlock>(closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "text" && b.id === id,- (ex) => (ex && ex.text === text ? ex : { kind: "text", id, text }),+ (ex) => (ex && (ex.raw ?? ex.text) === text ? ex : textBlock(id, text)),),);}@@ -717,6 +781,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {answers: questions.map(() => null),expiresMs: num(p.expires_ms),closed: false,+ ...(p.deferred ? { deferred: true } : {}),};return updateTurn(base, turnId, (turn) => withQuestion(turn, question, ev.ts_ms));}@@ -776,6 +841,17 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {};}+ case "plan_ready":+ return updateTurn(base, turnId, (turn) => ({+ ...turn,+ plan: { buildMode: str(p.build_mode), decision: null },+ }));++ case "plan_resolved":+ return updateTurn(base, turnId, (turn) =>+ turn.plan ? { ...turn, plan: { ...turn.plan, decision: str(p.decision) || "keep" } } : turn,+ );+case "session_updated":return { ...base, sessionPatch: { ...p } };diff --git a/jarvis/ui/web/frontend/src/components/agentchat/turnPrompts.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/turnPrompts.test.tsnew file mode 100644index 0000000000..64b82a4879--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/turnPrompts.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";++import type { AgentChatEvent } from "@/lib/agentChatApi";+import { ASK_FENCE, hideAskBlocks } from "./askFence";+import { EMPTY_TIMELINE, reduceEvents, type TextBlock, type ToolBlock, type TurnItem } from "./reduce";++let seq = 0;+function ev(kind: string, payload: Record<string, unknown>, persisted = true): AgentChatEvent {+ if (persisted) seq += 1;+ return { seq: persisted ? seq : 0, ts_ms: 1_000 + seq, kind, payload };+}++const QUESTIONS = [{ question: "Which database?", options: [{ label: "SQLite" }, { label: "Postgres" }] }];+const BLOCK = `\`\`\`${ASK_FENCE}\n${JSON.stringify({ questions: QUESTIONS })}\n\`\`\``;++function turn(tl: { items: unknown[] }, index = 1): TurnItem {+ return tl.items[index] as TurnItem;+}++describe("end-of-turn cards", () => {+ it("hides the question block from the reply, also while it streams in", () => {+ expect(hideAskBlocks(`Two choices.\n\n${BLOCK}\n`)).toBe("Two choices.");+ expect(hideAskBlocks(`Two choices.\n\n\`\`\`${ASK_FENCE}\n{"questions": [`)).toBe("Two choices.");+ expect(hideAskBlocks("```json\n{}\n```")).toBe("```json\n{}\n```");++ const tl = reduceEvents(EMPTY_TIMELINE, [+ ev("turn_started", { turn_id: "t1" }),+ ev("text_delta", { turn_id: "t1", message_id: "m1", text: "Two choices.\n\n```jarvis-a" }, false),+ ev("text_delta", { turn_id: "t1", message_id: "m1", text: "sk\n{\"questions\":" }, false),+ ]);+ const live = turn(tl, 0).blocks[0] as TextBlock;+ expect(live.text).toBe("Two choices.");+ const done = reduceEvents(tl, [+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: `Two choices.\n\n${BLOCK}` }),+ ]);+ expect((turn(done, 0).blocks[0] as TextBlock).text).toBe("Two choices.");+ });++ it("keeps a deferred card open after its turn and settles it when another turn starts", () => {+ const tl = reduceEvents(EMPTY_TIMELINE, [+ ev("user_message", { text: "set it up" }),+ ev("turn_started", { turn_id: "t1" }),+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Two choices." }),+ ev("turn_finished", { turn_id: "t1", status: "done" }),+ ev("question_required", { turn_id: "t1", question_id: "q1", questions: QUESTIONS, deferred: true }),+ ]);+ const card = turn(tl).blocks.find((b): b is ToolBlock => b.kind === "tool")?.question;+ expect(card).toMatchObject({ questionId: "q1", deferred: true, closed: false });++ const moved = reduceEvents(tl, [ev("user_message", { text: "never mind" }), ev("turn_started", { turn_id: "t2" })]);+ const settled = turn(moved).blocks.find((b): b is ToolBlock => b.kind === "tool")?.question;+ expect(settled).toMatchObject({ closed: true, answers: [{ source: "closed" }] });+ });++ it("attaches Claude's own question tool to its card", () => {+ const tl = reduceEvents(EMPTY_TIMELINE, [+ ev("turn_started", { turn_id: "t1" }),+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: "AskUserQuestion", input: { questions: QUESTIONS } }),+ ev("question_required", { turn_id: "t1", question_id: "q1", questions: QUESTIONS }),+ ]);+ const tools = turn(tl, 0).blocks.filter((b): b is ToolBlock => b.kind === "tool");+ expect(tools).toHaveLength(1);+ expect(tools[0]).toMatchObject({ callId: "c1", question: { questionId: "q1" } });+ });++ it("carries a plan card until the person answers it or moves on", () => {+ const tl = reduceEvents(EMPTY_TIMELINE, [+ ev("turn_started", { turn_id: "t1" }),+ ev("turn_finished", { turn_id: "t1", status: "done" }),+ ev("plan_ready", { turn_id: "t1", build_mode: "auto" }),+ ]);+ expect(turn(tl, 0).plan).toEqual({ buildMode: "auto", decision: null });+ expect(turn(reduceEvents(tl, [ev("plan_resolved", { turn_id: "t1", decision: "build" })]), 0).plan)+ .toEqual({ buildMode: "auto", decision: "build" });+ expect(turn(reduceEvents(tl, [ev("turn_started", { turn_id: "t2" })]), 0).plan)+ .toEqual({ buildMode: "auto", decision: "superseded" });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsxindex 6d8b850798..4bd3eb9f41 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx@@ -1,15 +1,16 @@import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";-import { ArrowUp, Loader2, MessageCircleQuestion, ShieldAlert, Square, X } from "lucide-react";+import { ArrowUp, Hammer, ListChecks, Loader2, MessageCircleQuestion, ShieldAlert, Square, X } from "lucide-react";import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";import { ComposerTypeahead } from "@/components/agentchat/ComposerTypeahead";import { DictationButton } from "@/components/agentchat/DictationButton";-import { runningTurn, type QuestionState, type Timeline, type ToolBlock } from "@/components/agentchat/reduce";+import { runningTurn, type QuestionState, type Timeline, type ToolBlock, type TurnItem } from "@/components/agentchat/reduce";import { useChatAttachments } from "@/components/agentchat/useChatAttachments";import { useComposerDictation } from "@/components/agentchat/useComposerDictation";import { useComposerTypeahead } from "@/components/agentchat/useComposerTypeahead";import { useT } from "@/i18n";-import type { ChatAttachment } from "@/lib/agentChatApi";-import { joinProviderOptions, type ComposerDraft } from "@/store/agentChat";+import type { ChatAttachment, PlanDecision } from "@/lib/agentChatApi";+import { joinProviderOptions, type ComposerDraft, type ProviderOption } from "@/store/agentChat";import { cn } from "@/lib/utils";import { AccessPicker, AgentModelPicker, EffortPicker } from "./ThreadPickers";import { rememberSeat, rememberedSeat, threadAgents, useThreadChatStore } from "./threadModel";@@ -39,27 +40,89 @@ function openQuestion(timeline: Timeline): { block: ToolBlock; question: Questioreturn null;}+const PLAN_PROSE = cn(+ "prose prose-neutral max-w-none text-sm leading-6 text-foreground dark:prose-invert dark:text-foreground [overflow-wrap:anywhere]",+ "prose-p:my-1.5 prose-p:text-foreground prose-li:text-foreground prose-headings:text-foreground-strong prose-strong:text-foreground-strong",+ "[&>div>:first-child]:mt-0 [&>div>:last-child]:mb-0",+);+function ApprovalPanel({ timeline, onDecide }: { timeline: Timeline; onDecide: (id: string, decision: "allow" | "allow_always" | "deny") => void }) {const pending = timeline.pendingApprovals[0];if (!pending) return null;const input = pending.input && typeof pending.input === "object" ? pending.input as Record<string, unknown> : {};- const detail = String(input.command ?? input.file_path ?? input.path ?? input.url ?? "");+ // Claude Code's finished plan asks here too, and the plan itself is what gets approved.+ const isPlan = pending.name === "ExitPlanMode";+ const plan = isPlan ? String(input.plan ?? "").trim() : "";+ const detail = isPlan ? "" : String(input.command ?? input.file_path ?? input.path ?? input.url ?? "");return <div data-testid="thread-approval" className="border-b border-border px-4 py-3"><div className="flex items-start gap-2.5">- <ShieldAlert aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-warning" />+ {isPlan+ ? <ListChecks aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-accent" />+ : <ShieldAlert aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-warning" />}<div className="min-w-0 flex-1">- <p className="text-sm font-medium text-foreground-strong">Approval needed{timeline.pendingApprovals.length > 1 ? ` (${timeline.pendingApprovals.length})` : ""}</p>- <p className="mt-0.5 text-sm text-muted-foreground">{pending.summary || pending.name}</p>+ <p className="text-sm font-medium text-foreground-strong">{isPlan ? "Plan ready" : "Approval needed"}{timeline.pendingApprovals.length > 1 ? ` (${timeline.pendingApprovals.length})` : ""}</p>+ <p className="mt-0.5 text-sm text-muted-foreground">{isPlan ? "Build it, or keep planning and say what to change." : pending.summary || pending.name}</p>+ {plan && <div data-testid="thread-approval-plan" className={cn("mt-2 max-h-72 overflow-auto rounded-md bg-secondary px-3 py-2 scrollbar-jarvis", PLAN_PROSE)}><ChatMarkdown text={plan} /></div>}{detail && <pre className="mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded-md bg-secondary px-2.5 py-1.5 font-mono text-xs text-foreground scrollbar-jarvis">{detail}</pre>}</div></div><div className="mt-3 flex flex-wrap justify-end gap-2"><button type="button" onClick={() => onDecide(pending.approvalId, "deny")}- className="rounded-lg px-3 py-1.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Decline</button>- <button type="button" onClick={() => onDecide(pending.approvalId, "allow_always")}- className="rounded-lg border border-border px-3 py-1.5 text-sm text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Always allow</button>+ className="rounded-lg px-3 py-1.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">{isPlan ? "Keep planning" : "Decline"}</button>+ {!isPlan && <button type="button" onClick={() => onDecide(pending.approvalId, "allow_always")}+ className="rounded-lg border border-border px-3 py-1.5 text-sm text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Always allow</button>}<button type="button" data-testid="thread-approve" onClick={() => onDecide(pending.approvalId, "allow")}- className="rounded-lg bg-accent px-3 py-1.5 text-sm font-medium text-accent-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Approve</button>+ className="rounded-lg bg-accent px-3 py-1.5 text-sm font-medium text-accent-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">{isPlan ? "Build it" : "Approve"}</button>+ </div>+ </div>;+}++/** The newest turn, when it is the timeline's last item and its plan card still waits. */+function waitingPlan(timeline: Timeline): TurnItem | null {+ const last = timeline.items[timeline.items.length - 1];+ return last && last.type === "turn" && last.plan && last.plan.decision === null ? last : null;+}++/**+ * Any coding agent's finished plan (jarvis/agent_chat/turn_prompts.py): build+ * it in the runner's build mode, or keep planning and type what to change.+ */+function PlanPanel({ timeline, provider }: { timeline: Timeline; provider: ProviderOption | null }) {+ const turn = waitingPlan(timeline);+ const [sending, setSending] = useState(false);+ const [error, setError] = useState("");+ if (!turn?.plan) return null;+ const buildMode = turn.plan.buildMode;+ const mode = provider?.permission_modes?.find((row) => row.id === buildMode);+ const decide = async (decision: PlanDecision) => {+ setSending(true);+ setError("");+ try {+ await useThreadChatStore.getState().resolvePlan(turn.id, decision);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSending(false);+ }+ };+ return <div data-testid="thread-plan" className="border-b border-border px-4 py-3">+ <div className="flex items-start gap-2.5">+ <ListChecks aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-accent" />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-foreground-strong">Plan ready</p>+ <p className="mt-0.5 text-sm text-muted-foreground">+ {mode ? `Build it switches access to ${mode.label} and starts building.` : "Build it starts building."} Or keep planning and type what to change.+ </p>+ {error && <p role="alert" className="mt-1 text-xs text-destructive">{error}</p>}+ </div>+ </div>+ <div className="mt-3 flex flex-wrap justify-end gap-2">+ <button type="button" disabled={sending} onClick={() => void decide("keep")}+ className="rounded-lg px-3 py-1.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Keep planning</button>+ <button type="button" data-testid="thread-plan-build" disabled={sending} onClick={() => void decide("build")}+ className="flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-sm font-medium text-accent-foreground hover:opacity-90 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Hammer aria-hidden className="h-3.5 w-3.5" />Build it+ </button></div></div>;}@@ -342,6 +405,7 @@ export function ThreadComposer({)}><ApprovalPanel timeline={timeline} onDecide={decide} /><QuestionPanel timeline={timeline} />+ {!running && <PlanPanel timeline={timeline} provider={provider} />}{(files.attachments.length > 0 || files.analyzing > 0) && <div className="px-3 pt-3 sm:px-4"><ChatAttachmentStrip attachments={files.attachments} analyzing={files.analyzing}onRemove={files.remove} previews={files.previews} look="thumbnail" />diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPrompts.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPrompts.test.tsxnew file mode 100644index 0000000000..1df2698c75--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPrompts.test.tsx@@ -0,0 +1,151 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AgentChatCatalog, AgentChatEvent, AgentChatSession } from "@/lib/agentChatApi";+import type { IdeProject } from "@/lib/agenticIdeApi";+import { useIdeProjectsStore } from "@/store/ideProjects";+import { useIdeThreadsStore } from "@/store/ideThreads";++const api = vi.hoisted(() => ({+ fetchAgentChatCatalog: vi.fn(),+ fetchAgentConnections: vi.fn(),+ fetchProviderHealth: vi.fn(),+ fetchAgentChatSessions: vi.fn(),+ answerAgentChatQuestion: vi.fn(),+ resolveAgentChatPlan: vi.fn(),+ resolveAgentChatApproval: vi.fn(),+}));+vi.mock("@/lib/agentChatApi", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/agentChatApi")>()), ...api }));+vi.mock("@/lib/gitApi", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/gitApi")>()),+ inspectGit: vi.fn().mockResolvedValue({ is_repo: false, branches: [], changes: [], remotes: [] }),+ prepareGit: vi.fn(),+}));+vi.mock("@/lib/chatLibraryApi", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/chatLibraryApi")>()),+ fetchProjectLaunchers: vi.fn().mockResolvedValue({ file_manager: true, editors: [], remote_url: null, remote_label: null }),+}));++import { ThreadView } from "./ThreadView";+import { useThreadChatStore } from "./threadModel";++class FakeSocket {+ onopen: (() => void) | null = null;+ onmessage: ((msg: { data: string }) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;+ constructor(readonly url: string) {}+ close() { /* frames are driven by hand */ }+}++const CATALOG: AgentChatCatalog = {+ default_cwd: "/home",+ shell: "bash",+ selection: null,+ providers: [{+ id: "openai-codex", label: "OpenAI Codex", family: "openai", runner: "codex-cli", agent: "codex",+ models_source: "curated", curated_models: [], default_model: "",+ keyless: false, native_resume: true, effort_levels: ["high"], default_effort: "high",+ permission_modes: [{ id: "auto", label: "Auto", description: "" }, { id: "plan", label: "Plan", description: "" }],+ default_permission_mode: "auto", cli_installed: true, typeahead: [],+ }],+} as AgentChatCatalog;++const project = { id: "p1", path: "/repo", name: "App", color: null, pinned: false, archived: false, scratch: false,+ created_at: 0, last_opened_at: 0, exists: true, chats: 0, workspaces: [] } as IdeProject;++function sessionRow(extra: Partial<AgentChatSession> = {}): AgentChatSession {+ return { session_id: "s1", title: "add a database", provider: "openai-codex", model: "", effort: "high", cwd: "/repo",+ permission_mode: "plan", surface: "agent", vendor_session: null, created_ms: 1, updated_ms: 2, message_count: 1, preview: "", ...extra };+}++let seq = 0;+function feed(events: [string, Record<string, unknown>][]): void {+ const store = useThreadChatStore.getState();+ act(() => {+ for (const [kind, payload] of events) {+ seq += 1;+ store.ingest({ seq, ts_ms: 1000 + seq, kind, payload } as AgentChatEvent);+ }+ });+}++async function openThread(): Promise<void> {+ useIdeThreadsStore.setState({ selection: { projectId: "p1", sessionId: "s1" } });+ api.fetchAgentChatSessions.mockResolvedValue([sessionRow()]);+ render(<ThreadView onScreen />);+ await waitFor(() => expect(useThreadChatStore.getState().activeSessionId).toBe("s1"));+ feed([+ ["user_message", { text: "add a database" }],+ ["turn_started", { turn_id: "t1", provider: "openai-codex", model: "", effort: "high", runner: "codex-cli" }],+ ]);+}++beforeEach(() => {+ localStorage.clear();+ vi.stubGlobal("WebSocket", FakeSocket);+ api.fetchAgentChatCatalog.mockReset().mockResolvedValue(CATALOG);+ api.fetchAgentConnections.mockReset().mockResolvedValue([]);+ api.fetchProviderHealth.mockReset().mockResolvedValue([]);+ api.fetchAgentChatSessions.mockReset().mockResolvedValue([]);+ api.answerAgentChatQuestion.mockReset().mockResolvedValue(undefined);+ api.resolveAgentChatPlan.mockReset().mockResolvedValue(undefined);+ api.resolveAgentChatApproval.mockReset().mockResolvedValue(undefined);+ useIdeProjectsStore.setState({ projects: [project], activeWorkspaceId: null });+ useIdeThreadsStore.setState({ layout: "threads", selection: { projectId: "p1", sessionId: null }, projectOf: {}, seen: {}, archived: {}, order: {}, focusNonce: 0 });+ useThreadChatStore.getState().newChat();+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("a coding agent's questions and plans in a thread", () => {+ it("asks an end-of-turn question on the composer's card and keeps the reply readable", async () => {+ await openThread();+ feed([+ ["assistant_text", { turn_id: "t1", message_id: "m1", text: "I need one decision.\n\n```jarvis-ask\n{\"questions\": []}\n```" }],+ ["turn_finished", { turn_id: "t1", status: "done", duration_ms: 1000 }],+ ["question_required", {+ turn_id: "t1", question_id: "q1", deferred: true,+ questions: [{ question: "Which database?", options: [{ label: "SQLite" }, { label: "Postgres" }] }],+ }],+ ]);+ expect(screen.getByText("I need one decision.")).toBeTruthy();+ expect(screen.queryByText(/jarvis-ask/)).toBeNull();+ expect(screen.getByTestId("thread-question").textContent).toContain("Which database?");+ await act(async () => { fireEvent.click(screen.getByText("Postgres")); });+ expect(api.answerAgentChatQuestion).toHaveBeenCalledWith("s1", "q1", 0, { optionIndex: 1 });+ });++ it("offers to build a finished plan in the agent's build mode", async () => {+ await openThread();+ feed([+ ["assistant_text", { turn_id: "t1", message_id: "m1", text: "1. Add the table\n2. Wire the route" }],+ ["turn_finished", { turn_id: "t1", status: "done", duration_ms: 1000 }],+ ["plan_ready", { turn_id: "t1", build_mode: "auto" }],+ ]);+ const card = await screen.findByTestId("thread-plan");+ expect(card.textContent).toContain("switches access to Auto");+ await act(async () => { fireEvent.click(screen.getByTestId("thread-plan-build")); });+ expect(api.resolveAgentChatPlan).toHaveBeenCalledWith("s1", "t1", "build");+ feed([["plan_resolved", { turn_id: "t1", decision: "build" }]]);+ expect(screen.queryByTestId("thread-plan")).toBeNull();+ });++ it("shows Claude's plan on its approval card, without an always-allow", async () => {+ await openThread();+ feed([+ ["approval_required", {+ turn_id: "t1", approval_id: "a1", call_id: "c1", name: "ExitPlanMode",+ input: { plan: "## Steps\n\n1. Add the table" }, summary: "Plan ready — approve to start building",+ }],+ ]);+ const card = screen.getByTestId("thread-approval");+ expect(card.textContent).toContain("Plan ready");+ expect(screen.getByTestId("thread-approval-plan").textContent).toContain("Add the table");+ expect(screen.queryByText("Always allow")).toBeNull();+ await act(async () => { fireEvent.click(screen.getByTestId("thread-approve")); });+ expect(api.resolveAgentChatApproval).toHaveBeenCalledWith("s1", "a1", "allow");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsxindex a2772f0f22..a368709301 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx@@ -551,11 +551,13 @@ function pendingLabel(block: ToolBlock): { icon: ReactNode; text: string } | nul/*** A finished turn read the short way: everything up to its last step folds* behind one "Worked for …" line, and the text written after that step — the- * answer — stays in view. A turn with no step at all has nothing to fold.+ * answer — stays in view. A turn with no step at all has nothing to fold. A+ * card the turn ended on (an end-of-turn question) is no step: it stays with+ * the answer it belongs to.*/export function foldFinished(rows: ThreadRow[]): { work: ThreadRow[]; answer: ThreadRow[] } {let last = -1;- rows.forEach((row, index) => { if (row.kind !== "text") last = index; });+ rows.forEach((row, index) => { if (row.kind === "work") last = index; });return { work: rows.slice(0, last + 1), answer: rows.slice(last + 1) };}diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex 368ecb57b8..2c970402df 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -604,6 +604,25 @@ export async function skipAgentChatQuestion(sessionId: string, questionId: strin);}+/** A coding agent's plan card: `build` switches to building and sends the go-ahead. */+export type PlanDecision = "build" | "keep";++/** Answer the plan card of `turnId`. */+export async function resolveAgentChatPlan(+ sessionId: string,+ turnId: string,+ decision: PlanDecision,+): Promise<void> {+ await json(+ await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/plan`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ turn_id: turnId, decision }),+ }),+ "plan-failed",+ );+}+export async function pickAgentChatFolder(start?: string): Promise<string | null> {const data = await json<{ path: string | null; cancelled: boolean }>(await fetch("/api/agent-chat/pick-folder", {diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.tsindex f4a84c5efc..8209f1edcb 100644--- a/jarvis/ui/web/frontend/src/store/agentChat.ts+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts@@ -17,6 +17,8 @@ import {answerAgentChatQuestion,bindVoiceChat,skipAgentChatQuestion,+ resolveAgentChatPlan,+ type PlanDecision,type QuestionAnswerInput,sendAgentChatMessage,saveChatSelection,@@ -180,6 +182,8 @@ export interface AgentChatStore {answerQuestion: (questionId: string, index: number, answer: QuestionAnswerInput) => Promise<void>;/** Close an agent's card so its recommendations apply; throws so the card can say why. */skipQuestion: (questionId: string) => Promise<void>;+ /** Answer a coding agent's plan card in the active session; throws so the card can say why. */+ resolvePlan: (turnId: string, decision: PlanDecision) => Promise<void>;/** Tests and the socket: fold one event into the active timeline. */ingest: (event: AgentChatEvent) => void;disconnect: () => void;@@ -830,6 +834,12 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =await skipAgentChatQuestion(sid, questionId);},+ resolvePlan: async (turnId, decision) => {+ const sid = get().activeSessionId;+ if (!sid) throw new Error("no open chat");+ await resolveAgentChatPlan(sid, turnId, decision);+ },+ingest: (event) => {const st = get();const tl = reduceEvent(st.timeline, event);diff --git a/jarvis/ui/web/frontend/src/store/newPaneChat.ts b/jarvis/ui/web/frontend/src/store/newPaneChat.tsindex 9007062ff7..d1b9d95c6f 100644--- a/jarvis/ui/web/frontend/src/store/newPaneChat.ts+++ b/jarvis/ui/web/frontend/src/store/newPaneChat.ts@@ -265,6 +265,7 @@ export function createNewPaneChatStore(options: NewPaneChatOptions) {decide: async () => undefined,answerQuestion: async () => undefined,skipQuestion: async () => undefined,+ resolvePlan: async () => undefined,ingest: () => undefined,disconnect: () => undefined,};diff --git a/jarvis/ui/web/frontend/src/store/paneChat.ts b/jarvis/ui/web/frontend/src/store/paneChat.tsindex 2d3f5b3d5e..6a48217dd3 100644--- a/jarvis/ui/web/frontend/src/store/paneChat.ts+++ b/jarvis/ui/web/frontend/src/store/paneChat.ts@@ -684,6 +684,7 @@ export function createPaneChatStore(options: PaneChatStoreOptions) {decide: async () => undefined,answerQuestion: async () => undefined,skipQuestion: async () => undefined,+ resolvePlan: async () => undefined,ingest: (event: AgentChatEvent) => set({ timeline: reduceEvent(get().timeline, event) }),disconnect: () => get().stop(),diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.pyindex 6c11401389..6b5f406e09 100644--- a/jarvis/workspace/agents.py+++ b/jarvis/workspace/agents.py@@ -35,6 +35,7 @@ import sysimport timefrom collections.abc import Callablefrom dataclasses import dataclass+from pathlib import Pathfrom typing import Any, Literalfrom jarvis.clis.prober import CliStatusProber@@ -1264,6 +1265,33 @@ def get_agent(name: str) -> WorkspaceAgent | None:return _registry().get(name)+def behind_win_shim(spec: WorkspaceAgent, shim: str) -> tuple[str, ...] | None:+ """What the Windows ``.cmd`` shim would have launched, launched directly.++ Going through the shim means going through ``cmd.exe``, which wedges a+ second process between the caller and the agent and re-parses every+ argument: a line break ends the command there, so a multi-line prompt on+ argv arrives cut after its first line. When the entry declares where the+ real thing sits inside the installed package we skip the shim entirely.++ Two shapes exist and the entry says which: a Node script that needs+ ``node.exe`` in front of it, and a native executable that is simply run.+ ``None`` whenever the declared path is not actually there — an install+ laid out differently than expected must fall back, never fail.+ """+ if spec.win_shim is None:+ return None+ target = Path(shim).resolve().parent.joinpath(*spec.win_shim.relative_path)+ if not target.is_file():+ return None+ if spec.win_shim.kind == "exe":+ return (str(target),)+ from jarvis.core.path_augment import resolve_node_executable++ node = resolve_node_executable()+ return (node, str(target)) if node else None++def agent_names() -> tuple[str, ...]:"""Every registered name, plain terminal included."""return tuple(_registry())diff --git a/tests/unit/agent_chat/test_ide_cli_seats.py b/tests/unit/agent_chat/test_ide_cli_seats.pyindex 1a37c9aa33..a258612ab7 100644--- a/tests/unit/agent_chat/test_ide_cli_seats.py+++ b/tests/unit/agent_chat/test_ide_cli_seats.py@@ -360,7 +360,9 @@ def test_plan_kimi_prints_json_and_finds_its_session_afterwards(stubbed: None) -)assert plan.argv[:3] == ["kimi", "--output-format", "stream-json"]assert plan.argv[plan.argv.index("--model") + 1] == "k2"- assert "--auto" in plan.argv+ # Kimi Code refuses --auto / --yolo / --plan next to --prompt; print mode+ # is autonomous on its own.+ assert not {"--auto", "--yolo", "--plan"} & set(plan.argv)assert plan.argv[-2:] == ["--prompt", "hi"]assert plan.shape == "kimi" and plan.env["AGENT"] == "kimi"# Fresh conversation: the id is looked up in Kimi's store afterwards.diff --git a/tests/unit/agent_chat/test_turn_prompts.py b/tests/unit/agent_chat/test_turn_prompts.pynew file mode 100644index 0000000000..85d14a6691--- /dev/null+++ b/tests/unit/agent_chat/test_turn_prompts.py@@ -0,0 +1,531 @@+"""Every coding agent can ask and have its plan approved (jarvis/agent_chat/turn_prompts.py).++Claude Code asks mid-turn over its control protocol; every other CLI asks at+the end of its turn with a ``jarvis-ask`` block, and a finished plan-mode turn+gets a plan card. These tests drive both paths through the real service, store+and CLI pump; only the vendor process is a small Python stand-in.+"""++from __future__ import annotations++import asyncio+import json+import os+import re+import sys+from pathlib import Path+from typing import Any++import pytest++from jarvis.agent_chat import runner_cli as rc+from jarvis.agent_chat import turn_prompts+from jarvis.agent_chat.events import make_event+from jarvis.agent_chat.questions import QuestionAnswer+from jarvis.agent_chat.runner_api import TurnHandle+from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatSession, AgentChatStore++_ASK = {+ "questions": [+ {+ "question": "Which database?",+ "options": [+ {"label": "SQLite", "description": "One file"},+ {"label": "Postgres", "description": "A server"},+ ],+ "recommendation_reason": "Nothing to run.",+ },+ {"question": "Where does it run?", "options": [{"label": "Laptop"}, {"label": "VPS"}]},+ ]+}+++def _reply_with_block(payload: Any = _ASK) -> str:+ return f"I need two decisions.\n\n```{turn_prompts.ASK_FENCE}\n{json.dumps(payload)}\n```\n"+++# ------------------------------------------------------------------ parsing+++def test_the_last_valid_block_is_the_card() -> None:+ specs = turn_prompts.parse_ask_block(_reply_with_block())+ assert specs is not None and [s.question for s in specs] == [+ "Which database?",+ "Where does it run?",+ ]+ # A bare list of questions is accepted too.+ listed = turn_prompts.parse_ask_block(_reply_with_block(_ASK["questions"][:1]))+ assert listed is not None and len(listed) == 1+ # No block, broken JSON, or questions that do not validate: plain text.+ assert turn_prompts.parse_ask_block("Which database do you want?") is None+ assert turn_prompts.parse_ask_block(f"```{turn_prompts.ASK_FENCE}\n{{oops\n```") is None+ one_option = {"questions": [{"question": "A?", "options": [{"label": "only"}]}]}+ assert turn_prompts.parse_ask_block(_reply_with_block(one_option)) is None+ # An ordinary code block is never a question.+ assert turn_prompts.parse_ask_block(f"```json\n{json.dumps(_ASK)}\n```") is None+++def test_the_frontend_hides_the_same_fence() -> None:+ root = Path(__file__).resolve().parents[3]+ source = (+ root / "jarvis/ui/web/frontend/src/components/agentchat/askFence.ts"+ ).read_text(encoding="utf-8")+ match = re.search(r'export const ASK_FENCE = "([^"]+)"', source)+ assert match is not None and match.group(1) == turn_prompts.ASK_FENCE+++# ------------------------------------------------------------------ the service+++async def _service(+ tmp_path: Path, *, mode: str = "auto", provider: str = "openai-codex"+) -> tuple[AgentChatService, str, list[tuple[str, str | None]]]:+ svc = AgentChatService(AgentChatStore(":memory:"))+ session = svc.store.create_session(+ provider=provider,+ model="",+ effort="",+ cwd=str(tmp_path),+ permission_mode=mode,+ surface="agent",+ )+ sent: list[tuple[str, str | None]] = []++ async def send(session_id: str, text: str, *_: Any, **kwargs: Any) -> str:+ assert session_id == session.session_id+ sent.append((text, kwargs.get("display_text")))+ return "next-turn"++ svc.send = send # type: ignore[method-assign]+ return svc, session.session_id, sent+++async def _finish_turn(+ svc: AgentChatService, sid: str, text: str, *, status: str = "done", turn_id: str = "t1"+) -> None:+ await svc._emit(sid, make_event("turn_started", {"turn_id": turn_id}))+ await svc._emit(sid, make_event("assistant_text", {"turn_id": turn_id, "text": text}))+ await svc._emit(sid, make_event("turn_finished", {"turn_id": turn_id, "status": status}))+++def _kinds(svc: AgentChatService, sid: str, kind: str) -> list[dict[str, Any]]:+ return [e["payload"] for e in svc.store.list_events(sid) if e["kind"] == kind]+++def test_an_ask_block_becomes_a_card_and_the_answers_the_next_message(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _service(tmp_path)+ await _finish_turn(svc, sid, _reply_with_block())+ await svc._open_turn_prompts(sid, "t1", "codex-cli")+ (card,) = _kinds(svc, sid, "question_required")+ assert card["deferred"] is True and card["turn_id"] == "t1"+ qid = card["question_id"]++ assert await svc.answer_turn_question(sid, qid, index=0, option_index=1)+ assert not await svc.answer_turn_question(sid, qid, index=0, option_index=0)+ (progress,) = _kinds(svc, sid, "question_progress")+ assert progress["answers"][0]["answer"] == "Postgres" and progress["answers"][1] is None+ assert sent == []++ assert await svc.answer_turn_question(sid, qid, index=1, text="A Raspberry Pi")+ (resolved,) = _kinds(svc, sid, "question_resolved")+ assert [a["answer"] for a in resolved["answers"]] == ["Postgres", "A Raspberry Pi"]+ ((prompt, shown),) = sent+ assert "Which database? -> Postgres" in prompt and "A Raspberry Pi" in prompt+ assert shown == "Which database? — Postgres\nWhere does it run? — A Raspberry Pi"+ # Closed: no second answer, no second message.+ assert not await svc.answer_turn_question(sid, qid, index=1, text="again")+ assert len(sent) == 1++ asyncio.run(scenario())+++def test_closing_the_card_leaves_the_rest_to_the_agent(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _service(tmp_path)+ await _finish_turn(svc, sid, _reply_with_block())+ await svc._open_turn_prompts(sid, "t1", "codex-cli")+ qid = _kinds(svc, sid, "question_required")[0]["question_id"]+ assert await svc.answer_turn_question(sid, qid, index=0, option_index=1)+ assert await svc.skip_turn_question(sid, qid)+ (resolved,) = _kinds(svc, sid, "question_resolved")+ assert [(a["answer"], a["source"]) for a in resolved["answers"]] == [+ ("Postgres", "person"),+ ("Laptop", "skipped"),+ ]+ ((prompt, _),) = sent+ assert "left to you; go with your recommendation (Laptop)" in prompt++ asyncio.run(scenario())+++def test_a_new_turn_closes_an_unanswered_card(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _service(tmp_path)+ await _finish_turn(svc, sid, _reply_with_block())+ await svc._open_turn_prompts(sid, "t1", "codex-cli")+ qid = _kinds(svc, sid, "question_required")[0]["question_id"]+ # The person typed something else instead: that turn moved on.+ await _finish_turn(svc, sid, "ok", turn_id="t2")+ assert not await svc.answer_turn_question(sid, qid, index=0, option_index=0)+ assert not await svc.skip_turn_question(sid, qid)+ assert sent == []++ asyncio.run(scenario())+++def test_no_card_for_a_failed_turn_or_plain_text(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, _ = await _service(tmp_path)+ await _finish_turn(svc, sid, _reply_with_block(), status="error")+ await svc._open_turn_prompts(sid, "t1", "codex-cli")+ await _finish_turn(svc, sid, "Done. Anything else?", turn_id="t2")+ await svc._open_turn_prompts(sid, "t2", "codex-cli")+ assert _kinds(svc, sid, "question_required") == []+ assert _kinds(svc, sid, "plan_ready") == []++ asyncio.run(scenario())+++ ("provider", "runner", "build"),+ [+ ("openai-codex", "codex-cli", "auto"),+ ("antigravity", "agy-cli", "accept-edits"),+ ("grok-build", "grok-cli", "acceptEdits"),+ ("opencode", "opencode-cli", "default"),+ ("kimi", "kimi-cli", "auto"),+ ("cursor", "cursor-cli", "auto"),+ ("claude-api", "claude-cli", "acceptEdits"),+ ],+)+def test_a_finished_plan_gets_a_build_card(+ tmp_path: Path, provider: str, runner: str, build: str+) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _service(tmp_path, mode="plan", provider=provider)+ await _finish_turn(svc, sid, "1. Add the table\n2. Wire the route")+ await svc._open_turn_prompts(sid, "t1", runner)+ (card,) = _kinds(svc, sid, "plan_ready")+ assert card == {"turn_id": "t1", "build_mode": build}++ assert await svc.resolve_turn_plan(sid, "t1", "build")+ assert svc.store.get_session(sid).permission_mode == build+ assert _kinds(svc, sid, "session_updated") == [{"permission_mode": build}]+ assert _kinds(svc, sid, "plan_resolved") == [{"turn_id": "t1", "decision": "build"}]+ assert sent == [(turn_prompts.PLAN_GO_AHEAD, None)]+ assert not await svc.resolve_turn_plan(sid, "t1", "build")++ asyncio.run(scenario())+++def test_keep_planning_only_closes_the_card(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _service(tmp_path, mode="plan")+ await _finish_turn(svc, sid, "1. Add the table")+ await svc._open_turn_prompts(sid, "t1", "codex-cli")+ with pytest.raises(ValueError):+ await svc.resolve_turn_plan(sid, "t1", "maybe")+ assert await svc.resolve_turn_plan(sid, "t1", "keep")+ assert svc.store.get_session(sid).permission_mode == "plan"+ assert sent == []+ # Outside plan mode a finished turn is just a reply.+ svc.store.update_session(sid, permission_mode="auto")+ await _finish_turn(svc, sid, "Done.", turn_id="t2")+ await svc._open_turn_prompts(sid, "t2", "codex-cli")+ assert len(_kinds(svc, sid, "plan_ready")) == 1++ asyncio.run(scenario())+++# ------------------------------------------------------------------ the CLI runner+++def _session(tmp_path: Path, provider: str, *, surface: str, mode: str = "") -> AgentChatSession:+ return AgentChatSession(+ session_id="s1",+ title="",+ provider=provider,+ model="",+ effort="",+ cwd=str(tmp_path),+ permission_mode=mode,+ vendor_session=None,+ created_ms=0,+ updated_ms=0,+ message_count=0,+ preview="",+ surface=surface,+ )+++def _prompt_seen(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, runner: str, provider: str, surface: str+) -> str:+ seen: list[str] = []++ async def once(handle: Any, user_text: str, *_: Any, **__: Any) -> Any:+ seen.append(user_text)+ return rc._Outcome(+ status="done", error=None, usage={}, cost_usd=None, vendor_session=None+ )++ monkeypatch.setattr(rc, "_run_cli_once", once)++ async def emit(_ev: dict[str, Any]) -> None:+ return None++ async def ask(*_: object) -> str:+ return "deny"++ handle = TurnHandle(+ session=_session(tmp_path, provider, surface=surface),+ turn_id="t1",+ emit=emit,+ request_approval=ask,+ cancel=asyncio.Event(),+ )+ asyncio.run(rc.run_cli_turn(handle, "build the thing", runner))+ return seen[0]+++ ("runner", "provider"),+ [+ ("codex-cli", "openai-codex"),+ ("agy-cli", "antigravity"),+ ("grok-cli", "grok-build"),+ ("opencode-cli", "opencode"),+ ("kimi-cli", "kimi"),+ ("cursor-cli", "cursor"),+ ("dsh-cli", "deepseek-harness"),+ ],+)+def test_every_cli_without_a_question_channel_learns_the_protocol(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, runner: str, provider: str+) -> None:+ prompt = _prompt_seen(monkeypatch, tmp_path, runner, provider, "agent")+ assert prompt == turn_prompts.ASK_PROTOCOL + "build the thing"+++def test_claude_and_other_surfaces_keep_their_own_prompt(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ assert _prompt_seen(monkeypatch, tmp_path, "claude-cli", "claude-api", "agent") == (+ "build the thing"+ )+ assert _prompt_seen(monkeypatch, tmp_path, "codex-cli", "openai-codex", "jarvis") == (+ "build the thing"+ )+++def _fake_claude(requests: list[dict[str, Any]], out: Path) -> list[str]:+ """A Claude Code stand-in: asks each control request, records the answers."""+ body = f"""+import json, sys+requests = {json.dumps(requests)!r}+answers = []+def send(obj):+ sys.stdout.write(json.dumps(obj) + chr(10)); sys.stdout.flush()+send({{"type": "system", "subtype": "init", "session_id": "v1"}})+pending = list(json.loads(requests))+if pending:+ send(pending.pop(0))+for line in sys.stdin:+ try:+ obj = json.loads(line)+ except ValueError:+ continue+ if obj.get("type") != "control_response":+ continue+ if obj["response"]["request_id"] == "jarvis-init":+ continue+ answers.append(obj["response"]["response"])+ if pending:+ send(pending.pop(0))+ continue+ break+open({str(out)!r}, "w", encoding="utf-8").write(json.dumps(answers))+send({{"type": "result", "subtype": "success", "result": "ok", "session_id": "v1"}})+"""+ return [sys.executable, "-c", body]+++class _FakeChat:+ """The service surface a Claude turn reaches: the question card and the store."""++ def __init__(self) -> None:+ self.asked: list[Any] = []+ self.updates: list[dict[str, Any]] = []+ self.store = self++ async def ask_questions(self, session_id: str, specs: Any, **_: Any) -> list[QuestionAnswer]:+ self.asked.append(specs)+ return [QuestionAnswer("Blue", 1, "person")]++ def update_session(self, session_id: str, **fields: Any) -> None:+ self.updates.append(fields)+++def _claude_turn(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ requests: list[dict[str, Any]],+ *,+ mode: str,+ decision: str = "allow",+) -> tuple[list[dict[str, Any]], _FakeChat, list[dict[str, Any]]]:+ out = tmp_path / "answers.json"+ plan = rc.CliPlan(+ _fake_claude(requests, out),+ dict(os.environ),+ rc.claude_stream_input("hi"),+ "claude",+ "v1",+ keep_stdin=True,+ control_init=rc.claude_control_init(),+ )+ monkeypatch.setitem(rc._PLANNERS, "claude-cli", lambda **kw: plan)+ events: list[dict[str, Any]] = []+ chat = _FakeChat()++ async def emit(ev: dict[str, Any]) -> None:+ events.append(ev)++ async def ask(*_: object) -> str:+ return decision++ handle = TurnHandle(+ session=_session(tmp_path, "claude-api", surface="agent", mode=mode),+ turn_id="t1",+ emit=emit,+ request_approval=ask,+ cancel=asyncio.Event(),+ control_service=chat,+ )+ asyncio.run(rc.run_cli_turn(handle, "hi", "claude-cli"))+ return json.loads(out.read_text(encoding="utf-8")), chat, events+++def _can_use(tool: str, tool_input: dict[str, Any], request_id: str = "r1") -> dict[str, Any]:+ return {+ "type": "control_request",+ "request_id": request_id,+ "request": {+ "subtype": "can_use_tool",+ "tool_name": tool,+ "input": tool_input,+ "tool_use_id": f"call-{request_id}",+ },+ }+++def test_claude_asks_on_the_question_card_and_reads_the_answers(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ question = {+ "question": "Which colour?",+ "header": "Colour",+ "options": [{"label": "Red"}, {"label": "Blue"}],+ "multiSelect": False,+ }+ answers, chat, _ = _claude_turn(+ monkeypatch,+ tmp_path,+ [_can_use("AskUserQuestion", {"questions": [question]})],+ mode="default",+ )+ ((spec,),) = chat.asked+ assert spec.question == "Which colour?" and [o.label for o in spec.options] == ["Red", "Blue"]+ assert answers == [+ {+ "behavior": "allow",+ "updatedInput": {"questions": [question], "answers": {"Which colour?": "Blue"}},+ }+ ]+++def test_an_approved_claude_plan_leaves_plan_mode(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ answers, chat, events = _claude_turn(+ monkeypatch, tmp_path, [_can_use("ExitPlanMode", {"plan": "1. Do it"})], mode="plan"+ )+ (body,) = answers+ assert body["behavior"] == "allow"+ assert body["updatedPermissions"] == [+ {"type": "setMode", "mode": "acceptEdits", "destination": "session"}+ ]+ assert chat.updates == [{"permission_mode": "acceptEdits"}]+ assert {"permission_mode": "acceptEdits"} in [+ e["payload"] for e in events if e["kind"] == "session_updated"+ ]+++def test_a_declined_claude_plan_stays_in_plan_mode(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ answers, chat, _ = _claude_turn(+ monkeypatch,+ tmp_path,+ [_can_use("ExitPlanMode", {"plan": "1. Do it"})],+ mode="plan",+ decision="deny",+ )+ assert answers == [{"behavior": "deny", "message": "The person declined this action."}]+ assert chat.updates == []+++# ------------------------------------------------------------------ prompts on argv+++def _npm_layout(tmp_path: Path, shim: str, *target: str) -> Path:+ """An npm global prefix: ``<shim>.cmd`` beside ``node_modules/...``."""+ real = tmp_path.joinpath("node_modules", *target)+ real.parent.mkdir(parents=True, exist_ok=True)+ real.write_text("", encoding="utf-8")+ cmd = tmp_path / f"{shim}.cmd"+ cmd.write_text("@echo off\r\n", encoding="utf-8")+ return cmd+++def test_a_multi_line_prompt_skips_the_batch_shim(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ # cmd.exe ends a command at the first line break: through ``opencode.cmd``+ # the task after the protocol paragraph never reached the agent.+ cmd = _npm_layout(tmp_path, "opencode", "opencode-ai", "bin", "opencode.exe")+ monkeypatch.setattr(rc, "_which", lambda *names: str(cmd))+ prefix = rc.opencode_argv_prefix()+ assert prefix == [str(tmp_path / "node_modules" / "opencode-ai" / "bin" / "opencode.exe")]+ plan = rc.plan_opencode(+ prompt="line one\n\nline two", cwd=tmp_path, model="", effort="",+ permission_mode="default", resume=None,+ )+ assert plan.argv[-1] == "line one\n\nline two"++ from jarvis.core import path_augment++ monkeypatch.setattr(path_augment, "resolve_node_executable", lambda: "node-bin")+ kimi = _npm_layout(tmp_path, "kimi", "@moonshot-ai", "kimi-code", "dist", "main.mjs")+ monkeypatch.setattr(rc, "_which", lambda *names: str(kimi))+ assert rc.kimi_argv_prefix() == [+ "node-bin",+ str(tmp_path / "node_modules" / "@moonshot-ai" / "kimi-code" / "dist" / "main.mjs"),+ ]+++def test_a_shim_that_stays_gets_the_prompt_on_one_line(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ lonely = tmp_path / "dsh.cmd"+ lonely.write_text("@echo off\r\n", encoding="utf-8")+ monkeypatch.setattr(rc, "_which", lambda *names: str(lonely))+ assert rc.dsh_argv_prefix() == [str(lonely)] # no package beside it: the shim stays+ plan = rc.plan_dsh(+ prompt="first\n\n second\nthird", cwd=tmp_path, model="", effort="",+ permission_mode="", resume=None,+ )+ assert plan.argv[-1] == "first second third"+ assert rc._argv_prompt(["/usr/bin/opencode"], "a\nb") == "a\nb"