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
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-10 08:35:19 -04:00
1 parent 931f1215e6
commit 4e32fd5b00
16 files changed
+833 -61

No files matched your search

@@ -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({
<Pencil className={`w-4 h-4 flex-shrink-0 mt-0.5 text-muted-foreground transition-all ${isMobile ? 'opacity-100' : 'opacity-50 group-hover/edit:opacity-100 group-hover/edit:text-primary'}`} />
</button>
)
})
})
@@ -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(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
)
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(
<MessageThread
opcodeUrl="http://localhost:5551"
sessionID="test-session"
messages={messages as any}
/>
)
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),
)
})
})
@@ -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(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} />
</QueryClientProvider>,
)
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(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} isStreamingResponse />
</QueryClientProvider>,
)
await waitFor(() => {
expect(input).toHaveValue('')
})
})
it('allows queuing a follow-up while a non-queued send is pending', async () => {
mocks.sendPromptPending.mockReturnValue(true)
render(
<QueryClientProvider client={createTestQueryClient()}>
<PromptInput {...defaultProps} isStreamingResponse />
</QueryClientProvider>,
)
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(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} isStreamingResponse />
</QueryClientProvider>,
)
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(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByPlaceholderText('Send a message...')).toHaveValue('queued message')
})
})
it('keeps stop available while active with prompt content', async () => {
render(
<QueryClientProvider client={createTestQueryClient()}>
<PromptInput {...defaultProps} isSessionActive />
</QueryClientProvider>
)
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()
+118 -41
View File
@@ -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<PromptInputHandle, PromptInputProps>(
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const [selectedAgent, setSelectedAgent] = useState<string | null>(null)
const [localMode, setLocalMode] = useState<string | null>(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<PromptInputHandle, PromptInputProps>(
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<PromptInputHandle, PromptInputProps>(
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
}, [])
useEffect(() => {
promptRef.current = prompt
attachedFilesRef.current = attachedFiles
imageAttachmentsRef.current = imageAttachments
}, [attachedFiles, imageAttachments, prompt])
const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map<string, FileAttachmentInfo>, 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<string, FileAttachmentInfo>
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<PromptInputHandle, PromptInputProps>(
}), [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<PromptInputHandle, PromptInputProps>(
)
const { data: agents = [] } = useAgents(opcodeUrl, directory)
const failedPrompt = useSendErrorStore((state) => state.errors[sessionID]?.failedPrompt)
const restoredFailedPromptRef = useRef<string | null>(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<PromptInputHandle, PromptInputProps>(
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<PromptInputHandle, PromptInputProps>(
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<PromptInputHandle, PromptInputProps>(
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 (
<div className={`relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-white/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full transition-all ${hasPendingPermissionForSession ? 'border-orange-500/50 ring-1 ring-orange-500/30' : ''}`}>
{showStopButton && !(isFocused && prompt.trim().length > 0) && (
{showStopButton && (
<button
onClick={handleStop}
disabled={disabled}
@@ -1189,8 +1268,6 @@ return (
: "Send a message..."
}
disabled={disabled}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
className={`w-full bg-muted/50 pl-2 md:pl-3 pr-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg [field-sizing:content] ${
isBashMode
? 'border-purple-500/50 bg-purple-500/5 focus:bg-purple-500/10'
@@ -1317,7 +1394,7 @@ return (
<button
data-submit-prompt
onClick={hasPendingPermissionForSession ? () => setShowDialog(true) : handleSubmit}
disabled={hasPendingPermissionForSession ? false : ((!prompt.trim() && imageAttachments.length === 0) || disabled)}
disabled={hasPendingPermissionForSession ? false : ((!prompt.trim() && imageAttachments.length === 0) || disabled || (isPromptSubmitPending && !isStreamingResponse))}
className={`px-4 md:px-5 py-1.5 md:py-2 rounded-lg text-sm font-medium transition-colors dark:border flex-shrink-0 min-w-[52px] ${
hasPendingPermissionForSession
? 'bg-orange-500 hover:bg-orange-600 border-orange-400 text-primary-foreground ring-orange-500/20'