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

+8
View File
@@ -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
View File
@@ -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>
)
}
+2 -1
View File
@@ -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}`,
+31 -1
View File
@@ -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 -14
View File
@@ -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 ''
+1 -1
View File
@@ -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";
+1 -1
View File
@@ -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);