mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(assistant): self-configuring assistant mode (#244)
* test(backend): replace better-sqlite3 test mock with node:sqlite Reimplement the bun:sqlite test mock on top of node:sqlite with an explicit BEGIN/COMMIT/ROLLBACK transaction wrapper. * feat(assistant): self-configuring assistant mode Add a self-editable assistant workspace and the APIs that support it: - POST /assistant/reload disposes and re-bootstraps the assistant instance (directory-scoped, rate-limited) so agent.md edits apply. - Internal settings API accepts non-secret TTS/STT patches via dedicated partial schemas. - Strip the generated agent persona from opencode.json on repair so user-customized agents are preserved across config recovery. - Cache the last assistant session id to avoid redundant session listing on launch. * style(repo): align worktree and workspace tabs with primary/orange theme
This commit is contained in:
1 parent
eedbbfb94e
commit
dbd6866682
22 files changed
+733
-156
No files matched your search
@@ -9,7 +9,7 @@
|
||||
"build": "bun build src/index.ts --outdir=dist --target=bun",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "pnpm run test:bun && pnpm run test:vitest",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal-assistant.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts",
|
||||
"test:vitest": "vitest run",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:watch": "vitest --watch",
|
||||
|
||||
@@ -317,7 +317,7 @@ app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
|
||||
|
||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService))
|
||||
|
||||
const protectedApi = new Hono()
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { OpenCodeClient } from '../../services/opencode/client'
|
||||
import { getAssistantModeDirectory } from '../../services/assistant-mode'
|
||||
import { TokenBucketRateLimiter } from '../../utils/rate-limit'
|
||||
|
||||
export function createInternalAssistantRoutes(openCodeClient: OpenCodeClient) {
|
||||
const app = new Hono()
|
||||
const limiter = new TokenBucketRateLimiter({ capacity: 5, refillPerMs: 60_000 })
|
||||
|
||||
app.post('/reload', async (c) => {
|
||||
const token = (c.req.header('authorization') ?? '').slice('Bearer '.length)
|
||||
const limit = limiter.tryConsume(token || 'anon')
|
||||
if (!limit.allowed) {
|
||||
c.header('Retry-After', String(Math.ceil(limit.retryAfterMs / 1000)))
|
||||
return c.json({ error: 'Rate limit exceeded' }, 429)
|
||||
}
|
||||
|
||||
const directory = getAssistantModeDirectory()
|
||||
const response = await openCodeClient.forward({ method: 'POST', path: '/instance/dispose', directory })
|
||||
if (!response.ok) {
|
||||
return c.json({ error: 'Failed to reload assistant workspace' }, 502)
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { Database } from 'bun:sqlite'
|
||||
import type { ScheduleService } from '../../services/schedules'
|
||||
import type { NotificationService } from '../../services/notification'
|
||||
import type { SettingsService } from '../../services/settings'
|
||||
import type { OpenCodeClient } from '../../services/opencode/client'
|
||||
import { createScheduleRoutes } from '../schedules'
|
||||
import { createInternalTokenMiddleware } from '../../auth/internal-token-middleware'
|
||||
import { createInternalNotificationRoutes } from './notifications'
|
||||
@@ -11,12 +12,14 @@ import { createInternalRepoRoutes } from './repos'
|
||||
import { createInternalRepoSyncRoutes } from './repo-sync'
|
||||
import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
|
||||
import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
|
||||
import { createInternalAssistantRoutes } from './assistant'
|
||||
|
||||
export function createInternalRoutes(
|
||||
db: Database,
|
||||
scheduleService: ScheduleService,
|
||||
notificationService: NotificationService,
|
||||
settingsService: SettingsService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
) {
|
||||
const app = new Hono()
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
@@ -30,5 +33,6 @@ export function createInternalRoutes(
|
||||
repos.route('/', mirrorRoutes(db))
|
||||
app.route('/repos', repos)
|
||||
app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db))
|
||||
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
|
||||
return app
|
||||
}
|
||||
@@ -27,7 +27,28 @@ export function createInternalSettingsRoutes(settingsService: SettingsService) {
|
||||
return c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400)
|
||||
}
|
||||
|
||||
const updated = settingsService.updateSettings(parsed.data as Partial<UserPreferences>, userId)
|
||||
const patch = parsed.data
|
||||
const currentPrefs = settingsService.getSettings(userId).preferences
|
||||
const updates: Partial<UserPreferences> = {}
|
||||
for (const key of Object.keys(patch)) {
|
||||
if (key !== 'tts' && key !== 'stt') {
|
||||
(updates as Record<string, unknown>)[key] = (patch as Record<string, unknown>)[key]
|
||||
}
|
||||
}
|
||||
if (patch.tts) {
|
||||
if (!currentPrefs.tts?.apiKey) {
|
||||
return c.json({ error: 'TTS is not configured. Set up TTS (including credentials) in the UI before adjusting it.' }, 400)
|
||||
}
|
||||
updates.tts = { ...currentPrefs.tts, ...patch.tts }
|
||||
}
|
||||
if (patch.stt) {
|
||||
if (!currentPrefs.stt?.apiKey) {
|
||||
return c.json({ error: 'STT is not configured. Set up STT (including credentials) in the UI before adjusting it.' }, 400)
|
||||
}
|
||||
updates.stt = { ...currentPrefs.stt, ...patch.stt }
|
||||
}
|
||||
|
||||
const updated = settingsService.updateSettings(updates as Partial<UserPreferences>, userId)
|
||||
return c.json(updated)
|
||||
})
|
||||
|
||||
|
||||
@@ -150,8 +150,7 @@ function buildLegacyAssistantAgentPrompt(): string {
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildLegacyAssistantDefaultAgentMd(): string {
|
||||
const prompt = buildLegacyAssistantAgentPrompt()
|
||||
function buildAssistantDefaultAgentMdFromPrompt(prompt: string): string {
|
||||
const permission = buildAssistantAgentPermission()
|
||||
|
||||
return `---
|
||||
@@ -171,6 +170,10 @@ ${prompt}
|
||||
`
|
||||
}
|
||||
|
||||
function buildLegacyAssistantDefaultAgentMd(): string {
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildLegacyAssistantAgentPrompt())
|
||||
}
|
||||
|
||||
function matchesGeneratedAssistantAgentsMd(content: string): boolean {
|
||||
const currentHash = hashContent(buildAssistantAgentsMd())
|
||||
const legacyHash = hashContent(buildLegacyAssistantAgentsMd())
|
||||
@@ -180,17 +183,19 @@ function matchesGeneratedAssistantAgentsMd(content: string): boolean {
|
||||
|
||||
function matchesGeneratedAssistantDefaultAgentMd(content: string): boolean {
|
||||
const currentHash = hashContent(buildAssistantDefaultAgentMd())
|
||||
const previousHash = hashContent(buildPreviousAssistantDefaultAgentMd())
|
||||
const legacyHash = hashContent(buildLegacyAssistantDefaultAgentMd())
|
||||
const contentHash = hashContent(content)
|
||||
return contentHash === currentHash || contentHash === legacyHash
|
||||
return contentHash === currentHash || contentHash === previousHash || contentHash === legacyHash
|
||||
}
|
||||
|
||||
function matchesGeneratedAssistantAgentPrompt(content: unknown): content is string {
|
||||
if (typeof content !== 'string') return false
|
||||
const currentHash = hashContent(buildAssistantAgentPrompt())
|
||||
const previousHash = hashContent(buildPreviousAssistantAgentPrompt())
|
||||
const legacyHash = hashContent(buildLegacyAssistantAgentPrompt())
|
||||
const contentHash = hashContent(content)
|
||||
return contentHash === currentHash || contentHash === legacyHash
|
||||
return contentHash === currentHash || contentHash === previousHash || contentHash === legacyHash
|
||||
}
|
||||
|
||||
function containsLegacyAssistantAgentsGuidance(content: string): boolean {
|
||||
@@ -215,7 +220,7 @@ Assistant-specific instructions belong in \`.opencode/agents/assistant.md\`.
|
||||
`
|
||||
}
|
||||
|
||||
function buildAssistantAgentPrompt(): string {
|
||||
function buildPreviousAssistantAgentPrompt(): string {
|
||||
return [
|
||||
'You are the default Assistant Mode agent for OpenCode Manager.',
|
||||
'',
|
||||
@@ -239,6 +244,32 @@ function buildAssistantAgentPrompt(): string {
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildAssistantAgentPrompt(): string {
|
||||
return [
|
||||
'You are the default Assistant Mode agent for OpenCode Manager.',
|
||||
'',
|
||||
'This workspace is the shared assistant workspace for OpenCode Manager. Help the user manage repos, schedules, notifications, settings, and assistant behavior safely.',
|
||||
'',
|
||||
'## Self-Editing Rules',
|
||||
'',
|
||||
'Durable assistant instructions, behavior, and preferences belong in `.opencode/agents/assistant.md`. Edit that file when the user expresses lasting preferences or when you need to refine your behavior.',
|
||||
'',
|
||||
'The workspace directory explanation belongs in `AGENTS.md`. Keep that file focused on describing the directory contents and pointing to managed files.',
|
||||
'',
|
||||
'Preserve user-customized workspace files unless the user explicitly asks you to change them. Ask before making significant, destructive, or out-of-workspace changes.',
|
||||
'',
|
||||
'After editing `.opencode/agents/assistant.md`, load `manager-settings` and call `POST /assistant/reload` to apply changes. Always ask the user before reloading.',
|
||||
'',
|
||||
'## Skill Usage',
|
||||
'',
|
||||
'Use the workspace skills when relevant:',
|
||||
'- Load `repo-management` before `schedule-management` when you need a repo ID.',
|
||||
'- Load `schedule-management` for schedule jobs and runs.',
|
||||
'- Load `notifications` when the user should be notified about important events.',
|
||||
'- Load `manager-settings` when reading or safely updating UI preferences.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildAssistantAgentPermission(): { read: 'allow'; edit: 'allow'; glob: 'allow'; grep: 'allow'; list: 'allow'; bash: 'allow'; external_directory: 'ask' } {
|
||||
return {
|
||||
read: 'allow',
|
||||
@@ -251,34 +282,12 @@ function buildAssistantAgentPermission(): { read: 'allow'; edit: 'allow'; glob:
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAssistantDefaultAgentConfig() {
|
||||
return {
|
||||
description: 'Default OpenCode Manager assistant workspace agent',
|
||||
mode: 'primary',
|
||||
prompt: buildAssistantAgentPrompt(),
|
||||
permission: buildAssistantAgentPermission(),
|
||||
}
|
||||
function buildPreviousAssistantDefaultAgentMd(): string {
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildPreviousAssistantAgentPrompt())
|
||||
}
|
||||
|
||||
export function buildAssistantDefaultAgentMd(): string {
|
||||
const prompt = buildAssistantAgentPrompt()
|
||||
const permission = buildAssistantAgentPermission()
|
||||
|
||||
return `---
|
||||
description: Default OpenCode Manager assistant workspace agent
|
||||
mode: primary
|
||||
permission:
|
||||
read: ${permission.read}
|
||||
edit: ${permission.edit}
|
||||
glob: ${permission.glob}
|
||||
grep: ${permission.grep}
|
||||
list: ${permission.list}
|
||||
bash: ${permission.bash}
|
||||
external_directory: ${permission.external_directory}
|
||||
---
|
||||
|
||||
${prompt}
|
||||
`
|
||||
return buildAssistantDefaultAgentMdFromPrompt(buildAssistantAgentPrompt())
|
||||
}
|
||||
|
||||
function toLocalhostInternalBaseUrl(baseUrl: string): string {
|
||||
@@ -559,12 +568,16 @@ The following preference keys can be modified:
|
||||
- \`simpleChatMode\`, \`leaderKey\`, \`directShortcuts\`
|
||||
- \`keyboardShortcuts\`, \`customCommands\`, \`notifications\`
|
||||
- \`repoOrder\`, \`repoSortMode\`
|
||||
- \`tts\` — Non-secret TTS preferences (\`enabled\`, \`provider\`, \`autoPlay\`, \`voice\`, \`model\`, \`speed\`). TTS must already be configured in the UI (the endpoint returns 400 otherwise).
|
||||
- \`stt\` — Non-secret STT preferences (\`enabled\`, \`provider\`, \`model\`, \`language\`). STT must already be configured in the UI (the endpoint returns 400 otherwise).
|
||||
|
||||
**DO NOT attempt to set:**
|
||||
- \`gitCredentials\` - Git credentials must be managed via the full UI
|
||||
- \`gitIdentity\` - Git identity must be managed via the full UI
|
||||
- \`tts.apiKey\` - TTS credentials must be managed via the full UI
|
||||
- \`tts.endpoint\` - TTS endpoint must be managed via the full UI
|
||||
- \`stt.apiKey\` - STT credentials must be managed via the full UI
|
||||
- \`stt.endpoint\` - STT endpoint must be managed via the full UI
|
||||
- \`lastKnownGoodConfig\` - Internal state, do not modify
|
||||
- Any other keys not in the allowed list above
|
||||
|
||||
@@ -582,6 +595,25 @@ curl -X PATCH -H "Authorization: Bearer <token>" \\
|
||||
**Response:**
|
||||
Returns the updated settings object with the same structure as GET.
|
||||
|
||||
### POST /assistant/reload
|
||||
|
||||
Reload the assistant workspace by disposing the current OpenCode instance. Use this after editing \`.opencode/agents/assistant.md\` or \`opencode.json\` so changes take effect on the next message.
|
||||
|
||||
**Note:** Always confirm with the user before reloading, as it re-bootstraps the workspace.
|
||||
|
||||
**Rate Limiting:** 5 requests per minute per token. Returns \`429 Too Many Requests\` with \`Retry-After\` header when exceeded.
|
||||
|
||||
**Example:**
|
||||
\`\`\`bash
|
||||
curl -X POST -H "Authorization: Bearer <token>" \\
|
||||
"${internalBaseUrl}/assistant/reload"
|
||||
\`\`\`
|
||||
|
||||
**Response:**
|
||||
\`\`\`ts
|
||||
{ "success": true }
|
||||
\`\`\`
|
||||
|
||||
## Safety
|
||||
|
||||
- This API intentionally rejects any attempt to modify credentials, API keys, or other sensitive settings
|
||||
@@ -660,12 +692,10 @@ curl -H "Authorization: Bearer <token>" "${internalBaseUrl}/repos"
|
||||
export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
|
||||
const config: OpenCodeConfigInput = {
|
||||
default_agent: ASSISTANT_DEFAULT_AGENT_NAME,
|
||||
instructions: [
|
||||
'AGENTS.md',
|
||||
],
|
||||
instructions: ['AGENTS.md'],
|
||||
permission: buildAssistantAgentPermission(),
|
||||
agent: {
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: buildAssistantDefaultAgentConfig(),
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: { mode: 'primary' },
|
||||
},
|
||||
}
|
||||
|
||||
@@ -731,8 +761,8 @@ export async function ensureAssistantMode(
|
||||
const existingContent = await readFileContent(opencodeJsonPath)
|
||||
const existingConfig = JSON.parse(existingContent) as OpenCodeConfigInput
|
||||
const mergedConfig = mergeAssistantOpenCodeConfig(existingConfig)
|
||||
return assistantOpenCodeConfigPromptNeedsMigration(mergedConfig)
|
||||
? migrateGeneratedAssistantOpenCodePrompt(mergedConfig)
|
||||
return assistantOpenCodeConfigHasGeneratedAgentPersona(mergedConfig)
|
||||
? stripGeneratedAssistantAgentPersona(mergedConfig)
|
||||
: mergedConfig
|
||||
} catch {
|
||||
return buildAssistantOpenCodeConfig()
|
||||
@@ -748,8 +778,8 @@ export async function ensureAssistantMode(
|
||||
const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingConfig)
|
||||
? mergeAssistantOpenCodeConfig(existingConfig)
|
||||
: existingConfig
|
||||
const updatedConfig = assistantOpenCodeConfigPromptNeedsMigration(repairedConfig)
|
||||
? migrateGeneratedAssistantOpenCodePrompt(repairedConfig)
|
||||
const updatedConfig = assistantOpenCodeConfigHasGeneratedAgentPersona(repairedConfig)
|
||||
? stripGeneratedAssistantAgentPersona(repairedConfig)
|
||||
: repairedConfig
|
||||
|
||||
if (updatedConfig !== existingConfig) {
|
||||
@@ -890,26 +920,31 @@ function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInput): boolea
|
||||
const mode = (assistantAgent as { mode?: unknown }).mode
|
||||
if (mode !== 'primary' && mode !== 'all') return true
|
||||
if ((assistantAgent as { disable?: unknown }).disable === true) return true
|
||||
if (assistantOpenCodeConfigHasGeneratedAgentPersona(config)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
function assistantOpenCodeConfigPromptNeedsMigration(config: OpenCodeConfigInput): boolean {
|
||||
const prompt = (config.agent?.[ASSISTANT_DEFAULT_AGENT_NAME] as { prompt?: unknown } | undefined)?.prompt
|
||||
return matchesGeneratedAssistantAgentPrompt(prompt) && prompt !== buildAssistantAgentPrompt()
|
||||
function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigInput): boolean {
|
||||
const agent = config.agent?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
if (typeof agent !== 'object' || agent === null) return false
|
||||
const prompt = (agent as { prompt?: unknown }).prompt
|
||||
return matchesGeneratedAssistantAgentPrompt(prompt)
|
||||
}
|
||||
|
||||
function migrateGeneratedAssistantOpenCodePrompt(config: OpenCodeConfigInput): OpenCodeConfigInput {
|
||||
function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
|
||||
const mode = (agent as { mode?: unknown } | undefined)?.mode
|
||||
return mode === 'primary' || mode === 'all' ? mode : 'primary'
|
||||
}
|
||||
|
||||
function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInput): OpenCodeConfigInput {
|
||||
const existingAssistantAgent = config.agent?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
if (typeof existingAssistantAgent !== 'object' || existingAssistantAgent === null) return config
|
||||
const validMode = resolveValidAssistantMode(existingAssistantAgent)
|
||||
|
||||
return {
|
||||
...config,
|
||||
agent: {
|
||||
...(config.agent ?? {}),
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: {
|
||||
...existingAssistantAgent,
|
||||
prompt: buildAssistantAgentPrompt(),
|
||||
},
|
||||
[ASSISTANT_DEFAULT_AGENT_NAME]: { mode: validMode },
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -917,14 +952,23 @@ function migrateGeneratedAssistantOpenCodePrompt(config: OpenCodeConfigInput): O
|
||||
function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInput): OpenCodeConfigInput {
|
||||
const generated = buildAssistantOpenCodeConfig()
|
||||
const existingAssistantAgent = existing?.agent?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||
const existingMode = (existingAssistantAgent as { mode?: 'primary' | 'all' | unknown } | undefined)?.mode
|
||||
const validMode = existingMode === 'primary' || existingMode === 'all' ? existingMode : 'primary'
|
||||
const validMode = resolveValidAssistantMode(existingAssistantAgent)
|
||||
|
||||
const mergedAssistantAgent = {
|
||||
...generated.agent?.[ASSISTANT_DEFAULT_AGENT_NAME],
|
||||
...(typeof existingAssistantAgent === 'object' && existingAssistantAgent !== null ? existingAssistantAgent : {}),
|
||||
mode: validMode,
|
||||
disable: false,
|
||||
const existingIsGenerated = existingAssistantAgent != null &&
|
||||
typeof existingAssistantAgent === 'object' &&
|
||||
matchesGeneratedAssistantAgentPrompt(
|
||||
(existingAssistantAgent as { prompt?: unknown }).prompt,
|
||||
)
|
||||
|
||||
let mergedAssistantAgent: Record<string, unknown>
|
||||
if (existingIsGenerated) {
|
||||
mergedAssistantAgent = { mode: validMode }
|
||||
} else {
|
||||
mergedAssistantAgent = {
|
||||
...(typeof existingAssistantAgent === 'object' && existingAssistantAgent !== null ? existingAssistantAgent : {}),
|
||||
mode: validMode,
|
||||
disable: false,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
import DatabaseImpl from 'better-sqlite3'
|
||||
import type { Database as BetterSqlite3Database } from 'better-sqlite3'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
|
||||
// Adapter to make better-sqlite3 compatible with bun:sqlite API
|
||||
// Adapter to make node:sqlite compatible with bun:sqlite API
|
||||
export class Database {
|
||||
private db: BetterSqlite3Database
|
||||
private db: DatabaseSync
|
||||
|
||||
constructor(path: string) {
|
||||
this.db = new DatabaseImpl(path)
|
||||
this.db = new DatabaseSync(path)
|
||||
}
|
||||
|
||||
prepare(sql: string) {
|
||||
const stmt = this.db.prepare(sql)
|
||||
return {
|
||||
run: (...params: unknown[]) => stmt.run(...params),
|
||||
get: (...params: unknown[]) => stmt.get(...params),
|
||||
all: (...params: unknown[]) => stmt.all(...params),
|
||||
run: (...params: unknown[]) => (stmt.run as (...args: unknown[]) => void)(...params),
|
||||
get: (...params: unknown[]) => (stmt.get as (...args: unknown[]) => unknown)(...params),
|
||||
all: (...params: unknown[]) => (stmt.all as (...args: unknown[]) => unknown[])(...params),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,11 +22,22 @@ export class Database {
|
||||
}
|
||||
|
||||
run(sql: string, ...params: unknown[]) {
|
||||
return this.db.prepare(sql).run(...params)
|
||||
const stmt = this.db.prepare(sql)
|
||||
return (stmt.run as (...args: unknown[]) => void)(...params)
|
||||
}
|
||||
|
||||
transaction<T extends (...args: unknown[]) => void>(fn: T) {
|
||||
return this.db.transaction(fn)
|
||||
return (...args: unknown[]) => {
|
||||
this.db.exec('BEGIN')
|
||||
try {
|
||||
const result = fn(...args)
|
||||
this.db.exec('COMMIT')
|
||||
return result
|
||||
} catch (e) {
|
||||
this.db.exec('ROLLBACK')
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { createInternalRoutes } from '../../src/routes/internal'
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { getAssistantModeDirectory } from '../../src/services/assistant-mode'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
describe('internal/assistant routes', () => {
|
||||
let db: Database
|
||||
let scheduleService: ScheduleService
|
||||
let notificationService: NotificationService
|
||||
let settingsService: SettingsService
|
||||
let app: Hono
|
||||
let token: string
|
||||
let forwardMock: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
|
||||
forwardMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({}), { status: 200 }))
|
||||
const openCodeClient = {
|
||||
forward: forwardMock,
|
||||
forwardRaw: vi.fn(),
|
||||
getJson: vi.fn(),
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
scheduleService = new ScheduleService(db, openCodeClient)
|
||||
notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = getOrCreateInternalToken(db)
|
||||
})
|
||||
|
||||
it('POST /api/internal/assistant/reload returns 401 without bearer token', async () => {
|
||||
const res = await app.request('/api/internal/assistant/reload', { method: 'POST' })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('POST /api/internal/assistant/reload returns 200 with valid token', async () => {
|
||||
const res = await app.request('/api/internal/assistant/reload', {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { success: boolean }
|
||||
expect(body.success).toBe(true)
|
||||
})
|
||||
|
||||
it('forwards POST /instance/dispose with correct directory', async () => {
|
||||
await app.request('/api/internal/assistant/reload', {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(forwardMock).toHaveBeenCalledTimes(1)
|
||||
expect(forwardMock).toHaveBeenCalledWith({
|
||||
method: 'POST',
|
||||
path: '/instance/dispose',
|
||||
directory: getAssistantModeDirectory(),
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 429 after exceeding rate limit (5 calls/min)', async () => {
|
||||
const results: number[] = []
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const res = await app.request('/api/internal/assistant/reload', {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
results.push(res.status)
|
||||
}
|
||||
|
||||
// First 5 should succeed
|
||||
expect(results.slice(0, 5)).toEqual([200, 200, 200, 200, 200])
|
||||
// 6th should be rate limited
|
||||
expect(results[5]).toBe(429)
|
||||
})
|
||||
|
||||
it('429 response includes Retry-After header', async () => {
|
||||
// Burn through the 5 allowed calls
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await app.request('/api/internal/assistant/reload', {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
}
|
||||
|
||||
const res = await app.request('/api/internal/assistant/reload', {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('returns 502 when OpenCode responds non-2xx', async () => {
|
||||
forwardMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'Internal error' }), { status: 500 }),
|
||||
)
|
||||
const res = await app.request('/api/internal/assistant/reload', {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(res.status).toBe(502)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('Failed to reload assistant workspace')
|
||||
})
|
||||
|
||||
})
|
||||
@@ -26,7 +26,7 @@ describe('internal/notifications routes', () => {
|
||||
notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = getOrCreateInternalToken(db)
|
||||
})
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createInternalRoutes } from '../../src/routes/internal'
|
||||
import type { ScheduleService } from '../../src/services/schedules'
|
||||
import type { NotificationService } from '../../src/services/notification'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { Repo } from '../../src/types/repo'
|
||||
|
||||
const mockDb = {
|
||||
@@ -73,8 +74,18 @@ describe('internal-opencode-workspaces routes', () => {
|
||||
const scheduleService = {} as ScheduleService
|
||||
const notificationService = {} as NotificationService
|
||||
const settingsService = {} as SettingsService
|
||||
const openCodeClient = {
|
||||
forward: vi.fn(),
|
||||
forwardRaw: vi.fn(),
|
||||
getJson: vi.fn(),
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService))
|
||||
app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = 'test-internal-token'
|
||||
})
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ describe('internal-repos routes', () => {
|
||||
notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = getOrCreateInternalToken(db)
|
||||
})
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ describe('internal-schedules routes', () => {
|
||||
notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = getOrCreateInternalToken(db)
|
||||
})
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createOpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import type { UserPreferences } from '@opencode-manager/shared/types'
|
||||
|
||||
describe('internal/settings routes', () => {
|
||||
let db: Database
|
||||
@@ -26,7 +27,7 @@ describe('internal/settings routes', () => {
|
||||
notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = getOrCreateInternalToken(db)
|
||||
})
|
||||
|
||||
@@ -118,4 +119,151 @@ describe('internal/settings routes', () => {
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with { tts: { voice: "x", speed: 1.5 } } merges and preserves apiKey/endpoint', async () => {
|
||||
// Seed a full TTS config (including secrets) directly via settingsService
|
||||
settingsService.updateSettings({
|
||||
tts: {
|
||||
enabled: true,
|
||||
provider: 'external',
|
||||
autoPlay: false,
|
||||
endpoint: 'https://custom.endpoint',
|
||||
apiKey: 'sk-secret-123',
|
||||
voice: 'alloy',
|
||||
model: 'tts-1',
|
||||
speed: 1.0,
|
||||
},
|
||||
} as Partial<UserPreferences>)
|
||||
|
||||
// Now patch only non-secret fields via the API
|
||||
const patchRes = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ tts: { voice: 'nova', speed: 1.5 } }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(patchRes.status).toBe(200)
|
||||
const body = await patchRes.json() as { preferences: { tts: { voice: string; speed: number; apiKey: string; endpoint: string } } }
|
||||
expect(body.preferences.tts.voice).toBe('nova')
|
||||
expect(body.preferences.tts.speed).toBe(1.5)
|
||||
expect(body.preferences.tts.apiKey).toBe('sk-secret-123')
|
||||
expect(body.preferences.tts.endpoint).toBe('https://custom.endpoint')
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with { tts: { voice: "nova" } } preserves autoPlay and other omitted fields', async () => {
|
||||
// Seed TTS with autoPlay: true (a non-default value)
|
||||
settingsService.updateSettings({
|
||||
tts: {
|
||||
enabled: true,
|
||||
provider: 'external',
|
||||
autoPlay: true,
|
||||
endpoint: 'https://custom.endpoint',
|
||||
apiKey: 'sk-secret-123',
|
||||
voice: 'alloy',
|
||||
model: 'tts-1',
|
||||
speed: 1.0,
|
||||
},
|
||||
} as Partial<UserPreferences>)
|
||||
|
||||
// Patch only voice — autoPlay, provider, model, speed must remain as seeded
|
||||
const patchRes = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ tts: { voice: 'nova' } }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(patchRes.status).toBe(200)
|
||||
const body = await patchRes.json() as { preferences: { tts: { voice: string; autoPlay: boolean; speed: number; model: string } } }
|
||||
expect(body.preferences.tts.voice).toBe('nova')
|
||||
expect(body.preferences.tts.autoPlay).toBe(true) // must NOT reset to default false
|
||||
expect(body.preferences.tts.speed).toBe(1.0) // preserved
|
||||
expect(body.preferences.tts.model).toBe('tts-1') // preserved
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with { tts: { apiKey: "leak" } } returns 400 (strict reject)', async () => {
|
||||
const res = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ tts: { apiKey: 'leak' } }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with { tts: { endpoint: "http://x" } } returns 400 (strict reject)', async () => {
|
||||
const res = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ tts: { endpoint: 'http://x' } }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with { stt: { model: "whisper-1" } } preserves non-default language and omitted fields', async () => {
|
||||
// Seed full STT config with a non-default language
|
||||
settingsService.updateSettings({
|
||||
stt: {
|
||||
enabled: true,
|
||||
provider: 'builtin',
|
||||
endpoint: 'https://api.openai.com',
|
||||
apiKey: 'sk-secret-456',
|
||||
model: 'whisper-1',
|
||||
language: 'fr-FR',
|
||||
},
|
||||
} as Partial<UserPreferences>)
|
||||
|
||||
// Patch only model — language, provider, enabled must remain as seeded
|
||||
const patchRes = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ stt: { model: 'whisper-2' } }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(patchRes.status).toBe(200)
|
||||
const body = await patchRes.json() as { preferences: { stt: { model: string; language: string; provider: string; enabled: boolean } } }
|
||||
expect(body.preferences.stt.model).toBe('whisper-2')
|
||||
expect(body.preferences.stt.language).toBe('fr-FR') // must NOT reset to default 'en-US'
|
||||
expect(body.preferences.stt.provider).toBe('builtin') // preserved
|
||||
expect(body.preferences.stt.enabled).toBe(true) // preserved
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with { stt: { ... } } when no stt config exists returns 400', async () => {
|
||||
const res = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ stt: { enabled: true, language: 'fr-FR' } }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('STT is not configured')
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with existing keys (theme) still works after tts/stt additions', async () => {
|
||||
const res = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ theme: 'light', mode: 'plan' }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { preferences: { theme: string; mode: string } }
|
||||
expect(body.preferences.theme).toBe('light')
|
||||
expect(body.preferences.mode).toBe('plan')
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,7 @@ 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, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig } from '../../src/services/assistant-mode'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig } from '../../src/services/assistant-mode'
|
||||
import { createTempAssistantWorkspace, createTestDb, mockRepo } from '../helpers/assistant-workspace'
|
||||
import { createInternalRoutes } from '../../src/routes/internal'
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
@@ -44,6 +44,43 @@ describe('buildReposSkill', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildSettingsSkill', () => {
|
||||
it('uses ENV.SERVER.PORT in the internal base URL', () => {
|
||||
const skill = buildSettingsSkill('https://example.com:443/api/internal')
|
||||
expect(skill).toContain(`http://localhost:${ENV.SERVER.PORT}/api/internal`)
|
||||
expect(skill).not.toContain(':443')
|
||||
})
|
||||
|
||||
it('includes tts and stt in allowed non-secret preferences', () => {
|
||||
const skill = buildSettingsSkill('http://localhost:5003/api/internal')
|
||||
expect(skill).toContain('tts')
|
||||
expect(skill).toContain('stt')
|
||||
expect(skill).toContain('enabled')
|
||||
expect(skill).toContain('provider')
|
||||
expect(skill).toContain('autoPlay')
|
||||
expect(skill).toContain('voice')
|
||||
expect(skill).toContain('model')
|
||||
expect(skill).toContain('speed')
|
||||
expect(skill).toContain('language')
|
||||
})
|
||||
|
||||
it('documents the POST /assistant/reload endpoint', () => {
|
||||
const skill = buildSettingsSkill('http://localhost:5003/api/internal')
|
||||
expect(skill).toContain('/assistant/reload')
|
||||
expect(skill).toContain('Always confirm with the user before reloading')
|
||||
expect(skill).toContain('5 requests per minute')
|
||||
})
|
||||
|
||||
it('still lists apiKey and endpoint as forbidden', () => {
|
||||
const skill = buildSettingsSkill('http://localhost:5003/api/internal')
|
||||
expect(skill).toContain('tts.apiKey')
|
||||
expect(skill).toContain('tts.endpoint')
|
||||
expect(skill).toContain('stt.apiKey')
|
||||
expect(skill).toContain('stt.endpoint')
|
||||
expect(skill).toContain('DO NOT attempt to set')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAssistantDefaultAgentMd', () => {
|
||||
it('contains description and mode in frontmatter', () => {
|
||||
const content = buildAssistantDefaultAgentMd()
|
||||
@@ -59,6 +96,12 @@ describe('buildAssistantDefaultAgentMd', () => {
|
||||
expect(content).toContain('manager-settings')
|
||||
})
|
||||
|
||||
it('contains reload guidance in the agent prompt', () => {
|
||||
const content = buildAssistantDefaultAgentMd()
|
||||
expect(content).toContain('/assistant/reload')
|
||||
expect(content).toContain('Always ask the user before reloading')
|
||||
})
|
||||
|
||||
it('does not contain v file', () => {
|
||||
const content = buildAssistantDefaultAgentMd()
|
||||
expect(content).not.toContain('v file')
|
||||
@@ -66,13 +109,13 @@ describe('buildAssistantDefaultAgentMd', () => {
|
||||
})
|
||||
|
||||
describe('buildAssistantOpenCodeConfig', () => {
|
||||
it('includes default_agent and agent.assistant with primary mode', () => {
|
||||
it('includes default_agent and agent.assistant with primary mode and no embedded persona', () => {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
expect(config.default_agent).toBe('assistant')
|
||||
expect(config.agent?.assistant?.mode).toBe('primary')
|
||||
expect(config.agent?.assistant?.prompt).toContain('default Assistant Mode agent')
|
||||
expect(config.agent?.assistant?.permission?.read).toBe('allow')
|
||||
expect(config.agent?.assistant?.permission?.external_directory).toBe('ask')
|
||||
expect(config.agent?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(config.agent?.assistant?.prompt).toBeUndefined()
|
||||
expect(config.agent?.assistant?.description).toBeUndefined()
|
||||
expect(config.agent?.assistant?.permission).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -102,8 +145,10 @@ describe('ensureAssistantMode', () => {
|
||||
const parsedConfig = JSON.parse(opencodeJson)
|
||||
expect(parsedConfig.default_agent).toBe('assistant')
|
||||
expect(parsedConfig).not.toHaveProperty('mcp')
|
||||
expect(parsedConfig.agent?.assistant?.mode).toBe('primary')
|
||||
expect(parsedConfig.agent?.assistant?.prompt).toContain('default Assistant Mode agent')
|
||||
expect(parsedConfig.agent?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(parsedConfig.agent?.assistant?.prompt).toBeUndefined()
|
||||
expect(parsedConfig.agent?.assistant?.description).toBeUndefined()
|
||||
expect(parsedConfig.agent?.assistant?.permission).toBeUndefined()
|
||||
expect(token).toMatch(/^[0-9a-f]{64}$/)
|
||||
expect(skill).toContain('Authorization: Bearer')
|
||||
expect(skill).toContain(localApiBaseUrl)
|
||||
@@ -161,23 +206,10 @@ describe('ensureAssistantMode', () => {
|
||||
bash: 'allow',
|
||||
external_directory: 'ask',
|
||||
})
|
||||
expect(opencodeJson.agent?.assistant?.description).toBe('Default OpenCode Manager assistant workspace agent')
|
||||
expect(opencodeJson.agent?.assistant?.mode).toBe('primary')
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toContain('This workspace is the shared assistant workspace')
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toContain('Self-Editing')
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toContain('repo-management')
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toContain('schedule-management')
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toContain('notifications')
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toContain('manager-settings')
|
||||
expect(opencodeJson.agent?.assistant?.permission).toEqual({
|
||||
read: 'allow',
|
||||
edit: 'allow',
|
||||
glob: 'allow',
|
||||
grep: 'allow',
|
||||
list: 'allow',
|
||||
bash: 'allow',
|
||||
external_directory: 'ask',
|
||||
})
|
||||
expect(opencodeJson.agent?.assistant).toEqual({ mode: 'primary' })
|
||||
expect(opencodeJson.agent?.assistant?.prompt).toBeUndefined()
|
||||
expect(opencodeJson.agent?.assistant?.description).toBeUndefined()
|
||||
expect(opencodeJson.agent?.assistant?.permission).toBeUndefined()
|
||||
|
||||
const agentsMdContent = await readFile(agentsMdPath, 'utf8')
|
||||
expect(agentsMdContent).toContain('Assistant Mode Workspace')
|
||||
@@ -262,8 +294,8 @@ describe('ensureAssistantMode', () => {
|
||||
const repaired = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
||||
|
||||
expect(repaired.default_agent).toBe('assistant')
|
||||
expect(repaired.agent.assistant.mode).toBe('primary')
|
||||
expect(repaired.agent.assistant.prompt).toContain('default Assistant Mode agent')
|
||||
expect(repaired.agent.assistant).toEqual({ mode: 'primary', disable: false })
|
||||
expect(repaired.agent.assistant.prompt).toBeUndefined()
|
||||
expect(repaired.agent.custom.prompt).toBe('Custom agent')
|
||||
expect(repaired.model).toBe('provider/model')
|
||||
expect(repaired.skills.paths).toEqual(['.opencode/skills'])
|
||||
@@ -424,18 +456,17 @@ Ask before destructive operations or changes outside this assistant workspace.
|
||||
expect(updatedAgentsMd).not.toContain('Self-Editing Rules')
|
||||
|
||||
expect(updatedAssistantAgent).toContain('Self-Editing')
|
||||
expect(updatedAssistantAgent).toContain('/assistant/reload')
|
||||
expect(updatedAssistantAgent).toContain('Always ask the user before reloading')
|
||||
expect(updatedAssistantAgent).toContain('repo-management')
|
||||
expect(updatedAssistantAgent).toContain('schedule-management')
|
||||
expect(updatedAssistantAgent).toContain('notifications')
|
||||
expect(updatedAssistantAgent).toContain('manager-settings')
|
||||
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toContain('Self-Editing')
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toContain('.opencode/agents/assistant.md')
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toContain('repo-management')
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toContain('schedule-management')
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toContain('notifications')
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toContain('manager-settings')
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).not.toContain('Update AGENTS.md')
|
||||
expect(updatedOpenCodeJson.agent.assistant.prompt).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agent.assistant.description).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agent.assistant.permission).toBeUndefined()
|
||||
expect(updatedOpenCodeJson.agent.assistant.mode).toBe('primary')
|
||||
|
||||
expect(result.files.agentsMd?.created).toBe(true)
|
||||
expect(result.files.opencodeJson?.created).toBe(true)
|
||||
@@ -544,7 +575,7 @@ describe('assistant-mode end-to-end', () => {
|
||||
const notificationService = new NotificationService(db)
|
||||
const settingsService = new SettingsService(db)
|
||||
const app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService))
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, createOpenCodeClient()))
|
||||
|
||||
const unauth = await app.request('/api/internal/schedules/all')
|
||||
expect(unauth.status).toBe(401)
|
||||
|
||||
@@ -104,13 +104,17 @@ The following preference keys can be modified:
|
||||
- `simpleChatMode`, `leaderKey`, `directShortcuts`
|
||||
- `keyboardShortcuts`, `customCommands`, `notifications`
|
||||
- `repoOrder`, `repoSortMode`
|
||||
- `tts` — Non-secret TTS preferences (`enabled`, `provider`, `autoPlay`, `voice`, `model`, `speed`). TTS must already be configured in the UI (the endpoint returns 400 otherwise).
|
||||
- `stt` — Non-secret STT preferences (`enabled`, `provider`, `model`, `language`). STT must already be configured in the UI (the endpoint returns 400 otherwise).
|
||||
|
||||
**Restricted Keys:**
|
||||
The following keys are **NOT** allowed and will be rejected:
|
||||
- `gitCredentials` - Git credentials must be managed via the full UI
|
||||
- `gitIdentity` - Git identity must be managed via the full UI
|
||||
- `tts.apiKey` - TTS credentials must be managed via the full UI
|
||||
- `tts.endpoint` - TTS endpoint must be managed via the full UI
|
||||
- `stt.apiKey` - STT credentials must be managed via the full UI
|
||||
- `stt.endpoint` - STT endpoint must be managed via the full UI
|
||||
- `lastKnownGoodConfig` - Internal state, do not modify
|
||||
|
||||
**Request Body:**
|
||||
@@ -124,6 +128,31 @@ Returns the updated settings object.
|
||||
- `400`: Invalid request body or disallowed key
|
||||
- `401`: Missing or invalid bearer token
|
||||
|
||||
### Assistant
|
||||
|
||||
**POST `/api/internal/assistant/reload`**
|
||||
|
||||
Reload the assistant workspace by disposing the current OpenCode instance. Use this after editing `.opencode/agents/assistant.md` or `opencode.json` so changes take effect on the next message.
|
||||
|
||||
**Rate Limiting:** 5 requests per minute per token. Returns `429 Too Many Requests` with `Retry-After` header when exceeded.
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer <token>" \
|
||||
"http://localhost:5003/api/internal/assistant/reload"
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```ts
|
||||
{ "success": true }
|
||||
```
|
||||
|
||||
**Status Codes:**
|
||||
- `200`: Assistant workspace reloaded
|
||||
- `401`: Missing or invalid bearer token
|
||||
- `429`: Rate limit exceeded
|
||||
- `502`: Failed to reload (upstream OpenCode error)
|
||||
|
||||
### Repos
|
||||
|
||||
**GET `/api/internal/repos`**
|
||||
|
||||
@@ -22,11 +22,17 @@ Four skills are provisioned automatically when assistant mode is initialized:
|
||||
|-------|----------------|
|
||||
| `schedule-management` | Create, list, update, delete, and run scheduled jobs |
|
||||
| `notifications` | Send push notifications to registered user devices |
|
||||
| `manager-settings` | Read and patch user preferences |
|
||||
| `manager-settings` | Read and patch user preferences, and reload the assistant workspace |
|
||||
| `repo-management` | List all managed repositories |
|
||||
|
||||
See [Assistant Internal API](assistant-internal-api.md) for the full API reference these skills expose.
|
||||
|
||||
## Assistant Persona
|
||||
|
||||
The assistant's system prompt, behavior, and durable preferences live solely in `.opencode/agents/assistant.md`. This file is the single source of truth for the assistant agent's personality and self-editing rules. The `opencode.json` configuration no longer duplicates the agent persona — it only stores agent mode and workspace-level settings.
|
||||
|
||||
When the assistant self-edits its agent definition (e.g., to refine behavior or add durable preferences), it uses the `manager-settings` skill to call the `POST /assistant/reload` endpoint. This disposes the current OpenCode workspace instance so the changes take effect on the next message. The reload endpoint is rate-limited to 5 requests per minute; the assistant always asks the user before reloading.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Click **Assistant** in the sidebar or mobile tab bar
|
||||
|
||||
@@ -3,6 +3,9 @@ import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
|
||||
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
|
||||
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
|
||||
type SessionListParams = NonNullable<paths['/session']['get']['parameters']['query']> & {
|
||||
roots?: boolean
|
||||
}
|
||||
type CreateSessionRequest = NonNullable<paths['/session']['post']['requestBody']>['content']['application/json']
|
||||
type MessageListResponse = paths['/session/{sessionID}/message']['get']['responses']['200']['content']['application/json']
|
||||
type SendPromptRequest = NonNullable<paths['/session/{sessionID}/message']['post']['requestBody']>['content']['application/json']
|
||||
@@ -67,9 +70,9 @@ export class OpenCodeClient {
|
||||
return { ...params, directory: this.directory }
|
||||
}
|
||||
|
||||
async listSessions() {
|
||||
async listSessions(params?: SessionListParams) {
|
||||
return fetchWrapper<SessionListResponse>(`${this.baseURL}/session`, {
|
||||
params: this.getParams(),
|
||||
params: this.getParams(params),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ export function WorkspaceManager({
|
||||
const isActive = !!workspace.fullPath && workspace.fullPath === activeWorkspaceDirectory
|
||||
const label = workspaceLabel(workspace)
|
||||
const rowClassName = isActive
|
||||
? 'border-purple-500/50 bg-purple-500/10 text-foreground'
|
||||
? 'border-primary/50 bg-primary/10 text-foreground'
|
||||
: 'border-border bg-muted/30 hover:bg-muted/50'
|
||||
if (!manageMode) {
|
||||
return (
|
||||
@@ -197,9 +197,9 @@ export function WorkspaceManager({
|
||||
className={`flex min-h-11 items-center gap-2 rounded-md border px-3 py-2 text-sm text-left ${rowClassName}`}
|
||||
aria-pressed={isActive}
|
||||
>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{isActive && <span className="text-xs text-purple-400">Selected</span>}
|
||||
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
<span className={isActive ? 'truncate text-orange-600 dark:text-orange-400' : 'truncate'}>{label}</span>
|
||||
{isActive && <span className="text-xs text-orange-600 dark:text-orange-400">Selected</span>}
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{workspace.fullPath}
|
||||
@@ -219,7 +219,7 @@ export function WorkspaceManager({
|
||||
onCheckedChange={(checked) => toggle(workspaceId, checked === true)}
|
||||
aria-label={`Select workspace ${label}`}
|
||||
/>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
|
||||
@@ -24,30 +24,33 @@ export function WorktreeTabs({
|
||||
}: WorktreeTabsProps) {
|
||||
const hasWorkspaces = workspaces.length > 0
|
||||
const workspaceLabel = value === 'workspaces' && activeWorkspaceLabel ? activeWorkspaceLabel : 'Workspaces'
|
||||
const tabClassName =
|
||||
'group min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3 data-[state=active]:border data-[state=active]:border-primary/50 data-[state=active]:bg-primary/10 data-[state=inactive]:hover:bg-accent data-[state=inactive]:hover:text-foreground'
|
||||
const activeLabelClassName = 'group-data-[state=active]:text-orange-600 dark:group-data-[state=active]:text-orange-400'
|
||||
|
||||
return (
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
<Tabs value={value} onValueChange={(next) => onValueChange(next as WorktreeTabValue)} className="min-w-0">
|
||||
<TabsList className="w-full justify-start overflow-hidden">
|
||||
<TabsTrigger value="repo" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3">
|
||||
<TabsList className="w-full justify-start gap-1 overflow-hidden">
|
||||
<TabsTrigger value="repo" className={tabClassName}>
|
||||
<GitBranch className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate">{baseLabel}</span>
|
||||
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{baseLabel}</span>
|
||||
</TabsTrigger>
|
||||
{hasWorkspaces ? (
|
||||
<>
|
||||
<TabsTrigger value="workspaces" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3" onClick={onWorkspaceMenu}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<span className="min-w-0 truncate">{workspaceLabel}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">({workspaces.length})</span>
|
||||
<TabsTrigger value="workspaces" className={tabClassName} onClick={onWorkspaceMenu}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-primary" />
|
||||
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{workspaceLabel}</span>
|
||||
<span className={`shrink-0 text-xs text-muted-foreground ${activeLabelClassName}`}>({workspaces.length})</span>
|
||||
</TabsTrigger>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCreateWorkspace}
|
||||
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-background hover:text-foreground sm:flex-none sm:px-3"
|
||||
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground sm:flex-none sm:px-3"
|
||||
>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<Layers className="h-3 w-3 shrink-0 text-primary" />
|
||||
<span className="min-w-0 truncate">Workspace</span>
|
||||
<Plus className="h-3.5 w-3.5 shrink-0" />
|
||||
</button>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { initializeAssistantMode } from '@/api/repos'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listSessions: vi.fn(),
|
||||
getSession: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
sendPromptAsync: vi.fn(),
|
||||
initializeAssistantMode: vi.fn(),
|
||||
@@ -18,6 +19,7 @@ vi.mock('@/api/repos', () => ({
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
OpenCodeClient: vi.fn(() => ({
|
||||
listSessions: mocks.listSessions,
|
||||
getSession: mocks.getSession,
|
||||
createSession: mocks.createSession,
|
||||
sendPromptAsync: mocks.sendPromptAsync,
|
||||
})),
|
||||
@@ -30,9 +32,29 @@ beforeEach(() => {
|
||||
describe('useAssistantSessionLauncher', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
mocks.initializeAssistantMode.mockResolvedValue({ directory: '/assistant' })
|
||||
})
|
||||
|
||||
it('opens the cached assistant session without listing sessions', async () => {
|
||||
localStorage.setItem('ocm:assistant:last-session:123:/assistant', 'cached')
|
||||
mocks.getSession.mockResolvedValue({ id: 'cached', directory: '/assistant', time: { updated: 20 } })
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(mocks.getSession).toHaveBeenCalledWith('cached')
|
||||
expect(mocks.listSessions).not.toHaveBeenCalled()
|
||||
expect(onNavigate).toHaveBeenCalledWith('cached')
|
||||
})
|
||||
|
||||
it('opens the latest root session in the assistant directory', async () => {
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'older', directory: '/assistant', time: { updated: 10 } },
|
||||
@@ -53,11 +75,36 @@ describe('useAssistantSessionLauncher', () => {
|
||||
|
||||
expect(initializeAssistantMode).toHaveBeenCalledWith(123)
|
||||
expect(OpenCodeClient).toHaveBeenCalledWith('http://localhost:5551', '/assistant')
|
||||
expect(mocks.listSessions).toHaveBeenCalledWith({ limit: 1, roots: true })
|
||||
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()
|
||||
})
|
||||
|
||||
it('falls back to latest lookup when the cached session is stale', async () => {
|
||||
localStorage.setItem('ocm:assistant:last-session:123:/assistant', 'stale')
|
||||
mocks.getSession.mockRejectedValueOnce(new Error('not found'))
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'latest', directory: '/assistant', time: { updated: 30 } },
|
||||
])
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(mocks.getSession).toHaveBeenCalledWith('stale')
|
||||
expect(mocks.listSessions).toHaveBeenCalledWith({ limit: 1, roots: true })
|
||||
expect(onNavigate).toHaveBeenCalledWith('latest')
|
||||
expect(localStorage.getItem('ocm:assistant:last-session:123:/assistant')).toBe('latest')
|
||||
})
|
||||
|
||||
it('notifies an existing assistant session when some generated updates were preserved', async () => {
|
||||
mocks.initializeAssistantMode.mockResolvedValue({
|
||||
directory: '/assistant',
|
||||
@@ -84,6 +131,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
})
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledWith('existing')
|
||||
expect(mocks.listSessions).toHaveBeenCalledWith({ limit: 1, roots: true })
|
||||
expect(mocks.sendPromptAsync).toHaveBeenCalledWith('existing', {
|
||||
parts: [
|
||||
expect.objectContaining({
|
||||
@@ -122,6 +170,7 @@ 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
|
||||
|
||||
@@ -2,6 +2,7 @@ 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
|
||||
@@ -9,6 +10,79 @@ interface UseAssistantSessionLauncherOptions {
|
||||
onNavigate: (sessionId: string) => void
|
||||
}
|
||||
|
||||
type OpenCodeSession = components['schemas']['Session']
|
||||
|
||||
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 getCachedAssistantSessionId(repoId: number, directory: string): string | undefined {
|
||||
try {
|
||||
return localStorage.getItem(getLastAssistantSessionKey(repoId, directory)) || undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function setCachedAssistantSessionId(repoId: number, directory: string, sessionId: string): void {
|
||||
try {
|
||||
localStorage.setItem(getLastAssistantSessionKey(repoId, directory), sessionId)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function removeCachedAssistantSessionId(repoId: number, directory: string): void {
|
||||
try {
|
||||
localStorage.removeItem(getLastAssistantSessionKey(repoId, directory))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function isAssistantRootSession(session: OpenCodeSession, assistantDirectory: string): boolean {
|
||||
return !session.parentID && session.directory === assistantDirectory
|
||||
}
|
||||
|
||||
function findNewestRootAssistantSession(sessions: OpenCodeSession[], assistantDirectory: string): OpenCodeSession | undefined {
|
||||
return sessions
|
||||
.filter((session) => isAssistantRootSession(session, assistantDirectory))
|
||||
.sort((a, b) => b.time.updated - a.time.updated)[0]
|
||||
}
|
||||
|
||||
async function getCachedAssistantSession(
|
||||
client: OpenCodeClient,
|
||||
repoId: number,
|
||||
assistantDirectory: string,
|
||||
): Promise<OpenCodeSession | undefined> {
|
||||
const cachedSessionId = getCachedAssistantSessionId(repoId, assistantDirectory)
|
||||
if (!cachedSessionId) return undefined
|
||||
|
||||
try {
|
||||
const session = await client.getSession(cachedSessionId)
|
||||
if (isAssistantRootSession(session, assistantDirectory)) return session
|
||||
removeCachedAssistantSessionId(repoId, assistantDirectory)
|
||||
} catch {
|
||||
removeCachedAssistantSessionId(repoId, assistantDirectory)
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
async function getLatestAssistantSession(
|
||||
client: OpenCodeClient,
|
||||
assistantDirectory: string,
|
||||
): Promise<OpenCodeSession | undefined> {
|
||||
const latestSessions = await client.listSessions({ limit: 1, roots: true })
|
||||
const latestRootSession = findNewestRootAssistantSession(latestSessions, assistantDirectory)
|
||||
if (latestRootSession || latestSessions.length === 0) return latestRootSession
|
||||
|
||||
const sessions = await client.listSessions()
|
||||
return findNewestRootAssistantSession(sessions, assistantDirectory)
|
||||
}
|
||||
|
||||
const ASSISTANT_WELCOME_PROMPT = `Welcome to OpenCode Manager! I'm your assistant and I'm here to help you work with your code.
|
||||
|
||||
To get started, let's set up your assistant:
|
||||
@@ -77,27 +151,18 @@ export function useAssistantSessionLauncher({
|
||||
const openAssistant = useCallback(async () => {
|
||||
const assistant = await initializeAssistantMode(repoId)
|
||||
const client = new OpenCodeClient(opcodeUrl, assistant.directory)
|
||||
const sessions = await client.listSessions()
|
||||
|
||||
const assistantDirectory = assistant.directory
|
||||
|
||||
const rootSessions = sessions.filter(
|
||||
(session) => !session.parentID
|
||||
)
|
||||
|
||||
const assistantSessions = rootSessions.filter(
|
||||
(session) => session.directory === assistantDirectory
|
||||
)
|
||||
|
||||
const newest = assistantSessions.sort(
|
||||
(a, b) => b.time.updated - a.time.updated
|
||||
)[0]
|
||||
const newest = await getCachedAssistantSession(client, repoId, assistantDirectory)
|
||||
?? await getLatestAssistantSession(client, assistantDirectory)
|
||||
|
||||
if (newest) {
|
||||
setCachedAssistantSessionId(repoId, assistantDirectory, newest.id)
|
||||
onNavigate(newest.id)
|
||||
void sendAssistantModeWarningsPrompt(client, newest.id, assistant)
|
||||
} else {
|
||||
const session = await client.createSession({ title: 'Assistant' })
|
||||
setCachedAssistantSessionId(repoId, assistantDirectory, session.id)
|
||||
onNavigate(session.id)
|
||||
void sendAssistantWelcomePrompt(client, session.id, assistant)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,26 @@ export const AssistantNotificationResponseSchema = z.object({
|
||||
noSubscriptions: z.boolean(),
|
||||
})
|
||||
|
||||
// NOTE: These are defined as plain z.object (not .pick() from the full schemas)
|
||||
// so that .default() values from the source schemas are NOT inherited. A patch
|
||||
// like { voice: 'nova' } must produce only { voice: 'nova' } in the parsed output,
|
||||
// not { voice: 'nova', provider: 'external', autoPlay: false }.
|
||||
export const AssistantTTSPatchSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
provider: z.enum(['external', 'builtin']),
|
||||
autoPlay: z.boolean(),
|
||||
voice: z.string(),
|
||||
model: z.string(),
|
||||
speed: z.number().min(0.25).max(4.0),
|
||||
}).partial().strict()
|
||||
|
||||
export const AssistantSTTPatchSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
provider: z.enum(['external', 'builtin']),
|
||||
model: z.string(),
|
||||
language: z.string(),
|
||||
}).partial().strict()
|
||||
|
||||
export const AssistantSettingsPatchSchema = UserPreferencesSchema.pick({
|
||||
theme: true,
|
||||
mode: true,
|
||||
@@ -35,23 +55,7 @@ export const AssistantSettingsPatchSchema = UserPreferencesSchema.pick({
|
||||
notifications: true,
|
||||
repoOrder: true,
|
||||
repoSortMode: true,
|
||||
}).extend({
|
||||
tts: AssistantTTSPatchSchema,
|
||||
stt: AssistantSTTPatchSchema,
|
||||
}).partial().strict()
|
||||
|
||||
export const ASSISTANT_SETTINGS_ALLOWED_KEYS = [
|
||||
'theme',
|
||||
'mode',
|
||||
'defaultModel',
|
||||
'defaultAgent',
|
||||
'autoScroll',
|
||||
'expandDiffs',
|
||||
'expandToolCalls',
|
||||
'showReasoning',
|
||||
'simpleChatMode',
|
||||
'leaderKey',
|
||||
'directShortcuts',
|
||||
'keyboardShortcuts',
|
||||
'customCommands',
|
||||
'notifications',
|
||||
'repoOrder',
|
||||
'repoSortMode',
|
||||
] as const
|
||||
Reference in new issue
Block a user