mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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:
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()
|
||||
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
|
||||
vi.mock('@/api/repos')
|
||||
|
||||
@@ -109,6 +110,42 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('does not show assistant as a repo option', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([
|
||||
{
|
||||
id: ASSISTANT_REPO_ID,
|
||||
repoUrl: 'Assistant',
|
||||
localPath: '/assistant',
|
||||
sourcePath: null,
|
||||
currentBranch: null,
|
||||
isLocal: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo1.git',
|
||||
localPath: '/path/to/repo1',
|
||||
sourcePath: null,
|
||||
currentBranch: 'main',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<RepoQuickSwitchSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
expect(screen.queryByText('Assistant')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('navigates on repo click and closes sheet', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@ import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
|
||||
import { FolderGit2, Check, Plus, House } from 'lucide-react'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
|
||||
|
||||
interface RepoQuickSwitchSheetProps {
|
||||
isOpen: boolean
|
||||
@@ -24,6 +25,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
const [addRepoOpen, setAddRepoOpen] = useState(false)
|
||||
|
||||
const activeRepoId = useMemo(() => {
|
||||
if (isAssistantPath(location.pathname)) return null
|
||||
const match = location.pathname.match(/^\/repos\/(\d+)/)
|
||||
return match ? Number(match[1]) : null
|
||||
}, [location.pathname])
|
||||
@@ -59,6 +61,11 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
}
|
||||
|
||||
const handleClick = (id: number) => {
|
||||
if (searchParams.get('mobileTabAction') === 'assistant') {
|
||||
navigateAndClose(getAssistantPath(), { replace: true })
|
||||
return
|
||||
}
|
||||
|
||||
if (id === activeRepoId) {
|
||||
onClose()
|
||||
return
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { paths, components } from "../api/opencode-types";
|
||||
import { parseNetworkError } from "../lib/opencode-errors";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { useSendErrorStore } from "../stores/sendErrorStore";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
import { invalidateSessionListCaches, messagesQueryKey } from "../lib/queryInvalidation";
|
||||
|
||||
type AssistantMessage = components["schemas"]["AssistantMessage"];
|
||||
@@ -366,6 +367,16 @@ const createOptimisticUserMessageInfo = (
|
||||
return { ...message, agent, variant } as Message;
|
||||
};
|
||||
|
||||
const getPromptText = (prompt: string | undefined, parts: ContentPart[] | undefined): string => {
|
||||
if (prompt !== undefined) return prompt;
|
||||
if (!parts) return "";
|
||||
return parts
|
||||
.filter((part): part is ContentPart & { type: "text" } => part.type === "text")
|
||||
.map((part) => part.content)
|
||||
.join("")
|
||||
.trim();
|
||||
};
|
||||
|
||||
export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: string) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -411,6 +422,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
queryKey,
|
||||
(old) => [...(old || []), optimisticMessageWithParts],
|
||||
);
|
||||
useSessionStatus.getState().setOptimisticActive(sessionID);
|
||||
|
||||
const requestData: SendPromptRequest = {
|
||||
parts: parts?.map((part) =>
|
||||
@@ -469,7 +481,15 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
}
|
||||
|
||||
if (queued) {
|
||||
await client.sendPromptAsync(sessionID, requestData);
|
||||
useSendErrorStore.getState().setQueuedPrompt(sessionID, getPromptText(prompt, parts));
|
||||
|
||||
try {
|
||||
await client.sendPromptAsync(sessionID, requestData);
|
||||
} catch (error) {
|
||||
useSendErrorStore.getState().clearQueuedPrompt(sessionID);
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { optimisticUserID, queued: true };
|
||||
}
|
||||
|
||||
@@ -478,9 +498,13 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
return { optimisticUserID, response, queued: false };
|
||||
},
|
||||
onError: (error, variables) => {
|
||||
const { sessionID } = variables;
|
||||
const { sessionID, queued } = variables;
|
||||
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
|
||||
|
||||
if (queued) {
|
||||
useSendErrorStore.getState().clearQueuedPrompt(sessionID);
|
||||
}
|
||||
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
queryKey,
|
||||
(old) => old?.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_")),
|
||||
@@ -493,6 +517,8 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
return;
|
||||
}
|
||||
|
||||
useSessionStatus.getState().clearStatus(sessionID);
|
||||
|
||||
const parsed = parseNetworkError(error);
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID,
|
||||
|
||||
@@ -5,7 +5,7 @@ export function useRepoActivity(repoId: number, isReady: boolean): void {
|
||||
const hasLoggedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isReady || hasLoggedRef.current || !repoId) {
|
||||
if (!isReady || hasLoggedRef.current || repoId == null) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -15,4 +15,4 @@ export function useRepoActivity(repoId: number, isReady: boolean): void {
|
||||
// Silent failure - activity tracking must not block navigation
|
||||
})
|
||||
}, [repoId, isReady])
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useSSE } from './useSSE'
|
||||
import { useSessionStatus } from '../stores/sessionStatusStore'
|
||||
import { useSendErrorStore } from '../stores/sendErrorStore'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
import { createTextPart } from '@/lib/partsBatcher'
|
||||
|
||||
@@ -71,12 +72,14 @@ describe('useSSE', () => {
|
||||
MockEventSource.instances = []
|
||||
mocks.getSessionStatuses.mockResolvedValue({})
|
||||
useSessionStatus.getState().replaceStatuses({})
|
||||
useSendErrorStore.setState({ errors: {}, queuedPrompts: {} })
|
||||
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
|
||||
globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useSessionStatus.getState().replaceStatuses({})
|
||||
useSendErrorStore.setState({ errors: {}, queuedPrompts: {} })
|
||||
globalThis.EventSource = originalEventSource
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
@@ -164,6 +167,20 @@ describe('useSSE', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('preserves optimistic active status when a poll snapshot omits the session', () => {
|
||||
useSessionStatus.getState().setOptimisticActive('session-1', 10_000)
|
||||
|
||||
useSessionStatus.getState().replaceStatuses({})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'busy' })
|
||||
|
||||
useSessionStatus.getState().replaceStatuses({
|
||||
'session-1': { type: 'idle' },
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
it('ignores stale status snapshots after the directory changes', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -277,6 +294,170 @@ describe('useSSE', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('clears optimistic active status when session status reports idle', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
queryClient.setQueryData(
|
||||
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'],
|
||||
[],
|
||||
)
|
||||
useSessionStatus.getState().setOptimisticActive('session-1')
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSSE('http://localhost:5551', '/repo', 'session-1'),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('connected', { clientId: 'client-1' })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
useSessionStatus.getState().setOptimisticActive('session-1')
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'session.status',
|
||||
properties: {
|
||||
sessionID: 'session-1',
|
||||
status: { type: 'idle' },
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('stores queued prompt text for restoration when the queued session errors', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
useSendErrorStore.getState().setQueuedPrompt('session-1', 'queued message')
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSSE('http://localhost:5551', '/repo', 'session-1'),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('connected', { clientId: 'client-1' })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'message.updated',
|
||||
properties: {
|
||||
info: {
|
||||
id: 'assistant-current',
|
||||
role: 'assistant',
|
||||
sessionID: 'session-1',
|
||||
time: { created: 1 },
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'session.error',
|
||||
properties: {
|
||||
sessionID: 'session-1',
|
||||
error: {
|
||||
name: 'UnknownError',
|
||||
data: { message: 'Queued send failed' },
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
expect(useSendErrorStore.getState().getError('session-1')).toEqual({
|
||||
sessionID: 'session-1',
|
||||
title: 'Error',
|
||||
message: 'Queued send failed',
|
||||
failedPrompt: 'queued message',
|
||||
})
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('does not create a send error banner once the queued prompt has been cleared', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
useSendErrorStore.getState().setQueuedPrompt('session-1', 'queued message')
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSSE('http://localhost:5551', '/repo', 'session-1'),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('connected', { clientId: 'client-1' })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'message.updated',
|
||||
properties: {
|
||||
info: {
|
||||
id: 'queued-user',
|
||||
role: 'user',
|
||||
sessionID: 'session-1',
|
||||
time: { created: 1 },
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'session.error',
|
||||
properties: {
|
||||
sessionID: 'session-1',
|
||||
error: {
|
||||
name: 'UnknownError',
|
||||
data: { message: 'Unrelated failure' },
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
expect(useSendErrorStore.getState().getError('session-1')).toBeNull()
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('routes streamed part deltas to the event directory in multi-directory subscriptions', async () => {
|
||||
const origRAF = window.requestAnimationFrame
|
||||
window.requestAnimationFrame = ((cb: FrameRequestCallback) => {
|
||||
@@ -450,4 +631,3 @@ function assistantMessage(sessionID: string, messageID: string): MessageWithPart
|
||||
parts: [],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,14 @@ import { showToast } from '@/lib/toast'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
import { useSendErrorStore } from '@/stores/sendErrorStore'
|
||||
import { openCodeEventStream } from '@/lib/opencode-event-stream'
|
||||
import type { EventStreamSubscription } from '@/lib/opencode-event-stream'
|
||||
import { parseOpenCodeError } from '@/lib/opencode-errors'
|
||||
import { createPartsBatcher } from '@/lib/partsBatcher'
|
||||
|
||||
const STATUS_POLL_INTERVAL_MS = 5000
|
||||
|
||||
const getEventDirectory = (event: SSEEvent): string | undefined => {
|
||||
const directory = (event as { directory?: unknown }).directory
|
||||
return typeof directory === 'string' ? directory : undefined
|
||||
@@ -153,7 +156,10 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
|
||||
|
||||
const { info } = event.properties
|
||||
const sessionID = info.sessionID
|
||||
|
||||
if (info.role === 'user') {
|
||||
useSendErrorStore.getState().clearQueuedPrompt(sessionID)
|
||||
}
|
||||
|
||||
const queryKey = messagesQueryKey(opcodeUrl, sessionID, cacheDirectory)
|
||||
const currentData = queryClient.getQueryData<MessageWithParts[]>(queryKey)
|
||||
if (!currentData) {
|
||||
@@ -309,12 +315,20 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
|
||||
|
||||
case 'session.error': {
|
||||
if (!('error' in event.properties)) break
|
||||
if ('sessionID' in event.properties && event.properties.sessionID === currentSessionId) break
|
||||
const sessionID = 'sessionID' in event.properties ? event.properties.sessionID : undefined
|
||||
const parsed = parseOpenCodeError(event.properties.error)
|
||||
if (sessionID && parsed) {
|
||||
useSendErrorStore.getState().failQueuedPrompt({
|
||||
sessionID,
|
||||
title: parsed.title,
|
||||
message: parsed.message,
|
||||
})
|
||||
}
|
||||
if (sessionID === currentSessionId) break
|
||||
|
||||
const error = event.properties.error
|
||||
if (error?.name === 'MessageAbortedError') break
|
||||
|
||||
const parsed = parseOpenCodeError(error)
|
||||
if (parsed) {
|
||||
showToast.error(parsed.title, {
|
||||
description: parsed.message,
|
||||
@@ -355,6 +369,16 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
|
||||
}
|
||||
}, [client, primaryDirectory, replaceSessionStatuses])
|
||||
|
||||
useEffect(() => {
|
||||
if (!client || !primaryDirectory) return
|
||||
|
||||
const interval = setInterval(() => {
|
||||
void fetchInitialData().catch(() => undefined)
|
||||
}, STATUS_POLL_INTERVAL_MS)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [client, primaryDirectory, fetchInitialData])
|
||||
|
||||
const syncCurrentSession = useCallback(() => {
|
||||
const sessionId = sessionIdRef.current
|
||||
if (!sessionId || !opcodeUrl || !primaryDirectory) return
|
||||
@@ -393,7 +417,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
|
||||
|
||||
if (connected) {
|
||||
setError(null)
|
||||
fetchInitialData()
|
||||
void fetchInitialData().catch(() => undefined)
|
||||
syncCurrentSession()
|
||||
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
|
||||
} else {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { createElement } from 'react'
|
||||
import { useSendPrompt } from './useOpenCode'
|
||||
@@ -7,6 +7,8 @@ import { FetchError } from '../api/fetchWrapper'
|
||||
|
||||
const mockSendPrompt = vi.fn()
|
||||
const mockSendPromptAsync = vi.fn()
|
||||
const mockSetOptimisticActive = vi.fn()
|
||||
const mockClearStatus = vi.fn()
|
||||
|
||||
vi.mock('../api/opencode', async () => {
|
||||
const actual = await vi.importActual('../api/opencode')
|
||||
@@ -20,7 +22,12 @@ vi.mock('../api/opencode', async () => {
|
||||
})
|
||||
|
||||
vi.mock('@/stores/sessionStatusStore', () => ({
|
||||
useSessionStatus: vi.fn(() => vi.fn()),
|
||||
useSessionStatus: Object.assign(vi.fn(() => vi.fn()), {
|
||||
getState: () => ({
|
||||
setOptimisticActive: mockSetOptimisticActive,
|
||||
clearStatus: mockClearStatus,
|
||||
}),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('../lib/toast', () => ({
|
||||
@@ -37,12 +44,18 @@ vi.mock('../lib/opencode-errors', () => ({
|
||||
|
||||
const mockClearError = vi.fn()
|
||||
const mockSetError = vi.fn()
|
||||
const mockSetQueuedPrompt = vi.fn()
|
||||
const mockClearQueuedPrompt = vi.fn()
|
||||
const mockFailQueuedPrompt = vi.fn()
|
||||
|
||||
vi.mock('../stores/sendErrorStore', () => ({
|
||||
useSendErrorStore: {
|
||||
getState: () => ({
|
||||
clearError: mockClearError,
|
||||
setError: mockSetError,
|
||||
setQueuedPrompt: mockSetQueuedPrompt,
|
||||
clearQueuedPrompt: mockClearQueuedPrompt,
|
||||
failQueuedPrompt: mockFailQueuedPrompt,
|
||||
getError: vi.fn(),
|
||||
}),
|
||||
},
|
||||
@@ -178,6 +191,63 @@ describe('useSendPrompt', () => {
|
||||
).resolves.toEqual(expect.objectContaining({ queued: true }))
|
||||
|
||||
expect(mockClearError).toHaveBeenCalledWith('session-1')
|
||||
expect(mockSetQueuedPrompt).toHaveBeenCalledWith('session-1', 'Hello')
|
||||
})
|
||||
|
||||
it('stores the raw prompt for queued restoration when parts omit file mentions', async () => {
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await expect(
|
||||
result.current.mutateAsync({
|
||||
sessionID: 'session-raw',
|
||||
prompt: 'please inspect @App.tsx',
|
||||
parts: [
|
||||
{ type: 'text', content: 'please inspect ' },
|
||||
{ type: 'file', path: '/repo/src/App.tsx', name: 'App.tsx' },
|
||||
],
|
||||
queued: true,
|
||||
})
|
||||
).resolves.toEqual(expect.objectContaining({ queued: true }))
|
||||
|
||||
expect(mockSetQueuedPrompt).toHaveBeenCalledWith('session-raw', 'please inspect @App.tsx')
|
||||
})
|
||||
|
||||
it('stores queued prompt before the async queue request resolves', async () => {
|
||||
let resolveQueued: () => void = () => {}
|
||||
mockSendPromptAsync.mockImplementationOnce(() => new Promise<void>((resolve) => {
|
||||
resolveQueued = resolve
|
||||
}))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
const queued = result.current.mutateAsync({
|
||||
sessionID: 'session-pending',
|
||||
prompt: 'pending queued prompt',
|
||||
queued: true,
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSetQueuedPrompt).toHaveBeenCalledWith('session-pending', 'pending queued prompt')
|
||||
})
|
||||
|
||||
resolveQueued()
|
||||
await expect(queued).resolves.toEqual(expect.objectContaining({ queued: true }))
|
||||
})
|
||||
|
||||
it('clears queued prompt when the async queue request fails', async () => {
|
||||
mockSendPromptAsync.mockRejectedValueOnce(new Error('Queue failed'))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await expect(
|
||||
result.current.mutateAsync({
|
||||
sessionID: 'session-failed',
|
||||
prompt: 'failed queued prompt',
|
||||
queued: true,
|
||||
})
|
||||
).rejects.toThrow('Queue failed')
|
||||
|
||||
expect(mockClearQueuedPrompt).toHaveBeenCalledWith('session-failed')
|
||||
})
|
||||
|
||||
it('clears stored send error on successful non-queued response', async () => {
|
||||
|
||||
@@ -511,7 +511,7 @@ export function SessionDetail() {
|
||||
content={latestPlayableAssistant.text}
|
||||
/>
|
||||
)}
|
||||
{hasPromptContent && (
|
||||
{hasPromptContent && !isSessionActive && (
|
||||
<button
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onTouchEnd={(e) => {
|
||||
|
||||
@@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({
|
||||
useAutoScroll: vi.fn(),
|
||||
useDialogParam: vi.fn(),
|
||||
useSidebarAction: vi.fn(),
|
||||
useSessionStatusForSession: vi.fn(),
|
||||
PromptInput: vi.fn(),
|
||||
}))
|
||||
|
||||
@@ -110,7 +111,7 @@ vi.mock('@/stores/uiStateStore', () => ({
|
||||
|
||||
vi.mock('@/stores/sessionStatusStore', () => ({
|
||||
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
|
||||
useSessionStatusForSession: vi.fn(() => ({ type: 'idle' })),
|
||||
useSessionStatusForSession: mocks.useSessionStatusForSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSSE', () => ({
|
||||
@@ -226,6 +227,7 @@ describe('SessionDetail scroll floating button', () => {
|
||||
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
|
||||
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
|
||||
mocks.useSidebarAction.mockReturnValue(undefined)
|
||||
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
|
||||
mocks.PromptInput.mockImplementation(() => <div>MockedPromptInput</div>)
|
||||
})
|
||||
|
||||
@@ -239,6 +241,7 @@ describe('SessionDetail scroll floating button', () => {
|
||||
sessionActive?: boolean
|
||||
}) => {
|
||||
mocks.useMobile.mockReturnValue(opts.mobile)
|
||||
mocks.useSessionStatusForSession.mockReturnValue({ type: opts.sessionActive ? 'busy' : 'idle' })
|
||||
mocks.useAutoScroll.mockImplementation(
|
||||
({ onScrollStateChange }: { onScrollStateChange?: (v: boolean) => void }) => {
|
||||
if (opts.showScrollButton) {
|
||||
@@ -316,6 +319,19 @@ describe('SessionDetail scroll floating button', () => {
|
||||
expect(screen.queryByLabelText('Scroll to bottom')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows clear button for prompt content only when session is idle', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: false, promptContent: true })
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText('Clear')).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('does not show clear button for prompt content while session is active', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: false, promptContent: true, sessionActive: true })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
|
||||
expect(screen.queryByLabelText('Clear')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clicking PromptInput scroll button calls scrollToBottom from useAutoScroll', async () => {
|
||||
renderWith({ mobile: true, showScrollButton: true })
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useSendErrorStore } from './sendErrorStore'
|
||||
|
||||
describe('useSendErrorStore', () => {
|
||||
beforeEach(() => {
|
||||
useSendErrorStore.setState({ errors: {} })
|
||||
useSendErrorStore.setState({ errors: {}, queuedPrompts: {} })
|
||||
})
|
||||
|
||||
it('stores error keyed by sessionID', () => {
|
||||
@@ -23,4 +23,32 @@ describe('useSendErrorStore', () => {
|
||||
it('returns null when no error exists for sessionID', () => {
|
||||
expect(useSendErrorStore.getState().getError('nonexistent')).toBeNull()
|
||||
})
|
||||
|
||||
it('moves queued prompt text into failed error and clears the queued draft', () => {
|
||||
useSendErrorStore.getState().setQueuedPrompt('session-1', 'queued message')
|
||||
|
||||
useSendErrorStore.getState().failQueuedPrompt({
|
||||
sessionID: 'session-1',
|
||||
title: 'Error',
|
||||
message: 'Failed',
|
||||
})
|
||||
|
||||
expect(useSendErrorStore.getState().getError('session-1')).toEqual({
|
||||
sessionID: 'session-1',
|
||||
title: 'Error',
|
||||
message: 'Failed',
|
||||
failedPrompt: 'queued message',
|
||||
})
|
||||
expect(useSendErrorStore.getState().queuedPrompts['session-1']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not store an error when no queued prompt was tracked', () => {
|
||||
useSendErrorStore.getState().failQueuedPrompt({
|
||||
sessionID: 'session-1',
|
||||
title: 'Error',
|
||||
message: 'Failed',
|
||||
})
|
||||
|
||||
expect(useSendErrorStore.getState().getError('session-1')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -5,22 +5,55 @@ export interface SendError {
|
||||
title: string
|
||||
message: string
|
||||
detail?: string
|
||||
failedPrompt?: string
|
||||
}
|
||||
|
||||
interface SendErrorStore {
|
||||
errors: Record<string, SendError>
|
||||
queuedPrompts: Record<string, string>
|
||||
setError: (err: SendError) => void
|
||||
setQueuedPrompt: (sessionID: string, prompt: string) => void
|
||||
clearQueuedPrompt: (sessionID: string) => void
|
||||
failQueuedPrompt: (err: Omit<SendError, 'failedPrompt'>) => void
|
||||
clearError: (sessionID: string) => void
|
||||
getError: (sessionID: string) => SendError | null
|
||||
}
|
||||
|
||||
export const useSendErrorStore = create<SendErrorStore>((set, get) => ({
|
||||
errors: {},
|
||||
queuedPrompts: {},
|
||||
setError: (err: SendError) => {
|
||||
set((state) => ({
|
||||
errors: { ...state.errors, [err.sessionID]: err },
|
||||
}))
|
||||
},
|
||||
setQueuedPrompt: (sessionID: string, prompt: string) => {
|
||||
set((state) => ({
|
||||
queuedPrompts: { ...state.queuedPrompts, [sessionID]: prompt },
|
||||
}))
|
||||
},
|
||||
clearQueuedPrompt: (sessionID: string) => {
|
||||
set((state) => {
|
||||
const queuedPrompts = { ...state.queuedPrompts }
|
||||
delete queuedPrompts[sessionID]
|
||||
return { queuedPrompts }
|
||||
})
|
||||
},
|
||||
failQueuedPrompt: (err: Omit<SendError, 'failedPrompt'>) => {
|
||||
set((state) => {
|
||||
const failedPrompt = state.queuedPrompts[err.sessionID]
|
||||
if (!failedPrompt) return state
|
||||
const queuedPrompts = { ...state.queuedPrompts }
|
||||
delete queuedPrompts[err.sessionID]
|
||||
return {
|
||||
errors: {
|
||||
...state.errors,
|
||||
[err.sessionID]: { ...err, failedPrompt },
|
||||
},
|
||||
queuedPrompts,
|
||||
}
|
||||
})
|
||||
},
|
||||
clearError: (sessionID: string) => {
|
||||
set((state) => {
|
||||
const newErrors = { ...state.errors }
|
||||
|
||||
@@ -10,12 +10,22 @@ interface SessionStatusStore {
|
||||
statuses: Map<string, SessionStatusType>
|
||||
statusCache: Map<string, string>
|
||||
setStatus: (sessionID: string, status: SessionStatusType) => void
|
||||
setOptimisticActive: (sessionID: string, timeoutMs?: number) => void
|
||||
replaceStatuses: (statuses: Record<string, SessionStatusType>) => void
|
||||
getStatus: (sessionID: string) => SessionStatusType
|
||||
clearStatus: (sessionID: string) => void
|
||||
}
|
||||
|
||||
const DEFAULT_STATUS: SessionStatusType = { type: 'idle' }
|
||||
const OPTIMISTIC_ACTIVE_TIMEOUT_MS = 120_000
|
||||
const optimisticActiveTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
|
||||
const clearOptimisticActiveTimer = (sessionID: string): void => {
|
||||
const timer = optimisticActiveTimers.get(sessionID)
|
||||
if (!timer) return
|
||||
clearTimeout(timer)
|
||||
optimisticActiveTimers.delete(sessionID)
|
||||
}
|
||||
|
||||
const getStatusHash = (status: SessionStatusType): string => {
|
||||
if (status.type === 'retry') {
|
||||
@@ -29,6 +39,7 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => ({
|
||||
statusCache: new Map(),
|
||||
|
||||
setStatus: (sessionID: string, status: SessionStatusType) => {
|
||||
clearOptimisticActiveTimer(sessionID)
|
||||
const hash = getStatusHash(status)
|
||||
const previousHash = get().statusCache.get(sessionID)
|
||||
|
||||
@@ -56,9 +67,40 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => ({
|
||||
})
|
||||
},
|
||||
|
||||
setOptimisticActive: (sessionID: string, timeoutMs = OPTIMISTIC_ACTIVE_TIMEOUT_MS) => {
|
||||
clearOptimisticActiveTimer(sessionID)
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
optimisticActiveTimers.delete(sessionID)
|
||||
const currentStatus = get().getStatus(sessionID)
|
||||
if (currentStatus.type === 'busy') {
|
||||
get().clearStatus(sessionID)
|
||||
}
|
||||
}, timeoutMs)
|
||||
|
||||
optimisticActiveTimers.set(sessionID, timer)
|
||||
|
||||
const hash = getStatusHash({ type: 'busy' })
|
||||
const previousHash = get().statusCache.get(sessionID)
|
||||
if (previousHash === hash) return
|
||||
|
||||
set((state) => {
|
||||
const newMap = new Map(state.statuses)
|
||||
const newCache = new Map(state.statusCache)
|
||||
newMap.set(sessionID, { type: 'busy' })
|
||||
newCache.set(sessionID, hash)
|
||||
return { statuses: newMap, statusCache: newCache }
|
||||
})
|
||||
},
|
||||
|
||||
replaceStatuses: (statuses: Record<string, SessionStatusType>) => {
|
||||
for (const sessionID of Object.keys(statuses)) {
|
||||
clearOptimisticActiveTimer(sessionID)
|
||||
}
|
||||
|
||||
const newMap = new Map<string, SessionStatusType>()
|
||||
const newCache = new Map<string, string>()
|
||||
const currentStatuses = get().statuses
|
||||
|
||||
for (const [sessionID, status] of Object.entries(statuses)) {
|
||||
if (status.type === 'idle') continue
|
||||
@@ -66,6 +108,12 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => ({
|
||||
newCache.set(sessionID, getStatusHash(status))
|
||||
}
|
||||
|
||||
for (const [sessionID, status] of currentStatuses.entries()) {
|
||||
if (!optimisticActiveTimers.has(sessionID) || sessionID in statuses) continue
|
||||
newMap.set(sessionID, status)
|
||||
newCache.set(sessionID, getStatusHash(status))
|
||||
}
|
||||
|
||||
const currentCache = get().statusCache
|
||||
if (currentCache.size === newCache.size) {
|
||||
let unchanged = true
|
||||
@@ -86,6 +134,7 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => ({
|
||||
},
|
||||
|
||||
clearStatus: (sessionID: string) => {
|
||||
clearOptimisticActiveTimer(sessionID)
|
||||
const previousHash = get().statusCache.get(sessionID)
|
||||
if (!previousHash) return
|
||||
|
||||
|
||||
Reference in new issue
Block a user