Skip to content

The agent that grows with you

fix(state,desktop): only a compacted rewind target says the message was summarized

Teknium216e66150cc3
diff --git a/apps/desktop/src/i18n/ar_boot.ts b/apps/desktop/src/i18n/ar_boot.ts
index 7f99bc4c927..edc47f750fb 100644
--- a/apps/desktop/src/i18n/ar_boot.ts
+++ b/apps/desktop/src/i18n/ar_boot.ts
@@ -82,6 +82,7 @@ export const arBoot = {
mcpReloadNotInChat: server => `${server} غير مفعّل في هذه المحادثة`,
mcpReloadUnavailable: servers => `تعذّر الاتصال: ${servers}`,
compactedTurnUnavailable: 'تم تلخيص هذه الرسالة عند ضغط المحادثة، لذا لم يعد بالإمكان استعادتها أو تحريرها.',
+ staleTurnUnavailable: 'لم تعد هذه الرسالة موجودة في سجل هذه المحادثة.',
sessionCommands: arSessionCommands
},
updates: {
diff --git a/apps/desktop/src/i18n/de_notices.ts b/apps/desktop/src/i18n/de_notices.ts
index 0dfa82d2de5..15e6e325c1a 100644
--- a/apps/desktop/src/i18n/de_notices.ts
+++ b/apps/desktop/src/i18n/de_notices.ts
@@ -26,6 +26,7 @@ export const deNotices = {
mcpReloadUnavailable: servers => `Keine Verbindung: ${servers}`,
compactedTurnUnavailable:
'Diese Nachricht wurde beim Komprimieren des Chats zusammengefasst und kann nicht mehr wiederhergestellt oder bearbeitet werden.',
+ staleTurnUnavailable: 'Diese Nachricht ist nicht mehr im Verlauf dieses Chats.',
sessionCommands: deSessionCommands
},
keepAwakeOffer: {
diff --git a/apps/desktop/src/i18n/en_notices.ts b/apps/desktop/src/i18n/en_notices.ts
index 9cd8e0504a7..5dca1ecd381 100644
--- a/apps/desktop/src/i18n/en_notices.ts
+++ b/apps/desktop/src/i18n/en_notices.ts
@@ -26,6 +26,7 @@ export const enNotices = {
mcpReloadUnavailable: servers => `Did not connect: ${servers}`,
compactedTurnUnavailable:
"That message was summarized when the chat was compressed, so it can't be restored or edited anymore.",
+ staleTurnUnavailable: "That message is no longer in this chat's history.",
sessionCommands: enSessionCommands
},
keepAwakeOffer: {
diff --git a/apps/desktop/src/i18n/es_notices.ts b/apps/desktop/src/i18n/es_notices.ts
index c014e4880fe..b388f6f2b22 100644
--- a/apps/desktop/src/i18n/es_notices.ts
+++ b/apps/desktop/src/i18n/es_notices.ts
@@ -26,6 +26,7 @@ export const esNotices = {
mcpReloadUnavailable: servers => `No se conectó: ${servers}`,
compactedTurnUnavailable:
'Ese mensaje se resumió al comprimir el chat, así que ya no se puede restaurar ni editar.',
+ staleTurnUnavailable: 'Ese mensaje ya no está en el historial de este chat.',
sessionCommands: esSessionCommands
},
keepAwakeOffer: {
diff --git a/apps/desktop/src/i18n/fr_notices.ts b/apps/desktop/src/i18n/fr_notices.ts
index 65ebf03c516..9870aafbee7 100644
--- a/apps/desktop/src/i18n/fr_notices.ts
+++ b/apps/desktop/src/i18n/fr_notices.ts
@@ -26,6 +26,7 @@ export const frNotices = {
mcpReloadUnavailable: servers => `Connexion impossible : ${servers}`,
compactedTurnUnavailable:
'Ce message a été résumé lors de la compression de la conversation : il ne peut plus être restauré ni modifié.',
+ staleTurnUnavailable: 'Ce message ne fait plus partie de l’historique de cette discussion.',
sessionCommands: frSessionCommands
},
keepAwakeOffer: {
diff --git a/apps/desktop/src/i18n/ja_notices.ts b/apps/desktop/src/i18n/ja_notices.ts
index 6e135d23743..e0d709ea1f9 100644
--- a/apps/desktop/src/i18n/ja_notices.ts
+++ b/apps/desktop/src/i18n/ja_notices.ts
@@ -25,6 +25,7 @@ export const jaNotices = {
mcpReloadNotInChat: server => `${server} はこのチャットでは有効になっていません`,
mcpReloadUnavailable: servers => `接続できませんでした: ${servers}`,
compactedTurnUnavailable: 'このメッセージはチャットの圧縮時に要約されたため、復元や編集はできなくなりました。',
+ staleTurnUnavailable: 'このメッセージはこのチャットの履歴にはもうありません。',
sessionCommands: jaSessionCommands
},
keepAwakeOffer: {
diff --git a/apps/desktop/src/i18n/ru_notices.ts b/apps/desktop/src/i18n/ru_notices.ts
index 97a4a1e0cbd..4303773b3d3 100644
--- a/apps/desktop/src/i18n/ru_notices.ts
+++ b/apps/desktop/src/i18n/ru_notices.ts
@@ -26,6 +26,7 @@ export const ruNotices = {
mcpReloadUnavailable: servers => `Не удалось подключиться: ${servers}`,
compactedTurnUnavailable:
'Это сообщение было сжато в краткое изложение при сжатии чата, поэтому его больше нельзя восстановить или изменить.',
+ staleTurnUnavailable: 'Этого сообщения больше нет в истории этого чата.',
sessionCommands: ruSessionCommands
},
keepAwakeOffer: {
diff --git a/apps/desktop/src/i18n/types_notices.ts b/apps/desktop/src/i18n/types_notices.ts
index a011619b8f0..9623ffc6f02 100644
--- a/apps/desktop/src/i18n/types_notices.ts
+++ b/apps/desktop/src/i18n/types_notices.ts
@@ -21,6 +21,8 @@ export interface NoticeTranslations {
mcpReloadUnavailable: (servers: string) => string
/** An edit/restore/regenerate whose target compaction archived: the owner refused the rewind. */
compactedTurnUnavailable: string
+ /** The same refusal for any other stale target: undone in another window, not a user turn, or gone. */
+ staleTurnUnavailable: string
/** Typed /undo /retry /steer /queue lines (the Ink TUI's wording on the same gateway). */
sessionCommands: SessionCommandNotices
}
diff --git a/apps/desktop/src/i18n/zh-hant_boot.ts b/apps/desktop/src/i18n/zh-hant_boot.ts
index 2080b18c046..578cf3f9c91 100644
--- a/apps/desktop/src/i18n/zh-hant_boot.ts
+++ b/apps/desktop/src/i18n/zh-hant_boot.ts
@@ -83,6 +83,7 @@ export const zhHantBoot = {
mcpReloadNotInChat: server => `此對話未啟用 ${server}`,
mcpReloadUnavailable: servers => `未能連線:${servers}`,
compactedTurnUnavailable: '這則訊息在壓縮對話時已被摘要,無法再還原或編輯。',
+ staleTurnUnavailable: '這則訊息已不在此對話的歷史記錄中。',
sessionCommands: zhHantSessionCommands
},
diff --git a/apps/desktop/src/i18n/zh_notices.ts b/apps/desktop/src/i18n/zh_notices.ts
index 98265b53e08..795e4d9f580 100644
--- a/apps/desktop/src/i18n/zh_notices.ts
+++ b/apps/desktop/src/i18n/zh_notices.ts
@@ -22,6 +22,7 @@ export const zhNotices = {
mcpReloadNotInChat: server => `此对话未启用 ${server}`,
mcpReloadUnavailable: servers => `未能连接:${servers}`,
compactedTurnUnavailable: '这条消息在压缩对话时已被概括,无法再恢复或编辑。',
+ staleTurnUnavailable: '这条消息已不在此对话的历史记录中。',
sessionCommands: zhSessionCommands
},
keepAwakeOffer: {
diff --git a/apps/desktop/src/store/notifications.test.ts b/apps/desktop/src/store/notifications.test.ts
index 21d04a708c7..4d406b71848 100644
--- a/apps/desktop/src/store/notifications.test.ts
+++ b/apps/desktop/src/store/notifications.test.ts
@@ -144,14 +144,14 @@ test('code-skew 503 unwraps to a restart-required summary, not raw IPC JSON', ()
})
// RT-39: an edit/restore aimed above a compaction boundary is refused by the owner with
-// invalid_params on target_message_id. The toast says so in plain words, not the bare code.
+// invalid_params on target_message_id and a `compacted:` detail. The toast says so in plain words.
test('a rewind refused for a compacted target says the message was summarized', () => {
const refused = new JsonRpcGatewayError('invalid_params', {
code: 4001,
data: {
reason: 'invalid_params',
field: 'target_message_id',
- detail: 'target user message is no longer in session history'
+ detail: 'compacted: target user message was summarized when the session was compressed'
}
})
@@ -164,6 +164,28 @@ test('a rewind refused for a compacted target says the message was summarized',
expect(toast?.detail).toBeUndefined()
})
+// The same refusal without the marker (a turn another window undid, an assistant row, an unknown id)
+// never claims a compression happened.
+test('a rewind refused for any other stale target says it is no longer in the history', () => {
+ notifyError(
+ new JsonRpcGatewayError('invalid_params', {
+ code: 4001,
+ data: {
+ reason: 'invalid_params',
+ field: 'target_message_id',
+ detail: 'target user message is no longer in session history'
+ }
+ }),
+ 'Restore failed'
+ )
+
+ const toast = $notifications.get()[0]
+ expect(toast?.title).toBe('Restore failed')
+ expect(toast?.message).toBe(en.promptNotices.staleTurnUnavailable)
+ expect(toast?.message).not.toBe(en.promptNotices.compactedTurnUnavailable)
+ expect(toast?.detail).toBeUndefined()
+})
+
test('an unrelated invalid_params keeps the generic toast', () => {
notifyError(
new JsonRpcGatewayError('invalid_params', { code: 4001, data: { reason: 'invalid_params', field: 'title' } }),
diff --git a/apps/desktop/src/store/notifications.ts b/apps/desktop/src/store/notifications.ts
index 5483b317e90..6655e827035 100644
--- a/apps/desktop/src/store/notifications.ts
+++ b/apps/desktop/src/store/notifications.ts
@@ -228,19 +228,25 @@ function summarizeErrorMessage(message: string, fallback: string) {
}
}
-// The owner's rewind refusal for a row compaction archived (hermes_state_mutations._rewind): an
-// edit, restore or regenerate aimed above the compaction boundary. Matched on the structured
-// reason + field, so every other invalid_params keeps the generic toast.
-function isCompactedRewindRefusal(error: unknown): boolean {
+// The owner's refusal of an edit, restore or regenerate whose target is not a live user turn
+// (hermes_state_mutations._rewind): invalid_params on target_message_id. Its detail starts with
+// `compacted:` only when compaction summarized the turn; a turn another window already undid, an
+// assistant row or an unknown id is stale for another reason. Every other invalid_params keeps the
+// generic toast.
+function staleRewindRefusal(error: unknown): 'compacted' | 'stale' | null {
const data = error && typeof error === 'object' ? (error as { data?: unknown }).data : undefined
if (!data || typeof data !== 'object') {
- return false
+ return null
}
- const { field, reason } = data as { field?: unknown; reason?: unknown }
+ const { detail, field, reason } = data as { detail?: unknown; field?: unknown; reason?: unknown }
- return reason === 'invalid_params' && field === 'target_message_id'
+ if (reason !== 'invalid_params' || field !== 'target_message_id') {
+ return null
+ }
+
+ return typeof detail === 'string' && detail.startsWith('compacted:') ? 'compacted' : 'stale'
}
// Exported so flows that surface errors inline (e.g. ConfirmDialog's onConfirm
@@ -249,8 +255,12 @@ export function readableError(
error: unknown,
fallback: string
): { message: string; detail?: string; action?: NotificationAction; category: ErrorToastCategory } {
- if (isCompactedRewindRefusal(error)) {
- return { message: translateNow('promptNotices.compactedTurnUnavailable'), category: 'other' }
+ const staleRewind = staleRewindRefusal(error)
+
+ if (staleRewind) {
+ const key = staleRewind === 'compacted' ? 'compactedTurnUnavailable' : 'staleTurnUnavailable'
+
+ return { message: translateNow(`promptNotices.${key}`), category: 'other' }
}
const raw = error instanceof Error ? error.message : typeof error === 'string' ? error : fallback
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
index 5bf6688e34a..f5b68ce8880 100644
--- a/hermes_state_mutations.py
+++ b/hermes_state_mutations.py
@@ -124,10 +124,13 @@ def _rewind(db, conn, session_id, payload):
require_idle(db, conn, list({session_id, physical}))
# The client names the row: like a branch boundary it must be an active row of the physical
# target. A row compaction archived (still shown, still carrying its id) would deactivate the
- # summary and every later turn, since both have larger ids.
+ # summary and every later turn, since both have larger ids. That refusal says so (``compacted:``
+ # detail); a row a rewind or undo already took back, an assistant row or an unknown id does not.
row = conn.execute('SELECT role FROM messages WHERE id=? AND session_id=? AND active=1',
(payload['target_message_id'], physical)).fetchone()
if row is None or row['role'] != 'user':
+ if _summarized_by_compaction(conn, physical, payload['target_message_id']):
+ raise RuntimeStoreError('invalid_params', field='target_message_id', detail=COMPACTED_TARGET_DETAIL)
raise RuntimeStoreError('invalid_params', field='target_message_id',
detail='target user message is no longer in session history')
# A composite compaction carrier (summary + the next ask in one row) keeps its handoff, as
@@ -145,6 +148,36 @@ def _rewind(db, conn, session_id, payload):
'new_head_id': head, 'replacement_message_id': replacement}
+# The refusal's ``detail`` for a target compaction summarized: ``compacted:`` is the machine-readable
+# prefix clients match (Desktop's restore/edit toast); the rest is the log line.
+COMPACTED_TARGET_DETAIL = 'compacted: target user message was summarized when the session was compressed'
+
+
+def _summarized_by_compaction(conn, physical, message_id):
+ """Whether *message_id* is a user turn compaction took out of *physical*'s live transcript, as
+ opposed to one a rewind/undo deactivated, an assistant row, or no row at all. In-place compaction
+ archives with ``active=0, compacted=1`` (``_ARCHIVE_ACTIVE_SQL``) while rewind, undo and replace
+ mark ``active=0, compacted=0``; a rotating compaction leaves the turn on a compression ancestor of
+ *physical*, still displayed (``active=1 OR compacted=1``)."""
+ row = conn.execute('SELECT session_id, role, active, compacted FROM messages WHERE id=?',
+ (message_id,)).fetchone()
+ if row is None or row['role'] != 'user':
+ return False
+ if row['session_id'] == physical:
+ return row['active'] == 0 and row['compacted'] == 1
+ if not (row['active'] == 1 or row['compacted'] == 1):
+ return False
+ from hermes_state_sessions import _expand_compression_lineage_ids
+ from hermes_state_compression import _CHAIN_CAP
+ lineage, frontier = {physical}, [physical]
+ for _ in range(_CHAIN_CAP):
+ frontier = [sid for sid in _expand_compression_lineage_ids(conn, frontier) if sid not in lineage]
+ if not frontier:
+ break
+ lineage.update(frontier)
+ return row['session_id'] in lineage
+
+
def _carrier_live_view(db, conn, session_id, message_id):
from agent.context_compressor import split_user_originated_turn
row = conn.execute('SELECT * FROM messages WHERE id=? AND session_id=? AND active=1',
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index bd66aa6196a..e89be70c175 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -2454,6 +2454,7 @@
"promptNotices.sessionCommands.undidOther",
"promptNotices.sessionCommands.undoNothing",
"promptNotices.sessionCommands.undoUsage",
+ "promptNotices.staleTurnUnavailable",
"prompts.gatewayDisconnected",
"prompts.reconnect",
"prompts.secretDesc",
diff --git a/tests/hermes_state/test_runtime_rewind_mutations.py b/tests/hermes_state/test_runtime_rewind_mutations.py
index d37646b6e56..6e26686a0cf 100644
--- a/tests/hermes_state/test_runtime_rewind_mutations.py
+++ b/tests/hermes_state/test_runtime_rewind_mutations.py
@@ -91,3 +91,42 @@ def test_rewind_refuses_a_row_a_compression_archived(tmp_path):
rt.mutate_runtime_session(db, epoch=epoch, principal_id='human', session_id='s', request_id='rewind',
expected_revision=0, expected_generation=0, operation='rewind', payload={'target_message_id': archived})
assert [m['content'] for m in db.get_messages('s')] == live
+
+
+def _refusal(db, epoch, target, request_id):
+ with pytest.raises(rt.RuntimeStoreError, match='invalid_params') as refused:
+ _rewind_to(db, epoch, target, request_id=request_id)
+ assert refused.value.field == 'target_message_id'
+ return refused.value.detail
+
+
+def test_only_a_compacted_target_carries_the_compaction_marker(tmp_path):
+ """Desktop says "summarized when the chat was compressed" only for the ``compacted:`` detail: a turn
+ another window already undid, an assistant row and an unknown id are stale for other reasons."""
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ shown, epoch = _compacted_session(db)
+ db.append_messages_batch('s', [{'role': 'user', 'content': 'Q4'}, {'role': 'assistant', 'content': 'A4'}])
+ q4 = db.get_messages('s')[-2]['id']
+ db.rewind_to_message('s', q4) # another client's /undo: no compaction involved
+ compacted = _refusal(db, epoch, shown['Q2'], 'compacted')
+ assert compacted.startswith('compacted:')
+ for name, target in {'assistant': shown['A3'], 'undone': q4, 'archived-assistant': shown['A1'],
+ 'missing': 99999}.items():
+ detail = _refusal(db, epoch, target, name)
+ assert detail != compacted and not detail.startswith('compacted:'), name
+
+
+def test_a_turn_a_rotating_compression_left_on_the_parent_carries_the_marker(tmp_path):
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('p', source='test')
+ db.append_messages_batch('p', [{'role': 'user', 'content': 'old'}, {'role': 'assistant', 'content': 'reply'}])
+ old = db.get_messages('p')[0]['id']
+ db.end_session('p', 'compression')
+ db.create_session('s', source='test', parent_session_id='p')
+ db.append_messages_batch('s', [{'role': 'user', 'content': '[CONTEXT SUMMARY] old'},
+ {'role': 'user', 'content': 'live'}, {'role': 'assistant', 'content': 'ok'}])
+ db.create_session('elsewhere', source='test')
+ foreign = db.append_message('elsewhere', 'user', 'not this chat')
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ assert _refusal(db, epoch, old, 'parent').startswith('compacted:')
+ assert not _refusal(db, epoch, foreign, 'foreign').startswith('compacted:')