Skip to content

The agent that grows with you

fix(desktop): never send ordinal-only truncation — resolve durable row ids by content

Teknium3e8ab0610736
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 1e96c891758..64aa2129666 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -13,7 +13,6 @@ import { useCallback, useMemo, useRef } from 'react'
import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'
import type { ClientSessionState } from '@/app/types'
-import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'
import { useI18n } from '@/i18n'
import { textPart } from '@/lib/chat-messages'
import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
@@ -44,9 +43,7 @@ import {
planRestore,
rebindSurvivorRowIds,
runRewindSubmit,
- survivorRowIdsFrom,
- type SurvivorUserRowIds,
- truncateSubmitParams
+ type SurvivorUserRowIds
} from '../session/hooks/use-prompt-actions/rewind'
import { useSubmitPrompt } from '../session/hooks/use-prompt-actions/submit'
import {
@@ -394,7 +391,8 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
truncateOrdinal: number | undefined,
interruptFirst: boolean,
truncateMessageId?: string,
- truncateRowId?: number
+ truncateRowId?: number,
+ sourceText?: string
) =>
runRewindSubmit(
requestGateway,
@@ -409,7 +407,8 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
runtimeIdRef.current = recoveredId
}
},
- truncateRowId
+ truncateRowId,
+ sourceText
),
[requestGateway]
)
@@ -447,23 +446,15 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
update(current => applyReloadOptimistic(current, plan))
try {
- const result = await requestGateway<{ survivor_user_row_ids?: unknown }>(
- 'prompt.submit',
- {
- session_id: runtimeIdRef.current,
- text: plan.text,
- ...truncateSubmitParams(plan.truncateOrdinal, plan.truncateMessageId, plan.truncateRowId)
- },
- PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
+ applySurvivorRowIds(
+ await submitRewind(plan.text, plan.truncateOrdinal, false, plan.truncateMessageId, plan.truncateRowId, plan.sourceText)
)
-
- applySurvivorRowIds(survivorRowIdsFrom(result))
} catch (err) {
update(current => ({ ...current, busy: false, awaitingResponse: false }))
notifyError(err, copy.regenerateFailed)
}
},
- [applySurvivorRowIds, copy.regenerateFailed, readState, requestGateway, update]
+ [applySurvivorRowIds, copy.regenerateFailed, readState, submitRewind, update]
)
const restoreToMessage = useCallback(
@@ -490,7 +481,8 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
plan.truncateOrdinal,
interruptFirst,
plan.truncateMessageId,
- plan.truncateRowId
+ plan.truncateRowId,
+ plan.sourceText
)
)
} catch (err) {
@@ -530,7 +522,8 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
plan.truncateOrdinal,
interruptFirst,
plan.truncateMessageId,
- plan.truncateRowId
+ plan.truncateRowId,
+ plan.sourceText
)
)
} catch (err) {
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 333bca63e33..85b92b0946b 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
@@ -2,7 +2,7 @@ import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
-import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS, transcribeAudio } from '@/hermes'
+import { transcribeAudio } from '@/hermes'
import { useI18n } from '@/i18n'
import { stripAnsi } from '@/lib/ansi'
import { type ChatMessage, textPart } from '@/lib/chat-messages'
@@ -60,9 +60,7 @@ import {
planRestore,
rebindSurvivorRowIds,
runRewindSubmit,
- survivorRowIdsFrom,
- type SurvivorUserRowIds,
- truncateSubmitParams
+ type SurvivorUserRowIds
} from './rewind'
import { useSlashCommand } from './slash'
import { useSubmitPrompt } from './submit'
@@ -826,6 +824,37 @@ export function usePromptActions({
[updateSessionState]
)
+ const submitRewindPrompt = useCallback(
+ (
+ sessionId: string,
+ text: string,
+ truncateOrdinal: number | undefined,
+ truncateMessageId: string | undefined,
+ interruptFirst: boolean,
+ truncateRowId?: number,
+ sourceText?: string
+ ) =>
+ runRewindSubmit(
+ requestGateway,
+ sessionId,
+ text,
+ truncateOrdinal,
+ truncateMessageId,
+ interruptFirst,
+ {
+ storedSessionId: selectedStoredSessionIdRef.current,
+ onSessionRecovered: recoveredId => {
+ activeSessionIdRef.current = recoveredId
+ setActiveSessionId(recoveredId)
+ }
+ },
+ truncateRowId,
+ sourceText
+ ),
+ [activeSessionIdRef, requestGateway, selectedStoredSessionIdRef]
+ )
+
+
const reloadFromMessage = useCallback(
async (parentId: string | null) => {
// Ref, not the closure-captured prop — a truncating resubmit aimed at a
@@ -846,17 +875,17 @@ export function usePromptActions({
updateSessionState(sessionId, state => applyReloadOptimistic(state, plan))
try {
- const result = await requestGateway<{ survivor_user_row_ids?: unknown }>(
- 'prompt.submit',
- {
- session_id: sessionId,
- text: plan.text,
- ...truncateSubmitParams(plan.truncateOrdinal, plan.truncateMessageId, plan.truncateRowId)
- },
- PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
+ const survivorRowIds = await submitRewindPrompt(
+ sessionId,
+ plan.text,
+ plan.truncateOrdinal,
+ plan.truncateMessageId,
+ false,
+ plan.truncateRowId,
+ plan.sourceText
)
- applySurvivorRowIds(sessionId, survivorRowIdsFrom(result))
+ applySurvivorRowIds(sessionId, survivorRowIds)
} catch (err) {
updateSessionState(sessionId, state => ({
...state,
@@ -866,7 +895,7 @@ export function usePromptActions({
notifyError(err, copy.regenerateFailed)
}
},
- [activeSessionIdRef, applySurvivorRowIds, copy.regenerateFailed, requestGateway, updateSessionState]
+ [activeSessionIdRef, applySurvivorRowIds, copy.regenerateFailed, submitRewindPrompt, updateSessionState]
)
// Cursor-style "restore checkpoint": rewind the conversation to a past user
@@ -878,34 +907,6 @@ export function usePromptActions({
// interrupting an idle agent can leave a stale interrupt flag that cancels the
// fresh turn. Live/stuck turns interrupt first, and a raced "session busy"
// response interrupts + retries through the shared busy gate.
- const submitRewindPrompt = useCallback(
- (
- sessionId: string,
- text: string,
- truncateOrdinal: number | undefined,
- truncateMessageId: string | undefined,
- interruptFirst: boolean,
- truncateRowId?: number
- ) =>
- runRewindSubmit(
- requestGateway,
- sessionId,
- text,
- truncateOrdinal,
- truncateMessageId,
- interruptFirst,
- {
- storedSessionId: selectedStoredSessionIdRef.current,
- onSessionRecovered: recoveredId => {
- activeSessionIdRef.current = recoveredId
- setActiveSessionId(recoveredId)
- }
- },
- truncateRowId
- ),
- [activeSessionIdRef, requestGateway, selectedStoredSessionIdRef]
- )
-
const restoreToMessage = useCallback(
async (messageId: string, target?: RestoreMessageTarget) => {
// Ref, not the closure-captured prop — a rewind is destructive, so a
@@ -946,7 +947,8 @@ export function usePromptActions({
plan.truncateOrdinal,
plan.truncateMessageId,
interruptFirst,
- plan.truncateRowId
+ plan.truncateRowId,
+ plan.sourceText
)
applySurvivorRowIds(sessionId, survivorRowIds)
@@ -1009,7 +1011,8 @@ export function usePromptActions({
plan.truncateOrdinal,
plan.truncateMessageId,
interruptFirst,
- plan.truncateRowId
+ plan.truncateRowId,
+ plan.sourceText
)
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.ts
index de69b180847..d9b1ffbd32a 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
@@ -5,7 +5,12 @@ import { type ChatMessage, textPart } from '@/lib/chat-messages'
import {
appendMidTurnUserMessage,
finalizeInterruptedMessages,
+ planEdit,
+ planReload,
+ planRestore,
rebindSurvivorRowIds,
+ resolveDurableRowId,
+ runRewindSubmit,
survivorRowIdsFrom,
truncateSubmitParams
} from './rewind'
@@ -259,5 +264,205 @@ describe('finalizeInterruptedMessages', () => {
expect(message.parts).toHaveLength(1)
expect(message.parts[0].completedAt).toBe(11.25)
expect(message.completedAt).toBe(11.25)
+
+ })
+})
+
+describe('failed-turn-aware ordinal space', () => {
+ const user = (id: string, rowId?: number): ChatMessage => ({
+ id,
+ role: 'user',
+ parts: [textPart(`text ${id}`)],
+ ...(rowId !== undefined ? { rowId } : {})
+ })
+
+ const assistant = (id: string, rowId?: number): ChatMessage => ({
+ id,
+ role: 'assistant',
+ parts: [textPart(`reply ${id}`)],
+ ...(rowId !== undefined ? { rowId } : {})
+ })
+
+ const failedAssistant = (id: string): ChatMessage => ({
+ id,
+ role: 'assistant',
+ parts: [textPart(`err ${id}`)],
+ error: 'provider down'
+ })
+
+ it('planEdit/planReload skip failed turns when counting ordinals (#41275)', () => {
+ // u0 failed (never persisted), u1/u2 succeeded. Backend counts u1 before
+ // u2, so editing u2 must aim at ordinal 1, not 2.
+ const messages: ChatMessage[] = [
+ user('u0', undefined),
+ failedAssistant('a0'),
+ user('u1', 11),
+ assistant('a1', 12),
+ user('u2', 13),
+ assistant('a2', 14)
+ ]
+
+ const reload = planReload(messages, 'a2')
+
+ expect(reload?.truncateOrdinal).toBe(1)
+ expect(reload?.truncateRowId).toBe(13)
+ })
+
+ it('planEdit still flags failed turns via the shared helper', () => {
+ const messages: ChatMessage[] = [user('u0', 11), assistant('a0', 12), user('u1', undefined), failedAssistant('a1')]
+
+ const plan = planEdit(messages, {
+ role: 'user',
+ sourceId: 'u1',
+ parentId: null,
+ content: [{ type: 'text', text: 'better text' }]
+ } as never)
+
+ expect(plan?.isFailedTurn).toBe(true)
+ expect(plan?.truncateOrdinal).toBeUndefined()
+ expect(plan?.sourceText).toBe('text u1')
+ })
+
+ it('planReload degrades a failed turn to a plain resubmit (#86623)', () => {
+ const messages: ChatMessage[] = [user('u0', 11), assistant('a0', 12), user('u1', undefined), failedAssistant('a1')]
+
+ const reload = planReload(messages, 'a1')
+
+ expect(reload?.text).toBe('text u1')
+ expect(reload?.truncateOrdinal).toBeUndefined()
+ expect(reload?.truncateRowId).toBeUndefined()
+ expect(reload?.truncateMessageId).toBeUndefined()
+ })
+
+ it('planRestore degrades a failed turn to a plain resubmit', () => {
+ const messages: ChatMessage[] = [user('u0', 11), assistant('a0', 12), user('u1', undefined), failedAssistant('a1')]
+
+ const plan = planRestore(messages, 'u1')
+
+ expect(plan.truncateOrdinal).toBeUndefined()
+ expect(plan.truncateRowId).toBeUndefined()
+ expect(plan.truncateMessageId).toBeUndefined()
+ })
+
+ it('rebindSurvivorRowIds skips failed turns — they hold no survivor slot', () => {
+ const messages: ChatMessage[] = [user('u0', 1), failedAssistant('a0'), user('u1', 3), assistant('a1', 4)]
+ const rebound = rebindSurvivorRowIds(messages, [9])
+
+ // u0 failed: untouched. u1 is survivor ordinal 0.
+ expect(rebound[0].rowId).toBe(1)
+ expect(rebound[2].rowId).toBe(9)
+ })
+})
+
+describe('resolveDurableRowId', () => {
+ const gatewayWith = (messages: unknown[]) => {
+ const request = (async (method: string) => {
+ expect(method).toBe('session.history')
+
+ return { messages }
+ }) as <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>
+
+ return request
+ }
+
+ it('resolves a unique content match to its durable row id', async () => {
+ const request = gatewayWith([
+ { role: 'user', text: 'first prompt', row_id: 11 },
+ { role: 'assistant', text: 'reply', row_id: 12 },
+ { role: 'user', text: 'typo prompt', row_id: 13 }
+ ])
+
+ expect(await resolveDurableRowId(request, 'sid', 'typo prompt', 1)).toBe(13)
+ })
+
+ it('ignores synthetic user-role injections (display_kind rows)', async () => {
+ const request = gatewayWith([
+ { role: 'user', text: 'real prompt', row_id: 11 },
+ { role: 'user', text: 'real prompt', row_id: 12, display_kind: 'auto_continue' }
+ ])
+
+ expect(await resolveDurableRowId(request, 'sid', 'real prompt', 0)).toBe(11)
+ })
+
+ it('refuses ambiguous matches unless the target is provably the newest turn', async () => {
+ const request = gatewayWith([
+ { role: 'user', text: 'same text', row_id: 11 },
+ { role: 'user', text: 'same text', row_id: 13 }
+ ])
+
+ // Ambiguous + target not the latest -> undefined (plain resubmit).
+ expect(await resolveDurableRowId(request, 'sid', 'same text', 0)).toBeUndefined()
+ // Ambiguous + target IS the latest persisted turn -> last match wins.
+ expect(await resolveDurableRowId(request, 'sid', 'same text', 1)).toBe(13)
+ })
+
+ it('returns undefined on gateway failure or empty text', async () => {
+ const failing = (async () => {
+ throw new Error('boom')
+ }) as <T>(method: string) => Promise<T>
+
+ expect(await resolveDurableRowId(failing, 'sid', 'text', 0)).toBeUndefined()
+ expect(await resolveDurableRowId(gatewayWith([]), 'sid', ' ', 0)).toBeUndefined()
+ })
+})
+
+describe('runRewindSubmit durable-address discipline (#87059)', () => {
+ interface Call {
+ method: string
+ params?: Record<string, unknown>
+ }
+
+ const historyMessages = [
+ { role: 'user', text: 'first prompt', row_id: 11 },
+ { role: 'assistant', text: 'ok', row_id: 12 },
+ { role: 'user', text: 'typo prompt', row_id: 13 }
+ ]
+
+ const makeGateway = (calls: Call[]) =>
+ (async (method: string, params?: Record<string, unknown>) => {
+ calls.push({ method, params })
+
+ if (method === 'session.history') {
+ return { messages: historyMessages }
+ }
+
+ return { status: 'streaming' }
+ }) as <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>
+
+ it('resolves a missing rowId by content before submitting, and drops the client ordinal', async () => {
+ const calls: Call[] = []
+
+ await runRewindSubmit(makeGateway(calls), 'sid', 'fixed prompt', 5, undefined, false, undefined, undefined, 'typo prompt')
+
+ 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).toBeUndefined()
+ expect(submit?.params?.confirm_truncate).toBe(true)
+ })
+
+ it('degrades to a plain resubmit when the row id cannot be resolved', async () => {
+ const calls: Call[] = []
+
+ await runRewindSubmit(makeGateway(calls), 'sid', 'fixed prompt', 5, undefined, false, undefined, undefined, 'unknown text')
+
+ const submit = calls.find(call => call.method === 'prompt.submit')
+
+ expect(submit?.params?.truncate_before_row_id).toBeUndefined()
+ expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()
+ expect(submit?.params?.confirm_truncate).toBeUndefined()
+ })
+
+ it('leaves a bound durable rowId untouched (no extra history call)', async () => {
+ const calls: Call[] = []
+
+ await runRewindSubmit(makeGateway(calls), 'sid', 'fixed prompt', 1, undefined, false, undefined, 13, 'typo prompt')
+
+ expect(calls.some(call => call.method === 'session.history')).toBe(false)
+
+ 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)
})
})
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 890071624ee..91250fdb659 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
@@ -23,9 +23,10 @@ import {
import {
appendText,
+ isFailedUserTurn,
isSessionBusyError,
- isVisibleUserMessage,
visibleUserIndexAtOrdinal,
+ visibleUserMessageIndices,
visibleUserOrdinal,
withSessionBusyRetry,
withSessionNotFoundResume
@@ -70,10 +71,13 @@ export function survivorRowIdsFrom(result: PromptSubmitResult | undefined): Surv
* stale id now addresses an archived row and would be refused with 4018.
*/
export function rebindSurvivorRowIds(messages: ChatMessage[], survivorRowIds: SurvivorUserRowIds): ChatMessage[] {
+ // Same ordinal space as the truncate math: visible AND persisted (failed
+ // turns never reached the gateway, so they hold no survivor slot).
+ const indices = new Set(visibleUserMessageIndices(messages))
let ordinal = 0
- return messages.map(message => {
- if (!isVisibleUserMessage(message)) {
+ return messages.map((message, index) => {
+ if (!indices.has(index)) {
return message
}
@@ -88,6 +92,21 @@ export function rebindSurvivorRowIds(messages: ChatMessage[], survivorRowIds: Su
})
}
+/**
+ * Renderer-synthetic message ids (`${timestamp}-${index}-${role}` from
+ * chat-messages.ts, plus older `user-…` / `assistant-…` shapes). Gateway
+ * history never carries them — only durable `row_id` / platform message_id.
+ */
+export function isSyntheticRendererId(messageId: string | undefined): boolean {
+ return (
+ typeof messageId === 'string' &&
+ (messageId.startsWith('user-') ||
+ messageId.startsWith('assistant-') ||
+ messageId.includes('-synthetic-') ||
+ /^\d+-\d+-(user|assistant|tools)\b/.test(messageId))
+ )
+}
+
/**
* Build `prompt.submit` truncation params. `confirm_truncate` states that this
* submit really is a rewind/edit/regenerate: the gateway drops history only for
@@ -104,17 +123,8 @@ export function truncateSubmitParams(
const hasOrdinal = typeof truncateOrdinal === 'number' && Number.isInteger(truncateOrdinal) && truncateOrdinal >= 0
const hasRowId = typeof truncateRowId === 'number' && Number.isInteger(truncateRowId)
- // Renderer ids are ephemeral (`${timestamp}-${index}-${role}` from
- // chat-messages.ts, plus older `user-…` / `assistant-…` shapes). Gateway
- // history never carries them — only durable `row_id` / platform message_id.
- const isSyntheticId =
- typeof truncateMessageId === 'string' &&
- (truncateMessageId.startsWith('user-') ||
- truncateMessageId.startsWith('assistant-') ||
- truncateMessageId.includes('-synthetic-') ||
- /^\d+-\d+-(user|assistant|tools)\b/.test(truncateMessageId))
-
- const hasMessageId = typeof truncateMessageId === 'string' && truncateMessageId.length > 0 && !isSyntheticId
+ const hasMessageId =
+ typeof truncateMessageId === 'string' && truncateMessageId.length > 0 && !isSyntheticRendererId(truncateMessageId)
if (!hasOrdinal && !hasMessageId && !hasRowId) {
return {}
@@ -129,6 +139,68 @@ export function truncateSubmitParams(
}
}
+interface DurableHistoryMessage {
+ display_kind?: string
+ role?: string
+ row_id?: unknown
+ text?: string
+}
+
+/**
+ * Resolve the durable row id of a user turn by CONTENT against the gateway's
+ * stamped transcript (`session.history` ships `row_id` per persisted row).
+ *
+ * The edit-after-interrupt bubble has no bound rowId (the durable row exists —
+ * the client just never learned its id), and renderer/gateway ordinal spaces
+ * diverge, so ordinal math cannot substitute (#87059: a 12-turn divergence cut
+ * 78 messages). Content matching is exact-or-nothing: a unique text match wins;
+ * ambiguity prefers the LAST match only when `expectedOrdinal` says the target
+ * is the latest persisted turn (the edit-after-interrupt shape — the just-sent
+ * message is by definition the newest). Anything else returns undefined and the
+ * caller degrades to a plain resubmit, never a guessed cut.
+ */
+export async function resolveDurableRowId(
+ requestGateway: RequestGateway,
+ sessionId: string,
+ sourceText: string,
+ expectedOrdinal: number | undefined
+): Promise<number | undefined> {
+ const wanted = sourceText.trim()
+
+ if (!wanted) {
+ return undefined
+ }
+
+ let messages: DurableHistoryMessage[]
+
+ try {
+ const result = await requestGateway<{ messages?: unknown }>('session.history', { session_id: sessionId })
+
+ messages = Array.isArray(result?.messages) ? (result.messages as DurableHistoryMessage[]) : []
+ } catch {
+ return undefined
+ }
+
+ const durableUsers = messages.filter(
+ message =>
+ message.role === 'user' && !message.display_kind && typeof message.row_id === 'number' && Number.isInteger(message.row_id)
+ )
+
+ const matches = durableUsers.filter(message => (message.text ?? '').trim() === wanted)
+
+ if (matches.length === 1) {
+ return matches[0].row_id as number
+ }
+
+ if (matches.length > 1 && typeof expectedOrdinal === 'number' && expectedOrdinal >= durableUsers.length - 1) {
+ const last = matches[matches.length - 1]
+
+ return durableUsers[durableUsers.length - 1] === last ? (last.row_id as number) : undefined
+ }
+
+ return undefined
+}
+
/**
* Rewind a turn: `prompt.submit` with an optional `truncate_before_user_ordinal`
* / `truncate_before_message_id` / `truncate_before_row_id` (drops that user turn + everything after).
@@ -147,12 +219,46 @@ export async function runRewindSubmit(
truncateMessageId: string | undefined,
interruptFirst: boolean,
recovery?: { storedSessionId?: null | string; onSessionRecovered?: (sessionId: string) => void },
- truncateRowId?: number
+ truncateRowId?: number,
+ sourceText?: string
): Promise<SurvivorUserRowIds | undefined> {
// Recovery may rebind the live id mid-flight; interrupt/submit must both
// follow it rather than pinning the dead one.
let liveSessionId = sessionId
+ // A truncation without a durable address is the #87059 shape: the gateway
+ // fails it closed (4004) for any persisted session, so sending it can only
+ // produce an error. Resolve the row id by content first (the durable row
+ // usually exists — the bubble just never learned its id, e.g. edit after an
+ // interrupted turn). When resolution fails too, degrade to a PLAIN resubmit:
+ // append the corrected text without dropping anything, never guess a cut.
+ let resolvedRowId = truncateRowId
+ let resolvedOrdinal = truncateOrdinal
+ let resolvedMessageId = truncateMessageId
+
+ const wantsTruncation =
+ typeof truncateOrdinal === 'number' ||
+ typeof truncateRowId === 'number' ||
+ (typeof truncateMessageId === 'string' && truncateMessageId.length > 0 && !isSyntheticRendererId(truncateMessageId))
+
+ const hasDurableAddress =
+ typeof truncateRowId === 'number' ||
+ (typeof truncateMessageId === 'string' && truncateMessageId.length > 0 && !isSyntheticRendererId(truncateMessageId))
+
+ if (wantsTruncation && !hasDurableAddress) {
+ resolvedRowId =
+ sourceText === undefined
+ ? undefined
+ : await resolveDurableRowId(requestGateway, liveSessionId, sourceText, truncateOrdinal)
+
+ // Either way the client-side ordinal is untrustworthy here (its space can
+ // diverge from the gateway's — the #87059 root). Resolved: the row id alone
+ // is the address; sending the divergent ordinal too would trip the
+ // gateway's 4030 cross-check. Unresolved: plain resubmit, no truncation.
+ resolvedOrdinal = undefined
+ resolvedMessageId = undefined
+ }
+
const interrupt = async () => {
try {
await requestGateway('session.interrupt', { session_id: liveSessionId })
@@ -167,7 +273,15 @@ export async function runRewindSubmit(
{
session_id: targetId,
text,
- ...truncateSubmitParams(truncateOrdinal, truncateMessageId, truncateRowId)
+ ...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 }
+ : {})
},
PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
)
@@ -274,8 +388,10 @@ export function appendMidTurnUserMessage<
export interface ReloadPlan {
branchGroupId: string
+ /** Original persisted text of the turn — the durable-row-id content key. */
+ sourceText: string
text: string
- truncateOrdinal: number
+ truncateOrdinal: number | undefined
truncateMessageId?: string
truncateRowId?: number
userIndex: number
@@ -305,12 +421,17 @@ export function planReload(messages: ChatMessage[], parentId: null | string): nu
? messages[parentIndex]
: messages.slice(userIndex + 1).find(m => m.role === 'assistant')
+ // Failed turn: the user msg never reached the gateway, so any truncation
+ // address would mis-aim (#86573/#86623) — resubmit plainly instead.
+ const isFailedTurn = isFailedUserTurn(messages, userIndex)
+
return {
branchGroupId: targetAssistant?.branchGroupId ?? branchGroupForUser(userMessage),
+ sourceText: text,
text,
- truncateOrdinal: visibleUserOrdinal(messages, userIndex),
- truncateMessageId: userMessage.id,
- truncateRowId: userMessage.rowId,
+ truncateOrdinal: isFailedTurn ? undefined : visibleUserOrdinal(messages, userIndex),
+ truncateMessageId: isFailedTurn ? undefined : userMessage.id,
+ truncateRowId: isFailedTurn ? undefined : userMessage.rowId,
userIndex
}
}
@@ -347,8 +468,10 @@ export interface RestoreTarget {
export interface RestorePlan {
sourceIndex: number
+ /** Original persisted text of the turn — the durable-row-id content key. */
+ sourceText: string
text: string
- truncateOrdinal: number
+ truncateOrdinal: number | undefined
truncateMessageId?: string
truncateRowId?: number
}
@@ -369,18 +492,30 @@ export function planRestore(messages: ChatMessage[], messageId: string, target?:
throw new Error('Could not find the message to restore.')
}
- const text = (chatMessageText(source).trim() || target?.text?.trim() || '').trim()
+ const sourceText = chatMessageText(source).trim()
+ const text = (sourceText || target?.text?.trim() || '').trim()
if (!text) {
throw new Error('Cannot restore an empty message.')
}
+ // Failed turn: the target user msg never reached the gateway, so any
+ // truncation address would mis-aim (#86573/#86623) — resubmit plainly.
+ const isFailedTurn = isFailedUserTurn(messages, sourceIndex)
+
const truncateOrdinal =
target?.userOrdinal === null || target?.userOrdinal === undefined
? visibleUserOrdinal(messages, sourceIndex)
: target.userOrdinal
- return { sourceIndex, text, truncateOrdinal, truncateMessageId: source.id, truncateRowId: source.rowId }
+ return {
+ sourceIndex,
+ sourceText: sourceText || text,
+ text,
+ truncateOrdinal: isFailedTurn ? undefined : truncateOrdinal,
+ truncateMessageId: isFailedTurn ? undefined : source.id,
+ truncateRowId: isFailedTurn ? undefined : source.rowId
+ }
}
// ---------------------------------------------------------------------------
@@ -391,6 +526,8 @@ export interface EditPlan {
editedMessage: ChatMessage
isFailedTurn: boolean
sourceIndex: number
+ /** Original persisted text of the edited turn — the durable-row-id content key. */
+ sourceText: string
text: string
truncateOrdinal: number | undefined
truncateMessageId?: string
@@ -415,13 +552,13 @@ export function planEdit(messages: ChatMessage[], edited: AppendMessage): EditPl
// Failed turn: the optimistic user msg never reached the gateway, so a
// truncate-by-ordinal would 422 — resubmit plainly instead.
- const nextMessage = messages[sourceIndex + 1]
- const isFailedTurn = nextMessage?.role === 'assistant' && Boolean(nextMessage.error)
+ const isFailedTurn = isFailedUserTurn(messages, sourceIndex)
return {
editedMessage: { ...source, parts: [textPart(text)] },
isFailedTurn,
sourceIndex,
+ sourceText: chatMessageText(source).trim(),
text,
truncateOrdinal: isFailedTurn ? undefined : visibleUserOrdinal(messages, sourceIndex),
truncateMessageId: isFailedTurn ? undefined : source.id,