Skip to content

The agent that grows with you

fix(tui_gateway): a stale submit-time row is never adopted by a later turn

teknium17016e996a666
diff --git a/apps/desktop/src/store/session-states-profile-rename.test.ts b/apps/desktop/src/store/session-states-profile-rename.test.ts
index dd2a0f3563c..0ab0cb7fe60 100644
--- a/apps/desktop/src/store/session-states-profile-rename.test.ts
+++ b/apps/desktop/src/store/session-states-profile-rename.test.ts
@@ -38,6 +38,11 @@ describe('migrateTilesForProfile', () => {
connectionId: 'local',
profile: 'webdesign_bhp'
})
+ // Same-named profile on a remote connection: not renamed, its tail must stay put.
+ tails.saveTranscriptTail('s-9', [{ id: 'm9', parts: [{ text: 'remote', type: 'text' }], role: 'user' } as never], {
+ connectionId: 'remote-1',
+ profile: 'webdesign_bhp'
+ })
const sessionStore = await import('@/store/session')
sessionStore.setRememberedSessionId('s-1', 'webdesign_bhp')
@@ -58,6 +63,8 @@ describe('migrateTilesForProfile', () => {
expect(tails.loadTranscriptTail('s-1', { connectionId: 'local', profile: 'hutnik-projectmanager' })).toHaveLength(1)
expect(tails.loadTranscriptTail('s-1', { connectionId: 'local', profile: 'webdesign_bhp' })).toBeNull()
+ expect(tails.loadTranscriptTail('s-9', { connectionId: 'remote-1', profile: 'webdesign_bhp' })).toHaveLength(1)
+ expect(tails.loadTranscriptTail('s-9', { connectionId: 'remote-1', profile: 'hutnik-projectmanager' })).toBeNull()
expect(sessionStore.getRememberedSessionId('hutnik-projectmanager')).toBe('s-1')
expect(sessionStore.getRememberedSessionId('webdesign_bhp')).toBeNull()
diff --git a/apps/desktop/src/store/transcript-tail-cache.ts b/apps/desktop/src/store/transcript-tail-cache.ts
index b06f35a2cb7..5735198e74b 100644
--- a/apps/desktop/src/store/transcript-tail-cache.ts
+++ b/apps/desktop/src/store/transcript-tail-cache.ts
@@ -338,11 +338,10 @@ export function dropTranscriptTailEverywhere(storedSessionId: string): void {
}
}
-/** Wipe the whole cache (connection/mode re-home, quota recovery). */
/** Re-key every cached tail owned by `oldProfile` under `newProfile` (profile
* rename; the sessions still exist, only their owner's name changed). Entries
* stay unreachable under the old name by construction, so without this a
- * rename costs a cold paint for every open chat. Best effort. */
+ * rename costs a cold paint for every open chat. Local connection only. Best effort. */
export function migrateTranscriptTailsForProfile(oldProfile: string, newProfile: string): void {
const store = storage()
const from = oldProfile.trim() || 'default'
@@ -368,6 +367,13 @@ export function migrateTranscriptTailsForProfile(oldProfile: string, newProfile:
}
const [connectionId, , storedId] = parsed as [string, string, string]
+
+ // Local-connection state only (same rule as migrateTilesForProfile): a same-named
+ // profile on a remote connection was not renamed.
+ if ((String(connectionId ?? '').trim() || 'local') !== 'local') {
+ continue
+ }
+
const next = JSON.stringify([connectionId, to, storedId])
try {
@@ -387,6 +393,7 @@ export function migrateTranscriptTailsForProfile(oldProfile: string, newProfile:
writeIndex(store, ids)
}
+/** Wipe the whole cache (connection/mode re-home, quota recovery). */
export function clearTranscriptTails(): void {
const store = storage()
diff --git a/tests/tui_gateway/test_submit_time_user_row.py b/tests/tui_gateway/test_submit_time_user_row.py
index 059bf0d89b9..85d303c7ffc 100644
--- a/tests/tui_gateway/test_submit_time_user_row.py
+++ b/tests/tui_gateway/test_submit_time_user_row.py
@@ -62,7 +62,7 @@ def test_turn_adopts_the_submit_row_and_writes_no_duplicate(monkeypatch, tmp_pat
agent = _flush_agent(db, key)
# The prologue rewrote the persisted prompt (@-expansion): the early row follows it.
expanded = "look at @notes.md\n\n<file notes.md>todo</file>"
- server._adopt_submit_user_row(session, agent, expanded)
+ server._adopt_submit_user_row(session, agent, expanded, "look at @notes.md")
assert "_submit_user_row" not in session
user_msg, _pending = _stage_turn_user_message(agent, expanded, expanded, None, None, None, None)
assert user_msg is agent._pending_cli_user_message # adopted by identity, not rebuilt
@@ -75,3 +75,38 @@ def test_turn_adopts_the_submit_row_and_writes_no_duplicate(monkeypatch, tmp_pat
finally:
server._sessions.pop(sid, None)
db.close()
+
+
+def test_failed_build_drops_the_staged_row_and_a_later_turn_never_adopts_it(monkeypatch, tmp_path):
+ """The submit-time row is the durable record of THAT send only. A turn that ends before the agent runs
+ (build failed / bounded wait expired) must drop the staging dict, and a later turn without a matching
+ prompt.submit (wake-up, auto-continue, queued drain) must not rewrite the user's row to its own text."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ monkeypatch.setattr(server, "_emit", lambda *_a, **_k: None)
+ monkeypatch.setattr(server, "_wait_agent_for_prompt",
+ lambda _session, _rid, _sid: {"error": {"message": "agent initialization failed"}})
+ try:
+ with session["history_lock"]:
+ session["running"] = True
+ server._start_inflight_turn(session, "please refactor the login page")
+ assert server._persist_session_row_for_submit("rid", session, "please refactor the login page", None) is None
+ server._run_after_agent_ready("rid", sid, session, "please refactor the login page", None, None)
+ assert "_submit_user_row" not in session, "staged row survived a turn that never reached the agent"
+
+ # Even if a staged row were still around, a turn whose raw submit differs must leave the DB alone.
+ with session["history_lock"]:
+ server._start_inflight_turn(session, "please refactor the login page")
+ server._persist_submit_user_row(session, "please refactor the login page", None)
+ agent = _flush_agent(db, key)
+ synthesized = "[subagent finished] result summary"
+ server._adopt_submit_user_row(session, agent, synthesized, synthesized)
+ assert "_submit_user_row" not in session
+ assert agent._pending_cli_user_message is None
+ rows = db.get_messages_as_conversation(key, include_inactive=True)
+ assert [(r["role"], r["content"]) for r in rows] == [
+ ("user", "please refactor the login page"), ("user", "please refactor the login page")]
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index 2fa45ba19c4..d04de58ecf9 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -120,6 +120,7 @@ def _admit_prompt_turn(
getattr(ownership_refusal, "reason", None) or "refused")
with session["history_lock"]:
session["running"] = False
+ session.pop("_submit_user_row", None) # no turn runs: the submit-time row stays as the send
_emit("error", sid, {"message": str(ownership_refusal)})
return None
with session["history_lock"]:
@@ -127,6 +128,7 @@ def _admit_prompt_turn(
queued_prompt_generation is not None
and int(session.get("_queued_prompt_generation", 0)) != queued_prompt_generation):
session["running"] = False
+ session.pop("_submit_user_row", None)
return None
images = list(session.get("attached_images", []) if image_paths is None else image_paths)
if image_paths is None:
@@ -550,8 +552,9 @@ def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, images
def _invoke_agent(
sid: str, session: dict, st: _TurnRun, prompt: Any, run_message: Any, streamer,
images: list[str], display_kind: str | None, display_metadata: dict | None,
- turn_author: dict | None = None) -> None:
- """Wire the streaming callbacks and run the conversation into ``st.result``."""
+ turn_author: dict | None = None, text: Any = None) -> None:
+ """Wire the streaming callbacks and run the conversation into ``st.result``.
+ ``text`` is the turn's raw submit, matched against the row staged by prompt.submit."""
agent = st.agent
# Bot Chat mirrors gateway.stream_consumer: deltas are withheld while the streamed buffer
# could still resolve to a silence marker ("NO"->"NO_REPLY"), so a bare marker is never
@@ -599,7 +602,7 @@ def _invoke_agent(
run_kwargs["persist_user_display_metadata"] = display_metadata
if turn_author and "turn_author" in run_params:
run_kwargs["turn_author"] = turn_author
- _adopt_submit_user_row(session, agent, run_kwargs["persist_user_message"])
+ _adopt_submit_user_row(session, agent, run_kwargs["persist_user_message"], text)
# Live-rename hook: auto-titling fires inside the turn prologue.
_title_key = session.get("session_key") or sid
agent._on_session_title = lambda t, _src, _k=_title_key: _emit(
@@ -898,7 +901,7 @@ def _run_prompt_submit(
prompt, run_message, cols, streamer = prepared
_invoke_agent(
sid, session, st, prompt, run_message, streamer, images, display_kind,
- display_metadata, turn_author)
+ display_metadata, turn_author, text)
status_note = _absorb_turn_result(
sid, session, st, text, display_kind, display_metadata)
payload, raw, status = _complete_turn_payload(session, st, status_note, cols)
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
index e35102026c0..f58f6ce36aa 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -333,6 +333,9 @@ def _fail_inflight_turn(session: dict, error: Any, error_surface: Optional[dict]
turn.pop("error_surface", None)
turn.update(streaming=False, updated_at=now)
session["inflight_turn"] = turn
+ # The turn is over (build failed, agent missing, prologue raised): the submit-time row stays as the
+ # durable record of the send, but a later turn must not adopt it as its own input.
+ session.pop("_submit_user_row", None)
_TURN_FAILURE_DETAIL_LIMIT = 240
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index 81117b19ae3..bb3caf00569 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -365,13 +365,15 @@ def _persist_submit_user_row(session: dict, text: Any, display_kind: str | None)
session["_submit_user_row"] = staged
-def _adopt_submit_user_row(session: dict, agent, persist_user_message: Any) -> None:
+def _adopt_submit_user_row(session: dict, agent, persist_user_message: Any, text: Any) -> None:
"""Hand the row written at submit to the turn as its user dict (``agent._pending_cli_user_message``,
adopted by ``_stage_turn_user_message`` when the content matches). A prompt the prologue rewrote
(@-expansion, image parts) first updates that row so the durable transcript replays what the model
- was sent and the ``api_content`` sidecar can address it; ``_row_id`` rides along for that stamp."""
+ was sent and the ``api_content`` sidecar can address it; ``_row_id`` rides along for that stamp.
+ ``text`` is THIS turn's raw submit: a staged row from an earlier send (its turn ended before the agent
+ ran) is discarded untouched, so the DB row stays the user's message and never a synthesized turn's text."""
staged = session.pop("_submit_user_row", None)
- if not isinstance(staged, dict) or agent is None:
+ if not isinstance(staged, dict) or agent is None or staged.get("content") != text:
return
if staged["content"] != persist_user_message:
from agent.session_persistence import _durable_content