feat(web,ui): per-project forced git provider and settings gating

Adds a per-project forced provider (github|gitlab|gitea) on top of the
per-project API base URL overrides: stored under gitProviders.provider in
projects/<projectId>.json, sanitized server-side, and winning over remote-host
detection both in useGitProvider and in server repo resolution
(parseGitLabRemoteUrl/parseGiteaRemoteUrl accept any host when the provider
is forced). The Projects settings page replaces the three always-visible URL
fields with a provider selector (auto-detect + the three forges) and one URL
override for the active provider. Global provider override fields on the
GitHub/GitLab/Gitea settings tabs now render only once an account is
connected, and Settings search availability matches that gating.

Also fixes the useConfigStore/useDirectoryStore circular-import TDZ in the
bundled chunk via the window-registered store handle and defers the directory
subscription to a microtask; fixes the Gitea PR merge payload (Do carries the
merge-style string enum, not a boolean + MergeMethod); and adds a documented
Gitea client live-test harness (scripts/gitea-live-test.ts + client.d.ts).
This commit is contained in:
2026-08-17 09:57:54 +00:00
parent 66edc74fac
commit 45437a4221
38 changed files with 1306 additions and 125 deletions
@@ -13,6 +13,7 @@
- `packages/web/server/lib/gitea/routes.js`: Express route registration for `/api/gitea/*` endpoints.
- `packages/web/server/lib/gitea/auth.js`: PAT auth storage, multi-account support, base URL normalization.
- `packages/web/server/lib/gitea/client.js`: raw `fetch` Gitea REST v1 client (timeout, ETag conditional GET, rate-limit cooldown, `Link`-header pagination, redirect handling).
- `packages/web/server/lib/gitea/client.d.ts`: hand-written type declaration for `client.js` (the module is plain JS); consumed by the live-test harness.
- `packages/web/server/lib/gitea/repo.js`: Gitea remote URL parsing (flat `owner/repo`) and directory-to-repo resolution.
- `packages/web/server/lib/opencode/feature-routes-runtime.js`: API route layer that calls this module (via `registerGiteaRoutes`).
- `packages/web/src/api/gitea.ts`: web client wrapper for Gitea endpoints.
@@ -48,7 +49,7 @@
- Auth storage: `~/.config/openchamber/gitea-auth.json` (override with `OPENCHAMBER_DATA_DIR`).
- Writes are atomic (tmp file + rename) and file mode is `0o600`.
- Base URL resolution: the caller-supplied `baseUrl` (normalized) is the primary source, then the effective default (configured `settings.json` `gitProviders.gitea.apiBaseUrl`, else `https://codeberg.org`). Stored entries without a usable base URL are dropped.
- Per-project overrides: a per-project `gitProviders.gitea.apiBaseUrl` override (stored under `projects/<projectId>.json`, resolved via `getEffectiveProviderApiBaseUrl('gitea', directory)` in `packages/web/server/lib/git-providers/project-config.js`) replaces the account's base URL for that project's data routes (`getGiteaClientOrNull(directory)`), and its host is accepted for directory-to-repo resolution (`resolveGiteaRepoFromDirectory`). Global routes (`auth/status`, `auth/connect`, `auth/activate`, DELETE auth, `me`, `repo/branches`) stay global.
- Per-project overrides: a per-project `gitProviders.gitea.apiBaseUrl` override (stored under `projects/<projectId>.json`, resolved via `getEffectiveProviderApiBaseUrl('gitea', directory)` in `packages/web/server/lib/git-providers/project-config.js`) replaces the account's base URL for that project's data routes (`getGiteaClientOrNull(directory)`), and its host is accepted for directory-to-repo resolution (`resolveGiteaRepoFromDirectory`). A forced `gitProviders.provider: 'gitea'` accepts any remote host for directory resolution. Global routes (`auth/status`, `auth/connect`, `auth/activate`, DELETE auth, `me`, `repo/branches`) stay global.
- Account id: `` `${host}:${username}` `` (e.g. `gitea.example.com:alice`), falling back to `token:<first8>` when the username is missing.
- Auth header on every request: `Authorization: token <pat>`.
- Gitea's `GET /user` uses `login`/`full_name`/`html_url`; `setGiteaAuth` accepts both that and the `username`/`web_url` variants.
@@ -80,7 +81,7 @@
- Commit statuses: `GET /repos/{owner}/{repo}/commits/{sha}/statuses?limit=100` (the `prs/statuses` route resolves the PR `head.sha` first, then maps statuses to `{ state, name, description, url, createdAt }` with `state` lowercased).
- PR create: `POST /repos/{owner}/{repo}/pulls` with `{ title, head, base, body? }` (body omitted when absent).
- PR update: `PATCH /repos/{owner}/{repo}/pulls/{number}` with `{ title?, body?, state? }` (undefined fields omitted; the PR number IS the issue index, so the edit-issue `state` transition applies directly).
- PR merge: `POST /repos/{owner}/{repo}/pulls/{number}/merge` with `{ Do: true, MergeMethod: 'merge' | 'squash' | 'rebase' }` (`method` defaults to `'merge'`).
- PR merge: `POST /repos/{owner}/{repo}/pulls/{number}/merge` with `{ Do: 'merge' | 'squash' | 'rebase' }` (`method` defaults to `'merge'`). `Do` is a string enum of the merge style — Gitea has no separate `MergeMethod` field.
- Issue comment write: `POST /repos/{owner}/{repo}/issues/{number}/comments` with `{ body }` (PRs are issues at the API level, so `prs/comment` uses the same endpoint with the PR number as the index).
- Issue update: `PATCH /repos/{owner}/{repo}/issues/{number}` with `{ title?, body?, state?, labels?, assignees?, milestone?, unset_milestone? }` (labels are label **names**, assignees are logins; `milestone` is resolved from a title to a milestone id and `null` sets `unset_milestone: true`).
- Pull review write: `POST /repos/{owner}/{repo}/pulls/{number}/reviews` with `{ event, body? }` (`event` is `APPROVED`/`REQUEST_CHANGES`/`COMMENT`).
@@ -131,6 +132,7 @@ Conventions mirror `github/routes.js` and `gitlab/routes.js`:
- `packages/web/src/api/gitea.ts` calls every `/api/gitea/*` endpoint and maps them to the shared types.
- `packages/ui/src/lib/api/types.ts` defines the shared `Gitea*` response types used across web, desktop, VS Code, and mobile.
- `packages/web/scripts/gitea-live-test.ts` is a live-test harness for the raw client: run with `bun run gitea:live-test` (requires `GITEA_TOKEN`; `GITEA_BASE_URL` defaults to `https://git.example.com`). It exercises every client method against a real instance, reports PASS/WARN/FAIL/SKIP per endpoint, and runs a controlled write pass (scratch issue plus a scratch-repo PR lifecycle that is deleted afterward).
## Failure handling
+63
View File
@@ -0,0 +1,63 @@
// Hand-written declaration for the plain-JS Gitea/Forgejo REST v1 client
// (client.js). Kept in sync with the client's public surface; the web package
// type-checks the gitea live-test harness which imports this module.
export interface GiteaClientPageInfo {
page: number | null;
next: string | null;
total: number | null;
hasMore: boolean;
nextUrl?: string;
}
export interface GiteaClientResponse {
status: number;
headers: Record<string, string>;
data: unknown;
page: GiteaClientPageInfo | null;
error?: string;
}
export type GiteaQuery = Record<string, string | number | boolean | null | undefined>;
export interface GiteaRequestOptions {
method?: string;
query?: GiteaQuery;
body?: unknown;
signal?: AbortSignal;
raw?: boolean;
}
export interface GiteaClient {
baseUrl: string;
request: (path: string, options?: GiteaRequestOptions) => Promise<GiteaClientResponse>;
user: () => Promise<GiteaClientResponse>;
repo: (owner: string, repo: string) => Promise<GiteaClientResponse>;
issues: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
issue: (owner: string, repo: string, number: number) => Promise<GiteaClientResponse>;
issueComments: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
createIssueComment: (owner: string, repo: string, number: number, body: string) => Promise<GiteaClientResponse>;
createIssue: (owner: string, repo: string, params: Record<string, unknown>) => Promise<GiteaClientResponse>;
updateIssue: (owner: string, repo: string, number: number, params: Record<string, unknown>) => Promise<GiteaClientResponse>;
milestones: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
repoLabels: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
pullRequests: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
pullRequest: (owner: string, repo: string, number: number) => Promise<GiteaClientResponse>;
pullRequestDiff: (owner: string, repo: string, number: number) => Promise<GiteaClientResponse>;
pullRequestFiles: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
pullRequestCommits: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
pullRequestReviews: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
createPullReview: (owner: string, repo: string, number: number, params: Record<string, unknown>) => Promise<GiteaClientResponse>;
commitStatuses: (owner: string, repo: string, sha: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
createPullRequest: (owner: string, repo: string, body: Record<string, unknown>) => Promise<GiteaClientResponse>;
updatePullRequest: (owner: string, repo: string, number: number, body: Record<string, unknown>) => Promise<GiteaClientResponse>;
mergePullRequest: (owner: string, repo: string, number: number, body: Record<string, unknown>) => Promise<GiteaClientResponse>;
branches: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
assignees: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
tags: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
}
export function createGiteaClient(options: { token: string; baseUrl: string }): GiteaClient;
export function getGiteaClientOrNull(directory?: string): GiteaClient | null;
export function isGiteaRateLimited(): boolean;
export function noteGiteaRateLimit(error: unknown): void;
+4 -4
View File
@@ -242,17 +242,17 @@ describe('pull request write methods', () => {
expect(JSON.parse(options.body)).toEqual({ title: 'Updated', body: 'Body text' });
});
test('mergePullRequest POSTs Do and MergeMethod to the merge endpoint', async () => {
test('mergePullRequest POSTs the merge style in Do to the merge endpoint', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ merged: true }));
globalThis.fetch = fetchMock;
const client = createGiteaClient({ token: 't', baseUrl: 'https://gitea.example.com' });
await client.mergePullRequest('owner', 'repo', 5, { Do: true, MergeMethod: 'squash' });
await client.mergePullRequest('owner', 'repo', 5, { Do: 'squash' });
const [url, options] = fetchMock.mock.calls[0];
expect(String(url)).toBe('https://gitea.example.com/api/v1/repos/owner/repo/pulls/5/merge');
expect(options.method).toBe('POST');
expect(JSON.parse(options.body)).toEqual({ Do: true, MergeMethod: 'squash' });
expect(JSON.parse(options.body)).toEqual({ Do: 'squash' });
});
test('write methods surface error statuses without throwing', async () => {
@@ -260,7 +260,7 @@ describe('pull request write methods', () => {
globalThis.fetch = fetchMock;
const client = createGiteaClient({ token: 't', baseUrl: 'https://gitea.example.com' });
const result = await client.mergePullRequest('owner', 'repo', 5, { Do: true, MergeMethod: 'merge' });
const result = await client.mergePullRequest('owner', 'repo', 5, { Do: 'merge' });
expect(result.status).toBe(409);
expect(result.data).toEqual({ message: 'Conflict' });
});
+6 -4
View File
@@ -1,6 +1,6 @@
import { getRemoteUrl } from '../git/index.js';
import { getGiteaAuthAccounts, normalizeBaseUrl } from './auth.js';
import { getEffectiveProviderApiBaseUrl } from '../git-providers/project-config.js';
import { getEffectiveProviderApiBaseUrl, getProjectProviderFromDirectory } from '../git-providers/project-config.js';
// When no explicit host allowlist is provided, accept any host that matches the
// base URL of a stored Gitea account. Gitea/Forgejo is self-hosted, so there is
@@ -50,7 +50,7 @@ function acceptedHosts(knownHosts) {
* When omitted, hosts from stored auth accounts are accepted. `github.com` and
* `gitlab.com` are never accepted.
*/
export const parseGiteaRemoteUrl = (raw, knownHosts) => {
export const parseGiteaRemoteUrl = (raw, knownHosts, options = {}) => {
if (typeof raw !== 'string') {
return null;
}
@@ -85,7 +85,7 @@ export const parseGiteaRemoteUrl = (raw, knownHosts) => {
if (host === 'github.com' || host === 'gitlab.com') {
return null;
}
if (!acceptedHosts(knownHosts).has(host)) {
if (!options.allowAnyHost && !acceptedHosts(knownHosts).has(host)) {
return null;
}
@@ -133,8 +133,10 @@ export async function resolveGiteaRepoFromDirectory(directory, remoteName = 'ori
// ignore a malformed override base URL
}
}
// A forced gitea provider (per-project override) accepts any remote host.
const forcedProvider = getProjectProviderFromDirectory(directory);
return {
repo: parseGiteaRemoteUrl(remoteUrl, knownHosts),
repo: parseGiteaRemoteUrl(remoteUrl, knownHosts, { allowAnyHost: forcedProvider === 'gitea' }),
remoteUrl,
};
}
@@ -22,6 +22,12 @@ vi.mock('../git-providers/project-config.js', async (importOriginal) => {
}
return actual.getEffectiveProviderApiBaseUrl(provider, directory);
}),
getProjectProviderFromDirectory: vi.fn((directory) => {
if (directory === '/forced/project') {
return 'gitea';
}
return actual.getProjectProviderFromDirectory(directory);
}),
};
});
@@ -150,4 +156,11 @@ describe('resolveGiteaRepoFromDirectory', () => {
const { repo } = await resolveGiteaRepoFromDirectory('/some/project');
expect(repo).toBeNull();
});
test('accepts any remote host when the provider is forced to gitea', async () => {
vi.mocked(getRemoteUrl).mockResolvedValue('git@gitea.internal.corp:team/app.git');
const { repo, remoteUrl } = await resolveGiteaRepoFromDirectory('/forced/project');
expect(remoteUrl).toBe('git@gitea.internal.corp:team/app.git');
expect(repo).toMatchObject({ owner: 'team', repo: 'app', host: 'gitea.internal.corp' });
});
});
+4 -1
View File
@@ -1225,7 +1225,10 @@ export function registerGiteaRoutes(app, options = {}) {
return res.status(400).json({ error: 'Unable to resolve Gitea repo from directory' });
}
const body = { Do: true, MergeMethod: method };
// Gitea's merge endpoint takes the merge style directly in `Do` (a
// string enum: merge/rebase/rebase-merge/squash/fast-forward-only/
// manually-merged). There is no separate `MergeMethod` field.
const body = { Do: method };
const resp = await withTimeout(client.mergePullRequest(owner, repo, number, body), ROUTE_TIMEOUT_MS, 'gitea pr merge');
if (resp.status === 429) {
+4 -4
View File
@@ -889,7 +889,7 @@ describe('Gitea data routes', () => {
expect(response.body).toEqual({ error: 'Pull request not found' });
});
test('pr/merge POSTs Do/MergeMethod and reports merged:true', async () => {
test('pr/merge POSTs the merge style in Do and reports merged:true', async () => {
const fetchMock = scriptedFetch([
(url, options) => {
if (matches(/\/pulls\/12\/merge$/)(url) && options.method === 'POST') {
@@ -908,10 +908,10 @@ describe('Gitea data routes', () => {
expect(response.body).toEqual({ connected: true, merged: true });
const [, options] = fetchMock.mock.calls[0];
expect(options.method).toBe('POST');
expect(JSON.parse(options.body)).toEqual({ Do: true, MergeMethod: 'merge' });
expect(JSON.parse(options.body)).toEqual({ Do: 'merge' });
});
test('pr/merge maps the method to MergeMethod', async () => {
test('pr/merge maps the method to Do', async () => {
const fetchMock = scriptedFetch([
(url, options) => {
if (matches(/\/pulls\/12\/merge$/)(url) && options.method === 'POST') {
@@ -927,7 +927,7 @@ describe('Gitea data routes', () => {
.send({ directory: '/tmp/work', number: 12, method: 'squash' });
const [, options] = fetchMock.mock.calls[0];
expect(JSON.parse(options.body)).toEqual({ Do: true, MergeMethod: 'squash' });
expect(JSON.parse(options.body)).toEqual({ Do: 'squash' });
});
test('pr/merge passes through a Gitea merge rejection as merged:false', async () => {