Files
opencode-manager/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx
T
Chris Scott d26ab578f0 feat(sessions): move the session picker into the desktop right tool panel
Replace the tool rail's Activity tool with a Sessions tool that renders the
full session picker (Activity, This project and Projects tabs, linked-server
selector, add repository), shared with the mobile sheet via RouteSessionPicker.

- A docked panel stays open and follows navigation (picker navigation mode
  'panel'); the floating overlay closes on select (mode 'replace').
- The session page's sessions shortcut and /sessions open the panel; the
  collapsed sidebar opens it when a tool rail is mounted and falls back to
  the modal dialog otherwise.
- useToolPanelToggle is the single panel toggle for the rail, shortcuts and
  sidebar.
- Remove ActivityList, the fixed activity panel width and the window label.
2026-10-25 17:16:36 -04:00

471 lines
15 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { useEffect } from 'react'
import { SessionDetail } from '../SessionDetail'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
useSessionTranscript: vi.fn(),
useSSE: vi.fn(),
useRepoActivity: vi.fn(),
usePermissions: vi.fn(),
useForms: vi.fn(),
useSSEHealth: vi.fn(),
useConfig: vi.fn(),
useSettings: vi.fn(),
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useShortcutActions: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(),
interruptMutate: vi.fn(),
PromptInput: vi.fn(),
uiState: { isEditingMessage: false },
setToolRailMounted: vi.fn(),
}))
vi.mock('@/config', () => ({
OPENCODE_API_ENDPOINT: 'http://localhost:5551/api/opencode',
API_BASE_URL: 'http://localhost:5551',
SERVER_PORT: 5003,
OPENCODE_PORT: 5551,
FILE_LIMITS: {},
DEFAULTS: {},
ALLOWED_MIME_TYPES: [],
GIT_PROVIDERS: [],
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession,
useInterruptSession: vi.fn(() => ({ mutate: mocks.interruptMutate })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
useConfig: mocks.useConfig,
useSendPrompt: vi.fn(() => ({ mutate: vi.fn() })),
useSendShell: vi.fn(() => ({ mutate: vi.fn() })),
useAgents: vi.fn(() => ({ data: [] })),
}))
vi.mock('@/hooks/useSessionTranscript', () => ({
useSessionTranscript: mocks.useSessionTranscript,
}))
vi.mock('@/hooks/useRepoSiblings', () => ({
useRepoSiblings: vi.fn(() => ({ data: [] })),
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null, modelRef: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: vi.fn(() => ({ isEnabled: false })),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: vi.fn(() => ({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})),
}))
vi.mock('@/hooks/useSettingsDialog', () => ({
useSettingsDialog: vi.fn(() => ({ open: vi.fn() })),
}))
vi.mock('@/hooks/useMobile', () => ({
useMobile: mocks.useMobile,
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
useSwipeDismiss: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })),
}))
vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
useShortcutActions: mocks.useShortcutActions,
}))
vi.mock('@/hooks/useAutoScroll', () => ({
useAutoScroll: mocks.useAutoScroll,
}))
vi.mock('@/hooks/useDialogParam', () => ({
useDialogParam: vi.fn(() => [false, vi.fn()]),
}))
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
getAssistantText: vi.fn(() => ''),
getLatestPlayableAssistantMessage: vi.fn(() => null),
useAutoPlayLastResponse: vi.fn(() => {}),
}))
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn((selector?: (state: Record<string, unknown>) => unknown) =>
typeof selector === 'function'
? selector({
isEditingMessage: mocks.uiState.isEditingMessage,
isToolRailMounted: false,
setToolRailMounted: mocks.setToolRailMounted,
})
: false
),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
useSessionStatusForSession: mocks.useSessionStatusForSession,
}))
vi.mock('@/hooks/useSSE', () => ({
useSSE: mocks.useSSE,
}))
vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/contexts/EventContext', async (importOriginal) => {
const actual = await importOriginal()
return {
...(actual as object),
usePermissions: mocks.usePermissions,
useForms: mocks.useForms,
useSSEHealth: mocks.useSSEHealth,
}
})
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWorkCounts: () => ({ needsInput: 0, running: 0 }),
useRepoActivityState: () => null,
}))
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve({
id: 1,
repoUrl: 'https://github.com/test/repo',
localPath: '/test/repo',
sourcePath: null,
fullPath: '/test/repo',
branch: 'main',
currentBranch: 'main',
fullSlug: 'test/repo',
repoType: 'github' as const,
})),
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/test/repo' })),
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: vi.fn(() => null) }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: vi.fn(() => ({ data: undefined })),
useStartSessionGoal: vi.fn(() => ({ mutateAsync: vi.fn(), isPending: false })),
usePauseSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({
RepoSkillsDialog: vi.fn(() => null),
}))
vi.mock('@/components/source-control', () => ({
SourceControlPanel: vi.fn(() => null),
}))
vi.mock('@/components/session/FormPrompt', () => ({
FormPrompt: vi.fn(() => null),
}))
vi.mock('@/components/session/MinimizedFormIndicator', () => ({
MinimizedFormIndicator: vi.fn(() => null),
}))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({
PendingActionsGroup: vi.fn(() => null),
}))
vi.mock('@/components/message/PromptInput', () => ({
PromptInput: mocks.PromptInput,
}))
interface ObservedElement {
element: Element
callback: ResizeObserverCallback
observer: ResizeObserver
}
const observedElements: ObservedElement[] = []
class TestResizeObserver {
constructor(private readonly callback: ResizeObserverCallback) {}
observe(element: Element) {
observedElements.push({ element, callback: this.callback, observer: this as unknown as ResizeObserver })
}
unobserve(element: Element) {
const index = observedElements.findIndex((entry) => entry.observer === (this as unknown) && entry.element === element)
if (index !== -1) observedElements.splice(index, 1)
}
disconnect() {
for (let index = observedElements.length - 1; index >= 0; index -= 1) {
if (observedElements[index].observer === (this as unknown)) observedElements.splice(index, 1)
}
}
}
const reportObservedHeight = (height: number) => {
act(() => {
for (const entry of [...observedElements]) {
if (!entry.element.isConnected) continue
entry.callback(
[{ target: entry.element, contentRect: { height } } as unknown as ResizeObserverEntry],
entry.observer
)
}
})
}
describe('SessionDetail scroll floating button', () => {
let mockScrollToBottom: ReturnType<typeof vi.fn>
beforeEach(() => {
vi.clearAllMocks()
observedElements.length = 0
mocks.uiState.isEditingMessage = false
vi.stubGlobal('ResizeObserver', TestResizeObserver)
mockScrollToBottom = vi.fn()
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
mocks.useSessionTranscript.mockReturnValue({
messages: [],
pending: [],
status: 'idle',
isLoading: false,
fetchOlder: vi.fn(),
hasOlder: false,
})
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
mocks.useRepoActivity.mockReturnValue(undefined)
mocks.usePermissions.mockReturnValue({
pendingCount: 0,
hasPermissionsForSession: vi.fn(() => false),
syncForSession: vi.fn(),
})
mocks.useForms.mockReturnValue({
current: null,
getForSession: vi.fn(() => null),
pendingCount: 0,
hasFormsForSession: vi.fn(() => false),
reply: vi.fn(),
cancel: vi.fn(),
syncForSession: vi.fn(),
})
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
mocks.PromptInput.mockImplementation(() => <div>MockedPromptInput</div>)
})
const createQueryClient = () =>
new QueryClient({ defaultOptions: { queries: { retry: false } } })
const renderWith = (opts: {
mobile: boolean
showScrollButton: boolean
promptContent?: boolean
sessionActive?: boolean
messagesLoading?: boolean
}) => {
mocks.useMobile.mockReturnValue(opts.mobile)
mocks.useSessionStatusForSession.mockReturnValue({ type: opts.sessionActive ? 'busy' : 'idle' })
mocks.useSessionTranscript.mockReturnValue({
messages: [],
pending: [],
status: opts.sessionActive ? 'busy' : 'idle',
isLoading: opts.messagesLoading ?? false,
fetchOlder: vi.fn(),
hasOlder: false,
})
mocks.useAutoScroll.mockImplementation(
({ onScrollStateChange }: { onScrollStateChange?: (v: boolean) => void }) => {
if (opts.showScrollButton) {
Promise.resolve().then(() => onScrollStateChange?.(true))
}
return { scrollToBottom: mockScrollToBottom }
}
)
mocks.PromptInput.mockImplementation((props: { onPromptChange?: (hasContent: boolean) => void }) => {
const { onPromptChange } = props
useEffect(() => {
onPromptChange?.(opts.promptContent ?? false)
}, [onPromptChange])
return <div>MockedPromptInput</div>
})
const queryClient = createQueryClient()
const buildTree = () => (
<MemoryRouter initialEntries={['/repos/1/sessions/test-session']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
return Object.assign(render(buildTree()), { buildTree })
}
it('shows the jump to latest button while scrolled up on mobile', async () => {
renderWith({ mobile: true, showScrollButton: true })
expect(await screen.findByRole('button', { name: 'Jump to latest' })).toBeInTheDocument()
})
it('shows the jump to latest button while scrolled up on desktop', async () => {
renderWith({ mobile: false, showScrollButton: true })
expect(await screen.findByRole('button', { name: 'Jump to latest' })).toBeInTheDocument()
})
it('shows the jump to latest button even when the prompt has content', async () => {
renderWith({ mobile: true, showScrollButton: true, promptContent: true })
expect(await screen.findByRole('button', { name: 'Jump to latest' })).toBeInTheDocument()
})
it('hides the jump to latest button while at the bottom of the transcript', async () => {
renderWith({ mobile: true, showScrollButton: false })
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
expect(screen.queryByRole('button', { name: 'Jump to latest' })).not.toBeInTheDocument()
})
it('no longer passes scroll button state to PromptInput', async () => {
renderWith({ mobile: true, showScrollButton: true })
await screen.findByRole('button', { name: 'Jump to latest' })
const props = mocks.PromptInput.mock.calls.at(-1)?.[0] as Record<string, unknown>
expect(props.showScrollButton).toBeUndefined()
})
it('scrolls to the bottom when the jump to latest button is clicked', async () => {
renderWith({ mobile: true, showScrollButton: true })
fireEvent.click(await screen.findByRole('button', { name: 'Jump to latest' }))
expect(mockScrollToBottom).toHaveBeenCalledTimes(1)
})
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('renders the mobile stop button while the session is active and interrupts on click', async () => {
renderWith({ mobile: true, showScrollButton: false, sessionActive: true })
const stopButton = await screen.findByTitle('Stop')
fireEvent.click(stopButton)
expect(mocks.interruptMutate).toHaveBeenCalledWith('test-session')
})
it('does not render the stop button while the session is idle', async () => {
renderWith({ mobile: true, showScrollButton: false, sessionActive: false })
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
})
it('does NOT disable PromptInput when SSE is disconnected', async () => {
mocks.useSSE.mockReturnValue({ isConnected: false, isReconnecting: true })
renderWith({ mobile: true, showScrollButton: false })
await waitFor(() => {
expect(mocks.PromptInput).toHaveBeenCalled()
})
const props = mocks.PromptInput.mock.calls.at(-1)?.[0] as { disabled?: boolean }
expect(props.disabled).not.toBe(true)
})
it('restores message list clearance after the prompt overlay remounts following a message edit', async () => {
const { buildTree, rerender } = renderWith({ mobile: true, showScrollButton: false })
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
const paddingBottom = () => screen.getByTestId('session-message-scroll').style.paddingBottom
reportObservedHeight(140)
expect(paddingBottom()).toBe('156px')
mocks.uiState.isEditingMessage = true
rerender(buildTree())
await waitFor(() => expect(screen.queryByText('MockedPromptInput')).not.toBeInTheDocument())
expect(paddingBottom()).toBe('16px')
mocks.uiState.isEditingMessage = false
rerender(buildTree())
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
reportObservedHeight(140)
expect(paddingBottom()).toBe('156px')
})
it('marks the transcript content as not ready while messages load and ready afterwards', async () => {
const { buildTree, rerender } = renderWith({ mobile: true, showScrollButton: false, messagesLoading: true })
await waitFor(() => {
expect(mocks.useAutoScroll.mock.calls.at(-1)?.[0]).toMatchObject({ isContentReady: false })
})
mocks.useSessionTranscript.mockReturnValue({
messages: [],
pending: [],
status: 'idle',
isLoading: false,
fetchOlder: vi.fn(),
hasOlder: false,
})
rerender(buildTree())
await waitFor(() => {
expect(mocks.useAutoScroll.mock.calls.at(-1)?.[0]).toMatchObject({ isContentReady: true })
})
})
})