mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
refactor: move assistant workspace install before OpenCode server start (#263)
* refactor: move assistant workspace install before OpenCode server start * refactor: skip assistant-mode status fetch on open, use repo fullPath and cached session
This commit is contained in:
1 parent
0d14e754e1
commit
0d384d6cf0
9 files changed
+151
-169
No files matched your search
@@ -45,7 +45,7 @@ import { createOpenCodeClient } from './services/opencode/client'
|
||||
import { NotificationService } from './services/notification'
|
||||
import { ScheduleRunner, ScheduleService } from './services/schedules'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
import { warmAssistantWorkspace } from './services/assistant-mode'
|
||||
import { installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
@@ -263,6 +263,12 @@ try {
|
||||
|
||||
await migrateGlobalSkills()
|
||||
|
||||
await installAssistantWorkspace({
|
||||
db,
|
||||
apiBaseUrl: `http://localhost:${PORT}/api/internal`,
|
||||
})
|
||||
logger.info('Assistant workspace installed')
|
||||
|
||||
ipcServer = await createIPCServer(process.env.STORAGE_PATH || undefined)
|
||||
await gitAuthService.initialize(ipcServer, db)
|
||||
logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`)
|
||||
@@ -273,11 +279,6 @@ try {
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
void warmAssistantWorkspace({
|
||||
db,
|
||||
apiBaseUrl: `http://localhost:${PORT}/api/internal`,
|
||||
openCodeClient,
|
||||
})
|
||||
} else {
|
||||
logger.warn(`OpenCode server unavailable after startup recovery: ${openCodeStatus.lastError ?? openCodeStatus.state}`)
|
||||
}
|
||||
|
||||
@@ -17,10 +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 type { OpenCodeClient } from './opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
const ASSISTANT_WARMUP_OPENCODE_TIMEOUT_MS = 90000
|
||||
|
||||
const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH
|
||||
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
|
||||
@@ -1080,22 +1077,12 @@ export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeS
|
||||
}
|
||||
}
|
||||
|
||||
export async function warmAssistantWorkspace(deps: {
|
||||
export async function installAssistantWorkspace(deps: {
|
||||
db: Database
|
||||
apiBaseUrl: string
|
||||
openCodeClient: OpenCodeClient
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const status = await ensureAssistantMode(buildAssistantRepo(), {
|
||||
db: deps.db,
|
||||
apiBaseUrl: deps.apiBaseUrl,
|
||||
})
|
||||
await deps.openCodeClient.getJson('/api/session?limit=1&order=desc', {
|
||||
directory: status.directory,
|
||||
signal: AbortSignal.timeout(ASSISTANT_WARMUP_OPENCODE_TIMEOUT_MS),
|
||||
})
|
||||
logger.info('Assistant workspace warmed')
|
||||
} catch (error) {
|
||||
logger.warn('Assistant workspace warmup failed (non-fatal):', error)
|
||||
}
|
||||
}): Promise<AssistantModeStatus> {
|
||||
return ensureAssistantMode(buildAssistantRepo(), {
|
||||
db: deps.db,
|
||||
apiBaseUrl: deps.apiBaseUrl,
|
||||
})
|
||||
}
|
||||
@@ -163,6 +163,8 @@ describe('Repo Routes', () => {
|
||||
const body = await res.json() as typeof mockStatus
|
||||
expect(body.repoId).toBe(1)
|
||||
expect(body.relativePath).toBe('repos/assistant')
|
||||
|
||||
expect(ensureAssistantMode).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -217,6 +219,17 @@ describe('Repo Routes', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = await res.json() as typeof mockStatus
|
||||
expect(body).toEqual(mockStatus)
|
||||
|
||||
expect(ensureAssistantMode).toHaveBeenCalledTimes(1)
|
||||
expect(ensureAssistantMode).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 1, localPath: 'repos/test-repo' }),
|
||||
expect.objectContaining({ db: mockDb, apiBaseUrl: 'http://localhost:5003/api/internal' }),
|
||||
expect.objectContaining({ overwriteAgentsMd: true }),
|
||||
)
|
||||
|
||||
expect(opencodeServerManager.clearStartupError).not.toHaveBeenCalled()
|
||||
expect(opencodeServerManager.restart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -2,9 +2,8 @@ import { describe, expect, it, beforeEach, afterEach } from 'bun:test'
|
||||
import path from 'path'
|
||||
import { readFile, stat, writeFile } from 'fs/promises'
|
||||
import { Hono } from 'hono'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, warmAssistantWorkspace } from '../../src/services/assistant-mode'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace } from '../../src/services/assistant-mode'
|
||||
import { createTempAssistantWorkspace, createTestDb, mockRepo } from '../helpers/assistant-workspace'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { createInternalRoutes } from '../../src/routes/internal'
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
@@ -609,7 +608,7 @@ describe('buildAssistantRepo', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('warmAssistantWorkspace', () => {
|
||||
describe('installAssistantWorkspace', () => {
|
||||
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
|
||||
let db: ReturnType<typeof createTestDb>
|
||||
const apiBaseUrl = 'http://localhost:5003/api/internal'
|
||||
@@ -620,34 +619,50 @@ describe('warmAssistantWorkspace', () => {
|
||||
})
|
||||
afterEach(async () => { await ws.cleanup() })
|
||||
|
||||
it('provisions the workspace and triggers a bounded directory-scoped session request', async () => {
|
||||
const getJsonCalls: Array<{ path: string; directory?: string }> = []
|
||||
const client = {
|
||||
getJson: async (requestPath: string, opts?: { directory?: string }) => {
|
||||
getJsonCalls.push({ path: requestPath, directory: opts?.directory })
|
||||
return []
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
await warmAssistantWorkspace({ db, apiBaseUrl, openCodeClient: client })
|
||||
it('provisions the assistant workspace files without contacting OpenCode', async () => {
|
||||
const result = await installAssistantWorkspace({ db, apiBaseUrl })
|
||||
|
||||
const opencodeJson = await readFile(path.join(ws.assistantDir, 'opencode.json'), 'utf8')
|
||||
expect(JSON.parse(opencodeJson).default_agent).toBe('assistant')
|
||||
expect(getJsonCalls).toHaveLength(1)
|
||||
expect(getJsonCalls[0]?.path).toBe('/api/session?limit=1&order=desc')
|
||||
expect(getJsonCalls[0]?.directory).toBe(ws.assistantDir)
|
||||
|
||||
const agentsMd = await readFile(path.join(ws.assistantDir, 'AGENTS.md'), 'utf8')
|
||||
expect(agentsMd).toContain('Assistant Mode Workspace')
|
||||
|
||||
const assistantAgent = await readFile(path.join(ws.assistantDir, '.opencode/agents/assistant.md'), 'utf8')
|
||||
expect(assistantAgent).toContain('mode: primary')
|
||||
|
||||
expect(result.files.opencodeJson?.exists).toBe(true)
|
||||
expect(result.files.agentsMd?.exists).toBe(true)
|
||||
expect(result.defaultAgent?.exists).toBe(true)
|
||||
})
|
||||
|
||||
it('does not throw and still provisions the workspace when the session request fails', async () => {
|
||||
const client = {
|
||||
getJson: async () => { throw new Error('opencode unavailable') },
|
||||
} as unknown as OpenCodeClient
|
||||
it('is idempotent — second call does not recreate files and content is unchanged', async () => {
|
||||
await installAssistantWorkspace({ db, apiBaseUrl })
|
||||
|
||||
await expect(
|
||||
warmAssistantWorkspace({ db, apiBaseUrl, openCodeClient: client })
|
||||
).resolves.toBeUndefined()
|
||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
||||
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
|
||||
|
||||
const opencodeJson = await stat(path.join(ws.assistantDir, 'opencode.json'))
|
||||
expect(opencodeJson.isFile()).toBe(true)
|
||||
const firstContent = {
|
||||
opencodeJson: await readFile(opencodeJsonPath, 'utf8'),
|
||||
agentsMd: await readFile(agentsMdPath, 'utf8'),
|
||||
assistantAgent: await readFile(assistantAgentPath, 'utf8'),
|
||||
}
|
||||
|
||||
const result = await installAssistantWorkspace({ db, apiBaseUrl })
|
||||
|
||||
const secondContent = {
|
||||
opencodeJson: await readFile(opencodeJsonPath, 'utf8'),
|
||||
agentsMd: await readFile(agentsMdPath, 'utf8'),
|
||||
assistantAgent: await readFile(assistantAgentPath, 'utf8'),
|
||||
}
|
||||
|
||||
expect(secondContent.opencodeJson).toBe(firstContent.opencodeJson)
|
||||
expect(secondContent.agentsMd).toBe(firstContent.agentsMd)
|
||||
expect(secondContent.assistantAgent).toBe(firstContent.assistantAgent)
|
||||
|
||||
expect(result.files.opencodeJson?.created).toBe(false)
|
||||
expect(result.files.agentsMd?.created).toBe(false)
|
||||
expect(result.defaultAgent?.created).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -2,18 +2,12 @@ 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(),
|
||||
listSessionsPage: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
sendPromptAsync: vi.fn(),
|
||||
initializeAssistantMode: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
initializeAssistantMode: mocks.initializeAssistantMode,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
@@ -33,7 +27,6 @@ describe('useAssistantSessionLauncher', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
mocks.initializeAssistantMode.mockResolvedValue({ directory: '/assistant' })
|
||||
})
|
||||
|
||||
it('opens the latest root session in the assistant directory', async () => {
|
||||
@@ -49,6 +42,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
directory: '/assistant',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
@@ -56,7 +50,6 @@ describe('useAssistantSessionLauncher', () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(initializeAssistantMode).toHaveBeenCalledWith(123)
|
||||
expect(OpenCodeClient).toHaveBeenCalledWith('http://localhost:5551', '/assistant')
|
||||
expect(mocks.listSessionsPage).toHaveBeenCalledWith({ limit: 25, order: 'desc' })
|
||||
expect(mocks.listSessions).not.toHaveBeenCalled()
|
||||
@@ -83,6 +76,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
directory: '/assistant',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
@@ -96,26 +90,13 @@ describe('useAssistantSessionLauncher', () => {
|
||||
expect(onNavigate).toHaveBeenCalledWith('newest')
|
||||
})
|
||||
|
||||
it('notifies an existing assistant session when some generated updates were preserved', async () => {
|
||||
mocks.initializeAssistantMode.mockResolvedValue({
|
||||
directory: '/assistant',
|
||||
warnings: [
|
||||
{
|
||||
code: 'assistant-agents-md-preserved',
|
||||
path: '/assistant/AGENTS.md',
|
||||
message: 'Some Assistant Mode instruction updates were not applied because AGENTS.md appears to contain customized legacy assistant instructions. To regenerate the default workspace explanation, manually delete AGENTS.md and initialize Assistant Mode again.',
|
||||
},
|
||||
],
|
||||
})
|
||||
mocks.listSessionsPage.mockResolvedValue({
|
||||
items: [
|
||||
{ id: 'existing', directory: '/assistant', time: { updated: 10 } },
|
||||
],
|
||||
})
|
||||
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,
|
||||
}))
|
||||
|
||||
@@ -123,18 +104,11 @@ describe('useAssistantSessionLauncher', () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledWith('existing')
|
||||
expect(mocks.listSessionsPage).toHaveBeenCalledWith({ limit: 25, order: 'desc' })
|
||||
expect(mocks.sendPromptAsync).toHaveBeenCalledWith('existing', {
|
||||
parts: [
|
||||
expect.objectContaining({
|
||||
type: 'text',
|
||||
text: expect.stringContaining('some generated instruction changes were not applied'),
|
||||
}),
|
||||
],
|
||||
})
|
||||
const promptText = mocks.sendPromptAsync.mock.calls[0][1].parts[0].text as string
|
||||
expect(promptText).toContain('manually delete AGENTS.md')
|
||||
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 () => {
|
||||
@@ -148,6 +122,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
directory: '/assistant',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
@@ -191,6 +166,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
directory: '/assistant',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
@@ -218,6 +194,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
directory: '/assistant',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
@@ -228,4 +205,22 @@ describe('useAssistantSessionLauncher', () => {
|
||||
expect(onNavigate).toHaveBeenCalledWith('created')
|
||||
expect(mocks.sendPromptAsync).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects when the assistant directory is unavailable', async () => {
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await expect(result.current.openAssistant()).rejects.toThrow('Assistant workspace directory is unavailable')
|
||||
})
|
||||
|
||||
expect(OpenCodeClient).not.toHaveBeenCalled()
|
||||
expect(mocks.listSessionsPage).not.toHaveBeenCalled()
|
||||
expect(mocks.createSession).not.toHaveBeenCalled()
|
||||
expect(onNavigate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,12 +1,11 @@
|
||||
import { useCallback } from 'react'
|
||||
import { initializeAssistantMode } from '@/api/repos'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
|
||||
interface UseAssistantSessionLauncherOptions {
|
||||
repoId: number
|
||||
opcodeUrl: string
|
||||
directory?: string
|
||||
onNavigate: (sessionId: string) => void
|
||||
}
|
||||
|
||||
@@ -28,6 +27,14 @@ function setCachedAssistantSessionId(repoId: number, directory: string, sessionI
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -71,43 +78,12 @@ AGENTS.md explains the assistant workspace directory and points to the files Ope
|
||||
|
||||
Take your time exploring and customizing these settings. Let me know when you're ready to start coding, or if you have any questions about getting set up!`
|
||||
|
||||
function buildAssistantModeWarningsPrompt(assistant: AssistantModeStatus): string | undefined {
|
||||
if (!assistant.warnings?.length) return undefined
|
||||
|
||||
return [
|
||||
'Assistant Mode was updated, but some generated instruction changes were not applied.',
|
||||
'',
|
||||
...assistant.warnings.map((warning) => `- ${warning.message}`),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildAssistantWelcomePrompt(assistant: AssistantModeStatus): string {
|
||||
const warningsPrompt = buildAssistantModeWarningsPrompt(assistant)
|
||||
return warningsPrompt
|
||||
? `${ASSISTANT_WELCOME_PROMPT}\n\n${warningsPrompt}`
|
||||
: ASSISTANT_WELCOME_PROMPT
|
||||
}
|
||||
|
||||
async function sendAssistantWelcomePrompt(client: OpenCodeClient, sessionId: string, assistant: AssistantModeStatus): Promise<void> {
|
||||
async function sendAssistantWelcomePrompt(client: OpenCodeClient, sessionId: string): Promise<void> {
|
||||
await client.sendPromptAsync(sessionId, {
|
||||
parts: [
|
||||
{
|
||||
type: 'text',
|
||||
text: buildAssistantWelcomePrompt(assistant),
|
||||
},
|
||||
],
|
||||
}).catch(() => undefined)
|
||||
}
|
||||
|
||||
async function sendAssistantModeWarningsPrompt(client: OpenCodeClient, sessionId: string, assistant: AssistantModeStatus): Promise<void> {
|
||||
const warningsPrompt = buildAssistantModeWarningsPrompt(assistant)
|
||||
if (!warningsPrompt) return
|
||||
|
||||
await client.sendPromptAsync(sessionId, {
|
||||
parts: [
|
||||
{
|
||||
type: 'text',
|
||||
text: warningsPrompt,
|
||||
text: ASSISTANT_WELCOME_PROMPT,
|
||||
},
|
||||
],
|
||||
}).catch(() => undefined)
|
||||
@@ -116,26 +92,34 @@ async function sendAssistantModeWarningsPrompt(client: OpenCodeClient, sessionId
|
||||
export function useAssistantSessionLauncher({
|
||||
repoId,
|
||||
opcodeUrl,
|
||||
directory,
|
||||
onNavigate,
|
||||
}: UseAssistantSessionLauncherOptions) {
|
||||
const openAssistant = useCallback(async () => {
|
||||
const assistant = await initializeAssistantMode(repoId)
|
||||
const client = new OpenCodeClient(opcodeUrl, assistant.directory)
|
||||
const assistantDirectory = assistant.directory
|
||||
if (!directory) {
|
||||
throw new Error('Assistant workspace directory is unavailable')
|
||||
}
|
||||
|
||||
const newest = await getLatestAssistantSession(client, assistantDirectory)
|
||||
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, assistantDirectory, newest.id)
|
||||
setCachedAssistantSessionId(repoId, directory, newest.id)
|
||||
onNavigate(newest.id)
|
||||
void sendAssistantModeWarningsPrompt(client, newest.id, assistant)
|
||||
} else {
|
||||
const session = await client.createSession({ title: 'Assistant' })
|
||||
setCachedAssistantSessionId(repoId, assistantDirectory, session.id)
|
||||
setCachedAssistantSessionId(repoId, directory, session.id)
|
||||
onNavigate(session.id)
|
||||
void sendAssistantWelcomePrompt(client, session.id, assistant)
|
||||
void sendAssistantWelcomePrompt(client, session.id)
|
||||
}
|
||||
}, [repoId, opcodeUrl, onNavigate])
|
||||
}, [repoId, opcodeUrl, directory, onNavigate])
|
||||
|
||||
return { openAssistant }
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { useParams, useNavigate, useLocation } from "react-router-dom"
|
||||
import { useNavigate, useLocation } from "react-router-dom"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { getRepo, initializeAssistantMode } from "@/api/repos"
|
||||
import { getRepo } from "@/api/repos"
|
||||
import { useAssistantSessionLauncher } from "@/hooks/useAssistantSessionLauncher"
|
||||
import { useCreateSession } from "@/hooks/useOpenCode"
|
||||
import { useDialogParam } from "@/hooks/useDialogParam"
|
||||
@@ -22,11 +22,10 @@ import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog"
|
||||
import { Loader2, Plus } 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 repoId = 0
|
||||
const showSessionList = new URLSearchParams(location.search).get('view') === 'sessions'
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files')
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp')
|
||||
@@ -38,10 +37,9 @@ export function AssistantRedirect() {
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT
|
||||
const { data: repo } = useQuery({
|
||||
const { data: repo, isLoading: repoLoading, error: repoError } = useQuery({
|
||||
queryKey: ["repo", repoId],
|
||||
queryFn: () => getRepo(repoId),
|
||||
enabled: showSessionList && repoId !== undefined,
|
||||
})
|
||||
|
||||
const handleNavigate = useCallback((sessionId: string) => {
|
||||
@@ -55,16 +53,11 @@ export function AssistantRedirect() {
|
||||
const { openAssistant } = useAssistantSessionLauncher({
|
||||
repoId,
|
||||
opcodeUrl,
|
||||
directory: repo?.fullPath,
|
||||
onNavigate: handleNavigate,
|
||||
})
|
||||
|
||||
const { data: assistantMode, isLoading: assistantModeLoading, error: assistantModeError } = useQuery({
|
||||
queryKey: ["repo", repoId, "assistant-mode"],
|
||||
queryFn: () => initializeAssistantMode(repoId),
|
||||
enabled: showSessionList && repoId !== undefined,
|
||||
})
|
||||
|
||||
const assistantDirectory = assistantMode?.directory
|
||||
const assistantDirectory = repo?.fullPath
|
||||
const assistantFileBasePath = assistantDirectory?.split('/').filter(Boolean).at(-1)
|
||||
|
||||
useSSE(opcodeUrl, assistantDirectory)
|
||||
@@ -84,14 +77,8 @@ export function AssistantRedirect() {
|
||||
try {
|
||||
if (showSessionList) return
|
||||
setStatus("preparing")
|
||||
if (repoId <= 0) {
|
||||
if (cancelled) return
|
||||
setStatus("creating")
|
||||
await openAssistant()
|
||||
return
|
||||
}
|
||||
|
||||
await getRepo(repoId)
|
||||
if (repoLoading) return
|
||||
if (repoError || !repo?.fullPath) throw new Error("Failed to load Assistant workspace")
|
||||
if (cancelled) return
|
||||
setStatus("creating")
|
||||
await openAssistant()
|
||||
@@ -107,7 +94,7 @@ export function AssistantRedirect() {
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [repoId, openAssistant, navigate, showSessionList, id])
|
||||
}, [repo?.fullPath, repoError, repoLoading, openAssistant, showSessionList])
|
||||
|
||||
if (showSessionList) {
|
||||
return (
|
||||
@@ -129,9 +116,9 @@ export function AssistantRedirect() {
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{assistantModeError ? (
|
||||
{repoError ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">Failed to load Assistant sessions</div>
|
||||
) : assistantModeLoading || !assistantMode ? (
|
||||
) : repoLoading || !repo?.fullPath ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">Loading Assistant sessions...</div>
|
||||
) : (
|
||||
<SessionList
|
||||
@@ -204,7 +191,7 @@ export function AssistantRedirect() {
|
||||
<>
|
||||
<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 === "preparing" && "Opening Assistant..."}
|
||||
{status === "creating" && "Opening your last session chat..."}
|
||||
{status === "opening" && "Opening your last session chat..."}
|
||||
</p>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Navigate, useLocation } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getRepo, initializeAssistantMode } from "@/api/repos";
|
||||
import { getRepo } from "@/api/repos";
|
||||
import { MessageThread } from "@/components/message/MessageThread";
|
||||
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
|
||||
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
|
||||
@@ -111,20 +111,14 @@ export function SessionDetail() {
|
||||
const { data: repo, isLoading: repoLoading } = useQuery({
|
||||
queryKey: ["repo", repoId],
|
||||
queryFn: () => getRepo(repoId),
|
||||
enabled: !!repoId,
|
||||
});
|
||||
|
||||
const { data: assistantMode, isLoading: assistantModeLoading } = useQuery({
|
||||
queryKey: ["repo", repoId, "assistant-mode"],
|
||||
queryFn: () => initializeAssistantMode(repoId),
|
||||
enabled: isAssistantSession,
|
||||
enabled: id !== undefined,
|
||||
});
|
||||
|
||||
useRepoActivity(repoId, Boolean(repo));
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
|
||||
const repoDirectory = isAssistantSession ? (assistantMode?.directory || repo?.fullPath) : repo?.fullPath;
|
||||
const repoDirectory = repo?.fullPath;
|
||||
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
|
||||
|
||||
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId);
|
||||
@@ -179,7 +173,7 @@ export function SessionDetail() {
|
||||
}, [lastAssistantMessage, session?.time?.compacting, sessionStatus.type])
|
||||
const hasIncompleteMessages = lastAssistantMessage ? !('completed' in lastAssistantMessage.info.time && lastAssistantMessage.info.time.completed) : false;
|
||||
const isStreamingResponse = hasIncompleteMessages && isSessionActive;
|
||||
const assistantFileBasePath = assistantMode?.directory.split('/').filter(Boolean).at(-1);
|
||||
const assistantFileBasePath = repo?.fullPath.split('/').filter(Boolean).at(-1);
|
||||
const workspaceBasePath = (isAssistantSession ? assistantFileBasePath : repo?.localPath) ?? repo?.localPath;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -488,7 +482,7 @@ export function SessionDetail() {
|
||||
|
||||
<div className="relative flex-1 overflow-hidden flex flex-col">
|
||||
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + PROMPT_OVERLAY_CLEARANCE_PX }}>
|
||||
{repoLoading || assistantModeLoading || sessionLoading || messagesLoading ? (
|
||||
{repoLoading || sessionLoading || messagesLoading ? (
|
||||
<MessageSkeleton />
|
||||
) : opcodeUrl && repoDirectory ? (
|
||||
<MessageThread
|
||||
|
||||
@@ -116,8 +116,14 @@ vi.mock('@/contexts/EventContext', async (importOriginal) => {
|
||||
})
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
getRepo: vi.fn(() => Promise.resolve(null)),
|
||||
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/abs/assistant', warnings: [] })),
|
||||
getRepo: vi.fn((repoId: number) => Promise.resolve(repoId === 0 ? {
|
||||
id: 0,
|
||||
localPath: 'assistant',
|
||||
fullPath: '/abs/assistant',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 1,
|
||||
} : null)),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/model/ModelSelectDialog', () => ({
|
||||
@@ -236,7 +242,7 @@ describe('SessionDetail assistant loading at repoId=0', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('passes directory from assistantMode to RepoSkillsDialog once loaded', async () => {
|
||||
it('passes directory from assistant repo to RepoSkillsDialog once loaded', async () => {
|
||||
renderAssistantSession('sess-asst-1')
|
||||
|
||||
await waitFor(() => {
|
||||
|
||||
Reference in new issue
Block a user