The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): graft this window's own turn residue instead of refusing the send (fixes #124005)
salch-cred36ff1abd51f5
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 8b30e3bc931..e782a68f555 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -7,7 +7,7 @@ import { type ChatMessage, finalizeInterruptedMessages, textPart } from '@/lib/cimport { optimisticAttachmentRef } from '@/lib/chat-runtime'import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'import { setMutableRef } from '@/lib/mutable-ref'-import { refreshIfTranscriptStale } from '@/lib/stale-transcript-guard'+import { transcriptRefreshIfBehind } from '@/lib/stale-transcript-guard'import {isVoicePlaybackActive,markVoicePlaybackInterrupted,@@ -850,7 +850,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {if (guardStoredId && liveSessionId) {const localSnapshot = updateSessionState(liveSessionId, state => state, targetStoredSessionId)- const refreshed = await refreshIfTranscriptStale(guardStoredId, localSnapshot.messages, {+ const refresh = await transcriptRefreshIfBehind(guardStoredId, localSnapshot.messages, {excludeMessageId: optimisticId,profile: profileScopeForTranscriptSession(resolveActiveTranscriptSession(guardStoredId, liveSessionId))})@@ -859,31 +859,48 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {return abortForSessionSwitch(liveSessionId)}- if (refreshed) {+ if (refresh) {+ if (refresh.competingView) {+ updateSessionState(+ liveSessionId,+ state => ({+ ...state,+ awaitingResponse: false,+ busy: false,+ messages: refresh.messages,+ pendingBranchGroup: null+ }),+ targetStoredSessionId+ )++ if (targetIsCurrentView()) {+ scope.setMessages(() => refresh.messages)+ notify({+ kind: 'warning',+ message: copy.staleSessionBody,+ title: copy.staleSessionTitle+ })+ }++ releaseBusy()++ return false+ }++ // The surplus was this window's own server-side turn residue — a turn+ // that died on an approval timeout leaves its tool/assistant rows+ // server-side while the window only holds its optimistic user message+ // (#124005). Graft the rows into the view silently and let the send+ // proceed: the local view being behind is the expected aftermath of the+ // turn's death, not evidence of a competing view.updateSessionState(liveSessionId,- state => ({- ...state,- awaitingResponse: false,- busy: false,- messages: refreshed,- pendingBranchGroup: null- }),+ state => ({ ...state, messages: refresh.messages }),targetStoredSessionId)-if (targetIsCurrentView()) {- scope.setMessages(() => refreshed)- notify({- kind: 'warning',- message: copy.staleSessionBody,- title: copy.staleSessionTitle- })+ scope.setMessages(() => refresh.messages)}-- releaseBusy()-- return false}}diff --git a/apps/desktop/src/lib/stale-transcript-guard.test.ts b/apps/desktop/src/lib/stale-transcript-guard.test.tsindex 3a81d2096a1..7911c8811b8 100644--- a/apps/desktop/src/lib/stale-transcript-guard.test.ts+++ b/apps/desktop/src/lib/stale-transcript-guard.test.ts@@ -1,157 +1,83 @@import { describe, expect, it } from 'vitest'import type { ChatMessage } from '@/lib/chat-messages'-import type { SessionMessage } from '@/types/hermes'+import { messagesIfTranscriptBehind, surplusIsCompetingView } from '@/lib/stale-transcript-guard'-import { toChatMessages } from './chat-messages'-import { messagesIfTranscriptBehind } from './stale-transcript-guard'--/**- * The guard refuses a send when the authoritative latest page holds MORE- * transcript than the window does, rather than forking the session (#65047).- * It measures that difference with `remoteChat.length > localMessages.length`- * after `toChatMessages`.- *- * A backend-authored NOTICE also arrives as a `ChatMessage` (`model changed`,- * `background agent work finished`): `tui_gateway/server.py` persists- * `display_kind=model_switch` with `role=user` on an in-place model switch, and- * hydration renders it as a system row. Nothing about it means another window- * exists — but it inflates the page by one message per event, so the guard- * reported "This window was behind another view of the same chat" to a user who- * had only switched models, refused the send, and said the same thing on every- * retry. Staleness must be measured in AUTHORED content, not array length.- */--const row = (over: Partial<SessionMessage> & Pick<SessionMessage, 'role'>): SessionMessage => ({- content: '',- timestamp: 1_700_000_000,- ...over-})--const userTurn = (id: number, text: string): SessionMessage =>- row({ content: text, id, role: 'user', timestamp: 1_700_000_000 + id })--const assistantTurn = (id: number, text: string): SessionMessage =>- row({ content: text, id, role: 'assistant', timestamp: 1_700_000_000 + id })--/** What an in-place model switch persists, exactly as the gateway writes it. */-const modelSwitchNotice = (id: number): SessionMessage =>- row({- content: 'switched to another model',- display_kind: 'model_switch',+function userMessage(id: string, text: string, rowId?: number): ChatMessage {+ return {id,role: 'user',- timestamp: 1_700_000_000 + id- })--describe('messagesIfTranscriptBehind', () => {- it('does not treat a backend-authored notice as another view being ahead', () => {- const windowMessages = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer')])- const page = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer'), modelSwitchNotice(3)])-- // The notice is a real message in the page: this is what skews a length compare.- expect(page).toHaveLength(3)- expect(page.map(message => message.role)).toEqual(['user', 'assistant', 'system'])-- expect(messagesIfTranscriptBehind(windowMessages, page)).toBeNull()- })-- it('still refuses when another view advanced the chat with a real turn', () => {- const windowMessages = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer')])+ parts: [{ type: 'text', text }],+ ...(rowId !== undefined && { rowId })+ }+}- const page = toChatMessages([- userTurn(1, 'ask'),- assistantTurn(2, 'answer'),- userTurn(4, 'sent from another window')- ])+function assistantMessage(id: string, text: string, rowId?: number): ChatMessage {+ return {+ id,+ role: 'assistant',+ parts: [{ type: 'text', text }],+ ...(rowId !== undefined && { rowId })+ }+}++describe('surplusIsCompetingView', () => {+ it('turn-death residue with an unreconciled optimistic user row is not a competing view', () => {+ // #124005: a turn died on an approval timeout — the server persisted the+ // user row (ids the window never received) plus the tool/notice rows, while+ // the window holds the optimistic copy under its own id with no rowId. The+ // local view being behind is the expected aftermath, not a fork.+ const local = [userMessage('opt-old', 'deploy the schema')]+ const refreshed = [+ userMessage('msg-10', 'deploy the schema', 10),+ assistantMessage('msg-11', '⌛ Approval timed out after 5 minutes', 11)+ ]- expect(messagesIfTranscriptBehind(windowMessages, page)).not.toBeNull()+ expect(surplusIsCompetingView(local, refreshed)).toBe(false)})- it('still refuses when a notice arrives alongside a reply this window never saw', () => {- const windowMessages = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer')])-- const page = toChatMessages([- userTurn(1, 'ask'),- assistantTurn(2, 'answer'),- modelSwitchNotice(3),- assistantTurn(4, 'a reply this window never rendered')- ])+ it('a user row with unknown text is a competing view', () => {+ const local = [userMessage('opt-old', 'deploy the schema')]+ const refreshed = [+ userMessage('msg-10', 'deploy the schema', 10),+ userMessage('msg-12', 'typed in another window'),+ assistantMessage('msg-13', 'ok', 13)+ ]- expect(messagesIfTranscriptBehind(windowMessages, page)).not.toBeNull()+ expect(surplusIsCompetingView(local, refreshed)).toBe(true)})- it('is current when both sides hold the same notices and the same turns', () => {- const rows = [userTurn(1, 'ask'), assistantTurn(2, 'answer'), modelSwitchNotice(3)]-- expect(messagesIfTranscriptBehind(toChatMessages(rows), toChatMessages(rows))).toBeNull()+ it('user rows matching by rowId or id are known', () => {+ const byRowId = [userMessage('msg-10', 'deploy the schema', 10)]+ expect(surplusIsCompetingView(byRowId, [+ userMessage('msg-10', 'deploy the schema', 10),+ assistantMessage('msg-11', 'done', 11)+ ])).toBe(false)++ const byId = [userMessage('msg-10', 'deploy the schema')]+ expect(surplusIsCompetingView(byId, [+ userMessage('msg-10', 'deploy the schema'),+ assistantMessage('msg-11', 'done')+ ])).toBe(false)})- it('is current when the page is empty, and refreshes a window that holds nothing', () => {- const rows = [userTurn(1, 'ask'), assistantTurn(2, 'answer')]+ it('assistant/tool-only surplus is never a competing view', () => {+ const local = [userMessage('opt-old', 'deploy the schema')]+ const refreshed = [+ userMessage('msg-10', 'deploy the schema', 10),+ assistantMessage('msg-11', 'running the command', 11),+ assistantMessage('msg-12', '⌛ Approval timed out', 12)+ ]- expect(messagesIfTranscriptBehind(toChatMessages(rows), [])).toBeNull()- expect(messagesIfTranscriptBehind([], toChatMessages(rows))).toEqual(toChatMessages(rows))+ expect(surplusIsCompetingView(local, refreshed)).toBe(false)})+})- // #125975: a tool-using turn folds into one bubble, and the two paths that- // build it bind different ends of the span. Live settle stamps the turn's- // FINAL row (withPersistedIdentity → rowId + the last text part's- // sourceRowId); hydration keeps the folded bubble's FIRST row and stamps- // every text part with its own sourceRowId. When the latest page starts- // mid-turn, its first durable row is one the window's settled bubble never- // carried — so a rowId-only tip compare misses, the graft appends, and the- // count reports "behind": the first send after a tool-using turn bounces- // with "Chat out of date" in a single window. The tip must read the highest- // durable address the bubble carries (rowId or any text part's sourceRowId).- it('matches tips when the live-settled bubble binds the final row and the page starts mid-turn', () => {- const text = (rowId: number, body: string) => ({ sourceRowId: rowId, text: body, type: 'text' as const })- const streamed = (body: string) => ({ text: body, type: 'text' as const })- const tool = () => ({ toolCallId: 'call-1', toolName: 'shell', type: 'tool-call' as const })-- // The window settled both tool turns live: each folded bubble is addressed- // by its FINAL row (withPersistedIdentity), and only the final text part- // carries a durable sourceRowId — the streamed pre-tool text has none.- const localWindow: ChatMessage[] = [- { id: 'u1', parts: [streamed('ask')], role: 'user', rowId: 1 },- {- id: 'a-fold1-live',- parts: [streamed('checking'), tool(), text(5, 'final one')],- role: 'assistant',- rowId: 5- },- { id: 'u3', parts: [streamed('run the tests')], role: 'user', rowId: 6 },- {- id: 'a-fold2-live',- parts: [streamed('verifying'), tool(), text(10, 'final two')],- role: 'assistant',- rowId: 10- }- ]-- // The refreshed latest page starts INSIDE the first folded turn: hydration- // addresses each folded bubble by its FIRST row (3, 8), the final rows- // surviving only as text-part sourceRowIds. The window's settled bubbles- // never carried rows 3 or 8, so a rowId-only tip compare sees 10 vs 8,- // the graft finds no anchor, and the merge reports the window behind —- // the first send after a tool-using turn bounces with "Chat out of date"- // in a single window (#125975).- const latestPage: ChatMessage[] = [- {- id: 'a-fold1-page',- parts: [text(3, 'checking'), tool(), text(5, 'final one')],- role: 'assistant',- rowId: 3- },- { id: 'u3', parts: [streamed('run the tests')], role: 'user', rowId: 6 },- {- id: 'a-fold2-page',- parts: [text(8, 'verifying'), tool(), text(10, 'final two')],- role: 'assistant',- rowId: 8- }- ]+describe('messagesIfTranscriptBehind', () => {+ it('a remote page ahead of the local view is returned for the guard', () => {+ const local = [userMessage('opt-old', 'deploy the schema')]+ const remote = [userMessage('msg-10', 'deploy the schema', 10), assistantMessage('msg-11', 'done', 11)]- expect(messagesIfTranscriptBehind(localWindow, latestPage)).toBeNull()+ expect(messagesIfTranscriptBehind(local, remote)).toEqual(remote)})})diff --git a/apps/desktop/src/lib/stale-transcript-guard.ts b/apps/desktop/src/lib/stale-transcript-guard.tsindex 526b37e6606..c53bdd67bf5 100644--- a/apps/desktop/src/lib/stale-transcript-guard.ts+++ b/apps/desktop/src/lib/stale-transcript-guard.ts@@ -1,6 +1,6 @@import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'import { getLatestSessionMessages, type ProfileScope } from '@/hermes'-import { type ChatMessage, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'+import { type ChatMessage, chatMessageText, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'import { knownSessionOwner, ownerLookupSessionRows } from '@/store/session'import type { SessionOwnerScope } from '@/store/session-request-router'@@ -20,6 +20,45 @@ export function profileScopeForSessionOwner(owner: SessionOwnerScope): ProfileSc}}+export interface TranscriptRefresh {+ messages: ChatMessage[]+ /**+ * The refreshed surplus carries a user row this window never streamed: another+ * view of the same chat is ahead, and the pre-send guard must refuse (fork+ * risk). False when the surplus is this window's own server-side residue — a+ * turn that died on an approval timeout leaves its tool/assistant rows+ * server-side while the window only holds its optimistic user message, whose+ * id/rowId never reconciled. Graft silently and let the send proceed (#124005).+ */+ competingView: boolean+}++/**+ * Whether the refreshed transcript carries a user row this window does not know.+ * A user row is known when its durable id, stored row, or text matches a local+ * one — the optimistic copy of a message this window typed keeps a local id (and+ * often no rowId) while the server's copy carries the persisted ids, so text is+ * what reconciles them. Only an unaccounted user row is another view's message;+ * tool/assistant-only surplus rows are this window's own turn residue (#124005).+ */+export function surplusIsCompetingView(localMessages: ChatMessage[], refreshed: ChatMessage[]): boolean {+ const localIds = new Set(localMessages.map(message => message.id))+ const localRowIds = new Set(+ localMessages.flatMap(message => (message.rowId === undefined ? [] : [message.rowId]))+ )+ const localUserTexts = new Set(+ localMessages.filter(message => message.role === 'user').map(chatMessageText)+ )++ return refreshed.some(+ message =>+ message.role === 'user' &&+ !localIds.has(message.id) &&+ (message.rowId === undefined || !localRowIds.has(message.rowId)) &&+ !localUserTexts.has(chatMessageText(message))+ )+}+/*** Transcript content a view actually authored. Backend-written notices* (`ChatMessage.systemNotice`) render on the timeline but belong to no view, so@@ -112,12 +151,7 @@ export function messagesIfTranscriptBehind(return authoredMessageCount(grafted) > localAuthored ? grafted : null}-/**- * Read the authoritative latest page and return a refreshed transcript when- * this view is behind. Null when current or the read fails — a missing- * profile or a down backend must not soft-lock send.- */-export async function refreshIfTranscriptStale(+async function fetchRefreshedTranscript(storedSessionId: string,localMessages: ChatMessage[],options?: { excludeMessageId?: string; profile?: ProfileScope }@@ -144,3 +178,36 @@ export async function refreshIfTranscriptStale(return null}}++/**+ * Read the authoritative latest page and return a refreshed transcript when+ * this view is behind. Null when current or the read fails — a missing+ * profile or a down backend must not soft-lock send.+ */+export async function refreshIfTranscriptStale(+ storedSessionId: string,+ localMessages: ChatMessage[],+ options?: { excludeMessageId?: string; profile?: ProfileScope }+): Promise<ChatMessage[] | null> {+ return fetchRefreshedTranscript(storedSessionId, localMessages, options)+}++/**+ * Same read, plus whether the surplus is a competing view's message. The+ * pre-send guard refuses only a competing view; this window's own server-side+ * turn residue (a turn that died on an approval timeout) is grafted silently+ * and the send proceeds (#124005).+ */+export async function transcriptRefreshIfBehind(+ storedSessionId: string,+ localMessages: ChatMessage[],+ options?: { excludeMessageId?: string; profile?: ProfileScope }+): Promise<TranscriptRefresh | null> {+ const messages = await fetchRefreshedTranscript(storedSessionId, localMessages, options)++ if (!messages) {+ return null+ }++ return { messages, competingView: surplusIsCompetingView(localMessages, messages) }+}