diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index c02e57ac..fe4a73f2 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -23,6 +23,8 @@ interface RepoRow { const REPO_GIT_CREDENTIAL_SETTING_KEY = 'gitCredentialId' +const REPO_GIT_IDENTITY_SETTING_KEY = 'gitIdentityId' + const REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY = 'sandboxGitCredentials' function rowToRepo(row: RepoRow): Repo { @@ -82,6 +84,14 @@ export function setRepoGitCredentialId(db: Database, repoId: number, credentialI setRepoSetting(db, repoId, REPO_GIT_CREDENTIAL_SETTING_KEY, credentialId) } +export function getRepoGitIdentityId(db: Database, repoId: number): string | null { + return getRepoSetting(db, repoId, REPO_GIT_IDENTITY_SETTING_KEY) +} + +export function setRepoGitIdentityId(db: Database, repoId: number, identityId: string | null): void { + setRepoSetting(db, repoId, REPO_GIT_IDENTITY_SETTING_KEY, identityId) +} + export function getRepoSandboxGitCredentials(db: Database, repoId: number): boolean | null { const value = getRepoSetting(db, repoId, REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY) if (value === null) return null diff --git a/backend/src/routes/internal/git-credentials.ts b/backend/src/routes/internal/git-credentials.ts index 53a1c470..df1185c5 100644 --- a/backend/src/routes/internal/git-credentials.ts +++ b/backend/src/routes/internal/git-credentials.ts @@ -7,7 +7,7 @@ export function createInternalGitCredentialsRoutes(db: Database) { app.get('/gh-env', (c) => { const provider = new CredentialProvider(db) - return c.json(provider.getGhCliEnv({ cwd: c.req.query('cwd') })) + return c.json(provider.getShellEnv({ cwd: c.req.query('cwd') })) }) return app diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 065af547..ff13bb32 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -18,14 +18,9 @@ import { createRepoGitRoutes } from './repo-git' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' import { ScheduleService } from '../services/schedules' -import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode' -import { canonicalPathSync } from '../utils/fs-safe' +import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode' import path from 'path' -function resolveRepo(database: Database, id: number): Repo | null { - return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null) -} - const DeleteWorkspaceRequestSchema = z.object({ directory: z.string().trim().min(1), }) @@ -150,7 +145,7 @@ app.get('/', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo: Repo | null = resolveRepo(database, id) + const repo: Repo | null = repoService.resolveRepoOrAssistant(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -270,10 +265,7 @@ app.get('/', async (c) => { const directory = parsed.data.directory const siblings = await repoService.getSiblingRepos(database, id, gitAuthService.getGitEnvironment(), openCodeClient) - const requestedDirectory = canonicalPathSync(path.resolve(directory)) - const worktree = siblings.find( - (sibling) => isWorktreeSibling(sibling) && canonicalPathSync(path.resolve(sibling.fullPath)) === requestedDirectory, - ) + const worktree = repoService.findSiblingByDirectory(siblings.filter(isWorktreeSibling), directory) if (!worktree) return c.json({ error: 'Not a deletable worktree of this repo' }, 400) try { @@ -491,7 +483,7 @@ app.get('/', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo: Repo | null = resolveRepo(database, id) + const repo: Repo | null = repoService.resolveRepoOrAssistant(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -509,7 +501,7 @@ app.get('/', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo: Repo | null = resolveRepo(database, id) + const repo: Repo | null = repoService.resolveRepoOrAssistant(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) diff --git a/backend/src/services/credential-provider.ts b/backend/src/services/credential-provider.ts index 611b34b2..3ca9141d 100644 --- a/backend/src/services/credential-provider.ts +++ b/backend/src/services/credential-provider.ts @@ -6,6 +6,7 @@ import { getSSHCredentialsForHost, createGitEnv, createGhCliEnv, + createGitIdentityEnv, findGitHubCredential, type ResolvedGitCredential, } from '../utils/git-auth' @@ -14,6 +15,7 @@ import { logger } from '../utils/logger' import { getRepoByDirectory, getRepoGitCredentialId, + getRepoGitIdentityId, getRepoSandboxGitCredentials, listRepos, } from '../db/queries' @@ -95,6 +97,21 @@ export class CredentialProvider { return this.getGhCliEnvForContext(this.resolveContext(options)) } + getShellEnv(options: CredentialResolutionOptions = {}): Record { + return { ...this.getGhCliEnv(options), ...this.getAssignedGitIdentityEnv(options) } + } + + getAssignedGitIdentityEnv(options: CredentialResolutionOptions = {}): Record { + const repo = this.resolveRepo(options) + if (!repo) return {} + + const identityId = getRepoGitIdentityId(this.database, repo.id) + if (!identityId) return {} + + const profile = this.getPreferences().gitIdentities?.find((identity) => identity.id === identityId) + return profile ? createGitIdentityEnv(profile) : {} + } + private resolveContext(options: CredentialResolutionOptions, repo = this.resolveRepo(options)): CredentialResolutionContext { const preferences = this.getPreferences() return { diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 6a926868..98499cce 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite' import type { Repo, CreateRepoInput } from '../types/repo' import { logger } from '../utils/logger' import { getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' -import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN } from '@opencode-manager/shared/utils' +import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import type { GitAuthService } from './git-auth' import { isGitHubHttpsUrl } from '../utils/git-auth' import path from 'path' @@ -18,6 +18,7 @@ import { resolveProjectId, isGitMainCheckout } from './project-id-resolver' import { listRepos } from '../db/queries' import { listActiveScheduleRunWorktreePaths } from '../db/schedules' import { SettingsService } from './settings' +import { buildAssistantRepo } from './assistant-mode' import type { OpenCodeClient } from './opencode/client' import { openCodeLocation } from '@opencode-manager/shared/opencode' import { canonicalPathSync, mkdirSafe } from '../utils/fs-safe' @@ -1168,6 +1169,26 @@ export async function resolveRepoProjectId(openCodeClient: OpenCodeClient, direc return project.id } +export function resolveRepoOrAssistant(database: Database, id: number): Repo | null { + return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null) +} + +export function findSiblingByDirectory(siblings: T[], directory: string): T | undefined { + const requestedDirectory = canonicalPathSync(path.resolve(directory)) + return siblings.find((sibling) => canonicalPathSync(path.resolve(sibling.fullPath)) === requestedDirectory) +} + +export async function resolveRepoWorkingDirectory( + repo: Repo, + directory: string | undefined, + loadSiblings: () => Promise>, +): Promise { + if (directory === undefined) return repo.fullPath + if (canonicalPathSync(path.resolve(directory)) === canonicalPathSync(path.resolve(repo.fullPath))) return repo.fullPath + + return findSiblingByDirectory(await loadSiblings(), directory)?.fullPath ?? null +} + export async function getSiblingRepos( database: Database, repoId: number, diff --git a/backend/test/routes/internal/git-credentials.test.ts b/backend/test/routes/internal/git-credentials.test.ts index 4ae326be..93e4b762 100644 --- a/backend/test/routes/internal/git-credentials.test.ts +++ b/backend/test/routes/internal/git-credentials.test.ts @@ -3,6 +3,7 @@ import { Database } from 'bun:sqlite' import { migrate } from '../../../src/db/migration-runner' import { allMigrations } from '../../../src/db/migrations' import { SettingsService } from '../../../src/services/settings' +import { createRepo, setRepoGitIdentityId } from '../../../src/db/queries' import { createInternalGitCredentialsRoutes } from '../../../src/routes/internal/git-credentials' import type { GitCredential } from '@opencode-manager/shared' @@ -37,4 +38,54 @@ describe('internal git-credentials routes', () => { expect(res.status).toBe(200) expect(await res.json()).toEqual({}) }) + + it('GET /gh-env includes the assigned identity env for a repo cwd', async () => { + settingsService.updateSettings({ + gitCredentials: [ + { name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential, + ], + gitIdentities: [{ id: 'identity-1', name: 'Alice', email: 'alice@example.com' }], + }) + const repo = createRepo(db, { + repoUrl: 'https://github.com/acme/repo.git', + localPath: 'repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + setRepoGitIdentityId(db, repo.id, 'identity-1') + + const res = await app.request(`/gh-env?cwd=${encodeURIComponent(repo.fullPath)}`) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ + GH_TOKEN: 'ghp_test_token', + GITHUB_TOKEN: 'ghp_test_token', + GIT_AUTHOR_NAME: 'Alice', + GIT_AUTHOR_EMAIL: 'alice@example.com', + GIT_COMMITTER_NAME: 'Alice', + GIT_COMMITTER_EMAIL: 'alice@example.com', + }) + }) + + it('GET /gh-env omits the identity env without an assignment', async () => { + settingsService.updateSettings({ + gitCredentials: [ + { name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential, + ], + gitIdentities: [{ id: 'identity-1', name: 'Alice', email: 'alice@example.com' }], + }) + const repo = createRepo(db, { + repoUrl: 'https://github.com/acme/repo.git', + localPath: 'repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + + const res = await app.request(`/gh-env?cwd=${encodeURIComponent(repo.fullPath)}`) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' }) + }) }) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index 5574e819..af33e242 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -32,6 +32,8 @@ vi.mock('../../src/services/repo', () => ({ createBranch: vi.fn(), deleteRepoFiles: vi.fn(), getSiblingRepos: vi.fn(), + resolveRepoOrAssistant: vi.fn(), + findSiblingByDirectory: vi.fn(), })) vi.mock('../../src/services/assistant-mode', () => ({ @@ -79,6 +81,7 @@ import type { AssistantModeStatus, Repo } from '@opencode-manager/shared/types' import type { OpenCodeApi } from '@opencode-manager/shared/opencode' import { ClientError } from '@opencode-manager/shared/opencode' import { getAssistantModeStatus, ensureAssistantMode, buildAssistantRepo } from '../../src/services/assistant-mode' +import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' const mockGitAuthService = { getGitEnvironment: vi.fn().mockReturnValue({}) @@ -118,6 +121,9 @@ describe('Repo Routes', () => { updatedAt: Date.now(), }) vi.mocked(db.getRepoGitCredentialId).mockReturnValue(null) + vi.mocked(repoService.resolveRepoOrAssistant).mockImplementation( + (_database, id) => vi.mocked(db.getRepoById)(_database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null), + ) }) describe('POST /:id/access', () => { diff --git a/backend/test/services/credential-provider.test.ts b/backend/test/services/credential-provider.test.ts index 14096f95..49abfbee 100644 --- a/backend/test/services/credential-provider.test.ts +++ b/backend/test/services/credential-provider.test.ts @@ -4,7 +4,7 @@ import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { SettingsService } from '../../src/services/settings' import { CredentialProvider } from '../../src/services/credential-provider' -import { createRepo, setRepoGitCredentialId, setRepoSandboxGitCredentials } from '../../src/db/queries' +import { createRepo, setRepoGitCredentialId, setRepoGitIdentityId, setRepoSandboxGitCredentials } from '../../src/db/queries' import { SANDBOX_MAX_FORWARDED_GIT_CONFIGS } from '../../src/services/sandbox/shell-shim' import type { GitCredential } from '@opencode-manager/shared' @@ -316,4 +316,65 @@ describe('CredentialProvider', () => { } }) }) + + describe('shell env', () => { + function createGithubRepo() { + return createRepo(db, { + repoUrl: 'https://github.com/acme/repo.git', + localPath: 'repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + } + + beforeEach(() => { + settingsService.updateSettings({ + gitCredentials: [createPatCredential('github', 'github.com', 'ghp_test_token', undefined, 'github-id')], + gitIdentities: [{ id: 'identity-1', name: 'Alice', email: 'alice@example.com' }], + }) + }) + + it('getShellEnv returns only the GH CLI env without an assigned identity', () => { + expect(provider.getShellEnv()).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' }) + }) + + it('getAssignedGitIdentityEnv returns an empty object without an assignment', () => { + const repo = createGithubRepo() + expect(provider.getAssignedGitIdentityEnv({ cwd: repo.fullPath })).toEqual({}) + }) + + it('getAssignedGitIdentityEnv returns the identity env for an assigned profile', () => { + const repo = createGithubRepo() + setRepoGitIdentityId(db, repo.id, 'identity-1') + + expect(provider.getAssignedGitIdentityEnv({ cwd: repo.fullPath })).toEqual({ + GIT_AUTHOR_NAME: 'Alice', + GIT_AUTHOR_EMAIL: 'alice@example.com', + GIT_COMMITTER_NAME: 'Alice', + GIT_COMMITTER_EMAIL: 'alice@example.com', + }) + }) + + it('getShellEnv merges the GH CLI env with the assigned identity env', () => { + const repo = createGithubRepo() + setRepoGitIdentityId(db, repo.id, 'identity-1') + + expect(provider.getShellEnv({ cwd: repo.fullPath })).toEqual({ + GH_TOKEN: 'ghp_test_token', + GITHUB_TOKEN: 'ghp_test_token', + GIT_AUTHOR_NAME: 'Alice', + GIT_AUTHOR_EMAIL: 'alice@example.com', + GIT_COMMITTER_NAME: 'Alice', + GIT_COMMITTER_EMAIL: 'alice@example.com', + }) + }) + + it('getAssignedGitIdentityEnv ignores a dangling assigned identity', () => { + const repo = createGithubRepo() + setRepoGitIdentityId(db, repo.id, 'missing-identity') + + expect(provider.getAssignedGitIdentityEnv({ cwd: repo.fullPath })).toEqual({}) + }) + }) }) diff --git a/backend/test/services/repo-working-directory.test.ts b/backend/test/services/repo-working-directory.test.ts new file mode 100644 index 00000000..ebd59137 --- /dev/null +++ b/backend/test/services/repo-working-directory.test.ts @@ -0,0 +1,98 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { findSiblingByDirectory, resolveRepoWorkingDirectory } from '../../src/services/repo' +import type { Repo } from '@opencode-manager/shared/types' + +describe('resolveRepoWorkingDirectory', () => { + let root: string + let repoPath: string + let siblingPath: string + let unrelatedPath: string + let repoLinkPath: string + let siblingLinkPath: string + + beforeAll(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-repo-working-directory-')) + repoPath = path.join(root, 'repo') + siblingPath = path.join(root, 'sibling') + unrelatedPath = path.join(root, 'unrelated') + repoLinkPath = path.join(root, 'repo-link') + siblingLinkPath = path.join(root, 'sibling-link') + + fs.mkdirSync(repoPath) + fs.mkdirSync(siblingPath) + fs.mkdirSync(unrelatedPath) + fs.symlinkSync(repoPath, repoLinkPath, 'dir') + fs.symlinkSync(siblingPath, siblingLinkPath, 'dir') + }) + + afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }) + }) + + function createRepo(): Repo { + return { fullPath: repoPath } as Repo + } + + it('returns the repo path when no directory is given', async () => { + expect(await resolveRepoWorkingDirectory(createRepo(), undefined, async () => [])).toBe(repoPath) + }) + + it('returns the repo path for the repo directory itself', async () => { + expect(await resolveRepoWorkingDirectory(createRepo(), repoPath, async () => [])).toBe(repoPath) + }) + + it('returns the repo path for a symlinked equivalent of the repo directory', async () => { + expect(await resolveRepoWorkingDirectory(createRepo(), repoLinkPath, async () => [])).toBe(repoPath) + }) + + it('returns a matching sibling path', async () => { + const siblings = [{ fullPath: siblingPath }] + expect(await resolveRepoWorkingDirectory(createRepo(), siblingPath, async () => siblings)).toBe(siblingPath) + }) + + it('matches a sibling through a symlinked directory', async () => { + const siblings = [{ fullPath: siblingPath }] + expect(await resolveRepoWorkingDirectory(createRepo(), siblingLinkPath, async () => siblings)).toBe(siblingPath) + }) + + it('returns null for an unrelated directory', async () => { + const siblings = [{ fullPath: siblingPath }] + expect(await resolveRepoWorkingDirectory(createRepo(), unrelatedPath, async () => siblings)).toBeNull() + }) +}) + +describe('findSiblingByDirectory', () => { + let root: string + let siblingPath: string + let siblingLinkPath: string + + beforeAll(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-find-sibling-')) + siblingPath = path.join(root, 'sibling') + siblingLinkPath = path.join(root, 'sibling-link') + fs.mkdirSync(siblingPath) + fs.symlinkSync(siblingPath, siblingLinkPath, 'dir') + }) + + afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }) + }) + + it('returns the sibling whose canonical path matches', () => { + const sibling = { fullPath: siblingPath, id: 1 } + expect(findSiblingByDirectory([sibling], siblingPath)).toBe(sibling) + }) + + it('matches through a symlinked directory', () => { + const sibling = { fullPath: siblingPath, id: 1 } + expect(findSiblingByDirectory([sibling], siblingLinkPath)).toBe(sibling) + }) + + it('returns undefined when no sibling matches', () => { + const sibling = { fullPath: siblingPath, id: 1 } + expect(findSiblingByDirectory([sibling], path.join(root, 'missing'))).toBeUndefined() + }) +}) diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 82864267..516347f5 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -106,6 +106,12 @@ export const GitIdentitySchema = z.object({ export type GitIdentity = z.infer; +export const GitIdentityProfileSchema = GitIdentitySchema.extend({ + id: z.string().min(1), +}); + +export type GitIdentityProfile = z.infer; + export const ServerEnvVarSchema = z.object({ key: z.string().min(1), value: z.string(), @@ -160,6 +166,7 @@ export const UserPreferencesSchema = z.object({ gitCredentials: z.array(GitCredentialSchema).optional(), defaultGitCredentialId: z.string().optional(), gitIdentity: GitIdentitySchema.optional(), + gitIdentities: z.array(GitIdentityProfileSchema).optional(), tts: TTSConfigSchema.optional(), stt: STTConfigSchema.optional(), notifications: NotificationPreferencesSchema.optional(), diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 4c9e7a31..a895fff0 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -111,7 +111,7 @@ export interface SuccessResponse { } export type { SSHHostKeyRequest, SSHHostKeyResponse, TrustedSSHHost } from '../schemas/ssh' -export type { GitCredential } from '../schemas/settings' +export type { GitCredential, GitIdentity, GitIdentityProfile } from '../schemas/settings' export type { ProviderApiConfig, ModelConfig,