The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge current main into composite-carrier fix
poisdahlabf87e7248b0
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.tsindex d5f13f7240f,8e2f8b90f2f..3a42802f61b--- 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@@@ -217,6 -229,29 +232,30 @@@ describe('rebindSurvivorRowIds', () =>expect(rebindSurvivorRowIds(messages, [7])[0]).toBe(messages[0])})++ it('rebinds a paged tail by previous row id instead of global position', () => {+ const messages = [+ user('archived-u250', 800),+ user('tail-u298', 901),+ assistant('tail-a298', 902),+ user('edited', 903)+ ]+++ const rebound = rebindSurvivorRowIds(+ messages,+ new Map([+ [901, 1001],+ [902, 1002],+ [903, null]+ ])+ )++ expect(rebound[0]).toBe(messages[0])+ expect(rebound[0].rowId).toBe(800)+ expect(rebound[1].rowId).toBe(1001)+ expect(rebound[2].rowId).toBe(1002)+ expect(rebound[3].rowId).toBeUndefined()+ })})describe('finalizeInterruptedMessages', () => {@@@ -475,10 -510,21 +514,21 @@@ describe('runRewindSubmit durable-addreexpect(submit?.params?.confirm_truncate).toBeUndefined()})- it('uses a bound durable rowId without a tail-local ordinal or 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')+ await runRewindSubmit(+ makeGateway(calls),+ 'sid',+ 'fixed prompt',+ 1,+ undefined,+ false,+ undefined,+ 13,+ 'typo prompt',+ [11, 12, 13]+ )expect(calls.some(call => call.method === 'session.history')).toBe(false)@@@ -486,113 -532,7 +536,115 @@@expect(submit?.params?.truncate_before_row_id).toBe(13)expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()+ expect(submit?.params?.confirm_empty_truncate).toBe(true)+ expect(submit?.params?.rebind_survivor_row_ids).toEqual([11, 12, 13])})++ 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()+ })+})++describe('optimistic rewind/reload turn-clock seeding (#86795)', () => {+ // The no-payload settle gate in gateway-event/session-info.ts holds a running=false+ // heartbeat off while an optimistically armed turn waits for the backend —+ // but only for a bounded grace window measured from turnStartedAt. These+ // transforms are the arm sites for restore/edit/regenerate, so they must+ // seed the clock (and reset turnLive): an armed state without a clock is+ // settled by the first heartbeat, and a STALE clock from a previous turn+ // would let a heartbeat settle the fresh arm immediately.+ const seeded = (extra: Partial<ReturnType<typeof createClientSessionState>>) => ({+ ...createClientSessionState(null, [row('u1', 'user', 'first'), row('a1', 'assistant', 'answer')]),+ ...extra+ })++ it('applyRewindOptimistic arms busy with a fresh turn clock', () => {+ const before = Date.now()+ const next = applyRewindOptimistic(seeded({ turnLive: true, turnStartedAt: before - 60_000 }), 0)++ expect(next.busy).toBe(true)+ expect(next.awaitingResponse).toBe(true)+ expect(next.turnLive).toBe(false)+ expect(next.turnStartedAt).toBeGreaterThanOrEqual(before)+ })++ it('applyReloadOptimistic arms busy with a fresh turn clock', () => {+ const state = seeded({ turnLive: true, turnStartedAt: Date.now() - 60_000 })+ const plan = planReload(state.messages, null)+ const before = Date.now()++ expect(plan).not.toBeNull()++ const next = applyReloadOptimistic(state, plan!)++ expect(next.busy).toBe(true)+ expect(next.turnLive).toBe(false)+ expect(next.turnStartedAt).toBeGreaterThanOrEqual(before)+ })})diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.tsindex 6ca5483cd9c,e964f4d96cd..72b25801d3c--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts@@@ -71,6 -88,27 +88,28 @@@ export function survivorRowIdsFrom(resu* stale id now addresses an archived row and would be refused with 4018.*/export function rebindSurvivorRowIds(messages: ChatMessage[], survivorRowIds: SurvivorUserRowIds): ChatMessage[] {+ if (survivorRowIds instanceof Map) {+ return messages.map(message => {+ if (message.rowId === undefined) {+ return message+ }+++ if (!survivorRowIds.has(message.rowId)) {+ // Requested rows outside the active tip (compacted/ancestor history)+ // were not rewritten and keep their durable identity.+ return message+ }++ const next = survivorRowIds.get(message.rowId)++ return next === null || next === undefined+ ? { ...message, rowId: undefined }+ : message.rowId === next+ ? message+ : { ...message, rowId: next }+ })+ }+// 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))@@@ -92,9 -130,19 +131,19 @@@})}+ export function durableRowIdsForRebind(messages: readonly ChatMessage[]): number[] {+ return [+ ...new Set(+ messages.flatMap(message =>+ typeof message.rowId === 'number' && Number.isInteger(message.rowId) ? [message.rowId] : []+ )+ )+ ]+ }+/*** Renderer-synthetic message ids (`${timestamp}-${index}-${role}` from- * chat-messages.ts, plus older `user-…` / `assistant-…` shapes). Gateway+ * chat-messages/hydration.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 {@@@ -248,6 -297,14 +298,18 @@@ export async function runRewindSubmittypeof truncateRowId === 'number' ||(typeof truncateMessageId === 'string' && truncateMessageId.length > 0 && !isSyntheticRendererId(truncateMessageId))- if (typeof resolvedRowId === 'number' && Number.isInteger(resolvedRowId)) {- // A durable row id is globally stable, while the rendered ordinal can be- // relative to a paged transcript tail. Do not cross-check those different- // spaces; the gateway still validates the row against its full transcript.++ if (wantsTruncation && hasDurableAddress) {++ // A durable row or platform-message id is globally stable, while the++ // rendered ordinal can be relative to a paged transcript tail. Do not++ // cross-check those different spaces; the gateway still validates the++ // durable address against its full transcript.+ resolvedOrdinal = undefined- resolvedMessageId = undefined++++ if (typeof resolvedRowId === 'number' && Number.isInteger(resolvedRowId)) {++ resolvedMessageId = undefined++ }+ }+if (wantsTruncation && !hasDurableAddress) {resolvedRowId =sourceText === undefined@@@ -290,11 -335,15 +340,17 @@@text,...truncateSubmitParams(resolvedOrdinal, resolvedMessageId, resolvedRowId),// A first-turn rewind resolves to an empty transcript, which the- // 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 } : {})+ // gateway additionally gates behind confirm_empty_truncate. In- // In resolved-row-id mode the tail-local ordinal was dropped (see++ // resolved-row-id mode the tail-local ordinal was dropped (see+ // above). The durable target is authoritative, so explicitly allow a+ // first-active-tip cut; the gateway ignores this when the prefix is+ // non-empty.- ...(resolvedRowId !== undefined && resolvedOrdinal === undefined ? { confirm_empty_truncate: true } : {}),++ ...(resolvedOrdinal === undefined && (resolvedRowId !== undefined || truncateOrdinal === 0)++ ? { confirm_empty_truncate: true }++ : {}),+ ...(rebindRowIds?.length+ ? { rebind_survivor_row_ids: [...new Set(rebindRowIds.filter(Number.isInteger))] }+ : {})},PROMPT_SUBMIT_REQUEST_TIMEOUT_MS)diff --cc apps/desktop/src/lib/chat-messages/hydration.tsindex 13fef62d32e,00000000000..69bc09a174cmode 100644,000000..100644--- a/apps/desktop/src/lib/chat-messages/hydration.ts+++ b/apps/desktop/src/lib/chat-messages/hydration.ts@@@ -1,324 -1,0 +1,327 @@@+import { skillInvocationText } from '@hermes/shared'++import { extractImageRefs } from '@/lib/embedded-images'+import { dedupeGeneratedImageEchoesInParts } from '@/lib/generated-images'+import type { MessageReaction, SessionMessage } from '@/types/hermes'++import { assistantTextPart, chatMessageText, dedupeRepeatedTextInParts, reasoningPart, textPart } from './parts'+import {+ applyStoredToolResult,+ applyStoredToolResultToParts,+ storedToolMessagePart,+ textFromUnknown,+ toolPartFromStoredCall,+ withUniqueToolCallIds+} from './tool-parts'+import type { ChatMessage, ChatMessagePart } from './types'++const ATTACHED_CONTEXT_MARKER_RE = /(?:^|\n)--- Attached Context ---\s*\n/+const CONTEXT_WARNINGS_MARKER_RE = /(?:^|\n)--- Context Warnings ---[\s\S]*$/+const CONTEXT_REF_RE = /@(file|folder|url|image|tool|terminal):(?:"[^"\n]+"|'[^'\n]+'|`[^`\n]+`|\S+)/g++function displayContentForMessage(role: SessionMessage['role'], content: unknown): string {+ const textContent = textFromUnknown(content)++ if (role !== 'user') {+ return textContent+ }++ // A `/skill` turn is stored expanded (the whole skill body). Current+ // gateways project it to the invocation before it ever reaches us; this is+ // the fallback for an older backend that still ships the raw payload.+ const invocation = skillInvocationText(textContent)++ if (invocation) {+ return invocation+ }++ const marker = textContent.match(ATTACHED_CONTEXT_MARKER_RE)++ if (!marker || marker.index === undefined) {+ return textContent.replace(CONTEXT_WARNINGS_MARKER_RE, '').trim()+ }++ const visibleText = textContent.slice(0, marker.index).replace(CONTEXT_WARNINGS_MARKER_RE, '').trim()+ const attachedContext = textContent.slice(marker.index + marker[0].length)+ const refs = [...new Set(Array.from(attachedContext.matchAll(CONTEXT_REF_RE)).map(match => match[0]))]++ // The prose keeps the `@file:` token the user typed, so it already chips in+ // place. Only hoist a ref the prose is missing — a turn persisted by an older+ // backend that stripped the tokens. Re-listing an inline ref would chip twice.+ const missing = refs.filter(ref => !visibleText.includes(ref))++ return [missing.join('\n'), visibleText].filter(Boolean).join('\n\n') || visibleText+}++function transcriptContent(displayKind: SessionMessage['display_kind'], content: string): string | null {+ return displayKind === 'hidden' ? null : content+}++// A remote backend older than this app serves display_metadata as raw JSON text,+// and `in` throws on a primitive — which used to fail the whole session resume.+function parseDisplayMetadata(metadata: SessionMessage['display_metadata']): null | Record<string, unknown> {+ let parsed: unknown = metadata++ if (typeof parsed === 'string') {+ try {+ parsed = JSON.parse(parsed)+ } catch {+ return null+ }+ }++ return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null+}++function timelineTaskCount(metadata: SessionMessage['display_metadata']): number | undefined {+ const count = parseDisplayMetadata(metadata)?.task_count++ return typeof count === 'number' ? count : undefined+}++function messageReactions(metadata: SessionMessage['display_metadata']): MessageReaction[] {+ const reactions = parseDisplayMetadata(metadata)?.reactions++ if (!Array.isArray(reactions)) {+ return []+ }++ return reactions.filter(+ (r): r is MessageReaction => Boolean(r) && typeof r === 'object' && typeof (r as MessageReaction).emoji === 'string'+ )+}++function timelineDisplayContent(message: SessionMessage, content: string): string {+ if (message.display_kind === 'model_switch') {+ return 'model changed'+ }++ if (message.display_kind === 'auto_continue') {+ return 'resumed interrupted turn'+ }++ if (message.display_kind === 'personality_switch') {+ return 'personality changed'+ }++ if (message.display_kind === 'async_delegation_complete') {+ const count = timelineTaskCount(message.display_metadata)++ return count === undefined+ ? 'background agent work finished'+ : `${count} background agent${count === 1 ? '' : 's'} finished`+ }++ return content+}++export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {+ const result: ChatMessage[] = []+ let pendingToolParts: ChatMessagePart[] = []+ let pendingToolTimestamp: number | undefined+ let activeAssistantIndex: null | number = null++ const clearPendingTools = () => {+ pendingToolParts = []+ pendingToolTimestamp = undefined+ }++ const earliestTimestamp = (...values: (number | undefined)[]) => {+ const timestamps = values.filter((value): value is number => value !== undefined)++ return timestamps.length ? Math.min(...timestamps) : undefined+ }++ const appendPartsToActiveAssistant = (parts: ChatMessagePart[], timestamp?: number): boolean => {+ if (activeAssistantIndex === null) {+ return false+ }++ const active = result[activeAssistantIndex]++ if (!active || active.role !== 'assistant') {+ activeAssistantIndex = null++ return false+ }++ active.parts = [...active.parts, ...parts]+ active.timestamp = earliestTimestamp(active.timestamp, timestamp, ...parts.map(part => part.timestamp))++ return true+ }++ const flushPendingTools = (index: number) => {+ if (!pendingToolParts.length) {+ return+ }++ if (!appendPartsToActiveAssistant(pendingToolParts, pendingToolTimestamp)) {+ result.push({+ id: `${pendingToolTimestamp || Date.now()}-${index}-tools`,+ role: 'assistant',+ parts: pendingToolParts,+ timestamp: pendingToolTimestamp+ })+ activeAssistantIndex = result.length - 1+ }++ clearPendingTools()+ }++ messages.forEach((message, index) => {+ if (message.role === 'tool') {+ const updatedPendingToolParts = applyStoredToolResultToParts(pendingToolParts, message)++ if (updatedPendingToolParts) {+ pendingToolParts = updatedPendingToolParts++ return+ }++ if (applyStoredToolResult(result, message)) {+ return+ }++ pendingToolParts = [...pendingToolParts, storedToolMessagePart(message, index)]+ pendingToolTimestamp ??= message.timestamp++ return+ }+- const content = message.content || message.text || message.context || message.name++ const content =++ message.display_content !== undefined++ ? message.display_content++ : message.content || message.text || message.context || message.name++ const rawDisplayContent = transcriptContent(+ message.display_kind,+ timelineDisplayContent(message, displayContentForMessage(message.role, content))+ )++ const displayRole =+ message.display_kind === 'model_switch' ||+ message.display_kind === 'async_delegation_complete' ||+ message.display_kind === 'auto_continue' ||+ message.display_kind === 'personality_switch'+ ? 'system'+ : message.role++ // Persisted user turns carry `@image:<path>` directive lines inline in+ // the text (see tui_gateway/server.py's persist-time rewrite). The+ // read-only bubble clamps its body to ~2 lines, and a large inline image+ // thumbnail pushes any caption text below the clamp's visible area — so+ // pull image refs out into `attachmentRefs` (same shape the local+ // optimistic composer already uses) and render them via the dedicated+ // attachments row below the bubble instead.+ const imageRefExtraction = displayRole === 'user' && rawDisplayContent ? extractImageRefs(rawDisplayContent) : null+ const displayContent = imageRefExtraction ? imageRefExtraction.cleanedText : rawDisplayContent+ const extractedAttachmentRefs = imageRefExtraction?.refs.length ? imageRefExtraction.refs : undefined++ const parts: ChatMessagePart[] = []++ const reasoning =+ message.reasoning ||+ message.reasoning_content ||+ (typeof message.reasoning_details === 'string' ? message.reasoning_details : '')++ if (reasoning && message.role === 'assistant') {+ parts.push(reasoningPart(reasoning, message.timestamp))+ }++ if (displayContent) {+ parts.push(+ displayRole === 'assistant'+ ? assistantTextPart(displayContent, message.timestamp)+ : textPart(displayContent, message.timestamp)+ )+ }++ if (message.role === 'assistant' && Array.isArray(message.tool_calls)) {+ parts.push(+ ...message.tool_calls.map((call, callIndex) => toolPartFromStoredCall(call, callIndex, message.timestamp))+ )+ }++ if (!parts.length && !extractedAttachmentRefs?.length) {+ if (message.role !== 'assistant') {+ flushPendingTools(index)+ activeAssistantIndex = null+ }++ return+ }++ const isToolOnlyAssistant =+ message.role === 'assistant' && parts.length > 0 && parts.every(part => part.type === 'tool-call')++ if (isToolOnlyAssistant) {+ pendingToolParts = [...pendingToolParts, ...parts]+ pendingToolTimestamp ??= message.timestamp++ return+ }++ if (message.role === 'assistant') {+ if (pendingToolParts.length) {+ if (!appendPartsToActiveAssistant(pendingToolParts, message.timestamp ?? pendingToolTimestamp)) {+ parts.unshift(...pendingToolParts)+ }++ clearPendingTools()+ }++ const activeAssistant =+ activeAssistantIndex !== null && result[activeAssistantIndex]?.role === 'assistant'+ ? result[activeAssistantIndex]+ : null++ const currentHasToolCall = parts.some(part => part.type === 'tool-call')+ const activeHasToolCall = Boolean(activeAssistant?.parts.some(part => part.type === 'tool-call'))++ if (activeAssistant && (currentHasToolCall || activeHasToolCall)) {+ activeAssistant.parts = [...activeAssistant.parts, ...parts]+ activeAssistant.timestamp = earliestTimestamp(+ activeAssistant.timestamp,+ message.timestamp,+ ...parts.map(part => part.timestamp)+ )++ return+ }+ } else {+ flushPendingTools(index)+ }++ const reactions = messageReactions(message.display_metadata)+ // Gateway resume names the durable row id `row_id`; the REST transcript+ // prefetch ships the same messages.id as a numeric `id`. Either one lets+ // reactions address this exact row later.+ const rowId = message.row_id ?? (typeof message.id === 'number' ? message.id : undefined)++ result.push({+ id: `${message.timestamp || Date.now()}-${index}-${displayRole}`,+ role: displayRole,+ parts,+ timestamp: earliestTimestamp(message.timestamp, ...parts.map(part => part.timestamp)),+ ...(rowId !== undefined ? { rowId } : {}),+ ...(reactions.length ? { reactions } : {}),+ ...(extractedAttachmentRefs ? { attachmentRefs: extractedAttachmentRefs } : {})+ })++ activeAssistantIndex = message.role === 'assistant' ? result.length - 1 : null+ })+ flushPendingTools(messages.length)++ const withoutGeneratedImageEchoes = result.map(message =>+ message.role === 'assistant'+ ? { ...message, parts: dedupeRepeatedTextInParts(dedupeGeneratedImageEchoesInParts(message.parts)) }+ : message+ )++ return withUniqueToolCallIds(+ withoutGeneratedImageEchoes.filter(+ m => chatMessageText(m).trim() || m.parts.some(part => part.type !== 'text') || m.attachmentRefs?.length+ )+ )+}diff --cc tui_gateway/methods_prompt.pyindex fa0dcd949f3,8eb898ff712..1adc70b556b--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@@ -645,90 -675,112 +679,147 @@@ 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- old_active_row_ids = {- row_id- for message in history- if isinstance((row_id := _message_row_id(message)), int)- }- if requested_rebind_ids is not None:- # Row-id fallback can resolve a durable target even- # when the live list is too misaligned to stamp safely,- # and alternation repair can merge a physical user;user- # pair while preserving only the first row id. Read the- # authoritative un-repaired pre-write active-id set so- # a rewritten row is never mistaken for an untouched- # archived/ancestor row by the bounded client map.- durable_rebind_history = _load_durable_truncation_history(- session,- truncation_key,- repair_alternation=False,- )- if durable_rebind_history is None:- raise RuntimeError(- "could not load durable row identities for truncation"- )- old_active_row_ids.update(+ #+ # _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++ old_active_row_ids = {+ row_id- for message in durable_rebind_history++ for message in history+ if isinstance(+ (row_id := _message_row_id(message)), int+ )++ }++ if requested_rebind_ids is not None:++ # Row-id fallback can resolve a durable target even++ # when the live list is too misaligned to stamp safely,++ # and alternation repair can merge a physical user;user++ # pair while preserving only the first row id. Read the++ # authoritative un-repaired pre-write active-id set so++ # a rewritten row is never mistaken for an untouched++ # archived/ancestor row by the bounded client map.++ durable_rebind_history = (++ _load_durable_truncation_history(++ session,++ truncation_key,++ repair_alternation=False,++ )++ )++ if durable_rebind_history is None:++ raise RuntimeError(++ "could not load durable row identities for truncation"++ )++ old_active_row_ids.update(++ row_id++ for message in durable_rebind_history++ if isinstance(++ (row_id := _message_row_id(message)), int++ )++ )++ old_survivor_row_ids = [++ _message_row_id(message) for message in truncated++ ]+ db.replace_messages(+ truncation_key,+ truncated,+ active_only=True,+ archive_dropped=True,++ reject_active_turn_lease=True,)- old_survivor_row_ids = [- _message_row_id(message) for message in truncated+ 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)]- db.replace_messages(- truncation_key,- truncated,- active_only=True,- archive_dropped=True,- reject_active_turn_lease=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}",- )++ if requested_rebind_ids is not None:++ survivor_row_id_map = {++ str(old_row_id): new_row_id++ for old_row_id, new_row_id in zip(++ old_survivor_row_ids,++ (++ _message_row_id(message)++ for message in truncated++ ),++ )++ if isinstance(old_row_id, int)++ and isinstance(new_row_id, int)++ and old_row_id in requested_rebind_ids++ }++ for dropped_row_id in requested_rebind_ids.intersection(++ old_active_row_ids++ ):++ survivor_row_id_map.setdefault(++ str(dropped_row_id), None++ )session["history"] = truncatedsession["history_version"] = int(session.get("history_version", 0)) + 1- if db is not None:- survivor_user_row_ids = [- _message_row_id(truncated[i])- for i in _history_user_indices(truncated)- ]- if requested_rebind_ids is not None:- survivor_row_id_map = {- str(old_row_id): new_row_id- for old_row_id, new_row_id in zip(- old_survivor_row_ids,- (_message_row_id(message) for message in truncated),- )- if isinstance(old_row_id, int)- and isinstance(new_row_id, int)- and old_row_id in requested_rebind_ids- }- for dropped_row_id in requested_rebind_ids.intersection(- old_active_row_ids- ):- survivor_row_id_map.setdefault(str(dropped_row_id), None)session["running"] = Truesession["_turn_cancel_requested"] = Falsesession["last_active"] = time.time()_start_inflight_turn(session, text)if turn_isolation:- isolated_response = _submit_prompt_to_compute_host(rid, sid, session, text)+ isolated_response = _submit_prompt_to_compute_host(+ rid, sid, session, text, display_kind=display_kind+ )if not isolated_response.get("error"):- if survivor_user_row_ids is not None:+ if survivor_user_row_ids is not None and requested_rebind_ids is None:# The truncation already happened inline above (memory + DB),# before compute-host dispatch — the rebind payload applies to# this path exactly as it does to the inline one.