diff --git a/docs/request-for-change/README.md b/docs/request-for-change/README.md index 215d2ea315a0..2329116e1b95 100644 --- a/docs/request-for-change/README.md +++ b/docs/request-for-change/README.md @@ -95,7 +95,7 @@ was added 2026-08-27. The `rfc-crew-agent-sdk-boundary` row was added 2026-08-28 | [rfc-chat-backend-selection.md](rfc-chat-backend-selection.md) | `draft` | Nothing yet. Acceptance requested from a maintainer; the status flips to `accepted` when one records it here. Verified at `c4c51aac52`: a dashboard chat slot stores a `model` but no backend, `/api/chat/slots/{slot}/model` in `src/kiro_crew/dashboard/routes/chat.py` has no backend sibling, `mcp_dashboard_session_tools.py` has `session_set_model` but no `session_set_backend`, and `backend_override` reaches `select_provider_backend` only from `spawn_run`. Tracks [#13892](https://github.com/kirodotdev/KiroCrew/issues/13892). | | [rfc-subagent-backend-selection.md](rfc-subagent-backend-selection.md) | `draft` | Phase 1 only. Acceptance requested from a maintainer; the status flips to `accepted` when one records it here. [#18150](https://github.com/kirodotdev/KiroCrew/pull/18150) merged 2026-10-11: `spawn_run` and its task items take an optional `backend`, limited to governance-selectable backends and refused at spawn time, and the child keeps it across continuations. Phase 2 (refusing a continuation or retry whose backend can no longer start, and recording the backend that actually ran) is not on main. Tracks [#13892](https://github.com/kirodotdev/KiroCrew/issues/13892). | | [rfc-chat-document-attachments.md](rfc-chat-document-attachments.md) | `draft` | Nothing. Acceptance requested from a maintainer; the status flips to `accepted` when one records it in that document's §11. This document lands first because it changes what every dashboard prompt carrying a `.pdf`/`.docx`/`.pptx` attachment says to the agent, and the First Principles lane reads that decision from the base branch. Verified at `8c6e7eba90` and re-read at `2e8831ea52` on 2026-10-12: `api_upload_file` in `src/kiro_crew/dashboard/file_api/uploads.py` writes the upload and returns its path with no text extraction; `build_prompt_blocks` in `src/kiro_crew/acp/prompt_blocks.py` rewrites image paths into `[image: ]` and passes a document path through bare; `ingest_attachments` in `src/kiro_crew/messaging/attachments.py` already extracts, redacts and inlines document text for the eight messaging channels, so the dashboard is the parity gap. Tracks [#14570](https://github.com/kirodotdev/KiroCrew/issues/14570). | -| [rfc-agent-started-turns.md](rfc-agent-started-turns.md) | `partial` | Phases 1 and 2 shipped ([#18285](https://github.com/kirodotdev/KiroCrew/pull/18285), [#25132](https://github.com/kirodotdev/KiroCrew/pull/25132), [#25133](https://github.com/kirodotdev/KiroCrew/pull/25133), [#29269](https://github.com/kirodotdev/KiroCrew/pull/29269)): `on_agent_turn` in `acp/client_transport.py` and `dashboard/chat_turn/agent_started.py`. Phase 3 is blocked and the "started by the agent" label is not built. Re-audited 2026-11-14 against `1d08e941b3`. | +| [rfc-agent-started-turns.md](rfc-agent-started-turns.md) | `partial` | Phases 1 and 2 shipped ([#18285](https://github.com/kirodotdev/KiroCrew/pull/18285), [#25132](https://github.com/kirodotdev/KiroCrew/pull/25132), [#25133](https://github.com/kirodotdev/KiroCrew/pull/25133), [#29269](https://github.com/kirodotdev/KiroCrew/pull/29269)): `on_agent_turn` in `acp/client_transport.py` and `dashboard/chat_turn/agent_started.py`. Phase 3 is blocked. The "Started by the agent" label heads the turn's own group in the transcript. Re-audited 2026-11-14 against `1d08e941b3`. | | [rfc-conductor-default-patrol.md](rfc-conductor-default-patrol.md) | `implemented` | Phase 1 ([#17069](https://github.com/kirodotdev/KiroCrew/pull/17069)), phase 2 ([#19742](https://github.com/kirodotdev/KiroCrew/pull/19742): `patrol_reason` in `dashboard/handlers/session_control.py` and `work_ledger_conductor.py`) and the §10 member-thread arm ([#27948](https://github.com/kirodotdev/KiroCrew/pull/27948): `autonudge_authz.admits_member_default_patrol`) are on main. The bind route's `ensure_patrol` call is in `dashboard/handlers/work_ledger_conductor.py`. Re-audited 2026-11-14 against `1d08e941b3`. | | [rfc-conductor-round-reset.md](rfc-conductor-round-reset.md) | `implemented` | Shipped in [#18113](https://github.com/kirodotdev/KiroCrew/pull/18113) (`5665e9310217`); verified at `a84f616557`. `_CONDUCTOR_CORE_GRANTS` in `src/kiro_crew/agent_parts/spec_grants.py` grants `reset_conversation`; `apply_session_directive` in `src/kiro_crew/dashboard/session_directive_apply.py` admits it from a person's turn and, through `_refuse_unvouched_wake_reset`, from a conductor's own self-armed patrol wake when nothing waits on a person; `autonudge_authz.py` records the self-arm for a conductor slot (`WAKE_RESET_AGENTS` in `autonudge_selfarm.py`); the goal-conductor skill and `_CONDUCTOR_SYSTEM_PROMPT` carry the drop-your-chat step. | | [rfc-conductor-chat-board-on-tab.md](rfc-conductor-chat-board-on-tab.md) | `implemented` | Shipped in [#18608](https://github.com/kirodotdev/KiroCrew/pull/18608): the "When your Dashboard tab already shows the board" rule is in the conductor prompt, now in `src/kiro_crew/agent_parts/spec_prompts.py`. Re-audited 2026-11-14 against `1d08e941b3`. | diff --git a/docs/request-for-change/rfc-agent-started-turns.md b/docs/request-for-change/rfc-agent-started-turns.md index e08cb7acdfaf..fa3abc5a4ff2 100644 --- a/docs/request-for-change/rfc-agent-started-turns.md +++ b/docs/request-for-change/rfc-agent-started-turns.md @@ -14,7 +14,7 @@ superseded-by: [] # RFC: Agent-started turns — show a turn the agent starts between user turns as its own reply -- Status: partial (Phases 1 and 2 on main; Phase 3 blocked). Accepted: the product owner chose option A on all four [decisions](#decisions-needed) on 2026-10-08: an agent-started turn is its own assistant message with a notification, claude only, a user message queues behind it, and every other backend keeps today's behaviour. Phases 0 to 2 are unlocked; Phase 3 stays blocked. Phase 0's verdicts are recorded under [Phase 0](#phase-0--probe-no-product-code). Phase 1 (the transport) is implemented, and so is Phase 2 (the dashboard wiring): the dashboard chat registers `on_agent_turn`, and how it is built is recorded in `docs/system-specs/modules/claude-code-provider.md` ("A turn Claude Code starts on its own"). Two Phase 2 points differ from the design below: the assistant row's `meta.origin` carries `kind` only, because the closing origin's kind is read by the transport and not handed to the dashboard, so no `reason` is stored; and the "started by the agent" label and its browser-harness frame are not built yet, so the reply renders as an ordinary assistant row. +- Status: partial (Phases 1 and 2 on main; Phase 3 blocked). Accepted: the product owner chose option A on all four [decisions](#decisions-needed) on 2026-10-08: an agent-started turn is its own assistant message with a notification, claude only, a user message queues behind it, and every other backend keeps today's behaviour. Phases 0 to 2 are unlocked; Phase 3 stays blocked. Phase 0's verdicts are recorded under [Phase 0](#phase-0--probe-no-product-code). Phase 1 (the transport) is implemented, and so is Phase 2 (the dashboard wiring): the dashboard chat registers `on_agent_turn`, and how it is built is recorded in `docs/system-specs/modules/claude-code-provider.md` ("A turn Claude Code starts on its own"). Two Phase 2 points differ from the design below: the assistant row's `meta.origin` carries `kind` only, because the closing origin's kind is read by the transport and not handed to the dashboard, so no `reason` is stored; and the turn's first row, whatever its role, also carries `turn_start: true` in its `meta.origin`, so a turn that wrote only tool rows is marked too. The transcript starts the turn's own group at that row and heads it with the "Started by the agent" label; its browser-harness frame is `website/scripts/capture-17566-agent-started-reply.mjs`. - Author: iamwhatever - Design credit: the reader hand-off, the prompt-less turn through `_run_chat` and the end-of-turn signal are rinbn's [design note on #17566](https://github.com/kirodotdev/KiroCrew/issues/17566). This document writes that note up and adds what review of [#17884](https://github.com/kirodotdev/KiroCrew/pull/17884) found a new path must keep. - Related: `docs/system-specs/modules/acp-client.md` (stdout, the replay buffer, cancellation), `docs/system-specs/modules/app-notifications.md` (unread badge, turn sound) diff --git a/docs/system-specs/modules/claude-code-provider.md b/docs/system-specs/modules/claude-code-provider.md index 0efd9bb44a6f..26ead5a86656 100644 --- a/docs/system-specs/modules/claude-code-provider.md +++ b/docs/system-specs/modules/claude-code-provider.md @@ -1190,7 +1190,12 @@ of its own on that chat (`_run_chat(_agent_started=True)`). The turn sends nothi and reads the pending turn with `AcpProvider.stream_unsolicited`, through the same event loop a user turn uses: its tool rows, permission cards, PreToolUse / PostToolUse hooks, SEL records, redaction and persistence are a user turn's own. It -writes no user row, its assistant rows carry `meta.origin = {"kind": "agent"}`, it +writes no user row, its assistant rows carry `meta.origin = {"kind": "agent"}`, and +its first saved row, whatever its role, carries `{"kind": "agent", "turn_start": true}` +(`agent_started.agent_turn_opener_meta`, owed to the slot when the turn opens its +stream and paid by the next row `append` writes outside `_TRANSIENT_ROLES`, so a +permission or elicitation card, which is never saved and whose meta a refresh +rebuilds, leaves it for the row after; a turn that wrote no such row drops it). It records crew-log actor `agent`, and it ends through the normal end-of-turn path, so the unread badge and turn sound fire. A message sent while it runs queues behind it: the turn is responsive-protected, so a send never cancels it. It is @@ -1212,8 +1217,12 @@ without spending that arm's retry budget. A caller that still asks `_queue_recovery` (a Stop hook's block) is declined and posts nothing. Its reply and tool stream reach a linked Slack thread like any reply; no prompt echo is posted, because none was typed. It does not count as an -AutoNudge or monitor cycle. Regenerate refuses (`agent_started_reply`) while a -reply it wrote sits after the newest user row: re-running that prompt would retire +AutoNudge or monitor cycle. The transcript starts the turn's own group at that +first row, in the chat page (`groupDisplayItems`) and the pane (`ChatMessageList`), +and TurnBlock heads the group with a "Started by the agent" label above its tool +rows and its reply; the chat page, which shows permission requests in the approval +bar rather than as rows, opens the group at the next row it shows. Regenerate refuses +(`agent_started_reply`) while a row it marked sits after the newest user row: re-running that prompt would retire the agent's reply, and any reply beside it, for a variant of only the newest one. A session no dashboard chat turn runs (a channel conversation on the messaging driver, a cron job's own session, a sub-agent) diff --git a/docs/system-specs/modules/learn-cron-dashboard.md b/docs/system-specs/modules/learn-cron-dashboard.md index e0e79fe3a6f9..f27c71fbf2db 100644 --- a/docs/system-specs/modules/learn-cron-dashboard.md +++ b/docs/system-specs/modules/learn-cron-dashboard.md @@ -2951,7 +2951,7 @@ surface. The modules of | `recovery` | empty-turn config, terminal error metadata, retry delays and stop gates, the drain and consume seams of the recovery-replay ledger, auth and busy requeues, the refusal card text and the compact-after-turn notice. The ledger itself is the plain module `dashboard/recovery_replays.py` (`slot.replays`: the records, the drained-alone claim, the sweep, the revocation rule and each family's policy). A new replay family is a `ReplayFamily` member and a `POLICIES` row there (the row's position is the drain's re-check order; its `consume_phase` puts the consume-seam check before or after the turn-start allowance refresh), plus the arm site that queues it | | `acp_recovery` | the post-token transient re-prompt and the thinking-binding discard-and-replay gate (`_binding_rebuild_allowed`); the except arms that recover the turn: a dead process (`_on_process_died`) and the `except AcpError` ladder's arms for a retryable ACP error on a fresh session, a lost or rebound session, an unsupported image, and a transient error before the first token (retried or spent) and after it (the `_on_acp_*` arms); a new arm that retries, resets or replays the turn goes here (a model fallback hop in `model_fallback`), one that ends it in `turn_failures` | | `turn_marker` | the in-flight turn marker's write, retire and clear | -| `agent_started` | a turn the agent starts on its own between a chat's prompts (`docs/request-for-change/rfc-agent-started-turns.md`): the watch each turn registers on its session (`_watch_agent_turns`, gated by `agent.agent_started_turns`), the slot claim when it fires (`_on_agent_turn`: skipped for a closed or replaced slot or session, retried when the task holding the slot ends), the turn's `meta.origin` value and the predicate that reads it (`is_agent_started_row`, which `chat_regenerate` refuses on) and the close of its event stream | +| `agent_started` | a turn the agent starts on its own between a chat's prompts (`docs/request-for-change/rfc-agent-started-turns.md`): the watch each turn registers on its session (`_watch_agent_turns`, gated by `agent.agent_started_turns`), the slot claim when it fires (`_on_agent_turn`: skipped for a closed or replaced slot or session, retried when the task holding the slot ends), the turn's `meta.origin` value, the opener meta its first row carries (`agent_turn_opener_meta`) and the predicate that reads them (`is_agent_started_row`, which `chat_regenerate` refuses on) and the close of its event stream, which also drops an opener no row took | | `directives` | not-applied directive wording and the unclaimed-directive backstop | | `stream_chunks` | the stream's text and thinking arms, which hold the live-stream and thinking-stream sinks `security_posture` names: a chunk of the reply's text (`_on_text_chunk`): the segment cut after a tool group, with the tool rows it marks done and the crew log's next model-call step, the drop of text after an applied terminal directive, the per-delta redaction and the segment's raw copy, the turn-emit flag and the consumption report, and the `chat_chunk` frame the live-stream redactor releases, a plain sentence end included (`release_sentence_end`); and a chunk of thinking (`_on_thinking_chunk`) and the `chat_thinking` frame the thinking-stream redactor releases | | `tool_rows` | what a turn's tool rows persist and broadcast: row meta, the WS payload, the refinement rewrite, the tool-call identity key and the rows-only save, and the stream's tool-call and tool-update arms (`_on_tool_call`, `_on_tool_call_update`) | diff --git a/src/kiro_crew/dashboard/chat_runner.py b/src/kiro_crew/dashboard/chat_runner.py index e44892d21f16..160a631cf84a 100644 --- a/src/kiro_crew/dashboard/chat_runner.py +++ b/src/kiro_crew/dashboard/chat_runner.py @@ -150,6 +150,7 @@ _ask_the_owed_cancel_answered, _close_agent_turn_stream, _send_owed_agent_cancel, + agent_turn_opener_meta, is_agent_started_row, ) from kiro_crew.dashboard.chat_turn.app_agent_binding import ( @@ -1148,6 +1149,7 @@ async def _run_chat( # re-apply build_message's provenance so only the user's text is upgraded. if _agent_started: event_stream = turn._agent_turn_stream = client.stream_unsolicited() + slot._owed_turn_opener = agent_turn_opener_meta elif is_slash: if turn.first_word == "/compact": _begin_compact_command(turn) diff --git a/src/kiro_crew/dashboard/chat_turn/agent_started.py b/src/kiro_crew/dashboard/chat_turn/agent_started.py index ec9ca260969c..a98f831fb293 100644 --- a/src/kiro_crew/dashboard/chat_turn/agent_started.py +++ b/src/kiro_crew/dashboard/chat_turn/agent_started.py @@ -38,6 +38,8 @@ AGENT_STARTED_ACTOR = "agent" #: The assistant row meta key that says who started the turn the row answers. AGENT_ORIGIN_META_KEY = "origin" +#: Set in ``meta.origin`` on the first row a turn the agent started writes. +AGENT_TURN_START_KEY = "turn_start" def agent_origin_meta() -> dict[str, str]: @@ -48,8 +50,19 @@ def agent_origin_meta() -> dict[str, str]: return {"kind": AGENT_STARTED_ACTOR} +def agent_turn_opener_meta(meta: dict | None) -> dict: + """*meta* for the first row a turn the agent started writes, whatever its role. + + That turn has no prompt row, so this row is where the transcript starts the + turn's own group, and it exists for a turn that wrote only tool rows too. + """ + out = dict(meta) if meta else {} + out[AGENT_ORIGIN_META_KEY] = {**agent_origin_meta(), AGENT_TURN_START_KEY: True} + return out + + def is_agent_started_row(row: object) -> bool: - """Whether *row* is a reply a turn the agent started wrote (:func:`agent_origin_meta`).""" + """Whether a turn the agent started wrote *row* and marked it (:func:`agent_origin_meta`).""" meta = row.get("meta") if isinstance(row, dict) else None origin = meta.get(AGENT_ORIGIN_META_KEY) if isinstance(meta, dict) else None return isinstance(origin, dict) and origin.get("kind") == AGENT_STARTED_ACTOR @@ -72,12 +85,14 @@ async def _close_agent_turn_stream(turn: _ChatTurn) -> None: The client holds the next prompt back while that stream is open, so a turn that leaves its loop early (a Stop, a raise, a ``break``) must not leave it - for the garbage collector to close. + for the garbage collector to close. A turn that wrote no row leaves its + opener unclaimed, and the next row on the slot is not this turn's. """ stream = turn._agent_turn_stream if stream is None: return turn._agent_turn_stream = None + turn.slot._owed_turn_opener = None try: await stream.aclose() except Exception: diff --git a/src/kiro_crew/dashboard/state_parts/chat_slot.py b/src/kiro_crew/dashboard/state_parts/chat_slot.py index 7f10661a2eae..e50157c31c2b 100644 --- a/src/kiro_crew/dashboard/state_parts/chat_slot.py +++ b/src/kiro_crew/dashboard/state_parts/chat_slot.py @@ -355,6 +355,7 @@ class _ChatSlot: "_steer_segment_cut", "_compact_command_turn", "_owed_segment_cut", + "_owed_turn_opener", "_native_subagent_tracker", "_native_subagent_output", "_steer_confirmed", @@ -729,6 +730,7 @@ class _ChatSlot: _steer_segment_cut: Callable[[], None] | None _compact_command_turn: bool _owed_segment_cut: Callable[[], None] | None + _owed_turn_opener: Callable[[dict | None], dict] | None _native_subagent_tracker: dict[str, dict[str, Any]] _native_subagent_output: dict[str, list[str]] _steer_confirmed: set[str] diff --git a/src/kiro_crew/dashboard/state_parts/slot_ladder.py b/src/kiro_crew/dashboard/state_parts/slot_ladder.py index cb513f1882de..acb16226495c 100644 --- a/src/kiro_crew/dashboard/state_parts/slot_ladder.py +++ b/src/kiro_crew/dashboard/state_parts/slot_ladder.py @@ -342,6 +342,9 @@ def init_ladder_fields(self: _ChatSlot) -> None: # A segment cut a permission request owes: paid by ``append`` before the # next durable row, dropped when the request lands none. None when idle. self._owed_segment_cut = None + # The meta a turn with no prompt row puts on its first durable row, set when + # that turn opens its stream and consumed by ``append``. None when idle. + self._owed_turn_opener = None # Native kiro-cli subagents run inside the parent ACP turn. Keep their # live and terminal state on the slot so reconnects can hydrate cards. self._native_subagent_tracker = {} diff --git a/src/kiro_crew/dashboard/state_parts/slot_transcript.py b/src/kiro_crew/dashboard/state_parts/slot_transcript.py index ddf9b0d664df..7af6d74d4729 100644 --- a/src/kiro_crew/dashboard/state_parts/slot_transcript.py +++ b/src/kiro_crew/dashboard/state_parts/slot_transcript.py @@ -326,6 +326,14 @@ def append( owed_cut() except Exception: logger.warning("owed segment cut failed for slot %s", self.key, exc_info=True) + # A turn with no prompt row has its first durable row open it, after any + # row the cut above wrote first. A transient row (a permission or + # elicitation card) is never saved and a refresh rebuilds its meta, so it + # would carry the mark away: the first saved row takes it instead. + owed_opener = getattr(self, "_owed_turn_opener", None) + if owed_opener is not None and role not in _TRANSIENT_ROLES and role != "user": + self._owed_turn_opener = None + meta = owed_opener(meta) # A live row the person typed makes any in-flight return summary stale. # The local import avoids a state -> warm_task_brief -> state cycle, and # replay appends (broadcast=False) deliberately do not cancel current work. diff --git a/temp-screenshots/17566-agent-started-reply/after-dark.png b/temp-screenshots/17566-agent-started-reply/after-dark.png new file mode 100644 index 000000000000..bc45bee45d2b Binary files /dev/null and b/temp-screenshots/17566-agent-started-reply/after-dark.png differ diff --git a/temp-screenshots/17566-agent-started-reply/after-light.png b/temp-screenshots/17566-agent-started-reply/after-light.png new file mode 100644 index 000000000000..c1f3ab22dcc3 Binary files /dev/null and b/temp-screenshots/17566-agent-started-reply/after-light.png differ diff --git a/temp-screenshots/17566-agent-started-reply/before-dark.png b/temp-screenshots/17566-agent-started-reply/before-dark.png new file mode 100644 index 000000000000..638a392fac72 Binary files /dev/null and b/temp-screenshots/17566-agent-started-reply/before-dark.png differ diff --git a/temp-screenshots/17566-agent-started-reply/before-light.png b/temp-screenshots/17566-agent-started-reply/before-light.png new file mode 100644 index 000000000000..70955785ed39 Binary files /dev/null and b/temp-screenshots/17566-agent-started-reply/before-light.png differ diff --git a/temp-screenshots/17566-agent-started-reply/tool-only-dark.png b/temp-screenshots/17566-agent-started-reply/tool-only-dark.png new file mode 100644 index 000000000000..74c82fc4f883 Binary files /dev/null and b/temp-screenshots/17566-agent-started-reply/tool-only-dark.png differ diff --git a/temp-screenshots/17566-agent-started-reply/tool-only-light.png b/temp-screenshots/17566-agent-started-reply/tool-only-light.png new file mode 100644 index 000000000000..c22a97d91d98 Binary files /dev/null and b/temp-screenshots/17566-agent-started-reply/tool-only-light.png differ diff --git a/test/test_dashboard_agent_started_turn.py b/test/test_dashboard_agent_started_turn.py index 67092cd7c139..b3facaa5c0ad 100644 --- a/test/test_dashboard_agent_started_turn.py +++ b/test/test_dashboard_agent_started_turn.py @@ -33,11 +33,17 @@ from kiro_crew.acp.transport_errors import AcpError, AcpProcessDied from kiro_crew.acp.types import STOP_REASON_STALE_RECOVER from kiro_crew.agent_sdk.backends import ACP_BACKEND_CLAUDE, ACP_BACKEND_KIRO +from kiro_crew.context import build_session_replay from kiro_crew.dashboard import chat_runner from kiro_crew.dashboard import gateway_notice as gn from kiro_crew.dashboard.chat import _run_chat from kiro_crew.dashboard.chat_turn import turn_ledgers -from kiro_crew.dashboard.chat_utils import TRANSIENT_GIVE_UP_TEXT, TRANSIENT_RETRY_KIND +from kiro_crew.dashboard.chat_turn.agent_started import agent_turn_opener_meta +from kiro_crew.dashboard.chat_utils import ( + TRANSIENT_GIVE_UP_TEXT, + TRANSIENT_RETRY_KIND, + slot_history_key, +) from kiro_crew.hooks import ToolHookResult from kiro_crew.providers import acp_turns from kiro_crew.providers.acp import AcpProvider @@ -45,6 +51,7 @@ EVENT_COMPLETE, EVENT_PERMISSION_REQUEST, EVENT_TEXT_CHUNK, + EVENT_TOOL_CALL, LLMEvent, ) from kiro_crew.recovery.ladder import InfraError @@ -55,6 +62,8 @@ # A credential-shaped string the agent's own reply carries; it must be stored redacted. _SECRET = github_classic(seed=316) _ORIGIN = {"kind": "agent"} +# The first row the turn writes opens it. +_OPENER = {"kind": "agent", "turn_start": True} def _text(text: str) -> LLMEvent: @@ -124,7 +133,7 @@ async def test_the_turn_shows_its_permission_card_and_its_reply_on_its_own_row(t [reply] = _rows(slot, "assistant") assert "The background build finished." in reply["content"] assert _SECRET not in reply["content"] - assert reply["meta"]["origin"] == _ORIGIN + assert reply["meta"]["origin"] == _OPENER # The permission card rendered as on a user turn. assert any(m.get("role") == "permission" for m in slot.messages) @@ -147,7 +156,7 @@ async def test_the_next_user_bubble_holds_only_its_own_reply(tmp_path): agent_reply, user_reply = _rows(slot, "assistant") assert agent_reply["content"] == "it finished, output: done" - assert agent_reply["meta"]["origin"] == _ORIGIN + assert agent_reply["meta"]["origin"] == _OPENER assert user_reply["content"] == "All quiet." assert "origin" not in (user_reply.get("meta") or {}) @@ -497,6 +506,112 @@ def test_a_session_another_provider_serves_registers_no_watch(): assert client.watch_agent_turns.call_args_list == [] +# ── the row that opens the turn ── + + +def _tool_call() -> LLMEvent: + return LLMEvent( + kind=EVENT_TOOL_CALL, tool_call_id="tc-1", title="Read the build log", tool_kind="read" + ) + + +def _saved(state, slot) -> list[dict]: + return state.conversation_log.read_messages(slot_history_key(slot)) + + +@pytest.mark.asyncio +async def test_a_turn_of_only_tool_rows_is_marked_on_its_first_row(tmp_path): + state, client = _make_state(tmp_path) + slot = _make_slot() + _agent_turn_client(state, client, [_tool_call(), _complete_event()]) + + with _patch_stats(): + await _run_agent_turn(state, slot) + + assert _rows(slot, "assistant") == [] + [tool] = _rows(slot, "tool") + assert tool["meta"]["origin"] == _OPENER + [saved_tool] = [m for m in _saved(state, slot) if m.get("role") == "tool"] + assert saved_tool["meta"]["origin"] == _OPENER + # Spent on that row: a row written after the turn is not the turn's. + slot.append("notice", "the session went idle") + assert "origin" not in (slot.messages[-1].get("meta") or {}) + + +@pytest.mark.asyncio +async def test_only_the_turns_first_row_opens_it_and_its_reply_is_in_the_resume_replay(tmp_path): + state, client = _make_state(tmp_path) + slot = _make_slot() + _agent_turn_client( + state, + client, + [_text("Checking the log."), _tool_call(), _text("The build passed."), _complete_event()], + ) + + with _patch_stats(): + await _run_agent_turn(state, slot) + + durable = [m for m in slot.messages if m.get("role") in ("assistant", "tool")] + assert durable[0]["meta"]["origin"] == _OPENER + assert [m["meta"].get("origin") for m in durable[1:] if m["role"] == "assistant"] == [_ORIGIN] + assert ( + sum(bool((m.get("meta") or {}).get("origin", {}).get("turn_start")) for m in slot.messages) + == 1 + ) + assert _saved(state, slot)[0]["meta"]["origin"] == _OPENER + replay = build_session_replay(state.conversation_log, slot_history_key(slot)) + assert replay is not None and "The build passed." in replay + + +@pytest.mark.asyncio +async def test_a_turn_that_wrote_no_row_leaves_no_opener_for_a_later_row(tmp_path): + state, client = _make_state(tmp_path) + slot = _make_slot() + _agent_turn_client(state, client, [_complete_event()]) + + with _patch_stats(): + await _run_agent_turn(state, slot) + + assert slot._owed_turn_opener is None + slot.append("notice", "a cron job ran") + assert "origin" not in (slot.messages[-1].get("meta") or {}) + + +def test_the_first_durable_row_the_turn_writes_takes_the_opener(): + slot = _make_slot() + slot._owed_turn_opener = agent_turn_opener_meta + slot.append("chunk", "partial text") + slot.append("user", "a message relayed meanwhile") + # A permission row pays the segment cut it owes first, so the cut's row is the first. + slot._owed_segment_cut = lambda: slot.append( + "assistant", "Before the card.", meta={"origin": _ORIGIN} + ) + slot.append("permission", "fs_write", meta={"request_id": "req-1"}) + + origins = [(m["role"], (m.get("meta") or {}).get("origin")) for m in slot.messages] + assert origins == [ + ("chunk", None), + ("user", None), + ("assistant", _OPENER), + ("permission", None), + ] + assert slot._owed_turn_opener is None + + +@pytest.mark.parametrize("transient", ["permission", "elicitation"]) +def test_a_card_first_turn_leaves_the_opener_for_the_first_saved_row(transient): + # A card row is never saved and a refresh rebuilds its meta, so it cannot + # hold the turn's boundary: the tool row after it takes the opener. + slot = _make_slot() + slot._owed_turn_opener = agent_turn_opener_meta + slot.append(transient, "fs_write", meta={"request_id": "req-1"}) + slot.append("tool", "🔧 fs_write", meta={"origin": _ORIGIN}) + + origins = [(m["role"], (m.get("meta") or {}).get("origin")) for m in slot.messages] + assert origins == [(transient, None), ("tool", _OPENER)] + assert slot._owed_turn_opener is None + + # ── Regenerate never re-runs a prompt over a reply the agent started ── @@ -508,6 +623,8 @@ def test_a_session_another_provider_serves_registers_no_watch(): [("user", "Q", None), ("assistant", "A", None), ("assistant", "B", {"origin": _ORIGIN})], # A prompted reply follows it: the prompt queued behind the agent's turn. [("user", "Q", None), ("assistant", "B", {"origin": _ORIGIN}), ("assistant", "A", None)], + # The agent's turn wrote only a tool row, which opens it. + [("user", "Q", None), ("assistant", "A", None), ("tool", "🔧 Read", {"origin": _OPENER})], ], ) async def test_regenerate_refuses_a_span_holding_a_reply_the_agent_started(state, rows) -> None: @@ -666,7 +783,8 @@ async def test_a_request_wait_in_the_hand_off_window_does_not_leave_the_turn_emp [reply] = _rows(slot, "assistant") assert "The background build finished." in reply["content"] - assert reply["meta"]["origin"] == _ORIGIN + # The reply is the turn's only row, so it is also its opener. + assert reply["meta"]["origin"] == _OPENER await async_wait_until(lambda: client._stdout_claims == 0) await client._stop_idle_reader() diff --git a/test/test_state_parts_facade.py b/test/test_state_parts_facade.py index 1caa36b13bda..a45d57664e00 100644 --- a/test/test_state_parts_facade.py +++ b/test/test_state_parts_facade.py @@ -569,6 +569,7 @@ "_on_row": ("value", "None"), "_origin": ("value", "''"), "_owed_segment_cut": ("value", "None"), + "_owed_turn_opener": ("value", "None"), "_pending": ("value", "[]"), "_pending_consumers": ("value", "0"), "_pending_context": ("value", "[]"), diff --git a/website/capture/agent-started-reply.html b/website/capture/agent-started-reply.html new file mode 100644 index 000000000000..2481a5c6b782 --- /dev/null +++ b/website/capture/agent-started-reply.html @@ -0,0 +1,12 @@ + + + + + + agent-started reply + + +
+ + + diff --git a/website/capture/agent-started-reply.tsx b/website/capture/agent-started-reply.tsx new file mode 100644 index 000000000000..01875dd408d5 --- /dev/null +++ b/website/capture/agent-started-reply.tsx @@ -0,0 +1,99 @@ +/** + * Isolated capture entry for a turn the agent started on its own + * (#17566, docs/request-for-change/rfc-agent-started-turns.md). + * + * Renders the shared ChatPane transcript against the real stylesheet, theme tokens + * and i18n catalog, for the repro: a background command, then the turn the agent + * starts when it finishes, then the person's next message. + * - after (default): the agent's turn is its own group, headed by its label. + * - before: the same rows as main marks them, so the agent's tool row and reply + * fold into the turn above them, unlabelled. + * - tool-only: the agent's turn wrote only a tool row. + * + * Query: ?state=after|before|tool-only ?theme=dark|light + */ +import { createRoot } from 'react-dom/client' +import { Provider } from 'react-redux' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { MemoryRouter } from 'react-router-dom' + +import ChatPane from '../src/components/ChatPane' +import { ThemeProvider } from '../src/hooks/useTheme' +import { initI18n } from '../src/i18n/all' +import { store } from '../src/store' +import { sseSlots } from '../src/store/dashboardSlice' +import { hydrateSlotMessages } from '../src/store/chatSlice' +import '../src/index.css' + +const params = new URLSearchParams(location.search) +const state = params.get('state') || 'after' +const theme = params.get('theme') || 'dark' +localStorage.setItem('mc-theme', theme === 'light' ? 'light' : 'dark') +document.documentElement.setAttribute('data-theme', theme === 'light' ? 'kiro-light' : 'kiro-dark') + +const SLOT = 'chat-1-agent-started' +const ASK = 'Run `sleep 60; echo done` in the background and tell me when it finishes.' +const STARTED = 'Started it in the background. I will report back when it finishes.' +const FINISHED = 'The background command finished with exit code 0 and printed `done`.' +const STATUS = 'Nothing else is running.' +const TOOL = { role: 'tool', content: '🔧 Read background task output', meta: { kind: 'read' } } + +const opening = [ + { role: 'user', content: ASK, ts: '2026-10-30T18:00:00Z' }, + { role: 'assistant', content: STARTED, ts: '2026-10-30T18:00:04Z', meta: { turn_stats: { elapsed_ms: 4100, cost_usd: 0.0112 } } }, +] +// The rows main writes mark the agent's reply only; this change also marks the +// turn's first row, which opens its group. +const AGENT = { kind: 'agent' } +const OPENER = { kind: 'agent', turn_start: true } +const agentTool = { ...TOOL, ts: '2026-10-30T18:01:05Z', meta: { ...TOOL.meta, ...(state === 'before' ? {} : { origin: OPENER }) } } +const agentReply = { + role: 'assistant', + content: FINISHED, + ts: '2026-10-30T18:01:07Z', + meta: { origin: AGENT, turn_stats: { elapsed_ms: 2600, cost_usd: 0.0094 } }, +} +const messages = [ + ...opening, + agentTool, + ...(state === 'tool-only' ? [] : [agentReply]), + { role: 'user', content: 'status?', ts: '2026-10-30T18:04:10Z' }, + { role: 'assistant', content: STATUS, ts: '2026-10-30T18:04:12Z', meta: { turn_stats: { elapsed_ms: 2100, cost_usd: 0.0078 } } }, +] + +const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + +async function mount() { + // The transcript read answers with the same rows the store is seeded with. + const realFetch = window.fetch.bind(window) + window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url + if (new URL(url, location.origin).pathname === `/api/chat/slots/${SLOT}`) { + const body = { title: 'background job', running: false, messages, total: messages.length } + return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } }) + } + return realFetch(input, init) + } + store.dispatch(sseSlots([{ key: SLOT, title: 'background job', messages: messages.length, running: false }] as never)) + store.dispatch( + hydrateSlotMessages({ slot: SLOT, messages, hasMore: false, total: messages.length, running: false } as never), + ) + await initI18n() + createRoot(document.getElementById('root')!).render( + + + + +
+
+ +
+
+
+
+
+
, + ) +} + +void mount() diff --git a/website/scripts/capture-17566-agent-started-reply.mjs b/website/scripts/capture-17566-agent-started-reply.mjs new file mode 100644 index 000000000000..9523f7129474 --- /dev/null +++ b/website/scripts/capture-17566-agent-started-reply.mjs @@ -0,0 +1,65 @@ +/** + * Screenshot harness: a turn the agent started on its own, in the chat pane, + * before (main) and after, light and dark, plus a turn that wrote only a tool + * row. Prints how many "Started by the agent" labels each frame draws and, + * where it should draw one, whether it sits above the turn's tool-call toggle, + * so the frame and the check come from the same render. + * + * Gateway-free: an in-process vite dev server serves the build-excluded capture + * entry (capture/agent-started-reply.html). + * + * Usage: node scripts/capture-17566-agent-started-reply.mjs [outDir] + */ +import { chromium } from 'playwright' +import { mkdirSync } from 'node:fs' +import { createServer } from 'vite' +import { chromiumExecutable } from './lib/chromium-executable.mjs' + +const OUT = process.argv[2] || 'temp-screenshots/17566-agent-started-reply' +mkdirSync(OUT, { recursive: true }) + +const vite = await createServer({ + configFile: new URL('../vite.config.ts', import.meta.url).pathname, + server: { port: 0, host: '127.0.0.1' }, + logLevel: 'error', +}) +await vite.listen() +const BASE = `http://127.0.0.1:${vite.httpServer.address().port}` +const browser = await chromium.launch({ executablePath: chromiumExecutable() }) + +let failed = false +try { + for (const state of ['after', 'before', 'tool-only']) { + for (const theme of ['light', 'dark']) { + // Tall enough that neither state scrolls: a scrolled pane pins the prompt and fades the top row. + const context = await browser.newContext({ deviceScaleFactor: 2, viewport: { width: 820, height: 1000 } }) + const page = await context.newPage() + page.on('pageerror', e => { console.log(`FAIL pageerror: ${e.message}`); failed = true }) + await page.goto(`${BASE}/capture/agent-started-reply.html?state=${state}&theme=${theme}`, { waitUntil: 'domcontentloaded' }) + await page.waitForSelector('[data-role="assistant"]', { timeout: 60_000 }) + await page.evaluate(() => document.fonts.ready) + await page.waitForTimeout(1500) + const m = await page.evaluate(() => { + const labels = [...document.querySelectorAll('[data-testid="agent-started-label"]')] + const toggle = [...document.querySelectorAll('button[aria-expanded]')].find(b => /tool call/i.test(b.textContent ?? '')) + const top = el => (el ? Math.round(el.getBoundingClientRect().top) : null) + return { labels: labels.length, labelTop: top(labels[0]), toggleTop: top(toggle) } + }) + const headed = m.labelTop !== null && m.toggleTop !== null && m.labelTop < m.toggleTop + const labelled = state !== 'before' + console.log(`${state} ${theme}: labels=${m.labels} label y=${m.labelTop} tool-call toggle y=${m.toggleTop}${labelled ? ` | ${headed ? 'label heads the turn' : 'LABEL NOT ABOVE THE TOOL ROWS'}` : ''}`) + if (labelled ? m.labels !== 1 || !headed : m.labels !== 0) failed = true + // The transcript only: the composer's banners are a capture without a gateway behind it. + const root = await page.locator('[data-capture-root]').boundingBox() + const last = await page.locator('[data-role="assistant"]').last().boundingBox() + const clip = { x: root.x, y: root.y, width: root.width, height: last.y + last.height + 24 - root.y } + await page.screenshot({ path: `${OUT}/${state}-${theme}.png`, clip }) + console.log(`wrote ${OUT}/${state}-${theme}.png`) + await context.close() + } + } +} finally { + await browser.close() + await vite.close() +} +process.exit(failed ? 1 : 0) diff --git a/website/src/app-sdk/ChatMessageList.tsx b/website/src/app-sdk/ChatMessageList.tsx index a85f78a5e390..581453ca7ef9 100644 --- a/website/src/app-sdk/ChatMessageList.tsx +++ b/website/src/app-sdk/ChatMessageList.tsx @@ -24,7 +24,7 @@ import { createTranscriptVersioner } from '../chat-core/transcript/transcriptVer import { useLanguageGeneration } from '../i18n/useLanguageGeneration' import CollapsibleToolGroup from '../pages/chat/CollapsibleToolGroup' import TurnBlock from '../pages/chat/TurnBlock' -import { createDisplayItemReconciler, hasToolStep, isSynthesisInjection, opensDisplayTurn, REASONING_ROLES } from '../pages/chat/groupDisplayItems' +import { createDisplayItemReconciler, hasToolStep, isSynthesisInjection, itemOpensAgentTurn, opensAgentTurn, opensDisplayTurn, REASONING_ROLES } from '../pages/chat/groupDisplayItems' import { isSubagentCompletionMessage } from '../pages/chat/subagentCompletion' import { isHiddenSupersededSteer } from '../pages/chat/groupDisplayItems' import { @@ -275,6 +275,8 @@ const ChatMessageList = memo(forwardRef { if (!turnItems.length) return - // A tool call wraps at any length, so a one-tool turn folds (#23017). - if (hasToolStep(turnItems) || (hasWorkingSteps(turnItems) && turnItems.length > 2)) { + // A tool call wraps at any length, so a one-tool turn folds (#23017). A + // turn the agent started wraps at any length too, so TurnBlock heads it. + if (agentTurnOpen) { + turns.push({ kind: 'turn', items: turnItems, complete, agentStarted: true }) + } else if (hasToolStep(turnItems) || (hasWorkingSteps(turnItems) && turnItems.length > 2)) { turns.push({ kind: 'turn', items: turnItems, complete }) } else { turns.push(...turnItems) } turnItems = [] + agentTurnOpen = false } for (const item of raw) { @@ -321,6 +329,11 @@ const ChatMessageList = memo(forwardRef) items.forEach((it, i) => { const k = rowKey(i) if (i === fold.first) { @@ -776,6 +778,18 @@ function CollapseToggle({ expanded, onToggle, label }: { expanded: boolean; onTo ) } +/** The mark on a turn the agent started on its own, with no prompt above it. */ +function AgentStartedLabel() { + return ( +
+ + +
+ ) +} + // Memoized so settled turns bail out entirely when the grouping's structural // sharing (createTurnGrouper) hands back identical `turn` references across // streaming flushes. The bail-out only holds when the host also passes stable diff --git a/website/src/pages/chat/groupDisplayItems.ts b/website/src/pages/chat/groupDisplayItems.ts index bfff5a17e999..e35281fe15d2 100644 --- a/website/src/pages/chat/groupDisplayItems.ts +++ b/website/src/pages/chat/groupDisplayItems.ts @@ -198,6 +198,17 @@ export const isTurnEnd = (msg: ChatMessage): boolean => msg.role === 'assistant' && !!(msg.meta as Record | undefined)?.turn_stats +/** Whether *msg* is the first row of a turn the agent started on its own: its + * `meta.origin` is `{kind: 'agent', turn_start: true}` (`chat_turn/agent_started.py`). */ +export function opensAgentTurn(msg: ChatMessage | undefined): boolean { + const origin = (msg?.meta as Record | undefined)?.origin as Record | undefined + return typeof origin === 'object' && origin !== null && origin.kind === 'agent' && origin.turn_start === true +} + +/** Whether *item* begins with the first row of a turn the agent started (`opensAgentTurn`). */ +export const itemOpensAgentTurn = (item: TurnItem): boolean => + opensAgentTurn(item.kind === 'single' ? item.msg : item.msgs[0]) + /** A `recovery` inject: the runner resuming the SAME turn after it ended * abnormally (`build_recovery_requeue`), not a prompt of its own. */ export const isRecoveryInjection = (msg: ChatMessage): boolean => @@ -346,20 +357,28 @@ export function groupDisplayItems(messages: ChatMessage[]): GroupedTurns { // Phase 1: build raw items (singles + groups) const raw: TurnItem[] = [] let group: ChatMessage[] = [], groupStart = 0 + // A skipped row that opened an agent-started turn hands that to the next shown row. + const carriedOpeners = new Set() + let carryOpener = false for (let i = 0; i < messages.length; i++) { // Permission messages handled by pinned ApprovalBar — skip entirely - if (messages[i].role === 'permission') continue + if (messages[i].role === 'permission') { carryOpener ||= opensAgentTurn(messages[i]); continue } // A sub-agent completion the card cannot parse stays internal: the LLM sees // it, the user does not. One it CAN parse renders as a compact outcome row, // which is the only scrollback record that a wave's results arrived. - if (messages[i].role === 'subagent' && !isSubagentCompletionMessage(messages[i])) continue - if (isHiddenSupersededSteer(messages, i)) continue + if (messages[i].role === 'subagent' && !isSubagentCompletionMessage(messages[i])) { + carryOpener ||= opensAgentTurn(messages[i]) + continue + } + if (isHiddenSupersededSteer(messages, i)) { carryOpener ||= opensAgentTurn(messages[i]); continue } if (GROUPABLE.has(messages[i].role)) { if (!group.length) groupStart = i group.push(messages[i]) } else { if (group.length) { raw.push({ kind: 'group', msgs: group, startIdx: groupStart }); group = [] } - raw.push({ kind: 'single', msg: messages[i], idx: i }) + const item: TurnItem = { kind: 'single', msg: messages[i], idx: i } + if (carryOpener) { carriedOpeners.add(item); carryOpener = false } + raw.push(item) } } if (group.length) raw.push({ kind: 'group', msgs: group, startIdx: groupStart }) @@ -381,6 +400,8 @@ export function groupDisplayItems(messages: ChatMessage[]): GroupedTurns { // ANSWER, which `settlePendingSynthesisAnswer` below splits off before any // later fold can reach it. let pendingSynthesisAnswer = false + // Set while the open batch is a turn the agent started on its own. + let agentTurnOpen = false const hasWorkingSteps = (items: TurnItem[]) => items.some(t => (t.kind === 'single' && (t.msg.role === 'tool' || t.msg.role === 'assistant' || t.msg.role === 'streaming')) || @@ -410,8 +431,12 @@ export function groupDisplayItems(messages: ChatMessage[]): GroupedTurns { // spread a one-tool turn (tool + answer) loose, so it never got the // "1 tool call" fold a two-tool turn gets. Assistant-only batches keep the // length rule: a lone answer has no step to fold and must stay loose. - const flushTurn = (items: TurnItem[], complete: boolean) => { - if (hasToolStep(items) || (hasWorkingSteps(items) && items.length > 2) || contentThinkingCount(items) >= 2) { + // A turn the agent started wraps at any length too, so TurnBlock heads it with + // its label even when it holds a single row. + const flushTurn = (items: TurnItem[], complete: boolean, agentStarted = false) => { + if (agentStarted) { + turns.push({ kind: 'turn', items, complete, agentStarted: true }) + } else if (hasToolStep(items) || (hasWorkingSteps(items) && items.length > 2) || contentThinkingCount(items) >= 2) { turns.push({ kind: 'turn', items, complete }) } else { turns.push(...items) @@ -467,7 +492,8 @@ export function groupDisplayItems(messages: ChatMessage[]): GroupedTurns { // A previous synthesis in this same user turn left its answer inside the // open batch; get it out before the fold below runs. settlePendingSynthesisAnswer() - if (turnItems.length > 0) { flushTurn(turnItems, true); turnItems = [] } + if (turnItems.length > 0) { flushTurn(turnItems, true, agentTurnOpen); turnItems = [] } + agentTurnOpen = false if (!regionHasForeign) foldInterimRegion(turns, regionStart) // The synthesis row leads the turn that carries the answer, so it opens // the next batch rather than joining the region behind it. @@ -501,7 +527,8 @@ export function groupDisplayItems(messages: ChatMessage[]): GroupedTurns { // is flushed into the region a later synthesis folds, and that synthesis // then reads the next wave's own reply as the answer boundary. settlePendingSynthesisAnswer() - if (turnItems.length > 0) { flushTurn(turnItems, true); turnItems = [] } + if (turnItems.length > 0) { flushTurn(turnItems, true, agentTurnOpen); turnItems = [] } + agentTurnOpen = false turns.push(item) // A user/nudge prompt begins a fresh interim region; a sub-agent // completion belongs to the one already open. @@ -520,6 +547,13 @@ export function groupDisplayItems(messages: ChatMessage[]): GroupedTurns { } continue } + // A turn the agent started on its own has no prompt row; its first row opens + // it instead, so the rows before that row stay with the turn they belong to. + if (carriedOpeners.has(item) || itemOpensAgentTurn(item)) { + settlePendingSynthesisAnswer() + if (turnItems.length > 0) { flushTurn(turnItems, true, agentTurnOpen); turnItems = [] } + agentTurnOpen = true + } turnItems.push(item) } // Flush the trailing group as complete, and remember whether that flush @@ -529,7 +563,7 @@ export function groupDisplayItems(messages: ChatMessage[]): GroupedTurns { let trailingTurnIdx = -1 if (turnItems.length > 0) { const before = turns.length - flushTurn(turnItems, true) + flushTurn(turnItems, true, agentTurnOpen) const last = turns[turns.length - 1] if (turns.length === before + 1 && last && last.kind === 'turn') { trailingTurnIdx = turns.length - 1 @@ -564,6 +598,7 @@ const sameDisplayItem = (a: DisplayItem, b: DisplayItem): boolean => { // list (the presence of a synthesis row), so it must be compared or the // substitution below would freeze a turn at a stale fold state. if (!!a.interim !== !!b.interim) return false + if (!!a.agentStarted !== !!b.agentStarted) return false for (let i = 0; i < a.items.length; i++) if (!sameTurnItem(a.items[i], b.items[i])) return false return true } diff --git a/website/src/pages/chat/types.ts b/website/src/pages/chat/types.ts index 25a4f42fc6aa..7c71980b5f4d 100644 --- a/website/src/pages/chat/types.ts +++ b/website/src/pages/chat/types.ts @@ -37,4 +37,12 @@ export type DisplayItem = * per-completion summaries that say the same thing. */ interim?: boolean + /** + * This turn is one the agent started on its own: it begins at the row + * that opens it (`opensAgentTurn`) and runs to the next prompt or the + * next such row. Set by `groupDisplayItems` (and app-sdk + * `ChatMessageList`), and read by TurnBlock, which heads the turn with + * the "Started by the agent" label. + */ + agentStarted?: boolean } diff --git a/website/src/test/TurnBlock.agentStarted.test.tsx b/website/src/test/TurnBlock.agentStarted.test.tsx new file mode 100644 index 000000000000..3b0cbf2510cf --- /dev/null +++ b/website/src/test/TurnBlock.agentStarted.test.tsx @@ -0,0 +1,116 @@ +/** + * A turn the agent started on its own is headed by ONE "Started by the agent" + * label, above its tool-call toggle, its tool rows and its reply, in the chat + * page's turn and in the app-sdk pane alike, including a turn that wrote only + * tool rows and a turn that is a lone reply. + */ +import { describe, it, expect, vi } from 'vitest' +import { render, screen, fireEvent } from '@testing-library/react' +import type { ReactNode } from 'react' +import TurnBlock from '../pages/chat/TurnBlock' +import ChatMessageList from '../app-sdk/ChatMessageList' +import { groupDisplayItems, applyRunningState } from '../pages/chat/groupDisplayItems' +import type { DisplayItem, TurnItem } from '../pages/chat/types' +import type { ChatMessage } from '../types' + +vi.mock('../components/MarkdownRenderer', () => ({ + default: ({ content }: { content: string }) =>
{content}
, +})) +vi.mock('../hooks/useSmoothStream', () => ({ + useSmoothStream: (content: string) => content, +})) + +let seq = 0 +const at = () => `2026-11-05T10:00:${String(++seq).padStart(2, '0')}Z` +const OPENER = { kind: 'agent', turn_start: true } +const prompt = (): ChatMessage[] => [ + { role: 'user', content: 'run the build in the background', cls: '', ts: at() }, + { role: 'assistant', content: 'Started it.', cls: '', ts: at(), meta: { turn_stats: { elapsed_ms: 1000 } } }, +] +const toolRow = (meta: Record = {}): ChatMessage => + ({ role: 'tool', content: '🔧 Read the build log', cls: '', ts: at(), meta: { kind: 'read', ...meta } }) as ChatMessage +const reply = (origin: Record): ChatMessage => + ({ role: 'assistant', content: 'The build passed.', cls: '', ts: at(), meta: { turn_stats: { elapsed_ms: 1000 }, origin } }) as ChatMessage + +const withToolAndReply = (): ChatMessage[] => { seq = 0; return [...prompt(), toolRow({ origin: OPENER }), reply({ kind: 'agent' })] } +const toolOnly = (): ChatMessage[] => { seq = 0; return [...prompt(), toolRow({ origin: OPENER })] } +const loneReply = (): ChatMessage[] => { seq = 0; return [...prompt(), reply(OPENER)] } + +/** The rendered order of the label, the tool-call toggle, the tool row and the agent's reply. */ +function order(): string[] { + const marks = [ + ...screen.queryAllByTestId('agent-started-label').map(el => ['label', el] as const), + ...screen.queryAllByRole('button', { name: /tool call/i }).map(el => ['toggle', el] as const), + ...screen.queryAllByText(/Read the build log/).map(el => ['tool', el] as const), + ...screen.queryAllByText('The build passed.').map(el => ['reply', el] as const), + ] + marks.sort(([, a], [, b]) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)) + return marks.map(([name]) => name) +} + +const renderItem = (it: TurnItem): ReactNode => + it.kind === 'single' ?
{it.msg.content}
: null + +function renderAgentTurn(messages: ChatMessage[]) { + const items = applyRunningState(groupDisplayItems(messages), false) + const turn = items.find((d): d is Extract => d.kind === 'turn' && !!d.agentStarted) + expect(turn).toBeTruthy() + render() +} + +const openFold = () => fireEvent.click(screen.getByRole('button', { name: /tool call/i })) + +describe('the chat page heads a turn the agent started with one label', () => { + it('above its tool rows and its reply, fold closed and open', () => { + renderAgentTurn(withToolAndReply()) + + expect(order()).toEqual(['label', 'toggle', 'reply']) + openFold() + expect(order()).toEqual(['label', 'toggle', 'tool', 'reply']) + }) + + it('above a turn that wrote only tool rows', () => { + renderAgentTurn(toolOnly()) + + expect(order()).toEqual(['label', 'toggle']) + openFold() + expect(order()).toEqual(['label', 'toggle', 'tool']) + }) + + it('above a lone reply', () => { + renderAgentTurn(loneReply()) + + expect(order()).toEqual(['label', 'reply']) + }) +}) + +describe('the app-sdk pane heads a turn the agent started with one label', () => { + it('above its tool rows and its reply, and not above the prompted turn before it', () => { + render() + + expect(screen.getByText('Started it.').compareDocumentPosition(screen.getByTestId('agent-started-label')) + & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(order()).toEqual(['label', 'toggle', 'reply']) + openFold() + expect(order()).toEqual(['label', 'toggle', 'tool', 'reply']) + }) + + it('above a turn that wrote only tool rows', () => { + render() + + expect(order()).toEqual(['label', 'toggle']) + }) + + it('above a lone reply', () => { + render() + + expect(order()).toEqual(['label', 'reply']) + }) + + it('draws no label on a prompted turn', () => { + seq = 0 + render() + + expect(screen.queryByTestId('agent-started-label')).toBeNull() + }) +}) diff --git a/website/src/test/groupDisplayItems.test.ts b/website/src/test/groupDisplayItems.test.ts index 590777803ee5..19d2bc122fa5 100644 --- a/website/src/test/groupDisplayItems.test.ts +++ b/website/src/test/groupDisplayItems.test.ts @@ -866,3 +866,102 @@ describe('superseded steer rows', () => { expect(drawnContents(groupDisplayItems(rows).turns, 'nudge')).toEqual([WAKE, WAKE]) }) }) + +describe('groupDisplayItems: a turn the agent started on its own', () => { + const withMeta = (role: string, content: string, meta: Record): ChatMessage => + ({ role, content, cls: '', meta } as unknown as ChatMessage) + const ended = (content: string): ChatMessage => withMeta('assistant', content, { turn_stats: { elapsed_ms: 1000 } }) + /** The first row the agent's turn wrote, whatever its role. */ + const opener = (role: string, content: string, meta: Record = {}): ChatMessage => + withMeta(role, content, { ...meta, origin: { kind: 'agent', turn_start: true } }) + /** A later reply of that turn: marked as the agent's, but not its opener. */ + const agentReply = (content: string): ChatMessage => + withMeta('assistant', content, { origin: { kind: 'agent' }, turn_stats: { elapsed_ms: 1000 } }) + const contents = (d: DisplayItem): string[] => + d.kind === 'turn' + ? d.items.flatMap(t => (t.kind === 'single' ? [t.msg.content] : t.msgs.map(m => m.content))) + : d.kind === 'single' ? [d.msg.content] : d.msgs.map(m => m.content) + const agentTurns = (turns: DisplayItem[]) => turns.filter(d => d.kind === 'turn' && d.agentStarted).map(contents) + + it('groups the agent turn on its own, from its first row to the next prompt', () => { + const { turns } = groupDisplayItems([ + msg('user', 'run the build in the background'), + ended('started it'), + opener('tool', 'read the build log'), + agentReply('the build passed'), + msg('user', 'status?'), + ended('all quiet'), + ]) + + expect(turns.map(contents)).toEqual([ + ['run the build in the background'], + ['started it'], + ['read the build log', 'the build passed'], + ['status?'], + ['all quiet'], + ]) + expect(turns.map(d => d.kind === 'turn' && !!d.agentStarted)).toEqual([false, false, true, false, false]) + }) + + it('wraps a turn that wrote only tool rows, and a lone reply, so either can be headed', () => { + const toolOnly = groupDisplayItems([msg('user', 'u'), ended('a'), opener('tool', 'started another job')]) + expect(agentTurns(toolOnly.turns)).toEqual([['started another job']]) + + const lone = groupDisplayItems([msg('user', 'u'), ended('a'), opener('assistant', 'it finished', { turn_stats: {} })]) + expect(agentTurns(lone.turns)).toEqual([['it finished']]) + }) + + it('leaves the rows before the opener with the turn they belong to, even with no end marker', () => { + // The user's turn ran a tool and wrote no closing reply, so it left no footer row. + const { turns } = groupDisplayItems([ + msg('user', 'u'), + msg('tool', 'user tool'), + opener('assistant', 'agent reply', { turn_stats: {} }), + ]) + + expect(turns.map(contents)).toEqual([['u'], ['user tool'], ['agent reply']]) + expect(agentTurns(turns)).toEqual([['agent reply']]) + }) + + it('starts a second agent turn at its own first row', () => { + const { turns } = groupDisplayItems([ + msg('user', 'u'), + ended('a'), + opener('tool', 'first job'), + opener('tool', 'second job'), + agentReply('both done'), + ]) + + expect(agentTurns(turns)).toEqual([['first job'], ['second job', 'both done']]) + }) + + it('opens the turn at the next shown row when its first row is a permission card', () => { + // The chat page shows permission requests in the approval bar, not as rows. + const { turns } = groupDisplayItems([ + msg('user', 'u'), + ended('a'), + opener('permission', 'fs_write'), + msg('tool', 'write the file'), + agentReply('wrote it'), + ]) + + expect(agentTurns(turns)).toEqual([['write the file', 'wrote it']]) + expect(turns.map(contents)).toEqual([['u'], ['a'], ['write the file', 'wrote it']]) + }) + + it('leaves an agent reply that carries no opener as it was', () => { + // A reply saved before turns were marked at their first row. + const { turns } = groupDisplayItems([msg('user', 'u'), ended('a'), msg('tool', 't'), agentReply('b')]) + + expect(agentTurns(turns)).toEqual([]) + expect(turns.map(contents)).toEqual([['u'], ['a', 't', 'b']]) + }) + + it('marks the running agent turn as the trailing turn', () => { + const grouped = groupDisplayItems([msg('user', 'u'), ended('a'), opener('tool', 'working')]) + const items = applyRunningState(grouped, true) + const last = items[items.length - 1] + + expect(last.kind === 'turn' && last.agentStarted && !last.complete).toBe(true) + }) +})