diff --git a/backend/src/db/migrations/011-repo-last-accessed.ts b/backend/src/db/migrations/011-repo-last-accessed.ts new file mode 100644 index 00000000..8b440f45 --- /dev/null +++ b/backend/src/db/migrations/011-repo-last-accessed.ts @@ -0,0 +1,25 @@ +import type { Migration } from '../migration-runner' + +interface ColumnInfo { + name: string +} + +const migration: Migration = { + version: 11, + name: 'repo-last-accessed', + + up(db) { + const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[] + const existing = new Set(tableInfo.map((column) => column.name)) + + if (!existing.has('last_accessed_at')) { + db.run('ALTER TABLE repos ADD COLUMN last_accessed_at INTEGER') + } + }, + + down(db) { + void db + }, +} + +export default migration \ No newline at end of file diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index 705443db..d2ae1e91 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -9,6 +9,7 @@ import migration007 from './007-schedules' import migration008 from './008-schedule-cron-support' import migration009 from './009-repo-source-path' import migration010 from './009-prompt-templates' +import migration011 from './011-repo-last-accessed' export const allMigrations: Migration[] = [ migration001, @@ -21,4 +22,5 @@ export const allMigrations: Migration[] = [ migration008, migration009, migration010, + migration011, ] diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index cc704bae..26a5f7e0 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -14,6 +14,7 @@ interface RepoRow { clone_status: string cloned_at: number last_pulled?: number + last_accessed_at?: number opencode_config_name?: string is_worktree?: number is_local?: number @@ -33,12 +34,20 @@ function rowToRepo(row: RepoRow): Repo { cloneStatus: row.clone_status as Repo['cloneStatus'], clonedAt: row.cloned_at, lastPulled: row.last_pulled, + lastAccessedAt: row.last_accessed_at, openCodeConfigName: row.opencode_config_name, isWorktree: row.is_worktree ? Boolean(row.is_worktree) : undefined, isLocal: row.is_local ? Boolean(row.is_local) : undefined, } } +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 + + return row ? rowToRepo(row) : null +} + export function createRepo(db: Database, repo: CreateRepoInput): Repo { const normalizedPath = repo.localPath.trim().replace(/\/+$/, '') @@ -53,8 +62,8 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo { } const stmt = db.prepare(` - INSERT INTO repos (repo_url, local_path, source_path, branch, default_branch, clone_status, cloned_at, is_worktree, is_local) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO repos (repo_url, local_path, source_path, branch, default_branch, clone_status, cloned_at, last_accessed_at, is_worktree, is_local) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `) try { @@ -66,6 +75,7 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo { repo.defaultBranch, repo.cloneStatus, repo.clonedAt, + repo.clonedAt, repo.isWorktree ? 1 : 0, repo.isLocal ? 1 : 0 ) @@ -96,13 +106,6 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo { } } -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 - - return row ? rowToRepo(row) : null -} - export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: string): Repo | null { const query = branch ? 'SELECT * FROM repos WHERE repo_url = ? AND branch = ?' @@ -189,6 +192,14 @@ export function updateLastPulled(db: Database, id: number): void { } } +export function updateLastAccessed(db: Database, id: number): void { + const stmt = db.prepare('UPDATE repos SET last_accessed_at = ? WHERE id = ?') + const result = stmt.run(Date.now(), id) + if (result.changes === 0) { + throw new Error(`Repository with id ${id} not found`) + } +} + export function updateRepoBranch(db: Database, id: number, branch: string): void { const stmt = db.prepare('UPDATE repos SET branch = ? WHERE id = ?') const result = stmt.run(branch, id) @@ -201,3 +212,4 @@ export function deleteRepo(db: Database, id: number): void { const stmt = db.prepare('DELETE FROM repos WHERE id = ?') stmt.run(id) } + diff --git a/backend/src/routes/repo-git.ts b/backend/src/routes/repo-git.ts index 070f0094..beb9463b 100644 --- a/backend/src/routes/repo-git.ts +++ b/backend/src/routes/repo-git.ts @@ -1,7 +1,7 @@ import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import type { ContentfulStatusCode } from 'hono/utils/http-status' -import * as db from '../db/queries' +import { getRepoById } from '../db/queries' import { logger } from '../utils/logger' import { parseGitError } from '../utils/git-errors' import { GitService } from '../services/git/GitService' @@ -17,7 +17,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.get('/:id/git/status', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -94,7 +94,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json({ error: 'path query parameter is required' }, 400) } - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -124,7 +124,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json({ error: 'path query parameter is required' }, 400) } - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) } @@ -144,7 +144,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/fetch', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -167,7 +167,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/pull', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -190,7 +190,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/commit', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -220,7 +220,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/push', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -246,7 +246,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/stage', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -276,7 +276,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/unstage', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -306,7 +306,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/discard', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -337,7 +337,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS try { const id = parseInt(c.req.param('id')) const hash = c.req.param('hash') - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -369,7 +369,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS const id = parseInt(c.req.param('id')) const hash = c.req.param('hash') const filePath = c.req.query('path') - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -398,7 +398,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.get('/:id/git/log', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -421,7 +421,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.post('/:id/git/reset', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -451,7 +451,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS app.get('/:id/git/branches', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index c3fb087d..e62d9944 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono' import type { ContentfulStatusCode } from 'hono/utils/http-status' import type { Database } from 'bun:sqlite' import { DiscoverReposRequestSchema } from '@opencode-manager/shared/schemas' -import * as db from '../db/queries' +import { listRepos, getRepoById, updateLastAccessed, updateRepoConfigName } from '../db/queries' import * as repoService from '../services/repo' import * as archiveService from '../services/archive' import { SettingsService } from '../services/settings' @@ -61,7 +61,7 @@ export function createRepoRoutes(database: Database, gitAuthService: GitAuthServ if (configContent) { const openCodeConfigPath = getOpenCodeConfigFilePath() await writeFileContent(openCodeConfigPath, configContent) - db.updateRepoConfigName(database, repo.id, openCodeConfigName) + updateRepoConfigName(database, repo.id, openCodeConfigName) logger.info(`Applied config '${openCodeConfigName}' to: ${openCodeConfigPath}`) } } @@ -100,7 +100,7 @@ app.get('/', async (c) => { try { const settingsService = new SettingsService(database) const settings = settingsService.getSettings() - const repos = db.listRepos(database, settings.preferences.repoOrder) + const repos = listRepos(database, settings.preferences.repoOrder) const reposWithCurrentBranch = await Promise.all( repos.map(async (repo) => { @@ -139,7 +139,7 @@ app.get('/', async (c) => { app.get('/:id', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -153,11 +153,29 @@ app.get('/', async (c) => { return c.json({ error: getErrorMessage(error) }, 500) } }) + + app.post('/:id/access', async (c) => { + try { + const id = parseInt(c.req.param('id')) + const repo = getRepoById(database, id) + + if (!repo) { + return c.json({ error: 'Repo not found' }, 404) + } + + updateLastAccessed(database, id) + + return c.json({ success: true }) + } catch (error: unknown) { + logger.error('Failed to update repo access:', error) + return c.json({ error: getErrorMessage(error) }, 500) + } + }) app.delete('/:id', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -177,7 +195,7 @@ app.get('/', async (c) => { const id = parseInt(c.req.param('id')) await repoService.pullRepo(database, gitAuthService, id) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) return c.json(repo) } catch (error: unknown) { logger.error('Failed to pull repo:', error) @@ -188,7 +206,7 @@ app.get('/', async (c) => { app.post('/:id/config/switch', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -212,7 +230,7 @@ app.get('/', async (c) => { await writeFileContent(openCodeConfigPath, configContent) - db.updateRepoConfigName(database, id, configName) + updateRepoConfigName(database, id, configName) logger.info(`Switched config for repo ${id} to '${configName}'`) logger.info(`Updated OpenCode config: ${openCodeConfigPath}`) @@ -221,7 +239,7 @@ app.get('/', async (c) => { await opencodeServerManager.stop() await opencodeServerManager.start() - const updatedRepo = db.getRepoById(database, id) + const updatedRepo = getRepoById(database, id) return c.json(updatedRepo) } catch (error: unknown) { logger.error('Failed to switch repo config:', error) @@ -232,7 +250,7 @@ app.get('/', async (c) => { app.post('/:id/branch/switch', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -247,7 +265,7 @@ app.get('/', async (c) => { await repoService.switchBranch(database, gitAuthService, id, branch) - const updatedRepo = db.getRepoById(database, id) + const updatedRepo = getRepoById(database, id) const currentBranch = await repoService.getCurrentBranch(updatedRepo!, gitAuthService.getGitEnvironment()) return c.json({ ...updatedRepo, currentBranch }) @@ -260,7 +278,7 @@ app.get('/', async (c) => { app.post('/:id/branch/create', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -275,7 +293,7 @@ app.get('/', async (c) => { await repoService.createBranch(database, gitAuthService, id, branch) - const updatedRepo = db.getRepoById(database, id) + const updatedRepo = getRepoById(database, id) const currentBranch = await repoService.getCurrentBranch(updatedRepo!, gitAuthService.getGitEnvironment()) return c.json({ ...updatedRepo, currentBranch }) @@ -288,7 +306,7 @@ app.get('/', async (c) => { app.get('/:id/download', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -335,7 +353,7 @@ app.get('/', async (c) => { app.post('/:id/reset-permissions', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo = db.getRepoById(database, id) + const repo = getRepoById(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 27cf4e6c..72fa8154 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite' import { SettingsService } from '../services/settings' import { writeFileContent, readFileContent, fileExists } from '../services/file-operations' import { patchOpenCodeConfig, proxyToOpenCodeWithDirectory } from '../services/proxy' -import { getOpenCodeConfigFilePath, getAgentsMdPath, ENV } from '@opencode-manager/shared/config/env' +import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/shared/config/env' import { UserPreferencesSchema, OpenCodeConfigSchema, @@ -19,7 +19,7 @@ import { SkillScopeSchema, } from '@opencode-manager/shared' import { logger } from '../utils/logger' -import { opencodeServerManager } from '../services/opencode-single-server' +import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server' import type { GitAuthService } from '../services/git-auth' import { DEFAULT_AGENTS_MD } from '../constants' import { validateSSHPrivateKey } from '../utils/ssh-validation' @@ -56,6 +56,18 @@ function getOpenCodeInstallMethod(): string { return 'curl' } +function getOpenCodeConfigContentToWrite( + rawContent: string, + appliedConfig?: Record, + removedFields?: string[] +): string { + if (!appliedConfig || !removedFields || removedFields.length === 0) { + return rawContent + } + + return JSON.stringify(appliedConfig, null, 2) +} + function execWithTimeout( command: string | [executable: string, ...args: string[]], timeoutMs: number, @@ -291,20 +303,54 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic const userId = c.req.query('userId') || 'default' const body = await c.req.json() const validated = CreateOpenCodeConfigSchema.parse(body) - - const config = settingsService.createOpenCodeConfig(validated, userId) - - if (config.isDefault) { - const configPath = getOpenCodeConfigFilePath() - await writeFileContent(configPath, config.rawContent) - logger.info(`Wrote default config to: ${configPath}`) - - const patchResult = await patchOpenCodeConfig(config.content) + + if (validated.isDefault) { + settingsService.saveLastKnownGoodConfig(userId) + + const provisionalConfig = settingsService.createOpenCodeConfig( + { ...validated, isDefault: false }, + userId, + { suppressAutoDefault: true } + ) + + const patchResult = await patchOpenCodeConfig(provisionalConfig.content) if (!patchResult.success) { - return c.json({ error: 'Config saved but failed to apply', details: patchResult.error }, 500) + settingsService.deleteOpenCodeConfig(provisionalConfig.name, userId) + return c.json({ + error: 'Config validation failed', + details: patchResult.error, + validationIssues: patchResult.details, + removedFields: patchResult.removedFields + }, 400) } + + const contentToWrite = getOpenCodeConfigContentToWrite( + provisionalConfig.rawContent, + patchResult.appliedConfig, + patchResult.removedFields + ) + const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, { + content: contentToWrite, + isDefault: true, + }, userId) + + if (!config) { + return c.json({ error: 'Failed to finalize OpenCode config creation' }, 500) + } + + const configPath = getOpenCodeConfigFilePath() + await writeFileContent(configPath, contentToWrite) + logger.info(`Wrote default config to: ${configPath}`) + + if (patchResult.removedFields && patchResult.removedFields.length > 0) { + logger.info(`Config applied with auto-removed fields: ${patchResult.removedFields.join(', ')}`) + return c.json({ ...config, removedFields: patchResult.removedFields }) + } + + return c.json(config) } - + + const config = settingsService.createOpenCodeConfig(validated, userId) return c.json(config) } catch (error) { logger.error('Failed to create OpenCode config:', error) @@ -334,10 +380,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic } if (config.isDefault) { - const configPath = getOpenCodeConfigFilePath() - await writeFileContent(configPath, config.rawContent) - logger.info(`Wrote default config to: ${configPath}`) - const newAgents = config.content?.agent const agentsChanged = JSON.stringify(existingAgents) !== JSON.stringify(newAgents) @@ -347,7 +389,25 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic } else { const patchResult = await patchOpenCodeConfig(config.content) if (!patchResult.success) { - return c.json({ error: 'Config saved but failed to apply', details: patchResult.error }, 500) + return c.json({ + error: 'Config saved but failed to apply', + details: patchResult.error, + validationIssues: patchResult.details, + removedFields: patchResult.removedFields + }, 500) + } + + const configPath = getOpenCodeConfigFilePath() + const contentToWrite = patchResult.removedFields && patchResult.removedFields.length > 0 + ? JSON.stringify(config.content, null, 2) + : config.rawContent + + await writeFileContent(configPath, contentToWrite) + logger.info(`Wrote default config to: ${configPath}`) + + if (patchResult.removedFields && patchResult.removedFields.length > 0) { + logger.info(`Config applied with auto-removed fields: ${patchResult.removedFields.join(', ')}`) + return c.json({ ...config, removedFields: patchResult.removedFields }) } } } @@ -386,18 +446,46 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic settingsService.saveLastKnownGoodConfig(userId) + const existingConfig = settingsService.getOpenCodeConfigByName(configName, userId) + if (!existingConfig) { + return c.json({ error: 'Config not found' }, 404) + } + + const patchResult = await patchOpenCodeConfig(existingConfig.content) + if (!patchResult.success) { + return c.json({ + error: 'Config validation failed', + details: patchResult.error, + validationIssues: patchResult.details, + removedFields: patchResult.removedFields + }, 400) + } + + const contentToWrite = getOpenCodeConfigContentToWrite( + existingConfig.rawContent, + patchResult.appliedConfig, + patchResult.removedFields + ) + const updatedConfig = settingsService.updateOpenCodeConfig(configName, { + content: contentToWrite, + }, userId) + + if (!updatedConfig) { + return c.json({ error: 'Failed to update OpenCode config' }, 500) + } + const config = settingsService.setDefaultOpenCodeConfig(configName, userId) if (!config) { return c.json({ error: 'Config not found' }, 404) } const configPath = getOpenCodeConfigFilePath() - await writeFileContent(configPath, config.rawContent) + await writeFileContent(configPath, contentToWrite) logger.info(`Wrote default config '${configName}' to: ${configPath}`) - const patchResult = await patchOpenCodeConfig(config.content) - if (!patchResult.success) { - return c.json({ error: 'Config saved but failed to apply', details: patchResult.error }, 500) + if (patchResult.removedFields && patchResult.removedFields.length > 0) { + logger.info(`Config applied with auto-removed fields: ${patchResult.removedFields.join(', ')}`) + return c.json({ ...config, removedFields: patchResult.removedFields }) } return c.json(config) @@ -517,13 +605,21 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic app.post('/opencode-reload', async (c) => { try { logger.info('OpenCode configuration reload requested') - await fetch(`http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}/config`, { - method: 'GET' - }) await opencodeServerManager.reloadConfig() return c.json({ success: true, message: 'OpenCode configuration reloaded successfully' }) } catch (error) { logger.error('Failed to reload OpenCode config:', error) + if (error instanceof ConfigReloadError) { + const details = error.validationIssues.length > 0 + ? error.validationIssues.map((issue) => `${issue.path}: ${issue.message}`).join('; ') + : error.message + return c.json({ + error: error.message, + details, + validationIssues: error.validationIssues, + removedFields: error.removedFields + }, 500) + } return c.json({ error: 'Failed to reload OpenCode configuration', details: error instanceof Error ? error.message : 'Unknown error' diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index edc8eefc..78bf155e 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -19,6 +19,7 @@ import { SettingsService } from './settings' import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env' import type { Database } from 'bun:sqlite' import { compareVersions } from '../utils/version-utils' +import { patchOpenCodeConfig } from './proxy' const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST @@ -30,6 +31,18 @@ type StartupValidationIssue = { message: string } +export class ConfigReloadError extends Error { + validationIssues: StartupValidationIssue[] + removedFields: string[] + + constructor(message: string, validationIssues: StartupValidationIssue[] = [], removedFields: string[] = []) { + super(message) + this.name = 'ConfigReloadError' + this.validationIssues = validationIssues + this.removedFields = removedFields + } +} + function parseStartupValidationIssues(stderrOutput: string): StartupValidationIssue[] { const match = stderrOutput.match(/ZodError:\s*(\[[\s\S]*?\])(?:\n\s+at |$)/) if (!match?.[1]) { @@ -379,16 +392,22 @@ class OpenCodeServerManager { throw new Error(`Failed to get current config: ${response.status}`) } - const currentConfig = await response.json() + const currentConfig = await response.json() as Record logger.info('Triggering OpenCode config reload via PATCH') - const patchResponse = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/config`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(currentConfig) - }) - - if (!patchResponse.ok) { - throw new Error(`Failed to reload config: ${patchResponse.status}`) + + const patchResult = await patchOpenCodeConfig(currentConfig) + if (!patchResult.success) { + const errorMessage = patchResult.error || 'Failed to reload config' + const validationIssues = patchResult.details || [] + const removedFields = patchResult.removedFields || [] + if (validationIssues.length > 0) { + const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ') + logger.error(`Config reload validation errors: ${issueSummary}`) + } + if (removedFields.length > 0) { + logger.info(`Removed fields during config reload: ${removedFields.join(', ')}`) + } + throw new ConfigReloadError(errorMessage, validationIssues, removedFields) } logger.info('OpenCode configuration reloaded successfully') diff --git a/backend/src/services/proxy.ts b/backend/src/services/proxy.ts index bad413bb..5776573e 100644 --- a/backend/src/services/proxy.ts +++ b/backend/src/services/proxy.ts @@ -1,5 +1,6 @@ import { logger } from '../utils/logger' import { ENV } from '@opencode-manager/shared/config/env' +import { parseJsonc } from '@opencode-manager/shared/utils' export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}` @@ -43,9 +44,143 @@ export async function deleteOpenCodeAuth(providerId: string): Promise { } } +export type PatchConfigValidationIssue = { + path: string + message: string +} + export type PatchConfigResult = { success: boolean error?: string + details?: PatchConfigValidationIssue[] + removedFields?: string[] + appliedConfig?: Record +} + +function getIssuePath(value: unknown): string { + if (Array.isArray(value)) { + const path = value + .map((part) => typeof part === 'string' || typeof part === 'number' ? String(part) : '') + .filter(Boolean) + .join('.') + return path || 'root' + } + + if (typeof value === 'string' && value.length > 0) { + return value + } + + if (typeof value === 'number') { + return String(value) + } + + return 'root' +} + +function getIssueMessage(value: unknown): string { + if (typeof value === 'string' && value.length > 0) { + return value + } + + return 'Validation error' +} + +function extractValidationIssues(value: unknown): PatchConfigValidationIssue[] { + if (!Array.isArray(value)) { + return [] + } + + return value.flatMap((item) => { + if (!item || typeof item !== 'object') { + return [] + } + + const issue = item as Record + const nestedIssues = extractValidationIssues(issue.issues ?? issue.errors) + if (nestedIssues.length > 0) { + return nestedIssues + } + + if ( + typeof issue.message === 'string' + || typeof issue.path === 'string' + || Array.isArray(issue.path) + || typeof issue.instancePath === 'string' + || Array.isArray(issue.instancePath) + ) { + return [{ + path: getIssuePath(issue.path ?? issue.instancePath), + message: getIssueMessage(issue.message), + }] + } + + return [] + }) +} + +function removeFieldFromConfig(config: Record, path: string): Record { + const result = JSON.parse(JSON.stringify(config)) as Record + const parts = path.split('.') + + let current: Record = result + for (let i = 0; i < parts.length - 1; i++) { + const part = parts[i] + if (!part || !current[part] || typeof current[part] !== 'object') { + return result + } + current = current[part] as Record + } + + const lastPart = parts[parts.length - 1] + if (lastPart) { + delete current[lastPart] + } + + return result +} + +function parseErrorResponse(responseText: string): { details: PatchConfigValidationIssue[]; errorMessage: string } { + const details: PatchConfigValidationIssue[] = [] + let errorMessage = 'Unknown error' + + try { + const errorBody = parseJsonc(responseText) as Record + const structuredIssues = extractValidationIssues( + errorBody?.errors + ?? errorBody?.issues + ?? (errorBody?.data && typeof errorBody.data === 'object' + ? (errorBody.data as Record).errors ?? (errorBody.data as Record).issues + : undefined) + ) + + if (structuredIssues.length > 0) { + details.push(...structuredIssues) + errorMessage = details.map((d) => `${d.path}: ${d.message}`).join('; ') + } else if (errorBody?.name === 'ConfigInvalidError' && errorBody?.data) { + const data = errorBody.data as { issues?: Array<{ message: string; path?: string[] }> } + if (data.issues) { + for (const issue of data.issues) { + const path = issue.path ? issue.path.join('.') : 'root' + details.push({ path, message: issue.message }) + } + errorMessage = details.map((d) => `${d.path}: ${d.message}`).join('; ') + } + } else if (typeof errorBody?.error === 'string') { + errorMessage = errorBody.error + } else if (typeof errorBody?.message === 'string') { + errorMessage = errorBody.message + } else if (typeof errorBody?.success === 'boolean' && errorBody.success === false && errorBody?.data) { + errorMessage = 'Config validation failed' + } else { + const snippet = responseText.slice(0, 300) + errorMessage = `Request failed (${snippet.length < responseText.length ? 'truncated' : 'raw'} response): ${snippet}` + } + } catch { + const snippet = responseText.slice(0, 300) + errorMessage = `Parse error: ${snippet}` + } + + return { details, errorMessage } } export async function patchOpenCodeConfig(config: Record): Promise { @@ -55,36 +190,72 @@ export async function patchOpenCodeConfig(config: Record): Prom headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config), }) - + if (response.ok) { logger.info('Patched OpenCode config via API') - return { success: true } + return { success: true, appliedConfig: config } } + + const responseText = await response.text() + const { details, errorMessage: initialError } = parseErrorResponse(responseText) - let errorMessage = `${response.status} ${response.statusText}` - try { - const errorBody = await response.json() as Record - if (errorBody?.name === 'ConfigInvalidError' && errorBody?.data) { - const data = errorBody.data as { issues?: Array<{ message: string; path?: string[] }> } - if (data.issues) { - const issues = data.issues - .map((issue) => - issue.path ? `${issue.path.join('.')}: ${issue.message}` : issue.message - ) - .join('; ') - errorMessage = `Invalid config: ${issues}` - } - } else if (typeof errorBody?.error === 'string') { - errorMessage = errorBody.error - } else if (typeof errorBody?.message === 'string') { - errorMessage = errorBody.message + if (details.length === 0) { + logger.error(`Failed to patch OpenCode config: ${initialError}`) + return { success: false, error: initialError, details } + } + + logger.warn(`OpenCode rejected config with validation errors: ${initialError}`) + + const problematicPaths = [...new Set(details.map((d) => d.path))] + const removablePaths = problematicPaths.filter((path) => path !== 'root' && path.split('.').length <= 3) + const nonRemovablePaths = problematicPaths.filter((path) => path === 'root' || path.split('.').length > 3) + + if (nonRemovablePaths.length > 0) { + logger.error(`Failed to patch OpenCode config: ${initialError}`) + return { success: false, error: initialError, details } + } + + if (removablePaths.length === 0) { + logger.error(`Failed to patch OpenCode config: ${initialError}`) + return { success: false, error: initialError, details } + } + + let cleanedConfig = config + const removedFields: string[] = [] + + for (const path of removablePaths) { + cleanedConfig = removeFieldFromConfig(cleanedConfig, path) + removedFields.push(path) + logger.info(`Removed problematic field from config: ${path}`) + } + + logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`) + const retryResponse = await fetch(`${OPENCODE_SERVER_URL}/config`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(cleanedConfig), + }) + + if (retryResponse.ok) { + logger.info('Patched OpenCode config via API after removing invalid fields') + return { + success: true, + appliedConfig: cleanedConfig, + removedFields, + details } - } catch { - // Use default error message if we can't parse response body } - - logger.error(`Failed to patch OpenCode config: ${errorMessage}`) - return { success: false, error: errorMessage } + + const retryResponseText = await retryResponse.text() + const { details: retryDetails, errorMessage } = parseErrorResponse(retryResponseText) + logger.error(`Failed to patch OpenCode config even after removing invalid fields: ${errorMessage}`) + + return { + success: false, + error: errorMessage, + details: retryDetails.length > 0 ? retryDetails : details, + removedFields + } } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error' logger.error('Failed to patch OpenCode config:', error) @@ -244,4 +415,3 @@ export async function proxyMcpAuthAuthenticate( }) } } - diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index d9cddde3..1bd6f7fc 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -2,7 +2,7 @@ import fs from 'fs/promises' import { existsSync, rmSync } from 'node:fs' import { executeCommand } from '../utils/process' import { ensureDirectoryExists } from './file-operations' -import * as db from '../db/queries' +import { createRepo, getRepoByLocalPath, getRepoBySourcePath, getRepoById, updateRepoStatus, updateRepoBranch, updateLastPulled, deleteRepo, getRepoByUrlAndBranch } from '../db/queries' import type { Database } from 'bun:sqlite' import type { Repo, CreateRepoInput } from '../types/repo' import { logger } from '../utils/logger' @@ -186,14 +186,14 @@ async function createWorkspaceLink(alias: string, sourcePath: string): Promise { - const existingRepo = db.getRepoBySourcePath(database, sourcePath) + const existingRepo = getRepoBySourcePath(database, sourcePath) if (existingRepo) { return existingRepo.localPath } const candidates = buildWorkspaceAliasCandidates(sourcePath, rootPath) for (const candidate of candidates) { - const existingByLocalPath = db.getRepoByLocalPath(database, candidate) + const existingByLocalPath = getRepoByLocalPath(database, candidate) if (!existingByLocalPath && await isWorkspaceAliasAvailable(candidate, sourcePath)) { return candidate } @@ -203,7 +203,7 @@ async function pickWorkspaceAlias(database: Database, sourcePath: string, rootPa let suffix = 2 while (true) { const candidate = `${baseCandidate}-${suffix}` - const existingByLocalPath = db.getRepoByLocalPath(database, candidate) + const existingByLocalPath = getRepoByLocalPath(database, candidate) if (!existingByLocalPath && await isWorkspaceAliasAvailable(candidate, sourcePath)) { return candidate } @@ -249,7 +249,7 @@ async function registerExistingLocalRepo( ): Promise<{ repo: Repo; existed: boolean }> { const normalizedSourcePath = normalizeAbsolutePath(sourcePath) const env = gitAuthService.getGitEnvironment() - const existingBySourcePath = db.getRepoBySourcePath(database, normalizedSourcePath) + const existingBySourcePath = getRepoBySourcePath(database, normalizedSourcePath) if (existingBySourcePath) { logger.info(`Local repo already exists in database: ${normalizedSourcePath}`) @@ -277,7 +277,7 @@ async function registerExistingLocalRepo( const workspaceLocalPath = getWorkspaceLocalPathForRepo(normalizedSourcePath) if (workspaceLocalPath) { - const existingByLocalPath = db.getRepoByLocalPath(database, workspaceLocalPath) + const existingByLocalPath = getRepoByLocalPath(database, workspaceLocalPath) if (existingByLocalPath) { logger.info(`Workspace repo already exists in database: ${workspaceLocalPath}`) return { repo: existingByLocalPath, existed: true } @@ -289,7 +289,7 @@ async function registerExistingLocalRepo( await createWorkspaceLink(repoLocalPath, normalizedSourcePath) } - const repo = db.createRepo(database, { + const repo = createRepo(database, { localPath: repoLocalPath, sourcePath: workspaceLocalPath ? undefined : normalizedSourcePath, branch: branch || currentBranch || undefined, @@ -504,7 +504,7 @@ export async function initLocalRepo( const repoLocalPath = normalizedInputPath const targetPath = path.join(getReposPath(), repoLocalPath) - const existing = db.getRepoByLocalPath(database, repoLocalPath) + const existing = getRepoByLocalPath(database, repoLocalPath) if (existing) { logger.info(`Local repo already exists in database: ${repoLocalPath}`) return existing @@ -523,7 +523,7 @@ export async function initLocalRepo( let directoryCreated = false try { - repo = db.createRepo(database, createRepoInput) + repo = createRepo(database, createRepoInput) logger.info(`Created database record for local repo: ${repoLocalPath} (id: ${repo.id})`) } catch (error: unknown) { logger.error(`Failed to create database record for local repo: ${repoLocalPath}`, error) @@ -550,14 +550,14 @@ export async function initLocalRepo( throw new Error(`Git initialization failed - directory exists but is not a valid git repository`) } - db.updateRepoStatus(database, repo.id, 'ready') + updateRepoStatus(database, repo.id, 'ready') logger.info(`Local git repo ready: ${repoLocalPath}`) return { ...repo, cloneStatus: 'ready' } } catch (error: unknown) { logger.error(`Failed to initialize local repo, rolling back: ${repoLocalPath}`, error) try { - db.deleteRepo(database, repo.id) + deleteRepo(database, repo.id) logger.info(`Rolled back database record for repo id: ${repo.id}`) } catch (dbError: unknown) { logger.error(`Failed to rollback database record for repo id ${repo.id}:`, getErrorMessage(dbError)) @@ -594,7 +594,7 @@ export async function cloneRepo( const worktreeDirName = branch && useWorktree ? `${repoName}-${branch.replace(/[\\/]/g, '-')}` : repoName const localPath = worktreeDirName - const existing = db.getRepoByUrlAndBranch(database, normalizedRepoUrl, branch) + const existing = getRepoByUrlAndBranch(database, normalizedRepoUrl, branch) if (existing) { logger.info(`Repo branch already exists: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}`) @@ -622,7 +622,7 @@ export async function cloneRepo( createRepoInput.isWorktree = true } - const repo = db.createRepo(database, createRepoInput) + const repo = createRepo(database, createRepoInput) try { const env = { @@ -741,7 +741,7 @@ export async function cloneRepo( } } - db.updateRepoStatus(database, repo.id, 'ready') + updateRepoStatus(database, repo.id, 'ready') return { ...repo, cloneStatus: 'ready' } } else { logger.warn(`Invalid repository directory found, removing and recloning: ${baseRepoDirName}`) @@ -805,12 +805,12 @@ export async function cloneRepo( } } - db.updateRepoStatus(database, repo.id, 'ready') + updateRepoStatus(database, repo.id, 'ready') logger.info(`Repo ready: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}${shouldUseWorktree ? ' (worktree)' : ''}`) return { ...repo, cloneStatus: 'ready' } } catch (error: unknown) { logger.error(`Failed to create repo: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}`, error) - db.deleteRepo(database, repo.id) + deleteRepo(database, repo.id) throw error } finally { await gitAuthService.cleanupSSHKey() @@ -829,7 +829,7 @@ export async function switchBranch( repoId: number, branch: string ): Promise { - const repo = db.getRepoById(database, repoId) + const repo = getRepoById(database, repoId) if (!repo) { throw new Error(`Repo not found: ${repoId}`) } @@ -851,7 +851,7 @@ export async function switchBranch( logger.info(`Successfully switched to branch: ${sanitizedBranch}`) - db.updateRepoBranch(database, repoId, sanitizedBranch) + updateRepoBranch(database, repoId, sanitizedBranch) } catch (error: unknown) { logger.error(`Failed to switch branch for repo ${repoId}:`, error) throw error @@ -859,7 +859,7 @@ export async function switchBranch( } export async function createBranch(database: Database, gitAuthService: GitAuthService, repoId: number, branch: string): Promise { - const repo = db.getRepoById(database, repoId) + const repo = getRepoById(database, repoId) if (!repo) { throw new Error(`Repo not found: ${repoId}`) } @@ -877,7 +877,7 @@ export async function createBranch(database: Database, gitAuthService: GitAuthSe await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch], { env }) logger.info(`Successfully created and switched to branch: ${sanitizedBranch}`) - db.updateRepoBranch(database, repoId, sanitizedBranch) + updateRepoBranch(database, repoId, sanitizedBranch) } catch (error: unknown) { logger.error(`Failed to create branch for repo ${repoId}:`, error) throw error @@ -889,7 +889,7 @@ export async function pullRepo( gitAuthService: GitAuthService, repoId: number ): Promise { - const repo = db.getRepoById(database, repoId) + const repo = getRepoById(database, repoId) if (!repo) { throw new Error(`Repo not found: ${repoId}`) } @@ -905,7 +905,7 @@ export async function pullRepo( logger.info(`Pulling repo: ${repo.repoUrl}`) await executeCommand(['git', '-C', path.resolve(repo.fullPath), 'pull'], { env }) - db.updateLastPulled(database, repoId) + updateLastPulled(database, repoId) logger.info(`Repo pulled successfully: ${repo.repoUrl}`) } catch (error: unknown) { logger.error(`Failed to pull repo: ${repo.repoUrl}`, error) @@ -914,7 +914,7 @@ export async function pullRepo( } export async function deleteRepoFiles(database: Database, repoId: number): Promise { - const repo = db.getRepoById(database, repoId) + const repo = getRepoById(database, repoId) if (!repo) { throw new Error(`Repo not found: ${repoId}`) } @@ -935,7 +935,7 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi } await executeCommand(['rm', '-rf', repo.localPath], getReposPath()) - db.deleteRepo(database, repoId) + deleteRepo(database, repoId) } function normalizeRepoUrl(url: string, preserveSSH: boolean = false): { url: string; name: string } { diff --git a/backend/src/services/settings.ts b/backend/src/services/settings.ts index 1bbaccb8..8a8a4678 100644 --- a/backend/src/services/settings.ts +++ b/backend/src/services/settings.ts @@ -38,6 +38,10 @@ interface OpenCodeConfigResponseWithRaw { defaultConfig: OpenCodeConfigWithRaw | null } +interface CreateOpenCodeConfigOptions { + suppressAutoDefault?: boolean +} + export class SettingsService { private static lastKnownGoodConfigContent: string | null = null @@ -216,7 +220,8 @@ export class SettingsService { createOpenCodeConfig( request: CreateOpenCodeConfigRequest, - userId: string = 'default' + userId: string = 'default', + options: CreateOpenCodeConfigOptions = {} ): OpenCodeConfigWithRaw { // Check for existing config with the same name const existing = this.getOpenCodeConfigByName(request.name, userId) @@ -239,7 +244,7 @@ export class SettingsService { .query('SELECT COUNT(*) as count FROM opencode_configs WHERE user_id = ?') .get(userId) as { count: number } - const shouldBeDefault = request.isDefault || existingCount.count === 0 + const shouldBeDefault = request.isDefault || (!options.suppressAutoDefault && existingCount.count === 0) if (shouldBeDefault) { this.db diff --git a/backend/src/types/repo.ts b/backend/src/types/repo.ts index 81736697..07977809 100644 --- a/backend/src/types/repo.ts +++ b/backend/src/types/repo.ts @@ -4,6 +4,7 @@ export * from '../../../shared/src/schemas/repo' export interface Repo extends BaseRepo { isWorktree?: boolean + lastAccessedAt?: number } interface CreateRepoInputBase { diff --git a/backend/test/db/queries.test.ts b/backend/test/db/queries.test.ts index 5fc66f18..d909817d 100644 --- a/backend/test/db/queries.test.ts +++ b/backend/test/db/queries.test.ts @@ -21,6 +21,7 @@ describe('Database Queries', () => { describe('createRepo', () => { it('should insert new repo record', () => { + const clonedAt = Date.now() const repo = { repoUrl: 'https://github.com/test/repo', localPath: 'repos/test-repo', @@ -28,7 +29,7 @@ describe('Database Queries', () => { branch: 'main', defaultBranch: 'main', cloneStatus: 'ready' as const, - clonedAt: Date.now(), + clonedAt, isWorktree: false, isLocal: true, } @@ -55,6 +56,7 @@ describe('Database Queries', () => { default_branch: repo.defaultBranch, clone_status: repo.cloneStatus, cloned_at: repo.clonedAt, + last_accessed_at: clonedAt, is_worktree: 0 }) } @@ -76,6 +78,7 @@ describe('Database Queries', () => { repo.defaultBranch, repo.cloneStatus, repo.clonedAt, + clonedAt, repo.isWorktree ? 1 : 0, 1 ) @@ -86,6 +89,7 @@ describe('Database Queries', () => { describe('getRepoById', () => { it('should retrieve repo by ID', () => { const clonedAt = Date.now() + const lastAccessedAt = Date.now() const repoRow = { id: 1, repo_url: 'https://github.com/test/repo', @@ -96,6 +100,7 @@ describe('Database Queries', () => { clone_status: 'ready', cloned_at: clonedAt, last_pulled: null, + last_accessed_at: lastAccessedAt, opencode_config_name: null, is_worktree: 0, is_local: 0 @@ -119,6 +124,7 @@ describe('Database Queries', () => { cloneStatus: 'ready', clonedAt: clonedAt, lastPulled: null, + lastAccessedAt: lastAccessedAt, openCodeConfigName: null, isWorktree: undefined, isLocal: undefined @@ -226,6 +232,31 @@ describe('Database Queries', () => { }) }) + describe('updateLastAccessed', () => { + it('should update repo last accessed timestamp', () => { + const stmt = { + run: vi.fn().mockReturnValue({ changes: 1 }) + } + mockDb.prepare.mockReturnValue(stmt) + + db.updateLastAccessed(mockDb, 1) + + expect(mockDb.prepare).toHaveBeenCalledWith( + 'UPDATE repos SET last_accessed_at = ? WHERE id = ?' + ) + expect(stmt.run).toHaveBeenCalledWith(expect.any(Number), 1) + }) + + it('should throw error when repo not found', () => { + const stmt = { + run: vi.fn().mockReturnValue({ changes: 0 }) + } + mockDb.prepare.mockReturnValue(stmt) + + expect(() => db.updateLastAccessed(mockDb, 999)).toThrow('Repository with id 999 not found') + }) + }) + describe('deleteRepo', () => { it('should delete repo by ID', () => { const stmt = { diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts new file mode 100644 index 00000000..466c664d --- /dev/null +++ b/backend/test/routes/repos.test.ts @@ -0,0 +1,101 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' +import type { Database } from 'bun:sqlite' + +const mockDb = { + prepare: vi.fn(), + exec: vi.fn(), + close: vi.fn(), + transaction: vi.fn() +} as unknown as Database + +vi.mock('bun:sqlite', () => ({ + Database: vi.fn(() => mockDb) +})) + +vi.mock('../../src/db/queries', () => ({ + getRepoById: vi.fn(), + updateLastAccessed: vi.fn() +})) + +vi.mock('../../src/services/repo', () => ({ + getCurrentBranch: vi.fn() +})) + +import * as db from '../../src/db/queries' +import { createRepoRoutes } from '../../src/routes/repos' +import type { GitAuthService } from '../../src/services/git-auth' +import type { ScheduleService } from '../../src/services/schedules' + +const mockGitAuthService = { + getGitEnvironment: vi.fn().mockReturnValue({}) +} as unknown as GitAuthService + +const mockScheduleService = {} as ScheduleService + +describe('Repo Routes', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + describe('POST /:id/access', () => { + it('should return 404 when repo not found', async () => { + vi.mocked(db.getRepoById).mockReturnValue(null) + + const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService) + const res = await app.request('/1/access', { method: 'POST' }) + + expect(res.status).toBe(404) + const body = await res.json() as { error: string } + expect(body.error).toBe('Repo not found') + }) + + it('should return 200 and call updateLastAccessed when repo exists', async () => { + const mockRepo = { + id: 1, + repoUrl: 'https://github.com/test/repo', + localPath: 'repos/test-repo', + fullPath: '/Users/test/repos/test-repo', + sourcePath: '/Users/test/repos/test-repo', + branch: 'main', + defaultBranch: 'main', + cloneStatus: 'ready' as const, + clonedAt: Date.now(), + lastAccessedAt: Date.now() + } + vi.mocked(db.getRepoById).mockReturnValue(mockRepo) + + const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService) + const res = await app.request('/1/access', { method: 'POST' }) + + expect(res.status).toBe(200) + const body = await res.json() as { success: boolean } + expect(body.success).toBe(true) + expect(db.updateLastAccessed).toHaveBeenCalledWith(mockDb, 1) + }) + + it('should return 500 when updateLastAccessed throws', async () => { + const mockRepo = { + id: 1, + repoUrl: 'https://github.com/test/repo', + localPath: 'repos/test-repo', + fullPath: '/Users/test/repos/test-repo', + sourcePath: '/Users/test/repos/test-repo', + branch: 'main', + defaultBranch: 'main', + cloneStatus: 'ready' as const, + clonedAt: Date.now() + } + vi.mocked(db.getRepoById).mockReturnValue(mockRepo) + vi.mocked(db.updateLastAccessed).mockImplementation(() => { + throw new Error('Database error') + }) + + const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService) + const res = await app.request('/1/access', { method: 'POST' }) + + expect(res.status).toBe(500) + const body = await res.json() as { error: string } + expect(body.error).toBe('Database error') + }) + }) +}) \ No newline at end of file diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index cb41a997..e9aa3753 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -1,6 +1,15 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { execSync, spawnSync } from 'child_process' +const mockGetSettings = vi.fn() +const mockUpdateSettings = vi.fn() +const mockSaveLastKnownGoodConfig = vi.fn() +const mockCreateOpenCodeConfig = vi.fn() +const mockUpdateOpenCodeConfig = vi.fn() +const mockDeleteOpenCodeConfig = vi.fn() +const mockGetOpenCodeConfigByName = vi.fn() +const mockSetDefaultOpenCodeConfig = vi.fn() + vi.mock('fs', () => ({ existsSync: vi.fn(() => false), promises: { @@ -36,8 +45,14 @@ vi.mock('../../src/constants', () => ({ vi.mock('../../src/services/settings', () => ({ SettingsService: vi.fn().mockImplementation(() => ({ - getSettings: vi.fn(), - updateSettings: vi.fn(), + getSettings: mockGetSettings, + updateSettings: mockUpdateSettings, + saveLastKnownGoodConfig: mockSaveLastKnownGoodConfig, + createOpenCodeConfig: mockCreateOpenCodeConfig, + updateOpenCodeConfig: mockUpdateOpenCodeConfig, + deleteOpenCodeConfig: mockDeleteOpenCodeConfig, + getOpenCodeConfigByName: mockGetOpenCodeConfigByName, + setDefaultOpenCodeConfig: mockSetDefaultOpenCodeConfig, })), })) @@ -52,18 +67,36 @@ vi.mock('../../src/services/proxy', () => ({ proxyToOpenCodeWithDirectory: vi.fn(), })) -vi.mock('../../src/services/opencode-single-server', () => ({ - opencodeServerManager: { - getVersion: vi.fn(), - fetchVersion: vi.fn(), - reloadConfig: vi.fn(), - restart: vi.fn(), - clearStartupError: vi.fn(), - getLastStartupError: vi.fn(), - setDatabase: vi.fn(), - reinitializeBinDirectory: vi.fn(), - }, -})) +vi.mock('../../src/services/opencode-single-server', async (importOriginal) => { + const actual = await importOriginal() + + class MockConfigReloadError extends Error { + validationIssues: Array<{ path: string; message: string }> + removedFields: string[] + + constructor(message: string, validationIssues: Array<{ path: string; message: string }> = [], removedFields: string[] = []) { + super(message) + this.name = 'ConfigReloadError' + this.validationIssues = validationIssues + this.removedFields = removedFields + } + } + + return { + ...actual, + opencodeServerManager: { + getVersion: vi.fn(), + fetchVersion: vi.fn(), + reloadConfig: vi.fn(), + restart: vi.fn(), + clearStartupError: vi.fn(), + getLastStartupError: vi.fn(), + setDatabase: vi.fn(), + reinitializeBinDirectory: vi.fn(), + }, + ConfigReloadError: MockConfigReloadError, + } +}) vi.mock('../../src/services/opencode-import', () => ({ OpenCodeImportProtectionError: class OpenCodeImportProtectionError extends Error { @@ -109,9 +142,11 @@ vi.mock('@opencode-manager/shared/config/env', () => ({ })) import { createSettingsRoutes } from '../../src/routes/settings' +import { writeFileContent } from '../../src/services/file-operations' import { getImportedSessionDirectories, getOpenCodeImportStatus, OpenCodeImportProtectionError, syncOpenCodeImport } from '../../src/services/opencode-import' import { relinkReposFromSessionDirectories } from '../../src/services/repo' -import { opencodeServerManager } from '../../src/services/opencode-single-server' +import { opencodeServerManager, ConfigReloadError } from '../../src/services/opencode-single-server' +import { patchOpenCodeConfig } from '../../src/services/proxy' const mockExecSync = execSync as ReturnType const mockSpawnSync = spawnSync as ReturnType @@ -124,6 +159,8 @@ const mockGetOpenCodeImportStatus = getOpenCodeImportStatus as ReturnType const mockGetImportedSessionDirectories = getImportedSessionDirectories as ReturnType const mockRelinkReposFromSessionDirectories = relinkReposFromSessionDirectories as ReturnType +const mockWriteFileContent = writeFileContent as ReturnType +const mockPatchOpenCodeConfig = patchOpenCodeConfig as ReturnType describe('Settings Routes - OpenCode Upgrade', () => { let settingsApp: ReturnType @@ -137,10 +174,20 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockReloadConfig.mockReset() mockRestart.mockReset() mockClearStartupError.mockReset() + mockGetSettings.mockReset() + mockUpdateSettings.mockReset() + mockSaveLastKnownGoodConfig.mockReset() + mockCreateOpenCodeConfig.mockReset() + mockUpdateOpenCodeConfig.mockReset() + mockDeleteOpenCodeConfig.mockReset() + mockGetOpenCodeConfigByName.mockReset() + mockSetDefaultOpenCodeConfig.mockReset() mockGetOpenCodeImportStatus.mockReset() mockSyncOpenCodeImport.mockReset() mockGetImportedSessionDirectories.mockReset() mockRelinkReposFromSessionDirectories.mockReset() + mockWriteFileContent.mockReset() + mockPatchOpenCodeConfig.mockReset() testDb = {} as any settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any) @@ -148,6 +195,8 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockReloadConfig.mockResolvedValue(undefined) mockRestart.mockResolvedValue(undefined) mockClearStartupError.mockReturnValue(undefined) + mockPatchOpenCodeConfig.mockResolvedValue({ success: true, appliedConfig: { $schema: 'https://opencode.ai/config.json' } }) + mockWriteFileContent.mockResolvedValue(undefined) mockGetOpenCodeImportStatus.mockResolvedValue({ configSourcePath: null, stateSourcePath: null, @@ -168,6 +217,201 @@ describe('Settings Routes - OpenCode Upgrade', () => { }) }) + describe('OpenCode config routes', () => { + it('should reject create-as-default when runtime validation fails', async () => { + mockCreateOpenCodeConfig.mockReturnValue({ + id: 1, + name: 'broken', + content: { command: { review: true } }, + rawContent: '{"command":{"review":true}}', + isValid: true, + isDefault: false, + createdAt: 1, + updatedAt: 1, + }) + mockPatchOpenCodeConfig.mockResolvedValueOnce({ + success: false, + error: 'command.review: Invalid field', + details: [{ path: 'command.review', message: 'Invalid field' }], + }) + + const req = new Request('http://localhost/opencode-configs', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'broken', + content: '{"command":{"review":true}}', + isDefault: true, + }), + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('Config validation failed') + expect(mockSaveLastKnownGoodConfig).toHaveBeenCalledWith('default') + expect(mockCreateOpenCodeConfig).toHaveBeenCalledWith( + { + name: 'broken', + content: '{"command":{"review":true}}', + isDefault: false, + }, + 'default', + { suppressAutoDefault: true } + ) + expect(mockDeleteOpenCodeConfig).toHaveBeenCalledWith('broken', 'default') + expect(mockSetDefaultOpenCodeConfig).not.toHaveBeenCalled() + expect(mockWriteFileContent).not.toHaveBeenCalled() + }) + + it('should persist sanitized content before marking a new config as default', async () => { + mockCreateOpenCodeConfig.mockReturnValue({ + id: 1, + name: 'cleaned', + content: { command: { review: true }, theme: 'dark' }, + rawContent: '{"command":{"review":true},"theme":"dark"}', + isValid: true, + isDefault: false, + createdAt: 1, + updatedAt: 1, + }) + mockPatchOpenCodeConfig.mockResolvedValueOnce({ + success: true, + appliedConfig: { theme: 'dark' }, + removedFields: ['command.review'], + details: [{ path: 'command.review', message: 'Invalid field' }], + }) + mockUpdateOpenCodeConfig.mockReturnValue({ + id: 1, + name: 'cleaned', + content: { theme: 'dark' }, + rawContent: '{\n "theme": "dark"\n}', + isValid: true, + isDefault: true, + createdAt: 1, + updatedAt: 2, + }) + + const req = new Request('http://localhost/opencode-configs', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'cleaned', + content: '{"command":{"review":true},"theme":"dark"}', + isDefault: true, + }), + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(mockUpdateOpenCodeConfig).toHaveBeenCalledWith( + 'cleaned', + { + content: '{\n "theme": "dark"\n}', + isDefault: true, + }, + 'default' + ) + expect(mockWriteFileContent).toHaveBeenCalledWith( + '/tmp/test-workspace/.config/opencode.json', + '{\n "theme": "dark"\n}' + ) + expect(json.removedFields).toEqual(['command.review']) + }) + + it('should reject set-default when runtime validation fails', async () => { + mockGetOpenCodeConfigByName.mockReturnValue({ + id: 2, + name: 'broken', + content: { command: { review: true } }, + rawContent: '{"command":{"review":true}}', + isValid: true, + isDefault: false, + createdAt: 1, + updatedAt: 1, + }) + mockPatchOpenCodeConfig.mockResolvedValueOnce({ + success: false, + error: 'command.review: Invalid field', + details: [{ path: 'command.review', message: 'Invalid field' }], + }) + + const req = new Request('http://localhost/opencode-configs/broken/set-default', { + method: 'POST', + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('Config validation failed') + expect(mockSetDefaultOpenCodeConfig).not.toHaveBeenCalled() + expect(mockWriteFileContent).not.toHaveBeenCalled() + }) + + it('should sanitize existing config content before switching the default flag', async () => { + mockGetOpenCodeConfigByName.mockReturnValue({ + id: 2, + name: 'cleaned', + content: { command: { review: true }, theme: 'dark' }, + rawContent: '{"command":{"review":true},"theme":"dark"}', + isValid: true, + isDefault: false, + createdAt: 1, + updatedAt: 1, + }) + mockPatchOpenCodeConfig.mockResolvedValueOnce({ + success: true, + appliedConfig: { theme: 'dark' }, + removedFields: ['command.review'], + details: [{ path: 'command.review', message: 'Invalid field' }], + }) + mockUpdateOpenCodeConfig.mockReturnValue({ + id: 2, + name: 'cleaned', + content: { theme: 'dark' }, + rawContent: '{\n "theme": "dark"\n}', + isValid: true, + isDefault: false, + createdAt: 1, + updatedAt: 2, + }) + mockSetDefaultOpenCodeConfig.mockReturnValue({ + id: 2, + name: 'cleaned', + content: { theme: 'dark' }, + rawContent: '{\n "theme": "dark"\n}', + isValid: true, + isDefault: true, + createdAt: 1, + updatedAt: 3, + }) + + const req = new Request('http://localhost/opencode-configs/cleaned/set-default', { + method: 'POST', + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + const updateCallOrder = mockUpdateOpenCodeConfig.mock.invocationCallOrder[0] + const setDefaultCallOrder = mockSetDefaultOpenCodeConfig.mock.invocationCallOrder[0] + + expect(res.status).toBe(200) + expect(mockUpdateOpenCodeConfig).toHaveBeenCalledWith( + 'cleaned', + { content: '{\n "theme": "dark"\n}' }, + 'default' + ) + expect(updateCallOrder).toBeDefined() + expect(setDefaultCallOrder).toBeDefined() + expect(updateCallOrder ?? 0).toBeLessThan(setDefaultCallOrder ?? 0) + expect(mockWriteFileContent).toHaveBeenCalledWith( + '/tmp/test-workspace/.config/opencode.json', + '{\n "theme": "dark"\n}' + ) + expect(json.removedFields).toEqual(['command.review']) + }) + }) + describe('OpenCode import routes', () => { it('should return import status', async () => { mockGetOpenCodeImportStatus.mockResolvedValueOnce({ @@ -691,4 +935,86 @@ describe('Settings Routes - OpenCode Upgrade', () => { expect(json.recovered).toBe(true) }) }) + + describe('POST /opencode-reload', () => { + beforeEach(() => { + vi.clearAllMocks() + mockReloadConfig.mockReset() + mockRestart.mockReset() + mockClearStartupError.mockReset() + mockReloadConfig.mockResolvedValue(undefined) + mockRestart.mockResolvedValue(undefined) + mockClearStartupError.mockReturnValue(undefined) + }) + + it('should return success when reload succeeds', async () => { + mockReloadConfig.mockResolvedValueOnce(undefined) + + const req = new Request('http://localhost/opencode-reload', { + method: 'POST' + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.success).toBe(true) + expect(json.message).toBe('OpenCode configuration reloaded successfully') + }) + + it('should propagate validationIssues and removedFields when ConfigReloadError is thrown', async () => { + const validationIssues = [ + { path: 'command.review', message: 'Invalid field' }, + { path: 'agent.temperature', message: 'Temperature out of range' } + ] + const removedFields = ['command.review'] + + mockReloadConfig.mockRejectedValueOnce( + new ConfigReloadError('Config validation failed', validationIssues, removedFields) + ) + + const req = new Request('http://localhost/opencode-reload', { + method: 'POST' + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(500) + expect(json.error).toBe('Config validation failed') + expect(json.details).toBe('command.review: Invalid field; agent.temperature: Temperature out of range') + expect(json.validationIssues).toEqual(validationIssues) + expect(json.removedFields).toEqual(removedFields) + }) + + it('should return generic error when non-ConfigReloadError is thrown', async () => { + mockReloadConfig.mockRejectedValueOnce(new Error('Some other error')) + + const req = new Request('http://localhost/opencode-reload', { + method: 'POST' + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(500) + expect(json.error).toBe('Failed to reload OpenCode configuration') + expect(json.details).toBe('Some other error') + }) + + it('should propagate empty arrays when ConfigReloadError has no issues', async () => { + mockReloadConfig.mockRejectedValueOnce( + new ConfigReloadError('Reload failed', [], []) + ) + + const req = new Request('http://localhost/opencode-reload', { + method: 'POST' + }) + const res = await settingsApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(500) + expect(json.error).toBe('Reload failed') + expect(json.details).toBe('Reload failed') + expect(json.validationIssues).toEqual([]) + expect(json.removedFields).toEqual([]) + }) + }) }) diff --git a/backend/test/services/opencode-single-server.test.ts b/backend/test/services/opencode-single-server.test.ts index 808926bc..8b77c715 100644 --- a/backend/test/services/opencode-single-server.test.ts +++ b/backend/test/services/opencode-single-server.test.ts @@ -46,13 +46,19 @@ vi.mock('child_process', () => ({ execSync: vi.fn(), })) +vi.mock('../../src/services/proxy', () => ({ + patchOpenCodeConfig: vi.fn(), +})) + import { promises as fs } from 'fs' import { execSync } from 'child_process' +import { ConfigReloadError } from '../../src/services/opencode-single-server' vi.mock('../../src/utils/logger', () => ({ logger: { info: vi.fn(), error: vi.fn(), + warn: vi.fn(), }, })) @@ -210,3 +216,62 @@ describe('OpenCodeServerManager - reinitializeBinDirectory', () => { }) }) }) + +describe('ConfigReloadError', () => { + it('should create error with validation issues and removed fields', () => { + const issues = [{ path: 'command.review', message: 'Invalid' }] + const removed = ['command.review'] + const error = new ConfigReloadError('Test error', issues, removed) + + expect(error.name).toBe('ConfigReloadError') + expect(error.message).toBe('Test error') + expect(error.validationIssues).toEqual(issues) + expect(error.removedFields).toEqual(removed) + }) + + it('should default to empty arrays for issues and removed fields', () => { + const error = new ConfigReloadError('Test error') + + expect(error.validationIssues).toEqual([]) + expect(error.removedFields).toEqual([]) + }) +}) + +describe('OpenCodeServerManager - reloadConfig', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + vi.clearAllMocks() + }) + + it('should call fetch to get current config before patching', async () => { + const mockFetch = vi.fn().mockImplementation((url: string) => { + if (url.includes('/config')) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve({ command: { review: 'test' } }) + }) + } + if (url.includes('/doc')) { + return Promise.resolve({ ok: true }) + } + return Promise.resolve({ ok: false }) + }) + global.fetch = mockFetch as unknown as typeof fetch + + vi.mock('../../src/services/proxy', () => ({ + patchOpenCodeConfig: vi.fn().mockResolvedValue({ success: true }), + })) + + const { opencodeServerManager } = await import('../../src/services/opencode-single-server') + + await opencodeServerManager.reloadConfig() + + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/config'), + expect.objectContaining({ method: 'GET' }) + ) + }) +}) diff --git a/backend/test/services/proxy.test.ts b/backend/test/services/proxy.test.ts new file mode 100644 index 00000000..74093bb7 --- /dev/null +++ b/backend/test/services/proxy.test.ts @@ -0,0 +1,445 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' + +vi.mock('bun:sqlite', () => ({ + Database: vi.fn(), +})) + +vi.mock('@opencode-manager/shared/config/env', () => ({ + getWorkspacePath: vi.fn(() => '/test/workspace'), + getOpenCodeConfigFilePath: vi.fn(() => '/test/workspace/.config/opencode.json'), + getReposPath: vi.fn(() => '/test/workspace/repos'), + getAgentsMdPath: vi.fn(() => '/test/workspace/AGENTS.md'), + getDatabasePath: vi.fn(() => ':memory:'), + getConfigPath: vi.fn(() => '/test/workspace/config'), + ENV: { + SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' }, + AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' }, + WORKSPACE: { BASE_PATH: '/test/workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' }, + OPENCODE: { PORT: 5551, HOST: '127.0.0.1' }, + DATABASE: { PATH: ':memory:' }, + FILE_LIMITS: { + MAX_SIZE_BYTES: 1024 * 1024, + MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024, + }, + }, + FILE_LIMITS: { + MAX_SIZE_BYTES: 1024 * 1024, + MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024, + }, +})) + +vi.mock('fs', () => ({ + promises: { + mkdir: vi.fn(), + access: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn(), + chmod: vi.fn(), + unlink: vi.fn(), + rm: vi.fn(), + readdir: vi.fn(), + }, +})) + +vi.mock('child_process', () => ({ + execSync: vi.fn(), +})) + +vi.mock('../../src/utils/logger', () => ({ + logger: { + info: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})) + +const createMockFetch = (response: Response) => { + return vi.fn().mockResolvedValue(response) as unknown as typeof fetch +} + +describe('proxy service', () => { + describe('patchOpenCodeConfig', () => { + const originalFetch = global.fetch + + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + global.fetch = originalFetch + }) + + describe('when OpenCode returns 400 with structured errors', () => { + it('should parse errors array and extract path and message', async () => { + const mockResponse = { + success: false, + data: { command: { review: 'some value' } }, + errors: [ + { path: ['command', 'review'], message: 'Invalid command review field' }, + { path: ['agent', 'temperature'], message: 'Temperature must be between 0 and 2' } + ] + } + + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => JSON.stringify(mockResponse) + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(false) + expect(result.details).toHaveLength(2) + expect(result.details?.[0]).toEqual({ path: 'command.review', message: 'Invalid command review field' }) + expect(result.details?.[1]).toEqual({ path: 'agent.temperature', message: 'Temperature must be between 0 and 2' }) + expect(result.error).toBe('command.review: Invalid command review field; agent.temperature: Temperature must be between 0 and 2') + }) + + it('should handle errors with string path format', async () => { + const mockResponse = { + success: false, + data: {}, + errors: [ + { path: 'command.review', message: 'Invalid field' } + ] + } + + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => JSON.stringify(mockResponse) + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(false) + expect(result.details).toHaveLength(1) + expect(result.details?.[0]).toEqual({ path: 'command.review', message: 'Invalid field' }) + }) + + it('should handle errors with missing path (defaults to root)', async () => { + const mockResponse = { + success: false, + data: {}, + errors: [ + { message: 'Configuration is invalid' } + ] + } + + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => JSON.stringify(mockResponse) + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({}) + + expect(result.success).toBe(false) + expect(result.details).toHaveLength(1) + expect(result.details?.[0]).toEqual({ path: 'root', message: 'Configuration is invalid' }) + }) + + it('should parse nested data.issues from runtime validation payloads', async () => { + const mockResponse = { + success: false, + data: { + issues: [ + { path: ['command', 'review'], message: 'Invalid review command' }, + { path: ['provider', 'openai', 'models'], message: 'Expected object' } + ] + } + } + + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => JSON.stringify(mockResponse) + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(false) + expect(result.details).toEqual([ + { path: 'command.review', message: 'Invalid review command' }, + { path: 'provider.openai.models', message: 'Expected object' } + ]) + expect(result.error).toBe('command.review: Invalid review command; provider.openai.models: Expected object') + }) + }) + + describe('when OpenCode returns 400 with only data (no errors)', () => { + it('should not use data as error message source', async () => { + const mockResponse = { + success: false, + data: { command: { review: 'some long value that should not be the error message' } } + } + + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => JSON.stringify(mockResponse) + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(false) + expect(result.error).not.toContain('some long value') + expect(result.details).toEqual([]) + }) + }) + + describe('when OpenCode returns 400 with unstructured text', () => { + it('should create bounded fallback message without giant config blobs', async () => { + const longConfig = 'x'.repeat(1000) + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => longConfig + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ config: longConfig }) + + expect(result.success).toBe(false) + expect(result.error?.length).toBeLessThan(400) + expect(result.details).toEqual([]) + }) + + it('should handle JSON parse errors gracefully', async () => { + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => 'not valid json at all' + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({}) + + expect(result.success).toBe(false) + expect(result.error).toContain('Parse error') + }) + }) + + describe('retry logic with removable paths', () => { + it('should retry after removing a valid nested path like command.review', async () => { + const errorResponse = { + success: false, + data: {}, + errors: [ + { path: ['command', 'review'], message: 'Invalid field' } + ] + } + + let callCount = 0 + global.fetch = vi.fn().mockImplementation(async () => { + callCount++ + if (callCount === 1) { + return { + ok: false, + status: 400, + text: async () => JSON.stringify(errorResponse) + } as unknown as Response + } + return { + ok: true, + text: async () => '{}' + } as unknown as Response + }) as unknown as typeof fetch + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ + command: { review: 'test', other: 'value' }, + agent: { name: 'test' } + }) + + expect(result.success).toBe(true) + expect(result.removedFields).toContain('command.review') + expect(result.details).toHaveLength(1) + }) + + it('should not retry if any path is non-removable (root level)', async () => { + const errorResponse = { + success: false, + data: {}, + errors: [ + { path: ['root'], message: 'Invalid configuration' } + ] + } + + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => JSON.stringify(errorResponse) + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ invalid: 'config' }) + + expect(result.success).toBe(false) + expect(result.removedFields).toEqual(undefined) + expect(result.error).toContain('Invalid configuration') + }) + + it('should not retry if any path exceeds depth limit', async () => { + const errorResponse = { + success: false, + data: {}, + errors: [ + { path: ['a', 'b', 'c', 'd'], message: 'Too deep' } + ] + } + + global.fetch = createMockFetch({ + ok: false, + status: 400, + text: async () => JSON.stringify(errorResponse) + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ a: { b: { c: { d: 'value' } } } }) + + expect(result.success).toBe(false) + expect(result.removedFields).toEqual(undefined) + }) + }) + + describe('retry failure handling', () => { + it('should return retry-specific details when retry fails with structured errors', async () => { + const initialError = { + success: false, + data: {}, + errors: [ + { path: ['command', 'review'], message: 'Initial error' } + ] + } + + const retryError = { + success: false, + data: {}, + errors: [ + { path: ['agent'], message: 'Retry error - agent invalid' } + ] + } + + let callCount = 0 + global.fetch = vi.fn().mockImplementation(async () => { + callCount++ + if (callCount === 1) { + return { + ok: false, + status: 400, + text: async () => JSON.stringify(initialError) + } as unknown as Response + } + return { + ok: false, + status: 400, + text: async () => JSON.stringify(retryError) + } as unknown as Response + }) as unknown as typeof fetch + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(false) + expect(result.removedFields).toContain('command.review') + expect(result.details).toHaveLength(1) + expect(result.details?.[0]?.message).toBe('Retry error - agent invalid') + expect(result.error).toContain('Retry error') + }) + + it('should fall back to initial details if retry response is unstructured', async () => { + const initialError = { + success: false, + data: {}, + errors: [ + { path: ['command', 'review'], message: 'Initial error' } + ] + } + + let callCount = 0 + global.fetch = vi.fn().mockImplementation(async () => { + callCount++ + if (callCount === 1) { + return { + ok: false, + status: 400, + text: async () => JSON.stringify(initialError) + } as unknown as Response + } + return { + ok: false, + status: 500, + text: async () => 'Internal Server Error' + } as unknown as Response + }) as unknown as typeof fetch + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(false) + expect(result.removedFields).toContain('command.review') + expect(result.details?.[0]?.message).toBe('Initial error') + }) + }) + + describe('path deduplication', () => { + it('should deduplicate paths before removal', async () => { + const errorResponse = { + success: false, + data: {}, + errors: [ + { path: ['command', 'review'], message: 'Error 1' }, + { path: ['command', 'review'], message: 'Error 2' } + ] + } + + let callCount = 0 + global.fetch = vi.fn().mockImplementation(async () => { + callCount++ + if (callCount === 1) { + return { + ok: false, + status: 400, + text: async () => JSON.stringify(errorResponse) + } as unknown as Response + } + return { + ok: true, + text: async () => '{}' + } as unknown as Response + }) as unknown as typeof fetch + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(true) + expect(result.removedFields).toHaveLength(1) + expect(result.removedFields?.[0]).toBe('command.review') + }) + }) + + describe('successful patch without errors', () => { + it('should return success without details', async () => { + global.fetch = createMockFetch({ + ok: true, + text: async () => '{}' + } as Response) + + const { patchOpenCodeConfig } = await import('../../src/services/proxy') + const result = await patchOpenCodeConfig({ command: { review: 'test' } }) + + expect(result.success).toBe(true) + expect(result.error).toBeUndefined() + expect(result.details).toBeUndefined() + expect(result.removedFields).toBeUndefined() + }) + }) + }) +}) diff --git a/frontend/src/api/fetchWrapper.ts b/frontend/src/api/fetchWrapper.ts index cfbf83dd..98e2d1ec 100644 --- a/frontend/src/api/fetchWrapper.ts +++ b/frontend/src/api/fetchWrapper.ts @@ -35,7 +35,12 @@ async function handleResponse(response: Response): Promise { data.error || 'Request failed', response.status, data.code, - detail + detail, + { + details: data.details, + validationIssues: data.validationIssues, + removedFields: data.removedFields, + } ) } diff --git a/frontend/src/api/providers.ts b/frontend/src/api/providers.ts index d43a0310..e374dcb3 100644 --- a/frontend/src/api/providers.ts +++ b/frontend/src/api/providers.ts @@ -62,6 +62,7 @@ export interface OpenCodeProvider { export interface Model { id: string; + key?: string; name: string; release_date?: string; attachment?: boolean; @@ -162,7 +163,8 @@ async function getProvidersFromOpenCodeServer(): Promise<{ providers: Provider[] Object.entries(openCodeProvider.models).forEach(([modelId, openCodeModel]) => { models[modelId] = { - id: modelId, + id: openCodeModel.api.id || modelId, + key: modelId, name: openCodeModel.name, attachment: openCodeModel.capabilities.attachment, reasoning: openCodeModel.capabilities.reasoning, @@ -235,7 +237,8 @@ async function getConfiguredProviders(connectedIds: Set): Promise { .map((provider) => { const models = Object.entries(provider.models || {}).map(([id, model]) => ({ ...model, - id: id, + id: model.id || id, + key: id, name: model.name || id, })); return { diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index df7f5f43..88a4d218 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -157,3 +157,9 @@ export async function resetRepoPermissions(id: number): Promise { method: 'POST', }) } + +export async function touchRepoActivity(id: number): Promise { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${id}/access`, { + method: 'POST', + }) +} diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 35284640..d58bbdd1 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -10,6 +10,7 @@ export interface Repo { cloneStatus: 'cloning' | 'ready' | 'error' clonedAt: number lastPulled?: number + lastAccessedAt?: number openCodeConfigName?: string isWorktree?: boolean isLocal?: boolean diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 1316941a..c3dc0cd6 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -7,6 +7,8 @@ import { type TTSConfig, type STTConfig, type OpenCodeConfigContent, + type ModelConfig, + type ProviderConfig, type SkillFileInfo, type CreateSkillRequest, type UpdateSkillRequest, @@ -14,7 +16,7 @@ import { } from '@opencode-manager/shared' import type { NotificationPreferences } from '@opencode-manager/shared/types' -export type { TTSConfig, STTConfig, OpenCodeConfigContent, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } +export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY } export interface CustomCommand { @@ -59,6 +61,7 @@ export interface UserPreferences { stt?: STTConfig notifications?: NotificationPreferences repoOrder?: number[] + repoSortMode?: 'recent' | 'manual' | 'name' memoryDedupThreshold?: number } @@ -82,6 +85,7 @@ export interface OpenCodeConfig { path: string message: string }> + removedFields?: string[] isValid: boolean isDefault: boolean createdAt: number diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 7c64c4b8..6c32c83d 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -4,6 +4,7 @@ import { useCommands } from '@/hooks/useCommands' import { useCommandHandler } from '@/hooks/useCommandHandler' import { useFileSearch } from '@/hooks/useFileSearch' import { useModelSelection } from '@/hooks/useModelSelection' +import { useOpenCodeClient } from '@/hooks/useOpenCode' import { useVariants } from '@/hooks/useVariants' import { useSessionAgent } from '@/hooks/useSessionAgent' import { useSTT } from '@/hooks/useSTT' @@ -23,6 +24,8 @@ import { SessionStatusIndicator } from '@/components/ui/session-status-indicator import { ModelQuickSelect } from '@/components/model/ModelQuickSelect' import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect' import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQuery } from '@/lib/promptParser' +import { formatModelName, getProviders } from '@/api/providers' +import { useQuery } from '@tanstack/react-query' import type { components } from '@/api/opencode-types' @@ -205,6 +208,9 @@ export const PromptInput = memo(forwardRef( variant: currentVariant }) setStoredAgent(sessionID, agentUsed) + if (model) { + setStoredModel({ providerID: model.providerID, modelID: model.modelID }) + } setPrompt('') setAttachedFiles(new Map()) revokeBlobUrls(imageAttachments) @@ -256,6 +262,9 @@ export const PromptInput = memo(forwardRef( }) setStoredAgent(sessionID, agentUsed) + if (model) { + setStoredModel({ providerID: model.providerID, modelID: model.modelID }) + } setPrompt('') setAttachedFiles(new Map()) revokeBlobUrls(imageAttachments) @@ -733,9 +742,26 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) const currentMode = localMode ?? sessionAgent.agent const setStoredAgent = useSessionAgentStore((s) => s.setAgent) -const { model, modelString } = useModelSelection(opcodeUrl, directory) + const client = useOpenCodeClient(opcodeUrl, directory) + const { data: providersData } = useQuery({ + queryKey: ['opencode', 'providers', opcodeUrl, directory], + queryFn: () => getProviders(), + enabled: !!client, + staleTime: 30000, + }) + +const { model, modelString, setModel: setStoredModel } = useModelSelection(opcodeUrl, directory) const currentModel = modelString || '' - const displayModelName = model?.modelID || currentModel + const displayModelName = useMemo(() => { + if (!model) { + return currentModel + } + + const provider = providersData?.providers.find((item) => item.id === model.providerID) + const modelData = provider?.models?.[model.modelID] + + return modelData ? formatModelName(modelData) : model.modelID || currentModel + }, [currentModel, model, providersData]) const isMobile = useMobile() const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions() const hasPendingPermissionForSession = hasPermissionsForSession(sessionID) diff --git a/frontend/src/components/model/ModelSelectDialog.tsx b/frontend/src/components/model/ModelSelectDialog.tsx index decc1797..677b26dd 100644 --- a/frontend/src/components/model/ModelSelectDialog.tsx +++ b/frontend/src/components/model/ModelSelectDialog.tsx @@ -100,7 +100,7 @@ const ModelCard = memo(function ModelCard({ ? "bg-blue-600/20 border-blue-500" : "bg-card border-border hover:bg-accent" }`} - onClick={() => onSelect(provider.id, model.id)} + onClick={() => onSelect(provider.id, model.key || model.id)} >
@@ -321,7 +321,7 @@ export function ModelSelectDialog({ provider.models.map((model) => ({ model, provider, - modelKey: `${provider.id}/${model.id}`, + modelKey: `${provider.id}/${model.key || model.id}`, })) ); }, [connectedProviders]); @@ -347,7 +347,7 @@ export function ModelSelectDialog({ if (search) { filtered = filtered.filter((item) => item.model.name.toLowerCase().includes(search) || - item.model.id.toLowerCase().includes(search) || + (item.model.key || item.model.id).toLowerCase().includes(search) || item.provider.name.toLowerCase().includes(search) ); } diff --git a/frontend/src/components/repo/RepoCard.test.tsx b/frontend/src/components/repo/RepoCard.test.tsx new file mode 100644 index 00000000..162e2142 --- /dev/null +++ b/frontend/src/components/repo/RepoCard.test.tsx @@ -0,0 +1,133 @@ +import { describe, it, expect, vi } from 'vitest' +import { render, screen, fireEvent } from '@testing-library/react' +import { BrowserRouter } from 'react-router-dom' +import { RepoCard } from './RepoCard' + +const mockNavigate = vi.fn() +vi.mock('react-router-dom', async () => { + const actual = await vi.importActual('react-router-dom') + return { + ...actual, + useNavigate: () => mockNavigate, + } +}) + +const defaultProps = { + repo: { + id: 1, + repoUrl: 'https://github.com/test/repo', + localPath: 'repos/test-repo', + fullPath: '/Users/test/repos/test-repo', + branch: 'main', + currentBranch: 'main', + cloneStatus: 'ready' as const, + isWorktree: false, + isLocal: false, + }, + onDelete: vi.fn(), + isDeleting: false, + isSelected: false, + onSelect: vi.fn(), +} + +const renderWithRouter = (ui: React.ReactElement) => { + return render({ui}) +} + +describe('RepoCard', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('should not navigate when cloneStatus is not ready', () => { + const props = { + ...defaultProps, + repo: { ...defaultProps.repo, cloneStatus: 'cloning' as const }, + } + renderWithRouter() + + fireEvent.click(screen.getByText('test-repo')) + expect(mockNavigate).not.toHaveBeenCalled() + }) + + it('should not show checkbox when manageMode is false', () => { + renderWithRouter() + expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() + }) + + it('should show checkbox when manageMode is true', () => { + const props = { + ...defaultProps, + onSelect: vi.fn(), + } + renderWithRouter() + expect(screen.getByRole('checkbox')).toBeInTheDocument() + }) + + it('should call onSelect when checkbox is clicked', () => { + const onSelect = vi.fn() + const props = { + ...defaultProps, + onSelect, + manageMode: true, + } + renderWithRouter() + + fireEvent.click(screen.getByRole('checkbox')) + expect(onSelect).toHaveBeenCalledWith(1, true) + }) + + it('should show dirty state indicator when gitStatus has changes', () => { + const props = { + ...defaultProps, + gitStatus: { + branch: 'main', + ahead: 0, + behind: 0, + files: [{ path: 'file.txt', status: 'modified' as const, staged: false }], + hasChanges: true, + }, + } + renderWithRouter() + + const indicator = screen.getByTestId('dirty-indicator') || screen.container.querySelector('.bg-orange-500') + expect(indicator).toBeTruthy() + }) + + it('should show ahead/behind indicators when gitStatus has ahead or behind', () => { + const props = { + ...defaultProps, + gitStatus: { + branch: 'main', + ahead: 2, + behind: 1, + files: [], + hasChanges: false, + }, + } + renderWithRouter() + + expect(screen.getByText('↑2')).toBeInTheDocument() + expect(screen.getByText('↓1')).toBeInTheDocument() + }) + + it('should display activity label when provided', () => { + const props = { + ...defaultProps, + activityLabel: '2h ago', + } + renderWithRouter() + + expect(screen.getByText('2h ago')).toBeInTheDocument() + }) + + it('should show cloning state correctly', () => { + const props = { + ...defaultProps, + repo: { ...defaultProps.repo, cloneStatus: 'cloning' as const }, + } + renderWithRouter() + + expect(screen.getByText('Cloning...')).toBeInTheDocument() + }) +}) \ No newline at end of file diff --git a/frontend/src/components/repo/RepoCard.tsx b/frontend/src/components/repo/RepoCard.tsx index fba03bd7..3030f857 100644 --- a/frontend/src/components/repo/RepoCard.tsx +++ b/frontend/src/components/repo/RepoCard.tsx @@ -1,15 +1,10 @@ import { useState } from "react"; -import { Button } from "@/components/ui/button"; - -import { Checkbox } from "@/components/ui/checkbox"; -import { Loader2, Trash2, Download, GitBranch, FolderOpen, AlertCircle } from "lucide-react"; import { useNavigate } from "react-router-dom"; -import { downloadRepo } from "@/api/repos"; -import { showToast } from "@/lib/toast"; +import { Loader2, GitBranch, FolderOpen, AlertCircle } from "lucide-react"; +import { Checkbox } from "@/components/ui/checkbox"; import { getRepoDisplayName } from "@/lib/utils"; -import type { GitStatusResponse } from "@/types/git"; -import { SourceControlPanel } from "@/components/source-control/SourceControlPanel"; -import { DownloadDialog } from "@/components/ui/download-dialog"; +import type { GitStatusResponse } from "@/types/git" +import { RepoRowActions } from "./RepoRowActions" interface RepoCardProps { repo: { @@ -23,12 +18,16 @@ interface RepoCardProps { isWorktree?: boolean; isLocal?: boolean; fullPath?: string; + lastAccessedAt?: number; }; onDelete: (id: number) => void; isDeleting: boolean; isSelected?: boolean; onSelect?: (id: number, selected: boolean) => void; gitStatus?: GitStatusResponse; + manageMode?: boolean; + isMobile?: boolean; + activityLabel?: string; } export function RepoCard({ @@ -38,10 +37,12 @@ export function RepoCard({ isSelected = false, onSelect, gitStatus, + manageMode = false, + isMobile = false, + activityLabel, }: RepoCardProps) { const navigate = useNavigate(); - const [showDownloadDialog, setShowDownloadDialog] = useState(false); - const [showSourceControl, setShowSourceControl] = useState(false); + const [actionsOpen, setActionsOpen] = useState(false); const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath); const branchToDisplay = gitStatus?.branch || repo.currentBranch || repo.branch; @@ -51,11 +52,11 @@ export function RepoCard({ const isDirty = gitStatus?.hasChanges || false; const ahead = gitStatus?.ahead || 0; const behind = gitStatus?.behind || 0; - const stagedCount = gitStatus?.files.filter((f) => f.staged).length || 0; - const unstagedCount = gitStatus?.files.filter((f) => !f.staged).length || 0; + const stagedCount = gitStatus?.files?.filter((f) => f.staged).length || 0; + const unstagedCount = gitStatus?.files?.filter((f) => !f.staged).length || 0; const handleCardClick = () => { - if (isReady && !showSourceControl && !showDownloadDialog) { + if (isReady && !actionsOpen) { navigate(`/repos/${repo.id}`); } }; @@ -65,15 +66,6 @@ export function RepoCard({ action(); }; - const handleDownload = async (options: { includeGit?: boolean, includePaths?: string[] }) => { - try { - await downloadRepo(repo.id, repoName, options); - showToast.success("Download complete"); - } catch (error: unknown) { - showToast.error(error instanceof Error ? error.message : "Download failed"); - } - }; - return (
- {onSelect && ( + {manageMode && onSelect && (
handleActionClick(e, () => onSelect(repo.id, !isSelected))} > @@ -100,15 +92,25 @@ export function RepoCard({
)} -
+

{repoName}

{isReady && (
)} -
+ + {!manageMode && ( + + )}
@@ -151,64 +153,14 @@ export function RepoCard({ )}
-
e.stopPropagation()}> - - - - - -
+ {activityLabel && ( + + {activityLabel} + + )}
- - setShowSourceControl(false)} - currentBranch={branchToDisplay || ""} - repoUrl={repo.repoUrl} - isRepoWorktree={repo.isWorktree} - repoName={repoName} - /> -
); -} +} \ No newline at end of file diff --git a/frontend/src/components/repo/RepoList.tsx b/frontend/src/components/repo/RepoList.tsx index 2a988f6a..edfc8635 100644 --- a/frontend/src/components/repo/RepoList.tsx +++ b/frontend/src/components/repo/RepoList.tsx @@ -6,14 +6,44 @@ import { CSS } from "@dnd-kit/utilities" import { listRepos, deleteRepo, updateRepoOrder } from "@/api/repos" import { fetchReposGitStatus } from "@/api/git" import { DeleteDialog } from "@/components/ui/delete-dialog" -import { ListToolbar } from "@/components/ui/list-toolbar" import { GitBranch, Search, GripVertical } from "lucide-react" import type { Repo } from "@/api/types" import type { GitStatusResponse } from "@/types/git" import { RepoCard } from "./RepoCard" import { RepoCardSkeleton } from "./RepoCardSkeleton" import { useMobile } from "@/hooks/useMobile" -import { getRepoDisplayName } from "@/lib/utils" +import { useSettings } from "@/hooks/useSettings" +import { + buildRepoViewModels, + filterReposBySearch, + filterReposByMode, + sortRepos, + groupReposIntoSections, + countAttentionItems, + type RepoFilterMode, + type RepoSortMode, +} from "./repo-list-state" +import { RepoListControls } from "./RepoListControls" + +function formatActivityLabel(timestamp: number): string { + const now = Date.now() + const diff = now - timestamp + const seconds = Math.floor(diff / 1000) + const minutes = Math.floor(seconds / 60) + const hours = Math.floor(minutes / 60) + const days = Math.floor(hours / 24) + + if (days > 0) { + return days === 1 ? '1d ago' : `${days}d ago` + } + if (hours > 0) { + return hours === 1 ? '1h ago' : `${hours}h ago` + } + if (minutes > 0) { + return minutes === 1 ? '1m ago' : `${minutes}m ago` + } + return 'just now' +} interface RepoCardWrapperProps { repo: Repo @@ -22,6 +52,9 @@ interface RepoCardWrapperProps { isSelected: boolean onSelect: (id: number, selected: boolean) => void gitStatus?: GitStatusResponse + manageMode: boolean + isMobile: boolean + activityLabel?: string } function SortableRepoCard({ @@ -31,7 +64,11 @@ function SortableRepoCard({ isSelected, onSelect, gitStatus, -}: RepoCardWrapperProps) { + manageMode, + isMobile, + activityLabel, + isManualSort, +}: RepoCardWrapperProps & { isManualSort: boolean }) { const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id: repo.id }) const style = { @@ -43,15 +80,17 @@ function SortableRepoCard({ return (
-
- -
-
+ {isManualSort && ( +
+ +
+ )} +
@@ -73,6 +115,9 @@ function StaticRepoCard({ isSelected, onSelect, gitStatus, + manageMode, + isMobile, + activityLabel, }: RepoCardWrapperProps) { return ( ) } @@ -89,13 +137,23 @@ function StaticRepoCard({ export function RepoList() { const queryClient = useQueryClient() const isMobile = useMobile() + const { preferences, updateSettings } = useSettings() const [deleteDialogOpen, setDeleteDialogOpen] = useState(false) const [repoToDelete, setRepoToDelete] = useState(null) const [selectedRepos, setSelectedRepos] = useState>(new Set()) const [searchQuery, setSearchQuery] = useState("") - const [reorderMode, setReorderMode] = useState(false) - - const isDragEnabled = !isMobile || reorderMode + const [filterMode, setFilterMode] = useState('recent') + const [manageMode, setManageMode] = useState(false) + + const sortMode = (preferences?.repoSortMode as RepoSortMode) || 'recent' + const repoOrder = preferences?.repoOrder + + const handleSortModeChange = (newSortMode: RepoSortMode) => { + updateSettings({ repoSortMode: newSortMode }) + } + + const isManualSort = sortMode === 'manual' + const isDragEnabled = !isMobile || (manageMode && isManualSort) const { data: repos, @@ -129,6 +187,28 @@ export function RepoList() { gcTime: 60 * 60 * 1000, }) + const viewModels = useMemo(() => { + if (!repos) return [] + return buildRepoViewModels(repos, gitStatuses) + }, [repos, gitStatuses]) + + const filteredViewModels = useMemo(() => { + const searched = filterReposBySearch(viewModels, searchQuery) + return filterReposByMode(searched, filterMode) + }, [viewModels, searchQuery, filterMode]) + + const sortedViewModels = useMemo(() => { + return sortRepos(filteredViewModels, sortMode, repoOrder) + }, [filteredViewModels, sortMode, repoOrder]) + + const sections = useMemo(() => { + return groupReposIntoSections(sortedViewModels, filterMode, sortMode) + }, [sortedViewModels, filterMode, sortMode]) + + const attentionCount = useMemo(() => { + return countAttentionItems(viewModels) + }, [viewModels]) + const deleteMutation = useMutation({ mutationFn: deleteRepo, onSuccess: () => { @@ -252,30 +332,6 @@ export function RepoList() { ) } - const dedupedRepos = repos.reduce((acc, repo) => { - if (repo.isWorktree) { - acc.push(repo) - } else { - const key = repo.repoUrl || repo.sourcePath || repo.localPath - const existing = acc.find((r) => (r.repoUrl || r.sourcePath || r.localPath) === key && !r.isWorktree) - - if (!existing) { - acc.push(repo) - } - } - - return acc - }, [] as Repo[]) - - const filteredRepos = dedupedRepos.filter((repo) => { - const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath) - const searchTarget = repo.repoUrl || repo.sourcePath || repo.localPath || "" - return ( - repoName.toLowerCase().includes(searchQuery.toLowerCase()) || - searchTarget.toLowerCase().includes(searchQuery.toLowerCase()) - ) - }) - const handleSelectRepo = (id: number, selected: boolean) => { const newSelected = new Set(selectedRepos) if (selected) { @@ -286,60 +342,29 @@ export function RepoList() { setSelectedRepos(newSelected) } - const handleSelectAll = () => { - const allFilteredSelected = filteredRepos.every((repo) => - selectedRepos.has(repo.id), - ) - - if (allFilteredSelected) { - setSelectedRepos(new Set()) - } else { - const filteredIds = filteredRepos.map((repo) => repo.id) - setSelectedRepos(new Set([...selectedRepos, ...filteredIds])) - } - } - - const handleBatchDelete = () => { - if (selectedRepos.size > 0) { - setDeleteDialogOpen(true) - } - } - - const handleDeleteAll = () => { - if (filteredRepos.length === 0) return - setSelectedRepos(new Set(filteredRepos.map((r) => r.id))) - setDeleteDialogOpen(true) - } - return ( <>
-
- 0 && - filteredRepos.every((repo) => selectedRepos.has(repo.id)) - } - onToggleSelectAll={handleSelectAll} - onDelete={handleBatchDelete} - onDeleteAll={handleDeleteAll} - reorderMode={reorderMode} - onToggleReorderMode={() => setReorderMode((m) => !m)} - showReorderToggle={isMobile} - /> -
+
- {filteredRepos.length === 0 ? ( + {sortedViewModels.length === 0 ? (

- No repositories found matching "{searchQuery}" + {sections[0]?.emptyMessage || `No repositories found${searchQuery ? ` matching "${searchQuery}"` : ''}`}

) : isDragEnabled ? ( @@ -348,9 +373,9 @@ export function RepoList() { collisionDetection={closestCenter} onDragEnd={handleDragEnd} > - r.id)} strategy={verticalListSortingStrategy}> + r.id)} strategy={verticalListSortingStrategy}>
- {filteredRepos.map((repo) => ( + {sortedViewModels.map((repo) => ( ))}
@@ -371,7 +400,7 @@ export function RepoList() { ) : (
- {filteredRepos.map((repo) => ( + {sortedViewModels.map((repo) => ( ))}
diff --git a/frontend/src/components/repo/RepoListControls.tsx b/frontend/src/components/repo/RepoListControls.tsx new file mode 100644 index 00000000..7b9d4c9a --- /dev/null +++ b/frontend/src/components/repo/RepoListControls.tsx @@ -0,0 +1,196 @@ +import { useState } from 'react' +import { Search, SlidersHorizontal, Pencil, Check } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu' +import { useMobile } from '@/hooks/useMobile' +import type { RepoFilterMode, RepoSortMode } from './repo-list-state' + +interface RepoListControlsProps { + searchQuery: string + onSearchChange: (query: string) => void + filterMode: RepoFilterMode + onFilterModeChange: (mode: RepoFilterMode) => void + sortMode: RepoSortMode + onSortModeChange: (mode: RepoSortMode) => void + manageMode: boolean + onManageModeChange: (enabled: boolean) => void + filteredCount: number + attentionCount: number +} + +const FILTER_OPTIONS: { value: RepoFilterMode; label: string }[] = [ + { value: 'all', label: 'All' }, + { value: 'recent', label: 'Recent' }, + { value: 'attention', label: 'Changes' }, + { value: 'worktrees', label: 'Worktrees' }, + { value: 'local', label: 'Local' }, +] + +const SORT_OPTIONS: { value: RepoSortMode; label: string }[] = [ + { value: 'recent', label: 'Recent' }, + { value: 'manual', label: 'Manual' }, + { value: 'name', label: 'Name' }, +] + +export function RepoListControls({ + searchQuery, + onSearchChange, + filterMode, + onFilterModeChange, + sortMode, + onSortModeChange, + manageMode, + onManageModeChange, + filteredCount, + attentionCount, +}: RepoListControlsProps) { + const isMobile = useMobile() + const [showMenu, setShowMenu] = useState(false) + + const currentSortLabel = SORT_OPTIONS.find((s) => s.value === sortMode)?.label ?? 'Recent' + const currentFilterLabel = FILTER_OPTIONS.find((f) => f.value === filterMode)?.label ?? 'All' + + return ( +
+
+
+ + onSearchChange(e.target.value)} + placeholder="Search repositories..." + className="pl-9 h-9" + /> +
+ + {isMobile && ( + + )} + + {isMobile ? ( + + + + + + {FILTER_OPTIONS.map((option) => { + const count = + option.value === 'attention' + ? attentionCount + : option.value === 'all' + ? filteredCount + : undefined + + return ( + { + onFilterModeChange(option.value) + setShowMenu(false) + }} + className={filterMode === option.value ? 'bg-accent' : ''} + > + {option.label} + {count !== undefined && count > 0 && ( + + {count} + + )} + + ) + })} + + + ) : ( + + + + + + {SORT_OPTIONS.map((option) => ( + { + onSortModeChange(option.value) + setShowMenu(false) + }} + className={sortMode === option.value ? 'bg-accent' : ''} + > + {option.label} + + ))} + + + )} +
+ + {!isMobile && ( +
+ {FILTER_OPTIONS.map((option) => { + const count = + option.value === 'attention' + ? attentionCount + : option.value === 'all' + ? filteredCount + : undefined + + return ( + + ) + })} +
+ )} + + {!isMobile && ( +
+ + {filteredCount} {filteredCount === 1 ? 'repo' : 'repos'} + {searchQuery && ` matching "${searchQuery}"`} + + {attentionCount > 0 && filterMode !== 'attention' && ( + + {attentionCount} {attentionCount === 1 ? 'needs attention' : 'need attention'} + + )} +
+ )} +
+ ) +} \ No newline at end of file diff --git a/frontend/src/components/repo/RepoRowActions.tsx b/frontend/src/components/repo/RepoRowActions.tsx new file mode 100644 index 00000000..c183d9c4 --- /dev/null +++ b/frontend/src/components/repo/RepoRowActions.tsx @@ -0,0 +1,205 @@ +import { useState } from 'react' +import { Loader2, GitBranch, Download, Trash2, MoreVertical } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu' +import { SourceControlPanel } from '@/components/source-control/SourceControlPanel' +import { DownloadDialog } from '@/components/ui/download-dialog' +import { downloadRepo } from '@/api/repos' +import { showToast } from '@/lib/toast' +import { getRepoDisplayName } from '@/lib/utils' + +interface RepoRowActionsProps { + repo: { + id: number + repoUrl?: string | null + localPath?: string + sourcePath?: string + branch?: string + currentBranch?: string + cloneStatus: string + isWorktree?: boolean + isLocal?: boolean + fullPath?: string + } + gitStatus?: { + branch: string + ahead: number + behind: number + } + onDelete: (id: number) => void + isDeleting: boolean + isMobile: boolean + onActionsOpenChange?: (isOpen: boolean) => void +} + +export function RepoRowActions({ + repo, + gitStatus, + onDelete, + isDeleting, + isMobile, + onActionsOpenChange, +}: RepoRowActionsProps) { + const [showDownloadDialog, setShowDownloadDialog] = useState(false) + const [showSourceControl, setShowSourceControl] = useState(false) + + const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath) + const branchToDisplay = gitStatus?.branch || repo.currentBranch || repo.branch + const isReady = repo.cloneStatus === 'ready' + + const handleSourceControlOpen = (open: boolean) => { + setShowSourceControl(open) + onActionsOpenChange?.(open) + } + + const handleDownloadDialogOpen = (open: boolean) => { + setShowDownloadDialog(open) + onActionsOpenChange?.(open) + } + + const handleDownload = async (options: { includeGit?: boolean; includePaths?: string[] }) => { + try { + await downloadRepo(repo.id, repoName, options) + showToast.success('Download complete') + } catch (error: unknown) { + showToast.error(error instanceof Error ? error.message : 'Download failed') + } + } + + if (isMobile) { + return ( + <> + + + + + + handleSourceControlOpen(true)} + disabled={!isReady} + > + + Source Control + + handleDownloadDialogOpen(true)} + disabled={!isReady} + > + + Download + + onDelete(repo.id)} + disabled={isDeleting} + className="text-destructive" + > + {isDeleting ? ( + + ) : ( + + )} + {repo.isLocal ? 'Unlink' : 'Delete'} + + + + + { + setShowSourceControl(false) + onActionsOpenChange?.(false) + }} + currentBranch={branchToDisplay || ''} + repoUrl={repo.repoUrl} + isRepoWorktree={repo.isWorktree} + repoName={repoName} + /> + { + setShowDownloadDialog(open) + onActionsOpenChange?.(open) + }} + onDownload={handleDownload} + title="Download Repository" + description="This will create a ZIP archive of the entire repository." + itemName={repoName} + targetPath={repo.fullPath} + /> + + ) + } + + return ( + <> +
e.stopPropagation()}> + + + + + +
+ + { setShowSourceControl(false); onActionsOpenChange?.(false); }} + currentBranch={branchToDisplay || ''} + repoUrl={repo.repoUrl} + isRepoWorktree={repo.isWorktree} + repoName={repoName} + /> + { setShowDownloadDialog(open); onActionsOpenChange?.(open); }} + onDownload={handleDownload} + title="Download Repository" + description="This will create a ZIP archive of the entire repository." + itemName={repoName} + targetPath={repo.fullPath} + /> + + ) +} \ No newline at end of file diff --git a/frontend/src/components/repo/repo-list-state.test.ts b/frontend/src/components/repo/repo-list-state.test.ts new file mode 100644 index 00000000..1685962b --- /dev/null +++ b/frontend/src/components/repo/repo-list-state.test.ts @@ -0,0 +1,374 @@ +import { describe, it, expect } from 'vitest' +import type { Repo } from '@/api/types' +import type { GitStatusResponse } from '@/types/git' +import { + getActivityTimestamp, + getAttentionState, + dedupeRepos, + filterReposBySearch, + filterReposByMode, + sortRepos, + groupReposIntoSections, + countAttentionItems, + type RepoViewModel, +} from './repo-list-state' + +const createMockRepo = (overrides: Partial = {}): Repo => ({ + id: 1, + repoUrl: 'https://github.com/test/repo', + localPath: 'repos/test-repo', + fullPath: '/Users/test/repos/test-repo', + sourcePath: undefined, + branch: 'main', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now() - 100000, + lastPulled: undefined, + lastAccessedAt: undefined, + openCodeConfigName: undefined, + isWorktree: false, + isLocal: false, + ...overrides, +}) + +const createMockGitStatus = (overrides: Partial = {}): GitStatusResponse => ({ + branch: 'main', + ahead: 0, + behind: 0, + files: [], + hasChanges: false, + ...overrides, +}) + +describe('repo-list-state', () => { + describe('getActivityTimestamp', () => { + it('should return lastAccessedAt when available', () => { + const now = Date.now() + const repo = createMockRepo({ lastAccessedAt: now }) + expect(getActivityTimestamp(repo)).toBe(now) + }) + + it('should return lastPulled when lastAccessedAt is not available', () => { + const now = Date.now() + const repo = createMockRepo({ lastAccessedAt: undefined, lastPulled: now }) + expect(getActivityTimestamp(repo)).toBe(now) + }) + + it('should return clonedAt as fallback', () => { + const clonedAt = Date.now() - 100000 + const repo = createMockRepo({ lastAccessedAt: undefined, lastPulled: undefined, clonedAt }) + expect(getActivityTimestamp(repo)).toBe(clonedAt) + }) + }) + + describe('getAttentionState', () => { + it('should return ready state for ready repos without git status', () => { + const repo = createMockRepo({ cloneStatus: 'ready' }) + const result = getAttentionState(repo, undefined) + expect(result).toEqual({ + hasChanges: false, + ahead: 0, + behind: 0, + isCloneStatusReady: true, + }) + }) + + it('should return not ready for cloning repos', () => { + const repo = createMockRepo({ cloneStatus: 'cloning' }) + const gitStatus = createMockGitStatus({ hasChanges: true, ahead: 2, behind: 1 }) + const result = getAttentionState(repo, gitStatus) + expect(result).toEqual({ + hasChanges: false, + ahead: 0, + behind: 0, + isCloneStatusReady: false, + }) + }) + + it('should return attention state from git status when ready', () => { + const repo = createMockRepo({ cloneStatus: 'ready' }) + const gitStatus = createMockGitStatus({ hasChanges: true, ahead: 3, behind: 2 }) + const result = getAttentionState(repo, gitStatus) + expect(result).toEqual({ + hasChanges: true, + ahead: 3, + behind: 2, + isCloneStatusReady: true, + }) + }) + }) + + describe('dedupeRepos', () => { + it('should preserve worktrees', () => { + const repos = [ + createMockRepo({ id: 1, isWorktree: true, localPath: 'repos/parent/.worktrees/feature1' }), + createMockRepo({ id: 2, isWorktree: true, localPath: 'repos/parent/.worktrees/feature2' }), + ] + const result = dedupeRepos(repos) + expect(result).toHaveLength(2) + }) + + it('should dedupe non-worktree repos by key', () => { + const repos = [ + createMockRepo({ id: 1, repoUrl: 'https://github.com/test/repo', localPath: 'repos/test-repo' }), + createMockRepo({ id: 2, repoUrl: 'https://github.com/test/repo', localPath: 'repos/test-repo-clone' }), + ] + const result = dedupeRepos(repos) + expect(result).toHaveLength(1) + expect(result[0].id).toBe(1) + }) + + it('should keep first occurrence when deduping', () => { + const repos = [ + createMockRepo({ id: 1, repoUrl: 'https://github.com/test/repo', localPath: 'repos/test-repo' }), + createMockRepo({ id: 2, repoUrl: 'https://github.com/test/repo', localPath: 'repos/test-repo' }), + ] + const result = dedupeRepos(repos) + expect(result[0].id).toBe(1) + }) + + it('should preserve worktrees alongside deduped repos', () => { + const parentRepo = createMockRepo({ id: 1, repoUrl: 'https://github.com/test/repo', isWorktree: false }) + const worktree = createMockRepo({ id: 2, isWorktree: true, sourcePath: '/repos/test-repo/.worktrees/feature' }) + const repos = [parentRepo, worktree] + const result = dedupeRepos(repos) + expect(result).toHaveLength(2) + }) + }) + + describe('filterReposBySearch', () => { + it('should return all repos when search is empty', () => { + const repos = [ + createMockRepo({ id: 1, localPath: 'repos/test-repo' }), + createMockRepo({ id: 2, localPath: 'repos/other-repo' }), + ] + const viewModels = repos.map(r => ({ ...r, attentionState: getAttentionState(r), activityTimestamp: getActivityTimestamp(r) })) + const result = filterReposBySearch(viewModels, '') + expect(result).toHaveLength(2) + }) + + it('should filter by display name', () => { + const repos = [ + createMockRepo({ id: 1, localPath: 'repos/test-repo' }), + createMockRepo({ id: 2, localPath: 'repos/other-repo' }), + ] + const viewModels = repos.map(r => ({ ...r, attentionState: getAttentionState(r), activityTimestamp: getActivityTimestamp(r) })) + const result = filterReposBySearch(viewModels, 'test') + expect(result).toHaveLength(1) + expect(result[0].id).toBe(1) + }) + + it('should filter case-insensitively', () => { + const repos = [ + createMockRepo({ id: 1, localPath: 'repos/test-repo' }), + createMockRepo({ id: 2, localPath: 'repos/other-repo' }), + ] + const viewModels = repos.map(r => ({ ...r, attentionState: getAttentionState(r), activityTimestamp: getActivityTimestamp(r) })) + const result = filterReposBySearch(viewModels, 'TEST') + expect(result).toHaveLength(1) + }) + }) + + describe('filterReposByMode', () => { + const createViewModel = (overrides: Partial = {}): RepoViewModel => { + const repo = createMockRepo(overrides) + return { + ...repo, + attentionState: getAttentionState(repo), + activityTimestamp: getActivityTimestamp(repo), + } + } + + it('should return all repos for "all" mode', () => { + const repos = [createViewModel({ id: 1 }), createViewModel({ id: 2 })] + const result = filterReposByMode(repos, 'all') + expect(result).toHaveLength(2) + }) + + it('should filter by "recent" mode (ready repos)', () => { + const repos = [ + createViewModel({ id: 1, cloneStatus: 'ready' }), + createViewModel({ id: 2, cloneStatus: 'cloning' }), + ] + const result = filterReposByMode(repos, 'recent') + expect(result).toHaveLength(1) + expect(result[0].id).toBe(1) + }) + + it('should filter by "attention" mode', () => { + const gitStatusWithChanges = createMockGitStatus({ hasChanges: true }) + const gitStatusClean = createMockGitStatus({ hasChanges: false }) + const repos = [ + { ...createViewModel({ id: 1 }), attentionState: getAttentionState(createMockRepo({ cloneStatus: 'ready' }), gitStatusWithChanges) }, + { ...createViewModel({ id: 2 }), attentionState: getAttentionState(createMockRepo({ cloneStatus: 'ready' }), gitStatusClean) }, + ] + const result = filterReposByMode(repos, 'attention') + expect(result).toHaveLength(1) + expect(result[0].id).toBe(1) + }) + + it('should filter by "worktrees" mode', () => { + const repos = [ + createViewModel({ id: 1, isWorktree: true }), + createViewModel({ id: 2, isWorktree: false }), + ] + const result = filterReposByMode(repos, 'worktrees') + expect(result).toHaveLength(1) + expect(result[0].id).toBe(1) + }) + + it('should filter by "local" mode', () => { + const repos = [ + createViewModel({ id: 1, isLocal: true }), + createViewModel({ id: 2, isLocal: false }), + ] + const result = filterReposByMode(repos, 'local') + expect(result).toHaveLength(1) + expect(result[0].id).toBe(1) + }) + }) + + describe('sortRepos', () => { + const createViewModel = (id: number, overrides: Partial = {}): RepoViewModel => { + const repo = createMockRepo({ id, ...overrides }) + return { + ...repo, + attentionState: getAttentionState(repo), + activityTimestamp: getActivityTimestamp(repo), + } + } + + it('should sort by recent (descending) by default', () => { + const now = Date.now() + const repos = [ + createViewModel(1, { lastAccessedAt: now - 1000 }), + createViewModel(2, { lastAccessedAt: now - 500 }), + createViewModel(3, { lastAccessedAt: now - 2000 }), + ] + const result = sortRepos(repos, 'recent') + expect(result[0].id).toBe(2) + expect(result[1].id).toBe(1) + expect(result[2].id).toBe(3) + }) + + it('should sort alphabetically by name', () => { + const repos = [ + createViewModel(1, { localPath: 'repos/zebra' }), + createViewModel(2, { localPath: 'repos/alpha' }), + createViewModel(3, { localPath: 'repos/middle' }), + ] + const result = sortRepos(repos, 'name') + expect(result[0].id).toBe(2) + expect(result[1].id).toBe(3) + expect(result[2].id).toBe(1) + }) + + it('should preserve manual order when provided', () => { + const repos = [ + createViewModel(1), + createViewModel(2), + createViewModel(3), + ] + const manualOrder = [3, 1, 2] + const result = sortRepos(repos, 'manual', manualOrder) + expect(result[0].id).toBe(3) + expect(result[1].id).toBe(1) + expect(result[2].id).toBe(2) + }) + + it('should place unordered repos at the end for manual sort', () => { + const repos = [ + createViewModel(1), + createViewModel(2), + createViewModel(3), + ] + const manualOrder = [1] + const result = sortRepos(repos, 'manual', manualOrder) + expect(result[0].id).toBe(1) + expect(result[1].id).toBe(2) + expect(result[2].id).toBe(3) + }) + + it('should return repos unchanged when manual order is empty', () => { + const repos = [createViewModel(1), createViewModel(2)] + const result = sortRepos(repos, 'manual', []) + expect(result).toEqual(repos) + }) + }) + + describe('groupReposIntoSections', () => { + const createViewModel = (id: number, overrides: Partial = {}): RepoViewModel => { + const repo = createMockRepo({ id, ...overrides }) + return { + ...repo, + attentionState: getAttentionState(repo), + activityTimestamp: overrides.activityTimestamp ?? getActivityTimestamp(repo), + } + } + + it('should return single section for manual sort mode', () => { + const repos = [createViewModel(1), createViewModel(2)] + const result = groupReposIntoSections(repos, 'all', 'manual') + expect(result).toHaveLength(1) + expect(result[0].title).toBe('All Repositories') + }) + + it('should return attention section for attention filter', () => { + const now = Date.now() + const repos = [ + createViewModel(1, { + activityTimestamp: now, + attentionState: { hasChanges: true, ahead: 0, behind: 0, isCloneStatusReady: true } + }), + createViewModel(2, { + activityTimestamp: now, + attentionState: { hasChanges: false, ahead: 0, behind: 0, isCloneStatusReady: true } + }), + ] + const result = groupReposIntoSections(repos, 'attention', 'recent') + expect(result).toHaveLength(1) + expect(result[0].title).toBe('Needs Attention') + expect(result[0].repos).toHaveLength(1) + }) + + it('should group repos into recent and all sections', () => { + const now = Date.now() + const oneHourAgo = now - 60 * 60 * 1000 + const repos = [ + createViewModel(1, { + activityTimestamp: now, + attentionState: { hasChanges: false, ahead: 0, behind: 0, isCloneStatusReady: true } + }), + createViewModel(2, { + activityTimestamp: oneHourAgo, + attentionState: { hasChanges: false, ahead: 0, behind: 0, isCloneStatusReady: true } + }), + ] + const result = groupReposIntoSections(repos, 'all', 'recent') + expect(result.length).toBeGreaterThanOrEqual(1) + }) + }) + + describe('countAttentionItems', () => { + it('should count repos with changes, ahead, or behind', () => { + const repos = [ + { + ...createMockRepo({ id: 1 }), + attentionState: { hasChanges: true, ahead: 0, behind: 0, isCloneStatusReady: true }, + activityTimestamp: Date.now(), + }, + { + ...createMockRepo({ id: 2 }), + attentionState: { hasChanges: false, ahead: 2, behind: 0, isCloneStatusReady: true }, + activityTimestamp: Date.now(), + }, + { + ...createMockRepo({ id: 3 }), + attentionState: { hasChanges: false, ahead: 0, behind: 0, isCloneStatusReady: true }, + activityTimestamp: Date.now(), + }, + ] + expect(countAttentionItems(repos)).toBe(2) + }) + }) +}) \ No newline at end of file diff --git a/frontend/src/components/repo/repo-list-state.ts b/frontend/src/components/repo/repo-list-state.ts new file mode 100644 index 00000000..48a302e1 --- /dev/null +++ b/frontend/src/components/repo/repo-list-state.ts @@ -0,0 +1,258 @@ +import type { Repo } from "@/api/types" +import type { GitStatusResponse } from "@/types/git" +import { getRepoDisplayName } from "@/lib/utils" + +export type RepoFilterMode = 'all' | 'recent' | 'attention' | 'worktrees' | 'local' +export type RepoSortMode = 'recent' | 'manual' | 'name' + +export interface RepoAttentionState { + hasChanges: boolean + ahead: number + behind: number + isCloneStatusReady: boolean +} + +export interface RepoViewModel extends Repo { + attentionState: RepoAttentionState + activityTimestamp: number +} + +export interface RepoListSection { + title: string + repos: RepoViewModel[] + emptyMessage?: string +} + +export function getActivityTimestamp(repo: Repo): number { + return repo.lastAccessedAt ?? repo.lastPulled ?? repo.clonedAt +} + +export function getAttentionState(repo: Repo, gitStatus?: GitStatusResponse): RepoAttentionState { + if (!gitStatus || repo.cloneStatus !== 'ready') { + return { + hasChanges: false, + ahead: 0, + behind: 0, + isCloneStatusReady: repo.cloneStatus === 'ready' + } + } + + return { + hasChanges: gitStatus.hasChanges, + ahead: gitStatus.ahead, + behind: gitStatus.behind, + isCloneStatusReady: true + } +} + +export function dedupeRepos(repos: Repo[]): Repo[] { + return repos.reduce((acc, repo) => { + if (repo.isWorktree) { + acc.push(repo) + } else { + const key = repo.repoUrl || repo.sourcePath || repo.localPath + const existing = acc.find( + (r) => (r.repoUrl || r.sourcePath || r.localPath) === key && !r.isWorktree + ) + + if (!existing) { + acc.push(repo) + } + } + + return acc + }, [] as Repo[]) +} + +export function buildRepoViewModels( + repos: Repo[], + gitStatuses: Map | undefined +): RepoViewModel[] { + return dedupeRepos(repos).map((repo) => ({ + ...repo, + attentionState: getAttentionState(repo, gitStatuses?.get(repo.id)), + activityTimestamp: getActivityTimestamp(repo) + })) +} + +export function filterReposBySearch(repos: RepoViewModel[], searchQuery: string): RepoViewModel[] { + if (!searchQuery.trim()) { + return repos + } + + const query = searchQuery.toLowerCase() + return repos.filter((repo) => { + const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath) + const searchTarget = repo.repoUrl || repo.sourcePath || repo.localPath || "" + return ( + repoName.toLowerCase().includes(query) || + searchTarget.toLowerCase().includes(query) + ) + }) +} + +export function filterReposByMode(repos: RepoViewModel[], mode: RepoFilterMode): RepoViewModel[] { + switch (mode) { + case 'recent': + return repos.filter((repo) => repo.attentionState.isCloneStatusReady) + case 'attention': + return repos.filter( + (repo) => + repo.attentionState.hasChanges || + repo.attentionState.ahead > 0 || + repo.attentionState.behind > 0 + ) + case 'worktrees': + return repos.filter((repo) => repo.isWorktree) + case 'local': + return repos.filter((repo) => repo.isLocal) + case 'all': + default: + return repos + } +} + +export function sortRepos(repos: RepoViewModel[], mode: RepoSortMode, manualOrder?: number[]): RepoViewModel[] { + switch (mode) { + case 'recent': + return [...repos].sort((a, b) => b.activityTimestamp - a.activityTimestamp) + case 'name': + return [...repos].sort((a, b) => { + const nameA = getRepoDisplayName(a.repoUrl, a.localPath, a.sourcePath).toLowerCase() + const nameB = getRepoDisplayName(b.repoUrl, b.localPath, b.sourcePath).toLowerCase() + return nameA.localeCompare(nameB) + }) + case 'manual': { + if (!manualOrder || manualOrder.length === 0) { + return repos + } + const orderMap = new Map(manualOrder.map((id, index) => [id, index])) + const orderedRepos = repos + .filter((repo) => orderMap.has(repo.id)) + .sort((a, b) => { + const indexA = orderMap.get(a.id)! + const indexB = orderMap.get(b.id)! + return indexA - indexB + }) + const remainingRepos = repos.filter((repo) => !orderMap.has(repo.id)) + return [...orderedRepos, ...remainingRepos] + } + default: + return repos + } +} + +export function groupReposIntoSections( + repos: RepoViewModel[], + filterMode: RepoFilterMode, + sortMode: RepoSortMode +): RepoListSection[] { + if (sortMode === 'manual') { + return [{ + title: 'All Repositories', + repos, + emptyMessage: repos.length === 0 ? 'No repositories found' : undefined + }] + } + + if (filterMode === 'attention') { + const needsAttention = repos.filter( + (repo) => + repo.attentionState.hasChanges || + repo.attentionState.ahead > 0 || + repo.attentionState.behind > 0 + ) + + if (needsAttention.length === 0) { + return [{ + title: 'Needs Attention', + repos: [], + emptyMessage: 'No repositories need attention' + }] + } + + return [{ + title: 'Needs Attention', + repos: needsAttention + }] + } + + if (filterMode === 'recent') { + const recentRepos = repos.filter((repo) => repo.attentionState.isCloneStatusReady) + + if (recentRepos.length === 0) { + return [{ + title: 'Recent', + repos: [], + emptyMessage: 'No recently accessed repositories' + }] + } + + return [{ + title: 'Recent', + repos: recentRepos + }] + } + + const now = Date.now() + const oneDayAgo = now - 24 * 60 * 60 * 1000 + const needsAttention = repos.filter( + (repo) => + repo.attentionState.isCloneStatusReady && + (repo.attentionState.hasChanges || + repo.attentionState.ahead > 0 || + repo.attentionState.behind > 0) + ) + + const recentThreshold = oneDayAgo + const recentlyActive = repos.filter( + (repo) => + repo.attentionState.isCloneStatusReady && + repo.activityTimestamp >= recentThreshold + ) + + const sections: RepoListSection[] = [] + + if (needsAttention.length > 0) { + sections.push({ + title: 'Needs Attention', + repos: needsAttention + }) + } + + if (recentlyActive.length > 0) { + sections.push({ + title: 'Recent', + repos: recentlyActive + }) + } + + const remaining = repos.filter( + (repo) => + !needsAttention.includes(repo) && !recentlyActive.includes(repo) + ) + + if (remaining.length > 0) { + sections.push({ + title: 'All Repositories', + repos: remaining + }) + } else if (sections.length === 0) { + sections.push({ + title: 'All Repositories', + repos, + emptyMessage: repos.length === 0 ? 'No repositories found' : undefined + }) + } + + return sections +} + +export function countAttentionItems(repos: RepoViewModel[]): number { + return repos.filter( + (repo) => + repo.attentionState.hasChanges || + repo.attentionState.ahead > 0 || + repo.attentionState.behind > 0 + ).length +} \ No newline at end of file diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx index dfe8c3f5..93920d62 100644 --- a/frontend/src/components/session/SessionList.tsx +++ b/frontend/src/components/session/SessionList.tsx @@ -1,8 +1,9 @@ import { useState, useMemo } from "react"; -import { useSessions, useDeleteSession } from "@/hooks/useOpenCode"; +import { useSessions, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode"; import { ListToolbar } from "@/components/ui/list-toolbar"; import { DeleteSessionDialog } from "./DeleteSessionDialog"; import { SessionCard } from "./SessionCard"; +import { Card } from "@/components/ui/card"; interface SessionListProps { opcodeUrl: string; @@ -19,6 +20,9 @@ export const SessionList = ({ }: SessionListProps) => { const { data: sessions, isLoading } = useSessions(opcodeUrl, directory); const deleteSession = useDeleteSession(opcodeUrl, directory); + const createSession = useCreateSession(opcodeUrl, directory, (newSession) => { + onSelectSession(newSession.id); + }); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [sessionToDelete, setSessionToDelete] = useState< string | string[] | null @@ -68,8 +72,18 @@ export const SessionList = ({ if (!sessions || sessions.length === 0) { return ( -
- No sessions yet. Create one to get started. +
+ createSession.mutate({ agent: undefined })} + > +
+

No sessions yet

+

+ Click here to start a new session +

+
+
); } diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.tsx index 8c4305ee..9b4543bb 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.tsx @@ -6,6 +6,12 @@ import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle } from ' import type { OpenCodeConfig } from '@/api/types/settings' import { parseJsonc } from '@/lib/jsonc' import { FetchError } from '@/api/fetchWrapper' +import { OpenCodeConfigSchema } from '@opencode-manager/shared' + +type ValidationIssue = { + path: string + message: string +} interface OpenCodeConfigEditorProps { config: OpenCodeConfig | null @@ -25,6 +31,8 @@ export function OpenCodeConfigEditor({ const [editConfigContent, setEditConfigContent] = useState('') const [editError, setEditError] = useState('') const [editErrorLine, setEditErrorLine] = useState(null) + const [validationIssues, setValidationIssues] = useState([]) + const [removedFields, setRemovedFields] = useState([]) const editTextareaRef = useRef(null) useEffect(() => { @@ -32,6 +40,8 @@ export function OpenCodeConfigEditor({ setEditConfigContent(config.rawContent || JSON.stringify(config.content, null, 2)) setEditError('') setEditErrorLine(null) + setValidationIssues([]) + setRemovedFields([]) } }, [config, isOpen]) @@ -41,11 +51,34 @@ export function OpenCodeConfigEditor({ } }, [isOpen]) + const resetErrors = () => { + setEditError('') + setEditErrorLine(null) + setValidationIssues([]) + setRemovedFields([]) + } + + const getIssueText = (issue: ValidationIssue) => { + return `${issue.path}: ${issue.message}` + } + const updateConfig = async () => { if (!config) return try { - parseJsonc>(editConfigContent) + resetErrors() + const parsedConfig = parseJsonc>(editConfigContent) + const validationResult = OpenCodeConfigSchema.safeParse(parsedConfig) + if (!validationResult.success) { + const issues = validationResult.error.issues.map((issue) => ({ + path: issue.path.length > 0 ? issue.path.map(String).join('.') : 'root', + message: issue.message, + })) + setValidationIssues(issues) + setEditError(`Configuration validation failed: ${issues.map(getIssueText).join('; ')}`) + return + } + await onUpdate(editConfigContent) onClose() } catch (error) { @@ -58,6 +91,8 @@ export function OpenCodeConfigEditor({ } setEditError(`Invalid JSON/JSONC: ${error.message}`) } else if (error instanceof FetchError) { + setValidationIssues(error.validationIssues || []) + setRemovedFields(error.removedFields || []) setEditError(error.detail || error.message) } else if (error instanceof Error) { setEditError(error.message) @@ -103,19 +138,30 @@ export function OpenCodeConfigEditor({ value={editConfigContent} onChange={(e) => { setEditConfigContent(e.target.value) - setEditError('') - setEditErrorLine(null) + resetErrors() }} className={`flex-1 font-mono text-[16px] sm:text-xs md:text-sm resize-none h-full rounded-none sm:rounded-md ${editErrorLine ? 'error-highlight' : ''}`} /> {editError && ( -
-

+

+

{editError} {editErrorLine && ( (Line {editErrorLine}) )}

+ {validationIssues.length > 0 && ( +
    + {validationIssues.map((issue) => ( +
  • {getIssueText(issue)}
  • + ))} +
+ )} + {removedFields.length > 0 && ( +

+ Removed invalid fields: {removedFields.join(', ')} +

+ )}
)}
diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index 37ae7981..4b736570 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -173,12 +173,41 @@ export function OpenCodeConfigManager() { const getApiErrorMessage = (error: unknown, fallback: string): string => { if (error instanceof FetchError) { - return error.detail || error.message || fallback + let message = error.detail || error.message || fallback + + if (error.validationIssues && error.validationIssues.length > 0) { + const issues = error.validationIssues + .map((issue) => `${issue.path}: ${issue.message}`) + .join('; ') + message = `Validation failed: ${issues}` + } + + if (error.removedFields && error.removedFields.length > 0) { + message += ` (removed invalid fields: ${error.removedFields.join(', ')})` + } + + return message } if (error && typeof error === 'object' && 'response' in error) { - const response = (error as { response?: { data?: { details?: string; error?: string } } }).response - return response?.data?.details || response?.data?.error || fallback + const response = (error as { response?: { data?: { details?: string; error?: string; validationIssues?: Array<{ path: string; message: string }>; removedFields?: string[] } } }).response + const data = response?.data + + let message = data?.details || data?.error || fallback + + if (data?.validationIssues && data.validationIssues.length > 0) { + const issues = data.validationIssues + .map((issue) => `${issue.path}: ${issue.message}`) + .join('; ') + message = `Validation failed: ${issues}` + } + + if (data?.removedFields && data.removedFields.length > 0) { + const removed = data.removedFields.join(', ') + message += ` (removed invalid fields: ${removed})` + } + + return message } return fallback } @@ -212,7 +241,7 @@ export function OpenCodeConfigManager() { setIsUpdating(true) const previousContent = configs.find(c => c.name === configName)?.content - await settingsApi.updateOpenCodeConfig(configName, { content: newContent }) + const result = await settingsApi.updateOpenCodeConfig(configName, { content: newContent }) setConfigs(prev => prev.map(config => config.name === configName @@ -227,17 +256,26 @@ export function OpenCodeConfigManager() { const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent) const pluginsChanged = JSON.stringify(previousContent?.plugin) !== JSON.stringify(newContent.plugin) const skillsChanged = JSON.stringify(previousContent?.skills) !== JSON.stringify(newContent.skills) - if (restartServer || agentsChanged || pluginsChanged || skillsChanged) { + const providersChanged = JSON.stringify(previousContent?.provider) !== JSON.stringify(newContent.provider) + if (restartServer || agentsChanged || pluginsChanged || skillsChanged || providersChanged) { showToast.loading('Reloading server...', { id: 'update-restart' }) try { await reloadConfigMutation.mutateAsync() - showToast.success('Configuration updated and server reloaded', { id: 'update-restart' }) + if (result.removedFields && result.removedFields.length > 0) { + showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'update-restart' }) + } else { + showToast.success('Configuration updated and server reloaded', { id: 'update-restart' }) + } } catch (error) { showToast.error(getRestartErrorMessage(error), { id: 'update-restart' }) throw error } } else { - showToast.success('Configuration updated') + if (result.removedFields && result.removedFields.length > 0) { + showToast.info(`Configuration applied after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'update-restart' }) + } else { + showToast.success('Configuration updated') + } invalidateConfigCaches(queryClient) } } catch (error) { @@ -271,7 +309,7 @@ export function OpenCodeConfigManager() { throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`) } - await settingsApi.createOpenCodeConfig({ + const result = await settingsApi.createOpenCodeConfig({ name: name.trim(), content: rawContent, isDefault, @@ -281,13 +319,10 @@ export function OpenCodeConfigManager() { await fetchConfigs() if (isDefault) { - showToast.loading('Reloading server...', { id: 'create-config' }) - try { - await reloadConfigMutation.mutateAsync() - showToast.success('Configuration created and server reloaded', { id: 'create-config' }) - } catch (error) { - showToast.error(getRestartErrorMessage(error), { id: 'create-config' }) - throw error + if (result.removedFields && result.removedFields.length > 0) { + showToast.info(`Configuration created after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'create-config' }) + } else { + showToast.success('Configuration created and applied', { id: 'create-config' }) } } else { showToast.success('Configuration created', { id: 'create-config' }) @@ -323,13 +358,16 @@ export function OpenCodeConfigManager() { } const setDefaultConfig = async (config: OpenCodeConfig) => { - showToast.loading('Setting default config and reloading server...', { id: 'set-default' }) + showToast.loading('Setting default config...', { id: 'set-default' }) try { setIsUpdating(true) - await settingsApi.setDefaultOpenCodeConfig(config.name) + const result = await settingsApi.setDefaultOpenCodeConfig(config.name) await fetchConfigs() - await reloadConfigMutation.mutateAsync() - showToast.success('Default config updated and server reloaded', { id: 'set-default' }) + if (result.removedFields && result.removedFields.length > 0) { + showToast.info(`Default config updated after removing invalid fields: ${result.removedFields.join(', ')}`, { id: 'set-default' }) + } else { + showToast.success('Default config updated and applied', { id: 'set-default' }) + } } catch (error) { console.error('Failed to set default config:', error) showToast.error(getApiErrorMessage(error, 'Failed to set default config'), { id: 'set-default' }) diff --git a/frontend/src/components/settings/OpenCodeModelDialog.tsx b/frontend/src/components/settings/OpenCodeModelDialog.tsx index e3eb6d67..b2e5632b 100644 --- a/frontend/src/components/settings/OpenCodeModelDialog.tsx +++ b/frontend/src/components/settings/OpenCodeModelDialog.tsx @@ -5,16 +5,106 @@ import { useCallback, useEffect, useMemo } from 'react' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' +import { Textarea } from '@/components/ui/textarea' import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Switch } from '@/components/ui/switch' +import type { ModelConfig, ProviderConfig } from '@/api/types/settings' + +type ConfigModel = Partial & { + limit?: { + context?: number + input?: number + output?: number + } +} & Record + +type ConfigProvider = Omit, 'models' | 'env'> & { + api?: string + npm?: string + env?: string[] + models?: Record +} & Record + +const handledModelKeys = new Set([ + 'id', + 'providerID', + 'api', + 'name', + 'family', + 'capabilities', + 'cost', + 'limit', + 'status', + 'options', + 'headers', + 'release_date', + 'variants', +]) + +function parseJsonObject(value: string): Record | null { + try { + const parsed = JSON.parse(value) as unknown + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + return parsed as Record + } + return null + } catch { + return null + } +} + +function stringifyJson(value: unknown): string { + if (!value || (typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record).length === 0)) { + return '' + } + + return JSON.stringify(value, null, 2) +} + +function parseOptionalJsonField(value: string): Record | undefined { + if (!value.trim()) return undefined + return parseJsonObject(value) ?? undefined +} + +function parseOptionalNumber(value: string): number | undefined { + if (!value.trim()) return undefined + const parsed = Number(value) + return Number.isFinite(parsed) ? parsed : undefined +} + +function jsonObjectField(label: string) { + return z.string().superRefine((value, ctx) => { + if (!value.trim()) return + if (!parseJsonObject(value)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${label} must be a valid JSON object`, + }) + } + }) +} const modelFormSchema = z.object({ providerId: z.string().min(1, 'Provider is required'), - modelId: z.string().min(1, 'Model ID is required').regex(/^[a-zA-Z0-9_-]+$/, 'Must be alphanumeric with hyphens/underscores'), - name: z.string().min(1, 'Display name is required'), - contextLimit: z.number().min(0).optional(), - outputLimit: z.number().min(0).optional(), + modelId: z.string().min(1, 'Model ID is required').regex(/^[a-zA-Z0-9._-]+$/, 'Must use only letters, numbers, dots, hyphens, and underscores'), + backingModelId: z.string(), + providerModelProviderId: z.string(), + displayName: z.string(), + family: z.string(), + status: z.enum(['none', 'alpha', 'beta', 'deprecated', 'active']), + releaseDate: z.string(), + apiUrl: z.string(), + apiNpm: z.string(), + contextLimit: z.string(), + inputLimit: z.string(), + outputLimit: z.string(), + capabilitiesJson: jsonObjectField('Capabilities'), + costJson: jsonObjectField('Cost'), + optionsJson: jsonObjectField('Options'), + headersJson: jsonObjectField('Headers'), + variantsJson: jsonObjectField('Variants'), + extraJson: jsonObjectField('Advanced fields'), createNewProvider: z.boolean(), newProviderType: z.enum(['api', 'npm']), newProviderId: z.string(), @@ -24,55 +114,32 @@ const modelFormSchema = z.object({ }).superRefine((data, ctx) => { if (data.createNewProvider) { if (!data.newProviderId?.trim()) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Provider ID is required when creating a new provider', - path: ['newProviderId'], - }) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Provider ID is required when creating a new provider', path: ['newProviderId'] }) } else if (!/^[a-z0-9-]+$/.test(data.newProviderId)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Must be lowercase letters, numbers, and hyphens only', - path: ['newProviderId'], - }) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Must be lowercase letters, numbers, and hyphens only', path: ['newProviderId'] }) } if (data.newProviderType === 'api' && !data.newProviderBaseUrl?.trim()) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Base URL is required for API providers', - path: ['newProviderBaseUrl'], - }) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Base URL is required for API providers', path: ['newProviderBaseUrl'] }) } if (data.newProviderType === 'npm' && !data.newProviderNpm?.trim()) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'NPM package is required for npm providers', - path: ['newProviderNpm'], - }) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'NPM package is required for npm providers', path: ['newProviderNpm'] }) + } + } + + for (const [field, label] of [ + ['contextLimit', 'Context limit'], + ['inputLimit', 'Input limit'], + ['outputLimit', 'Output limit'], + ] as const) { + const value = data[field] + if (value.trim() && parseOptionalNumber(value) === undefined) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} must be a number`, path: [field] }) } } }) type ModelFormValues = z.infer -interface ConfigModel { - name?: string - limit?: { - context?: number - output?: number - } - [key: string]: unknown -} - -interface ConfigProvider { - name?: string - npm?: string - api?: string - options?: Record - models?: Record - [key: string]: unknown -} - export interface NewProviderConfig { id: string type: 'api' | 'npm' @@ -106,28 +173,61 @@ export function OpenCodeModelDialog({ }: OpenCodeModelDialogProps) { const getDefaultValues = useCallback((): ModelFormValues => { if (editingModel) { + const extraEntries = Object.fromEntries( + Object.entries(editingModel.model).filter(([key]) => !handledModelKeys.has(key)) + ) + return { providerId: editingModel.providerId, modelId: editingModel.modelId, - name: editingModel.model.name || '', - contextLimit: editingModel.model.limit?.context, - outputLimit: editingModel.model.limit?.output, + backingModelId: typeof editingModel.model.id === 'string' ? editingModel.model.id : '', + providerModelProviderId: typeof editingModel.model.providerID === 'string' ? editingModel.model.providerID : '', + displayName: editingModel.model.name || '', + family: editingModel.model.family || '', + status: (editingModel.model.status as ModelFormValues['status']) || 'none', + releaseDate: editingModel.model.release_date || '', + apiUrl: editingModel.model.api?.url || '', + apiNpm: editingModel.model.api?.npm || '', + contextLimit: editingModel.model.limit?.context?.toString() || '', + inputLimit: editingModel.model.limit?.input?.toString() || '', + outputLimit: editingModel.model.limit?.output?.toString() || '', + capabilitiesJson: stringifyJson(editingModel.model.capabilities), + costJson: stringifyJson(editingModel.model.cost), + optionsJson: stringifyJson(editingModel.model.options), + headersJson: stringifyJson(editingModel.model.headers), + variantsJson: stringifyJson(editingModel.model.variants), + extraJson: stringifyJson(extraEntries), createNewProvider: false, - newProviderType: 'api' as const, + newProviderType: 'api', newProviderId: '', newProviderName: '', newProviderBaseUrl: '', newProviderNpm: '', } } + return { providerId: selectedProviderId || availableProviders[0] || '', modelId: '', - name: '', - contextLimit: undefined, - outputLimit: undefined, + backingModelId: '', + providerModelProviderId: '', + displayName: '', + family: '', + status: 'none', + releaseDate: '', + apiUrl: '', + apiNpm: '', + contextLimit: '', + inputLimit: '', + outputLimit: '', + capabilitiesJson: '', + costJson: '', + optionsJson: '', + headersJson: '', + variantsJson: '', + extraJson: '', createNewProvider: availableProviders.length === 0, - newProviderType: 'api' as const, + newProviderType: 'api', newProviderId: '', newProviderName: '', newProviderBaseUrl: '', @@ -138,32 +238,60 @@ export function OpenCodeModelDialog({ const form = useForm({ resolver: zodResolver(modelFormSchema), defaultValues: getDefaultValues(), + mode: 'onChange', }) + const { isValid } = form.formState const createNewProvider = form.watch('createNewProvider') const newProviderType = form.watch('newProviderType') useEffect(() => { if (open) { form.reset(getDefaultValues()) + void form.trigger() } - }, [open, getDefaultValues, form]) + }, [open, form, getDefaultValues]) const handleSubmit = (values: ModelFormValues) => { + const extra = parseOptionalJsonField(values.extraJson) + const capabilities = parseOptionalJsonField(values.capabilitiesJson) + const cost = parseOptionalJsonField(values.costJson) + const options = parseOptionalJsonField(values.optionsJson) + const headers = parseOptionalJsonField(values.headersJson) + const variants = parseOptionalJsonField(values.variantsJson) + const model: ConfigModel = { - name: values.name, + ...(extra || {}), } - if (values.contextLimit !== undefined || values.outputLimit !== undefined) { - model.limit = {} - if (values.contextLimit !== undefined) { - model.limit.context = values.contextLimit - } - if (values.outputLimit !== undefined) { - model.limit.output = values.outputLimit - } + if (values.backingModelId.trim()) model.id = values.backingModelId.trim() + if (values.providerModelProviderId.trim()) model.providerID = values.providerModelProviderId.trim() + if (values.displayName.trim()) model.name = values.displayName.trim() + if (values.family.trim()) model.family = values.family.trim() + if (values.status !== 'none') model.status = values.status + if (values.releaseDate.trim()) model.release_date = values.releaseDate.trim() + + if (values.apiUrl.trim() || values.apiNpm.trim()) { + model.api = { url: values.apiUrl.trim(), ...(values.apiNpm.trim() ? { npm: values.apiNpm.trim() } : {}) } } + const contextLimit = parseOptionalNumber(values.contextLimit) + const inputLimit = parseOptionalNumber(values.inputLimit) + const outputLimit = parseOptionalNumber(values.outputLimit) + if (contextLimit !== undefined || inputLimit !== undefined || outputLimit !== undefined) { + model.limit = { + ...(contextLimit !== undefined ? { context: contextLimit } : {}), + ...(inputLimit !== undefined ? { input: inputLimit } : {}), + ...(outputLimit !== undefined ? { output: outputLimit } : {}), + } as ConfigModel['limit'] + } + + if (capabilities) model.capabilities = capabilities as ConfigModel['capabilities'] + if (cost) model.cost = cost as ConfigModel['cost'] + if (options) model.options = options + if (headers) model.headers = headers as Record + if (variants) model.variants = variants as ConfigModel['variants'] + let newProvider: NewProviderConfig | undefined if (values.createNewProvider) { newProvider = { @@ -175,33 +303,26 @@ export function OpenCodeModelDialog({ } } - if (newProvider) { - onSubmit(values.providerId, values.modelId, model, newProvider) - } else { - onSubmit(values.providerId, values.modelId, model) - } + if (newProvider) onSubmit(values.providerId, values.modelId, model, newProvider) + else onSubmit(values.providerId, values.modelId, model) + form.reset() onOpenChange(false) } const handleOpenChange = (isOpen: boolean) => { - if (!isOpen) { - form.reset() - } + if (!isOpen) form.reset() onOpenChange(isOpen) } const providerOptions = useMemo(() => { - return availableProviders.map((p: string) => ({ - value: p, - label: existingProviders?.[p]?.name || p, - })) + return availableProviders.map((p: string) => ({ value: p, label: existingProviders?.[p]?.name || p })) }, [availableProviders, existingProviders]) const isEditing = !!editingModel return ( - + {isEditing ? 'Edit Model' : 'Create Model'} @@ -218,15 +339,10 @@ export function OpenCodeModelDialog({
Create new provider -

- Add a new provider configuration -

+

Add a new provider configuration

- +
)} @@ -237,237 +353,281 @@ export function OpenCodeModelDialog({

New Provider

- ( - - Provider Type - - - - )} - /> - - ( - - Provider ID - - - - - - )} - /> - - ( - - Display Name (optional) - - - - - - )} - /> - - {newProviderType === 'api' && ( - ( - - Base URL - - - - - - )} - /> - )} - - {newProviderType === 'npm' && ( - ( - - NPM Package - - - - - - )} - /> - )} -
- ) : ( - ( + ( - Provider - + - {providerOptions.map(option => ( - - {option.label} - - ))} + API (HTTP endpoint) + NPM Package + )} /> + + ( + + Provider ID + + + + )} /> + + ( + + Display Name + + + + )} /> + + {newProviderType === 'api' && ( + ( + + Base URL + + + + )} /> )} - /> + + {newProviderType === 'npm' && ( + ( + + NPM Package + + + + )} /> + )} +
+ ) : ( + ( + + Provider + + + + )} /> )} - ( +
+ ( - Model ID - - - + Config Key + - )} - /> + )} /> - ( + ( + + Provider Model ID + + + + )} /> +
+ +
+ ( Display Name + + + + )} /> + + ( + + Family + + + + )} /> +
+ +
+ ( + + Status + + + + )} /> + + ( + + Release Date + + + + )} /> +
+ +
+ ( + + Model Provider ID + + + + )} /> + +
+ ( + + API URL + + + + )} /> + + ( + + API NPM + + + + )} /> +
+
+ +
+ ( + + Context Limit + + + + )} /> + + ( + + Input Limit + + + + )} /> + + ( + + Output Limit + + + + )} /> +
+ +
+

Structured JSON fields

+ + ( + + Options JSON - +