mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Merge pull request #484 from chriswritescode-dev/chore/oxlint-anti-slop
chore(lint): replace ESLint with Oxlint and clear anti-slop findings
This commit is contained in:
1110 files changed
+70090
-80281
No files matched your search
@@ -114,6 +114,9 @@ DEBUG=false
|
||||
# so set true explicitly for HTTPS.
|
||||
# AUTH_SECURE_COOKIES=true
|
||||
|
||||
# Auth rate limit: maximum auth requests per client per 60 seconds (production only)
|
||||
# AUTH_RATE_LIMIT_MAX=100
|
||||
|
||||
# OAuth Providers (optional - enable by providing client ID and secret)
|
||||
# GITHUB_CLIENT_ID=
|
||||
# GITHUB_CLIENT_SECRET=
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
- `cd backend && pnpm exec vitest --ui` - Interactive test UI
|
||||
- `cd backend && pnpm exec vitest run --coverage` - Coverage report (80% threshold)
|
||||
- `cd backend && bun test <filename>` - Run a Bun-only suite, excluded from Vitest (`test/routes/internal-sandbox.test.ts`, `src/routes/repos.test.ts`)
|
||||
- `pnpm lint` - Lint CLI, frontend, and backend
|
||||
- `pnpm lint:backend` - Backend linting
|
||||
- `pnpm lint:frontend` - Frontend linting
|
||||
- `pnpm lint` - Lint the repository with Oxlint
|
||||
- `pnpm lint:backend` - Oxlint for the backend
|
||||
- `pnpm lint:frontend` - Oxlint for the frontend
|
||||
|
||||
## Code Style
|
||||
|
||||
- Doc comments only in new and changed code: JSDoc/TSDoc attached to the declaration they document, in the language's native doc convention. No inline, explanatory, or section comments; code must be self-documenting
|
||||
- No comments of any kind, including JSDoc and lint-disable directives, enforced by `anti-slop/no-comments`; code must be self-documenting
|
||||
- No console logs (use Bun's logger or proper error handling)
|
||||
- Strict TypeScript everywhere, proper typing required
|
||||
- Named imports only: `import { Hono } from 'hono'`, `import { useState } from 'react'`
|
||||
@@ -35,7 +35,7 @@
|
||||
- @/ alias for components: `import { Button } from '@/components/ui/button'`
|
||||
- Radix UI + Tailwind CSS, React Hook Form + Zod
|
||||
- React Query (@tanstack/react-query) for state management
|
||||
- ESLint TypeScript rules enforced
|
||||
- Oxlint TypeScript rules enforced
|
||||
- Use React hooks properly, no direct state mutations
|
||||
|
||||
### General
|
||||
|
||||
+2
-2
@@ -49,7 +49,7 @@ Each item is tagged with a theme to help you find work in your area of interest:
|
||||
|
||||
### Code Style
|
||||
|
||||
- New and changed code uses doc comments only (JSDoc/TSDoc on the declaration they document); no inline or explanatory comments
|
||||
- New and changed code has no comments of any kind (including JSDoc and lint-disable directives); code must be self-documenting
|
||||
- Strict TypeScript with proper typing
|
||||
- Named imports only
|
||||
- DRY principles - check for existing patterns before adding new ones
|
||||
@@ -80,7 +80,7 @@ cd backend && bun test <filename> # Run a Bun-only suite (test/rou
|
||||
### Linting and Type Checking
|
||||
|
||||
```bash
|
||||
pnpm lint # Lint CLI, frontend, and backend
|
||||
pnpm lint # Lint the repository with Oxlint
|
||||
pnpm typecheck # Type-check CLI, frontend, and backend
|
||||
```
|
||||
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ COPY backend ./backend
|
||||
COPY frontend/src ./frontend/src
|
||||
COPY frontend/public ./frontend/public
|
||||
COPY frontend/plugins ./frontend/plugins
|
||||
COPY frontend/index.html frontend/vite.config.ts frontend/tsconfig*.json frontend/components.json frontend/eslint.config.js ./frontend/
|
||||
COPY frontend/index.html frontend/vite.config.ts frontend/tsconfig*.json frontend/components.json ./frontend/
|
||||
|
||||
RUN pnpm --filter frontend build
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import js from '@eslint/js'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist', '.env*', 'coverage', 'src/utils/logger.ts']),
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2022,
|
||||
globals: {
|
||||
process: 'readonly',
|
||||
Buffer: 'readonly',
|
||||
console: 'readonly',
|
||||
},
|
||||
parserOptions: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-console': ['warn', { allow: ['warn', 'error'] }],
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'@typescript-eslint/no-unused-vars': 'error',
|
||||
'no-useless-escape': 'warn',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['test/**/*.ts'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -12,9 +12,7 @@
|
||||
"test:bun": "bun test test/routes/internal-sandbox.test.ts src/routes/repos.test.ts",
|
||||
"test:vitest": "vitest run --coverage",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:watch": "vitest --watch",
|
||||
"lint": "eslint . --ext .ts",
|
||||
"lint:fix": "eslint . --ext .ts --fix"
|
||||
"test:watch": "vitest --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "^1.7.12",
|
||||
@@ -30,7 +28,6 @@
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
"@types/archiver": "^7.0.0",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/bun": "latest",
|
||||
@@ -38,8 +35,6 @@
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"@vitest/ui": "^3.2.4",
|
||||
"better-sqlite3": "^12.9.0",
|
||||
"eslint": "^9.39.1",
|
||||
"typescript-eslint": "^8.45.0",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env bun
|
||||
import http from 'http'
|
||||
import fs from 'fs'
|
||||
import { z } from 'zod'
|
||||
|
||||
interface AskpassRequest {
|
||||
askpassType: 'https' | 'ssh'
|
||||
@@ -9,11 +10,12 @@ interface AskpassRequest {
|
||||
repoId?: number
|
||||
}
|
||||
|
||||
function fatal(err: unknown): never {
|
||||
if (err instanceof Error) {
|
||||
console.error(err.message)
|
||||
} else if (typeof err === 'string') {
|
||||
console.error(err)
|
||||
function fatal(cause: unknown): never {
|
||||
if (cause instanceof Error) {
|
||||
console.error(cause.message)
|
||||
} else {
|
||||
const text = z.string().safeParse(cause)
|
||||
if (text.success) console.error(text.data)
|
||||
}
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
@@ -53,7 +53,6 @@ export interface DevicePairingOptions {
|
||||
onDeviceRevoked?: (sessionId: string) => void
|
||||
}
|
||||
|
||||
/** Adds pairing code, paired device, and revoke endpoints to Better Auth. */
|
||||
export function devicePairing(options: DevicePairingOptions = {}) {
|
||||
const { onDeviceRevoked } = options
|
||||
return {
|
||||
|
||||
+35
-21
@@ -9,45 +9,59 @@ import { devicePairing } from './device-pairing'
|
||||
import { closeSessionConnections } from '../services/session-connections'
|
||||
import { deletePushSubscriptionsForSession } from '../db/push-subscriptions'
|
||||
|
||||
export type AuthEnv = { -readonly [Key in keyof typeof ENV.AUTH]: (typeof ENV.AUTH)[Key] }
|
||||
|
||||
export type AuthInstance = ReturnType<typeof createAuth>
|
||||
|
||||
export function isAdminConfigured(): boolean {
|
||||
return !!(ENV.AUTH.ADMIN_EMAIL && ENV.AUTH.ADMIN_PASSWORD)
|
||||
export interface AuthServerConfig {
|
||||
trustedOrigins: string[]
|
||||
port: number
|
||||
}
|
||||
|
||||
export function createAuth(db: Database) {
|
||||
export function isAdminConfigured(env: AuthEnv = ENV.AUTH): boolean {
|
||||
return !!(env.ADMIN_EMAIL && env.ADMIN_PASSWORD)
|
||||
}
|
||||
|
||||
export function createAuth(
|
||||
db: Database,
|
||||
env: AuthEnv = ENV.AUTH,
|
||||
serverConfig: AuthServerConfig = { trustedOrigins: getTrustedOrigins(), port: ENV.SERVER.PORT },
|
||||
) {
|
||||
const socialProviders: Record<string, { clientId: string; clientSecret: string }> = {}
|
||||
|
||||
if (ENV.AUTH.GITHUB_CLIENT_ID && ENV.AUTH.GITHUB_CLIENT_SECRET) {
|
||||
if (env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET) {
|
||||
socialProviders.github = {
|
||||
clientId: ENV.AUTH.GITHUB_CLIENT_ID,
|
||||
clientSecret: ENV.AUTH.GITHUB_CLIENT_SECRET,
|
||||
clientId: env.GITHUB_CLIENT_ID,
|
||||
clientSecret: env.GITHUB_CLIENT_SECRET,
|
||||
}
|
||||
}
|
||||
|
||||
if (ENV.AUTH.GOOGLE_CLIENT_ID && ENV.AUTH.GOOGLE_CLIENT_SECRET) {
|
||||
if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
|
||||
socialProviders.google = {
|
||||
clientId: ENV.AUTH.GOOGLE_CLIENT_ID,
|
||||
clientSecret: ENV.AUTH.GOOGLE_CLIENT_SECRET,
|
||||
clientId: env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: env.GOOGLE_CLIENT_SECRET,
|
||||
}
|
||||
}
|
||||
|
||||
if (ENV.AUTH.DISCORD_CLIENT_ID && ENV.AUTH.DISCORD_CLIENT_SECRET) {
|
||||
if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
|
||||
socialProviders.discord = {
|
||||
clientId: ENV.AUTH.DISCORD_CLIENT_ID,
|
||||
clientSecret: ENV.AUTH.DISCORD_CLIENT_SECRET,
|
||||
clientId: env.DISCORD_CLIENT_ID,
|
||||
clientSecret: env.DISCORD_CLIENT_SECRET,
|
||||
}
|
||||
}
|
||||
|
||||
const trustedOrigins = getTrustedOrigins()
|
||||
const baseURL = trustedOrigins[0] || `http://localhost:${ENV.SERVER.PORT}`
|
||||
const { trustedOrigins } = serverConfig
|
||||
const baseURL = trustedOrigins[0] || `http://localhost:${serverConfig.port}`
|
||||
|
||||
const auth = betterAuth({
|
||||
baseURL,
|
||||
basePath: '/api/auth',
|
||||
database: db,
|
||||
secret: ENV.AUTH.SECRET,
|
||||
secret: env.SECRET,
|
||||
trustedOrigins,
|
||||
rateLimit: {
|
||||
max: env.RATE_LIMIT_MAX,
|
||||
},
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
@@ -66,7 +80,7 @@ export function createAuth(db: Database) {
|
||||
user: {
|
||||
create: {
|
||||
before: async (user, context) => {
|
||||
if (isAdminConfigured() && (context?.request || user.email.toLowerCase() !== ENV.AUTH.ADMIN_EMAIL!.toLowerCase())) {
|
||||
if (isAdminConfigured(env) && (context?.request || user.email.toLowerCase() !== (env.ADMIN_EMAIL ?? '').toLowerCase())) {
|
||||
throw new APIError('FORBIDDEN', { message: 'Registration is disabled' })
|
||||
}
|
||||
},
|
||||
@@ -75,9 +89,9 @@ export function createAuth(db: Database) {
|
||||
},
|
||||
plugins: [
|
||||
passkey({
|
||||
rpID: ENV.AUTH.PASSKEY_RP_ID,
|
||||
rpName: ENV.AUTH.PASSKEY_RP_NAME,
|
||||
origin: ENV.AUTH.PASSKEY_ORIGIN,
|
||||
rpID: env.PASSKEY_RP_ID,
|
||||
rpName: env.PASSKEY_RP_NAME,
|
||||
origin: env.PASSKEY_ORIGIN,
|
||||
authenticatorSelection: {
|
||||
residentKey: 'required',
|
||||
userVerification: 'required',
|
||||
@@ -103,7 +117,7 @@ export function createAuth(db: Database) {
|
||||
},
|
||||
advanced: {
|
||||
cookiePrefix: AUTH_COOKIE_PREFIX,
|
||||
useSecureCookies: ENV.AUTH.SECURE_COOKIES,
|
||||
useSecureCookies: env.SECURE_COOKIES,
|
||||
ipAddress: {
|
||||
ipAddressHeaders: [AUTH_SOCKET_IP_HEADER],
|
||||
},
|
||||
@@ -133,6 +147,6 @@ export type Session = {
|
||||
image?: string | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
role?: string
|
||||
role?: string | null
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,18 @@
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
import { getTrustedOrigins } from '@opencode-manager/shared/config/env'
|
||||
import type { AuthInstance, Session } from './index'
|
||||
import type { Session } from './index'
|
||||
import type { AuthSessionReader } from '../routes/auth'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
||||
const UNTRUSTED_FETCH_SITES = new Set(['same-site', 'cross-site'])
|
||||
|
||||
export interface AuthSessionProvider {
|
||||
api: AuthSessionReader
|
||||
}
|
||||
|
||||
export function createAuthMiddleware(
|
||||
auth: AuthInstance,
|
||||
auth: AuthSessionProvider,
|
||||
resolveTrustedOrigins: () => string[] = getTrustedOrigins,
|
||||
) {
|
||||
return createMiddleware<{
|
||||
@@ -47,8 +52,8 @@ export function createAuthMiddleware(
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
c.set('session', session.session as Session['session'])
|
||||
c.set('user', session.user as Session['user'])
|
||||
c.set('session', session.session)
|
||||
c.set('user', session.user)
|
||||
await next()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,600 @@
|
||||
import { serve } from '@hono/node-server'
|
||||
import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws'
|
||||
import { Hono } from 'hono'
|
||||
import { cors } from 'hono/cors'
|
||||
import { serveStatic } from '@hono/node-server/serve-static'
|
||||
import { readFile } from 'fs/promises'
|
||||
import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { initializeDatabase } from './db/schema'
|
||||
import { createRepoRoutes } from './routes/repos'
|
||||
import { createRepoTerminalSocketRoutes } from './routes/repo-terminal-socket'
|
||||
import { createIPCServer, type IPCServer } from './ipc/ipcServer'
|
||||
import { GitAuthService } from './services/git-auth'
|
||||
import { createSettingsRoutes } from './routes/settings'
|
||||
import { createDevicePairingRoutes } from './routes/device-pairing'
|
||||
import { createHealthRoutes } from './routes/health'
|
||||
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts'
|
||||
import { createSTTRoutes } from './routes/stt'
|
||||
import { createFileRoutes } from './routes/files'
|
||||
import { createFilesystemRoutes } from './routes/filesystem'
|
||||
import { createScheduleRoutes, createServerScheduleRoutes } from './routes/schedules'
|
||||
import { createProvidersRoutes } from './routes/providers'
|
||||
import { createOAuthRoutes } from './routes/oauth'
|
||||
import { createSSERoutes } from './routes/sse'
|
||||
import { createSSHRoutes } from './routes/ssh'
|
||||
import { createNotificationRoutes } from './routes/notifications'
|
||||
import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy'
|
||||
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
|
||||
import { createAuth } from './auth'
|
||||
import { createAuthMiddleware } from './auth/middleware'
|
||||
import { createPromptTemplateRoutes } from './routes/prompt-templates'
|
||||
import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createSessionPermissionModeRoutes } from './routes/session-permission-modes'
|
||||
import { createSessionSandboxRoutes } from './routes/session-sandbox'
|
||||
import { createMultiRunRoutes } from './routes/multi-runs'
|
||||
import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
|
||||
import { getChangeWalkthroughByWalkthroughSession } from './db/change-walkthroughs'
|
||||
import { createLogRoutes } from './routes/logs'
|
||||
import { createPreviewRoutes, createPreviewAvailability, type PreviewAvailability } from './routes/preview'
|
||||
import { createGlobalSecretRoutes } from './routes/secrets'
|
||||
import { createPreviewGatewayApp, PreviewSessionStore, type PreviewGateway } from './services/preview/gateway'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from './routes/opencode-auth-proxy'
|
||||
import { createOpenCodeServerProxyRoutes } from './routes/opencode-server-proxy'
|
||||
import { createOpenCodeServerRoutes } from './routes/opencode-servers'
|
||||
import {
|
||||
createOpenCodeServerTerminalRoutes,
|
||||
createOpenCodeServerTerminalSocketRoutes,
|
||||
} from './routes/opencode-server-terminals'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { RemoteServerEventHub } from './services/remote-server-events'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists } from './services/file-operations'
|
||||
import { SettingsService } from './services/settings'
|
||||
import { RemoteAccessHeadersService } from './services/remote-access-headers'
|
||||
import { SessionPermissionModeService } from './services/session-permission-modes'
|
||||
import { SessionSandboxService } from './services/session-sandbox'
|
||||
import { SessionAncestry } from './services/session-ancestry'
|
||||
import { GoalOutcomeTracker } from './services/goal-outcomes'
|
||||
import { MultiRunService } from './services/multi-runs'
|
||||
import { ChangeWalkthroughService } from './services/change-walkthroughs'
|
||||
import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { createOpenCodeClient } from './services/opencode/client'
|
||||
import { OpenCodeServerRegistry } from './services/opencode-server-registry'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './services/opencode/upstream'
|
||||
import { NotificationService } from './services/notification'
|
||||
import { ScheduleRunner, ScheduleService } from './services/schedules'
|
||||
import { CredentialProvider } from './services/credential-provider'
|
||||
import { TerminalService } from './services/terminal'
|
||||
import { ProjectConfigService } from './services/project-config'
|
||||
import { SecretsService } from './services/secrets'
|
||||
import { RepoEnvService } from './services/repo-env'
|
||||
import { RepoWorkspaceService } from './services/repo-workspace'
|
||||
import { createGitService } from './services/git/GitService'
|
||||
import { ScheduleWorktreeManager } from './services/schedule-worktree'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
import { convertAssistantOpenCodeConfigToV2, installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { detectSandboxCapability } from './services/sandbox/capability'
|
||||
import { SandboxRuntimeService, stopSandboxesOnShutdown } from './services/sandbox/runtime'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { readOpenCodeConfigFile, foldLegacyConfigJsonSource, withOpenCodeConfigLock } from './services/opencode-config-file'
|
||||
import { seedOpenCodeConfigFile } from './services/opencode-config-apply'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
import { logger } from './utils/logger'
|
||||
import {
|
||||
getWorkspacePath,
|
||||
getReposPath,
|
||||
getConfigPath,
|
||||
getAgentsMdPath,
|
||||
getDatabasePath,
|
||||
getTrustedOrigins,
|
||||
ENV,
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { DEFAULT_AGENTS_MD } from './constants'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, NotificationEventType } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const PackageJsonSchema = z.object({ version: z.string().optional() })
|
||||
|
||||
const ServerErrorCodeSchema = z.object({ code: z.string().optional() })
|
||||
|
||||
const REFLECT_ANY_ORIGIN_PREFIXES = ['/api/opencode-proxy/', '/api/internal/']
|
||||
|
||||
export type BackendOpenCodeSupervisor = Pick<
|
||||
OpenCodeSupervisor,
|
||||
'start' | 'stop' | 'restart' | 'getStatus' | 'checkNow'
|
||||
>
|
||||
|
||||
export type BackendScheduleRunner = Pick<ScheduleRunner, 'start' | 'stop'>
|
||||
|
||||
export interface BackendAppDependencies {
|
||||
database?: Database
|
||||
createSupervisor?: (
|
||||
manager: typeof opencodeServerManager,
|
||||
settings: SettingsService,
|
||||
) => BackendOpenCodeSupervisor
|
||||
createScheduleRunner?: (service: ScheduleService) => BackendScheduleRunner
|
||||
installAssistantWorkspace?: typeof installAssistantWorkspace
|
||||
migrateGlobalSkills?: () => Promise<void>
|
||||
}
|
||||
|
||||
export interface BackendApp {
|
||||
app: Hono
|
||||
injectWebSocket: NodeWebSocket['injectWebSocket']
|
||||
preview: { gateway: PreviewGateway; availability: PreviewAvailability }
|
||||
initialize: () => Promise<void>
|
||||
shutdown: () => Promise<void>
|
||||
}
|
||||
|
||||
export interface PreviewGatewayServerOptions {
|
||||
preview: BackendApp['preview']
|
||||
port: number
|
||||
hostname: string
|
||||
serveFn?: typeof serve
|
||||
}
|
||||
|
||||
async function getAppVersion(): Promise<string> {
|
||||
try {
|
||||
const packageUrl = new URL('../../package.json', import.meta.url)
|
||||
const packageJsonRaw = await readFile(packageUrl, 'utf-8')
|
||||
const parsedPackageJson = PackageJsonSchema.safeParse(JSON.parse(packageJsonRaw))
|
||||
return parsedPackageJson.success ? parsedPackageJson.data.version ?? 'unknown' : 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
|
||||
export function startPreviewGateway({ preview, port, hostname, serveFn = serve }: PreviewGatewayServerOptions) {
|
||||
const server = serveFn({
|
||||
fetch: preview.gateway.app.fetch,
|
||||
port,
|
||||
hostname,
|
||||
})
|
||||
server.on('listening', () => {
|
||||
preview.availability.markAvailable()
|
||||
logger.info(`Preview gateway running on http://${hostname}:${port}`)
|
||||
})
|
||||
server.on('error', (cause: Error) => {
|
||||
preview.availability.markUnavailable()
|
||||
const code = ServerErrorCodeSchema.safeParse(cause)
|
||||
logger.warn(`Preview gateway failed to listen on port ${port}${code.success && code.data.code ? ` (${code.data.code})` : ''}; preview disabled`)
|
||||
})
|
||||
preview.gateway.injectWebSocket(server)
|
||||
return server
|
||||
}
|
||||
|
||||
export function createBackendApp(dependencies: BackendAppDependencies = {}): BackendApp {
|
||||
const { PORT, HOST } = ENV.SERVER
|
||||
const database = dependencies.database ?? initializeDatabase(getDatabasePath())
|
||||
|
||||
const app = new Hono()
|
||||
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app })
|
||||
|
||||
app.use('/*', cors({
|
||||
origin: (origin, c) => {
|
||||
if (origin && REFLECT_ANY_ORIGIN_PREFIXES.some(prefix => c.req.path.startsWith(prefix))) {
|
||||
return origin
|
||||
}
|
||||
const trustedOrigins = getTrustedOrigins()
|
||||
if (!origin) return trustedOrigins[0]
|
||||
if (trustedOrigins.includes(origin)) return origin
|
||||
return trustedOrigins[0]
|
||||
},
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
|
||||
allowHeaders: ['Content-Type', 'Authorization', 'CF-Access-Client-Id', 'CF-Access-Client-Secret'],
|
||||
credentials: true,
|
||||
}))
|
||||
|
||||
const auth = createAuth(database)
|
||||
const requireAuth = createAuthMiddleware(auth)
|
||||
const openCodeClient = createOpenCodeClient(
|
||||
() => new SettingsService(database).getOpenCodeServerPassword(),
|
||||
() => opencodeServerManager.getEffectiveServerHost(),
|
||||
)
|
||||
const opencodeServerRegistry = new OpenCodeServerRegistry(database, openCodeClient)
|
||||
|
||||
let ipcServer: IPCServer | undefined
|
||||
const gitAuthService = new GitAuthService()
|
||||
const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(database, gitService, gitAuthService)
|
||||
const secretsService = new SecretsService(database)
|
||||
const repoEnvService = new RepoEnvService(database, projectConfigService, secretsService)
|
||||
const sandboxRuntimeService = new SandboxRuntimeService(database, repoEnvService)
|
||||
const settingsService = new SettingsService(database)
|
||||
const openCodeSupervisor = dependencies.createSupervisor?.(opencodeServerManager, settingsService)
|
||||
?? new OpenCodeSupervisor(opencodeServerManager, settingsService)
|
||||
const installWorkspace = dependencies.installAssistantWorkspace ?? installAssistantWorkspace
|
||||
const migrateSkills = dependencies.migrateGlobalSkills ?? migrateGlobalSkills
|
||||
|
||||
const terminalService = new TerminalService(
|
||||
{
|
||||
client: openCodeClient,
|
||||
baseUrl: () => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
includeLocalEnv: true,
|
||||
},
|
||||
new CredentialProvider(database),
|
||||
repoEnvService,
|
||||
)
|
||||
const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
const connection = opencodeServerRegistry.getConnection(serverId)
|
||||
return terminalService.forTarget({
|
||||
client: opencodeServerRegistry.getClient(serverId),
|
||||
baseUrl: () => connection.baseUrl,
|
||||
includeLocalEnv: false,
|
||||
})
|
||||
}
|
||||
const sessionAncestry = new SessionAncestry((serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const sessionSandboxService = new SessionSandboxService(database, sessionAncestry, settingsService, {
|
||||
removeSessionSandbox: (rootSessionId) => sandboxRuntimeService.removeSessionSandbox(rootSessionId),
|
||||
})
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, database)
|
||||
const scheduleService = new ScheduleService(database, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry, {
|
||||
sessions: sessionSandboxService,
|
||||
runtime: sandboxRuntimeService,
|
||||
})
|
||||
scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
try {
|
||||
await terminalService.removeAll(directory)
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to remove terminals for schedule worktree ${directory}:`, error)
|
||||
}
|
||||
})
|
||||
const repoWorkspaces = new RepoWorkspaceService(database, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService)
|
||||
const scheduleRunnerInstance = dependencies.createScheduleRunner?.(scheduleService) ?? new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(database, opencodeServerRegistry)
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(database, opencodeServerRegistry, settingsService, sessionAncestry)
|
||||
const goalOutcomes = new GoalOutcomeTracker()
|
||||
|
||||
const multiRunService = new MultiRunService(database, openCodeClient, repoWorkspaces, sessionPermissionModeService, (serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(database, openCodeClient, settingsService, gitAuthService, gitService)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionSandboxService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session sandbox event handling error:', err)
|
||||
})
|
||||
try {
|
||||
changeWalkthroughService.handleEvent(event)
|
||||
} catch (err) {
|
||||
logger.error('Change walkthrough event handling error:', err)
|
||||
}
|
||||
})
|
||||
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Session permission mode event handling error:', err)
|
||||
})
|
||||
const outcome = goalOutcomes.observe(serverId, directory, event)
|
||||
if (outcome) {
|
||||
void notificationService.notifyGoalOutcome(outcome).catch((error) => {
|
||||
logger.error('Goal outcome notification error:', error)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
notificationService.addEventSuppressor((event, sessionId, serverId) =>
|
||||
sessionPermissionModeService.suppressesPermissionNotification(event, sessionId, serverId),
|
||||
)
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId, serverId) => {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) return false
|
||||
if (!sessionId) return false
|
||||
if (event.type !== NotificationEventType.SESSION_IDLE && event.type !== NotificationEventType.SESSION_FAILED) return false
|
||||
return getChangeWalkthroughByWalkthroughSession(database, sessionId) !== null
|
||||
})
|
||||
|
||||
if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
if (!ENV.VAPID.SUBJECT) {
|
||||
logger.warn('VAPID_SUBJECT is not set — push notifications require a mailto: subject (e.g. mailto:you@example.com)')
|
||||
} else if (!ENV.VAPID.SUBJECT.startsWith('mailto:')) {
|
||||
logger.warn(`VAPID_SUBJECT="${ENV.VAPID.SUBJECT}" does not use mailto: format — iOS/Safari push notifications will fail`)
|
||||
}
|
||||
|
||||
notificationService.configureVapid({
|
||||
publicKey: ENV.VAPID.PUBLIC_KEY,
|
||||
privateKey: ENV.VAPID.PRIVATE_KEY,
|
||||
subject: ENV.VAPID.SUBJECT || 'mailto:push@localhost',
|
||||
})
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
notificationService.handleSSEEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Push notification dispatch error:', err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
sseAggregator.setOpenCodeClient(openCodeClient)
|
||||
sseAggregator.setResyncGate(() => opencodeServerManager.isLifecycleInitialized())
|
||||
opencodeServerManager.onLifecycleInitialized(() => sseAggregator.releasePendingResync())
|
||||
sseAggregator.onServerConnected((serverId) => {
|
||||
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions(serverId).catch((err) => {
|
||||
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, err)
|
||||
})
|
||||
if (serverId === LOCAL_OPENCODE_SERVER_ID) {
|
||||
void convertAssistantOpenCodeConfigToV2(openCodeClient.api).catch((err) => {
|
||||
logger.error('Failed to convert the Assistant OpenCode config to v2:', err)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const remoteServerEvents = new RemoteServerEventHub(opencodeServerRegistry, sseAggregator)
|
||||
|
||||
sseAggregator.setScheduledSessionsResolver(
|
||||
() => scheduleService.getActiveRunSessions(),
|
||||
)
|
||||
|
||||
const previewSessionStore = new PreviewSessionStore()
|
||||
const previewAvailability = createPreviewAvailability(false)
|
||||
|
||||
app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth))
|
||||
app.route('/api/health', createHealthRoutes(database, openCodeSupervisor))
|
||||
|
||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
|
||||
app.route('/api/internal', createInternalRoutes(database, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, multiRunService, changeWalkthroughService, sessionSandboxService, repoEnvService))
|
||||
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(database, settingsService, upgradeWebSocket))
|
||||
|
||||
const protectedApi = new Hono()
|
||||
protectedApi.use('/*', requireAuth)
|
||||
|
||||
protectedApi.route('/repos', createRepoTerminalSocketRoutes(database, gitAuthService, openCodeClient, terminalService, upgradeWebSocket))
|
||||
protectedApi.route('/repos', createRepoRoutes(database, gitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces, secretsService))
|
||||
protectedApi.route('/settings', createSettingsRoutes(database, gitAuthService, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/device-pairing', createDevicePairingRoutes({
|
||||
mintPairingCode: (headers) => auth.api.createDevicePairingCode({ headers }),
|
||||
remoteAccessHeaders: new RemoteAccessHeadersService(database),
|
||||
readAllowPrivateNetworkHttp: () =>
|
||||
settingsService.getSettings('default').preferences.devicePairing?.allowPrivateNetworkHttp === true,
|
||||
}))
|
||||
protectedApi.route('/files', createFileRoutes())
|
||||
protectedApi.route('/filesystem', createFilesystemRoutes())
|
||||
protectedApi.route('/providers', createProvidersRoutes(openCodeClient))
|
||||
protectedApi.route('/oauth', createOAuthRoutes(openCodeClient))
|
||||
protectedApi.route('/tts', createTTSRoutes(database))
|
||||
protectedApi.route('/stt', createSTTRoutes(database))
|
||||
protectedApi.route('/sse', createSSERoutes())
|
||||
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(database))
|
||||
protectedApi.route('/secrets', createGlobalSecretRoutes(secretsService, 'secret'))
|
||||
protectedApi.route('/variables', createGlobalSecretRoutes(secretsService, 'variable'))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(database))
|
||||
protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalRoutes(resolveServerTerminalService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerRoutes(opencodeServerRegistry, () => remoteServerEvents.getStatuses()))
|
||||
protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService))
|
||||
protectedApi.route('/session-sandbox', createSessionSandboxRoutes(sessionSandboxService))
|
||||
protectedApi.route('/multi-runs', createMultiRunRoutes(multiRunService))
|
||||
protectedApi.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
|
||||
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/logs', createLogRoutes())
|
||||
protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore, isEnabled: previewAvailability.isEnabled }))
|
||||
|
||||
app.route('/api', protectedApi)
|
||||
|
||||
app.route('/api/opencode/servers', createOpenCodeServerProxyRoutes(opencodeServerRegistry, requireAuth))
|
||||
app.route('/api/opencode', createAuthenticatedOpenCodeProxyRoutes(openCodeClient, requireAuth))
|
||||
|
||||
const isProduction = ENV.SERVER.NODE_ENV === 'production'
|
||||
|
||||
if (isProduction) {
|
||||
app.use('/*', async (c, next) => {
|
||||
await next()
|
||||
if (c.req.path === '/sw.js') {
|
||||
c.res.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate')
|
||||
c.res.headers.set('Pragma', 'no-cache')
|
||||
c.res.headers.set('Expires', '0')
|
||||
}
|
||||
})
|
||||
|
||||
app.use('/*', serveStatic({ root: './frontend/dist' }))
|
||||
|
||||
app.get('*', async (c) => {
|
||||
if (c.req.path.startsWith('/api/')) {
|
||||
return c.notFound()
|
||||
}
|
||||
const fs = await import('fs/promises')
|
||||
const path = await import('path')
|
||||
const indexPath = path.join(process.cwd(), 'frontend/dist/index.html')
|
||||
const html = await fs.readFile(indexPath, 'utf-8')
|
||||
return c.html(html)
|
||||
})
|
||||
} else {
|
||||
app.get('/', async (c) => {
|
||||
const version = await getAppVersion()
|
||||
return c.json({
|
||||
name: 'OpenCode WebUI',
|
||||
version,
|
||||
status: 'running',
|
||||
endpoints: {
|
||||
health: '/api/health',
|
||||
repos: '/api/repos',
|
||||
settings: '/api/settings',
|
||||
sessions: '/api/sessions',
|
||||
files: '/api/files',
|
||||
providers: '/api/providers',
|
||||
opencode_proxy: '/api/opencode/*'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
app.get('/api/network-info', async (c) => {
|
||||
const os = await import('os')
|
||||
const interfaces = os.networkInterfaces()
|
||||
const ips = Object.values(interfaces)
|
||||
.flat()
|
||||
.filter(info => info && !info.internal && info.family === 'IPv4')
|
||||
.map(info => info!.address)
|
||||
|
||||
const requestHost = c.req.header('host') || `localhost:${PORT}`
|
||||
const protocol = c.req.header('x-forwarded-proto') || 'http'
|
||||
|
||||
return c.json({
|
||||
host: HOST,
|
||||
port: PORT,
|
||||
requestHost,
|
||||
protocol,
|
||||
availableIps: ips,
|
||||
apiUrls: [
|
||||
`${protocol}://localhost:${PORT}`,
|
||||
...ips.map(ip => `${protocol}://${ip}:${PORT}`)
|
||||
]
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const ensureOpenCodeConfigFileExists = async (): Promise<void> => {
|
||||
await withOpenCodeConfigLock(foldLegacyConfigJsonSource)
|
||||
|
||||
const existing = await readOpenCodeConfigFile()
|
||||
if (existing) {
|
||||
if (!existing.isValid) {
|
||||
logger.warn('OpenCode config file has validation issues', existing.validationIssues)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const status = await getOpenCodeImportStatus()
|
||||
if (status.configSourcePath) {
|
||||
logger.info(`Found importable OpenCode config at ${status.configSourcePath}, importing...`)
|
||||
try {
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, status })
|
||||
if (result.configImported) {
|
||||
logger.info(`Imported OpenCode config from ${status.configSourcePath} to workspace`)
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to import OpenCode config from ${status.configSourcePath}`, error)
|
||||
}
|
||||
}
|
||||
|
||||
await seedOpenCodeConfigFile()
|
||||
logger.info('Created minimal seed config')
|
||||
}
|
||||
|
||||
const ensureHomeStateImported = async (): Promise<void> => {
|
||||
try {
|
||||
const status = await getOpenCodeImportStatus()
|
||||
if (status.workspaceStateExists) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!status.stateSourcePath) {
|
||||
return
|
||||
}
|
||||
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, importConfig: false, status })
|
||||
if (result.stateImported) {
|
||||
logger.info(`Imported OpenCode state from ${status.stateSourcePath}`)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to import OpenCode state, continuing without imported state', error)
|
||||
}
|
||||
}
|
||||
|
||||
const ensureDefaultAgentsMdExists = async (): Promise<void> => {
|
||||
const agentsMdPath = getAgentsMdPath()
|
||||
const exists = await fileExists(agentsMdPath)
|
||||
|
||||
if (!exists) {
|
||||
await writeFileContent(agentsMdPath, DEFAULT_AGENTS_MD)
|
||||
logger.info(`Created default AGENTS.md at: ${agentsMdPath}`)
|
||||
}
|
||||
}
|
||||
|
||||
const initialize = async (): Promise<void> => {
|
||||
try {
|
||||
if (ENV.SERVER.NODE_ENV === 'production' && !ENV.AUTH.SECRET) {
|
||||
logger.error('AUTH_SECRET is required in production mode')
|
||||
logger.error('Generate one with: openssl rand -base64 32')
|
||||
logger.error('Set it as environment variable: AUTH_SECRET=your-secret')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
await ensureDirectoryExists(getWorkspacePath())
|
||||
await ensureDirectoryExists(getReposPath())
|
||||
await ensureDirectoryExists(getConfigPath())
|
||||
logger.info('Workspace directories initialized')
|
||||
|
||||
await cleanupExpiredCache()
|
||||
await sweepStaleUploadSessions()
|
||||
|
||||
await ensureOpenCodeConfigFileExists()
|
||||
await ensureHomeStateImported()
|
||||
await ensureDefaultAgentsMdExists()
|
||||
|
||||
settingsService.initializeLastKnownGoodConfig()
|
||||
|
||||
await migrateSkills()
|
||||
|
||||
await installWorkspace({ db: database })
|
||||
logger.info('Assistant workspace installed')
|
||||
|
||||
ipcServer = await createIPCServer(process.env.STORAGE_PATH || undefined)
|
||||
await gitAuthService.initialize(ipcServer, database)
|
||||
logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`)
|
||||
|
||||
await syncAdminFromEnv(auth, database)
|
||||
|
||||
opencodeServerManager.setDatabase(database)
|
||||
detectSandboxCapability()
|
||||
void sandboxRuntimeService.prepareSandboxOnBoot().catch((error) => {
|
||||
logger.warn('Sandbox preparation failed:', error)
|
||||
})
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
} else {
|
||||
logger.warn(`OpenCode server unavailable after startup recovery: ${openCodeStatus.lastError ?? openCodeStatus.state}`)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize workspace:', error)
|
||||
}
|
||||
|
||||
sseAggregator.start()
|
||||
remoteServerEvents.start()
|
||||
void scheduleRunnerInstance.start()
|
||||
}
|
||||
|
||||
let isShuttingDown = false
|
||||
|
||||
const shutdown = async (): Promise<void> => {
|
||||
if (isShuttingDown) return
|
||||
isShuttingDown = true
|
||||
|
||||
try {
|
||||
remoteServerEvents.shutdown()
|
||||
logger.info('Remote server event hub stopped')
|
||||
sseAggregator.shutdown()
|
||||
logger.info('SSE Aggregator stopped')
|
||||
if (ipcServer) {
|
||||
await ipcServer.dispose()
|
||||
logger.info('Git IPC server stopped')
|
||||
}
|
||||
await openCodeSupervisor.stop()
|
||||
scheduleRunnerInstance.stop()
|
||||
logger.info('Schedule runner stopped')
|
||||
logger.info('OpenCode server stopped')
|
||||
} catch (error) {
|
||||
logger.error('Error during shutdown:', error)
|
||||
}
|
||||
try {
|
||||
await stopSandboxesOnShutdown(database)
|
||||
logger.info('Sandbox microVMs stopped')
|
||||
} catch (error) {
|
||||
logger.error('Error stopping sandbox microVMs:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
app,
|
||||
injectWebSocket,
|
||||
preview: {
|
||||
gateway: createPreviewGatewayApp(previewSessionStore),
|
||||
availability: previewAvailability,
|
||||
},
|
||||
initialize,
|
||||
shutdown,
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { selectRow } from './rows'
|
||||
|
||||
const AuthSessionRowSchema = z.object({
|
||||
expiresAt: z.union([z.number(), z.string().transform((value) => Date.parse(value))]),
|
||||
})
|
||||
|
||||
/** Reports whether a Better Auth session row still exists and has not expired. */
|
||||
export function isAuthSessionActive(db: Database, sessionId: string, now: number = Date.now()): boolean {
|
||||
const row = db
|
||||
.prepare('SELECT expiresAt FROM "session" WHERE id = ?')
|
||||
.get(sessionId) as { expiresAt: string | number } | null
|
||||
const row = selectRow(db, AuthSessionRowSchema, 'SELECT expiresAt FROM "session" WHERE id = ?', sessionId)
|
||||
|
||||
if (!row) return false
|
||||
|
||||
const expiresAt = typeof row.expiresAt === 'number' ? row.expiresAt : Date.parse(row.expiresAt)
|
||||
return Number.isFinite(expiresAt) && expiresAt > now
|
||||
return Number.isFinite(row.expiresAt) && row.expiresAt > now
|
||||
}
|
||||
@@ -10,22 +10,28 @@ import {
|
||||
type WalkthroughSource,
|
||||
type WalkthroughStatus,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { selectRow, selectRows } from './rows'
|
||||
|
||||
interface ChangeWalkthroughRow {
|
||||
session_id: string
|
||||
source_key: string
|
||||
diff_hash: string
|
||||
generation_id: string
|
||||
walkthrough_session_id: string | null
|
||||
status: string
|
||||
artifact_path: string | null
|
||||
published_at: number | null
|
||||
error: string | null
|
||||
model: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
execution_started_at: number | null
|
||||
}
|
||||
const ChangeWalkthroughRowSchema = z.object({
|
||||
session_id: z.string(),
|
||||
source_key: z.string(),
|
||||
diff_hash: z.string(),
|
||||
generation_id: z.string(),
|
||||
walkthrough_session_id: z.string().nullable(),
|
||||
status: z.string(),
|
||||
artifact_path: z.string().nullable(),
|
||||
published_at: z.number().nullable(),
|
||||
error: z.string().nullable(),
|
||||
model: z.string().nullable(),
|
||||
created_at: z.number(),
|
||||
updated_at: z.number(),
|
||||
execution_started_at: z.number().nullable(),
|
||||
})
|
||||
|
||||
type ChangeWalkthroughRow = z.infer<typeof ChangeWalkthroughRowSchema>
|
||||
|
||||
const WalkthroughSessionIdRowSchema = z.object({ walkthrough_session_id: z.string() })
|
||||
|
||||
const ROW_COLUMNS = 'session_id, source_key, diff_hash, generation_id, walkthrough_session_id, status, artifact_path, published_at, error, model, created_at, updated_at, execution_started_at'
|
||||
|
||||
@@ -103,9 +109,13 @@ export function getChangeWalkthrough(
|
||||
sessionId: string,
|
||||
sourceKey: string,
|
||||
): ChangeWalkthrough | null {
|
||||
const row = db
|
||||
.prepare(`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE session_id = ? AND source_key = ?`)
|
||||
.get(sessionId, sourceKey) as ChangeWalkthroughRow | undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
ChangeWalkthroughRowSchema,
|
||||
`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE session_id = ? AND source_key = ?`,
|
||||
sessionId,
|
||||
sourceKey,
|
||||
)
|
||||
return row ? mapRow(row) : null
|
||||
}
|
||||
|
||||
@@ -113,9 +123,12 @@ export function getChangeWalkthroughByWalkthroughSession(
|
||||
db: Database,
|
||||
walkthroughSessionId: string,
|
||||
): { walkthrough: ChangeWalkthrough; generationId: string } | null {
|
||||
const row = db
|
||||
.prepare(`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE walkthrough_session_id = ?`)
|
||||
.get(walkthroughSessionId) as ChangeWalkthroughRow | undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
ChangeWalkthroughRowSchema,
|
||||
`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE walkthrough_session_id = ?`,
|
||||
walkthroughSessionId,
|
||||
)
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
@@ -223,16 +236,21 @@ export function updateChangeWalkthrough(
|
||||
}
|
||||
|
||||
export function listChangeWalkthroughSessionIds(db: Database): string[] {
|
||||
const rows = db
|
||||
.prepare('SELECT DISTINCT walkthrough_session_id FROM change_walkthroughs WHERE walkthrough_session_id IS NOT NULL')
|
||||
.all() as Array<{ walkthrough_session_id: string }>
|
||||
const rows = selectRows(
|
||||
db,
|
||||
WalkthroughSessionIdRowSchema,
|
||||
'SELECT DISTINCT walkthrough_session_id FROM change_walkthroughs WHERE walkthrough_session_id IS NOT NULL',
|
||||
)
|
||||
return rows.map((row) => row.walkthrough_session_id)
|
||||
}
|
||||
|
||||
export function listChangeWalkthroughs(db: Database, sessionId: string): ChangeWalkthrough[] {
|
||||
const rows = db
|
||||
.prepare(`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE session_id = ?`)
|
||||
.all(sessionId) as ChangeWalkthroughRow[]
|
||||
const rows = selectRows(
|
||||
db,
|
||||
ChangeWalkthroughRowSchema,
|
||||
`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE session_id = ?`,
|
||||
sessionId,
|
||||
)
|
||||
return rows.flatMap((row) => {
|
||||
const mapped = mapRow(row)
|
||||
return mapped ? [mapped] : []
|
||||
|
||||
@@ -1,18 +1,8 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { logger } from '../utils/logger'
|
||||
import { selectRows } from './rows'
|
||||
|
||||
/**
|
||||
* A schema change applied once per database. Migrations run in the order they appear in
|
||||
* `allMigrations`, and each is recorded by its `id`, which must never change once released.
|
||||
*
|
||||
* New migrations use a UTC timestamp id, `YYYYMMDDHHmm-short-name` (for example
|
||||
* `202610061345-schedule-workspace-mode`), in a file of the same name, so migrations written on
|
||||
* different branches cannot claim the same identity. Make `up` safe to run on a database that
|
||||
* already has the change, because merged branches may apply migrations in a different order.
|
||||
*
|
||||
* `legacy` only exists on the numbered migrations written before ids; it lets databases that
|
||||
* recorded them by version number in `schema_migrations` recognise them as applied.
|
||||
*/
|
||||
export interface Migration {
|
||||
id: string
|
||||
legacy?: { version: number; name: string }
|
||||
@@ -20,18 +10,20 @@ export interface Migration {
|
||||
down(db: Database): void
|
||||
}
|
||||
|
||||
interface LegacyMigrationRecord {
|
||||
version: number
|
||||
name: string
|
||||
applied_at: number
|
||||
}
|
||||
const AppliedMigrationIdRowSchema = z.object({ id: z.string() })
|
||||
|
||||
const LegacyMigrationRecordSchema = z.object({
|
||||
version: z.number(),
|
||||
name: z.string(),
|
||||
applied_at: z.number(),
|
||||
})
|
||||
|
||||
export function migrate(db: Database, migrations: Migration[]): void {
|
||||
assertUniqueIds(migrations)
|
||||
db.run('CREATE TABLE IF NOT EXISTS applied_migrations (id TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)')
|
||||
adoptLegacyMigrations(db, migrations)
|
||||
|
||||
const applied = new Set((db.prepare('SELECT id FROM applied_migrations').all() as Array<{ id: string }>).map((row) => row.id))
|
||||
const applied = new Set(selectRows(db, AppliedMigrationIdRowSchema, 'SELECT id FROM applied_migrations').map((row) => row.id))
|
||||
const pending = migrations.filter((migration) => !applied.has(migration.id))
|
||||
|
||||
if (pending.length === 0) {
|
||||
@@ -67,19 +59,12 @@ function assertUniqueIds(migrations: Migration[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records numbered migrations that a database applied under the old version-keyed table.
|
||||
* A version recorded under a different name is still treated as applied, as before, but warned
|
||||
* about because its schema change may be missing.
|
||||
*/
|
||||
function adoptLegacyMigrations(db: Database, migrations: Migration[]): void {
|
||||
const hasLegacyTable = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'").get()
|
||||
if (!hasLegacyTable) return
|
||||
|
||||
const records = new Map(
|
||||
(db.prepare('SELECT version, name, applied_at FROM schema_migrations').all() as LegacyMigrationRecord[])
|
||||
.map((record) => [record.version, record] as const),
|
||||
)
|
||||
const legacyRecords = selectRows(db, LegacyMigrationRecordSchema, 'SELECT version, name, applied_at FROM schema_migrations')
|
||||
const records = new Map(legacyRecords.map((record) => [record.version, record] as const))
|
||||
const adopted = migrations.flatMap((migration) => {
|
||||
const record = migration.legacy ? records.get(migration.legacy.version) : undefined
|
||||
if (!migration.legacy || !record) return []
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '002-repos-nullable-url',
|
||||
legacy: { version: 2, name: 'repos-nullable-url' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'repos')
|
||||
const repoUrlColumn = tableInfo.find(col => col.name === 'repo_url')
|
||||
if (!repoUrlColumn || repoUrlColumn.notnull !== 1) return
|
||||
|
||||
@@ -47,7 +43,7 @@ const migration: Migration = {
|
||||
},
|
||||
|
||||
down(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'repos')
|
||||
const existingColumns = tableInfo.map(col => col.name)
|
||||
|
||||
db.run(`
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const COLUMNS = [
|
||||
{ name: 'branch', sql: 'ALTER TABLE repos ADD COLUMN branch TEXT' },
|
||||
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
|
||||
@@ -20,7 +17,7 @@ const migration: Migration = {
|
||||
legacy: { version: 3, name: 'repos-add-columns' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'repos')
|
||||
const existing = new Set(tableInfo.map(col => col.name))
|
||||
|
||||
for (const col of COLUMNS) {
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { z } from 'zod'
|
||||
import { selectRows } from '../rows'
|
||||
|
||||
const RepoLocalPathRowSchema = z.object({
|
||||
id: z.number(),
|
||||
local_path: z.string(),
|
||||
})
|
||||
|
||||
const migration: Migration = {
|
||||
id: '005-repos-local-path-prefix',
|
||||
legacy: { version: 5, name: 'repos-local-path-prefix' },
|
||||
|
||||
up(db) {
|
||||
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
|
||||
id: number
|
||||
local_path: string
|
||||
}>
|
||||
const repos = selectRows(
|
||||
db,
|
||||
RepoLocalPathRowSchema,
|
||||
"SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'",
|
||||
)
|
||||
|
||||
if (repos.length === 0) return
|
||||
|
||||
|
||||
@@ -1,21 +1,35 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { z } from 'zod'
|
||||
import { JsonValueSchema } from '@opencode-manager/shared/utils'
|
||||
import { selectRows } from '../rows'
|
||||
|
||||
const PreferencesRowSchema = z.object({
|
||||
user_id: z.string(),
|
||||
preferences: z.string(),
|
||||
})
|
||||
|
||||
const LegacyGitTokenPreferencesSchema = z.looseObject({
|
||||
gitToken: z.string().optional(),
|
||||
gitCredentials: z.array(JsonValueSchema).optional(),
|
||||
})
|
||||
|
||||
const LegacyGitCredentialsPreferencesSchema = z.looseObject({
|
||||
gitCredentials: z.array(z.looseObject({ token: z.string() })).optional(),
|
||||
})
|
||||
|
||||
const migration: Migration = {
|
||||
id: '006-git-token-to-credentials',
|
||||
legacy: { version: 6, name: 'git-token-to-credentials' },
|
||||
|
||||
up(db) {
|
||||
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
|
||||
user_id: string
|
||||
preferences: string
|
||||
}>
|
||||
const rows = selectRows(db, PreferencesRowSchema, 'SELECT user_id, preferences FROM user_preferences')
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
|
||||
const gitToken = parsed.gitToken as string | undefined
|
||||
const existingCredentials = parsed.gitCredentials as Array<unknown> | undefined
|
||||
const parsed = LegacyGitTokenPreferencesSchema.parse(JSON.parse(row.preferences))
|
||||
const gitToken = parsed.gitToken
|
||||
const existingCredentials = parsed.gitCredentials
|
||||
|
||||
if (!gitToken) continue
|
||||
if (existingCredentials && existingCredentials.length > 0) continue
|
||||
@@ -42,15 +56,12 @@ const migration: Migration = {
|
||||
},
|
||||
|
||||
down(db) {
|
||||
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
|
||||
user_id: string
|
||||
preferences: string
|
||||
}>
|
||||
const rows = selectRows(db, PreferencesRowSchema, 'SELECT user_id, preferences FROM user_preferences')
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
|
||||
const credentials = parsed.gitCredentials as Array<{ token: string }> | undefined
|
||||
const parsed = LegacyGitCredentialsPreferencesSchema.parse(JSON.parse(row.preferences))
|
||||
const credentials = parsed.gitCredentials
|
||||
|
||||
const firstCredential = credentials?.[0]
|
||||
if (!firstCredential) continue
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '008-schedule-cron-support',
|
||||
legacy: { version: 8, name: 'schedule-cron-support' },
|
||||
@@ -62,7 +57,7 @@ const migration: Migration = {
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
|
||||
}
|
||||
|
||||
const tableInfo = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'schedule_jobs')
|
||||
const existingColumns = new Set(tableInfo.map((column) => column.name))
|
||||
const intervalMinutesColumn = tableInfo.find((column) => column.name === 'interval_minutes')
|
||||
const scheduleModeColumn = tableInfo.find((column) => column.name === 'schedule_mode')
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '009-repo-source-path',
|
||||
legacy: { version: 9, name: 'repo-source-path' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'repos')
|
||||
const existing = new Set(tableInfo.map((column) => column.name))
|
||||
|
||||
if (!existing.has('source_path')) {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '011-repo-last-accessed',
|
||||
legacy: { version: 11, name: 'repo-last-accessed' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'repos')
|
||||
const existing = new Set(tableInfo.map((column) => column.name))
|
||||
|
||||
if (!existing.has('last_accessed_at')) {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '014-repos-add-name',
|
||||
legacy: { version: 14, name: 'repos-add-name' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'repos')
|
||||
const existing = new Set(tableInfo.map((column) => column.name))
|
||||
|
||||
if (!existing.has('name')) {
|
||||
|
||||
@@ -1,24 +1,19 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '015-schedule-worktree-isolation',
|
||||
legacy: { version: 15, name: 'schedule-worktree-isolation' },
|
||||
|
||||
up(db) {
|
||||
const jobColumns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const jobColumns = selectTableColumns(db, 'schedule_jobs')
|
||||
const jobColumnNames = new Set(jobColumns.map((c) => c.name))
|
||||
|
||||
if (!jobColumnNames.has('branch')) {
|
||||
db.run('ALTER TABLE schedule_jobs ADD COLUMN branch TEXT')
|
||||
}
|
||||
|
||||
const runColumns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const runColumns = selectTableColumns(db, 'schedule_runs')
|
||||
const runColumnNames = new Set(runColumns.map((c) => c.name))
|
||||
|
||||
if (!runColumnNames.has('run_branch')) {
|
||||
@@ -33,8 +28,7 @@ const migration: Migration = {
|
||||
},
|
||||
|
||||
down(db) {
|
||||
// Rebuild schedule_jobs without branch
|
||||
const jobColumns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const jobColumns = selectTableColumns(db, 'schedule_jobs')
|
||||
const hasBranch = jobColumns.some((c) => c.name === 'branch')
|
||||
|
||||
if (hasBranch) {
|
||||
@@ -79,8 +73,7 @@ const migration: Migration = {
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
}
|
||||
|
||||
// Rebuild schedule_runs without run_branch, commit_hash, worktree_path
|
||||
const runColumns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const runColumns = selectTableColumns(db, 'schedule_runs')
|
||||
const hasRunBranch = runColumns.some((c) => c.name === 'run_branch')
|
||||
const hasCommitHash = runColumns.some((c) => c.name === 'commit_hash')
|
||||
const hasWorktreePath = runColumns.some((c) => c.name === 'worktree_path')
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '016-schedule-permission-config',
|
||||
legacy: { version: 16, name: 'schedule-permission-config' },
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const cols = selectTableColumns(db, 'schedule_jobs')
|
||||
if (!cols.some((c) => c.name === 'permission_config')) {
|
||||
db.run('ALTER TABLE schedule_jobs ADD COLUMN permission_config TEXT')
|
||||
}
|
||||
@@ -19,8 +14,6 @@ const migration: Migration = {
|
||||
|
||||
down(_db) {
|
||||
void _db
|
||||
// no-op: SQLite drop-column requires table rebuild; column is nullable so
|
||||
// leaving it in place is safe for rollback scenarios.
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '017-schedule-run-workspace-id',
|
||||
legacy: { version: 17, name: 'schedule-run-workspace-id' },
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const cols = selectTableColumns(db, 'schedule_runs')
|
||||
if (!cols.some((c) => c.name === 'workspace_id')) {
|
||||
db.run('ALTER TABLE schedule_runs ADD COLUMN workspace_id TEXT')
|
||||
}
|
||||
@@ -19,8 +14,6 @@ const migration: Migration = {
|
||||
|
||||
down(_db) {
|
||||
void _db
|
||||
// no-op: SQLite drop-column requires table rebuild; column is nullable so
|
||||
// leaving it in place is safe for rollback scenarios.
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -5,14 +5,20 @@ import path from 'node:path'
|
||||
import { getOpenCodeConfigFilePath, getOpenCodeConfigHome } from '@opencode-manager/shared/config/env'
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { z } from 'zod'
|
||||
import { selectRows } from '../rows'
|
||||
|
||||
const OpenCodeConfigArchiveRowSchema = z.object({
|
||||
config_name: z.string(),
|
||||
config_content: z.string(),
|
||||
is_default: z.number().nullable(),
|
||||
})
|
||||
|
||||
function firstExistingConfigSourcePath(): string | null {
|
||||
const candidates = [
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH,
|
||||
path.join(os.homedir(), '.config', 'opencode', 'opencode.json'),
|
||||
]
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.map((value) => path.resolve(value))
|
||||
].flatMap((value) => (value ? [path.resolve(value)] : []))
|
||||
|
||||
return Array.from(new Set(candidates)).find((candidate) => existsSync(candidate)) ?? null
|
||||
}
|
||||
@@ -23,7 +29,7 @@ function writeArchivedConfig(archiveDir: string, configName: string, content: st
|
||||
writeFileSync(path.join(archiveDir, `${base}.json`), content, { flag: 'wx' })
|
||||
return
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
|
||||
if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -32,7 +38,7 @@ function writeArchivedConfig(archiveDir: string, configName: string, content: st
|
||||
writeFileSync(path.join(archiveDir, `${base}-${suffix}.json`), content, { flag: 'wx' })
|
||||
}
|
||||
|
||||
function archiveConfigs(rows: Array<{ config_name: string; config_content: string }>): void {
|
||||
function archiveConfigs(rows: z.infer<typeof OpenCodeConfigArchiveRowSchema>[]): void {
|
||||
const archiveDir = path.join(getOpenCodeConfigHome(), 'opencode-configs-archive')
|
||||
mkdirSync(archiveDir, { recursive: true })
|
||||
for (const row of rows) {
|
||||
@@ -49,7 +55,7 @@ const migration: Migration = {
|
||||
legacy: { version: 19, name: 'drop-opencode-configs' },
|
||||
|
||||
up(db) {
|
||||
const rows = db.prepare('SELECT config_name, config_content, is_default FROM opencode_configs').all() as Array<{ config_name: string; config_content: string; is_default: number | null }>
|
||||
const rows = selectRows(db, OpenCodeConfigArchiveRowSchema, 'SELECT config_name, config_content, is_default FROM opencode_configs')
|
||||
|
||||
try {
|
||||
archiveConfigs(rows)
|
||||
|
||||
@@ -3,25 +3,35 @@ import path from 'node:path'
|
||||
import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env'
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { JsonObjectSchema, JsonValueSchema } from '@opencode-manager/shared/utils'
|
||||
import { z } from 'zod'
|
||||
import { selectRow } from '../rows'
|
||||
|
||||
interface ModelStateRow {
|
||||
recent: string
|
||||
favorite: string
|
||||
variant: string
|
||||
updated_at: number
|
||||
}
|
||||
const ModelStateRowSchema = z.object({
|
||||
recent: z.string(),
|
||||
favorite: z.string(),
|
||||
variant: z.string(),
|
||||
updated_at: z.number(),
|
||||
})
|
||||
|
||||
function readDefaultRow(db: Parameters<Migration['up']>[0]): ModelStateRow | undefined {
|
||||
type ModelStateRow = z.infer<typeof ModelStateRowSchema>
|
||||
|
||||
function readDefaultRow(db: Parameters<Migration['up']>[0]): ModelStateRow | null {
|
||||
try {
|
||||
return db.prepare("SELECT recent, favorite, variant, updated_at FROM opencode_model_state WHERE user_id = 'default'").get() as ModelStateRow | undefined
|
||||
return selectRow(
|
||||
db,
|
||||
ModelStateRowSchema,
|
||||
"SELECT recent, favorite, variant, updated_at FROM opencode_model_state WHERE user_id = 'default'",
|
||||
)
|
||||
} catch {
|
||||
return undefined
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function parseJson<T>(value: string, fallback: T): T {
|
||||
function parseJsonText<Schema extends z.ZodType>(value: string, schema: Schema, fallback: z.infer<Schema>): z.infer<Schema> {
|
||||
try {
|
||||
return JSON.parse(value) as T
|
||||
const parsed = schema.safeParse(JSON.parse(value))
|
||||
return parsed.success ? parsed.data : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
@@ -36,15 +46,15 @@ function restoreModelStateFile(row: ModelStateRow): void {
|
||||
}
|
||||
|
||||
const existing = fileExists
|
||||
? parseJson<Record<string, unknown>>(readFileSync(filePath, 'utf8'), {})
|
||||
? parseJsonText(readFileSync(filePath, 'utf8'), JsonObjectSchema, {})
|
||||
: {}
|
||||
|
||||
mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
writeFileSync(filePath, JSON.stringify({
|
||||
...existing,
|
||||
recent: parseJson<unknown[]>(row.recent, []),
|
||||
favorite: parseJson<unknown[]>(row.favorite, []),
|
||||
variant: parseJson<Record<string, unknown>>(row.variant, {}),
|
||||
recent: parseJsonText(row.recent, z.array(JsonValueSchema), []),
|
||||
favorite: parseJsonText(row.favorite, z.array(JsonValueSchema), []),
|
||||
variant: parseJsonText(row.variant, JsonObjectSchema, {}),
|
||||
}, null, 2))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '021-drop-schedule-run-workspace-id',
|
||||
legacy: { version: 21, name: 'drop-schedule-run-workspace-id' },
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const cols = selectTableColumns(db, 'schedule_runs')
|
||||
if (cols.some((c) => c.name === 'workspace_id')) {
|
||||
db.run('ALTER TABLE schedule_runs DROP COLUMN workspace_id')
|
||||
}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '023-schedule-mcp-servers',
|
||||
legacy: { version: 23, name: 'schedule-mcp-servers' },
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'schedule_jobs')
|
||||
if (!columns.some((column) => column.name === 'mcp_servers')) {
|
||||
db.run('ALTER TABLE schedule_jobs ADD COLUMN mcp_servers TEXT')
|
||||
}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '024-schedule-runs-viewed-at',
|
||||
legacy: { version: 24, name: 'schedule-runs-viewed-at' },
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'schedule_runs')
|
||||
if (!columns.some((column) => column.name === 'viewed_at')) {
|
||||
db.run('ALTER TABLE schedule_runs ADD COLUMN viewed_at INTEGER')
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610061345-schedule-workspace-mode',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'schedule_jobs')
|
||||
if (!columns.some((column) => column.name === 'workspace_mode')) {
|
||||
db.run("ALTER TABLE schedule_jobs ADD COLUMN workspace_mode TEXT NOT NULL DEFAULT 'worktree'")
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610081200-change-walkthrough-sources',
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{ name: string }>
|
||||
const columns = selectTableColumns(db, 'change_walkthroughs')
|
||||
if (columns.some((column) => column.name === 'source_key')) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610151200-change-walkthrough-sessions',
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{ name: string }>
|
||||
const columns = selectTableColumns(db, 'change_walkthroughs')
|
||||
if (columns.some((column) => column.name === 'generation_id')) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610161200-change-walkthrough-execution',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'change_walkthroughs')
|
||||
if (!columns.some((column) => column.name === 'execution_started_at')) {
|
||||
db.run('ALTER TABLE change_walkthroughs ADD COLUMN execution_started_at INTEGER')
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Migration } from '../migration-runner'
|
||||
@@ -6,27 +7,18 @@ const SERVER_ID_COLUMN = 'server_id'
|
||||
const PERMISSION_MODES_TABLE = 'session_permission_modes'
|
||||
const PERMISSION_MODES_REBUILD_TABLE = 'session_permission_modes_rebuild'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
pk: number
|
||||
}
|
||||
|
||||
function tableExists(db: Database, table: string): boolean {
|
||||
return Boolean(
|
||||
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table),
|
||||
)
|
||||
}
|
||||
|
||||
function tableColumns(db: Database, table: string): ColumnInfo[] {
|
||||
return db.prepare(`PRAGMA table_info(${table})`).all() as ColumnInfo[]
|
||||
}
|
||||
|
||||
function hasColumn(db: Database, table: string, column: string): boolean {
|
||||
return tableColumns(db, table).some((entry) => entry.name === column)
|
||||
return selectTableColumns(db, table).some((entry) => entry.name === column)
|
||||
}
|
||||
|
||||
function primaryKeyColumns(db: Database, table: string): string[] {
|
||||
return tableColumns(db, table)
|
||||
return selectTableColumns(db, table)
|
||||
.filter((column) => column.pk > 0)
|
||||
.sort((left, right) => left.pk - right.pk)
|
||||
.map((column) => column.name)
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { selectTableColumns, type TableColumn } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const REBUILT_COLUMNS = `
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER,
|
||||
@@ -17,7 +13,7 @@ const REBUILT_COLUMNS = `
|
||||
created_at INTEGER NOT NULL
|
||||
`
|
||||
|
||||
function needsRebuild(columns: ColumnInfo[]): boolean {
|
||||
function needsRebuild(columns: TableColumn[]): boolean {
|
||||
if (columns.length === 0) return false
|
||||
|
||||
const byName = new Map(columns.map((column) => [column.name, column]))
|
||||
@@ -30,7 +26,7 @@ const migration: Migration = {
|
||||
id: '202610181310-multi-run-targets',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(multi_runs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'multi_runs')
|
||||
if (!needsRebuild(columns)) return
|
||||
|
||||
const names = new Set(columns.map((column) => column.name))
|
||||
@@ -51,7 +47,7 @@ const migration: Migration = {
|
||||
},
|
||||
|
||||
down(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(multi_runs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'multi_runs')
|
||||
if (columns.length === 0) return
|
||||
|
||||
const names = new Set(columns.map((column) => column.name))
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const LEGACY_SUFFIX = '_legacy_202610181320'
|
||||
|
||||
function createJobsTable(db: { run: (sql: string) => void }, table: string): void {
|
||||
@@ -66,12 +62,12 @@ const migration: Migration = {
|
||||
id: '202610181320-remote-schedule-targets',
|
||||
|
||||
up(db) {
|
||||
const jobColumns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const jobColumns = selectTableColumns(db, 'schedule_jobs')
|
||||
if (jobColumns.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const runColumns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const runColumns = selectTableColumns(db, 'schedule_runs')
|
||||
const jobColumnNames = new Set(jobColumns.map((column) => column.name))
|
||||
const runColumnNames = new Set(runColumns.map((column) => column.name))
|
||||
const jobsNeedRebuild =
|
||||
|
||||
@@ -11,14 +11,6 @@ function rebuildScopeIndex(db: Database, globalScopeId: number): void {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the rows the legacy scope key cannot hold.
|
||||
*
|
||||
* The legacy index merged global rows (`repo_id IS NULL`) with the Assistant repository's scope
|
||||
* (`repo_id = 0`), and the old upsert let the last write win, so the newest row of each merged
|
||||
* group is the state legacy code would hold. Ordering by `updated_at`, then `id`, keeps that row
|
||||
* and deletes the rest, which lets the legacy unique index be recreated.
|
||||
*/
|
||||
function collapseLegacyScopeDuplicates(db: Database): void {
|
||||
db.run(`
|
||||
DELETE FROM secrets
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610221800-session-device-name',
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info("session")').all() as ColumnInfo[]
|
||||
const tableInfo = selectTableColumns(db, 'session')
|
||||
if (!tableInfo.some((column) => column.name === 'deviceName')) {
|
||||
db.run('ALTER TABLE "session" ADD COLUMN deviceName TEXT')
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610251900-schedule-sandbox-config',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'schedule_jobs')
|
||||
if (!columns.some((column) => column.name === 'sandbox_config')) {
|
||||
db.run('ALTER TABLE schedule_jobs ADD COLUMN sandbox_config TEXT')
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { selectTableColumns } from '../rows'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610271800-schedule-show-in-inbox',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const columns = selectTableColumns(db, 'schedule_jobs')
|
||||
if (!columns.some((column) => column.name === 'show_in_inbox')) {
|
||||
db.run('ALTER TABLE schedule_jobs ADD COLUMN show_in_inbox INTEGER NOT NULL DEFAULT 1')
|
||||
}
|
||||
|
||||
+114
-74
@@ -1,11 +1,15 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
MultiRunEntryStatusSchema,
|
||||
MultiRunFusionSourceSchema,
|
||||
MultiRunFusionStatusSchema,
|
||||
type MultiRunEntryStatus,
|
||||
type MultiRunFusionSource,
|
||||
type MultiRunFusionStatus,
|
||||
type MultiRunTarget,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { selectRow, selectRows } from './rows'
|
||||
|
||||
export interface MultiRunEntryRecord {
|
||||
id: number
|
||||
@@ -84,46 +88,61 @@ export interface MultiRunFusionPatch {
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
interface MultiRunRow {
|
||||
id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
directory: string | null
|
||||
name: string
|
||||
prompt: string
|
||||
isolated: number
|
||||
base_ref: string | null
|
||||
created_at: number
|
||||
}
|
||||
const MultiRunRowSchema = z.object({
|
||||
id: z.number(),
|
||||
repo_id: z.number().nullable(),
|
||||
server_id: z.string(),
|
||||
directory: z.string().nullable(),
|
||||
name: z.string(),
|
||||
prompt: z.string(),
|
||||
isolated: z.number(),
|
||||
base_ref: z.string().nullable(),
|
||||
created_at: z.number(),
|
||||
})
|
||||
|
||||
interface MultiRunEntryRow {
|
||||
id: number
|
||||
multi_run_id: number
|
||||
model: string
|
||||
status: MultiRunEntryStatus
|
||||
session_id: string | null
|
||||
directory: string | null
|
||||
error: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
type MultiRunRow = z.infer<typeof MultiRunRowSchema>
|
||||
|
||||
interface MultiRunFusionRow {
|
||||
id: number
|
||||
multi_run_id: number
|
||||
request_id: string
|
||||
model: string
|
||||
instructions: string | null
|
||||
isolated: number
|
||||
base_ref: string | null
|
||||
sources: string
|
||||
status: MultiRunFusionStatus
|
||||
session_id: string | null
|
||||
directory: string | null
|
||||
error: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
const MultiRunEntryRowSchema = z.object({
|
||||
id: z.number(),
|
||||
multi_run_id: z.number(),
|
||||
model: z.string(),
|
||||
status: MultiRunEntryStatusSchema,
|
||||
session_id: z.string().nullable(),
|
||||
directory: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
created_at: z.number(),
|
||||
updated_at: z.number(),
|
||||
})
|
||||
|
||||
type MultiRunEntryRow = z.infer<typeof MultiRunEntryRowSchema>
|
||||
|
||||
const MultiRunFusionRowSchema = z.object({
|
||||
id: z.number(),
|
||||
multi_run_id: z.number(),
|
||||
request_id: z.string(),
|
||||
model: z.string(),
|
||||
instructions: z.string().nullable(),
|
||||
isolated: z.number(),
|
||||
base_ref: z.string().nullable(),
|
||||
sources: z.string(),
|
||||
status: MultiRunFusionStatusSchema,
|
||||
session_id: z.string().nullable(),
|
||||
directory: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
created_at: z.number(),
|
||||
updated_at: z.number(),
|
||||
})
|
||||
|
||||
type MultiRunFusionRow = z.infer<typeof MultiRunFusionRowSchema>
|
||||
|
||||
const MultiRunIdRowSchema = z.object({ multi_run_id: z.number() })
|
||||
|
||||
const MultiRunFusionRefRowSchema = z.object({
|
||||
multi_run_id: z.number(),
|
||||
request_id: z.string(),
|
||||
})
|
||||
|
||||
const MultiRunIsolatedRowSchema = z.object({ isolated: z.number() })
|
||||
|
||||
const MULTI_RUN_COLUMNS = 'id, repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at'
|
||||
|
||||
@@ -242,9 +261,7 @@ export function createMultiRunWithEntries(
|
||||
}
|
||||
|
||||
export function getMultiRun(db: Database, id: number): MultiRunRecord | null {
|
||||
const row = db
|
||||
.prepare(`SELECT ${MULTI_RUN_COLUMNS} FROM multi_runs WHERE id = ?`)
|
||||
.get(id) as MultiRunRow | undefined
|
||||
const row = selectRow(db, MultiRunRowSchema, `SELECT ${MULTI_RUN_COLUMNS} FROM multi_runs WHERE id = ?`, id)
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
@@ -257,26 +274,33 @@ export function listMultiRuns(db: Database, target: MultiRunTarget, limit: numbe
|
||||
? ['repo_id = ?', [target.repoId] as const]
|
||||
: ['server_id = ? AND directory = ?', [target.serverId, target.directory] as const]
|
||||
|
||||
const rows = db
|
||||
.prepare(`
|
||||
const rows = selectRows(
|
||||
db,
|
||||
MultiRunRowSchema,
|
||||
`
|
||||
SELECT ${MULTI_RUN_COLUMNS} FROM multi_runs
|
||||
WHERE ${where}
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
.all(...params, limit) as MultiRunRow[]
|
||||
`,
|
||||
...params,
|
||||
limit,
|
||||
)
|
||||
if (rows.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const placeholders = rows.map(() => '?').join(', ')
|
||||
const entryRows = db
|
||||
.prepare(`
|
||||
const entryRows = selectRows(
|
||||
db,
|
||||
MultiRunEntryRowSchema,
|
||||
`
|
||||
SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries
|
||||
WHERE multi_run_id IN (${placeholders})
|
||||
ORDER BY multi_run_id ASC, id ASC
|
||||
`)
|
||||
.all(...rows.map((row) => row.id)) as MultiRunEntryRow[]
|
||||
`,
|
||||
...rows.map((row) => row.id),
|
||||
)
|
||||
|
||||
const entriesByRun = new Map<number, MultiRunEntryRow[]>()
|
||||
for (const row of rows) {
|
||||
@@ -286,13 +310,16 @@ export function listMultiRuns(db: Database, target: MultiRunTarget, limit: numbe
|
||||
entriesByRun.get(entryRow.multi_run_id)?.push(entryRow)
|
||||
}
|
||||
|
||||
const fusionRows = db
|
||||
.prepare(`
|
||||
const fusionRows = selectRows(
|
||||
db,
|
||||
MultiRunFusionRowSchema,
|
||||
`
|
||||
SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions
|
||||
WHERE multi_run_id IN (${placeholders})
|
||||
ORDER BY multi_run_id ASC, id ASC
|
||||
`)
|
||||
.all(...rows.map((row) => row.id)) as MultiRunFusionRow[]
|
||||
`,
|
||||
...rows.map((row) => row.id),
|
||||
)
|
||||
|
||||
const fusionsByRun = new Map<number, MultiRunFusionRow[]>()
|
||||
for (const row of rows) {
|
||||
@@ -308,16 +335,18 @@ export function listMultiRuns(db: Database, target: MultiRunTarget, limit: numbe
|
||||
}
|
||||
|
||||
export function getMultiRunEntry(db: Database, multiRunId: number, entryId: number): MultiRunEntryRecord | null {
|
||||
const row = db
|
||||
.prepare(`SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries WHERE id = ? AND multi_run_id = ?`)
|
||||
.get(entryId, multiRunId) as MultiRunEntryRow | undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
MultiRunEntryRowSchema,
|
||||
`SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries WHERE id = ? AND multi_run_id = ?`,
|
||||
entryId,
|
||||
multiRunId,
|
||||
)
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
|
||||
const group = db.prepare('SELECT isolated FROM multi_runs WHERE id = ?').get(multiRunId) as
|
||||
| { isolated: number }
|
||||
| undefined
|
||||
const group = selectRow(db, MultiRunIsolatedRowSchema, 'SELECT isolated FROM multi_runs WHERE id = ?', multiRunId)
|
||||
return mapEntryRow(row, group?.isolated === 1)
|
||||
}
|
||||
|
||||
@@ -331,9 +360,7 @@ export function updateMultiRunEntry(
|
||||
return null
|
||||
}
|
||||
|
||||
const row = db.prepare('SELECT multi_run_id FROM multi_run_entries WHERE id = ?').get(entryId) as
|
||||
| { multi_run_id: number }
|
||||
| undefined
|
||||
const row = selectRow(db, MultiRunIdRowSchema, 'SELECT multi_run_id FROM multi_run_entries WHERE id = ?', entryId)
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
@@ -345,9 +372,13 @@ export function getMultiRunFusionByRequest(
|
||||
multiRunId: number,
|
||||
requestId: string,
|
||||
): MultiRunFusionRecord | null {
|
||||
const row = db
|
||||
.prepare(`SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions WHERE multi_run_id = ? AND request_id = ?`)
|
||||
.get(multiRunId, requestId) as MultiRunFusionRow | undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
MultiRunFusionRowSchema,
|
||||
`SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions WHERE multi_run_id = ? AND request_id = ?`,
|
||||
multiRunId,
|
||||
requestId,
|
||||
)
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
@@ -402,9 +433,12 @@ export function updateMultiRunFusion(
|
||||
return null
|
||||
}
|
||||
|
||||
const row = db.prepare('SELECT multi_run_id, request_id FROM multi_run_fusions WHERE id = ?').get(fusionId) as
|
||||
| { multi_run_id: number; request_id: string }
|
||||
| undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
MultiRunFusionRefRowSchema,
|
||||
'SELECT multi_run_id, request_id FROM multi_run_fusions WHERE id = ?',
|
||||
fusionId,
|
||||
)
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
@@ -456,15 +490,21 @@ function runGuardedStatusUpdate(
|
||||
}
|
||||
|
||||
function loadEntries(db: Database, multiRunId: number): MultiRunEntryRow[] {
|
||||
return db
|
||||
.prepare(`SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries WHERE multi_run_id = ? ORDER BY id ASC`)
|
||||
.all(multiRunId) as MultiRunEntryRow[]
|
||||
return selectRows(
|
||||
db,
|
||||
MultiRunEntryRowSchema,
|
||||
`SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries WHERE multi_run_id = ? ORDER BY id ASC`,
|
||||
multiRunId,
|
||||
)
|
||||
}
|
||||
|
||||
function loadFusions(db: Database, multiRunId: number): MultiRunFusionRow[] {
|
||||
return db
|
||||
.prepare(`SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions WHERE multi_run_id = ? ORDER BY id ASC`)
|
||||
.all(multiRunId) as MultiRunFusionRow[]
|
||||
return selectRows(
|
||||
db,
|
||||
MultiRunFusionRowSchema,
|
||||
`SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions WHERE multi_run_id = ? ORDER BY id ASC`,
|
||||
multiRunId,
|
||||
)
|
||||
}
|
||||
|
||||
function toMultiRunRecord(
|
||||
|
||||
@@ -2,18 +2,22 @@ import { randomBytes } from 'node:crypto'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { OpenCodeServer } from '@opencode-manager/shared/schemas'
|
||||
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
|
||||
import { z } from 'zod'
|
||||
import { deleteSecret, readEncryptedSecret, writeEncryptedSecret } from './secrets'
|
||||
import { selectRow, selectRows } from './rows'
|
||||
|
||||
interface OpenCodeServerRow {
|
||||
id: string
|
||||
name: string
|
||||
base_url: string
|
||||
username: string
|
||||
enabled: number
|
||||
created_at: number
|
||||
updated_at: number
|
||||
has_password: number
|
||||
}
|
||||
const OpenCodeServerRowSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
base_url: z.string(),
|
||||
username: z.string(),
|
||||
enabled: z.number(),
|
||||
created_at: z.number(),
|
||||
updated_at: z.number(),
|
||||
has_password: z.number(),
|
||||
})
|
||||
|
||||
type OpenCodeServerRow = z.infer<typeof OpenCodeServerRowSchema>
|
||||
|
||||
export interface OpenCodeServerInsert {
|
||||
name: string
|
||||
@@ -61,16 +65,12 @@ function mapRow(row: OpenCodeServerRow): OpenCodeServer {
|
||||
}
|
||||
|
||||
export function listOpenCodeServers(db: Database): OpenCodeServer[] {
|
||||
const rows = db
|
||||
.prepare(`${SELECT_SERVER} ORDER BY s.name COLLATE NOCASE, s.created_at`)
|
||||
.all() as OpenCodeServerRow[]
|
||||
const rows = selectRows(db, OpenCodeServerRowSchema, `${SELECT_SERVER} ORDER BY s.name COLLATE NOCASE, s.created_at`)
|
||||
return rows.map(mapRow)
|
||||
}
|
||||
|
||||
export function getOpenCodeServer(db: Database, serverId: string): OpenCodeServer | null {
|
||||
const row = db
|
||||
.prepare(`${SELECT_SERVER} WHERE s.id = ?`)
|
||||
.get(serverId) as OpenCodeServerRow | undefined
|
||||
const row = selectRow(db, OpenCodeServerRowSchema, `${SELECT_SERVER} WHERE s.id = ?`, serverId)
|
||||
return row ? mapRow(row) : null
|
||||
}
|
||||
|
||||
|
||||
@@ -5,19 +5,23 @@ import {
|
||||
type CreatePromptTemplateRequest,
|
||||
type UpdatePromptTemplateRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { selectRow, selectRows } from './rows'
|
||||
|
||||
interface PromptTemplateRow {
|
||||
id: number
|
||||
title: string
|
||||
category: string
|
||||
cadence_hint: string
|
||||
suggested_name: string
|
||||
suggested_description: string
|
||||
description: string
|
||||
prompt: string
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
const PromptTemplateRowSchema = z.object({
|
||||
id: z.number(),
|
||||
title: z.string(),
|
||||
category: z.string(),
|
||||
cadence_hint: z.string(),
|
||||
suggested_name: z.string(),
|
||||
suggested_description: z.string(),
|
||||
description: z.string(),
|
||||
prompt: z.string(),
|
||||
created_at: z.number(),
|
||||
updated_at: z.number(),
|
||||
})
|
||||
|
||||
type PromptTemplateRow = z.infer<typeof PromptTemplateRowSchema>
|
||||
|
||||
function rowToPromptTemplate(row: PromptTemplateRow): PromptTemplate {
|
||||
return PromptTemplateSchema.parse({
|
||||
@@ -35,12 +39,12 @@ function rowToPromptTemplate(row: PromptTemplateRow): PromptTemplate {
|
||||
}
|
||||
|
||||
export function listPromptTemplates(db: Database): PromptTemplate[] {
|
||||
const rows = db.prepare('SELECT * FROM prompt_templates ORDER BY id ASC').all() as PromptTemplateRow[]
|
||||
const rows = selectRows(db, PromptTemplateRowSchema, 'SELECT * FROM prompt_templates ORDER BY id ASC')
|
||||
return rows.map(rowToPromptTemplate)
|
||||
}
|
||||
|
||||
export function getPromptTemplateById(db: Database, id: number): PromptTemplate | null {
|
||||
const row = db.prepare('SELECT * FROM prompt_templates WHERE id = ?').get(id) as PromptTemplateRow | null
|
||||
const row = selectRow(db, PromptTemplateRowSchema, 'SELECT * FROM prompt_templates WHERE id = ?', id)
|
||||
return row ? rowToPromptTemplate(row) : null
|
||||
}
|
||||
|
||||
@@ -50,7 +54,7 @@ export function createPromptTemplate(db: Database, data: CreatePromptTemplateReq
|
||||
INSERT INTO prompt_templates (title, category, cadence_hint, suggested_name, suggested_description, description, prompt, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(data.title, data.category, data.cadenceHint, data.suggestedName, data.suggestedDescription, data.description, data.prompt, now, now)
|
||||
return getPromptTemplateById(db, result.lastInsertRowid as number)!
|
||||
return getPromptTemplateById(db, Number(result.lastInsertRowid))!
|
||||
}
|
||||
|
||||
export function updatePromptTemplate(db: Database, id: number, data: UpdatePromptTemplateRequest): PromptTemplate | null {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { selectTableColumns } from './rows'
|
||||
|
||||
/** Creates the push subscriptions schema and adds the columns older databases lack. */
|
||||
export function ensurePushSubscriptionsTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
@@ -16,7 +16,7 @@ export function ensurePushSubscriptionsTable(db: Database): void {
|
||||
)
|
||||
`)
|
||||
|
||||
const columns = db.prepare('PRAGMA table_info(push_subscriptions)').all() as Array<{ name: string }>
|
||||
const columns = selectTableColumns(db, 'push_subscriptions')
|
||||
if (!columns.some((column) => column.name === 'session_id')) {
|
||||
db.run('ALTER TABLE push_subscriptions ADD COLUMN session_id TEXT')
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export function ensurePushSubscriptionsTable(db: Database): void {
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_push_sub_session ON push_subscriptions(session_id)')
|
||||
}
|
||||
|
||||
/** Deletes the push subscriptions registered by any of the given Better Auth sessions. */
|
||||
export function deletePushSubscriptionsForSessions(db: Database, sessionIds: string[]): number {
|
||||
if (sessionIds.length === 0) return 0
|
||||
const placeholders = sessionIds.map(() => '?').join(', ')
|
||||
@@ -35,7 +34,6 @@ export function deletePushSubscriptionsForSessions(db: Database, sessionIds: str
|
||||
.run(...sessionIds).changes
|
||||
}
|
||||
|
||||
/** Deletes the push subscriptions a revoked Better Auth session registered. */
|
||||
export function deletePushSubscriptionsForSession(db: Database, sessionId: string): number {
|
||||
return deletePushSubscriptionsForSessions(db, [sessionId])
|
||||
}
|
||||
+51
-47
@@ -1,27 +1,36 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo, CreateRepoInput } from '../types/repo'
|
||||
import { RepoStatusSchema } from '@opencode-manager/shared/schemas'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { invalidateRepoEnvCache } from '../utils/repo-env-cache'
|
||||
import { z } from 'zod'
|
||||
import path from 'path'
|
||||
import { selectRow, selectRows } from './rows'
|
||||
|
||||
interface RepoRow {
|
||||
id: number
|
||||
name?: string
|
||||
repo_url?: string
|
||||
local_path: string
|
||||
source_path?: string
|
||||
branch?: string
|
||||
default_branch: string
|
||||
clone_status: string
|
||||
cloned_at: number
|
||||
last_pulled?: number
|
||||
last_accessed_at?: number
|
||||
is_worktree?: number
|
||||
is_local?: number
|
||||
}
|
||||
const RepoRowSchema = z.object({
|
||||
id: z.number(),
|
||||
name: z.string().nullish(),
|
||||
repo_url: z.string().nullish(),
|
||||
local_path: z.string(),
|
||||
source_path: z.string().nullish(),
|
||||
branch: z.string().nullish(),
|
||||
default_branch: z.string(),
|
||||
clone_status: RepoStatusSchema,
|
||||
cloned_at: z.number(),
|
||||
last_pulled: z.number().nullish(),
|
||||
last_accessed_at: z.number().nullish(),
|
||||
is_worktree: z.number().nullish(),
|
||||
is_local: z.number().nullish(),
|
||||
})
|
||||
|
||||
type RepoRow = z.infer<typeof RepoRowSchema>
|
||||
|
||||
const RepoIdRowSchema = z.object({ id: z.number() })
|
||||
|
||||
const RepoSettingRowSchema = z.object({ value: z.string() })
|
||||
|
||||
const REPO_GIT_CREDENTIAL_SETTING_KEY = 'gitCredentialId'
|
||||
|
||||
@@ -33,25 +42,23 @@ function rowToRepo(row: RepoRow): Repo {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name ?? undefined,
|
||||
repoUrl: row.repo_url,
|
||||
repoUrl: row.repo_url ?? undefined,
|
||||
localPath: row.local_path,
|
||||
fullPath,
|
||||
sourcePath: row.source_path,
|
||||
branch: row.branch,
|
||||
sourcePath: row.source_path ?? undefined,
|
||||
branch: row.branch ?? undefined,
|
||||
defaultBranch: row.default_branch,
|
||||
cloneStatus: row.clone_status as Repo['cloneStatus'],
|
||||
cloneStatus: row.clone_status,
|
||||
clonedAt: row.cloned_at,
|
||||
lastPulled: row.last_pulled,
|
||||
lastAccessedAt: row.last_accessed_at,
|
||||
lastPulled: row.last_pulled ?? undefined,
|
||||
lastAccessedAt: row.last_accessed_at ?? undefined,
|
||||
isWorktree: row.is_worktree ? Boolean(row.is_worktree) : undefined,
|
||||
isLocal: row.is_local ? Boolean(row.is_local) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export function getRepoSetting(db: Database, repoId: number, key: string): string | null {
|
||||
const row = db
|
||||
.prepare('SELECT value FROM repo_settings WHERE repo_id = ? AND key = ?')
|
||||
.get(repoId, key) as { value: string } | undefined
|
||||
const row = selectRow(db, RepoSettingRowSchema, 'SELECT value FROM repo_settings WHERE repo_id = ? AND key = ?', repoId, key)
|
||||
|
||||
return row?.value ?? null
|
||||
}
|
||||
@@ -121,9 +128,8 @@ function updateRepoIdReference(db: Database, tableName: RepoIdTable, fromRepoId:
|
||||
}
|
||||
|
||||
export function getRepoById(db: Database, id: number): Repo | null {
|
||||
const stmt = db.prepare('SELECT * FROM repos WHERE id = ?')
|
||||
const row = stmt.get(id) as RepoRow | undefined
|
||||
|
||||
const row = selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE id = ?', id)
|
||||
|
||||
return row ? rowToRepo(row) : null
|
||||
}
|
||||
|
||||
@@ -131,8 +137,13 @@ export function ensureAssistantRepo(db: Database): Repo {
|
||||
const now = Date.now()
|
||||
|
||||
const syncAssistantRepo = db.transaction(() => {
|
||||
const existingAssistantPathRow = db.prepare('SELECT id FROM repos WHERE local_path = ? AND id != ?')
|
||||
.get(ASSISTANT_REPO_PATH, ASSISTANT_REPO_ID) as { id: number } | undefined
|
||||
const existingAssistantPathRow = selectRow(
|
||||
db,
|
||||
RepoIdRowSchema,
|
||||
'SELECT id FROM repos WHERE local_path = ? AND id != ?',
|
||||
ASSISTANT_REPO_PATH,
|
||||
ASSISTANT_REPO_ID,
|
||||
)
|
||||
|
||||
if (existingAssistantPathRow) {
|
||||
for (const table of TABLES_WITH_REPO_ID) {
|
||||
@@ -229,9 +240,10 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo {
|
||||
throw new Error(`Failed to retrieve newly created repo with id ${result.lastInsertRowid}`)
|
||||
}
|
||||
return newRepo
|
||||
} catch (error: unknown) {
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorMessage(error)
|
||||
if (errorMessage.includes('UNIQUE constraint failed') || (error && typeof error === 'object' && 'code' in error && error.code === 'SQLITE_CONSTRAINT_UNIQUE')) {
|
||||
const isUniqueConstraintCode = error instanceof Error && 'code' in error && error.code === 'SQLITE_CONSTRAINT_UNIQUE'
|
||||
if (errorMessage.includes('UNIQUE constraint failed') || isUniqueConstraintCode) {
|
||||
const conflictRepo = repo.isLocal
|
||||
? repo.sourcePath
|
||||
? getRepoBySourcePath(db, repo.sourcePath) ?? getRepoByLocalPath(db, normalizedPath)
|
||||
@@ -251,35 +263,27 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo {
|
||||
}
|
||||
|
||||
export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: string): Repo | null {
|
||||
const query = branch
|
||||
? 'SELECT * FROM repos WHERE repo_url = ? AND branch = ?'
|
||||
: 'SELECT * FROM repos WHERE repo_url = ? AND branch IS NULL'
|
||||
|
||||
const stmt = db.prepare(query)
|
||||
const row = branch
|
||||
? stmt.get(repoUrl, branch) as RepoRow | undefined
|
||||
: stmt.get(repoUrl) as RepoRow | undefined
|
||||
|
||||
const row = branch
|
||||
? selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE repo_url = ? AND branch = ?', repoUrl, branch)
|
||||
: selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE repo_url = ? AND branch IS NULL', repoUrl)
|
||||
|
||||
return row ? rowToRepo(row) : null
|
||||
}
|
||||
|
||||
export function getRepoByLocalPath(db: Database, localPath: string): Repo | null {
|
||||
const stmt = db.prepare('SELECT * FROM repos WHERE local_path = ?')
|
||||
const row = stmt.get(localPath) as RepoRow | undefined
|
||||
|
||||
const row = selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE local_path = ?', localPath)
|
||||
|
||||
return row ? rowToRepo(row) : null
|
||||
}
|
||||
|
||||
export function getRepoBySourcePath(db: Database, sourcePath: string): Repo | null {
|
||||
const stmt = db.prepare('SELECT * FROM repos WHERE source_path = ?')
|
||||
const row = stmt.get(sourcePath) as RepoRow | undefined
|
||||
const row = selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE source_path = ?', sourcePath)
|
||||
|
||||
return row ? rowToRepo(row) : null
|
||||
}
|
||||
|
||||
export function listRepos(db: Database, repoOrder?: number[]): Repo[] {
|
||||
const stmt = db.prepare('SELECT * FROM repos ORDER BY cloned_at DESC')
|
||||
const rows = stmt.all() as RepoRow[]
|
||||
const rows = selectRows(db, RepoRowSchema, 'SELECT * FROM repos ORDER BY cloned_at DESC')
|
||||
const repos = rows.map(rowToRepo)
|
||||
|
||||
if (!repoOrder || repoOrder.length === 0) {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Database, SQLQueryBindings } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
|
||||
export const TableColumnSchema = z.object({
|
||||
name: z.string(),
|
||||
notnull: z.number().default(0),
|
||||
dflt_value: z.string().nullable().default(null),
|
||||
pk: z.number().default(0),
|
||||
})
|
||||
|
||||
export type TableColumn = z.infer<typeof TableColumnSchema>
|
||||
|
||||
export function selectRow<Schema extends z.ZodType>(
|
||||
db: Database,
|
||||
schema: Schema,
|
||||
sql: string,
|
||||
...params: SQLQueryBindings[]
|
||||
): z.infer<Schema> | null {
|
||||
const row = db.prepare<unknown, SQLQueryBindings[]>(sql).get(...params)
|
||||
return row === null || row === undefined ? null : schema.parse(row)
|
||||
}
|
||||
|
||||
export function selectRows<Schema extends z.ZodType>(
|
||||
db: Database,
|
||||
schema: Schema,
|
||||
sql: string,
|
||||
...params: SQLQueryBindings[]
|
||||
): z.infer<Schema>[] {
|
||||
return db
|
||||
.prepare<unknown, SQLQueryBindings[]>(sql)
|
||||
.all(...params)
|
||||
.map((row) => schema.parse(row))
|
||||
}
|
||||
|
||||
export function selectTableColumns(db: Database, table: string): TableColumn[] {
|
||||
return selectRows(db, TableColumnSchema, `PRAGMA table_info(${table})`)
|
||||
}
|
||||
+223
-156
@@ -3,14 +3,15 @@ import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
ScheduleJobSchema,
|
||||
ScheduleMcpServersSchema,
|
||||
ScheduleModeSchema,
|
||||
SchedulePermissionConfigSchema,
|
||||
ScheduleRunSchema,
|
||||
ScheduleRunStatusSchema,
|
||||
ScheduleSandboxConfigSchema,
|
||||
ScheduleSkillMetadataSchema,
|
||||
ScheduleWorkspaceModeSchema,
|
||||
type ScheduleJob,
|
||||
type ScheduleMcpServer,
|
||||
type ScheduleMode,
|
||||
type SchedulePermissionConfig,
|
||||
type ScheduleRun,
|
||||
type ScheduleRunStatus,
|
||||
@@ -20,57 +21,82 @@ import {
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
|
||||
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
|
||||
import { z } from 'zod'
|
||||
import { selectRow, selectRows } from './rows'
|
||||
|
||||
interface ScheduleJobRow {
|
||||
id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
directory: string | null
|
||||
name: string
|
||||
description: string | null
|
||||
enabled: number
|
||||
show_in_inbox: number
|
||||
schedule_mode: ScheduleMode | null
|
||||
interval_minutes: number | null
|
||||
cron_expression: string | null
|
||||
timezone: string | null
|
||||
agent_slug: string | null
|
||||
prompt: string
|
||||
model: string | null
|
||||
skill_metadata: string | null
|
||||
permission_config: string | null
|
||||
mcp_servers: string | null
|
||||
branch: string | null
|
||||
workspace_mode: ScheduleWorkspaceMode | null
|
||||
sandbox_config: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
last_run_at: number | null
|
||||
next_run_at: number | null
|
||||
}
|
||||
const ScheduleJobRowSchema = z.object({
|
||||
id: z.number(),
|
||||
repo_id: z.number().nullable(),
|
||||
server_id: z.string().nullish(),
|
||||
directory: z.string().nullish(),
|
||||
name: z.string(),
|
||||
description: z.string().nullish(),
|
||||
enabled: z.number(),
|
||||
show_in_inbox: z.number().nullish(),
|
||||
schedule_mode: ScheduleModeSchema.nullish(),
|
||||
interval_minutes: z.number().nullish(),
|
||||
cron_expression: z.string().nullish(),
|
||||
timezone: z.string().nullish(),
|
||||
agent_slug: z.string().nullish(),
|
||||
prompt: z.string(),
|
||||
model: z.string().nullish(),
|
||||
skill_metadata: z.string().nullish(),
|
||||
permission_config: z.string().nullish(),
|
||||
mcp_servers: z.string().nullish(),
|
||||
branch: z.string().nullish(),
|
||||
workspace_mode: z.string().nullish(),
|
||||
sandbox_config: z.string().nullish(),
|
||||
created_at: z.number(),
|
||||
updated_at: z.number(),
|
||||
last_run_at: z.number().nullish(),
|
||||
next_run_at: z.number().nullish(),
|
||||
})
|
||||
|
||||
interface ScheduleRunRow {
|
||||
id: number
|
||||
job_id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
trigger_source: string
|
||||
status: string
|
||||
started_at: number
|
||||
finished_at: number | null
|
||||
viewed_at: number | null
|
||||
created_at: number
|
||||
session_id: string | null
|
||||
session_title: string | null
|
||||
log_text: string | null
|
||||
response_text: string | null
|
||||
error_text: string | null
|
||||
run_branch: string | null
|
||||
commit_hash: string | null
|
||||
worktree_path: string | null
|
||||
}
|
||||
type ScheduleJobRow = z.infer<typeof ScheduleJobRowSchema>
|
||||
|
||||
function parseSkillMetadata(raw: string | null) {
|
||||
const ScheduleRunRowSchema = z.object({
|
||||
id: z.number(),
|
||||
job_id: z.number(),
|
||||
repo_id: z.number().nullable(),
|
||||
server_id: z.string().nullish(),
|
||||
trigger_source: z.string(),
|
||||
status: z.string(),
|
||||
started_at: z.number(),
|
||||
finished_at: z.number().nullish(),
|
||||
viewed_at: z.number().nullish(),
|
||||
created_at: z.number(),
|
||||
session_id: z.string().nullish(),
|
||||
session_title: z.string().nullish(),
|
||||
log_text: z.string().nullish(),
|
||||
response_text: z.string().nullish(),
|
||||
error_text: z.string().nullish(),
|
||||
run_branch: z.string().nullish(),
|
||||
commit_hash: z.string().nullish(),
|
||||
worktree_path: z.string().nullish(),
|
||||
})
|
||||
|
||||
type ScheduleRunRow = z.infer<typeof ScheduleRunRowSchema>
|
||||
|
||||
const ScheduleJobIdRowSchema = z.object({ id: z.number() })
|
||||
|
||||
const ScheduleRunArtifactRowSchema = z.object({
|
||||
id: z.number(),
|
||||
status: ScheduleRunStatusSchema,
|
||||
run_branch: z.string().nullable(),
|
||||
worktree_path: z.string().nullable(),
|
||||
})
|
||||
|
||||
const ScheduleJobWorktreeOwnerRowSchema = z.object({
|
||||
id: z.number(),
|
||||
repo_id: z.number(),
|
||||
name: z.string(),
|
||||
})
|
||||
|
||||
const ShowInInboxRowSchema = z.object({ show_in_inbox: z.number() })
|
||||
|
||||
const UnreadScheduleRunCountRowSchema = z.object({ total: z.number(), failed: z.number() })
|
||||
|
||||
function parseSkillMetadata(raw: string | null | undefined) {
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
@@ -84,7 +110,7 @@ function parseSkillMetadata(raw: string | null) {
|
||||
}
|
||||
}
|
||||
|
||||
function parsePermissionConfig(raw: string | null): SchedulePermissionConfig | null {
|
||||
function parsePermissionConfig(raw: string | null | undefined): SchedulePermissionConfig | null {
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
@@ -98,7 +124,7 @@ function parsePermissionConfig(raw: string | null): SchedulePermissionConfig | n
|
||||
}
|
||||
}
|
||||
|
||||
function parseMcpServers(raw: string | null): ScheduleMcpServer[] {
|
||||
function parseMcpServers(raw: string | null | undefined): ScheduleMcpServer[] {
|
||||
if (!raw) {
|
||||
return []
|
||||
}
|
||||
@@ -111,7 +137,7 @@ function parseMcpServers(raw: string | null): ScheduleMcpServer[] {
|
||||
}
|
||||
}
|
||||
|
||||
function parseSandboxConfig(raw: string | null): ScheduleSandboxConfig | null {
|
||||
function parseSandboxConfig(raw: string | null | undefined): ScheduleSandboxConfig | null {
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
@@ -124,7 +150,7 @@ function parseSandboxConfig(raw: string | null): ScheduleSandboxConfig | null {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeWorkspaceMode(raw: string | null): ScheduleWorkspaceMode {
|
||||
function normalizeWorkspaceMode(raw: string | null | undefined): ScheduleWorkspaceMode {
|
||||
const result = ScheduleWorkspaceModeSchema.safeParse(raw)
|
||||
return result.success ? result.data : 'worktree'
|
||||
}
|
||||
@@ -207,32 +233,27 @@ function serializeSandboxConfig(sandbox: ScheduleJobPersistenceInput['sandbox'])
|
||||
}
|
||||
|
||||
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as ScheduleJobRow[]
|
||||
const rows = selectRows(db, ScheduleJobRowSchema, 'SELECT * FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC', repoId)
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listScheduleJobsByServer(db: Database, serverId: string): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE server_id = ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(serverId) as ScheduleJobRow[]
|
||||
const rows = selectRows(db, ScheduleJobRowSchema, 'SELECT * FROM schedule_jobs WHERE server_id = ? ORDER BY created_at DESC', serverId)
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listScheduleJobIdsByRepo(db: Database, repoId: number): number[] {
|
||||
const stmt = db.prepare('SELECT id FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as Array<{ id: number }>
|
||||
const rows = selectRows(db, ScheduleJobIdRowSchema, 'SELECT id FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC', repoId)
|
||||
return rows.map((row) => row.id)
|
||||
}
|
||||
|
||||
export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
|
||||
const rows = stmt.all() as ScheduleJobRow[]
|
||||
const rows = selectRows(db, ScheduleJobRowSchema, 'SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function getScheduleJobById(db: Database, repoId: number | null, jobId: number): ScheduleJob | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId) as ScheduleJobRow | undefined
|
||||
const row = selectRow(db, ScheduleJobRowSchema, 'SELECT * FROM schedule_jobs WHERE repo_id IS ? AND id = ?', repoId, jobId)
|
||||
return row ? rowToScheduleJob(row) : null
|
||||
}
|
||||
|
||||
@@ -348,12 +369,16 @@ export interface ScheduleRunArtifact {
|
||||
}
|
||||
|
||||
export function listScheduleRunArtifactsByJob(db: Database, repoId: number | null, jobId: number): ScheduleRunArtifact[] {
|
||||
const rows = db
|
||||
.prepare('SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id IS ? AND job_id = ? ORDER BY id DESC')
|
||||
.all(repoId, jobId) as { id: number; status: string; run_branch: string | null; worktree_path: string | null }[]
|
||||
const rows = selectRows(
|
||||
db,
|
||||
ScheduleRunArtifactRowSchema,
|
||||
'SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id IS ? AND job_id = ? ORDER BY id DESC',
|
||||
repoId,
|
||||
jobId,
|
||||
)
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
status: row.status as ScheduleRunStatus,
|
||||
status: row.status,
|
||||
runBranch: row.run_branch,
|
||||
worktreePath: row.worktree_path,
|
||||
}))
|
||||
@@ -366,7 +391,7 @@ export interface ScheduleJobWorktreeOwner {
|
||||
}
|
||||
|
||||
export function listScheduleJobWorktreeOwners(db: Database): ScheduleJobWorktreeOwner[] {
|
||||
const rows = db.prepare('SELECT id, repo_id, name FROM schedule_jobs WHERE repo_id IS NOT NULL').all() as Array<{ id: number; repo_id: number; name: string }>
|
||||
const rows = selectRows(db, ScheduleJobWorktreeOwnerRowSchema, 'SELECT id, repo_id, name FROM schedule_jobs WHERE repo_id IS NOT NULL')
|
||||
return rows.map((row) => ({ id: row.id, repoId: row.repo_id, name: row.name }))
|
||||
}
|
||||
|
||||
@@ -392,7 +417,12 @@ export function deleteScheduleRunsByIds(db: Database, repoId: number | null, job
|
||||
return result.changes
|
||||
}
|
||||
|
||||
export function cleanupOrphanedSchedules(db: Database): { orphanedJobs: number; orphanedRuns: number } {
|
||||
export interface OrphanedScheduleCleanup {
|
||||
orphanedJobs: number
|
||||
orphanedRuns: number
|
||||
}
|
||||
|
||||
export function cleanupOrphanedSchedules(db: Database): OrphanedScheduleCleanup {
|
||||
const runStmt = db.prepare(`
|
||||
DELETE FROM schedule_runs
|
||||
WHERE (repo_id IS NOT NULL AND repo_id != ? AND repo_id NOT IN (SELECT id FROM repos))
|
||||
@@ -453,12 +483,6 @@ export function createScheduleRun(
|
||||
return run
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes a schedule run and stores its session output. A completed run of a
|
||||
* job that does not announce itself in the inbox is marked viewed at the same
|
||||
* timestamp, so quiet schedules never surface as unread; failed and cancelled
|
||||
* runs stay unread, and the job's setting at finish time decides the outcome.
|
||||
*/
|
||||
export function updateScheduleRun(
|
||||
db: Database,
|
||||
repoId: number | null,
|
||||
@@ -574,8 +598,7 @@ export function updateScheduleRunWorktree(
|
||||
}
|
||||
|
||||
export function getScheduleRunById(db: Database, repoId: number | null, jobId: number, runId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId, runId) as ScheduleRunRow | undefined
|
||||
const row = selectRow(db, ScheduleRunRowSchema, 'SELECT * FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?', repoId, jobId, runId)
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
@@ -584,57 +607,74 @@ export function getScheduleRunBySessionId(
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE server_id = ? AND session_id = ? ORDER BY started_at DESC LIMIT 1')
|
||||
const row = stmt.get(serverId, sessionId) as ScheduleRunRow | undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
ScheduleRunRowSchema,
|
||||
'SELECT * FROM schedule_runs WHERE server_id = ? AND session_id = ? ORDER BY started_at DESC LIMIT 1',
|
||||
serverId,
|
||||
sessionId,
|
||||
)
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the latest run for a session belongs to a job that stays out
|
||||
* of the inbox. Sessions without a run, and sessions of announcing jobs, are
|
||||
* not quiet.
|
||||
*/
|
||||
export function isQuietScheduleRunSession(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): boolean {
|
||||
const stmt = db.prepare(`
|
||||
const row = selectRow(
|
||||
db,
|
||||
ShowInInboxRowSchema,
|
||||
`
|
||||
SELECT sj.show_in_inbox
|
||||
FROM schedule_runs sr
|
||||
JOIN schedule_jobs sj ON sj.id = sr.job_id
|
||||
WHERE sr.server_id = ? AND sr.session_id = ?
|
||||
ORDER BY sr.started_at DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
const row = stmt.get(serverId, sessionId) as { show_in_inbox: number } | undefined
|
||||
`,
|
||||
serverId,
|
||||
sessionId,
|
||||
)
|
||||
return row?.show_in_inbox === 0
|
||||
}
|
||||
|
||||
export function getRunningScheduleRunByJob(db: Database, repoId: number | null, jobId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare(`
|
||||
const row = selectRow(
|
||||
db,
|
||||
ScheduleRunRowSchema,
|
||||
`
|
||||
SELECT * FROM schedule_runs
|
||||
WHERE repo_id IS ? AND job_id = ? AND status = 'running'
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
const row = stmt.get(repoId, jobId) as ScheduleRunRow | undefined
|
||||
`,
|
||||
repoId,
|
||||
jobId,
|
||||
)
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
export function listRunningScheduleRuns(db: Database, limit: number = 100): ScheduleRun[] {
|
||||
const stmt = db.prepare(`
|
||||
const rows = selectRows(
|
||||
db,
|
||||
ScheduleRunRowSchema,
|
||||
`
|
||||
SELECT * FROM schedule_runs
|
||||
WHERE status = 'running'
|
||||
ORDER BY started_at ASC
|
||||
LIMIT ?
|
||||
`)
|
||||
const rows = stmt.all(limit) as ScheduleRunRow[]
|
||||
`,
|
||||
limit,
|
||||
)
|
||||
return rows.map(rowToScheduleRun)
|
||||
}
|
||||
|
||||
export function listScheduleRunsByJob(db: Database, repoId: number | null, jobId: number, limit: number = 20): ScheduleRun[] {
|
||||
const stmt = db.prepare(`
|
||||
const rows = selectRows(
|
||||
db,
|
||||
ScheduleRunRowSchema,
|
||||
`
|
||||
SELECT
|
||||
id,
|
||||
job_id,
|
||||
@@ -658,8 +698,11 @@ export function listScheduleRunsByJob(db: Database, repoId: number | null, jobId
|
||||
WHERE repo_id IS ? AND job_id = ?
|
||||
ORDER BY started_at DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
const rows = stmt.all(repoId, jobId, limit) as ScheduleRunRow[]
|
||||
`,
|
||||
repoId,
|
||||
jobId,
|
||||
limit,
|
||||
)
|
||||
return rows.map(rowToScheduleRun)
|
||||
}
|
||||
|
||||
@@ -680,32 +723,41 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
|
||||
lastRun: ScheduleRunSummary | null
|
||||
}
|
||||
|
||||
interface ScheduleJobWithRepoRow extends ScheduleJobRow {
|
||||
repo_url: string | null
|
||||
repo_path: string | null
|
||||
repo_name: string | null
|
||||
repo_source_path: string | null
|
||||
server_name: string | null
|
||||
last_run_id: number | null
|
||||
last_run_status: string | null
|
||||
last_run_started_at: number | null
|
||||
last_run_finished_at: number | null
|
||||
last_run_viewed_at: number | null
|
||||
last_run_error_text: string | null
|
||||
last_run_response_head: string | null
|
||||
const ScheduleJobWithRepoRowSchema = ScheduleJobRowSchema.extend({
|
||||
repo_url: z.string().nullish(),
|
||||
repo_path: z.string().nullish(),
|
||||
repo_name: z.string().nullish(),
|
||||
repo_source_path: z.string().nullish(),
|
||||
server_name: z.string().nullish(),
|
||||
last_run_id: z.number().nullish(),
|
||||
last_run_status: ScheduleRunStatusSchema.nullish(),
|
||||
last_run_started_at: z.number().nullish(),
|
||||
last_run_finished_at: z.number().nullish(),
|
||||
last_run_viewed_at: z.number().nullish(),
|
||||
last_run_error_text: z.string().nullish(),
|
||||
last_run_response_head: z.string().nullish(),
|
||||
})
|
||||
|
||||
type ScheduleJobWithRepoRow = z.infer<typeof ScheduleJobWithRepoRowSchema>
|
||||
|
||||
const RepoDisplayRowSchema = z.object({
|
||||
repo_id: z.number().nullable(),
|
||||
repo_path: z.string().nullish(),
|
||||
repo_name: z.string().nullish(),
|
||||
repo_url: z.string().nullish(),
|
||||
repo_source_path: z.string().nullish(),
|
||||
directory: z.string().nullish(),
|
||||
server_name: z.string().nullish(),
|
||||
})
|
||||
|
||||
type RepoDisplayRow = z.infer<typeof RepoDisplayRowSchema>
|
||||
|
||||
interface RepoDisplay {
|
||||
repoName: string
|
||||
repoPath: string
|
||||
}
|
||||
|
||||
interface RepoDisplayRow {
|
||||
repo_id: number | null
|
||||
repo_path: string | null
|
||||
repo_name: string | null
|
||||
repo_url?: string | null
|
||||
repo_source_path?: string | null
|
||||
directory?: string | null
|
||||
server_name?: string | null
|
||||
}
|
||||
|
||||
function resolveRepoDisplay(row: RepoDisplayRow): { repoName: string; repoPath: string } {
|
||||
function resolveRepoDisplay(row: RepoDisplayRow): RepoDisplay {
|
||||
if (row.repo_id === null) {
|
||||
return { repoName: row.server_name ?? 'Linked server', repoPath: row.directory ?? '' }
|
||||
}
|
||||
@@ -725,13 +777,17 @@ function buildLastRunSummary(row: ScheduleJobWithRepoRow): ScheduleRunSummary |
|
||||
if (row.last_run_id === null || row.last_run_id === undefined) {
|
||||
return null
|
||||
}
|
||||
const status = ScheduleRunStatusSchema.safeParse(row.last_run_status)
|
||||
if (!status.success) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: row.last_run_id,
|
||||
status: row.last_run_status as ScheduleRunStatus,
|
||||
status: status.data,
|
||||
startedAt: row.last_run_started_at ?? 0,
|
||||
finishedAt: row.last_run_finished_at,
|
||||
viewedAt: row.last_run_viewed_at,
|
||||
finishedAt: row.last_run_finished_at ?? null,
|
||||
viewedAt: row.last_run_viewed_at ?? null,
|
||||
preview: extractReportPreview(row.last_run_status === 'failed' ? row.last_run_error_text : row.last_run_response_head),
|
||||
}
|
||||
}
|
||||
@@ -747,7 +803,7 @@ function rowToScheduleJobWithRepo(row: ScheduleJobWithRepoRow): ScheduleJobWithR
|
||||
}
|
||||
|
||||
export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[] {
|
||||
const stmt = db.prepare(`
|
||||
const rows = selectRows(db, ScheduleJobWithRepoRowSchema, `
|
||||
SELECT
|
||||
sj.*, r.repo_url, r.local_path as repo_path, r.name as repo_name, r.source_path as repo_source_path,
|
||||
os.name AS server_name,
|
||||
@@ -766,7 +822,6 @@ export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[
|
||||
)
|
||||
ORDER BY COALESCE(r.local_path, sj.directory, ''), sj.name
|
||||
`)
|
||||
const rows = stmt.all() as ScheduleJobWithRepoRow[]
|
||||
return rows.map(rowToScheduleJobWithRepo)
|
||||
}
|
||||
|
||||
@@ -777,15 +832,17 @@ export interface ScheduleRunWithContext extends ScheduleRun {
|
||||
serverName: string | null
|
||||
}
|
||||
|
||||
interface ScheduleRunWithContextRow extends ScheduleRunRow {
|
||||
job_name: string
|
||||
repo_path: string | null
|
||||
repo_name: string | null
|
||||
repo_url: string | null
|
||||
repo_source_path: string | null
|
||||
directory?: string | null
|
||||
server_name?: string | null
|
||||
}
|
||||
const ScheduleRunWithContextRowSchema = ScheduleRunRowSchema.extend({
|
||||
job_name: z.string(),
|
||||
repo_path: z.string().nullish(),
|
||||
repo_name: z.string().nullish(),
|
||||
repo_url: z.string().nullish(),
|
||||
repo_source_path: z.string().nullish(),
|
||||
directory: z.string().nullish(),
|
||||
server_name: z.string().nullish(),
|
||||
})
|
||||
|
||||
type ScheduleRunWithContextRow = z.infer<typeof ScheduleRunWithContextRowSchema>
|
||||
|
||||
function rowToScheduleRunWithContext(row: ScheduleRunWithContextRow): ScheduleRunWithContext {
|
||||
return {
|
||||
@@ -846,7 +903,11 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
|
||||
|
||||
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
|
||||
const stmt = db.prepare(`
|
||||
params.push(limit, offset)
|
||||
const rows = selectRows(
|
||||
db,
|
||||
ScheduleRunWithContextRowSchema,
|
||||
`
|
||||
SELECT
|
||||
sr.id, sr.job_id, sr.repo_id, sr.server_id, sr.trigger_source, sr.status,
|
||||
sr.started_at, sr.finished_at, sr.created_at,
|
||||
@@ -863,10 +924,9 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
|
||||
${whereClause}
|
||||
ORDER BY sr.started_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`)
|
||||
|
||||
params.push(limit, offset)
|
||||
const rows = stmt.all(...params) as ScheduleRunWithContextRow[]
|
||||
`,
|
||||
...params,
|
||||
)
|
||||
return rows.map(rowToScheduleRunWithContext)
|
||||
}
|
||||
|
||||
@@ -882,12 +942,7 @@ function normalizeReportLine(rawLine: string): string {
|
||||
.trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces a finished run's markdown report to a single short, plain-text line
|
||||
* suitable for a notification or list preview, preferring the first heading
|
||||
* over any conversational preamble.
|
||||
*/
|
||||
export function extractReportPreview(text: string | null): string | null {
|
||||
export function extractReportPreview(text: string | null | undefined): string | null {
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
@@ -911,12 +966,15 @@ export interface ScheduleRunWithUnreadPreview extends ScheduleRunWithContext {
|
||||
preview: string | null
|
||||
}
|
||||
|
||||
interface UnreadScheduleRunRow extends ScheduleRunWithContextRow {
|
||||
response_head: string | null
|
||||
}
|
||||
const UnreadScheduleRunRowSchema = ScheduleRunWithContextRowSchema.extend({
|
||||
response_head: z.string().nullish(),
|
||||
})
|
||||
|
||||
export function listUnreadScheduleRuns(db: Database, limit: number = 20): ScheduleRunWithUnreadPreview[] {
|
||||
const stmt = db.prepare(`
|
||||
const rows = selectRows(
|
||||
db,
|
||||
UnreadScheduleRunRowSchema,
|
||||
`
|
||||
SELECT
|
||||
sr.id, sr.job_id, sr.repo_id, sr.server_id, sr.trigger_source, sr.status,
|
||||
sr.started_at, sr.finished_at, sr.created_at,
|
||||
@@ -933,24 +991,33 @@ export function listUnreadScheduleRuns(db: Database, limit: number = 20): Schedu
|
||||
WHERE sr.status IN ('completed', 'failed') AND sr.viewed_at IS NULL
|
||||
ORDER BY (sr.status = 'failed') DESC, sr.finished_at DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
const rows = stmt.all(limit) as UnreadScheduleRunRow[]
|
||||
`,
|
||||
limit,
|
||||
)
|
||||
return rows.map((row) => ({
|
||||
...rowToScheduleRunWithContext(row),
|
||||
preview: extractReportPreview(row.status === 'failed' ? row.error_text : row.response_head),
|
||||
}))
|
||||
}
|
||||
|
||||
export function countUnreadScheduleRuns(db: Database): { total: number; failed: number } {
|
||||
const stmt = db.prepare(`
|
||||
export interface UnreadScheduleRunCount {
|
||||
total: number
|
||||
failed: number
|
||||
}
|
||||
|
||||
export function countUnreadScheduleRuns(db: Database): UnreadScheduleRunCount {
|
||||
const row = selectRow(
|
||||
db,
|
||||
UnreadScheduleRunCountRowSchema,
|
||||
`
|
||||
SELECT
|
||||
COUNT(*) AS total,
|
||||
COALESCE(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END), 0) AS failed
|
||||
FROM schedule_runs
|
||||
WHERE status IN ('completed', 'failed') AND viewed_at IS NULL
|
||||
`)
|
||||
const row = stmt.get() as { total: number; failed: number }
|
||||
return { total: Number(row.total), failed: Number(row.failed) }
|
||||
`,
|
||||
)
|
||||
return { total: Number(row?.total ?? 0), failed: Number(row?.failed ?? 0) }
|
||||
}
|
||||
|
||||
export function markScheduleRunViewed(db: Database, runId: number): boolean {
|
||||
|
||||
@@ -1,7 +1 @@
|
||||
/**
|
||||
* Repo scope stored in place of a NULL `repo_id` for global secrets, so the unique scope index
|
||||
* and its conflict target treat every global entry as one scope while repository scopes keep
|
||||
* their own. Real repo ids are `0` (the Assistant repository) or positive, so a negative
|
||||
* sentinel can never collide with one.
|
||||
*/
|
||||
export const GLOBAL_SECRETS_SCOPE_ID = -1
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { decryptSecret, encryptSecret } from '../utils/crypto'
|
||||
import { logger } from '../utils/logger'
|
||||
import { selectRow } from './rows'
|
||||
|
||||
const SecretValueRowSchema = z.object({ value: z.string() })
|
||||
|
||||
export function readEncryptedSecret(db: Database, key: string): string | null {
|
||||
const row = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get(key) as { value: string } | undefined
|
||||
const row = selectRow(db, SecretValueRowSchema, 'SELECT value FROM app_secrets WHERE key = ?', key)
|
||||
if (!row) return null
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, type SessionPermissionMode } from '@opencode-manager/shared/schemas'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, SessionPermissionModeSchema, type SessionPermissionMode } from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { selectRow } from './rows'
|
||||
|
||||
const SessionPermissionModeRowSchema = z.object({ mode: SessionPermissionModeSchema })
|
||||
|
||||
export function ensureSessionPermissionModesTable(db: Database): void {
|
||||
db.run(`
|
||||
@@ -18,9 +22,13 @@ export function getSessionPermissionMode(
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): SessionPermissionMode | null {
|
||||
const row = db
|
||||
.prepare('SELECT mode FROM session_permission_modes WHERE server_id = ? AND session_id = ?')
|
||||
.get(serverId, sessionId) as { mode: SessionPermissionMode } | undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
SessionPermissionModeRowSchema,
|
||||
'SELECT mode FROM session_permission_modes WHERE server_id = ? AND session_id = ?',
|
||||
serverId,
|
||||
sessionId,
|
||||
)
|
||||
return row ? row.mode : null
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from './migration-runner'
|
||||
import { allMigrations } from './migrations'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { createTestDatabase } from '../../test/helpers/test-database'
|
||||
import { selectRow } from './rows'
|
||||
import { listSessionPins, setSessionPin, ensureSessionPinsTable } from './session-pins'
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
const TableNameRowSchema = z.object({ name: z.string() })
|
||||
|
||||
describe('session-pins', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
db = createTestDatabase()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
db.close()
|
||||
})
|
||||
|
||||
describe('listSessionPins', () => {
|
||||
@@ -32,13 +34,13 @@ describe('session-pins', () => {
|
||||
expect(pins[0]!.pinnedAt).toEqual(expect.any(Number))
|
||||
})
|
||||
|
||||
it('pinning the same (sessionId, directory) twice does not create a duplicate', async () => {
|
||||
it('pinning the same (sessionId, directory) twice does not create a duplicate', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
|
||||
setSessionPin(db, 'ses_1', '/w/a', true)
|
||||
const first = listSessionPins(db)
|
||||
const firstPinnedAt = first[0]!.pinnedAt
|
||||
const firstPinnedAt = listSessionPins(db)[0]!.pinnedAt
|
||||
|
||||
// Delay to guarantee a different pinnedAt timestamp
|
||||
await new Promise(r => setTimeout(r, 5))
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:01.000Z'))
|
||||
const second = setSessionPin(db, 'ses_1', '/w/a', true)
|
||||
expect(second).toHaveLength(1)
|
||||
expect(second[0]!.pinnedAt).toBeGreaterThan(firstPinnedAt)
|
||||
@@ -66,12 +68,13 @@ describe('session-pins', () => {
|
||||
db.run('DROP TABLE session_pins')
|
||||
|
||||
ensureSessionPinsTable(db)
|
||||
const table = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_pins'")
|
||||
.get() as { name: string } | undefined
|
||||
const table = selectRow(
|
||||
db,
|
||||
TableNameRowSchema,
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_pins'",
|
||||
)
|
||||
|
||||
expect(table).toBeTruthy()
|
||||
expect(table!.name).toBe('session_pins')
|
||||
expect(table?.name).toBe('session_pins')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,12 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { selectRows } from './rows'
|
||||
|
||||
const SessionPinRowSchema = z.object({
|
||||
session_id: z.string(),
|
||||
directory: z.string(),
|
||||
pinned_at: z.number(),
|
||||
})
|
||||
|
||||
export interface SessionPinRecord {
|
||||
sessionId: string
|
||||
@@ -18,9 +26,11 @@ export function ensureSessionPinsTable(db: Database): void {
|
||||
}
|
||||
|
||||
export function listSessionPins(db: Database): SessionPinRecord[] {
|
||||
const rows = db
|
||||
.prepare('SELECT session_id, directory, pinned_at FROM session_pins ORDER BY pinned_at DESC')
|
||||
.all() as { session_id: string; directory: string; pinned_at: number }[]
|
||||
const rows = selectRows(
|
||||
db,
|
||||
SessionPinRowSchema,
|
||||
'SELECT session_id, directory, pinned_at FROM session_pins ORDER BY pinned_at DESC',
|
||||
)
|
||||
return rows.map(r => ({ sessionId: r.session_id, directory: r.directory, pinnedAt: r.pinned_at }))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { SessionSandboxResources, SessionSandboxSource } from '@opencode-manager/shared/schemas'
|
||||
import { SessionSandboxSourceSchema, type SessionSandboxResources, type SessionSandboxSource } from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { selectRow } from './rows'
|
||||
|
||||
export interface SessionSandboxModeRow {
|
||||
sandboxed: boolean
|
||||
@@ -8,13 +10,13 @@ export interface SessionSandboxModeRow {
|
||||
resources: SessionSandboxResources | null
|
||||
}
|
||||
|
||||
interface SessionSandboxModeRawRow {
|
||||
sandboxed: number
|
||||
source: SessionSandboxSource
|
||||
toggled_at: number
|
||||
cpus: number | null
|
||||
memory_mib: number | null
|
||||
}
|
||||
const SessionSandboxModeRawRowSchema = z.object({
|
||||
sandboxed: z.number(),
|
||||
source: SessionSandboxSourceSchema,
|
||||
toggled_at: z.number(),
|
||||
cpus: z.number().nullable(),
|
||||
memory_mib: z.number().nullable(),
|
||||
})
|
||||
|
||||
export function ensureSessionSandboxModesTable(db: Database): void {
|
||||
db.run(`
|
||||
@@ -31,9 +33,12 @@ export function ensureSessionSandboxModesTable(db: Database): void {
|
||||
}
|
||||
|
||||
export function getSessionSandboxMode(db: Database, sessionId: string): SessionSandboxModeRow | null {
|
||||
const row = db
|
||||
.prepare('SELECT sandboxed, source, toggled_at, cpus, memory_mib FROM session_sandbox_modes WHERE session_id = ?')
|
||||
.get(sessionId) as SessionSandboxModeRawRow | undefined
|
||||
const row = selectRow(
|
||||
db,
|
||||
SessionSandboxModeRawRowSchema,
|
||||
'SELECT sandboxed, source, toggled_at, cpus, memory_mib FROM session_sandbox_modes WHERE session_id = ?',
|
||||
sessionId,
|
||||
)
|
||||
if (!row) return null
|
||||
return {
|
||||
sandboxed: row.sandboxed === 1,
|
||||
|
||||
+9
-547
@@ -1,544 +1,21 @@
|
||||
import { serve } from '@hono/node-server'
|
||||
import { createNodeWebSocket } from '@hono/node-ws'
|
||||
import { Hono } from 'hono'
|
||||
import { cors } from 'hono/cors'
|
||||
import { serveStatic } from '@hono/node-server/serve-static'
|
||||
import { readFile } from 'fs/promises'
|
||||
import { initializeDatabase } from './db/schema'
|
||||
import { createRepoRoutes } from './routes/repos'
|
||||
import { createRepoTerminalSocketRoutes } from './routes/repo-terminal-socket'
|
||||
import { createIPCServer, type IPCServer } from './ipc/ipcServer'
|
||||
import { GitAuthService } from './services/git-auth'
|
||||
import { createSettingsRoutes } from './routes/settings'
|
||||
import { createDevicePairingRoutes } from './routes/device-pairing'
|
||||
import { createHealthRoutes } from './routes/health'
|
||||
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts';
|
||||
import { createSTTRoutes } from './routes/stt'
|
||||
import { createFileRoutes } from './routes/files'
|
||||
import { createFilesystemRoutes } from './routes/filesystem'
|
||||
import { createScheduleRoutes, createServerScheduleRoutes } from './routes/schedules'
|
||||
|
||||
async function getAppVersion(): Promise<string> {
|
||||
try {
|
||||
const packageUrl = new URL('../../package.json', import.meta.url)
|
||||
const packageJsonRaw = await readFile(packageUrl, 'utf-8')
|
||||
const packageJson = JSON.parse(packageJsonRaw) as { version?: string }
|
||||
return packageJson.version ?? 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
import { createProvidersRoutes } from './routes/providers'
|
||||
import { createOAuthRoutes } from './routes/oauth'
|
||||
import { createSSERoutes } from './routes/sse'
|
||||
import { createSSHRoutes } from './routes/ssh'
|
||||
import { createNotificationRoutes } from './routes/notifications'
|
||||
import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy'
|
||||
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
|
||||
import { createAuth } from './auth'
|
||||
import { createAuthMiddleware } from './auth/middleware'
|
||||
import { createPromptTemplateRoutes } from './routes/prompt-templates'
|
||||
import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createSessionPermissionModeRoutes } from './routes/session-permission-modes'
|
||||
import { createSessionSandboxRoutes } from './routes/session-sandbox'
|
||||
import { createMultiRunRoutes } from './routes/multi-runs'
|
||||
import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
|
||||
import { getChangeWalkthroughByWalkthroughSession } from './db/change-walkthroughs'
|
||||
import { createLogRoutes } from './routes/logs'
|
||||
import { createPreviewRoutes, createPreviewAvailability } from './routes/preview'
|
||||
import { createGlobalSecretRoutes } from './routes/secrets'
|
||||
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from './routes/opencode-auth-proxy'
|
||||
import { createOpenCodeServerProxyRoutes } from './routes/opencode-server-proxy'
|
||||
import { createOpenCodeServerRoutes } from './routes/opencode-servers'
|
||||
import {
|
||||
createOpenCodeServerTerminalRoutes,
|
||||
createOpenCodeServerTerminalSocketRoutes,
|
||||
} from './routes/opencode-server-terminals'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { RemoteServerEventHub } from './services/remote-server-events'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists } from './services/file-operations'
|
||||
import { SettingsService } from './services/settings'
|
||||
import { RemoteAccessHeadersService } from './services/remote-access-headers'
|
||||
import { SessionPermissionModeService } from './services/session-permission-modes'
|
||||
import { SessionSandboxService } from './services/session-sandbox'
|
||||
import { SessionAncestry } from './services/session-ancestry'
|
||||
import { GoalOutcomeTracker } from './services/goal-outcomes'
|
||||
import { MultiRunService } from './services/multi-runs'
|
||||
import { ChangeWalkthroughService } from './services/change-walkthroughs'
|
||||
import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { createOpenCodeClient } from './services/opencode/client'
|
||||
import { OpenCodeServerRegistry } from './services/opencode-server-registry'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './services/opencode/upstream'
|
||||
import { NotificationService } from './services/notification'
|
||||
import { ScheduleRunner, ScheduleService } from './services/schedules'
|
||||
import { CredentialProvider } from './services/credential-provider'
|
||||
import { TerminalService } from './services/terminal'
|
||||
import { ProjectConfigService } from './services/project-config'
|
||||
import { SecretsService } from './services/secrets'
|
||||
import { RepoEnvService } from './services/repo-env'
|
||||
import { RepoWorkspaceService } from './services/repo-workspace'
|
||||
import { createGitService } from './services/git/GitService'
|
||||
import { ScheduleWorktreeManager } from './services/schedule-worktree'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
import { installAssistantWorkspace, convertAssistantOpenCodeConfigToV2 } from './services/assistant-mode'
|
||||
import { detectSandboxCapability } from './services/sandbox/capability'
|
||||
import { SandboxRuntimeService, stopSandboxesOnShutdown } from './services/sandbox/runtime'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { readOpenCodeConfigFile, foldLegacyConfigJsonSource, withOpenCodeConfigLock } from './services/opencode-config-file'
|
||||
import { seedOpenCodeConfigFile } from './services/opencode-config-apply'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createBackendApp, startPreviewGateway } from './backend-app'
|
||||
import { logger } from './utils/logger'
|
||||
import {
|
||||
getWorkspacePath,
|
||||
getReposPath,
|
||||
getConfigPath,
|
||||
getAgentsMdPath,
|
||||
getDatabasePath,
|
||||
getTrustedOrigins,
|
||||
ENV
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, NotificationEventType } from '@opencode-manager/shared/schemas'
|
||||
|
||||
|
||||
const { PORT, HOST } = ENV.SERVER
|
||||
const DB_PATH = getDatabasePath()
|
||||
|
||||
const app = new Hono()
|
||||
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app })
|
||||
|
||||
/**
|
||||
* Route prefixes reachable from custom WebViews whose origin is not a
|
||||
* trusted web origin (e.g. "null" for file://). These routes authenticate via
|
||||
* Bearer/CF-Access headers rather than cookies, so any origin may be reflected.
|
||||
*/
|
||||
const REFLECT_ANY_ORIGIN_PREFIXES = ['/api/opencode-proxy/', '/api/internal/']
|
||||
|
||||
app.use('/*', cors({
|
||||
origin: (origin, c) => {
|
||||
if (origin && REFLECT_ANY_ORIGIN_PREFIXES.some(prefix => c.req.path.startsWith(prefix))) {
|
||||
return origin
|
||||
}
|
||||
const trustedOrigins = getTrustedOrigins()
|
||||
if (!origin) return trustedOrigins[0]
|
||||
if (trustedOrigins.includes(origin)) return origin
|
||||
return trustedOrigins[0]
|
||||
},
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
|
||||
allowHeaders: ['Content-Type', 'Authorization', 'CF-Access-Client-Id', 'CF-Access-Client-Secret'],
|
||||
credentials: true,
|
||||
}))
|
||||
|
||||
const db = initializeDatabase(DB_PATH)
|
||||
const auth = createAuth(db)
|
||||
const requireAuth = createAuthMiddleware(auth)
|
||||
const openCodeClient = createOpenCodeClient(
|
||||
() => new SettingsService(db).getOpenCodeServerPassword(),
|
||||
() => opencodeServerManager.getEffectiveServerHost(),
|
||||
)
|
||||
export const opencodeServerRegistry = new OpenCodeServerRegistry(db, openCodeClient)
|
||||
|
||||
import { DEFAULT_AGENTS_MD } from './constants'
|
||||
|
||||
let ipcServer: IPCServer | undefined
|
||||
const gitAuthService = new GitAuthService()
|
||||
const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
|
||||
const secretsService = new SecretsService(db)
|
||||
const repoEnvService = new RepoEnvService(db, projectConfigService, secretsService)
|
||||
const sandboxRuntimeService = new SandboxRuntimeService(db, repoEnvService)
|
||||
let openCodeSupervisor: OpenCodeSupervisor | undefined
|
||||
async function ensureOpenCodeConfigFileExists(): Promise<void> {
|
||||
await withOpenCodeConfigLock(foldLegacyConfigJsonSource)
|
||||
|
||||
const existing = await readOpenCodeConfigFile()
|
||||
if (existing) {
|
||||
if (!existing.isValid) {
|
||||
logger.warn('OpenCode config file has validation issues', existing.validationIssues)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const status = await getOpenCodeImportStatus()
|
||||
if (status.configSourcePath) {
|
||||
logger.info(`Found importable OpenCode config at ${status.configSourcePath}, importing...`)
|
||||
try {
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, status })
|
||||
if (result.configImported) {
|
||||
logger.info(`Imported OpenCode config from ${status.configSourcePath} to workspace`)
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to import OpenCode config from ${status.configSourcePath}`, error)
|
||||
}
|
||||
}
|
||||
|
||||
await seedOpenCodeConfigFile()
|
||||
logger.info('Created minimal seed config')
|
||||
}
|
||||
|
||||
async function ensureHomeStateImported(): Promise<void> {
|
||||
try {
|
||||
const status = await getOpenCodeImportStatus()
|
||||
if (status.workspaceStateExists) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!status.stateSourcePath) {
|
||||
return
|
||||
}
|
||||
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, importConfig: false, status })
|
||||
if (result.stateImported) {
|
||||
logger.info(`Imported OpenCode state from ${status.stateSourcePath}`)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to import OpenCode state, continuing without imported state', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureDefaultAgentsMdExists(): Promise<void> {
|
||||
const agentsMdPath = getAgentsMdPath()
|
||||
const exists = await fileExists(agentsMdPath)
|
||||
|
||||
if (!exists) {
|
||||
await writeFileContent(agentsMdPath, DEFAULT_AGENTS_MD)
|
||||
logger.info(`Created default AGENTS.md at: ${agentsMdPath}`)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (ENV.SERVER.NODE_ENV === 'production' && !ENV.AUTH.SECRET) {
|
||||
logger.error('AUTH_SECRET is required in production mode')
|
||||
logger.error('Generate one with: openssl rand -base64 32')
|
||||
logger.error('Set it as environment variable: AUTH_SECRET=your-secret')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
await ensureDirectoryExists(getWorkspacePath())
|
||||
await ensureDirectoryExists(getReposPath())
|
||||
await ensureDirectoryExists(getConfigPath())
|
||||
logger.info('Workspace directories initialized')
|
||||
|
||||
await cleanupExpiredCache()
|
||||
await sweepStaleUploadSessions()
|
||||
|
||||
await ensureOpenCodeConfigFileExists()
|
||||
await ensureHomeStateImported()
|
||||
await ensureDefaultAgentsMdExists()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
settingsService.initializeLastKnownGoodConfig()
|
||||
|
||||
openCodeSupervisor = new OpenCodeSupervisor(opencodeServerManager, settingsService)
|
||||
|
||||
await migrateGlobalSkills()
|
||||
|
||||
await installAssistantWorkspace({ db })
|
||||
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}`)
|
||||
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
detectSandboxCapability()
|
||||
void sandboxRuntimeService.prepareSandboxOnBoot().catch((error) => {
|
||||
logger.warn('Sandbox preparation failed:', error)
|
||||
})
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
} else {
|
||||
logger.warn(`OpenCode server unavailable after startup recovery: ${openCodeStatus.lastError ?? openCodeStatus.state}`)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize workspace:', error)
|
||||
}
|
||||
|
||||
const terminalService = new TerminalService(
|
||||
{
|
||||
client: openCodeClient,
|
||||
baseUrl: () => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
includeLocalEnv: true,
|
||||
},
|
||||
new CredentialProvider(db),
|
||||
repoEnvService,
|
||||
)
|
||||
const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
const connection = opencodeServerRegistry.getConnection(serverId)
|
||||
return terminalService.forTarget({
|
||||
client: opencodeServerRegistry.getClient(serverId),
|
||||
baseUrl: () => connection.baseUrl,
|
||||
includeLocalEnv: false,
|
||||
})
|
||||
}
|
||||
const sessionSettingsService = new SettingsService(db)
|
||||
const sessionAncestry = new SessionAncestry((serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const sessionSandboxService = new SessionSandboxService(db, sessionAncestry, sessionSettingsService, {
|
||||
removeSessionSandbox: (rootSessionId) => sandboxRuntimeService.removeSessionSandbox(rootSessionId),
|
||||
})
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry, {
|
||||
sessions: sessionSandboxService,
|
||||
runtime: sandboxRuntimeService,
|
||||
})
|
||||
scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
try {
|
||||
await terminalService.removeAll(directory)
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to remove terminals for schedule worktree ${directory}:`, error)
|
||||
}
|
||||
})
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService)
|
||||
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(db, opencodeServerRegistry)
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(db, opencodeServerRegistry, sessionSettingsService, sessionAncestry)
|
||||
const goalOutcomes = new GoalOutcomeTracker()
|
||||
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService, (serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionSandboxService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session sandbox event handling error:', err)
|
||||
})
|
||||
try {
|
||||
changeWalkthroughService.handleEvent(event)
|
||||
} catch (err) {
|
||||
logger.error('Change walkthrough event handling error:', err)
|
||||
}
|
||||
})
|
||||
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Session permission mode event handling error:', err)
|
||||
})
|
||||
const outcome = goalOutcomes.observe(serverId, directory, event)
|
||||
if (outcome) {
|
||||
void notificationService.notifyGoalOutcome(outcome).catch((error) => {
|
||||
logger.error('Goal outcome notification error:', error)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
notificationService.addEventSuppressor((event, sessionId, serverId) =>
|
||||
sessionPermissionModeService.suppressesPermissionNotification(event, sessionId, serverId),
|
||||
)
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId, serverId) => {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) return false
|
||||
if (!sessionId) return false
|
||||
if (event.type !== NotificationEventType.SESSION_IDLE && event.type !== NotificationEventType.SESSION_FAILED) return false
|
||||
return getChangeWalkthroughByWalkthroughSession(db, sessionId) !== null
|
||||
})
|
||||
|
||||
if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
if (!ENV.VAPID.SUBJECT) {
|
||||
logger.warn('VAPID_SUBJECT is not set — push notifications require a mailto: subject (e.g. mailto:you@example.com)')
|
||||
} else if (!ENV.VAPID.SUBJECT.startsWith('mailto:')) {
|
||||
logger.warn(`VAPID_SUBJECT="${ENV.VAPID.SUBJECT}" does not use mailto: format — iOS/Safari push notifications will fail`)
|
||||
}
|
||||
|
||||
notificationService.configureVapid({
|
||||
publicKey: ENV.VAPID.PUBLIC_KEY,
|
||||
privateKey: ENV.VAPID.PRIVATE_KEY,
|
||||
subject: ENV.VAPID.SUBJECT || 'mailto:push@localhost',
|
||||
})
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
notificationService.handleSSEEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Push notification dispatch error:', err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
sseAggregator.setOpenCodeClient(openCodeClient)
|
||||
sseAggregator.setResyncGate(() => opencodeServerManager.isLifecycleInitialized())
|
||||
opencodeServerManager.onLifecycleInitialized(() => sseAggregator.releasePendingResync())
|
||||
sseAggregator.onServerConnected((serverId) => {
|
||||
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions(serverId).catch((err) => {
|
||||
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, err)
|
||||
})
|
||||
if (serverId === LOCAL_OPENCODE_SERVER_ID) {
|
||||
void convertAssistantOpenCodeConfigToV2(openCodeClient.api).catch((err) => {
|
||||
logger.error('Failed to convert the Assistant OpenCode config to v2:', err)
|
||||
})
|
||||
}
|
||||
})
|
||||
sseAggregator.start()
|
||||
|
||||
const remoteServerEvents = new RemoteServerEventHub(opencodeServerRegistry, sseAggregator)
|
||||
remoteServerEvents.start()
|
||||
|
||||
sseAggregator.setScheduledSessionsResolver(
|
||||
() => scheduleService.getActiveRunSessions(),
|
||||
)
|
||||
|
||||
void scheduleRunnerInstance.start()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
const previewSessionStore = new PreviewSessionStore()
|
||||
const previewAvailability = createPreviewAvailability(false)
|
||||
|
||||
app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth))
|
||||
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, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, multiRunService, changeWalkthroughService, sessionSandboxService, repoEnvService))
|
||||
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService, upgradeWebSocket))
|
||||
|
||||
const protectedApi = new Hono()
|
||||
protectedApi.use('/*', requireAuth)
|
||||
|
||||
protectedApi.route('/repos', createRepoTerminalSocketRoutes(db, gitAuthService, openCodeClient, terminalService, upgradeWebSocket))
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces, secretsService))
|
||||
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/device-pairing', createDevicePairingRoutes({
|
||||
mintPairingCode: (headers) => auth.api.createDevicePairingCode({ headers }),
|
||||
remoteAccessHeaders: new RemoteAccessHeadersService(db),
|
||||
readAllowPrivateNetworkHttp: () =>
|
||||
settingsService.getSettings('default').preferences.devicePairing?.allowPrivateNetworkHttp === true,
|
||||
}))
|
||||
protectedApi.route('/files', createFileRoutes())
|
||||
protectedApi.route('/filesystem', createFilesystemRoutes())
|
||||
protectedApi.route('/providers', createProvidersRoutes(openCodeClient))
|
||||
protectedApi.route('/oauth', createOAuthRoutes(openCodeClient))
|
||||
protectedApi.route('/tts', createTTSRoutes(db))
|
||||
protectedApi.route('/stt', createSTTRoutes(db))
|
||||
protectedApi.route('/sse', createSSERoutes())
|
||||
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/secrets', createGlobalSecretRoutes(secretsService, 'secret'))
|
||||
protectedApi.route('/variables', createGlobalSecretRoutes(secretsService, 'variable'))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalRoutes(resolveServerTerminalService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerRoutes(opencodeServerRegistry, () => remoteServerEvents.getStatuses()))
|
||||
protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService))
|
||||
protectedApi.route('/session-sandbox', createSessionSandboxRoutes(sessionSandboxService))
|
||||
protectedApi.route('/multi-runs', createMultiRunRoutes(multiRunService))
|
||||
protectedApi.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
|
||||
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/logs', createLogRoutes())
|
||||
protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore, isEnabled: previewAvailability.isEnabled }))
|
||||
|
||||
app.route('/api', protectedApi)
|
||||
|
||||
app.route('/api/opencode/servers', createOpenCodeServerProxyRoutes(opencodeServerRegistry, requireAuth))
|
||||
app.route('/api/opencode', createAuthenticatedOpenCodeProxyRoutes(openCodeClient, requireAuth))
|
||||
|
||||
const isProduction = ENV.SERVER.NODE_ENV === 'production'
|
||||
|
||||
if (isProduction) {
|
||||
app.use('/*', async (c, next) => {
|
||||
await next()
|
||||
if (c.req.path === '/sw.js') {
|
||||
c.res.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate')
|
||||
c.res.headers.set('Pragma', 'no-cache')
|
||||
c.res.headers.set('Expires', '0')
|
||||
}
|
||||
})
|
||||
|
||||
app.use('/*', serveStatic({ root: './frontend/dist' }))
|
||||
|
||||
app.get('*', async (c) => {
|
||||
if (c.req.path.startsWith('/api/')) {
|
||||
return c.notFound()
|
||||
}
|
||||
const fs = await import('fs/promises')
|
||||
const path = await import('path')
|
||||
const indexPath = path.join(process.cwd(), 'frontend/dist/index.html')
|
||||
const html = await fs.readFile(indexPath, 'utf-8')
|
||||
return c.html(html)
|
||||
})
|
||||
} else {
|
||||
app.get('/', async (c) => {
|
||||
const version = await getAppVersion()
|
||||
return c.json({
|
||||
name: 'OpenCode WebUI',
|
||||
version,
|
||||
status: 'running',
|
||||
endpoints: {
|
||||
health: '/api/health',
|
||||
repos: '/api/repos',
|
||||
settings: '/api/settings',
|
||||
sessions: '/api/sessions',
|
||||
files: '/api/files',
|
||||
providers: '/api/providers',
|
||||
opencode_proxy: '/api/opencode/*'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
app.get('/api/network-info', async (c) => {
|
||||
const os = await import('os')
|
||||
const interfaces = os.networkInterfaces()
|
||||
const ips = Object.values(interfaces)
|
||||
.flat()
|
||||
.filter(info => info && !info.internal && info.family === 'IPv4')
|
||||
.map(info => info!.address)
|
||||
|
||||
const requestHost = c.req.header('host') || `localhost:${PORT}`
|
||||
const protocol = c.req.header('x-forwarded-proto') || 'http'
|
||||
|
||||
return c.json({
|
||||
host: HOST,
|
||||
port: PORT,
|
||||
requestHost,
|
||||
protocol,
|
||||
availableIps: ips,
|
||||
apiUrls: [
|
||||
`${protocol}://localhost:${PORT}`,
|
||||
...ips.map(ip => `${protocol}://${ip}:${PORT}`)
|
||||
]
|
||||
})
|
||||
})
|
||||
}
|
||||
const backend = createBackendApp()
|
||||
await backend.initialize()
|
||||
|
||||
let isShuttingDown = false
|
||||
|
||||
const shutdown = async (signal: string) => {
|
||||
const shutdown = async (signal: string): Promise<void> => {
|
||||
if (isShuttingDown) return
|
||||
isShuttingDown = true
|
||||
|
||||
logger.info(`${signal} received, shutting down gracefully...`)
|
||||
try {
|
||||
remoteServerEvents.shutdown()
|
||||
logger.info('Remote server event hub stopped')
|
||||
sseAggregator.shutdown()
|
||||
logger.info('SSE Aggregator stopped')
|
||||
if (ipcServer) {
|
||||
await ipcServer.dispose()
|
||||
logger.info('Git IPC server stopped')
|
||||
}
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.stop()
|
||||
}
|
||||
scheduleRunnerInstance?.stop()
|
||||
logger.info('Schedule runner stopped')
|
||||
if (!openCodeSupervisor) {
|
||||
await opencodeServerManager.stop()
|
||||
}
|
||||
logger.info('OpenCode server stopped')
|
||||
} catch (error) {
|
||||
logger.error('Error during shutdown:', error)
|
||||
}
|
||||
try {
|
||||
await stopSandboxesOnShutdown(db)
|
||||
logger.info('Sandbox microVMs stopped')
|
||||
} catch (error) {
|
||||
logger.error('Error stopping sandbox microVMs:', error)
|
||||
}
|
||||
await backend.shutdown()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
@@ -546,30 +23,15 @@ process.on('SIGTERM', () => shutdown('SIGTERM'))
|
||||
process.on('SIGINT', () => shutdown('SIGINT'))
|
||||
|
||||
const server = serve({
|
||||
fetch: app.fetch,
|
||||
fetch: backend.app.fetch,
|
||||
port: PORT,
|
||||
hostname: HOST,
|
||||
})
|
||||
|
||||
injectWebSocket(server)
|
||||
backend.injectWebSocket(server)
|
||||
|
||||
if (ENV.PREVIEW.PORT > 0) {
|
||||
const previewGateway = createPreviewGatewayApp(previewSessionStore)
|
||||
const previewServer = serve({
|
||||
fetch: previewGateway.app.fetch,
|
||||
port: ENV.PREVIEW.PORT,
|
||||
hostname: HOST,
|
||||
})
|
||||
previewServer.on('listening', () => {
|
||||
previewAvailability.markAvailable()
|
||||
logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`)
|
||||
})
|
||||
previewServer.on('error', (error: Error) => {
|
||||
previewAvailability.markUnavailable()
|
||||
const code = (error as NodeJS.ErrnoException).code
|
||||
logger.warn(`Preview gateway failed to listen on port ${ENV.PREVIEW.PORT}${code ? ` (${code})` : ''}; preview disabled`)
|
||||
})
|
||||
previewGateway.injectWebSocket(previewServer)
|
||||
startPreviewGateway({ preview: backend.preview, port: ENV.PREVIEW.PORT, hostname: HOST })
|
||||
}
|
||||
|
||||
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import type { IPCServer, IPCHandler } from './ipcServer'
|
||||
import { z } from 'zod'
|
||||
import type { JsonValue } from '@opencode-manager/shared/utils'
|
||||
import type { IPCServer, IPCHandler, IpcEnvironment } from './ipcServer'
|
||||
import { CredentialProvider } from '../services/credential-provider'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
@@ -12,16 +14,18 @@ interface Credentials {
|
||||
password: string
|
||||
}
|
||||
|
||||
interface AskpassRequest {
|
||||
askpassType: 'https' | 'ssh'
|
||||
argv: string[]
|
||||
cwd?: string
|
||||
repoId?: number
|
||||
}
|
||||
const AskpassRequestSchema = z.object({
|
||||
askpassType: z.enum(['https', 'ssh']),
|
||||
argv: z.array(z.string()),
|
||||
cwd: z.string().optional(),
|
||||
repoId: z.number().optional(),
|
||||
})
|
||||
|
||||
type AskpassRequest = z.infer<typeof AskpassRequestSchema>
|
||||
|
||||
export class AskpassHandler implements IPCHandler {
|
||||
private cache = new Map<string, Credentials>()
|
||||
private env: Record<string, string>
|
||||
private env: IpcEnvironment
|
||||
|
||||
constructor(
|
||||
private ipcServer: IPCServer | undefined,
|
||||
@@ -46,7 +50,8 @@ export class AskpassHandler implements IPCHandler {
|
||||
}
|
||||
}
|
||||
|
||||
async handle(request: AskpassRequest): Promise<string> {
|
||||
async handle(payload: JsonValue): Promise<string> {
|
||||
const request = AskpassRequestSchema.parse(payload)
|
||||
logger.info(`Askpass request received: type=${request.askpassType}, argv=${JSON.stringify(request.argv)}`)
|
||||
if (request.askpassType === 'https') {
|
||||
return this.handleHttpsAskpass(request)
|
||||
@@ -93,7 +98,7 @@ export class AskpassHandler implements IPCHandler {
|
||||
return ''
|
||||
}
|
||||
|
||||
getEnv(): Record<string, string> {
|
||||
getEnv(): IpcEnvironment {
|
||||
return {
|
||||
...this.env,
|
||||
...(this.ipcServer?.getEnv() || {}),
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as crypto from 'crypto'
|
||||
import * as path from 'path'
|
||||
import * as os from 'os'
|
||||
import * as fs from 'fs/promises'
|
||||
import { JsonValueSchema, type JsonValue } from '@opencode-manager/shared/utils'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
function getIPCHandlePath(id: string): string {
|
||||
@@ -16,7 +17,11 @@ function getIPCHandlePath(id: string): string {
|
||||
}
|
||||
|
||||
export interface IPCHandler {
|
||||
handle(request: unknown): Promise<unknown>
|
||||
handle(request: JsonValue): Promise<JsonValue | void>
|
||||
}
|
||||
|
||||
export interface IpcEnvironment {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
export class IPCServer {
|
||||
@@ -37,7 +42,7 @@ export class IPCServer {
|
||||
return this.handlers.get(`/${name}`)
|
||||
}
|
||||
|
||||
getEnv(): Record<string, string> {
|
||||
getEnv(): IpcEnvironment {
|
||||
return { VSCODE_GIT_IPC_HANDLE: this.ipcHandlePath }
|
||||
}
|
||||
|
||||
@@ -63,7 +68,7 @@ export class IPCServer {
|
||||
res.end(JSON.stringify({ error: 'Empty request body' }))
|
||||
return
|
||||
}
|
||||
const request = JSON.parse(body)
|
||||
const request = JsonValueSchema.parse(JSON.parse(body))
|
||||
logger.info(`IPC calling handler for ${req.url} with:`, request)
|
||||
const result = await handler.handle(request)
|
||||
logger.info(`IPC handler result for ${req.url}:`, result)
|
||||
@@ -101,7 +106,6 @@ export async function createIPCServer(context?: string): Promise<IPCServer> {
|
||||
try {
|
||||
await fs.unlink(ipcHandlePath)
|
||||
} catch {
|
||||
/* socket file may not exist */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,35 @@
|
||||
import * as path from 'path'
|
||||
import { z } from 'zod'
|
||||
import { type JsonValue } from '@opencode-manager/shared/utils'
|
||||
import * as fs from 'fs/promises'
|
||||
import * as crypto from 'crypto'
|
||||
import type { IPCHandler } from './ipcServer'
|
||||
import type { IPCHandler, IpcEnvironment } from './ipcServer'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { selectRow, selectRows } from '../db/rows'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { broadcastSSHHostKeyRequest } from '../services/sse-aggregator'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { parseSSHHost, normalizeHostPort } from '../utils/ssh-key-manager'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
|
||||
const SSHHostKeyResponseSchema = z.object({
|
||||
requestId: z.string(),
|
||||
response: z.enum(['accept', 'reject']),
|
||||
})
|
||||
|
||||
const TrustedHostPublicKeyRowSchema = z.object({
|
||||
public_key: z.string(),
|
||||
})
|
||||
|
||||
const TrustedHostKeySchema = z.object({
|
||||
key_type: z.string(),
|
||||
public_key: z.string(),
|
||||
})
|
||||
|
||||
type TrustedHostKey = z.infer<typeof TrustedHostKeySchema>
|
||||
|
||||
interface SSHHostKeyRequest {
|
||||
id: string
|
||||
host: string
|
||||
@@ -92,8 +112,8 @@ export class SSHHostKeyHandler implements IPCHandler {
|
||||
|
||||
this.pendingRequests.set(requestId, { request: hostKeyRequest, resolve, timeout })
|
||||
})
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to fetch host key for ${hostPort}, rejecting connection:`, (error as Error).message)
|
||||
} catch (cause) {
|
||||
logger.warn(`Failed to fetch host key for ${hostPort}, rejecting connection:`, getErrorMessage(cause))
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -119,8 +139,8 @@ export class SSHHostKeyHandler implements IPCHandler {
|
||||
const result = await executeCommand(
|
||||
['ssh-keyscan', '-t', 'ed25519,rsa,ecdsa', ...portArgs, host],
|
||||
{ silent: true, ignoreExitCode: true }
|
||||
) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
const output = typeof result === 'string' ? result : result.stdout
|
||||
)
|
||||
const output = result.stdout
|
||||
const bracketedHost = port && port !== '22' ? `[${host}]:${port}` : host
|
||||
const lines = output.trim().split('\n')
|
||||
for (const line of lines) {
|
||||
@@ -132,9 +152,8 @@ export class SSHHostKeyHandler implements IPCHandler {
|
||||
throw new Error('No valid host keys found')
|
||||
}
|
||||
|
||||
async handle(request: unknown): Promise<unknown> {
|
||||
const response = request as { requestId: string; response: 'accept' | 'reject' }
|
||||
return await this.respond(response)
|
||||
async handle(payload: JsonValue): Promise<JsonValue> {
|
||||
return await this.respond(SSHHostKeyResponseSchema.parse(payload))
|
||||
}
|
||||
|
||||
async respond(response: { requestId: string; response: 'accept' | 'reject' }): Promise<{ success: boolean; error?: string }> {
|
||||
@@ -169,14 +188,7 @@ export class SSHHostKeyHandler implements IPCHandler {
|
||||
|
||||
private async loadFromDatabaseToKnownHosts(): Promise<void> {
|
||||
try {
|
||||
const hosts = this.database.prepare('SELECT * FROM trusted_ssh_hosts').all() as Array<{
|
||||
id: number
|
||||
host: string
|
||||
key_type: string
|
||||
public_key: string
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}>
|
||||
const hosts = selectRows(this.database, TrustedHostPublicKeyRowSchema, 'SELECT * FROM trusted_ssh_hosts')
|
||||
|
||||
const entries = hosts.map(h => h.public_key).join('\n')
|
||||
await fs.writeFile(this.knownHostsPath, entries + '\n', { mode: 0o600 })
|
||||
@@ -186,13 +198,15 @@ export class SSHHostKeyHandler implements IPCHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private getTrustedHost(host: string): { key_type: string; public_key: string } | null {
|
||||
private getTrustedHost(host: string): TrustedHostKey | null {
|
||||
try {
|
||||
const result = this.database.prepare('SELECT key_type, public_key FROM trusted_ssh_hosts WHERE host = ?').get(host) as {
|
||||
key_type: string
|
||||
public_key: string
|
||||
} | undefined
|
||||
return result || null
|
||||
const result = selectRow(
|
||||
this.database,
|
||||
TrustedHostKeySchema,
|
||||
'SELECT key_type, public_key FROM trusted_ssh_hosts WHERE host = ?',
|
||||
host,
|
||||
)
|
||||
return result ?? null
|
||||
} catch (error) {
|
||||
logger.error(`Failed to get trusted host ${host}:`, error)
|
||||
return null
|
||||
@@ -229,7 +243,7 @@ export class SSHHostKeyHandler implements IPCHandler {
|
||||
return this.knownHostsPath
|
||||
}
|
||||
|
||||
getEnv(): Record<string, string> {
|
||||
getEnv(): IpcEnvironment {
|
||||
return {
|
||||
KNOWN_HOSTS_PATH: this.knownHostsPath
|
||||
}
|
||||
|
||||
+23
-12
@@ -1,12 +1,23 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { isAdminConfigured, type AuthInstance } from '../auth'
|
||||
import { isAdminConfigured, type AuthEnv, type AuthInstance, type Session } from '../auth'
|
||||
import { applyClientIpHeaders, resolveSocketIp } from '../auth/client-ip'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { logger } from '../utils/logger'
|
||||
import { deletePushSubscriptionsForSessions } from '../db/push-subscriptions'
|
||||
|
||||
export function createAuthRoutes(auth: AuthInstance): Hono {
|
||||
export type AuthRouteHandler = Pick<AuthInstance, 'handler'>
|
||||
|
||||
export interface AuthSessionReader {
|
||||
getSession(context: { headers: Headers }): Promise<Session | null>
|
||||
}
|
||||
|
||||
export interface AuthInfoProvider {
|
||||
api: AuthSessionReader
|
||||
$context: AuthInstance['$context']
|
||||
}
|
||||
|
||||
export function createAuthRoutes(auth: AuthRouteHandler): Hono {
|
||||
const app = new Hono()
|
||||
|
||||
app.all('/*', (c) => {
|
||||
@@ -17,11 +28,11 @@ export function createAuthRoutes(auth: AuthInstance): Hono {
|
||||
return app
|
||||
}
|
||||
|
||||
export async function syncAdminFromEnv(auth: AuthInstance, db: Database): Promise<void> {
|
||||
if (!isAdminConfigured()) return
|
||||
export async function syncAdminFromEnv(auth: AuthInstance, db: Database, env: AuthEnv = ENV.AUTH): Promise<void> {
|
||||
if (!isAdminConfigured(env)) return
|
||||
|
||||
const adminEmail = ENV.AUTH.ADMIN_EMAIL!
|
||||
const adminPassword = ENV.AUTH.ADMIN_PASSWORD!
|
||||
const adminEmail = env.ADMIN_EMAIL ?? ''
|
||||
const adminPassword = env.ADMIN_PASSWORD ?? ''
|
||||
|
||||
const ctx = await auth.$context
|
||||
const existingAdmin = await ctx.adapter.findOne<{ id: string }>({
|
||||
@@ -30,7 +41,7 @@ export async function syncAdminFromEnv(auth: AuthInstance, db: Database): Promis
|
||||
})
|
||||
|
||||
if (existingAdmin) {
|
||||
if (ENV.AUTH.ADMIN_PASSWORD_RESET) {
|
||||
if (env.ADMIN_PASSWORD_RESET) {
|
||||
const credentialAccount = (await ctx.internalAdapter.findAccounts(existingAdmin.id))
|
||||
.find((account) => account.providerId === 'credential')
|
||||
|
||||
@@ -65,26 +76,26 @@ export async function syncAdminFromEnv(auth: AuthInstance, db: Database): Promis
|
||||
}
|
||||
}
|
||||
|
||||
export function createAuthInfoRoutes(auth: AuthInstance) {
|
||||
export function createAuthInfoRoutes(auth: AuthInfoProvider, env: AuthEnv = ENV.AUTH) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/config', async (c) => {
|
||||
const enabledProviders: string[] = ['credentials']
|
||||
|
||||
if (ENV.AUTH.GITHUB_CLIENT_ID && ENV.AUTH.GITHUB_CLIENT_SECRET) {
|
||||
if (env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET) {
|
||||
enabledProviders.push('github')
|
||||
}
|
||||
if (ENV.AUTH.GOOGLE_CLIENT_ID && ENV.AUTH.GOOGLE_CLIENT_SECRET) {
|
||||
if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
|
||||
enabledProviders.push('google')
|
||||
}
|
||||
if (ENV.AUTH.DISCORD_CLIENT_ID && ENV.AUTH.DISCORD_CLIENT_SECRET) {
|
||||
if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
|
||||
enabledProviders.push('discord')
|
||||
}
|
||||
|
||||
enabledProviders.push('passkey')
|
||||
|
||||
const userCount = await (await auth.$context).adapter.count({ model: 'user' })
|
||||
const adminConfigured = isAdminConfigured()
|
||||
const adminConfigured = isAdminConfigured(env)
|
||||
|
||||
return c.json({
|
||||
enabledProviders,
|
||||
|
||||
@@ -9,7 +9,17 @@ import type { ChangeWalkthroughService } from '../services/change-walkthroughs'
|
||||
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
|
||||
export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService) {
|
||||
export type ChangeWalkthroughRoutesService = Pick<ChangeWalkthroughService,
|
||||
| 'cancelGeneration'
|
||||
| 'getState'
|
||||
| 'listHelperSessionIds'
|
||||
| 'publishFromWalkthroughSession'
|
||||
| 'readChangesForWalkthroughSession'
|
||||
| 'refine'
|
||||
| 'startGeneration'
|
||||
>
|
||||
|
||||
export function createChangeWalkthroughRoutes(service: ChangeWalkthroughRoutesService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/helper-sessions', (c) => {
|
||||
|
||||
@@ -31,7 +31,6 @@ interface DevicePairingRouteDeps {
|
||||
isDevelopment?: () => boolean
|
||||
}
|
||||
|
||||
/** Creates the routes that mint device pairing links for the Manager origin. */
|
||||
export function createDevicePairingRoutes(deps: DevicePairingRouteDeps) {
|
||||
const app = new Hono()
|
||||
const resolveTrustedOrigins = deps.resolveTrustedOrigins ?? getTrustedOrigins
|
||||
|
||||
+56
-30
@@ -1,5 +1,6 @@
|
||||
import { Hono, type Context } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import { Readable } from 'node:stream'
|
||||
import { z } from 'zod'
|
||||
import * as fileService from '../services/files'
|
||||
import * as archiveService from '../services/archive'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -36,7 +37,32 @@ function matchesIfNoneMatch(ifNoneMatch: string | undefined, etag: string): bool
|
||||
return values.includes('*') || values.includes(etag)
|
||||
}
|
||||
|
||||
export function createFileRoutes() {
|
||||
export type FileRoutesService = Pick<
|
||||
typeof fileService,
|
||||
| 'getFile'
|
||||
| 'getRawFileContent'
|
||||
| 'getRawFileMetadata'
|
||||
| 'getFileRange'
|
||||
| 'uploadFile'
|
||||
| 'createFileOrFolder'
|
||||
| 'deleteFileOrFolder'
|
||||
| 'renameOrMoveFile'
|
||||
| 'applyFilePatches'
|
||||
>
|
||||
|
||||
export type FileArchiveRoutesService = Pick<
|
||||
typeof archiveService,
|
||||
| 'createDirectoryArchive'
|
||||
| 'getArchiveSize'
|
||||
| 'getArchiveStream'
|
||||
| 'deleteArchive'
|
||||
| 'getIgnoredPathsList'
|
||||
>
|
||||
|
||||
export function createFileRoutes(
|
||||
files: FileRoutesService = fileService,
|
||||
archives: FileArchiveRoutesService = archiveService,
|
||||
) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('*', async (c) => {
|
||||
@@ -61,22 +87,22 @@ export function createFileRoutes() {
|
||||
includePaths
|
||||
}
|
||||
|
||||
const archivePath = await archiveService.createDirectoryArchive(userPath, undefined, options)
|
||||
const archiveSize = await archiveService.getArchiveSize(archivePath)
|
||||
const archiveStream = archiveService.getArchiveStream(archivePath)
|
||||
const archivePath = await archives.createDirectoryArchive(userPath, undefined, options)
|
||||
const archiveSize = await archives.getArchiveSize(archivePath)
|
||||
const archiveStream = archives.getArchiveStream(archivePath)
|
||||
const dirName = userPath.split('/').pop() || 'download'
|
||||
|
||||
logger.info(`ZIP archive created: ${archivePath} (${archiveSize} bytes)`)
|
||||
|
||||
archiveStream.on('end', () => {
|
||||
archiveService.deleteArchive(archivePath)
|
||||
archives.deleteArchive(archivePath)
|
||||
})
|
||||
|
||||
archiveStream.on('error', () => {
|
||||
archiveService.deleteArchive(archivePath)
|
||||
archives.deleteArchive(archivePath)
|
||||
})
|
||||
|
||||
return new Response(archiveStream as unknown as ReadableStream, {
|
||||
return new Response(Readable.toWeb(archiveStream), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/zip',
|
||||
@@ -86,7 +112,7 @@ export function createFileRoutes() {
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create directory archive:', error)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to create archive' }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to create archive' }, getStatusCode(error))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,11 +124,11 @@ export function createFileRoutes() {
|
||||
}
|
||||
|
||||
try {
|
||||
const ignoredPaths = await archiveService.getIgnoredPathsList(userPath)
|
||||
const ignoredPaths = await archives.getIgnoredPathsList(userPath)
|
||||
return c.json({ ignoredPaths })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get ignored paths:', error)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to get ignored paths' }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to get ignored paths' }, getStatusCode(error))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,15 +147,15 @@ export function createFileRoutes() {
|
||||
return c.json({ error: 'Invalid line range parameters' }, 400)
|
||||
}
|
||||
|
||||
const result = await fileService.getFileRange(userPath, startLine, endLine)
|
||||
const result = await files.getFileRange(userPath, startLine, endLine)
|
||||
return c.json(result)
|
||||
}
|
||||
|
||||
if (raw) {
|
||||
const metadata = await fileService.getRawFileMetadata(userPath)
|
||||
const metadata = await files.getRawFileMetadata(userPath)
|
||||
|
||||
if (!metadata) {
|
||||
const result = await fileService.getFile(userPath)
|
||||
const result = await files.getFile(userPath)
|
||||
return c.json(result)
|
||||
}
|
||||
|
||||
@@ -149,7 +175,7 @@ export function createFileRoutes() {
|
||||
})
|
||||
}
|
||||
|
||||
const content = await fileService.getRawFileContent(userPath)
|
||||
const content = await files.getRawFileContent(userPath)
|
||||
return new Response(content, {
|
||||
headers: {
|
||||
'Content-Type': metadata.mimeType,
|
||||
@@ -163,7 +189,7 @@ export function createFileRoutes() {
|
||||
})
|
||||
}
|
||||
|
||||
const result = await fileService.getFile(userPath)
|
||||
const result = await files.getFile(userPath)
|
||||
|
||||
if (download && !result.isDirectory) {
|
||||
const content = result.content ? Buffer.from(result.content, 'base64') : Buffer.alloc(0)
|
||||
@@ -179,7 +205,7 @@ export function createFileRoutes() {
|
||||
return c.json(result)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get file:', error)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to get file' }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to get file' }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -188,17 +214,17 @@ export function createFileRoutes() {
|
||||
const path = getFilePathFromRequest(c, c.req.path.replace(/^\/api\/files\//, '') || '')
|
||||
const body = await c.req.parseBody()
|
||||
|
||||
const file = body.file as File
|
||||
if (!file) {
|
||||
const file = body.file
|
||||
if (!(file instanceof File)) {
|
||||
return c.json({ error: 'No file provided' }, 400)
|
||||
}
|
||||
|
||||
const relativePath = body.relativePath as string | undefined
|
||||
const result = await fileService.uploadFile(path, file, relativePath)
|
||||
|
||||
const relativePath = z.string().safeParse(body.relativePath)
|
||||
const result = await files.uploadFile(path, file, relativePath.success ? relativePath.data : undefined)
|
||||
return c.json(result)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to upload file:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -207,11 +233,11 @@ export function createFileRoutes() {
|
||||
const path = getFilePathFromRequest(c, c.req.path.replace(/^\/api\/files\//, '') || '')
|
||||
const body = await c.req.json()
|
||||
|
||||
const result = await fileService.createFileOrFolder(path, body)
|
||||
const result = await files.createFileOrFolder(path, body)
|
||||
return c.json(result)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create file/folder:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -219,11 +245,11 @@ export function createFileRoutes() {
|
||||
try {
|
||||
const path = getFilePathFromRequest(c, c.req.path.replace(/^\/api\/files\//, '') || '')
|
||||
|
||||
await fileService.deleteFileOrFolder(path)
|
||||
await files.deleteFileOrFolder(path)
|
||||
return c.json({ success: true })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to delete file/folder:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -233,15 +259,15 @@ export function createFileRoutes() {
|
||||
const body = await c.req.json()
|
||||
|
||||
if (body.patches && Array.isArray(body.patches)) {
|
||||
const result = await fileService.applyFilePatches(path, body.patches)
|
||||
const result = await files.applyFilePatches(path, body.patches)
|
||||
return c.json(result)
|
||||
}
|
||||
|
||||
const result = await fileService.renameOrMoveFile(path, body)
|
||||
const result = await files.renameOrMoveFile(path, body)
|
||||
return c.json(result)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to patch file:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Hono } from 'hono'
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { BrowseDirectoryResponseSchema } from '@opencode-manager/shared/schemas'
|
||||
import { readJson } from '../../test/helpers/read-json'
|
||||
import { createFilesystemRoutes } from './filesystem'
|
||||
|
||||
let tmpRoot: string
|
||||
@@ -32,7 +34,7 @@ describe('GET /api/filesystem/browse', () => {
|
||||
const res = await app.request('/filesystem/browse')
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = await res.json() as { isRoot: boolean; entries: { name: string }[] }
|
||||
const body = await readJson(res, BrowseDirectoryResponseSchema)
|
||||
expect(body.isRoot).toBe(true)
|
||||
expect(body.entries.map((e) => e.name)).toEqual(['projects'])
|
||||
})
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import * as filesystemService from '../services/filesystem'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
||||
@@ -14,7 +13,7 @@ export function createFilesystemRoutes() {
|
||||
return c.json(result)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to browse directory:', error)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to browse directory' }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to browse directory' }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { readFile } from 'fs/promises'
|
||||
import { z } from 'zod'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { compareSemver, normalizeSemver, parseSemver } from '@opencode-manager/shared/utils'
|
||||
import { githubFetch } from '../utils/github'
|
||||
import { logger } from '../utils/logger'
|
||||
import { SandboxRuntimeService } from '../services/sandbox/runtime'
|
||||
import { healthResponseSchema, type HealthResponse } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
|
||||
const GITHUB_REPO_NAME = 'opencode-manager'
|
||||
@@ -21,6 +23,35 @@ interface CachedRelease {
|
||||
let cachedRelease: CachedRelease | null = null
|
||||
const CACHE_TTL_MS = 60 * 60 * 1000
|
||||
|
||||
const GitHubReleaseSchema = z.object({
|
||||
tag_name: z.string().optional(),
|
||||
html_url: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
})
|
||||
|
||||
const PackageJsonSchema = z.object({
|
||||
version: z.string().optional(),
|
||||
})
|
||||
|
||||
type OpenCodeHealthFields = Pick<
|
||||
HealthResponse,
|
||||
| 'opencodePort'
|
||||
| 'opencodeVersion'
|
||||
| 'opencodeMinVersion'
|
||||
| 'opencodeVersionSupported'
|
||||
| 'opencodeRestartPending'
|
||||
>
|
||||
|
||||
function readOpenCodeHealthFields(openCodeStatus: HealthOpenCodeStatus): OpenCodeHealthFields {
|
||||
return {
|
||||
opencodePort: openCodeStatus.getPort(),
|
||||
opencodeVersion: openCodeStatus.getVersion(),
|
||||
opencodeMinVersion: openCodeStatus.getMinVersion(),
|
||||
opencodeVersionSupported: openCodeStatus.isVersionSupported(),
|
||||
opencodeRestartPending: openCodeStatus.isRestartPending(),
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchLatestRelease(): Promise<CachedRelease | null> {
|
||||
if (cachedRelease && Date.now() - cachedRelease.fetchedAt < CACHE_TTL_MS) {
|
||||
return cachedRelease
|
||||
@@ -35,7 +66,8 @@ async function fetchLatestRelease(): Promise<CachedRelease | null> {
|
||||
return cachedRelease
|
||||
}
|
||||
|
||||
const data = await response.json() as { tag_name?: string; html_url?: string; name?: string }
|
||||
const parsedRelease = GitHubReleaseSchema.safeParse(await response.json())
|
||||
const data = parsedRelease.success ? parsedRelease.data : {}
|
||||
const tagName = data.tag_name ?? '0.0.0'
|
||||
const htmlUrl = data.html_url ?? ''
|
||||
const name = data.name ?? tagName
|
||||
@@ -57,57 +89,76 @@ const opencodeManagerVersionPromise = (async (): Promise<string | null> => {
|
||||
try {
|
||||
const packageUrl = new URL('../../../package.json', import.meta.url)
|
||||
const packageJsonRaw = await readFile(packageUrl, 'utf-8')
|
||||
const packageJson = JSON.parse(packageJsonRaw) as { version?: unknown }
|
||||
return typeof packageJson.version === 'string' ? packageJson.version : null
|
||||
const parsedPackageJson = PackageJsonSchema.safeParse(JSON.parse(packageJsonRaw))
|
||||
return parsedPackageJson.success ? parsedPackageJson.data.version ?? null : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})()
|
||||
|
||||
export function createHealthRoutes(db: Database, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
export type HealthSupervisor = Pick<OpenCodeSupervisor, 'getStatus' | 'checkNow'>
|
||||
|
||||
export type HealthOpenCodeStatus = Pick<
|
||||
typeof opencodeServerManager,
|
||||
| 'checkHealth'
|
||||
| 'getLastStartupError'
|
||||
| 'getPort'
|
||||
| 'getVersion'
|
||||
| 'getMinVersion'
|
||||
| 'isVersionSupported'
|
||||
| 'isRestartPending'
|
||||
| 'isSandboxEnforced'
|
||||
>
|
||||
|
||||
export interface HealthProbes {
|
||||
pingDatabase: () => boolean
|
||||
}
|
||||
|
||||
export function createHealthRoutes(
|
||||
db: Database,
|
||||
openCodeSupervisor?: HealthSupervisor,
|
||||
openCodeStatus: HealthOpenCodeStatus = opencodeServerManager,
|
||||
probes: HealthProbes = { pingDatabase: () => Boolean(db.prepare('SELECT 1').get()) },
|
||||
) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', async (c) => {
|
||||
try {
|
||||
const opencodeManagerVersion = await opencodeManagerVersionPromise
|
||||
const dbCheck = db.prepare('SELECT 1').get()
|
||||
const databaseReachable = probes.pingDatabase()
|
||||
const lifecycle = openCodeSupervisor
|
||||
? openCodeSupervisor.getStatus()
|
||||
: null
|
||||
const opencodeHealthy = await opencodeServerManager.checkHealth()
|
||||
const startupError = lifecycle?.lastError ?? opencodeServerManager.getLastStartupError()
|
||||
const opencodeHealthy = await openCodeStatus.checkHealth()
|
||||
const startupError = lifecycle?.lastError ?? openCodeStatus.getLastStartupError()
|
||||
|
||||
const status = lifecycle?.state === 'recovering'
|
||||
? 'degraded'
|
||||
: startupError && !opencodeHealthy
|
||||
? 'unhealthy'
|
||||
: (dbCheck && opencodeHealthy ? 'healthy' : 'degraded')
|
||||
: (databaseReachable && opencodeHealthy ? 'healthy' : 'degraded')
|
||||
|
||||
const response: Record<string, unknown> = {
|
||||
const response: HealthResponse = {
|
||||
status,
|
||||
timestamp: new Date().toISOString(),
|
||||
database: dbCheck ? 'connected' : 'disconnected',
|
||||
database: databaseReachable ? 'connected' : 'disconnected',
|
||||
opencode: opencodeHealthy ? 'healthy' : 'unhealthy',
|
||||
opencodePort: opencodeServerManager.getPort(),
|
||||
opencodeVersion: opencodeServerManager.getVersion(),
|
||||
opencodeMinVersion: opencodeServerManager.getMinVersion(),
|
||||
opencodeVersionSupported: opencodeServerManager.isVersionSupported(),
|
||||
...readOpenCodeHealthFields(openCodeStatus),
|
||||
opencodeManagerVersion,
|
||||
opencodeRestartPending: opencodeServerManager.isRestartPending(),
|
||||
}
|
||||
|
||||
try {
|
||||
const runtimeStatus = new SandboxRuntimeService(db).getStatus()
|
||||
response.sandbox = {
|
||||
...runtimeStatus,
|
||||
enforced: opencodeServerManager.isSandboxEnforced(),
|
||||
enforced: openCodeStatus.isSandboxEnforced(),
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to collect sandbox status', error)
|
||||
response.sandbox = {
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: opencodeServerManager.isSandboxEnforced(),
|
||||
enforced: openCodeStatus.isSandboxEnforced(),
|
||||
reason: error instanceof Error ? error.message : 'sandbox status unavailable',
|
||||
}
|
||||
}
|
||||
@@ -120,15 +171,19 @@ export function createHealthRoutes(db: Database, openCodeSupervisor?: OpenCodeSu
|
||||
response.error = startupError
|
||||
}
|
||||
|
||||
return c.json(response, status === 'unhealthy' ? 503 : 200)
|
||||
return c.json(healthResponseSchema.parse(response), status === 'unhealthy' ? 503 : 200)
|
||||
} catch (error) {
|
||||
const opencodeManagerVersion = await opencodeManagerVersionPromise
|
||||
return c.json({
|
||||
const response: HealthResponse = {
|
||||
status: 'unhealthy',
|
||||
timestamp: new Date().toISOString(),
|
||||
database: 'disconnected',
|
||||
opencode: 'unhealthy',
|
||||
...readOpenCodeHealthFields(openCodeStatus),
|
||||
opencodeManagerVersion,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
}, 503)
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
}
|
||||
return c.json(healthResponseSchema.parse(response), 503)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -137,11 +192,11 @@ export function createHealthRoutes(db: Database, openCodeSupervisor?: OpenCodeSu
|
||||
const lifecycle = openCodeSupervisor
|
||||
? openCodeSupervisor.getStatus()
|
||||
: null
|
||||
const opencodeHealthy = await opencodeServerManager.checkHealth()
|
||||
const opencodeHealthy = await openCodeStatus.checkHealth()
|
||||
|
||||
return c.json({
|
||||
opencode: {
|
||||
port: opencodeServerManager.getPort(),
|
||||
port: openCodeStatus.getPort(),
|
||||
healthy: opencodeHealthy,
|
||||
lifecycle,
|
||||
},
|
||||
|
||||
@@ -2,12 +2,6 @@ import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { CredentialProvider } from '../../services/credential-provider'
|
||||
|
||||
/**
|
||||
* Legacy GitHub CLI environment route, kept for one release for OpenCode
|
||||
* processes that were adopted before the upgrade: those processes still run the
|
||||
* removed gh-env plugin and keep calling this path, so it answers with the same
|
||||
* flat env a fresh install fetches from `/shell-env`.
|
||||
*/
|
||||
export function createInternalGitCredentialsRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { ScheduleService } from '../../services/schedules'
|
||||
import type { NotificationService } from '../../services/notification'
|
||||
import type { ScheduleRoutesService } from '../schedules'
|
||||
import type { NotificationRoutesService } from './notifications'
|
||||
import type { SettingsService } from '../../services/settings'
|
||||
import type { OpenCodeClient } from '../../services/opencode/client'
|
||||
import { createScheduleRoutes } from '../schedules'
|
||||
@@ -22,27 +22,27 @@ import { createInternalSessionArtifactRoutes } from './session-artifacts'
|
||||
import { createMultiRunRoutes } from '../multi-runs'
|
||||
import { createChangeWalkthroughRoutes } from '../change-walkthroughs'
|
||||
import { createInternalWalkthroughSessionRoutes } from './walkthrough-sessions'
|
||||
import type { SessionPermissionModeService } from '../../services/session-permission-modes'
|
||||
import type { SessionSandboxService } from '../../services/session-sandbox'
|
||||
import type { RepoWorkspaceService } from '../../services/repo-workspace'
|
||||
import type { SessionPermissionModePinner } from '../../services/session-permission-modes'
|
||||
import type { SessionSandboxRoutesService } from '../session-sandbox'
|
||||
import type { RepoWorkspaceProvider } from '../../services/repo-workspace'
|
||||
import type { GitAuthService } from '../../services/git-auth'
|
||||
import type { MultiRunService } from '../../services/multi-runs'
|
||||
import type { ChangeWalkthroughService } from '../../services/change-walkthroughs'
|
||||
import type { RepoEnvService } from '../../services/repo-env'
|
||||
import type { MultiRunRoutesService } from '../multi-runs'
|
||||
import type { ChangeWalkthroughRoutesService } from '../change-walkthroughs'
|
||||
import type { RepoEnvResolver } from '../../services/repo-env'
|
||||
|
||||
export function createInternalRoutes(
|
||||
db: Database,
|
||||
scheduleService: ScheduleService,
|
||||
notificationService: NotificationService,
|
||||
scheduleService: ScheduleRoutesService,
|
||||
notificationService: NotificationRoutesService,
|
||||
settingsService: SettingsService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
permissionModes: SessionPermissionModeService,
|
||||
repoWorkspaces: RepoWorkspaceService,
|
||||
permissionModes: SessionPermissionModePinner,
|
||||
repoWorkspaces: RepoWorkspaceProvider,
|
||||
gitAuthService: GitAuthService,
|
||||
multiRuns: MultiRunService,
|
||||
changeWalkthroughService: ChangeWalkthroughService,
|
||||
sessionSandbox: SessionSandboxService,
|
||||
repoEnvService: RepoEnvService,
|
||||
multiRuns: MultiRunRoutesService,
|
||||
changeWalkthroughService: ChangeWalkthroughRoutesService,
|
||||
sessionSandbox: SessionSandboxRoutesService,
|
||||
repoEnvService: RepoEnvResolver,
|
||||
) {
|
||||
const app = new Hono()
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
|
||||
@@ -3,7 +3,9 @@ import { AssistantNotificationRequestSchema } from '@opencode-manager/shared/sch
|
||||
import type { NotificationService } from '../../services/notification'
|
||||
import { TokenBucketRateLimiter } from '../../utils/rate-limit'
|
||||
|
||||
export function createInternalNotificationRoutes(notificationService: NotificationService) {
|
||||
export type NotificationRoutesService = Pick<NotificationService, 'getScheduleRunReportUrl' | 'isConfigured' | 'sendToUser'>
|
||||
|
||||
export function createInternalNotificationRoutes(notificationService: NotificationRoutesService) {
|
||||
const app = new Hono()
|
||||
const limiter = new TokenBucketRateLimiter({ capacity: 10, refillPerMs: 60_000 })
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { dirname, join } from 'path'
|
||||
import { Readable } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { z } from 'zod'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { mkdirSafe, mkdirSyncSafe } from '../../utils/fs-safe'
|
||||
|
||||
@@ -14,19 +15,21 @@ const STALE_UPLOAD_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
export const TOTAL_PARTS_INVALID_MESSAGE = 'totalParts must be a positive integer'
|
||||
|
||||
export function isValidTotalParts(totalParts: number): boolean {
|
||||
return Number.isInteger(totalParts) && totalParts >= 1
|
||||
export function isValidTotalParts(totalParts: number | undefined): totalParts is number {
|
||||
return totalParts !== undefined && Number.isInteger(totalParts) && totalParts >= 1
|
||||
}
|
||||
|
||||
export interface UploadMeta {
|
||||
uploadId: string
|
||||
repoId: number
|
||||
fullPath: string
|
||||
created: boolean
|
||||
createdRepoId?: number
|
||||
force: boolean
|
||||
startedAt: number
|
||||
}
|
||||
const UploadMetaSchema = z.object({
|
||||
uploadId: z.string(),
|
||||
repoId: z.number(),
|
||||
fullPath: z.string(),
|
||||
created: z.boolean(),
|
||||
createdRepoId: z.number().optional(),
|
||||
force: z.boolean(),
|
||||
startedAt: z.number(),
|
||||
})
|
||||
|
||||
export type UploadMeta = z.infer<typeof UploadMetaSchema>
|
||||
|
||||
export function getStagingRoot(): string {
|
||||
return join(getReposPath(), '.ocm-staging')
|
||||
@@ -63,7 +66,8 @@ export async function createUploadSession(meta: Omit<UploadMeta, 'uploadId' | 's
|
||||
export async function readUploadMeta(uploadId: string): Promise<UploadMeta | null> {
|
||||
try {
|
||||
const raw = await fsp.readFile(getMetaPath(uploadId), 'utf-8')
|
||||
return JSON.parse(raw) as UploadMeta
|
||||
const parsed = UploadMetaSchema.safeParse(JSON.parse(raw))
|
||||
return parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -95,10 +99,12 @@ export interface ExtractResult {
|
||||
staging: string
|
||||
}
|
||||
|
||||
function isStdinClosedError(error: unknown): boolean {
|
||||
if (typeof error !== 'object' || error === null) return false
|
||||
const code = (error as { code?: unknown }).code
|
||||
return code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'EPIPE'
|
||||
const ErrorCodeSchema = z.object({ code: z.string().optional() })
|
||||
|
||||
function isStdinClosedError(cause: unknown): boolean {
|
||||
const parsed = ErrorCodeSchema.safeParse(cause)
|
||||
if (!parsed.success) return false
|
||||
return parsed.data.code === 'ERR_STREAM_PREMATURE_CLOSE' || parsed.data.code === 'EPIPE'
|
||||
}
|
||||
|
||||
export async function extractPartsToStaging(uploadId: string, totalParts: number, gzip: boolean): Promise<ExtractResult> {
|
||||
@@ -129,7 +135,7 @@ export async function extractPartsToStaging(uploadId: string, totalParts: number
|
||||
})
|
||||
tarDone.catch(() => {})
|
||||
|
||||
let writeError: unknown = null
|
||||
let writeError: unknown
|
||||
const partStreams = Readable.from(
|
||||
(async function* () {
|
||||
for (let i = 0; i < totalParts; i++) {
|
||||
@@ -167,7 +173,7 @@ export async function extractPartsToStaging(uploadId: string, totalParts: number
|
||||
if (statSync(candidate).isDirectory()) {
|
||||
extractedRoot = candidate
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
} catch { }
|
||||
}
|
||||
|
||||
return { extractedRoot, staging }
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Readable, Transform } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { join, resolve } from 'path'
|
||||
import * as fsp from 'fs/promises'
|
||||
import { z } from 'zod'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
MirrorTargetBranchRequestSchema,
|
||||
@@ -26,11 +27,12 @@ import {
|
||||
listGitWorktrees,
|
||||
resolveRepoWorkingDirectory,
|
||||
} from '../../services/repo'
|
||||
import type { RepoWorkspaceService } from '../../services/repo-workspace'
|
||||
import type { GitAuthService } from '../../services/git-auth'
|
||||
import type { RepoWorkspaceProvider } from '../../services/repo-workspace'
|
||||
import type { GitAuthEnvironmentProvider } from '../../services/git-auth'
|
||||
import type { OpenCodeClient } from '../../services/opencode/client'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { getErrorMessage } from '../../utils/error-utils'
|
||||
import { parseJsonBody } from '../../utils/route-helpers'
|
||||
import { canonicalPathSync, mkdirSyncSafe } from '../../utils/fs-safe'
|
||||
import { safeGitOut, gitOut } from './repo-sync-helpers'
|
||||
import {
|
||||
@@ -51,26 +53,58 @@ import {
|
||||
|
||||
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo']
|
||||
|
||||
interface BeginBody {
|
||||
create?: boolean
|
||||
name?: string
|
||||
originUrl?: string
|
||||
branch?: string
|
||||
force?: boolean
|
||||
export interface MirrorRouteDeps {
|
||||
getRepoById: typeof getRepoById
|
||||
updateLastPulled: typeof updateLastPulled
|
||||
updateRepoBranch: typeof updateRepoBranch
|
||||
deleteRepo: typeof deleteRepo
|
||||
ensureMirrorTargetPath: typeof ensureMirrorTargetPath
|
||||
createRepoRow: typeof createRepoRow
|
||||
isDirectoryInUse: typeof isDirectoryInUse
|
||||
isRepoInUse: typeof isRepoInUse
|
||||
resolveRepoWorkingDirectory: typeof resolveRepoWorkingDirectory
|
||||
listRepoSiblings: typeof listRepoSiblings
|
||||
listGitWorktrees: typeof listGitWorktrees
|
||||
gitOut: typeof gitOut
|
||||
safeGitOut: typeof safeGitOut
|
||||
}
|
||||
|
||||
interface CommitBody {
|
||||
uploadId: string
|
||||
totalParts: number
|
||||
gzip?: boolean
|
||||
export const mirrorRouteDeps: MirrorRouteDeps = {
|
||||
getRepoById,
|
||||
updateLastPulled,
|
||||
updateRepoBranch,
|
||||
deleteRepo,
|
||||
ensureMirrorTargetPath,
|
||||
createRepoRow,
|
||||
isDirectoryInUse,
|
||||
isRepoInUse,
|
||||
resolveRepoWorkingDirectory,
|
||||
listRepoSiblings,
|
||||
listGitWorktrees,
|
||||
gitOut,
|
||||
safeGitOut,
|
||||
}
|
||||
|
||||
interface PatchBody {
|
||||
baseHead?: string | null
|
||||
patch?: string
|
||||
force?: boolean
|
||||
directory?: string
|
||||
}
|
||||
const BeginBodySchema = z.object({
|
||||
create: z.boolean().optional(),
|
||||
name: z.string().optional(),
|
||||
originUrl: z.string().optional(),
|
||||
branch: z.string().optional(),
|
||||
force: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const CommitBodySchema = z.object({
|
||||
uploadId: z.string().optional(),
|
||||
totalParts: z.number().optional(),
|
||||
gzip: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const PatchBodySchema = z.object({
|
||||
baseHead: z.string().nullish(),
|
||||
patch: z.string().optional(),
|
||||
force: z.boolean().optional(),
|
||||
directory: z.string().optional(),
|
||||
})
|
||||
|
||||
const LEGACY_UPGRADE_MESSAGE = 'this ocm CLI is too old for this server; upgrade to ocm-cli >= 0.1.2 (the mirror upload protocol changed to chunked uploads)'
|
||||
const LEGACY_MOVE_UPGRADE_MESSAGE = 'this ocm CLI is too old for this server; upgrade to ocm-cli >= 0.4.0 (/ocm-move now moves sessions into OpenCode worktrees)'
|
||||
@@ -91,13 +125,13 @@ function gitRaw(repoPath: string, args: string[], env: NodeJS.ProcessEnv = proce
|
||||
})
|
||||
}
|
||||
|
||||
async function createMirrorPatch(fullPath: string): Promise<string> {
|
||||
async function createMirrorPatch(fullPath: string, deps: MirrorRouteDeps): Promise<string> {
|
||||
const untracked = (await gitRaw(fullPath, ['ls-files', '--others', '--exclude-standard', '-z']).catch(() => ''))
|
||||
.split('\0')
|
||||
.filter(Boolean)
|
||||
if (untracked.length === 0) return gitRaw(fullPath, ['diff', '--binary', 'HEAD', '--'])
|
||||
|
||||
const indexPath = (await safeGitOut(fullPath, ['rev-parse', '--git-path', 'index']))?.trim()
|
||||
const indexPath = (await deps.safeGitOut(fullPath, ['rev-parse', '--git-path', 'index']))?.trim()
|
||||
const tempIndexDir = mkdtempSync(join(getReposPath(), '.ocm-index-'))
|
||||
const tempIndex = join(tempIndexDir, 'index')
|
||||
const env = { ...process.env, GIT_INDEX_FILE: tempIndex }
|
||||
@@ -143,16 +177,16 @@ async function listLocalBranchNames(fullPath: string): Promise<Set<string>> {
|
||||
return new Set(out.split('\n').map((l) => l.trim()).filter(Boolean))
|
||||
}
|
||||
|
||||
async function isValidBranchName(repoPath: string, name: string): Promise<boolean> {
|
||||
async function isValidBranchName(repoPath: string, name: string, deps: MirrorRouteDeps): Promise<boolean> {
|
||||
if (name.startsWith('-')) return false
|
||||
return (await safeGitOut(repoPath, ['check-ref-format', '--branch', name])) !== null
|
||||
return (await deps.safeGitOut(repoPath, ['check-ref-format', '--branch', name])) !== null
|
||||
}
|
||||
|
||||
async function checkoutState(directory: string): Promise<MirrorCheckoutState> {
|
||||
async function checkoutState(directory: string, deps: MirrorRouteDeps): Promise<MirrorCheckoutState> {
|
||||
const [branch, head, status] = await Promise.all([
|
||||
currentBranchName(directory),
|
||||
safeGitOut(directory, ['rev-parse', 'HEAD']),
|
||||
safeGitOut(directory, ['status', '--porcelain', '--untracked-files=all']),
|
||||
deps.safeGitOut(directory, ['rev-parse', 'HEAD']),
|
||||
deps.safeGitOut(directory, ['status', '--porcelain', '--untracked-files=all']),
|
||||
])
|
||||
return {
|
||||
directory,
|
||||
@@ -172,21 +206,23 @@ function isMirrorCheckoutSibling(repo: Repo): (sibling: RepoSibling) => boolean
|
||||
async function listMirrorCheckoutSiblings(
|
||||
db: Database,
|
||||
repo: Repo,
|
||||
gitAuthService: GitAuthService,
|
||||
gitAuthService: GitAuthEnvironmentProvider,
|
||||
openCodeClient: OpenCodeClient,
|
||||
deps: MirrorRouteDeps,
|
||||
): Promise<RepoSibling[]> {
|
||||
return listRepoSiblings(db, repo.id, gitAuthService.getGitEnvironment(), openCodeClient, isMirrorCheckoutSibling(repo))
|
||||
return deps.listRepoSiblings(db, repo.id, gitAuthService.getGitEnvironment(), openCodeClient, isMirrorCheckoutSibling(repo))
|
||||
}
|
||||
|
||||
async function resolveMirrorDirectory(
|
||||
db: Database,
|
||||
repo: Repo,
|
||||
directory: string | undefined,
|
||||
gitAuthService: GitAuthService,
|
||||
gitAuthService: GitAuthEnvironmentProvider,
|
||||
openCodeClient: OpenCodeClient,
|
||||
deps: MirrorRouteDeps,
|
||||
): Promise<string | null> {
|
||||
return resolveRepoWorkingDirectory(repo, directory, () =>
|
||||
listMirrorCheckoutSiblings(db, repo, gitAuthService, openCodeClient),
|
||||
return deps.resolveRepoWorkingDirectory(repo, directory, () =>
|
||||
listMirrorCheckoutSiblings(db, repo, gitAuthService, openCodeClient, deps),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -208,8 +244,8 @@ function nextSuffixedWorktreeBranch(branch: string, localBranches: Set<string>,
|
||||
}
|
||||
}
|
||||
|
||||
async function branchHeadSha(fullPath: string, branch: string): Promise<string | null> {
|
||||
const sha = await safeGitOut(fullPath, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`])
|
||||
async function branchHeadSha(fullPath: string, branch: string, deps: MirrorRouteDeps): Promise<string | null> {
|
||||
const sha = await deps.safeGitOut(fullPath, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`])
|
||||
return sha?.trim() || null
|
||||
}
|
||||
|
||||
@@ -294,7 +330,7 @@ async function stageBundleFromBody(body: ReadableStream, dirPrefix: string, patc
|
||||
const bundleDir = mkdtempSync(join(stagingRoot, dirPrefix))
|
||||
try {
|
||||
const bundlePath = join(bundleDir, 'repo.bundle')
|
||||
const readable = Readable.fromWeb(body as unknown as Parameters<typeof Readable.fromWeb>[0])
|
||||
const readable = Readable.fromWeb(body)
|
||||
const patchChunks: Buffer[] = []
|
||||
let patchRead = 0
|
||||
const splitPatch = new Transform({
|
||||
@@ -329,8 +365,9 @@ async function stageBundleFromBody(body: ReadableStream, dirPrefix: string, patc
|
||||
export function createInternalRepoMirrorRoutes(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
gitAuthService: GitAuthService,
|
||||
repoWorkspaces: RepoWorkspaceService,
|
||||
gitAuthService: GitAuthEnvironmentProvider,
|
||||
repoWorkspaces: RepoWorkspaceProvider,
|
||||
deps: MirrorRouteDeps = mirrorRouteDeps,
|
||||
) {
|
||||
const app = new Hono()
|
||||
|
||||
@@ -340,12 +377,11 @@ export function createInternalRepoMirrorRoutes(
|
||||
|
||||
app.post('/:repoId/mirror/begin', async (c) => {
|
||||
const repoIdRaw = c.req.param('repoId')
|
||||
let body: BeginBody
|
||||
try {
|
||||
body = (await c.req.json()) as BeginBody
|
||||
} catch {
|
||||
return c.json({ error: 'invalid json body' }, 400)
|
||||
const parsedBody = await parseJsonBody(c, BeginBodySchema, { invalidMessage: 'invalid json body' })
|
||||
if (!parsedBody.ok) {
|
||||
return parsedBody.response
|
||||
}
|
||||
const body = parsedBody.data
|
||||
|
||||
const force = body.force === true
|
||||
const create = body.create === true
|
||||
@@ -357,8 +393,8 @@ export function createInternalRepoMirrorRoutes(
|
||||
|
||||
if (repoIdRaw === '0' && create) {
|
||||
if (!body.name) return c.json({ error: 'name required', message: 'provide name in body' }, 400)
|
||||
const target = ensureMirrorTargetPath(body.name)
|
||||
const { repo: newRepo, created: wasCreated } = createRepoRow(db, {
|
||||
const target = deps.ensureMirrorTargetPath(body.name)
|
||||
const { repo: newRepo, created: wasCreated } = deps.createRepoRow(db, {
|
||||
name: body.name,
|
||||
originUrl: body.originUrl,
|
||||
localPath: target.localPath,
|
||||
@@ -370,18 +406,18 @@ export function createInternalRepoMirrorRoutes(
|
||||
created = wasCreated
|
||||
createdRepoId = wasCreated ? newRepo.id : undefined
|
||||
|
||||
if (!wasCreated && !force && isRepoInUse(db, repoId)) {
|
||||
if (!wasCreated && !force && deps.isRepoInUse(db, repoId)) {
|
||||
return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409)
|
||||
}
|
||||
} else {
|
||||
const repoIdNum = Number(repoIdRaw)
|
||||
if (!Number.isFinite(repoIdNum)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
const repo = getRepoById(db, repoIdNum)
|
||||
const repo = deps.getRepoById(db, repoIdNum)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
repoId = repo.id
|
||||
fullPath = repo.fullPath
|
||||
|
||||
if (!force && isRepoInUse(db, repoId)) {
|
||||
if (!force && deps.isRepoInUse(db, repoId)) {
|
||||
return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409)
|
||||
}
|
||||
}
|
||||
@@ -392,7 +428,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
} catch (error) {
|
||||
logger.error('mirror begin failed:', error)
|
||||
if (createdRepoId !== undefined) {
|
||||
try { deleteRepo(db, createdRepoId) } catch { /* ignore */ }
|
||||
try { deps.deleteRepo(db, createdRepoId) } catch { }
|
||||
}
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
@@ -422,7 +458,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
|
||||
const partPath = getPartPath(uploadId, index)
|
||||
try {
|
||||
const body = Readable.fromWeb(rawBody as unknown as Parameters<typeof Readable.fromWeb>[0])
|
||||
const body = Readable.fromWeb(rawBody)
|
||||
await pipeline(body, createWriteStream(partPath))
|
||||
const stat = await fsp.stat(partPath)
|
||||
return c.json({ index, size: stat.size })
|
||||
@@ -434,14 +470,12 @@ export function createInternalRepoMirrorRoutes(
|
||||
})
|
||||
|
||||
app.post('/:repoId/mirror/commit', async (c) => {
|
||||
let body: CommitBody
|
||||
try {
|
||||
body = (await c.req.json()) as CommitBody
|
||||
} catch {
|
||||
return c.json({ error: 'invalid json body' }, 400)
|
||||
const parsedBody = await parseJsonBody(c, CommitBodySchema, { invalidMessage: 'invalid json body' })
|
||||
if (!parsedBody.ok) {
|
||||
return parsedBody.response
|
||||
}
|
||||
|
||||
const { uploadId, totalParts, gzip } = body
|
||||
const { uploadId, totalParts, gzip } = parsedBody.data
|
||||
if (!uploadId) return c.json({ error: 'uploadId required' }, 400)
|
||||
if (!isValidTotalParts(totalParts)) return c.json({ error: TOTAL_PARTS_INVALID_MESSAGE }, 400)
|
||||
|
||||
@@ -457,11 +491,11 @@ export function createInternalRepoMirrorRoutes(
|
||||
const swap = await atomicSwapIntoPlace(extracted.extractedRoot, meta.fullPath)
|
||||
backupDir = swap.backupDir
|
||||
|
||||
const branchName = await safeGitOut(meta.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD'])
|
||||
const head = await safeGitOut(meta.fullPath, ['rev-parse', 'HEAD'])
|
||||
const branchName = await deps.safeGitOut(meta.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD'])
|
||||
const head = await deps.safeGitOut(meta.fullPath, ['rev-parse', 'HEAD'])
|
||||
|
||||
if (branchName) updateRepoBranch(db, meta.repoId, branchName.trim())
|
||||
updateLastPulled(db, meta.repoId)
|
||||
if (branchName) deps.updateRepoBranch(db, meta.repoId, branchName.trim())
|
||||
deps.updateLastPulled(db, meta.repoId)
|
||||
|
||||
await carryOverIgnoredFiles(backupDir, meta.fullPath)
|
||||
await discardBackup(backupDir)
|
||||
@@ -481,7 +515,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
logger.error('mirror commit failed:', error)
|
||||
await restoreBackup(meta.fullPath, backupDir)
|
||||
if (meta.createdRepoId !== undefined) {
|
||||
try { deleteRepo(db, meta.createdRepoId) } catch { /* ignore */ }
|
||||
try { deps.deleteRepo(db, meta.createdRepoId) } catch { }
|
||||
}
|
||||
if (staging) {
|
||||
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
|
||||
@@ -495,7 +529,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
const uploadId = c.req.param('uploadId')
|
||||
const meta = await readUploadMeta(uploadId)
|
||||
if (meta?.createdRepoId !== undefined) {
|
||||
try { deleteRepo(db, meta.createdRepoId) } catch { /* ignore */ }
|
||||
try { deps.deleteRepo(db, meta.createdRepoId) } catch { }
|
||||
}
|
||||
await deleteUploadSession(uploadId)
|
||||
return c.json({ ok: true })
|
||||
@@ -505,10 +539,10 @@ export function createInternalRepoMirrorRoutes(
|
||||
const repoIdRaw = c.req.param('repoId')
|
||||
const repoId = Number(repoIdRaw)
|
||||
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient)
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient, deps)
|
||||
if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
|
||||
let bundlePath: string | undefined
|
||||
@@ -518,7 +552,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
stream.on('close', () => {
|
||||
if (bundlePath) fsp.rm(join(bundlePath, '..'), { recursive: true, force: true }).catch(() => {})
|
||||
})
|
||||
return new Response(Readable.toWeb(stream) as ReadableStream, {
|
||||
return new Response(Readable.toWeb(stream), {
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
})
|
||||
} catch (error) {
|
||||
@@ -532,14 +566,14 @@ export function createInternalRepoMirrorRoutes(
|
||||
const repoIdRaw = c.req.param('repoId')
|
||||
const repoId = Number(repoIdRaw)
|
||||
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient)
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient, deps)
|
||||
if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
|
||||
const force = c.req.query('force') === '1'
|
||||
if (isDirectoryInUse(directory) && !force) {
|
||||
if (deps.isDirectoryInUse(directory) && !force) {
|
||||
return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409)
|
||||
}
|
||||
|
||||
@@ -556,10 +590,10 @@ export function createInternalRepoMirrorRoutes(
|
||||
bundleDir = staged.bundleDir
|
||||
await importBundle(directory, staged.bundlePath, branch, requireCurrentBranch, force, targetBranch)
|
||||
|
||||
const state = await checkoutState(directory)
|
||||
const state = await checkoutState(directory, deps)
|
||||
if (directory === repo.fullPath) {
|
||||
if (state.branch) updateRepoBranch(db, repoId, state.branch)
|
||||
updateLastPulled(db, repoId)
|
||||
if (state.branch) deps.updateRepoBranch(db, repoId, state.branch)
|
||||
deps.updateLastPulled(db, repoId)
|
||||
}
|
||||
|
||||
return c.json({
|
||||
@@ -591,18 +625,18 @@ export function createInternalRepoMirrorRoutes(
|
||||
const branchParsed = MirrorTargetBranchRequestSchema.safeParse({ branch: c.req.query('branch') })
|
||||
if (!branchParsed.success) return c.json({ error: 'branch required' }, 400)
|
||||
const { branch } = branchParsed.data
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
if (!(await isValidBranchName(repo.fullPath, branch))) return c.json({ error: 'invalid branch name' }, 400)
|
||||
if (!(await isValidBranchName(repo.fullPath, branch, deps))) return c.json({ error: 'invalid branch name' }, 400)
|
||||
|
||||
try {
|
||||
const env = gitAuthService.getGitEnvironment()
|
||||
const [main, siblings, gitWorktrees, localBranches, branchHead] = await Promise.all([
|
||||
checkoutState(repo.fullPath),
|
||||
listMirrorCheckoutSiblings(db, repo, gitAuthService, openCodeClient),
|
||||
listGitWorktrees(repo.fullPath, env),
|
||||
checkoutState(repo.fullPath, deps),
|
||||
listMirrorCheckoutSiblings(db, repo, gitAuthService, openCodeClient, deps),
|
||||
deps.listGitWorktrees(repo.fullPath, env),
|
||||
listLocalBranchNames(repo.fullPath),
|
||||
branchHeadSha(repo.fullPath, branch),
|
||||
branchHeadSha(repo.fullPath, branch, deps),
|
||||
])
|
||||
|
||||
const branchByCanonicalPath = new Map<string, string | null>()
|
||||
@@ -623,7 +657,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
.filter((candidate): candidate is { sibling: RepoSibling; rank: number } => candidate.rank !== null)
|
||||
.sort((left, right) => left.rank - right.rank)
|
||||
|
||||
const worktrees = await Promise.all(candidates.map((candidate) => checkoutState(candidate.sibling.fullPath)))
|
||||
const worktrees = await Promise.all(candidates.map((candidate) => checkoutState(candidate.sibling.fullPath, deps)))
|
||||
|
||||
const response: MirrorCheckoutsResponse = {
|
||||
main,
|
||||
@@ -647,10 +681,10 @@ export function createInternalRepoMirrorRoutes(
|
||||
const targetBranch = c.req.header('x-ocm-target-branch')?.trim()
|
||||
if (!branch || !targetBranch) return c.json({ error: 'branch and target branch required' }, 400)
|
||||
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
|
||||
if (!(await isValidBranchName(repo.fullPath, branch)) || !(await isValidBranchName(repo.fullPath, targetBranch))) {
|
||||
if (!(await isValidBranchName(repo.fullPath, branch, deps)) || !(await isValidBranchName(repo.fullPath, targetBranch, deps))) {
|
||||
return c.json({ error: 'invalid branch name' }, 400)
|
||||
}
|
||||
|
||||
@@ -661,7 +695,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
patchBytes = Number(patchBytesHeader.trim())
|
||||
}
|
||||
|
||||
const gitWorktrees = await listGitWorktrees(repo.fullPath, gitAuthService.getGitEnvironment())
|
||||
const gitWorktrees = await deps.listGitWorktrees(repo.fullPath, gitAuthService.getGitEnvironment())
|
||||
if (gitWorktrees.some((worktree) => worktree.branch === targetBranch)) {
|
||||
return c.json({ error: 'branch_in_use', message: `branch '${targetBranch}' is checked out in a worktree of this repository` }, 409)
|
||||
}
|
||||
@@ -680,7 +714,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
await applyMirrorPatch(directory, staged.patch)
|
||||
},
|
||||
})
|
||||
const state = await checkoutState(worktree.directory)
|
||||
const state = await checkoutState(worktree.directory, deps)
|
||||
const response: MirrorWorktreeCreateResponse = {
|
||||
repoId: repo.id,
|
||||
fullPath: worktree.directory,
|
||||
@@ -702,13 +736,13 @@ export function createInternalRepoMirrorRoutes(
|
||||
const repoIdRaw = c.req.param('repoId')
|
||||
const repoId = Number(repoIdRaw)
|
||||
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient)
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient, deps)
|
||||
if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
|
||||
const state = await checkoutState(directory)
|
||||
const state = await checkoutState(directory, deps)
|
||||
return c.json({
|
||||
repoId: repo.id,
|
||||
branch: state.branch,
|
||||
@@ -723,13 +757,13 @@ export function createInternalRepoMirrorRoutes(
|
||||
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
const sha = c.req.param('sha')
|
||||
if (!/^[0-9a-f]{7,64}$/i.test(sha)) return c.json({ error: 'invalid sha' }, 400)
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient)
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient, deps)
|
||||
if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
|
||||
const ancestry = await safeGitOut(directory, ['merge-base', '--is-ancestor', sha, 'HEAD'])
|
||||
const ancestry = await deps.safeGitOut(directory, ['merge-base', '--is-ancestor', sha, 'HEAD'])
|
||||
return c.json({ repoId: repo.id, contained: ancestry !== null })
|
||||
})
|
||||
|
||||
@@ -737,15 +771,15 @@ export function createInternalRepoMirrorRoutes(
|
||||
const repoIdRaw = c.req.param('repoId')
|
||||
const repoId = Number(repoIdRaw)
|
||||
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient)
|
||||
const directory = await resolveMirrorDirectory(db, repo, c.req.query('directory'), gitAuthService, openCodeClient, deps)
|
||||
if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
|
||||
try {
|
||||
const state = await checkoutState(directory)
|
||||
const patch = await createMirrorPatch(directory)
|
||||
const state = await checkoutState(directory, deps)
|
||||
const patch = await createMirrorPatch(directory, deps)
|
||||
return c.json({
|
||||
repoId: repo.id,
|
||||
branch: state.branch,
|
||||
@@ -763,29 +797,25 @@ export function createInternalRepoMirrorRoutes(
|
||||
const repoId = Number(repoIdRaw)
|
||||
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
|
||||
let body: PatchBody
|
||||
try {
|
||||
body = (await c.req.json()) as PatchBody
|
||||
} catch {
|
||||
return c.json({ error: 'invalid json body' }, 400)
|
||||
const parsedBody = await parseJsonBody(c, PatchBodySchema, { invalidMessage: 'invalid json body' })
|
||||
if (!parsedBody.ok) {
|
||||
return parsedBody.response
|
||||
}
|
||||
const body = parsedBody.data
|
||||
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
if (!body.patch && body.patch !== '') return c.json({ error: 'patch required' }, 400)
|
||||
if (body.directory !== undefined && typeof body.directory !== 'string') {
|
||||
return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
}
|
||||
|
||||
const directory = await resolveMirrorDirectory(db, repo, body.directory, gitAuthService, openCodeClient)
|
||||
const directory = await resolveMirrorDirectory(db, repo, body.directory, gitAuthService, openCodeClient, deps)
|
||||
if (!directory) return c.json({ error: 'Directory is not part of this repository' }, 400)
|
||||
|
||||
if (body.force !== true && isDirectoryInUse(directory)) {
|
||||
if (body.force !== true && deps.isDirectoryInUse(directory)) {
|
||||
return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409)
|
||||
}
|
||||
|
||||
try {
|
||||
const state = await checkoutState(directory)
|
||||
const state = await checkoutState(directory, deps)
|
||||
const baseHead = body.baseHead?.trim() || null
|
||||
if (baseHead && state.head && baseHead !== state.head) {
|
||||
return c.json({ error: 'head_mismatch', message: 'Manager repo HEAD differs from patch base' }, 409)
|
||||
@@ -794,8 +824,8 @@ export function createInternalRepoMirrorRoutes(
|
||||
await applyMirrorPatch(directory, body.patch)
|
||||
|
||||
if (directory === repo.fullPath) {
|
||||
if (state.branch) updateRepoBranch(db, repoId, state.branch)
|
||||
updateLastPulled(db, repoId)
|
||||
if (state.branch) deps.updateRepoBranch(db, repoId, state.branch)
|
||||
deps.updateLastPulled(db, repoId)
|
||||
}
|
||||
|
||||
return c.json({
|
||||
@@ -816,7 +846,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
const repoIdRaw = c.req.param('repoId')
|
||||
const repoId = Number(repoIdRaw)
|
||||
if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400)
|
||||
const repo = getRepoById(db, repoId)
|
||||
const repo = deps.getRepoById(db, repoId)
|
||||
if (!repo) return c.json({ error: 'repo not found' }, 404)
|
||||
|
||||
const compress = c.req.query('compress') === 'gzip'
|
||||
@@ -829,7 +859,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
|
||||
let ignoreFile: string | undefined
|
||||
try {
|
||||
const ignored = await gitOut(fullPath, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'])
|
||||
const ignored = await deps.gitOut(fullPath, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'])
|
||||
if (ignored.trim()) {
|
||||
const excludeParent = getStagingRoot()
|
||||
mkdirSyncSafe(excludeParent)
|
||||
@@ -837,7 +867,7 @@ export function createInternalRepoMirrorRoutes(
|
||||
writeFileSync(join(ignoreFile, '.gitignore'), ignored)
|
||||
excludeArgs.push('--exclude-from', join(ignoreFile, '.gitignore'))
|
||||
}
|
||||
} catch { /* ignore git ls-files errors */ }
|
||||
} catch { }
|
||||
|
||||
const tarArgs = ['-c', '-C', fullPath, ...excludeArgs, '.']
|
||||
if (compress) {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { InternalCloneRepoRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { SettingsService } from '../../services/settings'
|
||||
@@ -9,7 +8,9 @@ import { cloneRepo } from '../../services/repo'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { getErrorMessage, getStatusCode } from '../../utils/error-utils'
|
||||
|
||||
export function createInternalRepoRoutes(db: Database, settingsService: SettingsService, gitAuthService: GitAuthService) {
|
||||
export type InternalRepoRoutesSettings = Pick<SettingsService, 'getSettings'>
|
||||
|
||||
export function createInternalRepoRoutes(db: Database, settingsService: InternalRepoRoutesSettings, gitAuthService: GitAuthService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
@@ -34,7 +35,7 @@ export function createInternalRepoRoutes(db: Database, settingsService: Settings
|
||||
return c.json(repo)
|
||||
} catch (error) {
|
||||
logger.error('Failed to clone internal repo:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SandboxRuntimeService } from '../../services/sandbox/runtime'
|
||||
import type { SessionSandboxService } from '../../services/session-sandbox'
|
||||
import type { RepoEnvService } from '../../services/repo-env'
|
||||
import type { SessionSandboxRoutesService } from '../session-sandbox'
|
||||
import type { RepoEnvResolver } from '../../services/repo-env'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
const SandboxShellRequestSchema = z.object({
|
||||
@@ -15,8 +15,8 @@ const SandboxShellRequestSchema = z.object({
|
||||
|
||||
export function createInternalSandboxRoutes(
|
||||
db: Database,
|
||||
sessionSandbox: SessionSandboxService,
|
||||
repoEnvService: RepoEnvService,
|
||||
sessionSandbox: SessionSandboxRoutesService,
|
||||
repoEnvService: RepoEnvResolver,
|
||||
) {
|
||||
const app = new Hono()
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import { toContentfulStatus } from '../../utils/error-utils'
|
||||
import type { OpenCodeClient } from '../../services/opencode/client'
|
||||
import { resolveSessionArtifactFile, SessionArtifactError } from '../../services/session-artifacts'
|
||||
import { handleOpenCodeError, parseJsonBody } from '../../utils/route-helpers'
|
||||
@@ -21,7 +21,7 @@ export function createInternalSessionArtifactRoutes(openCodeClient: OpenCodeClie
|
||||
return c.json({ path })
|
||||
} catch (error) {
|
||||
if (error instanceof SessionArtifactError) {
|
||||
return c.json({ error: error.message }, error.status as ContentfulStatusCode)
|
||||
return c.json({ error: error.message }, toContentfulStatus(error.status))
|
||||
}
|
||||
return handleOpenCodeError(c, error, 'Failed to resolve artifact file', { unknownStatus: 502 })
|
||||
}
|
||||
|
||||
@@ -10,9 +10,10 @@ import { buildSessionPath } from '@opencode-manager/shared/utils'
|
||||
import { getRepoById } from '../../db/queries'
|
||||
import { handleOpenCodeError, parseJsonBody } from '../../utils/route-helpers'
|
||||
import type { OpenCodeClient } from '../../services/opencode/client'
|
||||
import type { SessionPermissionModeService } from '../../services/session-permission-modes'
|
||||
import type { RepoWorkspaceService } from '../../services/repo-workspace'
|
||||
import type { SessionPermissionModePinner } from '../../services/session-permission-modes'
|
||||
import type { RepoWorkspaceProvider } from '../../services/repo-workspace'
|
||||
import { SessionLaunchError, SessionLauncher } from '../../services/session-launcher'
|
||||
import type { LaunchSessionInput } from '../../services/session-launcher'
|
||||
import {
|
||||
isSessionBusy,
|
||||
readLatestAssistantReply,
|
||||
@@ -27,6 +28,9 @@ const INTERNAL_SESSION_LIST_LIMIT_DEFAULT = 10
|
||||
const INTERNAL_SESSION_WORKSPACE_NAME_FALLBACK = 'ocm-session'
|
||||
const INTERNAL_SESSION_REPLY_WAIT_MAX_MS = 45000
|
||||
|
||||
type SessionListInput = NonNullable<Parameters<OpenCodeClient['api']['session']['list']>[0]>
|
||||
type SessionForkInput = NonNullable<Parameters<OpenCodeClient['api']['session']['fork']>[0]>
|
||||
|
||||
const ListSessionsQuerySchema = z.object({
|
||||
repoId: z.coerce.number().int().optional(),
|
||||
limit: z.coerce
|
||||
@@ -41,18 +45,18 @@ const ReplyQuerySchema = z.object({
|
||||
waitMs: z.coerce.number().int().min(0).max(INTERNAL_SESSION_REPLY_WAIT_MAX_MS).optional(),
|
||||
})
|
||||
|
||||
function handleSessionRouteError(c: Context, error: unknown) {
|
||||
if (error instanceof SessionLaunchError) {
|
||||
return c.json({ error: error.message }, error.status)
|
||||
function handleSessionRouteError(c: Context, cause: unknown) {
|
||||
if (cause instanceof SessionLaunchError) {
|
||||
return c.json({ error: cause.message }, cause.status)
|
||||
}
|
||||
return handleOpenCodeError(c, error, 'Internal session request failed', { unknownStatus: 502 })
|
||||
return handleOpenCodeError(c, cause, 'Internal session request failed', { unknownStatus: 502 })
|
||||
}
|
||||
|
||||
export function createInternalSessionRoutes(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
permissionModes: SessionPermissionModeService,
|
||||
repoWorkspaces: RepoWorkspaceService,
|
||||
permissionModes: SessionPermissionModePinner,
|
||||
repoWorkspaces: RepoWorkspaceProvider,
|
||||
) {
|
||||
const app = new Hono()
|
||||
const sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces)
|
||||
@@ -71,12 +75,8 @@ export function createInternalSessionRoutes(
|
||||
|
||||
try {
|
||||
const project = repo ? await resolveRepoProjectId(openCodeClient, repo.fullPath) : undefined
|
||||
const response = await openCodeClient.api.session.list({
|
||||
limit,
|
||||
order: 'desc',
|
||||
parentID: null,
|
||||
...(project ? { project } : {}),
|
||||
})
|
||||
const listInput: SessionListInput = { limit, order: 'desc', parentID: null, project }
|
||||
const response = await openCodeClient.api.session.list(listInput)
|
||||
const active = await openCodeClient.api.session.active()
|
||||
|
||||
const repoIdByDirectory = new Map<string, number | null>()
|
||||
@@ -112,21 +112,26 @@ export function createInternalSessionRoutes(
|
||||
|
||||
const input = body.data
|
||||
try {
|
||||
const launched = await sessionLauncher.launch({
|
||||
repoId: input.repoId,
|
||||
prompt: input.prompt,
|
||||
...(input.title ? { title: input.title } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(input.agent ? { agent: input.agent } : {}),
|
||||
...(input.worktree
|
||||
? {
|
||||
workspace: {
|
||||
name: input.title ?? INTERNAL_SESSION_WORKSPACE_NAME_FALLBACK,
|
||||
...(input.ref ? { ref: input.ref } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
const launchInput: LaunchSessionInput = { repoId: input.repoId, prompt: input.prompt }
|
||||
if (input.title) {
|
||||
launchInput.title = input.title
|
||||
}
|
||||
if (input.model) {
|
||||
launchInput.model = input.model
|
||||
}
|
||||
if (input.agent) {
|
||||
launchInput.agent = input.agent
|
||||
}
|
||||
if (input.worktree) {
|
||||
const workspace: NonNullable<LaunchSessionInput['workspace']> = {
|
||||
name: input.title ?? INTERNAL_SESSION_WORKSPACE_NAME_FALLBACK,
|
||||
}
|
||||
if (input.ref) {
|
||||
workspace.ref = input.ref
|
||||
}
|
||||
launchInput.workspace = workspace
|
||||
}
|
||||
const launched = await sessionLauncher.launch(launchInput)
|
||||
|
||||
permissionModes.pinAsk(launched.sessionId)
|
||||
|
||||
@@ -198,10 +203,8 @@ export function createInternalSessionRoutes(
|
||||
|
||||
const beforeMessageId = body.data.beforeMessageId
|
||||
try {
|
||||
const forked = await openCodeClient.api.session.fork({
|
||||
sessionID: sessionId,
|
||||
...(beforeMessageId ? { before: beforeMessageId } : {}),
|
||||
})
|
||||
const forkInput: SessionForkInput = { sessionID: sessionId, before: beforeMessageId }
|
||||
const forked = await openCodeClient.api.session.fork(forkInput)
|
||||
permissionModes.pinAsk(forked.id)
|
||||
return c.json({ sessionId: forked.id, directory: forked.location.directory })
|
||||
} catch (error) {
|
||||
|
||||
@@ -3,16 +3,15 @@ import { AssistantSettingsPatchSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { SettingsService } from '../../services/settings'
|
||||
import type { SettingsResponse, UserPreferences } from '@opencode-manager/shared/types'
|
||||
import { OPENCODE_CONFIG_REDACTED_VALUE } from '../../services/opencode-config-file'
|
||||
import { parseJsonBody } from '../../utils/route-helpers'
|
||||
|
||||
function redactSecret<T extends string | undefined>(value: T): T {
|
||||
return (value ? OPENCODE_CONFIG_REDACTED_VALUE : value) as T
|
||||
function redactSecret(value: string): string
|
||||
function redactSecret(value: undefined): undefined
|
||||
function redactSecret(value: string | undefined): string | undefined
|
||||
function redactSecret(value: string | undefined): string | undefined {
|
||||
return value ? OPENCODE_CONFIG_REDACTED_VALUE : value
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces stored credentials in a settings response with `<redacted>` so token clients such as the
|
||||
* agent-facing `ocm` tool can read preferences without receiving secrets. Empty values stay empty, so a
|
||||
* caller can still tell whether a credential is configured.
|
||||
*/
|
||||
function redactInternalSettings(settings: SettingsResponse): SettingsResponse {
|
||||
const { preferences } = settings
|
||||
return {
|
||||
@@ -34,7 +33,9 @@ function redactInternalSettings(settings: SettingsResponse): SettingsResponse {
|
||||
}
|
||||
}
|
||||
|
||||
export function createInternalSettingsRoutes(settingsService: SettingsService) {
|
||||
export type InternalSettingsRoutesService = Pick<SettingsService, 'getSettings' | 'updateSettings'>
|
||||
|
||||
export function createInternalSettingsRoutes(settingsService: InternalSettingsRoutesService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
@@ -45,40 +46,29 @@ export function createInternalSettingsRoutes(settingsService: SettingsService) {
|
||||
app.patch('/', async (c) => {
|
||||
const userId = c.req.query('userId') ?? 'default'
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await c.req.json()
|
||||
} catch {
|
||||
return c.json({ error: 'Invalid JSON' }, 400)
|
||||
const body = await parseJsonBody(c, AssistantSettingsPatchSchema, { invalidBodyMessage: 'Invalid request body' })
|
||||
if (!body.ok) {
|
||||
return body.response
|
||||
}
|
||||
|
||||
const parsed = AssistantSettingsPatchSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400)
|
||||
}
|
||||
|
||||
const patch = parsed.data
|
||||
const patch = body.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) {
|
||||
const { tts, stt, ...restPatch } = patch
|
||||
const updates: Partial<UserPreferences> = { ...restPatch }
|
||||
if (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 }
|
||||
updates.tts = { ...currentPrefs.tts, ...tts }
|
||||
}
|
||||
if (patch.stt) {
|
||||
if (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 }
|
||||
updates.stt = { ...currentPrefs.stt, ...stt }
|
||||
}
|
||||
|
||||
const updated = settingsService.updateSettings(updates as Partial<UserPreferences>, userId)
|
||||
const updated = settingsService.updateSettings(updates, userId)
|
||||
return c.json(redactInternalSettings(updated))
|
||||
})
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { CredentialProvider } from '../../services/credential-provider'
|
||||
import type { RepoEnvService } from '../../services/repo-env'
|
||||
import type { RepoEnvResolver } from '../../services/repo-env'
|
||||
|
||||
export function createInternalShellEnvRoutes(db: Database, repoEnvService: RepoEnvService) {
|
||||
export function createInternalShellEnvRoutes(db: Database, repoEnvService: RepoEnvResolver) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', async (c) => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Hono } from 'hono'
|
||||
import { WalkthroughChangesParamsSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { ChangeWalkthroughService } from '../../services/change-walkthroughs'
|
||||
import type { ChangeWalkthroughRoutesService } from '../change-walkthroughs'
|
||||
import { handleServiceError, parseJsonBody } from '../../utils/route-helpers'
|
||||
import { ServiceError } from '../../utils/service-error'
|
||||
|
||||
export function createInternalWalkthroughSessionRoutes(service: ChangeWalkthroughService) {
|
||||
export function createInternalWalkthroughSessionRoutes(service: ChangeWalkthroughRoutesService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.post('/:sessionId/changes', async (c) => {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context, MiddlewareHandler } from 'hono'
|
||||
import { createServer } from 'node:net'
|
||||
import type { AddressInfo } from 'node:net'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
MCP_OAUTH_CALLBACK_PATH,
|
||||
@@ -73,13 +72,19 @@ function renderPage(heading: string, message: string, isSuccess: boolean): strin
|
||||
</html>`
|
||||
}
|
||||
|
||||
const AddressInfoSchema = z.object({ port: z.number() })
|
||||
|
||||
function probeLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = createServer()
|
||||
server.once('error', reject)
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const { port } = server.address() as AddressInfo
|
||||
server.close(() => resolve(port))
|
||||
const address = AddressInfoSchema.safeParse(server.address())
|
||||
if (!address.success) {
|
||||
reject(new Error('Failed to determine the MCP OAuth loopback callback port'))
|
||||
return
|
||||
}
|
||||
server.close(() => resolve(address.data.port))
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -115,9 +120,6 @@ export function createMcpOauthProxyRoutes(openCodeClient: OpenCodeClient, requir
|
||||
}
|
||||
}
|
||||
|
||||
// V2 binds the redirect URI's port on the OpenCode host's loopback for the lifetime of an attempt, so
|
||||
// the Manager's own port would collide. Re-add the server on a free loopback port before connecting;
|
||||
// the browser still reaches the Manager because the redirect URI stays the Manager's callback.
|
||||
const reserveCallbackPort = async (server: { name: string; integrationID?: string }, origin: string, directory: string | undefined) => {
|
||||
const port = await probeLoopbackPort()
|
||||
if (!server.integrationID) return port
|
||||
@@ -132,7 +134,7 @@ export function createMcpOauthProxyRoutes(openCodeClient: OpenCodeClient, requir
|
||||
config: {
|
||||
...v2Config,
|
||||
oauth: {
|
||||
...(v2Config.oauth === false ? {} : v2Config.oauth ?? {}),
|
||||
...(v2Config.oauth === false ? undefined : v2Config.oauth),
|
||||
redirect_uri: mcpOAuthRedirectUri(origin),
|
||||
callback_port: port,
|
||||
},
|
||||
@@ -258,8 +260,6 @@ export function createMcpOauthProxyRoutes(openCodeClient: OpenCodeClient, requir
|
||||
}
|
||||
|
||||
try {
|
||||
// Hand the code to the OpenCode host's loopback listener, which owns PKCE, the token exchange,
|
||||
// and the credential; the Manager only relays the browser's redirect.
|
||||
const callbackUrl = new URL(MCP_OAUTH_CALLBACK_PATH, `http://127.0.0.1:${flow.callbackPort}`)
|
||||
callbackUrl.searchParams.set('code', code)
|
||||
callbackUrl.searchParams.set('state', state)
|
||||
|
||||
@@ -19,7 +19,9 @@ function listTarget(repoId: string | undefined, serverId: string | undefined, di
|
||||
return { kind: 'repo', repoId: parseId(repoId, 'repoId', MultiRunError) }
|
||||
}
|
||||
|
||||
export function createMultiRunRoutes(service: MultiRunService) {
|
||||
export type MultiRunRoutesService = Pick<MultiRunService, 'discard' | 'fuse' | 'launch' | 'list'>
|
||||
|
||||
export function createMultiRunRoutes(service: MultiRunRoutesService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
|
||||
@@ -8,8 +8,18 @@ interface NotificationRouteVariables {
|
||||
session?: Session['session'];
|
||||
}
|
||||
|
||||
export type NotificationRoutesService = Pick<NotificationService,
|
||||
| 'getVapidPublicKey'
|
||||
| 'saveSubscription'
|
||||
| 'removeSubscription'
|
||||
| 'getSubscriptions'
|
||||
| 'removeSubscriptionById'
|
||||
| 'isConfigured'
|
||||
| 'sendTestNotification'
|
||||
>
|
||||
|
||||
export function createNotificationRoutes(
|
||||
notificationService: NotificationService
|
||||
notificationService: NotificationRoutesService
|
||||
) {
|
||||
const app = new Hono<{ Variables: NotificationRouteVariables }>();
|
||||
|
||||
|
||||
@@ -1,16 +1,34 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import { JsonValueSchema } from '@opencode-manager/shared/utils'
|
||||
import { OAuthAuthorizeResponseSchema, OAuthAttemptStatusSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { JsonValue } from '@opencode-manager/shared/utils'
|
||||
import { readJson } from '../../test/helpers/read-json'
|
||||
import { createOAuthRoutes } from './oauth'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import { FetchOpenCodeClient } from '../services/opencode/client'
|
||||
import { resolveOpenCode2Binary, startOpenCodeServe } from '../../test/helpers/opencode-binary'
|
||||
import { buildOpenCodeBasicAuth, ClientError } from '@opencode-manager/shared/opencode'
|
||||
import type { IntegrationInfo, IntegrationKeyMethod, IntegrationMethod, IntegrationOAuthMethod } from '@opencode-manager/shared/opencode'
|
||||
import type { OAuthAttemptStatus, OAuthAuthorizeResponse } from '@opencode-manager/shared/schemas'
|
||||
import type { IntegrationInfo, IntegrationMethod } from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
|
||||
const LOCATION = { directory: '/tmp/repo' }
|
||||
|
||||
const AuthMethodsResponseSchema = z.object({
|
||||
providers: z.record(z.string(), z.array(JsonValueSchema)),
|
||||
})
|
||||
|
||||
const StubMethodBodySchema = z.object({
|
||||
id: z.string().optional(),
|
||||
type: z.string(),
|
||||
form: z.array(z.object({ key: z.string() })).optional(),
|
||||
})
|
||||
|
||||
const IntegrationCatalogueSchema = z.object({
|
||||
providers: z.record(z.string(), z.array(StubMethodBodySchema)),
|
||||
})
|
||||
|
||||
function taggedError(tag: string, message: string): Error {
|
||||
return Object.assign(new Error(message), { _tag: tag })
|
||||
}
|
||||
@@ -31,7 +49,7 @@ function integrationFixture(overrides: Partial<IntegrationInfo> = {}): Integrati
|
||||
}
|
||||
}
|
||||
|
||||
function authorizeRequest(app: Hono, providerId = 'github-copilot', body: unknown = { methodID: 'device' }) {
|
||||
function authorizeRequest(app: Hono, providerId: string = 'github-copilot', body: JsonValue = { methodID: 'device' }) {
|
||||
return app.request(`/oauth/${providerId}/oauth/authorize`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -39,7 +57,7 @@ function authorizeRequest(app: Hono, providerId = 'github-copilot', body: unknow
|
||||
})
|
||||
}
|
||||
|
||||
function callbackRequest(app: Hono, providerId = 'github-copilot', body: unknown = { attemptID: 'con_stub' }) {
|
||||
function callbackRequest(app: Hono, providerId: string = 'github-copilot', body: JsonValue = { attemptID: 'con_stub' }) {
|
||||
return app.request(`/oauth/${providerId}/oauth/callback`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -106,7 +124,7 @@ describe('oauth routes /auth-methods', () => {
|
||||
const res = await createOAuthApp(client).request('/oauth/auth-methods')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { providers: Record<string, unknown> }
|
||||
const data = await readJson(res, AuthMethodsResponseSchema)
|
||||
expect(data.providers).toEqual({
|
||||
'github-copilot': [oauthMethod, envMethod],
|
||||
azure: [keyMethod],
|
||||
@@ -182,7 +200,7 @@ describe('oauth routes /:id/oauth/authorize', () => {
|
||||
const res = await authorizeRequest(createOAuthApp(client))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(((await res.json()) as OAuthAuthorizeResponse).attemptID).toBe('con_stub')
|
||||
expect((await readJson(res, OAuthAuthorizeResponseSchema)).attemptID).toBe('con_stub')
|
||||
expect(connect).toHaveBeenCalledTimes(2)
|
||||
expect(vi.mocked(client.api.integration.get)).toHaveBeenCalledWith({ integrationID: 'github-copilot' })
|
||||
})
|
||||
@@ -355,11 +373,9 @@ describe.skipIf(!openCodeBinary)('oauth routes against a real OpenCode 2 server'
|
||||
|
||||
const methodsResponse = await app.request('/oauth/auth-methods')
|
||||
expect(methodsResponse.status).toBe(200)
|
||||
const { providers } = (await methodsResponse.json()) as {
|
||||
providers: Record<string, IntegrationMethod[]>
|
||||
}
|
||||
const { providers } = await readJson(methodsResponse, IntegrationCatalogueSchema)
|
||||
const device = providers['github-copilot']?.find(
|
||||
(method): method is IntegrationOAuthMethod => method.type === 'oauth' && method.id === 'device',
|
||||
(method) => method.type === 'oauth' && method.id === 'device',
|
||||
)
|
||||
expect(device?.form?.map((field) => field.key)).toEqual(['deploymentType', 'enterpriseUrl'])
|
||||
expect(
|
||||
@@ -367,9 +383,7 @@ describe.skipIf(!openCodeBinary)('oauth routes against a real OpenCode 2 server'
|
||||
method.type === 'oauth' || method.type === 'command' ? method.id : method.type,
|
||||
),
|
||||
).toEqual(['key', 'env', 'device'])
|
||||
const azureKey = providers.azure?.find(
|
||||
(method): method is IntegrationKeyMethod => method.type === 'key',
|
||||
)
|
||||
const azureKey = providers.azure?.find((method) => method.type === 'key')
|
||||
expect(azureKey?.form?.map((field) => field.key)).toEqual(['resourceName'])
|
||||
|
||||
const authorizeResponse = await app.request('/oauth/github-copilot/oauth/authorize', {
|
||||
@@ -378,13 +392,13 @@ describe.skipIf(!openCodeBinary)('oauth routes against a real OpenCode 2 server'
|
||||
body: JSON.stringify({ methodID: 'device', answer: { deploymentType: 'github.com' } }),
|
||||
})
|
||||
expect(authorizeResponse.status).toBe(200)
|
||||
const attempt = (await authorizeResponse.json()) as OAuthAuthorizeResponse
|
||||
const attempt = await readJson(authorizeResponse, OAuthAuthorizeResponseSchema)
|
||||
expect(attempt.mode).toBe('auto')
|
||||
expect(attempt.url).toContain('github.com/login/device')
|
||||
|
||||
const statusResponse = await app.request(`/oauth/github-copilot/oauth/${attempt.attemptID}`)
|
||||
expect(statusResponse.status).toBe(200)
|
||||
expect((await statusResponse.json()) as OAuthAttemptStatus).toEqual({ status: 'pending' })
|
||||
expect(await readJson(statusResponse, OAuthAttemptStatusSchema)).toEqual({ status: 'pending' })
|
||||
|
||||
const cancelResponse = await app.request(`/oauth/github-copilot/oauth/${attempt.attemptID}`, {
|
||||
method: 'DELETE',
|
||||
|
||||
@@ -1,20 +1,55 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import { cloneRawRequest } from 'hono/request'
|
||||
import { parseJsonText } from '@opencode-manager/shared/utils'
|
||||
import { z } from 'zod'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
|
||||
export type OpenCodeProxyClient = Pick<OpenCodeClient, 'forwardRaw'>
|
||||
|
||||
export type OpenCodeLifecycleGate = Pick<typeof opencodeServerManager, 'isLifecycleInitialized'>
|
||||
|
||||
const RPC_PATH_SEGMENT = '/rpc/'
|
||||
const RPC_UNAVAILABLE_TYPE = 'rpc.unavailable'
|
||||
const RPC_WARMUP_RETRY_DELAY_MS = 300
|
||||
|
||||
const rpcErrorSchema = z.object({ type: z.string() })
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
|
||||
async function isWarmingRpcUnavailable(response: Response): Promise<boolean> {
|
||||
if (response.status !== 400) return false
|
||||
const body = await response.clone().text()
|
||||
const parsed = rpcErrorSchema.safeParse(parseJsonText(body))
|
||||
return parsed.success && parsed.data.type === RPC_UNAVAILABLE_TYPE
|
||||
}
|
||||
|
||||
export function createAuthenticatedOpenCodeProxyRoutes(
|
||||
openCodeClient: OpenCodeClient,
|
||||
openCodeClient: OpenCodeProxyClient,
|
||||
requireAuth: MiddlewareHandler,
|
||||
lifecycleGate: OpenCodeLifecycleGate = opencodeServerManager,
|
||||
): Hono {
|
||||
const app = new Hono()
|
||||
|
||||
app.all('/*', requireAuth, async (c) => {
|
||||
if (!opencodeServerManager.isLifecycleInitialized()) {
|
||||
if (!lifecycleGate.isLifecycleInitialized()) {
|
||||
return c.json({ error: 'OpenCode lifecycle initialization is incomplete; refusing to proxy to an unmanaged server' }, 503)
|
||||
}
|
||||
|
||||
return openCodeClient.forwardRaw(c.req.raw)
|
||||
if (!c.req.path.includes(RPC_PATH_SEGMENT)) {
|
||||
return openCodeClient.forwardRaw(c.req.raw)
|
||||
}
|
||||
|
||||
const retryRequest = await cloneRawRequest(c.req)
|
||||
const response = await openCodeClient.forwardRaw(c.req.raw)
|
||||
if (!(await isWarmingRpcUnavailable(response))) return response
|
||||
await delay(RPC_WARMUP_RETRY_DELAY_MS)
|
||||
return openCodeClient.forwardRaw(retryRequest)
|
||||
})
|
||||
|
||||
return app
|
||||
|
||||
@@ -33,6 +33,7 @@ import { logger } from '../utils/logger'
|
||||
|
||||
interface OpenCodeConfigRoutesOptions {
|
||||
redactSecrets?: boolean
|
||||
isRestartPending?: () => boolean
|
||||
}
|
||||
|
||||
async function readMcpStatus(openCodeClient: OpenCodeClient): Promise<McpStatusMap> {
|
||||
@@ -49,21 +50,14 @@ function mergeMcpServerStatus(views: McpServerView[], status: McpStatusMap) {
|
||||
return views.map((view) => {
|
||||
const live = status[view.name]
|
||||
if (!live) return view
|
||||
return {
|
||||
...view,
|
||||
status: live.status,
|
||||
...('error' in live && live.error ? { error: live.error } : {}),
|
||||
}
|
||||
const merged = { ...view, status: live.status }
|
||||
return 'error' in live && live.error ? { ...merged, error: live.error } : merged
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a config read failure to a JSON error response: 503 when the OpenCode server is unreachable,
|
||||
* 502 for other client errors, and 500 otherwise, using `message` as the client-facing text.
|
||||
*/
|
||||
function toClientReadErrorResponse(c: Context, error: unknown, message: string) {
|
||||
if (error instanceof ClientError) {
|
||||
if (error.reason === 'Transport') {
|
||||
function toClientReadErrorResponse(c: Context, cause: unknown, message: string) {
|
||||
if (cause instanceof ClientError) {
|
||||
if (cause.reason === 'Transport') {
|
||||
return c.json({ error: 'OpenCode server unavailable' }, 503)
|
||||
}
|
||||
return c.json({ error: message }, 502)
|
||||
@@ -71,18 +65,13 @@ function toClientReadErrorResponse(c: Context, error: unknown, message: string)
|
||||
return c.json({ error: message }, 500)
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves the OpenCode config read routes (`/`, `/effective`, `/managed`, `/mcp`) and the `PUT` and
|
||||
* `PATCH` write routes. Reads and writes take the shared config file lock, `redactSecrets` masks
|
||||
* secret values in every response, and a `PATCH` that names config entities is rejected with 409
|
||||
* while OpenCode has not yet loaded the saved configuration.
|
||||
*/
|
||||
export function createOpenCodeConfigRoutes(
|
||||
settingsService: SettingsService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
options: OpenCodeConfigRoutesOptions = {},
|
||||
) {
|
||||
const app = new Hono()
|
||||
const isRestartPending = options.isRestartPending ?? (() => opencodeServerManager.isRestartPending())
|
||||
|
||||
app.get('/', async (c) => {
|
||||
try {
|
||||
@@ -106,7 +95,7 @@ export function createOpenCodeConfigRoutes(
|
||||
entry.type === 'document'
|
||||
? {
|
||||
...entry,
|
||||
info: redactOpenCodeConfigContent(entry.info).content as typeof entry.info,
|
||||
info: redactOpenCodeConfigContent(entry.info).content,
|
||||
}
|
||||
: entry,
|
||||
)
|
||||
@@ -124,7 +113,7 @@ export function createOpenCodeConfigRoutes(
|
||||
const info = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
|
||||
return c.json({
|
||||
info: options.redactSecrets
|
||||
? redactOpenCodeConfigContent(info as Record<string, unknown>).content
|
||||
? redactOpenCodeConfigContent(info).content
|
||||
: info,
|
||||
})
|
||||
} catch (error) {
|
||||
@@ -186,7 +175,7 @@ export function createOpenCodeConfigRoutes(
|
||||
return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400)
|
||||
}
|
||||
|
||||
if (opencodeServerManager.isRestartPending() && patchNamesOpenCodeConfigEntities(parsed.data.patch)) {
|
||||
if (isRestartPending() && patchNamesOpenCodeConfigEntities(parsed.data.patch)) {
|
||||
return c.json({
|
||||
error: 'OpenCode has not loaded the saved configuration yet. Restart OpenCode before editing entries.',
|
||||
}, 409)
|
||||
@@ -205,11 +194,6 @@ export function createOpenCodeConfigRoutes(
|
||||
return app
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a validated config update and maps the outcome to a JSON response, redacting secrets when
|
||||
* `redactSecrets` is set and translating conflict, invalid-source, shadowed-removal, redacted-value
|
||||
* and schema-validation failures into their matching status codes.
|
||||
*/
|
||||
async function applyUpdate(
|
||||
c: Context,
|
||||
input: Parameters<typeof applyOpenCodeConfigUpdate>[0],
|
||||
@@ -221,10 +205,11 @@ async function applyUpdate(
|
||||
if (!redactSecrets) {
|
||||
return c.json(response.body, response.status)
|
||||
}
|
||||
return c.json({
|
||||
...redactOpenCodeConfigFile(result.config),
|
||||
...(result.status === 'restart_pending' ? { restartRequired: true } : {}),
|
||||
}, response.status)
|
||||
const redactedConfig = redactOpenCodeConfigFile(result.config)
|
||||
return c.json(
|
||||
result.status === 'restart_pending' ? { ...redactedConfig, restartRequired: true } : redactedConfig,
|
||||
response.status,
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error('Failed to update OpenCode config:', error)
|
||||
if (error instanceof OpenCodeConfigConflictError) {
|
||||
|
||||
@@ -3,6 +3,9 @@ import type { Context } from 'hono'
|
||||
import type { UpgradeWebSocket } from 'hono/ws'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { buildOpenCodeBasicAuth } from '@opencode-manager/shared/opencode'
|
||||
import { parseJsonText } from '@opencode-manager/shared/utils'
|
||||
import { z } from 'zod'
|
||||
import { parseJsonObject } from '@opencode-manager/shared/utils'
|
||||
import { createInternalTokenMiddleware } from '../auth/internal-token-middleware'
|
||||
import type { SettingsService } from '../services/settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
@@ -53,13 +56,6 @@ function isWebSocketUpgrade(c: Context): boolean {
|
||||
&& c.req.header('upgrade')?.toLowerCase() === 'websocket'
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches OpenCode's ticketed persistent PTY socket connects. WebSocket clients cannot
|
||||
* send an Authorization header, so these rely on the single-use ticket minted through the
|
||||
* authenticated proxy and validated by the upstream server. Only persistent PTY connects
|
||||
* are ticketed; OpenCode's /api/pty route builds per-directory services before it can
|
||||
* validate a ticket, so it must never bypass the internal token.
|
||||
*/
|
||||
function isTicketedPersistentPtyConnect(pathSuffix: string, searchParams: URLSearchParams): boolean {
|
||||
return PERSISTENT_PTY_CONNECT_PATH.test(pathSuffix) && !!searchParams.get('ticket')
|
||||
}
|
||||
@@ -73,11 +69,6 @@ function decodeDirectoryHeader(value: string | undefined): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a directory the Manager's OpenCode server owns (repos, OpenCode and schedule
|
||||
* worktrees, all under the workspace) and maps anything else, such as the attaching
|
||||
* client's local cwd, to the bound repo.
|
||||
*/
|
||||
function createRepoDirectoryResolver(repoPath: string): RepoDirectoryResolver {
|
||||
return (directory) => (directory && isPathWithinRoot(getWorkspacePath(), directory) ? directory : repoPath)
|
||||
}
|
||||
@@ -95,31 +86,24 @@ function rewriteRepoLocation(parts: ProxyRequestParts, directory: string, resolv
|
||||
}
|
||||
|
||||
function rewriteRepoLocationBody(bodyText: string, resolveDirectory: RepoDirectoryResolver): string | undefined {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(bodyText)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
const parsed = parseJsonObject(parseJsonText(bodyText))
|
||||
if (!parsed) return undefined
|
||||
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
|
||||
const location = parseJsonObject(parsed.location)
|
||||
if (!location) return undefined
|
||||
|
||||
const location = (parsed as { location?: unknown }).location
|
||||
if (!location || typeof location !== 'object' || Array.isArray(location)) return undefined
|
||||
|
||||
const requested = (location as { directory?: unknown }).directory
|
||||
const directory = resolveDirectory(typeof requested === 'string' ? requested : undefined)
|
||||
;(parsed as { location: Record<string, unknown> }).location = { ...location, directory }
|
||||
const requestedDirectory = z.string().safeParse(location.directory)
|
||||
location.directory = resolveDirectory(requestedDirectory.success ? requestedDirectory.data : undefined)
|
||||
parsed.location = location
|
||||
return JSON.stringify(parsed)
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves `/repos/:repoId/*` and `/*` by forwarding to the managed OpenCode server, rewriting repo
|
||||
* directory references in the path, query and JSON body. Every request needs the internal token
|
||||
* except a ticketed persistent PTY WebSocket connect, which is origin-checked and bridged to the
|
||||
* upstream socket.
|
||||
*/
|
||||
export function createOpenCodeProxyRoutes(db: Database, settingsService: SettingsService, upgradeWebSocket: UpgradeWebSocket) {
|
||||
export function createOpenCodeProxyRoutes(
|
||||
db: Database,
|
||||
settingsService: SettingsService,
|
||||
upgradeWebSocket: UpgradeWebSocket,
|
||||
getUpstreamBaseUrl: () => string = getOpenCodeUpstreamBaseUrl,
|
||||
) {
|
||||
const app = new Hono()
|
||||
const requireInternalToken = createInternalTokenMiddleware(db)
|
||||
|
||||
@@ -142,7 +126,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
const pathSuffix = stripProxyPrefix(url.pathname)
|
||||
let pending: PendingUpstream
|
||||
try {
|
||||
pending = await connectUpstreamWebSocket(toWebSocketUrl(`${getOpenCodeUpstreamBaseUrl()}${pathSuffix}${url.search}`))
|
||||
pending = await connectUpstreamWebSocket(toWebSocketUrl(`${getUpstreamBaseUrl()}${pathSuffix}${url.search}`))
|
||||
} catch {
|
||||
return c.json({ error: 'PTY connection rejected' }, 403)
|
||||
}
|
||||
@@ -151,11 +135,6 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
return (await upgrade(c, async () => {})) ?? c.body(null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Forwards the current request to the managed OpenCode server with basic auth and a default
|
||||
* directory, letting the optional rewrites adjust path, query and JSON body first. Returns 503
|
||||
* before lifecycle initialization, 501 for non-PTY upgrades and 502 when the upstream call fails.
|
||||
*/
|
||||
async function forwardToOpenCode(
|
||||
c: Context,
|
||||
pathSuffix: string,
|
||||
@@ -201,7 +180,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
requestBody = rewrittenBody === undefined ? rawBody : rewrittenBody
|
||||
}
|
||||
|
||||
const upstreamUrl = `${getOpenCodeUpstreamBaseUrl()}${pathSuffix}${url.search}`
|
||||
const upstreamUrl = `${getUpstreamBaseUrl()}${pathSuffix}${url.search}`
|
||||
|
||||
try {
|
||||
return await forwardProxyRequest({
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import {
|
||||
OpenCodeServerError,
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
import { filterProxyHeaders } from '../utils/proxy-headers'
|
||||
import { forwardProxyRequest, ProxyHeadersTimeoutError } from '../utils/proxy-forward'
|
||||
import { logger } from '../utils/logger'
|
||||
import { toContentfulStatus } from '../utils/error-utils'
|
||||
|
||||
const MOUNT_PREFIX = '/api/opencode/servers/'
|
||||
const REQUEST_EXCLUDED_HEADERS = new Set(['cookie', 'origin', 'referer'])
|
||||
@@ -42,10 +42,6 @@ function decodePathSegments(path: string): string[] | null {
|
||||
return segments
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the upstream path for a request mounted at `/api/opencode/servers`.
|
||||
* Only OpenCode API paths are forwardable, and encoded traversal segments are refused.
|
||||
*/
|
||||
function resolveUpstreamPath(pathname: string): UpstreamPath {
|
||||
const remainder = pathname.slice(MOUNT_PREFIX.length)
|
||||
const separator = remainder.indexOf('/')
|
||||
@@ -59,11 +55,6 @@ function resolveUpstreamPath(pathname: string): UpstreamPath {
|
||||
|
||||
type UpstreamTarget = { basePath: string; url: URL }
|
||||
|
||||
/**
|
||||
* Builds the upstream URL for a resolved API path. The returned `basePath` is the
|
||||
* connection base path without trailing slashes and is used to bound the final,
|
||||
* URL-normalized pathname to the connection's own `/api/` space.
|
||||
*/
|
||||
function resolveUpstreamTarget(
|
||||
connection: OpenCodeServerConnection,
|
||||
path: string,
|
||||
@@ -80,11 +71,6 @@ function isWithinUpstreamApiPath(basePath: string, pathname: string): boolean {
|
||||
return pathname.startsWith(`${basePath}/api/`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves `/:serverId/*` behind `requireAuth`, proxying each request to the registry-resolved remote
|
||||
* OpenCode server while keeping the normalized upstream pathname inside that connection's own `/api/`
|
||||
* space. Maps an upstream header timeout to 504 and an unreachable server to 502.
|
||||
*/
|
||||
export function createOpenCodeServerProxyRoutes(
|
||||
registry: OpenCodeServerRegistry,
|
||||
requireAuth: MiddlewareHandler,
|
||||
@@ -107,7 +93,7 @@ export function createOpenCodeServerProxyRoutes(
|
||||
connection = registry.getConnection(c.req.param('serverId'))
|
||||
} catch (error) {
|
||||
if (error instanceof OpenCodeServerError) {
|
||||
return c.json({ error: error.message }, error.status as ContentfulStatusCode)
|
||||
return c.json({ error: error.message }, toContentfulStatus(error.status))
|
||||
}
|
||||
logger.error('Failed to resolve OpenCode server connection', error)
|
||||
return c.json({ error: 'Failed to proxy request' }, 500)
|
||||
|
||||
@@ -42,14 +42,14 @@ function rejectDirectory(c: Context): Response {
|
||||
return c.json({ error: 'An absolute directory is required' }, 400)
|
||||
}
|
||||
|
||||
function handleTerminalError(c: Context, error: unknown) {
|
||||
if (error instanceof TerminalNotFoundError) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
function handleTerminalError(c: Context, cause: unknown) {
|
||||
if (cause instanceof TerminalNotFoundError) {
|
||||
return c.json({ error: cause.message }, 404)
|
||||
}
|
||||
if (error instanceof OpenCodeServerError) {
|
||||
return handleServiceError(c, error, 'Terminal request failed', OpenCodeServerError)
|
||||
if (cause instanceof OpenCodeServerError) {
|
||||
return handleServiceError(c, cause, 'Terminal request failed', OpenCodeServerError)
|
||||
}
|
||||
return handleOpenCodeError(c, error, 'Terminal request failed')
|
||||
return handleOpenCodeError(c, cause, 'Terminal request failed')
|
||||
}
|
||||
|
||||
export function createOpenCodeServerTerminalRoutes(resolveTerminalService: ServerTerminalServiceResolver) {
|
||||
|
||||
@@ -12,11 +12,6 @@ export interface PreviewAvailability {
|
||||
markUnavailable: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks whether the preview gateway is usable at request time. It starts in
|
||||
* the given state and is flipped by the server lifecycle: available once the
|
||||
* port is bound, unavailable after a bind error.
|
||||
*/
|
||||
export function createPreviewAvailability(initialEnabled: boolean): PreviewAvailability {
|
||||
let enabled = initialEnabled
|
||||
return {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env'
|
||||
import { JsonObjectSchema } from '@opencode-manager/shared/utils'
|
||||
import type { JsonObject, JsonValue } from '@opencode-manager/shared/utils'
|
||||
import { createProvidersRoutes } from './providers'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import { FetchOpenCodeClient } from '../services/opencode/client'
|
||||
@@ -11,36 +14,24 @@ import { buildOpenCodeBasicAuth } from '@opencode-manager/shared/opencode'
|
||||
import { ClientError } from '@opencode-manager/shared/opencode'
|
||||
import type { IntegrationInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import type { ModelPreferenceDocument } from '@opencode-manager/shared/opencode'
|
||||
|
||||
const modelStatePaths = vi.hoisted(() => ({ file: '' }))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@opencode-manager/shared/config/env')>()
|
||||
return {
|
||||
...actual,
|
||||
getOpenCodeModelStatePath: () => modelStatePaths.file,
|
||||
}
|
||||
})
|
||||
|
||||
const modelStateMock = vi.hoisted(() => ({
|
||||
readOpenCodeModelState: vi.fn(),
|
||||
updateOpenCodeModelState: vi.fn(),
|
||||
actual: undefined as unknown,
|
||||
}))
|
||||
|
||||
vi.mock('../services/opencode-model-state', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../services/opencode-model-state')>()
|
||||
modelStateMock.actual = actual
|
||||
return {
|
||||
...actual,
|
||||
readOpenCodeModelState: modelStateMock.readOpenCodeModelState,
|
||||
updateOpenCodeModelState: modelStateMock.updateOpenCodeModelState,
|
||||
}
|
||||
})
|
||||
import { createTempWorkspace, type TempWorkspace } from '../../test/helpers/test-env'
|
||||
import { readJson } from '../../test/helpers/read-json'
|
||||
|
||||
const LOCATION = { directory: '/tmp/repo' }
|
||||
|
||||
const ModelSelectionBodySchema = z.object({ providerID: z.string(), modelID: z.string() })
|
||||
|
||||
const ModelPreferenceResponseSchema = z.object({
|
||||
recent: z.array(ModelSelectionBodySchema),
|
||||
favorite: z.array(ModelSelectionBodySchema),
|
||||
variant: z.record(z.string(), z.string().optional()),
|
||||
})
|
||||
|
||||
const CredentialListResponseSchema = z.object({ providers: z.array(z.string()) })
|
||||
const CredentialStatusResponseSchema = z.object({ hasCredentials: z.boolean() })
|
||||
const SuccessResponseSchema = z.object({ success: z.boolean() })
|
||||
const ErrorResponseSchema = z.object({ error: z.string(), code: z.string().optional() })
|
||||
|
||||
function integrationFixture(overrides: Partial<IntegrationInfo> = {}): IntegrationInfo {
|
||||
return {
|
||||
id: 'anthropic',
|
||||
@@ -71,189 +62,139 @@ function createCredentialApp(client: OpenCodeClient): Hono {
|
||||
return app
|
||||
}
|
||||
|
||||
async function postModelState(app: Hono, body: JsonValue): Promise<Response> {
|
||||
return app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
describe('providers routes', () => {
|
||||
let app: Hono
|
||||
let storedState: ModelPreferenceDocument
|
||||
let workspace: TempWorkspace
|
||||
let modelStatePath: string
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
storedState = { recent: [], favorite: [], variant: {} }
|
||||
modelStateMock.readOpenCodeModelState.mockImplementation(async () => storedState)
|
||||
modelStateMock.updateOpenCodeModelState.mockImplementation(
|
||||
async (mutate: (state: ModelPreferenceDocument) => ModelPreferenceDocument) => {
|
||||
storedState = mutate(storedState)
|
||||
return storedState
|
||||
},
|
||||
)
|
||||
workspace = createTempWorkspace('providers-model-state-')
|
||||
modelStatePath = getOpenCodeModelStatePath()
|
||||
app = createTestApp()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
workspace.restore()
|
||||
})
|
||||
|
||||
describe('GET /model-state', () => {
|
||||
it('returns the state owned by the service', async () => {
|
||||
it('returns the empty state when no file has been written', async () => {
|
||||
const res = await app.request('/providers/model-state')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { recent: unknown[]; favorite: unknown[]; variant: Record<string, unknown> }
|
||||
expect(data).toEqual({ recent: [], favorite: [], variant: {} })
|
||||
expect(modelStateMock.readOpenCodeModelState).toHaveBeenCalledTimes(1)
|
||||
expect(await readJson(res, ModelPreferenceResponseSchema)).toEqual({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /model-state', () => {
|
||||
it('with recent returns 200 with recent[0] set', async () => {
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ recent: { providerID: 'anthropic', modelID: 'claude' } }),
|
||||
})
|
||||
const res = await postModelState(app, { recent: { providerID: 'anthropic', modelID: 'claude' } })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { recent: Array<{ providerID: string; modelID: string }> }
|
||||
const data = await readJson(res, ModelPreferenceResponseSchema)
|
||||
expect(data.recent).toHaveLength(1)
|
||||
expect(data.recent[0]).toEqual({ providerID: 'anthropic', modelID: 'claude' })
|
||||
})
|
||||
|
||||
it('with removeRecent removes the model', async () => {
|
||||
storedState = {
|
||||
recent: [{ providerID: 'openai', modelID: 'gpt-4' }],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
}
|
||||
await postModelState(app, { recent: { providerID: 'openai', modelID: 'gpt-4' } })
|
||||
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ removeRecent: { providerID: 'openai', modelID: 'gpt-4' } }),
|
||||
})
|
||||
const res = await postModelState(app, { removeRecent: { providerID: 'openai', modelID: 'gpt-4' } })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { recent: Array<{ providerID: string; modelID: string }> }
|
||||
expect(data.recent).toHaveLength(0)
|
||||
expect((await readJson(res, ModelPreferenceResponseSchema)).recent).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('with favorite toggles favorite (add then remove)', async () => {
|
||||
const body = { favorite: { providerID: 'openai', modelID: 'gpt-4' } }
|
||||
|
||||
const res1 = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const res1 = await postModelState(app, body)
|
||||
expect(res1.status).toBe(200)
|
||||
const data1 = (await res1.json()) as { favorite: Array<{ providerID: string; modelID: string }> }
|
||||
expect(data1.favorite).toHaveLength(1)
|
||||
expect((await readJson(res1, ModelPreferenceResponseSchema)).favorite).toHaveLength(1)
|
||||
|
||||
const res2 = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const res2 = await postModelState(app, body)
|
||||
expect(res2.status).toBe(200)
|
||||
const data2 = (await res2.json()) as { favorite: Array<{ providerID: string; modelID: string }> }
|
||||
expect(data2.favorite).toHaveLength(0)
|
||||
expect((await readJson(res2, ModelPreferenceResponseSchema)).favorite).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('with variant persists the named variant', async () => {
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
variant: { model: { providerID: 'anthropic', modelID: 'claude' }, value: 'high' },
|
||||
}),
|
||||
const res = await postModelState(app, {
|
||||
variant: { model: { providerID: 'anthropic', modelID: 'claude' }, value: 'high' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { variant: Record<string, string | undefined> }
|
||||
expect(data.variant).toEqual({ 'anthropic/claude': 'high' })
|
||||
expect((await readJson(res, ModelPreferenceResponseSchema)).variant).toEqual({ 'anthropic/claude': 'high' })
|
||||
})
|
||||
|
||||
it('with variant value omitted or null persists default', async () => {
|
||||
const model = { providerID: 'anthropic', modelID: 'claude' }
|
||||
const variantCases: Array<{ label: string; variant: JsonObject }> = [
|
||||
{ label: 'omitted', variant: { model: { providerID: 'anthropic', modelID: 'claude' } } },
|
||||
{ label: 'explicitly null', variant: { model: { providerID: 'anthropic', modelID: 'claude' }, value: null } },
|
||||
]
|
||||
|
||||
const omitted = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ variant: { model } }),
|
||||
})
|
||||
expect(omitted.status).toBe(200)
|
||||
expect(((await omitted.json()) as { variant: Record<string, string | undefined> }).variant).toEqual({
|
||||
'anthropic/claude': 'default',
|
||||
})
|
||||
it.each(variantCases)('with variant value $label persists default', async ({ variant }) => {
|
||||
const res = await postModelState(app, { variant })
|
||||
|
||||
const explicitNull = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ variant: { model, value: null } }),
|
||||
})
|
||||
expect(explicitNull.status).toBe(200)
|
||||
expect(((await explicitNull.json()) as { variant: Record<string, string | undefined> }).variant).toEqual({
|
||||
expect(res.status).toBe(200)
|
||||
expect((await readJson(res, ModelPreferenceResponseSchema)).variant).toEqual({
|
||||
'anthropic/claude': 'default',
|
||||
})
|
||||
})
|
||||
|
||||
it('with invalid body returns 400', async () => {
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ invalid: 'data' }),
|
||||
})
|
||||
it('with invalid body returns 400 and leaves the state untouched', async () => {
|
||||
const res = await postModelState(app, { invalid: 'data' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const data = (await res.json()) as { error: string }
|
||||
expect(data.error).toBe('Invalid request data')
|
||||
expect(modelStateMock.updateOpenCodeModelState).not.toHaveBeenCalled()
|
||||
expect((await readJson(res, ErrorResponseSchema)).error).toBe('Invalid request data')
|
||||
const state = await app.request('/providers/model-state')
|
||||
expect(await readJson(state, ModelPreferenceResponseSchema)).toEqual({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 500 when the service rejects', async () => {
|
||||
modelStateMock.updateOpenCodeModelState.mockRejectedValueOnce(new Error('disk full'))
|
||||
it('returns 500 when the state file cannot be written', async () => {
|
||||
await mkdir(modelStatePath, { recursive: true })
|
||||
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ recent: { providerID: 'test', modelID: 'test' } }),
|
||||
})
|
||||
const res = await postModelState(app, { recent: { providerID: 'test', modelID: 'test' } })
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
const data = (await res.json()) as { error: string }
|
||||
expect(data.error).toBe('Failed to update OpenCode model state')
|
||||
expect((await readJson(res, ErrorResponseSchema)).error).toBe('Failed to update OpenCode model state')
|
||||
})
|
||||
})
|
||||
|
||||
describe('model-state response contract', () => {
|
||||
let workDir: string
|
||||
|
||||
beforeEach(async () => {
|
||||
workDir = await mkdtemp(path.join(tmpdir(), 'providers-model-state-'))
|
||||
modelStatePaths.file = path.join(workDir, 'model.json')
|
||||
const actual = modelStateMock.actual as typeof import('../services/opencode-model-state')
|
||||
modelStateMock.readOpenCodeModelState.mockImplementation(actual.readOpenCodeModelState)
|
||||
modelStateMock.updateOpenCodeModelState.mockImplementation(actual.updateOpenCodeModelState)
|
||||
await writeFile(
|
||||
modelStatePaths.file,
|
||||
JSON.stringify({ recent: [], favorite: [], variant: {}, extra: 1 }),
|
||||
'utf8',
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(workDir, { recursive: true, force: true })
|
||||
await mkdir(path.dirname(modelStatePath), { recursive: true })
|
||||
await writeFile(modelStatePath, JSON.stringify({ recent: [], favorite: [], variant: {}, extra: 1 }), 'utf8')
|
||||
})
|
||||
|
||||
it('GET omits unknown root keys', async () => {
|
||||
const res = await app.request('/providers/model-state')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as Record<string, unknown>
|
||||
const data = await readJson(res, ModelPreferenceResponseSchema)
|
||||
expect(data).toEqual({ recent: [], favorite: [], variant: {} })
|
||||
expect(data).not.toHaveProperty('extra')
|
||||
})
|
||||
|
||||
it('POST omits unknown root keys from the response but preserves them in the file', async () => {
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ recent: { providerID: 'anthropic', modelID: 'claude' } }),
|
||||
})
|
||||
const res = await postModelState(app, { recent: { providerID: 'anthropic', modelID: 'claude' } })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as Record<string, unknown>
|
||||
const data = await readJson(res, ModelPreferenceResponseSchema)
|
||||
expect(data).toEqual({
|
||||
recent: [{ providerID: 'anthropic', modelID: 'claude' }],
|
||||
favorite: [],
|
||||
@@ -261,7 +202,7 @@ describe('providers routes', () => {
|
||||
})
|
||||
expect(data).not.toHaveProperty('extra')
|
||||
|
||||
const file = JSON.parse(await readFile(modelStatePaths.file, 'utf8')) as { extra: unknown }
|
||||
const file = JsonObjectSchema.parse(JSON.parse(await readFile(modelStatePath, 'utf8')))
|
||||
expect(file.extra).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -280,7 +221,7 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/credentials')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ providers: ['anthropic'] })
|
||||
expect(await readJson(res, CredentialListResponseSchema)).toEqual({ providers: ['anthropic'] })
|
||||
})
|
||||
|
||||
it('maps a declared upstream error to 502 with the upstream message', async () => {
|
||||
@@ -292,7 +233,7 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/credentials')
|
||||
|
||||
expect(res.status).toBe(502)
|
||||
expect(await res.json()).toEqual({ error: 'upstream exploded' })
|
||||
expect(await readJson(res, ErrorResponseSchema)).toEqual({ error: 'upstream exploded' })
|
||||
})
|
||||
|
||||
it('maps an unreachable upstream to 502', async () => {
|
||||
@@ -302,7 +243,10 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/credentials')
|
||||
|
||||
expect(res.status).toBe(502)
|
||||
expect(await res.json()).toEqual({ error: 'Failed to list provider credentials', code: 'ClientError' })
|
||||
expect(await readJson(res, ErrorResponseSchema)).toEqual({
|
||||
error: 'Failed to list provider credentials',
|
||||
code: 'ClientError',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -317,7 +261,7 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/anthropic/credentials/status')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ hasCredentials: true })
|
||||
expect(await readJson(res, CredentialStatusResponseSchema)).toEqual({ hasCredentials: true })
|
||||
})
|
||||
|
||||
it('reports false when the integration only has env connections', async () => {
|
||||
@@ -330,7 +274,7 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/anthropic/credentials/status')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ hasCredentials: false })
|
||||
expect(await readJson(res, CredentialStatusResponseSchema)).toEqual({ hasCredentials: false })
|
||||
})
|
||||
|
||||
it('retries once after a loading integration becomes available', async () => {
|
||||
@@ -345,7 +289,7 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/anthropic/credentials/status')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ hasCredentials: true })
|
||||
expect(await readJson(res, CredentialStatusResponseSchema)).toEqual({ hasCredentials: true })
|
||||
expect(get).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
@@ -362,7 +306,7 @@ describe('providers routes', () => {
|
||||
const res = await pending
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({
|
||||
expect(await readJson(res, ErrorResponseSchema)).toEqual({
|
||||
error: 'Integration not found: nope',
|
||||
code: 'IntegrationNotFoundError',
|
||||
})
|
||||
@@ -373,7 +317,7 @@ describe('providers routes', () => {
|
||||
})
|
||||
|
||||
describe('POST /:id/credentials', () => {
|
||||
function connectRequest(app: Hono, providerId = 'anthropic', body: unknown = { apiKey: 'sk-test' }) {
|
||||
function connectRequest(app: Hono, providerId: string = 'anthropic', body: JsonValue = { apiKey: 'sk-test' }) {
|
||||
return app.request(`/providers/${providerId}/credentials`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -388,7 +332,7 @@ describe('providers routes', () => {
|
||||
const res = await connectRequest(createCredentialApp(client))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
expect(await readJson(res, SuccessResponseSchema)).toEqual({ success: true })
|
||||
expect(connectKey).toHaveBeenCalledWith({ integrationID: 'anthropic', key: 'sk-test' })
|
||||
})
|
||||
|
||||
@@ -402,7 +346,7 @@ describe('providers routes', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
expect(await readJson(res, SuccessResponseSchema)).toEqual({ success: true })
|
||||
expect(connectKey).toHaveBeenCalledWith({
|
||||
integrationID: 'azure',
|
||||
key: 'az-test',
|
||||
@@ -427,7 +371,7 @@ describe('providers routes', () => {
|
||||
const res = await connectRequest(createCredentialApp(client))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
expect(await readJson(res, SuccessResponseSchema)).toEqual({ success: true })
|
||||
expect(connectKey).toHaveBeenCalledTimes(2)
|
||||
expect(vi.mocked(client.api.integration.get)).toHaveBeenCalledWith({ integrationID: 'anthropic' })
|
||||
})
|
||||
@@ -445,7 +389,7 @@ describe('providers routes', () => {
|
||||
const res = await pending
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({
|
||||
expect(await readJson(res, ErrorResponseSchema)).toEqual({
|
||||
error: 'Integration not found: nope',
|
||||
code: 'IntegrationNotFoundError',
|
||||
})
|
||||
@@ -464,7 +408,7 @@ describe('providers routes', () => {
|
||||
const res = await connectRequest(createCredentialApp(client))
|
||||
|
||||
expect(res.status).toBe(502)
|
||||
expect(await res.json()).toEqual({
|
||||
expect(await readJson(res, ErrorResponseSchema)).toEqual({
|
||||
error: 'Missing required form field: account',
|
||||
code: 'InvalidRequestError',
|
||||
})
|
||||
@@ -485,7 +429,7 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/anthropic/credentials', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
expect(await readJson(res, SuccessResponseSchema)).toEqual({ success: true })
|
||||
expect(remove).toHaveBeenCalledTimes(2)
|
||||
expect(remove).toHaveBeenCalledWith({ credentialID: 'cred_1' })
|
||||
expect(remove).toHaveBeenCalledWith({ credentialID: 'cred_2' })
|
||||
@@ -516,7 +460,7 @@ describe('providers routes', () => {
|
||||
const res = await createCredentialApp(client).request('/providers/anthropic/credentials', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
expect(await readJson(res, SuccessResponseSchema)).toEqual({ success: true })
|
||||
expect(vi.mocked(client.api.credential.remove)).toHaveBeenCalledWith({ credentialID: 'cred_1' })
|
||||
expect(get).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
@@ -534,7 +478,7 @@ describe('providers routes', () => {
|
||||
const res = await pending
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({
|
||||
expect(await readJson(res, ErrorResponseSchema)).toEqual({
|
||||
error: 'Integration not found: nope',
|
||||
code: 'IntegrationNotFoundError',
|
||||
})
|
||||
@@ -569,11 +513,11 @@ describe.skipIf(!openCodeBinary)('providers routes against a real OpenCode 2 ser
|
||||
|
||||
const statusResponse = await app.request('/providers/anthropic/credentials/status')
|
||||
expect(statusResponse.status).toBe(200)
|
||||
expect(await statusResponse.json()).toEqual({ hasCredentials: true })
|
||||
expect(await readJson(statusResponse, CredentialStatusResponseSchema)).toEqual({ hasCredentials: true })
|
||||
|
||||
const listResponse = await app.request('/providers/credentials')
|
||||
expect(listResponse.status).toBe(200)
|
||||
const { providers } = (await listResponse.json()) as { providers: string[] }
|
||||
const { providers } = await readJson(listResponse, CredentialListResponseSchema)
|
||||
expect(providers).toContain('anthropic')
|
||||
} finally {
|
||||
await serve.stop()
|
||||
@@ -598,7 +542,7 @@ describe.skipIf(!openCodeBinary)('providers routes against a real OpenCode 2 ser
|
||||
body: JSON.stringify({ apiKey: 'az-binary-test' }),
|
||||
})
|
||||
expect(rejected.status).toBe(502)
|
||||
expect(await rejected.json()).toEqual({
|
||||
expect(await readJson(rejected, ErrorResponseSchema)).toEqual({
|
||||
error: 'Missing required form field: resourceName',
|
||||
code: 'InvalidRequestError',
|
||||
})
|
||||
@@ -612,7 +556,7 @@ describe.skipIf(!openCodeBinary)('providers routes against a real OpenCode 2 ser
|
||||
|
||||
const statusResponse = await app.request('/providers/azure/credentials/status')
|
||||
expect(statusResponse.status).toBe(200)
|
||||
expect(await statusResponse.json()).toEqual({ hasCredentials: true })
|
||||
expect(await readJson(statusResponse, CredentialStatusResponseSchema)).toEqual({ hasCredentials: true })
|
||||
} finally {
|
||||
await serve.stop()
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { runWhenIntegrationReady } from '../services/opencode/integration-ready'
|
||||
|
||||
type IntegrationConnectKeyInput = NonNullable<Parameters<OpenCodeClient['api']['integration']['connect']['key']>[0]>
|
||||
import {
|
||||
ModelSelectionSchema,
|
||||
readOpenCodeModelState,
|
||||
@@ -106,12 +108,13 @@ export function createProvidersRoutes(openCodeClient: OpenCodeClient) {
|
||||
const validated = SetCredentialRequestSchema.parse(body)
|
||||
|
||||
const integrationID = c.req.param('id')
|
||||
const connectInput: IntegrationConnectKeyInput = {
|
||||
integrationID,
|
||||
key: validated.apiKey,
|
||||
answer: validated.answer,
|
||||
}
|
||||
await runWhenIntegrationReady(openCodeClient.api, { integrationID }, () =>
|
||||
openCodeClient.api.integration.connect.key({
|
||||
integrationID,
|
||||
key: validated.apiKey,
|
||||
...(validated.answer ? { answer: validated.answer } : {}),
|
||||
}),
|
||||
openCodeClient.api.integration.connect.key(connectInput),
|
||||
)
|
||||
|
||||
return c.json({ success: true })
|
||||
|
||||
@@ -6,6 +6,7 @@ import { logger } from '../utils/logger'
|
||||
import { parseJsonBody, respondWithGitError } from '../utils/route-helpers'
|
||||
import { buildCommitMessagePrompt, normalizeGeneratedCommitMessage } from '../services/git/commit-message-prompt'
|
||||
import type { CommitMessageContext } from '../services/git/commit-message-prompt'
|
||||
import { z } from 'zod'
|
||||
import { RenameBranchRequestSchema, DeleteBranchRequestSchema, StashPushRequestSchema, StashApplyRequestSchema, StashDropRequestSchema, IntegrateBranchRequestSchema } from '@opencode-manager/shared'
|
||||
import type { GitService } from '../services/git/GitService'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
@@ -16,6 +17,10 @@ import { getErrorMessage } from '../utils/error-utils'
|
||||
|
||||
const DEFAULT_COMMIT_MESSAGE_TIMEOUT_MS = 30_000
|
||||
|
||||
const RepoIdsBodySchema = z.object({
|
||||
repoIds: z.array(z.number()),
|
||||
})
|
||||
|
||||
export interface RepoGitRouteOptions {
|
||||
commitMessageTimeoutMs?: number
|
||||
}
|
||||
@@ -64,11 +69,12 @@ export function createRepoGitRoutes(
|
||||
app.post('/git-status-batch', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { repoIds } = body
|
||||
const parsedBody = RepoIdsBodySchema.safeParse(body)
|
||||
|
||||
if (!Array.isArray(repoIds) || repoIds.some((id: unknown) => typeof id !== 'number')) {
|
||||
if (!parsedBody.success) {
|
||||
return c.json({ error: 'repoIds must be an array of numbers' }, 400)
|
||||
}
|
||||
const repoIds = parsedBody.data.repoIds
|
||||
|
||||
const BATCH_CONCURRENCY = 3
|
||||
const results: Array<[number, GitStatusResponse] | null> = []
|
||||
@@ -78,7 +84,8 @@ export function createRepoGitRoutes(
|
||||
batch.map(async (id) => {
|
||||
try {
|
||||
const status = await git.getStatus(id, database)
|
||||
return [id, status] as [number, GitStatusResponse]
|
||||
const result: [number, GitStatusResponse] = [id, status]
|
||||
return result
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to get git status for repo ${id}:`, error)
|
||||
return null
|
||||
@@ -271,6 +278,11 @@ export function createRepoGitRoutes(
|
||||
}
|
||||
|
||||
const diff = await git.getCommitDiff(id, hash, filePath, database)
|
||||
|
||||
if (!diff) {
|
||||
return c.json({ error: 'Commit not found' }, 404)
|
||||
}
|
||||
|
||||
return c.json(diff)
|
||||
}))
|
||||
|
||||
|
||||
+431
-367
File diff suppressed because it is too large.
Load diff
+26
-18
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { Readable } from 'node:stream'
|
||||
import { z } from 'zod'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { DeleteRepoResult, Repo } from '@opencode-manager/shared/types'
|
||||
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema, UpdateRepoRequestSchema, CreateRepoWorkspaceRequestSchema, DeleteRepoRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
@@ -34,6 +34,18 @@ const DeleteWorkspaceRequestSchema = z.object({
|
||||
directory: z.string().trim().min(1),
|
||||
})
|
||||
|
||||
const RepoOrderBodySchema = z.object({
|
||||
order: z.array(z.number()),
|
||||
})
|
||||
|
||||
const RepoGitCredentialBodySchema = z.object({
|
||||
credentialId: z.string().optional(),
|
||||
})
|
||||
|
||||
const RepoGitIdentityBodySchema = z.object({
|
||||
identityId: z.string().optional(),
|
||||
})
|
||||
|
||||
function withRepoSettings(database: Database, repo: Repo): Repo {
|
||||
return {
|
||||
...repo,
|
||||
@@ -41,11 +53,6 @@ function withRepoSettings(database: Database, repo: Repo): Repo {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts the repo git, terminal, project-config, schedule and secret/variable sub-routers, and serves
|
||||
* repo CRUD with discovery, ordering, access, credential, identity, workspace, pull/branch, download
|
||||
* and assistant-mode routes. Handler failures are mapped to their status codes with a JSON message.
|
||||
*/
|
||||
export function createRepoRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
@@ -104,7 +111,7 @@ export function createRepoRoutes(
|
||||
return c.json(repo)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create repo:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -127,7 +134,7 @@ export function createRepoRoutes(
|
||||
return c.json(discovery)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to discover repos:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -154,14 +161,15 @@ app.get('/', async (c) => {
|
||||
app.put('/order', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const parsedBody = RepoOrderBodySchema.safeParse(body)
|
||||
|
||||
if (!Array.isArray(body.order) || body.order.some((id: unknown) => typeof id !== 'number')) {
|
||||
if (!parsedBody.success) {
|
||||
return c.json({ error: 'order must be an array of numbers' }, 400)
|
||||
}
|
||||
|
||||
const settingsService = new SettingsService(database)
|
||||
settingsService.updateSettings({
|
||||
repoOrder: body.order,
|
||||
repoOrder: parsedBody.data.order,
|
||||
})
|
||||
|
||||
return c.json({ success: true })
|
||||
@@ -235,9 +243,9 @@ app.get('/', async (c) => {
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const credentialId = typeof body.credentialId === 'string' && body.credentialId.trim() !== ''
|
||||
? body.credentialId.trim()
|
||||
: null
|
||||
const parsedBody = RepoGitCredentialBodySchema.safeParse(body)
|
||||
const requestedCredentialId = parsedBody.success ? parsedBody.data.credentialId?.trim() : undefined
|
||||
const credentialId = requestedCredentialId ? requestedCredentialId : null
|
||||
|
||||
if (credentialId) {
|
||||
const settingsService = new SettingsService(database)
|
||||
@@ -281,9 +289,9 @@ app.get('/', async (c) => {
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const identityId = typeof body.identityId === 'string' && body.identityId.trim() !== ''
|
||||
? body.identityId.trim()
|
||||
: null
|
||||
const parsedBody = RepoGitIdentityBodySchema.safeParse(body)
|
||||
const requestedIdentityId = parsedBody.success ? parsedBody.data.identityId?.trim() : undefined
|
||||
const identityId = requestedIdentityId ? requestedIdentityId : null
|
||||
|
||||
let preset: { name: string; email: string } | null = null
|
||||
if (identityId) {
|
||||
@@ -508,7 +516,7 @@ app.get('/', async (c) => {
|
||||
return c.json({ ...updatedRepo, currentBranch })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create branch:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(error) }, getStatusCode(error))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -546,7 +554,7 @@ app.get('/', async (c) => {
|
||||
archiveService.deleteArchive(archivePath)
|
||||
})
|
||||
|
||||
return new Response(archiveStream as unknown as ReadableStream, {
|
||||
return new Response(Readable.toWeb(archiveStream), {
|
||||
headers: {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Disposition': `attachment; filename="${repoName}.zip"`,
|
||||
|
||||
@@ -6,9 +6,42 @@ import {
|
||||
UpdateScheduleJobRequestSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { ScheduleRunWorktreesMode } from '@opencode-manager/shared/types'
|
||||
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
|
||||
import { type ScheduleService, ScheduleServiceError } from '../services/schedules'
|
||||
import { parseId, handleServiceError } from '../utils/route-helpers'
|
||||
|
||||
export type ScheduleRoutesService = Pick<ScheduleService,
|
||||
| 'cancelRun'
|
||||
| 'cancelServerRun'
|
||||
| 'clearRunHistory'
|
||||
| 'clearServerRunHistory'
|
||||
| 'countUnreadRuns'
|
||||
| 'createJob'
|
||||
| 'createServerJob'
|
||||
| 'deleteJob'
|
||||
| 'deleteRun'
|
||||
| 'deleteServerJob'
|
||||
| 'deleteServerRun'
|
||||
| 'getJob'
|
||||
| 'getRun'
|
||||
| 'getServerJob'
|
||||
| 'getServerRun'
|
||||
| 'listAllJobsWithRepos'
|
||||
| 'listAllRuns'
|
||||
| 'listJobs'
|
||||
| 'listRuns'
|
||||
| 'listServerJobs'
|
||||
| 'listServerRuns'
|
||||
| 'listUnreadRuns'
|
||||
| 'listWorktrees'
|
||||
| 'markAllRunsViewed'
|
||||
| 'markRunViewed'
|
||||
| 'removeWorktrees'
|
||||
| 'runJob'
|
||||
| 'runServerJob'
|
||||
| 'updateJob'
|
||||
| 'updateServerJob'
|
||||
>
|
||||
|
||||
function parseServerId(value: string | undefined): string {
|
||||
if (!value) {
|
||||
throw new ScheduleServiceError('OpenCode server id is required', 400)
|
||||
@@ -54,7 +87,7 @@ function parseWorktreesMode(value: string | undefined): ScheduleRunWorktreesMode
|
||||
return result.data
|
||||
}
|
||||
|
||||
export function createScheduleRoutes(scheduleService: ScheduleService) {
|
||||
export function createScheduleRoutes(scheduleService: ScheduleRoutesService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/all', (c) => {
|
||||
@@ -277,11 +310,7 @@ export function createScheduleRoutes(scheduleService: ScheduleService) {
|
||||
return app
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule routes for a project directory on a linked OpenCode server. They mirror the
|
||||
* repo routes without worktree endpoints, because remote runs execute in place.
|
||||
*/
|
||||
export function createServerScheduleRoutes(scheduleService: ScheduleService) {
|
||||
export function createServerScheduleRoutes(scheduleService: ScheduleRoutesService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'bun:test'
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { SessionPinSchema } from '@opencode-manager/shared/schemas'
|
||||
import { createTestDatabase } from '../../test/helpers/test-database'
|
||||
import { readJson } from '../../test/helpers/read-json'
|
||||
import { createSessionPinRoutes } from './session-pins'
|
||||
|
||||
function createTestApp(db: Database): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/session-pins', createSessionPinRoutes(db))
|
||||
return app
|
||||
}
|
||||
const SessionPinListSchema = z.object({ pins: z.array(SessionPinSchema) })
|
||||
const ErrorSchema = z.object({ error: z.string() })
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
async function togglePin(app: Hono, sessionId: string, directory: string, pinned: boolean): Promise<Response> {
|
||||
return app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId, directory, pinned }),
|
||||
})
|
||||
}
|
||||
|
||||
describe('session pins routes', () => {
|
||||
@@ -22,8 +23,9 @@ describe('session pins routes', () => {
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
app = createTestApp(db)
|
||||
db = createTestDatabase()
|
||||
app = new Hono()
|
||||
app.route('/session-pins', createSessionPinRoutes(db))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -33,60 +35,36 @@ describe('session pins routes', () => {
|
||||
it('GET / returns empty pins list initially', async () => {
|
||||
const res = await app.request('/session-pins')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: unknown[] }
|
||||
expect(data.pins).toEqual([])
|
||||
expect((await readJson(res, SessionPinListSchema)).pins).toEqual([])
|
||||
})
|
||||
|
||||
it('PUT / creates a pin and returns updated list', async () => {
|
||||
const res = await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
const res = await togglePin(app, 'ses_1', '/w/a', true)
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: Array<{ sessionId: string; directory: string }> }
|
||||
expect(data.pins).toHaveLength(1)
|
||||
expect(data.pins[0]).toMatchObject({ sessionId: 'ses_1', directory: '/w/a' })
|
||||
const { pins } = await readJson(res, SessionPinListSchema)
|
||||
expect(pins).toHaveLength(1)
|
||||
expect(pins[0]).toMatchObject({ sessionId: 'ses_1', directory: '/w/a' })
|
||||
})
|
||||
|
||||
it('GET / returns pins after creation', async () => {
|
||||
await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
await togglePin(app, 'ses_1', '/w/a', true)
|
||||
|
||||
const res = await app.request('/session-pins')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: unknown[] }
|
||||
expect(data.pins).toHaveLength(1)
|
||||
expect((await readJson(res, SessionPinListSchema)).pins).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('PUT / with pinned: false removes the pin', async () => {
|
||||
await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
await togglePin(app, 'ses_1', '/w/a', true)
|
||||
|
||||
const res = await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: false }),
|
||||
})
|
||||
const res = await togglePin(app, 'ses_1', '/w/a', false)
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: unknown[] }
|
||||
expect(data.pins).toHaveLength(0)
|
||||
expect((await readJson(res, SessionPinListSchema)).pins).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('PUT / with invalid body returns 400', async () => {
|
||||
const res = await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: '', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
const res = await togglePin(app, '', '/w/a', true)
|
||||
expect(res.status).toBe(400)
|
||||
const data = await res.json() as { error: string }
|
||||
expect(data.error).toBe('Invalid request')
|
||||
expect((await readJson(res, ErrorSchema)).error).toBe('Invalid request')
|
||||
})
|
||||
})
|
||||
@@ -1,24 +1,21 @@
|
||||
import { Hono, type Context } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import { SetSessionSandboxRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { openCodeErrorStatus } from '@opencode-manager/shared/opencode'
|
||||
import { SessionSandboxError, type SessionSandboxService } from '../services/session-sandbox'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { getErrorMessage, toContentfulStatus } from '../utils/error-utils'
|
||||
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
|
||||
|
||||
/**
|
||||
* Maps both sandbox errors and the OpenCode errors raised while resolving a session (for example
|
||||
* `SessionNotFoundError` or `InvalidRequestError` for a malformed id) to their real status codes.
|
||||
*/
|
||||
function handleSessionSandboxError(c: Context, error: unknown, fallback: string) {
|
||||
const status = openCodeErrorStatus(error)
|
||||
function handleSessionSandboxError(c: Context, cause: unknown, fallback: string) {
|
||||
const status = openCodeErrorStatus(cause)
|
||||
if (status !== undefined) {
|
||||
return c.json({ error: getErrorMessage(error) || fallback }, status as ContentfulStatusCode)
|
||||
return c.json({ error: getErrorMessage(cause) || fallback }, toContentfulStatus(status))
|
||||
}
|
||||
return handleServiceError(c, error, fallback, SessionSandboxError)
|
||||
return handleServiceError(c, cause, fallback, SessionSandboxError)
|
||||
}
|
||||
|
||||
export function createSessionSandboxRoutes(service: SessionSandboxService) {
|
||||
export type SessionSandboxRoutesService = Pick<SessionSandboxService, 'getClaim' | 'getState' | 'resolveShellTarget' | 'update'>
|
||||
|
||||
export function createSessionSandboxRoutes(service: SessionSandboxRoutesService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/:sessionId', async (c) => {
|
||||
|
||||
+141
-248
@@ -1,216 +1,112 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createSettingsRoutes } from './settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
import { SettingsResponseSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { OpenCodeLifecycleStatus } from '@opencode-manager/shared/opencode'
|
||||
import { createSettingsRoutes, type SettingsRouteDependencies } from './settings'
|
||||
import { GitAuthService } from '../services/git-auth'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { ActiveUserSession } from '../services/opencode-restart'
|
||||
import { createTestDatabase } from '../../test/helpers/test-database'
|
||||
import { createTempWorkspace, type TempWorkspace } from '../../test/helpers/test-env'
|
||||
import { createFetchStub, type FetchStub } from '../../test/helpers/fetch-stub'
|
||||
import { readJson } from '../../test/helpers/read-json'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import type { OpenCodeRestartTarget } from '../services/opencode-restart'
|
||||
|
||||
interface TestUserPreferenceRow {
|
||||
preferences: string
|
||||
updated_at: number
|
||||
}
|
||||
const DirectoryFileListSchema = z.array(
|
||||
z.object({ kind: z.string(), name: z.string(), relativePath: z.string() }),
|
||||
)
|
||||
|
||||
interface StatementResult {
|
||||
get?: (..._params: unknown[]) => TestUserPreferenceRow | { count: number } | { name: string } | { user_id: string; preferences: string } | undefined
|
||||
run?: (..._params: unknown[]) => { changes: number }
|
||||
all?: () => Array<unknown>
|
||||
}
|
||||
const DirectoryFileInstallSchema = z.object({
|
||||
kind: z.string(),
|
||||
filesInstalled: z.array(z.string()),
|
||||
restartRequired: z.boolean(),
|
||||
})
|
||||
|
||||
class InMemoryDatabase {
|
||||
private userPreferences = new Map<string, TestUserPreferenceRow>()
|
||||
const DiscoveredModelsSchema = z.object({ models: z.array(z.string()), cached: z.boolean() })
|
||||
|
||||
private normalizeSql(sql: string): string {
|
||||
return sql.trim().toLowerCase().replace(/\s+/g, ' ')
|
||||
}
|
||||
const ActiveSessionsSchema = z.object({
|
||||
count: z.number(),
|
||||
sessions: z.array(z.object({ sessionID: z.string(), directory: z.string() })),
|
||||
})
|
||||
|
||||
private setUserPreference(userId: string, preferences: string, updatedAt: number): void {
|
||||
this.userPreferences.set(userId, { preferences, updated_at: updatedAt })
|
||||
}
|
||||
const RestartResponseSchema = z.object({
|
||||
success: z.boolean(),
|
||||
message: z.string().optional(),
|
||||
interruptedSessions: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
private createStatement(sql: string): StatementResult {
|
||||
const normalizedSql = this.normalizeSql(sql)
|
||||
|
||||
if (normalizedSql === 'select preferences, updated_at from user_preferences where user_id = ?') {
|
||||
return {
|
||||
get: (...params: unknown[]) => {
|
||||
const userId = params[0]
|
||||
if (typeof userId !== 'string') {
|
||||
return undefined
|
||||
}
|
||||
return this.userPreferences.get(userId)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('insert into user_preferences')) {
|
||||
return {
|
||||
run: (...params: unknown[]) => {
|
||||
const [userId, preferences, updatedAt] = params as [string, string, number]
|
||||
this.setUserPreference(userId, preferences, updatedAt)
|
||||
return { changes: 1 }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('delete from user_preferences where user_id = ?')) {
|
||||
return {
|
||||
run: (...params: unknown[]) => {
|
||||
const userId = params[0]
|
||||
if (typeof userId !== 'string') {
|
||||
return { changes: 0 }
|
||||
}
|
||||
const hadRow = this.userPreferences.delete(userId)
|
||||
return { changes: hadRow ? 1 : 0 }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('select user_id, preferences from user_preferences')) {
|
||||
return {
|
||||
all: () => [...this.userPreferences.entries()].map(([user_id, row]) => ({
|
||||
user_id,
|
||||
preferences: row.preferences,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('pragma table_info(') || normalizedSql.includes('select name from sqlite_master')) {
|
||||
return {
|
||||
all: () => [],
|
||||
get: () => undefined,
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('select count(*) as count')) {
|
||||
return {
|
||||
get: () => ({ count: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSql.startsWith('create table') ||
|
||||
normalizedSql.startsWith('create index') ||
|
||||
normalizedSql.startsWith('drop table') ||
|
||||
normalizedSql.startsWith('drop index')
|
||||
) {
|
||||
return {
|
||||
run: () => ({ changes: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSql.startsWith('begin transaction') ||
|
||||
normalizedSql.startsWith('commit') ||
|
||||
normalizedSql.startsWith('rollback')
|
||||
) {
|
||||
return {
|
||||
run: () => ({ changes: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get: () => undefined,
|
||||
run: () => ({ changes: 0 }),
|
||||
all: () => [],
|
||||
}
|
||||
}
|
||||
|
||||
query(sql: string): StatementResult {
|
||||
return this.createStatement(sql)
|
||||
}
|
||||
|
||||
prepare(sql: string): StatementResult {
|
||||
return this.createStatement(sql)
|
||||
}
|
||||
|
||||
run(sql: string, ...params: unknown[]): { changes: number } {
|
||||
const statement = this.createStatement(sql)
|
||||
return statement.run ? statement.run(...params) : { changes: 0 }
|
||||
}
|
||||
|
||||
close() {
|
||||
this.userPreferences.clear()
|
||||
function lifecycleStatus(): OpenCodeLifecycleStatus {
|
||||
return {
|
||||
state: 'healthy',
|
||||
healthy: true,
|
||||
port: 5551,
|
||||
version: '2.0.15',
|
||||
minVersion: '2.0.0',
|
||||
versionSupported: true,
|
||||
lastError: null,
|
||||
activeRecoveryAction: null,
|
||||
attemptedRecoveryActions: [],
|
||||
nextRecoveryAction: null,
|
||||
failureCount: 0,
|
||||
watching: false,
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: class {
|
||||
private db = new InMemoryDatabase()
|
||||
|
||||
query(sql: string) {
|
||||
return this.db.query(sql)
|
||||
}
|
||||
|
||||
prepare(sql: string) {
|
||||
return this.db.prepare(sql)
|
||||
}
|
||||
|
||||
run(sql: string, ...params: unknown[]) {
|
||||
return this.db.run(sql, ...params)
|
||||
}
|
||||
|
||||
close() {
|
||||
return this.db.close()
|
||||
}
|
||||
|
||||
exec(sql: string) {
|
||||
return this.db.run(sql)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
const mockGitAuthService = {
|
||||
getGitEnvironment: () => ({}),
|
||||
} as unknown as GitAuthService
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
function createSettingsDeps(): SettingsRouteDependencies {
|
||||
return {
|
||||
openCodeManager: {
|
||||
getVersion: () => '2.0.15',
|
||||
fetchVersion: async () => '2.0.15',
|
||||
clearStartupError: () => undefined,
|
||||
getLastStartupError: () => null,
|
||||
markRestartPending: vi.fn(),
|
||||
isRestartPending: () => false,
|
||||
restart: async () => undefined,
|
||||
checkHealth: async () => true,
|
||||
},
|
||||
installOpenCodeVersion: async (version) => version,
|
||||
detectSandboxCapability: () => ({ available: false, reason: 'sandbox unavailable in tests' }),
|
||||
sandboxResourceLimitError: () => null,
|
||||
syncManagerGitIdentityConfig: async () => ({ identity: null, error: null }),
|
||||
}
|
||||
}
|
||||
|
||||
function createTestApp(db: Database, openCodeSupervisor?: OpenCodeSupervisor): Hono {
|
||||
function createTestApp(
|
||||
db: Database,
|
||||
deps: SettingsRouteDependencies,
|
||||
openCodeSupervisor?: OpenCodeRestartTarget,
|
||||
): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient(), openCodeSupervisor))
|
||||
app.route('/settings', createSettingsRoutes(db, new GitAuthService(), createStubOpenCodeClient(), openCodeSupervisor, deps))
|
||||
return app
|
||||
}
|
||||
|
||||
describe('settings routes — serverEnvVars', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let originalWorkspacePath: string | undefined
|
||||
let workspace: TempWorkspace
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
app = createTestApp(db)
|
||||
originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
process.env.WORKSPACE_PATH = '/tmp/test-workspace-settings-routes'
|
||||
workspace = createTempWorkspace('settings-routes-')
|
||||
db = createTestDatabase()
|
||||
app = createTestApp(db, createSettingsDeps())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalWorkspacePath) {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
} else {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
}
|
||||
db.close()
|
||||
workspace.restore()
|
||||
})
|
||||
|
||||
it('GET / returns empty serverEnvVars by default', async () => {
|
||||
const res = await app.request('/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { preferences: { serverEnvVars?: Array<{ key: string; value: string }> } }
|
||||
expect(data.preferences.serverEnvVars).toEqual([])
|
||||
expect((await readJson(res, SettingsResponseSchema)).preferences.serverEnvVars).toEqual([])
|
||||
})
|
||||
|
||||
it('PATCH / saves and returns serverEnvVars', async () => {
|
||||
@@ -230,8 +126,7 @@ describe('settings routes — serverEnvVars', () => {
|
||||
})
|
||||
|
||||
expect(patchRes.status).toBe(200)
|
||||
const data = (await patchRes.json()) as { preferences: { serverEnvVars: Array<{ key: string; value: string }> } }
|
||||
expect(data.preferences.serverEnvVars).toEqual([
|
||||
expect((await readJson(patchRes, SettingsResponseSchema)).preferences.serverEnvVars).toEqual([
|
||||
{
|
||||
key: 'OPENCODE_EXPERIMENTAL_FEATURE',
|
||||
value: 'true',
|
||||
@@ -254,9 +149,8 @@ describe('settings routes — serverEnvVars', () => {
|
||||
})
|
||||
|
||||
const res = await app.request('/settings')
|
||||
const data = (await res.json()) as { preferences: { serverEnvVars: Array<{ key: string; value: string }> } }
|
||||
|
||||
expect(data.preferences.serverEnvVars).toEqual([
|
||||
expect((await readJson(res, SettingsResponseSchema)).preferences.serverEnvVars).toEqual([
|
||||
{
|
||||
key: 'MY_FLAG',
|
||||
value: '1',
|
||||
@@ -268,30 +162,21 @@ describe('settings routes — serverEnvVars', () => {
|
||||
describe('settings routes — OpenCode directory file upload', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let originalWorkspacePath: string | undefined
|
||||
let workspacePath: string
|
||||
const restart = vi.fn(async () => undefined)
|
||||
let markRestartPendingSpy: ReturnType<typeof vi.spyOn>
|
||||
let workspace: TempWorkspace
|
||||
let deps: SettingsRouteDependencies
|
||||
let restart: ReturnType<typeof vi.fn<OpenCodeRestartTarget['restart']>>
|
||||
|
||||
beforeEach(async () => {
|
||||
db = createTestDb()
|
||||
restart.mockClear()
|
||||
markRestartPendingSpy = vi.spyOn(opencodeServerManager, 'markRestartPending').mockImplementation(() => undefined)
|
||||
originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
workspacePath = await mkdtemp(join(tmpdir(), 'ocm-command-upload-'))
|
||||
process.env.WORKSPACE_PATH = workspacePath
|
||||
app = createTestApp(db, { restart } as unknown as OpenCodeSupervisor)
|
||||
beforeEach(() => {
|
||||
workspace = createTempWorkspace('ocm-command-upload-')
|
||||
db = createTestDatabase()
|
||||
deps = createSettingsDeps()
|
||||
restart = vi.fn<OpenCodeRestartTarget['restart']>(async () => lifecycleStatus())
|
||||
app = createTestApp(db, deps, { restart })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalWorkspacePath) {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
} else {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
}
|
||||
await rm(workspacePath, { recursive: true, force: true })
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
markRestartPendingSpy.mockRestore()
|
||||
workspace.restore()
|
||||
})
|
||||
|
||||
it('installs uploaded command markdown files into the OpenCode commands directory', async () => {
|
||||
@@ -309,32 +194,32 @@ describe('settings routes — OpenCode directory file upload', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({
|
||||
expect(await readJson(res, DirectoryFileInstallSchema)).toEqual({
|
||||
kind: 'commands',
|
||||
filesInstalled: ['git/commit.md'],
|
||||
restartRequired: true,
|
||||
})
|
||||
await expect(readFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'utf8')).resolves.toBe('commit body')
|
||||
await expect(readFile(join(workspace.path, '.config/opencode/commands/git/commit.md'), 'utf8')).resolves.toBe('commit body')
|
||||
expect(restart).not.toHaveBeenCalled()
|
||||
expect(markRestartPendingSpy).toHaveBeenCalledTimes(1)
|
||||
expect(deps.openCodeManager.markRestartPending).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('lists uploaded command and agent directory files', async () => {
|
||||
await mkdir(join(workspacePath, '.config/opencode/commands/git'), { recursive: true })
|
||||
await mkdir(join(workspacePath, '.config/opencode/agents/team'), { recursive: true })
|
||||
await writeFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'commit body')
|
||||
await writeFile(join(workspacePath, '.config/opencode/commands/git/.DS_Store'), 'metadata')
|
||||
await writeFile(join(workspacePath, '.config/opencode/agents/team/planner.md'), 'planner body')
|
||||
await mkdir(join(workspace.path, '.config/opencode/commands/git'), { recursive: true })
|
||||
await mkdir(join(workspace.path, '.config/opencode/agents/team'), { recursive: true })
|
||||
await writeFile(join(workspace.path, '.config/opencode/commands/git/commit.md'), 'commit body')
|
||||
await writeFile(join(workspace.path, '.config/opencode/commands/git/.DS_Store'), 'metadata')
|
||||
await writeFile(join(workspace.path, '.config/opencode/agents/team/planner.md'), 'planner body')
|
||||
|
||||
const commandsRes = await app.request('/settings/opencode-directory-files?kind=commands')
|
||||
const agentsRes = await app.request('/settings/opencode-directory-files?kind=agents')
|
||||
|
||||
expect(commandsRes.status).toBe(200)
|
||||
expect(agentsRes.status).toBe(200)
|
||||
await expect(commandsRes.json()).resolves.toEqual([
|
||||
expect(await readJson(commandsRes, DirectoryFileListSchema)).toEqual([
|
||||
{ kind: 'commands', name: 'commit', relativePath: 'git/commit.md' },
|
||||
])
|
||||
await expect(agentsRes.json()).resolves.toEqual([
|
||||
expect(await readJson(agentsRes, DirectoryFileListSchema)).toEqual([
|
||||
{ kind: 'agents', name: 'planner', relativePath: 'team/planner.md' },
|
||||
])
|
||||
})
|
||||
@@ -343,39 +228,40 @@ describe('settings routes — OpenCode directory file upload', () => {
|
||||
describe('settings routes — opencode model discovery', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let workspace: TempWorkspace
|
||||
let originalFetch: typeof globalThis.fetch
|
||||
let fetchMock: ReturnType<typeof vi.fn>
|
||||
let fetchStub: FetchStub
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
app = createTestApp(db)
|
||||
workspace = createTempWorkspace('settings-model-discovery-')
|
||||
db = createTestDatabase()
|
||||
app = createTestApp(db, createSettingsDeps())
|
||||
originalFetch = globalThis.fetch
|
||||
fetchMock = vi.fn()
|
||||
globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
|
||||
fetchStub = createFetchStub(async () => new Response(JSON.stringify({ data: [] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}))
|
||||
globalThis.fetch = fetchStub
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
db.close()
|
||||
workspace.restore()
|
||||
})
|
||||
|
||||
it('returns 400 when baseUrl is missing', async () => {
|
||||
const res = await app.request('/settings/opencode-discover-models')
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
it.each([
|
||||
{ label: 'missing', query: '' },
|
||||
{ label: 'invalid', query: '?baseUrl=not-a-url' },
|
||||
{ label: 'not http/https', query: '?baseUrl=ftp://example.com' },
|
||||
])('returns 400 when baseUrl is $label', async ({ query }) => {
|
||||
const res = await app.request(`/settings/opencode-discover-models${query}`)
|
||||
|
||||
it('returns 400 when baseUrl is invalid', async () => {
|
||||
const res = await app.request('/settings/opencode-discover-models?baseUrl=not-a-url')
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 when baseUrl is not http/https', async () => {
|
||||
const res = await app.request('/settings/opencode-discover-models?baseUrl=ftp://example.com')
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('discovers models from the endpoint', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
fetchStub.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: [{ id: 'gpt-4o' }, { id: 'gpt-3.5-turbo' }] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -383,14 +269,15 @@ describe('settings routes — opencode model discovery', () => {
|
||||
)
|
||||
|
||||
const res = await app.request('/settings/opencode-discover-models?baseUrl=http://localhost:1234&refresh=true')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { models: string[]; cached: boolean }
|
||||
const data = await readJson(res, DiscoveredModelsSchema)
|
||||
expect(data.models).toEqual(['gpt-4o', 'gpt-3.5-turbo'])
|
||||
expect(data.cached).toBe(false)
|
||||
})
|
||||
|
||||
it('returns cached models on subsequent requests without re-fetching', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
fetchStub.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: [{ id: 'llama-3' }] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -398,75 +285,81 @@ describe('settings routes — opencode model discovery', () => {
|
||||
)
|
||||
|
||||
const firstRes = await app.request('/settings/opencode-discover-models?baseUrl=http://localhost:5678&refresh=true')
|
||||
const firstData = (await firstRes.json()) as { models: string[]; cached: boolean }
|
||||
const firstData = await readJson(firstRes, DiscoveredModelsSchema)
|
||||
expect(firstData.models).toEqual(['llama-3'])
|
||||
expect(firstData.cached).toBe(false)
|
||||
|
||||
const secondRes = await app.request('/settings/opencode-discover-models?baseUrl=http://localhost:5678')
|
||||
const secondData = (await secondRes.json()) as { models: string[]; cached: boolean }
|
||||
const secondData = await readJson(secondRes, DiscoveredModelsSchema)
|
||||
expect(secondData.models).toEqual(['llama-3'])
|
||||
expect(secondData.cached).toBe(true)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(fetchStub).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('returns empty models when endpoint is unreachable', async () => {
|
||||
fetchMock.mockRejectedValue(new Error('connection refused'))
|
||||
fetchStub.mockRejectedValue(new Error('connection refused'))
|
||||
|
||||
const res = await app.request('/settings/opencode-discover-models?baseUrl=http://localhost:9999&refresh=true')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { models: string[] }
|
||||
expect(data.models).toEqual([])
|
||||
expect((await readJson(res, DiscoveredModelsSchema)).models).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('settings routes — active session reporting', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let workspace: TempWorkspace
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
workspace = createTempWorkspace('settings-active-sessions-')
|
||||
db = createTestDatabase()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
workspace.restore()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function stubActiveSessions(active: Record<string, string[]>, subagents: string[] = [], scheduled: string[] = []): void {
|
||||
vi.spyOn(sseAggregator, 'getActiveSessions').mockReturnValue(active)
|
||||
vi.spyOn(sseAggregator, 'isSubagentSession').mockImplementation((id: string) => subagents.includes(id))
|
||||
vi.spyOn(sseAggregator, 'isSubagentSession').mockImplementation((id) => subagents.includes(id))
|
||||
vi.spyOn(sseAggregator, 'getScheduledSessionIds').mockReturnValue(new Set(scheduled))
|
||||
}
|
||||
|
||||
it('GET /opencode-active-sessions returns active user sessions excluding subagent and scheduled sessions', async () => {
|
||||
stubActiveSessions({ '/a': ['s1', 'sub1', 'sched1'] }, ['sub1'], ['sched1'])
|
||||
const app = createTestApp(db, createSettingsDeps())
|
||||
|
||||
app = createTestApp(db)
|
||||
const res = await app.request('/settings/opencode-active-sessions')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { count: number; sessions: ActiveUserSession[] }
|
||||
const body = await readJson(res, ActiveSessionsSchema)
|
||||
expect(body.count).toBe(1)
|
||||
expect(body.sessions).toEqual([{ sessionID: 's1', directory: '/a' }])
|
||||
})
|
||||
|
||||
it('GET /opencode-active-sessions returns empty when nothing is active', async () => {
|
||||
stubActiveSessions({})
|
||||
app = createTestApp(db)
|
||||
const app = createTestApp(db, createSettingsDeps())
|
||||
|
||||
const res = await app.request('/settings/opencode-active-sessions')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { count: number; sessions: ActiveUserSession[] }
|
||||
const body = await readJson(res, ActiveSessionsSchema)
|
||||
expect(body.count).toBe(0)
|
||||
expect(body.sessions).toEqual([])
|
||||
})
|
||||
|
||||
it('POST /opencode-restart restarts the server without reporting interrupted sessions', async () => {
|
||||
stubActiveSessions({ '/a': ['s1'] })
|
||||
const restart = vi.fn().mockResolvedValue({ healthy: true })
|
||||
const restart = vi.fn<OpenCodeRestartTarget['restart']>(async () => lifecycleStatus())
|
||||
const app = createTestApp(db, createSettingsDeps(), { restart })
|
||||
|
||||
app = createTestApp(db, { restart } as unknown as OpenCodeSupervisor)
|
||||
const res = await app.request('/settings/opencode-restart', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { success: boolean; interruptedSessions?: string[] }
|
||||
const body = await readJson(res, RestartResponseSchema)
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.interruptedSessions).toBeUndefined()
|
||||
expect(restart).toHaveBeenCalledWith('settings_restart')
|
||||
|
||||
+129
-76
@@ -19,6 +19,7 @@ import {
|
||||
type UserPreferences,
|
||||
} from '../types/settings'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
import type { JsonValue } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
CreateSkillRequestSchema,
|
||||
UpdateSkillRequestSchema,
|
||||
@@ -34,11 +35,10 @@ import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { syncManagerGitIdentityConfig } from '../services/git-identity'
|
||||
import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { detectSandboxCapability } from '../services/sandbox/capability'
|
||||
import { detectSandboxCapability, type SandboxCapability } from '../services/sandbox/capability'
|
||||
import { sandboxResourceLimitError } from '../services/sandbox/resources'
|
||||
import { getProcessIdentityAttestationError } from '../services/opencode/process-identity'
|
||||
import { restartOpenCode, assertValidOpenCodeConfig, listActiveUserSessions } from '../services/opencode-restart'
|
||||
import { restartOpenCode, assertValidOpenCodeConfig, listActiveUserSessions, type OpenCodeRestartTarget } from '../services/opencode-restart'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { DEFAULT_AGENTS_MD } from '../constants'
|
||||
import { validateSSHPrivateKey } from '../utils/ssh-validation'
|
||||
@@ -71,23 +71,43 @@ import {
|
||||
normalizeOpenCodeVersion,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
|
||||
export interface SettingsRouteDependencies {
|
||||
openCodeManager: Pick<
|
||||
typeof opencodeServerManager,
|
||||
'getVersion' | 'fetchVersion' | 'clearStartupError' | 'getLastStartupError' | 'markRestartPending' | 'isRestartPending' | 'restart' | 'checkHealth'
|
||||
>
|
||||
installOpenCodeVersion: (version: string) => Promise<string>
|
||||
detectSandboxCapability: () => SandboxCapability
|
||||
sandboxResourceLimitError: (preferences: SandboxPreferences) => string | null
|
||||
syncManagerGitIdentityConfig: typeof syncManagerGitIdentityConfig
|
||||
}
|
||||
|
||||
export const settingsRouteDependencies: SettingsRouteDependencies = {
|
||||
openCodeManager: opencodeServerManager,
|
||||
installOpenCodeVersion,
|
||||
detectSandboxCapability,
|
||||
sandboxResourceLimitError,
|
||||
syncManagerGitIdentityConfig,
|
||||
}
|
||||
|
||||
async function installVerifiedOpenCodeVersion(
|
||||
version: string,
|
||||
openCodeSupervisor: OpenCodeSupervisor | undefined,
|
||||
openCodeSupervisor: OpenCodeRestartTarget | undefined,
|
||||
context: string,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<string> {
|
||||
await installOpenCodeVersion(version)
|
||||
await deps.installOpenCodeVersion(version)
|
||||
|
||||
try {
|
||||
const installedVersion = await opencodeServerManager.fetchVersion()
|
||||
const installedVersion = await deps.openCodeManager.fetchVersion()
|
||||
logger.info(`New OpenCode version: ${installedVersion}`)
|
||||
|
||||
if (installedVersion !== version) {
|
||||
throw new Error(`OpenCode install did not result in version ${version}; detected ${installedVersion ?? 'unknown'}`)
|
||||
}
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
deps.openCodeManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
logger.info(`OpenCode server restarted after ${context}`)
|
||||
|
||||
return installedVersion
|
||||
@@ -97,8 +117,11 @@ async function installVerifiedOpenCodeVersion(
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadOpenCodeForChange(openCodeClient: OpenCodeClient): Promise<{ restartRequired: boolean }> {
|
||||
return { restartRequired: await reloadOpenCodeOrMarkRestartPending(openCodeClient) === 'restart_pending' }
|
||||
async function reloadOpenCodeForChange(
|
||||
openCodeClient: OpenCodeClient,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<{ restartRequired: boolean }> {
|
||||
return { restartRequired: await reloadOpenCodeOrMarkRestartPending(openCodeClient, deps.openCodeManager) === 'restart_pending' }
|
||||
}
|
||||
|
||||
const OPENCODE_BIN_MANAGED_MESSAGE =
|
||||
@@ -106,7 +129,7 @@ const OPENCODE_BIN_MANAGED_MESSAGE =
|
||||
|
||||
function isOpenCodeBinaryExternallyManaged(): boolean {
|
||||
const binary = process.env.OPENCODE_BIN
|
||||
return typeof binary === 'string' && binary.length > 0
|
||||
return binary !== undefined && binary.length > 0
|
||||
}
|
||||
|
||||
interface OpenCodeInstallFailureMessages {
|
||||
@@ -115,15 +138,32 @@ interface OpenCodeInstallFailureMessages {
|
||||
unrecovered: string
|
||||
}
|
||||
|
||||
interface OpenCodeInstallFailureBody {
|
||||
success?: false
|
||||
error: string
|
||||
details: string
|
||||
oldVersion: string | null
|
||||
newVersion: string | null | undefined
|
||||
upgraded: false
|
||||
recovered: boolean
|
||||
recoveryMessage?: string
|
||||
}
|
||||
|
||||
interface OpenCodeInstallFailureResponse {
|
||||
status: 400 | 500
|
||||
body: OpenCodeInstallFailureBody
|
||||
}
|
||||
|
||||
async function buildOpenCodeInstallFailureResponse(
|
||||
openCodeSupervisor: OpenCodeSupervisor | undefined,
|
||||
error: unknown,
|
||||
openCodeSupervisor: OpenCodeRestartTarget | undefined,
|
||||
cause: unknown,
|
||||
oldVersion: string | null,
|
||||
messages: OpenCodeInstallFailureMessages,
|
||||
): Promise<{ status: 400 | 500; body: Record<string, unknown> }> {
|
||||
const details = error instanceof Error ? error.message : 'Unknown error'
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<OpenCodeInstallFailureResponse> {
|
||||
const details = cause instanceof Error ? cause.message : 'Unknown error'
|
||||
|
||||
if (!(error instanceof OpenCodeInstallError) || !error.swapStarted) {
|
||||
if (!(cause instanceof OpenCodeInstallError) || !cause.swapStarted) {
|
||||
logger.warn(`${messages.failed}: installation did not reach the binary swap, not restarting the server`)
|
||||
return {
|
||||
status: 500,
|
||||
@@ -131,12 +171,12 @@ async function buildOpenCodeInstallFailureResponse(
|
||||
}
|
||||
}
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
deps.openCodeManager.clearStartupError()
|
||||
|
||||
let recovered = false
|
||||
let recoveryMessage = ''
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
logger.warn('OpenCode server restarted after install failure')
|
||||
recovered = true
|
||||
recoveryMessage = 'Server recovered'
|
||||
@@ -147,7 +187,7 @@ async function buildOpenCodeInstallFailureResponse(
|
||||
|
||||
let currentVersion: string | null | undefined = oldVersion
|
||||
try {
|
||||
currentVersion = opencodeServerManager.getVersion() || oldVersion
|
||||
currentVersion = deps.openCodeManager.getVersion() || oldVersion
|
||||
} catch (versionError) {
|
||||
logger.error('Failed to get version after recovery:', versionError)
|
||||
currentVersion = oldVersion
|
||||
@@ -199,21 +239,21 @@ function matchErrorStatus<T extends number>(
|
||||
return match ? match[1] : null
|
||||
}
|
||||
|
||||
function handleOpenCodeDirectoryFileError(c: Context, error: unknown, operation: string) {
|
||||
logger.error(`Failed to ${operation} OpenCode directory file:`, error)
|
||||
function handleOpenCodeDirectoryFileError(c: Context, cause: unknown, operation: string) {
|
||||
logger.error(`Failed to ${operation} OpenCode directory file:`, cause)
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request', details: error.issues }, 400)
|
||||
if (cause instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request', details: cause.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
if ('code' in error && error.code === 'ENOENT') {
|
||||
if (cause instanceof Error) {
|
||||
if ('code' in cause && cause.code === 'ENOENT') {
|
||||
return c.json({ error: 'File not found' }, 404)
|
||||
}
|
||||
|
||||
const status = matchErrorStatus(OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS, error)
|
||||
const status = matchErrorStatus(OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS, cause)
|
||||
if (status) {
|
||||
return c.json({ error: error.message }, status)
|
||||
return c.json({ error: cause.message }, status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,7 +285,7 @@ function sandboxEnforcementChanged(
|
||||
return (previous?.enabled ?? false) !== next.enabled
|
||||
}
|
||||
|
||||
function preferenceChanged(previous: unknown, next: unknown): boolean {
|
||||
function preferenceChanged(previous: JsonValue | undefined, next: JsonValue | undefined): boolean {
|
||||
return next !== undefined && JSON.stringify(previous) !== JSON.stringify(next)
|
||||
}
|
||||
|
||||
@@ -254,7 +294,7 @@ function listOpenCodeRestartReasons(previous: UserPreferences, next: Partial<Use
|
||||
sandboxEnforcementChanged(previous.sandbox, next.sandbox) && 'sandbox',
|
||||
preferenceChanged(previous.gitCredentials ?? [], next.gitCredentials) && 'git credentials',
|
||||
preferenceChanged(previous.serverEnvVars ?? [], next.serverEnvVars) && 'server environment variables',
|
||||
].filter((reason): reason is string => typeof reason === 'string')
|
||||
].filter((reason) => reason !== false)
|
||||
}
|
||||
|
||||
function gitIdentityConfigChanged(previous: UserPreferences, next: Partial<UserPreferences>): boolean {
|
||||
@@ -262,10 +302,10 @@ function gitIdentityConfigChanged(previous: UserPreferences, next: Partial<UserP
|
||||
|| preferenceChanged(previous.gitCredentials ?? [], next.gitCredentials)
|
||||
}
|
||||
|
||||
function markOpenCodeRestartPendingFor(reasons: string[]): boolean {
|
||||
function markOpenCodeRestartPendingFor(reasons: string[], deps: SettingsRouteDependencies): boolean {
|
||||
if (reasons.length === 0) return false
|
||||
logger.info(`${reasons.join(', ')} changed, marking OpenCode server restart as pending`)
|
||||
opencodeServerManager.markRestartPending()
|
||||
deps.openCodeManager.markRestartPending()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -276,7 +316,9 @@ function parseOptionalRepoId(value: string | undefined): number | undefined {
|
||||
return parsed
|
||||
}
|
||||
|
||||
function parseBooleanFormValue(value: unknown): boolean | undefined {
|
||||
type FormParseValue = string | File | (string | File)[] | boolean | undefined
|
||||
|
||||
function parseBooleanFormValue(value: FormParseValue): boolean | undefined {
|
||||
if (value === true || value === 'true') return true
|
||||
if (value === false || value === 'false') return false
|
||||
return undefined
|
||||
@@ -286,7 +328,12 @@ function getMarkdownUploadManifest(manifest: ReturnType<typeof parseUploadManife
|
||||
return manifest.filter(entry => entry.relativePath.toLowerCase().endsWith('.md'))
|
||||
}
|
||||
|
||||
function spawnWithTimeout(args: string[], timeoutMs: number, env?: Record<string, string>): { output: string; timedOut: boolean } {
|
||||
interface SpawnResult {
|
||||
output: string
|
||||
timedOut: boolean
|
||||
}
|
||||
|
||||
function spawnWithTimeout(args: string[], timeoutMs: number, env?: Record<string, string>): SpawnResult {
|
||||
const result = spawnSync(args[0]!, args.slice(1), {
|
||||
encoding: 'utf8',
|
||||
timeout: timeoutMs,
|
||||
@@ -327,13 +374,16 @@ const UpdateSettingsSchema = z.object({
|
||||
})
|
||||
}
|
||||
})
|
||||
}).transform(({ preferences }) => ({
|
||||
preferences: {
|
||||
...preferences,
|
||||
...(preferences.gitIdentity ? { gitIdentity: trimGitIdentityEmail(preferences.gitIdentity) } : {}),
|
||||
...(preferences.gitIdentities ? { gitIdentities: preferences.gitIdentities.map(trimGitIdentityEmail) } : {}),
|
||||
},
|
||||
}))
|
||||
}).transform(({ preferences }) => {
|
||||
const trimmedPreferences = { ...preferences }
|
||||
if (preferences.gitIdentity) {
|
||||
trimmedPreferences.gitIdentity = trimGitIdentityEmail(preferences.gitIdentity)
|
||||
}
|
||||
if (preferences.gitIdentities) {
|
||||
trimmedPreferences.gitIdentities = preferences.gitIdentities.map(trimGitIdentityEmail)
|
||||
}
|
||||
return { preferences: trimmedPreferences }
|
||||
})
|
||||
|
||||
const CreateCustomCommandSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
@@ -359,7 +409,7 @@ const SyncOpenCodeImportSchema = z.object({
|
||||
})
|
||||
|
||||
|
||||
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeRestartTarget, deps: SettingsRouteDependencies = settingsRouteDependencies) {
|
||||
const app = new Hono()
|
||||
const settingsService = new SettingsService(db)
|
||||
|
||||
@@ -415,14 +465,14 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
requestedSandboxResources !== undefined
|
||||
&& (requestedSandboxResources.cpus !== undefined || requestedSandboxResources.memoryMib !== undefined)
|
||||
) {
|
||||
const limitError = sandboxResourceLimitError(requestedSandboxResources)
|
||||
const limitError = deps.sandboxResourceLimitError(requestedSandboxResources)
|
||||
if (limitError !== null) {
|
||||
return c.json({ error: limitError }, 400)
|
||||
}
|
||||
}
|
||||
|
||||
if (currentSettings.preferences.sandbox?.enabled !== true && validated.preferences.sandbox?.enabled === true) {
|
||||
const capability = detectSandboxCapability()
|
||||
const capability = deps.detectSandboxCapability()
|
||||
if (capability.available === false) {
|
||||
return c.json({ error: `Cannot enable sandboxing: ${capability.reason}` }, 400)
|
||||
}
|
||||
@@ -435,11 +485,12 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const settings = settingsService.updateSettings(validated.preferences, userId)
|
||||
|
||||
if (gitIdentityConfigChanged(currentSettings.preferences, validated.preferences)) {
|
||||
await syncManagerGitIdentityConfig(db)
|
||||
await deps.syncManagerGitIdentityConfig(db)
|
||||
}
|
||||
|
||||
const restartRequired = markOpenCodeRestartPendingFor(
|
||||
listOpenCodeRestartReasons(currentSettings.preferences, validated.preferences),
|
||||
deps,
|
||||
)
|
||||
|
||||
return c.json(restartRequired ? { ...settings, restartRequired: true } : settings)
|
||||
@@ -462,11 +513,12 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const settings = settingsService.resetSettings(userId)
|
||||
|
||||
if (gitIdentityConfigChanged(currentSettings.preferences, settings.preferences)) {
|
||||
await syncManagerGitIdentityConfig(db)
|
||||
await deps.syncManagerGitIdentityConfig(db)
|
||||
}
|
||||
|
||||
const restartRequired = markOpenCodeRestartPendingFor(
|
||||
listOpenCodeRestartReasons(currentSettings.preferences, settings.preferences),
|
||||
deps,
|
||||
)
|
||||
|
||||
return c.json(restartRequired ? { ...settings, restartRequired: true } : settings)
|
||||
@@ -476,22 +528,23 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
})
|
||||
|
||||
// OpenCode Config routes
|
||||
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient))
|
||||
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient, {
|
||||
isRestartPending: () => deps.openCodeManager.isRestartPending(),
|
||||
}))
|
||||
app.route('/remote-access-headers', createRemoteAccessHeaderRoutes(new RemoteAccessHeadersService(db)))
|
||||
|
||||
app.post('/opencode-restart', async (c) => {
|
||||
try {
|
||||
logger.info('Manual OpenCode server restart requested')
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
deps.openCodeManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
return c.json({
|
||||
success: true,
|
||||
message: 'OpenCode server restarted successfully',
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to restart OpenCode server:', error)
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
const startupError = deps.openCodeManager.getLastStartupError()
|
||||
return c.json({
|
||||
error: 'Failed to restart OpenCode server',
|
||||
details: startupError || (error instanceof Error ? error.message : 'Unknown error')
|
||||
@@ -543,8 +596,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
}
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
deps.openCodeManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
@@ -585,7 +638,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
try {
|
||||
await assertValidOpenCodeConfig()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
} catch (reloadError) {
|
||||
logger.error('Rollback config restart failed, attempting restart without the config file:', reloadError)
|
||||
|
||||
@@ -595,8 +648,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
logger.info('Deleted filesystem config, attempting restart with fallback')
|
||||
await new Promise(r => setTimeout(r, 1000))
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
deps.openCodeManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
@@ -626,7 +679,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json({ error: OPENCODE_BIN_MANAGED_MESSAGE }, 409)
|
||||
}
|
||||
|
||||
const oldVersion = opencodeServerManager.getVersion()
|
||||
const oldVersion = deps.openCodeManager.getVersion()
|
||||
logger.info(`Current OpenCode version: ${oldVersion}`)
|
||||
|
||||
try {
|
||||
@@ -649,7 +702,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
logger.info(`Installing OpenCode ${latestVersion} from opencode.ai...`)
|
||||
const newVersion = await installVerifiedOpenCodeVersion(latestVersion, openCodeSupervisor, 'upgrade')
|
||||
const newVersion = await installVerifiedOpenCodeVersion(latestVersion, openCodeSupervisor, 'upgrade', deps)
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
@@ -666,7 +719,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
failed: 'Failed to upgrade OpenCode',
|
||||
recovered: 'Upgrade failed but server recovered',
|
||||
unrecovered: 'Failed to upgrade OpenCode and could not recover',
|
||||
})
|
||||
}, deps)
|
||||
return c.json(body, status)
|
||||
}
|
||||
})
|
||||
@@ -684,7 +737,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
publishedAt: release.publishedAt,
|
||||
}))
|
||||
|
||||
const currentVersion = opencodeServerManager.getVersion()
|
||||
const currentVersion = deps.openCodeManager.getVersion()
|
||||
|
||||
return c.json({
|
||||
versions,
|
||||
@@ -704,7 +757,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json({ error: OPENCODE_BIN_MANAGED_MESSAGE }, 409)
|
||||
}
|
||||
|
||||
const oldVersion = opencodeServerManager.getVersion()
|
||||
const oldVersion = deps.openCodeManager.getVersion()
|
||||
logger.info(`Current OpenCode version: ${oldVersion}`)
|
||||
|
||||
let requestedVersion: string
|
||||
@@ -726,7 +779,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
try {
|
||||
logger.info(`Installing OpenCode version: ${requestedVersion}`)
|
||||
const newVersion = await installVerifiedOpenCodeVersion(requestedVersion, openCodeSupervisor, 'version change')
|
||||
const newVersion = await installVerifiedOpenCodeVersion(requestedVersion, openCodeSupervisor, 'version change', deps)
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
@@ -740,12 +793,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
failed: 'Failed to install OpenCode version',
|
||||
recovered: 'Version install failed but server recovered',
|
||||
unrecovered: 'Failed to install OpenCode version and could not recover',
|
||||
})
|
||||
}, deps)
|
||||
return c.json(body, status)
|
||||
}
|
||||
})
|
||||
|
||||
// Custom Commands routes
|
||||
app.get('/custom-commands', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
@@ -870,7 +922,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
await writeFileContent(agentsMdPath, content)
|
||||
logger.info(`Updated AGENTS.md at: ${agentsMdPath}`)
|
||||
|
||||
return c.json({ success: true, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ success: true, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update AGENTS.md:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -913,7 +965,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await installOpenCodeDirectoryFiles(kind, files)
|
||||
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
} catch (error) {
|
||||
logger.error('Failed to install OpenCode directory files:', error)
|
||||
|
||||
@@ -974,7 +1026,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await updateOpenCodeDirectoryFile(kind, relativePath, content)
|
||||
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'update')
|
||||
}
|
||||
@@ -987,7 +1039,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
await deleteOpenCodeDirectoryFile(kind, relativePath)
|
||||
|
||||
return c.json({ kind, relativePath, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ kind, relativePath, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'delete')
|
||||
}
|
||||
@@ -1007,7 +1059,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await installSkillFromGithubTree(db, validated)
|
||||
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
}
|
||||
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
@@ -1019,7 +1071,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const manifest = parseUploadManifest(formData['fileManifest'])
|
||||
|
||||
const repoId = parseOptionalRepoId(repoIdValue as string | undefined)
|
||||
const repoIdText = z.string().safeParse(repoIdValue)
|
||||
const repoId = parseOptionalRepoId(repoIdText.success ? repoIdText.data : undefined)
|
||||
const overwrite = parseBooleanFormValue(overwriteValue)
|
||||
|
||||
const uploadRequest = InstallSkillUploadRequestSchema.parse({
|
||||
@@ -1041,7 +1094,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await installSkillFromUploadedFiles(db, uploadRequest, files)
|
||||
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ ...result, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
}
|
||||
|
||||
return c.json({ error: 'Unsupported content type. Use application/json or multipart/form-data' }, 400)
|
||||
@@ -1104,7 +1157,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const skill = await createSkill(db, validated)
|
||||
|
||||
return c.json({ ...skill, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ ...skill, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
} catch (error) {
|
||||
logger.error('Failed to create skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -1131,7 +1184,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId)
|
||||
|
||||
return c.json({ ...skill, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ ...skill, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -1162,7 +1215,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
await deleteSkill(db, name, scope, repoId)
|
||||
|
||||
return c.json({ success: true, ...await reloadOpenCodeForChange(openCodeClient) })
|
||||
return c.json({ success: true, ...await reloadOpenCodeForChange(openCodeClient, deps) })
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -1323,11 +1376,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
} catch (restartError) {
|
||||
try {
|
||||
settingsService.restoreOpenCodeServerPasswordState(previousPasswordState)
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
await restartOpenCode(openCodeSupervisor, 'settings_restart', deps.openCodeManager)
|
||||
sseAggregator.reconnect()
|
||||
} catch (restoreError) {
|
||||
logger.error('Failed to restore OpenCode server auth runtime after restart failure:', restoreError)
|
||||
@@ -1361,7 +1414,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
try {
|
||||
const token = rotateInternalToken(db)
|
||||
logger.info('Manager token rotated, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
deps.openCodeManager.markRestartPending()
|
||||
return c.json({ token, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to rotate manager token:', error)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { encodeSSEFrame } from '../utils/sse-frame'
|
||||
|
||||
export interface QueuedSSEWriterInput {
|
||||
write: (chunk: Uint8Array) => Promise<unknown> | void
|
||||
onError: (error: unknown) => void
|
||||
write: (chunk: Uint8Array) => Promise<void> | void
|
||||
onError: (cause: unknown) => void
|
||||
}
|
||||
|
||||
export interface QueuedSSEWriter {
|
||||
@@ -23,7 +23,10 @@ export function createQueuedSSEWriter(input: QueuedSSEWriterInput): QueuedSSEWri
|
||||
draining = true
|
||||
try {
|
||||
while (queue.length > 0 && !closed) {
|
||||
const frame = queue.shift() as Uint8Array
|
||||
const frame = queue.shift()
|
||||
if (frame === undefined) {
|
||||
return
|
||||
}
|
||||
await input.write(frame)
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
+14
-12
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { stream } from 'hono/streaming'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import { sseAggregator, type SSEAggregator } from '../services/sse-aggregator'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, SSESubscribeSchema, SSEVisibilitySchema } from '@opencode-manager/shared/schemas'
|
||||
import { logger } from '../utils/logger'
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
@@ -14,7 +14,7 @@ interface SSERouteVariables {
|
||||
session?: Session['session']
|
||||
}
|
||||
|
||||
export function createSSERoutes() {
|
||||
export function createSSERoutes(aggregator: SSEAggregator = sseAggregator) {
|
||||
const app = new Hono<{ Variables: SSERouteVariables }>()
|
||||
|
||||
app.get('/stream', async (c) => {
|
||||
@@ -31,7 +31,9 @@ export function createSSERoutes() {
|
||||
let cleanup: () => void = () => {}
|
||||
|
||||
const queuedWriter = createQueuedSSEWriter({
|
||||
write: (chunk) => writer.write(chunk),
|
||||
write: async (chunk) => {
|
||||
await writer.write(chunk)
|
||||
},
|
||||
onError: (error) => {
|
||||
logger.error(`SSE write failed for ${clientId}:`, error)
|
||||
clearInterval(heartbeatInterval)
|
||||
@@ -43,7 +45,7 @@ export function createSSERoutes() {
|
||||
queuedWriter.writeSSE('heartbeat', JSON.stringify({ timestamp: Date.now() }))
|
||||
}, HEARTBEAT_INTERVAL_MS)
|
||||
|
||||
cleanup = sseAggregator.addClient(
|
||||
cleanup = aggregator.addClient(
|
||||
clientId,
|
||||
(event, data) => {
|
||||
queuedWriter.writeSSE(event, data)
|
||||
@@ -72,7 +74,7 @@ export function createSSERoutes() {
|
||||
endStream()
|
||||
})
|
||||
|
||||
queuedWriter.writeSSE('connected', JSON.stringify({ clientId, directories, ...sseAggregator.getConnectionStatus() }))
|
||||
queuedWriter.writeSSE('connected', JSON.stringify({ clientId, directories, ...aggregator.getConnectionStatus() }))
|
||||
|
||||
await streamEnded
|
||||
})
|
||||
@@ -84,7 +86,7 @@ export function createSSERoutes() {
|
||||
if (!result.success) {
|
||||
return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400)
|
||||
}
|
||||
const success = sseAggregator.addDirectories(result.data.clientId, result.data.directories)
|
||||
const success = aggregator.addDirectories(result.data.clientId, result.data.directories)
|
||||
if (!success) {
|
||||
return c.json({ success: false, error: 'Client not found' }, 404)
|
||||
}
|
||||
@@ -97,7 +99,7 @@ export function createSSERoutes() {
|
||||
if (!result.success) {
|
||||
return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400)
|
||||
}
|
||||
const success = sseAggregator.removeDirectories(result.data.clientId, result.data.directories)
|
||||
const success = aggregator.removeDirectories(result.data.clientId, result.data.directories)
|
||||
if (!success) {
|
||||
return c.json({ success: false, error: 'Client not found' }, 404)
|
||||
}
|
||||
@@ -110,7 +112,7 @@ export function createSSERoutes() {
|
||||
if (!result.success) {
|
||||
return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400)
|
||||
}
|
||||
const success = sseAggregator.setClientVisibility(
|
||||
const success = aggregator.setClientVisibility(
|
||||
result.data.clientId,
|
||||
result.data.visible,
|
||||
result.data.activeSessionId ?? null,
|
||||
@@ -124,10 +126,10 @@ export function createSSERoutes() {
|
||||
|
||||
app.get('/status', (c) => {
|
||||
return c.json({
|
||||
...sseAggregator.getConnectionStatus(),
|
||||
clients: sseAggregator.getClientCount(),
|
||||
directories: sseAggregator.getActiveDirectories(),
|
||||
activeSessions: sseAggregator.getActiveSessions()
|
||||
...aggregator.getConnectionStatus(),
|
||||
clients: aggregator.getClientCount(),
|
||||
directories: aggregator.getActiveDirectories(),
|
||||
activeSessions: aggregator.getActiveSessions()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+40
-27
@@ -2,11 +2,34 @@ import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { logger } from '../utils/logger'
|
||||
import { toContentfulStatus } from '../utils/error-utils'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
normalizeToBaseUrl,
|
||||
discoverModelsCached,
|
||||
} from '../utils/discovery-cache'
|
||||
import { type STTConfig } from '@opencode-manager/shared'
|
||||
|
||||
const SttTranscriptionResultSchema = z.object({
|
||||
text: z.string().optional(),
|
||||
})
|
||||
|
||||
const SttErrorDetailsSchema = z.object({
|
||||
error: z.object({ message: z.string() }).optional(),
|
||||
detail: z.object({ message: z.string() }).optional(),
|
||||
message: z.string().optional(),
|
||||
})
|
||||
|
||||
function parseSttErrorDetails(errorText: string): string {
|
||||
try {
|
||||
const parsed = SttErrorDetailsSchema.safeParse(JSON.parse(errorText))
|
||||
if (!parsed.success) {
|
||||
return errorText
|
||||
}
|
||||
return parsed.data.error?.message || parsed.data.detail?.message || parsed.data.message || errorText
|
||||
} catch {
|
||||
return errorText
|
||||
}
|
||||
}
|
||||
|
||||
export function createSTTRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
@@ -24,7 +47,7 @@ export function createSTTRoutes(db: Database) {
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
const settings = settingsService.getSettings(userId)
|
||||
const sttConfig = settings.preferences.stt as STTConfig | undefined
|
||||
const sttConfig = settings.preferences.stt
|
||||
|
||||
if (!sttConfig?.enabled) {
|
||||
return c.json({ error: 'STT is not enabled' }, 400)
|
||||
@@ -82,21 +105,9 @@ export function createSTTRoutes(db: Database) {
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
logger.error(`STT API error: ${response.status} - ${errorText}`)
|
||||
const status = response.status >= 400 && response.status < 600 ? response.status as 400 | 500 : 500
|
||||
const status = response.status >= 400 && response.status < 600 ? toContentfulStatus(response.status) : 500
|
||||
|
||||
let errorDetails = errorText
|
||||
try {
|
||||
const errorJson = JSON.parse(errorText)
|
||||
if (errorJson.error?.message) {
|
||||
errorDetails = errorJson.error.message
|
||||
} else if (errorJson.detail?.message) {
|
||||
errorDetails = errorJson.detail.message
|
||||
} else if (errorJson.message) {
|
||||
errorDetails = errorJson.message
|
||||
}
|
||||
} catch {
|
||||
// Use raw error text if parsing fails
|
||||
}
|
||||
const errorDetails = parseSttErrorDetails(errorText)
|
||||
|
||||
return c.json({
|
||||
error: 'STT API request failed',
|
||||
@@ -104,18 +115,20 @@ export function createSTTRoutes(db: Database) {
|
||||
}, status)
|
||||
}
|
||||
|
||||
const result = await response.json() as { text?: string } & Record<string, unknown>
|
||||
const rawResult = await response.json()
|
||||
const parsedResult = SttTranscriptionResultSchema.safeParse(rawResult)
|
||||
const transcribedText = parsedResult.success ? parsedResult.data.text : undefined
|
||||
|
||||
if (!result.text || typeof result.text !== 'string') {
|
||||
logger.error('STT API response missing text field:', { result })
|
||||
return c.json({
|
||||
error: 'STT API returned invalid response',
|
||||
details: `Response missing text field. Full response: ${JSON.stringify(result)}`
|
||||
if (!transcribedText) {
|
||||
logger.error('STT API response missing text field:', { result: rawResult })
|
||||
return c.json({
|
||||
error: 'STT API returned invalid response',
|
||||
details: `Response missing text field. Full response: ${JSON.stringify(rawResult)}`
|
||||
}, 500)
|
||||
}
|
||||
|
||||
logger.info(`STT transcription successful: ${result.text.substring(0, 50)}...`)
|
||||
return c.json({ text: result.text })
|
||||
logger.info(`STT transcription successful: ${transcribedText.substring(0, 50)}...`)
|
||||
return c.json({ text: transcribedText })
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return new Response(null, { status: 499 })
|
||||
@@ -132,7 +145,7 @@ export function createSTTRoutes(db: Database) {
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
const settings = settingsService.getSettings(userId)
|
||||
const sttConfig = settings.preferences.stt as STTConfig | undefined
|
||||
const sttConfig = settings.preferences.stt
|
||||
|
||||
if (!sttConfig?.endpoint) {
|
||||
return c.json({ error: 'STT not configured' }, 400)
|
||||
@@ -153,7 +166,7 @@ export function createSTTRoutes(db: Database) {
|
||||
...sttConfig,
|
||||
availableModels: models,
|
||||
lastModelsFetch: Date.now(),
|
||||
} as STTConfig,
|
||||
},
|
||||
}, userId)
|
||||
}
|
||||
|
||||
@@ -168,7 +181,7 @@ export function createSTTRoutes(db: Database) {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const settingsService = new SettingsService(db)
|
||||
const settings = settingsService.getSettings(userId)
|
||||
const sttConfig = settings.preferences.stt as STTConfig | undefined
|
||||
const sttConfig = settings.preferences.stt
|
||||
|
||||
return c.json({
|
||||
enabled: sttConfig?.enabled || false,
|
||||
|
||||
Loaded 100 of 1110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user