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(agents): forgiving follow-up questions with multi-select, review and chat replies (#907)
Ruben Lütke1fc7c0d37947
diff --git a/dodaios/agent_chat/questions.py b/dodaios/agent_chat/questions.pyindex c5135e8593..1140db3033 100644--- a/dodaios/agent_chat/questions.py+++ b/dodaios/agent_chat/questions.py@@ -17,6 +17,16 @@ answers were picked for it, so it can say so in its reply.Asking is rationed: at most ``MAX_QUESTIONS`` per call and ``MAX_ASKS_PER_TURN``calls per turn. An agent that keeps asking gets its own recommendations backinstead of another card.++Three kinds of question share the card. ``single`` (the default) takes one+option or the person's own words; ``multi`` takes any number of options, and+its answer reaches the agent as one label per line; ``text`` takes the+person's own words only, with the options (if any) offered as suggestions.+Every kind keeps a default answer for the timeout, so nothing ever stalls:+the recommended option(s), or an empty answer for a ``text`` question with no+options. The person may also skip one question (``declined``), answer from+the chat composer (``message``), or move on so that older open questions+fall back to their recommendations (``moved_on``)."""from __future__ import annotations@@ -44,6 +54,18 @@ SKIPPED: Final[str] = "skipped"CANCELLED: Final[str] = "cancelled"#: Applied without a card (a routine, a background run, the per-turn limit).UNATTENDED: Final[str] = "unattended"+#: The person skipped this one question: an empty answer, the agent decides.+DECLINED: Final[str] = "declined"+#: The person answered by sending a chat message while the card was open.+MESSAGE: Final[str] = "message"+#: The person sent a message instead of answering: the recommendation applies.+MOVED_ON: Final[str] = "moved_on"++#: Question kinds.+SINGLE: Final[str] = "single"+MULTI: Final[str] = "multi"+TEXT: Final[str] = "text"+KINDS: Final[tuple[str, ...]] = (SINGLE, MULTI, TEXT)_MAX_QUESTION: Final[int] = 600_MAX_LABEL: Final[int] = 80@@ -59,41 +81,85 @@ class QuestionOption:@dataclass(frozen=True, slots=True)class QuestionSpec:- """One validated question: the recommended option is always index 0."""+ """One validated question: the recommended option is always index 0.++ A ``multi`` question may recommend several options; they lead the list+ and ``recommended_count`` says how many. A ``text`` question may have no+ options at all.+ """question: stroptions: tuple[QuestionOption, ...]recommendation_reason: str = ""+ kind: str = SINGLE+ #: The person may type their own answer instead of (or, for ``multi``,+ #: next to) the options.+ allow_custom: bool = True+ #: A chat message sent instead of an answer settles this question with+ #: its recommendation ("moved on"); ``False`` keeps it open.+ dismiss_on_move_on: bool = True+ recommended_count: int = 1++ @property+ def recommended(self) -> QuestionOption | None:+ return self.options[0] if self.options else None@property- def recommended(self) -> QuestionOption:- return self.options[0]+ def recommended_indices(self) -> tuple[int, ...]:+ if not self.options:+ return ()+ count = self.recommended_count if self.kind == MULTI else 1+ return tuple(range(max(1, min(count, len(self.options)))))def to_payload(self) -> dict[str, Any]:- return {+ payload: dict[str, Any] = {"question": self.question,"options": [{"label": o.label, "description": o.description} for o in self.options],"recommended": 0,"recommendation_reason": self.recommendation_reason,}+ # Only what differs from the classic card, so older readers and+ # stored events stay identical for single questions.+ if self.kind != SINGLE:+ payload["kind"] = self.kind+ if self.kind == MULTI and self.recommended_count > 1:+ payload["recommended_count"] = self.recommended_count+ if not self.allow_custom:+ payload["allow_custom"] = False+ if not self.dismiss_on_move_on:+ payload["dismiss_on_move_on"] = False+ return payload@dataclass(frozen=True, slots=True)class QuestionAnswer:"""What the person (or the timeout, a skip, a cancel) chose for one question."""+ #: What the agent reads. A ``multi`` answer holds one label per line,+ #: the person's own words (if any) as the last line.answer: str- #: The picked option's index, or ``None`` for a typed answer or a cancel.+ #: The picked option's index, or ``None`` for a typed answer, a ``multi``+ #: answer or a cancel.option_index: int | None- #: ``person`` | ``timeout`` | ``skipped`` | ``cancelled`` | ``unattended``.+ #: ``person`` | ``timeout`` | ``skipped`` | ``cancelled`` | ``unattended``+ #: | ``declined`` | ``message`` | ``moved_on``.source: str+ #: The picked options of a ``multi`` answer, in option order.+ option_indices: tuple[int, ...] = ()@propertydef by_person(self) -> bool:- return self.source == PERSON+ return self.source in (PERSON, MESSAGE)def to_payload(self) -> dict[str, Any]:- return {"answer": self.answer, "option_index": self.option_index, "source": self.source}+ payload: dict[str, Any] = {+ "answer": self.answer,+ "option_index": self.option_index,+ "source": self.source,+ }+ if self.option_indices:+ payload["option_indices"] = list(self.option_indices)+ return payloadclass TooManyQuestions(RuntimeError):@@ -104,11 +170,54 @@ def _text(value: Any, limit: int) -> str:return " ".join(str(value or "").split())[:limit]+def _flag(value: Any, default: bool) -> bool:+ if isinstance(value, bool):+ return value+ if isinstance(value, str) and value.strip().lower() in ("true", "false"):+ return value.strip().lower() == "true"+ return default+++def _kind(raw: dict[str, Any]) -> str:+ """``kind``, else the multi-select flags the runtimes use (``multi``,+ ``multi_select``, Claude's ``multiSelect``); an unknown kind is single."""+ kind = str(raw.get("kind") or "").strip().lower()+ if kind in KINDS:+ return kind+ for key in ("multi", "multi_select", "multiSelect"):+ if _flag(raw.get(key), False):+ return MULTI+ return SINGLE+++def _recommended(raw: Any, count: int, kind: str) -> list[int]:+ """The recommended option indices, in the agent's order; raises on a bad index."""+ if not count: # a text question without suggestions recommends nothing+ return []+ values = raw if isinstance(raw, list) and kind == MULTI else [raw]+ picked: list[int] = []+ for value in values:+ if value is None:+ continue+ try:+ index = int(value)+ except (TypeError, ValueError): # a malformed pick means the first option leads+ continue+ if not 0 <= index < count:+ raise ValueError("recommended must be the index of one of the options")+ if index not in picked:+ picked.append(index)+ return picked or ([0] if count else [])++def _parse_one(raw: dict[str, Any]) -> QuestionSpec:question = _text(raw.get("question"), _MAX_QUESTION)if not question:raise ValueError("every question needs its question text")+ kind = _kind(raw)entries = raw.get("options")+ if entries is None and kind == TEXT:+ entries = []if not isinstance(entries, list):raise ValueError("options must be a list of {label, description}")options: list[QuestionOption] = []@@ -125,20 +234,38 @@ def _parse_one(raw: dict[str, Any]) -> QuestionSpec:continueseen.add(label.casefold())options.append(QuestionOption(label, description))- if not MIN_OPTIONS <= len(options) <= MAX_OPTIONS:+ if kind == TEXT:+ if len(options) > MAX_OPTIONS:+ raise ValueError(f"give a text question at most {MAX_OPTIONS} suggested answers")+ elif not MIN_OPTIONS <= len(options) <= MAX_OPTIONS:raise ValueError(f"give each question {MIN_OPTIONS} to {MAX_OPTIONS} distinct options")- try:- index = int(raw.get("recommended", 0))- 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))+ picked = _recommended(raw.get("recommended", 0), len(options), kind)+ stored_count = raw.get("recommended_count")+ if (+ kind == MULTI+ and picked == [0]+ and isinstance(stored_count, int)+ and not isinstance(stored_count, bool)+ and stored_count > 1+ ):+ # A stored card (an end-of-turn card read back from its event) keeps+ # its recommendations in front and says how many lead.+ picked = list(range(min(stored_count, len(options) - 1)))+ if picked:+ # The recommendations lead, in the agent's order; the rest keep theirs.+ lead = [options[i] for i in picked]+ options = lead + [o for i, o in enumerate(options) if i not in picked]+ if kind == MULTI and len(picked) >= len(options):+ raise ValueError("leave at least one option of a multi-select question unrecommended")return QuestionSpec(question=question,options=tuple(options),recommendation_reason=_text(raw.get("recommendation_reason"), _MAX_DESCRIPTION),+ kind=kind,+ # A text question is nothing but the person's own words.+ allow_custom=True if kind == TEXT else _flag(raw.get("allow_custom"), True),+ dismiss_on_move_on=_flag(raw.get("dismiss_on_move_on"), True),+ recommended_count=len(picked) if kind == MULTI else 1,)@@ -167,27 +294,104 @@ def parse_questions(args: dict[str, Any]) -> tuple[QuestionSpec, ...]:def answer_from(- spec: QuestionSpec, *, option_index: int | None, text: str | None+ spec: QuestionSpec,+ *,+ option_index: int | None,+ text: str | None,+ option_indices: list[int] | tuple[int, ...] | None = None,+ source: str = PERSON,) -> QuestionAnswer:- """The person's pick as an answer; raises ``ValueError`` for neither/both/out of range."""+ """The person's pick as an answer; raises ``ValueError`` for an answer that+ does not fit the question (nothing picked, both for a single question, an+ option out of range, own words where the question takes none)."""typed = (text or "").strip()[:_MAX_ANSWER]+ if typed and not spec.allow_custom and source != MESSAGE:+ raise ValueError("this question takes one of its options only")+ if option_indices is not None and spec.kind == MULTI:+ picks = sorted({int(i) for i in option_indices})+ if any(not 0 <= i < len(spec.options) for i in picks):+ raise ValueError("no such option")+ if not picks and not typed:+ raise ValueError("pick at least one option or type an answer")+ lines = [spec.options[i].label for i in picks] + ([typed] if typed else [])+ return QuestionAnswer("\n".join(lines), None, source, tuple(picks))+ if option_indices is not None:+ # A single pick sent as a list (one shared client for every kind).+ if len(option_indices) > 1:+ raise ValueError("this question takes one option")+ option_index = option_indices[0] if option_indices else option_indexif 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 spec.kind == MULTI:+ return QuestionAnswer(+ spec.options[option_index].label, None, source, (option_index,)+ )+ return QuestionAnswer(spec.options[option_index].label, option_index, source)if typed:- return QuestionAnswer(typed, None, PERSON)+ return QuestionAnswer(typed, None, source)raise ValueError("send an option or a typed answer")def recommended_answer(spec: QuestionSpec, source: str) -> QuestionAnswer:- return QuestionAnswer(spec.recommended.label, 0, source)+ """The default the agent proposed: its recommended option(s), or an empty+ answer for a ``text`` question that offered none."""+ if not spec.options:+ return QuestionAnswer("", None, source)+ if spec.kind == MULTI:+ picks = spec.recommended_indices+ return QuestionAnswer(+ "\n".join(spec.options[i].label for i in picks), None, source, picks+ )+ return QuestionAnswer(spec.options[0].label, 0, source)+++def declined_answer() -> QuestionAnswer:+ """The person skipped this one question: an empty answer, the agent decides."""+ return QuestionAnswer("", None, DECLINED)+++def answer_json(spec: QuestionSpec, raw: Any) -> QuestionAnswer:+ """One answer of a submitted series: ``{option_index | option_indices | text | skip}``."""+ if not isinstance(raw, dict):+ raise ValueError("every answer must be an object")+ if _flag(raw.get("skip"), False):+ return declined_answer()+ indices = raw.get("option_indices")+ if indices is not None and not isinstance(indices, list):+ raise ValueError("option_indices must be a list")+ option = raw.get("option_index")+ if option is not None and (isinstance(option, bool) or not isinstance(option, int)):+ raise ValueError("option_index must be a number")+ try:+ picks = [int(i) for i in indices] if indices is not None else None+ except (TypeError, ValueError) as exc:+ raise ValueError("option_indices must be numbers") from exc+ text = raw.get("text")+ return answer_from(+ spec,+ option_index=option,+ option_indices=picks,+ text=str(text) if text is not None else None,+ )+++def as_line(answer: str) -> str:+ """A ``multi`` answer on one line, for a sentence that lists several answers."""+ return ", ".join(line.strip() for line in answer.splitlines() if line.strip())__all__ = ["CANCELLED",+ "DECLINED",+ "KINDS",+ "MESSAGE",+ "MOVED_ON",+ "MULTI",+ "SINGLE",+ "TEXT","MAX_ASKS_PER_TURN","MAX_OPTIONS","MAX_QUESTIONS",@@ -202,6 +406,9 @@ __all__ = ["QuestionSpec","TooManyQuestions","answer_from",+ "answer_json",+ "as_line",+ "declined_answer","parse_questions","recommended_answer",]diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.pyindex b2fafa7382..c1bfccc391 100644--- a/dodaios/agent_chat/runner_cli.py+++ b/dodaios/agent_chat/runner_cli.py@@ -87,6 +87,7 @@ from dodaios.agent_chat.questions import (CANCELLED,UNATTENDED,TooManyQuestions,+ as_line,parse_questions,recommended_answer,)@@ -4059,8 +4060,9 @@ async def _drive_cli(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.+ A question's ``multiSelect`` becomes a multi-select card question. 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 []@@ -4086,8 +4088,12 @@ async def _drive_cli(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."}+ # A multi-select answer reads the way the CLI's own picker writes one:+ # the chosen labels joined by commas.+ # A skipped question (empty answer) still gets words the CLI can read.picked = {- str(row.get("question") or ""): a.answer for row, a in zip(rows, answers, strict=True)+ str(row.get("question") or ""): as_line(a.answer) or "No preference; decide yourself."+ for row, a in zip(rows, answers, strict=True)}return {"behavior": "allow", "updatedInput": {**tool_input, "answers": picked}}diff --git a/dodaios/agent_chat/service.py b/dodaios/agent_chat/service.pyindex df8b7a7178..4b571c9a8c 100644--- a/dodaios/agent_chat/service.py+++ b/dodaios/agent_chat/service.py@@ -49,6 +49,8 @@ from dodaios.agent_chat.permissions import default_permission, ladder_key, normafrom dodaios.agent_chat.questions import (CANCELLED,MAX_ASKS_PER_TURN,+ MESSAGE,+ MOVED_ON,QUESTION_TIMEOUT_S,SKIPPED,TIMEOUT,@@ -56,6 +58,8 @@ from dodaios.agent_chat.questions import (QuestionSpec,TooManyQuestions,answer_from,+ answer_json,+ declined_answer,recommended_answer,)from dodaios.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner@@ -320,7 +324,8 @@ class _OpenQuestion:"""__slots__ = (- "answers", "closing", "delivered", "result", "session_id", "specs", "turn_id", "wake",+ "answers", "closing", "delivered", "result", "session_id", "specs", "touched",+ "turn_id", "wake",)def __init__(@@ -339,12 +344,35 @@ class _OpenQuestion:self.wake = asyncio.Event()self.result = resultself.delivered = False+ #: The person is working through the card (picks not sent yet):+ #: the watcher restarts its quiet window once.+ self.touched = False@propertydef done(self) -> bool:return bool(self.closing) or all(a is not None for a in self.answers)+def _message_answer(spec: QuestionSpec, text: str) -> QuestionAnswer:+ """A chat message as the answer to ``spec``: a reply that names an option+ (its label, or its letter on its own) picks it; anything else is the+ person's own words."""+ typed = text.strip()+ folded = typed.casefold().rstrip(".!")+ for index, option in enumerate(spec.options):+ letter = "ABCD"[index] if index < 4 else ""+ if folded == option.label.casefold() or (letter and folded == letter.casefold()):+ if spec.kind == "multi":+ return answer_from(spec, option_index=None, text=None, option_indices=[index],+ source=MESSAGE)+ return answer_from(spec, option_index=index, text=None, source=MESSAGE)+ return answer_from(spec, option_index=None, text=typed, source=MESSAGE)+++def _first_open(answers: list[QuestionAnswer | None] | tuple[QuestionAnswer | None, ...]) -> int:+ return next((i for i, a in enumerate(answers) if a is None), -1)++def _expires_ms(timeout_s: float) -> int:return int(time.time() * 1000 + timeout_s * 1000)@@ -2479,7 +2507,8 @@ class AgentChatService:# before this watcher starts or while a progress event emits.open_q.wake.clear()answered = sum(a is not None for a in open_q.answers)- if answered > reported and not open_q.done:+ touched, open_q.touched = open_q.touched, False+ if (answered > reported or touched) and not open_q.done:reported = answereddeadline = loop.time() + timeout_sawait self._emit(@@ -2545,6 +2574,12 @@ class AgentChatService:answers.append(answer)return answers+ def _open_card(self, session_id: str, question_id: str) -> _OpenQuestion | None:+ open_q = getattr(self, "_questions", {}).get(question_id)+ if open_q is None or open_q.session_id != session_id or open_q.done:+ return None+ return open_q+def resolve_question(self,session_id: str,@@ -2552,6 +2587,7 @@ class AgentChatService:*,index: int = 0,option_index: int | None = None,+ option_indices: list[int] | None = None,text: str | None = None,) -> bool:"""The person's answer to question ``index`` of the card.@@ -2559,26 +2595,120 @@ class AgentChatService:False for an unknown, foreign, closed 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.done:+ open_q = self._open_card(session_id, question_id)+ if open_q is None:return Falseif not 0 <= index < len(open_q.specs) or open_q.answers[index] is not None:return Falseopen_q.answers[index] = answer_from(- open_q.specs[index], option_index=option_index, text=text+ open_q.specs[index], option_index=option_index, option_indices=option_indices,+ text=text,)open_q.wake.set()return True- def skip_question(self, session_id: str, question_id: str) -> bool:- """The person closed the card: every open question takes its recommendation."""- open_q = self._questions.get(question_id)- if open_q is None or open_q.session_id != session_id or open_q.done:+ def submit_questions(+ self, session_id: str, question_id: str, answers: list[dict[str, Any]]+ ) -> bool:+ """The person's reviewed answers to the whole card, sent at once.++ One entry per question (``{option_index | option_indices | text | skip}``);+ a question already answered keeps its answer. All entries are checked+ before any is stored, so a bad one changes nothing. False for an+ unknown, foreign or closed card; ``ValueError`` for an answer that does+ not fit or a list of the wrong length.+ """+ open_q = self._open_card(session_id, question_id)+ if open_q is None:return False- open_q.closing = SKIPPED+ if len(answers) != len(open_q.specs):+ raise ValueError(f"send one answer per question ({len(open_q.specs)})")+ parsed = [+ current if current is not None else answer_json(spec, raw)+ for spec, current, raw in zip(open_q.specs, open_q.answers, answers, strict=True)+ ]+ open_q.answers[:] = parsedopen_q.wake.set()return True+ def skip_question(self, session_id: str, question_id: str, index: int | None = None) -> bool:+ """The person closed the card: every open question takes its recommendation.++ With ``index``, only that question is skipped: it resolves to an empty+ answer the agent decides on its own, and the rest of the card stays open.+ """+ open_q = self._open_card(session_id, question_id)+ if open_q is None:+ return False+ if index is not None:+ if not 0 <= index < len(open_q.specs) or open_q.answers[index] is not None:+ return False+ open_q.answers[index] = declined_answer()+ else:+ open_q.closing = SKIPPED+ open_q.wake.set()+ return True++ def touch_question(self, session_id: str, question_id: str) -> bool:+ """The person is answering on the card but has not sent it yet: the+ quiet window starts again, so a careful reader is never cut off."""+ open_q = self._open_card(session_id, question_id)+ if open_q is None:+ return False+ open_q.touched = True+ open_q.wake.set()+ return True++ async def answer_by_message(+ self, session_id: str, text: str+ ) -> dict[str, Any]:+ """A chat message sent while a question card is open answers it.++ The newest open card takes the message as the answer to its current+ question (source ``message``); its other open questions, and every+ older open card, settle with their recommendations (``moved_on``)+ unless a question asked to stay open. Returns ``{"consumed": True}``+ when a running turn took the message as its answer, so the caller+ sends nothing else. An end-of-turn card is settled the same way, but+ ``consumed`` stays False: the message itself is what the agent reads+ next, so the caller sends it as usual.+ """+ typed = (text or "").strip()+ if not typed:+ return {"consumed": False, "question_id": None}+ live = [+ (qid, q) for qid, q in getattr(self, "_questions", {}).items()+ if q.session_id == session_id and not q.done+ ]+ if live:+ newest_id, newest = live[-1]+ for qid, open_q in live:+ current = _first_open(open_q.answers) if qid == newest_id else -1+ for index, spec in enumerate(open_q.specs):+ if open_q.answers[index] is not None:+ continue+ if index == current:+ open_q.answers[index] = _message_answer(spec, typed)+ elif spec.dismiss_on_move_on:+ open_q.answers[index] = recommended_answer(spec, MOVED_ON)+ open_q.wake.set()+ return {"consumed": True, "question_id": newest_id}+ async with self._turn_prompt_lock():+ card = turn_prompts.newest_open_ask(+ self.store.list_events(session_id, tail=self._TURN_PROMPT_TAIL)+ )+ if card is None:+ return {"consumed": False, "question_id": None}+ current = _first_open(card.answers)+ final = [+ a if a is not None+ else _message_answer(spec, typed) if index == current+ else recommended_answer(spec, MOVED_ON)+ for index, (spec, a) in enumerate(zip(card.specs, card.answers, strict=True))+ ]+ await self._resolve_turn_question(session_id, card, final)+ return {"consumed": False, "question_id": card.question_id}+def pending_questions(self, session_id: str) -> list[str]:return [qid for qid, q in self._questions.items() if q.session_id == session_id and not q.done@@ -2736,6 +2866,7 @@ class AgentChatService:option_index: int | None = None,text: str | None = None,author: dict[str, str] | None = None,+ option_indices: list[int] | None = None,) -> bool:"""The person's answer to one question of an end-of-turn card.@@ -2749,22 +2880,13 @@ class AgentChatService:return Falsetry:answers = turn_prompts.answer(- card, index, option_index=option_index, text=text+ card, index, option_index=option_index, text=text,+ option_indices=option_indices,)except IndexError: # a stale option index is a no-op click; the caller reports Falsereturn Falseif 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],- },- ),- )+ await self._turn_question_progress(session_id, card, answers)return Truefinal = [a for a in answers if a is not None]await self._resolve_turn_question(session_id, card, final)@@ -2772,18 +2894,79 @@ class AgentChatService:return Trueasync def skip_turn_question(- self, session_id: str, question_id: str, *, author: dict[str, str] | None = None+ self,+ session_id: str,+ question_id: str,+ *,+ index: int | None = None,+ author: dict[str, str] | None = None,+ ) -> bool:+ """The person closed an end-of-turn card: the agent's recommendations stand.++ With ``index``, only that question is skipped (an empty answer the+ agent decides on); the card sends once its last question is settled.+ """+ 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+ if index is None:+ final = turn_prompts.skipped(card)+ else:+ if not 0 <= index < len(card.specs) or card.answers[index] is not None:+ return False+ answers = list(card.answers)+ answers[index] = declined_answer()+ if any(a is None for a in answers):+ await self._turn_question_progress(session_id, card, 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, author=author)+ return True++ async def submit_turn_question(+ self,+ session_id: str,+ question_id: str,+ answers: list[dict[str, Any]],+ *,+ author: dict[str, str] | None = None,) -> bool:- """The person closed an end-of-turn card: the agent's recommendations stand."""+ """The person's reviewed answers to a whole end-of-turn card, sent as+ the next message. Same contract as :meth:`submit_questions`."""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)+ if len(answers) != len(card.specs):+ raise ValueError(f"send one answer per question ({len(card.specs)})")+ final = [+ current if current is not None else answer_json(spec, raw)+ for spec, current, raw in zip(card.specs, card.answers, answers, strict=True)+ ]await self._resolve_turn_question(session_id, card, final)await self._send_turn_answer(session_id, card, final, author=author)return True+ async def _turn_question_progress(+ self,+ session_id: str,+ card: turn_prompts.OpenAsk,+ answers: list[QuestionAnswer | None],+ ) -> None:+ await self._emit(+ session_id,+ make_event(+ "question_progress",+ {+ "turn_id": card.turn_id,+ "question_id": card.question_id,+ "answers": [a.to_payload() if a else None for a in answers],+ },+ ),+ )+async def _resolve_turn_question(self, session_id: str, card: turn_prompts.OpenAsk, answers: list[QuestionAnswer]) -> None:diff --git a/dodaios/agent_chat/turn_prompts.py b/dodaios/agent_chat/turn_prompts.pyindex f35002f007..54472dc1e8 100644--- a/dodaios/agent_chat/turn_prompts.py+++ b/dodaios/agent_chat/turn_prompts.py@@ -34,14 +34,17 @@ from dataclasses import dataclassfrom typing import Any, Finalfrom dodaios.agent_chat.questions import (+ DECLINED,MAX_OPTIONS,MAX_QUESTIONS,MIN_OPTIONS,+ MOVED_ON,PERSON,SKIPPED,QuestionAnswer,QuestionSpec,answer_from,+ as_line,parse_questions,recommended_answer,)@@ -58,8 +61,8 @@ ASK_PROTOCOL: Final[str] = (f"{ASK_FENCE} block: "'{"questions": [{"question": "...", "options": [{"label": "...", "description": "..."}], 'f'"recommendation_reason": "..."}}]}} with 1-{MAX_QUESTIONS} questions, '- f"{MIN_OPTIONS}-{MAX_OPTIONS} options each, recommended option first. Then stop; "- "the answers arrive as your next message.\n\n"+ f"{MIN_OPTIONS}-{MAX_OPTIONS} options each, recommended option first. Add \"multi\": true "+ "where several options may be picked. Then stop; the answers arrive as your next message.\n\n")#: What the agent is told when the person approved its plan.@@ -146,16 +149,33 @@ def _answers_from(raw: Any, count: int) -> list[QuestionAnswer | None]:out.append(None)continueoption = row.get("option_index")+ picks = row.get("option_indices")out.append(QuestionAnswer(str(row.get("answer") or ""),option if isinstance(option, int) else None,str(row.get("source") or PERSON),+ tuple(i for i in picks if isinstance(i, int)) if isinstance(picks, list) else (),))return out+def newest_open_ask(events: Sequence[dict[str, Any]]) -> OpenAsk | None:+ """The newest end-of-turn card that still waits for the person, or ``None``."""+ newest = ""+ for event in events:+ kind = event.get("kind")+ payload = event.get("payload") or {}+ if kind == "question_required" and payload.get("deferred"):+ newest = str(payload.get("question_id") or "")+ elif kind == "turn_started":+ newest = ""+ elif kind == "question_resolved" and payload.get("question_id") == newest:+ newest = ""+ return open_ask(events, newest) if newest else None++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@@ -207,7 +227,12 @@ def open_plan(events: Sequence[dict[str, Any]], turn_id: str) -> OpenPlan | Nonedef answer(- card: OpenAsk, index: int, *, option_index: int | None, text: str | None+ card: OpenAsk,+ index: int,+ *,+ option_index: int | None,+ text: str | None,+ option_indices: list[int] | None = None,) -> list[QuestionAnswer | None]:"""The card's answers with question ``index`` answered by the person.@@ -217,7 +242,9 @@ def answer(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)+ answers[index] = answer_from(+ card.specs[index], option_index=option_index, text=text, option_indices=option_indices+ )return answers@@ -233,19 +260,23 @@ def answers_prompt(specs: Sequence[QuestionSpec], answers: Sequence[QuestionAnsw"""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:+ answer_text = as_line(picked.answer)+ if picked.source in (SKIPPED, MOVED_ON):lines.append(- f"- {spec.question} -> left to you; go with your recommendation ({picked.answer})."+ f"- {spec.question} -> left to you; go with your recommendation ({answer_text}).")+ elif picked.source == DECLINED or not answer_text:+ lines.append(f"- {spec.question} -> skipped; decide it yourself.")else:- lines.append(f"- {spec.question} -> {picked.answer}")+ lines.append(f"- {spec.question} -> {answer_text}")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)+ f"{spec.question} — {as_line(picked.answer) or '—'}"+ for spec, picked in zip(specs, answers, strict=True))@@ -261,6 +292,7 @@ __all__ = ["answer","answers_display","answers_prompt",+ "newest_open_ask","open_ask","open_plan","parse_ask_block",diff --git a/dodaios/society/ask_tool.py b/dodaios/society/ask_tool.pyindex c9d95e0eb4..14a04d9f86 100644--- a/dodaios/society/ask_tool.py+++ b/dodaios/society/ask_tool.py@@ -3,6 +3,8 @@Each question offers two to four prepared answers with the recommended onefirst; the person taps an answer (or types their own) and the card walksthrough the series as "question 1 of 3" (dodaios/agent_chat/questions.py).+A question may also let the person pick several answers (``kind: multi``) or+ask for their own words only (``kind: text``).Three guarantees keep work moving and asking rare:* When nobody answers for five minutes, the open questions take their@@ -20,11 +22,14 @@ from typing import Any, Finalfrom dodaios.agent_chat.questions import (CANCELLED,+ DECLINED,+ KINDS,MAX_ASKS_PER_TURN,MAX_OPTIONS,MAX_QUESTIONS,+ MESSAGE,MIN_OPTIONS,- PERSON,+ MOVED_ON,QUESTION_TIMEOUT_S,SKIPPED,TIMEOUT,@@ -59,9 +64,16 @@ _QUESTION_SCHEMA: Final[dict[str, Any]] = {"type": "string","description": "The question, clear and specific, ending with a question mark.",},+ "kind": {+ "type": "string",+ "enum": list(KINDS),+ "description": (+ "single (default): one answer. multi: the user may pick several. "+ "text: the user writes the answer; options are optional suggestions."+ ),+ },"options": {"type": "array",- "minItems": MIN_OPTIONS,"maxItems": MAX_OPTIONS,"items": {"type": "object",@@ -74,14 +86,17 @@ _QUESTION_SCHEMA: Final[dict[str, Any]] = {},"required": ["label"],},- "description": "The answers, your recommendation FIRST.",+ "description": (+ f"{MIN_OPTIONS}-{MAX_OPTIONS} answers, your recommendation FIRST "+ "(optional for kind text)."+ ),},"recommendation_reason": {"type": "string","description": "One sentence: why the first option beats the runner-up.",},},- "required": ["question", "options", "recommendation_reason"],+ "required": ["question", "recommendation_reason"],}@@ -100,7 +115,8 @@ class AskUserTool:"better); the user answers them one after another. Each question offers "f"{MIN_OPTIONS}-{MAX_OPTIONS} concrete, mutually exclusive answers with your ""recommendation FIRST and recommendation_reason saying why it beats the "- "runner-up. The user may also type their own answer. If nobody answers within "+ "runner-up; set kind 'multi' only when several answers can be combined. "+ "The user may also type their own answer. If nobody answers within "f"{_MINUTES} minutes, your recommendations are applied, so recommend the safest ""sensible choice. Never ask for permission to do what you were asked, never ask ""what you could look up, and never ask again what was already answered. "@@ -251,12 +267,14 @@ def _result(specs: tuple[QuestionSpec, ...], answers: list[QuestionAnswer]) -> T"answer": answer.answer,"source": answer.source,}+ if answer.option_indices:+ row["picked"] = [spec.options[i].label for i in answer.option_indices]if answer.option_index is not None:row["recommended"] = answer.option_index == 0description = spec.options[answer.option_index].descriptionif description:row["option_description"] = description- elif answer.source == PERSON:+ elif answer.by_person and not answer.option_indices:row["typed"] = Truerows.append(row)output: dict[str, Any] = {"answers": rows}@@ -271,4 +289,12 @@ def _result(specs: tuple[QuestionSpec, ...], answers: list[QuestionAnswer]) -> T"The user closed the card and left the open questions to you: your ""recommendations were applied. Continue without asking again.")+ elif MESSAGE in sources or MOVED_ON in sources:+ output["note"] = (+ "The user replied in the chat instead of on the card: read that message as "+ "their answer. Questions they did not address took your recommendations."+ )+ if DECLINED in sources:+ skipped = "The user skipped a question (empty answer): decide it yourself."+ output["note"] = f"{output['note']} {skipped}" if "note" in output else skippedreturn ToolResult(success=True, output=output)diff --git a/dodaios/ui/web/agent_chat_routes.py b/dodaios/ui/web/agent_chat_routes.pyindex c1e8995f46..bf8b825a5d 100644--- a/dodaios/ui/web/agent_chat_routes.py+++ b/dodaios/ui/web/agent_chat_routes.py@@ -16,9 +16,14 @@ Prefix ``/api/agent-chat``:scope?: agent | chat, breadth?: action | app}POST /sessions/{id}/approvals/{aid}/rule {kind: always_allow | require_approval,scope, breadth} -> a rule from a settled card- POST /sessions/{id}/questions/{qid} {index, option_index} or {index, text} -> answer- one question of an agent's card- POST /sessions/{id}/questions/{qid}/skip close the card: recommendations apply+ POST /sessions/{id}/questions/{qid} {index, option_index | option_indices | text}+ -> answer one question of an agent's card+ POST /sessions/{id}/questions/{qid}/submit {answers: [...]} -> the whole reviewed card+ POST /sessions/{id}/questions/{qid}/skip close the card: recommendations apply;+ {index} skips that one question only+ POST /sessions/{id}/questions/{qid}/touch the person is still answering: restart+ the card's quiet window+ POST /sessions/{id}/reply-to-question {text} -> a chat message answers the open cardPOST /sessions/{id}/plan {turn_id, decision: build | keep} -> answera coding agent's plan cardWS /sessions/{id}/ws?after=<seq> snapshot, then live events@@ -295,10 +300,27 @@ class QuestionAnswerBody(BaseModel):index: int = 0#: 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.+ #: ... the picked options of a multi-select question ...+ option_indices: list[int] | None = None+ #: ... or the person's own typed answer (next to the picks of a multi-select).text: str | None = None+class QuestionSubmitBody(BaseModel):+ #: One entry per question: ``{option_index | option_indices | text | skip}``.+ answers: list[dict[str, Any]] = Field(default_factory=list, max_length=8)+++class QuestionSkipBody(BaseModel):+ #: Skip only this question of the series; absent closes the whole card.+ index: int | None = None+++class QuestionReplyBody(BaseModel):+ #: The chat message the person sent while a question card was open.+ text: str = Field(default="", max_length=20000)++class PlanBody(BaseModel):#: The turn whose plan card this answers.turn_id: str@@ -1411,6 +1433,7 @@ async def answer_question(question_id,index=body.index,option_index=body.option_index,+ option_indices=body.option_indices,text=body.text,)if not ok:@@ -1421,6 +1444,7 @@ async def answer_question(question_id,index=body.index,option_index=body.option_index,+ option_indices=body.option_indices,text=body.text,)except ValueError as exc:@@ -1436,11 +1460,17 @@ async def answer_question("/sessions/{session_id}/questions/{question_id}/skip",summary="Close an agent's question card and let its recommendations apply",)-async def skip_question(session_id: str, question_id: str, request: Request) -> dict[str, Any]:+async def skip_question(+ session_id: str,+ question_id: str,+ request: Request,+ body: QuestionSkipBody | None = None,+) -> dict[str, Any]:svc = (await _async_service(request))+ index = body.index if body is not None else Nonetry:- ok = svc.skip_question(session_id, question_id) or await svc.skip_turn_question(- session_id, question_id+ ok = svc.skip_question(session_id, question_id, index) or await svc.skip_turn_question(+ session_id, question_id, index=index)except SessionBusy as exc:raise HTTPException(status_code=409, detail="session is busy") from exc@@ -1449,6 +1479,52 @@ async def skip_question(session_id: str, question_id: str, request: Request) ->return {"ok": True, "question_id": question_id}+ "/sessions/{session_id}/questions/{question_id}/submit",+ summary="Send the person's reviewed answers to a whole question card at once",+)+async def submit_question(+ session_id: str, question_id: str, body: QuestionSubmitBody, request: Request+) -> dict[str, Any]:+ svc = (await _async_service(request))+ try:+ ok = svc.submit_questions(+ session_id, question_id, body.answers+ ) or await svc.submit_turn_question(session_id, question_id, body.answers)+ 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 question")+ return {"ok": True, "question_id": question_id}+++ "/sessions/{session_id}/questions/{question_id}/touch",+ summary="The person is still answering a question card: restart its quiet window",+)+async def touch_question(session_id: str, question_id: str, request: Request) -> dict[str, Any]:+ svc = (await _async_service(request))+ # An end-of-turn card has no window, so only a live card can be touched.+ return {"ok": bool(svc.touch_question(session_id, question_id))}+++ "/sessions/{session_id}/reply-to-question",+ summary="A chat message answers the open question card",+)+async def reply_to_question(+ session_id: str, body: QuestionReplyBody, request: Request+) -> dict[str, Any]:+ svc = (await _async_service(request))+ try:+ outcome = await svc.answer_by_message(session_id, body.text)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"ok": True, **outcome}++@router.post("/sessions/{session_id}/credentials/{request_id}",summary="Save the secret an agent asked for in its secure credential field",diff --git a/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsxindex 7cc33a0781..61a988ebfb 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx@@ -1,10 +1,12 @@-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";-import type { AgentChatEvent } from "@/lib/agentChatApi";+import { AgentChatApiError, 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";+import { QuestionCard } from "./QuestionCard";+import { EMPTY_TIMELINE, reduceEvents, type QuestionState, type ToolBlock, type TurnItem } from "./reduce";+import { useQuestionDrafts } from "./questions/questionDraftStore";+import { resetQuestionKeyboard } from "./questions/useQuestionKeyboard";let seq = 0;function ev(kind: string, payload: Record<string, unknown>, tsMs = 1000): AgentChatEvent {@@ -26,8 +28,17 @@ const HOST = {recommended: 0,recommendation_reason: "Nothing to pay for.",};+const FEATURES = {+ question: "Which features ship first?",+ kind: "multi",+ options: [{ label: "Search" }, { label: "Export" }, { label: "Sharing" }],+ recommended: 0,+ recommended_count: 2,+ recommendation_reason: "Most asked for.",+};+const NAME = { question: "What should it be called?", kind: "text", options: [] };-function asking(extra: AgentChatEvent[] = [], questions = [DB, HOST]): AgentChatEvent[] {+function asking(extra: AgentChatEvent[] = [], questions: unknown[] = [DB, HOST], payload: Record<string, unknown> = {}): AgentChatEvent[] {return [ev("turn_started", { turn_id: "t1" }),ev("tool_call", { turn_id: "t1", call_id: "c1", name: "mcp__jarvis__society_ask_user", input: {} }),@@ -37,28 +48,34 @@ function asking(extra: AgentChatEvent[] = [], questions = [DB, HOST]): AgentChatasker: "Ada",questions,expires_ms: Date.now() + 5 * 60_000,+ ...payload,}),...extra,];}-const ANSWERED_FIRST = ev("question_progress", {- turn_id: "t1",- question_id: "q1",- answers: [{ answer: "Postgres", option_index: 1, source: "person" }, null],- expires_ms: Date.now() + 5 * 60_000,-});+function questionOf(events: AgentChatEvent[]): QuestionState {+ const turn = reduceEvents(EMPTY_TIMELINE, events).items.find((i) => i.type === "turn") as TurnItem;+ return (turn.blocks.find((b) => b.kind === "tool" && (b as ToolBlock).question) as ToolBlock).question!;+}afterEach(() => {cleanup();seq = 0;vi.restoreAllMocks();+ vi.useRealTimers();+ useQuestionDrafts.setState({ drafts: {} });+ resetQuestionKeyboard();});describe("question events", () => {it("attach the series to the ask call and record each answer", () => {const tl = reduceEvents(EMPTY_TIMELINE, asking([- ANSWERED_FIRST,+ ev("question_progress", {+ turn_id: "t1",+ question_id: "q1",+ answers: [{ answer: "Postgres", option_index: 1, source: "person" }, null],+ }),ev("question_resolved", {turn_id: "t1",question_id: "q1",@@ -77,105 +94,366 @@ describe("question events", () => {expect(block.question?.closed).toBe(true);});- it("read an older single-question event", () => {+ it("read an older single-question event as a single-select question", () => {const tl = reduceEvents(EMPTY_TIMELINE, [ev("turn_started", { turn_id: "t1" }),ev("question_required", { turn_id: "t1", question_id: "q0", ...DB }),ev("question_resolved", { turn_id: "t1", question_id: "q0", answer: "SQLite", option_index: 0, source: "timeout" }),]);const block = (tl.items[0] as TurnItem).blocks[0] as ToolBlock;- expect(block.question?.questions).toHaveLength(1);+ expect(block.question?.questions[0]).toMatchObject({ kind: "single", allowCustom: true, recommendedCount: 1 });expect(block.question?.answers[0]).toEqual({ text: "SQLite", optionIndex: 0, source: "timeout" });});+ it("read multi-select and text-only questions with their picks", () => {+ const q = questionOf(asking([+ ev("question_resolved", {+ turn_id: "t1",+ question_id: "q1",+ answers: [+ { answer: "Search\nSharing", option_index: null, option_indices: [0, 2], source: "person" },+ { answer: "", option_index: null, source: "declined" },+ ],+ }),+ ], [FEATURES, NAME]));+ expect(q.questions.map((i) => i.kind)).toEqual(["multi", "text"]);+ expect(q.questions[0].recommendedCount).toBe(2);+ expect(q.questions[1].options).toEqual([]);+ expect(q.answers[0]?.optionIndices).toEqual([0, 2]);+ });+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?.closed).toBe(true);- expect(block.question?.answers.map((a) => a?.source)).toEqual(["closed", "closed"]);+ const q = questionOf(asking([ev("turn_finished", { turn_id: "t1", status: "cancelled" })]));+ expect(q.closed).toBe(true);+ expect(q.answers.map((a) => a?.source)).toEqual(["closed", "closed"]);});});-describe("QuestionCard", () => {- function draw(events: AgentChatEvent[]) {- const store = createAgentChatStore("jarvis");- const answer = vi.fn(async () => undefined);- const skip = vi.fn(async () => undefined);- store.setState({ answerQuestion: answer, skipQuestion: skip });- render(- <AgentChatStoreProvider store={store}>- <AgentTimeline items={reduceEvents(EMPTY_TIMELINE, events).items} assistantName="Ada" providerLabel={(id) => id} onDecide={() => undefined} />- </AgentChatStoreProvider>,- );- return { answer, skip };- }+function draw(questions: QuestionState | QuestionState[], overrides: Record<string, unknown> = {}) {+ const store = createAgentChatStore("society");+ const submit = vi.fn(async () => undefined);+ const skip = vi.fn(async () => undefined);+ const touch = vi.fn(async () => undefined);+ store.setState({ activeSessionId: "s1", submitQuestion: submit, skipQuestion: skip, touchQuestion: touch, ...overrides });+ const list = Array.isArray(questions) ? questions : [questions];+ const view = render(+ <AgentChatStoreProvider store={store}>+ {list.map((q) => <QuestionCard key={q.questionId} question={q} />)}+ </AgentChatStoreProvider>,+ );+ return { store, submit, skip, touch, view };+}- it("titles the card with the agent, steps through the series and lists lettered answers", async () => {- const { answer } = draw(asking());+function rowsOf(card: HTMLElement): HTMLButtonElement[] {+ return Array.from(card.querySelectorAll<HTMLButtonElement>(".qc-step[data-active] button[data-recommended]"));+}++describe("QuestionCard", () => {+ it("titles the card with the asker and the question, lettered rows and the recommendation", () => {+ draw(questionOf(asking([], [DB])));const card = screen.getByTestId("question-card");expect(card.getAttribute("data-state")).toBe("open");expect(card.textContent).toContain("Ada");- expect(card.textContent).toContain(DB.question);- expect(screen.getByTestId("question-step").textContent).toMatch(/1\D+2/);- const options = card.querySelectorAll("button[data-recommended]");- expect(options).toHaveLength(2);- expect(options[0].textContent).toMatch(/^A/);- expect(options[0].getAttribute("data-recommended")).toBe("true");+ expect(within(card).getByRole("heading").textContent).toBe(DB.question);+ const rows = rowsOf(card);+ expect(rows.map((r) => r.getAttribute("aria-keyshortcuts"))).toEqual(["A", "B"]);+ expect(rows[0].getAttribute("data-recommended")).toBe("true");+ expect(rows[0].textContent).toContain("Recommended");+ // The reason sits behind a disclosure, not in the way.+ const why = within(card).getByRole("button", { name: /why this recommendation/i });+ expect(why.getAttribute("aria-expanded")).toBe("false");+ fireEvent.click(why);+ expect(why.getAttribute("aria-expanded")).toBe("true");expect(card.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", 0, { optionIndex: 1 }));});- it("moves to the next question once the first is answered", () => {- const { answer } = draw(asking([ANSWERED_FIRST]));+ it("settles at once on a pick and sends the whole card", async () => {+ const { submit } = draw(questionOf(asking([], [DB])));+ fireEvent.click(rowsOf(screen.getByTestId("question-card"))[1]);+ // Optimistic: settled in the same frame, before the request returns.const card = screen.getByTestId("question-card");- expect(card.textContent).toContain(HOST.question);- expect(screen.getByTestId("question-step").textContent).toMatch(/2\D+2/);- fireEvent.keyDown(card, { key: "b" });- expect(answer).toHaveBeenCalledWith("q1", 1, { optionIndex: 1 });+ expect(card.hasAttribute("data-settled")).toBe(true);+ expect(card.textContent).toContain("Postgres");+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ option_index: 1 }]));});- it("draws no row for the calls that only wait on the card", () => {- draw(asking([- ev("tool_result", { turn_id: "t1", call_id: "c1", output: "waiting" }),- ev("tool_call", { turn_id: "t1", call_id: "c2", name: "mcp__jarvis__society_ask_user", input: { wait_for: "q1" } }),- ev("tool_result", { turn_id: "t1", call_id: "c2", output: "waiting" }),- ]));- expect(screen.getAllByTestId("question-card")).toHaveLength(1);- expect(document.querySelector("[data-trace-tool]")).toBeNull();+ it("rolls back a failed answer and replays it with Try again", async () => {+ const submit = vi.fn()+ .mockRejectedValueOnce(new AgentChatApiError("network down", 500))+ .mockResolvedValueOnce(undefined);+ draw(questionOf(asking([], [DB])), { submitQuestion: submit });+ fireEvent.click(rowsOf(screen.getByTestId("question-card"))[1]);+ const alert = await screen.findByRole("alert");+ expect(alert.textContent).toMatch(/did not go through/i);+ expect(screen.getByTestId("question-card").getAttribute("data-state")).toBe("open");+ fireEvent.click(screen.getByRole("button", { name: /try again/i }));+ await waitFor(() => expect(submit).toHaveBeenCalledTimes(2));+ expect(submit.mock.calls[1]).toEqual(["q1", [{ option_index: 1 }]]);+ await waitFor(() => expect(screen.getByTestId("question-card").hasAttribute("data-settled")).toBe(true));+ });++ it("gives way quietly when the server already closed the card", async () => {+ const submit = vi.fn().mockRejectedValue(new AgentChatApiError("no such open question", 404));+ draw(questionOf(asking([], [DB])), { submitQuestion: submit });+ fireEvent.click(rowsOf(screen.getByTestId("question-card"))[0]);+ await waitFor(() => expect(submit).toHaveBeenCalled());+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it("answers the newest open card by letter key, never while typing", async () => {+ const older = questionOf(asking([], [DB]));+ const newer = { ...questionOf(asking([], [HOST])), questionId: "q2" };+ const { submit } = draw([older, newer]);+ const input = document.createElement("input");+ document.body.appendChild(input);+ fireEvent.keyDown(input, { key: "b" });+ expect(submit).not.toHaveBeenCalled();+ fireEvent.keyDown(window, { key: "b", ctrlKey: true });+ expect(submit).not.toHaveBeenCalled();+ fireEvent.keyDown(window, { key: "b" });+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q2", [{ option_index: 1 }]));+ expect(submit).toHaveBeenCalledTimes(1);+ input.remove();+ });++ it("walks a series with auto-advance, review, change and one send", async () => {+ const { submit } = draw(questionOf(asking()));+ const card = screen.getByTestId("question-card");+ expect(screen.getByTestId("question-step").textContent).toBe("1 of 2");+ fireEvent.keyDown(window, { key: "a" });+ await waitFor(() => expect(screen.getByTestId("question-step").textContent).toBe("2 of 2"));+ fireEvent.click(rowsOf(card)[2]);+ const review = await screen.findByTestId("question-review");+ await waitFor(() => expect(review.closest(".qc-step")?.hasAttribute("data-active")).toBe(true));+ expect(review.textContent).toContain("SQLite");+ expect(review.textContent).toContain("Both");+ expect(submit).not.toHaveBeenCalled();+ // Change the first answer, then come back to the review.+ fireEvent.click(within(review).getAllByRole("button")[0]);+ expect(screen.getByTestId("question-step").textContent).toBe("1 of 2");+ expect(rowsOf(card)[0].querySelector("[data-on]")).not.toBeNull();+ fireEvent.click(rowsOf(card)[1]);+ await waitFor(() => expect(screen.getByTestId("question-step").textContent).toBe("2 of 2"));+ fireEvent.click(within(card).getByRole("button", { name: /^review$/i }));+ fireEvent.click(screen.getByTestId("question-send"));+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ option_index: 1 }, { option_index: 2 }]));+ });++ it("goes back and skips steps in a series", async () => {+ const { submit } = draw(questionOf(asking()));+ const card = screen.getByTestId("question-card");+ fireEvent.click(within(card).getByRole("button", { name: /^skip$/i }));+ expect(screen.getByTestId("question-step").textContent).toBe("2 of 2");+ fireEvent.click(within(card).getByRole("button", { name: /^back$/i }));+ expect(screen.getByTestId("question-step").textContent).toBe("1 of 2");+ fireEvent.click(within(card).getByRole("button", { name: /^skip$/i }));+ fireEvent.click(within(card).getByRole("button", { name: /^skip$/i }));+ fireEvent.click(screen.getByTestId("question-send"));+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ skip: true }, { skip: true }]));+ });++ it("toggles a multi-select question and sends it with Done", async () => {+ const { submit } = draw(questionOf(asking([], [FEATURES])));+ const card = screen.getByTestId("question-card");+ expect(card.textContent).toMatch(/pick all that apply/i);+ const rows = rowsOf(card);+ expect(rows.filter((r) => r.getAttribute("data-recommended") === "true")).toHaveLength(2);+ fireEvent.click(rows[0]);+ fireEvent.keyDown(window, { key: "c" });+ expect(rows[0].getAttribute("aria-pressed")).toBe("true");+ expect(rows[2].getAttribute("aria-pressed")).toBe("true");+ fireEvent.click(rows[0]);+ expect(rows[0].getAttribute("aria-pressed")).toBe("false");+ fireEvent.change(within(card).getByRole("textbox"), { target: { value: "Dark mode" } });+ fireEvent.click(screen.getByTestId("question-done"));+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ option_indices: [2], text: "Dark mode" }]));+ });++ it("skips a multi-select question sent with nothing picked", async () => {+ const { submit } = draw(questionOf(asking([], [FEATURES])));+ fireEvent.click(screen.getByTestId("question-done"));+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ skip: true }]));+ expect(screen.getByTestId("question-card").textContent).toContain("Skipped");});- it("sends a typed answer", async () => {- const { answer } = draw(asking([], [DB]));- expect(screen.queryByTestId("question-step")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: /own answer|eigene antwort/i }));- fireEvent.change(screen.getByRole("textbox"), { target: { value: "MySQL" } });- fireEvent.submit(screen.getByRole("textbox").closest("form")!);- await waitFor(() => expect(answer).toHaveBeenCalledWith("q1", 0, { text: "MySQL" }));+ it("sends a text-only answer with Enter", async () => {+ const { submit } = draw(questionOf(asking([], [NAME])));+ const field = within(screen.getByTestId("question-card")).getByRole("textbox");+ fireEvent.change(field, { target: { value: "Atlas" } });+ fireEvent.keyDown(field, { key: "Enter" });+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ text: "Atlas" }]));});- it("closing the card leaves the questions to the agent", async () => {- const { skip } = draw(asking());- fireEvent.click(screen.getByRole("button", { name: /let the agent decide|agenten entscheiden/i }));+ it("offers a Send button once own words are typed on a lone single question", async () => {+ const { submit } = draw(questionOf(asking([], [DB])));+ expect(screen.queryByTestId("question-done")).toBeNull();+ fireEvent.change(within(screen.getByTestId("question-card")).getByRole("textbox"), { target: { value: "MySQL" } });+ fireEvent.click(screen.getByTestId("question-done"));+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ text: "MySQL" }]));+ });++ it("keeps every multi pick when a store answers one question at a time", async () => {+ const answerQuestion = vi.fn(async () => undefined);+ draw(questionOf(asking([], [FEATURES])), { submitQuestion: undefined, answerQuestion });+ const rows = rowsOf(screen.getByTestId("question-card"));+ fireEvent.click(rows[0]);+ fireEvent.click(rows[2]);+ fireEvent.click(screen.getByTestId("question-done"));+ await waitFor(() =>+ expect(answerQuestion).toHaveBeenCalledWith("q1", 0, { optionIndices: [0, 2], text: undefined }),+ );+ });++ it("offers two named ways out instead of a silent close", async () => {+ const { skip, submit } = draw(questionOf(asking([], [DB])));+ fireEvent.click(screen.getByRole("button", { name: /question options/i }));+ const menu = screen.getByRole("menu");+ expect(within(menu).getAllByRole("menuitem").map((m) => m.textContent)).toEqual([+ expect.stringMatching(/skip this question/i),+ expect.stringMatching(/let ada decide all/i),+ ]);+ fireEvent.click(within(menu).getByRole("menuitem", { name: /let ada decide all/i }));await waitFor(() => expect(skip).toHaveBeenCalledWith("q1"));+ expect(submit).not.toHaveBeenCalled();+ // Settled optimistically with the recommendation.+ expect(screen.getByTestId("question-card").textContent).toContain("SQLite");});- it("shows a finished series as answers", () => {- draw(asking([+ it("shows the countdown ring only in the last minute of a live card", () => {+ const { view } = draw(questionOf(asking([], [DB])));+ expect(screen.queryByTestId("question-countdown")).toBeNull();+ view.unmount();+ draw(questionOf(asking([], [DB], { expires_ms: Date.now() + 42_000 })));+ expect(screen.getByTestId("question-countdown").getAttribute("aria-label")).toMatch(/0:4\d/);+ cleanup();+ draw(questionOf(asking([], [DB], { deferred: true, expires_ms: Date.now() + 42_000 })));+ expect(screen.queryByTestId("question-countdown")).toBeNull();+ });++ it("restarts a live card's quiet window while the person works on it", () => {+ const { touch } = draw(questionOf(asking()));+ fireEvent.click(rowsOf(screen.getByTestId("question-card"))[0]);+ fireEvent.click(rowsOf(screen.getByTestId("question-card"))[0]);+ expect(touch).toHaveBeenCalledTimes(1);+ expect(touch).toHaveBeenCalledWith("q1");+ });++ it("keeps picks and the step when the card remounts", async () => {+ const q = questionOf(asking());+ const first = draw(q);+ fireEvent.click(rowsOf(screen.getByTestId("question-card"))[1]);+ await waitFor(() => expect(screen.getByTestId("question-step").textContent).toBe("2 of 2"));+ first.view.unmount();+ draw(q);+ expect(screen.getByTestId("question-step").textContent).toBe("2 of 2");+ fireEvent.click(screen.getByRole("button", { name: /^back$/i }));+ expect(rowsOf(screen.getByTestId("question-card"))[1].querySelector("[data-on]")).not.toBeNull();+ });++ it("collapses a finished series to its answers and pages through them", () => {+ draw(questionOf(asking([ev("question_resolved", {turn_id: "t1",question_id: "q1",answers: [{ answer: "Postgres", option_index: 1, source: "person" },- { answer: "Laptop", option_index: 0, source: "skipped" },+ { answer: "Laptop", option_index: 0, source: "timeout" },],}),- ]));+ ])));const card = screen.getByTestId("question-card");- expect(card.getAttribute("data-state")).toBe("person skipped");+ expect(card.getAttribute("data-state")).toBe("person timeout");expect(card.textContent).toContain("Postgres");expect(card.textContent).toContain("Laptop");- expect(card.querySelector("button")).toBeNull();+ const summary = within(card).getByRole("button", { name: /show the answers/i });+ fireEvent.click(summary);+ expect(summary.getAttribute("aria-expanded")).toBe("true");+ expect(card.querySelector(".qc-step[data-active] .qc-title")?.textContent).toBe(DB.question);+ fireEvent.click(within(card).getByRole("button", { name: /^next$/i }));+ expect(card.querySelector(".qc-step[data-active] .qc-title")?.textContent).toBe(HOST.question);+ expect(card.textContent).toMatch(/no answer came/i);+ });++ it("reads a dismissed card as muted", () => {+ draw(questionOf(asking([+ ev("question_resolved", { turn_id: "t1", question_id: "q1", answers: [{ answer: "", option_index: null, source: "declined" }] }),+ ], [DB])));+ const card = screen.getByTestId("question-card");+ expect(card.hasAttribute("data-dismissed")).toBe(true);+ expect(card.textContent).toContain("Skipped");+ });++ it("turns a card answered in the chat into the question and the reply", () => {+ draw(questionOf(asking([+ ev("question_resolved", {+ turn_id: "t1",+ question_id: "q1",+ answers: [+ { answer: "Neither, use files", option_index: null, source: "message" },+ { answer: "Laptop", option_index: 0, source: "moved_on" },+ ],+ }),+ ])));+ const card = screen.getByTestId("question-card");+ expect(card.getAttribute("data-state")).toBe("message");+ expect(card.textContent).toContain(DB.question);+ expect(card.querySelector(".qc-reply-bubble")?.textContent).toBe("Neither, use files");+ });+});++describe("answering from the composer", () => {+ function storeWith(events: AgentChatEvent[]) {+ const store = createAgentChatStore("society");+ store.setState({ activeSessionId: "s1", timeline: reduceEvents(EMPTY_TIMELINE, events) });+ return store;+ }++ it("routes a message to the open card and reports whether the turn took it", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(JSON.stringify({ ok: true, consumed: true, question_id: "q1" }), { status: 200 }),+ );+ const store = storeWith(asking([], [DB]));+ await expect(store.getState().answerByMessage!("Postgres please")).resolves.toBe(true);+ const [url, init] = fetchMock.mock.calls[0];+ expect(String(url)).toBe("/api/agent-chat/sessions/s1/reply-to-question");+ expect(JSON.parse(String((init as RequestInit).body))).toEqual({ text: "Postgres please" });+ });++ it("sends nothing special without an open card, and falls back on a failed route", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch");+ const closed = storeWith(asking([ev("turn_finished", { turn_id: "t1", status: "done" })], [DB]));+ await expect(closed.getState().answerByMessage!("hello")).resolves.toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ fetchMock.mockResolvedValue(new Response("{}", { status: 500 }));+ await expect(storeWith(asking([], [DB])).getState().answerByMessage!("hello")).resolves.toBe(false);+ });++ it("a newer message from the person means no card is open any more", async () => {+ const { openQuestionOf } = await import("./questions/questionModel");+ const open = reduceEvents(EMPTY_TIMELINE, asking([], [DB], { deferred: true }));+ expect(openQuestionOf(open)?.question.questionId).toBe("q1");+ const after = reduceEvents(EMPTY_TIMELINE, [+ ...asking([], [DB], { deferred: true }),+ ev("user_message", { turn_id: "t2", text: "never mind" }),+ ]);+ expect(openQuestionOf(after)).toBeNull();+ });+});++describe("the reviewed submit", () => {+ it("posts the answers and treats a closed card as done", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(JSON.stringify({ detail: "no such open question" }), { status: 404 }),+ );+ const store = createAgentChatStore("society");+ store.setState({ activeSessionId: "s1" });+ await act(async () => {+ await store.getState().submitQuestion!("q1", [{ option_index: 1 }, { skip: true }]);+ });+ const [url, init] = fetchMock.mock.calls[0];+ expect(String(url)).toBe("/api/agent-chat/sessions/s1/questions/q1/submit");+ expect(JSON.parse(String((init as RequestInit).body))).toEqual({ answers: [{ option_index: 1 }, { skip: true }] });+ fetchMock.mockResolvedValue(new Response(JSON.stringify({ detail: "boom" }), { status: 500 }));+ await expect(store.getState().submitQuestion!("q1", [])).rejects.toThrow("boom");});});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.tsxindex f1cf6a63fb..44296d6b42 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.tsx@@ -1,283 +1,6 @@-import { memo, useEffect, useRef, useState, type FormEvent, type KeyboardEvent } from "react";-import { Check, CornerDownLeft, MessageCircleQuestion, PenLine, X } from "lucide-react";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";-import type { QuestionAnswerInput } from "@/lib/agentChatApi";-import { useAgentChat } from "./AgentChatStoreContext";-import type { QuestionAnswerState, QuestionState } from "./reduce";-/**- * An agent's question card (dodaios/agent_chat/questions.py).- *- * A short series the person answers one at a time ("question 1 of 3"). Each- * question lists its prepared answers as lettered rows, the agent's- * recommendation first. The close button leaves the open questions to the- * agent, and a countdown shows when that happens on its own — doing nothing- * is an answer too, so a workflow never waits forever.+ * The question card moved into `./questions/` (shell, steps, rows, review,+ * settled view, drafts and the keyboard target). This path stays for the+ * chats that import it: the society messenger, the front page and the IDE.*/--const LETTERS = "ABCD";--function useRemaining(expiresMs: number | null, live: boolean): number | null {- const [now, setNow] = useState(Date.now);- useEffect(() => {- if (!live || expiresMs === null) return;- setNow(Date.now());- 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")}`;-}--function useTitle(question: QuestionState): string {- const t = useT();- const name = question.asker || t("question_card.fallback_agent");- return question.questions.length > 1- ? t("question_card.title_many").replace("{agent}", name).replace("{count}", String(question.questions.length))- : t("question_card.title_one").replace("{agent}", name);-}--export const QuestionCard = memo(function QuestionCard({ question }: { question: QuestionState }) {- if (question.closed) return <AnsweredCard question={question} />;- return <OpenCard question={question} />;-});--function OpenCard({ question }: { question: QuestionState }) {- const t = useT();- const title = useTitle(question);- const answerQuestion = useAgentChat((s) => s.answerQuestion);- const skipQuestion = useAgentChat((s) => s.skipQuestion);- const total = question.questions.length;- const current = Math.max(0, question.answers.findIndex((a) => a === null));- const item = question.questions[current];- const remaining = useRemaining(question.expiresMs, true);- 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);-- // A new step starts clean: the server confirmed the previous answer.- useEffect(() => {- setBusy(false);- setTyping(false);- setText("");- submitting.current = false;- }, [current]);-- const run = async (action: () => Promise<void>) => {- if (submitting.current) return;- submitting.current = true;- setBusy(true);- setError(null);- try {- await action();- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- submitting.current = false;- setBusy(false);- }- };- const answer = (input: QuestionAnswerInput) => run(() => answerQuestion(question.questionId, current, input));- const skip = () => run(() => skipQuestion(question.questionId));-- const submitText = (event: FormEvent) => {- event.preventDefault();- const typed = text.trim();- if (typed) void answer({ text: typed });- };-- const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {- if (typing || busy || event.ctrlKey || event.metaKey || event.altKey) return;- const index = LETTERS.indexOf(event.key.toUpperCase());- if (event.key.length === 1 && index >= 0 && index < item.options.length) {- event.preventDefault();- void answer({ optionIndex: index });- }- };-- return (- <section- role="group"- aria-label={title}- tabIndex={-1}- onKeyDown={onKeyDown}- data-testid="question-card"- data-state="open"- className="my-2 w-full max-w-2xl rounded-2xl border border-border bg-card p-5 text-foreground shadow-sm focus:outline-none"- >- <header className="flex items-start gap-3">- <div className="min-w-0 flex-1">- <h3 className="text-lg font-semibold leading-7 [overflow-wrap:anywhere]">{title}</h3>- <p className="mt-1 text-base leading-6 text-muted-foreground [overflow-wrap:anywhere]">{item.question}</p>- </div>- {total > 1 ? (- <span className="mt-1.5 shrink-0 text-xs tabular-nums text-muted-foreground" data-testid="question-step">- {t("question_card.step").replace("{current}", String(current + 1)).replace("{total}", String(total))}- </span>- ) : null}- <button- type="button"- onClick={() => void skip()}- disabled={busy}- aria-label={t("question_card.close")}- title={t("question_card.close")}- className="-mr-1 -mt-0.5 shrink-0 rounded-md p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"- >- <X aria-hidden className="h-5 w-5" />- </button>- </header>-- {total > 1 ? (- <div className="mt-3 flex gap-1" aria-hidden>- {question.questions.map((_, i) => (- <span key={i} className={cn("h-1 flex-1 rounded-full", i <= current ? "bg-primary" : "bg-muted")} />- ))}- </div>- ) : null}-- <div className="mt-4 overflow-hidden rounded-xl border border-border">- {item.options.map((option, index) => (- <button- key={option.label}- type="button"- disabled={busy}- onClick={() => void answer({ optionIndex: index })}- data-recommended={index === 0 ? "true" : "false"}- className="flex w-full items-center gap-4 border-b border-border px-4 py-3 text-left !text-base transition-colors hover:bg-secondary focus-visible:bg-secondary focus-visible:outline-none disabled:opacity-60"- >- <span className="grid h-8 w-8 shrink-0 place-items-center rounded-md bg-muted !text-sm font-medium text-muted-foreground">- {LETTERS[index]}- </span>- <span className="min-w-0 flex-1">- <span className="block [overflow-wrap:anywhere]">{option.label}</span>- {option.description ? (- <span className="mt-0.5 block !text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere]">- {option.description}- </span>- ) : null}- </span>- {index === 0 ? (- <span className="shrink-0 rounded-full border border-primary/40 px-2 py-0.5 !text-[11px] font-medium text-primary">- {t("question_card.recommended")}- </span>- ) : null}- </button>- ))}- {typing ? (- <form onSubmit={submitText} className="flex items-center gap-4 px-4 py-2.5">- <span className="grid h-8 w-8 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">- <PenLine aria-hidden className="h-4 w-4" />- </span>- <input- autoFocus- value={text}- onChange={(event) => setText(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Escape") setTyping(false);- }}- maxLength={2000}- placeholder={t("question_card.own_placeholder")}- aria-label={t("question_card.own_answer")}- className="min-w-0 flex-1 bg-transparent text-base text-foreground placeholder:text-muted-foreground focus-visible:outline-none"- />- <button- type="submit"- disabled={busy || !text.trim()}- aria-label={t("question_card.send")}- title={t("question_card.send")}- className="shrink-0 rounded-md p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-40"- >- <CornerDownLeft aria-hidden className="h-4 w-4" />- </button>- </form>- ) : (- <button- type="button"- disabled={busy}- onClick={() => setTyping(true)}- className="flex w-full items-center gap-4 px-4 py-3 text-left !text-base text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:bg-secondary focus-visible:outline-none disabled:opacity-60"- >- <span className="grid h-8 w-8 shrink-0 place-items-center rounded-md bg-muted">- <PenLine aria-hidden className="h-4 w-4" />- </span>- <span>{t("question_card.own_answer")}</span>- </button>- )}- </div>-- <footer className="mt-3 space-y-1 text-xs leading-5 text-muted-foreground">- {item.recommendationReason ? (- <p className="[overflow-wrap:anywhere]">- {t("question_card.why").replace("{reason}", item.recommendationReason)}- </p>- ) : null}- {remaining !== null ? (- <p 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-destructive">- {error}- </p>- ) : null}- </footer>- </section>- );-}--function AnsweredCard({ question }: { question: QuestionState }) {- const title = useTitle(question);- return (- <div- data-testid="question-card"- data-state={question.answers.map((a) => a?.source ?? "closed").join(" ")}- className="my-1 w-full max-w-2xl rounded-xl border border-border px-4 py-3 text-sm text-muted-foreground"- >- <p className="flex items-center gap-2 text-xs">- <MessageCircleQuestion aria-hidden className="h-3.5 w-3.5 shrink-0" />- <span>{title}</span>- </p>- <ul className="mt-2 space-y-2">- {question.questions.map((item, i) => (- <li key={i} className="[overflow-wrap:anywhere]">- <p>{item.question}</p>- <AnswerLine answer={question.answers[i]} />- </li>- ))}- </ul>- </div>- );-}--function AnswerLine({ answer }: { answer: QuestionAnswerState | null }) {- const t = useT();- if (!answer || answer.source === "cancelled" || answer.source === "closed") {- return <p className="mt-0.5 text-xs">{t("question_card.unanswered")}</p>;- }- const note =- answer.source === "timeout"- ? t("question_card.auto_picked")- : answer.source === "skipped"- ? t("question_card.left_to_agent")- : answer.optionIndex === null- ? t("question_card.own_words")- : answer.optionIndex === 0- ? t("question_card.recommended")- : "";- return (- <p className="mt-0.5 flex flex-wrap items-center gap-1.5">- <Check aria-hidden className="h-3.5 w-3.5 text-primary" />- <span className="font-medium text-foreground">{answer.text}</span>- {note ? <span className="text-xs">· {note}</span> : null}- </p>- );-}+export { QuestionCard } from "./questions/QuestionCard";diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/runViewModels.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/runViewModels.test.tsindex 11d416c86b..223d568d16 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/activity/runViewModels.test.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/runViewModels.test.ts@@ -101,7 +101,7 @@ describe("countUnseen", () => {describe("run announcer", () => {const question = call("society_ask_user", {}, null, {- callId: "q", question: { questionId: "q1", asker: "", questions: [{ question: "Which branch?", options: [], recommendationReason: "" }],+ callId: "q", question: { questionId: "q1", asker: "", questions: [{ question: "Which branch?", options: [], recommendationReason: "", kind: "single", allowCustom: true, recommendedCount: 1 }],answers: [null], expiresMs: null, closed: false },});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/KeyCap.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/KeyCap.tsxnew file mode 100644index 0000000000..cbf97f8b3f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/KeyCap.tsx@@ -0,0 +1,10 @@+import type { ReactNode } from "react";++/** The letter tile in front of a row; filled in the agent's colour once chosen. */+export function KeyCap({ children, on = false, size }: { children: ReactNode; on?: boolean; size?: "sm" }) {+ return (+ <span className="qc-keycap" data-on={on ? "" : undefined} data-size={size} aria-hidden>+ {children}+ </span>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/OptionRow.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/OptionRow.tsxnew file mode 100644index 0000000000..725bc20486--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/OptionRow.tsx@@ -0,0 +1,98 @@+import { forwardRef, useLayoutEffect, useRef, type KeyboardEvent } from "react";+import { PenLine } from "lucide-react";+import { useT } from "@/i18n";+import type { QuestionOption } from "../reduce";+import { KeyCap } from "./KeyCap";++/** One prepared answer: a lettered row, toggled for a multi-select question. */+export function OptionRow({+ letter,+ option,+ selected,+ multi,+ recommended,+ disabled,+ onPick,+}: {+ letter: string;+ option: QuestionOption;+ selected: boolean;+ multi: boolean;+ recommended: boolean;+ disabled: boolean;+ onPick: () => void;+}) {+ const t = useT();+ return (+ <button+ type="button"+ data-qc-row=""+ data-recommended={recommended ? "true" : "false"}+ data-described={option.description ? "" : undefined}+ aria-pressed={multi ? selected : undefined}+ aria-keyshortcuts={letter}+ disabled={disabled}+ onClick={onPick}+ className="qc-row"+ >+ <KeyCap on={selected}>{letter}</KeyCap>+ <span className="qc-row-body">+ <span className="qc-label">{option.label}</span>+ {option.description ? <span className="qc-desc">{option.description}</span> : null}+ </span>+ {recommended ? <span className="qc-tag">{t("question_card.recommended")}</span> : null}+ </button>+ );+}++/**+ * The person's own words: an auto-growing field behind the next letter.+ * Enter sends it, Shift+Enter starts a new line, Escape leaves the field.+ */+export const OwnAnswerRow = forwardRef<HTMLTextAreaElement, {+ letter: string | null;+ value: string;+ placeholder: string;+ disabled: boolean;+ onChange: (text: string) => void;+ onSubmit: () => void;+}>(function OwnAnswerRow({ letter, value, placeholder, disabled, onChange, onSubmit }, ref) {+ const t = useT();+ const local = useRef<HTMLTextAreaElement | null>(null);+ // Browsers without `field-sizing: content` grow the field by hand.+ useLayoutEffect(() => {+ const el = local.current;+ if (!el || (typeof CSS !== "undefined" && CSS.supports?.("field-sizing", "content"))) return;+ el.style.height = "auto";+ el.style.height = `${el.scrollHeight}px`;+ }, [value]);+ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {+ event.preventDefault();+ onSubmit();+ } else if (event.key === "Escape") {+ event.currentTarget.blur();+ }+ };+ return (+ <label className="qc-own" data-qc-own="">+ <KeyCap on={Boolean(value.trim())}>{letter ?? <PenLine className="h-3 w-3" />}</KeyCap>+ <textarea+ ref={(el) => {+ local.current = el;+ if (typeof ref === "function") ref(el);+ else if (ref) ref.current = el;+ }}+ rows={1}+ value={value}+ disabled={disabled}+ maxLength={2000}+ placeholder={placeholder}+ aria-label={t("question_card.own_answer")}+ aria-keyshortcuts={letter ?? undefined}+ onChange={(event) => onChange(event.target.value)}+ onKeyDown={onKeyDown}+ />+ </label>+ );+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionCard.tsxnew file mode 100644index 0000000000..333346bcfc--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionCard.tsx@@ -0,0 +1,431 @@+import { memo, useEffect, useId, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";+import { CircleAlert, CornerDownLeft, MoreHorizontal, SkipForward, Sparkles, X } from "lucide-react";+import { useT } from "@/i18n";+import type { QuestionState } from "../reduce";+import { AskerMark, useAskerLook } from "./askerLook";+import { patchQuestionDraft, useQuestionDraft, useQuestionDrafts, type QuestionDraft } from "./questionDraftStore";+import {+ answerAsLocal,+ EMPTY_ANSWER,+ hasAnswer,+ LETTERS,+ pickSingle,+ remainingMs,+ RING_WINDOW_MS,+ toggleMulti,+ withText,+ type LocalAnswer,+} from "./questionModel";+import { QuestionStep } from "./QuestionStep";+import { Dots, SettledQuestion } from "./SettledQuestion";+import { useQuestionActions } from "./useQuestionActions";+import { useQuestionKeyboard } from "./useQuestionKeyboard";+import "./questionCard.css";++/**+ * An agent's question card (dodaios/agent_chat/questions.py).+ *+ * A calm, forgiving exchange: lettered answers the person picks by click or+ * by plain letter key, their own words behind the next letter, several picks+ * for a multi-select question, and a short series with Back, Skip and a+ * review step where any answer can still change before one Send. Answers+ * settle the card at once and roll back with Try again if they did not get+ * through. The quiet window shows only in its last minute; the menu offers+ * to skip this one question or to let the agent decide them all.+ */+export const QuestionCard = memo(function QuestionCard({ question }: { question: QuestionState }) {+ const t = useT();+ const draft = useQuestionDraft(question.questionId);+ const look = useAskerLook(question.asker);+ const agentName = question.asker || t("question_card.fallback_agent");+ const submission = draft.submission;+ // The server's word wins; until it comes, a sent answer already reads as settled.+ useEffect(() => {+ if (question.closed && submission) patchQuestionDraft(question.questionId, (d) => ({ ...d, submission: null, answers: [] }));+ }, [question.closed, question.questionId, submission]);+ if (question.closed) {+ return <SettledQuestion question={question} agent={look.agent} style={look.style} agentName={agentName} pending={false} />;+ }+ if (submission && submission.status !== "failed") {+ return (+ <SettledQuestion+ question={{ ...question, answers: submission.answers, closed: true }}+ agent={look.agent}+ style={look.style}+ agentName={agentName}+ pending+ />+ );+ }+ return <OpenCard question={question} draft={draft} look={look} agentName={agentName} />;+});++function useRemaining(question: QuestionState): number | null {+ const [now, setNow] = useState(() => Date.now());+ const left = remainingMs(question, now);+ useEffect(() => {+ if (left === null || left <= 0) return;+ // Sleep until the last minute starts, then tick once a second.+ const delay = left > RING_WINDOW_MS ? left - RING_WINDOW_MS : 1000;+ const id = window.setTimeout(() => setNow(Date.now()), Math.min(delay, 2_147_000_000));+ return () => window.clearTimeout(id);+ }, [left]);+ return left;+}++function clock(ms: number): string {+ const seconds = Math.ceil(ms / 1000);+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;+}++/** A slim ring that empties over the last minute of a live card. */+function CountdownRing({ question }: { question: QuestionState }) {+ const t = useT();+ const left = useRemaining(question);+ if (left === null || left > RING_WINDOW_MS) return null;+ const label = t("question_card.countdown").replace("{time}", clock(left));+ const r = 7;+ const length = 2 * Math.PI * r;+ return (+ <span className="qc-ring" role="timer" aria-live="off" aria-label={label} title={label} data-testid="question-countdown">+ <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden>+ <circle className="qc-ring-track" cx="9" cy="9" r={r} />+ <circle className="qc-ring-left" cx="9" cy="9" r={r} strokeDasharray={length}+ strokeDashoffset={length * (1 - left / RING_WINDOW_MS)} transform="rotate(-90 9 9)" />+ </svg>+ </span>+ );+}++function OpenCard({+ question,+ draft,+ look,+ agentName,+}: {+ question: QuestionState;+ draft: QuestionDraft;+ look: ReturnType<typeof useAskerLook>;+ agentName: string;+}) {+ const t = useT();+ const titleId = useId();+ const cardRef = useRef<HTMLElement>(null);+ const ownRefs = useRef<(HTMLTextAreaElement | null)[]>([]);+ const advance = useRef<number | null>(null);+ const [menuOpen, setMenuOpen] = useState(false);+ const [entered] = useState(() => (question.closed ? undefined : "new"));+ const actions = useQuestionActions(question);+ const { questionId, questions } = question;+ const total = questions.length;+ const series = total > 1;+ const failed = draft.submission?.status === "failed" ? draft.submission : null;++ const locals: LocalAnswer[] = questions.map((item, i) => draft.answers[i] ?? answerAsLocal(question.answers[i], item));+ const firstOpen = Math.max(0, question.answers.findIndex((a) => a === null));+ const step = Math.min(draft.step < 0 ? firstOpen : draft.step, series ? total : 0);+ const reviewing = series && step === total;+ const item = reviewing ? null : questions[step];+ const local = reviewing ? EMPTY_ANSWER : locals[step];+ const locked = (i: number) => question.answers[i] !== null;++ useEffect(() => () => {+ if (advance.current !== null) window.clearTimeout(advance.current);+ }, []);++ const write = (fn: (d: QuestionDraft, current: LocalAnswer[]) => QuestionDraft) => {+ patchQuestionDraft(questionId, (d) => {+ const current = questions.map((q, i) => d.answers[i] ?? answerAsLocal(question.answers[i], q));+ return fn(d, current);+ });+ actions.touch();+ };+ const setLocal = (index: number, next: LocalAnswer) =>+ write((d, current) => ({ ...d, answers: current.map((a, i) => (i === index ? next : a)) }));+ const goTo = (next: number) => {+ if (advance.current !== null) window.clearTimeout(advance.current);+ advance.current = null;+ write((d) => ({ ...d, step: Math.max(0, Math.min(next, total)) }));+ };+ /** Send the whole card with `override` folded in (the read is the store's newest). */+ const submitWith = (index: number, override: LocalAnswer) => {+ const current = questions.map((q, i) => {+ const saved = useQuestionDrafts.getState().drafts[questionId]?.answers[i];+ return i === index ? override : saved ?? answerAsLocal(question.answers[i], q);+ });+ setLocal(index, override);+ void actions.submit(current);+ };++ const pick = (optionIndex: number) => {+ if (!item || locked(step)) return;+ if (item.kind === "multi") {+ setLocal(step, toggleMulti(local, optionIndex));+ return;+ }+ const next = pickSingle(optionIndex);+ if (!series) {+ submitWith(step, next);+ return;+ }+ setLocal(step, next);+ // Let the pick show for a beat, then move on; the review step follows the last.+ if (advance.current !== null) window.clearTimeout(advance.current);+ const from = step;+ advance.current = window.setTimeout(() => {+ advance.current = null;+ patchQuestionDraft(questionId, (d) => ((d.step < 0 ? firstOpen : d.step) === from ? { ...d, step: from + 1 } : d));+ }, 180);+ };+ const typed = (text: string) => item && setLocal(step, withText(local, item, text));+ const commitStep = () => {+ if (!item) return;+ if (!series) {+ // Done with nothing picked skips the question instead of sending nothing.+ submitWith(step, hasAnswer(local) ? local : { ...EMPTY_ANSWER, skipped: true });+ return;+ }+ goTo(step + 1);+ };+ const skipStep = () => {+ setMenuOpen(false);+ const skipped = { ...EMPTY_ANSWER, skipped: true };+ if (!series) {+ submitWith(step, skipped);+ return;+ }+ setLocal(step, skipped);+ goTo(step + 1);+ };+ const decideAll = () => {+ setMenuOpen(false);+ void actions.decideAll();+ };+ const sendSeries = () => void actions.submit(locals);++ const onKey = (event: KeyboardEvent): boolean => {+ if (!item || menuOpen || draft.submission?.status === "sending") return false;+ if (event.key.length !== 1) return false;+ const index = LETTERS.indexOf(event.key.toUpperCase());+ if (index < 0) return false;+ if (index < item.options.length) {+ pick(index);+ return true;+ }+ if (item.allowCustom && index === item.options.length) {+ ownRefs.current[step]?.focus();+ return true;+ }+ return false;+ };+ const target = useQuestionKeyboard(cardRef, onKey, true);++ // Arrow keys walk the rows of the step on screen once one has focus.+ const onCardKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {+ if (event.key === "Escape" && menuOpen) {+ event.preventDefault();+ setMenuOpen(false);+ return;+ }+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;+ const rows = Array.from(cardRef.current?.querySelectorAll<HTMLElement>(+ ".qc-step[data-active] [data-qc-row]:not(:disabled), .qc-step[data-active] [data-qc-own] textarea",+ ) ?? []);+ const at = rows.findIndex((el) => el === document.activeElement);+ if (at < 0 || rows[at].tagName === "TEXTAREA" && event.key === "ArrowDown") return;+ event.preventDefault();+ rows[(at + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length]?.focus();+ };++ const answered = locals.map(hasAnswer);+ // A lone single question shows Send once the person typed their own words.+ const typedSingle = !series && item?.kind === "single" && Boolean(local.text.trim());+ const footer = series || item?.kind === "multi" || item?.kind === "text" || typedSingle || failed;++ return (+ <section+ ref={cardRef}+ className="qc"+ data-enter={entered}+ data-target={target ? "" : undefined}+ data-testid="question-card"+ data-state="open"+ aria-labelledby={titleId}+ onKeyDown={onCardKeyDown}+ style={look.style}+ >+ <header className="qc-head">+ <AskerMark agent={look.agent} />+ <span className="qc-asker">+ <b>{agentName}</b> {t("question_card.asks")}+ </span>+ {series && !reviewing ? (+ <span className="qc-count" data-testid="question-step">+ {t("question_card.step").replace("{current}", String(Math.min(step + 1, total))).replace("{total}", String(total))}+ </span>+ ) : null}+ <span className="flex-1" />+ <CountdownRing question={question} />+ <button+ type="button"+ className="qc-icon-btn"+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ aria-label={t("question_card.menu")}+ title={t("question_card.menu")}+ onClick={() => setMenuOpen((open) => !open)}+ >+ {menuOpen ? <X aria-hidden className="h-4 w-4" /> : <MoreHorizontal aria-hidden className="h-4 w-4" />}+ </button>+ </header>++ {menuOpen ? (+ <CardMenu+ agentName={agentName}+ canSkipStep={Boolean(item) && !locked(step)}+ onSkipStep={skipStep}+ onDecideAll={decideAll}+ onClose={() => setMenuOpen(false)}+ />+ ) : null}++ <div className="qc-steps">+ {questions.map((q, i) => (+ <QuestionStep+ key={i}+ ref={(el) => {+ ownRefs.current[i] = el;+ }}+ item={q}+ local={locals[i]}+ active={i === step}+ locked={locked(i)}+ titleId={i === step ? titleId : undefined}+ onPick={pick}+ onText={typed}+ onSubmitText={commitStep}+ />+ ))}+ {series ? (+ <div className="qc-step" data-active={reviewing ? "" : undefined} aria-hidden={reviewing ? undefined : true}+ {...(reviewing ? {} : ({ inert: "" } as Record<string, string>))}>+ <h3 id={reviewing ? titleId : undefined} className="qc-title">{t("question_card.review_title")}</h3>+ <div className="qc-review" data-testid="question-review">+ {questions.map((q, i) => {+ const a = locals[i];+ const text = a.skipped || !hasAnswer(a)+ ? ""+ : [...a.picks.map((p) => q.options[p]?.label), ...(a.text.trim() ? [a.text.trim()] : [])].join("\n");+ return (+ <button key={i} type="button" className="qc-review-row" onClick={() => goTo(i)} disabled={locked(i)}+ aria-label={`${q.question}: ${text || t("question_card.skipped_chip")}. ${t("question_card.change")}`}>+ <span className="qc-keycap" data-on={text ? "" : undefined} aria-hidden>{i + 1}</span>+ <span className="min-w-0 flex-1">+ <span className="qc-review-q">{q.question}</span>+ <span className="qc-review-a" data-empty={text ? undefined : ""}>{text || t("question_card.skipped_chip")}</span>+ </span>+ {locked(i) ? null : <span className="qc-review-edit">{t("question_card.change")}</span>}+ </button>+ );+ })}+ </div>+ </div>+ ) : null}+ </div>++ {footer ? (+ <footer className="qc-foot">+ {failed ? (+ <p role="alert" className="qc-alert">+ <CircleAlert aria-hidden className="h-3.5 w-3.5 shrink-0" />+ <span>{t("question_card.failed")}</span>+ </p>+ ) : series ? (+ <Dots total={total} current={step} done={answered} label={t("question_card.step")} />+ ) : null}+ <span className="qc-foot-end">+ {failed ? (+ <button type="button" className="qc-btn qc-btn-quiet" onClick={() => void actions.retry()} title={failed.error}>+ {t("question_card.try_again")}+ </button>+ ) : null}+ {series && step > 0 ? (+ <button type="button" className="qc-btn qc-btn-quiet" onClick={() => goTo(step - 1)}>{t("question_card.back")}</button>+ ) : null}+ {series && !reviewing ? (+ <button type="button" className="qc-btn qc-btn-quiet" onClick={skipStep} disabled={locked(step)}>+ {t("question_card.skip")}+ </button>+ ) : null}+ {series && !reviewing ? (+ <button type="button" className="qc-btn qc-btn-primary" onClick={() => goTo(step + 1)} disabled={!hasAnswer(local) && !locked(step)}>+ {step === total - 1 ? t("question_card.review") : t("question_card.next")}+ </button>+ ) : null}+ {reviewing ? (+ <button type="button" className="qc-btn qc-btn-primary" data-testid="question-send" onClick={sendSeries}>+ {t("question_card.send_answers")}+ </button>+ ) : null}+ {!series && item && (item.kind !== "single" || typedSingle) && !failed ? (+ <button type="button" className="qc-btn qc-btn-primary" data-testid="question-done" onClick={commitStep}>+ {item.kind === "multi" ? null : <CornerDownLeft aria-hidden className="h-3.5 w-3.5" />}+ {item.kind === "multi" ? t("question_card.done") : t("question_card.send")}+ </button>+ ) : null}+ </span>+ </footer>+ ) : (+ <div className="h-1" />+ )}+ {target ? <span className="qc-sr" aria-live="polite">{t("question_card.keys_hint")}</span> : null}+ </section>+ );+}++/** The card's own menu: two clearly named ways out, never a silent close. */+function CardMenu({+ agentName,+ canSkipStep,+ onSkipStep,+ onDecideAll,+ onClose,+}: {+ agentName: string;+ canSkipStep: boolean;+ onSkipStep: () => void;+ onDecideAll: () => void;+ onClose: () => void;+}) {+ const t = useT();+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => {+ ref.current?.querySelector<HTMLButtonElement>("button")?.focus();+ const away = (event: PointerEvent) => {+ const el = ref.current;+ if (el && !el.contains(event.target as Node) && !(event.target as HTMLElement).closest?.(".qc-icon-btn")) onClose();+ };+ document.addEventListener("pointerdown", away);+ return () => document.removeEventListener("pointerdown", away);+ }, [onClose]);+ return (+ <div ref={ref} className="qc-menu" role="menu" aria-label={t("question_card.menu")}>+ {canSkipStep ? (+ <button type="button" role="menuitem" className="qc-menu-item" onClick={onSkipStep}>+ <SkipForward aria-hidden className="h-4 w-4" />+ <span>+ <span className="qc-menu-title">{t("question_card.skip_this")}</span>+ <span className="qc-menu-hint">{t("question_card.skip_this_hint").replace("{agent}", agentName)}</span>+ </span>+ </button>+ ) : null}+ <button type="button" role="menuitem" className="qc-menu-item" onClick={onDecideAll}>+ <Sparkles aria-hidden className="h-4 w-4" />+ <span>+ <span className="qc-menu-title">{t("question_card.let_decide").replace("{agent}", agentName)}</span>+ <span className="qc-menu-hint">{t("question_card.let_decide_hint")}</span>+ </span>+ </button>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionStep.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionStep.tsxnew file mode 100644index 0000000000..e85b51829b--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionStep.tsx@@ -0,0 +1,77 @@+import { forwardRef, useId, useState } from "react";+import { ChevronDown, Info } from "lucide-react";+import { useT } from "@/i18n";+import type { QuestionItem } from "../reduce";+import { OptionRow, OwnAnswerRow } from "./OptionRow";+import { LETTERS, type LocalAnswer } from "./questionModel";++/**+ * One question of the card: its prompt as the title, the lettered answers,+ * and the person's own-words row behind the next letter. Every step of a+ * series is drawn at once and stacked in one grid cell (QuestionCard), so+ * only `active` is visible and the card keeps the height of its tallest step.+ */+export const QuestionStep = forwardRef<HTMLTextAreaElement, {+ item: QuestionItem;+ local: LocalAnswer;+ active: boolean;+ locked: boolean;+ titleId?: string;+ onPick: (index: number) => void;+ onText: (text: string) => void;+ onSubmitText: () => void;+}>(function QuestionStep({ item, local, active, locked, titleId, onPick, onText, onSubmitText }, ref) {+ const t = useT();+ const [why, setWhy] = useState(false);+ const reasonId = useId();+ const multi = item.kind === "multi";+ const help = multi ? t("question_card.pick_many") : item.kind === "text" ? t("question_card.write_answer") : "";+ const ownLetter = item.kind === "text" && !item.options.length ? null : LETTERS[item.options.length] ?? null;+ return (+ <div className="qc-step" data-active={active ? "" : undefined} aria-hidden={active ? undefined : true}+ // An inactive step keeps its height but must not take focus or clicks.+ {...(active ? {} : ({ inert: "" } as Record<string, string>))}>+ <h3 id={titleId} className="qc-title">{item.question}</h3>+ {help ? <p className="qc-help">{help}</p> : null}+ <div className="qc-list" role="group" aria-label={item.question}>+ {item.options.map((option, index) => (+ <OptionRow+ key={`${index}:${option.label}`}+ letter={LETTERS[index]}+ option={option}+ multi={multi}+ selected={local.picks.includes(index)}+ recommended={index < item.recommendedCount}+ disabled={locked}+ onPick={() => onPick(index)}+ />+ ))}+ {item.allowCustom ? (+ <OwnAnswerRow+ ref={ref}+ letter={ownLetter}+ value={local.text}+ disabled={locked}+ placeholder={item.kind === "text" ? t("question_card.text_placeholder") : t("question_card.something_else")}+ onChange={onText}+ onSubmit={onSubmitText}+ />+ ) : null}+ </div>+ {item.recommendationReason && item.options.length ? (+ <>+ <button type="button" className="qc-why" aria-expanded={why} aria-controls={reasonId} onClick={() => setWhy((open) => !open)}>+ <Info aria-hidden className="h-3.5 w-3.5" />+ <span>{t("question_card.why_toggle")}</span>+ <ChevronDown aria-hidden className="qc-chevron h-3 w-3" style={why ? { transform: "rotate(180deg)" } : undefined} />+ </button>+ <div className="qc-collapse" data-open={why ? "" : undefined} id={reasonId}>+ <div>+ <p className="qc-reason">{item.recommendationReason}</p>+ </div>+ </div>+ </>+ ) : null}+ </div>+ );+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/SettledQuestion.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/SettledQuestion.tsxnew file mode 100644index 0000000000..ded651cdf4--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/SettledQuestion.tsx@@ -0,0 +1,235 @@+import { useEffect, useState, type CSSProperties } from "react";+import { ArrowRight, Check, ChevronDown, Clock3, Copy, CornerUpRight, Sparkles } from "lucide-react";+import { useT } from "@/i18n";+import type { SocietyAgent } from "@/components/society/data";+import type { QuestionItem, QuestionState } from "../reduce";+import { AskerMark } from "./askerLook";+import { KeyCap } from "./KeyCap";+import { patchQuestionDraft, useQuestionDraft } from "./questionDraftStore";+import {+ answeredByMessage,+ copyText,+ isDismissed,+ LETTERS,+ ownWords,+ pickedIndices,+ settledNote,+ type SettledNote,+} from "./questionModel";++const NOTE_KEY: Partial<Record<SettledNote, string>> = {+ auto: "question_card.note_auto",+ agent: "question_card.note_agent",+ declined: "question_card.note_declined",+ moved_on: "question_card.note_moved_on",+ message: "question_card.note_message",+ unanswered: "question_card.unanswered",+ own: "question_card.own_words",+};++const QUIET_MARK = { auto: Clock3, agent: Sparkles, moved_on: CornerUpRight } as const;++/** A short line under each answer: how it came about, when that is not obvious. */+function useNoteText() {+ const t = useT();+ return (note: SettledNote, agentName: string) => {+ const key = NOTE_KEY[note];+ return key ? t(key).replace("{agent}", agentName) : "";+ };+}++/**+ * A question card after it settled: one quiet line, "prompt → chosen answers",+ * that opens into a read-only review of every step. A card nobody answered+ * reads muted with a dotted chip; a card answered from the chat reads as the+ * plain question followed by the person's reply.+ */+export function SettledQuestion({+ question,+ agent,+ style,+ agentName,+ pending,+}: {+ question: QuestionState;+ agent: SocietyAgent | null;+ style: CSSProperties | undefined;+ agentName: string;+ /** The answer is on its way (optimistic). */+ pending: boolean;+}) {+ const t = useT();+ const draft = useQuestionDraft(question.questionId);+ const noteText = useNoteText();+ const [copied, setCopied] = useState(false);+ useEffect(() => {+ if (!copied) return;+ const id = window.setTimeout(() => setCopied(false), 1500);+ return () => window.clearTimeout(id);+ }, [copied]);++ if (answeredByMessage(question)) return <AnsweredInChat question={question} agent={agent} style={style} />;++ const total = question.questions.length;+ const dismissed = isDismissed(question);+ const expanded = draft.expanded;+ const page = Math.min(draft.page, total - 1);+ const sources = question.answers.map((a) => a?.source ?? "closed").join(" ");+ const toggle = () => patchQuestionDraft(question.questionId, (d) => ({ ...d, expanded: !d.expanded }));+ const copy = () => {+ void navigator.clipboard?.writeText(copyText(question)).then(() => setCopied(true), () => undefined);+ };+ // An answer nobody picked by hand gets a quiet mark; its sentence is the tooltip.+ const quiet = question.answers.map(settledNote).find((note) => note in QUIET_MARK) as keyof typeof QUIET_MARK | undefined;+ const marker = quiet && !dismissed ? { Icon: QUIET_MARK[quiet], text: noteText(quiet, agentName) } : null;+ const summary = total > 1+ ? t("question_card.title_many").replace("{agent}", agentName).replace("{count}", String(total))+ : question.questions[0].question;++ return (+ <div+ className="qc"+ data-settled=""+ data-dismissed={dismissed ? "" : undefined}+ data-testid="question-card"+ data-state={sources}+ style={style}+ >+ <div className="flex items-center">+ <button type="button" className="qc-sum" aria-expanded={expanded} onClick={toggle}+ aria-label={`${summary} — ${expanded ? t("question_card.collapse") : t("question_card.expand")}`}>+ <AskerMark agent={agent} size={20} />+ <span className="qc-sum-prompt">{summary}</span>+ <ArrowRight aria-hidden className="qc-sum-arrow h-3.5 w-3.5" />+ <span className="qc-chips">+ {dismissed ? (+ <span className="qc-chip" data-muted="" data-plain="">{t("question_card.skipped_chip")}</span>+ ) : (+ question.questions.flatMap((item, i) => answerChips(item, question.answers[i], i, t("question_card.skipped_chip")))+ )}+ </span>+ <span className="qc-sum-tail">+ {marker ? <marker.Icon aria-label={marker.text} className="h-3.5 w-3.5" /> : null}+ {pending ? <span className="qc-pending" title={t("question_card.sending")} aria-label={t("question_card.sending")} role="status" /> : null}+ <ChevronDown aria-hidden className="qc-chevron h-4 w-4" />+ </span>+ </button>+ <button type="button" className="qc-icon-btn mr-1.5" onClick={copy}+ aria-label={copied ? t("question_card.copied") : t("question_card.copy")}+ title={copied ? t("question_card.copied") : t("question_card.copy")}>+ {copied ? <Check aria-hidden className="h-3.5 w-3.5" /> : <Copy aria-hidden className="h-3.5 w-3.5" />}+ </button>+ </div>+ <div className="qc-collapse" data-open={expanded ? "" : undefined}>+ <div>+ {expanded ? (+ <>+ <div className="qc-steps">+ {question.questions.map((item, i) => {+ const answer = question.answers[i];+ const picked = pickedIndices(answer);+ const own = ownWords(answer, item);+ const note = settledNote(answer);+ const text = noteText(note === "picked" || note === "own" ? "picked" : note, agentName);+ return (+ <div key={i} className="qc-step" data-active={i === page ? "" : undefined} aria-hidden={i === page ? undefined : true}>+ <h3 className="qc-title">{item.question}</h3>+ <div className="qc-list" role="group" aria-label={t("question_card.answer_label")}>+ {picked.map((index) => (+ <div key={index} className="qc-row" data-described={item.options[index]?.description ? "" : undefined}>+ <KeyCap on>{LETTERS[index]}</KeyCap>+ <span className="qc-row-body">+ <span className="qc-label">{item.options[index]?.label}</span>+ {item.options[index]?.description ? <span className="qc-desc">{item.options[index].description}</span> : null}+ </span>+ </div>+ ))}+ {own ? (+ <div className="qc-row">+ <KeyCap on>{LETTERS[item.options.length] ?? "·"}</KeyCap>+ <span className="qc-row-body"><span className="qc-label whitespace-pre-line">{own}</span></span>+ </div>+ ) : null}+ {!picked.length && !own ? (+ item.options.map((option, index) => (+ <div key={index} className="qc-row" aria-disabled>+ <KeyCap>{LETTERS[index]}</KeyCap>+ <span className="qc-row-body"><span className="qc-label text-muted-foreground">{option.label}</span></span>+ </div>+ ))+ ) : null}+ </div>+ {text ? <p className="qc-note">{text}</p> : null}+ </div>+ );+ })}+ </div>+ {total > 1 ? (+ <div className="qc-foot">+ <Dots total={total} current={page} done={total} label={t("question_card.step")} />+ <span className="qc-foot-end">+ <button type="button" className="qc-btn qc-btn-quiet" disabled={page === 0}+ onClick={() => patchQuestionDraft(question.questionId, (d) => ({ ...d, page: Math.max(0, page - 1) }))}>+ {t("question_card.back")}+ </button>+ <button type="button" className="qc-btn qc-btn-quiet" disabled={page >= total - 1}+ onClick={() => patchQuestionDraft(question.questionId, (d) => ({ ...d, page: Math.min(total - 1, page + 1) }))}>+ {t("question_card.next")}+ </button>+ </span>+ </div>+ ) : <div className="h-2" />}+ </>+ ) : null}+ </div>+ </div>+ </div>+ );+}++function answerChips(item: QuestionItem, answer: QuestionState["answers"][number], index: number, skippedLabel: string) {+ const picked = pickedIndices(answer);+ const own = ownWords(answer, item);+ const chips = picked.map((i) => (+ <span key={`${index}:${i}`} className="qc-chip">+ <KeyCap on size="sm">{LETTERS[i]}</KeyCap>+ <span>{item.options[i]?.label}</span>+ </span>+ ));+ if (own) chips.push(<span key={`${index}:own`} className="qc-chip" data-plain=""><span>{own.split("\n").join(", ")}</span></span>);+ if (!chips.length) chips.push(<span key={`${index}:none`} className="qc-chip" data-muted="" data-plain=""><span>{skippedLabel}</span></span>);+ return chips;+}++/** Progress dots of a series: a pill for the step on screen, darker for done ones. */+export function Dots({ total, current, done, label }: { total: number; current: number; done: number | readonly boolean[]; label: string }) {+ const isDone = (i: number) => (typeof done === "number" ? i < done : Boolean(done[i]));+ const text = label.replace("{current}", String(Math.min(current + 1, total))).replace("{total}", String(total));+ return (+ <span className="qc-dots" role="img" aria-label={text}>+ {Array.from({ length: total }, (_, i) => (+ <span key={i} className="qc-dot" data-on={i === current ? "" : undefined} data-done={isDone(i) && i !== current ? "" : undefined} />+ ))}+ </span>+ );+}++/** The person answered in the chat: the question reads as the agent's message, the reply as theirs. */+function AnsweredInChat({ question, agent, style }: { question: QuestionState; agent: SocietyAgent | null; style: CSSProperties | undefined }) {+ const t = useT();+ const index = question.answers.findIndex((a) => a?.source === "message");+ const reply = question.answers[index]?.text ?? "";+ return (+ <div className="flex w-full flex-col gap-1.5" data-testid="question-card" data-state="message" style={style}>+ <div className="qc-asked">+ <AskerMark agent={agent} size={20} />+ <div className="qc-asked-bubble jarvis-chat-in">+ <span className="qc-sr">{t("question_card.asked")}</span>+ {question.questions.map((item, i) => <p key={i}>{item.question}</p>)}+ </div>+ </div>+ {/* An end-of-turn card's reply went out as an ordinary message, which the chat shows itself. */}+ {question.deferred || !reply ? null : <div className="qc-reply"><div className="qc-reply-bubble">{reply}</div></div>}+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/askerLook.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/askerLook.tsxnew file mode 100644index 0000000000..d0502e4d41--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/askerLook.tsx@@ -0,0 +1,34 @@+import { useContext, type CSSProperties } from "react";+import { QueryClientContext } from "@tanstack/react-query";+import { MessageCircleQuestion } from "lucide-react";+import { AgentSwatch, agentColor } from "@/components/society/AgentSwatch";+import type { RosterData, SocietyAgent } from "@/components/society/data";+import { bubbleTint } from "@/lib/bubbleTint";++/** The society roster's query key (components/society/data.ts). */+const ROSTER_KEY = ["society", "roster"] as const;++/**+ * Who is asking, as far as this chat already knows: the agent's face and its+ * colour. It only READS the roster the society section has loaded, so a card+ * on any other surface (front page, IDE) never triggers a fetch and simply+ * falls back to a neutral mark and the theme's primary fill.+ */+export function useAskerLook(asker: string): { agent: SocietyAgent | null; style: CSSProperties | undefined } {+ const client = useContext(QueryClientContext);+ const name = asker.trim().toLocaleLowerCase();+ const roster = name ? client?.getQueryData<RosterData>(ROSTER_KEY) : undefined;+ const agent = roster?.agents.find((a) => a.name.trim().toLocaleLowerCase() === name) ?? null;+ const tint = agent ? bubbleTint(agentColor(agent)) : null;+ const style = tint ? ({ "--qc-tint": tint.background, "--qc-tint-ink": tint.color } as CSSProperties) : undefined;+ return { agent, style };+}++export function AskerMark({ agent, size = 22 }: { agent: SocietyAgent | null; size?: number }) {+ if (agent) return <AgentSwatch agent={{ ...agent, state: undefined }} size={size} />;+ return (+ <span className="qc-mark" aria-hidden style={{ width: size, height: size }}>+ <MessageCircleQuestion className="h-3.5 w-3.5" />+ </span>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/questionCard.css b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionCard.cssnew file mode 100644index 0000000000..f5b763d2ec--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionCard.css@@ -0,0 +1,755 @@+/*+ * The question card. Every colour comes from the theme tokens (index.css);+ * the one accent is the asking agent's own colour, handed in as --qc-tint+ * with its readable ink as --qc-tint-ink, and the theme's primary fill when+ * the agent is unknown. Calm by default: no borders between rows, one soft+ * lift, motion only where something changes.+ */++.qc {+ --qc-tint: hsl(var(--primary));+ --qc-tint-ink: hsl(var(--primary-foreground));+ --qc-ease-out: cubic-bezier(0.22, 1, 0.36, 1);+ --qc-ease-std: cubic-bezier(0.2, 0, 0, 1);+ position: relative;+ width: 100%;+ max-width: 40rem;+ border-radius: 20px;+ background: hsl(var(--card));+ color: hsl(var(--foreground));+ box-shadow:+ 0 0 0 1px hsl(var(--border)),+ 0 1px 2px rgb(var(--scrim-rgb) / 0.06),+ 0 10px 28px -14px rgb(var(--scrim-rgb) / 0.28);+}++.qc[data-enter="new"] {+ animation: qc-enter 320ms var(--qc-ease-out) backwards;+}++@keyframes qc-enter {+ from {+ opacity: 0;+ transform: translateY(4px) scale(0.985);+ }+}++@keyframes qc-fade {+ from {+ opacity: 0;+ }+}++/* --- Header ------------------------------------------------------------ */++.qc-head {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 40px;+ padding: 10px 10px 0 16px;+}++.qc-mark {+ display: grid;+ flex: none;+ place-items: center;+ width: 22px;+ height: 22px;+ border-radius: 7px;+ background: hsl(var(--secondary));+ color: hsl(var(--muted-foreground));+}++.qc-asker {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 12px;+ line-height: 16px;+ color: hsl(var(--muted-foreground));+}++.qc-asker b {+ font-weight: 500;+ color: hsl(var(--foreground));+}++.qc-count {+ flex: none;+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: hsl(var(--faint-foreground));+}++.qc-icon-btn {+ display: grid;+ flex: none;+ place-items: center;+ width: 28px;+ height: 28px;+ border-radius: 8px;+ color: hsl(var(--muted-foreground));+ transition: background-color 140ms, color 140ms;+}++.qc-icon-btn:hover,+.qc-icon-btn[aria-expanded="true"] {+ background: hsl(var(--secondary));+ color: hsl(var(--foreground));+}++.qc-icon-btn:focus-visible,+.qc-btn:focus-visible,+.qc-sum:focus-visible,+.qc-why:focus-visible {+ outline: 2px solid hsl(var(--ring));+ outline-offset: 1px;+}++.qc-ring {+ flex: none;+ color: hsl(var(--warning));+}++.qc-ring circle {+ fill: none;+ stroke-width: 2.2;+}++.qc-ring .qc-ring-track {+ stroke: hsl(var(--border-strong));+}++.qc-ring .qc-ring-left {+ stroke: currentColor;+ stroke-linecap: round;+ transition: stroke-dashoffset 1s linear;+}++/* --- The steps: stacked in one cell, so the card never jumps ------------- */++.qc-steps {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+}++.qc-step {+ grid-area: 1 / 1;+ min-width: 0;+ visibility: hidden;+}++.qc-step[data-active] {+ visibility: visible;+ animation: qc-fade 160ms ease-out;+}++.qc-title {+ padding: 6px 16px 0;+ font-size: 15px;+ font-weight: 600;+ line-height: 22px;+ color: hsl(var(--foreground-strong));+ overflow-wrap: anywhere;+}++.qc-help {+ padding: 2px 16px 0;+ font-size: 12px;+ line-height: 18px;+ color: hsl(var(--muted-foreground));+}++.qc-list {+ display: flex;+ flex-direction: column;+ gap: 1px;+ padding: 8px;+}++.qc-row {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ width: 100%;+ padding: 8px;+ border-radius: 12px;+ text-align: left;+ color: hsl(var(--foreground));+ transition: background-color 140ms;+}++.qc-row:hover {+ background: hsl(var(--secondary));+}++.qc-row:active {+ background: hsl(var(--surface-raised));+ transition-duration: 0ms;+}++.qc-row:focus-visible {+ outline: 2px solid hsl(var(--ring));+ outline-offset: -2px;+}++.qc-row:disabled {+ cursor: default;+ color: hsl(var(--faint-foreground));+}++.qc-row:disabled:hover {+ background: transparent;+}++.qc-row[data-described] {+ align-items: center;+}++.qc-keycap {+ display: grid;+ flex: none;+ place-items: center;+ width: 24px;+ height: 24px;+ border: 1px solid hsl(var(--border-strong));+ border-radius: 7px;+ background: hsl(var(--secondary));+ font-size: 12px;+ font-weight: 500;+ line-height: 1;+ color: hsl(var(--muted-foreground));+ transition: background-color 140ms, border-color 140ms, color 140ms, transform 140ms var(--qc-ease-out);+}++.qc[data-target] .qc-keycap {+ color: hsl(var(--foreground));+}++.qc-keycap[data-on] {+ border-color: transparent;+ background: var(--qc-tint);+ color: var(--qc-tint-ink);+ box-shadow: inset 0 1px 0 rgb(var(--sheen-rgb) / 0.12);+ transform: scale(1.04);+}++.qc-keycap[data-size="sm"] {+ width: 18px;+ height: 18px;+ border-radius: 5px;+ font-size: 10.5px;+}++.qc-row-body {+ min-width: 0;+ flex: 1;+ padding-top: 2px;+}++.qc-label {+ display: block;+ font-size: 14px;+ line-height: 20px;+ overflow-wrap: anywhere;+}++.qc-desc {+ display: block;+ font-size: 12px;+ line-height: 18px;+ color: hsl(var(--muted-foreground));+ overflow-wrap: anywhere;+}++.qc-tag {+ flex: none;+ align-self: center;+ border-radius: 999px;+ padding: 1px 7px;+ background: hsl(var(--secondary));+ font-size: 11px;+ line-height: 16px;+ color: hsl(var(--muted-foreground));+}++.qc-row:hover .qc-tag {+ background: hsl(var(--surface-raised));+}++.qc-own {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ padding: 8px;+ border-radius: 12px;+ cursor: text;+ transition: background-color 140ms;+}++.qc-own:hover {+ background: hsl(var(--secondary));+}++.qc-own:focus-within {+ background: hsl(var(--secondary));+}++.qc-own textarea {+ flex: 1;+ min-width: 0;+ min-height: 22px;+ max-height: 160px;+ padding: 1px 0 0;+ resize: none;+ overflow-y: auto;+ border: 0;+ background: transparent;+ font: inherit;+ font-size: 14px;+ line-height: 20px;+ color: hsl(var(--foreground));+ white-space: pre-wrap;+ field-sizing: content;+}++.qc-own textarea::placeholder {+ color: hsl(var(--faint-foreground));+}++.qc-own textarea:focus {+ outline: none;+}++.qc-why {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ margin: -2px 0 4px 16px;+ border-radius: 6px;+ font-size: 12px;+ line-height: 18px;+ color: hsl(var(--muted-foreground));+}++.qc-why:hover {+ color: hsl(var(--foreground));+}++.qc-reason {+ margin: 0 16px 6px;+ padding: 8px 10px;+ border-radius: 10px;+ background: hsl(var(--secondary));+ font-size: 12px;+ line-height: 18px;+ color: hsl(var(--foreground-secondary));+ overflow-wrap: anywhere;+}++/* --- Review step -------------------------------------------------------- */++.qc-review {+ display: flex;+ flex-direction: column;+ gap: 1px;+ padding: 6px 8px 8px;+}++.qc-review-row {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ width: 100%;+ padding: 8px;+ border-radius: 12px;+ text-align: left;+ transition: background-color 140ms;+}++.qc-review-row:hover {+ background: hsl(var(--secondary));+}++.qc-review-row:focus-visible {+ outline: 2px solid hsl(var(--ring));+ outline-offset: -2px;+}++.qc-review-q {+ display: block;+ font-size: 12px;+ line-height: 18px;+ color: hsl(var(--muted-foreground));+ overflow-wrap: anywhere;+}++.qc-review-a {+ display: block;+ font-size: 14px;+ line-height: 20px;+ color: hsl(var(--foreground));+ white-space: pre-line;+ overflow-wrap: anywhere;+}++.qc-review-a[data-empty] {+ color: hsl(var(--faint-foreground));+}++.qc-review-edit {+ flex: none;+ align-self: center;+ font-size: 12px;+ color: hsl(var(--faint-foreground));+ opacity: 0;+ transition: opacity 140ms;+}++.qc-review-row:hover .qc-review-edit,+.qc-review-row:focus-visible .qc-review-edit {+ opacity: 1;+}++@media (hover: none) {+ .qc-review-edit {+ opacity: 1;+ }+}++/* --- Footer ------------------------------------------------------------- */++.qc-foot {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ padding: 4px 12px 12px 16px;+}++.qc-foot-end {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-left: auto;+}++.qc-dots {+ display: flex;+ align-items: center;+ gap: 5px;+}++.qc-dot {+ width: 6px;+ height: 6px;+ border-radius: 999px;+ background: hsl(var(--border-strong));+ transition: width 200ms var(--qc-ease-std), background-color 200ms;+}++.qc-dot[data-done] {+ background: hsl(var(--muted-foreground));+}++.qc-dot[data-on] {+ width: 16px;+ background: var(--qc-tint);+}++.qc-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 32px;+ padding: 0 12px;+ border-radius: 10px;+ font-size: 13px;+ font-weight: 500;+ white-space: nowrap;+ transition: background-color 140ms, color 140ms, opacity 140ms;+}++.qc-btn:disabled {+ cursor: default;+ opacity: 0.45;+}++.qc-btn-primary {+ background: hsl(var(--primary));+ color: hsl(var(--primary-foreground));+}++.qc-btn-primary:not(:disabled):hover {+ opacity: 0.9;+}++.qc-btn-quiet {+ color: hsl(var(--muted-foreground));+}++.qc-btn-quiet:not(:disabled):hover {+ background: hsl(var(--secondary));+ color: hsl(var(--foreground));+}++.qc-alert {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ font-size: 12px;+ line-height: 18px;+ color: hsl(var(--destructive));+}++/* --- The card's menu ---------------------------------------------------- */++.qc-menu {+ position: absolute;+ top: 42px;+ right: 10px;+ z-index: 20;+ width: min(17rem, calc(100% - 20px));+ padding: 4px;+ border-radius: 12px;+ background: hsl(var(--popover));+ color: hsl(var(--popover-foreground));+ box-shadow:+ 0 0 0 1px hsl(var(--border-strong)),+ 0 12px 32px -10px rgb(var(--scrim-rgb) / 0.35);+ animation: qc-menu-in 150ms var(--qc-ease-out);+ transform-origin: top right;+}++@keyframes qc-menu-in {+ from {+ opacity: 0;+ transform: scale(0.97) translateY(-2px);+ }+}++.qc-menu-item {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ width: 100%;+ padding: 8px 10px;+ border-radius: 8px;+ text-align: left;+}++.qc-menu-item:hover,+.qc-menu-item:focus-visible {+ outline: none;+ background: hsl(var(--secondary));+}++.qc-menu-item svg {+ flex: none;+ margin-top: 2px;+ color: hsl(var(--muted-foreground));+}++.qc-menu-title {+ display: block;+ font-size: 13px;+ line-height: 18px;+ color: hsl(var(--foreground));+}++.qc-menu-hint {+ display: block;+ font-size: 11.5px;+ line-height: 16px;+ color: hsl(var(--muted-foreground));+}++/* --- Settled ------------------------------------------------------------ */++.qc[data-settled] {+ background: hsl(var(--background));+ box-shadow: 0 0 0 1px hsl(var(--border));+ border-radius: 16px;+}++.qc-sum {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ min-height: 40px;+ padding: 8px 8px 8px 12px;+ border-radius: 16px;+ text-align: left;+}++.qc-sum-prompt {+ min-width: 0;+ flex: 0 1 auto;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 13px;+ line-height: 18px;+ color: hsl(var(--muted-foreground));+}++.qc-sum-arrow {+ flex: none;+ color: hsl(var(--faint-foreground));+}++.qc-chips {+ display: flex;+ min-width: 0;+ flex: 1 1 auto;+ flex-wrap: wrap;+ gap: 4px;+}++.qc-chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ max-width: 16rem;+ padding: 2px 8px 2px 3px;+ border-radius: 8px;+ background: hsl(var(--secondary));+ font-size: 12.5px;+ line-height: 18px;+ color: hsl(var(--foreground));+}++.qc-chip > span:last-child {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.qc-chip[data-plain] {+ padding-left: 8px;+}++.qc-chip[data-muted] {+ border: 1px dashed hsl(var(--border-strong));+ background: transparent;+ color: hsl(var(--muted-foreground));+}++.qc-sum-tail {+ display: flex;+ flex: none;+ align-items: center;+ gap: 2px;+ margin-left: auto;+ color: hsl(var(--faint-foreground));+}++.qc-chevron {+ transition: transform 200ms var(--qc-ease-std);+}++.qc-sum[aria-expanded="true"] .qc-chevron {+ transform: rotate(180deg);+}++.qc-collapse {+ display: grid;+ grid-template-rows: 0fr;+ transition: grid-template-rows 300ms var(--qc-ease-std);+}++.qc-collapse[data-open] {+ grid-template-rows: 1fr;+ transition-duration: 240ms;+}++.qc-collapse > div {+ min-height: 0;+ overflow: hidden;+}++.qc-note {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 0 16px 6px;+ font-size: 12px;+ line-height: 18px;+ color: hsl(var(--muted-foreground));+}++.qc[data-dismissed] .qc-sum-prompt {+ color: hsl(var(--faint-foreground));+}++.qc-pending {+ width: 6px;+ height: 6px;+ border-radius: 999px;+ background: var(--qc-tint);+ animation: qc-pulse 1.2s ease-in-out infinite;+}++@keyframes qc-pulse {+ 50% {+ opacity: 0.35;+ }+}++/* --- Answered from the chat: a plain question and the person's reply ---- */++.qc-asked {+ display: flex;+ align-items: flex-start;+ gap: 8px;+}++.qc-asked-bubble {+ min-width: 0;+ max-width: min(85%, 42rem);+ padding: 8px 14px;+ border-radius: 18px;+ font-size: 14px;+ line-height: 21px;+ overflow-wrap: anywhere;+}++.qc-reply {+ display: flex;+ justify-content: flex-end;+}++.qc-reply-bubble {+ max-width: min(85%, 36rem);+ padding: 8px 14px;+ border-radius: 18px;+ background: hsl(var(--user-bubble));+ color: hsl(var(--user-bubble-foreground));+ font-size: 14px;+ line-height: 21px;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}++.qc-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+}++@media (prefers-reduced-motion: reduce) {+ .qc,+ .qc *,+ .qc *::before,+ .qc *::after {+ animation: none !important;+ transition: none !important;+ }+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/questionDraftStore.ts b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionDraftStore.tsnew file mode 100644index 0000000000..510e6de6e1--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionDraftStore.ts@@ -0,0 +1,80 @@+import { create } from "zustand";+import type { QuestionSubmitAnswer } from "@/lib/agentChatApi";+import type { QuestionAnswerState } from "../reduce";+import type { LocalAnswer } from "./questionModel";++/**+ * What the person did on a question card that the server does not know yet,+ * keyed by question id: the step they are on, their picks and words, and an+ * answer on its way. It lives outside the card, so a card that remounts (the+ * chat re-renders, the person switches agents and back) resumes mid-series+ * with every pick in place.+ *+ * `submission` is the optimistic answer: the card settles the moment it is+ * set and only reopens when the request failed, with the exact same request+ * ready to try again.+ */++/** What went to the server; a retry replays it unchanged. */+export type QuestionRequest =+ | { kind: "submit"; answers: QuestionSubmitAnswer[] }+ | { kind: "decide_all" };++export interface QuestionSubmission {+ status: "sending" | "sent" | "failed";+ request: QuestionRequest;+ /** The answers the card shows while the request is on its way. */+ answers: (QuestionAnswerState | null)[];+ error?: string;+}++export interface QuestionDraft {+ /** The step on screen; `questions.length` is the review step, -1 the first open one. */+ step: number;+ answers: LocalAnswer[];+ submission: QuestionSubmission | null;+ /** A settled card the person opened to read again, and the page they are on. */+ expanded: boolean;+ page: number;+}++export const EMPTY_DRAFT: QuestionDraft = { step: -1, answers: [], submission: null, expanded: false, page: 0 };++interface DraftStore {+ drafts: Record<string, QuestionDraft>;+ patch: (questionId: string, fn: (draft: QuestionDraft) => QuestionDraft) => void;+ clear: (questionId: string) => void;+}++/** Drafts kept at most; the oldest go first (a long-running app asks a lot). */+const MAX_DRAFTS = 64;++export const useQuestionDrafts = create<DraftStore>((set) => ({+ drafts: {},+ patch: (questionId, fn) =>+ set((state) => {+ const next = fn(state.drafts[questionId] ?? EMPTY_DRAFT);+ const { [questionId]: _old, ...rest } = state.drafts;+ const ids = Object.keys(rest);+ const kept = ids.length >= MAX_DRAFTS ? Object.fromEntries(ids.slice(ids.length - MAX_DRAFTS + 1).map((id) => [id, rest[id]])) : rest;+ return { drafts: { ...kept, [questionId]: next } };+ }),+ clear: (questionId) =>+ set((state) => {+ if (!(questionId in state.drafts)) return state;+ const { [questionId]: _gone, ...rest } = state.drafts;+ return { drafts: rest };+ }),+}));++export function useQuestionDraft(questionId: string): QuestionDraft {+ return useQuestionDrafts((state) => state.drafts[questionId] ?? EMPTY_DRAFT);+}++export function readQuestionDraft(questionId: string): QuestionDraft {+ return useQuestionDrafts.getState().drafts[questionId] ?? EMPTY_DRAFT;+}++export function patchQuestionDraft(questionId: string, fn: (draft: QuestionDraft) => QuestionDraft): void {+ useQuestionDrafts.getState().patch(questionId, fn);+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/questionModel.ts b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionModel.tsnew file mode 100644index 0000000000..67efcb2ed9--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionModel.ts@@ -0,0 +1,187 @@+import type { QuestionSubmitAnswer } from "@/lib/agentChatApi";+import type { QuestionAnswerState, QuestionItem, QuestionState, Timeline, ToolBlock } from "../reduce";++/**+ * The pure rules of the question card: what the person picked locally, what+ * that sends, which card is open, and how a settled answer reads. No React+ * here, so every rule is a plain unit test.+ */++/** Letters for the rows; the row after the last option is the own-answer field. */+export const LETTERS = "ABCDE";++/** What the person picked on one question before anything is sent. */+export interface LocalAnswer {+ /** Picked options (one for a single question). */+ picks: number[];+ /** Their own words (next to the picks of a multi question). */+ text: string;+ /** They skipped this question: an empty answer, the agent decides. */+ skipped: boolean;+}++export const EMPTY_ANSWER: LocalAnswer = { picks: [], text: "", skipped: false };++export function hasAnswer(local: LocalAnswer | undefined): boolean {+ return Boolean(local && (local.skipped || local.picks.length > 0 || local.text.trim()));+}++/** A single question takes one option OR own words; picking one clears the other. */+export function pickSingle(index: number): LocalAnswer {+ return { picks: [index], text: "", skipped: false };+}++export function toggleMulti(local: LocalAnswer, index: number): LocalAnswer {+ const picks = local.picks.includes(index) ? local.picks.filter((i) => i !== index) : [...local.picks, index];+ return { ...local, picks: picks.sort((a, b) => a - b), skipped: false };+}++export function withText(local: LocalAnswer, item: QuestionItem, text: string): LocalAnswer {+ // A typed single answer replaces the picked option; multi keeps both.+ return item.kind === "multi" ? { ...local, text, skipped: false } : { picks: [], text, skipped: false };+}++/** What `/submit` receives for one question; `null` when nothing was chosen. */+export function toSubmit(local: LocalAnswer | undefined, item: QuestionItem): QuestionSubmitAnswer | null {+ if (!local) return null;+ if (local.skipped) return { skip: true };+ const text = local.text.trim();+ if (item.kind === "multi") {+ if (!local.picks.length && !text) return null;+ return text ? { option_indices: local.picks, text } : { option_indices: local.picks };+ }+ if (local.picks.length) return { option_index: local.picks[0] };+ return text ? { text } : null;+}++/** Every answer of the series, a skip for each question left untouched. */+export function seriesPayload(question: QuestionState, locals: LocalAnswer[]): QuestionSubmitAnswer[] {+ return question.questions.map((item, i) => toSubmit(locals[i], item) ?? { skip: true });+}++/** How the agent will read a local answer, for the optimistic settled card. */+export function localAsAnswer(local: LocalAnswer | undefined, item: QuestionItem): QuestionAnswerState {+ if (!local || local.skipped || !hasAnswer(local)) return { text: "", optionIndex: null, source: "declined" };+ const labels = local.picks.map((i) => item.options[i]?.label ?? "").filter(Boolean);+ const text = local.text.trim();+ const lines = [...labels, ...(text ? [text] : [])];+ if (item.kind === "multi") return { text: lines.join("\n"), optionIndex: null, source: "person", optionIndices: local.picks };+ return { text: lines[0] ?? "", optionIndex: local.picks[0] ?? null, source: "person" };+}++/** The server's answer back as local picks, so a reopened card can be changed. */+export function answerAsLocal(answer: QuestionAnswerState | null, item: QuestionItem): LocalAnswer {+ if (!answer) return EMPTY_ANSWER;+ if (answer.source === "declined") return { ...EMPTY_ANSWER, skipped: true };+ if (answer.optionIndices?.length) {+ const labels = new Set(answer.optionIndices.map((i) => item.options[i]?.label));+ const own = answer.text.split("\n").filter((line) => line && !labels.has(line)).join("\n");+ return { picks: [...answer.optionIndices], text: own, skipped: false };+ }+ if (answer.optionIndex !== null) return pickSingle(answer.optionIndex);+ return { picks: [], text: answer.text, skipped: false };+}++/** The picked options of a settled answer (none for own words). */+export function pickedIndices(answer: QuestionAnswerState | null): number[] {+ if (!answer) return [];+ if (answer.optionIndices?.length) return answer.optionIndices;+ return answer.optionIndex !== null ? [answer.optionIndex] : [];+}++/** The person's own words in a settled answer, beside any picked options. */+export function ownWords(answer: QuestionAnswerState | null, item: QuestionItem): string {+ if (!answer) return "";+ const picked = new Set(pickedIndices(answer).map((i) => item.options[i]?.label));+ return answer.text.split("\n").filter((line) => line.trim() && !picked.has(line)).join("\n");+}++/** How a settled answer came about — the card's small note under it. */+export type SettledNote =+ | "picked"+ | "own"+ | "auto"+ | "agent"+ | "declined"+ | "moved_on"+ | "message"+ | "unanswered";++export function settledNote(answer: QuestionAnswerState | null): SettledNote {+ if (!answer) return "unanswered";+ switch (answer.source) {+ case "timeout":+ case "unattended":+ return "auto";+ case "skipped":+ return "agent";+ case "declined":+ return "declined";+ case "moved_on":+ return "moved_on";+ case "message":+ return "message";+ case "cancelled":+ case "closed":+ return "unanswered";+ default:+ return pickedIndices(answer).length ? "picked" : answer.text.trim() ? "own" : "declined";+ }+}++/** Every question was skipped or left unanswered: the card reads as dismissed. */+export function isDismissed(question: QuestionState): boolean {+ return question.closed && question.answers.every((a) => {+ const note = settledNote(a);+ return note === "declined" || note === "unanswered";+ });+}++/** The person answered from the chat: the card reads as a plain question. */+export function answeredByMessage(question: QuestionState): boolean {+ return question.closed && question.answers.some((a) => a?.source === "message");+}++/** "question\nanswer" lines for the clipboard. */+export function copyText(question: QuestionState): string {+ return question.questions+ .map((item, i) => {+ const answer = question.answers[i];+ const text = answer?.text.trim() ? answer.text.split("\n").join(", ") : "—";+ return `${item.question}\n${text}`;+ })+ .join("\n\n");+}++/** Milliseconds left on a live card, or null for an end-of-turn card / no deadline. */+export function remainingMs(question: QuestionState, nowMs: number): number | null {+ if (question.deferred || question.expiresMs === null || question.closed) return null;+ return Math.max(0, question.expiresMs - nowMs);+}++/** Below this, the card shows its quiet countdown ring. */+export const RING_WINDOW_MS = 60_000;++/** The newest card still waiting for the person — what the composer answers. */+export function openQuestionOf(timeline: Pick<Timeline, "items">): { block: ToolBlock; question: QuestionState } | null {+ for (let i = timeline.items.length - 1; i >= 0; i -= 1) {+ const item = timeline.items[i];+ if (item.type === "user" && item.origin !== "control") return null;+ if (item.type !== "turn") continue;+ for (let j = item.blocks.length - 1; j >= 0; j -= 1) {+ const block = item.blocks[j];+ if (block.kind === "tool" && block.question && !block.question.closed) return { block, question: block.question };+ }+ }+ return null;+}++/** The agent's own default for one question, as "let the agent decide" applies it. */+export function recommendationOf(item: QuestionItem, source: string): QuestionAnswerState {+ if (!item.options.length) return { text: "", optionIndex: null, source };+ if (item.kind === "multi") {+ const picks = Array.from({ length: item.recommendedCount }, (_, i) => i);+ return { text: picks.map((i) => item.options[i].label).join("\n"), optionIndex: null, source, optionIndices: picks };+ }+ return { text: item.options[0].label, optionIndex: 0, source };+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/useQuestionActions.ts b/dodaios/ui/web/frontend/src/components/agentchat/questions/useQuestionActions.tsnew file mode 100644index 0000000000..9a2b2054e4--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/useQuestionActions.ts@@ -0,0 +1,99 @@+import { useCallback, useRef } from "react";+import { AgentChatApiError, type QuestionSubmitAnswer } from "@/lib/agentChatApi";+import { useAgentChatApi } from "../AgentChatStoreContext";+import type { QuestionAnswerState, QuestionState } from "../reduce";+import { patchQuestionDraft, readQuestionDraft, type QuestionRequest } from "./questionDraftStore";+import { localAsAnswer, recommendationOf, seriesPayload, type LocalAnswer } from "./questionModel";++/** At most one "still answering" ping per this many milliseconds. */+export const TOUCH_EVERY_MS = 20_000;++/**+ * What a question card sends, optimistically.+ *+ * The card settles the moment the person answers; the request runs behind+ * it. A failure reopens the card where it was, with the error and the exact+ * request ready to try again. A card the server already closed (its window+ * ran out, the turn ended) is not a failure: its closing event tells the+ * truth, so the optimistic answer just gives way.+ */+export function useQuestionActions(question: QuestionState) {+ const store = useAgentChatApi();+ const { questionId } = question;+ const lastTouch = useRef(0);+ const live = useRef(question);+ live.current = question;++ const run = useCallback(async (request: QuestionRequest) => {+ const state = store.getState();+ if (request.kind === "decide_all") {+ await state.skipQuestion(questionId);+ return;+ }+ if (state.submitQuestion) {+ await state.submitQuestion(questionId, request.answers);+ return;+ }+ // A store without the reviewed submit gets the answers one by one.+ for (const [index, answer] of request.answers.entries()) {+ if (live.current.answers[index]) continue;+ if ("skip" in answer) await state.skipQuestion(questionId, index);+ else if ("option_index" in answer) await state.answerQuestion(questionId, index, { optionIndex: answer.option_index });+ else if ("option_indices" in answer) {+ await state.answerQuestion(questionId, index, { optionIndices: answer.option_indices, text: answer.text });+ } else await state.answerQuestion(questionId, index, { text: "text" in answer ? answer.text ?? "" : "" });+ }+ }, [store, questionId]);++ const send = useCallback(async (request: QuestionRequest, answers: (QuestionAnswerState | null)[]) => {+ if (readQuestionDraft(questionId).submission?.status === "sending") return;+ patchQuestionDraft(questionId, (draft) => ({ ...draft, submission: { status: "sending", request, answers } }));+ try {+ await run(request);+ patchQuestionDraft(questionId, (draft) =>+ draft.submission ? { ...draft, submission: { ...draft.submission, status: "sent" } } : draft);+ } catch (err) {+ if (err instanceof AgentChatApiError && (err.status === 404 || err.status === 410)) {+ patchQuestionDraft(questionId, (draft) => ({ ...draft, submission: null }));+ return;+ }+ const error = err instanceof Error ? err.message : String(err);+ patchQuestionDraft(questionId, (draft) =>+ draft.submission ? { ...draft, submission: { ...draft.submission, status: "failed", error } } : draft);+ }+ }, [questionId, run]);++ /** Send every answer of the card (a lone question is a series of one). */+ const submit = useCallback((locals: LocalAnswer[]) => {+ const q = live.current;+ const answers: QuestionSubmitAnswer[] = seriesPayload(q, locals);+ const shown = q.questions.map((item, i) => q.answers[i] ?? localAsAnswer(locals[i], item));+ return send({ kind: "submit", answers }, shown);+ }, [send]);++ /** Leave every open question to the agent: its recommendations apply. */+ const decideAll = useCallback(() => {+ const q = live.current;+ const shown = q.questions.map((item, i) => q.answers[i] ?? recommendationOf(item, "skipped"));+ return send({ kind: "decide_all" }, shown);+ }, [send]);++ /** Replay the exact request that failed. */+ const retry = useCallback(() => {+ const failed = readQuestionDraft(questionId).submission;+ if (failed?.status === "failed") return send(failed.request, failed.answers);+ return Promise.resolve();+ }, [questionId, send]);++ /** The person is working on the card: keep a live card from timing out under them. */+ const touch = useCallback(() => {+ const q = live.current;+ if (q.deferred || q.closed) return;+ const now = Date.now();+ if (now - lastTouch.current < TOUCH_EVERY_MS) return;+ lastTouch.current = now;+ void store.getState().touchQuestion?.(questionId);+ }, [store, questionId]);++ return { submit, decideAll, retry, touch };+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/useQuestionKeyboard.ts b/dodaios/ui/web/frontend/src/components/agentchat/questions/useQuestionKeyboard.tsnew file mode 100644index 0000000000..718782cd35--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/useQuestionKeyboard.ts@@ -0,0 +1,109 @@+import { useEffect, useRef, useSyncExternalStore, type RefObject } from "react";++/**+ * One keyboard target for every open question card on screen.+ *+ * Plain letter keys answer a card without clicking it first, but only ONE+ * card may hear them: the newest open one, i.e. the last registered card in+ * document order that is actually visible. Keys never reach it while the+ * person types in a field, holds a modifier, or works inside a dialog or a+ * menu that is not part of the card.+ */++type KeyHandler = (event: KeyboardEvent) => boolean;++interface Entry {+ el: HTMLElement;+ onKey: KeyHandler;+}++const entries = new Set<Entry>();+const listeners = new Set<() => void>();+let installed = false;++// jsdom lays nothing out, so every connected card counts as shown there.+const NO_LAYOUT = typeof navigator !== "undefined" && /jsdom/i.test(navigator.userAgent);++function visible(el: HTMLElement): boolean {+ if (!el.isConnected || el.closest("[hidden],[inert]")) return false;+ return NO_LAYOUT || el.getClientRects().length > 0;+}++/** The card that hears plain letter keys right now, if any. */+export function currentTarget(): HTMLElement | null {+ let best: Entry | null = null;+ for (const entry of entries) {+ if (!visible(entry.el)) continue;+ // A later card in the document is a newer question.+ if (!best || best.el.compareDocumentPosition(entry.el) & Node.DOCUMENT_POSITION_FOLLOWING) best = entry;+ }+ return best?.el ?? null;+}++function editable(node: EventTarget | null): boolean {+ if (!(node instanceof HTMLElement)) return false;+ if (node.isContentEditable) return true;+ const tag = node.tagName;+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";+}++function onWindowKey(event: KeyboardEvent): void {+ if (event.defaultPrevented || event.repeat || event.isComposing || event.ctrlKey || event.metaKey || event.altKey) return;+ if (editable(event.target)) return;+ const el = currentTarget();+ if (!el) return;+ const active = document.activeElement;+ // A dialog or menu elsewhere owns the keyboard while it has focus.+ if (active instanceof HTMLElement && !el.contains(active) && active.closest('[role="dialog"],[role="menu"],[role="listbox"]')) return;+ for (const entry of entries) {+ if (entry.el === el) {+ if (entry.onKey(event)) event.preventDefault();+ return;+ }+ }+}++function notify(): void {+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++/**+ * Register `ref`'s card as a keyboard target while `active`; returns whether+ * it is THE target (so it can show its key hints). `onKey` returns true when+ * it used the key.+ */+export function useQuestionKeyboard(ref: RefObject<HTMLElement | null>, onKey: KeyHandler, active: boolean): boolean {+ const handler = useRef(onKey);+ handler.current = onKey;+ useEffect(() => {+ const el = ref.current;+ if (!active || !el) return;+ if (!installed && typeof window !== "undefined") {+ window.addEventListener("keydown", onWindowKey);+ installed = true;+ }+ const entry: Entry = { el, onKey: (event) => handler.current(event) };+ entries.add(entry);+ notify();+ return () => {+ entries.delete(entry);+ notify();+ };+ }, [ref, active]);+ return useSyncExternalStore(+ subscribe,+ () => active && ref.current !== null && currentTarget() === ref.current,+ () => false,+ );+}++/** Test seam: forget every registered card. */+export function resetQuestionKeyboard(): void {+ entries.clear();+ notify();+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts b/dodaios/ui/web/frontend/src/components/agentchat/reduce.tsindex c4cfd2e123..3a0c4b0455 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts@@ -63,22 +63,36 @@ export interface QuestionOption {description: string;}+/** How a question is answered: one option, any number of them, or own words. */+export type QuestionKind = "single" | "multi" | "text";+/** One question of a card. Option 0 is always the agent's recommendation. */export interface QuestionItem {question: string;options: QuestionOption[];recommendationReason: string;+ /** `single` on older events. */+ kind: QuestionKind;+ /** The person may type their own answer (always true for `text`). */+ allowCustom: boolean;+ /** How many leading options a `multi` question recommends (1 otherwise). */+ recommendedCount: number;}/*** What one question resolved to. `source`: `person`, `timeout` (nobody- * answered for five minutes), `skipped` (the card was closed), `cancelled`,- * or `closed` (the turn ended without an answer).+ * answered in time), `skipped` (the agent was left to decide), `declined`+ * (the person skipped this one question), `message` (answered from the chat+ * composer), `moved_on` (the person wrote about something else), `cancelled`,+ * `unattended`, or `closed` (the turn ended without an answer).*/export interface QuestionAnswerState {+ /** What the agent reads; a multi answer holds one label per line. */text: string;optionIndex: number | null;source: string;+ /** The picked options of a multi answer. */+ optionIndices?: number[];}/**@@ -453,7 +467,29 @@ function questionOptions(raw: unknown): QuestionOption[] {function questionAnswer(raw: unknown): QuestionAnswerState | null {if (!raw || typeof raw !== "object") return null;const row = raw as Record<string, unknown>;- return { text: str(row.answer), optionIndex: num(row.option_index), source: str(row.source, "person") };+ const answer: QuestionAnswerState = { text: str(row.answer), optionIndex: num(row.option_index), source: str(row.source, "person") };+ const picks = Array.isArray(row.option_indices) ? row.option_indices.filter((i): i is number => typeof i === "number") : [];+ return picks.length ? { ...answer, optionIndices: picks } : answer;+}++const QUESTION_KINDS: readonly QuestionKind[] = ["single", "multi", "text"];++/** One question off a `question_required` payload, or null when it is unusable. */+function questionItem(entry: unknown): QuestionItem | null {+ if (!entry || typeof entry !== "object") return null;+ const row = entry as Record<string, unknown>;+ const text = str(row.question);+ const options = questionOptions(row.options);+ const kind = QUESTION_KINDS.includes(row.kind as QuestionKind) ? (row.kind as QuestionKind) : "single";+ if (!text || (!options.length && kind !== "text")) return null;+ return {+ question: text,+ options,+ recommendationReason: str(row.recommendation_reason),+ kind,+ allowCustom: kind === "text" || row.allow_custom !== false,+ recommendedCount: kind === "multi" ? Math.max(1, Math.min(options.length, num(row.recommended_count) ?? 1)) : 1,+ };}/** The answer slots off a progress/resolved payload; older events carried one flat answer. */@@ -1184,11 +1220,8 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {// Older events carried a single question's fields at the top level.const raw = Array.isArray(p.questions) ? p.questions : [p];const questions: QuestionItem[] = raw.flatMap((entry) => {- if (!entry || typeof entry !== "object") return [];- const row = entry as Record<string, unknown>;- const options = questionOptions(row.options);- const text = str(row.question);- return text && options.length ? [{ question: text, options, recommendationReason: str(row.recommendation_reason) }] : [];+ const item = questionItem(entry);+ return item ? [item] : [];});if (!questions.length) return base;const question: QuestionState = {diff --git a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 295e74e7ac..3a799ac98b 100644--- a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -64,6 +64,7 @@ import {import { AwaitingTurn, MessengerTurn, type MemoryLink } from "@/components/agentchat/MessengerTurn";import { ActionCard, type ActionSpec } from "@/components/agentchat/actionCard/ActionCard";import { WandSparkles as ProposalIcon } from "lucide-react";+import { openQuestionOf } from "@/components/agentchat/questions/questionModel";import { VoiceStage } from "@/components/home/VoiceStage";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { fill, useT } from "@/i18n";@@ -1254,6 +1255,8 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, sfieldRef.current?.setText(text);}, () => void submit());const timeline = useAgentChat((s) => s.timeline);+ // A card waiting on the person: the composer becomes a second way to answer it.+ const openAsk = useMemo(() => openQuestionOf(timeline), [timeline]);const sending = useAgentChat((s) => s.busy);// Track HTTP admission and running work independently of composer readiness.const live = runningTurn(timeline) !== null || sending;@@ -1365,6 +1368,13 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, sif (codingHint) lines.push(codingHint);const hint = lines.join("\n");setProblem(null);+ const answerByMessage = chatStore.getState().answerByMessage;+ if (openAsk && answerByMessage && text && !hint && attachments.attachments.length === 0) {+ writeComposerDraft(chatStore, sessionId, { text: "", choices: [] });+ fieldRef.current?.clear();+ // A running turn took the message as its answer: nothing else to send.+ if (await answerByMessage(text)) return;+ }const held = attachments.take();if (!text && held.attachments.length === 0) return;const draftTarget = captureComposerDraftTarget(chatStore, sessionId);@@ -1497,7 +1507,9 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, splaceholder={dictation.dictating? t("chats_view.dictation_listening")- : t("society.chat.placeholder").replace("{0}", agent.name)+ : openAsk+ ? t("question_card.composer_placeholder").replace("{agent}", openAsk.question.asker || agent.name)+ : t("society.chat.placeholder").replace("{0}", agent.name)}disabled={false}onSubmit={() => (dictation.dictating ? dictation.stopAndSend() : void submit())}diff --git a/dodaios/ui/web/frontend/src/components/society/chat/ComposerAnswersQuestion.test.tsx b/dodaios/ui/web/frontend/src/components/society/chat/ComposerAnswersQuestion.test.tsxnew file mode 100644index 0000000000..5a6ed51619--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/chat/ComposerAnswersQuestion.test.tsx@@ -0,0 +1,81 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";+import { EMPTY_TIMELINE, reduceEvents } from "@/components/agentchat/reduce";+import type { AgentChatEvent } from "@/lib/agentChatApi";+import { createAgentChatStore } from "@/store/agentChat";+import type { SocietyAgent } from "../data";+import { Composer } from "./AgentChatPanel";++vi.mock("../data", async (load) => ({+ ...await load<typeof import("../data")>(),+ useSocietyCapabilities: () => ({ data: [], isLoading: false }),+}));+vi.mock("./AgentModelPicker", () => ({ AgentModelPicker: () => null }));++beforeEach(() => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ commands: [] }))));+});+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++let seq = 0;+const ev = (kind: string, payload: Record<string, unknown>) => ({ seq: ++seq, ts_ms: 1000, kind, payload }) as AgentChatEvent;++const ASKING = [+ ev("turn_started", { turn_id: "t1" }),+ ev("question_required", {+ turn_id: "t1",+ question_id: "q1",+ asker: "Ada",+ questions: [{ question: "Which database?", options: [{ label: "SQLite" }, { label: "Postgres" }] }],+ expires_ms: Date.now() + 300_000,+ }),+];++function mount(events: AgentChatEvent[], consumed: boolean) {+ const store = createAgentChatStore("society");+ const answerByMessage = vi.fn(async () => consumed);+ store.setState({ activeSessionId: "chat-a", timeline: reduceEvents(EMPTY_TIMELINE, events), answerByMessage });+ const send = vi.fn().mockResolvedValue("sent");+ render(<AgentChatStoreProvider store={store}>+ <Composer agent={{ agentId: "ada", name: "Ada", tier: "specialist" } as unknown as SocietyAgent}+ mentionable={[]} busy sessionId="chat-a" cwd="" provider="local" surface="society"+ onSend={send} onCancel={async () => {}} />+ </AgentChatStoreProvider>);+ return { send, answerByMessage };+}++function write(text: string) {+ const box = screen.getByRole("textbox");+ box.textContent = text;+ fireEvent.input(box);+ return box;+}++it("invites an answer while a question is open", () => {+ mount(ASKING, true);+ expect(screen.getByRole("textbox").getAttribute("aria-placeholder")).toMatch(/answer ada, or write about something else/i);+});++it("a message the running turn takes as its answer is not sent again", async () => {+ const { send, answerByMessage } = mount(ASKING, true);+ fireEvent.keyDown(write("Postgres, please"), { key: "Enter" });+ await waitFor(() => expect(answerByMessage).toHaveBeenCalledWith("Postgres, please"));+ expect(send).not.toHaveBeenCalled();+ expect(screen.getByRole("textbox").textContent).toBe("");+});++it("an end-of-turn card settles and the message still goes out", async () => {+ const { send, answerByMessage } = mount(ASKING, false);+ fireEvent.keyDown(write("Postgres"), { key: "Enter" });+ await waitFor(() => expect(send).toHaveBeenCalledWith("Postgres", []));+ expect(answerByMessage).toHaveBeenCalledTimes(1);+});++it("without an open question the composer is an ordinary composer", async () => {+ const { send, answerByMessage } = mount([...ASKING, ev("turn_finished", { turn_id: "t1", status: "done" })], true);+ expect(screen.getByRole("textbox").getAttribute("aria-placeholder")).not.toMatch(/answer ada/i);+ fireEvent.keyDown(write("hello"), { key: "Enter" });+ await waitFor(() => expect(send).toHaveBeenCalled());+ expect(answerByMessage).not.toHaveBeenCalled();+});diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex ab43c570b0..9830ad4a4e 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -7269,21 +7269,51 @@"question_card": {"aria": "Rückfrage des Agenten","title_one": "{agent} hat eine Frage",- "title_many": "{agent} hat {count} Fragen",+ "title_many": "{count} Fragen von {agent}","fallback_agent": "Dein Agent",- "step": "Frage {current} von {total}",+ "asks": "fragt",+ "asked": "Frage des Agenten:",+ "step": "{current} von {total}","recommended": "Empfohlen",- "why": "Empfohlen, weil: {reason}",- "own_answer": "Eigene Antwort eingeben…",- "own_placeholder": "Deine Antwort",+ "why_toggle": "Warum diese Empfehlung?",+ "pick_many": "Wähle alles Passende.",+ "write_answer": "Antworte in deinen eigenen Worten.",+ "own_answer": "Deine eigene Antwort",+ "something_else": "Etwas anderes…",+ "text_placeholder": "Schreib deine Antwort…",+ "menu": "Optionen zur Frage",+ "skip_this": "Diese Frage überspringen",+ "skip_this_hint": "{agent} entscheidet sie ohne deine Antwort.",+ "let_decide": "Alles {agent} überlassen",+ "let_decide_hint": "Für jede offene Frage gilt die Empfehlung.",+ "countdown": "Ohne Antwort in {time} wird die Empfehlung gewählt.",+ "keys_hint": "Drück einen Buchstaben, um zu antworten.",+ "back": "Zurück",+ "next": "Weiter",+ "skip": "Überspringen",+ "review": "Prüfen",+ "review_title": "Deine Antworten",+ "change": "Ändern",+ "send_answers": "Antworten senden","send": "Senden",- "close": "Schließen und den Agenten entscheiden lassen",- "countdown": "Ohne Antwort in {time} werden automatisch die Empfehlungen gewählt.",- "choosing": "Die Empfehlungen werden gewählt…",- "auto_picked": "automatisch gewählt (keine Antwort in 5 Minuten)",- "left_to_agent": "dem Agenten überlassen",- "own_words": "deine eigene Antwort",- "unanswered": "Nicht beantwortet – der Durchlauf wurde beendet."+ "done": "Fertig",+ "sending": "Wird gesendet…",+ "failed": "Deine Antwort ist nicht angekommen.",+ "try_again": "Erneut versuchen",+ "answer_label": "Deine Antwort",+ "skipped_chip": "Übersprungen",+ "expand": "Antworten zeigen",+ "collapse": "Antworten ausblenden",+ "copy": "Frage und Antwort kopieren",+ "copied": "Kopiert",+ "own_words": "In deinen eigenen Worten.",+ "note_auto": "Es kam keine Antwort, darum wurde die Empfehlung gewählt.",+ "note_agent": "{agent} überlassen: Die Empfehlung gilt.",+ "note_declined": "Übersprungen. {agent} entscheidet diese Frage.",+ "note_moved_on": "Du hast weitergeschrieben, darum gilt die Empfehlung.",+ "note_message": "Im Chat beantwortet.",+ "unanswered": "Nicht beantwortet: Der Durchlauf wurde beendet.",+ "composer_placeholder": "Antworte {agent} oder schreib über etwas anderes"},"bot_stage": {"ponder": "Denkt nach…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex c22a2916a4..09c16eedb8 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -7269,21 +7269,51 @@"question_card": {"aria": "Question from the agent","title_one": "{agent} has a question",- "title_many": "{agent} has {count} questions",+ "title_many": "{agent}'s {count} questions","fallback_agent": "Your agent",- "step": "Question {current} of {total}",+ "asks": "asks",+ "asked": "Question from the agent:",+ "step": "{current} of {total}","recommended": "Recommended",- "why": "Recommended because: {reason}",- "own_answer": "Type your own answer…",- "own_placeholder": "Your answer",+ "why_toggle": "Why this recommendation?",+ "pick_many": "Pick all that apply.",+ "write_answer": "Answer in your own words.",+ "own_answer": "Your own answer",+ "something_else": "Something else…",+ "text_placeholder": "Write your answer…",+ "menu": "Question options",+ "skip_this": "Skip this question",+ "skip_this_hint": "{agent} decides it without your answer.",+ "let_decide": "Let {agent} decide all",+ "let_decide_hint": "Its recommendations are used for every open question.",+ "countdown": "No answer in {time}, and the recommendation is chosen.",+ "keys_hint": "Press a letter to answer.",+ "back": "Back",+ "next": "Next",+ "skip": "Skip",+ "review": "Review",+ "review_title": "Your answers",+ "change": "Change",+ "send_answers": "Send answers","send": "Send",- "close": "Close and let the agent decide",- "countdown": "No answer within {time} and the recommended options are chosen automatically.",- "choosing": "Choosing the recommended options…",- "auto_picked": "chosen automatically (no answer within 5 minutes)",- "left_to_agent": "left to the agent",- "own_words": "your own answer",- "unanswered": "Not answered — the turn ended."+ "done": "Done",+ "sending": "Sending…",+ "failed": "Your answer did not go through.",+ "try_again": "Try again",+ "answer_label": "Your answer",+ "skipped_chip": "Skipped",+ "expand": "show the answers",+ "collapse": "hide the answers",+ "copy": "Copy question and answer",+ "copied": "Copied",+ "own_words": "In your own words.",+ "note_auto": "No answer came, so the recommendation was chosen.",+ "note_agent": "Left to {agent}: the recommendation was used.",+ "note_declined": "Skipped. {agent} decides this one.",+ "note_moved_on": "You moved on, so the recommendation was used.",+ "note_message": "Answered in the chat.",+ "unanswered": "Not answered: the turn ended.",+ "composer_placeholder": "Answer {agent}, or write about something else"},"bot_stage": {"ponder": "Thinking…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex bb297283ed..1a49fbda7b 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -7269,21 +7269,51 @@"question_card": {"aria": "Pregunta del agente","title_one": "{agent} tiene una pregunta",- "title_many": "{agent} tiene {count} preguntas",+ "title_many": "{count} preguntas de {agent}","fallback_agent": "Tu agente",- "step": "Pregunta {current} de {total}",+ "asks": "pregunta",+ "asked": "Pregunta del agente:",+ "step": "{current} de {total}","recommended": "Recomendada",- "why": "Recomendada porque: {reason}",- "own_answer": "Escribir tu propia respuesta…",- "own_placeholder": "Tu respuesta",+ "why_toggle": "¿Por qué esta recomendación?",+ "pick_many": "Elige todas las que apliquen.",+ "write_answer": "Responde con tus propias palabras.",+ "own_answer": "Tu propia respuesta",+ "something_else": "Otra cosa…",+ "text_placeholder": "Escribe tu respuesta…",+ "menu": "Opciones de la pregunta",+ "skip_this": "Saltar esta pregunta",+ "skip_this_hint": "{agent} la decide sin tu respuesta.",+ "let_decide": "Dejar que {agent} decida todo",+ "let_decide_hint": "Se usan sus recomendaciones en cada pregunta abierta.",+ "countdown": "Sin respuesta en {time} se elige la recomendación.",+ "keys_hint": "Pulsa una letra para responder.",+ "back": "Atrás",+ "next": "Siguiente",+ "skip": "Saltar",+ "review": "Revisar",+ "review_title": "Tus respuestas",+ "change": "Cambiar",+ "send_answers": "Enviar respuestas","send": "Enviar",- "close": "Cerrar y dejar que decida el agente",- "countdown": "Sin respuesta en {time}, se eligen automáticamente las opciones recomendadas.",- "choosing": "Eligiendo las opciones recomendadas…",- "auto_picked": "elegida automáticamente (sin respuesta en 5 minutos)",- "left_to_agent": "decidida por el agente",- "own_words": "tu propia respuesta",- "unanswered": "Sin responder: el turno terminó."+ "done": "Listo",+ "sending": "Enviando…",+ "failed": "Tu respuesta no llegó.",+ "try_again": "Reintentar",+ "answer_label": "Tu respuesta",+ "skipped_chip": "Omitida",+ "expand": "mostrar las respuestas",+ "collapse": "ocultar las respuestas",+ "copy": "Copiar pregunta y respuesta",+ "copied": "Copiado",+ "own_words": "Con tus propias palabras.",+ "note_auto": "No llegó respuesta, así que se eligió la recomendación.",+ "note_agent": "Decidió {agent}: se usó la recomendación.",+ "note_declined": "Omitida. {agent} decide esta.",+ "note_moved_on": "Pasaste a otro tema, así que se usó la recomendación.",+ "note_message": "Respondida en el chat.",+ "unanswered": "Sin respuesta: el turno terminó.",+ "composer_placeholder": "Responde a {agent} o escribe sobre otra cosa"},"bot_stage": {"ponder": "Pensando…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex c0f32c681d..f0ed5ecf72 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -7269,21 +7269,51 @@"question_card": {"aria": "Pergunta do agente","title_one": "{agent} tem uma pergunta",- "title_many": "{agent} tem {count} perguntas",- "fallback_agent": "O teu agente",- "step": "Pergunta {current} de {total}",- "recommended": "Recomendado",- "why": "Recomendado porque: {reason}",- "own_answer": "Escreve a tua própria resposta…",- "own_placeholder": "A tua resposta",+ "title_many": "{count} perguntas de {agent}",+ "fallback_agent": "Seu agente",+ "asks": "pergunta",+ "asked": "Pergunta do agente:",+ "step": "{current} de {total}",+ "recommended": "Recomendada",+ "why_toggle": "Por que esta recomendação?",+ "pick_many": "Escolha todas as que se aplicam.",+ "write_answer": "Responda com suas próprias palavras.",+ "own_answer": "Sua própria resposta",+ "something_else": "Outra coisa…",+ "text_placeholder": "Escreva sua resposta…",+ "menu": "Opções da pergunta",+ "skip_this": "Pular esta pergunta",+ "skip_this_hint": "{agent} decide sem a sua resposta.",+ "let_decide": "Deixar {agent} decidir tudo",+ "let_decide_hint": "As recomendações valem para cada pergunta aberta.",+ "countdown": "Sem resposta em {time}, a recomendação é escolhida.",+ "keys_hint": "Pressione uma letra para responder.",+ "back": "Voltar",+ "next": "Próxima",+ "skip": "Pular",+ "review": "Revisar",+ "review_title": "Suas respostas",+ "change": "Alterar",+ "send_answers": "Enviar respostas","send": "Enviar",- "close": "Fechar e deixar o agente decidir",- "countdown": "Sem resposta em {time}, as opções recomendadas são escolhidas automaticamente.",- "choosing": "A escolher as opções recomendadas…",- "auto_picked": "escolhido automaticamente (sem resposta em 5 minutos)",- "left_to_agent": "deixado ao agente",- "own_words": "a tua própria resposta",- "unanswered": "Sem resposta — o turno terminou."+ "done": "Concluir",+ "sending": "Enviando…",+ "failed": "Sua resposta não foi enviada.",+ "try_again": "Tentar de novo",+ "answer_label": "Sua resposta",+ "skipped_chip": "Pulada",+ "expand": "mostrar as respostas",+ "collapse": "ocultar as respostas",+ "copy": "Copiar pergunta e resposta",+ "copied": "Copiado",+ "own_words": "Com suas próprias palavras.",+ "note_auto": "Nenhuma resposta chegou, então a recomendação foi escolhida.",+ "note_agent": "Ficou com {agent}: a recomendação foi usada.",+ "note_declined": "Pulada. {agent} decide esta.",+ "note_moved_on": "Você mudou de assunto, então a recomendação foi usada.",+ "note_message": "Respondida no chat.",+ "unanswered": "Sem resposta: o turno terminou.",+ "composer_placeholder": "Responda a {agent} ou escreva sobre outra coisa"},"bot_stage": {"ponder": "A pensar…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 2d19784a98..4aaad4253a 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -7267,23 +7267,53 @@"failed": "无法保存凭据。"},"question_card": {- "aria": "来自智能体的问题",+ "aria": "智能体的提问","title_one": "{agent} 有一个问题",- "title_many": "{agent} 有 {count} 个问题",+ "title_many": "{agent} 的 {count} 个问题","fallback_agent": "你的智能体",- "step": "第 {current}/{total} 个问题",+ "asks": "提问",+ "asked": "智能体的提问:",+ "step": "{current} / {total}","recommended": "推荐",- "why": "推荐理由:{reason}",- "own_answer": "输入你自己的回答…",- "own_placeholder": "你的回答",+ "why_toggle": "为什么推荐这个?",+ "pick_many": "选择所有适用的选项。",+ "write_answer": "用你自己的话回答。",+ "own_answer": "你自己的回答",+ "something_else": "其他…",+ "text_placeholder": "写下你的回答…",+ "menu": "问题选项",+ "skip_this": "跳过这个问题",+ "skip_this_hint": "{agent} 会在没有你回答的情况下决定。",+ "let_decide": "全部交给 {agent} 决定",+ "let_decide_hint": "每个未回答的问题都采用推荐选项。",+ "countdown": "{time} 内没有回答将选择推荐选项。",+ "keys_hint": "按字母键作答。",+ "back": "上一步",+ "next": "下一步",+ "skip": "跳过",+ "review": "检查",+ "review_title": "你的回答",+ "change": "修改",+ "send_answers": "发送回答","send": "发送",- "close": "关闭,让智能体决定",- "countdown": "如果 {time} 内没有回答,将自动选择推荐选项。",- "choosing": "正在选择推荐选项…",- "auto_picked": "已自动选择(5 分钟内没有回答)",- "left_to_agent": "交给智能体决定",- "own_words": "你自己的回答",- "unanswered": "未回答——本轮已结束。"+ "done": "完成",+ "sending": "正在发送…",+ "failed": "你的回答没有发送成功。",+ "try_again": "重试",+ "answer_label": "你的回答",+ "skipped_chip": "已跳过",+ "expand": "显示回答",+ "collapse": "隐藏回答",+ "copy": "复制问题和回答",+ "copied": "已复制",+ "own_words": "用你自己的话。",+ "note_auto": "没有收到回答,因此选择了推荐选项。",+ "note_agent": "交给 {agent}:采用了推荐选项。",+ "note_declined": "已跳过,由 {agent} 决定。",+ "note_moved_on": "你转到了别的话题,因此采用了推荐选项。",+ "note_message": "已在聊天中回答。",+ "unanswered": "未回答:本轮已结束。",+ "composer_placeholder": "回答 {agent},或聊点别的"},"bot_stage": {"ponder": "正在思考…",diff --git a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts b/dodaios/ui/web/frontend/src/lib/agentChatApi.tsindex 7cfea1b9f9..3e3e68bffb 100644--- a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts+++ b/dodaios/ui/web/frontend/src/lib/agentChatApi.ts@@ -654,8 +654,14 @@ export async function saveAgentChatApprovalRule(return reply.rule;}-/** The person's answer to an agent's question: one option, or their own words. */-export type QuestionAnswerInput = { optionIndex: number } | { text: string };+/**+ * The person's answer to an agent's question: one option, their own words, or+ * the picks of a multi-select question (with their own words beside them).+ */+export type QuestionAnswerInput =+ | { optionIndex: number }+ | { text: string }+ | { optionIndices: number[]; text?: string };function questionUrl(sessionId: string, questionId: string): string {return `/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/questions/${encodeURIComponent(questionId)}`;@@ -670,7 +676,11 @@ export async function answerAgentChatQuestion(): Promise<void> {const body = {index,- ...("optionIndex" in answer ? { option_index: answer.optionIndex } : { text: answer.text }),+ ...("optionIndex" in answer+ ? { option_index: answer.optionIndex }+ : "optionIndices" in answer+ ? { option_indices: answer.optionIndices, ...(answer.text ? { text: answer.text } : {}) }+ : { text: answer.text }),};await json(await fetch(questionUrl(sessionId, questionId), {@@ -682,10 +692,66 @@ export async function answerAgentChatQuestion();}-/** Close an agent's card: its open questions take the agent's recommendations. */-export async function skipAgentChatQuestion(sessionId: string, questionId: string): Promise<void> {+/**+ * Close an agent's card: its open questions take the agent's recommendations.+ * With `index`, only that question is skipped (an empty answer the agent+ * decides on) and the rest of the card stays open.+ */+export async function skipAgentChatQuestion(sessionId: string, questionId: string, index?: number): Promise<void> {+ await json(+ await fetch(`${questionUrl(sessionId, questionId)}/skip`, {+ method: "POST",+ ...(index === undefined+ ? {}+ : { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ index }) }),+ }),+ "question-failed",+ );+}++/** One reviewed answer of a card's series, as `/submit` takes it. */+export type QuestionSubmitAnswer =+ | { option_index: number }+ | { option_indices: number[]; text?: string }+ | { text: string }+ | { skip: true };++/** Send the person's reviewed answers to the whole card at once. */+export async function submitAgentChatQuestion(+ sessionId: string,+ questionId: string,+ answers: QuestionSubmitAnswer[],+): Promise<void> {await json(- await fetch(`${questionUrl(sessionId, questionId)}/skip`, { method: "POST" }),+ await fetch(`${questionUrl(sessionId, questionId)}/submit`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ answers }),+ }),+ "question-failed",+ );+}++/** The person is still answering on the card: its quiet window starts again. */+export async function touchAgentChatQuestion(sessionId: string, questionId: string): Promise<void> {+ await json(await fetch(`${questionUrl(sessionId, questionId)}/touch`, { method: "POST" }), "question-failed");+}++/**+ * A chat message sent while a question card is open answers it. `consumed`+ * means a running turn took it as its answer and nothing else is sent; an+ * end-of-turn card settles too, and the message then goes out as usual.+ */+export async function replyToAgentChatQuestion(+ sessionId: string,+ text: string,+): Promise<{ consumed: boolean; question_id: string | null }> {+ return json(+ await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/reply-to-question`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ text }),+ }),"question-failed",);}diff --git a/dodaios/ui/web/frontend/src/store/agentChat.ts b/dodaios/ui/web/frontend/src/store/agentChat.tsindex 4b691f900f..818409827d 100644--- a/dodaios/ui/web/frontend/src/store/agentChat.ts+++ b/dodaios/ui/web/frontend/src/store/agentChat.ts@@ -20,7 +20,11 @@ import {saveAgentChatApprovalRule,answerAgentChatQuestion,bindVoiceChat,+ replyToAgentChatQuestion,skipAgentChatQuestion,+ submitAgentChatQuestion,+ touchAgentChatQuestion,+ type QuestionSubmitAnswer,resolveAgentChatPlan,type PlanDecision,type QuestionAnswerInput,@@ -41,6 +45,7 @@ import {type ProviderHealth,} from "@/lib/agentChatApi";import { EMPTY_TIMELINE, noteApprovalRule, reduceEvent, reduceEvents, settleApproval, type Timeline } from "@/components/agentchat/reduce";+import { openQuestionOf } from "@/components/agentchat/questions/questionModel";import { jitteredDelay, requestConnect } from "../lib/connectBudget";import { reuseHistoryRows } from "@/lib/historyRequests";@@ -198,8 +203,25 @@ export interface AgentChatStore {saveApprovalRule: (approvalId: string, rule: ApprovalRuleRequest) => Promise<void>;/** Answer question `index` of an agent's card in the active session; throws so the card can say why. */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>;+ /**+ * Close an agent's card so its recommendations apply; with `index`, skip+ * only that question. Throws so the card can say why.+ */+ skipQuestion: (questionId: string, index?: number) => Promise<void>;+ /**+ * Send the person's reviewed answers to the whole card at once. Optional:+ * a store without it gets the answers one question at a time. Throws so the+ * card can roll back; a card the server no longer holds resolves quietly.+ */+ submitQuestion?: (questionId: string, answers: QuestionSubmitAnswer[]) => Promise<void>;+ /** The person is still answering: the card's quiet window starts again. Never throws. */+ touchQuestion?: (questionId: string) => Promise<void>;+ /**+ * A composer message while a card is open answers it. True when a running+ * turn took the message as its answer, so nothing else is sent; false sends+ * it as usual (an end-of-turn card is settled by the same call).+ */+ answerByMessage?: (text: string) => Promise<boolean>;/** 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. */@@ -928,10 +950,45 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =await answerAgentChatQuestion(sid, questionId, index, answer);},- skipQuestion: async (questionId) => {+ skipQuestion: async (questionId, index) => {const sid = get().activeSessionId;if (!sid) throw new Error("no open chat");- await skipAgentChatQuestion(sid, questionId);+ await skipAgentChatQuestion(sid, questionId, index);+ },++ submitQuestion: async (questionId, answers) => {+ const sid = get().activeSessionId;+ if (!sid) throw new Error("no open chat");+ try {+ await submitAgentChatQuestion(sid, questionId, answers);+ } catch (err) {+ // 404: the card closed on the server meanwhile (its window ran out,+ // or the turn ended). Its own closing event says what was chosen.+ if (err instanceof AgentChatApiError && err.status === 404) return;+ throw err;+ }+ },++ touchQuestion: async (questionId) => {+ const sid = get().activeSessionId;+ if (!sid) return;+ try {+ await touchAgentChatQuestion(sid, questionId);+ } catch {+ /* a lost touch only means the card keeps its first deadline */+ }+ },++ answerByMessage: async (text) => {+ const sid = get().activeSessionId;+ if (!sid || !text.trim() || !openQuestionOf(get().timeline)) return false;+ try {+ const outcome = await replyToAgentChatQuestion(sid, text);+ return outcome.consumed;+ } catch {+ // The route failed: the message still goes out as an ordinary one.+ return false;+ }},resolvePlan: async (turnId, decision) => {diff --git a/tests/unit/agent_chat/test_questions_kinds.py b/tests/unit/agent_chat/test_questions_kinds.pynew file mode 100644index 0000000000..76adbcc9df--- /dev/null+++ b/tests/unit/agent_chat/test_questions_kinds.py@@ -0,0 +1,425 @@+"""Question kinds and the forgiving answer paths of the question card.++Multi-select and text-only questions, a reviewed series sent at once, skipping+one question, a chat message as the answer, and the guarantee that silence or+an unattended run never stalls, whatever the kind.+"""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from dodaios.agent_chat import turn_prompts+from dodaios.agent_chat.events import make_event+from dodaios.agent_chat.questions import (+ DECLINED,+ MESSAGE,+ MOVED_ON,+ MULTI,+ SINGLE,+ TEXT,+ answer_from,+ answer_json,+ parse_questions,+ recommended_answer,+)+from dodaios.agent_chat.service import AgentChatService, _Running+from dodaios.agent_chat.store import AgentChatStore+from dodaios.society.ask_tool import AskUserTool++_DB: dict[str, Any] = {+ "question": "Which database should the project use?",+ "options": [{"label": "SQLite"}, {"label": "Postgres"}],+ "recommendation_reason": "No server to run.",+}+_FEATURES: dict[str, Any] = {+ "question": "Which features should ship first?",+ "kind": "multi",+ "options": [{"label": "Search"}, {"label": "Export"}, {"label": "Sharing"}],+ "recommended": [2, 0],+ "recommendation_reason": "Most asked for.",+}+_NAME: dict[str, Any] = {"question": "What should the project be called?", "kind": "text"}+++# ------------------------------------------------------------------ parsing+++def test_multi_keeps_its_recommendations_first_in_the_agents_order() -> None:+ (spec,) = parse_questions(_FEATURES)+ assert spec.kind == MULTI+ assert [o.label for o in spec.options] == ["Sharing", "Search", "Export"]+ assert spec.recommended_indices == (0, 1)+ payload = spec.to_payload()+ assert payload["kind"] == "multi" and payload["recommended_count"] == 2+++def test_every_runtime_spelling_of_multi_select_is_understood() -> None:+ for flag in ({"multiSelect": True}, {"multi": True}, {"multi_select": "true"}):+ (spec,) = parse_questions({**_DB, **flag})+ assert spec.kind == MULTI+ (plain,) = parse_questions({**_DB, "multiSelect": False})+ assert plain.kind == SINGLE+++def test_a_single_question_payload_is_unchanged() -> None:+ (spec,) = parse_questions(_DB)+ assert set(spec.to_payload()) == {"question", "options", "recommended", "recommendation_reason"}+++def test_a_text_question_needs_no_options_and_defaults_to_empty() -> None:+ (spec,) = parse_questions(_NAME)+ assert spec.kind == TEXT and spec.options == () and spec.allow_custom+ default = recommended_answer(spec, "timeout")+ assert (default.answer, default.option_index, default.source) == ("", None, "timeout")+ with pytest.raises(ValueError):+ answer_from(spec, option_index=None, text="")+ assert answer_from(spec, option_index=None, text=" Atlas ").answer == "Atlas"+++def test_multi_answers_reach_the_agent_one_label_per_line() -> None:+ (spec,) = parse_questions(_FEATURES)+ picked = answer_from(spec, option_index=None, text="Dark mode", option_indices=[2, 0])+ assert picked.answer == "Sharing\nExport\nDark mode"+ assert picked.option_indices == (0, 2) and picked.option_index is None+ assert picked.to_payload()["option_indices"] == [0, 2]+ default = recommended_answer(spec, "timeout")+ assert default.answer == "Sharing\nSearch" and default.option_indices == (0, 1)+ with pytest.raises(ValueError):+ answer_from(spec, option_index=None, text=None, option_indices=[])+ with pytest.raises(ValueError):+ answer_from(spec, option_index=None, text=None, option_indices=[7])+ with pytest.raises(ValueError):+ parse_questions({**_FEATURES, "recommended": [0, 1, 2]})+++def test_a_question_can_refuse_own_words() -> None:+ (spec,) = parse_questions({**_DB, "allow_custom": False})+ with pytest.raises(ValueError):+ answer_from(spec, option_index=None, text="MySQL")+ assert answer_json(spec, {"option_indices": [1]}).answer == "Postgres"+ assert answer_json(spec, {"skip": True}).source == DECLINED+ for bad in ({"option_index": "1"}, {"option_indices": "1"}, "nope", {}):+ with pytest.raises(ValueError):+ answer_json(spec, bad)+++# ------------------------------------------------------------------ live cards+++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_a_reviewed_series_resolves_with_one_submit(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, task = await _service_with_turn(tmp_path)+ q = svc.subscribe(sid)+ specs = parse_questions({"questions": [_DB, _FEATURES, _NAME]})+ asking = asyncio.create_task(svc.ask_questions(sid, specs))+ qid = (await _next(q, "question_required"))["question_id"]+ # A bad entry changes nothing: every answer is checked first.+ with pytest.raises(ValueError):+ svc.submit_questions(sid, qid, [{"option_index": 1}, {"option_indices": [9]}, {}])+ with pytest.raises(ValueError):+ svc.submit_questions(sid, qid, [{"option_index": 1}])+ assert svc.pending_questions(sid) == [qid]+ assert svc.submit_questions(+ sid,+ qid,+ [{"option_index": 1}, {"option_indices": [1, 2], "text": "Dark mode"}, {"skip": True}],+ )+ answers = await asking+ assert [(a.answer, a.source) for a in answers] == [+ ("Postgres", "person"),+ ("Search\nExport\nDark mode", "person"),+ ("", DECLINED),+ ]+ resolved = await _next(q, "question_resolved")+ assert resolved["answers"][1]["option_indices"] == [1, 2]+ assert not svc.submit_questions(sid, qid, [{}, {}, {}]) # closed+ task.cancel()++ asyncio.run(scenario())+++def test_skipping_one_question_keeps_the_rest_open(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, task = await _service_with_turn(tmp_path)+ asking = asyncio.create_task(+ svc.ask_questions(sid, parse_questions({"questions": [_DB, _FEATURES]}))+ )+ await asyncio.sleep(0)+ (qid,) = svc.pending_questions(sid)+ assert svc.skip_question(sid, qid, 0)+ assert not svc.skip_question(sid, qid, 0) # already settled+ assert svc.pending_questions(sid) == [qid]+ assert svc.resolve_question(sid, qid, index=1, option_indices=[2])+ answers = await asking+ assert [(a.answer, a.source) for a in answers] == [+ ("", DECLINED),+ ("Export", "person"),+ ]+ task.cancel()++ asyncio.run(scenario())+++def test_silence_applies_multi_recommendations(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, task = await _service_with_turn(tmp_path)+ specs = parse_questions({"questions": [_FEATURES, _NAME]})+ answers = await svc.ask_questions(sid, specs, timeout_s=0.05)+ assert [(a.answer, a.source) for a in answers] == [+ ("Sharing\nSearch", "timeout"),+ ("", "timeout"),+ ]+ task.cancel()++ asyncio.run(scenario())+++def test_a_touch_restarts_the_quiet_window(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, task = await _service_with_turn(tmp_path)+ q = svc.subscribe(sid)+ qid = await svc.open_questions(sid, parse_questions(_DB), timeout_s=0.4)+ first = await _next(q, "question_required")+ await asyncio.sleep(0.25)+ assert svc.touch_question(sid, qid)+ progress = await _next(q, "question_progress")+ assert progress["expires_ms"] > first["expires_ms"]+ await asyncio.sleep(0.25) # past the first deadline, inside the new one+ assert svc.pending_questions(sid) == [qid]+ answers = await svc.wait_questions(sid, qid, 5)+ assert answers is not None and answers[0].source == "timeout"+ assert not svc.touch_question(sid, qid)+ task.cancel()++ asyncio.run(scenario())+++def test_a_chat_message_answers_the_newest_card(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, task = await _service_with_turn(tmp_path)+ svc._running[sid].asks = -1 # room for three cards in this turn+ older = await svc.open_questions(sid, parse_questions(_DB))+ sticky = await svc.open_questions(+ sid, parse_questions({**_NAME, "dismiss_on_move_on": False})+ )+ newest = await svc.open_questions(+ sid, parse_questions({"questions": [_FEATURES, {**_DB, "question": "And hosting?"}]})+ )+ outcome = await svc.answer_by_message(sid, "Only search, please")+ assert outcome == {"consumed": True, "question_id": newest}+ answers = await svc.wait_questions(sid, newest, 5)+ assert answers is not None+ assert [(a.answer, a.source) for a in answers] == [+ ("Only search, please", MESSAGE),+ ("SQLite", MOVED_ON),+ ]+ (old,) = await svc.wait_questions(sid, older, 5) or []+ assert (old.answer, old.source) == ("SQLite", MOVED_ON)+ assert svc.pending_questions(sid) == [sticky] # asked to stay open+ task.cancel()++ asyncio.run(scenario())+++def test_a_message_naming_an_option_picks_it(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, task = await _service_with_turn(tmp_path)+ qid = await svc.open_questions(sid, parse_questions(_DB))+ assert (await svc.answer_by_message(sid, "b"))["consumed"]+ (answer,) = await svc.wait_questions(sid, qid, 5) or []+ assert (answer.answer, answer.option_index, answer.source) == ("Postgres", 1, MESSAGE)+ # Nothing open: the message is an ordinary message.+ assert await svc.answer_by_message(sid, "thanks") == {+ "consumed": False,+ "question_id": None,+ }+ task.cancel()++ asyncio.run(scenario())+++# ------------------------------------------------------------------ the ask tool+++class _Service:+ def __init__(self, answers: Any) -> None:+ self.answers = answers++ async def open_questions(self, session_id: str, specs: Any, *, asker: str = "") -> str:+ self.specs = specs+ return "q1"++ async def wait_questions(self, session_id: str, question_id: str, timeout_s: Any) -> Any:+ return self.answers(self.specs)+++def _tool(session_id: str, service: Any) -> AskUserTool:+ runtime = SimpleNamespace(+ chat_service=lambda: service, cached_agent=lambda _id: SimpleNamespace(name="Ada")+ )+ return AskUserTool(runtime, "ada", session_id=session_id)+++def test_the_tool_offers_the_kinds_without_requiring_options() -> None:+ item = AskUserTool.schema["properties"]["questions"]["items"]+ assert item["properties"]["kind"]["enum"] == ["single", "multi", "text"]+ assert "options" not in item["required"]+++def test_the_tool_reports_multi_picks_and_a_skipped_question() -> None:+ def answers(specs: Any) -> Any:+ return [+ answer_from(specs[0], option_index=None, text=None, option_indices=[1, 2]),+ answer_json(specs[1], {"skip": True}),+ ]++ args = {"questions": [_FEATURES, _NAME]}+ result = asyncio.run(_tool("society:ada", _Service(answers)).execute(args, None))+ assert result.success+ first, second = result.output["answers"]+ assert first["picked"] == ["Search", "Export"] and first["answer"] == "Search\nExport"+ assert second["source"] == DECLINED+ assert "decide it yourself" in result.output["note"]+++def test_the_tool_reads_a_chat_reply_as_the_answer() -> None:+ def answers(specs: Any) -> Any:+ return [answer_from(specs[0], option_index=None, text="Neither", source=MESSAGE)]++ result = asyncio.run(_tool("society:ada", _Service(answers)).execute(dict(_DB), None))+ (row,) = result.output["answers"]+ assert row["typed"] is True and row["source"] == MESSAGE+ assert "replied in the chat" in result.output["note"]+++def test_a_routine_never_waits_on_any_kind() -> None:+ def never(_specs: Any) -> Any:+ raise AssertionError("a routine must not open a card")++ args = {"questions": [_FEATURES, _NAME]}+ result = asyncio.run(_tool("society:ada:routine:t1:run1", _Service(never)).execute(args, None))+ assert [r["answer"] for r in result.output["answers"]] == ["Sharing\nSearch", ""]+ assert {r["source"] for r in result.output["answers"]} == {"unattended"}+++# ------------------------------------------------------------------ end-of-turn cards+++async def _deferred(tmp_path: Path, payload: Any) -> tuple[AgentChatService, str, list[Any]]:+ svc = AgentChatService(AgentChatStore(":memory:"))+ session = svc.store.create_session(+ provider="openai-codex", model="", effort="", cwd=str(tmp_path),+ permission_mode="auto", surface="agent",+ )+ sent: list[tuple[str, str | None]] = []++ async def send(session_id: str, text: str, *_: Any, **kwargs: Any) -> str:+ sent.append((text, kwargs.get("display_text")))+ return "next"++ svc.send = send # type: ignore[method-assign]+ sid = session.session_id+ block = f"Two choices.\n\n```{turn_prompts.ASK_FENCE}\n{json.dumps(payload)}\n```\n"+ await svc._emit(sid, make_event("turn_started", {"turn_id": "t1"}))+ await svc._emit(sid, make_event("assistant_text", {"turn_id": "t1", "text": block}))+ await svc._emit(sid, make_event("turn_finished", {"turn_id": "t1", "status": "done"}))+ await svc._open_turn_prompts(sid, "t1", "codex-cli")+ return svc, sid, sent+++def _payloads(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_a_fence_can_ask_a_multi_select_question(tmp_path: Path) -> None:+ async def scenario() -> None:+ fence = {"questions": [{**_DB, "multi": True}, _NAME]}+ svc, sid, sent = await _deferred(tmp_path, fence)+ (card,) = _payloads(svc, sid, "question_required")+ assert card["questions"][0]["kind"] == "multi" and card["questions"][1]["kind"] == "text"+ qid = card["question_id"]+ assert await svc.submit_turn_question(+ sid, qid, [{"option_indices": [0, 1]}, {"text": "Atlas"}]+ )+ ((prompt, shown),) = sent+ assert "Which database should the project use? -> SQLite, Postgres" in prompt+ assert "What should the project be called? -> Atlas" in prompt+ assert shown.splitlines()[0].endswith("SQLite, Postgres")+ assert not await svc.submit_turn_question(sid, qid, [{}, {}])++ asyncio.run(scenario())+++def test_skipping_one_deferred_question_sends_once_settled(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _deferred(tmp_path, {"questions": [_DB, _NAME]})+ qid = _payloads(svc, sid, "question_required")[0]["question_id"]+ assert await svc.skip_turn_question(sid, qid, index=1)+ assert sent == [] and len(_payloads(svc, sid, "question_progress")) == 1+ assert await svc.answer_turn_question(sid, qid, index=0, option_index=1)+ ((prompt, _),) = sent+ assert "-> skipped; decide it yourself." in prompt++ asyncio.run(scenario())+++def test_a_chat_message_settles_a_deferred_card_without_consuming(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _deferred(tmp_path, {"questions": [_DB, _NAME]})+ qid = _payloads(svc, sid, "question_required")[0]["question_id"]+ assert turn_prompts.newest_open_ask(svc.store.list_events(sid)) is not None+ outcome = await svc.answer_by_message(sid, "Postgres, and call it Atlas")+ assert outcome == {"consumed": False, "question_id": qid}+ (resolved,) = _payloads(svc, sid, "question_resolved")+ assert [(a["answer"], a["source"]) for a in resolved["answers"]] == [+ ("Postgres, and call it Atlas", MESSAGE),+ ("", MOVED_ON),+ ]+ assert sent == [] # the caller sends the message itself+ assert turn_prompts.newest_open_ask(svc.store.list_events(sid)) is None++ asyncio.run(scenario())+++def test_a_stored_multi_card_keeps_every_recommendation(tmp_path: Path) -> None:+ async def scenario() -> None:+ svc, sid, sent = await _deferred(tmp_path, {"questions": [_FEATURES]})+ (card,) = _payloads(svc, sid, "question_required")+ assert card["questions"][0]["recommended_count"] == 2+ # The card is read back from its event; closing it applies both picks.+ assert await svc.skip_turn_question(sid, card["question_id"])+ ((prompt, _),) = sent+ assert "go with your recommendation (Sharing, Search)" in prompt++ asyncio.run(scenario())+++def test_a_stored_multi_payload_parses_back_to_the_same_question() -> None:+ (spec,) = parse_questions(_FEATURES)+ (again,) = parse_questions({"questions": [spec.to_payload()]})+ assert again == specdiff --git a/tests/unit/agent_chat/test_questions_routes.py b/tests/unit/agent_chat/test_questions_routes.pynew file mode 100644index 0000000000..7c3956eebd--- /dev/null+++ b/tests/unit/agent_chat/test_questions_routes.py@@ -0,0 +1,62 @@+"""The question card's routes: reviewed submit, single-question skip, touch, chat reply."""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++from fastapi import FastAPI+from fastapi.testclient import TestClient++from dodaios.agent_chat.questions import parse_questions+from dodaios.agent_chat.service import AgentChatService, _Running+from dodaios.agent_chat.store import AgentChatStore+from dodaios.ui.web.agent_chat_routes import router++_DB: dict[str, Any] = {+ "question": "Which database?",+ "options": [{"label": "SQLite"}, {"label": "Postgres"}],+}+_FEATURES: dict[str, Any] = {+ "question": "Which features?",+ "multi": True,+ "options": [{"label": "Search"}, {"label": "Export"}, {"label": "Sharing"}],+}+++def test_the_card_routes_drive_a_live_card(tmp_path: Path) -> None:+ svc = AgentChatService(AgentChatStore(":memory:"))+ sid = svc.store.create_session(provider="p", model="m", effort="", cwd=str(tmp_path)).session_id++ async def open_cards() -> tuple[str, str]:+ run = _Running("t1", asyncio.Event())+ run.task = asyncio.ensure_future(asyncio.sleep(3600))+ svc._running[sid] = run+ first = await svc.open_questions(sid, parse_questions({"questions": [_DB, _FEATURES]}))+ second = await svc.open_questions(sid, parse_questions(_DB))+ return first, second++ app = FastAPI()+ app.include_router(router)+ app.state.agent_chat = svc+ with TestClient(app) as client:+ # The service's cards live on the client's loop.+ first, second = client.portal.call(open_cards) # type: ignore[union-attr]+ base = f"/api/agent-chat/sessions/{sid}/questions"+ assert client.post(f"{base}/{first}/touch").json() == {"ok": True}+ bad = client.post(f"{base}/{first}/submit", json={"answers": [{"option_index": 9}, {}]})+ assert bad.status_code == 400+ assert client.post(f"{base}/{first}/skip", json={"index": 0}).status_code == 200+ picks = {"answers": [{}, {"option_indices": [0, 2]}]}+ ok = client.post(f"{base}/{first}/submit", json=picks)+ assert ok.status_code == 200+ assert client.post(f"{base}/{first}/submit", json={"answers": [{}, {}]}).status_code == 404+ reply = client.post(f"/api/agent-chat/sessions/{sid}/reply-to-question", json={"text": "a"})+ assert reply.json() == {"ok": True, "consumed": True, "question_id": second}+ assert svc.pending_questions(sid) == []+ answers = client.portal.call(svc.wait_questions, sid, first, 5) # type: ignore[union-attr]+ assert [(a.answer, a.source) for a in answers] == [+ ("", "declined"),+ ("Search\nSharing", "person"),+ ]diff --git a/tests/unit/agent_chat/test_turn_prompts.py b/tests/unit/agent_chat/test_turn_prompts.pyindex 826a34babc..4a9d818f86 100644--- a/tests/unit/agent_chat/test_turn_prompts.py+++ b/tests/unit/agent_chat/test_turn_prompts.py@@ -446,6 +446,58 @@ def test_claude_asks_on_the_question_card_and_reads_the_answers(]+def test_claude_multi_select_becomes_a_multi_card_and_answers_with_commas(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ question = {+ "question": "Which toppings?",+ "header": "Toppings",+ "options": [{"label": "Cheese"}, {"label": "Olives"}, {"label": "Basil"}],+ "multiSelect": True,+ }++ async def ask_multi(self: Any, session_id: str, specs: Any, **_: Any) -> list[QuestionAnswer]:+ self.asked.append(specs)+ return [QuestionAnswer("Cheese\nBasil", None, "person", (0, 2))]++ monkeypatch.setattr(_FakeChat, "ask_questions", ask_multi)+ answers, chat, _ = _claude_turn(+ monkeypatch,+ tmp_path,+ [_can_use("AskUserQuestion", {"questions": [question]})],+ mode="default",+ )+ ((spec,),) = chat.asked+ assert spec.kind == "multi"+ assert answers[0]["updatedInput"]["answers"] == {"Which toppings?": "Cheese, Basil"}+++def test_a_skipped_claude_question_still_answers_in_words(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ async def ask_declined(self: Any, session_id: str, specs: Any, **_: Any) -> list[QuestionAnswer]:+ self.asked.append(specs)+ return [QuestionAnswer("", None, "declined")]++ monkeypatch.setattr(_FakeChat, "ask_questions", ask_declined)+ answers, _, _ = _claude_turn(+ monkeypatch,+ tmp_path,+ [_can_use("AskUserQuestion", {"questions": [_ASK["questions"][0]]})],+ mode="default",+ )+ (picked,) = answers[0]["updatedInput"]["answers"].values()+ assert picked == "No preference; decide yourself."+++def test_the_protocol_names_multi_select_in_one_sentence() -> None:+ assert '"multi": true' in turn_prompts.ASK_PROTOCOL+ specs = turn_prompts.parse_ask_block(+ _reply_with_block({"questions": [{**_ASK["questions"][0], "multi": True}]})+ )+ assert specs is not None and specs[0].kind == "multi"++def test_an_approved_claude_plan_leaves_plan_mode(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: