Skip to content

The agent that grows with you

feat(onboarding): a message sent past a setup card ends its turn and runs as the next one

alt-glitch4a23324a3954
diff --git a/agent/inline_tool_executors.py b/agent/inline_tool_executors.py
index 61be920327b..f7fac6f04e7 100644
--- a/agent/inline_tool_executors.py
+++ b/agent/inline_tool_executors.py
@@ -227,12 +227,16 @@ def _manage_catalog(agent, args: dict, ctx: InlineToolContext) -> Any:
def _setup_beat(agent, args: dict, ctx: InlineToolContext) -> Any:
- # The run record lives on the session row and the card callback on the agent.
+ # The run record lives on the session row and the card callback on the agent. A card the user wrote
+ # past ends the turn as a new message does: setup_beat runs inline (never parallel), so its result is
+ # kept and the loop stops before the next model call.
+ from agent.interrupt_control import _REASON_NEW_MESSAGE
from tools.setup_beat_tool import setup_beat_tool
return setup_beat_tool(
args, db=getattr(agent, "_session_db", None), session_id=getattr(agent, "session_id", None) or "",
tool_call_id=ctx.tool_call_id or "", callback=getattr(agent, "setup_beat_callback", None),
+ end_turn=lambda: agent.interrupt(tool_reason=_REASON_NEW_MESSAGE),
)
diff --git a/agent/onboarding_flow.py b/agent/onboarding_flow.py
index a2356e61faf..91d3b78796d 100644
--- a/agent/onboarding_flow.py
+++ b/agent/onboarding_flow.py
@@ -80,9 +80,11 @@ class Answered:
@dataclass(frozen=True)
-class Said:
+class Wrote:
+ """The user sent a message instead of answering the card. The message is their own next turn, so the
+ result carries none of it."""
+
beat: str
- text: str
present: Any = None
@@ -127,7 +129,7 @@ class Applied:
result: Mapping[str, Any]
-Event = Shown | Answered | Said | TimedOut | Recorded | Skipped | End | Done | Applied
+Event = Shown | Answered | Wrote | TimedOut | Recorded | Skipped | End | Done | Applied
@dataclass(frozen=True)
@@ -297,16 +299,16 @@ def _answered(record: dict, event: Answered, facts: Facts, now: float) -> Step:
BEAT_BY_ID[event.beat].after(record["picks"]))
-def _note_present(record: dict, event: Said | TimedOut | Recorded | Skipped) -> dict:
+def _note_present(record: dict, event: Wrote | TimedOut | Recorded | Skipped) -> dict:
"""Record the beat's picks as the machine has them now; returns them for the result."""
present = {key: value for key, value in (event.present or {}).items() if key in BEAT_BY_ID[event.beat].picks}
record["picks"].update(present)
return present
-def _said(record: dict, event: Said, facts: Facts, now: float) -> Step:
+def _wrote(record: dict, event: Wrote, facts: Facts, now: float) -> Step:
record["waiting"] = None
- return Step(record, {"beat": event.beat, "said": event.text, **_note_present(record, event)}, "said")
+ return Step(record, {"beat": event.beat, "wrote_instead": True, **_note_present(record, event)}, "wrote")
def _timed_out(record: dict, event: TimedOut, facts: Facts, now: float) -> Step:
@@ -389,7 +391,7 @@ def _applied(record: dict, event: Applied, facts: Facts, now: float) -> Step:
_HANDLERS: dict[type, Callable[[dict, Any, Facts, float], Step]] = {
- Shown: _shown, Answered: _answered, Said: _said, TimedOut: _timed_out, Recorded: _recorded,
+ Shown: _shown, Answered: _answered, Wrote: _wrote, TimedOut: _timed_out, Recorded: _recorded,
Skipped: _skipped, End: _end, Done: _done, Applied: _applied,
}
_ENDED = "Onboarding is over in this chat; it is a normal chat now."
diff --git a/agent/onboarding_text.py b/agent/onboarding_text.py
index 9db2348dbfe..164cd4a2095 100644
--- a/agent/onboarding_text.py
+++ b/agent/onboarding_text.py
@@ -73,7 +73,7 @@ How it works:
- setup_beat shows a beat's card and waits for the user. setup_beat(beat="next") shows the next beat. Its result carries their answer and a reminder of what to do next. Follow the reminder.
- Before a card, acknowledge in a few words and at most one more sentence. The card asks its own question and shows its own options: never ask it yourself, never list the options in text.
- After a pick, say it by its label in three words or fewer. No opinion, no praise, never the same words twice.
-- If they answer in words while a card waits, the card closes and you get their words. If the words answer the card, apply it yourself and move on. Otherwise answer them properly and briefly, then bring the card back in one line with setup_beat(beat=<that beat>). Never show a card again unless you are bringing it back.
+- If they write a message while a card waits, the card closes unanswered and their message comes as their next turn (words typed on the name card are the name). If the message answers the card, apply it yourself and move on. Otherwise answer it properly and briefly, then bring the card back in one line with setup_beat(beat=<that beat>). Never show a card again unless you are bringing it back.
- If they ask you to pick (a colour, a layout), pick from what you know and say why in one line.
- If they skip a beat in words, call setup_beat(beat=<that beat>, skip=true), take the default, and never ask it again in the same form. If they want to stop altogether, say in one line that the Skip setup button ends it, then carry on; only they can end it, with that button.
- Off-script requests are done now, then you bring the card back.
@@ -291,14 +291,14 @@ def _already(record, beat: str) -> str:
f"for a change. {_next(record)}")
-def _said(record, facts, beat: str) -> str:
- return (f"They typed this while the {beat} card waited; the card is closed. If their words answer it, apply it "
- f"yourself ({_TYPED_ANSWER[beat]}) and move on. Otherwise answer them properly and briefly, then bring "
- f'the card back in one line with setup_beat(beat="{beat}").')
+def _wrote(record, facts, beat: str) -> str:
+ # The turn ends on this result; the turn note on their message says how to go on.
+ return (f"The {beat} card closed unanswered: they wrote a message instead. It comes next as their own turn; "
+ "write nothing until it does.")
def _timed_out(record, facts, beat: str) -> str:
- # Also the result when they sent a file or a slash command while the card waited.
+ # Also the result when they ran a slash command while the card waited.
return (f"The {beat} card closed without an answer. If a message from them comes next, answer it first. "
f"Otherwise say one short line that they can pick up whenever they are back, then stop. When they "
f'return, bring it back with setup_beat(beat="{beat}").')
@@ -306,12 +306,12 @@ def _timed_out(record, facts, beat: str) -> str:
def reminder(key: str, record: Mapping[str, Any], facts: Facts, beat: str | None = None,
has_skill: Callable[[str], bool] = lambda name: True) -> str:
- """The text for a reminder key; ``beat`` names the card a ``said`` / ``timed_out`` result is about;
+ """The text for a reminder key; ``beat`` names the card a ``wrote`` / ``timed_out`` result is about;
``has_skill`` drops a first task's bundled skill missing on this install."""
if not key:
return ""
- if key in ("said", "timed_out"):
- return (_said if key == "said" else _timed_out)(record, facts, beat or _waiting_beat(record) or "build")
+ if key in ("wrote", "timed_out"):
+ return (_wrote if key == "wrote" else _timed_out)(record, facts, beat or _waiting_beat(record) or "build")
if key.startswith("build_"):
option = key.removeprefix("build_")
label = next((o["label"] for o in record["picks"].get("build_options") or () if o["id"] == option), "")
@@ -322,12 +322,14 @@ def reminder(key: str, record: Mapping[str, Any], facts: Facts, beat: str | None
def turn_note(record: Mapping[str, Any]) -> str:
- """The note on a user turn while no card waits: which card is closed and how to bring it back.
- Empty once every card is settled: the build is under way and nothing is left to reopen."""
+ """The note on a user turn while no card waits: which card is closed, how their message applies it
+ when it answers it, and how to bring it back. Empty once every card is settled: the build is under
+ way and nothing is left to reopen."""
if (beat := _waiting_beat(record)) is None:
return ""
- return (f"[System note: Onboarding continues; the {beat} card is closed. Answer their message first, then bring "
- f'the card back in one line with setup_beat(beat="{beat}").]')
+ return (f"[System note: Onboarding continues; the {beat} card is closed. If their message answers it, apply it "
+ f"yourself ({_TYPED_ANSWER[beat]}) and move on. Otherwise answer their message first, then bring the card "
+ f'back in one line with setup_beat(beat="{beat}").]')
def finish_reminder(record: Mapping[str, Any]) -> str:
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 1bb2fe27404..96582abe8d1 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4585,10 +4585,11 @@ export interface SetupConnectorsCard {
export interface SetupPluginsCard {
plugins: string[]
}
-/** ``answer`` holds the shown beat's picks; ids must be one of the card's options (the backend rejects any other answer). ``said`` is composer text typed while the card waited. A response with neither, or none within 300 s, closes the card unanswered. */
+/** ``answer`` holds the shown beat's picks; ids must be one of the card's options (the backend rejects any other answer). ``said`` is composer text typed while the name card waited: the name. ``wrote_instead``: the user sent a message instead of answering; the backend ends the turn and the client sends that message as the next one. A response with none of these, or none within 300 s, closes the card unanswered. */
export interface SetupBeatResult {
answer?: SetupNameAnswer | SetupThemeAnswer | SetupLayoutAnswer | SetupConnectorsAnswer | SetupPluginsAnswer | SetupTourAnswer | SetupBuildAnswer | null
said?: string | null
+ wrote_instead?: boolean
}
export interface SetupNameAnswer {
name: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index e22cef87f99..b3bbdb22c01 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -33619,7 +33619,7 @@
},
"SetupBeatResult": {
"additionalProperties": false,
- "description": "``answer`` holds the shown beat's picks; ids must be one of the card's options (the backend\nrejects any other answer). ``said`` is composer text typed while the card waited. A response\nwith neither, or none within 300 s, closes the card unanswered.",
+ "description": "``answer`` holds the shown beat's picks; ids must be one of the card's options (the backend\nrejects any other answer). ``said`` is composer text typed while the name card waited: the name.\n``wrote_instead``: the user sent a message instead of answering; the backend ends the turn and the\nclient sends that message as the next one. A response with none of these, or none within 300 s,\ncloses the card unanswered.",
"properties": {
"answer": {
"anyOf": [
@@ -33662,6 +33662,11 @@
],
"default": null,
"title": "Said"
+ },
+ "wrote_instead": {
+ "default": false,
+ "title": "Wrote Instead",
+ "type": "boolean"
}
},
"title": "SetupBeatResult",
diff --git a/tests/agent/test_onboarding_flow.py b/tests/agent/test_onboarding_flow.py
index 68834cafe03..3b4b1737048 100644
--- a/tests/agent/test_onboarding_flow.py
+++ b/tests/agent/test_onboarding_flow.py
@@ -10,8 +10,8 @@ import pytest
from agent import onboarding_flow as flow
from agent.onboarding_flow import (
- DONE, PENDING, SHOWN, SKIPPED, Answered, Applied, Done, Facts, End, Recorded, Said, Shown, Skipped,
- TimedOut, apply, new_record, next_beat,
+ DONE, PENDING, SHOWN, SKIPPED, Answered, Applied, Done, Facts, End, Recorded, Shown, Skipped,
+ TimedOut, Wrote, apply, new_record, next_beat,
)
from agent.onboarding_first_tasks import eligible_tasks
from agent.onboarding_text import _LOOK_AROUND, opening_prompt, reminder, turn_note
@@ -90,18 +90,18 @@ def test_the_full_name_never_reaches_the_record_or_the_opening(machine):
def test_run_hrs0_typed_answer_is_applied_and_never_reshows_the_card():
- """hrs0: "elite sounds like my type ;)" got a second layout picker. Typed words close the card;
- the model applies them with set_theme and the hook settles the beat."""
+ """hrs0: "elite sounds like my type ;)" got a second layout picker. A message closes the card and
+ comes as the next turn; the model applies it with set_theme and the hook settles the beat."""
facts = MACHINES["mac"]
steps = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"),
- Answered("theme", {"accent": "Ultraviolet"}), Shown("layout"),
- Said("layout", "elite sounds like my type ;)"),
+ Answered("theme", {"accent": "Ultraviolet"}), Shown("layout"), Wrote("layout"),
Applied("set_theme", {"layout": "terminal-deck"}, {"success": True, "applied": {"layout": "terminal-deck"}}))
- said, applied = steps[-2], steps[-1]
- assert said.result == {"beat": "layout", "said": "elite sounds like my type ;)"}
- assert said.record["waiting"] is None and said.record["beats"]["layout"] == SHOWN
- assert "apply it yourself" in reminder("said", said.record, facts, "layout")
+ wrote, applied = steps[-2], steps[-1]
+ assert wrote.result == {"beat": "layout", "wrote_instead": True}
+ assert wrote.record["waiting"] is None and wrote.record["beats"]["layout"] == SHOWN
+ assert "wrote a message instead" in reminder(wrote.reminder, wrote.record, facts, "layout")
+ assert "apply it yourself" in turn_note(wrote.record)
assert applied.record["beats"]["layout"] == DONE and applied.record["picks"]["layout"] == "terminal-deck"
assert next_beat(applied.record) == "connectors"
@@ -110,7 +110,7 @@ def test_set_theme_settling_the_layout_beat_tells_the_model_the_next_beat():
"""Without a reminder the model recorded the applied layout with setup_beat and was refused."""
facts = MACHINES["mac"]
steps = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"),
- Answered("theme", {"accent": "Ultraviolet"}), Shown("layout"), Said("layout", "basic"),
+ Answered("theme", {"accent": "Ultraviolet"}), Shown("layout"), Wrote("layout"),
Applied("set_theme", {"layout": "sidebar-left"}, {"success": True, "applied": {"layout": "sidebar-left"}}),
Applied("set_theme", {"layout": "terminal-deck"}, {"success": True, "applied": {"layout": "terminal-deck"}}))
@@ -147,11 +147,11 @@ def test_run_hrs0_off_script_questions_keep_one_card_and_continue_settles_it():
facts = MACHINES["mac"]
events = [Shown("name"), Answered("name", {"name": "Sid"}), Skipped("theme"), Skipped("layout")]
for question in ("tell me about SpaceX first", "who runs it?"):
- events += [Shown("connectors", question), Said("connectors", question)]
- events += [Shown("connectors"), Said("connectors", "continue"), Recorded("connectors", "continue")]
+ events += [Shown("connectors", question), Wrote("connectors")]
+ events += [Shown("connectors"), Wrote("connectors"), Recorded("connectors", "continue")]
steps = run(facts, *events)
- assert all(step.record["waiting"] is None for step in steps if isinstance(step.result.get("said"), str))
+ assert all(step.record["waiting"] is None for step in steps if step.result.get("wrote_instead"))
assert steps[-1].result == {"recorded": "connectors", "next": "plugins"}
assert steps[-1].record["beats"]["connectors"] == DONE
@@ -165,7 +165,7 @@ def test_run_3ofn_pick_for_me_applies_layout_and_the_look_around_offer_waits_for
"""3ofn: "look around and pick one for me" ended in Elite through set_theme. The offer no longer
rides the layout result: it comes back on the first try to show the connectors card."""
facts = MACHINES["mac"]
- steps = run(facts, *TO_LAYOUT, Said("layout", "look around and pick one for me"), LAYOUT_SET)
+ steps = run(facts, *TO_LAYOUT, Wrote("layout"), LAYOUT_SET)
assert steps[-1].record["beats"]["layout"] == DONE and steps[-1].record["look_around"] == "not_offered"
assert "look around" not in reminder("after_layout", steps[-1].record, facts)
@@ -254,7 +254,7 @@ def test_out_of_order_card_leaves_earlier_pending_beats_for_next():
def test_a_later_card_settles_an_earlier_card_left_open():
facts = MACHINES["mac"]
- step = run(facts, Shown("name"), Said("name", "hi"), Shown("theme"))[-1]
+ step = run(facts, Shown("name"), Wrote("name"), Shown("theme"))[-1]
assert step.record["beats"]["name"] == DONE and step.record["beats"]["theme"] == SHOWN
@@ -401,7 +401,8 @@ def test_a_layout_or_theme_given_in_words_is_applied_by_set_theme_not_recorded()
for beat, value in [("layout", "terminal-deck"), ("theme", "Ultraviolet")]:
step = apply(new_record(facts), Recorded(beat, value), facts, now=1.0)
assert "set_theme" in step.result["error"] and step.record["beats"][beat] == PENDING
- assert '"name":"set_theme"' in reminder("said", new_record(facts), facts, "layout")
+ record = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Skipped("theme"), Shown("layout"))[-1].record
+ assert '"name":"set_theme"' in turn_note(record)
def test_no_turn_note_once_every_card_is_settled():
diff --git a/tests/agent/test_setup_beat_card_round.py b/tests/agent/test_setup_beat_card_round.py
index 28decbcf087..d03d72403ad 100644
--- a/tests/agent/test_setup_beat_card_round.py
+++ b/tests/agent/test_setup_beat_card_round.py
@@ -1,16 +1,24 @@
-"""A setup_beat round never ends in the empty-response nudge: the line written with the card is the
-turn's reply when the follow-up comes back empty (agent/turn_tool_round.py ``_LINE_IS_REPLY_TOOLS``)."""
+"""A setup_beat round in the turn loop. It never ends in the empty-response nudge: the line written with
+the card is the turn's reply when the follow-up comes back empty (agent/turn_tool_round.py
+``_LINE_IS_REPLY_TOOLS``). A card the user wrote past ends the turn on its result."""
from __future__ import annotations
+import json
from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
import pytest
+from agent import onboarding_record
from agent.agent_init import _CALLBACK_PARAMS
+from agent.onboarding_flow import Facts
from agent.turn_empty_response import recover_empty_response
from agent.turn_tool_round import stage_tool_call_message
+from hermes_state import SessionDB
from run_agent import AIAgent
+from tests.agent.test_run_agent import _mock_response
+from tools.setup_beat_tool import SETUP_BEAT_SCHEMA
def _agent():
@@ -51,3 +59,46 @@ def test_an_empty_follow_up_after_a_card_round_keeps_the_cards_line(tool, reused
else:
assert verdict.final_response != "Pick a colour whenever you're back."
assert agent._mute_post_response is False
+
+
+def _loop_agent(db):
+ with (patch("model_tools.get_tool_definitions", return_value=[{"type": "function", "function": SETUP_BEAT_SCHEMA}]),
+ patch("model_tools.check_toolset_requirements", return_value={}),
+ patch("agent.process_bootstrap.OpenAI")):
+ agent = AIAgent(api_key="test-key-1234567890", base_url="https://openrouter.ai/api/v1", platform="desktop",
+ quiet_mode=True, skip_context_files=True, skip_memory=True)
+ agent.client = MagicMock()
+ agent._disable_streaming, agent._cached_system_prompt, agent._use_prompt_caching = True, "You are helpful.", False
+ agent.tool_delay, agent.compression_enabled, agent.save_trajectories = 0, False, False
+ db.create_session(agent.session_id, "desktop")
+ onboarding_record.start(db, agent.session_id, Facts(os="macos"))
+ agent._session_db = db
+ return agent
+
+
+def test_a_card_closed_by_a_message_ends_the_turn_without_another_model_call(tmp_path, monkeypatch):
+ """The message runs as the user's own next turn, so the old turn must not go on to answer it."""
+ monkeypatch.setattr("hermes_cli.onboarding_run.set_run", lambda *a, **k: None)
+ db = SessionDB(db_path=tmp_path / "state.db")
+ agent = _loop_agent(db)
+ agent.setup_beat_callback = lambda payload: {"wrote_instead": True}
+ calls = []
+
+ def model_call(api_kwargs):
+ calls.append(api_kwargs)
+ if len(calls) > 1:
+ return _mock_response(content="Elite puts a terminal beside the chat.", finish_reason="stop")
+ card = SimpleNamespace(id="c1", type="function",
+ function=SimpleNamespace(name="setup_beat", arguments='{"beat": "layout"}'))
+ return _mock_response(content="Which one suits you?", finish_reason="tool_calls", tool_calls=[card])
+
+ agent._interruptible_api_call = model_call
+ with (patch.object(agent, "_flush_messages_to_session_db"), patch.object(agent, "_persist_session"),
+ patch.object(agent, "_save_trajectory"), patch.object(agent, "_cleanup_task_resources")):
+ result = agent.run_conversation("[opening]")
+
+ assert len(calls) == 1
+ tool = next(m for m in result["messages"] if m["role"] == "tool")
+ assert json.loads(tool["content"])["wrote_instead"] is True
+ # The tool tail is closed, so the user's message that follows alternates roles.
+ assert result["interrupted"] is True and result["messages"][-1]["role"] == "assistant"
diff --git a/tests/tools/test_setup_beat_tool.py b/tests/tools/test_setup_beat_tool.py
index a180d2694ed..b2ce88613e4 100644
--- a/tests/tools/test_setup_beat_tool.py
+++ b/tests/tools/test_setup_beat_tool.py
@@ -40,17 +40,19 @@ def machine(monkeypatch):
@pytest.fixture
def desktop():
- """A card answerer: replies come off a queue; every payload it was shown is kept."""
- shown, replies = [], []
+ """A card answerer: replies come off a queue; every payload it was shown is kept, and every time the
+ tool ended the agent's turn."""
+ shown, replies, ended = [], [], []
def answer(payload):
shown.append(payload)
return replies.pop(0) if replies else None
- return SimpleNamespace(shown=shown, replies=replies, answer=answer)
+ return SimpleNamespace(shown=shown, replies=replies, answer=answer, ended=ended)
def call(db, desktop, call_id="call_1", **args):
- agent = SimpleNamespace(_session_db=db, session_id=SID, setup_beat_callback=desktop.answer)
+ agent = SimpleNamespace(_session_db=db, session_id=SID, setup_beat_callback=desktop.answer,
+ interrupt=lambda **kw: desktop.ended.append(kw))
return json.loads(INLINE_TOOL_EXECUTORS["setup_beat"](agent, args, InlineToolContext("task", call_id)))
@@ -78,28 +80,33 @@ def test_next_shows_the_first_open_beat_and_the_name_card_offers_the_account_nam
# Words typed while the name card waits are the name; the account name reaches the model only if picked.
assert result["answer"] == {"name": "Ada"} and "Ada Lovelace" not in json.dumps(result)
assert result["said"] == "Ada" # drawn as the user's bubble, not a receipt
+ assert desktop.ended == [] # the name answered the card: the turn goes on
-def test_no_answer_closes_the_card_and_typed_words_come_back_as_said(db, desktop):
+def test_a_message_sent_while_a_card_waits_closes_it_unanswered_and_ends_the_turn(db, desktop):
onboarding_record.start(db, SID, FACTS)
timed_out = call(db, desktop, beat="layout")
- desktop.replies.append({"said": "what is Elite?"})
- said = call(db, desktop, beat="layout", call_id="call_2")
+ desktop.replies.append({"wrote_instead": True})
+ wrote = call(db, desktop, beat="layout", call_id="call_2")
assert timed_out["timed_out"] is True and "closed without an answer" in timed_out["reminder"]
- assert said["said"] == "what is Elite?" and 'setup_beat(beat="layout")' in said["reminder"]
- assert onboarding_record.load(db, SID)["waiting"] is None
+ # The message is the user's own next turn: the result carries none of it, and the turn ends on it.
+ assert wrote["beat"] == "layout" and wrote["wrote_instead"] is True and "said" not in wrote
+ assert "wrote a message instead" in wrote["reminder"]
+ assert desktop.ended == [{"tool_reason": "user sent a new message"}]
+ record = onboarding_record.load(db, SID)
+ assert record["waiting"] is None and record["beats"]["layout"] == "shown"
def test_a_card_closed_by_words_a_value_or_the_deadline_reports_what_is_connected_and_installed(db, desktop):
onboarding_record.start(db, SID, FACTS)
timed_out = call(db, desktop, beat="plugins")
call(db, desktop, beat="connectors", call_id="call_2") # refused once: the look-around offer
- desktop.replies.append({"said": "done"})
- said = call(db, desktop, beat="connectors", call_id="call_3")
+ desktop.replies.append({"wrote_instead": True})
+ wrote = call(db, desktop, beat="connectors", call_id="call_3")
continued = call(db, desktop, beat="connectors", value="continue")
- assert timed_out["installed"] == ["blender"] and said["connected"] == ["slack"]
+ assert timed_out["installed"] == ["blender"] and wrote["connected"] == ["slack"]
assert continued["connected"] == ["slack"] and "Connected: slack" in continued["reminder"]
assert onboarding_record.load(db, SID)["picks"]["installed"] == ["blender"]
diff --git a/tests/tui_gateway/test_onboarding_e2e.py b/tests/tui_gateway/test_onboarding_e2e.py
index 5611185c8c0..8c4b6c19381 100644
--- a/tests/tui_gateway/test_onboarding_e2e.py
+++ b/tests/tui_gateway/test_onboarding_e2e.py
@@ -34,8 +34,10 @@ def chat(tmp_path, monkeypatch):
db.create_session(STORED, "desktop")
onboarding_record.start(db, STORED, FACTS)
monkeypatch.setitem(server._sessions, SID, {"session_key": STORED, "source": "desktop"})
+ ended = []
agent = SimpleNamespace(_session_db=db, session_id=STORED, valid_tool_names={"setup_beat", "set_theme"},
- setup_beat_callback=server._agent_cbs(SID)["setup_beat_callback"])
+ setup_beat_callback=server._agent_cbs(SID)["setup_beat_callback"],
+ interrupt=lambda **kw: ended.append(kw), _gateway_turn_context_notes="")
desktop = SimpleNamespace(cards=[], replies=[])
def answer(frame):
@@ -47,7 +49,7 @@ def chat(tmp_path, monkeypatch):
monkeypatch.setattr(server_requests, "_answerable", lambda _sid: True)
monkeypatch.setattr(server_requests, "_write", answer)
monkeypatch.setattr(server_requests, "_emit", lambda *a: None)
- return SimpleNamespace(db=db, agent=agent, desktop=desktop, home=home)
+ return SimpleNamespace(db=db, agent=agent, desktop=desktop, home=home, ended=ended)
def beat(chat, reply=None, **args):
@@ -63,9 +65,10 @@ def test_every_beat_from_the_name_card_to_done(chat):
assert beat(chat, {"answer": {"accent": "Ultraviolet"}}, beat="next")["next"] == "layout"
- # Typed instead of picking: the card closes, the model applies the pick itself through set_theme.
- typed = beat(chat, {"said": "elite please"}, beat="next")
- assert typed["said"] == "elite please"
+ # Typed instead of picking: the card closes, the words are the next turn, the model applies the pick
+ # itself through set_theme.
+ typed = beat(chat, {"wrote_instead": True}, beat="next")
+ assert typed["wrote_instead"] is True
observe_tool_result(chat.agent, "set_theme", {"layout": "terminal-deck"},
json.dumps({"success": True, "applied": {"layout": "terminal-deck"}}))
@@ -93,6 +96,22 @@ def test_every_beat_from_the_name_card_to_done(chat):
assert "error" in beat(chat, beat="next")
+def test_a_message_written_while_a_card_waits_ends_the_turn_and_the_next_turn_brings_the_card_back(chat):
+ beat(chat, {"answer": {"name": "Sid"}}, beat="name")
+ beat(chat, {"answer": {"accent": "Ultraviolet"}}, beat="next")
+
+ closed = beat(chat, {"wrote_instead": True}, beat="next")
+
+ assert closed["beat"] == "layout" and closed["wrote_instead"] is True and "said" not in closed
+ assert chat.ended == [{"tool_reason": "user sent a new message"}]
+ # Their message starts the next turn; its note names the closed card, how a typed answer applies it,
+ # and how to bring it back.
+ server._stage_onboarding_turn_note(SID, chat.agent, history_empty=False)
+ note = chat.agent._gateway_turn_context_notes
+ assert "the layout card is closed" in note and 'setup_beat(beat="layout")' in note
+ assert '"layout":"sidebar-left" or "terminal-deck"' in note
+
+
def test_skip_setup_on_the_card_ends_onboarding(chat, monkeypatch):
def skip_on_show(frame):
chat.desktop.cards.append(frame["params"])
diff --git a/tools/setup_beat_tool.py b/tools/setup_beat_tool.py
index e2d0fb93488..ee7a0eee98d 100644
--- a/tools/setup_beat_tool.py
+++ b/tools/setup_beat_tool.py
@@ -64,10 +64,12 @@ def _direct_event(beat: str, args: Mapping[str, Any]) -> flow.Event | None:
def _reply_event(beat: str, reply: Mapping[str, Any] | None) -> flow.Event:
reply = reply or {}
said = reply.get("said")
- if isinstance(said, str) and said.strip():
+ if beat == "name" and isinstance(said, str) and said.strip():
# Words typed while the name card waits are the name, like its own text box.
- return (flow.Answered(beat, {"name": said.strip()}, said.strip()) if beat == "name"
- else flow.Said(beat, said.strip(), _present(beat)))
+ return flow.Answered(beat, {"name": said.strip()}, said.strip())
+ if reply.get("wrote_instead"):
+ # A message sent instead of answering: the desktop sends it as the user's next turn.
+ return flow.Wrote(beat, _present(beat))
answer = reply.get("answer")
return flow.Answered(beat, answer) if isinstance(answer, dict) and answer else flow.TimedOut(beat, _present(beat))
@@ -100,9 +102,11 @@ def _card(beat: str, step: flow.Step, args: Mapping[str, Any]) -> dict:
def setup_beat_tool(args: Mapping[str, Any], *, db=None, session_id: str = "", tool_call_id: str = "",
- callback: Callable[[dict], dict | None] | None = None) -> str:
- """``callback(payload) -> {answer?, said?} | {timed_out: true} | None`` asks the desktop to show
- ``{beat, question, card}`` and blocks until the user answers or the card closes."""
+ callback: Callable[[dict], dict | None] | None = None,
+ end_turn: Callable[[], object] | None = None) -> str:
+ """``callback(payload) -> {answer?} | {said} | {wrote_instead: true} | None`` asks the desktop to show
+ ``{beat, question, card}`` and blocks until the user answers or the card closes. ``end_turn`` ends the
+ agent's turn once this result is in: a card the user wrote past, whose message is the next turn."""
from agent import onboarding_record as records
beat = args.get("beat")
@@ -130,7 +134,12 @@ def setup_beat_tool(args: Mapping[str, Any], *, db=None, session_id: str = "", t
if after is not None and after["phase"] == flow.PHASE_SKIPPED:
# Skip setup closed the card (onboarding.skip already wrote the record).
return _result(flow.Step(after, {"skipped_all": True}, "skip_all"))
- return _result(records.advance(db, session_id, _reply_event(beat, reply)), beat)
+ event = _reply_event(beat, reply)
+ result = _result(records.advance(db, session_id, event), beat)
+ if isinstance(event, flow.Wrote) and end_turn is not None:
+ # Otherwise the model answers a card the user moved past while their message waits for the turn to end.
+ end_turn()
+ return result
SETUP_BEAT_SCHEMA = {
diff --git a/tui_gateway/contracts/server_requests.py b/tui_gateway/contracts/server_requests.py
index 2347358b762..5511b718ab7 100644
--- a/tui_gateway/contracts/server_requests.py
+++ b/tui_gateway/contracts/server_requests.py
@@ -178,12 +178,15 @@ class SetupBuildAnswer(Result):
class SetupBeatResult(Result):
"""``answer`` holds the shown beat's picks; ids must be one of the card's options (the backend
- rejects any other answer). ``said`` is composer text typed while the card waited. A response
- with neither, or none within 300 s, closes the card unanswered."""
+ rejects any other answer). ``said`` is composer text typed while the name card waited: the name.
+ ``wrote_instead``: the user sent a message instead of answering; the backend ends the turn and the
+ client sends that message as the next one. A response with none of these, or none within 300 s,
+ closes the card unanswered."""
answer: (SetupNameAnswer | SetupThemeAnswer | SetupLayoutAnswer | SetupConnectorsAnswer | SetupPluginsAnswer
| SetupTourAnswer | SetupBuildAnswer | None) = None
said: str | None = None
+ wrote_instead: bool = False
server_request("setup_beat", params=SetupBeatRequestParams, result=SetupBeatResult,