feat: add repo rename capability with custom name field (#294)

* feat: add repo rename capability with custom name field

Add a custom name field to repos, allowing users to set a display name
independent of the repo URL or path. Includes a migration, PATCH endpoint,
rename dialog, and display name consolidation.

- DB migration 014 adds name column to repos table
- PATCH /api/repos/:id endpoint with Zod validation
- RenameRepoDialog component with clear/reset support
- RepoRowActions gains Rename action in both dropdown and inline modes
- getRepoDisplayName() consolidated to accept a repo object and prefer name
- All repo name display call sites updated to use the new API

* fix: add DialogTitle to RenameRepoDialog for a11y compliance

* refactor: extract getRepoDisplayName to shared utils, fix schedule cache invalidation on rename
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-28 14:49:00 -04:00
1 parent 01e50a7019
commit 6a4e8734f9
33 files changed
+535 -84

No files matched your search

@@ -0,0 +1,25 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
}
const migration: Migration = {
version: 14,
name: 'repos-add-name',
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('name')) {
db.run('ALTER TABLE repos ADD COLUMN name TEXT')
}
},
down(db) {
void db
},
}
export default migration
+2
View File
@@ -12,6 +12,7 @@ import migration010 from './009-prompt-templates'
import migration011 from './011-repo-last-accessed'
import migration012 from './012-opencode-model-state'
import migration013 from './013-app-secrets'
import migration014 from './014-repos-add-name'
export const allMigrations: Migration[] = [
migration001,
@@ -27,4 +28,5 @@ export const allMigrations: Migration[] = [
migration011,
migration012,
migration013,
migration014,
]
+13 -5
View File
@@ -1,12 +1,13 @@
import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
import { getErrorMessage } from '../utils/error-utils'
import path from 'path'
interface RepoRow {
id: number
name?: string
repo_url?: string
local_path: string
source_path?: string
@@ -28,6 +29,7 @@ function rowToRepo(row: RepoRow): Repo {
return {
id: row.id,
name: row.name ?? undefined,
repoUrl: row.repo_url,
localPath: row.local_path,
fullPath,
@@ -285,10 +287,8 @@ export function listRepos(db: Database, repoOrder?: number[]): Repo[] {
return [...orderedRepos, ...remainingRepos]
}
function getRepoName(repo: Repo): string {
return repo.repoUrl
? repo.repoUrl.split('/').slice(-1)[0]?.replace('.git', '') || repo.localPath
: repo.sourcePath ? path.basename(repo.sourcePath) : repo.localPath
export function getRepoName(repo: Repo): string {
return getRepoDisplayName(repo)
}
export function updateRepoStatus(db: Database, id: number, cloneStatus: Repo['cloneStatus']): void {
@@ -331,6 +331,14 @@ export function updateRepoBranch(db: Database, id: number, branch: string): void
}
}
export function updateRepoName(db: Database, id: number, name: string | null): void {
const stmt = db.prepare('UPDATE repos SET name = ? WHERE id = ?')
const result = stmt.run(name, id)
if (result.changes === 0) {
throw new Error(`Repository with id ${id} not found`)
}
}
export function deleteRepo(db: Database, id: number): void {
if (id === ASSISTANT_REPO_ID) {
return
+26 -11
View File
@@ -9,7 +9,7 @@ import {
type ScheduleRunStatus,
type ScheduleRunTriggerSource,
} from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
interface ScheduleJobRow {
@@ -403,31 +403,42 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
interface ScheduleJobWithRepoRow extends ScheduleJobRow {
repo_url: string | null
repo_path: string | null
repo_name: string | null
repo_source_path: string | null
}
function repoNameFromPath(repoPath: string): string {
if (!repoPath || repoPath === '/') return 'Unknown'
return repoPath.split(/[\\/]/).pop() ?? repoPath
interface RepoDisplayRow {
repo_id: number
repo_path: string | null
repo_name: string | null
repo_url?: string | null
repo_source_path?: string | null
}
function resolveRepoDisplay(repoId: number, repoPath: string | null): { repoName: string; repoPath: string } {
if (repoId === ASSISTANT_REPO_ID) {
function resolveRepoDisplay(row: RepoDisplayRow): { repoName: string; repoPath: string } {
if (row.repo_id === ASSISTANT_REPO_ID) {
return { repoName: ASSISTANT_REPO_NAME, repoPath: ASSISTANT_REPO_PATH }
}
return { repoName: repoNameFromPath(repoPath ?? ''), repoPath: repoPath ?? '' }
const displayName = getRepoDisplayName({
name: row.repo_name,
repoUrl: row.repo_url,
sourcePath: row.repo_source_path,
localPath: row.repo_path,
})
return { repoName: displayName, repoPath: row.repo_path ?? '' }
}
function rowToScheduleJobWithRepo(row: ScheduleJobWithRepoRow): ScheduleJobWithRepo {
return {
...rowToScheduleJob(row),
...resolveRepoDisplay(row.repo_id, row.repo_path),
...resolveRepoDisplay(row),
repoUrl: row.repo_url ?? '',
}
}
export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[] {
const stmt = db.prepare(`
SELECT sj.*, r.repo_url, r.local_path as repo_path
SELECT sj.*, r.repo_url, r.local_path as repo_path, r.name as repo_name, r.source_path as repo_source_path
FROM schedule_jobs sj
LEFT JOIN repos r ON sj.repo_id = r.id
ORDER BY COALESCE(r.local_path, ''), sj.name
@@ -445,13 +456,16 @@ export interface ScheduleRunWithContext extends ScheduleRun {
interface ScheduleRunWithContextRow extends ScheduleRunRow {
job_name: string
repo_path: string | null
repo_name: string | null
repo_url: string | null
repo_source_path: string | null
}
function rowToScheduleRunWithContext(row: ScheduleRunWithContextRow): ScheduleRunWithContext {
return {
...rowToScheduleRun(row),
jobName: row.job_name,
...resolveRepoDisplay(row.repo_id, row.repo_path),
...resolveRepoDisplay(row),
}
}
@@ -494,7 +508,8 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
sr.started_at, sr.finished_at, sr.created_at,
sr.session_id, sr.session_title,
NULL AS log_text, NULL AS response_text, sr.error_text,
sj.name AS job_name, r.local_path AS repo_path
sj.name AS job_name, r.local_path AS repo_path, r.name AS repo_name,
r.repo_url AS repo_url, r.source_path AS repo_source_path
FROM schedule_runs sr
JOIN schedule_jobs sj ON sr.job_id = sj.id
LEFT JOIN repos r ON sr.repo_id = r.id
@@ -1,10 +1,9 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { listRepos } from '../../db/queries'
import { getRepoName, listRepos } from '../../db/queries'
import { resolveProjectId } from '../../services/project-id-resolver'
import { logger } from '../../utils/logger'
import { getErrorMessage } from '../../utils/error-utils'
import path from 'path'
export function createInternalOpenCodeWorkspacesRoutes(db: Database) {
const app = new Hono()
@@ -15,11 +14,7 @@ export function createInternalOpenCodeWorkspacesRoutes(db: Database) {
const workspaces = await Promise.all(
repos.map(async (repo) => ({
repoId: repo.id,
name: repo.repoUrl
? repo.repoUrl.split('/').slice(-1)[0]?.replace('.git', '') || repo.localPath
: repo.sourcePath
? path.basename(repo.sourcePath)
: repo.localPath,
name: getRepoName(repo),
branch: repo.branch ?? null,
cloneStatus: repo.cloneStatus,
directory: repo.fullPath,
+2 -2
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { getRepoById } from '../../db/queries'
import { getRepoById, getRepoName } from '../../db/queries'
import { logger } from '../../utils/logger'
import { getErrorMessage } from '../../utils/error-utils'
import { safeGitOut } from './repo-sync-helpers'
@@ -25,7 +25,7 @@ export function createInternalRepoSyncRoutes(db: Database) {
])
return c.json({
repoId,
repoName: repo.repoUrl?.split('/').slice(-1)[0]?.replace('.git', '') ?? null,
repoName: getRepoName(repo),
directory: repoPath,
originUrl: originUrl?.trim() || null,
head: head?.trim() || null,
+72 -1
View File
@@ -4,10 +4,11 @@ import { Database } from 'bun:sqlite'
import { migrate } from '../db/migration-runner'
import { allMigrations } from '../db/migrations'
import { createRepoRoutes } from './repos'
import { createRepo } from '../db/queries'
import { createRepo, getRepoById } from '../db/queries'
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
import type { GitAuthService } from '../services/git-auth'
import type { OpenCodeClient } from '../services/opencode/client'
import type { Repo } from '@opencode-manager/shared/types'
import { getReposPath } from '@opencode-manager/shared/config/env'
import path from 'path'
@@ -332,3 +333,73 @@ describe('POST /api/repos/:id/workspaces', () => {
expect(await res.json()).toMatchObject({ id: 'wrk_test', type: 'worktree' })
})
})
describe('PATCH /api/repos/:id', () => {
let db: Database
let app: Hono
beforeEach(() => {
db = createTestDb()
app = createTestApp(db)
})
afterEach(() => {
db.close()
})
it('sets a custom name on a ready repo', async () => {
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
const res = await app.request('/repos/1', { method: 'PATCH', body: JSON.stringify({ name: 'My Fork' }), headers: { 'Content-Type': 'application/json' } })
expect(res.status).toBe(200)
const data = await res.json() as Repo
expect(data.name).toBe('My Fork')
const stored = getRepoById(db, 1)
expect(stored?.name).toBe('My Fork')
})
it('clears a custom name (reverts to derived)', async () => {
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
await app.request('/repos/1', { method: 'PATCH', body: JSON.stringify({ name: 'My Fork' }), headers: { 'Content-Type': 'application/json' } })
const res = await app.request('/repos/1', { method: 'PATCH', body: JSON.stringify({ name: '' }), headers: { 'Content-Type': 'application/json' } })
expect(res.status).toBe(200)
const data = await res.json() as Repo
expect(data.name).toBeUndefined()
const stored = getRepoById(db, 1)
expect(stored?.name).toBeUndefined()
})
it('trims whitespace from the name', async () => {
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
const res = await app.request('/repos/1', { method: 'PATCH', body: JSON.stringify({ name: ' Spaced ' }), headers: { 'Content-Type': 'application/json' } })
expect(res.status).toBe(200)
const data = await res.json() as Repo
expect(data.name).toBe('Spaced')
})
it('returns 404 for non-existent repo', async () => {
const res = await app.request('/repos/999999', { method: 'PATCH', body: JSON.stringify({ name: 'Test' }), headers: { 'Content-Type': 'application/json' } })
expect(res.status).toBe(404)
const data = await res.json() as { error: string }
expect(data.error).toBe('Repo not found')
})
it('returns 400 for assistant repo', async () => {
const res = await app.request('/repos/0', { method: 'PATCH', body: JSON.stringify({ name: 'Test' }), headers: { 'Content-Type': 'application/json' } })
expect(res.status).toBe(400)
const data = await res.json() as { error: string }
expect(data.error).toBe('Assistant repository cannot be renamed')
})
it('returns 400 for name exceeding 100 characters', async () => {
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
const longName = 'a'.repeat(101)
const res = await app.request('/repos/1', { method: 'PATCH', body: JSON.stringify({ name: longName }), headers: { 'Content-Type': 'application/json' } })
expect(res.status).toBe(400)
})
})
+28 -2
View File
@@ -2,8 +2,8 @@ import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { Database } from 'bun:sqlite'
import type { Repo } from '@opencode-manager/shared/types'
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema } from '@opencode-manager/shared/schemas'
import { listRepos, getRepoById, updateLastAccessed, updateRepoConfigName, getRepoGitCredentialId, setRepoGitCredentialId } from '../db/queries'
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema, UpdateRepoRequestSchema } from '@opencode-manager/shared/schemas'
import { listRepos, getRepoById, updateLastAccessed, updateRepoConfigName, getRepoGitCredentialId, setRepoGitCredentialId, updateRepoName } from '../db/queries'
import * as repoService from '../services/repo'
import * as archiveService from '../services/archive'
import { SettingsService } from '../services/settings'
@@ -249,6 +249,32 @@ app.get('/', async (c) => {
}
})
app.patch('/:id', async (c) => {
try {
const id = parseInt(c.req.param('id'))
if (Number.isNaN(id)) return c.json({ error: 'Invalid repo id' }, 400)
if (id === ASSISTANT_REPO_ID) {
return c.json({ error: 'Assistant repository cannot be renamed' }, 400)
}
const repo = getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const body = await c.req.json()
const parsed = UpdateRepoRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
}
const trimmed = parsed.data.name?.trim()
updateRepoName(database, id, trimmed && trimmed.length > 0 ? trimmed : null)
const updated = getRepoById(database, id)
return c.json(withRepoSettings(database, updated ?? repo))
} catch (error: unknown) {
logger.error('Failed to rename repo:', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.delete('/:id/workspaces/:workspaceId', async (c) => {
try {
const id = parseInt(c.req.param('id'))
+2 -2
View File
@@ -14,7 +14,7 @@ import {
} from "@opencode-manager/shared/notifications";
import { SettingsService } from "./settings";
import { sseAggregator, type SSEEvent } from "./sse-aggregator";
import { getRepoByLocalPath, getRepoBySourcePath } from "../db/queries";
import { getRepoByLocalPath, getRepoBySourcePath, getRepoName } from "../db/queries";
import { getReposPath } from "@opencode-manager/shared/config/env";
import path from "path";
@@ -271,7 +271,7 @@ export class NotificationService {
if (repo) {
repoId = repo.id;
repoName = path.basename(repo.localPath);
repoName = getRepoName(repo);
notificationUrl = sessionId
? `/repos/${repo.id}/sessions/${sessionId}`
: `/repos/${repo.id}`;
+5 -5
View File
@@ -5,7 +5,7 @@ import type { Database } from 'bun:sqlite'
import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest, InstallSkillUploadRequest, InstallSkillFromGithubRequest, InstallSkillResponse } from '@opencode-manager/shared'
import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shared'
import { getWorkspacePath, FILE_LIMITS } from '@opencode-manager/shared/config/env'
import { getRepoById, listRepos } from '../db/queries'
import { getRepoById, getRepoName, listRepos } from '../db/queries'
import type { Repo } from '@opencode-manager/shared/types'
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory, normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations'
import type { OpenCodeClient } from './opencode/client'
@@ -161,7 +161,7 @@ async function installSkillFiles(
scope: input.scope,
location: skillPath,
repoId: input.scope === 'project' ? input.repoId : undefined,
repoName: repo?.localPath,
repoName: repo ? getRepoName(repo) : undefined,
},
overwritten: Boolean(existingTarget),
sourceType: input.sourceType,
@@ -434,7 +434,7 @@ function toSkillFileInfo(
scope: classification.scope,
location: skill.location,
repoId: classification.repo?.id,
repoName: classification.repo?.localPath,
repoName: classification.repo ? getRepoName(classification.repo) : undefined,
}
}
@@ -468,7 +468,7 @@ async function scanSkillRoot(root: string, scope: SkillScope, repo?: Repo): Prom
scope,
location: skillPath,
repoId: scope === 'project' ? repo?.id : undefined,
repoName: scope === 'project' ? repo?.localPath : undefined,
repoName: scope === 'project' && repo ? getRepoName(repo) : undefined,
}
} catch (error) {
logger.warn(`Failed to read skill at ${skillPath}:`, error)
@@ -597,7 +597,7 @@ export async function createSkill(
scope,
location: skillPath,
repoId: scope === 'project' ? repoId : undefined,
repoName: repo?.localPath,
repoName: repo ? getRepoName(repo) : undefined,
}
}
@@ -24,9 +24,13 @@ vi.mock('bun:sqlite', () => ({
}))
const mockListRepos = vi.fn()
vi.mock('../../src/db/queries', () => ({
listRepos: (...args: unknown[]) => mockListRepos(...args),
}))
vi.mock('../../src/db/queries', async () => {
const { getRepoDisplayName } = await vi.importActual<typeof import('@opencode-manager/shared/utils')>('@opencode-manager/shared/utils')
return {
listRepos: (...args: unknown[]) => mockListRepos(...args),
getRepoName: (repo: Parameters<typeof getRepoDisplayName>[0]) => getRepoDisplayName(repo),
}
})
vi.mock('../../src/db/migration-runner', () => ({
migrate: vi.fn(),
+18 -14
View File
@@ -16,19 +16,23 @@ vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
}
})
vi.mock('../../src/db/queries', () => ({
getRepoById: vi.fn(),
listRepos: vi.fn(() => []),
getRepoByUrlAndBranch: vi.fn(),
getRepoByLocalPath: vi.fn(),
getRepoBySourcePath: vi.fn(),
createRepo: vi.fn(),
updateRepoStatus: vi.fn(),
updateRepoConfigName: vi.fn(),
updateLastPulled: vi.fn(),
updateRepoBranch: vi.fn(),
deleteRepo: vi.fn(),
}))
vi.mock('../../src/db/queries', async () => {
const { getRepoDisplayName } = await vi.importActual<typeof import('@opencode-manager/shared/utils')>('@opencode-manager/shared/utils')
return {
getRepoById: vi.fn(),
listRepos: vi.fn(() => []),
getRepoByUrlAndBranch: vi.fn(),
getRepoByLocalPath: vi.fn(),
getRepoBySourcePath: vi.fn(),
createRepo: vi.fn(),
updateRepoStatus: vi.fn(),
updateRepoConfigName: vi.fn(),
updateLastPulled: vi.fn(),
updateRepoBranch: vi.fn(),
deleteRepo: vi.fn(),
getRepoName: (repo: Parameters<typeof getRepoDisplayName>[0]) => getRepoDisplayName(repo),
}
})
function createMockClient(skills: Array<{ name: string; description: string; location: string; content: string }>): OpenCodeClient {
return {
@@ -332,7 +336,7 @@ describe('SkillService', () => {
description: 'Helps project work',
scope: 'project',
repoId: repo.id,
repoName: 'Project Zero',
repoName: 'project-zero',
}))
}
})