feat(assistant): warm assistant workspace on startup and extract buildAssistantRepo (#246)

* feat(assistant): warm assistant workspace on startup and extract buildAssistantRepo

* feat(notification): rich notification content with shared format helpers (#245)

* loop: notification-format completed after 2 iterations

* refactor: deduplicate permission display logic into shared package

* refactor: consolidate assistant repo construction into buildAssistantRepo
This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-31 16:07:12 -04:00
1 parent 626a4c42d1
commit 36b8f1453f
5 files changed
+108 -86

No files matched your search

+6
View File
@@ -45,6 +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 { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
import { OpenCodeSupervisor } from './services/opencode-supervisor'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
@@ -272,6 +273,11 @@ 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}`)
}
+7 -68
View File
@@ -18,7 +18,7 @@ import { createRepoGitRoutes } from './repo-git'
import { createScheduleRoutes } from './schedules'
import type { GitAuthService } from '../services/git-auth'
import { ScheduleService } from '../services/schedules'
import { ensureAssistantMode, getAssistantModeStatus, getAssistantModeDirectory } from '../services/assistant-mode'
import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode'
import path from 'path'
async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
@@ -156,31 +156,10 @@ app.get('/', async (c) => {
app.get('/:id', async (c) => {
try {
const id = parseInt(c.req.param('id'))
let repo: Repo | null
let isAssistant = false
if (id === 0) {
isAssistant = true
repo = {
id: 0,
repoUrl: undefined,
localPath: 'assistant',
sourcePath: undefined,
fullPath: getAssistantModeDirectory(),
branch: undefined,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
lastPulled: undefined,
lastAccessedAt: undefined,
openCodeConfigName: undefined,
isWorktree: false,
isLocal: false,
}
} else {
repo = getRepoById(database, id)
}
const isAssistant = id === 0
const repo: Repo | null = isAssistant ? buildAssistantRepo() : getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
@@ -499,27 +478,7 @@ app.get('/', async (c) => {
try {
const id = parseInt(c.req.param('id'))
let repo: Repo | null
if (id === 0) {
repo = {
id: 0,
repoUrl: undefined,
localPath: 'assistant',
sourcePath: undefined,
fullPath: '',
branch: undefined,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
lastPulled: undefined,
lastAccessedAt: undefined,
openCodeConfigName: undefined,
isWorktree: false,
isLocal: false,
}
} else {
repo = getRepoById(database, id)
}
const repo: Repo | null = id === 0 ? buildAssistantRepo() : getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
@@ -537,27 +496,7 @@ app.get('/', async (c) => {
try {
const id = parseInt(c.req.param('id'))
let repo: Repo | null
if (id === 0) {
repo = {
id: 0,
repoUrl: undefined,
localPath: 'assistant',
sourcePath: undefined,
fullPath: '',
branch: undefined,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
lastPulled: undefined,
lastAccessedAt: undefined,
openCodeConfigName: undefined,
isWorktree: false,
isLocal: false,
}
} else {
repo = getRepoById(database, id)
}
const repo: Repo | null = id === 0 ? buildAssistantRepo() : getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
+37
View File
@@ -16,6 +16,10 @@ import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
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'
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
@@ -46,6 +50,19 @@ export function getAssistantModeDirectory(): string {
return resolvedAssistantDir
}
export function buildAssistantRepo(): Repo {
return {
id: 0,
localPath: ASSISTANT_MODE_DIR,
fullPath: getAssistantModeDirectory(),
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
isWorktree: false,
isLocal: false,
}
}
function getInternalTokenPath(assistantDir: string): string {
return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_INTERNAL_TOKEN_FILENAME)
}
@@ -1057,3 +1074,23 @@ export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeS
},
}
}
export async function warmAssistantWorkspace(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('/session', {
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)
}
}
+2 -17
View File
@@ -38,7 +38,7 @@ import type { OpenCodeClient } from './opencode/client'
import { sseAggregator, type SSEEvent } from './sse-aggregator'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
import { getAssistantModeDirectory } from './assistant-mode'
import { buildAssistantRepo } from './assistant-mode'
class ScheduleServiceError extends Error {
status: number
@@ -1057,22 +1057,7 @@ export class ScheduleService {
private assertRepo(repoId: number) {
if (repoId === 0) {
const assistantDir = getAssistantModeDirectory()
return {
id: 0,
repoUrl: undefined,
localPath: 'assistant',
fullPath: assistantDir,
sourcePath: undefined,
branch: undefined,
currentBranch: undefined,
defaultBranch: 'main',
cloneStatus: 'ready' as const,
clonedAt: Date.now(),
lastAccessedAt: Date.now(),
isWorktree: false,
isLocal: true,
}
return { ...buildAssistantRepo(), lastAccessedAt: Date.now(), isLocal: true, currentBranch: undefined }
}
const repo = getRepoById(this.db, repoId)
if (!repo) {
+56 -1
View File
@@ -2,8 +2,9 @@ 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 } from '../../src/services/assistant-mode'
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, warmAssistantWorkspace } 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'
@@ -588,3 +589,57 @@ describe('assistant-mode end-to-end', () => {
expect(Array.isArray(body.jobs)).toBe(true)
})
})
describe('buildAssistantRepo', () => {
it('returns the synthetic assistant repo with id 0', () => {
const repo = buildAssistantRepo()
expect(repo.id).toBe(0)
expect(repo.localPath).toBe('assistant')
expect(repo.cloneStatus).toBe('ready')
expect(repo.repoUrl).toBeUndefined()
expect(repo.isWorktree).toBe(false)
})
})
describe('warmAssistantWorkspace', () => {
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
let db: ReturnType<typeof createTestDb>
const apiBaseUrl = 'http://localhost:5003/api/internal'
beforeEach(async () => {
ws = await createTempAssistantWorkspace()
db = createTestDb()
})
afterEach(async () => { await ws.cleanup() })
it('provisions the workspace and triggers a 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 })
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('/session')
expect(getJsonCalls[0]?.directory).toBe(ws.assistantDir)
})
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
await expect(
warmAssistantWorkspace({ db, apiBaseUrl, openCodeClient: client })
).resolves.toBeUndefined()
const opencodeJson = await stat(path.join(ws.assistantDir, 'opencode.json'))
expect(opencodeJson.isFile()).toBe(true)
})
})