DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(chat): let a turn read as a running account instead of an answer with hidden working
Bingxi Zhao (Frank)541b7f4f16f9
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yamlindex f98664b8b..6e78dacef 100644--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml@@ -61,18 +61,25 @@ loop:files, notebooks, or ask_user to clarify). Default to acting: useask_user only when a missing piece genuinely blocks reasonable progress,and ask everything in one call; otherwise proceed on sensible- assumptions and state them in the answer. When you call a tool you may- add one short sentence saying what you are about to do and why; keep it- brief. After each round you see the results and may call more tools.+ assumptions and state them in the answer. After each round you see the+ results and may call more tools.++ Before you call a tool, say what you are about to do and why, in a+ sentence or two of plain language. The reader sees that text as you write+ it, with the tool's own row underneath it, so it is how they follow the+ work — not an internal note. Keep it to what a colleague would say out+ loud: what you are checking now, and what a result changed when it sends+ you somewhere new. No preamble before a single trivial lookup.When you have gathered enough — or the request needs no tools at all —- stop calling tools and write the final, user-facing answer directly.- That tool-less reply is shown to the user as the answer and ends the- loop, so write it for the reader: use concise Markdown and clear teaching- language, do not mention these internal mechanics or repeat your working- notes verbatim, and refer to generated artifacts exactly as the tool result- lists them. Build the answer on the conversation above — the gathered- evidence, memory, persona, and attached sources.+ stop calling tools and write the closing answer. That tool-less reply+ ends the loop. The reader has already followed the progress notes above+ it, so do not replay them: lead with the outcome and add only what they+ still need. Use concise Markdown and clear teaching language, do not+ mention these internal mechanics or repeat your working notes verbatim,+ and refer to generated artifacts exactly as the tool result lists them.+ Build the answer on the conversation above — the gathered evidence,+ memory, persona, and attached sources.If a skill listed in the Skills block matches the task, call read_skillbefore attempting that workflow, then follow the skill instructions.diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yamlindex 378928355..95a7a45d0 100644--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml@@ -45,12 +45,17 @@ loop:你在一个循环里回答每个用户请求。每一轮你都可以调用工具(检索、读取来源、搜索、脚本、文件、笔记本,或用 ask_user 向用户澄清)。默认直接动手:只有缺少关键信息、确实无法合理继续时才用 ask_user,而且一次问全;其余情况用合理假设直接做,并在回答里说明你的假设。- 调用工具时,可以用一句话简短说明你接下来要做什么、为什么,保持简短。每轮结束后你会看到工具结果,可以继续调用。- 当材料已经足够——或这个请求根本不需要工具时——就停止调用工具,直接写出面向用户的最终回答。- 这条不带工具调用的回复会作为正式答案呈现给用户并结束循环,所以要为读者而写:用简洁 Markdown- 和清晰的教学语言,不要提及这些内部机制、也不要逐字复述你的工作笔记,并按工具结果原样引用生成文件。+ 调用工具之前,先用一两句平实的话说明你接下来要做什么、为什么。这段文字会随着你写出来即时呈现给+ 读者,工具自己的执行行就显示在它下面——这是读者跟进你工作的方式,不是内部备注。+ 像同事口头交代那样即可:你现在在查什么;某个结果让你改变方向时,是什么改变了。+ 单次琐碎查询前不必铺垫。++ 当材料已经足够——或这个请求根本不需要工具时——就停止调用工具,写出收尾的回答。+ 这条不带工具调用的回复会结束循环。读者已经一路看过上面的进展说明,所以不要复述它们:+ 先给结论,只补充读者还需要的部分。用简洁 Markdown 和清晰的教学语言,不要提及这些内部机制、+ 也不要逐字复述你的工作笔记,并按工具结果原样引用生成文件。基于上面的对话——已收集的证据、记忆、persona 和附件来源——作答。如果 Skills 区域里有匹配任务的 skill,先调用 read_skill 再执行该工作流,并遵循 skill 的指示。diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.pyindex 75fe6caaa..66f012df6 100644--- a/deeptutor/agents/loop/agent_loop.py+++ b/deeptutor/agents/loop/agent_loop.py@@ -5,12 +5,13 @@ One chat turn = ONE agent loop over a single growing conversation:* each round is one LLM call; its text streams to the user as a ``content``block, and its tool calls are dispatched with their ``role=tool`` resultsappended back into the conversation;-* a round that DOES call tools is "narration" by default — its text is a- preamble to the tool work — and the loop continues; modes that intentionally- combine learner-facing prose with a tool call mark that prose answer-visible;-* a round that calls NO tools is the ``finish``: its text IS the final- user-facing answer and the loop ends (the model deciding it is done; a- first round without tool calls is the "no exploration needed" fast path);+* every round's text is part of the answer, in the order it was written. A+ round that DOES call tools has written *commentary* — what it is about to do+ and why — and the loop continues; the reader keeps that text, with the tool+ work rendered inline beneath it, the way a terminal agent reads;+* a round that calls NO tools is the ``finish``: its text closes the answer and+ the loop ends (the model deciding it is done; a first round without tool+ calls is the "no exploration needed" fast path);* if the exploration budget runs out while work is still in protocol, asmall bounded settlement phase keeps tools available for already-startedfollow-up (including user input); one final tool-less round is forced only@@ -19,10 +20,13 @@ One chat turn = ONE agent loop over a single growing conversation:``ask_user`` pauses the turn for a reply and resumes in-protocol; anunresolved pause (or a terminator tool) halts the turn.-There is no separate respond pass and no text destination has to be guessed-mid-stream: every round's text streams to the user as it is generated, and a-``call_role`` (``narration`` vs ``finish``) emitted when the round completes-tells the frontend how to render that round's text.+There is no separate respond pass and no text destination has to be guessed:+every round's text streams to the user as it is generated and stays there. The+``call_status`` marker a completed round emits carries two independent facts —+``call_role`` (``narration`` = more work follows, ``finish`` = terminal) says+where the turn is, while ``answer_visible`` says whether the text counts as+answer content. It is ``True`` for every ordinary round; only a capability+retracting a rejected round sets it ``False``."""from __future__ import annotations@@ -504,8 +508,10 @@ class AgentLoop:if output_policy == "discard":await self._discard_deferred_output(result)else:- if output_policy == "publish" and result.deferred_completion_metadata is not None:- result.deferred_completion_metadata["answer_visible"] = True+ # ``publish`` needs no marker any more: a tool round's prose is+ # answer content by default. The hook is still consulted because+ # capabilities act on it (partner_group saves the formal answer+ # from the very round it classifies).await self._release_deferred_output(result)assistant = assistant_message_with_tool_calls(result.text,@@ -745,13 +751,16 @@ class AgentLoop:async def _discard_deferred_output(self, result: LLMCallResult) -> None:"""Take a rejected round's prose back out of the answer.- Two shapes reach here. A *buffered* round is simply never published:- closing its trace as ``narration`` is the whole retraction. A round+ Two shapes reach here. A *buffered* round is simply never published,+ so closing its trace as retracted is the whole retraction. A roundthat already **streamed** — the ordinary case now that only protocol- capabilities buffer — was published optimistically and closed as- ``finish``, so its retraction has to be a correction: the same- ``call_id``, re-marked ``narration``, which is what moves that text out- of the answer and into the collapsed trace on the reader's side.+ capabilities buffer — was published optimistically, so its retraction+ has to be a correction: the same ``call_id`` re-marked+ ``answer_visible: False``, which is what moves that text out of the+ answer and into the collapsed trace on the reader's side.++ This is the ONLY way prose leaves the answer. Ordinary commentary+ written before a tool call stays where the reader saw it.Emitting nothing in that second case was what left rejected prosesitting in the answer as though it had been accepted.@@ -760,7 +769,7 @@ class AgentLoop:if metadata is not None:metadata = dict(metadata)metadata["call_role"] = "narration"- metadata.pop("answer_visible", None)+ metadata["answer_visible"] = Falsemetadata["finish_rejected"] = Trueawait self.stream.progress("",@@ -881,12 +890,11 @@ class AgentLoop:# DeepSeek's Anthropic-compatible endpoint can interleave# user-facing prose and DSML calls in one content stream.dsml_filter = DSMLStreamFilter()- answer_content_emitted = Falsevisible_text_parts: list[str] = []output_emitted = Falseasync def _emit_segments(segments: list[tuple[str, str]]) -> None:- nonlocal answer_content_emitted, output_emitted+ nonlocal output_emittedfor kind, segment in segments:if kind == "thinking":# Reasoning goes to the trace on every round shape.@@ -905,8 +913,6 @@ class AgentLoop:continueoutput_emitted = Truevisible_text_parts.append(segment)- if segment.strip():- answer_content_emitted = Trueif not defer_visible_output:await self.stream.content(segment, source=self.source, stage=stage, metadata=chunk_meta@@ -1148,21 +1154,18 @@ class AgentLoop:completion_metadata: dict[str, Any] = {"trace_kind": "call_status","call_state": "complete",- # A round with tool calls is narration; a tool-less round is the- # finish whose text is the user-facing answer. Token-truncated- # output remains visible but is not terminal: the loop continues.+ # ``call_role`` states this round's PHASE, not whether its text is+ # shown: ``narration`` is mid-turn commentary (more work follows),+ # ``finish`` is the terminal round. Token-truncated output is+ # visible but not terminal, so it stays ``narration``."call_role": "narration" if tool_calls or truncated_round else "finish",+ # Every round's prose belongs to the answer, in the order it was+ # written. Commentary written before a tool call is what the reader+ # is told while the work happens, not an internal preamble to hide,+ # so the only text that ever leaves the answer is text a capability+ # explicitly retracts (see ``_discard_deferred_output``).+ "answer_visible": True,}- mastery_tool_round = bool(tool_calls) and bool(self.context.metadata.get("mastery_mode"))- if (dsml_calls or truncated_round or mastery_tool_round) and answer_content_emitted:- # DSML providers may intentionally combine tutor feedback and an- # ask_user/tool call in the same round. Preserve only that cleaned- # surrounding prose in the answer surfaces. Truncated rounds also- # keep their partial answer visible while retaining a truthful- # non-terminal ``narration`` role. Mastery rounds likewise combine- # learner-facing teaching with state/quiz tools; that teaching is- # answer content, not an internal tool preamble.- completion_metadata["answer_visible"] = Truecompletion_event_metadata = merge_trace_metadata(trace_meta, completion_metadata)if forced_tool_choice and not tool_calls and text:diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.pyindex b117ecece..a43123c15 100644--- a/deeptutor/services/partners/runtime.py+++ b/deeptutor/services/partners/runtime.py@@ -13,8 +13,10 @@ Event → IM mapping:text (the loop's RESULT is empty for an unresolved ask_user pause — thepending question IS the reply, and the user's next IM message simplystarts the next turn)-* trace-only narration rounds (``call_role=narration``) → optional- ``_progress`` messages (``send_progress`` channel flag)+* mid-turn commentary rounds (``call_role=narration``) → live ``_progress``+ messages on a channel that carries them (``send_progress`` flag), and+ otherwise a prefix of the closing reply, so the reader gets the running+ commentary either way* ``TOOL_CALL`` → optional ``_tool_hint``"""@@ -500,19 +502,29 @@ class PartnerRunner:call_id = str(meta.get("call_id") or "")raw_text = "".join(round_buffers.pop(call_id, []))text = raw_text.strip()- if meta.get("answer_visible") is True:- if raw_text:- answer_visible_parts.append(raw_text)- if call_id in streamed_rounds:- ended_rounds.add(call_id)- await self._publish_stream_end(msg, turn_id, call_id)- continueif call_id in streamed_rounds:# Already streamed live — freeze the segment.ended_rounds.add(call_id)await self._publish_stream_end(msg, turn_id, call_id)- elif is_im and send_progress and text:+ elif meta.get("answer_visible") is False:+ # A capability retracted this round; it was+ # never the reader's to see.+ pass+ elif not is_im:+ # The web surface renders each round itself,+ # in place. Folding the text into the reply+ # as well would show it twice.+ pass+ elif send_progress and text:+ # This channel carries commentary live, so+ # the reader already has it and the closing+ # reply must not repeat it.await self._publish_hint(msg, text, tool_hint=False)+ elif raw_text:+ # Nothing carried it live. Keep it for the+ # closing reply so the reader still gets the+ # running commentary, in the order written.+ answer_visible_parts.append(raw_text)elif event.type == StreamEventType.RESULT and event.source == "chat":final_text = str(meta.get("response") or "")diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.pyindex 5bdf7a523..3669ae1b5 100644--- a/deeptutor/services/session/_turn_runtime_shared.py+++ b/deeptutor/services/session/_turn_runtime_shared.py@@ -29,9 +29,10 @@ MemoryReference = Literal["recent", "profile", "scope", "preferences", "summary"# Content call_kinds that make up the persisted answer. The chat agent loop-# streams every round's text as ``content`` with ``agent_loop_round``; the-# finish round (and forced-finish) are the answer, narration rounds are-# filtered back out via their ``call_role`` marker (see _narration_marker_call_id).+# streams every round's text as ``content`` with ``agent_loop_round``, and all+# of it is the answer — the commentary a round wrote before calling a tool+# included. Only a round a capability retracted is filtered back out (see+# _retracted_round_call_id)._ANSWER_CONTENT_CALL_KINDS = frozenset({"llm_final_response", "agent_loop_round"})_FINAL_TURN_STATUSES = frozenset({"completed", "failed", "cancelled"})@@ -84,21 +85,20 @@ def _resolve_turn_outcome(return status, error-def _narration_marker_call_id(event: StreamEvent) -> str | None:- """call_id of a chat-loop round that resolved as narration (a short- preamble streamed alongside a tool call). Its text belongs to the trace,- not the persisted answer, so it is excluded when assembling content.+def _retracted_round_call_id(event: StreamEvent) -> str | None:+ """call_id of a chat-loop round whose prose was taken back out of the answer.- A round may explicitly keep learner-facing prose surrounding a call via- ``answer_visible`` (for example DSML or mastery tutoring); that narrow- exception remains part of the persisted answer.+ Commentary a round wrote before calling a tool is answer content — the+ reader was shown it as the work happened, and the persisted answer keeps it+ so a reloaded turn reads the way it did live. The single exception is a+ round a capability's finish guard rejected, which republishes its marker+ with ``answer_visible: False``; that text belongs to the trace only."""metadata = event.metadata or {}if (metadata.get("trace_kind") == "call_status"and metadata.get("call_state") == "complete"- and metadata.get("call_role") == "narration"- and metadata.get("answer_visible") is not True+ and metadata.get("answer_visible") is False):call_id = metadata.get("call_id")return str(call_id) if call_id else None@@ -107,14 +107,14 @@ def _narration_marker_call_id(event: StreamEvent) -> str | None:def _assemble_persisted_answer(content_segments: Sequence[tuple[str | None, str]],- narration_call_ids: set[str],+ retracted_call_ids: set[str],) -> str:- """Replay visible content bytes, excluding trace-only narration rounds."""+ """Replay visible content bytes, excluding rounds a capability retracted."""return clean_thinking_tags("".join(textfor call_id, text in content_segments- if not (call_id and call_id in narration_call_ids)+ if not (call_id and call_id in retracted_call_ids)))@@ -263,13 +263,29 @@ def _repair_chinese_emphasis_for_persistence(content: str, language: str) -> str)-def _stamp_ask_user_content_offset(+def _stamp_content_offset(payload_event: dict[str, Any],assistant_content: str,) -> None:- """Attach the replay boundary to a persisted ask_user resolution event."""+ """Attach the replay boundary to an event the answer must be laid out around.++ A settled turn is reloaded from an event *preview* that carries no+ ``content`` events (see the web client's ``compactTracePreview``), so the+ body has to be rebuilt from the persisted answer string. Without a mark+ saying how much of that answer had been written when a row appeared, every+ tool call and card would pile up at one end and the reload would not+ resemble what the reader watched.++ Two kinds of event carry the mark: a resolved ``ask_user`` card, and the+ start of a tool call. Both are rendered between runs of answer text.+ """metadata = payload_event.get("metadata")- if isinstance(metadata, dict) and metadata.get("ask_user_resolved"):+ if not isinstance(metadata, dict):+ return+ anchors_layout = bool(metadata.get("ask_user_resolved")) or (+ payload_event.get("type") == StreamEventType.TOOL_CALL.value+ )+ if anchors_layout:metadata.setdefault("assistant_content_offset", len(assistant_content))diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 3cef6a508..31cfbe091 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -34,7 +34,6 @@ from .._turn_runtime_shared import (_format_selection_tutor_context,_mastery_action_context,_mastery_path_id,- _narration_marker_call_id,_partner_group_references,_reading_action_context,_reading_material_id,@@ -46,8 +45,9 @@ from .._turn_runtime_shared import (_request_snapshot_metadata,_resolve_selection_tutor_context,_resolve_turn_outcome,+ _retracted_round_call_id,_should_capture_assistant_content,- _stamp_ask_user_content_offset,+ _stamp_content_offset,_timed_media_id,_timed_media_viewport,_topic_material_manifest,@@ -146,18 +146,19 @@ class TurnExecutor:assistant_events: list[dict[str, Any]] = []assistant_content = ""provider_response_state: dict[str, Any] | None = None- # Per-round content segments + narration call_ids: a chat-loop round's- # text is captured live but a round that resolves as narration is- # dropped from the persisted answer (mirrors the frontend bubble).+ # Per-round content segments + retracted call_ids: every chat-loop+ # round's text is captured live and kept, commentary written before a+ # tool call included. Only a round a capability retracted is dropped+ # from the persisted answer (mirrors the frontend bubble).content_segments: list[tuple[str | None, str]] = []- narration_call_ids: set[str] = set()+ retracted_call_ids: set[str] = set()def _persisted_answer() -> str:# clean_thinking_tags is a second line of defence: providers that# inline <think> in the content channel are split at streaming# time by the agent loop, but anything that slips through must# never be persisted as the user-facing answer.- return _assemble_persisted_answer(content_segments, narration_call_ids)+ return _assemble_persisted_answer(content_segments, retracted_call_ids)# Files the model generated this turn (exec artifacts),# persisted as assistant-message attachments so the UI shows openable@@ -854,17 +855,19 @@ class TurnExecutor:continuepayload_event = await self._publish_live_event(execution, event)if payload_event.get("type") not in {"done", "session"}:- # A card reply lives inside this assistant row. Persist- # the exact user-facing answer boundary so future context- # can replay assistant -> user -> assistant in order.- _stamp_ask_user_content_offset(payload_event, _persisted_answer())+ # Cards and tool calls render between runs of answer+ # text. Persist the exact boundary each one sat at so a+ # reloaded turn lays the answer out the way it streamed,+ # and so future context can replay assistant -> user ->+ # assistant in order.+ _stamp_content_offset(payload_event, _persisted_answer())assistant_events.append(payload_event)if _should_capture_assistant_content(event):call_id = (event.metadata or {}).get("call_id")content_segments.append((str(call_id) if call_id else None, event.content))- narration_call_id = _narration_marker_call_id(event)- if narration_call_id:- narration_call_ids.add(narration_call_id)+ retracted_call_id = _retracted_round_call_id(event)+ if retracted_call_id:+ retracted_call_ids.add(retracted_call_id)for attachment in artifact_attachments(event):if attachment["url"] not in seen_artifact_urls:seen_artifact_urls.add(attachment["url"])@@ -906,8 +909,8 @@ class TurnExecutor:# already unwinding and must not start new blocking work.await fill_preview_text(generated_attachments)- # The persisted answer is the captured content minus any narration- # rounds (their text stayed in the trace, never the answer). Apply+ # The persisted answer is the captured content minus any round a+ # capability retracted (that text stayed in the trace). Apply# the CJK Markdown repair only after every streamed segment has# arrived, so no incomplete response is ever rewritten.assistant_content = _repair_chinese_emphasis_for_persistence(diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex 38048cc04..99868f865 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -195,8 +195,9 @@ def _answer_text(events: list[StreamEvent]) -> str:"""The reply a reader is left with, by the same rule the client applies.Mirrors ``recomputeAnswerContent`` in ``web/lib/stream.ts``: append the- content of answer-bearing rounds, then take back out any round whose- completion marker resolved as ``narration``.+ content of every answer-bearing round, then take back out any round whose+ completion marker retracted it (``answer_visible: False``). Commentary a+ round wrote before calling a tool is kept — the reader watched it arrive.Rounds stream optimistically, so text that a capability's finish guardrejects *is* briefly on the wire and then withdrawn. Asserting on this@@ -204,14 +205,13 @@ def _answer_text(events: list[StreamEvent]) -> str:actually matters — what the reader ends up holding — instead of whether arejected round was buffered, which is an implementation choice."""- narration = {+ retracted = {str(event.metadata.get("call_id"))for event in eventsif event.type == StreamEventType.PROGRESSand event.metadata.get("trace_kind") == "call_status"and event.metadata.get("call_state") == "complete"- and event.metadata.get("call_role") == "narration"- and event.metadata.get("answer_visible") is not True+ and event.metadata.get("answer_visible") is Falseand event.metadata.get("call_id")}parts: list[str] = []@@ -223,7 +223,7 @@ def _answer_text(events: list[StreamEvent]) -> str:if call_id:if metadata.get("call_kind") not in ANSWER_BEARING_CALL_KINDS:continue- if str(call_id) in narration:+ if str(call_id) in retracted:continueparts.append(event.content)return "".join(parts)@@ -624,7 +624,11 @@ async def test_tool_round_then_finish(monkeypatch: pytest.MonkeyPatch) -> None:result = _result(events)assert result.metadata["tool_steps"] == 1assert result.metadata["rounds"] == 2- # Only the finish round's text is the persisted answer.+ # The reader keeps BOTH: the commentary that introduced the search and the+ # closing answer, in the order they were written.+ assert _answer_text(events) == "Searching.Found what was needed."+ # RESULT still reports the closing answer alone — it is what an SDK caller+ # or a title generator asked for, not the running commentary.assert result.metadata["response"] == "Found what was needed."diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.pyindex c2b340001..33a3c15f6 100644--- a/tests/services/partners/test_partner_runtime.py+++ b/tests/services/partners/test_partner_runtime.py@@ -36,6 +36,11 @@ def _msg(content: str = "hello", channel: str = "telegram") -> InboundMessage:return InboundMessage(channel=channel, sender_id="42", chat_id="42", content=content)+def _muted_progress_config() -> PartnerConfig:+ """A partner whose telegram channel carries no live progress messages."""+ return PartnerConfig(name="Ada", channels={"telegram": {"sendProgress": False}})++class TestTurnExecution:@pytest.mark.asyncio@pytest.mark.parametrize("channel", ["weixin", "telegram"])@@ -177,7 +182,14 @@ class TestTurnExecution:assert progress.metadata["_tool_hint"] is False@pytest.mark.asyncio- async def test_answer_visible_narration_stays_in_reply(self, partners_root, fake_orchestrator):+ async def test_commentary_reaches_a_progress_channel_live_not_twice(+ self, partners_root, fake_orchestrator+ ):+ """Commentary is the reader's either way — once, by the fastest route.++ A channel that carries progress shows each round as it lands, so the+ closing reply must not repeat it.+ """fake_orchestrator.script = answer_visible_narration("c1", "Great job on that answer.") + finish("Choose the next topic.")@@ -185,6 +197,23 @@ class TestTurnExecution:final = await runner.process_message(_msg())+ progress = await runner.bus.outbound.get()+ assert progress.content == "Great job on that answer."+ assert progress.metadata["_progress"] is True+ assert final == "Choose the next topic."++ @pytest.mark.asyncio+ async def test_commentary_rides_the_reply_when_no_channel_carries_it(+ self, partners_root, fake_orchestrator+ ):+ """With progress muted, the reply is the only route left — so it carries it."""+ fake_orchestrator.script = answer_visible_narration(+ "c1", "Great job on that answer."+ ) + finish("Choose the next topic.")+ runner = _runner(partners_root, _muted_progress_config())++ final = await runner.process_message(_msg())+assert final == "Great job on that answer.\n\nChoose the next topic."assert runner.bus.outbound.empty()@@ -208,7 +237,7 @@ class TestTurnExecution:metadata={"response": "Part one. Part two."},),]- runner = _runner(partners_root)+ runner = _runner(partners_root, _muted_progress_config())final = await runner.process_message(_msg())diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.pyindex a1e6a4a8d..3d03d7162 100644--- a/tests/services/session/test_turn_runtime.py+++ b/tests/services/session/test_turn_runtime.py@@ -14,11 +14,11 @@ from deeptutor.services.session.turn_runtime import (_extract_selection_tutor_context,_format_followup_question_context,_format_selection_tutor_context,- _narration_marker_call_id,_repair_chinese_emphasis_for_persistence,_resolve_selection_tutor_context,+ _retracted_round_call_id,_should_capture_assistant_content,- _stamp_ask_user_content_offset,+ _stamp_content_offset,)# ---------------------------------------------------------------------------@@ -67,55 +67,61 @@ class TestShouldCaptureAssistantContent:assert _should_capture_assistant_content(event) is False-class TestNarrationMarkerCallId:- def test_narration_marker_returns_call_id(self) -> None:- event = StreamEvent(+class TestRetractedRoundCallId:+ @staticmethod+ def _marker(**metadata: object) -> StreamEvent:+ return StreamEvent(type=StreamEventType.PROGRESS,metadata={- "call_id": "round-1","trace_kind": "call_status","call_state": "complete",- "call_role": "narration",+ **metadata,},)- assert _narration_marker_call_id(event) == "round-1"- def test_finish_marker_is_not_narration(self) -> None:- event = StreamEvent(- type=StreamEventType.PROGRESS,- metadata={- "call_id": "round-2",- "trace_kind": "call_status",- "call_state": "complete",- "call_role": "finish",- },+ def test_retracted_round_returns_call_id(self) -> None:+ event = self._marker(+ call_id="round-rejected",+ call_role="narration",+ answer_visible=False,)- assert _narration_marker_call_id(event) is None-- def test_dsml_clean_content_is_kept_in_persisted_answer(self) -> None:- event = StreamEvent(- type=StreamEventType.PROGRESS,- metadata={- "call_id": "round-dsml",- "trace_kind": "call_status",- "call_state": "complete",- "call_role": "narration",- "answer_visible": True,- },+ assert _retracted_round_call_id(event) == "round-rejected"++ def test_commentary_before_a_tool_call_stays_in_the_answer(self) -> None:+ """The paradigm: a round that called tools still wrote answer text.++ The reader watched that sentence arrive above the tool's own row, so+ reloading the turn must show it in the same place. Only an explicit+ retraction takes text back out of the answer.+ """+ event = self._marker(+ call_id="search-round",+ call_role="narration",+ answer_visible=True,)- assert _narration_marker_call_id(event) is None+ assert _retracted_round_call_id(event) is None- def test_running_status_is_not_narration(self) -> None:- event = StreamEvent(- type=StreamEventType.PROGRESS,- metadata={- "call_id": "round-1",- "trace_kind": "call_status",- "call_state": "running",- "call_role": "narration",- },+ def test_finish_marker_is_not_retracted(self) -> None:+ event = self._marker(+ call_id="round-2",+ call_role="finish",+ answer_visible=True,+ )+ assert _retracted_round_call_id(event) is None++ def test_running_status_is_not_retracted(self) -> None:+ event = self._marker(+ call_id="round-1",+ call_state="running",+ call_role="narration",+ answer_visible=False,)- assert _narration_marker_call_id(event) is None+ assert _retracted_round_call_id(event) is None++ def test_legacy_marker_without_the_flag_is_not_retracted(self) -> None:+ """Sessions recorded before the flag existed keep their text."""+ event = self._marker(call_id="round-old", call_role="narration")+ assert _retracted_round_call_id(event) is Noneclass TestAssemblePersistedAnswer:@@ -154,23 +160,53 @@ class TestAssemblePersistedAnswer:assert _assemble_persisted_answer(segments, set()) == "Part one. Part two."- def test_trace_only_narration_is_still_excluded(self) -> None:+ def test_commentary_rounds_are_part_of_the_persisted_answer(self) -> None:segments = [- ("search-round", "Searching."),+ ("search-round", "Checking the syllabus first. "),("finish-round", "Answer."),]- assert _assemble_persisted_answer(segments, {"search-round"}) == "Answer."+ assert _assemble_persisted_answer(segments, set()) == "Checking the syllabus first. Answer."++ def test_a_retracted_round_is_excluded(self) -> None:+ segments = [+ ("rejected-round", "A question I never actually posed."),+ ("finish-round", "Answer."),+ ]++ assert _assemble_persisted_answer(segments, {"rejected-round"}) == "Answer."def test_ask_user_resolution_records_the_current_answer_boundary() -> None:event = {"type": "progress", "metadata": {"ask_user_resolved": True}}- _stamp_ask_user_content_offset(event, "Visible teaching before the card.")+ _stamp_content_offset(event, "Visible teaching before the card.")assert event["metadata"]["assistant_content_offset"] == 33+def test_tool_call_records_the_boundary_it_was_rendered_at() -> None:+ """A reloaded turn lays the answer out around its tool rows by this mark.++ The event preview a settled turn is restored from carries no content+ events, so without the boundary every tool row would collapse to one end+ of the answer instead of sitting where the reader watched it run.+ """+ event = {"type": "tool_call", "metadata": {"call_id": "c1"}}++ _stamp_content_offset(event, "Checking the syllabus first.")++ assert event["metadata"]["assistant_content_offset"] == 28+++def test_plain_progress_event_gets_no_boundary() -> None:+ event = {"type": "progress", "metadata": {"trace_kind": "call_status"}}++ _stamp_content_offset(event, "Some answer text.")++ assert "assistant_content_offset" not in event["metadata"]++# ---------------------------------------------------------------------------# _clip_text# ---------------------------------------------------------------------------diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsxindex 8938c8102..038520707 100644--- a/web/components/chat/home/AskUserOptions.tsx+++ b/web/components/chat/home/AskUserOptions.tsx@@ -13,9 +13,10 @@ import {type MasteryQuestion,} from "@/lib/mastery-question";import {- collectNarrationCallIds,+ collectRetractedCallIds,shouldAppendEventContent,} from "@/lib/stream";+import { hasRenderableCallTrace } from "@/features/chat/trace/selectors";import type { StreamEvent } from "@/features/chat/model/protocol";/**@@ -289,12 +290,13 @@ export type MessageSegment =key: string;}/**- * The trace of the round(s) that ran AFTER a card — the reasoning the- * resumed turn produced once the user answered. It renders below the- * card it followed, because the message's activity block is pinned to- * the top: everything emitted after a submit used to land back up- * there, above content the user had already scrolled past, so the- * turn looked frozen after they picked an option.+ * One run of work — tool calls, their results, the reasoning around them —+ * rendered exactly where it happened, between the text that introduced it+ * and the text that followed. This is what makes the message read like a+ * terminal agent: say what you are about to do, do it, say what came of it.+ *+ * A region opens as soon as trace events arrive after some answer text, and+ * closes when the next text run starts.*/| { kind: "trace"; events: StreamEvent[]; key: string };@@ -331,14 +333,15 @@ export function extractMessageSegments(let anonymousDraftIdx: number | null = null;let pendingTextIdx: number | null = null;let pendingTraceIdx: number | null = null;- let sawAskUser = false;let seq = 0;- // Narration rounds (chat-loop preamble alongside a tool call) stream as- // content but belong in the trace, not the answer — keep them out of the- // inline text segments too.- const narrationCallIds = collectNarrationCallIds(events);+ // A round a capability rejected was streamed and then taken back: its text+ // is trace material, never answer text. Ordinary commentary stays.+ const retractedCallIds = collectRetractedCallIds(events);const ensureTextSegment = () => {+ // Text resuming closes the run of work above it, so the next tool call+ // opens a region of its own below this paragraph rather than joining the+ // one the reader has already scrolled past.pendingTraceIdx = null;if (pendingTextIdx === null) {pendingTextIdx = segments.length;@@ -347,21 +350,44 @@ export function extractMessageSegments(return pendingTextIdx;};- /** Collect one post-card trace event; a no-op before the first card. */+ /** Collect one trace event into the region currently open below the text. */const appendTraceEvent = (event: StreamEvent) => {- if (!sawAskUser) return;+ // Where this event sat in the answer, when it recorded one. A live turn+ // records none — its text is on the wire and separates the regions by+ // itself. A reloaded one has no text events at all, so this mark is the+ // only thing that still says which paragraph a row belonged under.+ const raw = ((event.metadata ?? {}) as Record<string, unknown>)+ .assistant_content_offset;+ const offset = typeof raw === "number" ? raw : null;+ if (pendingTraceIdx !== null && offset !== null) {+ const open = answerOffsets.get(pendingTraceIdx);+ // Two calls made at different points in the answer are two runs of work+ // with prose between them, even though the preview dropped that prose.+ // Without this they collapsed into one block and the reloaded turn+ // stopped resembling the one the reader had watched.+ if (open !== undefined && open !== offset) pendingTraceIdx = null;+ }if (pendingTraceIdx === null) {+ // Work starting closes the paragraph above it, so what the next round+ // writes lands in a new run *below* this region rather than being+ // appended to text the reader has already passed.+ pendingTextIdx = null;pendingTraceIdx = segments.length;segments.push({ kind: "trace", events: [], key: `r${seq++}` });}const seg = segments[pendingTraceIdx];if (seg.kind === "trace") seg.events.push(event);+ // Read from the first event in the region that recorded a mark — a region+ // often opens on a status marker, which carries none.+ if (offset !== null && !answerOffsets.has(pendingTraceIdx)) {+ answerOffsets.set(pendingTraceIdx, offset);+ }};for (const event of events) {if (shouldAppendEventContent(event)) {const callId = ((event.metadata ?? {}) as { call_id?: string }).call_id;- if (callId && narrationCallIds.has(callId)) {+ if (callId && retractedCallIds.has(callId)) {appendTraceEvent(event);continue;}@@ -379,12 +405,10 @@ export function extractMessageSegments(const cardKey = `mastery:${posed.questionId}`;if (seenAskUserCards.has(cardKey)) continue;seenAskUserCards.add(cardKey);- // Same bookkeeping as a card below: close the text run so the round's- // remaining prose starts fresh underneath, and open the post-card- // trace region.+ // Same bookkeeping as a card below: close the text and trace runs so+ // the round's remaining prose starts fresh underneath the card.pendingTextIdx = null;pendingTraceIdx = null;- sawAskUser = true;const masteryIdx = segments.length;segments.push({kind: "mastery_question",@@ -422,7 +446,6 @@ export function extractMessageSegments(// emits starts fresh segments below this card.pendingTextIdx = null;pendingTraceIdx = null;- sawAskUser = true;// This call was previewed while it streamed: promote that card rather// than appending a second one. Keeping the segment's key keeps the// rendered card mounted, so the picked-option state and scroll@@ -483,12 +506,9 @@ export function extractMessageSegments(continue;}pendingTextIdx = null;- // Deliberately *not* setting ``sawAskUser``: the trace events that- // belong to this very call are still ahead of us in the stream, and- // ``leadingTraceEvents`` renders them above the bubble. Opening the- // post-card trace run here showed them a second time *below* the card- // — so the call's own "asking you" step read as happening after the- // question it produced. The dispatched result below owns that switch.+ // Deliberately leaving the trace region open: the events that belong to+ // this very call are still ahead of us in the stream, and they read as+ // the work that produced the question — above it, not below.const idx = segments.length;segments.push({kind: "ask_user",@@ -570,48 +590,62 @@ export function extractMessageSegments(appendTraceEvent(event);}- // The turn is over: a preview still marked streaming never became a- // dispatched call (a duplicate parallel ask_user, a guard that rejected the- // arguments), so there is nothing behind it to answer. Dropping it shifts- // the segment indices ``answerOffsets`` is keyed by, so both are rebuilt- // together.- let kept = segments;- let keptOffsets = answerOffsets;- if (!streaming && segments.some((s) => s.kind === "ask_user" && s.data.streaming)) {- kept = [];- keptOffsets = new Map<number, number>();- segments.forEach((segment, idx) => {- if (segment.kind === "ask_user" && segment.data.streaming) return;- const offset = answerOffsets.get(idx);- if (offset !== undefined) keptOffsets.set(kept.length, offset);- kept.push(segment);- });- }+ // Two kinds of segment are dropped before the body is laid out around what+ // remains, because a segment removed afterwards would leave the text it had+ // split sitting in two paragraphs with nothing between them:+ //+ // - a region holding nothing worth a row. Regions open on a round's status+ // marker, which on its own is bookkeeping, not something to show;+ // - once the turn has settled, a preview still marked streaming. It never+ // became a dispatched call (a duplicate parallel ask_user, a guard that+ // rejected the arguments), so there is nothing behind it to answer.+ //+ // Dropping either shifts the indices ``answerOffsets`` is keyed by, so the+ // offsets are rebuilt alongside.+ const kept: MessageSegment[] = [];+ const keptOffsets = new Map<number, number>();+ segments.forEach((segment, idx) => {+ if (segment.kind === "trace" && !hasRenderableCallTrace(segment.events)) {+ return;+ }+ if (!streaming && segment.kind === "ask_user" && segment.data.streaming) {+ return;+ }+ const offset = answerOffsets.get(idx);+ if (offset !== undefined) keptOffsets.set(kept.length, offset);+ kept.push(segment);+ });+ // A live turn carries its own text on the wire. A settled one is restored+ // from an event preview that drops `content` entirely, so its body has to be+ // rebuilt from the persisted answer and laid out around the rows.const textFromEvents = kept.some((s) => s.kind === "text" && s.text.length > 0,);const laidOut =- !textFromEvents && sawAskUser && answerContent+ !textFromEvents && answerContent? layOutAnswerContent(kept, answerContent, keptOffsets): kept;- // Drop empty trailing/leading text segments so the renderer doesn't- // emit blank ``<AssistantResponse>`` nodes, and trace regions whose- // events all turned out to be unrenderable.- return laidOut.filter((s) =>- s.kind === "text"- ? s.text.length > 0- : s.kind !== "trace" || s.events.length > 0,- );+ // Empty text segments last: the layout above creates them, and a blank one+ // would render as an empty ``<AssistantResponse>``.+ return laidOut.filter((s) => s.kind !== "text" || s.text.length > 0);}/**- * Lay the persisted answer out around the cards of a settled message.+ * Lay the persisted answer out around the rows of a settled message.*- * Each card takes the text between the previous cut and its own offset; the- * text past the last cut trails after everything. Offsets are read in order- * and never move backwards, so a stray value cannot reorder the body.+ * A reloaded turn has no `content` events — the event preview drops them — so+ * the body is one stored string and every card and run of tool work has to be+ * put back where it happened. Each row takes the text between the previous cut+ * and its own recorded offset; the text past the last cut trails after+ * everything. Offsets are read in order and never move backwards, so a stray+ * value cannot reorder the body.+ *+ * A row with no recorded offset is placed differently by kind. A card is a+ * question the reader was asked, so it belongs below everything written before+ * it. A run of tool work is not worth pushing the whole answer above, so it+ * simply keeps its position in the sequence.*/function layOutAnswerContent(segments: MessageSegment[],@@ -632,13 +666,11 @@ function layOutAnswerContent(};segments.forEach((segment, idx) => {if (segment.kind === "text") return;- if (segment.kind === "ask_user" || segment.kind === "mastery_question") {- const offset = answerOffsets.get(idx);- pushText(- offset === undefined- ? answerContent.length- : snapToLineStart(answerContent, Math.max(cursor, offset)),- );+ const offset = answerOffsets.get(idx);+ if (offset !== undefined) {+ pushText(snapToLineStart(answerContent, Math.max(cursor, offset)));+ } else if (segment.kind !== "trace") {+ pushText(answerContent.length);}laidOut.push(segment);});@@ -680,18 +712,46 @@ function snapToLineStart(content: string, offset: number): number {return best;}+/**+ * Whether this event is what a card is built from, rather than trace material.+ *+ * A card renders in the message body, so the row its own events would draw in+ * the activity block is the same step shown twice — as a question the reader+ * can answer, and as a bare "tool call" line above the text that introduced+ * it.+ */+function producesCard(event: StreamEvent): boolean {+ const meta = (event.metadata ?? {}) as Record<string, unknown>;+ if (event.type === "progress") {+ return Boolean(meta.ask_user_resolved) || readAskUserDraft(event) !== null;+ }+ if (event.type !== "tool_result") return false;+ if (readPosedQuestion(event)) return true;+ const toolMetadata = meta.tool_metadata;+ const askUser =+ toolMetadata && typeof toolMetadata === "object"+ ? (toolMetadata as Record<string, unknown>).ask_user+ : null;+ return normaliseAskUserPayload(askUser) !== null;+}+/*** The events whose trace rows still belong to the message's top activity- * block: everything the segments did not claim for a post-card region.+ * block — which, now that every row renders inline where the work happened,+ * should be nothing at all. Kept as the honest statement of that: anything it+ * returns is a step the body did not account for.+ ** Pass it as ``AssistantActivity``'s ``traceEvents`` (or to a bare- * ``TraceFlow``) so a resumed round's reasoning is not shown twice — once- * where the user is looking, and once back above the card.+ * ``TraceFlow``) so no step is shown twice.*/export function leadingTraceEvents(events: StreamEvent[] | undefined,segments: MessageSegment[],): StreamEvent[] {const claimed = new Set<StreamEvent>();+ for (const event of events ?? []) {+ if (producesCard(event)) claimed.add(event);+ }for (const segment of segments) {if (segment.kind !== "trace") continue;for (const event of segment.events) claimed.add(event);diff --git a/web/components/partners/PartnerChat.tsx b/web/components/partners/PartnerChat.tsxindex 0fbd6a205..86170ee70 100644--- a/web/components/partners/PartnerChat.tsx+++ b/web/components/partners/PartnerChat.tsx@@ -8,7 +8,7 @@* `StreamEvent` shape), so this reuses product chat's rendering wholesale:* `AssistantActivity` shows the live thinking/tool trace (open while* working, collapsed once answered) and the answer text is recomputed with- * the same narration-demotion rules as chat.+ * the same retraction rules as chat.*/import { useCallback, useEffect, useRef, useState } from "react";@@ -32,7 +32,7 @@ import type { ExportableMessage } from "@/lib/chat-export";import type { StreamEvent } from "@/features/chat/model/protocol";import { docIconFor, formatBytes, isSvgFilename } from "@/lib/doc-attachments";import {- isNarrationMarker,+ isRetractionMarker,recomputeAnswerContent,shouldAppendEventContent,} from "@/lib/stream";@@ -409,7 +409,7 @@ export default function PartnerChat({current.events.push(data.event);if (shouldAppendEventContent(data.event)) {current.content += data.event.content;- } else if (isNarrationMarker(data.event)) {+ } else if (isRetractionMarker(data.event)) {current.content = recomputeAnswerContent(current.events);}externalLive.set(activityId, current);@@ -468,9 +468,9 @@ export default function PartnerChat({live.events.push(event);if (shouldAppendEventContent(event)) {live.content += event.content;- } else if (isNarrationMarker(event)) {- // A round resolved as narration — its streamed text belongs to- // the trace, not the answer. Same demotion rule as product chat.+ } else if (isRetractionMarker(event)) {+ // A capability took this round's text back out of the answer.+ // Same retraction rule as product chat.live.content = recomputeAnswerContent(live.events);}publish();diff --git a/web/components/partners/group/useGroupSession.ts b/web/components/partners/group/useGroupSession.tsindex 7a008c10c..4bec9e772 100644--- a/web/components/partners/group/useGroupSession.ts+++ b/web/components/partners/group/useGroupSession.ts@@ -24,7 +24,7 @@ import {} from "@/lib/partner-groups-api";import { ReconnectingWebSocket } from "@/lib/reconnecting-websocket";import {- isNarrationMarker,+ isRetractionMarker,recomputeAnswerContent,shouldAppendEventContent,} from "@/lib/stream";@@ -95,14 +95,14 @@ type GroupFrame =/*** Grow a seat's visible body from one trace event.*- * Answer text and narration arrive on the same ``content`` channel; a round is- * only revealed as narration when its marker lands, so the body is appended- * optimistically and recomputed when that happens. This is the same rule the- * product chat uses (``lib/stream``), so a Partner's body reads identically in- * both surfaces.+ * Every round's text is body text, commentary written before a tool call+ * included. A capability can retract a round it rejected, and that is only+ * known when the round's marker lands — so the body is appended optimistically+ * and recomputed then. This is the same rule the product chat uses+ * (``lib/stream``), so a Partner's body reads identically in both surfaces.*/function growBody(seat: Seat, event: StreamEvent): string {- if (isNarrationMarker(event)) {+ if (isRetractionMarker(event)) {return recomputeAnswerContent([...seat.events, event]);}return shouldAppendEventContent(event)diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex 9ac681978..8cc446146 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -56,7 +56,7 @@ import {import { nextOptimisticId, resolvePersistedMessage } from "@/lib/optimistic-id";import { reconcileTurnIds } from "@/lib/turn-reconcile";import {- isNarrationMarker,+ isRetractionMarker,recomputeAnswerContent,shouldAppendEventContent,} from "@/lib/stream";@@ -745,10 +745,10 @@ function reducer(state: ProviderState, action: Action): ProviderState {const language = session.language;let rawContent = last?.rawContent ?? last?.content ?? "";let content = last?.content ?? "";- if (isNarrationMarker(action.event)) {- // A round just resolved as narration (preamble before a tool call):- // drop its already-streamed text from the answer — it stays in the- // trace. Recompute from immutable event content, never from display text.+ if (isRetractionMarker(action.event)) {+ // A capability rejected this round after it had already streamed:+ // drop its text from the answer — it stays in the trace. Recompute+ // from immutable event content, never from display text.rawContent = recomputeAnswerContent(events);content = repairChineseEmphasis(rawContent, language);} else if (shouldAppendEventContent(action.event)) {diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex 850cb7cf4..f96936de8 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -574,40 +574,44 @@ export const AssistantMessage = memo(function AssistantMessage({[courseHandoffs.length, isStreaming, msg.content],);- // Interleaved segments for the default chat surface — text emitted- // before the card renders above it; text emitted by the round that- // follows renders below. Only walked when this message will actually- // render through the default branch (the research / quiz / animator /- // visualize branches have their own layout and pin the card elsewhere).- const useInlineCardSegments =+ // Interleaved segments for the default chat surface: the message is laid+ // out in the order it was written — what DeepTutor said it was about to do,+ // the work it then did, what it found, and so on down to the closing answer.+ // Only walked when this message will actually render through the default+ // branch (the research / quiz / animator / visualize branches have their own+ // layout and pin their cards elsewhere).+ const useInlineSegments =!outlinePreview &&!mathAnimatorResult &&!visualizeResult &&!(quizQuestions && quizQuestions.length > 0);const messageSegments = useMemo(() =>- useInlineCardSegments+ useInlineSegments? extractMessageSegments(msg.events, msg.content, {streaming: isStreaming,}): [],- [useInlineCardSegments, msg.events, msg.content, isStreaming],+ [useInlineSegments, msg.events, msg.content, isStreaming],);// Either card kind: a clarifying ask_user, or a posed mastery question.- // Both interleave with the prose, and a message that has one lays itself- // out from the segments rather than from a single body string.const hasInlineCards =- useInlineCardSegments &&+ useInlineSegments &&messageSegments.some((seg) => seg.kind === "ask_user" || seg.kind === "mastery_question",);- // The activity block is pinned to the top of the message, so it can only- // show the rounds that ran BEFORE the first card. What the resumed rounds- // reason about renders below the card they answer, in stream order.+ // Lay the body out from the segments whenever there is more to place than+ // one run of prose. A message with nothing but text gets the plain body+ // branch below, which is the same thing with less machinery.+ const useSegmentLayout =+ useInlineSegments && messageSegments.some((seg) => seg.kind !== "text");+ // Every trace row now renders inline, where the work happened. The header+ // block keeps its status line and nothing else — leaving rows up there too+ // would show each step twice.const headerTraceEvents = useMemo(() =>- hasInlineCards ? leadingTraceEvents(events, messageSegments) : undefined,- [hasInlineCards, messageSegments, events],+ useSegmentLayout ? leadingTraceEvents(events, messageSegments) : undefined,+ [useSegmentLayout, messageSegments, events],);const researchInProgress =@@ -721,11 +725,12 @@ export const AssistantMessage = memo(function AssistantMessage({language={language}/></>- ) : hasInlineCards ? (- // Default chat surface with one or more cards: render text and- // cards in the exact order they were streamed, so the narration- // that introduced a card sits above it and whatever the next round- // said sits below.+ ) : useSegmentLayout ? (+ // Default chat surface: render text, tool work and cards in the exact+ // order they were streamed. The sentence that introduced a step sits+ // above it and whatever the next round said sits below, so the message+ // reads as a running account rather than an answer with its working+ // hidden in a block at the top.messageSegments.map((seg) =>seg.kind === "text" ? (<AssistantResponse@@ -738,8 +743,8 @@ export const AssistantMessage = memo(function AssistantMessage({events={events}/>) : seg.kind === "trace" ? (- // What DeepTutor worked out after the user answered — shown- // where they are looking, not back up in the header block.+ // One run of work, shown where it happened — between the text+ // that introduced it and the text that followed.<NestedTraceFlowkey={seg.key}events={seg.events}diff --git a/web/features/chat/trace/TracePresentation.tsx b/web/features/chat/trace/TracePresentation.tsxindex 69f2e2d16..10b3bef8c 100644--- a/web/features/chat/trace/TracePresentation.tsx+++ b/web/features/chat/trace/TracePresentation.tsx@@ -42,7 +42,7 @@ import {groupTraceEvents,hasRenderableCallTrace as selectHasRenderableCallTrace,isChatLoopAnswerContent,- isNarrationRound,+ isRetractedRound,isTracePending,selectTraceDisplayItems,} from "./selectors";@@ -446,17 +446,15 @@ function getTraceHeader(}// Chat-loop `content` (call_kind "agent_loop_round") is the model's-// user-facing text. Whether it belongs in the trace depends on the round:-// - a NARRATION round (the round ended with a tool call) → its text was-// the model's commentary before acting. It is stripped from the answer-// bubble, so it MUST surface in the trace.-// - a FINISH round (the round ended with no tool call) → its text IS the-// answer bubble; keep it out of the trace to avoid duplication.-// The differentiator is the round's own ``call_status`` marker (call_role).+// user-facing text, and it stays in the answer bubble — commentary written+// before a tool call included. So it is kept OUT of the trace by default, to+// avoid showing the same sentence twice. The one exception is a round a+// capability retracted: that text is no longer in the bubble, so the trace is+// the only place left for it.function getTraceText(events: StreamEvent[],eventTypes: Array<StreamEvent["type"]>,- // When the caller knows this group is a narration round, its+ // When the caller knows this group's text was retracted, its// ``agent_loop_round`` content is trace material and should NOT be// filtered out as answer-bubble text.includeChatLoopContent = false,@@ -781,7 +779,7 @@ function TraceRowBody({);const thoughtText = getTraceText(callEvents, ["thinking"]);const observationText = getTraceText(callEvents, ["observation"]);- // A chat round can emit BOTH reasoning (thinking) and narration commentary+ // A chat round can emit BOTH reasoning (thinking) and retracted commentary// (content) in a single call; both are trace material and render as// separate stacked blocks. Other pipelines keep the legacy "thought or// content" fallback so their rows are unchanged.@@ -789,7 +787,7 @@ function TraceRowBody({const contentText = getTraceText(callEvents,["content"],- isNarrationRound(callEvents),+ isRetractedRound(callEvents),);const bodyBlocks =role === "observe"@@ -954,7 +952,7 @@ function hasExpandableContent(const contentText = getTraceText(callEvents,["content"],- isNarrationRound(callEvents),+ isRetractedRound(callEvents),);const genericBodyText =role === "observe"@@ -1021,7 +1019,7 @@ function TraceRowItem({const isToolRow = kind === "tool_planning" || group === "tool_call";const isChatRound = kind === "agent_loop_round";const isRetrieve = role === "retrieve";- const narration = isNarrationRound(callEvents);+ const retracted = isRetractedRound(callEvents);// The model's own text-form deliberation — chat-loop reasoning/narration and// pipeline "Thought"/"Plan" rounds. Unlike a tool call (whose result is// secondary detail worth folding away), here the text IS the substance, so@@ -1058,7 +1056,7 @@ function TraceRowItem({| undefined;const thoughtText = getTraceText(callEvents, ["thinking"]).trim();- const contentText = getTraceText(callEvents, ["content"], narration).trim();+ const contentText = getTraceText(callEvents, ["content"], retracted).trim();// Resolve every row into a uniform { icon, headline, chip } triple so the// activity feed reads consistently across pipelines. Tool calls get a human@@ -1149,7 +1147,11 @@ function TraceRowItem({title={headline}detail={chip?.text ??- (isThinking && deliberation.length+ // The preview is what stands in for the text while the row is folded.+ // An open row already shows that text in full below, so repeating its+ // opening on the title line prints the same sentence twice — which is+ // what a short deliberation looks like the whole time it streams.+ (isThinking && deliberation.length && !open? plainPreview(deliberation[0]): undefined)}@@ -1340,9 +1342,9 @@ function detectStreamingMode(// question with the structured qa_pair in metadata — that's the signal// the quizzing phase is active.if (callKind === "agent_loop_round") {- // The chat loop streams user-facing text as `content` (a short- // narration before a tool call, or the finish answer): show- // "responding" while text is flowing; thinking keeps "exploring".+ // The chat loop streams user-facing text as `content` (commentary+ // before a tool call, or the closing answer): show "responding" while+ // text is flowing; thinking keeps "exploring".return event.type === "content" ? "responding" : "exploring";}if (callKind === "quiz_question_emitted") return "quizzing";@@ -1677,26 +1679,24 @@ function isChatLoopTurn(events: StreamEvent[]): boolean {}/**- * Whether the most recently *completed* round settled the turn: either a- * genuinely tool-less ``finish`` round, or a round the backend explicitly- * marked ``answer_visible`` — mastery's teaching-plus-status-check rounds, a- * DSML-fallback round, a token-truncated-but-visible round (see- * ``agent_loop.py``'s completion metadata) all combine tool calls with- * learner-facing text in the same round, so ``call_role`` never reaches- * ``"finish"`` for them even though the round is exactly what the trace- * should collapse for.+ * Whether the most recently *completed* round settled the turn — a tool-less+ * ``finish`` round, the one shape that ends the loop.** Looks at only the LATEST completed round, not "has one ever appeared" —* a token-truncated round is explicitly non-terminal (the loop keeps* writing), so once ITS OWN next round completes, that round's marker* supersedes this one and correctly reopens the trace if fresh tool calls* are still coming.+ *+ * ``answer_visible`` is deliberately not consulted: it says whether a round's+ * text belongs to the answer, which is true of nearly every round and says+ * nothing about whether the turn is over.*/function lastRoundSettledFinal(events: StreamEvent[]): boolean {for (let idx = events.length - 1; idx >= 0; idx -= 1) {const meta = getTraceMeta(events[idx]);if (meta.trace_kind === "call_status" && meta.call_state === "complete") {- return meta.call_role === "finish" || meta.answer_visible === true;+ return meta.call_role === "finish";}}return false;@@ -1711,10 +1711,10 @@ function isFinalAnswerPhase(if (lastRoundSettledFinal(events)) return true;const mode = detectStreamingMode(events, hasFinalContent, true);if (mode === "responding" || mode === "responded") {- // Chat's single loop streams narration text mid-loop, which also reads- // as "responding" — there only a settled round marker (above) settles- // the phase; trusting the mode would flap the trace shut on every- // narration line and open again on the next tool call.+ // Chat's single loop streams commentary mid-loop, which also reads as+ // "responding" — there only a settled round marker (above) settles the+ // phase; trusting the mode would flap the trace shut on every line of+ // commentary and open again on the next tool call.return !isChatLoopTurn(events);}return false;diff --git a/web/features/chat/trace/index.ts b/web/features/chat/trace/index.tsindex 97242eef8..49c7f3638 100644--- a/web/features/chat/trace/index.ts+++ b/web/features/chat/trace/index.ts@@ -16,7 +16,7 @@ export {getTraceRole,groupTraceEvents,hasRenderableCallTrace,- isNarrationRound,+ isRetractedRound,isTracePending,selectTraceDisplayItems,} from "./selectors";diff --git a/web/features/chat/trace/memory.ts b/web/features/chat/trace/memory.tsindex 8291128e7..ade9a3227 100644--- a/web/features/chat/trace/memory.ts+++ b/web/features/chat/trace/memory.ts@@ -1,6 +1,6 @@import type { StreamEvent } from "@/features/chat/model/protocol";import {- collectNarrationCallIds,+ collectRetractedCallIds,shouldAppendEventContent,} from "@/lib/stream";@@ -172,7 +172,7 @@ export function settleMessageTrace(events: StreamEvent[],turnId: string | null,): { events: StreamEvent[]; trace: MessageTraceMetadata } {- const narration = collectNarrationCallIds(events);+ const retracted = collectRetractedCallIds(events);let answerLength = 0;let lastSeq = 0;const stamped = events.map((event) => {@@ -180,7 +180,7 @@ export function settleMessageTrace(const meta = metadata(event);if (shouldAppendEventContent(event)) {const callId = typeof meta.call_id === "string" ? meta.call_id : "";- if (!callId || !narration.has(callId))+ if (!callId || !retracted.has(callId))answerLength += event.content.length;return event;}diff --git a/web/features/chat/trace/selectors.ts b/web/features/chat/trace/selectors.tsindex 04bd8fef5..ac20942e1 100644--- a/web/features/chat/trace/selectors.ts+++ b/web/features/chat/trace/selectors.ts@@ -118,20 +118,24 @@ export function isChatLoopAnswerContent(event: StreamEvent): boolean {);}-export function isNarrationRound(events: StreamEvent[]): boolean {+/**+ * Whether this group's own text was taken back out of the answer. Only then+ * is a chat-loop round's prose trace material — ordinary commentary stays in+ * the bubble where the reader watched it arrive.+ */+export function isRetractedRound(events: StreamEvent[]): boolean {return events.some((event) => {const meta = getTraceMeta(event);return (meta.trace_kind === "call_status" &&meta.call_state === "complete" &&- meta.call_role === "narration" &&- meta.answer_visible !== true+ meta.answer_visible === false);});}export function groupHasTraceSubstance(events: StreamEvent[]): boolean {- const narration = isNarrationRound(events);+ const retracted = isRetractedRound(events);return events.some((event) => {if (event.type === "tool_call" ||@@ -151,7 +155,7 @@ export function groupHasTraceSubstance(events: StreamEvent[]): boolean {}if (event.type === "content") {return (- (narration || !isChatLoopAnswerContent(event)) &&+ (retracted || !isChatLoopAnswerContent(event)) &&Boolean(event.content.trim()));}diff --git a/web/lib/stream.ts b/web/lib/stream.tsindex 2ee8ffb1a..9bb9a292d 100644--- a/web/lib/stream.ts+++ b/web/lib/stream.ts@@ -17,10 +17,10 @@ export function shouldAppendEventContent(event: StreamEvent): boolean {if (event.type !== "content") return false;const meta = eventMeta(event);if (!meta.call_id) return true;- // The chat agent loop streams every round's text as `content`. The- // tool-less finish round (and the forced-finish round) are the- // user-facing answer; trace-only narration rounds are filtered back out via- // their call_role marker (see collectNarrationCallIds).+ // The chat agent loop streams every round's text as `content`, and all of+ // it is the answer — the commentary a round wrote before calling a tool+ // included. Only a round the backend retracts is filtered back out (see+ // collectRetractedCallIds).return (meta.call_kind === "llm_final_response" ||meta.call_kind === "agent_loop_round"@@ -28,21 +28,22 @@ export function shouldAppendEventContent(event: StreamEvent): boolean {}/**- * call_ids whose round resolved as "narration" — a short preamble the chat- * loop streamed alongside a tool call. That text belongs to the trace, not- * the answer, so it is excluded once the round's call_status marker arrives.- * Interactive rounds can explicitly preserve learner-facing prose that- * surrounded a call with `answer_visible`.+ * call_ids whose round was taken back out of the answer.+ *+ * A round that called tools still wrote answer text: the reader watched that+ * sentence arrive above the tool's own row, so it stays where they saw it.+ * The one exception is a round a capability's finish guard rejected — the+ * backend republishes that round's marker with `answer_visible: false`, and+ * the text moves into the trace.*/-export function collectNarrationCallIds(events: StreamEvent[]): Set<string> {+export function collectRetractedCallIds(events: StreamEvent[]): Set<string> {const ids = new Set<string>();for (const event of events) {const meta = eventMeta(event);if (meta.trace_kind === "call_status" &&meta.call_state === "complete" &&- meta.call_role === "narration" &&- meta.answer_visible !== true &&+ meta.answer_visible === false &&meta.call_id) {ids.add(meta.call_id);@@ -51,29 +52,28 @@ export function collectNarrationCallIds(events: StreamEvent[]): Set<string> {return ids;}-/** True for a per-round marker that demotes its content to narration. */-export function isNarrationMarker(event: StreamEvent): boolean {+/** True for a per-round marker that takes its content back out of the answer. */+export function isRetractionMarker(event: StreamEvent): boolean {const meta = eventMeta(event);return (meta.trace_kind === "call_status" &&meta.call_state === "complete" &&- meta.call_role === "narration" &&- meta.answer_visible !== true+ meta.answer_visible === false);}/*** Recompute the answer text from a turn's events: appended content minus any- * narration rounds. Cheap to call only when a narration marker arrives (a- * handful of times per turn) rather than per streamed chunk.+ * retracted round. Cheap to call only when a retraction arrives (rare — most+ * turns never have one) rather than per streamed chunk.*/export function recomputeAnswerContent(events: StreamEvent[]): string {- const narration = collectNarrationCallIds(events);+ const retracted = collectRetractedCallIds(events);let content = "";for (const event of events) {if (!shouldAppendEventContent(event)) continue;const callId = eventMeta(event).call_id;- if (callId && narration.has(callId)) continue;+ if (callId && retracted.has(callId)) continue;content += event.content;}return content;diff --git a/web/tests/ask-user-segments.test.ts b/web/tests/ask-user-segments.test.tsindex 364f7d7f7..bcef713bf 100644--- a/web/tests/ask-user-segments.test.ts+++ b/web/tests/ask-user-segments.test.ts@@ -49,6 +49,87 @@ const resolved = (toolCallId: string) =>answers: [{ questionId: "q1", text: "B" }],});+test("work is laid out between the text that introduced it and what followed", () => {+ // The shape the whole change exists for: say what you are about to do, do+ // it, say what came of it — in that order, in one bubble.+ const segments = extractMessageSegments([+ event(+ "content",+ { call_id: "round-1", call_kind: "agent_loop_round" },+ "Let me look that up.",+ ),+ event("tool_call", { call_id: "tool-1" }, "web_search"),+ event("tool_result", { call_id: "tool-1" }, "three results"),+ event(+ "content",+ { call_id: "round-2", call_kind: "agent_loop_round" },+ "It is 1957.",+ ),+ ]);++ assert.deepEqual(+ segments.map((segment) => segment.kind),+ ["text", "trace", "text"],+ );+ assert.equal(+ segments[0].kind === "text" && segments[0].text,+ "Let me look that up.",+ );+ assert.equal(segments[2].kind === "text" && segments[2].text, "It is 1957.");+});++test("a fresh run of work opens below the text that follows the previous one", () => {+ const segments = extractMessageSegments([+ event("content", { call_id: "r1", call_kind: "agent_loop_round" }, "First,"),+ event("tool_call", { call_id: "t1" }, "read_source"),+ event("content", { call_id: "r2", call_kind: "agent_loop_round" }, "Now,"),+ event("tool_call", { call_id: "t2" }, "web_search"),+ event("content", { call_id: "r3", call_kind: "agent_loop_round" }, "Done."),+ ]);++ assert.deepEqual(+ segments.map((segment) => segment.kind),+ ["text", "trace", "text", "trace", "text"],+ );+ // Each region holds only its own call, not everything that came before.+ const first = segments[1];+ const second = segments[3];+ assert.equal(first.kind === "trace" && first.events.length, 1);+ assert.equal(second.kind === "trace" && second.events.length, 1);+});++test("a reloaded turn keeps each run of work under its own paragraph", () => {+ // The event preview a settled turn is restored from carries no `content`,+ // so the two calls arrive back to back with nothing between them. Only the+ // boundary each recorded still says which paragraph it belonged under —+ // without it both rows collapsed into one block and the reload no longer+ // resembled the turn the reader had watched.+ const first = "Let me look that up.\n\n";+ const second = "That confirms it. Checking one more thing.\n\n";+ const closing = "So the answer is 1957.";+ const segments = extractMessageSegments(+ [+ event("tool_call", { call_id: "t1", assistant_content_offset: first.length }),+ event("tool_result", { call_id: "t1" }, "a source"),+ event("tool_call", {+ call_id: "t2",+ assistant_content_offset: (first + second).length,+ }),+ event("tool_result", { call_id: "t2" }, "three results"),+ event("done", { status: "completed" }),+ ],+ first + second + closing,+ );++ assert.deepEqual(+ segments.map((segment) => segment.kind),+ ["text", "trace", "text", "trace", "text"],+ );+ assert.equal(segments[0].kind === "text" && segments[0].text, first);+ assert.equal(segments[2].kind === "text" && segments[2].text, second);+ assert.equal(segments[4].kind === "text" && segments[4].text, closing);+});+test("reasoning produced after a card becomes its own segment below it", () => {const before = event("thinking",@@ -75,31 +156,36 @@ test("reasoning produced after a card becomes its own segment below it", () => {assert.deepEqual(segments.map((segment) => segment.kind),- ["ask_user", "trace", "text"],+ ["trace", "ask_user", "trace", "text"],+ );+ const beforeCard = segments[0];+ assert.equal(+ beforeCard.kind === "trace" && beforeCard.events[0].content,+ "planning a question",);- const traceSegment = segments[1];- assert.equal(traceSegment.kind === "trace" && traceSegment.events.length, 1);+ const afterCard = segments[2];+ assert.equal(afterCard.kind === "trace" && afterCard.events.length, 1);assert.equal(- traceSegment.kind === "trace" && traceSegment.events[0].content,+ afterCard.kind === "trace" && afterCard.events[0].content,"grading their answer",);});-test("the pre-card rounds stay with the top activity block", () => {+test("every round is claimed inline, leaving the header block nothing to show", () => {+ // Trace rows render where the work happened. Anything still handed to the+ // pinned activity block would be the same step shown a second time.const before = event("thinking", { call_id: "round-1" }, "planning");const after = event("thinking", { call_id: "round-2" }, "grading");const events = [before, askUserCard("call-1"), resolved("call-1"), after];const leading = leadingTraceEvents(events, extractMessageSegments(events));- assert.deepEqual(leading, [- before,- askUserCard("call-1"),- resolved("call-1"),- ]);+ // Nothing at all: the reasoning is claimed by its inline region, and the+ // card's own events render as the card rather than as a bare tool row.+ assert.deepEqual(leading, []);});-test("a turn with no card keeps every event in the top block", () => {+test("a turn with no tool work is a single run of prose", () => {const events = [event("thinking", { call_id: "round-1" }, "thinking"),event(@@ -112,9 +198,11 @@ test("a turn with no card keeps every event in the top block", () => {assert.deepEqual(segments.map((segment) => segment.kind),- ["text"],+ ["trace", "text"],);- assert.deepEqual(leadingTraceEvents(events, segments), events);+ // The reasoning is claimed by the inline region; only the answer text is+ // left over, and answer text was never a trace row to begin with.+ assert.deepEqual(leadingTraceEvents(events, segments), [events[1]]);});test("each card gets the rounds that followed it", () => {@@ -218,9 +306,12 @@ test("a posed mastery question is its own segment, not an ask_user card", () =>answer,);+ // The `mastery_quiz` call carries no call_id of its own, so there is no row+ // to draw for it and the region it opened is dropped rather than left as an+ // empty gap.assert.deepEqual(segments.map((segment) => segment.kind),- ["text", "mastery_question", "trace"],+ ["text", "mastery_question"],);// The whole settled answer lays out above the card that ended the turn.assert.equal(segments[0].kind === "text" && segments[0].text, answer);@@ -278,14 +369,14 @@ test("a resolved card splits the settled answer at its stamped offset", () => {assert.deepEqual(segments.map((segment) => segment.kind),- ["text", "ask_user", "trace", "text"],+ ["text", "ask_user", "text"],);assert.equal(segments[0].kind === "text" && segments[0].text, intro);assert.equal(segments[1].kind === "ask_user" && segments[1].data.resolved,true,);- assert.equal(segments[3].kind === "text" && segments[3].text, reply);+ assert.equal(segments[2].kind === "text" && segments[2].text, reply);});test("an offset measured before the CJK repair still cuts at the paragraph", () => {diff --git a/web/tests/stream.test.ts b/web/tests/stream.test.tsindex 04f8c3508..194e4ded5 100644--- a/web/tests/stream.test.ts+++ b/web/tests/stream.test.ts@@ -1,8 +1,8 @@import test from "node:test";import assert from "node:assert/strict";import {- collectNarrationCallIds,- isNarrationMarker,+ collectRetractedCallIds,+ isRetractionMarker,recomputeAnswerContent,} from "../lib/stream";import type { StreamEvent } from "../features/chat/model/protocol";@@ -25,9 +25,12 @@ function event(};}-test("ordinary narration is removed from answer content", () => {+test("commentary written before a tool call stays in the answer", () => {+ // The reader watched this sentence arrive above the tool's own row. Taking+ // it back out on the round's completion marker is what used to make a turn+ // look like it had said nothing while it worked.const events = [- event("content", "Searching.", {+ event("content", "Checking the syllabus first.", {call_id: "round-1",call_kind: "agent_loop_round",}),@@ -36,35 +39,52 @@ test("ordinary narration is removed from answer content", () => {trace_kind: "call_status",call_state: "complete",call_role: "narration",+ answer_visible: true,}),];- assert.deepEqual([...collectNarrationCallIds(events)], ["round-1"]);- assert.equal(isNarrationMarker(events[1]), true);- assert.equal(recomputeAnswerContent(events), "");+ assert.deepEqual([...collectRetractedCallIds(events)], []);+ assert.equal(isRetractionMarker(events[1]), false);+ assert.equal(recomputeAnswerContent(events), "Checking the syllabus first.");});-test("clean prose surrounding a DSML call remains answer-visible", () => {+test("a round a capability retracted leaves the answer", () => {const events = [event("content", "Great job! Choose the next topic.", {- call_id: "round-dsml",+ call_id: "round-rejected",call_kind: "agent_loop_round",}),event("progress", "", {- call_id: "round-dsml",+ call_id: "round-rejected",trace_kind: "call_status",call_state: "complete",call_role: "narration",- answer_visible: true,+ answer_visible: false,}),];- assert.deepEqual([...collectNarrationCallIds(events)], []);- assert.equal(isNarrationMarker(events[1]), false);- assert.equal(- recomputeAnswerContent(events),- "Great job! Choose the next topic.",- );+ assert.deepEqual([...collectRetractedCallIds(events)], ["round-rejected"]);+ assert.equal(isRetractionMarker(events[1]), true);+ assert.equal(recomputeAnswerContent(events), "");+});++test("a round recorded before the flag existed keeps its text", () => {+ // Sessions written by an older build carry no `answer_visible` at all.+ const events = [+ event("content", "Searching.", {+ call_id: "round-legacy",+ call_kind: "agent_loop_round",+ }),+ event("progress", "", {+ call_id: "round-legacy",+ trace_kind: "call_status",+ call_state: "complete",+ call_role: "narration",+ }),+ ];++ assert.equal(collectRetractedCallIds(events).size, 0);+ assert.equal(recomputeAnswerContent(events), "Searching.");});test("token-limit continuation replays the exact visible answer", () => {@@ -98,8 +118,8 @@ test("token-limit continuation replays the exact visible answer", () => {test("a finish that is rejected after streaming is withdrawn from the answer", () => {// A guarded surface (mastery, partner authoring) streams optimistically and// closes the round as `finish`. When its capability then rejects that finish,- // the loop re-marks the same call_id as `narration`, and the already-visible- // text has to come back out of the reply.+ // the loop republishes the same call_id with `answer_visible: false`, and the+ // already-visible text has to come back out of the reply.const events = [event("content", "Which value is correct?\n\nA. one\nB. two\nC. three", {call_id: "round-1",@@ -116,6 +136,7 @@ test("a finish that is rejected after streaming is withdrawn from the answer", (trace_kind: "call_status",call_state: "complete",call_role: "narration",+ answer_visible: false,finish_rejected: true,}),event("content", "Let us try that on a card instead.", {@@ -130,7 +151,7 @@ test("a finish that is rejected after streaming is withdrawn from the answer", (}),];- assert.deepEqual([...collectNarrationCallIds(events)], ["round-1"]);+ assert.deepEqual([...collectRetractedCallIds(events)], ["round-1"]);assert.equal(recomputeAnswerContent(events),"Let us try that on a card instead.",@@ -151,6 +172,6 @@ test("an accepted finish keeps its text even after later rounds close", () => {}),];- assert.equal(collectNarrationCallIds(events).size, 0);+ assert.equal(collectRetractedCallIds(events).size, 0);assert.equal(recomputeAnswerContent(events), "The derivative is 2x.");});diff --git a/web/tests/trace-memory.test.ts b/web/tests/trace-memory.test.tsindex 9b1a5cb18..5eb355647 100644--- a/web/tests/trace-memory.test.ts+++ b/web/tests/trace-memory.test.ts@@ -123,6 +123,7 @@ test("settling a message keeps its card and stamps where the answer was cut", ()trace_kind: "call_status",call_state: "complete",call_role: "narration",+ answer_visible: true,}),seq: 2,},@@ -157,10 +158,11 @@ test("settling a message keeps its card and stamps where the answer was cut", ()settled.events.map((item) => item.type),["tool_result", "progress", "done"],);- // The narration preamble never reached the answer, so it is not counted.+ // The commentary the turn opened with is answer text too, so the boundary+ // the card was cut at counts it.assert.equal(settled.events[1].metadata?.assistant_content_offset,- "Two ways.\n\n".length,+ "preamble Two ways.\n\n".length,);assert.deepEqual(settled.trace, {turn_id: "turn-1",diff --git a/web/tests/trace-selectors.test.ts b/web/tests/trace-selectors.test.tsindex b22c6025e..d9adc8c7a 100644--- a/web/tests/trace-selectors.test.ts+++ b/web/tests/trace-selectors.test.ts@@ -5,7 +5,7 @@ import {detectStreamingMode,groupTraceEvents,hasRenderableCallTrace,- isNarrationRound,+ isRetractedRound,isTracePending,selectTraceDisplayItems,} from "../features/chat/trace/selectors";@@ -63,8 +63,11 @@ test("final answer and absorbed groups stay out of progressive trace disclosure"assert.equal(hasRenderableCallTrace(events), false);});-test("narration before a tool remains visible while a finish answer does not", () => {- const narration = [+test("only a retracted round's text becomes trace material", () => {+ // Chat-loop text lives in the answer bubble, so showing it in the trace as+ // well would print the same sentence twice. The exception is a round whose+ // text was taken back out — the trace is then the only place left for it.+ const commentary = [event("content","round-1",@@ -75,24 +78,27 @@ test("narration before a tool remains visible while a finish answer does not", (trace_kind: "call_status",call_state: "complete",call_role: "narration",+ answer_visible: true,}),];- const finish = [+ const retracted = [event("content","round-2",{ call_kind: "agent_loop_round" },- "Final answer",+ "A question I never posed",),event("progress", "round-2", {trace_kind: "call_status",call_state: "complete",- call_role: "finish",+ call_role: "narration",+ answer_visible: false,}),];- assert.equal(isNarrationRound(narration), true);- assert.equal(hasRenderableCallTrace(narration), true);- assert.equal(hasRenderableCallTrace(finish), false);+ assert.equal(isRetractedRound(commentary), false);+ assert.equal(hasRenderableCallTrace(commentary), false);+ assert.equal(isRetractedRound(retracted), true);+ assert.equal(hasRenderableCallTrace(retracted), true);});test("adjacent react rounds and their trailing trace collapse into one display step", () => {