The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui-gateway): refuse a prompt.submit cut that archives >1 user turn without confirm_deep_truncate
kshitijk4poor0e630b920ef9
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.tsindex 6c41b39251c..c3b60d784b7 100644--- a/apps/desktop/src/app/chat/session-tile-actions.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.ts@@ -510,7 +510,8 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedtruncateMessageId?: string,truncateRowId?: number,sourceText?: string,- rebindRowIds?: readonly number[]+ rebindRowIds?: readonly number[],+ confirmDeepTruncate?: boolean) =>runRewindSubmit(requestSessionGateway,@@ -525,7 +526,8 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored},truncateRowId,sourceText,- rebindRowIds+ rebindRowIds,+ confirmDeepTruncate),[bindRecoveredRuntime, requestSessionGateway])@@ -578,7 +580,8 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedplan.truncateMessageId,plan.truncateRowId,plan.sourceText,- durableRowIdsForRebind(messages)+ durableRowIdsForRebind(messages),+ plan.confirmDeepTruncate ?? false))} catch (err) {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 6e0d6b0a7fd..c0b26b1d08a 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@@ -3085,7 +3085,8 @@ describe('usePromptActions restoreToMessage', () => {text: 'first prompt',confirm_truncate: true,truncate_before_message_id: 'u1',- confirm_empty_truncate: true+ confirm_empty_truncate: true,+ confirm_deep_truncate: true},1_800_000)@@ -3154,7 +3155,8 @@ describe('usePromptActions restoreToMessage', () => {text: 'first prompt',confirm_truncate: true,truncate_before_message_id: 'u1',- confirm_empty_truncate: true+ confirm_empty_truncate: true,+ confirm_deep_truncate: true},1_800_000)@@ -3201,7 +3203,8 @@ describe('usePromptActions restoreToMessage', () => {text: 'first prompt',confirm_truncate: true,truncate_before_message_id: 'u1',- confirm_empty_truncate: true+ confirm_empty_truncate: true,+ confirm_deep_truncate: true},1_800_000)diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.tsindex 56634ead17a..b025d86b10a 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts@@ -969,7 +969,8 @@ export function usePromptActions({interruptFirst: boolean,truncateRowId?: number,sourceText?: string,- rebindRowIds?: readonly number[]+ rebindRowIds?: readonly number[],+ confirmDeepTruncate?: boolean) =>runRewindSubmit(requestGateway,@@ -987,7 +988,8 @@ export function usePromptActions({},truncateRowId,sourceText,- rebindRowIds+ rebindRowIds,+ confirmDeepTruncate),[activeSessionIdRef, requestGateway, selectedStoredSessionIdRef])@@ -1026,7 +1028,8 @@ export function usePromptActions({false,plan.truncateRowId,plan.sourceText,- durableRowIdsForRebind(messages)+ durableRowIdsForRebind(messages),+ plan.confirmDeepTruncate ?? false)applySurvivorRowIds(sessionId, survivorRowIds)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 72d36f3b269..5d65fb73259 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@@ -736,7 +736,9 @@ describe('planConfirmedReload (#133716)', () => {false,undefined,plan.truncateRowId,- plan.sourceText+ plan.sourceText,+ undefined,+ plan.confirmDeepTruncate ?? false)}@@ -751,12 +753,14 @@ describe('planConfirmedReload (#133716)', () => {expect(asked).toBe(1)expect(await submitPlan(await planConfirmedReload(transcript, 'a1', async () => true))).toMatchObject({- truncate_before_row_id: 11+ truncate_before_row_id: 11,+ confirm_deep_truncate: true})const tail = await submitPlan(await planConfirmedReload(transcript, 'a2', askAndDecline))expect(asked).toBe(1)expect(tail).toMatchObject({ confirm_truncate: true, truncate_before_row_id: 13 })+ expect(tail?.confirm_deep_truncate).toBeUndefined()})})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 e42f75bac30..9938313a0e2 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@@ -164,12 +164,15 @@ export function isSyntheticRendererId(messageId: string | undefined): boolean {* 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.+ * behind `confirm_empty_truncate` on top of that. A cut that archives later+ * user turns (restore/edit an older turn, confirmed deep regenerate) also+ * needs `confirm_deep_truncate` (#133716).*/export function truncateSubmitParams(truncateOrdinal: number | undefined,truncateMessageId?: string,- truncateRowId?: number+ truncateRowId?: number,+ confirmDeepTruncate = false): Record<string, unknown> {const hasOrdinal = typeof truncateOrdinal === 'number' && Number.isInteger(truncateOrdinal) && truncateOrdinal >= 0const hasRowId = typeof truncateRowId === 'number' && Number.isInteger(truncateRowId)@@ -186,7 +189,8 @@ export function truncateSubmitParams(...(hasOrdinal ? { truncate_before_user_ordinal: truncateOrdinal } : {}),...(hasMessageId ? { truncate_before_message_id: truncateMessageId } : {}),...(hasRowId ? { truncate_before_row_id: truncateRowId } : {}),- ...(truncateOrdinal === 0 ? { confirm_empty_truncate: true } : {})+ ...(truncateOrdinal === 0 ? { confirm_empty_truncate: true } : {}),+ ...(confirmDeepTruncate ? { confirm_deep_truncate: true } : {})}}@@ -275,7 +279,10 @@ export async function runRewindSubmit(recovery?: { storedSessionId?: null | string; onSessionRecovered?: (sessionId: string) => void },truncateRowId?: number,sourceText?: string,- rebindRowIds?: readonly number[]+ rebindRowIds?: readonly number[],+ // Restore/edit name their target explicitly; only regenerate (implicit+ // target) passes false unless the user confirmed a deep cut (#133716).+ confirmDeepTruncate = true): Promise<SurvivorUserRowIds | undefined> {// Recovery may rebind the live id mid-flight; interrupt/submit must both// follow it rather than pinning the dead one.@@ -340,7 +347,7 @@ export async function runRewindSubmit({session_id: targetId,text,- ...truncateSubmitParams(resolvedOrdinal, resolvedMessageId, resolvedRowId),+ ...truncateSubmitParams(resolvedOrdinal, resolvedMessageId, resolvedRowId, confirmDeepTruncate),// A first-turn rewind resolves to an empty transcript, which the// gateway additionally gates behind confirm_empty_truncate. In// resolved-row-id mode the tail-local ordinal was dropped (see@@ -484,6 +491,8 @@ export function appendMidTurnUserMessage<export interface ReloadPlan {branchGroupId: string+ /** Set only after the user confirmed a reload that archives later user turns. */+ confirmDeepTruncate?: boolean/** Original persisted text of the turn — the durable-row-id content key. */sourceText: stringtext: string@@ -566,7 +575,7 @@ export async function planConfirmedReload(return plan}- return (await confirmDeep()) ? plan : null+ return (await confirmDeep()) ? { ...plan, confirmDeepTruncate: true } : null}/** Optimistic reload state: keep the user turn, hide the branch's assistants. */diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 09b780c7311..e9eca2dbdd0 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -2691,6 +2691,7 @@ export interface PromptSubmitParams {truncate_before_message_id?: string | nullconfirm_truncate?: boolean | nullconfirm_empty_truncate?: boolean | null+ confirm_deep_truncate?: boolean | nullrebind_survivor_row_ids?: number[] | null}/** ``status`` is absent only on the typed-stop-phrase reply (``voice_stopped``). After a truncation the survivor row ids let the client rebind its cached ``rowId``s (``None`` map entries: drop the cached id). ``turn_isolation`` marks a compute-host dispatch. */diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex caf8fafb4cd..e9a670f8f31 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -26682,6 +26682,18 @@"default": null,"title": "Confirm Empty Truncate"},+ "confirm_deep_truncate": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Confirm Deep Truncate"+ },"rebind_survivor_row_ids": {"anyOf": [{diff --git a/tests/tui_gateway/test_session_profile_db.py b/tests/tui_gateway/test_session_profile_db.pyindex 0e023ee4f40..11e1af9e3ff 100644--- a/tests/tui_gateway/test_session_profile_db.py+++ b/tests/tui_gateway/test_session_profile_db.py@@ -239,6 +239,7 @@ def test_truncation_persists_to_the_profile_db(server, launch_db, profile_db, mo"truncate_before_row_id": user_row_ids[1],"truncate_before_user_ordinal": 1,"confirm_truncate": True,+ "confirm_deep_truncate": True, # cuts 2 of 3 user turns (#133716)},)@@ -279,6 +280,7 @@ def test_truncation_does_not_copy_rows_into_the_launch_profile("truncate_before_row_id": user_row_ids[1],"truncate_before_user_ordinal": 1,"confirm_truncate": True,+ "confirm_deep_truncate": True, # cuts 2 of 3 user turns (#133716)},)@@ -314,6 +316,7 @@ def test_truncation_surfaces_the_profile_dbs_live_row_ids("truncate_before_row_id": user_row_ids[1],"truncate_before_user_ordinal": 1,"confirm_truncate": True,+ "confirm_deep_truncate": True, # cuts 2 of 3 user turns (#133716)},)@@ -343,6 +346,7 @@ def test_truncation_without_a_profile_uses_the_shared_handle(server, launch_db,"truncate_before_row_id": user_row_ids[1],"truncate_before_user_ordinal": 1,"confirm_truncate": True,+ "confirm_deep_truncate": True, # cuts 2 of 3 user turns (#133716)},)diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex f0769f5454d..956acad7eb1 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -7548,6 +7548,7 @@ def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):"truncate_before_user_ordinal": 0,"confirm_truncate": True,"confirm_empty_truncate": True,+ "confirm_deep_truncate": True, # drops both user turns (#133716)},})diff --git a/tests/tui_gateway/test_tui_gateway_server_deep_truncate.py b/tests/tui_gateway/test_tui_gateway_server_deep_truncate.pynew file mode 100644index 00000000000..a793420f1d9--- /dev/null+++ b/tests/tui_gateway/test_tui_gateway_server_deep_truncate.py@@ -0,0 +1,49 @@+"""prompt.submit depth gate (#133716): a cut that archives more than one user turn needs+``confirm_deep_truncate`` — a valid anchor can still name the wrong (stale) row."""++import threading+import types++from tui_gateway import server+++def test_prompt_submit_refuses_deep_truncation_without_confirm(monkeypatch):+ replaced = []++ class _FakeDB:+ def replace_messages(self, key, messages, **_kwargs):+ replaced.append(list(messages))++ history = []+ for turn in range(3):+ history += [+ {"_row_id": 100 + 2 * turn, "role": "user", "content": f"u{turn}"},+ {"_row_id": 101 + 2 * turn, "role": "assistant", "content": f"a{turn}"},+ ]+ sess = {+ "agent": types.SimpleNamespace(), "session_key": "session-key", "history": list(history),+ "history_lock": threading.Lock(), "history_version": 0, "running": False,+ "attached_images": [], "image_counter": 0, "cols": 80, "slash_worker": None,+ "show_reasoning": False, "tool_progress_mode": "all",+ }+ server._sessions["deep-trunc-sid"] = sess+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)+ # The confirmed submit starts a turn; never run it on a real thread (it would leak).+ monkeypatch.setattr(server.threading, "Thread", lambda *a, **k: types.SimpleNamespace(start=lambda: None))++ def _submit(**extra):+ return server.handle_request({"id": "1", "method": "prompt.submit", "params": {+ "session_id": "deep-trunc-sid", "text": "u1", "truncate_before_row_id": 102,+ "confirm_truncate": True, **extra}})++ try:+ refused = _submit()+ assert refused["error"]["code"] == 4033+ assert refused["error"]["data"] == {"archived_messages": 4, "archived_user_turns": 2}+ assert sess["history"] == history and replaced == []++ assert _submit(confirm_deep_truncate=True).get("error") is None+ assert replaced == [history[:2]]+ finally:+ server._sessions.pop("deep-trunc-sid", None)diff --git a/tui_gateway/contracts/prompt_voice.py b/tui_gateway/contracts/prompt_voice.pyindex 83e4da975d9..f0919f23c9c 100644--- a/tui_gateway/contracts/prompt_voice.py+++ b/tui_gateway/contracts/prompt_voice.py@@ -43,6 +43,7 @@ class PromptSubmitParams(SessionParams):truncate_before_message_id: str | None = Noneconfirm_truncate: bool | None = Noneconfirm_empty_truncate: bool | None = None+ confirm_deep_truncate: bool | None = None # required when the cut archives >1 user turnrebind_survivor_row_ids: list[int] | None = None# In-process only: injected by the hosted-room / bot-relay handlers, never accepted from a# client (a client dict for ``_turn_author`` answers 4124). Excluded from the rendered wire.diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex f63ceb3fdd2..221609bcaff 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -464,6 +464,22 @@ def _truncate_history_for_submit(rid, sid, session, params, requested_rebind_idsrid, 4028,"truncation would erase the entire session transcript; ""resubmit with confirm_empty_truncate=true if this is intended"), {}+ # Depth gate (#133716): a valid anchor can still name the wrong row (a stale client+ # binding replayed a 4-hour-old turn and archived 107 messages). Tail regenerate and+ # edit-last drop exactly the target turn; anything deeper needs its own opt-in.+ archived_user_turns = len(_history_user_indices(history)) - ordinal+ if archived_user_turns > 1 and not is_truthy_value(params.get("confirm_deep_truncate")):+ archived_messages = len(history) - len(truncated)+ logger.warning(+ "prompt.submit: REFUSED deep truncation of session %s (%d messages / %d user "+ "turns would be archived; ordinal=%d).",+ sid, archived_messages, archived_user_turns, ordinal)+ return _err(+ rid, 4033,+ "truncation would archive later user turns; resubmit with "+ "confirm_deep_truncate=true if this is intended",+ data={"archived_messages": archived_messages,+ "archived_user_turns": archived_user_turns}), {}log_fn = logger.warning if not truncated else logger.infolog_fn("prompt.submit: truncating session %s history %d -> %d messages (ordinal=%d)",diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.mdindex 828b3151028..ba53268be24 100644--- a/website/docs/developer-guide/programmatic-integration.md+++ b/website/docs/developer-guide/programmatic-integration.md@@ -73,6 +73,7 @@ A rewind / edit / regenerate is a `prompt.submit` that drops part of the stored| `truncate_before_row_id` | Integer SQLite row ID (`messages.id` / `row_id`) of the target user turn to cut at. Preferred durable address. When both ordinal and row ID are provided, gateway verifies they match (returning `4030` on mismatch). An unknown/stale row ID is refused with `4018` — it does **not** fall back to the ordinal. || `confirm_truncate` | Required whenever an ordinal, message ID, or row ID is sent. Declares that this submit really is a rewind, not an ordinary send that happens to carry leftover parameters. Sending it without a target is refused with code `4004`. || `confirm_empty_truncate` | Additionally required when the cut would leave the transcript empty (ordinal `0`). |+| `confirm_deep_truncate` | Additionally required when the cut would archive more than one user turn (anything deeper than regenerating or editing the last turn). Without it the submit is refused with code `4033`; `error.data` carries `archived_messages` and `archived_user_turns`, and nothing is written. |A truncation parameter without `confirm_truncate` is refused with code `4004` or `4029` and nothing is written. Hosts that implement rewind must set the flag at the moment the user asks for it, and must never keep truncation parameters in state across ordinary submits. Prefer `truncate_before_row_id` (from resume `row_id` / `_row_id`) over ordinals; keep the ordinal as a back-compat / optimistic-row path only when no durable id is available yet.