From 6c13d78563175ad70a0a4040f5f1f0a7bd8bf54a Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 28 Jun 2026 20:28:34 -0400 Subject: [PATCH] fix: reconcile confirmed prompt on message fetch to clear stale send errors (#296) * fix: reconcile confirmed prompt on message fetch to clear stale send errors * refactor: extract reconcileConfirmedPrompt into dedicated module --- frontend/src/hooks/useOpenCode.test.tsx | 76 ++++++++++++++++++++++++- frontend/src/hooks/useOpenCode.ts | 2 + frontend/src/lib/sendErrorReconcile.ts | 39 +++++++++++++ 3 files changed, 116 insertions(+), 1 deletion(-) create mode 100644 frontend/src/lib/sendErrorReconcile.ts diff --git a/frontend/src/hooks/useOpenCode.test.tsx b/frontend/src/hooks/useOpenCode.test.tsx index 018ecf90..5fea8069 100644 --- a/frontend/src/hooks/useOpenCode.test.tsx +++ b/frontend/src/hooks/useOpenCode.test.tsx @@ -2,7 +2,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { act, renderHook, waitFor } from '@testing-library/react' import type { ReactNode } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useDeleteSession, useSessionsAcrossDirectories } from './useOpenCode' +import { useDeleteSession, useMessages, useSessionsAcrossDirectories } from './useOpenCode' +import { useSendErrorStore } from '../stores/sendErrorStore' vi.mock('../lib/toast', () => ({ showToast: { @@ -264,3 +265,76 @@ describe('useSessionsAcrossDirectories', () => { ) }) }) + +describe('useMessages send error reconciliation', () => { + const fetchMock = vi.fn() + + beforeEach(() => { + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + useSendErrorStore.setState({ errors: {}, queuedPrompts: {} }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('clears a stale network send error when fetched messages contain the prompt', async () => { + useSendErrorStore.getState().setError({ + sessionID: 'session-1', + title: 'Error', + message: 'Load failed', + failedPrompt: 'sent while backgrounded', + kind: 'network', + }) + + fetchMock.mockResolvedValueOnce(new Response(JSON.stringify([ + { + info: { id: 'user-1', role: 'user', sessionID: 'session-1', time: { created: 1 } }, + parts: [{ id: 'part-1', type: 'text', text: 'sent while backgrounded', messageID: 'user-1', sessionID: 'session-1' }], + }, + ]), { headers: { 'Content-Type': 'application/json' } })) + + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ) + + renderHook(() => useMessages('/api/opencode', 'session-1', '/repo'), { wrapper }) + + await waitFor(() => { + expect(useSendErrorStore.getState().getError('session-1')).toBeNull() + }) + }) + + it('keeps a network send error when fetched messages do not contain the prompt', async () => { + useSendErrorStore.getState().setError({ + sessionID: 'session-1', + title: 'Error', + message: 'Load failed', + failedPrompt: 'missing prompt', + kind: 'network', + }) + + fetchMock.mockResolvedValueOnce(new Response(JSON.stringify([ + { + info: { id: 'user-1', role: 'user', sessionID: 'session-1', time: { created: 1 } }, + parts: [{ id: 'part-1', type: 'text', text: 'different prompt', messageID: 'user-1', sessionID: 'session-1' }], + }, + ]), { headers: { 'Content-Type': 'application/json' } })) + + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ) + + renderHook(() => useMessages('/api/opencode', 'session-1', '/repo'), { wrapper }) + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + expect(useSendErrorStore.getState().getError('session-1')).toEqual(expect.objectContaining({ + failedPrompt: 'missing prompt', + })) + }) +}) diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 13a17b95..f6e85d04 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -14,6 +14,7 @@ import { showToast } from "../lib/toast"; import { useSendErrorStore } from "../stores/sendErrorStore"; import { useSessionStatus } from "../stores/sessionStatusStore"; import { invalidateSessionListCaches, messagesQueryKey } from "../lib/queryInvalidation"; +import { reconcileConfirmedPrompt } from "../lib/sendErrorReconcile"; type AssistantMessage = components["schemas"]["AssistantMessage"]; @@ -143,6 +144,7 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str queryKey: messagesQueryKey(opcodeUrl, sessionID, directory), queryFn: async () => { const response = await client!.listMessages(sessionID!) + reconcileConfirmedPrompt(sessionID!, response as MessageWithParts[]) return response as MessageWithParts[] }, enabled: !!client && !!sessionID, diff --git a/frontend/src/lib/sendErrorReconcile.ts b/frontend/src/lib/sendErrorReconcile.ts new file mode 100644 index 00000000..8392b0d6 --- /dev/null +++ b/frontend/src/lib/sendErrorReconcile.ts @@ -0,0 +1,39 @@ +import type { MessageWithParts } from '../api/types' +import { useSendErrorStore } from '../stores/sendErrorStore' + +const getUserMessageText = (message: MessageWithParts): string => { + if (message.info.role !== 'user') return '' + return message.parts + .map((part) => (part.type === 'text' ? part.text || '' : '')) + .join('') + .trim() +} + +const hasUserMessageText = (messages: MessageWithParts[], prompt: string): boolean => { + const expected = prompt.trim() + if (!expected) return false + return messages.some((message) => getUserMessageText(message) === expected) +} + +/** + * Strict backstop for clearing stale send state when a prompt is confirmed delivered. + * + * The SSE `message.updated` handler is the realtime authority and clears send errors + * unconditionally because it only receives message metadata (text parts stream in + * separately). This helper runs against a fully fetched message list — where text parts + * are present — and clears only when the failed/queued prompt text actually appears, + * recovering sessions whose confirming SSE events were missed (e.g. backgrounded tab). + */ +export const reconcileConfirmedPrompt = (sessionID: string, messages: MessageWithParts[]): void => { + const sendErrorStore = useSendErrorStore.getState() + const sendError = sendErrorStore.getError(sessionID) + const queuedPrompt = sendErrorStore.queuedPrompts[sessionID] + + if (sendError?.kind === 'network' && sendError.failedPrompt && hasUserMessageText(messages, sendError.failedPrompt)) { + sendErrorStore.clearNetworkError(sessionID) + } + + if (queuedPrompt && hasUserMessageText(messages, queuedPrompt)) { + sendErrorStore.clearQueuedPrompt(sessionID) + } +}