From 4e32fd5b00d18d7e11715d2f72d715c769f821e8 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 10 Jun 2026 08:35:19 -0400 Subject: [PATCH] feat: add session status store with optimistic active state and SSE polling (#272) * feat: add session status store with optimistic active state and SSE polling - Adds sessionStatusStore with setOptimisticActive (auto-timeout), statusCache deduplication, and replaceStatuses/clearStatus - Integrates store in useSendPrompt (set optimistic on send, clear on error) - Adds session.status SSE event handling in useSSE with 5s polling fallback - Refactors test to mock the store instead of using real store instance - Fixes repoId null check in useRepoActivity * feat: replace event-source-polyfill with native SSE for PromptInput * fix: keep stop button visible and hide clear prompt button during active session * feat: restore failed queued prompts and preserve optimistic active status during poll * test: add MessageThread tests for optimistic editing state and resend flow * fix: handle queued prompt edge cases during pending submission and SSE errors --- .../message/EditableUserMessage.tsx | 3 +- .../components/message/MessageThread.test.tsx | 87 +++++++++ .../message/PromptInput.stt.test.tsx | 147 +++++++++++++- .../src/components/message/PromptInput.tsx | 159 +++++++++++---- .../navigation/RepoQuickSwitchSheet.test.tsx | 37 ++++ .../navigation/RepoQuickSwitchSheet.tsx | 7 + frontend/src/hooks/useOpenCode.ts | 30 ++- frontend/src/hooks/useRepoActivity.ts | 4 +- frontend/src/hooks/useSSE.test.tsx | 182 +++++++++++++++++- frontend/src/hooks/useSSE.ts | 32 ++- frontend/src/hooks/useSendPrompt.test.ts | 74 ++++++- frontend/src/pages/SessionDetail.tsx | 2 +- .../SessionDetail.scroll-floating.test.tsx | 18 +- frontend/src/stores/sendErrorStore.test.ts | 30 ++- frontend/src/stores/sendErrorStore.ts | 33 ++++ frontend/src/stores/sessionStatusStore.ts | 49 +++++ 16 files changed, 833 insertions(+), 61 deletions(-) diff --git a/frontend/src/components/message/EditableUserMessage.tsx b/frontend/src/components/message/EditableUserMessage.tsx index cc3aa8ce..62ab586b 100644 --- a/frontend/src/components/message/EditableUserMessage.tsx +++ b/frontend/src/components/message/EditableUserMessage.tsx @@ -88,7 +88,6 @@ export const EditableUserMessage = memo(function EditableUserMessage({ onChange={(e) => setEditedContent(e.target.value)} onKeyDown={handleKeyDown} onFocus={() => setIsEditingMessage(true)} - onBlur={() => setIsEditingMessage(false)} className="w-full p-3 rounded-lg bg-background border border-primary/50 focus:border-primary focus:ring-1 focus:ring-primary outline-none resize-none min-h-[60px] text-[16px] md:text-sm" placeholder="Edit your message..." disabled={refreshMessage.isPending} @@ -158,4 +157,4 @@ export const ClickableUserMessage = memo(function ClickableUserMessage({ ) -}) \ No newline at end of file +}) diff --git a/frontend/src/components/message/MessageThread.test.tsx b/frontend/src/components/message/MessageThread.test.tsx index 3fc8c52e..8ed09100 100644 --- a/frontend/src/components/message/MessageThread.test.tsx +++ b/frontend/src/components/message/MessageThread.test.tsx @@ -1,6 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { render, screen, fireEvent } from '@testing-library/react' import { MessageThread } from './MessageThread' +import { useUIState } from '@/stores/uiStateStore' const mocks = vi.hoisted(() => ({ useSessionStatus: vi.fn(), @@ -8,6 +9,8 @@ const mocks = vi.hoisted(() => ({ useSettings: vi.fn(), usePermissions: vi.fn(), useQuestions: vi.fn(), + useRefreshMessage: vi.fn(), + useSessionAgent: vi.fn(), })) vi.mock('@/stores/sessionStatusStore', () => ({ @@ -27,6 +30,14 @@ vi.mock('@/contexts/EventContext', () => ({ useQuestions: () => mocks.useQuestions(), })) +vi.mock('@/hooks/useRemoveMessage', () => ({ + useRefreshMessage: () => mocks.useRefreshMessage(), +})) + +vi.mock('@/hooks/useSessionAgent', () => ({ + useSessionAgent: () => mocks.useSessionAgent(), +})) + interface MockSettingsReturn { preferences: { simpleChatMode: boolean @@ -147,6 +158,12 @@ describe('MessageThread', () => { mocks.useQuestions.mockReturnValue({ getForCallID: vi.fn(() => null), }) + mocks.useRefreshMessage.mockReturnValue({ + isPending: false, + mutate: vi.fn(), + }) + mocks.useSessionAgent.mockReturnValue({ agent: 'test-agent' }) + useUIState.getState().setIsEditingMessage(false) }) it('renders assistant message with only subtask part as standalone row without header', () => { @@ -397,4 +414,74 @@ describe('MessageThread', () => { expect(screen.getByText('Hello')).toBeInTheDocument() expect(screen.getByText('You')).toBeInTheDocument() }) + + it('keeps global editing state active when edit textarea blurs', () => { + setupSettings({ + simpleChatMode: false, + showReasoning: false, + }) + + const messages = [ + createUserMessage('1', 'Hello'), + createAssistantMessage('2', [createTextPart('This is a response', '2')]), + ] + + const { unmount } = render( + + ) + + fireEvent.click(screen.getByTitle('Edit message')) + const textarea = screen.getByPlaceholderText('Edit your message...') + fireEvent.focus(textarea) + expect(useUIState.getState().isEditingMessage).toBe(true) + + fireEvent.blur(textarea) + expect(useUIState.getState().isEditingMessage).toBe(true) + + unmount() + expect(useUIState.getState().isEditingMessage).toBe(false) + }) + + it('resends an edited prompt after the edit textarea blurs', () => { + setupSettings({ + simpleChatMode: false, + showReasoning: false, + }) + const mutate = vi.fn() + mocks.useRefreshMessage.mockReturnValue({ + isPending: false, + mutate, + }) + + const messages = [ + createUserMessage('1', 'Hello'), + createAssistantMessage('2', [createTextPart('This is a response', '2')]), + ] + + render( + + ) + + fireEvent.click(screen.getByTitle('Edit message')) + const textarea = screen.getByPlaceholderText('Edit your message...') + fireEvent.change(textarea, { target: { value: 'Updated prompt' } }) + fireEvent.blur(textarea) + fireEvent.click(screen.getByRole('button', { name: /resend/i })) + + expect(mutate).toHaveBeenCalledWith( + expect.objectContaining({ + assistantMessageID: '2', + userMessageContent: 'Updated prompt', + }), + expect.any(Object), + ) + }) }) diff --git a/frontend/src/components/message/PromptInput.stt.test.tsx b/frontend/src/components/message/PromptInput.stt.test.tsx index 76d2a999..89a0f1ff 100644 --- a/frontend/src/components/message/PromptInput.stt.test.tsx +++ b/frontend/src/components/message/PromptInput.stt.test.tsx @@ -23,8 +23,11 @@ const mocks = vi.hoisted(() => ({ useVariants: vi.fn(), useSessionAgent: vi.fn(), useAgents: vi.fn(), + useSendPromptMutate: vi.fn(), + sendPromptPending: vi.fn(() => false), useUserBash: vi.fn(), useSessionAgentStore: vi.fn(), + useSendErrorStore: vi.fn(), useSettings: vi.fn(), EventContext: vi.fn(), })) @@ -38,9 +41,9 @@ vi.mock('@/hooks/useMobile', () => ({ })) vi.mock('@/hooks/useOpenCode', () => ({ - useSendPrompt: () => ({ mutate: vi.fn() }), + useSendPrompt: () => ({ mutate: mocks.useSendPromptMutate, isPending: mocks.sendPromptPending() }), useAbortSession: () => ({ mutate: vi.fn() }), - useSendShell: () => ({ mutate: vi.fn() }), + useSendShell: () => ({ mutate: vi.fn(), isPending: false }), useOpenCodeClient: () => ({}), useAgents: () => ({ data: [] }), })) @@ -77,6 +80,10 @@ vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore, })) +vi.mock('@/stores/sendErrorStore', () => ({ + useSendErrorStore: mocks.useSendErrorStore, +})) + vi.mock('@/contexts/EventContext', () => ({ usePermissions: () => ({ hasForSession: vi.fn().mockReturnValue(false), @@ -153,6 +160,10 @@ describe('PromptInput STT Gesture Tests', () => { mockReset.mockReturnValue(undefined) mockClear.mockReturnValue(undefined) mockSetAgent.mockClear() + mocks.useSendPromptMutate.mockImplementation((_variables, options) => { + options?.onSuccess?.() + }) + mocks.sendPromptPending.mockReturnValue(false) mocks.useMobile.mockReturnValue(true) mocks.useSTT.mockReturnValue({ @@ -189,8 +200,9 @@ describe('PromptInput STT Gesture Tests', () => { }) mocks.useSessionAgent.mockReturnValue({ agent: 'default' }) mocks.useAgents.mockReturnValue({ data: [] }) - mocks.useUserBash.mockReturnValue({ addUserBashCommand: vi.fn() }) - mocks.useSessionAgentStore.mockReturnValue({ setAgent: mockSetAgent }) + mocks.useUserBash.mockImplementation((selector) => selector({ addUserBashCommand: vi.fn() })) + mocks.useSessionAgentStore.mockImplementation((selector) => selector({ setAgent: mockSetAgent })) + mocks.useSendErrorStore.mockImplementation((selector) => selector({ errors: {} })) useUIState.getState().clearPendingPromptCommand() useUIState.getState().clearPendingPromptFile() }) @@ -241,6 +253,133 @@ describe('PromptInput STT Gesture Tests', () => { } describe('quick tap behavior', () => { + it('keeps submitted text until send succeeds', async () => { + mocks.useSendPromptMutate.mockImplementation(() => undefined) + renderComponent() + + const input = screen.getByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: 'retry me' } }) + fireEvent.click(screen.getByTitle('Send')) + + expect(input).toHaveValue('retry me') + }) + + it('clears submitted text after send success', async () => { + renderComponent() + + const input = screen.getByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: 'sent message' } }) + fireEvent.click(screen.getByTitle('Send')) + + await waitFor(() => { + expect(input).toHaveValue('') + }) + }) + + it('clears submitted text once the server confirms it is processing', async () => { + mocks.useSendPromptMutate.mockImplementation(() => undefined) + const queryClient = createTestQueryClient() + const { rerender } = render( + + + , + ) + + const input = screen.getByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: 'do the thing' } }) + fireEvent.click(screen.getByTitle('Send')) + + expect(input).toHaveValue('do the thing') + + rerender( + + + , + ) + + await waitFor(() => { + expect(input).toHaveValue('') + }) + }) + + it('allows queuing a follow-up while a non-queued send is pending', async () => { + mocks.sendPromptPending.mockReturnValue(true) + render( + + + , + ) + + const input = screen.getByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: 'follow-up' } }) + + const queueButton = screen.getByTitle('Queue message') + expect(queueButton).not.toBeDisabled() + + fireEvent.click(queueButton) + + expect(mocks.useSendPromptMutate).toHaveBeenCalledWith( + expect.objectContaining({ prompt: 'follow-up', queued: true }), + expect.any(Object), + ) + }) + + it('restores a failed queued prompt when the input is empty', async () => { + const queryClient = createTestQueryClient() + const { rerender } = render( + + + , + ) + + const input = screen.getByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: 'queued message' } }) + fireEvent.click(screen.getByTitle('Queue message')) + + expect(mocks.useSendPromptMutate).toHaveBeenCalledWith( + expect.objectContaining({ prompt: 'queued message', queued: true }), + expect.any(Object), + ) + + await waitFor(() => { + expect(input).toHaveValue('') + }) + + mocks.useSendErrorStore.mockImplementation((selector) => selector({ + errors: { + 'test-session': { + sessionID: 'test-session', + title: 'Error', + message: 'Queued send failed', + failedPrompt: 'queued message', + }, + }, + })) + + rerender( + + + , + ) + + await waitFor(() => { + expect(screen.getByPlaceholderText('Send a message...')).toHaveValue('queued message') + }) + }) + + it('keeps stop available while active with prompt content', async () => { + render( + + + + ) + + const input = screen.getByPlaceholderText('Send a message...') + fireEvent.change(input, { target: { value: 'draft while active' } }) + + expect(screen.getAllByTitle('Stop').length).toBeGreaterThan(0) + }) + it('inserts a command selected from the mobile drawer', async () => { renderComponent() diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 4dc6b696..63eb1990 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -13,6 +13,7 @@ import { useUserBash } from '@/stores/userBashStore' import { useModelStore } from '@/stores/modelStore' import { useSessionAgentStore } from '@/stores/sessionAgentStore' import { useUIState } from '@/stores/uiStateStore' +import { useSendErrorStore } from '@/stores/sendErrorStore' import { useMobile } from '@/hooks/useMobile' import { usePermissions } from '@/contexts/EventContext' @@ -105,7 +106,6 @@ export const PromptInput = memo(forwardRef( const [selectedCommandIndex, setSelectedCommandIndex] = useState(0) const [selectedAgent, setSelectedAgent] = useState(null) const [localMode, setLocalMode] = useState(null) - const [isFocused, setIsFocused] = useState(false) const [isTogglingRecording, setIsTogglingRecording] = useState(false) const [isVoiceSwipeArmed, setIsVoiceSwipeArmed] = useState(false) const [isVoiceAutoSendPending, setIsVoiceAutoSendPending] = useState(false) @@ -117,6 +117,9 @@ export const PromptInput = memo(forwardRef( const ignoreVoiceClickUntilRef = useRef(0) const voiceStartRequestRef = useRef(0) const handleSubmitRef = useRef<() => void>(() => {}) + const promptRef = useRef(prompt) + const attachedFilesRef = useRef(attachedFiles) + const imageAttachmentsRef = useRef(imageAttachments) const pendingPromptCommand = useUIState((state) => state.pendingPromptCommand) const pendingPromptFile = useUIState((state) => state.pendingPromptFile) const clearPendingPromptCommand = useUIState((state) => state.clearPendingPromptCommand) @@ -148,7 +151,44 @@ export const PromptInput = memo(forwardRef( setIsVoiceAutoSendPending(false) setIsVoiceAutoSendWaitingForTranscript(false) }, []) - + + useEffect(() => { + promptRef.current = prompt + attachedFilesRef.current = attachedFiles + imageAttachmentsRef.current = imageAttachments + }, [attachedFiles, imageAttachments, prompt]) + + const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map, submittedImageAttachments: ImageAttachment[]) => { + if ( + promptRef.current !== submittedPrompt || + attachedFilesRef.current !== submittedAttachedFiles || + imageAttachmentsRef.current !== submittedImageAttachments + ) { + return + } + + setPrompt('') + setAttachedFiles(new Map()) + revokeBlobUrls(submittedImageAttachments) + setImageAttachments([]) + setSelectedAgent(null) + clearSTT() + }, [clearSTT]) + + const pendingConfirmClearRef = useRef<{ + prompt: string + files: Map + images: ImageAttachment[] + } | null>(null) + + useEffect(() => { + if (!isStreamingResponse) return + const pending = pendingConfirmClearRef.current + if (!pending) return + pendingConfirmClearRef.current = null + clearSubmittedPrompt(pending.prompt, pending.files, pending.images) + }, [isStreamingResponse, clearSubmittedPrompt]) + useImperativeHandle(ref, () => ({ setPromptValue: (value: string) => { setPrompt(value) @@ -174,6 +214,7 @@ export const PromptInput = memo(forwardRef( }), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState]) const sendPrompt = useSendPrompt(opcodeUrl, directory) const sendShell = useSendShell(opcodeUrl, directory) + const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending const abortSession = useAbortSession(opcodeUrl, directory, sessionID) const { filterCommands } = useCommands(opcodeUrl) const { executeCommand } = useCommandHandler({ @@ -196,6 +237,16 @@ export const PromptInput = memo(forwardRef( ) const { data: agents = [] } = useAgents(opcodeUrl, directory) + const failedPrompt = useSendErrorStore((state) => state.errors[sessionID]?.failedPrompt) + const restoredFailedPromptRef = useRef(null) + + useEffect(() => { + if (!failedPrompt || restoredFailedPromptRef.current === failedPrompt) return + restoredFailedPromptRef.current = failedPrompt + if (promptRef.current) return + setPrompt(failedPrompt) + textareaRef.current?.focus() + }, [failedPrompt]) const mentionItems = useMemo((): MentionItem[] => { const filteredAgents = filterAgentsByQuery( @@ -234,39 +285,52 @@ export const PromptInput = memo(forwardRef( onScrollToBottom() const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments) const agentUsed = selectedAgent || currentMode - sendPrompt.mutate({ - sessionID, - parts, - model: currentModel, - agent: agentUsed, - variant: currentVariant, - queued: true - }) + const submittedPrompt = prompt + const submittedAttachedFiles = attachedFiles + const submittedImageAttachments = imageAttachments + sendPrompt.mutate( + { + sessionID, + prompt: submittedPrompt, + parts, + model: currentModel, + agent: agentUsed, + variant: currentVariant, + queued: true + }, + { + onSuccess: () => clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments) + } + ) setStoredAgent(sessionID, agentUsed) if (model) { setStoredModel({ providerID: model.providerID, modelID: model.modelID }) } - setPrompt('') - setAttachedFiles(new Map()) - revokeBlobUrls(imageAttachments) - setImageAttachments([]) - setSelectedAgent(null) - clearSTT() return } + if (isPromptSubmitPending) return + if (isBashMode) { const command = prompt.startsWith('!') ? prompt.slice(1) : prompt addUserBashCommand(command) - sendShell.mutate({ - sessionID, - command, - agent: currentMode - }) + const submittedPrompt = prompt + sendShell.mutate( + { + sessionID, + command, + agent: currentMode + }, + { + onSuccess: () => { + if (promptRef.current !== submittedPrompt) return + setPrompt('') + setIsBashMode(false) + clearSTT() + } + } + ) setStoredAgent(sessionID, currentMode) - setPrompt('') - setIsBashMode(false) - clearSTT() return } @@ -287,14 +351,35 @@ export const PromptInput = memo(forwardRef( const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments) const agentUsed = selectedAgent || currentMode + const submittedPrompt = prompt + const submittedAttachedFiles = attachedFiles + const submittedImageAttachments = imageAttachments - sendPrompt.mutate({ - sessionID, - parts, - model: currentModel, - agent: agentUsed, - variant: currentVariant - }) + pendingConfirmClearRef.current = { + prompt: submittedPrompt, + files: submittedAttachedFiles, + images: submittedImageAttachments + } + + sendPrompt.mutate( + { + sessionID, + prompt: submittedPrompt, + parts, + model: currentModel, + agent: agentUsed, + variant: currentVariant + }, + { + onSuccess: () => { + pendingConfirmClearRef.current = null + clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments) + }, + onError: () => { + pendingConfirmClearRef.current = null + } + } + ) onScrollToBottom() @@ -302,12 +387,6 @@ export const PromptInput = memo(forwardRef( if (model) { setStoredModel({ providerID: model.providerID, modelID: model.modelID }) } - setPrompt('') - setAttachedFiles(new Map()) - revokeBlobUrls(imageAttachments) - setImageAttachments([]) - setSelectedAgent(null) - clearSTT() } handleSubmitRef.current = handleSubmit @@ -1163,7 +1242,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) return (
- {showStopButton && !(isFocused && prompt.trim().length > 0) && ( + {showStopButton && (