## Summary While a turn is running, the page now sends the reader's next message into that turn instead of queueing it for a fresh turn after the answer. The backend already had the mechanism (`turn.send` with `busy: "inject"`, merged at the top of the loop's next iteration, before the model call); channels and the ACP steer path use it. What was missing sat in three layers: 1. `feat(agent)`: the injected messages reached the model as bare user messages, so a correction read like a fresh question. Each adjacent run of mid-turn arrivals is now folded, at the call seam only, into one user message under a bracketed "Mid-turn messages" header with the bodies joined by blank lines. History keeps one entry per message the reader sent, stamped with its arrival time; the merged message keeps the mid-turn mark the rerun seed relies on, and folding is idempotent so the prompt-cache prefix is stable. 2. `feat(rpc)`: an inject that merged emitted no event, and the persisted mark never reached the wire, so a reload drew the message as the question opening a new turn. A new `message.injected` event (the inject's own turn id and text, tagged for a direct chat) is emitted once the scheduler accepts it and enters the replay buffer; the stored mark becomes a plain `mid_turn` field on the transcript message. Both generated clients are regenerated. 3. `feat(ui-web)`: the busy branch of send calls `turn.send` with `busy: "inject"` and touches nothing on the runtime; the echo draws the bubble so every window shows the same one. The client queue stays as the fallback (an older gateway refusing the field, a lane gone idle in between, a dropped socket). On replay a `mid_turn` row draws inside its turn: no fold closed, no turn number spent, no narration promoted to an answer, no workspace turn counted. The two surfaces that enumerate the wire vocabulary exhaustively name the new event without forwarding it: the ACP update translator (the client's own steer request is already the record that it sent a message mid-turn) and the terminal's event switch (it queues its own follow-ups and draws no row for a message it did not send). A fifth commit covers the field and the event in the offline contract gates. The sixth commit, `fix(*)`, answers an adversarial pass over the served page. Live, the work a turn did after a mid-turn message was drawn above the bubble and the turn lost its fold and elapsed header (the fold, the merge of silent steps and the stop note all read the bubble as the start of a turn), while a reload drew it correctly; the bubble now carries a mid-turn mark on the live path too, runs are never merged across it, and the fold closes below it when work followed it and above it when none did. A message the host turn ended before draining runs as a turn of its own, and its bubble is now taken back from inside the ended turn and drawn where the new turn opens, below the earlier answer. The stored entry is stamped when the message reached the server (`TurnRequest.received_at`), not when the turn reached its next gap. The injected-files note names only paths the text does not already name, so a page send reads the same live and after a reload. A second message typed while a brand-new conversation is still being made is queued rather than sent with no session key, and `turn.send` answers a malformed request with `-32602 invalid_params` (new `InvalidParamsError`) instead of an internal error with a traceback. Stated limits, unchanged in this PR: a mid-turn message sent while the turn waits on an approval or question merges after the reader answers it; a mid-turn attachment still reaches the model as a text note rather than an image block; Stop with an undrained inject lets that message run as its own turn (pinned by a test); the TUI's `steer` mode and the sub-agent direct-chat composer keep their current behaviour. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification - `uv run pytest tests/test_agent_loop_run_emit.py tests/test_rpc_turn_send.py tests/test_rpc_turn_cancel.py tests/test_agent_loop_mid_turn_merge.py tests/test_transcript_mid_turn.py tests/test_agent_loop_session_stamps.py tests/test_rpc_schema_match.py tests/test_rpc_registration.py -q` -- 546 passed; the new files again with an empty `HOME` -- 117 passed. Cases from the first five commits: two injects in one gap reach the second provider call as one labelled message with both bodies in order, one inject is labelled too, injects from different gaps stay apart; the merge is idempotent, keeps the mark, hands an unmarked list back unchanged and never labels replayed history; the mark is renamed for storage, reaches the wire and is declared in the schema; an accepted inject is announced once with its own turn id and no `message.start`, a direct-chat inject carries its target, a refused inject is announced to nobody, an undrained inject is announced once and opened once, a stop leaves an unmerged inject to run as its own turn. Sixth commit: the inject request carries `received_at`; the stored mid-turn row carries it rather than the drain clock, and keeps the drain clock when no arrival is given; an attachment the text already names is not named twice while one it does not name still is; a missing or null `session_key` and a missing `content` answer `-32602`. - `uv run pytest tests/ -q -k "rpc or spine or agent_loop or transcript or session_stamps or acp_updates"` -- 3681 passed. - `npm test --prefix ui-web -- src/state/session src/features/transcript src/features/workspace` -- the earlier cases plus: on the live path a turn [ask, step, mid-turn ask, step, answer] folds with its header below the bubble and the second step stays below it, the fallback shape [ask, step, mid-turn ask] folds above it, and `turnKept` is true above a mid-turn bubble; `message.injected` marks the bubble mid-turn, and a `message.start` with the same id re-files it once as the new turn's question however many windows announced it; a busy send during a draft's promotion queues and calls no `turn.send`. The live-path, re-file and promotion cases fail against the fifth commit's `store.ts`, `stages.ts`/`runtime.ts`. - `npm test --prefix ui-web` -- 190 files, 2483 tests passed, the contract gates included. - `uv run pytest tests/test_acp_updates.py -q` -- 196 passed (the vocabulary sweep names the new event; a mid-turn message produces no ACP update). - `uv run pytest tests/ -q` -- full suite green; `npm run type-check --prefix ui-tui`, `npm run type-check --prefix ui-web`, `npm run lint --prefix ui-web`, `npm run gen:check --prefix ui-web`, `npm run lint:rpc --prefix ui-tui`, `uv run ruff check raven tests` -- clean. - Served page, isolated agent home, a turn that sleeps in a shell tool, two messages typed while it runs: before the change both sit in the composer queue and go out as their own turns after the answer, and the provider payload carries no header; after the change both are drawn at once inside the running turn in the sending tab and in a second tab, the provider call made after the sends carries one user message with the header and both bodies, the session file holds two `mid_turn` entries stamped before the answer, and a reload draws them inside the one turn. Second pass, after the sixth commit: with two gaps the live transcript and the reload read in the same order (first command above the first bubble, second command inside the fold below it, the fold's elapsed header present), and the stored stamps are the send times; a message sent in the turn's last second opens its own card below the earlier answer, live and after a reload; Stop with a pending message leaves the bubble below the stop note, live and after a reload; a page send with an attachment shows the same text and chip live and after a reload. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [ ] User-facing docs or screenshots are updated when needed ## Risk - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes The header and the folding change what the model sees for mid-turn arrivals on every surface that injects (channels included); the folded shape is deterministic. The bubble depends on the websocket echo; an RPC refusal re-queues the text, a wedged socket already breaks every other event. `mid_turn` and `message.injected` are additive: older clients ignore the field and the event. A malformed `turn.send` now answers `-32602` where it answered `-32603`; the page treats both as a refusal. Rollback: revert the six commits in reverse order. ## Related Issues N/A --------- Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
96 lines
3.5 KiB
Python
96 lines
3.5 KiB
Python
"""A message merged into a running turn is marked as such in the transcript.
|
|
|
|
A live client draws it inside the turn it joined, off ``message.injected``. A
|
|
reload has only the stored entry to go on, and an unmarked user entry is a
|
|
question: the fold closed over the narration above it, the turn number moved,
|
|
and the sentence the model had just written was promoted to the answer of a turn
|
|
that had not finished. The mark is what keeps the two views the same.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from raven.agent.loop._shared import _MID_TURN_USER_KEY
|
|
from raven.rpc.methods.session import _map_to_wire
|
|
|
|
|
|
def _stored(**over):
|
|
entry = {"role": "user", "content": "only the last quarter", "timestamp": "2026-09-22T09:00:30"}
|
|
entry.update(over)
|
|
return entry
|
|
|
|
|
|
# ── the wire ──────────────────────────────────────────────────────
|
|
|
|
|
|
def test_a_stored_mark_reaches_the_wire() -> None:
|
|
"""`session.resume` copies a whitelist onto the wire entry; a field absent
|
|
from it is dropped however carefully it was written."""
|
|
[entry] = _map_to_wire([_stored(mid_turn=True)], "tui:default")
|
|
assert entry["mid_turn"] is True
|
|
|
|
|
|
def test_an_unmarked_entry_carries_no_mark() -> None:
|
|
[entry] = _map_to_wire([_stored()], "tui:default")
|
|
assert "mid_turn" not in entry
|
|
|
|
|
|
def test_the_text_still_rides() -> None:
|
|
"""It is a real user message; only where the reader draws it changes."""
|
|
[entry] = _map_to_wire([_stored(mid_turn=True)], "tui:default")
|
|
assert entry["text"] == "only the last quarter"
|
|
|
|
|
|
# ── the storage rename ────────────────────────────────────────────
|
|
|
|
|
|
def _loop():
|
|
from raven.agent.loop.main import AgentLoop
|
|
|
|
loop = object.__new__(AgentLoop)
|
|
loop._now_fn = lambda: __import__("datetime").datetime(2026, 9, 22, 10, 0)
|
|
return loop
|
|
|
|
|
|
class _Session:
|
|
def __init__(self):
|
|
self.entries = []
|
|
|
|
def record(self, entry):
|
|
self.entries.append(entry)
|
|
|
|
|
|
def test_the_private_key_is_renamed_for_storage() -> None:
|
|
"""Same underscore-then-rename convention as ``_origin``: the underscore
|
|
keeps it out of the live provider payload, storage gets the plain name."""
|
|
from raven.agent.loop.main import AgentLoop
|
|
|
|
session = _Session()
|
|
messages = [{"role": "user", "content": "only the last quarter", _MID_TURN_USER_KEY: True}]
|
|
AgentLoop._save_turn(_loop(), session, messages, 0)
|
|
|
|
[stored] = session.entries
|
|
assert stored["mid_turn"] is True
|
|
assert _MID_TURN_USER_KEY not in stored
|
|
|
|
|
|
def test_an_ordinary_question_stores_no_mark() -> None:
|
|
from raven.agent.loop.main import AgentLoop
|
|
|
|
session = _Session()
|
|
AgentLoop._save_turn(_loop(), session, [{"role": "user", "content": "summarise the report"}], 0)
|
|
assert "mid_turn" not in session.entries[0]
|
|
|
|
|
|
# ── the contract ──────────────────────────────────────────────────
|
|
|
|
|
|
def test_the_schema_declares_the_field() -> None:
|
|
"""The page's client is generated from this file, so a field the schema does
|
|
not name cannot be read by the reader that needs it."""
|
|
schema = json.loads((Path(__file__).resolve().parent.parent / "rpc-schema" / "openrpc.json").read_text())
|
|
props = schema["components"]["schemas"]["TranscriptMessage"]["properties"]
|
|
assert props["mid_turn"]["type"] == "boolean"
|