The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): order mid-turn user messages after the assistant output that predates them
Teknium5a3b59323056
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.tsindex 112a805f950..b991bf596f4 100644--- a/apps/desktop/src/app/chat/session-tile-actions.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.ts@@ -34,6 +34,7 @@ import type { SessionInfo } from '@/types/hermes'import { uploadComposerAttachment } from '../session/hooks/use-prompt-actions'import {+ appendMidTurnUserMessage,applyBranchVisibility,applyReloadOptimistic,applyRewindOptimistic,@@ -310,27 +311,20 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Sesconst mutate = (updater: (state: ClientSessionState) => ClientSessionState) =>sessionTileDelegate()?.updateSession(sessionId, updater)- // Match the primary composer: insert the correction before the active- // reply before awaiting the redirect RPC, whose completion can race us.- mutate(state => {- const message = {+ // Match the primary composer: record the correction in arrival order —+ // sealed already-streamed output above, correction below, post-redirect+ // deltas below that — before awaiting the redirect RPC, whose completion+ // can race us. The old insert-before-the-active-reply splice put the+ // bubble above output the user had already read (#73793), and its+ // last-assistant fallback could land it mid-thread when the stream id+ // was missing or stale (#83151).+ mutate(state =>+ appendMidTurnUserMessage(state, {id: messageId,role: 'user' as const,parts: [textPart(text)]- }-- const streamIndex = state.streamId ? state.messages.findIndex(candidate => candidate.id === state.streamId) : -1-- const lastAssistantIndex = state.messages.map(candidate => candidate.role).lastIndexOf('assistant')- const insertionIndex = streamIndex >= 0 ? streamIndex : lastAssistantIndex-- const messages =- insertionIndex >= 0- ? [...state.messages.slice(0, insertionIndex), message, ...state.messages.slice(insertionIndex)]- : [...state.messages, message]-- return { ...state, messages }- })+ })+ )const discardOptimisticMessage = () =>mutate(state => ({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.tsxindex f8c41b76253..baaffd47875 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@@ -105,6 +105,7 @@ function Harness({resumeStoredSession,runtimeIdByStoredSessionIdRef: runtimeIdByStoredSessionIdRefProp,seedMessages,+ seedStreamId,selectedStoredSessionIdRef: selectedStoredSessionIdRefProp,storedSessionId,activeSessionId,@@ -128,6 +129,7 @@ function Harness({resumeStoredSession?: (storedSessionId: string) => Promise<void> | voidruntimeIdByStoredSessionIdRef?: MutableRefObject<Map<string, string>>seedMessages?: unknown[]+ seedStreamId?: null | stringselectedStoredSessionIdRef?: MutableRefObject<string | null>storedSessionId?: null | stringactiveSessionId?: null | string@@ -159,7 +161,9 @@ function Harness({messages: seedMessages ?? [],busy: false,awaitingResponse: false,- interrupted: true+ interrupted: true,+ streamId: seedStreamId ?? null,+ interimBoundaryPending: false} as never)const actions = usePromptActions({@@ -2189,6 +2193,82 @@ describe('usePromptActions redirectPrompt', () => {expect(requestGateway).not.toHaveBeenCalled()})+ it('records the correction AFTER the assistant output that predates it (#73793, #83151)', async () => {+ const requestGateway = vi.fn(async () => ({ status: 'redirected' }) as never)++ let handle: HarnessHandle | null = null+ const capturedStates: Record<string, unknown>[] = []+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={state => capturedStates.push(state)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[+ { id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'long task' }] },+ {+ id: 'assistant-stream-1',+ role: 'assistant',+ parts: [{ type: 'text', text: 'two screens of already-read output' }],+ pending: true+ }+ ]}+ seedStreamId="assistant-stream-1"+ />+ )++ expect(await handle!.redirectPrompt('urgently')).toBe(true)++ const messages = capturedStates.at(-1)?.messages as { id: string; interim?: boolean; pending?: boolean }[]++ // Arrival order: the correction lands BELOW the streamed output the user+ // had already read, never spliced above it.+ expect(messages.map(message => message.id)).toEqual([+ 'user-1',+ 'assistant-stream-1',+ expect.stringMatching(/^user-/)+ ])+ expect(messages[1]).toMatchObject({ pending: false, interim: true })+ // streamId cleared: the post-redirect deltas seed a fresh bubble below.+ expect(capturedStates.at(-1)?.streamId).toBeNull()+ })++ it('appends at the tail — never mid-thread — when the stream id is stale (#83151)', async () => {+ const requestGateway = vi.fn(async () => ({ status: 'redirected' }) as never)++ let handle: HarnessHandle | null = null+ const capturedStates: Record<string, unknown>[] = []+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={state => capturedStates.push(state)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[+ { id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'old prompt' }] },+ { id: 'assistant-1', role: 'assistant', parts: [{ type: 'text', text: 'old committed reply' }] },+ { id: 'user-2', role: 'user', parts: [{ type: 'text', text: 'newer prompt' }] },+ { id: 'assistant-2', role: 'assistant', parts: [{ type: 'text', text: 'newer committed reply' }] }+ ]}+ seedStreamId="assistant-stream-gone"+ />+ )++ expect(await handle!.redirectPrompt('mid-turn note')).toBe(true)++ const messages = capturedStates.at(-1)?.messages as { id: string }[]++ // The retired fallback spliced this before 'assistant-2' — halfway up the+ // chat. It must be the last row.+ expect(messages.map(message => message.id)).toEqual([+ 'user-1',+ 'assistant-1',+ 'user-2',+ 'assistant-2',+ expect.stringMatching(/^user-/)+ ])+ })+it('accepts a queued redirect during the agent-build window and records the correction', async () => {// running=True but the agent is still building: the gateway queues the// correction instead of rejecting, so the composer must NOT re-queue it.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.tsindex 3fabb514c7b..20ebc58ccf0 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@@ -49,6 +49,7 @@ import type {} from '../../../types'import {+ appendMidTurnUserMessage,applyBranchVisibility,applyReloadOptimistic,applyRewindOptimistic,@@ -282,7 +283,7 @@ export function usePromptActions({role: ChatMessage['role'],text: string,storedSessionId?: string | null,- options: { insertBeforeActiveReply?: boolean } = {}+ options: { appendAfterActiveReply?: boolean } = {}) => {// Strip ANSI: slash-command output from the backend worker carries SGR// color codes (e.g. "Unknown command" in red). The ESC byte is invisible@@ -305,23 +306,16 @@ export function usePromptActions({parts: [textPart(body)]}- const streamIndex =- options.insertBeforeActiveReply && state.streamId- ? state.messages.findIndex(candidate => candidate.id === state.streamId)- : -1-- const lastAssistantIndex = options.insertBeforeActiveReply- ? state.messages.map(candidate => candidate.role).lastIndexOf('assistant')- : -1-- const insertionIndex = streamIndex >= 0 ? streamIndex : lastAssistantIndex-- const messages =- insertionIndex >= 0- ? [...state.messages.slice(0, insertionIndex), message, ...state.messages.slice(insertionIndex)]- : [...state.messages, message]+ // Mid-turn correction: arrival order. The bubble lands after the+ // assistant output the user had already seen (sealing the live+ // stream so post-redirect deltas continue BELOW the correction),+ // never spliced above it (#73793) or mid-thread via the old+ // last-assistant fallback (#83151).+ if (options.appendAfterActiveReply) {+ return appendMidTurnUserMessage(state, message)+ }- return { ...state, messages }+ return { ...state, messages: [...state.messages, message] }},storedSessionId ?? selectedStoredSessionIdRef.current)@@ -729,10 +723,11 @@ export function usePromptActions({// transcript rather than a system note that changes role after reload.const send = async (id: string): Promise<boolean> => {// Redirect aborts the model request, so the completion event can race- // its RPC response. Insert before the live reply *before* awaiting the- // gateway; appending after the response leaves the correction below a- // reply that the redirect has already replaced.- const messageId = appendSessionTextMessage(id, 'user', text, undefined, { insertBeforeActiveReply: true })+ // its RPC response. Record the correction *before* awaiting the+ // gateway, in arrival order: sealed already-streamed output above,+ // correction bubble below it, post-redirect deltas below that+ // (#73793, #83151).+ const messageId = appendSessionTextMessage(id, 'user', text, undefined, { appendAfterActiveReply: true })const discardOptimisticMessage = () =>updateSessionState(id, state => ({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.tsindex 3cbabbf9b61..ebe6ca7528e 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@@ -2,7 +2,79 @@ import { describe, expect, it } from 'vitest'import { type ChatMessage, textPart } from '@/lib/chat-messages'-import { rebindSurvivorRowIds, survivorRowIdsFrom, truncateSubmitParams } from './rewind'+import { appendMidTurnUserMessage, rebindSurvivorRowIds, survivorRowIdsFrom, truncateSubmitParams } from './rewind'++const row = (id: string, role: ChatMessage['role'], text: string, extra: Partial<ChatMessage> = {}): ChatMessage => ({+ id,+ role,+ parts: [textPart(text)],+ ...extra+})++type MidTurnState = { interimBoundaryPending: boolean; messages: ChatMessage[]; streamId: null | string }++describe('appendMidTurnUserMessage', () => {+ // #73793: a message typed while a turn streams must land AFTER the assistant+ // output the user had already watched arrive — never spliced above it.+ it('appends the mid-turn message after the live assistant output, sealed in place', () => {+ const state: MidTurnState = {+ interimBoundaryPending: false,+ streamId: 'assistant-stream-1',+ messages: [+ row('user-1', 'user', 'long task'),+ row('assistant-stream-1', 'assistant', 'two screens of output', { pending: true })+ ]+ }++ const next = appendMidTurnUserMessage(state, row('user-2', 'user', 'urgently'))++ expect(next.messages.map(message => message.id)).toEqual(['user-1', 'assistant-stream-1', 'user-2'])+ // The sealed bubble stops streaming; the turn's next delta seeds a fresh+ // bubble BELOW the correction instead of mutating the one above it.+ expect(next.messages[1]).toMatchObject({ pending: false, interim: true })+ expect(next.streamId).toBeNull()+ expect(next.interimBoundaryPending).toBe(true)+ })++ // #83151: the retired insert-before splice fell back to the LAST assistant+ // row anywhere in the transcript when the stream id was stale, landing the+ // new prompt mid-thread. A stale/missing stream id must append at the tail.+ it('appends at the live tail when the stream id is stale or missing', () => {+ const state: MidTurnState = {+ interimBoundaryPending: false,+ streamId: 'assistant-stream-stale',+ messages: [+ row('user-1', 'user', 'old prompt'),+ row('assistant-1', 'assistant', 'old committed reply'),+ row('user-2', 'user', 'newer prompt'),+ row('assistant-2', 'assistant', 'newer committed reply')+ ]+ }++ const next = appendMidTurnUserMessage(state, row('user-3', 'user', 'mid-turn note'))++ expect(next.messages.map(message => message.id)).toEqual(['user-1', 'assistant-1', 'user-2', 'assistant-2', 'user-3'])+ expect(next.messages.at(-1)?.id).toBe('user-3')+ expect(next.interimBoundaryPending).toBe(false)+ })++ it('drops an empty pending stream placeholder instead of sealing it', () => {+ const state: MidTurnState = {+ interimBoundaryPending: false,+ streamId: 'assistant-stream-1',+ messages: [+ row('user-1', 'user', 'task'),+ { id: 'assistant-stream-1', role: 'assistant', parts: [], pending: true }+ ]+ }++ const next = appendMidTurnUserMessage(state, row('user-2', 'user', 'correction'))++ expect(next.messages.map(message => message.id)).toEqual(['user-1', 'user-2'])+ expect(next.streamId).toBeNull()+ expect(next.interimBoundaryPending).toBe(false)+ })+})describe('truncateSubmitParams', () => {it('omits truncation fields when no ordinal is set', () => {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.tsindex 5726a98aa3c..fcf83c4ba71 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@@ -209,6 +209,39 @@ export function finalizeInterruptedMessages(messages: ChatMessage[], streamId?:.map(message => (message.pending || message.id === streamId ? { ...message, pending: false } : message))}+/**+ * Arrival-ordered mid-turn user insert (#73793, #83151).+ *+ * A message typed while a turn streams must land AFTER every assistant row the+ * user had already watched arrive — never spliced above it. Seal the live+ * stream bubble in place (marked interim so the terminal completion settles+ * onto it or follows it instead of duplicating), append the new user bubble at+ * the live tail, and clear `streamId` so the turn's next delta seeds a fresh+ * assistant bubble BELOW the correction rather than mutating the sealed one+ * above it. Also retires the old insert-before-the-active-reply contract whose+ * `lastAssistantIndex` fallback could splice the bubble mid-thread when the+ * stream id was missing or stale (#83151).+ */+export function appendMidTurnUserMessage<+ State extends { interimBoundaryPending: boolean; messages: ChatMessage[]; streamId: null | string }+>(state: State, message: ChatMessage): State {+ const liveId = state.streamId+ const sealed = finalizeInterruptedMessages(state.messages, liveId)+ const sealedLiveKept = liveId !== null && sealed.some(row => row.id === liveId)++ const messages = [+ ...(sealedLiveKept ? sealed.map(row => (row.id === liveId ? { ...row, interim: true } : row)) : sealed),+ message+ ]++ return {+ ...state,+ messages,+ streamId: null,+ interimBoundaryPending: state.interimBoundaryPending || sealedLiveKept+ }+}+// ---------------------------------------------------------------------------// Reload (regenerate)// ---------------------------------------------------------------------------diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.tsindex 4a18397200e..27bff4795e0 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts@@ -714,6 +714,25 @@ describe('preserveLocalPendingTurnMessages', () => {])})+ // Arrival-ordered mid-turn corrections (#73793) seal the live output BETWEEN+ // the prompt and the correction. The sealed live-tail row must not end the+ // optimistic run, or a refresh drops the prompt that started the turn.+ it('keeps the whole live run when sealed live output sits between prompt and correction', () => {+ const previous = [+ msg('user-1000', 'user', 'remove the session counts'),+ msg('assistant-stream-1', 'assistant', 'two screens of output', { interim: true }),+ msg('user-2000', 'user', 'hurry up'),+ msg('assistant-stream-2', 'assistant', 'post-redirect output', { pending: true })+ ]++ expect(preserveLocalPendingTurnMessages([], previous).map(message => message.id)).toEqual([+ 'user-1000',+ 'assistant-stream-1',+ 'user-2000',+ 'assistant-stream-2'+ ])+ })+it('still drops optimistic rows separated from the live run by an assistant reply', () => {const previous = [msg('user-stale', 'user', 'compressed-away prompt'),@@ -1148,8 +1167,10 @@ describe('preserveLocalPendingTurnMessages', () => {describe('appendLiveSessionProjection', () => {// Corrections typed while a turn ran are their own user bubbles on the same- // turn. Resume must rebuild the prompt AND every correction, in order.- it('projects mid-turn redirect corrections after the prompt that started the turn', () => {+ // turn, ordered by ARRIVAL. Without boundary offsets (older gateway) the+ // whole dump precedes them — never the old prompt → corrections → reply+ // order that spliced them above output the user had already read (#73793).+ it('projects mid-turn redirect corrections after the assistant output that predates them', () => {const restored = appendLiveSessionProjection([], {session_id: 'runtime-1',inflight: {@@ -1162,10 +1183,72 @@ describe('appendLiveSessionProjection', () => {expect(restored.map(message => message.parts.map(part => ('text' in part ? part.text : '')).join(''))).toEqual(['remove the session counts',+ 'Moving.',+ 'hurry up',+ 'and the worktree ones'+ ])+ })++ // With correction_offsets the flat dump is split at each accepted-correction+ // boundary, so every correction lands after exactly the output it followed+ // and before the output it redirected — arrival order end to end (#73793).+ it('interleaves corrections into the assistant dump at their arrival offsets', () => {+ const restored = appendLiveSessionProjection([], {+ session_id: 'runtime-1',+ inflight: {+ user: 'remove the session counts',+ corrections: ['hurry up', 'and the worktree ones'],+ correction_offsets: [7, 13],+ assistant: 'Moving.Still.Done soon.',+ streaming: true+ }+ })++ expect(restored.map(message => message.parts.map(part => ('text' in part ? part.text : '')).join(''))).toEqual([+ 'remove the session counts',+ 'Moving.','hurry up',+ 'Still.','and the worktree ones',- 'Moving.'+ 'Done soon.'+ ])+ expect(restored.map(message => message.role)).toEqual([+ 'user',+ 'assistant',+ 'user',+ 'assistant',+ 'user',+ 'assistant'+ ])+ // Only the live tail streams; sealed pre-correction segments are settled.+ expect(restored.at(-1)).toMatchObject({ id: 'assistant-stream-runtime-1', pending: true })+ expect(restored[1]).toMatchObject({ pending: false, interim: true })+ expect(restored[3]).toMatchObject({ pending: false, interim: true })+ })++ it('keeps the live stream row even when every offset points at the dump tail', () => {+ const restored = appendLiveSessionProjection([], {+ session_id: 'runtime-1',+ inflight: {+ user: 'prompt',+ corrections: ['nudge'],+ correction_offsets: [4],+ assistant: 'text',+ streaming: true+ }+ })++ // The whole dump precedes the correction, and the still-streaming turn+ // keeps its (empty for now) live row at the tail so future deltas land+ // BELOW the correction, not above it.+ expect(restored.map(message => message.parts.map(part => ('text' in part ? part.text : '')).join(''))).toEqual([+ 'prompt',+ 'text',+ 'nudge',+ ''])+ expect(restored.at(-1)).toMatchObject({ id: 'assistant-stream-runtime-1', pending: true })+ expect(restored.at(-1)?.role).toBe('assistant')})it('does not re-project a correction the transcript already persisted', () => {diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex 6c031768acc..1a510c778cd 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -503,11 +503,21 @@ export function preserveLocalPendingTurnMessages(for (let index = previousMessages.indexOf(newestOptimisticUser); index >= 0; index -= 1) {const candidate = previousMessages[index]- if (candidate.role !== 'user' || !candidate.id.startsWith('user-')) {- break+ if (candidate.role === 'user' && candidate.id.startsWith('user-')) {+ liveOptimisticUsers.add(candidate)++ continue}- liveOptimisticUsers.add(candidate)+ // Arrival-ordered mid-turn corrections sit BELOW the sealed live output+ // (#73793): a live-tail assistant row between the prompt and its+ // correction is still the same turn's run. Only a committed reply ends+ // it — that is the post-compression staleness the rule exists to catch.+ if (candidate.role === 'assistant' && isLiveTailRow(candidate)) {+ continue+ }++ break}}@@ -688,10 +698,22 @@ export function appendLiveSessionProjection(const inflightStreaming = Boolean(projection.inflight?.streaming)// Mid-turn redirect corrections. They are additional user bubbles belonging- // to this same turn, ordered after the prompt that started it.- const inflightCorrections = (projection.inflight?.corrections ?? [])- .map(correction => correction?.trim() ?? '')- .filter(Boolean)+ // to this same turn, ordered by arrival: after the output that had already+ // streamed when they were typed, before the output they redirected.+ // `correction_offsets` (assistant-text length at each accepted correction)+ // carries that boundary; older gateways omit it.+ const rawCorrections = projection.inflight?.corrections ?? []+ const rawOffsets = projection.inflight?.correction_offsets++ const inflightCorrectionEntries = rawCorrections+ .map((correction, index) => ({ text: correction?.trim() ?? '', offset: rawOffsets?.[index] }))+ .filter(entry => entry.text)++ const inflightCorrections = inflightCorrectionEntries.map(entry => entry.text)++ const correctionOffsetsUsable =+ inflightCorrectionEntries.length > 0 &&+ inflightCorrectionEntries.every(entry => typeof entry.offset === 'number' && entry.offset >= 0)// A retained failed turn (the gateway keeps error snapshots replayable when// the terminal frame may have been lost to a disconnect) — surface the@@ -718,13 +740,27 @@ export function appendLiveSessionProjection(// Only suppress the projection when the latest authoritative user row is the// same turn — older identical prompts must not hide a newly accepted repeat.// A mid-turn redirect gives that turn a RUN of user rows (prompt +- // corrections), so match the contiguous run ending at the latest user row- // rather than the single last one.+ // corrections). Arrival order seals already-streamed output BETWEEN those+ // rows (#73793), so collect the run by walking back over the live tail:+ // user rows count, live-tail assistant rows are skipped, and a committed+ // assistant reply ends the turn.const latestUserIndex = messages.map(message => message.role).lastIndexOf('user')const latestUserRun: ChatMessage[] = []- for (let index = latestUserIndex; index >= 0 && messages[index].role === 'user'; index -= 1) {- latestUserRun.unshift(messages[index])+ for (let index = latestUserIndex; index >= 0; index -= 1) {+ const candidate = messages[index]++ if (candidate.role === 'user') {+ latestUserRun.unshift(candidate)++ continue+ }++ if (candidate.role === 'assistant' && isLiveTailRow(candidate)) {+ continue+ }++ break}const persistedInLatestRun = (text: string): boolean =>@@ -742,22 +778,6 @@ export function appendLiveSessionProjection(})}- // Corrections typed while the turn ran. Each is its own bubble, placed after- // the original prompt and before the reply they redirected — the same order- // the live transcript showed. Skip any the transcript already holds so a- // resume doesn't double them.- for (const [index, correction] of inflightCorrections.entries()) {- if (persistedInLatestRun(correction)) {- continue- }-- projected.push({- id: `user-inflight-correction-${index}-${sessionId}`,- role: 'user',- parts: [textPart(correction)]- })- }-// Keep a pending assistant boundary even before the first delta when a// queued user turn follows it. This preserves the two distinct turns.//@@ -796,10 +816,65 @@ export function appendLiveSessionProjection(isLiveTailRow(liveAssistantOfCurrentTurn))- if (inflightAssistant || inflightStreaming || inflightError || (inflightUser && queuedUser)) {- if (turnAlreadyStructured && !inflightError) {- // Structure is authoritative; skip the text-only dump row.- } else {+ const wantsAssistantRow = Boolean(+ inflightAssistant || inflightStreaming || inflightError || (inflightUser && queuedUser)+ )++ const projectAssistantDump = wantsAssistantRow && !(turnAlreadyStructured && !inflightError)++ const pushCorrection = (correction: string, index: number): void => {+ if (persistedInLatestRun(correction)) {+ return+ }++ projected.push({+ id: `user-inflight-correction-${index}-${sessionId}`,+ role: 'user',+ parts: [textPart(correction)]+ })+ }++ // Corrections typed while the turn ran are ordered by ARRIVAL: each lands+ // after the assistant output that had already streamed when it was typed and+ // before the output it redirected (#73793 — the old prompt → corrections →+ // reply order spliced them above screens of output the user had already+ // read). With usable offsets the flat dump is split at each boundary; without+ // them (older gateway, or a structured/error tail that must stay whole) the+ // corrections follow the projected reply, matching the live transcript's+ // append-at-tail contract.+ if (projectAssistantDump && correctionOffsetsUsable && !inflightError && inflightAssistant) {+ let cursor = 0++ for (const [index, entry] of inflightCorrectionEntries.entries()) {+ const boundary = Math.min(Math.max(entry.offset as number, cursor), inflightAssistant.length)+ const segment = inflightAssistant.slice(cursor, boundary)++ if (segment.trim()) {+ // Sealed pre-correction output. The `inflight-assistant-` prefix marks+ // it a live-tail row so repeated resumes keep the user run intact.+ projected.push({+ id: `inflight-assistant-segment-${index}-${sessionId}`,+ role: 'assistant',+ parts: [assistantTextPart(segment)],+ pending: false,+ interim: true+ })+ }++ cursor = boundary+ pushCorrection(entry.text, index)+ }++ const tail = inflightAssistant.slice(cursor)++ projected.push({+ id: liveStreamId,+ role: 'assistant',+ parts: tail.trim() ? [assistantTextPart(tail)] : [],+ pending: inflightStreaming+ })+ } else {+ if (projectAssistantDump) {projected.push({id: liveStreamId,role: 'assistant',@@ -808,6 +883,10 @@ export function appendLiveSessionProjection(...(inflightError ? { error: inflightError } : {})})}++ for (const [index, correction] of inflightCorrections.entries()) {+ pushCorrection(correction, index)+ }}if (queuedUser) {diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 8fc2e23ef90..5d04fdde54f 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -605,6 +605,12 @@ export interface SessionResumeResponse {/** Mid-turn redirect corrections, oldest first. The turn's original prompt* stays in `user`; these are the follow-ups typed while it ran. */corrections?: string[]+ /** Parallel to `corrections`: the length of `assistant` already streamed+ * when each correction was accepted. Lets a resume rebuild arrival order —+ * the correction bubble lands after the output the user had already seen+ * and before the output it redirected (#73793). Omitted by older+ * gateways. */+ correction_offsets?: number[]/** Retained failed turn: the error the terminal frame carried (the frame* itself may have been lost to a disconnect). */error?: stringdiff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex cfb26d270ae..e02559a06d6 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -9819,6 +9819,47 @@ def test_session_redirect_records_correction_without_erasing_prompt():assert snapshot["corrections"] == ["hurry up", "and the worktree ones"]+def test_inflight_snapshot_carries_arrival_order_offsets():+ """Each correction records how much assistant text had already streamed.++ Resuming clients rebuild ARRIVAL order from these boundaries: the+ correction bubble lands after the output the user had already seen and+ before the output it redirected (#73793), instead of above the whole+ reply.+ """+ session = {}+ server._start_inflight_turn(session, "remove the session counts")+ server._append_inflight_delta(session, "Moving.")+ server._record_inflight_correction(session, "hurry up")+ server._append_inflight_delta(session, "Still.")+ server._record_inflight_correction(session, "and the worktree ones")+ server._append_inflight_delta(session, "Done soon.")++ snapshot = server._inflight_snapshot(session)+ assert snapshot is not None++ assert snapshot["corrections"] == ["hurry up", "and the worktree ones"]+ assert snapshot["correction_offsets"] == [len("Moving."), len("Moving.Still.")]+++def test_inflight_snapshot_omits_offsets_when_not_fully_recorded():+ """A pre-upgrade in-memory turn may carry corrections without offsets.++ The parallel list is only sent when every correction has one, so clients+ can trust the pairing and older snapshots degrade to the no-offset path.+ """+ session = {}+ server._start_inflight_turn(session, "prompt")+ turn = session["inflight_turn"]+ turn["corrections"] = ["legacy correction"]++ snapshot = server._inflight_snapshot(session)+ assert snapshot is not None++ assert snapshot["corrections"] == ["legacy correction"]+ assert "correction_offsets" not in snapshot++def test_inflight_snapshot_omits_corrections_when_none_recorded():session = {}server._start_inflight_turn(session, "just the prompt")diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 00896954bcd..dead62de116 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -7516,6 +7516,13 @@ def _record_inflight_correction(session: dict, text: Any) -> None:corrections = list(turn.get("corrections") or [])corrections.append(correction)turn["corrections"] = corrections+ # Arrival-order boundary: how much assistant text had already streamed+ # when this correction was accepted. Resuming clients use it to place the+ # correction bubble AFTER the output the user had already seen and BEFORE+ # the output it redirected (#73793) instead of above the whole reply.+ offsets = list(turn.get("correction_offsets") or [])+ offsets.append(len(str(turn.get("assistant") or "")))+ turn["correction_offsets"] = offsetsturn["updated_at"] = time.time()session["inflight_turn"] = turn@@ -8081,11 +8088,23 @@ def _inflight_snapshot(session: dict) -> dict | None:"streaming": streaming,"user": user,}- corrections = [c for c in (turn.get("corrections") or []) if str(c).strip()]- if corrections:+ raw_corrections = turn.get("corrections") or []+ raw_offsets = turn.get("correction_offsets") or []+ correction_pairs = [+ (str(c), raw_offsets[i] if i < len(raw_offsets) else None)+ for i, c in enumerate(raw_corrections)+ if str(c).strip()+ ]+ if correction_pairs:# Mid-turn redirects. Carried alongside the original prompt (not over# it) so resume can rebuild every user bubble the turn produced.- snapshot["corrections"] = [str(c) for c in corrections]+ snapshot["corrections"] = [c for c, _ in correction_pairs]+ # Assistant-text lengths at each correction boundary (parallel list).+ # Only sent when every correction has one, so clients can trust the+ # pairing; older in-memory turns without offsets omit the field and+ # clients fall back to placing corrections after the assistant dump.+ if all(isinstance(offset, int) and offset >= 0 for _, offset in correction_pairs):+ snapshot["correction_offsets"] = [int(offset) for _, offset in correction_pairs] # type: ignore[arg-type]if error:# Retained failed turn (see _fail_inflight_turn): carry the error# semantics so a resuming client can rebuild the failed-turn bubble