mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Feat/assistant session list (#198)
* feat: add assistant mode integration and fix test environment - Add assistant-mode service for managing assistant workspace files (AGENTS.md, opencode.json) - Add backend GET/POST routes for assistant-mode status and initialization - Add AssistantRedirect page and useAssistantSessionLauncher hook - Update mobile navigation to include Assistant tab (replaces Alerts) - Fix React.act compatibility by setting NODE_ENV=test in vitest config - Add shared Zod schemas for AssistantMode types and requests * feat: enhance assistant mode with session list view and legacy config migration - Add session list view for assistant mode with full workspace management - Migrate legacy opencode.json permission format to granular permissions - Enable assistant navigation from mobile tab bar and repo switcher - Preserve assistant context in session routes via query params - Auto-restart OpenCode server after assistant mode initialization - Add comprehensive tests for legacy config detection and navigation
This commit is contained in:
1 parent
0a2e337efc
commit
c894ff5756
22 files changed
+1347
-154
No files matched your search
@@ -12,6 +12,7 @@ import { GlobalSchedules } from './pages/GlobalSchedules'
|
||||
import { Login } from './pages/Login'
|
||||
import { Register } from './pages/Register'
|
||||
import { Setup } from './pages/Setup'
|
||||
import { AssistantRedirect } from './pages/AssistantRedirect'
|
||||
import { SettingsDialog } from './components/settings/SettingsDialog'
|
||||
import { VersionNotifier } from './components/VersionNotifier'
|
||||
import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt'
|
||||
@@ -188,11 +189,21 @@ const router = createBrowserRouter([
|
||||
element: <Repos />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/assistant',
|
||||
element: <AssistantRedirect />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id',
|
||||
element: <RepoDetail />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id/assistant',
|
||||
element: <AssistantRedirect />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id/sessions/:sessionId',
|
||||
element: <SessionDetail />,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Repo } from './types'
|
||||
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { DiscoverReposResponse } from '@opencode-manager/shared/types'
|
||||
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
|
||||
|
||||
export interface CreateRepoOptions {
|
||||
repoUrl?: string
|
||||
@@ -166,3 +166,20 @@ export async function touchRepoActivity(id: number): Promise<void> {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function getAssistantModeStatus(id: number): Promise<AssistantModeStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, {
|
||||
method: 'GET',
|
||||
})
|
||||
}
|
||||
|
||||
export async function initializeAssistantMode(
|
||||
id: number,
|
||||
options?: AssistantModeInitRequest
|
||||
): Promise<AssistantModeStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(options ?? {}),
|
||||
})
|
||||
}
|
||||
@@ -1,22 +1,25 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
vi.mock('@/hooks/useMobile')
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
usePendingAlerts: vi.fn(),
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MobileTabBar } from './MobileTabBar'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { usePendingAlerts } from '@/contexts/EventContext'
|
||||
|
||||
function LocationSpy() {
|
||||
const { pathname, search } = useLocation()
|
||||
return <div data-testid="location">{`${pathname}${search}`}</div>
|
||||
}
|
||||
|
||||
describe('MobileTabBar', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('renders nothing when useMobile returns false', () => {
|
||||
@@ -59,6 +62,65 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders global tabs on assistant session list path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123/assistant?view=sessions']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Assistant')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('navigates to assistant route when repo id is present', async () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123']}>
|
||||
<Routes>
|
||||
<Route path="*" element={<>
|
||||
<MobileTabBar />
|
||||
<LocationSpy />
|
||||
</>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Assistant' }))
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/123/assistant')
|
||||
})
|
||||
|
||||
it('navigates to assistant route when assistant is clicked without repo id', async () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/schedules']}>
|
||||
<Routes>
|
||||
<Route path="*" element={<>
|
||||
<MobileTabBar />
|
||||
<LocationSpy />
|
||||
</>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Assistant' }))
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/assistant')
|
||||
})
|
||||
|
||||
it('renders schedule tabs on /repos/:id/schedules path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
@@ -72,7 +134,7 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByText('Jobs')).toBeInTheDocument()
|
||||
expect(screen.getByText('Detail')).toBeInTheDocument()
|
||||
expect(screen.getByText('Runs')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Alerts')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Assistant')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders tab bar on root path', () => {
|
||||
@@ -87,7 +149,7 @@ describe('MobileTabBar', () => {
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Files')).toBeInTheDocument()
|
||||
expect(screen.getByText('Alerts')).toBeInTheDocument()
|
||||
expect(screen.getByText('Assistant')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
expect(screen.getByText('More')).toBeInTheDocument()
|
||||
})
|
||||
@@ -106,36 +168,6 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows badge when usePendingAlerts returns true', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const badge = document.querySelector('.bg-orange-500')
|
||||
expect(badge).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show badge when usePendingAlerts returns false', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(false)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const badge = document.querySelector('.bg-orange-500')
|
||||
expect(badge).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('Repos tab is active when pathname is / and no sheet is open', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
@@ -218,7 +250,7 @@ describe('MobileTabBar', () => {
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Files')).toBeInTheDocument()
|
||||
expect(screen.getByText('Alerts')).toBeInTheDocument()
|
||||
expect(screen.getByText('Assistant')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
expect(screen.getByText('More')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { memo, useMemo } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { FolderGit2, FolderOpen, Bell, CalendarClock, Menu, Info, History } from 'lucide-react'
|
||||
import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useMobileTabBar, useScheduleTab, type ScheduleTabKey } from '@/hooks/useMobileTabBar'
|
||||
import { usePendingAlerts } from '@/contexts/EventContext'
|
||||
|
||||
interface TabDef {
|
||||
key: string
|
||||
@@ -17,24 +16,75 @@ interface TabDef {
|
||||
|
||||
interface GlobalTabsArgs {
|
||||
pathname: string
|
||||
search: string
|
||||
openSheet: ReturnType<typeof useMobileTabBar>['openSheet']
|
||||
open: ReturnType<typeof useMobileTabBar>['open']
|
||||
close: ReturnType<typeof useMobileTabBar>['close']
|
||||
navigate: ReturnType<typeof useNavigate>
|
||||
hasPending: boolean
|
||||
isInsideRepo: boolean
|
||||
repoId: string | null
|
||||
}
|
||||
|
||||
function buildGlobalTabs({ pathname, openSheet, open, navigate, hasPending, isInsideRepo, repoId }: GlobalTabsArgs): TabDef[] {
|
||||
type TabBarMode = 'hidden' | 'global' | 'schedule'
|
||||
|
||||
interface MobileTabRouteState {
|
||||
mode: TabBarMode
|
||||
isInsideRepo: boolean
|
||||
repoId: string | null
|
||||
}
|
||||
|
||||
function getMobileTabRouteState(pathname: string): MobileTabRouteState {
|
||||
const repoMatch = pathname.match(/^\/repos\/(\d+)(?:\/([^/]+))?/)
|
||||
const repoId = repoMatch?.[1] ?? null
|
||||
const repoSection = repoMatch?.[2]
|
||||
|
||||
if (pathname === '/' || pathname === '/schedules') {
|
||||
return { mode: 'global', isInsideRepo: false, repoId: null }
|
||||
}
|
||||
|
||||
if (!repoId) {
|
||||
return { mode: 'hidden', isInsideRepo: false, repoId: null }
|
||||
}
|
||||
|
||||
switch (repoSection) {
|
||||
case undefined:
|
||||
case 'memories':
|
||||
case 'assistant':
|
||||
return { mode: 'global', isInsideRepo: true, repoId }
|
||||
case 'schedules':
|
||||
return { mode: 'schedule', isInsideRepo: true, repoId }
|
||||
default:
|
||||
return { mode: 'hidden', isInsideRepo: false, repoId }
|
||||
}
|
||||
}
|
||||
|
||||
function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, isInsideRepo, repoId }: GlobalTabsArgs): TabDef[] {
|
||||
const navigateWithSearch = (params: URLSearchParams) => {
|
||||
const nextSearch = params.toString()
|
||||
navigate(nextSearch ? `${pathname}?${nextSearch}` : pathname, { replace: true })
|
||||
}
|
||||
|
||||
const handleFilesClick = () => {
|
||||
if (isInsideRepo && repoId) {
|
||||
const newParams = new URLSearchParams({ dialog: 'files' })
|
||||
navigate(`${pathname}?${newParams.toString()}`, { replace: true })
|
||||
const newParams = new URLSearchParams(search)
|
||||
newParams.set('dialog', 'files')
|
||||
navigateWithSearch(newParams)
|
||||
} else {
|
||||
open('files')
|
||||
}
|
||||
}
|
||||
|
||||
const handleAssistantClick = () => {
|
||||
if (repoId) {
|
||||
close()
|
||||
navigate(`/repos/${repoId}/assistant`)
|
||||
return
|
||||
}
|
||||
|
||||
close()
|
||||
navigate('/assistant')
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
key: 'repos',
|
||||
@@ -51,12 +101,11 @@ function buildGlobalTabs({ pathname, openSheet, open, navigate, hasPending, isIn
|
||||
active: openSheet === 'files',
|
||||
},
|
||||
{
|
||||
key: 'notifications',
|
||||
label: 'Alerts',
|
||||
icon: Bell,
|
||||
onClick: () => open('notifications'),
|
||||
badge: hasPending,
|
||||
active: openSheet === 'notifications',
|
||||
key: 'assistant',
|
||||
label: 'Assistant',
|
||||
icon: Bot,
|
||||
onClick: handleAssistantClick,
|
||||
active: false,
|
||||
},
|
||||
{
|
||||
key: 'schedules',
|
||||
@@ -137,42 +186,41 @@ const TabBarRow = memo(function TabBarRow({ tabs }: TabBarRowProps) {
|
||||
})
|
||||
|
||||
export const MobileTabBar = memo(function MobileTabBar() {
|
||||
const { pathname } = useLocation()
|
||||
const { pathname, search } = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const { openSheet, open } = useMobileTabBar()
|
||||
const { openSheet, open, close } = useMobileTabBar()
|
||||
const { scheduleTab, setScheduleTab } = useScheduleTab()
|
||||
const hasPending = usePendingAlerts()
|
||||
|
||||
const isOnRepoSchedules = /^\/repos\/\d+\/schedules$/.test(pathname)
|
||||
const isRepoMemories = /^\/repos\/\d+\/memories$/.test(pathname)
|
||||
const isMobile = useMobile()
|
||||
const isRoot = pathname === '/'
|
||||
const isGlobalSchedules = pathname === '/schedules'
|
||||
const isRepoDetail = /^\/repos\/\d+$/.test(pathname)
|
||||
const isInsideRepo = isRepoDetail || isOnRepoSchedules || isRepoMemories
|
||||
const isRepoSession = /^\/repos\/\d+\/sessions\/\w+/.test(pathname)
|
||||
const allow = isRoot || isGlobalSchedules || (isInsideRepo && !isRepoSession)
|
||||
|
||||
const repoIdMatch = pathname.match(/^\/repos\/(\d+)/)
|
||||
const repoId = repoIdMatch ? repoIdMatch[1] : null
|
||||
const routeState = useMemo(() => getMobileTabRouteState(pathname), [pathname])
|
||||
|
||||
const tabs = useMemo<TabDef[]>(
|
||||
() => (isOnRepoSchedules
|
||||
() => (routeState.mode === 'schedule'
|
||||
? buildScheduleTabs(scheduleTab, setScheduleTab)
|
||||
: buildGlobalTabs({
|
||||
pathname,
|
||||
openSheet,
|
||||
open,
|
||||
navigate,
|
||||
hasPending,
|
||||
isInsideRepo,
|
||||
repoId,
|
||||
})),
|
||||
[isOnRepoSchedules, scheduleTab, setScheduleTab, pathname, openSheet, open, navigate, hasPending, isInsideRepo, repoId],
|
||||
pathname,
|
||||
search,
|
||||
openSheet,
|
||||
open,
|
||||
close,
|
||||
navigate,
|
||||
isInsideRepo: routeState.isInsideRepo,
|
||||
repoId: routeState.repoId,
|
||||
})),
|
||||
[
|
||||
routeState,
|
||||
scheduleTab,
|
||||
setScheduleTab,
|
||||
pathname,
|
||||
search,
|
||||
openSheet,
|
||||
open,
|
||||
close,
|
||||
navigate,
|
||||
],
|
||||
)
|
||||
|
||||
if (!isMobile) return null
|
||||
if (!allow) return null
|
||||
if (routeState.mode === 'hidden') return null
|
||||
|
||||
return <TabBarRow tabs={tabs} />
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
|
||||
import { listRepos } from '@/api/repos'
|
||||
@@ -24,6 +24,11 @@ function createWrapper() {
|
||||
)
|
||||
}
|
||||
|
||||
function LocationSpy() {
|
||||
const { pathname, search } = useLocation()
|
||||
return <div data-testid="location">{`${pathname}${search}`}</div>
|
||||
}
|
||||
|
||||
describe('RepoQuickSwitchSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -117,4 +122,46 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
fireEvent.click(screen.getByText('repo1'))
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('navigates directly to assistant when mobileTabAction is assistant', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo1.git',
|
||||
localPath: '/path/to/repo1',
|
||||
sourcePath: null,
|
||||
currentBranch: 'main',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<MemoryRouter initialEntries={['/schedules?mobileTab=repos&mobileTabAction=assistant']}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
|
||||
<LocationSpy />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('repo1'))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/assistant')
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -43,6 +43,13 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
|
||||
const pendingAction = new URLSearchParams(location.search).get('mobileTabAction')
|
||||
if (pendingAction === 'assistant') {
|
||||
navigate(`/repos/${id}/assistant`)
|
||||
return
|
||||
}
|
||||
|
||||
navigate(`/repos/${id}`, { replace: true })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
getAssistantModeStatus,
|
||||
initializeAssistantMode,
|
||||
} from '@/api/repos'
|
||||
import type { AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
|
||||
|
||||
export function useAssistantMode(repoId: number) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const statusQuery = useQuery<AssistantModeStatus>({
|
||||
queryKey: ['repo', repoId, 'assistant-mode'],
|
||||
queryFn: () => getAssistantModeStatus(repoId),
|
||||
enabled: !!repoId,
|
||||
})
|
||||
|
||||
const initializeMutation = useMutation({
|
||||
mutationFn: (options?: AssistantModeInitRequest) =>
|
||||
initializeAssistantMode(repoId, options),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['repo', repoId, 'assistant-mode'],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoading: statusQuery.isLoading,
|
||||
isError: statusQuery.isError,
|
||||
error: statusQuery.error,
|
||||
initialize: initializeMutation.mutateAsync,
|
||||
isInitializing: initializeMutation.isPending,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { useAssistantSessionLauncher } from './useAssistantSessionLauncher'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import { initializeAssistantMode } from '@/api/repos'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listSessions: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
initializeAssistantMode: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
initializeAssistantMode: mocks.initializeAssistantMode,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
OpenCodeClient: vi.fn(() => ({
|
||||
listSessions: mocks.listSessions,
|
||||
createSession: mocks.createSession,
|
||||
})),
|
||||
}))
|
||||
|
||||
describe('useAssistantSessionLauncher', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.initializeAssistantMode.mockResolvedValue({ directory: '/assistant' })
|
||||
})
|
||||
|
||||
it('opens the latest root session in the assistant directory', async () => {
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'older', directory: '/assistant', time: { updated: 10 } },
|
||||
{ id: 'newest-child', parentID: 'newest', directory: '/assistant', time: { updated: 40 } },
|
||||
{ id: 'different-directory', directory: '/other', time: { updated: 50 } },
|
||||
{ id: 'newest', directory: '/assistant', time: { updated: 30 } },
|
||||
])
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(initializeAssistantMode).toHaveBeenCalledWith(123)
|
||||
expect(OpenCodeClient).toHaveBeenCalledWith('http://localhost:5551', '/assistant')
|
||||
expect(onNavigate).toHaveBeenCalledWith('newest')
|
||||
expect(mocks.createSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('creates a session when the assistant directory has no root sessions', async () => {
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'other', directory: '/other', time: { updated: 50 } },
|
||||
])
|
||||
mocks.createSession.mockResolvedValue({ id: 'created' })
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(mocks.createSession).toHaveBeenCalledWith({ title: 'Assistant' })
|
||||
expect(onNavigate).toHaveBeenCalledWith('created')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useCallback } from 'react'
|
||||
import { initializeAssistantMode } from '@/api/repos'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
|
||||
interface UseAssistantSessionLauncherOptions {
|
||||
repoId: number
|
||||
opcodeUrl: string
|
||||
onNavigate: (sessionId: string) => void
|
||||
}
|
||||
|
||||
export function useAssistantSessionLauncher({
|
||||
repoId,
|
||||
opcodeUrl,
|
||||
onNavigate,
|
||||
}: UseAssistantSessionLauncherOptions) {
|
||||
const openAssistant = useCallback(async () => {
|
||||
const assistant = await initializeAssistantMode(repoId)
|
||||
const client = new OpenCodeClient(opcodeUrl, assistant.directory)
|
||||
const sessions = await client.listSessions()
|
||||
|
||||
const assistantDirectory = assistant.directory
|
||||
|
||||
const rootSessions = sessions.filter(
|
||||
(session) => !session.parentID
|
||||
)
|
||||
|
||||
const assistantSessions = rootSessions.filter(
|
||||
(session) => session.directory === assistantDirectory
|
||||
)
|
||||
|
||||
const newest = assistantSessions.sort(
|
||||
(a, b) => b.time.updated - a.time.updated
|
||||
)[0]
|
||||
|
||||
if (newest) {
|
||||
onNavigate(newest.id)
|
||||
} else {
|
||||
const session = await client.createSession({ title: 'Assistant' })
|
||||
onNavigate(session.id)
|
||||
}
|
||||
}, [repoId, opcodeUrl, onNavigate])
|
||||
|
||||
return { openAssistant }
|
||||
}
|
||||
@@ -25,10 +25,10 @@ describe('useSwipeBack', () => {
|
||||
|
||||
it('calls onClose when swipe completes and canBack is false', () => {
|
||||
mockCanBack.mockReturnValue(false)
|
||||
|
||||
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
@@ -39,7 +39,7 @@ describe('useSwipeBack', () => {
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 10, clientY: 100 }] as any,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
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 { useAssistantSessionLauncher } from "@/hooks/useAssistantSessionLauncher"
|
||||
import { useCreateSession } from "@/hooks/useOpenCode"
|
||||
import { useDialogParam } from "@/hooks/useDialogParam"
|
||||
import { useMemoryPluginStatus } from "@/hooks/useMemoryPluginStatus"
|
||||
import { useSSE } from "@/hooks/useSSE"
|
||||
import { OPENCODE_API_ENDPOINT } from "@/config"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Header } from "@/components/ui/header"
|
||||
import { SessionList } from "@/components/session/SessionList"
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"
|
||||
import { SourceControlPanel } from "@/components/source-control"
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"
|
||||
import { invalidateConfigCaches } from "@/lib/queryInvalidation"
|
||||
import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog"
|
||||
import { Brain, CalendarClock, FolderOpen, GitCommitHorizontal, Loader2, Plug, Plus, ShieldOff, Sparkles } from "lucide-react"
|
||||
|
||||
export function AssistantRedirect() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const queryClient = useQueryClient()
|
||||
const repoId = Number(id) || 0
|
||||
const showSessionList = new URLSearchParams(location.search).get('view') === 'sessions'
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files')
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp')
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills')
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl')
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions')
|
||||
const [switchConfigOpen, setSwitchConfigOpen] = useState(false)
|
||||
const [status, setStatus] = useState<"preparing" | "opening" | "creating" | "error">("preparing")
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT
|
||||
const { memoryPluginEnabled } = useMemoryPluginStatus()
|
||||
|
||||
const { data: repo } = useQuery({
|
||||
queryKey: ["repo", repoId],
|
||||
queryFn: () => getRepo(repoId),
|
||||
enabled: showSessionList && !!repoId,
|
||||
})
|
||||
|
||||
const handleNavigate = useCallback((sessionId: string) => {
|
||||
setStatus("opening")
|
||||
navigate(`/repos/${repoId}/sessions/${sessionId}?assistant=1`)
|
||||
}, [navigate, repoId])
|
||||
|
||||
const { openAssistant } = useAssistantSessionLauncher({
|
||||
repoId,
|
||||
opcodeUrl,
|
||||
onNavigate: handleNavigate,
|
||||
})
|
||||
|
||||
const { data: assistantMode, isLoading: assistantModeLoading, error: assistantModeError } = useQuery({
|
||||
queryKey: ["repo", repoId, "assistant-mode"],
|
||||
queryFn: () => initializeAssistantMode(repoId),
|
||||
enabled: showSessionList && !!repoId,
|
||||
})
|
||||
|
||||
const assistantDirectory = assistantMode?.directory
|
||||
const assistantFileBasePath = assistantDirectory?.split('/').filter(Boolean).at(-1)
|
||||
|
||||
useSSE(opcodeUrl, assistantDirectory)
|
||||
|
||||
const createSessionMutation = useCreateSession(opcodeUrl, assistantDirectory, (session) => {
|
||||
navigate(`/repos/${repoId}/sessions/${session.id}?assistant=1`)
|
||||
})
|
||||
|
||||
const handleCreateSession = async () => {
|
||||
await createSessionMutation.mutateAsync({ agent: undefined })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
async function loadAndOpen() {
|
||||
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 })
|
||||
return
|
||||
}
|
||||
|
||||
await getRepo(repoId)
|
||||
if (cancelled) return
|
||||
setStatus("creating")
|
||||
await openAssistant()
|
||||
} catch (error) {
|
||||
if (cancelled) return
|
||||
setStatus("error")
|
||||
setErrorMessage(error instanceof Error ? error.message : "Failed to open Assistant")
|
||||
}
|
||||
}
|
||||
|
||||
loadAndOpen()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [repoId, openAssistant, navigate, showSessionList])
|
||||
|
||||
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.Title>Assistant</Header.Title>
|
||||
<Header.Actions>
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setMcpDialogOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<Plug className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">MCP</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSkillsDialogOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<Sparkles className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Skills</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSourceControlOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<GitCommitHorizontal className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Source</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setFileBrowserOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<FolderOpen className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Files</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setResetPermissionsOpen(true)} size="sm" className="hidden lg:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<ShieldOff className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Reset Permissions</span>
|
||||
</Button>
|
||||
{memoryPluginEnabled && (
|
||||
<Button variant="outline" onClick={() => navigate(`/repos/${repoId}/memories`)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => navigate(`/repos/${repoId}/schedules`)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<Button onClick={() => handleCreateSession()} disabled={!opcodeUrl || !assistantDirectory || createSessionMutation.isPending} size="sm" className="hidden sm:inline-flex bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
<span>New Session</span>
|
||||
</Button>
|
||||
<Button onClick={() => handleCreateSession()} disabled={!opcodeUrl || !assistantDirectory || createSessionMutation.isPending} size="sm" className="sm:hidden h-10 w-10 p-0 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105">
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{assistantModeError ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">Failed to load Assistant sessions</div>
|
||||
) : assistantModeLoading || !assistantMode ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">Loading Assistant sessions...</div>
|
||||
) : (
|
||||
<SessionList
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={assistantDirectory}
|
||||
onSelectSession={(sessionId) => navigate(`/repos/${repoId}/sessions/${sessionId}?assistant=1`)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{assistantDirectory && (
|
||||
<>
|
||||
<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} />
|
||||
<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} />
|
||||
</>
|
||||
)}
|
||||
{repo && (
|
||||
<SwitchConfigDialog
|
||||
open={switchConfigOpen}
|
||||
onOpenChange={setSwitchConfigOpen}
|
||||
repoId={repoId}
|
||||
currentConfigName={repo.openCodeConfigName}
|
||||
onConfigSwitched={(configName) => {
|
||||
queryClient.setQueryData(["repo", repoId], { ...repo, openCodeConfigName: configName })
|
||||
invalidateConfigCaches(queryClient)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-background">
|
||||
<div className="text-center max-w-md px-4">
|
||||
{status === "error" ? (
|
||||
<>
|
||||
<p className="text-muted-foreground mb-4">{errorMessage}</p>
|
||||
<Button
|
||||
onClick={() => navigate(`/repos/${repoId}`)}
|
||||
variant="outline"
|
||||
>
|
||||
Go Back
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => window.location.reload()}
|
||||
className="ml-2"
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">
|
||||
{status === "preparing" && "Preparing Assistant workspace..."}
|
||||
{status === "creating" && "Opening your last session chat..."}
|
||||
{status === "opening" && "Opening your last session chat..."}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -111,20 +111,16 @@ export function RepoDetail() {
|
||||
<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="/" />
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Header.Title>{repoName}</Header.Title>
|
||||
{isWorktree ? (
|
||||
<Badge className="text-xs px-1.5 sm:px-2.5 py-0.5 bg-purple-600/20 text-purple-400 border-purple-600/40" title="Worktree">
|
||||
<GitBranch className="h-3 w-3 sm:mr-1" />
|
||||
<span className="hidden sm:inline">WT: {currentBranch}</span>
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
<Header>
|
||||
<Header.BackButton to="/" />
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Header.Title>{repoName}</Header.Title>
|
||||
{isWorktree ? (
|
||||
<Badge className="text-xs px-1.5 sm:px-2.5 py-0.5 bg-purple-600/20 text-purple-400 border-purple-600/40" title="Worktree">
|
||||
<GitBranch className="h-3 w-3 sm:mr-1" />
|
||||
<span className="hidden sm:inline">WT: {currentBranch}</span>
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -186,42 +182,98 @@ export function RepoDetail() {
|
||||
{memoryPluginEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/memories`)}
|
||||
onClick={() => setMcpDialogOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
<Plug className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">MCP</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/schedules`)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="hidden sm:inline-flex bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
<span>New Session</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="sm:hidden h-10 w-10 p-0 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setSkillsDialogOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Sparkles className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Skills</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setSourceControlOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<GitCommitHorizontal className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Source</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setFileBrowserOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Files</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setResetPermissionsOpen(true)}
|
||||
size="sm"
|
||||
className="hidden lg:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<ShieldOff className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Reset Permissions</span>
|
||||
</Button>
|
||||
{memoryPluginEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/memories`)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/schedules`)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => navigate(`/repos/${repoId}/assistant`)}
|
||||
disabled={!opcodeUrl}
|
||||
size="sm"
|
||||
className="hidden sm:inline-flex bg-purple-600 hover:bg-purple-700 text-white transition-all duration-200 hover:scale-105"
|
||||
aria-label="Open Assistant"
|
||||
>
|
||||
<Bot className="w-4 h-4 mr-2" />
|
||||
<span>Assistant</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="hidden sm:inline-flex bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
<span>New Session</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="sm:hidden h-10 w-10 p-0 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{opcodeUrl && repoDirectory && (
|
||||
|
||||
@@ -24,7 +24,7 @@ export function Repos() {
|
||||
<Header.Title logo>OpenCode</Header.Title>
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Navigate } from "react-router-dom";
|
||||
import { useParams, useNavigate, Navigate, useLocation } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getRepo } from "@/api/repos";
|
||||
import { getRepo, initializeAssistantMode } from "@/api/repos";
|
||||
import { MessageThread } from "@/components/message/MessageThread";
|
||||
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
|
||||
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
|
||||
@@ -62,7 +62,9 @@ const compareMessageIds = (id1: string, id2: string): number => {
|
||||
export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const repoId = Number(id) || 0;
|
||||
const isAssistantSession = new URLSearchParams(location.search).get('assistant') === '1';
|
||||
const { preferences, updateSettings } = useSettings();
|
||||
const { open: openSettings } = useSettingsDialog();
|
||||
const messageContainerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -109,13 +111,20 @@ export function SessionDetail() {
|
||||
enabled: !!repoId,
|
||||
});
|
||||
|
||||
const { data: assistantMode, isLoading: assistantModeLoading } = useQuery({
|
||||
queryKey: ["repo", repoId, "assistant-mode"],
|
||||
queryFn: () => initializeAssistantMode(repoId),
|
||||
enabled: isAssistantSession && !!repoId,
|
||||
});
|
||||
|
||||
useRepoActivity(repoId, Boolean(repo));
|
||||
|
||||
const { memoryPluginEnabled } = useMemoryPluginStatus();
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
|
||||
const repoDirectory = repo?.fullPath;
|
||||
const repoDirectory = isAssistantSession ? assistantMode?.directory : repo?.fullPath;
|
||||
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
|
||||
|
||||
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory);
|
||||
const { data: session, isLoading: sessionLoading } = useSession(
|
||||
@@ -189,12 +198,12 @@ export function SessionDetail() {
|
||||
try {
|
||||
const newSession = await createSession.mutateAsync({ agent: undefined });
|
||||
if (newSession?.id) {
|
||||
navigate(`/repos/${repoId}/sessions/${newSession.id}`);
|
||||
navigate(`/repos/${repoId}/sessions/${newSession.id}${sessionRouteSuffix}`);
|
||||
}
|
||||
} catch {
|
||||
showToast.error('Failed to create new session');
|
||||
}
|
||||
}, [createSession, navigate, repoId]);
|
||||
}, [createSession, navigate, repoId, sessionRouteSuffix]);
|
||||
|
||||
const handleCompact = useCallback(async () => {
|
||||
if (!opcodeUrl || !sessionId) return;
|
||||
@@ -241,17 +250,17 @@ export function SessionDetail() {
|
||||
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
|
||||
const forkedSession = await client.forkSession(sessionId);
|
||||
if (forkedSession?.id) {
|
||||
navigate(`/repos/${repoId}/sessions/${forkedSession.id}`);
|
||||
navigate(`/repos/${repoId}/sessions/${forkedSession.id}${sessionRouteSuffix}`);
|
||||
showToast.success('Session forked');
|
||||
}
|
||||
} catch (error) {
|
||||
showToast.error(`Fork failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}, [opcodeUrl, sessionId, repoDirectory, navigate, repoId]);
|
||||
}, [opcodeUrl, sessionId, repoDirectory, navigate, repoId, sessionRouteSuffix]);
|
||||
|
||||
const handleCloseSession = useCallback(() => {
|
||||
navigate(`/repos/${repoId}`);
|
||||
}, [navigate, repoId]);
|
||||
navigate(isAssistantSession ? `/repos/${repoId}/assistant?view=sessions` : `/repos/${repoId}`);
|
||||
}, [navigate, repoId, isAssistantSession]);
|
||||
|
||||
const { leaderActive } = useKeyboardShortcuts({
|
||||
openModelDialog: () => setModelDialogOpen(true),
|
||||
@@ -312,14 +321,14 @@ export function SessionDetail() {
|
||||
}, [setFileBrowserOpen]);
|
||||
|
||||
const handleChildSessionClick = useCallback((childSessionId: string) => {
|
||||
navigate(`/repos/${repoId}/sessions/${childSessionId}`)
|
||||
}, [navigate, repoId]);
|
||||
navigate(`/repos/${repoId}/sessions/${childSessionId}${sessionRouteSuffix}`)
|
||||
}, [navigate, repoId, sessionRouteSuffix]);
|
||||
|
||||
const handleParentSessionClick = useCallback(() => {
|
||||
if (session?.parentID) {
|
||||
navigate(`/repos/${repoId}/sessions/${session.parentID}`)
|
||||
navigate(`/repos/${repoId}/sessions/${session.parentID}${sessionRouteSuffix}`)
|
||||
}
|
||||
}, [navigate, repoId, session?.parentID]);
|
||||
}, [navigate, repoId, session?.parentID, sessionRouteSuffix]);
|
||||
|
||||
const handleToggleDetails = useCallback(() => {
|
||||
const newValue = !preferences?.expandToolCalls
|
||||
@@ -366,6 +375,11 @@ export function SessionDetail() {
|
||||
);
|
||||
}
|
||||
|
||||
const workspaceDisplayName = isAssistantSession ? 'Assistant' : getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
|
||||
const assistantFileBasePath = assistantMode?.directory.split('/').filter(Boolean).at(-1);
|
||||
const workspaceBasePath = (isAssistantSession ? assistantFileBasePath : repo.localPath) ?? repo.localPath;
|
||||
const sessionBackPath = isAssistantSession ? `/repos/${repoId}/assistant?view=sessions` : `/repos/${repoId}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col"
|
||||
@@ -385,20 +399,20 @@ export function SessionDetail() {
|
||||
<span className="hidden sm:inline text-xs">Parent</span>
|
||||
</Button>
|
||||
<div className="hidden sm:block">
|
||||
<Header.BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
|
||||
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<Header.BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
|
||||
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
|
||||
)}
|
||||
<Header.EditableTitle
|
||||
value={session?.title || "Untitled Session"}
|
||||
onChange={handleSessionTitleUpdate}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}</span>}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{workspaceDisplayName}</span>}
|
||||
/>
|
||||
</div>
|
||||
<Header.Actions className="gap-2 sm:gap-4">
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<ContextUsageIndicator
|
||||
@@ -488,7 +502,7 @@ export function SessionDetail() {
|
||||
|
||||
<div className="flex-1 overflow-hidden flex flex-col relative">
|
||||
<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 || sessionLoading || messagesLoading ? (
|
||||
{repoLoading || assistantModeLoading || sessionLoading || messagesLoading ? (
|
||||
<MessageSkeleton />
|
||||
) : opcodeUrl && repoDirectory ? (
|
||||
<MessageThread
|
||||
@@ -595,7 +609,7 @@ export function SessionDetail() {
|
||||
directory={repoDirectory}
|
||||
activeSessionID={sessionId || undefined}
|
||||
onSelectSession={(sessionID) => {
|
||||
navigate(`/repos/${repoId}/sessions/${sessionID}`)
|
||||
navigate(`/repos/${repoId}/sessions/${sessionID}${sessionRouteSuffix}`)
|
||||
setSessionsDialogOpen(false)
|
||||
}}
|
||||
/>
|
||||
@@ -607,8 +621,8 @@ export function SessionDetail() {
|
||||
<FileBrowserSheet
|
||||
isOpen={fileBrowserOpen}
|
||||
onClose={handleFileBrowserClose}
|
||||
basePath={repo.localPath}
|
||||
repoName={getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
|
||||
basePath={workspaceBasePath}
|
||||
repoName={workspaceDisplayName}
|
||||
repoId={repoId}
|
||||
initialSelectedFile={selectedFilePath}
|
||||
/>
|
||||
@@ -637,7 +651,7 @@ export function SessionDetail() {
|
||||
isOpen={sourceControlOpen}
|
||||
onClose={() => setSourceControlOpen(false)}
|
||||
currentBranch={repo.currentBranch || repo.branch || "main"}
|
||||
repoName={getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
|
||||
repoName={workspaceDisplayName}
|
||||
/>
|
||||
|
||||
<ResetPermissionsDialog
|
||||
|
||||
@@ -1 +1 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
Reference in new issue
Block a user