From 36b8f1453f2bb5337223c798c258ed94919bd21c Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 31 May 2026 16:07:12 -0400 Subject: [PATCH] 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 --- backend/src/index.ts | 6 ++ backend/src/routes/repos.ts | 75 ++------------------ backend/src/services/assistant-mode.ts | 37 ++++++++++ backend/src/services/schedules.ts | 19 +---- backend/test/services/assistant-mode.test.ts | 57 ++++++++++++++- 5 files changed, 108 insertions(+), 86 deletions(-) diff --git a/backend/src/index.ts b/backend/src/index.ts index 35811f8a..689a8e50 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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}`) } diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 4b2cdd7c..f12988c4 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -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 { @@ -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) diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index 586da57e..b8c1e3f7 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -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 { + 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) + } +} diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 3c221356..04b31353 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -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) { diff --git a/backend/test/services/assistant-mode.test.ts b/backend/test/services/assistant-mode.test.ts index 6c68f718..297025d1 100644 --- a/backend/test/services/assistant-mode.test.ts +++ b/backend/test/services/assistant-mode.test.ts @@ -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> + let db: ReturnType + 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) + }) +})