refactor: persist assistant repo in database with ID migration (#271)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-09 14:46:39 -04:00
1 parent 0d384d6cf0
commit 8133b655b0
12 files changed
+188 -112

No files matched your search

@@ -8,8 +8,8 @@ import { cn, getRepoDisplayName } from '@/lib/utils'
import { listRepos } from '@/api/repos'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { FolderGit2, Check, Plus, House } from 'lucide-react'
import { isAssistantPath, getAssistantPath } from '@/lib/navigation'
import { useUrlParams } from '@/hooks/useUrlParams'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
interface RepoQuickSwitchSheetProps {
isOpen: boolean
@@ -23,13 +23,10 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
const [searchQuery, setSearchQuery] = useState('')
const [addRepoOpen, setAddRepoOpen] = useState(false)
const isAssistantRoute = useMemo(() => isAssistantPath(location.pathname), [location.pathname])
const activeRepoId = useMemo(() => {
if (isAssistantRoute) return null
const match = location.pathname.match(/^\/repos\/(\d+)/)
return match ? Number(match[1]) : null
}, [location.pathname, isAssistantRoute])
}, [location.pathname])
const { data: repos, isLoading } = useQuery({
queryKey: ['repos'],
@@ -37,15 +34,20 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
enabled: isOpen,
})
const regularRepos = useMemo(
() => repos?.filter((r) => r.id !== ASSISTANT_REPO_ID) ?? null,
[repos],
)
const filteredRepos = useMemo(() => {
if (!repos) return []
const sorted = [...repos].sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))
if (!regularRepos) return []
const sorted = [...regularRepos].sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))
if (!searchQuery.trim()) return sorted
const query = searchQuery.toLowerCase()
return sorted.filter((repo) =>
getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath).toLowerCase().includes(query)
)
}, [repos, searchQuery])
}, [regularRepos, searchQuery])
const isUrlControlledSheet = searchParams.get('mobileTab') === 'repos'
@@ -57,18 +59,6 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
}
const handleClick = (id: number) => {
const pendingAction = searchParams.get('mobileTabAction')
if (isAssistantRoute) {
navigateAndClose(`/repos/${id}`, { replace: true })
return
}
if (pendingAction === 'assistant') {
navigateAndClose(getAssistantPath())
return
}
if (id === activeRepoId) {
onClose()
return
+10 -4
View File
@@ -24,6 +24,7 @@ import {
type RepoSortMode,
} from "./repo-list-state"
import { RepoListControls } from "./RepoListControls"
import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils"
function formatActivityLabel(timestamp: number): string {
const now = Date.now()
@@ -175,6 +176,11 @@ export function RepoList() {
queryFn: listRepos,
})
const regularRepos = useMemo(
() => repos?.filter((r) => r.id !== ASSISTANT_REPO_ID) ?? null,
[repos],
)
const repoForDelete = useMemo(() => {
return repoToDelete ? repos?.find(r => r.id === repoToDelete) : null
}, [repoToDelete, repos])
@@ -188,7 +194,7 @@ export function RepoList() {
}
}, [selectedRepos, repos])
const repoIds = repos?.map((repo) => repo.id) || []
const repoIds = regularRepos?.map((repo) => repo.id) || []
const { data: gitStatuses } = useQuery({
queryKey: ["reposGitStatus", repoIds],
@@ -199,9 +205,9 @@ export function RepoList() {
})
const viewModels = useMemo(() => {
if (!repos) return []
return buildRepoViewModels(repos, gitStatuses)
}, [repos, gitStatuses])
if (!regularRepos) return []
return buildRepoViewModels(regularRepos, gitStatuses)
}, [regularRepos, gitStatuses])
const filteredViewModels = useMemo(() => {
const searched = filterReposBySearch(viewModels, searchQuery)
+4 -3
View File
@@ -3,6 +3,7 @@ import {
getAssistantModeStatus,
initializeAssistantMode,
} from '@/api/repos'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import type { AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
export function useAssistantMode(repoId?: number) {
@@ -10,13 +11,13 @@ export function useAssistantMode(repoId?: number) {
const statusQuery = useQuery<AssistantModeStatus>({
queryKey: ['assistant-mode'],
queryFn: () => getAssistantModeStatus(0),
enabled: repoId === 0,
queryFn: () => getAssistantModeStatus(ASSISTANT_REPO_ID),
enabled: repoId === ASSISTANT_REPO_ID,
})
const initializeMutation = useMutation({
mutationFn: (options?: AssistantModeInitRequest) =>
initializeAssistantMode(0, options),
initializeAssistantMode(ASSISTANT_REPO_ID, options),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['assistant-mode'],
@@ -40,7 +40,6 @@ describe('useAssistantSessionLauncher', () => {
})
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
directory: '/assistant',
onNavigate,
@@ -54,7 +53,6 @@ describe('useAssistantSessionLauncher', () => {
expect(mocks.listSessionsPage).toHaveBeenCalledWith({ limit: 25, order: 'desc' })
expect(mocks.listSessions).not.toHaveBeenCalled()
expect(onNavigate).toHaveBeenCalledWith('newest')
expect(localStorage.getItem('ocm:assistant:last-session:123:/assistant')).toBe('newest')
expect(mocks.createSession).not.toHaveBeenCalled()
expect(mocks.sendPromptAsync).not.toHaveBeenCalled()
})
@@ -74,7 +72,6 @@ describe('useAssistantSessionLauncher', () => {
})
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
directory: '/assistant',
onNavigate,
@@ -90,27 +87,6 @@ describe('useAssistantSessionLauncher', () => {
expect(onNavigate).toHaveBeenCalledWith('newest')
})
it('navigates directly to the cached assistant session without querying OpenCode', async () => {
localStorage.setItem('ocm:assistant:last-session:123:/assistant', 'cached')
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
directory: '/assistant',
onNavigate,
}))
await act(async () => {
await result.current.openAssistant()
})
expect(onNavigate).toHaveBeenCalledWith('cached')
expect(OpenCodeClient).not.toHaveBeenCalled()
expect(mocks.listSessionsPage).not.toHaveBeenCalled()
expect(mocks.createSession).not.toHaveBeenCalled()
expect(mocks.sendPromptAsync).not.toHaveBeenCalled()
})
it('creates a session when the assistant directory has no root sessions', async () => {
mocks.listSessionsPage.mockResolvedValue({
items: [
@@ -120,7 +96,6 @@ describe('useAssistantSessionLauncher', () => {
mocks.createSession.mockResolvedValue({ id: 'created' })
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
directory: '/assistant',
onNavigate,
@@ -140,7 +115,6 @@ describe('useAssistantSessionLauncher', () => {
],
})
expect(onNavigate).toHaveBeenCalledWith('created')
expect(localStorage.getItem('ocm:assistant:last-session:123:/assistant')).toBe('created')
const promptCall = mocks.sendPromptAsync.mock.calls[0]
const promptText = promptCall[1].parts[0].text as string
@@ -164,7 +138,6 @@ describe('useAssistantSessionLauncher', () => {
mocks.sendPromptAsync.mockImplementation(() => promptPromise)
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
directory: '/assistant',
onNavigate,
@@ -192,7 +165,6 @@ describe('useAssistantSessionLauncher', () => {
mocks.sendPromptAsync.mockRejectedValueOnce(new Error('provider unavailable'))
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
directory: '/assistant',
onNavigate,
@@ -209,7 +181,6 @@ describe('useAssistantSessionLauncher', () => {
it('rejects when the assistant directory is unavailable', async () => {
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
onNavigate,
}))
@@ -3,7 +3,6 @@ import { OpenCodeClient } from '@/api/opencode'
import type { components } from '@/api/opencode-types'
interface UseAssistantSessionLauncherOptions {
repoId: number
opcodeUrl: string
directory?: string
onNavigate: (sessionId: string) => void
@@ -13,28 +12,6 @@ type OpenCodeSession = components['schemas']['Session']
const ASSISTANT_SESSION_LOOKUP_PAGE_SIZE = 25
const LAST_ASSISTANT_SESSION_KEY_PREFIX = 'ocm:assistant:last-session'
function getLastAssistantSessionKey(repoId: number, directory: string): string {
return `${LAST_ASSISTANT_SESSION_KEY_PREFIX}:${repoId}:${directory}`
}
function setCachedAssistantSessionId(repoId: number, directory: string, sessionId: string): void {
try {
localStorage.setItem(getLastAssistantSessionKey(repoId, directory), sessionId)
} catch {
return
}
}
function getCachedAssistantSessionId(repoId: number, directory: string): string | undefined {
try {
return localStorage.getItem(getLastAssistantSessionKey(repoId, directory)) ?? undefined
} catch {
return undefined
}
}
function isAssistantRootSession(session: OpenCodeSession, assistantDirectory: string): boolean {
return !session.parentID && session.directory === assistantDirectory
}
@@ -90,7 +67,6 @@ async function sendAssistantWelcomePrompt(client: OpenCodeClient, sessionId: str
}
export function useAssistantSessionLauncher({
repoId,
opcodeUrl,
directory,
onNavigate,
@@ -100,26 +76,18 @@ export function useAssistantSessionLauncher({
throw new Error('Assistant workspace directory is unavailable')
}
const cachedSessionId = getCachedAssistantSessionId(repoId, directory)
if (cachedSessionId) {
onNavigate(cachedSessionId)
return
}
const client = new OpenCodeClient(opcodeUrl, directory)
const newest = await getLatestAssistantSession(client, directory)
if (newest) {
setCachedAssistantSessionId(repoId, directory, newest.id)
onNavigate(newest.id)
} else {
const session = await client.createSession({ title: 'Assistant' })
setCachedAssistantSessionId(repoId, directory, session.id)
onNavigate(session.id)
void sendAssistantWelcomePrompt(client, session.id)
}
}, [repoId, opcodeUrl, directory, onNavigate])
}, [opcodeUrl, directory, onNavigate])
return { openAssistant }
}
-1
View File
@@ -51,7 +51,6 @@ export function AssistantRedirect() {
}, [navigate, repoId, showSessionList])
const { openAssistant } = useAssistantSessionLauncher({
repoId,
opcodeUrl,
directory: repo?.fullPath,
onNavigate: handleNavigate,