mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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:
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
|
||||
@@ -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,
|
||||
]
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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'))
|
||||
|
||||
@@ -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,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(),
|
||||
|
||||
@@ -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',
|
||||
}))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -122,6 +122,14 @@ export async function updateRepoGitCredential(id: number, credentialId?: string)
|
||||
})
|
||||
}
|
||||
|
||||
export async function renameRepo(id: number, name: string | null): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: name ?? '' }),
|
||||
})
|
||||
}
|
||||
|
||||
export class GitAuthError extends Error {
|
||||
code: string
|
||||
constructor(message: string, code: string) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export interface Repo {
|
||||
id: number
|
||||
name?: string
|
||||
repoUrl?: string
|
||||
localPath: string
|
||||
fullPath: string
|
||||
|
||||
@@ -63,7 +63,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
const currentBranch = repo?.currentBranch || repo?.branch
|
||||
const repoDisplayName = isAssistantRoute || isAssistantSession
|
||||
? 'Assistant'
|
||||
: repo ? getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath) : null
|
||||
: repo ? getRepoDisplayName(repo) : null
|
||||
|
||||
const handleSettingsClick = () => {
|
||||
updateParams((p) => {
|
||||
|
||||
@@ -50,7 +50,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
if (!searchQuery.trim()) return sorted
|
||||
const query = searchQuery.toLowerCase()
|
||||
return sorted.filter((repo) =>
|
||||
getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath).toLowerCase().includes(query)
|
||||
getRepoDisplayName(repo).toLowerCase().includes(query)
|
||||
)
|
||||
}, [regularRepos, searchQuery])
|
||||
|
||||
@@ -161,7 +161,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 font-medium text-sm text-foreground truncate">
|
||||
{getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
|
||||
{getRepoDisplayName(repo)}
|
||||
</div>
|
||||
{isActive && <Check className="h-4 w-4 text-primary flex-shrink-0" />}
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { RenameRepoDialog } from './RenameRepoDialog'
|
||||
|
||||
describe('RenameRepoDialog', () => {
|
||||
const defaultProps = {
|
||||
isOpen: true,
|
||||
currentName: 'my-custom-name',
|
||||
derivedName: 'original-repo-name',
|
||||
onClose: vi.fn(),
|
||||
onSave: vi.fn(),
|
||||
}
|
||||
|
||||
it('renders with the input prefilled from currentName', () => {
|
||||
render(<RenameRepoDialog {...defaultProps} />)
|
||||
const input = screen.getByRole('textbox')
|
||||
expect(input).toHaveValue('my-custom-name')
|
||||
})
|
||||
|
||||
it('shows the derived name as placeholder', () => {
|
||||
render(<RenameRepoDialog {...defaultProps} />)
|
||||
const input = screen.getByRole('textbox')
|
||||
expect(input).toHaveAttribute('placeholder', 'original-repo-name')
|
||||
})
|
||||
|
||||
it('calls onSave with trimmed value when submitting a new name', async () => {
|
||||
const onSave = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<RenameRepoDialog {...defaultProps} onSave={onSave} />)
|
||||
|
||||
const input = screen.getByRole('textbox')
|
||||
await user.clear(input)
|
||||
await user.type(input, ' new-name ')
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith('new-name')
|
||||
})
|
||||
|
||||
it('calls onSave(null) when submitting an empty value', async () => {
|
||||
const onSave = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<RenameRepoDialog {...defaultProps} onSave={onSave} />)
|
||||
|
||||
const input = screen.getByRole('textbox')
|
||||
await user.clear(input)
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it('calls onClose without saving when pressing Escape', async () => {
|
||||
const onClose = vi.fn()
|
||||
const onSave = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<RenameRepoDialog {...defaultProps} onClose={onClose} onSave={onSave} />)
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onClose without saving when clicking Cancel', async () => {
|
||||
const onClose = vi.fn()
|
||||
const onSave = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<RenameRepoDialog {...defaultProps} onClose={onClose} onSave={onSave} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /cancel/i }))
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onSave(null) when input is cleared via the clear button and submitted', async () => {
|
||||
const onSave = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<RenameRepoDialog {...defaultProps} onSave={onSave} />)
|
||||
|
||||
// Click the clear (X) button to clear the input
|
||||
const clearButton = screen.getByRole('button', { name: /clear/i })
|
||||
await user.click(clearButton)
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(null)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { X, Check } from 'lucide-react'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
|
||||
interface RenameRepoDialogProps {
|
||||
isOpen: boolean
|
||||
currentName: string
|
||||
derivedName: string
|
||||
onClose: () => void
|
||||
onSave: (name: string | null) => void
|
||||
}
|
||||
|
||||
export function RenameRepoDialog({
|
||||
isOpen,
|
||||
currentName,
|
||||
derivedName,
|
||||
onClose,
|
||||
onSave,
|
||||
}: RenameRepoDialogProps) {
|
||||
const [editName, setEditName] = useState(currentName)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setEditName(currentName)
|
||||
}
|
||||
}, [isOpen, currentName])
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
const trimmed = editName.trim()
|
||||
onSave(trimmed.length > 0 ? trimmed : null)
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
setEditName(currentName)
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent
|
||||
hideCloseButton
|
||||
mobileFullscreen
|
||||
className="gap-0 p-4 sm:p-6"
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-sm text-muted-foreground font-normal">Rename repository</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="min-w-0">
|
||||
<div className="relative">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
placeholder={derivedName}
|
||||
className="text-base font-semibold bg-background border border-border rounded px-3 py-2.5 pr-10 outline-none w-full focus:border-primary focus:ring-2 focus:ring-primary/20"
|
||||
autoFocus
|
||||
/>
|
||||
{editName && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Clear"
|
||||
onClick={() => {
|
||||
setEditName('')
|
||||
inputRef.current?.focus()
|
||||
}}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full hover:bg-red-500/10 text-red-500 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleCancel}
|
||||
className="flex-1 h-10"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="flex-1 h-10"
|
||||
>
|
||||
<Check className="w-4 h-4 mr-2" />
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { RepoRowActions } from "./RepoRowActions"
|
||||
interface RepoCardProps {
|
||||
repo: {
|
||||
id: number;
|
||||
name?: string | null;
|
||||
repoUrl?: string | null;
|
||||
localPath?: string;
|
||||
sourcePath?: string;
|
||||
@@ -47,7 +48,7 @@ export function RepoCard({
|
||||
const navigate = useNavigate();
|
||||
const [actionsOpen, setActionsOpen] = useState(false);
|
||||
|
||||
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
|
||||
const repoName = getRepoDisplayName(repo);
|
||||
const branchToDisplay = gitStatus?.branch || repo.currentBranch || repo.branch;
|
||||
const isReady = repo.cloneStatus === "ready";
|
||||
const isCloning = repo.cloneStatus === "cloning";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { Loader2, GitBranch, GitBranchPlus, Download, Trash2, MoreVertical } from 'lucide-react'
|
||||
import { Loader2, GitBranch, GitBranchPlus, Download, Trash2, MoreVertical, Pencil } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -10,14 +10,18 @@ import {
|
||||
import { SourceControlPanel } from '@/components/source-control/SourceControlPanel'
|
||||
import { DownloadDialog } from '@/components/ui/download-dialog'
|
||||
import { CreateWorktreeDialog } from '@/components/repo/CreateWorktreeDialog'
|
||||
import { RenameRepoDialog } from '@/components/repo/RenameRepoDialog'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { downloadRepo } from '@/api/repos'
|
||||
import { useQueryClient, useMutation } from '@tanstack/react-query'
|
||||
import { downloadRepo, renameRepo } from '@/api/repos'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { invalidateRepoListCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
interface RepoRowActionsProps {
|
||||
repo: {
|
||||
id: number
|
||||
name?: string | null
|
||||
repoUrl?: string | null
|
||||
localPath?: string
|
||||
sourcePath?: string
|
||||
@@ -50,16 +54,38 @@ export function RepoRowActions({
|
||||
const [showDownloadDialog, setShowDownloadDialog] = useState(false)
|
||||
const [showSourceControl, setShowSourceControl] = useState(false)
|
||||
const [showWorktreeDialog, setShowWorktreeDialog] = useState(false)
|
||||
const [showRenameDialog, setShowRenameDialog] = useState(false)
|
||||
|
||||
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)
|
||||
const repoName = getRepoDisplayName(repo)
|
||||
const branchToDisplay = gitStatus?.branch || repo.currentBranch || repo.branch
|
||||
const isReady = repo.cloneStatus === 'ready'
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const renameMutation = useMutation({
|
||||
mutationFn: (name: string | null) => renameRepo(repo.id, name),
|
||||
onSuccess: (updated) => {
|
||||
invalidateRepoListCaches(queryClient)
|
||||
queryClient.setQueryData(['repo', repo.id], updated)
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repo.id] })
|
||||
showToast.success('Repository renamed')
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
showToast.error(error instanceof Error ? error.message : 'Rename failed')
|
||||
},
|
||||
})
|
||||
|
||||
const handleSourceControlOpen = (open: boolean) => {
|
||||
setShowSourceControl(open)
|
||||
onActionsOpenChange?.(open)
|
||||
}
|
||||
|
||||
const handleRenameOpen = (open: boolean) => {
|
||||
setShowRenameDialog(open)
|
||||
onActionsOpenChange?.(open)
|
||||
}
|
||||
|
||||
const handleDownloadDialogOpen = (open: boolean) => {
|
||||
setShowDownloadDialog(open)
|
||||
onActionsOpenChange?.(open)
|
||||
@@ -111,6 +137,10 @@ export function RepoRowActions({
|
||||
<GitBranch className="w-4 h-4 mr-2" />
|
||||
Source Control
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleRenameOpen(true)}>
|
||||
<Pencil className="w-4 h-4 mr-2" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDownloadDialogOpen(true)}
|
||||
disabled={!isReady}
|
||||
@@ -155,6 +185,13 @@ export function RepoRowActions({
|
||||
itemName={repoName}
|
||||
targetPath={repo.fullPath}
|
||||
/>
|
||||
<RenameRepoDialog
|
||||
isOpen={showRenameDialog}
|
||||
currentName={repo.name ?? ''}
|
||||
derivedName={repoName}
|
||||
onClose={() => handleRenameOpen(false)}
|
||||
onSave={(name) => renameMutation.mutate(name)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -163,6 +200,22 @@ export function RepoRowActions({
|
||||
<>
|
||||
<TooltipProvider delayDuration={200}>
|
||||
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
aria-label="Rename Repository"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleRenameOpen(true)}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Rename Repository"
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Rename Repository</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
@@ -261,6 +314,13 @@ export function RepoRowActions({
|
||||
repoUrl={repo.repoUrl}
|
||||
defaultBaseBranch={branchToDisplay}
|
||||
/>
|
||||
<RenameRepoDialog
|
||||
isOpen={showRenameDialog}
|
||||
currentName={repo.name ?? ''}
|
||||
derivedName={repoName}
|
||||
onClose={() => handleRenameOpen(false)}
|
||||
onSave={(name) => renameMutation.mutate(name)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -82,7 +82,7 @@ export function filterReposBySearch(repos: RepoViewModel[], searchQuery: string)
|
||||
|
||||
const query = searchQuery.toLowerCase()
|
||||
return repos.filter((repo) => {
|
||||
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)
|
||||
const repoName = getRepoDisplayName(repo)
|
||||
const searchTarget = repo.repoUrl || repo.sourcePath || repo.localPath || ""
|
||||
return (
|
||||
repoName.toLowerCase().includes(query) ||
|
||||
@@ -118,8 +118,8 @@ export function sortRepos(repos: RepoViewModel[], mode: RepoSortMode, manualOrde
|
||||
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()
|
||||
const nameA = getRepoDisplayName(a).toLowerCase()
|
||||
const nameB = getRepoDisplayName(b).toLowerCase()
|
||||
return nameA.localeCompare(nameB)
|
||||
})
|
||||
case 'manual': {
|
||||
|
||||
@@ -118,7 +118,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
.filter((repo) => repo.cloneStatus === 'ready')
|
||||
.map((repo) => ({
|
||||
value: repo.id.toString(),
|
||||
label: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath),
|
||||
label: getRepoDisplayName(repo),
|
||||
description: repo.localPath,
|
||||
}))
|
||||
return [assistantOption, ...repoEntries]
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Alert } from '@/components/ui/alert'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { MultiSelect, type MultiSelectOption } from '@/components/ui/multi-select'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import type { GitCredential } from '@/api/types/settings'
|
||||
import type { Repo } from '@/api/types'
|
||||
|
||||
@@ -83,7 +84,7 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, re
|
||||
|
||||
const repoOptions: MultiSelectOption[] = repos.map((repo) => ({
|
||||
value: String(repo.id),
|
||||
label: repo.repoUrl?.split('/').pop()?.replace('.git', '') || repo.localPath,
|
||||
label: getRepoDisplayName(repo),
|
||||
description: repo.repoUrl || repo.fullPath,
|
||||
}))
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import type { SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { listRepos } from '@/api/repos'
|
||||
@@ -205,7 +206,7 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil
|
||||
<SelectContent>
|
||||
{repos.map((repo) => (
|
||||
<SelectItem key={repo.id} value={repo.id.toString()}>
|
||||
{repo.localPath}
|
||||
{getRepoDisplayName(repo)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
@@ -194,7 +195,7 @@ export function SkillInstallDialog({ open, onOpenChange, onInstalled }: SkillIns
|
||||
<SelectContent>
|
||||
{repos.map((repo) => (
|
||||
<SelectItem key={repo.id} value={repo.id.toString()}>
|
||||
{repo.localPath}
|
||||
{getRepoDisplayName(repo)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
|
||||
@@ -21,7 +21,7 @@ export function scheduleTargetFromRepo(repo: Repo): ScheduleTarget {
|
||||
return {
|
||||
repoId: repo.id,
|
||||
kind: 'repo',
|
||||
name: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath),
|
||||
name: getRepoDisplayName(repo),
|
||||
subtitle: repo.localPath,
|
||||
fullPath: repo.fullPath,
|
||||
backHref: `/repos/${repo.id}`,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { sanitizeForTTS } from './utils'
|
||||
import { getRepoDisplayName, sanitizeForTTS } from './utils'
|
||||
|
||||
describe('sanitizeForTTS', () => {
|
||||
it('should handle headers', () => {
|
||||
@@ -82,3 +82,33 @@ describe('sanitizeForTTS', () => {
|
||||
expect(sanitizeForTTS('Text with <tag>content</tag> here')).toBe('Text with content here')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getRepoDisplayName', () => {
|
||||
it('prefers name when present', () => {
|
||||
expect(getRepoDisplayName({ name: 'Fork A', repoUrl: 'https://github.com/x/y.git' })).toBe('Fork A')
|
||||
})
|
||||
|
||||
it('trims and ignores empty name', () => {
|
||||
expect(getRepoDisplayName({ name: ' ', repoUrl: 'https://github.com/x/y.git' })).toBe('y')
|
||||
})
|
||||
|
||||
it('falls back to repoUrl basename stripping .git', () => {
|
||||
expect(getRepoDisplayName({ repoUrl: 'https://github.com/user/repo.git' })).toBe('repo')
|
||||
})
|
||||
|
||||
it('falls back to sourcePath basename', () => {
|
||||
expect(getRepoDisplayName({ sourcePath: '/home/user/projects/my-repo' })).toBe('my-repo')
|
||||
})
|
||||
|
||||
it('falls back to the localPath basename', () => {
|
||||
expect(getRepoDisplayName({ localPath: '/some/path' })).toBe('path')
|
||||
})
|
||||
|
||||
it('falls back to Repository when all are empty', () => {
|
||||
expect(getRepoDisplayName({})).toBe('Repository')
|
||||
})
|
||||
|
||||
it('handles null values properly', () => {
|
||||
expect(getRepoDisplayName({ repoUrl: null, localPath: null, sourcePath: null })).toBe('Repository')
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,8 @@ import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import type { CSSProperties } from "react"
|
||||
|
||||
export { getRepoDisplayName } from '@opencode-manager/shared/utils'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -14,20 +16,6 @@ export const GPU_ACCELERATED_STYLE: CSSProperties = {
|
||||
|
||||
export const MODAL_TRANSITION_MS = 300
|
||||
|
||||
function getPathBaseName(filePath: string): string {
|
||||
return filePath.split(/[\\/]/).pop() || filePath
|
||||
}
|
||||
|
||||
export function getRepoDisplayName(repoUrl?: string | null, localPath?: string | null, sourcePath?: string | null): string {
|
||||
if (repoUrl) {
|
||||
return repoUrl.split("/").pop()?.replace(".git", "") || "Repository"
|
||||
}
|
||||
if (sourcePath) {
|
||||
return getPathBaseName(sourcePath) || localPath || 'Repository'
|
||||
}
|
||||
return localPath || "Repository"
|
||||
}
|
||||
|
||||
export function sanitizeForTTS(text: string): string {
|
||||
if (!text) return ''
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ export function RepoDetail() {
|
||||
);
|
||||
}
|
||||
|
||||
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
|
||||
const repoName = getRepoDisplayName(repo);
|
||||
const branchToDisplay = repo.currentBranch || repo.branch;
|
||||
const displayName = branchToDisplay ? `${repoName} (${branchToDisplay})` : repoName;
|
||||
const currentBranch = repo.currentBranch || repo.branch || "main";
|
||||
|
||||
@@ -421,7 +421,7 @@ export function SessionDetail() {
|
||||
|
||||
const workspaceDisplayName = isAssistantSession || !repo
|
||||
? 'Assistant'
|
||||
: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
|
||||
: getRepoDisplayName(repo);
|
||||
const tabFromUrl = new URLSearchParams(location.search).get('repoTab') ?? undefined;
|
||||
const sessionBackPath = getSessionListPath(repoId, isAssistantSession, tabFromUrl);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ export const RepoStatusSchema = z.enum(['cloning', 'ready', 'error'])
|
||||
|
||||
export const RepoSchema = z.object({
|
||||
id: z.number(),
|
||||
name: z.string().optional(),
|
||||
repoUrl: z.string().url().optional(),
|
||||
localPath: z.string(),
|
||||
fullPath: z.string(),
|
||||
@@ -45,6 +46,10 @@ export const DiscoverReposRequestSchema = z.object({
|
||||
maxDepth: z.number().int().min(0).max(8).optional(),
|
||||
})
|
||||
|
||||
export const UpdateRepoRequestSchema = z.object({
|
||||
name: z.string().trim().max(100).nullable(),
|
||||
})
|
||||
|
||||
export const DiscoverReposResponseSchema = z.object({
|
||||
repos: z.array(RepoSchema),
|
||||
discoveredCount: z.number().int().nonnegative(),
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
CreateRepoRequestSchema,
|
||||
DiscoverReposRequestSchema,
|
||||
DiscoverReposResponseSchema,
|
||||
UpdateRepoRequestSchema,
|
||||
RepoStatusSchema,
|
||||
AssistantModeStatusSchema,
|
||||
AssistantModeInitRequestSchema,
|
||||
@@ -65,6 +66,7 @@ export type CreateRepoRequest = z.infer<typeof CreateRepoRequestSchema>
|
||||
export type DiscoverReposRequest = z.infer<typeof DiscoverReposRequestSchema>
|
||||
export type DiscoverReposResponse = z.infer<typeof DiscoverReposResponseSchema>
|
||||
export type RepoStatus = z.infer<typeof RepoStatusSchema>
|
||||
export type UpdateRepoRequest = z.infer<typeof UpdateRepoRequestSchema>
|
||||
export type AssistantModeStatus = z.infer<typeof AssistantModeStatusSchema>
|
||||
export type AssistantModeInitRequest = z.infer<typeof AssistantModeInitRequestSchema>
|
||||
|
||||
|
||||
@@ -79,6 +79,23 @@ export function getRepoNameFromUrl(url: string): string {
|
||||
return parts[parts.length - 1] || ''
|
||||
}
|
||||
|
||||
function getPathBaseName(filePath: string): string {
|
||||
return filePath.split(/[\\/]/).pop() || filePath
|
||||
}
|
||||
|
||||
export function getRepoDisplayName(repo: {
|
||||
name?: string | null
|
||||
repoUrl?: string | null
|
||||
localPath?: string | null
|
||||
sourcePath?: string | null
|
||||
}): string {
|
||||
if (repo.name && repo.name.trim()) return repo.name.trim()
|
||||
const fromLocalPath = repo.localPath ? getPathBaseName(repo.localPath) : ''
|
||||
if (repo.repoUrl) return getRepoNameFromUrl(repo.repoUrl) || fromLocalPath || 'Repository'
|
||||
if (repo.sourcePath) return getPathBaseName(repo.sourcePath) || fromLocalPath || 'Repository'
|
||||
return fromLocalPath || 'Repository'
|
||||
}
|
||||
|
||||
export function normalizeRepoUrlForCompare(url: string): string {
|
||||
let normalized = trimTrailingChar(url.trim().replace(/\.git$/, ''), '/')
|
||||
const shorthandMatch = normalized.match(/^([^/]+)\/([^/]+)$/)
|
||||
|
||||
Reference in new issue
Block a user