mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
refactor: persist assistant repo in database with ID migration (#271)
This commit is contained in:
1 parent
0d384d6cf0
commit
8133b655b0
12 files changed
+188
-112
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo, CreateRepoInput } from '../types/repo'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import path from 'path'
|
||||
|
||||
@@ -41,6 +42,13 @@ function rowToRepo(row: RepoRow): Repo {
|
||||
}
|
||||
}
|
||||
|
||||
const TABLES_WITH_REPO_ID = ['schedule_jobs', 'schedule_runs', 'repo_settings'] as const
|
||||
type RepoIdTable = typeof TABLES_WITH_REPO_ID[number]
|
||||
|
||||
function updateRepoIdReference(db: Database, tableName: RepoIdTable, fromRepoId: number, toRepoId: number): void {
|
||||
db.prepare(`UPDATE ${tableName} SET repo_id = ? WHERE repo_id = ?`).run(toRepoId, fromRepoId)
|
||||
}
|
||||
|
||||
export function getRepoById(db: Database, id: number): Repo | null {
|
||||
const stmt = db.prepare('SELECT * FROM repos WHERE id = ?')
|
||||
const row = stmt.get(id) as RepoRow | undefined
|
||||
@@ -48,6 +56,70 @@ export function getRepoById(db: Database, id: number): Repo | null {
|
||||
return row ? rowToRepo(row) : null
|
||||
}
|
||||
|
||||
export function ensureAssistantRepo(db: Database): Repo {
|
||||
const now = Date.now()
|
||||
|
||||
const syncAssistantRepo = db.transaction(() => {
|
||||
const existingAssistantPathRow = db.prepare('SELECT id FROM repos WHERE local_path = ? AND id != ?')
|
||||
.get(ASSISTANT_REPO_PATH, ASSISTANT_REPO_ID) as { id: number } | undefined
|
||||
|
||||
if (existingAssistantPathRow) {
|
||||
for (const table of TABLES_WITH_REPO_ID) {
|
||||
updateRepoIdReference(db, table, existingAssistantPathRow.id, ASSISTANT_REPO_ID)
|
||||
}
|
||||
db.prepare('DELETE FROM repos WHERE id = ?').run(existingAssistantPathRow.id)
|
||||
}
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO repos (
|
||||
id,
|
||||
repo_url,
|
||||
local_path,
|
||||
source_path,
|
||||
branch,
|
||||
default_branch,
|
||||
clone_status,
|
||||
cloned_at,
|
||||
last_accessed_at,
|
||||
is_worktree,
|
||||
is_local
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
repo_url = excluded.repo_url,
|
||||
local_path = excluded.local_path,
|
||||
source_path = excluded.source_path,
|
||||
branch = excluded.branch,
|
||||
default_branch = excluded.default_branch,
|
||||
clone_status = excluded.clone_status,
|
||||
last_accessed_at = excluded.last_accessed_at,
|
||||
is_worktree = excluded.is_worktree,
|
||||
is_local = excluded.is_local
|
||||
`).run(
|
||||
ASSISTANT_REPO_ID,
|
||||
null,
|
||||
ASSISTANT_REPO_PATH,
|
||||
null,
|
||||
null,
|
||||
'main',
|
||||
'ready',
|
||||
now,
|
||||
now,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
})
|
||||
|
||||
syncAssistantRepo()
|
||||
|
||||
const repo = getRepoById(db, ASSISTANT_REPO_ID)
|
||||
if (!repo) {
|
||||
throw new Error('Failed to sync Assistant repository')
|
||||
}
|
||||
|
||||
return repo
|
||||
}
|
||||
|
||||
export function createRepo(db: Database, repo: CreateRepoInput): Repo {
|
||||
const normalizedPath = repo.localPath.trim().replace(/\/+$/, '')
|
||||
|
||||
@@ -209,8 +281,9 @@ export function updateRepoBranch(db: Database, id: number, branch: string): void
|
||||
}
|
||||
|
||||
export function deleteRepo(db: Database, id: number): void {
|
||||
db.prepare('DELETE FROM schedule_runs WHERE repo_id = ?').run(id)
|
||||
db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ?').run(id)
|
||||
for (const table of TABLES_WITH_REPO_ID) {
|
||||
db.prepare(`DELETE FROM ${table} WHERE repo_id = ?`).run(id)
|
||||
}
|
||||
const stmt = db.prepare('DELETE FROM repos WHERE id = ?')
|
||||
stmt.run(id)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
||||
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { createRepoGitRoutes } from './repo-git'
|
||||
import { createScheduleRoutes } from './schedules'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
@@ -31,6 +32,10 @@ async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
|
||||
function resolveRepo(database: Database, id: number): Repo | null {
|
||||
return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null)
|
||||
}
|
||||
|
||||
export function createRepoRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
@@ -122,7 +127,7 @@ app.get('/', async (c) => {
|
||||
const reposWithCurrentBranch = await Promise.all(
|
||||
repos.map(async (repo) => {
|
||||
const env = gitAuthService.getGitEnvironment()
|
||||
const currentBranch = await repoService.getCurrentBranch(repo, env)
|
||||
const currentBranch = repo.id === ASSISTANT_REPO_ID ? undefined : await repoService.getCurrentBranch(repo, env)
|
||||
return { ...repo, currentBranch }
|
||||
})
|
||||
)
|
||||
@@ -157,14 +162,13 @@ app.get('/', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
|
||||
const isAssistant = id === 0
|
||||
const repo: Repo | null = isAssistant ? buildAssistantRepo() : getRepoById(database, id)
|
||||
const repo: Repo | null = resolveRepo(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const currentBranch = isAssistant ? undefined : await repoService.getCurrentBranch(repo, gitAuthService.getGitEnvironment())
|
||||
const currentBranch = id === ASSISTANT_REPO_ID ? undefined : await repoService.getCurrentBranch(repo, gitAuthService.getGitEnvironment())
|
||||
|
||||
return c.json({ ...repo, currentBranch })
|
||||
} catch (error: unknown) {
|
||||
@@ -267,6 +271,11 @@ app.get('/', async (c) => {
|
||||
app.delete('/:id', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
|
||||
if (id === ASSISTANT_REPO_ID) {
|
||||
return c.json({ error: 'Cannot delete the assistant repository' }, 403)
|
||||
}
|
||||
|
||||
const repo = getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
@@ -480,7 +489,7 @@ app.get('/', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
|
||||
const repo: Repo | null = id === 0 ? buildAssistantRepo() : getRepoById(database, id)
|
||||
const repo: Repo | null = resolveRepo(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
@@ -498,7 +507,7 @@ app.get('/', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
|
||||
const repo: Repo | null = id === 0 ? buildAssistantRepo() : getRepoById(database, id)
|
||||
const repo: Repo | null = resolveRepo(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
|
||||
@@ -17,6 +17,7 @@ import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH } from '@opencode-manager/shared
|
||||
import { getReposPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { ensureAssistantRepo } from '../db/queries'
|
||||
|
||||
|
||||
const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH
|
||||
@@ -1081,7 +1082,9 @@ export async function installAssistantWorkspace(deps: {
|
||||
db: Database
|
||||
apiBaseUrl: string
|
||||
}): Promise<AssistantModeStatus> {
|
||||
return ensureAssistantMode(buildAssistantRepo(), {
|
||||
const assistantRepo = ensureAssistantRepo(deps.db)
|
||||
|
||||
return ensureAssistantMode(assistantRepo, {
|
||||
db: deps.db,
|
||||
apiBaseUrl: deps.apiBaseUrl,
|
||||
})
|
||||
|
||||
@@ -1080,6 +1080,8 @@ export class ScheduleService {
|
||||
|
||||
private assertRepo(repoId: number) {
|
||||
if (repoId === ASSISTANT_REPO_ID) {
|
||||
const repo = getRepoById(this.db, ASSISTANT_REPO_ID)
|
||||
if (repo) return repo
|
||||
return { ...buildAssistantRepo(), lastAccessedAt: Date.now(), isLocal: true, currentBranch: undefined }
|
||||
}
|
||||
const repo = getRepoById(this.db, repoId)
|
||||
|
||||
@@ -259,27 +259,25 @@ describe('Database Queries', () => {
|
||||
|
||||
describe('deleteRepo', () => {
|
||||
it('should delete repo schedules before deleting repo by ID', () => {
|
||||
const deleteRunsStmt = {
|
||||
run: vi.fn().mockReturnValue({ changes: 2 })
|
||||
}
|
||||
const deleteJobsStmt = {
|
||||
run: vi.fn().mockReturnValue({ changes: 1 })
|
||||
}
|
||||
const deleteRepoStmt = {
|
||||
run: vi.fn().mockReturnValue({ changes: 1 })
|
||||
}
|
||||
const deleteRunsStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
|
||||
const deleteJobsStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
|
||||
const deleteSettingsStmt = { run: vi.fn().mockReturnValue({ changes: 0 }) }
|
||||
const deleteRepoStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
|
||||
mockDb.prepare
|
||||
.mockReturnValueOnce(deleteRunsStmt)
|
||||
.mockReturnValueOnce(deleteJobsStmt)
|
||||
.mockReturnValueOnce(deleteSettingsStmt)
|
||||
.mockReturnValueOnce(deleteRepoStmt)
|
||||
|
||||
db.deleteRepo(mockDb, 1)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_runs WHERE repo_id = ?')
|
||||
expect(deleteRunsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
|
||||
expect(deleteJobsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(3,
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_runs WHERE repo_id = ?')
|
||||
expect(deleteRunsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(3, 'DELETE FROM repo_settings WHERE repo_id = ?')
|
||||
expect(deleteSettingsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(4,
|
||||
'DELETE FROM repos WHERE id = ?'
|
||||
)
|
||||
expect(deleteRepoStmt.run).toHaveBeenCalledWith(1)
|
||||
|
||||
@@ -9,6 +9,7 @@ import { ScheduleService } from '../../src/services/schedules'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { createOpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { getRepoById } from '../../src/db/queries'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
|
||||
describe('buildSchedulesSkill', () => {
|
||||
@@ -634,6 +635,61 @@ describe('installAssistantWorkspace', () => {
|
||||
expect(result.files.opencodeJson?.exists).toBe(true)
|
||||
expect(result.files.agentsMd?.exists).toBe(true)
|
||||
expect(result.defaultAgent?.exists).toBe(true)
|
||||
expect(result.repoId).toBe(0)
|
||||
|
||||
const assistantRepo = getRepoById(db, 0)
|
||||
expect(assistantRepo?.id).toBe(0)
|
||||
expect(assistantRepo?.localPath).toBe('assistant')
|
||||
expect(assistantRepo?.fullPath).toBe(ws.assistantDir)
|
||||
expect(assistantRepo?.cloneStatus).toBe('ready')
|
||||
expect(assistantRepo?.defaultBranch).toBe('main')
|
||||
})
|
||||
|
||||
it('repairs an assistant row created with a non-zero id', async () => {
|
||||
db.prepare(`
|
||||
INSERT INTO repos (
|
||||
id,
|
||||
repo_url,
|
||||
local_path,
|
||||
source_path,
|
||||
branch,
|
||||
default_branch,
|
||||
clone_status,
|
||||
cloned_at,
|
||||
last_accessed_at,
|
||||
is_worktree,
|
||||
is_local
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(99, null, 'assistant', null, null, 'main', 'ready', Date.now(), Date.now(), 0, 0)
|
||||
db.prepare(`
|
||||
INSERT INTO schedule_jobs (
|
||||
repo_id,
|
||||
name,
|
||||
description,
|
||||
enabled,
|
||||
interval_minutes,
|
||||
schedule_mode,
|
||||
cron_expression,
|
||||
timezone,
|
||||
agent_slug,
|
||||
prompt,
|
||||
model,
|
||||
skill_metadata,
|
||||
created_at,
|
||||
updated_at,
|
||||
last_run_at,
|
||||
next_run_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(99, 'Assistant job', null, 1, 60, 'interval', null, null, null, 'hello', null, null, Date.now(), Date.now(), null, null)
|
||||
|
||||
await installAssistantWorkspace({ db, apiBaseUrl })
|
||||
|
||||
expect(getRepoById(db, 99)).toBeNull()
|
||||
const assistantRepo = getRepoById(db, 0)
|
||||
expect(assistantRepo?.localPath).toBe('assistant')
|
||||
|
||||
const migratedJob = db.prepare('SELECT repo_id FROM schedule_jobs WHERE name = ?').get('Assistant job') as { repo_id: number }
|
||||
expect(migratedJob.repo_id).toBe(0)
|
||||
})
|
||||
|
||||
it('is idempotent — second call does not recreate files and content is unchanged', async () => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -51,7 +51,6 @@ export function AssistantRedirect() {
|
||||
}, [navigate, repoId, showSessionList])
|
||||
|
||||
const { openAssistant } = useAssistantSessionLauncher({
|
||||
repoId,
|
||||
opcodeUrl,
|
||||
directory: repo?.fullPath,
|
||||
onNavigate: handleNavigate,
|
||||
|
||||
Reference in new issue
Block a user