import { afterEach, describe, expect, it, vi } from 'vitest'
import { createEvent, fireEvent, render, screen, within } from '@testing-library/react'
import '@testing-library/jest-dom'
import { act } from 'react'
vi.mock('../components/chat/MessageList', () => ({
MessageList: ({ compact }: { compact?: boolean }) => (
),
}))
vi.mock('../components/chat/ChatInput', () => ({
ChatInput: ({ compact, variant }: { compact?: boolean; variant?: string }) => (
),
}))
vi.mock('../components/teams/TeamStatusBar', () => ({
TeamStatusBar: () => ,
}))
vi.mock('../components/chat/SessionTaskBar', () => ({
SessionTaskBar: () => ,
}))
vi.mock('../components/workspace/WorkspacePanel', () => ({
WorkspacePanel: ({ sessionId }: { sessionId: string }) => (
workspace:{sessionId}
),
}))
vi.mock('./TerminalSettings', () => ({
TerminalSettings: ({
cwd,
onOpenInTab,
onClose,
testId,
}: {
cwd?: string
onOpenInTab?: () => void
onClose?: () => void
testId: string
}) => (
),
}))
import { ActiveSession } from './ActiveSession'
import { useChatStore } from '../stores/chatStore'
import { useCLITaskStore } from '../stores/cliTaskStore'
import { useSessionStore } from '../stores/sessionStore'
import { useTabStore } from '../stores/tabStore'
import { useTeamStore } from '../stores/teamStore'
import { useWorkspacePanelStore } from '../stores/workspacePanelStore'
import { WORKSPACE_PANEL_DEFAULT_WIDTH } from '../stores/workspacePanelStore'
import { useTerminalPanelStore } from '../stores/terminalPanelStore'
import {
TERMINAL_PANEL_DEFAULT_HEIGHT,
TERMINAL_PANEL_MAX_HEIGHT,
TERMINAL_PANEL_MIN_HEIGHT,
} from '../stores/terminalPanelStore'
afterEach(() => {
vi.useRealTimers()
useTabStore.setState({ tabs: [], activeTabId: null })
useSessionStore.setState({ sessions: [], activeSessionId: null, isLoading: false, error: null })
useChatStore.setState({ sessions: {} })
useTeamStore.setState({ teams: [], activeTeam: null, memberColors: new Map(), error: null })
useWorkspacePanelStore.setState(useWorkspacePanelStore.getInitialState(), true)
useTerminalPanelStore.setState(useTerminalPanelStore.getInitialState(), true)
})
describe('ActiveSession task polling', () => {
it('refreshes CLI tasks repeatedly while a turn is active', async () => {
vi.useFakeTimers()
const sessionId = 'polling-session'
const originalCliTaskState = useCLITaskStore.getState()
const fetchSessionTasks = vi.fn().mockResolvedValue(undefined)
useCLITaskStore.setState({
sessionId,
tasks: [],
fetchSessionTasks,
})
useSessionStore.setState({
sessions: [{
id: sessionId,
title: 'Polling Session',
createdAt: '2026-04-10T00:00:00.000Z',
modifiedAt: '2026-04-10T00:00:00.000Z',
messageCount: 1,
projectPath: '',
workDir: null,
workDirExists: true,
}],
activeSessionId: sessionId,
isLoading: false,
error: null,
})
useTabStore.setState({
tabs: [{ sessionId, title: 'Polling Session', type: 'session', status: 'idle' }],
activeTabId: sessionId,
})
useChatStore.setState({
sessions: {
[sessionId]: {
messages: [],
chatState: 'thinking',
connectionState: 'connected',
streamingText: '',
streamingToolInput: '',
activeToolUseId: null,
activeToolName: null,
activeThinkingId: null,
pendingPermission: null,
pendingComputerUsePermission: null,
tokenUsage: { input_tokens: 0, output_tokens: 0 },
elapsedSeconds: 0,
statusVerb: '',
slashCommands: [],
agentTaskNotifications: {},
elapsedTimer: null,
},
},
})
const { unmount } = render()
expect(fetchSessionTasks).toHaveBeenCalledWith(sessionId)
await act(async () => {
await vi.advanceTimersByTimeAsync(2200)
})
expect(
fetchSessionTasks.mock.calls.filter(([currentSessionId]) => currentSessionId === sessionId),
).toHaveLength(4)
unmount()
useCLITaskStore.setState(originalCliTaskState)
})
it('keeps member sessions interactive and skips leader task polling', () => {
const memberSessionId = 'team-member:security-reviewer@test-team'
const originalCliTaskState = useCLITaskStore.getState()
const fetchSessionTasks = vi.fn().mockResolvedValue(undefined)
useCLITaskStore.setState({
sessionId: null,
tasks: [],
fetchSessionTasks,
})
useTeamStore.setState({
teams: [],
activeTeam: {
name: 'test-team',
leadAgentId: 'team-lead@test-team',
leadSessionId: 'leader-session',
members: [
{
agentId: 'team-lead@test-team',
role: 'team-lead',
status: 'running',
sessionId: 'leader-session',
},
{
agentId: 'security-reviewer@test-team',
role: 'security-reviewer',
status: 'running',
},
],
},
memberColors: new Map(),
error: null,
})
useTabStore.setState({
tabs: [{ sessionId: memberSessionId, title: 'security-reviewer', type: 'session', status: 'idle' }],
activeTabId: memberSessionId,
})
useChatStore.setState({
sessions: {
[memberSessionId]: {
messages: [],
chatState: 'thinking',
connectionState: 'connected',
streamingText: '',
streamingToolInput: '',
activeToolUseId: null,
activeToolName: null,
activeThinkingId: null,
pendingPermission: null,
pendingComputerUsePermission: null,
tokenUsage: { input_tokens: 0, output_tokens: 0 },
elapsedSeconds: 0,
statusVerb: '',
slashCommands: [],
agentTaskNotifications: {},
elapsedTimer: null,
},
},
})
const { queryByTestId, unmount } = render()
expect(queryByTestId('chat-input')).toBeInTheDocument()
expect(queryByTestId('session-task-bar')).not.toBeInTheDocument()
expect(fetchSessionTasks).not.toHaveBeenCalled()
unmount()
useCLITaskStore.setState(originalCliTaskState)
})
it('renders the workspace panel to the right of chat and supports resizing', () => {
const sessionId = 'workspace-session'
useSessionStore.setState({
sessions: [{
id: sessionId,
title: 'Workspace Session',
createdAt: '2026-04-10T00:00:00.000Z',
modifiedAt: '2026-04-10T00:00:00.000Z',
messageCount: 1,
projectPath: '',
workDir: '/tmp/project',
workDirExists: true,
}],
activeSessionId: sessionId,
isLoading: false,
error: null,
})
useTabStore.setState({
tabs: [{ sessionId, title: 'Workspace Session', type: 'session', status: 'idle' }],
activeTabId: sessionId,
})
useChatStore.setState({
sessions: {
[sessionId]: {
messages: [{ id: 'msg-1', type: 'assistant_text', content: 'hello', timestamp: 1 }],
chatState: 'idle',
connectionState: 'connected',
streamingText: '',
streamingToolInput: '',
activeToolUseId: null,
activeToolName: null,
activeThinkingId: null,
pendingPermission: null,
pendingComputerUsePermission: null,
tokenUsage: { input_tokens: 0, output_tokens: 0 },
elapsedSeconds: 0,
statusVerb: '',
slashCommands: [],
agentTaskNotifications: {},
elapsedTimer: null,
},
},
})
useWorkspacePanelStore.getState().openPanel(sessionId)
render()
const contentRow = screen.getByTestId('active-session-content-row')
const chatColumn = screen.getByTestId('active-session-chat-column')
const resizeHandle = screen.getByTestId('workspace-resize-handle')
expect(within(contentRow).getByTestId('message-list')).toBeInTheDocument()
expect(within(contentRow).getByTestId('message-list')).toHaveAttribute('data-compact', 'true')
expect(within(contentRow).getByTestId('workspace-panel')).toHaveTextContent(`workspace:${sessionId}`)
expect(within(chatColumn).getByTestId('chat-input')).toBeInTheDocument()
expect(within(chatColumn).getByTestId('chat-input')).toHaveAttribute('data-compact', 'true')
expect(chatColumn).toHaveClass('flex-1')
expect(chatColumn).not.toHaveClass('shrink-0')
expect(contentRow.children[0]).toBe(chatColumn)
expect(contentRow.children[1]).toBe(resizeHandle)
expect(contentRow.children[2]).toBe(screen.getByTestId('workspace-panel'))
act(() => {
fireEvent.keyDown(resizeHandle, { key: 'ArrowLeft' })
})
expect(useWorkspacePanelStore.getState().width).toBe(WORKSPACE_PANEL_DEFAULT_WIDTH + 32)
})
it('does not render the workspace panel when closed or for member sessions', () => {
const regularSessionId = 'regular-session'
useSessionStore.setState({
sessions: [{
id: regularSessionId,
title: 'Regular Session',
createdAt: '2026-04-10T00:00:00.000Z',
modifiedAt: '2026-04-10T00:00:00.000Z',
messageCount: 0,
projectPath: '',
workDir: '/tmp/project',
workDirExists: true,
}],
activeSessionId: regularSessionId,
isLoading: false,
error: null,
})
useTabStore.setState({
tabs: [{ sessionId: regularSessionId, title: 'Regular Session', type: 'session', status: 'idle' }],
activeTabId: regularSessionId,
})
useChatStore.setState({
sessions: {
[regularSessionId]: {
messages: [],
chatState: 'idle',
connectionState: 'connected',
streamingText: '',
streamingToolInput: '',
activeToolUseId: null,
activeToolName: null,
activeThinkingId: null,
pendingPermission: null,
pendingComputerUsePermission: null,
tokenUsage: { input_tokens: 0, output_tokens: 0 },
elapsedSeconds: 0,
statusVerb: '',
slashCommands: [],
agentTaskNotifications: {},
elapsedTimer: null,
},
},
})
const { rerender } = render()
expect(screen.queryByTestId('workspace-panel')).not.toBeInTheDocument()
const memberSessionId = 'team-member:security-reviewer@test-team'
useTeamStore.setState({
teams: [],
activeTeam: {
name: 'test-team',
leadAgentId: 'team-lead@test-team',
leadSessionId: 'leader-session',
members: [
{
agentId: 'team-lead@test-team',
role: 'team-lead',
status: 'running',
sessionId: 'leader-session',
},
{
agentId: 'security-reviewer@test-team',
role: 'security-reviewer',
status: 'running',
},
],
},
memberColors: new Map(),
error: null,
})
useTabStore.setState({
tabs: [{ sessionId: memberSessionId, title: 'security-reviewer', type: 'session', status: 'idle' }],
activeTabId: memberSessionId,
})
useChatStore.setState({
sessions: {
[memberSessionId]: {
messages: [{ id: 'msg-2', type: 'assistant_text', content: 'hello', timestamp: 1 }],
chatState: 'idle',
connectionState: 'connected',
streamingText: '',
streamingToolInput: '',
activeToolUseId: null,
activeToolName: null,
activeThinkingId: null,
pendingPermission: null,
pendingComputerUsePermission: null,
tokenUsage: { input_tokens: 0, output_tokens: 0 },
elapsedSeconds: 0,
statusVerb: '',
slashCommands: [],
agentTaskNotifications: {},
elapsedTimer: null,
},
},
})
useWorkspacePanelStore.getState().openPanel(memberSessionId)
rerender()
expect(screen.queryByTestId('workspace-panel')).not.toBeInTheDocument()
expect(screen.getByTestId('message-list')).toBeInTheDocument()
})
it('renders a bottom terminal panel in the current session cwd and can promote it to a tab', async () => {
const sessionId = 'terminal-session'
useSessionStore.setState({
sessions: [{
id: sessionId,
title: 'Terminal Session',
createdAt: '2026-04-10T00:00:00.000Z',
modifiedAt: '2026-04-10T00:00:00.000Z',
messageCount: 1,
projectPath: '/tmp/project-root',
workDir: '/tmp/project-root/packages/app',
workDirExists: true,
}],
activeSessionId: sessionId,
isLoading: false,
error: null,
})
useTabStore.setState({
tabs: [{ sessionId, title: 'Terminal Session', status: 'idle' } as ReturnType['tabs'][number]],
activeTabId: sessionId,
})
useChatStore.setState({
sessions: {
[sessionId]: {
messages: [{ id: 'msg-1', type: 'assistant_text', content: 'hello', timestamp: 1 }],
chatState: 'idle',
connectionState: 'connected',
streamingText: '',
streamingToolInput: '',
activeToolUseId: null,
activeToolName: null,
activeThinkingId: null,
pendingPermission: null,
pendingComputerUsePermission: null,
tokenUsage: { input_tokens: 0, output_tokens: 0 },
elapsedSeconds: 0,
statusVerb: '',
slashCommands: [],
agentTaskNotifications: {},
elapsedTimer: null,
},
},
})
useTerminalPanelStore.getState().openPanel(sessionId)
render()
const panel = screen.getByTestId('session-terminal-panel')
const resizeHandle = screen.getByTestId('terminal-resize-handle')
const host = screen.getByTestId(`session-terminal-host-${sessionId}`)
expect(panel).toHaveStyle({ height: `${TERMINAL_PANEL_DEFAULT_HEIGHT}px` })
expect(host).toHaveAttribute('data-cwd', '/tmp/project-root/packages/app')
expect(resizeHandle).toHaveAttribute('aria-valuemin', `${TERMINAL_PANEL_MIN_HEIGHT}`)
expect(resizeHandle).toHaveAttribute('aria-valuemax', `${TERMINAL_PANEL_MAX_HEIGHT}`)
act(() => {
fireEvent.keyDown(resizeHandle, { key: 'ArrowUp' })
})
expect(useTerminalPanelStore.getState().height).toBe(TERMINAL_PANEL_DEFAULT_HEIGHT + 24)
await act(async () => {
const pointerDown = createEvent.pointerDown(resizeHandle)
Object.defineProperty(pointerDown, 'button', { value: 0 })
Object.defineProperty(pointerDown, 'clientY', { value: 300 })
fireEvent(resizeHandle, pointerDown)
})
await act(async () => {
const pointerMove = new Event('pointermove')
Object.defineProperty(pointerMove, 'clientY', { value: 260 })
window.dispatchEvent(pointerMove)
window.dispatchEvent(new Event('pointerup'))
})
expect(useTerminalPanelStore.getState().height).toBe(TERMINAL_PANEL_DEFAULT_HEIGHT + 64)
act(() => {
fireEvent.keyDown(resizeHandle, { key: 'End' })
})
expect(useTerminalPanelStore.getState().height).toBe(TERMINAL_PANEL_MAX_HEIGHT)
act(() => {
fireEvent.keyDown(resizeHandle, { key: 'Home' })
})
expect(useTerminalPanelStore.getState().height).toBe(TERMINAL_PANEL_MIN_HEIGHT)
act(() => {
fireEvent.doubleClick(resizeHandle)
})
expect(useTerminalPanelStore.getState().height).toBe(TERMINAL_PANEL_DEFAULT_HEIGHT)
fireEvent.click(screen.getByRole('button', { name: 'Open in Tab' }))
const terminalTab = useTabStore.getState().tabs.find((tab) => tab.type === 'terminal')
expect(useTerminalPanelStore.getState().isPanelOpen(sessionId)).toBe(false)
expect(terminalTab?.terminalCwd).toBe('/tmp/project-root/packages/app')
expect(useTabStore.getState().activeTabId).toBe(terminalTab?.sessionId)
})
})