mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)
This commit is contained in:
1 parent
3cc24288a6
commit
c3d6549f01
133 files changed
+7284
-6293
No files matched your search
@@ -0,0 +1,119 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { useCommandHandler } from '../useCommandHandler'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
sendCommand: vi.fn(),
|
||||
summarizeSession: vi.fn(),
|
||||
setStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
createOpenCodeClient: vi.fn().mockImplementation(() => ({
|
||||
sendCommand: mocks.sendCommand,
|
||||
summarizeSession: mocks.summarizeSession,
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
info: vi.fn(),
|
||||
loading: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useCreateSession: vi.fn(() => ({
|
||||
mutateAsync: vi.fn(),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useModelSelection: vi.fn(() => ({
|
||||
model: { providerID: 'test-provider', modelID: 'test-model' },
|
||||
modelString: 'test-provider/test-model',
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('react-router-dom', () => ({
|
||||
useNavigate: vi.fn(() => vi.fn()),
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/sessionStatusStore', () => ({
|
||||
useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })),
|
||||
}))
|
||||
|
||||
describe('useCommandHandler', () => {
|
||||
const baseProps = {
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
sessionID: 'test-session-id',
|
||||
directory: '/test/dir',
|
||||
currentAgent: 'test-agent',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('themes command sends command', async () => {
|
||||
mocks.sendCommand.mockResolvedValue({ info: { id: 'asm_1' }, parts: [] })
|
||||
|
||||
const { result } = renderHook(() => useCommandHandler(baseProps))
|
||||
const themesCommand = { name: 'themes' as const }
|
||||
|
||||
await result.current.executeCommand(themesCommand, '')
|
||||
|
||||
expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', {
|
||||
command: 'themes',
|
||||
arguments: '',
|
||||
agent: 'test-agent',
|
||||
model: 'test-provider/test-model',
|
||||
})
|
||||
})
|
||||
|
||||
it('compact command summarizes session', async () => {
|
||||
mocks.summarizeSession.mockResolvedValue(undefined)
|
||||
|
||||
const { result } = renderHook(() => useCommandHandler(baseProps))
|
||||
const compactCommand = { name: 'compact' as const }
|
||||
|
||||
await result.current.executeCommand(compactCommand, '')
|
||||
|
||||
expect(mocks.summarizeSession).toHaveBeenCalledWith(
|
||||
'test-session-id',
|
||||
'test-provider',
|
||||
'test-model'
|
||||
)
|
||||
})
|
||||
|
||||
it('unknown command sends command', async () => {
|
||||
mocks.sendCommand.mockResolvedValue({ info: { id: 'asm_1' }, parts: [] })
|
||||
|
||||
const { result } = renderHook(() => useCommandHandler(baseProps))
|
||||
const unknownCommand = { name: 'myskill' as const }
|
||||
|
||||
await result.current.executeCommand(unknownCommand, '')
|
||||
|
||||
expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', {
|
||||
command: 'myskill',
|
||||
arguments: '',
|
||||
agent: 'test-agent',
|
||||
model: 'test-provider/test-model',
|
||||
})
|
||||
})
|
||||
|
||||
it('sessions command opens sessions dialog without sending command', async () => {
|
||||
const onShowSessionsDialog = vi.fn()
|
||||
const { result } = renderHook(() =>
|
||||
useCommandHandler({ ...baseProps, onShowSessionsDialog })
|
||||
)
|
||||
const sessionsCommand = { name: 'sessions' as const }
|
||||
|
||||
await result.current.executeCommand(sessionsCommand, '')
|
||||
|
||||
expect(mocks.sendCommand).not.toHaveBeenCalled()
|
||||
expect(onShowSessionsDialog).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,250 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useLoadSkill } from '../useOpenCode'
|
||||
import type { MessageWithParts } from '../../api/types'
|
||||
|
||||
import { showToast } from '../../lib/toast'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
sendCommand: vi.fn(),
|
||||
setStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../api/opencode', () => ({
|
||||
OpenCodeClient: vi.fn().mockImplementation(() => ({
|
||||
sendCommand: mocks.sendCommand,
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../lib/toast', () => ({
|
||||
showToast: {
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../stores/sessionStatusStore', () => ({
|
||||
useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })),
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) =>
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
}
|
||||
|
||||
describe('useLoadSkill', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('calls sendCommand with correct parameters when mutate is called', async () => {
|
||||
const mockResponse = {
|
||||
info: { id: 'asm_1', sessionID: 'test-session-id', role: 'assistant' },
|
||||
parts: []
|
||||
}
|
||||
mocks.sendCommand.mockResolvedValue(mockResponse)
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true)
|
||||
})
|
||||
|
||||
expect(mocks.sendCommand).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', {
|
||||
command: 'my-skill',
|
||||
arguments: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('throws error when sessionID is undefined', async () => {
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', undefined, '/test/dir'),
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
expect(result.current.error).toBeInstanceOf(Error)
|
||||
expect((result.current.error as Error).message).toBe('No active session')
|
||||
})
|
||||
|
||||
it('throws error when client is not available', async () => {
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill(null, 'test-session-id', '/test/dir'),
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
expect(result.current.error).toBeInstanceOf(Error)
|
||||
expect((result.current.error as Error).message).toBe('No OpenCode client available')
|
||||
})
|
||||
|
||||
it('calls showToast.error when sendCommand fails', async () => {
|
||||
const testError = new Error('Command failed')
|
||||
mocks.sendCommand.mockRejectedValue(testError)
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
expect(showToast.error).toHaveBeenCalledTimes(1)
|
||||
expect(showToast.error).toHaveBeenCalledWith('Command failed')
|
||||
})
|
||||
|
||||
it('calls showToast.error with default message for non-Error objects', async () => {
|
||||
mocks.sendCommand.mockRejectedValue('string error')
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
expect(showToast.error).toHaveBeenCalledTimes(1)
|
||||
expect(showToast.error).toHaveBeenCalledWith('Failed to load skill')
|
||||
})
|
||||
|
||||
it('adds optimistic user message with skill name on mutate', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
const messagesKey = ['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir']
|
||||
queryClient.setQueryData(messagesKey, [])
|
||||
|
||||
mocks.sendCommand.mockReturnValue(new Promise(() => {}))
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
|
||||
{ wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> },
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
const messages = queryClient.getQueryData<MessageWithParts[]>(messagesKey)
|
||||
expect(messages).toHaveLength(1)
|
||||
expect(messages?.[0].info.id).toMatch(/^optimistic_user_/)
|
||||
expect((messages?.[0].parts[0] as { text?: string }).text).toBe('Loading skill: my-skill')
|
||||
})
|
||||
})
|
||||
|
||||
it('sets session status to busy on mutate and idle on error', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
const testError = new Error('Command failed')
|
||||
mocks.sendCommand.mockRejectedValue(testError)
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
|
||||
{ wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> },
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'busy' })
|
||||
expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'idle' })
|
||||
})
|
||||
|
||||
it('removes optimistic message from cache on error', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
const messagesKey = ['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir']
|
||||
queryClient.setQueryData(messagesKey, [])
|
||||
|
||||
const testError = new Error('Command failed')
|
||||
mocks.sendCommand.mockRejectedValue(testError)
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
|
||||
{ wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> },
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
const messages = queryClient.getQueryData<MessageWithParts[]>(messagesKey)
|
||||
expect(messages).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('replaces optimistic message with assistant response on success', async () => {
|
||||
const assistant = {
|
||||
info: { id: 'asm_skill_1', sessionID: 'test-session-id', role: 'assistant' },
|
||||
parts: [{ type: 'text', text: 'done' }]
|
||||
}
|
||||
mocks.sendCommand.mockResolvedValue(assistant)
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) =>
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
const { result } = renderHook(
|
||||
() => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'),
|
||||
{ wrapper }
|
||||
)
|
||||
|
||||
result.current.mutate({ skillName: 'my-skill' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true)
|
||||
})
|
||||
|
||||
const messages = queryClient.getQueryData<MessageWithParts[]>(['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir'])
|
||||
expect(messages?.some(m => m.info.id === 'asm_skill_1')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useMessages } from '../useOpenCode'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listMessages: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
OpenCodeClient: vi.fn(() => ({
|
||||
listMessages: mocks.listMessages,
|
||||
})),
|
||||
}))
|
||||
|
||||
describe('useMessages fallback poll', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const createQueryClient = () => new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
it('should poll every 5s when fallbackPoll is enabled', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
mocks.listMessages.mockResolvedValue([])
|
||||
|
||||
renderHook(
|
||||
() => useMessages('http://localhost:5003', 'session-1', '/repo', { fallbackPoll: true }),
|
||||
{ wrapper }
|
||||
)
|
||||
|
||||
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listMessages).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should not poll when fallbackPoll is disabled', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
mocks.listMessages.mockResolvedValue([])
|
||||
|
||||
renderHook(
|
||||
() => useMessages('http://localhost:5003', 'session-1', '/repo', { fallbackPoll: false }),
|
||||
{ wrapper }
|
||||
)
|
||||
|
||||
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(15000)
|
||||
|
||||
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should not poll by default (no opts)', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
mocks.listMessages.mockResolvedValue([])
|
||||
|
||||
renderHook(
|
||||
() => useMessages('http://localhost:5003', 'session-1', '/repo'),
|
||||
{ wrapper }
|
||||
)
|
||||
|
||||
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(15000)
|
||||
|
||||
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,301 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { useAutoScroll } from './useAutoScroll'
|
||||
import type { Message } from '../api/types'
|
||||
|
||||
function createScrollContainer() {
|
||||
const div = document.createElement('div')
|
||||
document.body.appendChild(div)
|
||||
|
||||
let scrollTopValue = 0
|
||||
const clientHeight = 400
|
||||
let scrollHeightValue = 800
|
||||
|
||||
Object.defineProperty(div, 'clientHeight', {
|
||||
configurable: true,
|
||||
get: () => clientHeight,
|
||||
})
|
||||
|
||||
Object.defineProperty(div, 'scrollHeight', {
|
||||
configurable: true,
|
||||
get: () => scrollHeightValue,
|
||||
})
|
||||
|
||||
Object.defineProperty(div, 'scrollTop', {
|
||||
configurable: true,
|
||||
get: () => scrollTopValue,
|
||||
set: (value: number) => {
|
||||
scrollTopValue = Math.max(0, Math.min(value, scrollHeightValue - clientHeight))
|
||||
div.dispatchEvent(new Event('scroll'))
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
div,
|
||||
setScrollHeight: (value: number) => {
|
||||
scrollHeightValue = value
|
||||
},
|
||||
getScrollTop: () => scrollTopValue,
|
||||
setScrollTop: (value: number) => {
|
||||
scrollTopValue = value
|
||||
},
|
||||
cleanup: () => {
|
||||
document.body.removeChild(div)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('useAutoScroll', () => {
|
||||
let containerHarness: ReturnType<typeof createScrollContainer> | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (containerHarness) {
|
||||
containerHarness.cleanup()
|
||||
containerHarness = null
|
||||
}
|
||||
vi.restoreAllMocks()
|
||||
vi.clearAllTimers()
|
||||
})
|
||||
|
||||
const createMessage = (id: string, role: 'user' | 'assistant'): Message => ({
|
||||
id,
|
||||
sessionID: 'session-1',
|
||||
role,
|
||||
time: { created: Date.now() },
|
||||
} as Message)
|
||||
|
||||
const setupHook = (messages: Message[], sessionId = 'session-1') => {
|
||||
containerHarness = createScrollContainer()
|
||||
const containerRef = { current: containerHarness.div }
|
||||
const onScrollStateChange = vi.fn()
|
||||
|
||||
const renderResult = renderHook(
|
||||
(props) =>
|
||||
useAutoScroll({
|
||||
containerRef: props.containerRef,
|
||||
messages: props.messages,
|
||||
sessionId: props.sessionId,
|
||||
contentVersion: props.contentVersion,
|
||||
onScrollStateChange: props.onScrollStateChange,
|
||||
}),
|
||||
{
|
||||
initialProps: {
|
||||
containerRef,
|
||||
messages,
|
||||
sessionId,
|
||||
contentVersion: messages.length,
|
||||
onScrollStateChange,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
return { renderResult, containerHarness, onScrollStateChange }
|
||||
}
|
||||
|
||||
it('scrolls to bottom on initial messages', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { containerHarness } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(100)
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('auto-follows when new assistant message arrives', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(100)
|
||||
})
|
||||
|
||||
const initialScrollTop = containerHarness.getScrollTop()
|
||||
expect(initialScrollTop).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
|
||||
containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 200)
|
||||
const newMessages = [...messages, createMessage('2', 'assistant')]
|
||||
|
||||
act(() => {
|
||||
renderResult.rerender({
|
||||
containerRef: { current: containerHarness.div },
|
||||
messages: newMessages,
|
||||
sessionId: 'session-1',
|
||||
contentVersion: newMessages.length,
|
||||
onScrollStateChange,
|
||||
})
|
||||
vi.advanceTimersByTime(100)
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('stays engaged after scrollToBottom() through streaming reflow drift', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollToBottom()
|
||||
})
|
||||
|
||||
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
|
||||
containerHarness.setScrollTop(bottomPosition - 2)
|
||||
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(new Event('scroll'))
|
||||
})
|
||||
|
||||
containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 100)
|
||||
|
||||
act(() => {
|
||||
renderResult.rerender({
|
||||
containerRef: { current: containerHarness.div },
|
||||
messages,
|
||||
sessionId: 'session-1',
|
||||
contentVersion: messages.length + 1,
|
||||
onScrollStateChange,
|
||||
})
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('disengages when user fires a wheel-up event', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(true)
|
||||
|
||||
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
|
||||
containerHarness.setScrollHeight(bottomPosition + 200)
|
||||
|
||||
const currentScrollTop = containerHarness.getScrollTop()
|
||||
expect(currentScrollTop).not.toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('disengages when user drags upward (pointer down -> move up -> up)', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointerdown', {
|
||||
clientY: 200,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointermove', {
|
||||
clientY: 260,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(true)
|
||||
|
||||
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
|
||||
containerHarness.setScrollHeight(bottomPosition + 200)
|
||||
|
||||
const currentScrollTop = containerHarness.getScrollTop()
|
||||
expect(currentScrollTop).not.toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('re-engages when user scrolls back to within threshold', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(true)
|
||||
|
||||
const scrollHeight = containerHarness.div.scrollHeight
|
||||
const clientHeight = containerHarness.div.clientHeight
|
||||
const withinThresholdPosition = scrollHeight - clientHeight - 30
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(withinThresholdPosition)
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(false)
|
||||
})
|
||||
|
||||
it('always scrolls to bottom when user sends a message', () => {
|
||||
const messages = [createMessage('1', 'assistant')]
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(true)
|
||||
|
||||
const newMessages = [...messages, createMessage('2', 'user')]
|
||||
|
||||
act(() => {
|
||||
renderResult.rerender({
|
||||
containerRef: { current: containerHarness.div },
|
||||
messages: newMessages,
|
||||
sessionId: 'session-1',
|
||||
contentVersion: newMessages.length,
|
||||
onScrollStateChange,
|
||||
})
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('resets state when sessionId changes', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { renderResult, containerHarness } = setupHook(messages, 'session-1')
|
||||
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
const newMessages = [createMessage('2', 'user')]
|
||||
|
||||
act(() => {
|
||||
renderResult.rerender({
|
||||
containerRef: { current: containerHarness.div },
|
||||
messages: newMessages,
|
||||
sessionId: 'session-2',
|
||||
contentVersion: newMessages.length,
|
||||
onScrollStateChange: vi.fn(),
|
||||
})
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { useRef, useEffect, useCallback } from 'react'
|
||||
import type { Message } from '@/api/types'
|
||||
|
||||
const SCROLL_LOCK_MS = 300
|
||||
const BOTTOM_THRESHOLD_PX = 48
|
||||
|
||||
interface UseAutoScrollOptions {
|
||||
containerRef?: React.RefObject<HTMLDivElement | null>
|
||||
@@ -52,6 +53,9 @@ export function useAutoScroll({
|
||||
|
||||
const markDisengaged = () => {
|
||||
userScrolledAtRef.current = Date.now()
|
||||
if (!userDisengagedRef.current) {
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
userDisengagedRef.current = true
|
||||
}
|
||||
|
||||
@@ -84,20 +88,18 @@ export function useAutoScroll({
|
||||
|
||||
const handleScroll = () => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = container
|
||||
const isAtBottom = scrollHeight - scrollTop - clientHeight < 150
|
||||
|
||||
const isAtBottom = scrollHeight - scrollTop - clientHeight < BOTTOM_THRESHOLD_PX
|
||||
|
||||
if (isAtBottom) {
|
||||
if (userDisengagedRef.current) {
|
||||
userScrolledAtRef.current = 0
|
||||
userDisengagedRef.current = false
|
||||
onScrollStateChangeRef.current?.(false)
|
||||
}
|
||||
} else {
|
||||
if (!userDisengagedRef.current) {
|
||||
userScrolledAtRef.current = Date.now()
|
||||
userDisengagedRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
} else if (!userDisengagedRef.current) {
|
||||
userScrolledAtRef.current = Date.now()
|
||||
userDisengagedRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ export function useCommandHandler({
|
||||
onShowModelsDialog?.()
|
||||
break
|
||||
|
||||
case 'themes':
|
||||
case 'themes': {
|
||||
await client.sendCommand(sessionID, {
|
||||
command: command.name,
|
||||
arguments: args,
|
||||
@@ -65,6 +65,7 @@ export function useCommandHandler({
|
||||
model: modelString || undefined
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'help':
|
||||
onShowHelpDialog?.()
|
||||
@@ -130,7 +131,7 @@ export function useCommandHandler({
|
||||
case 'undo':
|
||||
case 'redo':
|
||||
case 'editor':
|
||||
case 'init':
|
||||
case 'init': {
|
||||
await client.sendCommand(sessionID, {
|
||||
command: command.name,
|
||||
arguments: args,
|
||||
@@ -138,14 +139,16 @@ export function useCommandHandler({
|
||||
model: modelString || undefined
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
default:
|
||||
default: {
|
||||
await client.sendCommand(sessionID, {
|
||||
command: command.name,
|
||||
arguments: args,
|
||||
agent: currentAgent,
|
||||
model: modelString || undefined
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
showToast.error(`Command failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
|
||||
@@ -159,4 +162,4 @@ export function useCommandHandler({
|
||||
executeCommand,
|
||||
loading
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { getLoopStatus, cancelLoop } from '@/api/memory'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
export function useLoopStatus(repoId: number | undefined, open: boolean) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['memory-loop-status', repoId],
|
||||
queryFn: () => getLoopStatus(repoId!),
|
||||
enabled: open && !!repoId,
|
||||
staleTime: 0,
|
||||
refetchInterval: ({ state }) => {
|
||||
const loops = state.data?.loops ?? []
|
||||
return loops.some(l => l.active) ? 5000 : false
|
||||
},
|
||||
})
|
||||
|
||||
const cancelMutation = useMutation({
|
||||
mutationFn: ({ sessionId }: { sessionId: string }) =>
|
||||
cancelLoop(repoId!, sessionId),
|
||||
onSuccess: (result) => {
|
||||
if (result.cancelled) {
|
||||
queryClient.invalidateQueries({ queryKey: ['memory-loop-status', repoId] })
|
||||
} else {
|
||||
showToast.error('Memory loop is no longer active')
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Unable to cancel the memory loop. Please try again.')
|
||||
},
|
||||
})
|
||||
|
||||
const pendingSessionId = cancelMutation.isPending ? (cancelMutation.variables?.sessionId ?? null) : null
|
||||
|
||||
return { data, isLoading, error, cancelMutation, pendingSessionId }
|
||||
}
|
||||
|
||||
export function useLoopActiveCount(repoId: number | undefined, enabled: boolean) {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['memory-loop-status', repoId],
|
||||
queryFn: () => getLoopStatus(repoId!),
|
||||
enabled: enabled && !!repoId,
|
||||
staleTime: 0,
|
||||
refetchInterval: 10000,
|
||||
})
|
||||
return data?.loops.filter(l => l.active).length ?? 0
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
listMemories,
|
||||
createMemory,
|
||||
getMemory,
|
||||
updateMemory,
|
||||
deleteMemory,
|
||||
getProjectSummary,
|
||||
listKvEntries,
|
||||
deleteKvEntry,
|
||||
createKvEntry,
|
||||
updateKvEntry,
|
||||
} from '@/api/memory'
|
||||
import type { CreateMemoryRequest, UpdateMemoryRequest, CreateKvEntryRequest, UpdateKvEntryRequest } from '@opencode-manager/shared/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
export function useMemories(filters?: {
|
||||
projectId?: string
|
||||
scope?: string
|
||||
content?: string
|
||||
limit?: number
|
||||
offset?: number
|
||||
}) {
|
||||
return useQuery({
|
||||
queryKey: ['memories', filters?.projectId, filters?.scope, filters?.content],
|
||||
queryFn: () => listMemories(filters).then(r => r.memories),
|
||||
enabled: !!filters?.projectId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useMemory(id: number | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['memory', id],
|
||||
queryFn: () => {
|
||||
if (id === undefined) throw new Error('Memory ID required')
|
||||
return getMemory(id).then(r => r.memory)
|
||||
},
|
||||
enabled: id !== undefined,
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateMemory() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: CreateMemoryRequest) => createMemory(data).then(r => r.memory),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['memories'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
|
||||
showToast.success('Memory created')
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast.error(`Failed to create memory: ${error}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateMemory() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: UpdateMemoryRequest }) =>
|
||||
updateMemory(id, data).then(r => r.memory),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['memories'] })
|
||||
showToast.success('Memory updated')
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast.error(`Failed to update memory: ${error}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteMemory() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteMemory(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['memories'] })
|
||||
showToast.success('Memory deleted')
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast.error(`Failed to delete memory: ${error}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useProjectSummary(repoId: number | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['projectSummary', repoId],
|
||||
queryFn: () => {
|
||||
if (repoId === undefined) throw new Error('Repo ID required')
|
||||
return getProjectSummary(repoId)
|
||||
},
|
||||
enabled: repoId !== undefined,
|
||||
})
|
||||
}
|
||||
|
||||
export function useKvEntries(projectId?: string, prefix?: string) {
|
||||
return useQuery({
|
||||
queryKey: ['kvEntries', projectId, prefix],
|
||||
queryFn: () => listKvEntries(projectId!, prefix).then(r => r.entries),
|
||||
enabled: !!projectId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteKvEntry() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ projectId, key }: { projectId: string; key: string }) =>
|
||||
deleteKvEntry(projectId, key),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
|
||||
showToast.success('KV entry deleted')
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast.error(`Failed to delete KV entry: ${error}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateKvEntry() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: CreateKvEntryRequest) => createKvEntry(data).then(r => r.entry),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
|
||||
showToast.success('KV entry created')
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast.error(`Failed to create KV entry: ${error}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateKvEntry() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ projectId, key, data }: { projectId: string; key: string; data: UpdateKvEntryRequest }) =>
|
||||
updateKvEntry(projectId, key, data).then(r => r.entry),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
|
||||
showToast.success('KV entry updated')
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast.error(`Failed to update KV entry: ${error}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
|
||||
export function useMemoryPluginStatus() {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['memory-plugin-status'],
|
||||
queryFn: () => settingsApi.getMemoryPluginStatus(),
|
||||
staleTime: 60000,
|
||||
})
|
||||
|
||||
return { memoryPluginEnabled: data?.memoryPluginEnabled ?? false }
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import { OpenCodeClient } from "../api/opencode";
|
||||
import { FetchError } from "../api/fetchWrapper";
|
||||
import { cancelLoop } from "../api/memory";
|
||||
import type {
|
||||
Message,
|
||||
Part,
|
||||
@@ -13,7 +12,6 @@ import type { paths, components } from "../api/opencode-types";
|
||||
import { parseNetworkError } from "../lib/opencode-errors";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
import { ensureSSEConnected, reconnectSSE } from "../lib/sseManager";
|
||||
|
||||
type AssistantMessage = components["schemas"]["AssistantMessage"];
|
||||
|
||||
@@ -21,6 +19,8 @@ type SendPromptRequest = NonNullable<
|
||||
paths["/session/{sessionID}/message"]["post"]["requestBody"]
|
||||
>["content"]["application/json"];
|
||||
|
||||
type SendCommandResponse = paths["/session/{sessionID}/command"]["post"]["responses"]["200"]["content"]["application/json"];
|
||||
|
||||
const parseModelString = (model: string) => {
|
||||
const [providerID, ...rest] = model.split("/");
|
||||
const modelID = rest.join("/");
|
||||
@@ -61,7 +61,7 @@ export const useSession = (opcodeUrl: string | null | undefined, sessionID: stri
|
||||
});
|
||||
};
|
||||
|
||||
export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string) => {
|
||||
export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string, opts?: { fallbackPoll?: boolean }) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
|
||||
return useQuery({
|
||||
@@ -76,7 +76,7 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str
|
||||
refetchOnReconnect: true,
|
||||
staleTime: 30000,
|
||||
gcTime: 10 * 60 * 1000,
|
||||
|
||||
refetchInterval: opts?.fallbackPoll ? 5000 : undefined,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -239,6 +239,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
model,
|
||||
agent,
|
||||
variant,
|
||||
queued,
|
||||
}: {
|
||||
sessionID: string;
|
||||
prompt?: string;
|
||||
@@ -246,15 +247,10 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
model?: string;
|
||||
agent?: string;
|
||||
variant?: string;
|
||||
queued?: boolean;
|
||||
}) => {
|
||||
if (!client) throw new Error("No client available");
|
||||
|
||||
const connected = await ensureSSEConnected();
|
||||
if (!connected) {
|
||||
showToast.error("Unable to connect. Please try again.");
|
||||
throw new Error("SSE connection failed");
|
||||
}
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
@@ -319,9 +315,14 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
requestData.variant = variant;
|
||||
}
|
||||
|
||||
if (queued) {
|
||||
await client.sendPromptAsync(sessionID, requestData);
|
||||
return { optimisticUserID, queued: true };
|
||||
}
|
||||
|
||||
const response = await client.sendPrompt(sessionID, requestData);
|
||||
|
||||
return { optimisticUserID, response };
|
||||
return { optimisticUserID, response, queued: false };
|
||||
},
|
||||
onError: (error, variables) => {
|
||||
const { sessionID } = variables;
|
||||
@@ -334,19 +335,12 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
);
|
||||
|
||||
const isNetworkError = error instanceof TypeError ||
|
||||
(error instanceof FetchError && error.code === 'TIMEOUT');
|
||||
(error instanceof FetchError && (error.code === 'TIMEOUT' || error.statusCode === 524));
|
||||
|
||||
if (isNetworkError) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchError = error as { statusCode?: number };
|
||||
const isCloudflareTimeout = fetchError.statusCode === 524;
|
||||
if (isCloudflareTimeout) {
|
||||
reconnectSSE();
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = parseNetworkError(error);
|
||||
showToast.error(parsed.title, {
|
||||
description: parsed.message,
|
||||
@@ -358,6 +352,11 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
const { response } = data;
|
||||
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
|
||||
if (data.queued || !response) {
|
||||
queryClient.invalidateQueries({ queryKey: messagesQueryKey });
|
||||
return;
|
||||
}
|
||||
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(old) => {
|
||||
@@ -386,7 +385,6 @@ export const useAbortSession = (
|
||||
opcodeUrl: string | null | undefined,
|
||||
directory?: string,
|
||||
sessionID?: string,
|
||||
repoId?: number
|
||||
) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -506,10 +504,6 @@ export const useAbortSession = (
|
||||
|
||||
attemptAbort();
|
||||
|
||||
if (repoId) {
|
||||
cancelLoop(repoId, targetSessionID).catch(() => {})
|
||||
}
|
||||
|
||||
retryIntervalRef.current = setInterval(() => {
|
||||
retryCountRef.current++;
|
||||
|
||||
@@ -590,6 +584,8 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
|
||||
return old.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_"));
|
||||
},
|
||||
);
|
||||
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
},
|
||||
onSuccess: (data, variables) => {
|
||||
const { sessionID } = variables;
|
||||
@@ -631,3 +627,82 @@ export const useAgents = (opcodeUrl: string | null | undefined, directory?: stri
|
||||
enabled: !!client,
|
||||
});
|
||||
};
|
||||
|
||||
export const useLoadSkill = (
|
||||
opcodeUrl: string | null | undefined,
|
||||
sessionID: string | undefined,
|
||||
directory?: string,
|
||||
) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
return useMutation<
|
||||
{ optimisticUserID: string; response: SendCommandResponse },
|
||||
Error,
|
||||
{ skillName: string }
|
||||
>({
|
||||
mutationFn: async ({ skillName }: { skillName: string }) => {
|
||||
if (!client) throw new Error("No OpenCode client available");
|
||||
if (!sessionID) throw new Error("No active session");
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
|
||||
const userMessageParts = createOptimisticUserMessageParts(
|
||||
sessionID,
|
||||
[{ type: "text" as const, content: `Loading skill: ${skillName}` }],
|
||||
optimisticUserID,
|
||||
);
|
||||
const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID);
|
||||
const optimisticMessageWithParts: MessageWithParts = {
|
||||
info: userMessageInfo,
|
||||
parts: userMessageParts,
|
||||
};
|
||||
|
||||
await queryClient.cancelQueries({ queryKey: messagesQueryKey });
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(old) => [...(old || []), optimisticMessageWithParts],
|
||||
);
|
||||
|
||||
const response = await client.sendCommand(sessionID, { command: skillName, arguments: "" });
|
||||
return { optimisticUserID, response };
|
||||
},
|
||||
onError: (error) => {
|
||||
if (sessionID) {
|
||||
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(old) => old?.filter((m) => !m.info.id.startsWith("optimistic_")),
|
||||
);
|
||||
}
|
||||
showToast.error(error instanceof Error ? error.message : "Failed to load skill");
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
const { response } = data;
|
||||
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(old) => {
|
||||
if (!old) return old;
|
||||
|
||||
const existingIdx = old.findIndex(m => m.info.id === response.info.id);
|
||||
if (existingIdx >= 0) {
|
||||
const updated = [...old];
|
||||
updated[existingIdx] = { info: response.info, parts: response.parts };
|
||||
return updated;
|
||||
}
|
||||
|
||||
return [...old, { info: response.info, parts: response.parts }];
|
||||
},
|
||||
);
|
||||
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { getOpenCodeServerAuth, updateOpenCodeServerAuth } from '@/api/settings'
|
||||
import type { OpenCodeServerAuthStatus as OpenCodeServerAuthStatusType } from '@/api/settings'
|
||||
|
||||
export function useOpenCodeServerAuth() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['settings', 'opencode-server-auth'],
|
||||
queryFn: getOpenCodeServerAuth,
|
||||
})
|
||||
|
||||
const setPassword = useMutation({
|
||||
mutationFn: (password: string) => updateOpenCodeServerAuth(password),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['settings', 'opencode-server-auth'] })
|
||||
},
|
||||
})
|
||||
|
||||
const clearPassword = useMutation({
|
||||
mutationFn: () => updateOpenCodeServerAuth(null),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['settings', 'opencode-server-auth'] })
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
status: query.data as OpenCodeServerAuthStatusType | undefined,
|
||||
isLoading: query.isLoading,
|
||||
setPassword,
|
||||
clearPassword,
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import { showToast } from '@/lib/toast'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
import { sseManager, subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager'
|
||||
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'
|
||||
|
||||
@@ -51,6 +52,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
const mountedRef = useRef(true)
|
||||
const sessionIdRef = useRef(currentSessionId)
|
||||
const statusSyncVersionRef = useRef(0)
|
||||
const eventStreamSubscriptionRef = useRef<EventStreamSubscription | null>(null)
|
||||
sessionIdRef.current = currentSessionId
|
||||
const [isConnected, setIsConnected] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -351,6 +353,9 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'messages', opcodeUrl, sessionId, directory],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, directory],
|
||||
})
|
||||
}, [queryClient, opcodeUrl, directory])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -378,22 +383,25 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
setError(null)
|
||||
fetchInitialData()
|
||||
syncCurrentSession()
|
||||
sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
|
||||
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
|
||||
} else {
|
||||
setError('Connection lost. Reconnecting...')
|
||||
}
|
||||
}
|
||||
|
||||
const directoryCleanup = addSSEDirectory(directory)
|
||||
|
||||
const unsubscribe = subscribeToSSE(handleMessage, handleStatusChange)
|
||||
const subscription = openCodeEventStream.subscribeToDirectory({
|
||||
directory,
|
||||
onEvent: handleMessage,
|
||||
onStatusChange: handleStatusChange,
|
||||
})
|
||||
eventStreamSubscriptionRef.current = subscription
|
||||
|
||||
const handleReconnect = () => {
|
||||
reconnectSSE()
|
||||
subscription.reconnect()
|
||||
}
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
|
||||
subscription.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange)
|
||||
@@ -406,14 +414,17 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||
window.removeEventListener('focus', handleReconnect)
|
||||
window.removeEventListener('online', handleReconnect)
|
||||
unsubscribe()
|
||||
directoryCleanup()
|
||||
subscription.reportVisibility(false, undefined)
|
||||
subscription.dispose()
|
||||
if (eventStreamSubscriptionRef.current === subscription) {
|
||||
eventStreamSubscriptionRef.current = null
|
||||
}
|
||||
}
|
||||
}, [opcodeUrl, directory, handleSSEEvent, fetchInitialData, syncCurrentSession])
|
||||
|
||||
useEffect(() => {
|
||||
if (isConnected && document.visibilityState === 'visible') {
|
||||
sseManager.reportVisibility(true, currentSessionId)
|
||||
eventStreamSubscriptionRef.current?.reportVisibility(true, currentSessionId)
|
||||
}
|
||||
}, [currentSessionId, isConnected])
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import { AudioRecorder } from '@/lib/audioRecorder'
|
||||
import { sttApi } from '@/api/stt'
|
||||
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
|
||||
|
||||
const STT_START_TIMEOUT_MS = 10_000
|
||||
|
||||
export function useSTT(userId = 'default') {
|
||||
const { preferences } = useSettings(userId)
|
||||
const [isRecording, setIsRecording] = useState(false)
|
||||
@@ -21,6 +23,8 @@ export function useSTT(userId = 'default') {
|
||||
const userIdRef = useRef(userId)
|
||||
const errorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const lastProcessedBlobRef = useRef<Blob | null>(null)
|
||||
const startupTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const startOpIdRef = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
userIdRef.current = userId
|
||||
@@ -183,6 +187,26 @@ export function useSTT(userId = 'default') {
|
||||
}
|
||||
}, [isEnabled, isExternalProvider, setupAudioRecorder])
|
||||
|
||||
const clearStartupTimeout = useCallback(() => {
|
||||
if (startupTimeoutRef.current) {
|
||||
clearTimeout(startupTimeoutRef.current)
|
||||
startupTimeoutRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const abortAndResetOnTimeout = useCallback(() => {
|
||||
if (isExternalProvider && audioRecorder.current) {
|
||||
audioRecorder.current.abort()
|
||||
} else {
|
||||
recognizer.current.abort()
|
||||
}
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
setIsError(true)
|
||||
setError('Microphone start timed out')
|
||||
}, [isExternalProvider])
|
||||
|
||||
const startRecording = useCallback(async (): Promise<boolean> => {
|
||||
if (!isSupported) {
|
||||
setError('Speech recognition is not supported in this browser')
|
||||
@@ -202,6 +226,9 @@ export function useSTT(userId = 'default') {
|
||||
setError(null)
|
||||
lastProcessedBlobRef.current = null
|
||||
|
||||
const startOpId = ++startOpIdRef.current
|
||||
clearStartupTimeout()
|
||||
|
||||
if (isExternalProvider) {
|
||||
if (!audioRecorder.current) {
|
||||
audioRecorder.current = new AudioRecorder()
|
||||
@@ -210,11 +237,30 @@ export function useSTT(userId = 'default') {
|
||||
|
||||
try {
|
||||
setIsProcessing(true)
|
||||
await audioRecorder.current.start()
|
||||
|
||||
const startupPromise = audioRecorder.current.start()
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
startupTimeoutRef.current = setTimeout(() => {
|
||||
if (startOpIdRef.current !== startOpId) return
|
||||
reject(new Error('Microphone start timed out'))
|
||||
}, STT_START_TIMEOUT_MS)
|
||||
})
|
||||
|
||||
await Promise.race([startupPromise, timeoutPromise])
|
||||
clearStartupTimeout()
|
||||
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
|
||||
setIsProcessing(false)
|
||||
return true
|
||||
} catch (err) {
|
||||
clearStartupTimeout()
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
setIsProcessing(false)
|
||||
if (err instanceof Error && err.message === 'Microphone start timed out') {
|
||||
abortAndResetOnTimeout()
|
||||
return false
|
||||
}
|
||||
setIsError(true)
|
||||
setError(err instanceof Error ? err.message : 'Failed to start recording')
|
||||
return false
|
||||
@@ -228,16 +274,35 @@ export function useSTT(userId = 'default') {
|
||||
|
||||
try {
|
||||
setIsProcessing(true)
|
||||
await recognizer.current.start(options)
|
||||
|
||||
const startupPromise = recognizer.current.start(options)
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
startupTimeoutRef.current = setTimeout(() => {
|
||||
if (startOpIdRef.current !== startOpId) return
|
||||
reject(new Error('Microphone start timed out'))
|
||||
}, STT_START_TIMEOUT_MS)
|
||||
})
|
||||
|
||||
await Promise.race([startupPromise, timeoutPromise])
|
||||
clearStartupTimeout()
|
||||
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
|
||||
return true
|
||||
} catch (err) {
|
||||
clearStartupTimeout()
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
setIsProcessing(false)
|
||||
if (err instanceof Error && err.message === 'Microphone start timed out') {
|
||||
abortAndResetOnTimeout()
|
||||
return false
|
||||
}
|
||||
setIsError(true)
|
||||
setError(err instanceof Error ? err.message : 'Failed to start recording')
|
||||
return false
|
||||
}
|
||||
}
|
||||
}, [isSupported, isEnabled, isExternalProvider, config.language, setupAudioRecorder])
|
||||
}, [isSupported, isEnabled, isExternalProvider, config.language, setupAudioRecorder, clearStartupTimeout, abortAndResetOnTimeout])
|
||||
|
||||
const stopRecording = useCallback(() => {
|
||||
if (isExternalProvider && audioRecorder.current) {
|
||||
@@ -286,8 +351,9 @@ export function useSTT(userId = 'default') {
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
|
||||
clearStartupTimeout()
|
||||
}
|
||||
}, [])
|
||||
}, [clearStartupTimeout])
|
||||
|
||||
return {
|
||||
isRecording,
|
||||
|
||||
@@ -4,6 +4,13 @@ import { toast } from 'sonner'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { invalidateConfigCaches, invalidateSettingsCaches } from '@/lib/queryInvalidation'
|
||||
import { fetchWrapper } from '@/api/fetchWrapper'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
|
||||
const MISSING_PASSWORD_ERROR_PATTERN = /no password is configured|OPENCODE_SERVER_PASSWORD/i
|
||||
|
||||
function isMissingPasswordError(error: string | undefined): boolean {
|
||||
return !!error && MISSING_PASSWORD_ERROR_PATTERN.test(error)
|
||||
}
|
||||
|
||||
interface HealthResponse {
|
||||
status: 'healthy' | 'degraded' | 'unhealthy'
|
||||
@@ -24,8 +31,10 @@ async function fetchHealth(): Promise<HealthResponse> {
|
||||
|
||||
export function useServerHealth(enabled = true) {
|
||||
const queryClient = useQueryClient()
|
||||
const { isOpen: isSettingsOpen, setActiveTab } = useSettingsDialog()
|
||||
const lastHealthStatusRef = useRef<'healthy' | 'unhealthy'>('healthy')
|
||||
const prevHealthRef = useRef<string | null>(null)
|
||||
const hasAutoOpenedSettingsRef = useRef(false)
|
||||
|
||||
const restartMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
@@ -76,8 +85,16 @@ export function useServerHealth(enabled = true) {
|
||||
const currentStatus = isUnhealthy ? 'unhealthy' : 'healthy'
|
||||
const previousStatus = lastHealthStatusRef.current
|
||||
const prevHealth = prevHealthRef.current
|
||||
const missingPassword = isUnhealthy && isMissingPasswordError(health.error)
|
||||
|
||||
if (prevHealth && currentStatus !== prevHealth) {
|
||||
if (isUnhealthy && missingPassword && !hasAutoOpenedSettingsRef.current && !isSettingsOpen) {
|
||||
hasAutoOpenedSettingsRef.current = true
|
||||
setActiveTab('opencode')
|
||||
toast.error(health.error || 'OpenCode server requires a password', {
|
||||
duration: Infinity,
|
||||
description: 'Set a password under Settings → OpenCode to start the server.',
|
||||
})
|
||||
} else if (prevHealth && currentStatus !== prevHealth) {
|
||||
if (isUnhealthy && previousStatus === 'healthy') {
|
||||
toast.error(health.error || 'OpenCode server is currently unhealthy', {
|
||||
duration: Infinity,
|
||||
@@ -88,12 +105,13 @@ export function useServerHealth(enabled = true) {
|
||||
})
|
||||
} else if (!isUnhealthy && previousStatus === 'unhealthy') {
|
||||
toast.success('Server is back online')
|
||||
hasAutoOpenedSettingsRef.current = false
|
||||
}
|
||||
}
|
||||
|
||||
lastHealthStatusRef.current = currentStatus
|
||||
prevHealthRef.current = currentStatus
|
||||
}, [health, restartMutation])
|
||||
}, [health, restartMutation, isSettingsOpen, setActiveTab])
|
||||
|
||||
return {
|
||||
...query,
|
||||
|
||||
@@ -18,7 +18,7 @@ interface SwipeState {
|
||||
|
||||
export function useSwipe(options: SwipeOptions = {}) {
|
||||
const {
|
||||
threshold = 80,
|
||||
threshold = 60,
|
||||
directionRatio = 1.5,
|
||||
enabled = true,
|
||||
onSwipeStart,
|
||||
|
||||
Reference in new issue
Block a user