Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(society): let agents ask the user multiple-choice questions

rubenluetke10-beep01305e62abcf
diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.py
index 49c5252775..730df35231 100644
--- a/jarvis/agent_chat/jarvis_harness.py
+++ b/jarvis/agent_chat/jarvis_harness.py
@@ -188,6 +188,11 @@ def codex_config_args(session_id: str | None = None) -> list[str]:
f'mcp_servers.{_SERVER_NAME}.http_headers={{"{HEADER_NAME}"="{session_id}"}}',
"-c",
f"mcp_servers.{_SERVER_NAME}.required=true",
+ # Codex cuts an MCP call off after 60 s by default. An agent's
+ # question card waits up to five minutes for the person
+ # (agent_chat/questions.py), and a browser task can run long.
+ "-c",
+ f"mcp_servers.{_SERVER_NAME}.tool_timeout_sec=600",
# The entrypoint delegates actual actions to Jarvis' executor
# and approval UI, including on the root chat's browser.
"-c",
diff --git a/jarvis/agent_chat/questions.py b/jarvis/agent_chat/questions.py
new file mode 100644
index 0000000000..e71c0aa1f9
--- /dev/null
+++ b/jarvis/agent_chat/questions.py
@@ -0,0 +1,165 @@
+"""A question an agent asks the person, answered from a card of choices.
+
+The open standard of chat agents: when a decision genuinely belongs to the
+person, the agent asks ONE question with a few prepared answers, marks the
+one it recommends, and the person taps an answer (or types their own). The
+card lives in the chat timeline as two events — ``question_required`` and
+``question_resolved`` — so a reopened chat replays it like any other row.
+
+Never a stall: an unanswered question resolves itself to the recommended
+answer after ``QUESTION_TIMEOUT_S``. The agent's turn, and any workflow
+waiting on it, keeps moving whether or not somebody is watching. The agent
+is told the answer was picked automatically, so it can say so in its reply.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Final
+
+#: How long a question waits for the person before the recommendation wins.
+QUESTION_TIMEOUT_S: Final[float] = 300.0
+
+#: Choices on one card: fewer is no choice, more is a form.
+MIN_OPTIONS: Final[int] = 2
+MAX_OPTIONS: Final[int] = 4
+
+_MAX_QUESTION: Final[int] = 600
+_MAX_HEADER: Final[int] = 24
+_MAX_LABEL: Final[int] = 80
+_MAX_DESCRIPTION: Final[int] = 300
+_MAX_ANSWER: Final[int] = 2000
+
+
+@dataclass(frozen=True, slots=True)
+class QuestionOption:
+ label: str
+ description: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class QuestionSpec:
+ """One validated question: the recommended option is always index 0."""
+
+ question: str
+ options: tuple[QuestionOption, ...]
+ header: str = ""
+ recommendation_reason: str = ""
+
+ @property
+ def recommended(self) -> QuestionOption:
+ return self.options[0]
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "question": self.question,
+ "header": self.header,
+ "options": [{"label": o.label, "description": o.description} for o in self.options],
+ "recommended": 0,
+ "recommendation_reason": self.recommendation_reason,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class QuestionAnswer:
+ """What the person (or the timeout) chose."""
+
+ answer: str
+ #: The picked option's index, or ``None`` for a typed answer or a cancel.
+ option_index: int | None
+ #: ``person`` | ``timeout`` | ``cancelled``.
+ source: str
+
+ @property
+ def auto(self) -> bool:
+ return self.source == "timeout"
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "answer": self.answer,
+ "option_index": self.option_index,
+ "source": self.source,
+ "auto": self.auto,
+ }
+
+
+def _text(value: Any, limit: int) -> str:
+ return " ".join(str(value or "").split())[:limit]
+
+
+def parse_question(args: dict[str, Any]) -> QuestionSpec:
+ """Validate a tool call's arguments; raises ``ValueError`` with a fixable reason.
+
+ ``recommended`` (an index into ``options``) moves that option to the
+ front, so every consumer can rely on index 0 being the recommendation.
+ """
+ question = _text(args.get("question"), _MAX_QUESTION)
+ if not question:
+ raise ValueError("question is required")
+ raw = args.get("options")
+ if not isinstance(raw, list):
+ raise ValueError("options must be a list of {label, description}")
+ options: list[QuestionOption] = []
+ seen: set[str] = set()
+ for entry in raw:
+ if isinstance(entry, str):
+ label, description = _text(entry, _MAX_LABEL), ""
+ elif isinstance(entry, dict):
+ label = _text(entry.get("label"), _MAX_LABEL)
+ description = _text(entry.get("description"), _MAX_DESCRIPTION)
+ else:
+ continue
+ if not label or label.casefold() in seen:
+ continue
+ seen.add(label.casefold())
+ options.append(QuestionOption(label, description))
+ if not MIN_OPTIONS <= len(options) <= MAX_OPTIONS:
+ raise ValueError(f"give {MIN_OPTIONS} to {MAX_OPTIONS} distinct options")
+ pick = args.get("recommended", 0)
+ try:
+ index = int(pick)
+ except (TypeError, ValueError): # a malformed pick means the first option leads
+ index = 0
+ if not 0 <= index < len(options):
+ raise ValueError("recommended must be the index of one of the options")
+ if index:
+ options.insert(0, options.pop(index))
+ return QuestionSpec(
+ question=question,
+ options=tuple(options),
+ header=_text(args.get("header"), _MAX_HEADER),
+ recommendation_reason=_text(args.get("recommendation_reason"), _MAX_DESCRIPTION),
+ )
+
+
+def answer_from(
+ spec: QuestionSpec, *, option_index: int | None, text: str | None
+) -> QuestionAnswer:
+ """The person's pick as an answer; raises ``ValueError`` for neither/both/out of range."""
+ typed = (text or "").strip()[:_MAX_ANSWER]
+ if option_index is not None and typed:
+ raise ValueError("send either an option or a typed answer, not both")
+ if option_index is not None:
+ if not 0 <= option_index < len(spec.options):
+ raise ValueError("no such option")
+ return QuestionAnswer(spec.options[option_index].label, option_index, "person")
+ if typed:
+ return QuestionAnswer(typed, None, "person")
+ raise ValueError("send an option or a typed answer")
+
+
+def timeout_answer(spec: QuestionSpec) -> QuestionAnswer:
+ return QuestionAnswer(spec.recommended.label, 0, "timeout")
+
+
+__all__ = [
+ "MAX_OPTIONS",
+ "MIN_OPTIONS",
+ "QUESTION_TIMEOUT_S",
+ "QuestionAnswer",
+ "QuestionOption",
+ "QuestionSpec",
+ "answer_from",
+ "parse_question",
+ "timeout_answer",
+]
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index d314f310bd..00242b76e6 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -37,6 +37,13 @@ from jarvis.agent_chat.catalog import PROVIDER_ROWS, api_seat, offers, provider_
from jarvis.agent_chat.effort import normalize_effort
from jarvis.agent_chat.events import make_event
from jarvis.agent_chat.permissions import ladder_key, normalize_permission
+from jarvis.agent_chat.questions import (
+ QUESTION_TIMEOUT_S,
+ QuestionAnswer,
+ QuestionSpec,
+ answer_from,
+ timeout_answer,
+)
from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner
from jarvis.agent_chat.runner_brain import run_brain_turn
from jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner
@@ -149,6 +156,18 @@ def stop_cli_at_cwd(cwd: str) -> int:
return stopped
+class _OpenQuestion:
+ __slots__ = ("future", "session_id", "spec", "turn_id")
+
+ def __init__(
+ self, session_id: str, turn_id: str, spec: QuestionSpec, future: asyncio.Future[Any]
+ ) -> None:
+ self.session_id = session_id
+ self.turn_id = turn_id
+ self.spec = spec
+ self.future = future
+
+
class _Running:
__slots__ = ("task", "cancel", "turn_id")
@@ -187,6 +206,8 @@ class AgentChatService:
self._subscribers: dict[str, set[Subscriber]] = {}
self._approvals: dict[str, asyncio.Future[str]] = {}
self._approval_session: dict[str, str] = {}
+ # Questions an agent is waiting on (questions.py), by question id.
+ self._questions: dict[str, _OpenQuestion] = {}
# "Always allow" on the Jarvis surface: the tools a person waved through
# for the rest of the session, per session. Claude Code's "don't ask
# again for this tool" rather than a mode flip — the unified ladder has
@@ -789,6 +810,7 @@ class AgentChatService:
self._approval_session.pop(aid, None)
if fut is not None and not fut.done():
fut.set_result("cancel")
+ self._cancel_questions(session_id)
if hasattr(self, "_controls"):
await self._controls.turn_completed(
session_id, turn_id, origin.user_text, origin.direct_user, read_only
@@ -896,6 +918,7 @@ class AgentChatService:
fut = self._approvals.get(aid)
if fut is not None and not fut.done():
fut.set_result("cancel")
+ self._cancel_questions(session_id)
return True
async def cancel(self, session_id: str, *, expected_turn_id: str | None = None) -> bool:
@@ -1014,6 +1037,110 @@ class AgentChatService:
fut.set_result(decision)
return True
+ # ------------------------------------------------------------ questions
+
+ async def ask_question(
+ self,
+ session_id: str,
+ spec: QuestionSpec,
+ *,
+ timeout_s: float = QUESTION_TIMEOUT_S,
+ ) -> QuestionAnswer:
+ """Show ``spec`` as a card in the session's running turn and wait for a pick.
+
+ Never waits longer than ``timeout_s``: the recommended option (index
+ 0) is then chosen on the person's behalf, so a workflow behind this
+ turn keeps moving. A cancelled or finished turn answers ``cancelled``.
+ Raises ``RuntimeError`` when the session has no running turn — there
+ is no card to show and no one to wait for.
+ """
+ run = self._running.get(session_id)
+ if run is None or run.task is None or run.task.done():
+ raise RuntimeError("this chat has no running turn to ask in")
+ question_id = uuid.uuid4().hex
+ loop = asyncio.get_running_loop()
+ fut: asyncio.Future[Any] = loop.create_future()
+ self._questions[question_id] = _OpenQuestion(session_id, run.turn_id, spec, fut)
+ await self._emit(
+ session_id,
+ make_event(
+ "question_required",
+ {
+ "turn_id": run.turn_id,
+ "question_id": question_id,
+ **spec.to_payload(),
+ "timeout_s": timeout_s,
+ "expires_ms": int(time.time() * 1000 + timeout_s * 1000),
+ },
+ ),
+ )
+ try:
+ answer: QuestionAnswer = await asyncio.wait_for(asyncio.shield(fut), timeout_s)
+ except asyncio.CancelledError:
+ # The caller went away (a cancelled tool call, a CLI that gave up
+ # on the MCP request): close the card rather than leave it open.
+ self._questions.pop(question_id, None)
+ await self._emit(
+ session_id,
+ make_event(
+ "question_resolved",
+ {
+ "turn_id": run.turn_id,
+ "question_id": question_id,
+ **QuestionAnswer("", None, "cancelled").to_payload(),
+ },
+ ),
+ )
+ raise
+ except TimeoutError: # the designed outcome: the recommendation wins
+ answer = timeout_answer(spec)
+ log.info(
+ "agent chat: question %s in %s timed out; the recommendation was chosen",
+ question_id,
+ session_id,
+ )
+ finally:
+ self._questions.pop(question_id, None)
+ if not fut.done():
+ fut.cancel()
+ await self._emit(
+ session_id,
+ make_event(
+ "question_resolved",
+ {"turn_id": run.turn_id, "question_id": question_id, **answer.to_payload()},
+ ),
+ )
+ return answer
+
+ def resolve_question(
+ self,
+ session_id: str,
+ question_id: str,
+ *,
+ option_index: int | None = None,
+ text: str | None = None,
+ ) -> bool:
+ """The person's pick. False for an unknown, foreign or already answered question.
+
+ Raises ``ValueError`` for an answer that does not fit the question.
+ """
+ open_q = self._questions.get(question_id)
+ if open_q is None or open_q.session_id != session_id or open_q.future.done():
+ return False
+ answer = answer_from(open_q.spec, option_index=option_index, text=text)
+ open_q.future.set_result(answer)
+ return True
+
+ def pending_questions(self, session_id: str) -> list[str]:
+ return [qid for qid, q in self._questions.items() if q.session_id == session_id]
+
+ def _cancel_questions(self, session_id: str) -> None:
+ # Tolerates a service built without __init__ (test doubles), like _controls.
+ questions: dict[str, _OpenQuestion] = getattr(self, "_questions", {})
+ for open_q in list(questions.values()):
+ if open_q.session_id == session_id and not open_q.future.done():
+ open_q.future.set_result(QuestionAnswer("", None, "cancelled"))
+
__all__ = [
"AgentChatService",
diff --git a/jarvis/society/ask_tool.py b/jarvis/society/ask_tool.py
new file mode 100644
index 0000000000..987f32f2a3
--- /dev/null
+++ b/jarvis/society/ask_tool.py
@@ -0,0 +1,154 @@
+"""``society_ask_user``: an agent asks the person one multiple-choice question.
+
+The agent offers two to four prepared answers and marks the one it
+recommends; the person taps one in the chat card or types their own
+(jarvis/agent_chat/questions.py). Two guarantees keep work moving:
+
+* After five minutes without an answer the recommendation is chosen
+ automatically, and the agent is told so.
+* A routine never asks. Its chat is unattended by design, so the tool is not
+ offered there (``society_tools``) and refuses to wait if called anyway —
+ the agent proceeds on its own recommendation.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Final
+
+from jarvis.agent_chat.questions import (
+ MAX_OPTIONS,
+ MIN_OPTIONS,
+ QUESTION_TIMEOUT_S,
+ QuestionAnswer,
+ QuestionSpec,
+ parse_question,
+ timeout_answer,
+)
+from jarvis.core.protocols import ToolResult
+
+from .routine_runner import is_routine_session
+
+log = logging.getLogger(__name__)
+
+__all__ = ["ASK_USER_TOOL_NAME", "AskUserTool"]
+
+ASK_USER_TOOL_NAME: Final[str] = "society_ask_user"
+_MINUTES: Final[int] = int(QUESTION_TIMEOUT_S // 60)
+
+
+class AskUserTool:
+ """Ask the person one question with prepared answers; wait for the pick."""
+
+ name: str = ASK_USER_TOOL_NAME
+ risk_tier: str = "safe"
+ is_action_tool: bool = False
+ description: str = (
+ "Ask the user ONE question when a decision genuinely belongs to them and you "
+ "cannot infer it from the request, your instructions, memory or sensible "
+ f"defaults. Offer {MIN_OPTIONS}-{MAX_OPTIONS} concrete, mutually exclusive answers "
+ "and recommend exactly one: put your recommendation FIRST and say in "
+ "recommendation_reason why it beats the runner-up. The user taps an answer or "
+ "types their own. If nobody answers within "
+ f"{_MINUTES} minutes, your recommendation is chosen automatically, so recommend "
+ "the safest sensible choice. Do not ask for permission to do what you were "
+ "asked, and do not ask several questions in a row — decide the rest yourself."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "question": {
+ "type": "string",
+ "description": "The question, clear and specific, ending with a question mark.",
+ },
+ "header": {
+ "type": "string",
+ "description": "Very short topic label for the card (max 24 chars).",
+ },
+ "options": {
+ "type": "array",
+ "minItems": MIN_OPTIONS,
+ "maxItems": MAX_OPTIONS,
+ "items": {
+ "type": "object",
+ "properties": {
+ "label": {"type": "string", "description": "1-5 word answer."},
+ "description": {
+ "type": "string",
+ "description": "What choosing this means, trade-offs included.",
+ },
+ },
+ "required": ["label"],
+ },
+ "description": "The answers, your recommendation first.",
+ },
+ "recommendation_reason": {
+ "type": "string",
+ "description": "One sentence: why the first option beats the runner-up.",
+ },
+ },
+ "required": ["question", "options", "recommendation_reason"],
+ }
+
+ def __init__(self, runtime: Any, agent_id: str, *, session_id: str) -> None:
+ self._runtime = runtime
+ self._agent_id = agent_id
+ self._session_id = session_id
+
+ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
+ try:
+ spec = parse_question(args)
+ except ValueError as exc:
+ return ToolResult(success=False, output=None, error=f"invalid question: {exc}")
+ if is_routine_session(self._session_id):
+ return _result(spec, timeout_answer(spec), reason="routine")
+ service = self._runtime.chat_service()
+ if service is None or not callable(getattr(service, "ask_question", None)):
+ return _result(spec, timeout_answer(spec), reason="unattended")
+ try:
+ answer = await service.ask_question(self._session_id, spec)
+ except RuntimeError as exc:
+ # No running chat turn to show a card in (a background run): nobody
+ # can answer, so the recommendation stands rather than a stall.
+ log.info("society ask: %s cannot ask here (%s)", self._agent_id, exc)
+ return _result(spec, timeout_answer(spec), reason="unattended")
+ return _result(spec, answer)
+
+
+def _result(spec: QuestionSpec, answer: QuestionAnswer, *, reason: str = "") -> ToolResult:
+ if answer.source == "cancelled":
+ return ToolResult(
+ success=False,
+ output={"answer": None, "source": "cancelled"},
+ error="The user stopped this turn before answering. Do not continue the task.",
+ )
+ output: dict[str, Any] = {
+ "question": spec.question,
+ "answer": answer.answer,
+ "source": answer.source,
+ }
+ if answer.option_index is not None:
+ option = spec.options[answer.option_index]
+ output["option_description"] = option.description
+ output["recommended"] = answer.option_index == 0
+ if reason == "routine":
+ output["note"] = (
+ "Routines run unattended and cannot ask the user. Your recommendation was "
+ "applied; continue with it and mention the assumption in your result."
+ )
+ output["source"] = "unattended"
+ elif reason == "unattended":
+ output["note"] = (
+ "Nobody can answer in this run. Your recommendation was applied; continue "
+ "with it and mention the assumption in your result."
+ )
+ output["source"] = "unattended"
+ elif answer.auto:
+ output["note"] = (
+ f"The user did not answer within {_MINUTES} minutes, so your recommendation "
+ "was chosen automatically. Continue with it and briefly mention that you "
+ "went with your recommendation."
+ )
+ elif answer.option_index is None:
+ output["note"] = "The user typed their own answer instead of picking an option."
+ return ToolResult(success=True, output=output)
diff --git a/jarvis/society/routine_runner.py b/jarvis/society/routine_runner.py
index a6375504b7..54a81de235 100644
--- a/jarvis/society/routine_runner.py
+++ b/jarvis/society/routine_runner.py
@@ -9,6 +9,14 @@ from uuid import uuid4
from .chat_binding import SURFACE, _workspace, pair_for
from .routines import agent_id_from_tags, routine_seat
+#: Marks a per-execution routine chat: ``society:<agent>:routine:<task>:<run>``.
+ROUTINE_SESSION_MARKER = ":routine:"
+
+
+def is_routine_session(session_id: str) -> bool:
+ """Whether ``session_id`` is an unattended routine execution's own chat."""
+ return ROUTINE_SESSION_MARKER in (session_id or "")
+
async def guard_owned_routine(runtime: Any, tags: tuple[str, ...]) -> Any:
"""Check live owner availability for both chat and native workflow actions."""
@@ -133,7 +141,7 @@ async def run_owned_routine(
cfg = runtime.config()
provider, model, effort, account_id = await _seat_for_run(runtime, agent, task_id)
session = service.store.create_session(
- session_id=f"{agent.session_id}:routine:{task_id}:{uuid4().hex}",
+ session_id=f"{agent.session_id}{ROUTINE_SESSION_MARKER}{task_id}:{uuid4().hex}",
surface=SURFACE,
provider=provider,
model=model,
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
index 7a1e7546f2..9e9ad1e2bc 100644
--- a/jarvis/society/surface.py
+++ b/jarvis/society/surface.py
@@ -35,6 +35,7 @@ from .agent_tools import (
ShellTool,
WikiNoteTool,
)
+from .ask_tool import ASK_USER_TOOL_NAME, AskUserTool
from .capabilities import CapabilityKind, CapabilityRow, capability_id_for_tool, select_tools
from .coding_tool import CodingSessionTool
from .communication import COMMUNICATION_GUIDANCE
@@ -42,6 +43,7 @@ from .conversation_tool import ConversationRecallTool, RoutineInvokeTool, Routin
from .learning import RunLearnedSkillTool
from .memory import resolve_society_vault
from .roster import AgentRecord, canonical_session_id
+from .routine_runner import is_routine_session
from .runtime import current_runtime
log = logging.getLogger(__name__)
@@ -84,6 +86,9 @@ Opening and sending obey your approval rules. Read recorded context before claim
answer, propose). Compose it yourself. When handing work to a teammate, include the result, \
its location and any unresolved dependency they need to continue. A reply to the user is a \
natural conversation, not a mandatory handoff checklist; mention only relevant details.
+- Questions: when a decision genuinely belongs to the user, ask ONE question with \
+society_ask_user: 2-4 prepared answers, your recommendation first with its reason. After five \
+minutes without an answer your recommendation is applied. Decide everything else yourself.
- Shell: society_shell runs commands in YOUR workspace folder only (relative paths stay inside it; \
outside paths are refused). Destructive commands ask the user first.
- Learning: after a finished task you may gain a learned skill of your own (listed \
@@ -340,6 +345,10 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:
),
}
)
+ session_id = str(getattr(session, "session_id", "") or "")
+ # A routine runs unattended: it never gets a way to ask the user.
+ if not is_routine_session(session_id):
+ tools[ASK_USER_TOOL_NAME] = cast(Tool, AskUserTool(rt, agent_id, session_id=session_id))
if rt.browser.is_installed() or rt.browser.live.model_resolver is not None:
from .browser.tool import BrowserTool
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 7ed8cf9bd3..74987bcbf1 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -13,6 +13,7 @@ Prefix ``/api/agent-chat``:
POST /sessions/{id}/messages {text, attachments} -> starts a turn
POST /sessions/{id}/cancel
POST /sessions/{id}/approvals/{aid} {decision: allow | allow_always | deny}
+ POST /sessions/{id}/questions/{qid} {option_index} or {text} -> answer an agent's question
WS /sessions/{id}/ws?after=<seq> snapshot, then live events
POST /attachments drop/paste/pick files for the next message
POST /pick-folder the system folder dialog (desktop only)
@@ -165,6 +166,13 @@ class ApprovalBody(BaseModel):
decision: str
+class QuestionAnswerBody(BaseModel):
+ #: The picked option (0 is the agent's recommendation) ...
+ option_index: int | None = None
+ #: ... or the person's own typed answer. Exactly one of the two.
+ text: str | None = None
+
+
class PickFolderBody(BaseModel):
start: str | None = None
@@ -844,6 +852,25 @@ async def resolve_approval(
return {"ok": True, "approval_id": approval_id, "decision": body.decision}
+ "/sessions/{session_id}/questions/{question_id}",
+ summary="Answer an agent's multiple-choice question",
+)
+async def answer_question(
+ session_id: str, question_id: str, body: QuestionAnswerBody, request: Request
+) -> dict[str, Any]:
+ svc = _service(request)
+ try:
+ ok = svc.resolve_question(
+ session_id, question_id, option_index=body.option_index, text=body.text
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if not ok:
+ raise HTTPException(status_code=404, detail="no such open question")
+ return {"ok": True, "question_id": question_id}
+
+
# ------------------------------------------------------------------ attachments
@@ -976,6 +1003,7 @@ async def session_stream(ws: WebSocket, session_id: str) -> None:
d = session.to_dict()
d["running"] = svc.is_running(session_id)
d["pending_approvals"] = svc.pending_approvals(session_id)
+ d["pending_questions"] = svc.pending_questions(session_id)
await ws.send_json({"type": "snapshot", "session": d, "events": events})
last_seq = events[-1]["seq"] if events else after
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx
new file mode 100644
index 0000000000..cae5308e5e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx
@@ -0,0 +1,106 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import { createAgentChatStore } from "@/store/agentChat";
+import { AgentChatStoreProvider } from "./AgentChatStoreContext";
+import { AgentTimeline } from "./AgentTimeline";
+import { EMPTY_TIMELINE, reduceEvents, type ToolBlock, type TurnItem } from "./reduce";
+
+let seq = 0;
+function ev(kind: string, payload: Record<string, unknown>, tsMs = 1000): AgentChatEvent {
+ return { seq: ++seq, ts_ms: tsMs, kind, payload } as AgentChatEvent;
+}
+
+const ASKED = {
+ turn_id: "t1",
+ question_id: "q1",
+ question: "Which database should the project use?",
+ header: "Database",
+ options: [
+ { label: "SQLite", description: "Zero setup" },
+ { label: "Postgres", description: "Scales further" },
+ ],
+ recommended: 0,
+ recommendation_reason: "No server to run.",
+ expires_ms: Date.now() + 5 * 60_000,
+};
+
+function asking(extra: AgentChatEvent[] = []): AgentChatEvent[] {
+ return [
+ ev("turn_started", { turn_id: "t1" }),
+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: "mcp__jarvis__society_ask_user", input: {} }),
+ ev("question_required", ASKED),
+ ...extra,
+ ];
+}
+
+afterEach(() => {
+ cleanup();
+ seq = 0;
+ vi.restoreAllMocks();
+});
+
+describe("question events", () => {
+ it("attach the card to the ask call and record the answer", () => {
+ const tl = reduceEvents(EMPTY_TIMELINE, asking([
+ ev("question_resolved", { turn_id: "t1", question_id: "q1", answer: "SQLite", option_index: 0, source: "timeout", auto: true }),
+ ]));
+ const turn = tl.items[0] as TurnItem;
+ expect(turn.blocks).toHaveLength(1);
+ const block = turn.blocks[0] as ToolBlock;
+ expect(block.callId).toBe("c1");
+ expect(block.question?.options.map((o) => o.label)).toEqual(["SQLite", "Postgres"]);
+ expect(block.question?.answer).toEqual({ text: "SQLite", optionIndex: 0, source: "timeout" });
+ });
+
+ it("close an unanswered card when the turn ends", () => {
+ const tl = reduceEvents(EMPTY_TIMELINE, asking([ev("turn_finished", { turn_id: "t1", status: "cancelled" })]));
+ const block = (tl.items[0] as TurnItem).blocks[0] as ToolBlock;
+ expect(block.question?.answer?.source).toBe("closed");
+ });
+});
+
+describe("QuestionCard", () => {
+ function draw(events: AgentChatEvent[]) {
+ const store = createAgentChatStore("jarvis");
+ const answer = vi.fn(async () => undefined);
+ store.setState({ answerQuestion: answer });
+ render(
+ <AgentChatStoreProvider store={store}>
+ <AgentTimeline items={reduceEvents(EMPTY_TIMELINE, events).items} assistantName="Ada" providerLabel={(id) => id} onDecide={() => undefined} />
+ </AgentChatStoreProvider>,
+ );
+ return answer;
+ }
+
+ it("marks the recommendation first, counts down and sends a pick", async () => {
+ const answer = draw(asking());
+ const card = screen.getByTestId("question-card");
+ expect(card.getAttribute("data-state")).toBe("open");
+ const options = card.querySelectorAll("button[data-recommended]");
+ expect(options[0].getAttribute("data-recommended")).toBe("true");
+ expect(options[0].textContent).toContain("SQLite");
+ expect(options[0].textContent).toContain("No server to run.");
+ expect(screen.getByTestId("question-countdown").textContent).toMatch(/[45]:\d\d/);
+ fireEvent.click(options[1]);
+ await waitFor(() => expect(answer).toHaveBeenCalledWith("q1", { optionIndex: 1 }));
+ });
+
+ it("sends a typed answer", async () => {
+ const answer = draw(asking());
+ fireEvent.click(screen.getByRole("button", { name: /different answer|andere antwort/i }));
+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "MySQL" } });
+ fireEvent.submit(screen.getByRole("textbox").closest("form")!);
+ await waitFor(() => expect(answer).toHaveBeenCalledWith("q1", { text: "MySQL" }));
+ });
+
+ it("shows an automatic pick as answered", () => {
+ draw(asking([
+ ev("question_resolved", { turn_id: "t1", question_id: "q1", answer: "SQLite", option_index: 0, source: "timeout", auto: true }),
+ ]));
+ const card = screen.getByTestId("question-card");
+ expect(card.getAttribute("data-state")).toBe("timeout");
+ expect(card.textContent).toContain("SQLite");
+ expect(card.querySelector("button")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/QuestionCard.tsx b/jarvis/ui/web/frontend/src/components/agentchat/QuestionCard.tsx
new file mode 100644
index 0000000000..d20440eb02
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/QuestionCard.tsx
@@ -0,0 +1,199 @@
+import { memo, useEffect, useRef, useState, type FormEvent } from "react";
+import { Check, MessageCircleQuestion, Send, Sparkles } from "lucide-react";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import type { QuestionAnswerInput } from "@/lib/agentChatApi";
+import { useAgentChat } from "./AgentChatStoreContext";
+import type { QuestionState } from "./reduce";
+
+/**
+ * An agent's question with prepared answers (jarvis/agent_chat/questions.py).
+ *
+ * The first option is the agent's recommendation. The card counts down to
+ * the moment the backend picks that recommendation on its own, so the person
+ * always sees that doing nothing is also an answer.
+ */
+
+function useRemaining(expiresMs: number | null, live: boolean): number | null {
+ const [now, setNow] = useState(Date.now);
+ useEffect(() => {
+ if (!live || expiresMs === null) return;
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [expiresMs, live]);
+ return expiresMs === null ? null : Math.max(0, expiresMs - now);
+}
+
+function clock(ms: number): string {
+ const seconds = Math.ceil(ms / 1000);
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
+}
+
+export const QuestionCard = memo(function QuestionCard({ question }: { question: QuestionState }) {
+ const t = useT();
+ const answerQuestion = useAgentChat((s) => s.answerQuestion);
+ const open = question.answer === null;
+ const remaining = useRemaining(question.expiresMs, open);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [typing, setTyping] = useState(false);
+ const [text, setText] = useState("");
+ const submitting = useRef(false);
+
+ const send = async (answer: QuestionAnswerInput) => {
+ if (submitting.current) return;
+ submitting.current = true;
+ setBusy(true);
+ setError(null);
+ try {
+ await answerQuestion(question.questionId, answer);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ submitting.current = false;
+ setBusy(false);
+ }
+ };
+
+ const submitText = (event: FormEvent) => {
+ event.preventDefault();
+ const typed = text.trim();
+ if (typed) void send({ text: typed });
+ };
+
+ if (!open) return <AnsweredQuestion question={question} />;
+
+ return (
+ <div
+ role="group"
+ aria-label={t("question_card.aria")}
+ data-testid="question-card"
+ data-state="open"
+ className="my-2 w-full max-w-xl space-y-3 rounded-xl border border-border bg-card p-4 text-sm text-foreground shadow-sm"
+ >
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <MessageCircleQuestion aria-hidden className="h-4 w-4 text-primary" />
+ <span className="font-medium uppercase tracking-wide">{question.header || t("question_card.title")}</span>
+ </div>
+ <p className="font-medium leading-6 [overflow-wrap:anywhere]">{question.question}</p>
+ <div className="space-y-2">
+ {question.options.map((option, index) => {
+ const recommended = index === 0;
+ return (
+ <button
+ key={option.label}
+ type="button"
+ disabled={busy}
+ onClick={() => void send({ optionIndex: index })}
+ data-recommended={recommended ? "true" : "false"}
+ className={cn(
+ "flex w-full flex-col items-start gap-1 rounded-lg border px-3 py-2.5 text-left transition-colors",
+ "hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",
+ "!text-sm",
+ recommended ? "border-primary/60 bg-primary/5" : "border-border",
+ )}
+ >
+ <span className="flex w-full flex-wrap items-center gap-2">
+ <span className="text-xs tabular-nums text-muted-foreground">{index + 1}.</span>
+ <span className="font-medium [overflow-wrap:anywhere]">{option.label}</span>
+ {recommended ? (
+ <span className="inline-flex items-center gap-1 rounded-full bg-primary/15 px-2 py-0.5 text-[11px] font-medium text-primary">
+ <Sparkles aria-hidden className="h-3 w-3" />
+ {t("question_card.recommended")}
+ </span>
+ ) : null}
+ </span>
+ {option.description ? (
+ <span className="text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere]">{option.description}</span>
+ ) : null}
+ {recommended && question.recommendationReason ? (
+ <span className="text-xs leading-5 text-foreground/80 [overflow-wrap:anywhere]">
+ {t("question_card.why").replace("{reason}", question.recommendationReason)}
+ </span>
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
+ {typing ? (
+ <form onSubmit={submitText} className="flex items-center gap-2">
+ <input
+ autoFocus
+ value={text}
+ onChange={(event) => setText(event.target.value)}
+ maxLength={2000}
+ placeholder={t("question_card.own_placeholder")}
+ aria-label={t("question_card.own_answer")}
+ className="min-w-0 flex-1 rounded-md border border-border bg-background px-3 py-1.5 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ <button
+ type="submit"
+ disabled={busy || !text.trim()}
+ aria-label={t("question_card.send")}
+ className="inline-flex items-center gap-1 rounded-md border border-border px-3 py-1.5 text-xs hover:bg-secondary focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
+ >
+ <Send aria-hidden className="h-3.5 w-3.5" />
+ {t("question_card.send")}
+ </button>
+ </form>
+ ) : (
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => setTyping(true)}
+ className="rounded-md px-1 text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {t("question_card.own_answer")}
+ </button>
+ )}
+ {remaining !== null ? (
+ <p className="text-xs text-muted-foreground" aria-live="off" data-testid="question-countdown">
+ {remaining > 0
+ ? t("question_card.countdown").replace("{time}", clock(remaining))
+ : t("question_card.choosing")}
+ </p>
+ ) : null}
+ {error ? (
+ <p role="alert" className="text-xs text-destructive">
+ {error}
+ </p>
+ ) : null}
+ </div>
+ );
+});
+
+function AnsweredQuestion({ question }: { question: QuestionState }) {
+ const t = useT();
+ const answer = question.answer!;
+ const stopped = answer.source === "cancelled" || answer.source === "closed";
+ const note = answer.source === "timeout"
+ ? t("question_card.auto_picked")
+ : answer.optionIndex === null && !stopped
+ ? t("question_card.own_words")
+ : answer.optionIndex === 0
+ ? t("question_card.recommended")
+ : "";
+ return (
+ <div
+ data-testid="question-card"
+ data-state={answer.source}
+ className="my-1 w-full max-w-xl rounded-lg border border-border px-3 py-2 text-xs text-muted-foreground"
+ >
+ <p className="flex items-center gap-1.5 [overflow-wrap:anywhere]">
+ <MessageCircleQuestion aria-hidden className="h-3.5 w-3.5 shrink-0" />
+ <span>{question.question}</span>
+ </p>
+ <p className="mt-1 flex flex-wrap items-center gap-1.5 pl-5">
+ {stopped ? (
+ <span>{t("question_card.unanswered")}</span>
+ ) : (
+ <>
+ <Check aria-hidden className="h-3.5 w-3.5 text-primary" />
+ <span className="font-medium text-foreground [overflow-wrap:anywhere]">{answer.text}</span>
+ {note ? <span>· {note}</span> : null}
+ </>
+ )}
+ </p>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
index 985e79b3b6..ef9fe7faba 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
@@ -1,5 +1,5 @@
import { createContext, memo, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
-import { Brain, Check, ChevronRight, CircleAlert, CircleDashed, FilePenLine, FileText, FolderSearch, ShieldQuestion, Terminal } from "lucide-react";
+import { Brain, Check, ChevronRight, CircleAlert, CircleDashed, FilePenLine, FileText, FolderSearch, MessageCircleQuestion, ShieldQuestion, Terminal } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { useT } from "@/i18n";
@@ -7,6 +7,7 @@ import { cn } from "@/lib/utils";
import type { ApprovalDecision } from "@/lib/agentChatApi";
import type { ReasoningBlock, TextBlock, ToolBlock, TurnBlock, TurnItem, TurnStatus } from "./reduce";
import { ChatMarkdown } from "./ChatMarkdown";
+import { QuestionCard } from "./QuestionCard";
import { toolDiff } from "./toolDiff";
import { formatTokens, outputTokens } from "./toolView";
import { activityParts, traceToolIdentity, traceToolName } from "./traceActivity";
@@ -46,7 +47,12 @@ function operation(name: string): string | null {
}
function attention(block: ToolBlock) {
- return block.isError || Boolean(block.approval);
+ return block.isError || Boolean(block.approval) || Boolean(block.question);
+}
+
+/** An agent's question still waiting for the person — it never folds away. */
+function isOpenQuestion(block: TurnBlock): block is ToolBlock {
+ return block.kind === "tool" && Boolean(block.question && block.question.answer === null);
}
/** Only adjacent, successful, read-only operations may lose individual rows. */
@@ -99,7 +105,7 @@ export function splitConversationTurn(blocks: TurnBlock[]): { work: TurnBlock[];
}
function isPendingApproval(block: TurnBlock): block is ToolBlock {
- return block.kind === "tool" && Boolean(block.approval && block.approval.decision === null);
+ return (block.kind === "tool" && Boolean(block.approval && block.approval.decision === null)) || isOpenQuestion(block);
}
function hasFoldableWork(blocks: TurnBlock[]): boolean {
@@ -292,6 +298,11 @@ function Detail({ label, text }: { label: string; text: string }) {
}
export const TraceTool = memo(function TraceTool({ block, status, onDecide }: { block: ToolBlock; status: TurnStatus; onDecide?: Decide }) {
+ if (block.question) return <QuestionCard question={block.question} />;
+ return <TraceToolRow block={block} status={status} onDecide={onDecide} />;
+});
+
+function TraceToolRow({ block, status, onDecide }: { block: ToolBlock; status: TurnStatus; onDecide?: Decide }) {
const t = useT();
const pending = Boolean(block.approval && block.approval.decision === null);
const denied = block.approval?.decision === "deny";
@@ -341,7 +352,7 @@ export const TraceTool = memo(function TraceTool({ block, status, onDecide }: {
{error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}
</div> : null}
</div>;
-});
+}
function ActivitySummary({ blocks, live }: { blocks: TurnBlock[]; live: boolean }) {
const t = useT();
@@ -445,9 +456,10 @@ export function WorkTrace({ blocks, status, startedMs, durationMs, error, onDeci
}, [split]);
const groups = useMemo(() => conversation ? groupConversationTrace(fold ? fold.workAll : blocks) : groupActivityTrace(blocks), [blocks, conversation, fold]);
const restGroups = useMemo(() => fold ? groupConversationTrace(fold.answer) : null, [fold]);
- const pending = blocks.some(block => block.kind === "tool" && block.approval?.decision === null);
- const outcome = pending ? "approval" : live ? "working" : status === "error" ? "failed" : status === "cancelled" ? "stopped" : "done";
- const Icon = pending ? ShieldQuestion : live ? CircleDashed : status === "error" ? CircleAlert : Check;
+ const asking = blocks.some(isOpenQuestion);
+ const pending = asking || blocks.some(block => block.kind === "tool" && block.approval?.decision === null);
+ const outcome = asking ? "question" : pending ? "approval" : live ? "working" : status === "error" ? "failed" : status === "cancelled" ? "stopped" : "done";
+ const Icon = asking ? MessageCircleQuestion : pending ? ShieldQuestion : live ? CircleDashed : status === "error" ? CircleAlert : Check;
const groupProps = { live, status, onDecide, renderText, conversation };
// A turn-level error next to a reply folds with the work — it stays one
// tap away behind the toggle. With no reply the error IS the outcome, so
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
index dfe89b03c8..b5b26e3092 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -43,6 +43,35 @@ export interface ApprovalState {
decision: string | null;
}
+/** One prepared answer on an agent's question card. */
+export interface QuestionOption {
+ label: string;
+ description: string;
+}
+
+/**
+ * An agent's multiple-choice question (jarvis/agent_chat/questions.py). Option
+ * 0 is always the agent's recommendation; it is picked automatically when
+ * nobody answers before `expiresMs`.
+ */
+export interface QuestionState {
+ questionId: string;
+ question: string;
+ header: string;
+ options: QuestionOption[];
+ recommendationReason: string;
+ expiresMs: number | null;
+ /** Set once answered: `person`, `timeout` (auto-picked), `cancelled`, or `closed` (turn ended). */
+ answer: { text: string; optionIndex: number | null; source: string } | null;
+}
+
+/** The tool an agent asks its question with — bare or behind an MCP prefix. */
+export const QUESTION_TOOL = "society_ask_user";
+
+export function isQuestionTool(name: string): boolean {
+ return name === QUESTION_TOOL || name.endsWith(`__${QUESTION_TOOL}`);
+}
+
export interface ToolBlock {
kind: "tool";
callId: string;
@@ -52,6 +81,8 @@ export interface ToolBlock {
isError: boolean;
durationMs: number | null;
approval: ApprovalState | null;
+ /** The question card this call shows, when the call is an agent's question. */
+ question?: QuestionState;
/** When the call was made; a result without its own duration is timed from here. */
startedMs: number;
}
@@ -247,6 +278,53 @@ function closeLiveReasoning(turn: TurnItem, nowMs: number): TurnItem {
};
}
+function questionOptions(raw: unknown): QuestionOption[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((entry) => {
+ if (!entry || typeof entry !== "object") return [];
+ const row = entry as Record<string, unknown>;
+ const label = str(row.label);
+ return label ? [{ label, description: str(row.description) }] : [];
+ });
+}
+
+/** Attach a question to its tool row: the open ask call, else a row of its own. */
+function withQuestion(turn: TurnItem, question: QuestionState, tsMs: number): TurnItem {
+ let index = -1;
+ for (let i = turn.blocks.length - 1; i >= 0; i -= 1) {
+ const b = turn.blocks[i];
+ if (b.kind !== "tool") continue;
+ if (b.question?.questionId === question.questionId) return turn;
+ if (isQuestionTool(b.name) && !b.question) {
+ index = i;
+ break;
+ }
+ }
+ if (index >= 0) {
+ const block = turn.blocks[index] as ToolBlock;
+ return { ...turn, blocks: replaceAt(turn.blocks, index, { ...block, question }) };
+ }
+ const closed = closeLiveReasoning(turn, tsMs);
+ return {
+ ...closed,
+ blocks: [
+ ...closed.blocks,
+ {
+ kind: "tool",
+ callId: `q-${question.questionId}`,
+ name: QUESTION_TOOL,
+ input: null,
+ output: null,
+ isError: false,
+ durationMs: null,
+ approval: null,
+ question,
+ startedMs: tsMs,
+ },
+ ],
+ };
+}
+
function upsertBlock<B extends TurnBlock>(
turn: TurnItem,
match: (b: TurnBlock) => boolean,
@@ -481,6 +559,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
turn,
(b) => b.kind === "tool" && b.callId === callId,
(ex) => ({
+ ...(ex?.question ? { question: ex.question } : {}),
kind: "tool",
callId,
name: ex?.name ?? str(p.name),
@@ -573,12 +652,49 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
};
}
+ case "question_required": {
+ const questionId = str(p.question_id);
+ if (!questionId) return base;
+ const question: QuestionState = {
+ questionId,
+ question: str(p.question),
+ header: str(p.header),
+ options: questionOptions(p.options),
+ recommendationReason: str(p.recommendation_reason),
+ expiresMs: num(p.expires_ms),
+ answer: null,
+ };
+ return updateTurn(base, turnId, (turn) => withQuestion(turn, question, ev.ts_ms));
+ }
+
+ case "question_resolved": {
+ const questionId = str(p.question_id);
+ return updateTurn(base, turnId, (turn) => {
+ const i = turn.blocks.findIndex(
+ (b) => b.kind === "tool" && b.question?.questionId === questionId,
+ );
+ if (i < 0) return turn;
+ const block = turn.blocks[i] as ToolBlock;
+ return {
+ ...turn,
+ blocks: replaceAt(turn.blocks, i, {
+ ...block,
+ question: {
+ ...block.question!,
+ answer: { text: str(p.answer), optionIndex: num(p.option_index), source: str(p.source, "person") },
+ },
+ }),
+ };
+ });
+ }
+
case "turn_finished": {
const status = str(p.status, "done") as TurnStatus;
const finished = updateTurn(base, turnId, (turn) => ({
...turn,
status: status === "running" ? "done" : status,
- // A turn that ended mid-stream closes its live reasoning block.
+ // A turn that ended mid-stream closes its live reasoning block, and
+ // a question nobody can answer any more stops asking.
blocks: turn.blocks.map((b) =>
b.kind === "reasoning" && b.live
? {
@@ -586,7 +702,9 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
live: false,
durationMs: b.durationMs ?? Math.max(0, ev.ts_ms - b.startedMs),
}
- : b,
+ : b.kind === "tool" && b.question && !b.question.answer
+ ? { ...b, question: { ...b.question, answer: { text: "", optionIndex: null, source: "closed" } } }
+ : b,
),
durationMs: num(p.duration_ms) ?? Math.max(0, ev.ts_ms - turn.startedMs),
usage:
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 66e4739d85..f6e78b683f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5653,7 +5653,22 @@
"hint": "Wähle Tools für die nächste Nachricht. Berechtigungen gelten weiterhin.",
"done": "Fertig"
},
+ "question_card": {
+ "aria": "Rückfrage des Agenten",
+ "title": "Rückfrage",
+ "recommended": "Empfohlen",
+ "why": "Warum: {reason}",
+ "own_answer": "Andere Antwort eingeben…",
+ "own_placeholder": "Deine Antwort",
+ "send": "Senden",
+ "countdown": "Ohne Antwort wird in {time} automatisch die Empfehlung gewählt.",
+ "choosing": "Die Empfehlung wird gewählt…",
+ "auto_picked": "automatisch gewählt (keine Antwort in 5 Minuten)",
+ "own_words": "deine eigene Antwort",
+ "unanswered": "Nicht beantwortet – der Durchlauf wurde beendet."
+ },
"work_trace": {
+ "question": "Wartet auf deine Antwort",
"integration_used": "{service} verwendet",
"activity_command": "Befehle ausgeführt",
"activity_edit": "Dateien bearbeitet",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 180e371215..048612f4a9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5686,7 +5686,22 @@
"hint": "Pick tools for your next message. Permissions still apply.",
"done": "Done"
},
+ "question_card": {
+ "aria": "Question from the agent",
+ "title": "Question",
+ "recommended": "Recommended",
+ "why": "Why: {reason}",
+ "own_answer": "Type a different answer…",
+ "own_placeholder": "Your answer",
+ "send": "Send",
+ "countdown": "No answer in {time} and the recommended option is chosen automatically.",
+ "choosing": "Choosing the recommended option…",
+ "auto_picked": "chosen automatically (no answer within 5 minutes)",
+ "own_words": "your own answer",
+ "unanswered": "Not answered — the turn ended."
+ },
"work_trace": {
+ "question": "Waiting for your answer",
"integration_used": "Used {service}",
"activity_command": "Ran commands",
"activity_edit": "Edited files",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 151b709311..ccb381401c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5653,7 +5653,22 @@
"hint": "Elige herramientas para el próximo mensaje. Se siguen aplicando los permisos.",
"done": "Listo"
},
+ "question_card": {
+ "aria": "Pregunta del agente",
+ "title": "Pregunta",
+ "recommended": "Recomendada",
+ "why": "Por qué: {reason}",
+ "own_answer": "Escribir otra respuesta…",
+ "own_placeholder": "Tu respuesta",
+ "send": "Enviar",
+ "countdown": "Sin respuesta en {time}, se elige automáticamente la opción recomendada.",
+ "choosing": "Eligiendo la opción recomendada…",
+ "auto_picked": "elegida automáticamente (sin respuesta en 5 minutos)",
+ "own_words": "tu propia respuesta",
+ "unanswered": "Sin responder: el turno terminó."
+ },
"work_trace": {
+ "question": "Esperando tu respuesta",
"integration_used": "Usó {service}",
"activity_command": "Ejecutó comandos",
"activity_edit": "Editó archivos",
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index b8da28c237..49a82a1efe 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -473,6 +473,28 @@ export async function resolveAgentChatApproval(
);
}
+/** The person's answer to an agent's question: one option, or their own words. */
+export type QuestionAnswerInput = { optionIndex: number } | { text: string };
+
+export async function answerAgentChatQuestion(
+ sessionId: string,
+ questionId: string,
+ answer: QuestionAnswerInput,
+): Promise<void> {
+ const body = "optionIndex" in answer ? { option_index: answer.optionIndex } : { text: answer.text };
+ await json(
+ await fetch(
+ `/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/questions/${encodeURIComponent(questionId)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ },
+ ),
+ "question-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.ts
index 125224d8c4..4a8d82ca80 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -13,6 +13,8 @@ import {
isApiRunner,
patchAgentChatSession,
resolveAgentChatApproval,
+ answerAgentChatQuestion,
+ type QuestionAnswerInput,
sendAgentChatMessage,
type AgentChatCatalog,
type AgentChatEvent,
@@ -156,6 +158,8 @@ export interface AgentChatStore {
send: (text: string, attachments?: ChatAttachment[], toolChoices?: string[]) => Promise<void>;
cancel: () => Promise<void>;
decide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
+ /** Answer an agent's question card in the active session; throws so the card can say why. */
+ answerQuestion: (questionId: string, answer: QuestionAnswerInput) => Promise<void>;
/** Tests and the socket: fold one event into the active timeline. */
ingest: (event: AgentChatEvent) => void;
disconnect: () => void;
@@ -694,6 +698,12 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
}
},
+ answerQuestion: async (questionId, answer) => {
+ const sid = get().activeSessionId;
+ if (!sid) throw new Error("no open chat");
+ await answerAgentChatQuestion(sid, questionId, answer);
+ },
+
ingest: (event) => {
const st = get();
const tl = reduceEvent(st.timeline, event);
diff --git a/tests/unit/agent_chat/test_questions.py b/tests/unit/agent_chat/test_questions.py
new file mode 100644
index 0000000000..288d37b055
--- /dev/null
+++ b/tests/unit/agent_chat/test_questions.py
@@ -0,0 +1,183 @@
+"""An agent's multiple-choice question: the card, the pick, the 5-minute fallback."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.agent_chat.questions import answer_from, parse_question
+from jarvis.agent_chat.service import AgentChatService, _Running
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.society.ask_tool import ASK_USER_TOOL_NAME, AskUserTool
+
+_ARGS: dict[str, Any] = {
+ "question": "Which database should the project use?",
+ "header": "Database",
+ "options": [
+ {"label": "SQLite", "description": "Zero setup"},
+ {"label": "Postgres", "description": "Scales further"},
+ ],
+ "recommendation_reason": "No server to run.",
+}
+
+
+def test_parse_moves_the_recommendation_first_and_rejects_bad_shapes() -> None:
+ spec = parse_question({**_ARGS, "recommended": 1})
+ assert [o.label for o in spec.options] == ["Postgres", "SQLite"]
+ assert spec.recommended.label == "Postgres"
+ with pytest.raises(ValueError):
+ parse_question({**_ARGS, "options": [{"label": "only one"}]})
+ with pytest.raises(ValueError):
+ parse_question({**_ARGS, "options": [{"label": str(i)} for i in range(5)]})
+ with pytest.raises(ValueError):
+ parse_question({**_ARGS, "question": " "})
+ with pytest.raises(ValueError):
+ parse_question({**_ARGS, "recommended": 7})
+
+
+def test_answer_needs_exactly_one_of_option_or_text() -> None:
+ spec = parse_question(_ARGS)
+ assert answer_from(spec, option_index=1, text=None).answer == "Postgres"
+ assert answer_from(spec, option_index=None, text=" MySQL ").answer == "MySQL"
+ for kwargs in (
+ {"option_index": None, "text": ""},
+ {"option_index": 0, "text": "x"},
+ {"option_index": 9, "text": None},
+ ):
+ with pytest.raises(ValueError):
+ answer_from(spec, **kwargs)
+
+
+async def _service_with_turn(tmp_path: Path) -> tuple[AgentChatService, str, asyncio.Task[None]]:
+ svc = AgentChatService(AgentChatStore(":memory:"), assistant_name=lambda: "Testo")
+ session = svc.store.create_session(
+ provider="fakeprov", model="m", effort="high", cwd=str(tmp_path)
+ )
+ run = _Running("turn-1", asyncio.Event())
+ run.task = asyncio.create_task(asyncio.sleep(3600))
+ svc._running[session.session_id] = run
+ return svc, session.session_id, run.task
+
+
+async def _next(q: asyncio.Queue, kind: str) -> dict[str, Any]:
+ while True:
+ ev = await asyncio.wait_for(q.get(), timeout=5)
+ if ev["kind"] == kind:
+ return ev["payload"]
+
+
+def test_the_person_picks_an_option(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc, sid, task = await _service_with_turn(tmp_path)
+ q = svc.subscribe(sid)
+ asking = asyncio.create_task(svc.ask_question(sid, parse_question(_ARGS)))
+ card = await _next(q, "question_required")
+ assert card["turn_id"] == "turn-1" and card["recommended"] == 0
+ assert [o["label"] for o in card["options"]] == ["SQLite", "Postgres"]
+ assert svc.pending_questions(sid) == [card["question_id"]]
+ assert not svc.resolve_question("other-session", card["question_id"], option_index=1)
+ assert svc.resolve_question(sid, card["question_id"], option_index=1)
+ answer = await asking
+ assert (answer.answer, answer.source, answer.auto) == ("Postgres", "person", False)
+ resolved = await _next(q, "question_resolved")
+ assert resolved["answer"] == "Postgres" and resolved["auto"] is False
+ assert svc.pending_questions(sid) == []
+ assert not svc.resolve_question(sid, card["question_id"], option_index=0)
+ task.cancel()
+
+ asyncio.run(scenario())
+
+
+def test_no_answer_in_time_picks_the_recommendation(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc, sid, task = await _service_with_turn(tmp_path)
+ q = svc.subscribe(sid)
+ answer = await svc.ask_question(sid, parse_question(_ARGS), timeout_s=0.05)
+ assert (answer.answer, answer.option_index, answer.auto) == ("SQLite", 0, True)
+ resolved = await _next(q, "question_resolved")
+ assert resolved["source"] == "timeout" and resolved["auto"] is True
+ task.cancel()
+
+ asyncio.run(scenario())
+
+
+def test_cancelling_the_turn_closes_the_question(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc, sid, task = await _service_with_turn(tmp_path)
+ q = svc.subscribe(sid)
+ asking = asyncio.create_task(svc.ask_question(sid, parse_question(_ARGS)))
+ await _next(q, "question_required")
+ assert svc.signal_cancel(sid)
+ answer = await asking
+ assert answer.source == "cancelled"
+ task.cancel()
+
+ asyncio.run(scenario())
+
+
+def test_asking_without_a_running_turn_raises(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc = AgentChatService(AgentChatStore(":memory:"))
+ session = svc.store.create_session(
+ provider="fakeprov", model="m", effort="high", cwd=str(tmp_path)
+ )
+ with pytest.raises(RuntimeError):
+ await svc.ask_question(session.session_id, parse_question(_ARGS))
+
+ asyncio.run(scenario())
+
+
+class _FakeService:
+ def __init__(self) -> None:
+ self.asked: list[str] = []
+
+ async def ask_question(self, session_id: str, spec: Any) -> Any:
+ self.asked.append(session_id)
+ return answer_from(spec, option_index=1, text=None)
+
+
+def _tool(session_id: str, service: _FakeService) -> AskUserTool:
+ runtime = SimpleNamespace(chat_service=lambda: service)
+ return AskUserTool(runtime, "ada", session_id=session_id)
+
+
+def test_tool_returns_the_persons_answer() -> None:
+ service = _FakeService()
+ result = asyncio.run(_tool("society:ada", service).execute(dict(_ARGS), None))
+ assert result.success and result.output["answer"] == "Postgres"
+ assert result.output["recommended"] is False
+ assert service.asked == ["society:ada"]
+
+
+def test_a_routine_never_waits_for_the_user() -> None:
+ service = _FakeService()
+ tool = _tool("society:ada:routine:t1:run1", service)
+ result = asyncio.run(tool.execute(dict(_ARGS), None))
+ assert result.success and result.output["answer"] == "SQLite"
+ assert result.output["source"] == "unattended" and "Routines" in result.output["note"]
+ assert service.asked == []
+
+
+def test_tool_rejects_an_invalid_question() -> None:
+ result = asyncio.run(
+ _tool("society:ada", _FakeService()).execute({"question": "?", "options": []}, None)
+ )
+ assert not result.success and "invalid question" in (result.error or "")
+
+
+def test_routine_chats_are_not_offered_the_tool(monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.society import surface
+
+ browser = SimpleNamespace(is_installed=lambda: False, live=SimpleNamespace(model_resolver=None))
+ rt = SimpleNamespace(browser=browser, chat_service=lambda: None)
+ monkeypatch.setattr(surface, "current_runtime", lambda: rt)
+ canonical = SimpleNamespace(session_id="society:ada", cwd="", permission_mode="")
+ routine = SimpleNamespace(
+ session_id="society:ada:routine:t1:run1", cwd="", permission_mode="bypass"
+ )
+ assert ASK_USER_TOOL_NAME in surface.society_tools(None, None, canonical)
+ assert ASK_USER_TOOL_NAME not in surface.society_tools(None, None, routine)
diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.py
index babb231fe6..7d484e1713 100644
--- a/tests/unit/society/test_surface.py
+++ b/tests/unit/society/test_surface.py
@@ -89,6 +89,7 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pa
"society_conversation_recall",
"society_routines",
"society_invoke_routine",
+ "society_ask_user",
*FOLDER,
}
assert "RunCommand" not in own
@@ -109,6 +110,7 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pa
"society_conversation_recall",
"society_routines",
"society_invoke_routine",
+ "society_ask_user",
*FOLDER,
}
assert set(picked[: len(own_names)]) == own_names