mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Frontend chat API, hooks and the chat session page
This commit is contained in:
1 parent
3c064e4b60
commit
275483f5e9
15 files changed
+1140
-110
No files matched your search
@@ -341,6 +341,11 @@ const router = createBrowserRouter([
|
||||
element: <SessionDetail />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/chats/:chatId/sessions/:sessionId',
|
||||
element: <SessionDetail />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id/schedules',
|
||||
element: <Schedules />,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type {
|
||||
Chat,
|
||||
CreateChatRequest,
|
||||
CreateChatResponse,
|
||||
DeleteChatSessionResponse,
|
||||
ListChatsResponse,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export async function listChats(input: {
|
||||
limit: number
|
||||
cursor?: string
|
||||
}): Promise<ListChatsResponse> {
|
||||
return fetchWrapper<ListChatsResponse>(`${API_BASE_URL}/api/chats`, {
|
||||
params: { limit: input.limit, cursor: input.cursor },
|
||||
})
|
||||
}
|
||||
|
||||
export async function getChat(chatId: string): Promise<Chat> {
|
||||
return fetchWrapper<Chat>(`${API_BASE_URL}/api/chats/${encodeURIComponent(chatId)}`)
|
||||
}
|
||||
|
||||
export async function createChat(input: CreateChatRequest): Promise<CreateChatResponse> {
|
||||
return fetchWrapper<CreateChatResponse>(`${API_BASE_URL}/api/chats`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteChatSession(
|
||||
chatId: string,
|
||||
sessionId: string,
|
||||
): Promise<DeleteChatSessionResponse> {
|
||||
return fetchWrapper<DeleteChatSessionResponse>(
|
||||
`${API_BASE_URL}/api/chats/${encodeURIComponent(chatId)}/sessions/${encodeURIComponent(sessionId)}`,
|
||||
{ method: 'DELETE' },
|
||||
)
|
||||
}
|
||||
@@ -50,6 +50,7 @@ function getBaseItems(): MoreDrawerItem[] {
|
||||
const SESSION_DETAIL_PATH = /^\/repos\/(\d+)\/sessions\/[^/]+$/
|
||||
const SERVER_SESSION_DETAIL_PATH = /^\/servers\/[^/]+\/sessions\/[^/]+$/
|
||||
const SERVER_PROJECT_PATH = /^\/servers\/[^/]+\/projects$/
|
||||
const CHAT_SESSION_DETAIL_PATH = /^\/chats\/[^/]+\/sessions\/[^/]+$/
|
||||
|
||||
export function isSessionDetailPath(pathname: string): boolean {
|
||||
return SESSION_DETAIL_PATH.test(pathname)
|
||||
@@ -178,6 +179,18 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
}
|
||||
}
|
||||
|
||||
if (CHAT_SESSION_DETAIL_PATH.test(pathname)) {
|
||||
return {
|
||||
primary: [getAssistantNavItem()],
|
||||
items: [
|
||||
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
|
||||
...baseItems,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
primary: [getAssistantNavItem()],
|
||||
items: baseItems,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react'
|
||||
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { SessionDetailsSheet, type SessionDetailsSheetProps } from './SessionDetailsSheet'
|
||||
@@ -250,4 +250,21 @@ describe('SessionDetailsSheet', () => {
|
||||
expect(screen.getByRole('dialog')).toHaveAccessibleName('Session details')
|
||||
expect(screen.getByText('feat/header')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('confirms the optional delete action', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onDeleteSession = vi.fn(() => Promise.resolve())
|
||||
renderSheet({ onDeleteSession })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete chat session' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }))
|
||||
|
||||
await waitFor(() => expect(onDeleteSession).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it('omits the delete action without a delete handler', () => {
|
||||
renderSheet()
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Delete chat session' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { Server } from 'lucide-react'
|
||||
import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -16,6 +17,8 @@ export interface SessionDetailsSheetProps {
|
||||
branch?: string | null
|
||||
directory?: string
|
||||
onRename: (title: string) => Promise<void>
|
||||
/** Deletes the open session, when the caller supports it. */
|
||||
onDeleteSession?: () => Promise<void>
|
||||
}
|
||||
|
||||
interface InfoRowProps {
|
||||
@@ -49,12 +52,16 @@ export function SessionDetailsSheet({
|
||||
branch,
|
||||
directory,
|
||||
onRename,
|
||||
onDeleteSession,
|
||||
}: SessionDetailsSheetProps) {
|
||||
const isMobile = useMobile()
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [draft, setDraft] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [renameFailed, setRenameFailed] = useState(false)
|
||||
const [deleteOpen, setDeleteOpen] = useState(false)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [deleteFailed, setDeleteFailed] = useState(false)
|
||||
const [lastOpen, setLastOpen] = useState(open)
|
||||
|
||||
if (open !== lastOpen) {
|
||||
@@ -62,6 +69,9 @@ export function SessionDetailsSheet({
|
||||
if (open) {
|
||||
setEditing(false)
|
||||
setRenameFailed(false)
|
||||
setDeleteFailed(false)
|
||||
} else {
|
||||
setDeleteOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +116,21 @@ export function SessionDetailsSheet({
|
||||
onOpenChange(true)
|
||||
}
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!onDeleteSession) return
|
||||
setDeleting(true)
|
||||
setDeleteFailed(false)
|
||||
try {
|
||||
await onDeleteSession()
|
||||
setDeleteOpen(false)
|
||||
onOpenChange(false)
|
||||
} catch {
|
||||
setDeleteFailed(true)
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const body = (
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
@@ -175,31 +200,63 @@ export function SessionDetailsSheet({
|
||||
<InfoRow label="Project" value={project} />
|
||||
{branch ? <InfoRow label="Branch" value={branch} mono /> : null}
|
||||
{directory ? <InfoRow label="Directory" value={directory} mono /> : null}
|
||||
{onDeleteSession ? (
|
||||
<div className="flex flex-col gap-2 border-t border-border pt-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
className="self-start"
|
||||
>
|
||||
Delete chat session
|
||||
</Button>
|
||||
{deleteFailed && (
|
||||
<span className="text-xs text-destructive">Delete failed</span>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
|
||||
const deleteDialog = onDeleteSession ? (
|
||||
<DeleteSessionDialog
|
||||
open={deleteOpen}
|
||||
onOpenChange={setDeleteOpen}
|
||||
onConfirm={() => { void confirmDelete() }}
|
||||
onCancel={() => setDeleteOpen(false)}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
) : null
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<BottomSheet
|
||||
isOpen={open}
|
||||
onClose={handleClose}
|
||||
ariaLabel="Session details"
|
||||
dismissible={!saving}
|
||||
>
|
||||
<BottomSheetHeader title="Session details" />
|
||||
<BottomSheetContent>{body}</BottomSheetContent>
|
||||
</BottomSheet>
|
||||
<>
|
||||
<BottomSheet
|
||||
isOpen={open}
|
||||
onClose={handleClose}
|
||||
ariaLabel="Session details"
|
||||
dismissible={!saving}
|
||||
>
|
||||
<BottomSheetHeader title="Session details" />
|
||||
<BottomSheetContent>{body}</BottomSheetContent>
|
||||
</BottomSheet>
|
||||
{deleteDialog}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Session details</DialogTitle>
|
||||
</DialogHeader>
|
||||
{body}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Session details</DialogTitle>
|
||||
</DialogHeader>
|
||||
{body}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{deleteDialog}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -30,7 +30,7 @@ import type { Repo } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
import { getServerSessionPath, getSessionPath, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from '@/lib/navigation'
|
||||
import { getServerSessionPath, getSessionPath, parseChatSessionRoute, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from '@/lib/navigation'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { repoMatchesDirectory } from '@/components/navigation/sidebar-session-tree'
|
||||
import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough'
|
||||
@@ -451,7 +451,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [location.pathname, location.search])
|
||||
|
||||
const viewedSessionId = useMemo(
|
||||
() => parseServerSessionRoute(location.pathname)?.sessionId ?? parseRepoRoute(location.pathname).sessionId,
|
||||
() => parseServerSessionRoute(location.pathname)?.sessionId ?? parseChatSessionRoute(location.pathname)?.sessionId ?? parseRepoRoute(location.pathname).sessionId,
|
||||
[location.pathname],
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Chat } from '@opencode-manager/shared/schemas'
|
||||
import type { Session } from '@/api/types'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import {
|
||||
useChat,
|
||||
useChatFolders,
|
||||
useChatSessions,
|
||||
useCreateChat,
|
||||
useDeleteChatSession,
|
||||
} from './useChats'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listChats: vi.fn(),
|
||||
getChat: vi.fn(),
|
||||
createChat: vi.fn(),
|
||||
deleteChatSession: vi.fn(),
|
||||
useSessionsAcrossDirectories: vi.fn(),
|
||||
removeDeletedSessionsFromListCaches: vi.fn(),
|
||||
cleanupSessionPins: vi.fn(),
|
||||
useSessionPins: vi.fn(),
|
||||
showToast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/chats', () => ({
|
||||
listChats: mocks.listChats,
|
||||
getChat: mocks.getChat,
|
||||
createChat: mocks.createChat,
|
||||
deleteChatSession: mocks.deleteChatSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useSessionsAcrossDirectories: mocks.useSessionsAcrossDirectories,
|
||||
removeDeletedSessionsFromListCaches: mocks.removeDeletedSessionsFromListCaches,
|
||||
cleanupSessionPins: mocks.cleanupSessionPins,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSessionPins', () => ({
|
||||
useSessionPins: mocks.useSessionPins,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: mocks.showToast,
|
||||
}))
|
||||
|
||||
const chat = (id: string, directory: string): Chat => ({
|
||||
id,
|
||||
directory,
|
||||
filesPath: `${directory}/files`,
|
||||
createdAt: 1000,
|
||||
})
|
||||
|
||||
const session = (id: string, directory: string, updated: number): Session => ({
|
||||
id,
|
||||
projectID: 'proj_1',
|
||||
title: `Session ${id}`,
|
||||
time: { created: updated, updated },
|
||||
location: { directory },
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
|
||||
const createQueryClient = () => new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
|
||||
const createWrapper = (queryClient: QueryClient) => {
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('useChatFolders', () => {
|
||||
beforeEach(() => {
|
||||
mocks.listChats.mockReset()
|
||||
})
|
||||
|
||||
it('pages chats and flattens pages in order', async () => {
|
||||
mocks.listChats.mockImplementation(async ({ cursor }: { cursor?: string }) => {
|
||||
if (cursor === 'cursor_2') {
|
||||
return { chats: [chat('20240101100000-bbbbbb', '/chats/old')] }
|
||||
}
|
||||
return {
|
||||
chats: [
|
||||
chat('20240102120000-aaaaaa', '/chats/new'),
|
||||
chat('20240102110000-cccccc', '/chats/mid'),
|
||||
],
|
||||
nextCursor: 'cursor_2',
|
||||
}
|
||||
})
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(() => useChatFolders(2), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false))
|
||||
|
||||
expect(result.current.chats.map((entry) => entry.id)).toEqual([
|
||||
'20240102120000-aaaaaa',
|
||||
'20240102110000-cccccc',
|
||||
])
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.fetchNextPage()
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.chats).toHaveLength(3))
|
||||
|
||||
expect(result.current.chats.map((entry) => entry.id)).toEqual([
|
||||
'20240102120000-aaaaaa',
|
||||
'20240102110000-cccccc',
|
||||
'20240101100000-bbbbbb',
|
||||
])
|
||||
expect(mocks.listChats).toHaveBeenLastCalledWith({ limit: 2, cursor: 'cursor_2' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('useChatSessions', () => {
|
||||
beforeEach(() => {
|
||||
mocks.listChats.mockReset()
|
||||
mocks.useSessionsAcrossDirectories.mockReset()
|
||||
mocks.useSessionPins.mockReset()
|
||||
mocks.useSessionsAcrossDirectories.mockReturnValue({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
})
|
||||
mocks.useSessionPins.mockReturnValue({ data: [] })
|
||||
})
|
||||
|
||||
it('orders rows by folder then update time, keeps pinned first, drops archived sessions', async () => {
|
||||
const now = Date.now()
|
||||
const newestChat = chat('20240102120000-aaaaaa', '/chats/new')
|
||||
const olderChat = chat('20240101100000-bbbbbb', '/chats/old')
|
||||
mocks.listChats.mockResolvedValue({ chats: [newestChat, olderChat] })
|
||||
|
||||
const archived = session('ses_archived', '/chats/new', now - 500)
|
||||
archived.time.archived = now - 500
|
||||
mocks.useSessionsAcrossDirectories.mockReturnValue({
|
||||
data: [
|
||||
session('ses_new_older', '/chats/new', now - 3000),
|
||||
session('ses_old_pinned', '/chats/old', now - 4000),
|
||||
session('ses_new_newer', '/chats/new', now - 1000),
|
||||
session('ses_old_unpinned', '/chats/old', now - 500),
|
||||
archived,
|
||||
session('ses_unrelated', '/chats/other', now - 1000),
|
||||
],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
})
|
||||
mocks.useSessionPins.mockReturnValue({
|
||||
data: [{ sessionId: 'ses_old_pinned', directory: '/chats/old', pinnedAt: now }],
|
||||
})
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(() => useChatSessions(2), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.rows).toHaveLength(4))
|
||||
|
||||
expect(result.current.rows.map((row) => row.session.id)).toEqual([
|
||||
'ses_old_pinned',
|
||||
'ses_new_newer',
|
||||
'ses_new_older',
|
||||
'ses_old_unpinned',
|
||||
])
|
||||
expect(mocks.useSessionsAcrossDirectories).toHaveBeenCalledWith(['/chats/new', '/chats/old'])
|
||||
|
||||
const pinnedRow = result.current.rows[0]
|
||||
expect(pinnedRow.isPinned).toBe(true)
|
||||
expect(pinnedRow.chat.id).toBe(olderChat.id)
|
||||
expect(pinnedRow.path).toBe(`/chats/${olderChat.id}/sessions/ses_old_pinned`)
|
||||
expect(result.current.rows[1].isPinned).toBe(false)
|
||||
expect(result.current.rows[1].path).toBe(`/chats/${newestChat.id}/sessions/ses_new_newer`)
|
||||
expect(result.current.chats.map((entry) => entry.id)).toEqual([newestChat.id, olderChat.id])
|
||||
expect(result.current.hasMore).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCreateChat', () => {
|
||||
beforeEach(() => {
|
||||
mocks.createChat.mockReset()
|
||||
mocks.showToast.success.mockReset()
|
||||
mocks.showToast.error.mockReset()
|
||||
})
|
||||
|
||||
it('creates the chat, invalidates caches and reports the built session path', async () => {
|
||||
const createdChat = chat('20240102120000-aaaaaa', '/chats/new')
|
||||
mocks.createChat.mockResolvedValue({ chat: createdChat, sessionId: 'ses_new' })
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const sessionsKey = ['opencode', 'sessions', '/chats/new', {}]
|
||||
const chatsKey = ['chats', 10]
|
||||
queryClient.setQueryData(sessionsKey, { pages: [], pageParams: [] })
|
||||
queryClient.setQueryData(chatsKey, { pages: [], pageParams: [] })
|
||||
|
||||
const onCreated = vi.fn()
|
||||
const { result } = renderHook(() => useCreateChat(onCreated), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ title: 'New chat' })
|
||||
})
|
||||
|
||||
expect(mocks.createChat).toHaveBeenCalledWith({ title: 'New chat' })
|
||||
expect(onCreated).toHaveBeenCalledWith(`/chats/${createdChat.id}/sessions/ses_new`)
|
||||
|
||||
await waitFor(() => expect(queryClient.getQueryState(chatsKey)?.isInvalidated).toBe(true))
|
||||
await waitFor(() => expect(queryClient.getQueryState(sessionsKey)?.isInvalidated).toBe(true))
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDeleteChatSession', () => {
|
||||
beforeEach(() => {
|
||||
mocks.deleteChatSession.mockReset()
|
||||
mocks.removeDeletedSessionsFromListCaches.mockReset()
|
||||
mocks.cleanupSessionPins.mockReset()
|
||||
mocks.showToast.success.mockReset()
|
||||
mocks.showToast.error.mockReset()
|
||||
})
|
||||
|
||||
it('deletes the session, updates list caches and shows a success toast', async () => {
|
||||
mocks.deleteChatSession.mockResolvedValue({ deleted: true, folderRemoved: false })
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const chatsKey = ['chats', 10]
|
||||
queryClient.setQueryData(chatsKey, { pages: [], pageParams: [] })
|
||||
|
||||
const { result } = renderHook(() => useDeleteChatSession(), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({
|
||||
chatId: '20240102120000-aaaaaa',
|
||||
sessionId: 'ses_new',
|
||||
directory: '/chats/new',
|
||||
})
|
||||
})
|
||||
|
||||
expect(mocks.deleteChatSession).toHaveBeenCalledWith('20240102120000-aaaaaa', 'ses_new')
|
||||
expect(mocks.removeDeletedSessionsFromListCaches).toHaveBeenCalledWith(queryClient, 'ses_new')
|
||||
expect(mocks.cleanupSessionPins).toHaveBeenCalledWith(
|
||||
queryClient,
|
||||
{ id: 'ses_new', directory: '/chats/new' },
|
||||
'/chats/new',
|
||||
)
|
||||
expect(mocks.showToast.success).toHaveBeenCalledWith('Chat deleted')
|
||||
await waitFor(() => expect(queryClient.getQueryState(chatsKey)?.isInvalidated).toBe(true))
|
||||
})
|
||||
})
|
||||
|
||||
describe('useChat', () => {
|
||||
beforeEach(() => {
|
||||
mocks.getChat.mockReset()
|
||||
})
|
||||
|
||||
it('resolves a missing chat to null', async () => {
|
||||
mocks.getChat.mockRejectedValue(new FetchError('Chat not found', 404))
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(() => useChat('20240102120000-aaaaaa'), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false))
|
||||
|
||||
expect(result.current.data).toBeNull()
|
||||
expect(mocks.getChat).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useMemo } from 'react'
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query'
|
||||
import type { Chat, CreateChatRequest } from '@opencode-manager/shared/schemas'
|
||||
import { buildChatSessionPath } from '@opencode-manager/shared/utils'
|
||||
import { createChat, deleteChatSession, getChat, listChats } from '@/api/chats'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import type { Session } from '@/api/types'
|
||||
import {
|
||||
cleanupSessionPins,
|
||||
removeDeletedSessionsFromListCaches,
|
||||
useSessionsAcrossDirectories,
|
||||
} from '@/hooks/useOpenCode'
|
||||
import { useSessionPins } from '@/hooks/useSessionPins'
|
||||
import { invalidateSessionListCaches } from '@/lib/queryInvalidation'
|
||||
import { parseNetworkError } from '@/lib/opencode-errors'
|
||||
import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey'
|
||||
import { partitionSessions } from '@/components/session/session-partition'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
const EMPTY_CHATS: Chat[] = []
|
||||
|
||||
/** A session of a loaded chat folder, ready to render in the chat list. */
|
||||
export interface ChatSessionRow {
|
||||
key: string
|
||||
session: Session
|
||||
chat: Chat
|
||||
path: string
|
||||
isPinned: boolean
|
||||
}
|
||||
|
||||
/** Paginated chat folders, newest first. */
|
||||
export function useChatFolders(pageSize = 10) {
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: ['chats', pageSize],
|
||||
queryFn: ({ pageParam }) => listChats({ limit: pageSize, cursor: pageParam }),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
})
|
||||
|
||||
const chats = useMemo(
|
||||
() => query.data?.pages.flatMap((page) => page.chats) ?? EMPTY_CHATS,
|
||||
[query.data],
|
||||
)
|
||||
|
||||
return {
|
||||
chats,
|
||||
fetchNextPage: query.fetchNextPage,
|
||||
hasNextPage: query.hasNextPage,
|
||||
isFetchingNextPage: query.isFetchingNextPage,
|
||||
isLoading: query.isLoading,
|
||||
isError: query.isError,
|
||||
error: query.error,
|
||||
}
|
||||
}
|
||||
|
||||
/** Root sessions of loaded chat folders, ordered and partitioned for the chat list. */
|
||||
export function useChatSessions(pageSize = 10) {
|
||||
const folders = useChatFolders(pageSize)
|
||||
const chats = folders.chats
|
||||
const directories = useMemo(() => chats.map((chat) => chat.directory), [chats])
|
||||
const sessions = useSessionsAcrossDirectories(directories)
|
||||
const { data: pins = [] } = useSessionPins()
|
||||
|
||||
const rows = useMemo<ChatSessionRow[]>(() => {
|
||||
const chatsByDirectory = new Map<string, { chat: Chat; order: number }>()
|
||||
chats.forEach((chat, order) => {
|
||||
if (!chatsByDirectory.has(chat.directory)) {
|
||||
chatsByDirectory.set(chat.directory, { chat, order })
|
||||
}
|
||||
})
|
||||
|
||||
const pinnedKeys = buildPinnedSessionKeys(pins)
|
||||
const ordered = sessions.data
|
||||
.flatMap((session) => {
|
||||
if (session.parentID || session.time.archived) return []
|
||||
const entry = chatsByDirectory.get(session.location.directory)
|
||||
return entry ? [{ session, order: entry.order }] : []
|
||||
})
|
||||
.sort((a, b) => a.order - b.order || b.session.time.updated - a.session.time.updated)
|
||||
.map((entry) => entry.session)
|
||||
|
||||
const partitioned = partitionSessions(ordered, pinnedKeys, getSessionKey)
|
||||
const pinnedSessionKeys = new Set(partitioned.pinned.map(getSessionKey))
|
||||
const orderedRows = [
|
||||
...partitioned.pinned,
|
||||
...ordered.filter((session) => !pinnedSessionKeys.has(getSessionKey(session))),
|
||||
]
|
||||
|
||||
return orderedRows.flatMap((session) => {
|
||||
const entry = chatsByDirectory.get(session.location.directory)
|
||||
if (!entry) return []
|
||||
const key = getSessionKey(session)
|
||||
return [{
|
||||
key,
|
||||
session,
|
||||
chat: entry.chat,
|
||||
path: buildChatSessionPath(entry.chat.id, session.id),
|
||||
isPinned: pinnedKeys.has(key),
|
||||
}]
|
||||
})
|
||||
}, [chats, pins, sessions.data])
|
||||
|
||||
return {
|
||||
rows,
|
||||
chats,
|
||||
hasMore: Boolean(folders.hasNextPage),
|
||||
showMore: folders.fetchNextPage,
|
||||
isLoading: folders.isLoading || sessions.isLoading,
|
||||
isError: folders.isError || sessions.isError,
|
||||
error: folders.error ?? sessions.error,
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates a chat folder and navigates to its first session through `onCreated`. */
|
||||
export function useCreateChat(onCreated?: (path: string) => void) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (input?: CreateChatRequest) => createChat(input ?? {}),
|
||||
onSuccess: (response) => {
|
||||
invalidateSessionListCaches(queryClient)
|
||||
void queryClient.invalidateQueries({ queryKey: ['chats'] })
|
||||
onCreated?.(buildChatSessionPath(response.chat.id, response.sessionId))
|
||||
},
|
||||
onError: (error) => {
|
||||
const parsed = parseNetworkError(error)
|
||||
showToast.error(parsed.title, {
|
||||
description: parsed.message,
|
||||
duration: 5000,
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Deletes one session from a chat folder and removes it from list and pin caches. */
|
||||
export function useDeleteChatSession() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (variables: { chatId: string; sessionId: string; directory?: string }) =>
|
||||
deleteChatSession(variables.chatId, variables.sessionId),
|
||||
onSuccess: (_response, variables) => {
|
||||
removeDeletedSessionsFromListCaches(queryClient, variables.sessionId)
|
||||
cleanupSessionPins(
|
||||
queryClient,
|
||||
variables.directory
|
||||
? { id: variables.sessionId, directory: variables.directory }
|
||||
: variables.sessionId,
|
||||
variables.directory,
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey: ['chats'] })
|
||||
showToast.success('Chat deleted')
|
||||
},
|
||||
onError: () => {
|
||||
invalidateSessionListCaches(queryClient)
|
||||
showToast.error('Failed to delete chat')
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Reads one chat folder, resolving a missing chat to `null`. */
|
||||
export function useChat(chatId?: string) {
|
||||
return useQuery({
|
||||
queryKey: ['chats', 'item', chatId],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return await getChat(chatId!)
|
||||
} catch (error) {
|
||||
if (error instanceof FetchError && error.statusCode === 404) return null
|
||||
throw error
|
||||
}
|
||||
},
|
||||
enabled: !!chatId,
|
||||
retry: (failureCount, error) =>
|
||||
!(error instanceof FetchError && error.statusCode === 404) && failureCount < 3,
|
||||
})
|
||||
}
|
||||
@@ -362,7 +362,7 @@ export const useDeleteSession = (directory?: string | string[]) => {
|
||||
});
|
||||
};
|
||||
|
||||
const removeDeletedSessionsFromListCaches = (
|
||||
export const removeDeletedSessionsFromListCaches = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
) => {
|
||||
@@ -386,7 +386,7 @@ const removeDeletedSessionsFromListCaches = (
|
||||
);
|
||||
};
|
||||
|
||||
const cleanupSessionPins = (
|
||||
export const cleanupSessionPins = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
primaryDirectory?: string,
|
||||
|
||||
@@ -3,11 +3,13 @@ import { useLocation, useMatch } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { isAssistantPath, parseRepoRoute } from '@/lib/navigation'
|
||||
import { isAssistantPath, parseChatSessionRoute, parseRepoRoute } from '@/lib/navigation'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
|
||||
function isLocalRoute(pathname: string): boolean {
|
||||
return parseRepoRoute(pathname).repoId !== null || isAssistantPath(pathname)
|
||||
return parseRepoRoute(pathname).repoId !== null
|
||||
|| isAssistantPath(pathname)
|
||||
|| parseChatSessionRoute(pathname) !== null
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerProjectPath, getServerSessionPath, getSessionPath, isSessionDetailRoute, parseActivePickerSession, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation';
|
||||
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerProjectPath, getServerSessionPath, getSessionPath, getChatSessionPath, isSessionDetailRoute, parseActivePickerSession, parseChatSessionRoute, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation';
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas';
|
||||
|
||||
describe('getAssistantPath', () => {
|
||||
@@ -103,6 +103,15 @@ describe('linked server paths', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getChatSessionPath', () => {
|
||||
it('builds a chat session path with encoded segments', () => {
|
||||
expect(getChatSessionPath('20260101-120000-abcdef', 'ses_1')).toBe(
|
||||
'/chats/20260101-120000-abcdef/sessions/ses_1'
|
||||
);
|
||||
expect(getChatSessionPath('chat a/b', 'ses 1')).toBe('/chats/chat%20a%2Fb/sessions/ses%201');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRepoPath', () => {
|
||||
it('routes the assistant repo to the assistant page and others to their repo page', () => {
|
||||
expect(getRepoPath(0)).toBe('/assistant');
|
||||
@@ -192,6 +201,36 @@ describe('parseServerSessionRoute', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseChatSessionRoute', () => {
|
||||
it('parses a chat session route', () => {
|
||||
expect(parseChatSessionRoute('/chats/20260101-120000-abcdef/sessions/ses_1')).toEqual({
|
||||
chatId: '20260101-120000-abcdef',
|
||||
sessionId: 'ses_1',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null for other routes', () => {
|
||||
expect(parseChatSessionRoute('/chats/20260101-120000-abcdef')).toBeNull();
|
||||
expect(parseChatSessionRoute('/repos/5/sessions/ses_1')).toBeNull();
|
||||
expect(parseChatSessionRoute('/servers/srv_kitchen/sessions/ses_1')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for a malformed chat id segment', () => {
|
||||
expect(parseChatSessionRoute('/chats/%E0%A4%A/sessions/ses_1')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for a malformed session id segment', () => {
|
||||
expect(parseChatSessionRoute('/chats/20260101-120000-abcdef/sessions/%E0%A4%A')).toBeNull();
|
||||
});
|
||||
|
||||
it('decodes valid encoded segments', () => {
|
||||
expect(parseChatSessionRoute('/chats/chat%20a%2Fb/sessions/ses%201')).toEqual({
|
||||
chatId: 'chat a/b',
|
||||
sessionId: 'ses 1',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseActivePickerSession', () => {
|
||||
it('reads a local session route on the local server', () => {
|
||||
expect(parseActivePickerSession('/repos/5/sessions/ses_1')).toEqual({
|
||||
@@ -200,6 +239,13 @@ describe('parseActivePickerSession', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('reads a chat session route on the local server', () => {
|
||||
expect(parseActivePickerSession('/chats/20260101-120000-abcdef/sessions/ses_1')).toEqual({
|
||||
sessionId: 'ses_1',
|
||||
serverId: LOCAL_OPENCODE_SERVER_ID,
|
||||
});
|
||||
});
|
||||
|
||||
it('reads a linked-server session route on its own server', () => {
|
||||
expect(parseActivePickerSession('/servers/srv_kitchen/sessions/ses_1')).toEqual({
|
||||
sessionId: 'ses_1',
|
||||
@@ -210,6 +256,7 @@ describe('parseActivePickerSession', () => {
|
||||
it('returns no session outside a session route', () => {
|
||||
expect(parseActivePickerSession('/repos/5')).toEqual({});
|
||||
expect(parseActivePickerSession('/servers/srv_kitchen/projects')).toEqual({});
|
||||
expect(parseActivePickerSession('/chats/20260101-120000-abcdef')).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -239,6 +286,11 @@ describe('isSessionDetailRoute', () => {
|
||||
expect(isSessionDetailRoute('/servers/https%3A%2F%2Fhost/sessions/ses_abc')).toBe(true);
|
||||
});
|
||||
|
||||
it('matches chat session detail routes', () => {
|
||||
expect(isSessionDetailRoute('/chats/20260101-120000-abcdef/sessions/ses_abc')).toBe(true);
|
||||
expect(isSessionDetailRoute('/chats/20260101-120000-abcdef/sessions/ses_abc/')).toBe(true);
|
||||
});
|
||||
|
||||
it('matches trailing-slash session detail routes', () => {
|
||||
expect(isSessionDetailRoute('/repos/42/sessions/abc/')).toBe(true);
|
||||
expect(isSessionDetailRoute('/servers/srv_kitchen/sessions/ses_abc/')).toBe(true);
|
||||
@@ -249,6 +301,7 @@ describe('isSessionDetailRoute', () => {
|
||||
expect(isSessionDetailRoute('/repos/42')).toBe(false);
|
||||
expect(isSessionDetailRoute('/servers/srv_kitchen/projects')).toBe(false);
|
||||
expect(isSessionDetailRoute('/servers/srv_kitchen/sessions')).toBe(false);
|
||||
expect(isSessionDetailRoute('/chats/20260101-120000-abcdef')).toBe(false);
|
||||
expect(isSessionDetailRoute('/assistant')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -316,6 +369,12 @@ describe('getSwipeBackTarget', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('chat routes', () => {
|
||||
it('returns root for a chat session detail', () => {
|
||||
expect(getSwipeBackTarget('/chats/20260101-120000-abcdef/sessions/ses_1', '')).toBe('/');
|
||||
});
|
||||
});
|
||||
|
||||
describe('repo route', () => {
|
||||
it('returns root for repo detail', () => {
|
||||
expect(getSwipeBackTarget('/repos/42', '')).toBe('/');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ASSISTANT_REPO_ID, buildServerSessionPath, buildSessionPath } from '@opencode-manager/shared/utils';
|
||||
import { ASSISTANT_REPO_ID, buildChatSessionPath, buildServerSessionPath, buildSessionPath } from '@opencode-manager/shared/utils';
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas';
|
||||
|
||||
export function getAssistantPath(): string {
|
||||
@@ -32,6 +32,10 @@ export function getServerSessionPath(serverId: string, sessionId: string): strin
|
||||
return buildServerSessionPath(serverId, sessionId);
|
||||
}
|
||||
|
||||
export function getChatSessionPath(chatId: string, sessionId: string): string {
|
||||
return buildChatSessionPath(chatId, sessionId);
|
||||
}
|
||||
|
||||
export function getServerProjectPath(serverId: string, directory: string): string {
|
||||
return `/servers/${encodeURIComponent(serverId)}/projects?directory=${encodeURIComponent(directory)}`;
|
||||
}
|
||||
@@ -65,6 +69,15 @@ export function parseServerSessionRoute(pathname: string): { serverId: string; s
|
||||
return { serverId, sessionId };
|
||||
}
|
||||
|
||||
export function parseChatSessionRoute(pathname: string): { chatId: string; sessionId: string } | null {
|
||||
const match = /^\/chats\/([^/]+)\/sessions\/([^/]+)$/.exec(pathname);
|
||||
if (!match) return null;
|
||||
const chatId = decodePathSegment(match[1]);
|
||||
const sessionId = decodePathSegment(match[2]);
|
||||
if (chatId === null || sessionId === null) return null;
|
||||
return { chatId, sessionId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session route in view, whether it belongs to the local server or a linked one.
|
||||
*
|
||||
@@ -76,6 +89,10 @@ export function parseActivePickerSession(pathname: string): { sessionId?: string
|
||||
if (repoRoute.sessionId) {
|
||||
return { sessionId: repoRoute.sessionId, serverId: LOCAL_OPENCODE_SERVER_ID };
|
||||
}
|
||||
const chatSessionRoute = parseChatSessionRoute(pathname);
|
||||
if (chatSessionRoute) {
|
||||
return { sessionId: chatSessionRoute.sessionId, serverId: LOCAL_OPENCODE_SERVER_ID };
|
||||
}
|
||||
const serverSessionRoute = parseServerSessionRoute(pathname);
|
||||
if (!serverSessionRoute) return {};
|
||||
return { sessionId: serverSessionRoute.sessionId, serverId: serverSessionRoute.serverId };
|
||||
@@ -83,7 +100,9 @@ export function parseActivePickerSession(pathname: string): { sessionId?: string
|
||||
|
||||
export function isSessionDetailRoute(pathname: string): boolean {
|
||||
const normalizedPathname = pathname.replace(/\/+$/, '');
|
||||
return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(normalizedPathname) || parseServerSessionRoute(normalizedPathname) !== null;
|
||||
return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(normalizedPathname)
|
||||
|| parseServerSessionRoute(normalizedPathname) !== null
|
||||
|| parseChatSessionRoute(normalizedPathname) !== null;
|
||||
}
|
||||
|
||||
export function parseRepoRoute(pathname: string): { repoId: number | null; section: string | null; sessionId: string | null } {
|
||||
@@ -144,6 +163,11 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
|
||||
return '/';
|
||||
}
|
||||
|
||||
const chatSession = parseChatSessionRoute(pathname);
|
||||
if (chatSession) {
|
||||
return '/';
|
||||
}
|
||||
|
||||
if (/^\/servers\/[^/]+$/.test(pathname)) {
|
||||
return '/';
|
||||
}
|
||||
|
||||
@@ -1,19 +1,39 @@
|
||||
export type TerminalTarget =
|
||||
| { kind: 'repo'; repoId: number }
|
||||
| { kind: 'server'; serverId: string }
|
||||
| { kind: 'chat'; chatId: string }
|
||||
|
||||
export function terminalTargetScope(target: TerminalTarget): number | string {
|
||||
return target.kind === 'repo' ? target.repoId : target.serverId
|
||||
switch (target.kind) {
|
||||
case 'repo':
|
||||
return target.repoId
|
||||
case 'server':
|
||||
return target.serverId
|
||||
case 'chat':
|
||||
return target.chatId
|
||||
}
|
||||
}
|
||||
|
||||
export function terminalTargetKey(target: TerminalTarget): string {
|
||||
return target.kind === 'repo' ? `repo:${target.repoId}` : `server:${target.serverId}`
|
||||
switch (target.kind) {
|
||||
case 'repo':
|
||||
return `repo:${target.repoId}`
|
||||
case 'server':
|
||||
return `server:${target.serverId}`
|
||||
case 'chat':
|
||||
return `chat:${target.chatId}`
|
||||
}
|
||||
}
|
||||
|
||||
export function terminalCollectionPath(target: TerminalTarget): string {
|
||||
return target.kind === 'repo'
|
||||
? `/api/repos/${target.repoId}/terminals`
|
||||
: `/api/opencode-servers/${encodeURIComponent(target.serverId)}/terminals`
|
||||
switch (target.kind) {
|
||||
case 'repo':
|
||||
return `/api/repos/${target.repoId}/terminals`
|
||||
case 'server':
|
||||
return `/api/opencode-servers/${encodeURIComponent(target.serverId)}/terminals`
|
||||
case 'chat':
|
||||
return `/api/chats/${encodeURIComponent(target.chatId)}/terminals`
|
||||
}
|
||||
}
|
||||
|
||||
export function terminalItemPath(target: TerminalTarget, ptyID: string): string {
|
||||
|
||||
@@ -9,8 +9,10 @@ import { X, CornerUpLeft, GitBranch, ArrowDown, Server } from "lucide-react";
|
||||
import { SquareFill } from "@/components/ui/square-fill";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { getServerProjectPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
|
||||
import { getChatSessionPath, getServerProjectPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { useChat, useDeleteChatSession } from '@/hooks/useChats'
|
||||
import type { TerminalTarget } from '@/lib/terminal-target'
|
||||
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { NotFoundState } from "@/components/ui/not-found-state";
|
||||
@@ -129,12 +131,13 @@ function isSessionNotFoundError(error: unknown): boolean {
|
||||
export function SessionDetail() {
|
||||
const serverId = useOpenCodeServerId();
|
||||
const isRemoteServer = !isLocalOpenCodeServer(serverId);
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
const { id, chatId, sessionId } = useParams<{ id?: string; chatId?: string; sessionId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const swipeNav = useSwipeNavigation();
|
||||
const isChatSession = chatId !== undefined;
|
||||
const repoId = Number(id) || 0;
|
||||
const isAssistantSession = new URLSearchParams(location.search).get('assistant') === '1';
|
||||
const isAssistantSession = !isChatSession && new URLSearchParams(location.search).get('assistant') === '1';
|
||||
const { preferences, updateSettings } = useSettings();
|
||||
const { open: openSettings, openTab: openSettingsTab } = useSettingsDialog();
|
||||
const messageContainerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -191,10 +194,13 @@ export function SessionDetail() {
|
||||
|
||||
const { data: repo, isLoading: repoLoading } = useQuery({
|
||||
...repoQueryOptions(repoId),
|
||||
enabled: id !== undefined && !isRemoteServer,
|
||||
enabled: id !== undefined && !isRemoteServer && !isChatSession,
|
||||
});
|
||||
|
||||
useRepoActivity(repoId, Boolean(repo) && !isRemoteServer);
|
||||
useRepoActivity(repoId, Boolean(repo) && !isRemoteServer && !isChatSession);
|
||||
|
||||
const { data: chat, isLoading: chatLoading } = useChat(chatId);
|
||||
const { mutateAsync: deleteChatSessionAsync } = useDeleteChatSession();
|
||||
|
||||
const repoDirectory = repo?.fullPath;
|
||||
const [resolvedSessionDirectory, setResolvedSessionDirectory] = useState<{ sessionId: string; directory: string } | null>(null);
|
||||
@@ -203,7 +209,9 @@ export function SessionDetail() {
|
||||
? resolvedSessionDirectory.directory
|
||||
: undefined
|
||||
);
|
||||
const sessionDirectory = isRemoteServer ? resolvedDirectory : resolvedDirectory ?? repoDirectory;
|
||||
const sessionDirectory = isChatSession
|
||||
? chat?.directory
|
||||
: isRemoteServer ? resolvedDirectory : resolvedDirectory ?? repoDirectory;
|
||||
const remoteProjectBackPath = isRemoteServer && sessionDirectory
|
||||
? getServerProjectPath(serverId, sessionDirectory)
|
||||
: '/';
|
||||
@@ -216,7 +224,7 @@ export function SessionDetail() {
|
||||
};
|
||||
}, [isRemoteServer, remoteProjectBackPath, swipeNav]);
|
||||
|
||||
const { data: repoSiblings } = useRepoSiblings(!isAssistantSession && !isRemoteServer && repo && !repo.isWorktree ? repoId : undefined);
|
||||
const { data: repoSiblings } = useRepoSiblings(!isChatSession && !isAssistantSession && !isRemoteServer && repo && !repo.isWorktree ? repoId : undefined);
|
||||
|
||||
const { servers: linkedServers } = useOpenCodeServers({ enabled: isRemoteServer });
|
||||
|
||||
@@ -230,8 +238,8 @@ export function SessionDetail() {
|
||||
const remoteProjectDisplayName = remoteProject ? remoteProjectName(remoteProject) : undefined;
|
||||
|
||||
const sessionBranch = useMemo(
|
||||
() => (repo && !isAssistantSession ? resolveSessionBranch(repo, sessionDirectory, repoSiblings) : null),
|
||||
[repo, isAssistantSession, sessionDirectory, repoSiblings],
|
||||
() => (repo && !isAssistantSession && !isChatSession ? resolveSessionBranch(repo, sessionDirectory, repoSiblings) : null),
|
||||
[repo, isAssistantSession, isChatSession, sessionDirectory, repoSiblings],
|
||||
);
|
||||
|
||||
const { data: remoteVcsInfo } = useVcsInfo(sessionDirectory, serverId, { enabled: isRemoteServer });
|
||||
@@ -364,7 +372,7 @@ export function SessionDetail() {
|
||||
}, [lastAssistantMessage, transcriptStatus])
|
||||
const hasIncompleteMessages = lastAssistantMessage ? lastAssistantMessage.time.completed === undefined : false;
|
||||
const isStreamingResponse = hasIncompleteMessages && isSessionActive;
|
||||
const workspaceBasePath = repo?.localPath;
|
||||
const workspaceBasePath = isChatSession ? chat?.filesPath : repo?.localPath;
|
||||
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: sessionId ?? '',
|
||||
@@ -400,7 +408,7 @@ export function SessionDetail() {
|
||||
useAutoOpenWalkthrough({
|
||||
sessionId,
|
||||
messages,
|
||||
enabled: docked && !isRemoteServer,
|
||||
enabled: docked && !isRemoteServer && !isChatSession,
|
||||
loading: messagesLoading,
|
||||
onOpen: handleShowWalkthrough,
|
||||
});
|
||||
@@ -446,16 +454,22 @@ export function SessionDetail() {
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const buildSessionRoute = useCallback((targetSessionId: string) => (
|
||||
chatId !== undefined
|
||||
? getChatSessionPath(chatId, targetSessionId)
|
||||
: getSessionPath(repoId, targetSessionId, { serverId })
|
||||
), [chatId, repoId, serverId]);
|
||||
|
||||
const handleNewSession = useCallback(async () => {
|
||||
try {
|
||||
const newSession = await createSessionAsync({ agent: undefined });
|
||||
if (newSession?.id) {
|
||||
navigate(getSessionPath(repoId, newSession.id, { serverId }));
|
||||
navigate(buildSessionRoute(newSession.id));
|
||||
}
|
||||
} catch {
|
||||
showToast.error('Failed to create new session');
|
||||
}
|
||||
}, [createSessionAsync, navigate, repoId, serverId]);
|
||||
}, [createSessionAsync, navigate, buildSessionRoute]);
|
||||
|
||||
const { mutateAsync: undoMessageAsync } = useUndoMessage({
|
||||
sessionId: sessionId ?? '',
|
||||
@@ -514,7 +528,7 @@ export function SessionDetail() {
|
||||
const forkedSession = await forkSession(sessionId, messageID, serverId);
|
||||
if (forkedSession?.id) {
|
||||
setMessagePickerMode(null);
|
||||
navigate(getSessionPath(repoId, forkedSession.id, { serverId }));
|
||||
navigate(buildSessionRoute(forkedSession.id));
|
||||
if (messageID) {
|
||||
const chosenMessage = forkPickerMessages?.find((message) => message.id === messageID);
|
||||
if (chosenMessage?.type === 'user') {
|
||||
@@ -526,7 +540,7 @@ export function SessionDetail() {
|
||||
} catch (error) {
|
||||
showToast.error(`Fork failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}, [sessionId, forkPickerMessages, navigate, repoId, serverId]);
|
||||
}, [sessionId, serverId, forkPickerMessages, navigate, buildSessionRoute]);
|
||||
|
||||
const openTimelinePicker = useCallback(() => setMessagePickerMode('timeline'), []);
|
||||
|
||||
@@ -542,13 +556,17 @@ export function SessionDetail() {
|
||||
}, []);
|
||||
|
||||
const handleCloseSession = useCallback(() => {
|
||||
if (isChatSession) {
|
||||
navigate('/')
|
||||
return
|
||||
}
|
||||
if (isRemoteServer) {
|
||||
navigate(remoteProjectBackPath)
|
||||
return
|
||||
}
|
||||
const tab = new URLSearchParams(location.search).get('repoTab') ?? undefined;
|
||||
navigate(getSessionListPath(repoId, isAssistantSession, tab))
|
||||
}, [navigate, repoId, isAssistantSession, isRemoteServer, remoteProjectBackPath, location.search])
|
||||
}, [navigate, repoId, isAssistantSession, isChatSession, isRemoteServer, remoteProjectBackPath, location.search])
|
||||
|
||||
const handleOpenModelDialog = useCallback(() => {
|
||||
promptInputRef.current?.openModelPicker();
|
||||
@@ -561,13 +579,19 @@ export function SessionDetail() {
|
||||
};
|
||||
|
||||
const handleFileClick = useCallback((filePath: string) => {
|
||||
setSelectedFilePath(getWorkspaceFilePath(filePath, {
|
||||
directory: sessionDirectory,
|
||||
repoFullPath: repo?.fullPath,
|
||||
repoLocalPath: repo?.localPath,
|
||||
}))
|
||||
setSelectedFilePath(getWorkspaceFilePath(filePath, isChatSession
|
||||
? {
|
||||
directory: sessionDirectory,
|
||||
repoFullPath: chat?.directory,
|
||||
repoLocalPath: chat?.filesPath,
|
||||
}
|
||||
: {
|
||||
directory: sessionDirectory,
|
||||
repoFullPath: repo?.fullPath,
|
||||
repoLocalPath: repo?.localPath,
|
||||
}))
|
||||
setFileBrowserOpen(true)
|
||||
}, [repo?.fullPath, repo?.localPath, sessionDirectory, setFileBrowserOpen]);
|
||||
}, [chat?.directory, chat?.filesPath, isChatSession, repo?.fullPath, repo?.localPath, sessionDirectory, setFileBrowserOpen]);
|
||||
|
||||
const renameSession = useCallback(async (title: string) => {
|
||||
if (!sessionId) throw new Error('No active session');
|
||||
@@ -586,6 +610,12 @@ export function SessionDetail() {
|
||||
}
|
||||
}, [renameSession]);
|
||||
|
||||
const handleDeleteChatSession = useCallback(async () => {
|
||||
if (!chatId || !sessionId || !chat?.directory) return;
|
||||
await deleteChatSessionAsync({ chatId, sessionId, directory: chat.directory });
|
||||
navigate('/');
|
||||
}, [chat?.directory, chatId, deleteChatSessionAsync, navigate, sessionId]);
|
||||
|
||||
const handleFileBrowserClose = useCallback(() => setFileBrowserOpen(false), [setFileBrowserOpen]);
|
||||
|
||||
const filesVisible = fileBrowserOpen || sidePanel.activeTool === 'files';
|
||||
@@ -594,14 +624,14 @@ export function SessionDetail() {
|
||||
}, [filesVisible]);
|
||||
|
||||
const handleChildSessionClick = useCallback((childSessionId: string) => {
|
||||
navigate(getSessionPath(repoId, childSessionId, { serverId }))
|
||||
}, [navigate, repoId, serverId]);
|
||||
navigate(buildSessionRoute(childSessionId))
|
||||
}, [navigate, buildSessionRoute]);
|
||||
|
||||
const handleParentSessionClick = useCallback(() => {
|
||||
if (session?.parentID) {
|
||||
navigate(getSessionPath(repoId, session.parentID, { serverId }))
|
||||
navigate(buildSessionRoute(session.parentID))
|
||||
}
|
||||
}, [navigate, repoId, session?.parentID, serverId]);
|
||||
}, [navigate, session?.parentID, buildSessionRoute]);
|
||||
|
||||
const handleToggleDetails = useCallback(() => {
|
||||
const newValue = !preferences?.expandToolCalls
|
||||
@@ -742,7 +772,22 @@ export function SessionDetail() {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
if (!isAssistantSession && !isRemoteServer && repoLoading) {
|
||||
if (isChatSession && chatLoading) {
|
||||
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">
|
||||
<div className="w-8 h-8 animate-spin rounded-full border-2 border-muted border-t-foreground" />
|
||||
<span className="text-muted-foreground">Loading chat...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isChatSession && !chat) {
|
||||
return <NotFoundState message="Chat not found" backTo="/" backLabel="Back to chats" />;
|
||||
}
|
||||
|
||||
if (!isAssistantSession && !isRemoteServer && !isChatSession && repoLoading) {
|
||||
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">
|
||||
@@ -753,7 +798,7 @@ export function SessionDetail() {
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAssistantSession && !isRemoteServer && !repo) {
|
||||
if (!isAssistantSession && !isRemoteServer && !isChatSession && !repo) {
|
||||
return <NotFoundState message="Repository not found" backTo="/" backLabel="Back to repositories" />;
|
||||
}
|
||||
|
||||
@@ -762,8 +807,8 @@ export function SessionDetail() {
|
||||
return (
|
||||
<NotFoundState
|
||||
message="Session not found"
|
||||
backTo={isRemoteServer ? remoteProjectBackPath : getSessionListPath(repoId, isAssistantSession, listTab)}
|
||||
backLabel={isRemoteServer ? 'Back to projects' : 'Back to sessions'}
|
||||
backTo={isChatSession ? '/' : isRemoteServer ? remoteProjectBackPath : getSessionListPath(repoId, isAssistantSession, listTab)}
|
||||
backLabel={isChatSession ? 'Back to chats' : isRemoteServer ? 'Back to projects' : 'Back to sessions'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -792,15 +837,24 @@ export function SessionDetail() {
|
||||
}
|
||||
|
||||
const linkedServer = linkedServers.find((candidate) => candidate.id === serverId);
|
||||
const projectDisplayName = isRemoteServer
|
||||
? remoteProjectDisplayName ?? (sessionDirectory ? getDirectoryName(sessionDirectory) : 'Project')
|
||||
: isAssistantSession || !repo
|
||||
? 'Assistant'
|
||||
: getRepoDisplayName(repo);
|
||||
const projectDisplayName = isChatSession
|
||||
? 'Chat'
|
||||
: isRemoteServer
|
||||
? remoteProjectDisplayName ?? (sessionDirectory ? getDirectoryName(sessionDirectory) : 'Project')
|
||||
: isAssistantSession || !repo
|
||||
? 'Assistant'
|
||||
: getRepoDisplayName(repo);
|
||||
const tabFromUrl = new URLSearchParams(location.search).get('repoTab') ?? undefined;
|
||||
const sessionBackPath = isRemoteServer
|
||||
? remoteProjectBackPath
|
||||
: getSessionListPath(repoId, isAssistantSession, tabFromUrl);
|
||||
const sessionBackPath = isChatSession
|
||||
? '/'
|
||||
: isRemoteServer
|
||||
? remoteProjectBackPath
|
||||
: getSessionListPath(repoId, isAssistantSession, tabFromUrl);
|
||||
const terminalTarget: TerminalTarget = chatId !== undefined
|
||||
? { kind: 'chat', chatId }
|
||||
: isRemoteServer
|
||||
? { kind: 'server', serverId }
|
||||
: { kind: 'repo', repoId };
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -865,10 +919,10 @@ export function SessionDetail() {
|
||||
</div>
|
||||
<Header.Actions className="gap-2 sm:gap-4">
|
||||
<div className="flex items-center gap-1">
|
||||
{!isAssistantSession && !isRemoteServer && (
|
||||
{!isAssistantSession && !isRemoteServer && !isChatSession && (
|
||||
<ProjectActionsMenu repoId={repoId} directory={sessionDirectory} />
|
||||
)}
|
||||
<PendingActionsGroup showScheduleReports={!isRemoteServer} />
|
||||
<PendingActionsGroup showScheduleReports={!isRemoteServer && !isChatSession} />
|
||||
</div>
|
||||
<SessionMoreButton />
|
||||
</Header.Actions>
|
||||
@@ -885,14 +939,14 @@ export function SessionDetail() {
|
||||
<MessageThread
|
||||
sessionID={sessionId}
|
||||
directory={sessionDirectory}
|
||||
repoFullPath={repo?.fullPath}
|
||||
repoLocalPath={repo?.localPath}
|
||||
repoFullPath={isChatSession ? chat?.directory : repo?.fullPath}
|
||||
repoLocalPath={isChatSession ? chat?.filesPath : repo?.localPath}
|
||||
messages={messages}
|
||||
pending={pendingPrompts}
|
||||
isSessionBusy={isSessionActive}
|
||||
onFileClick={isRemoteServer ? undefined : handleFileClick}
|
||||
onChildSessionClick={handleChildSessionClick}
|
||||
onOpenWalkthrough={isRemoteServer ? undefined : handleShowWalkthrough}
|
||||
onOpenWalkthrough={isRemoteServer || isChatSession ? undefined : handleShowWalkthrough}
|
||||
onUndoMessage={handleUndoMessage}
|
||||
model={modelRef ? formatOpenCodeModelRef(modelRef) : undefined}
|
||||
/>
|
||||
@@ -1019,19 +1073,19 @@ export function SessionDetail() {
|
||||
{showRail && (
|
||||
<ToolSidePanel
|
||||
panel={sidePanel}
|
||||
repoId={isRemoteServer ? undefined : repoId}
|
||||
repoId={isRemoteServer || isChatSession ? undefined : repoId}
|
||||
sessionId={sessionId}
|
||||
directory={sessionDirectory}
|
||||
filesBasePath={workspaceBasePath}
|
||||
currentBranch={repo?.currentBranch || repo?.branch || "main"}
|
||||
currentBranch={isChatSession ? undefined : repo?.currentBranch || repo?.branch || "main"}
|
||||
selectedFilePath={selectedFilePath}
|
||||
repoDirectory={isRemoteServer ? sessionDirectory : repoDirectory}
|
||||
terminalTarget={isRemoteServer ? { kind: 'server', serverId } : { kind: 'repo', repoId }}
|
||||
repoDirectory={isRemoteServer || isChatSession ? sessionDirectory : repoDirectory}
|
||||
terminalTarget={terminalTarget}
|
||||
onSkillLoaded={handleSkillLoaded}
|
||||
walkthroughSourceRequest={walkthroughSourceRequest}
|
||||
walkthroughModel={modelRef}
|
||||
walkthroughOnOpenSession={handleChildSessionClick}
|
||||
deleteActiveSessionPath={isRemoteServer ? remoteProjectBackPath : undefined}
|
||||
deleteActiveSessionPath={isChatSession ? '/' : isRemoteServer ? remoteProjectBackPath : undefined}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1043,9 +1097,10 @@ export function SessionDetail() {
|
||||
serverName={linkedServer?.name}
|
||||
remote={isRemoteServer}
|
||||
project={projectDisplayName}
|
||||
branch={headerBranch}
|
||||
branch={isChatSession ? null : headerBranch}
|
||||
directory={sessionDirectory}
|
||||
onRename={renameSession}
|
||||
onDeleteSession={isChatSession ? handleDeleteChatSession : undefined}
|
||||
/>
|
||||
|
||||
{sideQuestion && sessionId && (
|
||||
@@ -1080,12 +1135,12 @@ export function SessionDetail() {
|
||||
onClose={handleFileBrowserClose}
|
||||
basePath={workspaceBasePath}
|
||||
repoName={projectDisplayName}
|
||||
repoId={repoId}
|
||||
repoId={isChatSession ? undefined : repoId}
|
||||
initialSelectedFile={selectedFilePath}
|
||||
/>
|
||||
)}
|
||||
|
||||
{sessionId && (
|
||||
{!isChatSession && sessionId && (
|
||||
<RepoSkillsDialog
|
||||
open={!docked && skillsDialogOpen}
|
||||
onOpenChange={setSkillsDialogOpen}
|
||||
@@ -1096,7 +1151,7 @@ export function SessionDetail() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isRemoteServer && sessionId && (
|
||||
{!isRemoteServer && !isChatSession && sessionId && (
|
||||
<ChangesWalkthroughSheet
|
||||
sessionId={sessionId}
|
||||
open={!docked && walkthroughOpen}
|
||||
@@ -1107,13 +1162,15 @@ export function SessionDetail() {
|
||||
/>
|
||||
)}
|
||||
|
||||
<RepoMcpDialog
|
||||
open={!docked && mcpDialogOpen}
|
||||
onOpenChange={setMcpDialogOpen}
|
||||
directory={isRemoteServer ? sessionDirectory : repoDirectory}
|
||||
/>
|
||||
{!isChatSession && (
|
||||
<RepoMcpDialog
|
||||
open={!docked && mcpDialogOpen}
|
||||
onOpenChange={setMcpDialogOpen}
|
||||
directory={isRemoteServer ? sessionDirectory : repoDirectory}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isAssistantSession && !isRemoteServer && (
|
||||
{!isAssistantSession && !isRemoteServer && !isChatSession && (
|
||||
<RepoActionsDialog
|
||||
repoId={repoId}
|
||||
directory={sessionDirectory}
|
||||
@@ -1122,27 +1179,29 @@ export function SessionDetail() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{isRemoteServer
|
||||
? sessionDirectory && (
|
||||
<RemoteSourceControlPanel
|
||||
serverId={serverId}
|
||||
directory={sessionDirectory}
|
||||
isOpen={!docked && sourceControlOpen}
|
||||
onClose={() => setSourceControlOpen(false)}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<SourceControlPanel
|
||||
repoId={repoId}
|
||||
isOpen={!docked && sourceControlOpen}
|
||||
onClose={() => setSourceControlOpen(false)}
|
||||
currentBranch={repo?.currentBranch || repo?.branch || "main"}
|
||||
repoName={projectDisplayName}
|
||||
/>
|
||||
)}
|
||||
{!isChatSession && (
|
||||
isRemoteServer
|
||||
? sessionDirectory && (
|
||||
<RemoteSourceControlPanel
|
||||
serverId={serverId}
|
||||
directory={sessionDirectory}
|
||||
isOpen={!docked && sourceControlOpen}
|
||||
onClose={() => setSourceControlOpen(false)}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<SourceControlPanel
|
||||
repoId={repoId}
|
||||
isOpen={!docked && sourceControlOpen}
|
||||
onClose={() => setSourceControlOpen(false)}
|
||||
currentBranch={repo?.currentBranch || repo?.branch || "main"}
|
||||
repoName={projectDisplayName}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
|
||||
<TerminalPanel
|
||||
target={isRemoteServer ? { kind: 'server', serverId } : { kind: 'repo', repoId }}
|
||||
target={terminalTarget}
|
||||
directory={sessionDirectory}
|
||||
isOpen={!docked && terminalOpen}
|
||||
onClose={() => setTerminalOpen(false)}
|
||||
@@ -1156,7 +1215,7 @@ export function SessionDetail() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isRemoteServer && (
|
||||
{!isRemoteServer && !isChatSession && (
|
||||
<ResetPermissionsDialog
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } 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(),
|
||||
useChat: vi.fn(),
|
||||
useDeleteChatSession: vi.fn(),
|
||||
useSessionTranscript: vi.fn(),
|
||||
useSSE: vi.fn(),
|
||||
useRepoActivity: vi.fn(),
|
||||
useRepoSiblings: vi.fn(),
|
||||
usePermissions: vi.fn(),
|
||||
useForms: vi.fn(),
|
||||
useSettings: vi.fn(),
|
||||
useSettingsDialog: vi.fn(),
|
||||
useMobile: vi.fn(),
|
||||
useVisualViewport: vi.fn(),
|
||||
useShortcutActions: vi.fn(),
|
||||
useAutoScroll: vi.fn(),
|
||||
useDialogParam: vi.fn(),
|
||||
useTerminalDialogParam: vi.fn(),
|
||||
useOpenCodeServers: vi.fn(),
|
||||
useOpenCodeServerStatuses: vi.fn(),
|
||||
getRepo: vi.fn(),
|
||||
useSessionStatus: vi.fn(),
|
||||
MessageThread: vi.fn(() => <div data-testid="message-thread" />),
|
||||
PromptInput: vi.fn(() => null),
|
||||
FileBrowserSheet: vi.fn(() => null),
|
||||
TerminalPanel: vi.fn(() => null),
|
||||
PreviewPanel: vi.fn(() => null),
|
||||
ProjectActionsMenu: vi.fn(() => null),
|
||||
RepoActionsDialog: vi.fn(() => null),
|
||||
ResetPermissionsDialog: vi.fn(() => null),
|
||||
RepoSkillsDialog: vi.fn(() => null),
|
||||
RepoMcpDialog: vi.fn(() => null),
|
||||
SourceControlPanel: vi.fn(() => null),
|
||||
RemoteSourceControlPanel: vi.fn(() => null),
|
||||
ChangesWalkthroughSheet: vi.fn(() => null),
|
||||
ToolSidePanel: vi.fn(() => null),
|
||||
SessionMoreButton: vi.fn(() => null),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({ getRepo: mocks.getRepo }))
|
||||
|
||||
vi.mock('@/hooks/useChats', () => ({
|
||||
useChat: mocks.useChat,
|
||||
useDeleteChatSession: mocks.useDeleteChatSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useSession: mocks.useSession,
|
||||
useInterruptSession: vi.fn(() => ({ mutate: vi.fn() })),
|
||||
useUpdateSession: vi.fn(() => ({ mutate: vi.fn(), mutateAsync: vi.fn() })),
|
||||
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSessionTranscript', () => ({ useSessionTranscript: mocks.useSessionTranscript }))
|
||||
vi.mock('@/hooks/useRepoSiblings', () => ({ useRepoSiblings: mocks.useRepoSiblings }))
|
||||
vi.mock('@/hooks/useRepoActivity', () => ({ useRepoActivity: mocks.useRepoActivity }))
|
||||
vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE }))
|
||||
vi.mock('@/hooks/useOpenCodeServers', () => ({
|
||||
useOpenCodeServers: mocks.useOpenCodeServers,
|
||||
useOpenCodeServerStatuses: mocks.useOpenCodeServerStatuses,
|
||||
}))
|
||||
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: mocks.useSettings }))
|
||||
vi.mock('@/hooks/useSettingsDialog', () => ({ useSettingsDialog: mocks.useSettingsDialog }))
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: mocks.useMobile,
|
||||
useSwipeBack: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })),
|
||||
}))
|
||||
vi.mock('@/hooks/useVisualViewport', () => ({ useVisualViewport: mocks.useVisualViewport }))
|
||||
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({ useShortcutActions: mocks.useShortcutActions }))
|
||||
vi.mock('@/hooks/useAutoScroll', () => ({ useAutoScroll: mocks.useAutoScroll }))
|
||||
vi.mock('@/hooks/useDialogParam', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useDialogParam')>()
|
||||
return { ...actual, useDialogParam: mocks.useDialogParam }
|
||||
})
|
||||
vi.mock('@/hooks/useOpenTerminal', () => ({ useTerminalDialogParam: mocks.useTerminalDialogParam }))
|
||||
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
|
||||
getAssistantText: vi.fn(() => ''),
|
||||
getLatestPlayableAssistantMessage: vi.fn(() => null),
|
||||
useAutoPlayLastResponse: vi.fn(() => {}),
|
||||
}))
|
||||
vi.mock('@/hooks/useAutoOpenWalkthrough', () => ({ useAutoOpenWalkthrough: vi.fn(() => {}) }))
|
||||
vi.mock('@/hooks/useSpeakVisibleMessages', () => ({ useSpeakVisibleMessages: vi.fn(() => vi.fn()) }))
|
||||
vi.mock('@/hooks/useUndoMessage', () => ({
|
||||
useUndoMessage: vi.fn(() => ({ mutateAsync: vi.fn() })),
|
||||
useRedoMessage: vi.fn(() => ({ mutateAsync: vi.fn() })),
|
||||
}))
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), loading: vi.fn() },
|
||||
}))
|
||||
vi.mock('@/stores/uiStateStore', () => ({ useUIState: vi.fn(() => false) }))
|
||||
vi.mock('@/stores/sessionStatusStore', () => ({ useSessionStatus: mocks.useSessionStatus }))
|
||||
vi.mock('@/contexts/EventContext', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/contexts/EventContext')>()
|
||||
return { ...actual, usePermissions: mocks.usePermissions, useForms: mocks.useForms }
|
||||
})
|
||||
|
||||
vi.mock('@/components/message/MessageThread', () => ({ MessageThread: mocks.MessageThread }))
|
||||
vi.mock('@/components/message/PromptInput', () => ({ PromptInput: mocks.PromptInput }))
|
||||
vi.mock('@/components/message/FloatingTTSButton', () => ({ FloatingTTSButton: () => null }))
|
||||
vi.mock('@/components/message/MessageSkeleton', () => ({ MessageSkeleton: () => null }))
|
||||
vi.mock('@/components/session/SessionSendErrorBanner', () => ({ SessionSendErrorBanner: () => null }))
|
||||
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: () => null }))
|
||||
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: () => null }))
|
||||
vi.mock('@/components/session/FormPrompt', () => ({ FormPrompt: () => null }))
|
||||
vi.mock('@/components/session/MinimizedFormIndicator', () => ({ MinimizedFormIndicator: () => null }))
|
||||
vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({
|
||||
ChangesWalkthroughSheet: mocks.ChangesWalkthroughSheet,
|
||||
}))
|
||||
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
|
||||
vi.mock('@/components/navigation/SessionMoreButton', () => ({ SessionMoreButton: mocks.SessionMoreButton }))
|
||||
vi.mock('@/components/navigation/ToolSidePanel', () => ({ ToolSidePanel: mocks.ToolSidePanel }))
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: mocks.FileBrowserSheet }))
|
||||
vi.mock('@/components/source-control', () => ({
|
||||
SourceControlPanel: mocks.SourceControlPanel,
|
||||
RemoteSourceControlPanel: mocks.RemoteSourceControlPanel,
|
||||
}))
|
||||
vi.mock('@/components/terminal/TerminalPanel', () => ({ TerminalPanel: mocks.TerminalPanel }))
|
||||
vi.mock('@/components/preview/PreviewPanel', () => ({ PreviewPanel: mocks.PreviewPanel }))
|
||||
vi.mock('@/components/repo/ProjectActionsMenu', () => ({ ProjectActionsMenu: mocks.ProjectActionsMenu }))
|
||||
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: mocks.RepoActionsDialog }))
|
||||
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
|
||||
ResetPermissionsDialog: mocks.ResetPermissionsDialog,
|
||||
}))
|
||||
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: mocks.RepoSkillsDialog }))
|
||||
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: mocks.RepoMcpDialog }))
|
||||
|
||||
const chatId = '20260101-120000-abcdef'
|
||||
const chat = {
|
||||
id: chatId,
|
||||
directory: `/chats/${chatId}/work`,
|
||||
filesPath: `/chats/${chatId}`,
|
||||
createdAt: 1,
|
||||
}
|
||||
|
||||
const chatSession = {
|
||||
id: 'ses_chat',
|
||||
projectID: 'prj_chat',
|
||||
title: 'Scratch chat',
|
||||
time: { created: 1, updated: 2 },
|
||||
location: { directory: chat.directory },
|
||||
}
|
||||
|
||||
function renderChatSession() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[`/chats/${chatId}/sessions/ses_chat`]}>
|
||||
<Routes>
|
||||
<Route path="/" element={null} />
|
||||
<Route path="/chats/:chatId/sessions/:sessionId" element={<SessionDetail />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('SessionDetail chat session', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useChat.mockReturnValue({ data: chat, isLoading: false, error: undefined })
|
||||
mocks.useDeleteChatSession.mockReturnValue({ mutateAsync: vi.fn(), isPending: false })
|
||||
mocks.useSession.mockReturnValue({ data: chatSession, isLoading: false, error: undefined })
|
||||
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.useRepoSiblings.mockReturnValue({ data: [] })
|
||||
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(),
|
||||
forgetPendingActionsForSession: vi.fn(),
|
||||
syncForSession: vi.fn(),
|
||||
})
|
||||
mocks.useSettings.mockReturnValue({ preferences: { expandToolCalls: false }, updateSettings: vi.fn() })
|
||||
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn(), openTab: vi.fn() })
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
|
||||
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn(), scrollByUser: vi.fn() })
|
||||
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
|
||||
mocks.useTerminalDialogParam.mockReturnValue([false, vi.fn()])
|
||||
mocks.useSessionStatus.mockReturnValue({ setStatus: vi.fn() })
|
||||
mocks.useOpenCodeServers.mockReturnValue({ servers: [], isLoading: false })
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({ statusById: {} })
|
||||
})
|
||||
|
||||
it('renders the transcript and labels the project as a chat', async () => {
|
||||
renderChatSession()
|
||||
|
||||
expect(await screen.findByTestId('message-thread')).toBeInTheDocument()
|
||||
expect(mocks.PromptInput).toHaveBeenCalled()
|
||||
expect(screen.getByText('Chat')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not load a Manager repository', async () => {
|
||||
renderChatSession()
|
||||
|
||||
await screen.findByTestId('message-thread')
|
||||
|
||||
expect(mocks.getRepo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('scopes the file browser, terminal, and preview to the chat folder', async () => {
|
||||
renderChatSession()
|
||||
|
||||
await screen.findByTestId('message-thread')
|
||||
|
||||
expect(mocks.FileBrowserSheet.mock.calls.at(-1)?.[0]).toEqual(
|
||||
expect.objectContaining({ basePath: chat.filesPath }),
|
||||
)
|
||||
expect(mocks.TerminalPanel.mock.calls.at(-1)?.[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
target: { kind: 'chat', chatId },
|
||||
directory: chat.directory,
|
||||
}),
|
||||
)
|
||||
expect(mocks.PreviewPanel.mock.calls.at(-1)?.[0]).toEqual(
|
||||
expect.objectContaining({ directory: chat.directory }),
|
||||
)
|
||||
})
|
||||
|
||||
it('hides repository-only surfaces', async () => {
|
||||
renderChatSession()
|
||||
|
||||
await screen.findByTestId('message-thread')
|
||||
|
||||
expect(mocks.ProjectActionsMenu).not.toHaveBeenCalled()
|
||||
expect(mocks.RepoActionsDialog).not.toHaveBeenCalled()
|
||||
expect(mocks.RepoMcpDialog).not.toHaveBeenCalled()
|
||||
expect(mocks.RepoSkillsDialog).not.toHaveBeenCalled()
|
||||
expect(mocks.ResetPermissionsDialog).not.toHaveBeenCalled()
|
||||
expect(mocks.SourceControlPanel).not.toHaveBeenCalled()
|
||||
expect(mocks.RemoteSourceControlPanel).not.toHaveBeenCalled()
|
||||
expect(mocks.ChangesWalkthroughSheet).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows a chat not-found state for an unknown chat', async () => {
|
||||
mocks.useChat.mockReturnValue({ data: null, isLoading: false, error: undefined })
|
||||
|
||||
renderChatSession()
|
||||
|
||||
expect(await screen.findByText('Chat not found')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('message-thread')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user