Skip to content

The agent that grows with you

fix(tui): map lineage edit ordinals past compression prefix

rainbowgitse14b095f20eb
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 1c14665d444..fb1abcf4df5 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
@@ -1,3 +1,4 @@
+import { JsonRpcGatewayError } from '@hermes/shared'
import { act, cleanup, render, waitFor } from '@testing-library/react'
import type { MutableRefObject } from 'react'
import { useEffect, useRef } from 'react'
@@ -5169,3 +5170,71 @@ describe('usePromptActions stale-closure session routing', () => {
}
})
})
+
+describe('usePromptActions editMessage stale-target recovery (#82462)', () => {
+ afterEach(() => {
+ cleanup()
+ clearNotifications()
+ setMessages([])
+ $busy.set(false)
+ })
+
+ it('surfaces a compressed-away notice instead of plain-resubmitting without an ordinal', async () => {
+ let handle: HarnessHandle | undefined
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'prompt.submit') {
+ throw new JsonRpcGatewayError('target user message is no longer in session history', {
+ code: 4018,
+ data: {
+ user_turn_count: 1,
+ ordinal: 0,
+ segment_ordinal: -1,
+ prefix_user_count: 1
+ }
+ })
+ }
+
+ return {} as never
+ }) as unknown as GatewayMock
+
+ const seed = [
+ { id: 'u1', parts: [textPart('pre-compress')], role: 'user' as const, timestamp: 0 },
+ { id: 'a1', parts: [textPart('reply')], role: 'assistant' as const, timestamp: 1 }
+ ]
+ setMessages(seed)
+
+ await actRender(
+ <Harness
+ onReady={h => {
+ handle = h
+ }}
+ refreshSessions={async () => undefined}
+ requestGateway={requestGateway}
+ seedMessages={seed}
+ storedSessionId="stored-1"
+ />
+ )
+
+ await handle!.editMessage({
+ content: [{ text: 'edited', type: 'text' }],
+ parentId: null,
+ role: 'user',
+ sourceId: 'u1'
+ } as never)
+
+ await waitFor(() => {
+ const titles = $notifications.get().map(n => n.title)
+ expect(titles.some(t => /no longer in server history|compressed/i.test(t || ''))).toBe(true)
+ })
+
+ const submitCalls = (requestGateway as unknown as { mock: { calls: unknown[][] } }).mock.calls.filter(
+ ([method]) => method === 'prompt.submit'
+ )
+ // 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
+ })
+ })
+})
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.ts
index cedcc7a5674..c9695dfa690 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
@@ -1,4 +1,5 @@
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
+import { JsonRpcGatewayError } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
@@ -1003,6 +1004,23 @@ export function usePromptActions({
setAwaitingResponse(true)
updateSessionState(sessionId, state => applyRewindOptimistic(state, plan.sourceIndex, plan.editedMessage))
+ const isStaleTargetError = (err: unknown) =>
+ /no longer in session history|not in session history/i.test(err instanceof Error ? err.message : String(err))
+
+ const isCompressedAwayError = (err: unknown) => {
+ if (!(err instanceof JsonRpcGatewayError) || err.code !== 4018) {
+ return false
+ }
+
+ const data = err.data
+ if (!data || typeof data !== 'object') {
+ return false
+ }
+
+ const segmentOrdinal = (data as { segment_ordinal?: unknown }).segment_ordinal
+ return typeof segmentOrdinal === 'number' && segmentOrdinal < 0
+ }
+
try {
const survivorRowIds = await submitRewindPrompt(
sessionId,
@@ -1016,6 +1034,46 @@ export function usePromptActions({
applySurvivorRowIds(sessionId, survivorRowIds)
} catch (err) {
+ let surfaced: unknown = err
+ let unavailable = isCompressedAwayError(err)
+
+ // Stale target after compression/resume drift (the cached rowId and
+ // ordinal address the pre-compression segment): reload server history,
+ // recompute the full edit plan against the refreshed transcript, and
+ // retry the real edit once. Do NOT plain-resubmit without a truncation
+ // address — that drops rewind semantics and silently appends the edit
+ // as a new turn (#82462).
+ if (!plan.isFailedTurn && !unavailable && isStaleTargetError(err)) {
+ try {
+ const storedId = selectedStoredSessionIdRef.current
+ if (storedId) {
+ await resumeStoredSession(storedId)
+ }
+
+ const refreshed = $messages.get()
+ const retryPlan = planEdit(refreshed, edited)
+ if (retryPlan && !retryPlan.isFailedTurn) {
+ const survivorRowIds = await submitRewindPrompt(
+ sessionId,
+ retryPlan.text,
+ retryPlan.truncateOrdinal,
+ retryPlan.truncateMessageId,
+ false,
+ retryPlan.truncateRowId,
+ retryPlan.sourceText
+ )
+
+ applySurvivorRowIds(sessionId, survivorRowIds)
+ return
+ }
+
+ unavailable = true
+ } catch (retryErr) {
+ surfaced = retryErr
+ unavailable = isCompressedAwayError(retryErr) || isStaleTargetError(retryErr)
+ }
+ }
+
// Roll the optimistic edit/truncation back to the original history so the
// UI stays in sync with what's persisted instead of stranding a partial
// timeline.
@@ -1023,10 +1081,20 @@ export function usePromptActions({
setBusy(false)
setAwaitingResponse(false)
updateSessionState(sessionId, state => ({ ...state, busy: false, awaitingResponse: false, messages }))
- notifyError(err, copy.editFailed)
+ notifyError(surfaced, unavailable ? copy.editTurnUnavailable : copy.editFailed)
}
},
- [activeSessionIdRef, applySurvivorRowIds, busyRef, copy.editFailed, submitRewindPrompt, updateSessionState]
+ [
+ activeSessionIdRef,
+ applySurvivorRowIds,
+ busyRef,
+ copy.editFailed,
+ copy.editTurnUnavailable,
+ resumeStoredSession,
+ selectedStoredSessionIdRef,
+ submitRewindPrompt,
+ updateSessionState
+ ]
)
const handleThreadMessagesChange = useCallback(
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 7b77fa7d88a..32c39263b95 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -2577,6 +2577,7 @@ export const ar = defineLocale({
stopFailed: 'فشل الإيقاف',
regenerateFailed: 'فشلت إعادة التوليد',
editFailed: 'فشل التحرير',
+ editTurnUnavailable: 'هذه الجولة لم تعد في سجل الخادم (ربما أزيلت بالضغط).',
resumeFailed: 'فشل الاستئناف',
resumeStrandedTitle: 'تعذّر تحميل هذه الجلسة',
resumeStrandedBody:
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index f424ad3a518..0931d0c48f9 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -3106,6 +3106,7 @@ export const en: Translations = {
stopFailed: 'Stop failed',
regenerateFailed: 'Regenerate failed',
editFailed: 'Edit failed',
+ editTurnUnavailable: 'This turn is no longer in server history (it may have been compressed away).',
resumeFailed: 'Resume failed',
resumeStrandedTitle: "Couldn't load this session",
resumeStrandedBody:
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 0298cec9c62..e174f64998a 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -2809,6 +2809,7 @@ export const ja = defineLocale({
stopFailed: '停止に失敗しました',
regenerateFailed: '再生成に失敗しました',
editFailed: '編集に失敗しました',
+ editTurnUnavailable: 'このターンはサーバー履歴にありません(圧縮で削除された可能性があります)。',
resumeFailed: '再開に失敗しました',
resumeStrandedTitle: 'このセッションを読み込めませんでした',
resumeStrandedBody:
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index d1fdb50e23c..bd7878af0ac 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -2645,6 +2645,7 @@ export interface Translations {
stopFailed: string
regenerateFailed: string
editFailed: string
+ editTurnUnavailable: string
resumeFailed: string
resumeStrandedTitle: string
resumeStrandedBody: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 2bb8c819eb4..e8f7204433c 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -2695,6 +2695,7 @@ export const zhHant = defineLocale({
stopFailed: '停止失敗',
regenerateFailed: '重新生成失敗',
editFailed: '編輯失敗',
+ editTurnUnavailable: '此回合已不在伺服器歷史中(可能已被壓縮移除)。',
resumeFailed: '繼續失敗',
resumeStrandedTitle: '無法載入此工作階段',
resumeStrandedBody: '與此工作階段的連線失敗,自動重試已停止。請確認閘道正在執行,然後重試。',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index ff0558e5d18..55c35c01d25 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -3259,6 +3259,7 @@ export const zh: Translations = {
stopFailed: '停止失败',
regenerateFailed: '重新生成失败',
editFailed: '编辑失败',
+ editTurnUnavailable: '此回合已不在服务器历史中(可能已被压缩移除)。',
resumeFailed: '恢复失败',
resumeStrandedTitle: '无法加载此会话',
resumeStrandedBody: '与此会话的连接失败,自动重试已停止。请确认网关正在运行,然后重试。',
diff --git a/apps/desktop/src/lib/json-rpc-gateway-url-guard.test.ts b/apps/desktop/src/lib/json-rpc-gateway-url-guard.test.ts
index c3f58159b0e..563a1a148b0 100644
--- a/apps/desktop/src/lib/json-rpc-gateway-url-guard.test.ts
+++ b/apps/desktop/src/lib/json-rpc-gateway-url-guard.test.ts
@@ -1,7 +1,7 @@
// connect() must reject before WebSocket coerces garbage into
// `ws://<origin>/[object%20Object]` (#68250 stale-emit boot loop).
-import { JsonRpcGatewayClient } from '@hermes/shared'
+import { JsonRpcGatewayClient, JsonRpcGatewayError } from '@hermes/shared'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
class FakeSocket {
@@ -63,3 +63,65 @@ describe('JsonRpcGatewayClient connect() URL guard', () => {
}
})
})
+
+describe('JsonRpcGatewayClient structured errors', () => {
+ it('rejects with JsonRpcGatewayError including code and data', async () => {
+ class RespondingSocket {
+ static OPEN = 1
+ readyState = 0
+ private messageHandler: ((event: { data: string }) => void) | null = null
+
+ addEventListener = vi.fn((type: string, handler: (event?: { data: string }) => void) => {
+ if (type === 'open') {
+ setTimeout(() => {
+ this.readyState = RespondingSocket.OPEN
+ handler()
+ }, 0)
+ }
+
+ if (type === 'message') {
+ this.messageHandler = handler as (event: { data: string }) => void
+ }
+ })
+ removeEventListener = vi.fn()
+ close = vi.fn()
+ send = vi.fn((raw: string) => {
+ const req = JSON.parse(raw) as { id: string }
+ queueMicrotask(() => {
+ this.messageHandler?.({
+ data: JSON.stringify({
+ jsonrpc: '2.0',
+ id: req.id,
+ error: {
+ code: 4018,
+ message: 'target user message is no longer in session history',
+ data: { user_turn_count: 2, ordinal: 5, segment_ordinal: 3 }
+ }
+ })
+ })
+ })
+ })
+ }
+
+ vi.stubGlobal('WebSocket', RespondingSocket)
+ try {
+ const client = new JsonRpcGatewayClient({
+ requestTimeoutMs: 5_000,
+ socketFactory: () => new RespondingSocket() as unknown as WebSocket
+ })
+ await client.connect('ws://127.0.0.1:1234/api/ws?token=t')
+
+ await expect(client.request('prompt.submit', { session_id: 's' })).rejects.toEqual(
+ expect.objectContaining({
+ name: 'JsonRpcGatewayError',
+ code: 4018,
+ message: 'target user message is no longer in session history',
+ data: { user_turn_count: 2, ordinal: 5, segment_ordinal: 3 }
+ })
+ )
+ expect(new JsonRpcGatewayError('x')).toBeInstanceOf(Error)
+ } finally {
+ vi.unstubAllGlobals()
+ }
+ })
+})
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index fd40c471744..933120b215a 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -50,8 +50,10 @@ export {
type GatewayEvent,
type GatewayEventName,
type GatewayRequestId,
+ type JsonRpcErrorPayload,
type JsonRpcFrame,
JsonRpcGatewayClient,
+ JsonRpcGatewayError,
type WebSocketLike
} from './json-rpc-gateway'
export { skillInvocationText } from './skill-scaffold'
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index acde83e96cb..6948db62e70 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -34,14 +34,33 @@ export interface GatewayEvent<P = unknown> {
export type ConnectionState = 'idle' | 'connecting' | 'open' | 'closed' | 'error'
export type GatewayRequestId = number | string
+export interface JsonRpcErrorPayload {
+ code?: number
+ data?: unknown
+ message?: string
+}
+
export interface JsonRpcFrame {
- error?: { message?: string }
+ error?: JsonRpcErrorPayload
id?: GatewayRequestId | null
method?: string
params?: GatewayEvent
result?: unknown
}
+/** JSON-RPC error with optional structured `data` from the gateway. */
+export class JsonRpcGatewayError extends Error {
+ readonly code?: number
+ readonly data?: unknown
+
+ constructor(message: string, options?: { code?: number; data?: unknown }) {
+ super(message)
+ this.name = 'JsonRpcGatewayError'
+ this.code = options?.code
+ this.data = options?.data
+ }
+}
+
export type WebSocketLike = WebSocket
type PendingCall = {
@@ -372,7 +391,12 @@ export class JsonRpcGatewayClient {
this.clearPending(frame.id)
if (frame.error) {
- call.reject(new Error(frame.error.message || 'Hermes RPC failed'))
+ call.reject(
+ new JsonRpcGatewayError(frame.error.message || 'Hermes RPC failed', {
+ code: typeof frame.error.code === 'number' ? frame.error.code : undefined,
+ data: frame.error.data
+ })
+ )
} else {
call.resolve(frame.result)
}
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 9c1f33ed6a0..d193f66c47f 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -11233,6 +11233,223 @@ def test_prompt_submit_truncate_ordinal_skips_display_kind_rows(monkeypatch):
server._sessions.pop("sid", None)
+def test_prompt_submit_truncate_translates_display_prefix_ordinal(monkeypatch):
+ """Full-lineage Desktop ordinals must truncate the tip segment (#82462).
+
+ After compression, session["history"] is the tip while display_history_prefix
+ still holds ancestor user turns the UI shows. A client ordinal that includes
+ those ancestors must map into the tip, not 4018.
+ """
+
+ seen = {}
+
+ class _Agent:
+ def run_conversation(self, prompt, conversation_history=None, stream_callback=None, **_kwargs):
+ seen["prompt"] = prompt
+ seen["history"] = conversation_history
+ return {
+ "final_response": "edited reply",
+ "messages": [
+ *(conversation_history or []),
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": "edited reply"},
+ ],
+ }
+
+ class _ImmediateThread:
+ def __init__(self, target=None, daemon=None):
+ self._target = target
+
+ def start(self):
+ self._target()
+
+ tip_history = [
+ {"role": "user", "content": "post-compress A"},
+ {"role": "assistant", "content": "reply A"},
+ {"role": "user", "content": "post-compress B"},
+ {"role": "assistant", "content": "reply B"},
+ ]
+ display_prefix = [
+ {"role": "user", "content": "pre-compress 1"},
+ {"role": "assistant", "content": "pre reply 1"},
+ {"role": "user", "content": "pre-compress 2"},
+ {"role": "assistant", "content": "pre reply 2"},
+ ]
+ # Desktop lineage: pre1=0, pre2=1, postA=2, postB=3
+ desktop_ordinal_for_post_b = 3
+
+ server._sessions["sid"] = _session(
+ agent=_Agent(),
+ history=tip_history,
+ display_history_prefix=display_prefix,
+ )
+
+ class _StubDb:
+ def __init__(self):
+ self.replaced = []
+
+ def get_messages_as_conversation(self, *_args, **_kwargs):
+ # Empty durable transcript: proves this ephemeral-style session
+ # may take the ordinal-only path past the durability gate.
+ return []
+
+ def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
+ self.replaced.append((session_id, list(messages)))
+
+ stub_db = _StubDb()
+
+ try:
+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)
+ monkeypatch.setattr(server, "_get_usage", lambda _a: {})
+ monkeypatch.setattr(server, "render_message", lambda _t, _c: "")
+ monkeypatch.setattr(server, "_emit", lambda *a: None)
+ monkeypatch.setattr(server, "_get_db", lambda: stub_db)
+
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "sid",
+ "text": "edited post B",
+ "truncate_before_user_ordinal": desktop_ordinal_for_post_b,
+ "confirm_truncate": True,
+ },
+ }
+ )
+ assert resp.get("result"), f"got error: {resp.get('error')}"
+ assert seen["prompt"] == "edited post B"
+ assert seen["history"] == tip_history[:2]
+ assert stub_db.replaced == [("session-key", tip_history[:2])]
+ finally:
+ server._sessions.pop("sid", None)
+
+
+def test_prompt_submit_truncate_oor_includes_structured_user_turn_count(monkeypatch):
+ """4018 after compaction must carry recovery fields for Desktop (#82462)."""
+
+ tip_history = [
+ {"role": "user", "content": "post-compress A"},
+ {"role": "assistant", "content": "reply A"},
+ ]
+ display_prefix = [
+ {"role": "user", "content": "pre-compress 1"},
+ {"role": "assistant", "content": "pre reply 1"},
+ ]
+ # Ordinal 0 points at the ancestor prefix — not editable from the tip.
+ server._sessions["sid"] = _session(
+ history=tip_history,
+ display_history_prefix=display_prefix,
+ )
+
+ try:
+ monkeypatch.setattr(
+ server, "_start_inflight_turn", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "sid",
+ "text": "edit ancestor",
+ "truncate_before_user_ordinal": 0,
+ "confirm_truncate": True,
+ },
+ }
+ )
+ err = resp.get("error") or {}
+ assert err.get("code") == 4018
+ assert "no longer in session history" in (err.get("message") or "")
+ data = err.get("data") or {}
+ assert data.get("user_turn_count") == 1
+ assert data.get("ordinal") == 0
+ assert data.get("segment_ordinal") == -1
+ assert data.get("prefix_user_count") == 1
+ finally:
+ server._sessions.pop("sid", None)
+
+
+def test_prompt_submit_row_id_accepts_full_lineage_ordinal(monkeypatch):
+ """Desktop sends rowId + a full-lineage ordinal; both must agree (#82462).
+
+ After compression the client's visible-user ordinal counts the ancestor
+ prefix turns while the gateway resolves the row id tip-relative. The
+ reconcile cross-check must treat `tip_ordinal + prefix_user_count` as
+ agreement, not #82756 drift — and the cut stays aimed by the row id.
+ """
+ tip_history = [
+ {"_row_id": 501, "role": "user", "content": "post-compress A"},
+ {"_row_id": 502, "role": "assistant", "content": "reply A"},
+ {"_row_id": 503, "role": "user", "content": "post-compress B"},
+ {"_row_id": 504, "role": "assistant", "content": "reply B"},
+ ]
+ display_prefix = [
+ {"role": "user", "content": "pre-compress 1"},
+ {"role": "assistant", "content": "pre reply 1"},
+ {"role": "user", "content": "pre-compress 2"},
+ {"role": "assistant", "content": "pre reply 2"},
+ ]
+
+ replaced = []
+
+ class _FakeDB:
+ def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
+ replaced.append((key, list(messages)))
+
+ sess = _session(history=list(tip_history), display_history_prefix=display_prefix)
+ server._sessions["lineage-row-sid"] = sess
+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())
+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)
+
+ try:
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "lineage-row-sid",
+ "text": "edited post B",
+ # Row id resolves to tip ordinal 1; the client counted the
+ # 2 ancestor user turns, so its lineage ordinal is 3.
+ "truncate_before_row_id": 503,
+ "truncate_before_user_ordinal": 3,
+ "confirm_truncate": True,
+ },
+ }
+ )
+ assert resp.get("error") is None, f"got error: {resp.get('error')}"
+ assert sess["history"] == tip_history[:2]
+ finally:
+ server._sessions.pop("lineage-row-sid", None)
+
+ # A genuinely stale ordinal (matches neither the tip space nor the
+ # lineage space) must still refuse with the #82756 mismatch.
+ sess2 = _session(history=list(tip_history), display_history_prefix=display_prefix)
+ server._sessions["lineage-row-sid-2"] = sess2
+ monkeypatch.setattr(
+ server, "_start_agent_build", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+ try:
+ resp = server.handle_request(
+ {
+ "id": "2",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "lineage-row-sid-2",
+ "text": "edited post B",
+ "truncate_before_row_id": 503,
+ "truncate_before_user_ordinal": 2,
+ "confirm_truncate": True,
+ },
+ }
+ )
+ assert resp.get("error") is not None
+ assert resp["error"]["code"] == 4030
+ finally:
+ server._sessions.pop("lineage-row-sid-2", None)
+
+
# ---------------------------------------------------------------------------
# session.interrupt must only cancel pending prompts owned by the calling
# session — it must not blast-resolve clarify/sudo/secret prompts on
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 71fe628a35f..745a855e3d6 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -166,38 +166,53 @@ def _coerce_truncate_int(rid, value, param_name="truncate_before_user_ordinal"):
return None, _err(rid, 4004, f"{param_name} must be an integer")
-def _reconcile_client_ordinal(rid, sid, client_ordinal, msg_ordinal, param_name, target_repr):
+def _reconcile_client_ordinal(
+ rid, sid, client_ordinal, msg_ordinal, param_name, target_repr,
+ prefix_user_count=0,
+):
"""Cross-check a client ordinal against a resolved durable target.
- Returns ``(ordinal, error_response)``: the target's ordinal when the
- client sent none or agreed, else the 4004/4030 refusal. A stale ordinal
- alongside a *resolved* durable id is the #82756 drift class — refuse
- rather than guess which address the user meant.
+ Returns ``(ordinal, error_response)``: the target's tip-relative ordinal
+ when the client sent none or agreed, else the 4004/4030 refusal. A stale
+ ordinal alongside a *resolved* durable id is the #82756 drift class —
+ refuse rather than guess which address the user meant.
+
+ Desktop/TUI ordinals count the full displayed lineage: after context
+ compression the client still renders the ancestor turns from
+ ``display_history_prefix`` while ``msg_ordinal`` is relative to the tip
+ segment only (#82462). A client ordinal that equals
+ ``msg_ordinal + prefix_user_count`` is therefore the SAME turn counted in
+ lineage space, not drift — accept it. The cut itself is always aimed by
+ the resolved durable target, never by the client ordinal, so this wider
+ acceptance can never re-aim a truncation.
"""
if client_ordinal is None:
return msg_ordinal, None
ordinal, err = _coerce_truncate_int(rid, client_ordinal)
if err is not None:
return None, err
- if ordinal != msg_ordinal:
- logger.warning(
- "prompt.submit: REFUSED truncation due to ordinal mismatch for session %s "
- "(ordinal=%d, %s_ordinal=%d, %s=%s). "
- "Stale truncate_before_user_ordinal detected.",
- sid,
- ordinal,
- param_name,
- msg_ordinal,
- param_name,
- target_repr,
- )
- return None, _err(
- rid,
- 4030,
- f"truncate_before_user_ordinal ({ordinal}) does not match "
- f"{param_name} target turn ({msg_ordinal})",
- )
- return ordinal, None
+ if ordinal == msg_ordinal:
+ return msg_ordinal, None
+ if prefix_user_count > 0 and ordinal == msg_ordinal + prefix_user_count:
+ return msg_ordinal, None
+ logger.warning(
+ "prompt.submit: REFUSED truncation due to ordinal mismatch for session %s "
+ "(ordinal=%d, %s_ordinal=%d, %s=%s, prefix_user_count=%d). "
+ "Stale truncate_before_user_ordinal detected.",
+ sid,
+ ordinal,
+ param_name,
+ msg_ordinal,
+ param_name,
+ target_repr,
+ prefix_user_count,
+ )
+ return None, _err(
+ rid,
+ 4030,
+ f"truncate_before_user_ordinal ({ordinal}) does not match "
+ f"{param_name} target turn ({msg_ordinal})",
+ )
def _pending_reaction_notes(session: dict) -> str:
@@ -424,9 +439,41 @@ def _(rid, params: dict) -> dict:
"an ordinary prompt.submit must not drop session history "
"(update your Hermes client if a rewind was intended)",
)
+ # Desktop/TUI ordinals count the full displayed lineage. After
+ # compression, session["history"] holds only the tip segment while
+ # display_history_prefix holds the immutable ancestor display rows
+ # still shown in the transcript (#82462 / #69107). Count the
+ # ancestor user turns once so every comparison between a client
+ # ordinal and a tip-relative ordinal below can translate, instead
+ # of loading ancestors into the tip (which would duplicate
+ # compressed history on later resumes).
+ prefix_user_count = sum(
+ 1
+ for message in session.get("display_history_prefix") or []
+ if isinstance(message, dict)
+ and message.get("role") == "user"
+ and not message.get("display_kind")
+ )
user_indices = _history_user_indices(history)
+ def _stale_target_data(resolved_ordinal=None):
+ # Structured recovery fields for clients (#82462): Desktop
+ # resyncs + retries on a stale target, and shows an explicit
+ # "compressed away" state when segment_ordinal < 0 (the target
+ # only exists in the immutable ancestor prefix).
+ segment = (
+ client_ordinal - prefix_user_count
+ if client_ordinal is not None
+ else resolved_ordinal
+ )
+ return {
+ "user_turn_count": len(user_indices),
+ "ordinal": client_ordinal,
+ "segment_ordinal": segment,
+ "prefix_user_count": prefix_user_count,
+ }
+
ordinal = None
if target_row_id is not None:
@@ -449,12 +496,14 @@ def _(rid, params: dict) -> dict:
rid,
4018,
"target user message is no longer in session history",
+ data=_stale_target_data(),
)
msg_ordinal, _ = found_match
ordinal, err = _reconcile_client_ordinal(
rid, sid, client_ordinal, msg_ordinal,
"truncate_before_row_id", target_row_id,
+ prefix_user_count=prefix_user_count,
)
if err is not None:
return err
@@ -481,19 +530,31 @@ def _(rid, params: dict) -> dict:
rid,
4018,
"target user message is no longer in session history",
+ data=_stale_target_data(),
)
msg_ordinal, _ = found_match
ordinal, err = _reconcile_client_ordinal(
rid, sid, client_ordinal, msg_ordinal,
"truncate_before_message_id", msg_id_str,
+ prefix_user_count=prefix_user_count,
)
if err is not None:
return err
else:
- if client_ordinal < 0 or client_ordinal >= len(user_indices):
+ # Client ordinals count the full displayed lineage; translate
+ # into the tip segment before the bounds check (#82462). An
+ # ancestor-only target (segment_ordinal < 0) is not editable
+ # from this continuation segment — same stale-target refusal,
+ # with the structured fields so the client can tell the
+ # "compressed away" case apart from plain drift.
+ segment_ordinal = client_ordinal - prefix_user_count
+ if segment_ordinal < 0 or segment_ordinal >= len(user_indices):
return _err(
- rid, 4018, "target user message is no longer in session history"
+ rid,
+ 4018,
+ "target user message is no longer in session history",
+ data=_stale_target_data(),
)
# Durability is a state.db property, not an optional annotation
# on the live copy. Resume/reload paths historically omitted
@@ -523,7 +584,7 @@ def _(rid, params: dict) -> dict:
"ordinal-only truncation is unsafe for durable session history; "
"include truncate_before_row_id",
)
- ordinal = client_ordinal
+ ordinal = segment_ordinal
# Reject out-of-range ordinals on BOTH ends. A negative value would
# otherwise sail past the upper-bound check and hit Python's negative
@@ -531,7 +592,12 @@ def _(rid, params: dict) -> dict:
# truncating history to everything before it and persisting that loss
# via replace_messages — an unrecoverable overwrite of the session DB.
if ordinal < 0 or ordinal >= len(user_indices):
- return _err(rid, 4018, "target user message is no longer in session history")
+ return _err(
+ rid,
+ 4018,
+ "target user message is no longer in session history",
+ data=_stale_target_data(resolved_ordinal=ordinal),
+ )
truncated = history[: user_indices[ordinal]]
# Second gate, on top of confirm_truncate: ordinal 0 resolves to
# history[:0] == [] and replace_messages() DELETEs every durable
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index d8dfcaeda3b..3116bd23380 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -2001,8 +2001,11 @@ def _ok(rid, result: dict) -> dict:
return {"jsonrpc": "2.0", "id": rid, "result": result}
-def _err(rid, code: int, msg: str) -> dict:
- return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": msg}}
+def _err(rid, code: int, msg: str, data=None) -> dict:
+ error = {"code": code, "message": msg}
+ if data is not None:
+ error["data"] = data
+ return {"jsonrpc": "2.0", "id": rid, "error": error}
def method(name: str):