feat(git): extend source control with worktrees, stashes, conflicts and identities

- Create a worktree from a new or existing branch
- Integrate a worktree branch into a target branch by merge commit or cherry-pick, with continue/abort on conflicts
- Delete a worktree with keep, delete-local, or delete-local-and-remote branch options, using safe branch deletion for unmerged branches
- Add a stash tab (list, push, apply, pop, drop) shared across a repository and its worktrees
- Rename and delete branches, optionally deleting the remote branch and updating scheduled base branches
- Detect in-progress merge, rebase, cherry-pick and revert operations and hand conflicts to an agent session
- Generate commit messages from staged changes with the default model
- Add a default git identity and saved per-repository identities written to git config
- Unify git error mapping behind a typed error and one route helper; consolidate git mutations and cache invalidation
- Update repository docs
This commit is contained in:
Chris Scott committed 2026-10-03 21:59:00 -04:00
1 parent 52b6147ed3
commit 53238a6324
89 files changed
+7704 -793

No files matched your search

+91 -2
View File
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query'
import { fetchWrapper, FetchError } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { DeleteBranchRequest, DeleteBranchResult, GitStashEntry, IntegrateBranchRequest, IntegrateBranchResult, RenameBranchRequest, StashApplyRequest, StashDropRequest, StashPushRequest } from '@opencode-manager/shared'
import type { GitStatusResponse, FileDiffResponse, GitCommit, CommitDetails } from '@/types/git'
export async function fetchGitStatus(repoId: number): Promise<GitStatusResponse> {
@@ -73,6 +74,12 @@ export async function gitCommit(repoId: number, message: string, stagedPaths?: s
})
}
export async function gitGenerateCommitMessage(repoId: number): Promise<{ message: string }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit-message`, {
method: 'POST',
})
}
export async function gitStageFiles(repoId: number, paths: string[]): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stage`, {
method: 'POST',
@@ -105,12 +112,94 @@ export async function gitReset(repoId: number, commitHash: string): Promise<GitS
})
}
export function useGitStatus(repoId: number | undefined) {
export async function gitRenameBranch(repoId: number, request: RenameBranchRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches/rename`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitDeleteBranch(
repoId: number,
request: DeleteBranchRequest
): Promise<DeleteBranchResult & { status: GitStatusResponse }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
async function fetchGitStashes(repoId: number): Promise<{ stashes: GitStashEntry[] }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`)
}
export async function gitStashPush(repoId: number, request: StashPushRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitStashApply(repoId: number, index: number, request: StashApplyRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}/apply`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitStashDrop(repoId: number, index: number, request: StashDropRequest): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function gitContinueOperation(repoId: number): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/continue`, {
method: 'POST',
})
}
export async function gitAbortOperation(repoId: number): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/abort`, {
method: 'POST',
})
}
export async function gitIntegrateBranch(
repoId: number,
request: IntegrateBranchRequest
): Promise<IntegrateBranchResult & { targetStatus: GitStatusResponse }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/integrate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
interface GitStatusQueryOptions {
refetchInterval?: number | false
}
export function useGitStatus(repoId: number | undefined, options: GitStatusQueryOptions = {}) {
return useQuery({
queryKey: ['gitStatus', repoId],
queryFn: () => repoId ? fetchGitStatus(repoId) : Promise.reject(new Error('No repo ID')),
enabled: !!repoId,
refetchInterval: false,
refetchInterval: options.refetchInterval ?? false,
})
}
export function useGitStashes(repoId: number | undefined) {
return useQuery({
queryKey: ['gitStashes', repoId],
queryFn: () => repoId ? fetchGitStashes(repoId) : Promise.reject(new Error('No repo ID')),
enabled: !!repoId,
})
}
+43
View File
@@ -9,6 +9,7 @@ import {
compactSession,
createSession,
createSessionWithContext,
createSessionWithPrompt,
deleteSession,
findFiles,
forkSession,
@@ -215,6 +216,48 @@ describe('OpenCode facade', () => {
expect((deleteInit as RequestInit).method).toBe('DELETE')
})
it('creates a session in a directory and sends a prompt', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') }))
.mockResolvedValueOnce(
jsonResponse({
data: {
id: 'msg_1',
sessionID: 'ses_new',
time: { created: 1000 },
type: 'user',
payload: { text: 'Fix conflicts' },
},
}),
)
const session = await createSessionWithPrompt(
{ directory: '/abs/repos/my-repo', title: 'Resolve merge conflicts' },
'Fix conflicts',
)
expect(session.id).toBe('ses_new')
const [createUrl] = fetchMock.mock.calls[0] ?? []
expect(String(createUrl)).toBe('http://localhost/api/opencode/api/session')
const [promptUrl, promptInit] = fetchMock.mock.calls[1] ?? []
expect(String(promptUrl)).toBe('http://localhost/api/opencode/api/session/ses_new/prompt')
expect((promptInit as RequestInit).method).toBe('POST')
expect((promptInit as RequestInit).body).toBe(JSON.stringify({ text: 'Fix conflicts' }))
})
it('deletes the new session when sending the prompt fails', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse({ data: sessionInfo('ses_new', '/abs/repos/my-repo') }))
.mockResolvedValueOnce(new Response('nope', { status: 400 }))
.mockResolvedValueOnce(new Response(null, { status: 204 }))
await expect(createSessionWithPrompt({ directory: '/abs/repos/my-repo' }, 'Fix conflicts')).rejects.toBeInstanceOf(FetchError)
const [deleteUrl, deleteInit] = fetchMock.mock.calls[2] ?? []
expect(String(deleteUrl)).toBe('http://localhost/api/opencode/api/session/ses_new')
expect((deleteInit as RequestInit).method).toBe('DELETE')
})
it('finds files through the V2 filesystem route and returns paths', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
+13 -2
View File
@@ -140,10 +140,13 @@ export async function addSessionContext(sessionID: string, text: string): Promis
await callOpenCode((api) => api.session.synthetic({ sessionID, text, resume: false }))
}
export async function createSessionWithContext(input: CreateSessionInput, context: string): Promise<SessionInfo> {
async function createSessionThen(
input: CreateSessionInput,
step: (session: SessionInfo) => Promise<unknown>,
): Promise<SessionInfo> {
const session = await createSession(input)
try {
await addSessionContext(session.id, context)
await step(session)
} catch (error) {
await deleteSession(session.id).catch(() => undefined)
throw error
@@ -151,6 +154,14 @@ export async function createSessionWithContext(input: CreateSessionInput, contex
return session
}
export async function createSessionWithContext(input: CreateSessionInput, context: string): Promise<SessionInfo> {
return createSessionThen(input, (session) => addSessionContext(session.id, context))
}
export async function createSessionWithPrompt(input: CreateSessionInput, text: string): Promise<SessionInfo> {
return createSessionThen(input, (session) => sendPrompt({ sessionID: session.id, text }))
}
export async function switchSessionModel(sessionID: string, model: ModelRef): Promise<void> {
await callOpenCode((api) => api.session.switchModel({ sessionID, model }))
}
+24 -3
View File
@@ -2,7 +2,7 @@ import type { Repo } from './types'
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import { saveFile } from '@/lib/download'
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity } from '@opencode-manager/shared/types'
export interface CreateRepoOptions {
repoUrl?: string
@@ -69,9 +69,18 @@ export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree>
})
}
export async function deleteRepo(id: number): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${id}`, {
export type DeleteBranchChoice = NonNullable<DeleteRepoRequest['deleteBranch']>
export interface DeleteRepoOptions {
deleteBranch?: DeleteBranchChoice
}
export async function deleteRepo(id: number, options?: DeleteRepoOptions): Promise<DeleteRepoResult> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, {
method: 'DELETE',
...(options
? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(options) }
: {}),
})
}
@@ -83,6 +92,18 @@ export async function updateRepoGitCredential(id: number, credentialId?: string)
})
}
export async function getRepoGitIdentity(id: number): Promise<RepoGitIdentity> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`)
}
export async function updateRepoGitIdentity(id: number, identityId: string | null): Promise<RepoGitIdentity> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identityId }),
})
}
export async function renameRepo(id: number, name: string | null): Promise<Repo> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, {
method: 'PATCH',
+1 -1
View File
@@ -27,7 +27,7 @@ import type { NotificationPreferences } from '@opencode-manager/shared/types'
import { saveFile } from '@/lib/download'
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity } from '@opencode-manager/shared'
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile } from '@opencode-manager/shared'
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS }
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'