The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): make a history-dropping submit prove it meant to
HexLab98c24ff38c513c
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 48e5398b6ef..fc810946e3b 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -2248,6 +2248,7 @@ describe('usePromptActions restoreToMessage', () => {{session_id: RUNTIME_SESSION_ID,text: 'first prompt',+ confirm_truncate: true,truncate_before_user_ordinal: 0,confirm_empty_truncate: true},@@ -2316,6 +2317,7 @@ describe('usePromptActions restoreToMessage', () => {{session_id: RUNTIME_SESSION_ID,text: 'first prompt',+ confirm_truncate: true,truncate_before_user_ordinal: 0,confirm_empty_truncate: true},@@ -2362,6 +2364,7 @@ describe('usePromptActions restoreToMessage', () => {{session_id: RUNTIME_SESSION_ID,text: 'first prompt',+ confirm_truncate: true,truncate_before_user_ordinal: 0,confirm_empty_truncate: true},diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.tsindex 23d9c979815..9d1b0347a33 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts@@ -7,13 +7,27 @@ describe('truncateSubmitParams', () => {expect(truncateSubmitParams(undefined)).toEqual({})})- it('requires confirm_empty_truncate only for ordinal 0', () => {+ it('confirms intent for every ordinal, and the empty edge only for ordinal 0', () => {expect(truncateSubmitParams(0)).toEqual({+ confirm_truncate: true,truncate_before_user_ordinal: 0,confirm_empty_truncate: true})expect(truncateSubmitParams(1)).toEqual({+ confirm_truncate: true,truncate_before_user_ordinal: 1})})++ it('never sends an ordinal without the intent flag the gateway requires', () => {+ // The gateway drops history only for a submit that declares itself a+ // rewind. An ordinal built here without confirm_truncate would be refused+ // (and, on an older gateway, would truncate silently).+ for (const ordinal of [0, 1, 2, 7]) {+ const params = truncateSubmitParams(ordinal)++ expect(params.truncate_before_user_ordinal).toBe(ordinal)+ expect(params.confirm_truncate).toBe(true)+ }+ })})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.tsindex 32dc25c1ebf..6fd1d9c6cd7 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts@@ -26,10 +26,12 @@ import {type RequestGateway = <T = unknown>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>/**- * Build `prompt.submit` truncation params. Ordinal 0 truncates to an empty- * transcript (restore/regenerate the first user turn) — the gateway refuses- * that edge unless `confirm_empty_truncate` is set, so stale clients cannot- * silently wipe a session via a leftover ordinal.+ * Build `prompt.submit` truncation params. `confirm_truncate` states that this+ * submit really is a rewind/edit/regenerate: the gateway drops history only for+ * a submit that says so, so a leftover ordinal riding along on an ordinary send+ * cannot delete the transcript. Ordinal 0 additionally truncates to an empty+ * transcript (restore/regenerate the first user turn), which the gateway gates+ * behind `confirm_empty_truncate` on top of that.*/export function truncateSubmitParams(truncateOrdinal: number | undefined): Record<string, unknown> {if (truncateOrdinal === undefined) {@@ -37,6 +39,7 @@ export function truncateSubmitParams(truncateOrdinal: number | undefined): Recor}return {+ confirm_truncate: true,truncate_before_user_ordinal: truncateOrdinal,...(truncateOrdinal === 0 ? { confirm_empty_truncate: true } : {})}diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex 8f0eb124ac3..1b75d65f2fd 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -4276,6 +4276,7 @@ def test_prompt_submit_rejects_negative_truncate_ordinal(monkeypatch):"session_id": "trunc-sid","text": "next","truncate_before_user_ordinal": -1,+ "confirm_truncate": True,},})@@ -4288,12 +4289,77 @@ def test_prompt_submit_rejects_negative_truncate_ordinal(monkeypatch):server._sessions.pop("trunc-sid", None)+def test_prompt_submit_refuses_unconfirmed_nonempty_truncation(monkeypatch):+ """An ordinal without confirm_truncate must not drop the session tail.++ #80763: a desktop client carried a leftover truncate_before_user_ordinal+ into an ORDINARY submit. The request was indistinguishable from a real+ rewind — in-range ordinal, non-empty result — so the empty-truncation guard+ never fired and replace_messages() DELETEd 244 durable rows (296 -> 52).+ Intent has to be stated: refuse on 4029 and leave memory and DB untouched.+ """+ replaced = []++ class _FakeDB:+ def replace_messages(self, key, messages):+ replaced.append((key, list(messages)))++ history = [+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": "ok"},+ {"role": "user", "content": "second"},+ {"role": "assistant", "content": "done"},+ {"role": "user", "content": "third"},+ {"role": "assistant", "content": "sure"},+ ]+ server._sessions["unconfirmed-trunc-sid"] = _session(history=list(history))+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())+ monkeypatch.setattr(+ server, "_start_agent_build", lambda *a, **k: pytest.fail("must not start a turn")+ )+ monkeypatch.setattr(+ server, "_start_inflight_turn", lambda *a, **k: pytest.fail("must not start a turn")+ )++ def _submit(**extra):+ return server.handle_request(+ {+ "id": "1",+ "method": "prompt.submit",+ "params": {+ "session_id": "unconfirmed-trunc-sid",+ "text": "an ordinary typed message",+ "truncate_before_user_ordinal": 2,+ **extra,+ },+ }+ )++ try:+ resp = _submit()+ assert resp["error"]["code"] == 4029+ assert "confirm_truncate" in resp["error"]["message"]+ # Explicit falsey values must not satisfy the opt-in either.+ for falsey in (False, 0, "", "false", "no"):+ assert _submit(confirm_truncate=falsey)["error"]["code"] == 4029, falsey+ # confirm_empty_truncate is a different gate — it must not stand in for+ # rewind intent on a cut that leaves the transcript non-empty.+ assert _submit(confirm_empty_truncate=True)["error"]["code"] == 4029+ session = server._sessions["unconfirmed-trunc-sid"]+ assert session["history"] == history+ assert session["history_version"] == 0+ assert session["running"] is False+ assert replaced == []+ finally:+ server._sessions.pop("unconfirmed-trunc-sid", None)++def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):- """Stale truncate_before_user_ordinal=0 must not wipe a non-empty transcript.+ """A confirmed rewind still must not wipe a non-empty transcript by accident.- Desktop desync can attach ordinal 0 to an ordinary fresh submit. That cuts- at the first user message (history[:0] == []) and replace_messages() would- DELETE every durable row. Refuse unless confirm_empty_truncate is set.+ Ordinal 0 cuts at the first user message (history[:0] == []) and+ replace_messages() would DELETE every durable row. Even a submit that+ declares rewind intent needs the second opt-in for that edge."""replaced = []@@ -4326,6 +4392,7 @@ def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):"session_id": "empty-trunc-sid","text": "fresh typed message","truncate_before_user_ordinal": 0,+ "confirm_truncate": True,},})@@ -4341,6 +4408,7 @@ def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):"session_id": "empty-trunc-sid","text": "fresh typed message","truncate_before_user_ordinal": 0,+ "confirm_truncate": True,"confirm_empty_truncate": falsey,},}@@ -4411,6 +4479,7 @@ def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):"session_id": "confirm-empty-sid","text": "first","truncate_before_user_ordinal": 0,+ "confirm_truncate": True,"confirm_empty_truncate": True,},}@@ -9295,6 +9364,7 @@ def test_prompt_submit_can_truncate_before_user_ordinal(monkeypatch):"session_id": "sid","text": "edited second","truncate_before_user_ordinal": 1,+ "confirm_truncate": True,},})@@ -9351,6 +9421,7 @@ def test_prompt_submit_refuses_turn_when_truncate_persist_fails(monkeypatch):"session_id": "trunc-fail-sid","text": "edited second","truncate_before_user_ordinal": 1,+ "confirm_truncate": True,},})@@ -9444,6 +9515,7 @@ def test_prompt_submit_truncate_ordinal_skips_display_kind_rows(monkeypatch):"session_id": "sid","text": "edited first","truncate_before_user_ordinal": 1,+ "confirm_truncate": True,},})diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex b25c93a89f0..15b9328a109 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -163,6 +163,31 @@ def _(rid, params: dict) -> dict:except (TypeError, ValueError):return _err(rid, 4004, "truncate_before_user_ordinal must be an integer")history = session.get("history", [])+ # An ordinal alone is not consent. A client that carries a leftover+ # ordinal into an ORDINARY submit sends a request that is+ # indistinguishable, field by field, from a real rewind — same+ # method, same shape, an in-range target — and the cut it asks for+ # is a destructive replace_messages() the user never requested+ # (#80763: 296 -> 52 messages, 244 durable rows gone). Only the+ # client knows whether this submit is a rewind/edit/regenerate, so+ # it has to say so; refuse the cut when it doesn't.+ if not is_truthy_value(params.get("confirm_truncate")):+ logger.warning(+ "prompt.submit: REFUSED unconfirmed truncation of session %s "+ "(%d messages held; ordinal=%d). The client attached "+ "truncate_before_user_ordinal without confirm_truncate — "+ "likely a stale ordinal on an ordinary submit.",+ sid,+ len(history),+ ordinal,+ )+ return _err(+ rid,+ 4029,+ "truncate_before_user_ordinal requires confirm_truncate=true; "+ "an ordinary prompt.submit must not drop session history "+ "(update your Hermes client if a rewind was intended)",+ )user_indices = [i for i, m in enumerate(history)if m.get("role") == "user" and not m.get("display_kind")@@ -175,12 +200,11 @@ def _(rid, params: dict) -> dict:if ordinal < 0 or ordinal >= len(user_indices):return _err(rid, 4018, "target user message is no longer in session history")truncated = history[: user_indices[ordinal]]- # Stale clients can attach truncate_before_user_ordinal=0 to an- # ordinary submit. That resolves to history[:0] == [] and- # replace_messages() DELETEs every durable row — silent total- # transcript loss. Refuse the empty-truncation edge unless the- # client explicitly opts in (legitimate restore/regenerate of the- # first user turn).+ # Second gate, on top of confirm_truncate: ordinal 0 resolves to+ # history[:0] == [] and replace_messages() DELETEs every durable+ # row. A confirmed rewind that happens to erase the whole+ # transcript still needs its own opt-in (legitimate restore/+ # regenerate of the first user turn).if (not truncatedand history