fix: update settings and skills handling with assistant redirect (#220)

* fix: enable swipe-back suspension on more drawer and remove unused variable

* refactor(frontend): improve dialog component and settings navigation

* fix: disable route swipe suspension in MoreDrawer to prevent unintended navigation

* fix(frontend): enable swipe-back suspension on more drawer route

* refactor(frontend): improve mobile navigation drawer and tab bar

* feat: add schedules service and workspace hook with navigation updates

* chore: add workspace hook, schedules library, and tests

* fix: prevent MoreDrawer sentinel from undoing navigation

* feat: per-agent model selection and UI refinements (#217)

* feat: per-agent model selection and UI refinements

- Add agentModels store with setAgentModel/getAgentModel
- PromptInput uses session model priority and stores agent model on change
- useContextUsage derives model from assistant message instead of global
- Migrate sub-agent/subtask badges from purple to blue with refined styling
- Fix MoreDrawer sentinel to skip history-back on navigation

* refactor: improve per-agent model selection and task tool call status indicators

* feat: add repo management skill and internal repos API

* fix: improve assistant session launcher and UI components

* fix: update atomic-json test assertions

* refactor: split Assistant Mode instructions between AGENTS.md and assistant.md

* loop: todo-header-mobile completed after 3 iterations (#218)

* loop: stt-perf-1 completed after 5 iterations

* fix: load audio worklet per recording context

* fix: canonicalize assistant navigation routes

* fix: adjust scroll-up threshold for header visibility

* fix: update settings and skills handling with assistant redirect

* refactor: simplify context usage indicator and extract token sum helper

* feat: add currently selected model row to popover and fix responsive truncate
This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-07 18:36:03 -04:00
1 parent c7291518c8
commit 74cdeb3926
73 files changed
+4073 -632

No files matched your search

+27 -13
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useState } from "react"
import { useParams, useNavigate, useLocation } from "react-router-dom"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { getRepo, initializeAssistantMode, listRepos } from "@/api/repos"
import { getRepo, initializeAssistantMode } from "@/api/repos"
import { useAssistantSessionLauncher } from "@/hooks/useAssistantSessionLauncher"
import { useCreateSession } from "@/hooks/useOpenCode"
import { useDialogParam } from "@/hooks/useDialogParam"
@@ -17,7 +17,7 @@ import { SourceControlPanel } from "@/components/source-control"
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"
import { invalidateConfigCaches } from "@/lib/queryInvalidation"
import { getSessionListPath } from "@/lib/navigation"
import { getSessionListPath, getAssistantPath } from "@/lib/navigation"
import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog"
import { Loader2, Plus } from "lucide-react"
@@ -41,7 +41,7 @@ export function AssistantRedirect() {
const { data: repo } = useQuery({
queryKey: ["repo", repoId],
queryFn: () => getRepo(repoId),
enabled: showSessionList && !!repoId,
enabled: showSessionList && repoId !== undefined,
})
const handleNavigate = useCallback((sessionId: string) => {
@@ -61,7 +61,7 @@ export function AssistantRedirect() {
const { data: assistantMode, isLoading: assistantModeLoading, error: assistantModeError } = useQuery({
queryKey: ["repo", repoId, "assistant-mode"],
queryFn: () => initializeAssistantMode(repoId),
enabled: showSessionList && !!repoId,
enabled: showSessionList && repoId !== undefined,
})
const assistantDirectory = assistantMode?.directory
@@ -84,11 +84,10 @@ export function AssistantRedirect() {
try {
if (showSessionList) return
setStatus("preparing")
if (!repoId) {
const repos = await listRepos()
const fallbackRepo = repos.sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))[0]
if (!fallbackRepo) throw new Error("No repository available to open Assistant")
navigate(`/repos/${fallbackRepo.id}/assistant`, { replace: true })
if (repoId <= 0) {
if (cancelled) return
setStatus("creating")
await openAssistant()
return
}
@@ -108,13 +107,13 @@ export function AssistantRedirect() {
return () => {
cancelled = true
}
}, [repoId, openAssistant, navigate, showSessionList])
}, [repoId, openAssistant, navigate, showSessionList, id])
if (showSessionList) {
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<Header.BackButton to={`/repos/${repoId}`} />
<Header.BackButton to={getAssistantPath()} />
<Header.Title>Assistant</Header.Title>
<Header.Actions>
<div className="flex items-center gap-1">
@@ -146,7 +145,22 @@ export function AssistantRedirect() {
<>
<FileBrowserSheet isOpen={fileBrowserOpen} onClose={() => setFileBrowserOpen(false)} basePath={assistantFileBasePath} repoName="Assistant" repoId={repoId} />
<RepoMcpDialog open={mcpDialogOpen} onOpenChange={setMcpDialogOpen} directory={assistantDirectory} />
<RepoSkillsDialog open={skillsDialogOpen} onOpenChange={setSkillsDialogOpen} repoId={repoId} />
{assistantDirectory && opcodeUrl ? (
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
sessionId="assistant-session"
opcodeUrl={opcodeUrl}
directory={assistantDirectory}
/>
) : (
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
/>
)}
<SourceControlPanel repoId={repoId} isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} repoDirectory={assistantDirectory} />
</>
@@ -174,7 +188,7 @@ export function AssistantRedirect() {
<>
<p className="text-muted-foreground mb-4">{errorMessage}</p>
<Button
onClick={() => navigate(`/repos/${repoId}`)}
onClick={() => navigate(getAssistantPath())}
variant="outline"
>
Go Back
+12 -17
View File
@@ -1,8 +1,6 @@
import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
import { getRepo } from '@/api/repos'
import {
useCancelRepoScheduleRun,
useCreateRepoSchedule,
@@ -15,6 +13,7 @@ import {
useUpdateRepoSchedule,
} from '@/hooks/useSchedules'
import { useRepoActivity } from '@/hooks/useRepoActivity'
import { useWorkspace } from '@/hooks/useWorkspace'
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
import { useScheduleTab } from '@/hooks/useMobileTabBar'
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
@@ -23,7 +22,7 @@ import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { getRepoDisplayName, cn } from '@/lib/utils'
import { cn } from '@/lib/utils'
import { CalendarClock, Loader2, Plus } from 'lucide-react'
export function Schedules() {
@@ -36,13 +35,9 @@ export function Schedules() {
const [deleteJobId, setDeleteJobId] = useState<number | null>(null)
const { scheduleTab: activeTab, setScheduleTab: setActiveTab } = useScheduleTab()
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId!),
enabled: repoId !== undefined,
})
const { workspace, isLoading: workspaceLoading } = useWorkspace(repoId)
useRepoActivity(repoId ?? 0, Boolean(repo))
useRepoActivity(repoId ?? 0, Boolean(workspace) && workspace?.kind === 'repo')
const { data: jobs, isLoading: jobsLoading } = useRepoSchedules(repoId)
const { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, selectedJobId)
@@ -87,7 +82,7 @@ export function Schedules() {
const activeRun = selectedRunDetails ?? activeRunSummary
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
if (repoLoading || jobsLoading) {
if (workspaceLoading || jobsLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
@@ -95,15 +90,15 @@ export function Schedules() {
)
}
if (!repo || repoId === undefined) {
if (!workspace || repoId === undefined) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">Repository not found</p>
<p className="text-muted-foreground">
{repoId === 0 ? 'Workspace not found' : 'Repository not found'}
</p>
</div>
)
}
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath)
const enabledCount = jobs?.filter((job) => job.enabled).length ?? 0
const hasJobs = (jobs?.length ?? 0) > 0
@@ -197,10 +192,10 @@ export function Schedules() {
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<Header.BackButton to={`/repos/${repoId}`} />
<Header.BackButton to={workspace.backHref} />
<div className="min-w-0 flex-1 px-3">
<Header.Title className="truncate">Schedules</Header.Title>
<p className="text-xs text-muted-foreground truncate">{repoName}</p>
<Header.Title className="truncate">{workspace.name}</Header.Title>
<p className="text-xs text-muted-foreground truncate">{workspace.subtitle}</p>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="h-6 rounded-full px-2 text-xs">{jobs?.length ?? 0} jobs</Badge>
+12 -9
View File
@@ -118,14 +118,14 @@ export function SessionDetail() {
const { data: assistantMode, isLoading: assistantModeLoading } = useQuery({
queryKey: ["repo", repoId, "assistant-mode"],
queryFn: () => initializeAssistantMode(repoId),
enabled: isAssistantSession && !!repoId,
enabled: isAssistantSession,
});
useRepoActivity(repoId, Boolean(repo));
const opcodeUrl = OPENCODE_API_ENDPOINT;
const repoDirectory = isAssistantSession ? assistantMode?.directory : repo?.fullPath;
const repoDirectory = isAssistantSession ? (assistantMode?.directory || repo?.fullPath) : repo?.fullPath;
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId);
@@ -227,7 +227,7 @@ export function SessionDetail() {
const maxScrollTop = container.scrollHeight - container.clientHeight
const isAtBottom = maxScrollTop - currentScrollTop < 24
const isScrollingDown = currentScrollTop > previousScrollTop + 4
const isScrollingUp = currentScrollTop < previousScrollTop - 4
const isScrollingUp = currentScrollTop < previousScrollTop - 50
if (isAtBottom || isScrollingDown) {
setIsHeaderVisible(true)
@@ -438,7 +438,7 @@ export function SessionDetail() {
return <Navigate to="/" replace />;
}
if (!repo) {
if (!repo && !isAssistantSession) {
return (
<div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-background via-background to-background">
<div className="flex flex-col items-center gap-2">
@@ -449,7 +449,9 @@ export function SessionDetail() {
);
}
const workspaceDisplayName = isAssistantSession ? 'Assistant' : getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
const workspaceDisplayName = isAssistantSession || !repo
? 'Assistant'
: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
const sessionBackPath = getSessionListPath(repoId, isAssistantSession);
return (
@@ -457,9 +459,10 @@ export function SessionDetail() {
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col"
>
<div
data-testid="session-header-region"
className={`flex-shrink-0 overflow-hidden bg-background transition-all duration-200 ease-out ${
isHeaderVisible
? 'max-h-40 opacity-100 translate-y-0'
? 'max-h-72 sm:max-h-80 opacity-100 translate-y-0'
: 'max-h-0 opacity-0 -translate-y-2'
}`}
>
@@ -510,7 +513,7 @@ export function SessionDetail() {
</div>
</div>
<div className="flex-1 overflow-hidden flex flex-col">
<div className="relative flex-1 overflow-hidden flex flex-col">
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + 16 }}>
{repoLoading || assistantModeLoading || sessionLoading || messagesLoading ? (
<MessageSkeleton />
@@ -643,7 +646,7 @@ export function SessionDetail() {
directory={repoDirectory}
/>
{repoDirectory && opcodeUrl && sessionId && (
{opcodeUrl && sessionId && (
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
@@ -665,7 +668,7 @@ export function SessionDetail() {
repoId={repoId}
isOpen={sourceControlOpen}
onClose={() => setSourceControlOpen(false)}
currentBranch={repo.currentBranch || repo.branch || "main"}
currentBranch={repo?.currentBranch || repo?.branch || "main"}
repoName={workspaceDisplayName}
/>
@@ -0,0 +1,318 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Schedules } from '../Schedules'
const mocks = vi.hoisted(() => ({
useWorkspace: vi.fn(),
useRepoSchedules: vi.fn(),
useRepoSchedule: vi.fn(),
useRepoScheduleRuns: vi.fn(),
useRepoScheduleRun: vi.fn(),
useCreateRepoSchedule: vi.fn(),
useUpdateRepoSchedule: vi.fn(),
useDeleteRepoSchedule: vi.fn(),
useRunRepoSchedule: vi.fn(),
useCancelRepoScheduleRun: vi.fn(),
useRepoActivity: vi.fn(),
useScheduleTab: vi.fn(),
}))
const mockNavigate = vi.fn()
vi.mock('react-router-dom', async (importOriginal) => ({
...(await importOriginal('react-router-dom')),
useNavigate: () => mockNavigate,
}))
vi.mock('@/hooks/useWorkspace', () => ({
useWorkspace: mocks.useWorkspace,
}))
vi.mock('@/hooks/useSchedules', () => ({
useRepoSchedules: mocks.useRepoSchedules,
useRepoSchedule: mocks.useRepoSchedule,
useRepoScheduleRuns: mocks.useRepoScheduleRuns,
useRepoScheduleRun: mocks.useRepoScheduleRun,
useCreateRepoSchedule: mocks.useCreateRepoSchedule,
useUpdateRepoSchedule: mocks.useUpdateRepoSchedule,
useDeleteRepoSchedule: mocks.useDeleteRepoSchedule,
useRunRepoSchedule: mocks.useRunRepoSchedule,
useCancelRepoScheduleRun: mocks.useCancelRepoScheduleRun,
}))
vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/hooks/useMobileTabBar', () => ({
useScheduleTab: mocks.useScheduleTab,
}))
vi.mock('@/components/schedules', () => ({
ScheduleJobDialog: vi.fn(() => <div>ScheduleJobDialog</div>),
JobsTab: vi.fn(({ onSelectJob }) => (
<div>
<button onClick={() => onSelectJob(123)} data-testid="select-job">Select Job</button>
</div>
)),
JobDetailTab: vi.fn(({ onRunNow }) => (
<div>
<button onClick={onRunNow} data-testid="run-now">Run Now</button>
</div>
)),
RunHistoryTab: vi.fn(() => <div>RunHistoryTab</div>),
ScheduleTabMenu: vi.fn(() => <div>ScheduleTabMenu</div>),
}))
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) =>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
const renderSchedules = (repoId: string) => {
return render(
<MemoryRouter initialEntries={[`/repos/${repoId}/schedules`]}>
<Routes>
<Route path="/repos/:id/schedules" element={<Schedules />} />
</Routes>
</MemoryRouter>,
{ wrapper: createWrapper() }
)
}
describe('Schedules', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useScheduleTab.mockReturnValue({
scheduleTab: 'jobs',
setScheduleTab: vi.fn(),
})
mocks.useCreateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useUpdateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useRunRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useCancelRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false })
})
describe('assistant workspace (repoId=0)', () => {
it('renders assistant title and subtitle', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
expect(screen.getByText('Assistant')).toBeInTheDocument()
expect(screen.getByText('Assistant Workspace')).toBeInTheDocument()
})
it('does not render Repository not found', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
expect(screen.queryByText('Repository not found')).not.toBeInTheDocument()
})
it('renders back button with correct href', () => {
mockNavigate.mockClear()
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
const backButton = screen.getAllByRole('button')[0]
expect(backButton).toBeInTheDocument()
fireEvent.click(backButton)
expect(mockNavigate).toHaveBeenCalledWith('/assistant')
})
it('calls runMutation with repoId=0 when Run Now is clicked', () => {
const mutateMock = vi.fn()
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
const mockJob = {
id: 123,
name: 'Test Job',
repoId: 0,
cronExpression: null,
intervalMinutes: 30,
timezone: 'UTC',
enabled: true,
createdAt: 0,
updatedAt: 0,
scheduleMode: 'interval' as const,
agentSlug: null,
prompt: 'test',
triggerSource: 'manual' as const,
lastRunAt: null,
nextRunAt: null,
skillMetadata: null,
}
mocks.useScheduleTab.mockReturnValue({
scheduleTab: 'detail',
setScheduleTab: vi.fn(),
})
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
mocks.useRunRepoSchedule.mockReturnValue({ mutate: mutateMock, isPending: false })
renderSchedules('0')
const runNowButton = screen.getByTestId('run-now')
runNowButton.click()
expect(mutateMock).toHaveBeenCalledWith({ repoId: 0, jobId: 123 }, expect.any(Object))
})
})
describe('repo workspace (repoId=5)', () => {
it('renders repo name and subtitle', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5')
expect(screen.getByText('my-repo')).toBeInTheDocument()
expect(screen.getByText('repos/my-repo')).toBeInTheDocument()
})
it('renders back button with correct href', () => {
mockNavigate.mockClear()
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5')
const backButton = screen.getAllByRole('button')[0]
expect(backButton).toBeInTheDocument()
fireEvent.click(backButton)
expect(mockNavigate).toHaveBeenCalledWith('/repos/5')
})
})
describe('workspace not found', () => {
it('renders not found fallback for real repo', () => {
mocks.useWorkspace.mockReturnValue({
workspace: undefined,
isLoading: false,
isError: true,
})
mocks.useRepoSchedules.mockReturnValue({ data: undefined, isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('999')
expect(screen.getByText('Repository not found')).toBeInTheDocument()
})
it('renders not found fallback for assistant', () => {
mocks.useWorkspace.mockReturnValue({
workspace: undefined,
isLoading: false,
isError: true,
})
mocks.useRepoSchedules.mockReturnValue({ data: undefined, isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
expect(screen.getByText('Workspace not found')).toBeInTheDocument()
})
})
})
@@ -0,0 +1,274 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { SessionDetail } from '../SessionDetail'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
useMessages: vi.fn(),
useSSE: vi.fn(),
useRepoActivity: vi.fn(),
usePermissions: vi.fn(),
useQuestions: vi.fn(),
useSSEHealth: vi.fn(),
useConfig: vi.fn(),
useOpenCodeClient: vi.fn(),
useSettings: vi.fn(),
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useKeyboardShortcuts: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSidebarAction: vi.fn(),
RepoSkillsDialog: vi.fn(() => null),
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession,
useAbortSession: vi.fn(() => ({ mutate: vi.fn() })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
useMessages: mocks.useMessages,
useConfig: mocks.useConfig,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
}))
vi.mock('@/hooks/useOpenCodeClient', () => ({
useOpenCodeClient: mocks.useOpenCodeClient,
}))
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: vi.fn(() => false),
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
}))
vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
useAutoScroll: vi.fn(() => ({ scrollToBottom: vi.fn() })),
}))
vi.mock('@/hooks/useDialogParam', () => ({
useDialogParam: vi.fn(() => [false, vi.fn()]),
}))
vi.mock('@/hooks/useSidebarAction', () => ({
useSidebarAction: vi.fn(() => {}),
}))
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
getAssistantText: vi.fn(() => ''),
getLatestPlayableAssistantMessage: vi.fn(() => null),
useAutoPlayLastResponse: vi.fn(() => {}),
}))
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn(() => vi.fn()),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
useSessionStatusForSession: vi.fn(() => ({ type: 'idle' })),
}))
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,
useQuestions: mocks.useQuestions,
useSSEHealth: mocks.useSSEHealth,
}
})
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve(null)),
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/abs/assistant', warnings: [] })),
}))
vi.mock('@/components/model/ModelSelectDialog', () => ({
ModelSelectDialog: vi.fn(() => null),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoLspDialog', () => ({
RepoLspDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({
RepoSkillsDialog: mocks.RepoSkillsDialog,
}))
vi.mock('@/components/source-control', () => ({
SourceControlPanel: vi.fn(() => null),
}))
vi.mock('@/components/session/QuestionPrompt', () => ({
QuestionPrompt: vi.fn(() => null),
}))
vi.mock('@/components/session/MinimizedQuestionIndicator', () => ({
MinimizedQuestionIndicator: vi.fn(() => null),
}))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({
PendingActionsGroup: vi.fn(() => null),
}))
describe('SessionDetail assistant loading at repoId=0', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
mocks.useMessages.mockReturnValue({ data: [], isLoading: 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.useQuestions.mockReturnValue({
current: null,
pendingCount: 0,
hasQuestionsForSession: vi.fn(() => false),
reply: vi.fn(),
reject: vi.fn(),
syncForSession: vi.fn(),
})
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useOpenCodeClient.mockReturnValue({})
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSidebarAction.mockReturnValue(undefined)
})
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const renderAssistantSession = (sessionId: string) => {
return render(
<MemoryRouter initialEntries={[`/repos/0/sessions/${sessionId}?assistant=1`]}>
<QueryClientProvider client={createQueryClient()}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
}
it('does not show "Loading repository..." for assistant sessions at repoId=0', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
expect(screen.queryByText('Loading repository...')).not.toBeInTheDocument()
})
})
it('renders "Assistant" as the workspace display name', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
expect(screen.getByText('Assistant')).toBeInTheDocument()
})
})
it('passes directory from assistantMode to RepoSkillsDialog once loaded', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
const lastCall = mocks.RepoSkillsDialog.mock.calls.at(-1)
expect(lastCall).toBeDefined()
expect(lastCall![0].directory).toBe('/abs/assistant')
})
})
it('does not pass empty string for directory when repoDirectory is undefined', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
expect(mocks.RepoSkillsDialog).toHaveBeenCalled()
})
mocks.RepoSkillsDialog.mock.calls.forEach(([props]) => {
expect(props.directory).not.toBe('')
})
})
it('renders "Assistant" as workspaceDisplayName for non-assistant sessions without repo', async () => {
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
return render(
<MemoryRouter initialEntries={['/repos/1/sessions/sess-1']}>
<QueryClientProvider client={createQueryClient()}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
})
})
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { renderHook } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useQuery } from '@tanstack/react-query'
@@ -51,10 +51,8 @@ describe('SessionDetail pending-actions polling', () => {
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(30000)
await waitFor(() => {
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(2)
})
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(2)
vi.useRealTimers()
})
@@ -0,0 +1,330 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import type { Todo } from '@/components/message/SessionTodoDisplay'
import { SessionDetail } from '../SessionDetail'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
useMessages: vi.fn(),
useSSE: vi.fn(),
useRepoActivity: vi.fn(),
usePermissions: vi.fn(),
useQuestions: vi.fn(),
useSSEHealth: vi.fn(),
useConfig: vi.fn(),
useOpenCodeClient: vi.fn(),
useSettings: vi.fn(),
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useKeyboardShortcuts: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSidebarAction: vi.fn(),
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession,
useAbortSession: vi.fn(() => ({ mutate: vi.fn() })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
useMessages: mocks.useMessages,
useConfig: mocks.useConfig,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
}))
vi.mock('@/hooks/useOpenCodeClient', () => ({
useOpenCodeClient: mocks.useOpenCodeClient,
}))
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: vi.fn(() => false),
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
}))
vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
useAutoScroll: vi.fn(() => ({ scrollToBottom: vi.fn() })),
}))
vi.mock('@/hooks/useDialogParam', () => ({
useDialogParam: vi.fn(() => [false, vi.fn()]),
}))
vi.mock('@/hooks/useSidebarAction', () => ({
useSidebarAction: vi.fn(() => {}),
}))
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
getAssistantText: vi.fn(() => ''),
getLatestPlayableAssistantMessage: vi.fn(() => null),
useAutoPlayLastResponse: vi.fn(() => {}),
}))
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn(() => vi.fn()),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
useSessionStatusForSession: vi.fn(() => ({ type: 'idle' })),
}))
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,
useQuestions: mocks.useQuestions,
useSSEHealth: mocks.useSSEHealth,
}
})
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/model/ModelSelectDialog', () => ({
ModelSelectDialog: vi.fn(() => null),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoLspDialog', () => ({
RepoLspDialog: 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/QuestionPrompt', () => ({
QuestionPrompt: vi.fn(() => null),
}))
vi.mock('@/components/session/MinimizedQuestionIndicator', () => ({
MinimizedQuestionIndicator: vi.fn(() => null),
}))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({
PendingActionsGroup: vi.fn(() => null),
}))
const activeTodos: Todo[] = [
{ id: '1', content: 'Implement mobile header fix', status: 'in_progress', priority: 'high' },
{ id: '2', content: 'Add regression tests', status: 'pending', priority: 'medium' },
{ id: '3', content: 'Verify completed item grouping', status: 'completed', priority: 'low' },
]
describe('SessionDetail todo-header integration', () => {
beforeEach(() => {
vi.clearAllMocks()
useSessionTodos.setState({ todos: new Map() })
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
mocks.useMessages.mockReturnValue({ data: [], isLoading: 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.useQuestions.mockReturnValue({
current: null,
pendingCount: 0,
hasQuestionsForSession: vi.fn(() => false),
reply: vi.fn(),
reject: vi.fn(),
syncForSession: vi.fn(),
})
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useOpenCodeClient.mockReturnValue({})
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSidebarAction.mockReturnValue(undefined)
})
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const renderSessionDetail = (sessionId: string, repoId: number) => {
return render(
<MemoryRouter initialEntries={[`/repos/${repoId}/sessions/${sessionId}`]}>
<QueryClientProvider client={createQueryClient()}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
}
it('renders SessionTodoDisplay collapsed by default inside SessionDetail header', async () => {
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
})
expect(screen.queryByText('Implement mobile header fix')).not.toBeInTheDocument()
})
it('expands todo list when clicked inside SessionDetail header', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
})
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByText('Implement mobile header fix')).toBeInTheDocument()
expect(screen.getByText('Add regression tests')).toBeInTheDocument()
const expandedContainer = screen.getByTestId('todo-expanded-list')
expect(expandedContainer).toHaveClass('max-h-[80px]')
expect(expandedContainer).toHaveClass('sm:max-h-[160px]')
expect(expandedContainer).toHaveClass('overflow-y-auto')
})
it('header wrapper uses max-h-72 sm:max-h-80 and overflow-hidden for proper containment', async () => {
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByTestId('session-header-region')).toBeInTheDocument()
})
const headerRegion = screen.getByTestId('session-header-region')
expect(headerRegion.className).toContain('max-h-72')
expect(headerRegion.className).toContain('sm:max-h-80')
expect(headerRegion.className).toContain('overflow-hidden')
expect(headerRegion.className).not.toContain('max-h-40')
})
it('collapses todo list when expanded header is clicked again', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
})
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByTestId('todo-expanded-list')).toBeInTheDocument()
const expandedHeader = screen.getByText('Tasks: 1/3 complete')
await user.click(expandedHeader)
expect(screen.queryByTestId('todo-expanded-list')).not.toBeInTheDocument()
})
it('does not render SessionTodoDisplay when all tasks are completed', async () => {
const allCompletedTodos: Todo[] = [
{ id: '1', content: 'Task one', status: 'completed', priority: 'high' },
{ id: '2', content: 'Task two', status: 'completed', priority: 'medium' },
]
useSessionTodos.getState().setTodos('session-1', allCompletedTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
const headerRegion = screen.getByTestId('session-header-region')
expect(headerRegion).toBeInTheDocument()
})
expect(screen.queryByText(/Tasks:/)).not.toBeInTheDocument()
})
})