Skip to content

The agent that grows with you

fix: editing a message in an old session fails (profile DB + window-relative ordinal) (#91302)

brooklyn!02e270a47edb
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.tsx
index 178627865f5..abb2c10c24e 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
@@ -2517,7 +2517,6 @@ describe('usePromptActions restoreToMessage', () => {
session_id: RUNTIME_SESSION_ID,
text: 'first prompt',
confirm_truncate: true,
- truncate_before_user_ordinal: 0,
truncate_before_message_id: 'u1',
confirm_empty_truncate: true
},
@@ -2587,7 +2586,6 @@ describe('usePromptActions restoreToMessage', () => {
session_id: RUNTIME_SESSION_ID,
text: 'first prompt',
confirm_truncate: true,
- truncate_before_user_ordinal: 0,
truncate_before_message_id: 'u1',
confirm_empty_truncate: true
},
@@ -2635,7 +2633,6 @@ describe('usePromptActions restoreToMessage', () => {
session_id: RUNTIME_SESSION_ID,
text: 'first prompt',
confirm_truncate: true,
- truncate_before_user_ordinal: 0,
truncate_before_message_id: 'u1',
confirm_empty_truncate: true
},
@@ -5372,8 +5369,10 @@ describe('usePromptActions editMessage stale-target recovery (#82462)', () => {
// First attempt only — no plain resubmit that drops truncate_before_user_ordinal.
expect(submitCalls).toHaveLength(1)
expect(submitCalls[0]?.[1]).toMatchObject({
- truncate_before_user_ordinal: 0,
confirm_truncate: true
})
+ expect(
+ (submitCalls[0]?.[1] as { truncate_before_user_ordinal?: unknown } | undefined)?.truncate_before_user_ordinal
+ ).toBeUndefined()
})
})
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.ts
index 43d16f79a22..d5f13f7240f 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
@@ -475,7 +475,7 @@ describe('runRewindSubmit durable-address discipline (#87059)', () => {
expect(submit?.params?.confirm_truncate).toBeUndefined()
})
- it('leaves a bound durable rowId untouched (no extra history call)', async () => {
+ it('leaves a bound durable rowId untouched (no extra history call) and drops the client ordinal', async () => {
const calls: Call[] = []
await runRewindSubmit(makeGateway(calls), 'sid', 'fixed prompt', 1, undefined, false, undefined, 13, 'typo prompt')
@@ -485,7 +485,77 @@ describe('runRewindSubmit durable-address discipline (#87059)', () => {
const submit = calls.find(call => call.method === 'prompt.submit')
expect(submit?.params?.truncate_before_row_id).toBe(13)
- expect(submit?.params?.truncate_before_user_ordinal).toBe(1)
+ expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()
+ })
+
+ it('drops the client ordinal whenever a durable row id is present, including a complete live transcript (#88082, #89244)', async () => {
+ const calls: Call[] = []
+
+ await runRewindSubmit(
+ makeGateway(calls),
+ 'sid',
+ 'fixed prompt',
+ 1, // display-lineage / window-relative — not the gateway tip
+ undefined,
+ false,
+ undefined,
+ 13,
+ 'typo prompt'
+ )
+
+ // No content-resolution read needed — the bubble already holds a durable id.
+ expect(calls.some(call => call.method === 'session.history')).toBe(false)
+
+ const submit = calls.find(call => call.method === 'prompt.submit')
+
+ expect(submit?.params?.confirm_truncate).toBe(true)
+ expect(submit?.params?.truncate_before_row_id).toBe(13)
+ expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()
+ })
+
+ it('drops the client ordinal when the cut is addressed by durable message id alone', async () => {
+ const calls: Call[] = []
+
+ await runRewindSubmit(
+ makeGateway(calls),
+ 'sid',
+ 'fixed prompt',
+ 1,
+ 'durable-platform-msg-1',
+ false,
+ undefined,
+ undefined,
+ 'typo prompt'
+ )
+
+ const submit = calls.find(call => call.method === 'prompt.submit')
+
+ expect(submit?.params?.confirm_truncate).toBe(true)
+ expect(submit?.params?.truncate_before_message_id).toBe('durable-platform-msg-1')
+ expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()
+ })
+
+ it('still confirms an empty truncate when the dropped ordinal was 0', async () => {
+ const calls: Call[] = []
+
+ await runRewindSubmit(
+ makeGateway(calls),
+ 'sid',
+ 'fixed prompt',
+ 0,
+ 'durable-platform-msg-1',
+ false,
+ undefined,
+ 13,
+ 'typo prompt'
+ )
+
+ const submit = calls.find(call => call.method === 'prompt.submit')
+
+ expect(submit?.params?.confirm_truncate).toBe(true)
+ expect(submit?.params?.confirm_empty_truncate).toBe(true)
+ expect(submit?.params?.truncate_before_row_id).toBe(13)
+ expect(submit?.params?.truncate_before_user_ordinal).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.ts
index aec6ad6ac60..6ca5483cd9c 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
@@ -262,6 +262,18 @@ export async function runRewindSubmit(
resolvedMessageId = undefined
}
+ // Durable id present (#88082, #89244): drop the client ordinal. Renderer
+ // ordinals and gateway tip ordinals are different spaces — tail-only
+ // prefetch (window-relative), in-place compact (display-lineage scrollback
+ // vs tip, prefix_user_count structurally 0), and any later visibility
+ // skew. The cut is aimed by the resolved durable id; sending a divergent
+ // ordinal trips the gateway's 4030 cross-check. Unknown ids still fail
+ // closed at 4018. The ordinal is only a tripwire, and it is calibrated in
+ // a space the gateway cannot reliably compute.
+ if (wantsTruncation && hasDurableAddress) {
+ resolvedOrdinal = undefined
+ }
+
const interrupt = async () => {
try {
await requestGateway('session.interrupt', { session_id: liveSessionId })
@@ -278,13 +290,11 @@ export async function runRewindSubmit(
text,
...truncateSubmitParams(resolvedOrdinal, resolvedMessageId, resolvedRowId),
// A first-turn rewind resolves to an empty transcript, which the
- // gateway additionally gates behind confirm_empty_truncate. In
- // resolved-row-id mode the ordinal was dropped (see above), so carry
- // the flag from the caller's ordinal-0 belief: required when right,
- // ignored by the gateway when the cut isn't actually empty.
- ...(resolvedRowId !== undefined && resolvedOrdinal === undefined && truncateOrdinal === 0
- ? { confirm_empty_truncate: true }
- : {})
+ // gateway additionally gates behind confirm_empty_truncate. When the
+ // client ordinal is dropped (durable-id path), carry the flag from
+ // the caller's ordinal-0 belief: required when right, ignored by the
+ // gateway when the cut isn't actually empty.
+ ...(resolvedOrdinal === undefined && truncateOrdinal === 0 ? { confirm_empty_truncate: true } : {})
},
PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
)
diff --git a/tests/tui_gateway/test_session_profile_db.py b/tests/tui_gateway/test_session_profile_db.py
new file mode 100644
index 00000000000..f41a5873bf4
--- /dev/null
+++ b/tests/tui_gateway/test_session_profile_db.py
@@ -0,0 +1,392 @@
+"""Session-scoped transcript ops must resolve against the session's own DB.
+
+App-global remote mode gives a session its own profile (``profile_home`` on
+the session dict, see ``session.create``), and that profile keeps its own
+``state.db``. ``_get_db()`` is the *launch* profile's handle, so any
+session-scoped read or write that reaches for it operates on the wrong
+database: writes land in a foreign profile under this session's id, and reads
+come back empty because the row simply is not there.
+
+``_session_db(session)`` is the profile-aware resolver that already exists for
+exactly this (``tui_gateway/server.py``): the profile's ``state.db`` when
+``session['profile_home']`` is set, otherwise the shared launch handle.
+
+Every test here drives the real JSON-RPC entry point
+(``server.handle_request``). Handler bodies live in ``tui_gateway/methods_*``
+but are rebound onto ``server.py``'s globals by
+``method_ctx.HandlerRegistry.install()``, so calling a handler function
+directly would bypass the path the gateway actually executes.
+"""
+
+from __future__ import annotations
+
+import importlib
+import threading
+import types
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from hermes_state import SessionDB
+
+SESSION_ID = "sid-profile"
+SESSION_KEY = "tui-profile-1"
+
+
+def hermes_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ yield home
+
+
+def server(hermes_home):
+ # Mocks are scoped to the initial import only (see
+ # tests/tui_gateway/test_protocol.py for the rationale).
+ with patch.dict(
+ "sys.modules",
+ {
+ "hermes_cli.env_loader": MagicMock(),
+ "hermes_cli.banner": MagicMock(),
+ },
+ ):
+ mod = importlib.import_module("tui_gateway.server")
+
+ methods = dict(mod._methods)
+ yield mod
+ # Restore in place instead of clear+reload: importlib.reload re-registers
+ # atexit hooks and re-captures module-level paths against this test's
+ # soon-deleted tmpdir (see tests/tui_gateway/test_undo_command.py).
+ mod._methods.clear()
+ mod._methods.update(methods)
+ mod._sessions.clear()
+ mod._pending.clear()
+ mod._answers.clear()
+ mod._db = None
+
+
+def launch_db(server, hermes_home):
+ """The launch profile's state.db, wired in as the ``_get_db()`` handle."""
+ db = SessionDB(db_path=hermes_home / "state.db")
+ server._db = db
+ return db
+
+
+def profile_db(tmp_path):
+ """A second, non-launch profile's state.db."""
+ profile_home = tmp_path / "profiles" / "work"
+ profile_home.mkdir(parents=True)
+ return profile_home, SessionDB(db_path=profile_home / "state.db")
+
+
+def _seed(db, turns=3, *, _capture_user_row_ids=None):
+ db.create_session(SESSION_KEY, source="tui")
+ for i in range(1, turns + 1):
+ uid = db.append_message(SESSION_KEY, "user", f"question {i}")
+ if _capture_user_row_ids is not None:
+ _capture_user_row_ids.append(uid)
+ db.append_message(SESSION_KEY, "assistant", f"answer {i}")
+ return db.get_messages_as_conversation(SESSION_KEY)
+
+
+def _register(server, history, *, profile_home=None):
+ # SimpleNamespace, not MagicMock: the usage snapshot compares attributes
+ # numerically, and auto-created mock attributes are not orderable.
+ agent = types.SimpleNamespace(
+ _memory_manager=MagicMock(),
+ _last_flushed_db_idx=len(history),
+ model="test-model",
+ )
+ session = {
+ "session_key": SESSION_KEY,
+ "history": list(history),
+ "history_lock": threading.Lock(),
+ "history_version": 0,
+ "running": False,
+ "agent": agent,
+ "attached_images": [],
+ "image_counter": 0,
+ "cols": 120,
+ # The cap slot is claimed on the first real turn; pre-claim it so the
+ # test exercises the transcript path rather than the lease allocator.
+ "active_session_lease": object(),
+ }
+ if profile_home is not None:
+ session["profile_home"] = str(profile_home)
+ server._sessions[SESSION_ID] = session
+ return session
+
+
+def _rpc(server, method, params):
+ return server.handle_request({"id": "1", "method": method, "params": params})
+
+
+def _texts(rows):
+ out = []
+ for row in rows:
+ content = row.get("content")
+ if isinstance(content, list):
+ content = "".join(
+ part.get("text", "")
+ for part in content
+ if isinstance(part, dict) and part.get("type") == "text"
+ )
+ out.append(str(content or ""))
+ return out
+
+
+# ---------------------------------------------------------------------------
+# /undo — command.dispatch
+# ---------------------------------------------------------------------------
+
+
+def test_undo_rewinds_the_profile_transcript(server, launch_db, profile_db):
+ """/undo on a profile session must read and rewind that profile's db.
+
+ ``list_recent_user_messages`` is session-id scoped, so against the launch
+ handle it finds nothing and /undo fails closed with 4018 — the command is
+ unusable for the entire session in app-global remote mode.
+ """
+ profile_home, pdb = profile_db
+ history = _seed(pdb)
+ _register(server, history, profile_home=profile_home)
+
+ resp = _rpc(
+ server,
+ "command.dispatch",
+ {"session_id": SESSION_ID, "name": "undo", "arg": ""},
+ )
+
+ assert not resp.get("error"), f"/undo failed: {resp.get('error')}"
+ result = resp["result"]
+ assert result["type"] == "prefill"
+ assert result["message"] == "question 3"
+ # The rewind is durable in the profile's own db, not the launch one.
+ assert _texts(pdb.get_messages_as_conversation(SESSION_KEY)) == [
+ "question 1",
+ "answer 1",
+ "question 2",
+ "answer 2",
+ ]
+ assert launch_db.get_messages_as_conversation(SESSION_KEY) == []
+
+
+def test_undo_still_uses_the_shared_handle_without_a_profile(server, launch_db):
+ """A launch-profile session keeps borrowing the shared ``_get_db()`` handle."""
+ history = _seed(launch_db)
+ _register(server, history)
+
+ resp = _rpc(
+ server,
+ "command.dispatch",
+ {"session_id": SESSION_ID, "name": "undo", "arg": ""},
+ )
+
+ assert not resp.get("error"), f"/undo failed: {resp.get('error')}"
+ assert resp["result"]["message"] == "question 3"
+ assert _texts(launch_db.get_messages_as_conversation(SESSION_KEY)) == [
+ "question 1",
+ "answer 1",
+ "question 2",
+ "answer 2",
+ ]
+
+
+# ---------------------------------------------------------------------------
+# edit/resend truncation — prompt.submit
+# ---------------------------------------------------------------------------
+
+
+def _stop_after_truncate(server, monkeypatch):
+ """Return the RPC right after the truncate branch, before the agent turn.
+
+ Isolated turns hand the prompt to the compute host and return, which is
+ the natural exit closest to the code under test; stubbing the handoff keeps
+ the test on the transcript-persistence path instead of running a model.
+ """
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: True)
+ monkeypatch.setattr(
+ server,
+ "_submit_prompt_to_compute_host",
+ lambda rid, sid, session, text, **_kwargs: server._ok(
+ rid, {"status": "streaming"}
+ ),
+ )
+
+
+def test_truncation_persists_to_the_profile_db(server, launch_db, profile_db, monkeypatch):
+ """An edit/resend must truncate the profile's transcript, not the launch one."""
+ profile_home, pdb = profile_db
+ user_row_ids: list = []
+ history = _seed(pdb, _capture_user_row_ids=user_row_ids)
+ _register(server, history, profile_home=profile_home)
+ _stop_after_truncate(server, monkeypatch)
+
+ # Row-id addressed, not ordinal-only: current main refuses a bare ordinal
+ # for a durable session (truncate_before_row_id required). Target the 2nd
+ # user turn's durable row id; keep the matching ordinal as a cross-check.
+ resp = _rpc(
+ server,
+ "prompt.submit",
+ {
+ "session_id": SESSION_ID,
+ "text": "edited question 2",
+ "truncate_before_row_id": user_row_ids[1],
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ )
+
+ assert not resp.get("error"), f"prompt.submit failed: {resp.get('error')}"
+ # The undone turns are gone from the profile's own db, so session.resume
+ # (which opens the profile db correctly) cannot resurrect them.
+ assert _texts(pdb.get_messages_as_conversation(SESSION_KEY)) == [
+ "question 1",
+ "answer 1",
+ ]
+ # ...and nothing was copied into a foreign profile under this session id.
+ assert launch_db.get_messages_as_conversation(SESSION_KEY) == []
+
+
+def test_truncation_does_not_copy_rows_into_the_launch_profile(
+ server, launch_db, profile_db, monkeypatch
+):
+ """The launch profile must not receive a copy of a profile session's turns.
+
+ When the launch db happens to hold a row under the same session id, the
+ write through the launch handle succeeds instead of failing the foreign-key
+ check, so the truncated transcript is inserted into a profile the session
+ does not belong to.
+ """
+ profile_home, pdb = profile_db
+ user_row_ids: list = []
+ history = _seed(pdb, _capture_user_row_ids=user_row_ids)
+ launch_db.create_session(SESSION_KEY, source="unknown")
+ _register(server, history, profile_home=profile_home)
+ _stop_after_truncate(server, monkeypatch)
+
+ resp = _rpc(
+ server,
+ "prompt.submit",
+ {
+ "session_id": SESSION_ID,
+ "text": "edited question 2",
+ "truncate_before_row_id": user_row_ids[1],
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ )
+
+ assert not resp.get("error"), f"prompt.submit failed: {resp.get('error')}"
+ assert launch_db.get_messages_as_conversation(SESSION_KEY) == []
+ assert _texts(pdb.get_messages_as_conversation(SESSION_KEY)) == [
+ "question 1",
+ "answer 1",
+ ]
+
+
+def test_truncation_surfaces_the_profile_dbs_new_row_ids(
+ server, launch_db, profile_db, monkeypatch
+):
+ """``survivor_user_row_ids`` must carry the profile db's post-rewrite ids.
+
+ ``replace_messages`` re-inserts the surviving prefix as NEW rows and the
+ client rebinds its cached stamps from this payload, so the ids have to come
+ from the db that actually did the rewrite. Ids minted anywhere else address
+ nothing in the profile's transcript, and the next rewind is refused 4018.
+ """
+ profile_home, pdb = profile_db
+ user_row_ids: list = []
+ history = _seed(pdb, _capture_user_row_ids=user_row_ids)
+ _register(server, history, profile_home=profile_home)
+ _stop_after_truncate(server, monkeypatch)
+
+ resp = _rpc(
+ server,
+ "prompt.submit",
+ {
+ "session_id": SESSION_ID,
+ "text": "edited question 2",
+ "truncate_before_row_id": user_row_ids[1],
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ )
+
+ assert not resp.get("error"), f"prompt.submit failed: {resp.get('error')}"
+ surviving = [
+ row["_row_id"]
+ for row in pdb.get_messages_as_conversation(SESSION_KEY, include_row_ids=True)
+ if row["role"] == "user"
+ ]
+ assert resp["result"]["survivor_user_row_ids"] == surviving
+ # Fresh rows, not the pre-rewind ids the client sent in.
+ assert user_row_ids[0] not in surviving
+
+
+def test_truncation_without_a_profile_uses_the_shared_handle(server, launch_db, monkeypatch):
+ user_row_ids: list = []
+ history = _seed(launch_db, _capture_user_row_ids=user_row_ids)
+ _register(server, history)
+ _stop_after_truncate(server, monkeypatch)
+
+ resp = _rpc(
+ server,
+ "prompt.submit",
+ {
+ "session_id": SESSION_ID,
+ "text": "edited question 2",
+ "truncate_before_row_id": user_row_ids[1],
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ )
+
+ assert not resp.get("error"), f"prompt.submit failed: {resp.get('error')}"
+ assert _texts(launch_db.get_messages_as_conversation(SESSION_KEY)) == [
+ "question 1",
+ "answer 1",
+ ]
+
+
+# ---------------------------------------------------------------------------
+# /history and /context — slash.exec
+# ---------------------------------------------------------------------------
+
+
+def test_history_reads_the_profile_transcript(server, launch_db, profile_db):
+ """/history must render the profile session's own transcript."""
+ profile_home, pdb = profile_db
+ _seed(pdb)
+ # In-memory history is deliberately empty: the point of the db read is to
+ # rebuild the transcript for a session the process did not run itself.
+ _register(server, [], profile_home=profile_home)
+
+ resp = _rpc(server, "slash.exec", {"session_id": SESSION_ID, "command": "/history"})
+
+ assert not resp.get("error"), f"/history failed: {resp.get('error')}"
+ output = resp["result"]["output"]
+ assert "question 3" in output
+ assert "answer 3" in output
+
+
+def test_context_reads_the_profile_transcript(server, launch_db, profile_db, monkeypatch):
+ """/context must count the profile session's own messages."""
+ profile_home, pdb = profile_db
+ _seed(pdb)
+ _register(server, [], profile_home=profile_home)
+ # /context is an isolated-session read command, gated on the compute host.
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: True)
+
+ resp = _rpc(server, "slash.exec", {"session_id": SESSION_ID, "command": "/context"})
+
+ assert not resp.get("error"), f"/context failed: {resp.get('error')}"
+ output = resp["result"]["output"]
+ assert "Conversation: 6 messages" in output
+ assert "user: 3, assistant: 3" in output
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 6cae7b49e04..fa0dcd949f3 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -645,66 +645,79 @@ def _(rid, params: dict) -> dict:
# new exchange is appended on top of the "undone" turns — durable
# zombie history on resume, and the edit/regenerate never sticks.
# Fail closed: refuse the turn and leave memory/DB unchanged.
- if (db := _get_db()) is not None:
- try:
- # active_only=True: replace only the live (active=1) rows.
- # In-place compaction (#38763) keeps the pre-compaction
- # transcript as active=0/compacted=1 rows under this same
- # session key; a bare replace_messages() would DELETE that
- # durable archive on every edit/regenerate — the same bug
- # class #80216 fixed for /retry. On an uncompacted session
- # all rows are active=1, so this is behaviorally identical
- # to the full replace.
- # archive_dropped: a rewind overwrites turns the user may
- # not have meant to drop, and this write is the last step
- # before they are gone — three reported incidents ended
- # here with nothing to restore from (#70516, #80763,
- # #82756). Soft-archiving keeps them on disk (active=0) and
- # in the FTS index, so a mis-aimed cut is recoverable
- # instead of terminal. The live transcript is unchanged.
- # Fall back to session id when session_key is NULL — CLI-origin
- # sessions created before the session_key default fix have no
- # key, and replace_messages(None) triggers an FK violation.
- truncation_key = session.get("session_key") or sid
- db.replace_messages(
- truncation_key,
- truncated,
- active_only=True,
- archive_dropped=True,
- )
- except Exception as exc:
- logger.error(
- "prompt.submit: replace_messages failed for session %s "
- "(ordinal=%d); refusing turn so memory and DB stay "
- "aligned: %s",
- sid,
- ordinal,
- exc,
- exc_info=True,
- )
- return _err(
- rid,
- 5008,
- f"failed to persist history truncation: {exc}",
- )
+ #
+ # _session_db, not _get_db(): the truncation has to land in the db
+ # that owns this session's row. A profile session (app-global
+ # remote mode) keeps its transcript in its own profile's state.db,
+ # so writing through the launch handle both loses the edit — resume
+ # reopens the profile db and resurrects the undone turns — and
+ # copies the transcript into a foreign profile under this session's
+ # id when that profile happens to hold a row for it. Fail-closed
+ # only holds if the handle we check is the one that owns the row.
+ with _session_db(session) as db:
+ if db is not None:
+ try:
+ # active_only=True: replace only the live (active=1)
+ # rows. In-place compaction (#38763) keeps the
+ # pre-compaction transcript as active=0/compacted=1
+ # rows under this same session key; a bare
+ # replace_messages() would DELETE that durable archive
+ # on every edit/regenerate — the same bug class #80216
+ # fixed for /retry. On an uncompacted session all rows
+ # are active=1, so this is behaviorally identical to
+ # the full replace.
+ # archive_dropped: a rewind overwrites turns the user
+ # may not have meant to drop, and this write is the
+ # last step before they are gone — three reported
+ # incidents ended here with nothing to restore from
+ # (#70516, #80763, #82756). Soft-archiving keeps them
+ # on disk (active=0) and in the FTS index, so a
+ # mis-aimed cut is recoverable instead of terminal.
+ # The live transcript is unchanged.
+ # Fall back to session id when session_key is NULL —
+ # CLI-origin sessions created before the session_key
+ # default fix have no key, and replace_messages(None)
+ # triggers an FK violation.
+ truncation_key = session.get("session_key") or sid
+ db.replace_messages(
+ truncation_key,
+ truncated,
+ active_only=True,
+ archive_dropped=True,
+ )
+ except Exception as exc:
+ logger.error(
+ "prompt.submit: replace_messages failed for session %s "
+ "(ordinal=%d); refusing turn so memory and DB stay "
+ "aligned: %s",
+ sid,
+ ordinal,
+ exc,
+ exc_info=True,
+ )
+ return _err(
+ rid,
+ 5008,
+ f"failed to persist history truncation: {exc}",
+ )
+ # replace_messages re-inserted the surviving prefix as NEW
+ # rows and stamped fresh _row_id values onto these same
+ # dicts. Surface the surviving user-turn ids (in
+ # visible-user-ordinal order) so the client can rebind its
+ # cached rowId stamps — otherwise a second rewind targeting
+ # an older surviving turn sends the pre-rewind id and the
+ # fail-closed resolver refuses it with 4018 (#83202 review:
+ # consecutive-rewind staleness). Ordinal order matches the
+ # client's visible-user filter the same way truncate
+ # ordinals already do. Entries are None when a row somehow
+ # has no stamp — the client must drop its cached id for
+ # that turn rather than keep a stale one.
+ survivor_user_row_ids = [
+ _message_row_id(truncated[i])
+ for i in _history_user_indices(truncated)
+ ]
session["history"] = truncated
session["history_version"] = int(session.get("history_version", 0)) + 1
- if db is not None:
- # replace_messages re-inserted the surviving prefix as NEW rows
- # and stamped fresh _row_id values onto these same dicts.
- # Surface the surviving user-turn ids (in visible-user-ordinal
- # order) so the client can rebind its cached rowId stamps —
- # otherwise a second rewind targeting an older surviving turn
- # sends the pre-rewind id and the fail-closed resolver refuses
- # it with 4018 (#83202 review: consecutive-rewind staleness).
- # Ordinal order matches the client's visible-user filter the
- # same way truncate ordinals already do. Entries are None when
- # a row somehow has no stamp — the client must drop its cached
- # id for that turn rather than keep a stale one.
- survivor_user_row_ids = [
- _message_row_id(truncated[i])
- for i in _history_user_indices(truncated)
- ]
session["running"] = True
session["_turn_cancel_requested"] = False
session["last_active"] = time.time()
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index f92e2d4d9a7..cece5fbbe4a 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -887,50 +887,55 @@ def _(rid, params: dict) -> dict:
return _err(
rid, 4009, "session busy — /interrupt the current turn before /undo"
)
- db = _get_db()
- if db is None:
- return _db_unavailable_error(rid, code=5008)
- session_key = session.get("session_key", "")
- if not session_key:
- return _err(rid, 4001, "no session key for undo")
- # Parse the optional count argument (e.g. "/undo 3" → 3).
- n = 1
- arg_str = (arg or "").strip()
- if arg_str:
- try:
- n = int(arg_str.split()[0])
- except (ValueError, IndexError):
- return _err(rid, 4004, f"undo: invalid count {arg_str!r} — use /undo or /undo N")
- if n < 1:
+ # _session_db, not _get_db(): every read and write below is scoped by
+ # session id, and a profile session (app-global remote mode) keeps its
+ # rows in its own profile's state.db. Against the launch handle
+ # list_recent_user_messages finds nothing, so /undo fails closed with
+ # 4018 for the whole session instead of rewinding anything.
+ with _session_db(session) as db:
+ if db is None:
+ return _db_unavailable_error(rid, code=5008)
+ session_key = session.get("session_key", "")
+ if not session_key:
+ return _err(rid, 4001, "no session key for undo")
+ # Parse the optional count argument (e.g. "/undo 3" → 3).
n = 1
- try:
- recents = db.list_recent_user_messages(session_key, limit=max(n, 10))
- except Exception as e:
- return _err(rid, 5008, f"undo: failed to load history: {e}")
- if not recents:
- return _err(rid, 4018, "no user messages to undo")
- # recents[0] is the most-recent user turn; pick the Nth-from-last.
- # If N exceeds the number of user turns, back up to the oldest.
- target_idx = min(n - 1, len(recents) - 1)
- target_id = recents[target_idx]["id"]
- try:
- result = db.rewind_to_message(session_key, target_id)
- except ValueError as e:
- return _err(rid, 4004, f"undo: {e}")
- except Exception as e:
- return _err(rid, 5008, f"undo: {e}")
- # Reload the active-only transcript into the in-memory session
- # history so subsequent turns see the truncated view.
- # repair_alternation: this reload feeds LIVE REPLAY — session["history"]
- # is the working conversation for subsequent turns, and a rewind that
- # lands on a durable user;user pair would otherwise re-fire the
- # pre-request repair on every request from here on.
- try:
- active = db.get_messages_as_conversation(
- session_key, repair_alternation=True, include_row_ids=True
- )
- except Exception:
- active = []
+ arg_str = (arg or "").strip()
+ if arg_str:
+ try:
+ n = int(arg_str.split()[0])
+ except (ValueError, IndexError):
+ return _err(rid, 4004, f"undo: invalid count {arg_str!r} — use /undo or /undo N")
+ if n < 1:
+ n = 1
+ try:
+ recents = db.list_recent_user_messages(session_key, limit=max(n, 10))
+ except Exception as e:
+ return _err(rid, 5008, f"undo: failed to load history: {e}")
+ if not recents:
+ return _err(rid, 4018, "no user messages to undo")
+ # recents[0] is the most-recent user turn; pick the Nth-from-last.
+ # If N exceeds the number of user turns, back up to the oldest.
+ target_idx = min(n - 1, len(recents) - 1)
+ target_id = recents[target_idx]["id"]
+ try:
+ result = db.rewind_to_message(session_key, target_id)
+ except ValueError as e:
+ return _err(rid, 4004, f"undo: {e}")
+ except Exception as e:
+ return _err(rid, 5008, f"undo: {e}")
+ # Reload the active-only transcript into the in-memory session
+ # history so subsequent turns see the truncated view.
+ # repair_alternation: this reload feeds LIVE REPLAY — session["history"]
+ # is the working conversation for subsequent turns, and a rewind that
+ # lands on a durable user;user pair would otherwise re-fire the
+ # pre-request repair on every request from here on.
+ try:
+ active = db.get_messages_as_conversation(
+ session_key, repair_alternation=True, include_row_ids=True
+ )
+ except Exception:
+ active = []
with session["history_lock"]:
session["history"] = list(active)
session["history_version"] = int(session.get("history_version", 0)) + 1
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 7f8ea642b13..00fe1143658 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -13889,14 +13889,17 @@ def _format_live_usage_output(session: dict) -> str:
def _format_live_history_output(session: dict) -> str:
with session["history_lock"]:
history = list(session.get("history", []))
- db = _get_db()
- if db is not None and session.get("session_key"):
- try:
- history = db.get_messages_as_conversation(
- session["session_key"], include_ancestors=True, include_row_ids=True
- )
- except Exception:
- pass
+ # _session_db, not _get_db(): a profile session's transcript lives in its
+ # own profile's state.db, and this read is scoped by session id — through
+ # the launch handle it comes back empty and /history renders nothing.
+ with _session_db(session) as db:
+ if db is not None and session.get("session_key"):
+ try:
+ history = db.get_messages_as_conversation(
+ session["session_key"], include_ancestors=True, include_row_ids=True
+ )
+ except Exception:
+ pass
messages = _history_to_messages(history)
if not messages:
return "No conversation history yet."
@@ -13929,16 +13932,18 @@ def _format_live_prompt_output(session: dict) -> str:
def _format_live_context_output(session: dict) -> str:
messages = []
- db = _get_db()
- if db is not None and session.get("session_key"):
- try:
- messages = _history_to_messages(
- db.get_messages_as_conversation(
- session["session_key"], include_ancestors=True, include_row_ids=True
+ # Same session-scoped read as /history — resolve it against the db that
+ # owns this session's rows, not the launch profile's handle.
+ with _session_db(session) as db:
+ if db is not None and session.get("session_key"):
+ try:
+ messages = _history_to_messages(
+ db.get_messages_as_conversation(
+ session["session_key"], include_ancestors=True, include_row_ids=True
+ )
)
- )
- except Exception:
- messages = []
+ except Exception:
+ messages = []
if not messages:
with session["history_lock"]:
messages = _history_to_messages(list(session.get("history", [])))