Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: link and create pull requests from issues (#279)

I'm Groot 🌳513d0842a5fd
diff --git a/apps/api/src/modules/git/__tests__/integration/git-webhook.test.ts b/apps/api/src/modules/git/__tests__/integration/git-webhook.test.ts
index d4b7bb07..c46a806e 100644
--- a/apps/api/src/modules/git/__tests__/integration/git-webhook.test.ts
+++ b/apps/api/src/modules/git/__tests__/integration/git-webhook.test.ts
@@ -190,6 +190,41 @@ describe('Repository webhook', () => {
await resetDb();
});
+ it('exposes connected development repositories from an issue', async () => {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ const project = await asOwner.projects({ projectKey: 'MKT' }).get();
+ const issue = await createIssue(asOwner, project.data!.columns[0]!.id);
+
+ const response = await app.handle(
+ new Request(`http://localhost/issues/${issue.data!.id}/development/repositories`, {
+ headers: { cookie: owner.cookie },
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual([]);
+ });
+
+ it('rejects linking from a repository outside the issue project', async () => {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ const project = await asOwner.projects({ projectKey: 'MKT' }).get();
+ const issue = await createIssue(asOwner, project.data!.columns[0]!.id);
+
+ const response = await app.handle(
+ new Request(`http://localhost/issues/${issue.data!.id}/development`, {
+ method: 'POST',
+ headers: { cookie: owner.cookie, 'content-type': 'application/json' },
+ body: JSON.stringify({ repositoryId: 999, number: 1 }),
+ }),
+ );
+
+ expect(response.status).toBe(404);
+ });
+
it('closes the issue named by a closing magic word when the PR merges', async () => {
const { asOwner, webhookId, secret, columns } = await setupProject();
const issue = (await createIssue(asOwner, columns[0].id)).data!;
diff --git a/apps/api/src/modules/git/__tests__/unit/connections-provider.test.ts b/apps/api/src/modules/git/__tests__/unit/connections-provider.test.ts
index ba00d2db..b39dc066 100644
--- a/apps/api/src/modules/git/__tests__/unit/connections-provider.test.ts
+++ b/apps/api/src/modules/git/__tests__/unit/connections-provider.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from 'bun:test';
import {
bitbucketRepository,
giteaRepository,
+ githubPullRequest,
githubRepository,
+ gitlabPullRequest,
gitlabRepository,
providerErrorMessage,
} from '../../connections-provider';
@@ -106,6 +108,51 @@ describe('Git provider repository responses', () => {
}),
).toBeNull();
});
+
+ it('normalizes GitHub pull requests for manual linking', () => {
+ expect(
+ githubPullRequest({
+ number: 42,
+ title: 'Ship the feature',
+ html_url: 'https://github.com/acme/app/pull/42',
+ state: 'closed',
+ merged_at: '2026-08-30T12:00:00Z',
+ draft: false,
+ head: { ref: 'feature/ship', sha: 'abc123' },
+ base: { ref: 'main' },
+ updated_at: '2026-08-30T12:00:00Z',
+ }),
+ ).toMatchObject({
+ number: 42,
+ state: 'merged',
+ sourceBranch: 'feature/ship',
+ targetBranch: 'main',
+ headSha: 'abc123',
+ });
+ });
+
+ it('normalizes GitLab merge requests for manual linking', () => {
+ expect(
+ gitlabPullRequest({
+ iid: 17,
+ title: 'Draft: Ship the feature',
+ web_url: 'https://gitlab.com/acme/app/-/merge_requests/17',
+ state: 'opened',
+ draft: true,
+ source_branch: 'feature/ship',
+ target_branch: 'develop',
+ sha: 'def456',
+ updated_at: '2026-08-30T12:00:00Z',
+ }),
+ ).toMatchObject({
+ number: 17,
+ state: 'open',
+ draft: true,
+ sourceBranch: 'feature/ship',
+ targetBranch: 'develop',
+ headSha: 'def456',
+ });
+ });
});
describe('Git provider errors', () => {
diff --git a/apps/api/src/modules/git/connections-provider.ts b/apps/api/src/modules/git/connections-provider.ts
index ba265451..97c382f8 100644
--- a/apps/api/src/modules/git/connections-provider.ts
+++ b/apps/api/src/modules/git/connections-provider.ts
@@ -1,5 +1,7 @@
import { HttpError } from '#shared/lib';
import { assertPublicHttpUrl } from '#shared/net';
+import { pipelineStatus } from './providers';
+import type { PipelineEvent, PullRequestEvent, PullRequestState } from './providers';
export type GitProvider = 'github' | 'gitlab' | 'gitea' | 'forgejo' | 'bitbucket';
@@ -8,6 +10,7 @@ export interface ProviderRepository {
fullName: string;
webUrl: string;
private: boolean;
+ defaultBranch?: string | null;
}
export interface ProviderRepositoryPage {
@@ -21,6 +24,43 @@ export interface ProviderConnectionInput {
token: string;
}
+export interface ProviderPullRequest {
+ number: number;
+ title: string;
+ url: string | null;
+ state: PullRequestState;
+ draft: boolean;
+ sourceBranch: string | null;
+ targetBranch: string;
+ headSha: string | null;
+ updatedAt: string;
+}
+
+export interface ProviderPullRequestPage {
+ pullRequests: ProviderPullRequest[];
+ nextPage: number | null;
+}
+
+export interface ProviderPullRequestDetails {
+ pullRequest: ProviderPullRequest;
+ event: PullRequestEvent;
+ run: PipelineEvent | null;
+}
+
+export interface ProviderBranchPage {
+ branches: string[];
+ defaultBranch: string | null;
+ nextPage: number | null;
+}
+
+export interface CreateProviderPullRequestInput {
+ sourceBranch: string;
+ targetBranch: string;
+ title: string;
+ description: string;
+ draft: boolean;
+}
+
function record(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
@@ -203,7 +243,14 @@ export function githubRepository(value: unknown): ProviderRepository | null {
const permissions = record(row?.permissions);
if ((typeof id !== 'number' && typeof id !== 'string') || !fullName || !webUrl) return null;
if (!bool(permissions?.admin)) return null;
- return { externalId: String(id), fullName, webUrl, private: bool(row?.private) };
+ const defaultBranch = text(row?.default_branch);
+ return {
+ externalId: String(id),
+ fullName,
+ webUrl,
+ private: bool(row?.private),
+ ...(defaultBranch ? { defaultBranch } : {}),
+ };
}
export function gitlabRepository(value: unknown): ProviderRepository | null {
@@ -212,7 +259,14 @@ export function gitlabRepository(value: unknown): ProviderRepository | null {
const fullName = text(row?.path_with_namespace);
const webUrl = httpUrl(row?.web_url);
if ((typeof id !== 'number' && typeof id !== 'string') || !fullName || !webUrl) return null;
- return { externalId: String(id), fullName, webUrl, private: row?.visibility !== 'public' };
+ const defaultBranch = text(row?.default_branch);
+ return {
+ externalId: String(id),
+ fullName,
+ webUrl,
+ private: row?.visibility !== 'public',
+ ...(defaultBranch ? { defaultBranch } : {}),
+ };
}
export function giteaRepository(value: unknown): ProviderRepository | null {
@@ -377,6 +431,296 @@ function bitbucketRepoPath(fullName: string): string {
return `/repositories/${parts.map(encodeURIComponent).join('/')}`;
}
+function isoText(value: unknown): string | null {
+ const raw = text(value);
+ if (!raw || Number.isNaN(Date.parse(raw))) return null;
+ return new Date(raw).toISOString();
+}
+
+export function githubPullRequest(value: unknown): ProviderPullRequest | null {
+ const row = record(value);
+ const number = row?.number;
+ const title = text(row?.title);
+ const targetBranch = text(record(row?.base)?.ref);
+ const stateValue = text(row?.state);
+ const updatedAt = isoText(row?.updated_at);
+ if (typeof number !== 'number' || !title || !targetBranch || !stateValue || !updatedAt)
+ return null;
+ return {
+ number,
+ title,
+ url: httpUrl(row?.html_url),
+ state: text(row?.merged_at) ? 'merged' : stateValue === 'closed' ? 'closed' : 'open',
+ draft: bool(row?.draft),
+ sourceBranch: text(record(row?.head)?.ref),
+ targetBranch,
+ headSha: text(record(row?.head)?.sha),
+ updatedAt,
+ };
+}
+
+export function gitlabPullRequest(value: unknown): ProviderPullRequest | null {
+ const row = record(value);
+ const number = row?.iid;
+ const title = text(row?.title);
+ const targetBranch = text(row?.target_branch);
+ const stateValue = text(row?.state);
+ const updatedAt = isoText(row?.updated_at);
+ if (typeof number !== 'number' || !title || !targetBranch || !stateValue || !updatedAt)
+ return null;
+ return {
+ number,
+ title,
+ url: httpUrl(row?.web_url),
+ state: stateValue === 'merged' ? 'merged' : stateValue === 'closed' ? 'closed' : 'open',
+ draft: bool(row?.draft) || bool(row?.work_in_progress),
+ sourceBranch: text(row?.source_branch),
+ targetBranch,
+ headSha: text(row?.sha) ?? text(record(row?.diff_refs)?.head_sha),
+ updatedAt,
+ };
+}
+
+function pullRequestEvent(
+ provider: GitProvider,
+ repository: ProviderRepository,
+ row: Record<string, unknown>,
+ pullRequest: ProviderPullRequest,
+): PullRequestEvent {
+ return {
+ kind: 'pull_request',
+ action:
+ pullRequest.state === 'merged'
+ ? 'merged'
+ : pullRequest.state === 'closed'
+ ? 'closed'
+ : 'opened',
+ number: pullRequest.number,
+ title: pullRequest.title,
+ body: text(provider === 'gitlab' ? row.description : row.body) ?? '',
+ url: pullRequest.url,
+ repo: repository.fullName,
+ sourceBranch: pullRequest.sourceBranch,
+ targetBranch: pullRequest.targetBranch,
+ headSha: pullRequest.headSha,
+ defaultBranch: repository.defaultBranch ?? null,
+ draft: pullRequest.draft,
+ };
+}
+
+function gitlabPipeline(
+ value: unknown,
+ repository: ProviderRepository,
+ pullRequest: ProviderPullRequest,
+): PipelineEvent | null {
+ const row = record(value);
+ const id = row?.id;
+ const status = pipelineStatus(text(row?.status) ?? undefined);
+ const headSha = text(row?.sha) ?? pullRequest.headSha;
+ if ((typeof id !== 'number' && typeof id !== 'string') || !status || !headSha) return null;
+ return {
+ kind: 'pipeline',
+ repo: repository.fullName,
+ pullRequestNumber: pullRequest.number,
+ headSha,
+ status,
+ url: httpUrl(row?.web_url),
+ };
+}
+
+function githubWorkflowRun(
+ value: unknown,
+ repository: ProviderRepository,
+ pullRequest: ProviderPullRequest,
+): PipelineEvent | null {
+ const row = record(value);
+ const id = row?.id;
+ const status = pipelineStatus(text(row?.conclusion) ?? text(row?.status) ?? undefined);
+ const headSha = text(row?.head_sha);
+ if ((typeof id !== 'number' && typeof id !== 'string') || !status || !headSha) return null;
+ return {
+ kind: 'pipeline',
+ repo: repository.fullName,
+ pullRequestNumber: pullRequest.number,
+ headSha,
+ status,
+ url: httpUrl(row?.html_url),
+ };
+}
+
+function ensureDevelopmentProvider(provider: GitProvider): asserts provider is 'github' | 'gitlab' {
+ if (provider !== 'github' && provider !== 'gitlab')
+ throw new HttpError(400, 'Creating and linking pull requests supports GitHub and GitLab');
+}
+
+export async function listProviderPullRequests(
+ input: ProviderConnectionInput,
+ repository: ProviderRepository,
+ state: 'open' | 'all',
+ page: number,
+): Promise<ProviderPullRequestPage> {
+ ensureDevelopmentProvider(input.provider);
+ const perPage = 50;
+ const params = new URLSearchParams({
+ page: String(page),
+ per_page: String(perPage),
+ });
+ if (input.provider === 'github') {
+ params.set('state', state);
+ params.set('sort', 'updated');
+ params.set('direction', 'desc');
+ } else {
+ params.set('scope', 'all');
+ params.set('state', state === 'open' ? 'opened' : 'all');
+ params.set('order_by', 'updated_at');
+ params.set('sort', 'desc');
+ }
+ const path =
+ input.provider === 'github'
+ ? `${githubRepoPath(repository.fullName)}/pulls?${params}`
+ : `/projects/${encodeURIComponent(repository.externalId)}/merge_requests?${params}`;
+ const response = await providerRequest(input, path);
+ const body: unknown = await response.json();
+ if (!Array.isArray(body))
+ throw new HttpError(502, `${input.provider} returned an invalid pull request list`);
+ const normalize = input.provider === 'github' ? githubPullRequest : gitlabPullRequest;
+ const pullRequests = body
+ .map(normalize)
+ .filter((pullRequest): pullRequest is ProviderPullRequest => pullRequest !== null);
+ const providerNext = response.headers.get('x-next-page');
+ return {
+ pullRequests,
+ nextPage: providerNext
+ ? Number(providerNext) || null
+ : body.length === perPage
+ ? page + 1
+ : null,
+ };
+}
+
+export async function getProviderPullRequest(
+ input: ProviderConnectionInput,
+ repository: ProviderRepository,
+ number: number,
+): Promise<ProviderPullRequestDetails> {
+ ensureDevelopmentProvider(input.provider);
+ const currentRepository = await getProviderRepository(input, repository.externalId);
+ const path =
+ input.provider === 'github'
+ ? `${githubRepoPath(repository.fullName)}/pulls/${number}`
+ : `/projects/${encodeURIComponent(repository.externalId)}/merge_requests/${number}`;
+ const response = await providerRequest(input, path);
+ const body = record(await response.json());
+ if (!body) throw new HttpError(502, `${input.provider} returned an invalid pull request`);
+ const pullRequest =
+ input.provider === 'github' ? githubPullRequest(body) : gitlabPullRequest(body);
+ if (!pullRequest) throw new HttpError(502, `${input.provider} returned an invalid pull request`);
+
+ let run: PipelineEvent | null = null;
+ if (input.provider === 'gitlab') {
+ run = gitlabPipeline(body.head_pipeline, currentRepository, pullRequest);
+ } else if (pullRequest.headSha) {
+ try {
+ const params = new URLSearchParams({ head_sha: pullRequest.headSha, per_page: '1' });
+ const runsResponse = await providerRequest(
+ input,
+ `${githubRepoPath(repository.fullName)}/actions/runs?${params}`,
+ );
+ const runs = record(await runsResponse.json())?.workflow_runs;
+ if (Array.isArray(runs)) run = githubWorkflowRun(runs[0], currentRepository, pullRequest);
+ } catch {
+ run = null;
+ }
+ }
+ return {
+ pullRequest,
+ event: pullRequestEvent(input.provider, currentRepository, body, pullRequest),
+ run,
+ };
+}
+
+export async function listProviderBranches(
+ input: ProviderConnectionInput,
+ repository: ProviderRepository,
+ page: number,
+): Promise<ProviderBranchPage> {
+ ensureDevelopmentProvider(input.provider);
+ const perPage = 100;
+ const currentRepository = await getProviderRepository(input, repository.externalId);
+ const params = new URLSearchParams({ page: String(page), per_page: String(perPage) });
+ const path =
+ input.provider === 'github'
+ ? `${githubRepoPath(repository.fullName)}/branches?${params}`
+ : `/projects/${encodeURIComponent(repository.externalId)}/repository/branches?${params}`;
+ const response = await providerRequest(input, path);
+ const body: unknown = await response.json();
+ if (!Array.isArray(body))
+ throw new HttpError(502, `${input.provider} returned an invalid branch list`);
+ const branches = body
+ .map((item) => text(record(item)?.name))
+ .filter((name): name is string => name !== null);
+ const providerNext = response.headers.get('x-next-page');
+ return {
+ branches,
+ defaultBranch: currentRepository.defaultBranch ?? null,
+ nextPage: providerNext
+ ? Number(providerNext) || null
+ : body.length === perPage
+ ? page + 1
+ : null,
+ };
+}
+
+export async function createProviderPullRequest(
+ input: ProviderConnectionInput,
+ repository: ProviderRepository,
+ values: CreateProviderPullRequestInput,
+): Promise<ProviderPullRequestDetails> {
+ ensureDevelopmentProvider(input.provider);
+ const path =
+ input.provider === 'github'
+ ? `${githubRepoPath(repository.fullName)}/pulls`
+ : `/projects/${encodeURIComponent(repository.externalId)}/merge_requests`;
+ const title =
+ input.provider === 'gitlab' && values.draft && !/^(draft:|wip:)/i.test(values.title)
+ ? `Draft: ${values.title}`
+ : values.title;
+ const body =
+ input.provider === 'github'
+ ? {
+ title,
+ body: values.description,
+ head: values.sourceBranch,
+ base: values.targetBranch,
+ draft: values.draft,
+ maintainer_can_modify: true,
+ }
+ : {
+ title,
+ description: values.description,
+ source_branch: values.sourceBranch,
+ target_branch: values.targetBranch,
+ allow_collaboration: true,
+ };
+ const response = await providerRequest(input, path, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ });
+ const created = record(await response.json());
+ if (!created) throw new HttpError(502, `${input.provider} returned an invalid pull request`);
+ const pullRequest =
+ input.provider === 'github' ? githubPullRequest(created) : gitlabPullRequest(created);
+ if (!pullRequest) throw new HttpError(502, `${input.provider} returned an invalid pull request`);
+ return {
+ pullRequest,
+ event: pullRequestEvent(input.provider, repository, created, pullRequest),
+ run:
+ input.provider === 'gitlab'
+ ? gitlabPipeline(created.head_pipeline, repository, pullRequest)
+ : null,
+ };
+}
+
export async function installProviderWebhook(
input: ProviderConnectionInput,
repository: ProviderRepository,
diff --git a/apps/api/src/modules/git/connections-service.ts b/apps/api/src/modules/git/connections-service.ts
index c83fec98..a944b07a 100644
--- a/apps/api/src/modules/git/connections-service.ts
+++ b/apps/api/src/modules/git/connections-service.ts
@@ -3,15 +3,24 @@ import { decryptSecret, encryptSecret } from '@repo/crypto';
import { and, asc, eq, inArray } from 'drizzle-orm';
import { HttpError, iso } from '#shared/lib';
import {
+ createProviderPullRequest,
deleteProviderWebhook,
createPullRequestComment,
getProviderAccount,
+ getProviderPullRequest,
getProviderRepository,
installProviderWebhook,
+ listProviderBranches,
+ listProviderPullRequests,
listProviderRepositories,
normalizeProviderBaseUrl,
+ type CreateProviderPullRequestInput,
type GitProvider,
+ type ProviderBranchPage,
type ProviderConnectionInput,
+ type ProviderPullRequestDetails,
+ type ProviderPullRequestPage,
+ type ProviderRepository,
} from './connections-provider';
import { getOrCreateGitSettings, type GitSettings } from './service';
@@ -34,6 +43,13 @@ export interface GitManagedRepositoryDto {
lastError: string | null;
}
+export interface DevelopmentRepositoryDto {
+ id: number;
+ provider: 'github' | 'gitlab';
+ fullName: string;
+ webUrl: string;
+}
+
interface ConnectionSecret {
provider: GitProvider;
baseUrl: string;
@@ -60,6 +76,126 @@ function mapRepository(row: {
return { ...row, status: row.status === 'error' ? 'error' : 'connected' };
}
+interface ManagedDevelopmentRepository {
+ input: ProviderConnectionInput & { provider: 'github' | 'gitlab' };
+ repository: ProviderRepository;
+}
+
+async function managedDevelopmentRepository(
+ projectId: number,
+ repositoryId: number,
+): Promise<ManagedDevelopmentRepository> {
+ const [row] = await db
+ .select({
+ provider: gitProviderConnection.provider,
+ baseUrl: gitProviderConnection.baseUrl,
+ ciphertext: gitProviderConnection.ciphertext,
+ iv: gitProviderConnection.iv,
+ authTag: gitProviderConnection.authTag,
+ externalId: gitManagedRepository.externalId,
+ fullName: gitManagedRepository.fullName,
+ webUrl: gitManagedRepository.webUrl,
+ })
+ .from(gitManagedRepository)
+ .innerJoin(
+ gitProviderConnection,
+ eq(gitManagedRepository.connectionId, gitProviderConnection.id),
+ )
+ .where(
+ and(
+ eq(gitManagedRepository.id, repositoryId),
+ eq(gitProviderConnection.projectId, projectId),
+ eq(gitManagedRepository.status, 'connected'),
+ ),
+ )
+ .limit(1);
+ if (!row) throw new HttpError(404, 'Managed repository not found');
+ if (row.provider !== 'github' && row.provider !== 'gitlab')
+ throw new HttpError(400, 'Creating and linking pull requests supports GitHub and GitLab');
+ return {
+ input: { provider: row.provider, baseUrl: row.baseUrl, token: decryptSecret(row) },
+ repository: {
+ externalId: row.externalId,
+ fullName: row.fullName,
+ webUrl: row.webUrl,
+ private: false,
+ },
+ };
+}
+
+export async function listDevelopmentRepositories(
+ projectId: number,
+): Promise<DevelopmentRepositoryDto[]> {
+ const rows = await db
+ .select({
+ id: gitManagedRepository.id,
+ provider: gitProviderConnection.provider,
+ fullName: gitManagedRepository.fullName,
+ webUrl: gitManagedRepository.webUrl,
+ })
+ .from(gitManagedRepository)
+ .innerJoin(
+ gitProviderConnection,
+ eq(gitManagedRepository.connectionId, gitProviderConnection.id),
+ )
+ .where(
+ and(
+ eq(gitProviderConnection.projectId, projectId),
+ eq(gitManagedRepository.status, 'connected'),
+ inArray(gitProviderConnection.provider, ['github', 'gitlab']),
+ ),
+ )
+ .orderBy(asc(gitProviderConnection.provider), asc(gitManagedRepository.fullName));
+ return rows.map((row) => ({ ...row, provider: row.provider as 'github' | 'gitlab' }));
+}
+
+export async function listManagedPullRequests(
+ projectId: number,
+ repositoryId: number,
+ state: 'open' | 'all',
+ page: number,
+): Promise<{ provider: 'github' | 'gitlab'; repository: string; page: ProviderPullRequestPage }> {
+ const managed = await managedDevelopmentRepository(projectId, repositoryId);
+ return {
+ provider: managed.input.provider,
+ repository: managed.repository.fullName,
+ page: await listProviderPullRequests(managed.input, managed.repository, state, page),
+ };
+}
+
+export async function getManagedPullRequest(
+ projectId: number,
+ repositoryId: number,
+ number: number,
+): Promise<{ provider: 'github' | 'gitlab'; details: ProviderPullRequestDetails }> {
+ const managed = await managedDevelopmentRepository(projectId, repositoryId);
+ return {
+ provider: managed.input.provider,
+ details: await getProviderPullRequest(managed.input, managed.repository, number),
+ };
+}
+
+export async function listManagedBranches(
+ projectId: number,
+ repositoryId: number,
+ page: number,
+): Promise<ProviderBranchPage> {
+ const managed = await managedDevelopmentRepository(projectId, repositoryId);
+ return listProviderBranches(managed.input, managed.repository, page);
+}
+
+export async function createManagedPullRequest(
+ projectId: number,
+ repositoryId: number,
+ input: CreateProviderPullRequestInput,
+): Promise<{ provider: 'github' | 'gitlab'; details: ProviderPullRequestDetails }> {
+ const managed = await managedDevelopmentRepository(projectId, repositoryId);
+ return {
+ provider: managed.input.provider,
+ details: await createProviderPullRequest(managed.input, managed.repository, input),
+ };
+}
+
async function repositoriesByConnection(
connectionIds: number[],
): Promise<Map<number, GitManagedRepositoryDto[]>> {
diff --git a/apps/api/src/modules/git/development.ts b/apps/api/src/modules/git/development.ts
index 2021bb46..dd6dd470 100644
--- a/apps/api/src/modules/git/development.ts
+++ b/apps/api/src/modules/git/development.ts
@@ -1,6 +1,16 @@
import { db, issue, issueDevelopmentCheck, issueDevelopmentLink } from '@repo/db';
import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';
-import { iso } from '#shared/lib';
+import { HttpError, iso } from '#shared/lib';
+import {
+ createManagedPullRequest,
+ getManagedPullRequest,
+ listManagedPullRequests,
+} from './connections-service';
+import type {
+ CreateProviderPullRequestInput,
+ ProviderPullRequest,
+ ProviderPullRequestDetails,
+} from './connections-provider';
import type {
BranchEvent,
CheckEvent,
@@ -39,6 +49,15 @@ export interface DevelopmentLink {
updatedAt: string;
}
+export interface LinkablePullRequest extends ProviderPullRequest {
+ linked: boolean;
+}
+
+export interface LinkablePullRequestPage {
+ pullRequests: LinkablePullRequest[];
+ nextPage: number | null;
+}
+
function pullRequestState(event: PullRequestEvent): PullRequestState {
if (event.action === 'merged') return 'merged';
if (event.action === 'closed') return 'closed';
@@ -103,6 +122,79 @@ export async function listIssueDevelopmentLinks(issueId: number): Promise<Develo
});
}
+export async function listLinkablePullRequests(
+ projectId: number,
+ issueId: number,
+ repositoryId: number,
+ state: 'open' | 'all',
+ page: number,
+): Promise<LinkablePullRequestPage> {
+ const result = await listManagedPullRequests(projectId, repositoryId, state, page);
+ const linked = result.page.pullRequests.length
+ ? await db
+ .select({ number: issueDevelopmentLink.number })
+ .from(issueDevelopmentLink)
+ .where(
+ and(
+ eq(issueDevelopmentLink.issueId, issueId),
+ eq(issueDevelopmentLink.provider, result.provider),
+ eq(issueDevelopmentLink.repository, result.repository),
+ inArray(
+ issueDevelopmentLink.number,
+ result.page.pullRequests.map((pullRequest) => pullRequest.number),
+ ),
+ ),
+ )
+ : [];
+ const linkedNumbers = new Set(linked.map((item) => item.number));
+ return {
+ pullRequests: result.page.pullRequests.map((pullRequest) => ({
+ ...pullRequest,
+ linked: linkedNumbers.has(pullRequest.number),
+ })),
+ nextPage: result.page.nextPage,
+ };
+}
+
+async function storePullRequestLink(
+ projectId: number,
+ issueId: number,
+ provider: 'github' | 'gitlab',
+ details: ProviderPullRequestDetails,
+): Promise<{ link: DevelopmentLink; created: boolean }> {
+ const createdIssueIds = await upsertPullRequestLinks([issueId], provider, details.event);
+ if (details.run) await updatePipelineLinks(projectId, provider, details.run);
+ const links = await listIssueDevelopmentLinks(issueId);
+ const link = links.find(
+ (item) =>
+ item.provider === provider &&
+ item.repository === details.event.repo &&
+ item.number === details.event.number,
+ );
+ if (!link) throw new HttpError(500, 'Development link was not stored');
+ return { link, created: createdIssueIds.includes(issueId) };
+}
+
+export async function linkExistingPullRequest(
+ projectId: number,
+ issueId: number,
+ repositoryId: number,
+ number: number,
+): Promise<{ link: DevelopmentLink; created: boolean }> {
+ const result = await getManagedPullRequest(projectId, repositoryId, number);
+ return storePullRequestLink(projectId, issueId, result.provider, result.details);
+}
+
+export async function createAndLinkPullRequest(
+ projectId: number,
+ issueId: number,
+ repositoryId: number,
+ input: CreateProviderPullRequestInput,
+): Promise<{ link: DevelopmentLink; created: boolean }> {
+ const result = await createManagedPullRequest(projectId, repositoryId, input);
+ return storePullRequestLink(projectId, issueId, result.provider, result.details);
+}
+
export async function hasOpenDevelopmentLinks(issueId: number): Promise<boolean> {
const [link] = await db
.select({ id: issueDevelopmentLink.id })
diff --git a/apps/api/src/modules/git/providers.ts b/apps/api/src/modules/git/providers.ts
index 063d9c98..36aedd48 100644
--- a/apps/api/src/modules/git/providers.ts
+++ b/apps/api/src/modules/git/providers.ts
@@ -144,7 +144,7 @@ function githubRepo(payload: unknown): string | undefined {
return (payload as GithubPayload).repository?.full_name;
}
-function pipelineStatus(status: string | undefined): PipelineStatus | null {
+export function pipelineStatus(status: string | undefined): PipelineStatus | null {
const value = status;
if (!value) return null;
if (value === 'success' || value === 'passed') return 'success';
diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.ts
index ccde0c8c..12f8c260 100644
--- a/apps/api/src/modules/issues/index.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -32,6 +32,8 @@ import {
listFeedRange,
listGroupedFeed,
createComment,
+ recordActivity,
+ textSide,
type FeedCursor,
} from './activity';
import { listStatusTimeline } from './status-history';
@@ -54,7 +56,15 @@ import {
updateWorklog,
} from './worklogs';
import { listIssueCycles } from './cycle-history';
-import { listIssueDevelopmentLinks, removeIssueDevelopmentLink } from '#modules/git/development';
+import {
+ createAndLinkPullRequest,
+ linkExistingPullRequest,
+ listLinkablePullRequests,
+ listIssueDevelopmentLinks,
+ removeIssueDevelopmentLink,
+} from '#modules/git/development';
+import { listDevelopmentRepositories, listManagedBranches } from '#modules/git/connections-service';
+import { DevelopmentLinkResponse } from '#modules/git/model';
import {
createChecklist,
createChecklistItem,
@@ -72,6 +82,13 @@ import {
import {
issueParams,
issueDevelopmentLinkParams,
+ issueDevelopmentRepositoryParams,
+ issueDevelopmentListQuery,
+ linkIssueDevelopmentBody,
+ createIssuePullRequestBody,
+ DevelopmentRepositoryResponse,
+ LinkablePullRequestPageResponse,
+ DevelopmentBranchPageResponse,
IssueResponse,
IssueLinkResponse,
IssueWatcherResponse,
@@ -168,6 +185,9 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
workItem: entityGuard('work_items', 'Issue not found', (p) =>
getIssueProjectId(Number(p.issueId)),
),
+ developmentIntegration: entityGuard('integrations', 'Issue not found', (p) =>
+ getIssueProjectId(Number(p.issueId)),
+ ),
checklist: entityGuard('work_items', 'Checklist not found', async (p) => {
const issueId = await getChecklistIssueId(Number(p.checklistId));
return issueId == null ? null : getIssueProjectId(issueId);
@@ -500,6 +520,140 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
+ .get(
+ '/issues/:issueId/development/repositories',
+ async ({ projectId }) => listDevelopmentRepositories(projectId),
+ {
+ params: issueParams,
+ developmentIntegration: 'edit',
+ response: { 200: t.Array(DevelopmentRepositoryResponse), ...accessErrors },
+ detail: {
+ summary: 'List repositories available to an issue',
+ description:
+ 'List connected GitHub and GitLab repositories that can link development work.',
+ },
+ },
+ )
+
+ .get(
+ '/issues/:issueId/development/repositories/:repositoryId/pull-requests',
+ async ({ params, query, projectId }) =>
+ listLinkablePullRequests(
+ projectId,
+ params.issueId,
+ params.repositoryId,
+ query.state ?? 'open',
+ query.page ?? 1,
+ ),
+ {
+ params: issueDevelopmentRepositoryParams,
+ query: issueDevelopmentListQuery,
+ developmentIntegration: 'edit',
+ response: { 200: LinkablePullRequestPageResponse, ...commonErrors },
+ detail: {
+ summary: 'List pull requests available to an issue',
+ description: 'List current pull requests or merge requests from a connected repository.',
+ },
+ },
+ )
+
+ .get(
+ '/issues/:issueId/development/repositories/:repositoryId/branches',
+ async ({ params, query, projectId }) =>
+ listManagedBranches(projectId, params.repositoryId, query.page ?? 1),
+ {
+ params: issueDevelopmentRepositoryParams,
+ query: issueDevelopmentListQuery,
+ developmentIntegration: 'edit',
+ response: { 200: DevelopmentBranchPageResponse, ...commonErrors },
+ detail: {
+ summary: 'List repository branches available to an issue',
+ description: 'List source and target branches for creating a pull request.',
+ },
+ },
+ )
+
+ .post(
+ '/issues/:issueId/development',
+ async ({ params, body, projectId, user, set }) => {
+ const result = await linkExistingPullRequest(
+ projectId,
+ params.issueId,
+ body.repositoryId,
+ body.number,
+ );
+ if (result.created) {
+ if (result.link.number == null)
+ throw new HttpError(500, 'Linked pull request has no number');
+ await recordActivity(
+ params.issueId,
+ [
+ {
+ action: 'git_pr',
+ subject: textSide(result.link.state === 'merged' ? 'merged' : 'opened'),
+ from: {
+ value: `${result.link.repository}#${result.link.number}`,
+ repo: result.link.repository,
+ number: result.link.number,
+ },
+ to: textSide(result.link.url),
+ },
+ ],
+ requireUser(user).id,
+ );
+ }
+ set.status = result.created ? 201 : 200;
+ return result.link;
+ },
+ {
+ params: issueParams,
+ body: linkIssueDevelopmentBody,
+ developmentIntegration: 'edit',
+ response: {
+ 200: DevelopmentLinkResponse,
+ 201: DevelopmentLinkResponse,
+ ...commonErrors,
+ },
+ detail: {
+ summary: 'Link an existing pull request',
+ description: 'Link a current pull request or merge request from a connected repository.',
+ },
+ },
+ )
+
+ .post(
+ '/issues/:issueId/development/pull-requests',
+ async ({ params, body, projectId, set }) => {
+ const sourceBranch = body.sourceBranch.trim();
+ const targetBranch = body.targetBranch.trim();
+ const title = body.title.trim();
+ if (!sourceBranch || !targetBranch || !title)
+ throw new HttpError(400, 'Branches and title are required');
+ if (sourceBranch === targetBranch)
+ throw new HttpError(400, 'Source and target branches must be different');
+ const result = await createAndLinkPullRequest(projectId, params.issueId, body.repositoryId, {
+ sourceBranch,
+ targetBranch,
+ title,
+ description: body.description,
+ draft: body.draft,
+ });
+ set.status = 201;
+ return result.link;
+ },
+ {
+ params: issueParams,
+ body: createIssuePullRequestBody,
+ developmentIntegration: 'edit',
+ response: { 201: DevelopmentLinkResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Create a pull request for an issue',
+ description:
+ 'Create a GitHub pull request or GitLab merge request from an existing branch.',
+ },
+ },
+ )
+
.delete(
'/issues/:issueId/development/:linkId',
async ({ params }) => {
diff --git a/apps/api/src/modules/issues/model.ts b/apps/api/src/modules/issues/model.ts
index 14af667b..259fd58b 100644
--- a/apps/api/src/modules/issues/model.ts
+++ b/apps/api/src/modules/issues/model.ts
@@ -10,6 +10,60 @@ export const issueDevelopmentLinkParams = t.Object({
issueId: t.Numeric(),
linkId: t.Numeric(),
});
+export const issueDevelopmentRepositoryParams = t.Object({
+ issueId: t.Numeric(),
+ repositoryId: t.Numeric(),
+});
+
+export const issueDevelopmentListQuery = t.Object({
+ page: t.Optional(t.Numeric({ minimum: 1 })),
+ state: t.Optional(t.Union([t.Literal('open'), t.Literal('all')])),
+});
+
+export const linkIssueDevelopmentBody = t.Object({
+ repositoryId: t.Integer({ minimum: 1 }),
+ number: t.Integer({ minimum: 1 }),
+});
+
+export const createIssuePullRequestBody = t.Object({
+ repositoryId: t.Integer({ minimum: 1 }),
+ sourceBranch: t.String({ minLength: 1, maxLength: 500 }),
+ targetBranch: t.String({ minLength: 1, maxLength: 500 }),
+ title: t.String({ minLength: 1, maxLength: 500 }),
+ description: t.String({ maxLength: 50_000 }),
+ draft: t.Boolean(),
+});
+
+export const DevelopmentRepositoryResponse = t.Object({
+ id: t.Number(),
+ provider: t.Union([t.Literal('github'), t.Literal('gitlab')]),
+ fullName: t.String(),
+ webUrl: t.String(),
+});
+
+export const LinkablePullRequestResponse = t.Object({
+ number: t.Number(),
+ title: t.String(),
+ url: t.Nullable(t.String()),
+ state: t.Union([t.Literal('open'), t.Literal('merged'), t.Literal('closed')]),
+ draft: t.Boolean(),
+ sourceBranch: t.Nullable(t.String()),
+ targetBranch: t.String(),
+ headSha: t.Nullable(t.String()),
+ updatedAt: t.String(),
+ linked: t.Boolean(),
+});
+
+export const LinkablePullRequestPageResponse = t.Object({
+ pullRequests: t.Array(LinkablePullRequestResponse),
+ nextPage: t.Nullable(t.Number()),
+});
+
+export const DevelopmentBranchPageResponse = t.Object({
+ branches: t.Array(t.String()),
+ defaultBranch: t.Nullable(t.String()),
+ nextPage: t.Nullable(t.Number()),
+});
// --- Response DTO schemas (mirror the service interfaces the handlers return) -----
diff --git a/apps/web/messages/ar/issue.json b/apps/web/messages/ar/issue.json
index 720ea725..ed2bbdb9 100644
--- a/apps/web/messages/ar/issue.json
+++ b/apps/web/messages/ar/issue.json
@@ -328,6 +328,44 @@
"title": "التطوير",
"unlink": "إلغاء ربط عنصر التطوير",
"branch": "فرع",
+ "add": "إضافة",
+ "empty": "اربط طلب سحب موجودًا أو أنشئ طلبًا من فرع",
+ "linkExisting": "ربط طلب موجود",
+ "linkExistingDescription": "اختر طلب سحب أو دمج من مستودع متصل.",
+ "createPullRequest": "إنشاء طلب سحب",
+ "createPullRequestDescription": "أنشئ طلب سحب من فرع موجود واربطه بهذه المهمة.",
+ "noConnectedRepositories": "اربط مستودع GitHub أو GitLab من إعدادات المشروع أولًا.",
+ "loadingRepositories": "جارٍ تحميل المستودعات…",
+ "chooseRepository": "اختر المستودع",
+ "openOnly": "المفتوحة",
+ "allPullRequests": "الكل",
+ "searchPullRequests": "ابحث بالعنوان أو الفرع أو الرقم…",
+ "loadingPullRequests": "جارٍ تحميل طلبات السحب…",
+ "noPullRequests": "لم يتم العثور على طلبات سحب.",
+ "alreadyLinked": "مرتبط",
+ "loadMore": "تحميل المزيد",
+ "cancel": "إلغاء",
+ "linking": "جارٍ الربط…",
+ "linkPullRequest": "ربط طلب السحب",
+ "linkedSuccess": "تم ربط طلب السحب",
+ "linkFailed": "تعذر ربط طلب السحب",
+ "repository": "المستودع",
+ "sourceBranch": "فرع المصدر",
+ "targetBranch": "الفرع الهدف",
+ "chooseBranch": "اختر الفرع",
+ "loadingBranches": "جارٍ تحميل الفروع…",
+ "loadMoreBranches": "تحميل المزيد من الفروع",
+ "pullRequestTitle": "العنوان",
+ "description": "الوصف",
+ "descriptionPlaceholder": "أضف سياقًا للمراجعين…",
+ "mergeBehavior": "رابط المهمة",
+ "closeOnMerge": "إغلاق عند الدمج",
+ "referenceOnly": "مرجع فقط",
+ "createAsDraft": "إنشاء كمسودة",
+ "branchesMustDiffer": "يجب أن يختلف فرع المصدر عن الفرع الهدف.",
+ "creating": "جارٍ الإنشاء…",
+ "createdSuccess": "تم إنشاء طلب السحب وربطه",
+ "createFailed": "تعذر إنشاء طلب السحب",
"draft": "مسودة",
"ready": "جاهز للدمج",
"open": "مفتوح",
diff --git a/apps/web/messages/en/issue.json b/apps/web/messages/en/issue.json
index 2f6b9e7f..f480dca0 100644
--- a/apps/web/messages/en/issue.json
+++ b/apps/web/messages/en/issue.json
@@ -328,6 +328,44 @@
"title": "Development",
"unlink": "Unlink development item",
"branch": "Branch",
+ "add": "Add",
+ "empty": "Link an existing pull request or create one from a branch",
+ "linkExisting": "Link existing",
+ "linkExistingDescription": "Choose a pull request or merge request from a connected repository.",
+ "createPullRequest": "Create pull request",
+ "createPullRequestDescription": "Open a pull request from an existing branch and link it to this issue.",
+ "noConnectedRepositories": "Connect a GitHub or GitLab repository in project settings first.",
+ "loadingRepositories": "Loading repositories…",
+ "chooseRepository": "Choose repository",
+ "openOnly": "Open",
+ "allPullRequests": "All",
+ "searchPullRequests": "Search by title, branch, or number…",
+ "loadingPullRequests": "Loading pull requests…",
+ "noPullRequests": "No pull requests found.",
+ "alreadyLinked": "Linked",
+ "loadMore": "Load more",
+ "cancel": "Cancel",
+ "linking": "Linking…",
+ "linkPullRequest": "Link pull request",
+ "linkedSuccess": "Pull request linked",
+ "linkFailed": "Could not link this pull request",
+ "repository": "Repository",
+ "sourceBranch": "Source branch",
+ "targetBranch": "Target branch",
+ "chooseBranch": "Choose branch",
+ "loadingBranches": "Loading branches…",
+ "loadMoreBranches": "Load more branches",
+ "pullRequestTitle": "Title",
+ "description": "Description",
+ "descriptionPlaceholder": "Add context for reviewers…",
+ "mergeBehavior": "Issue link",
+ "closeOnMerge": "Close when merged",
+ "referenceOnly": "Reference only",
+ "createAsDraft": "Create as draft",
+ "branchesMustDiffer": "Source and target branches must be different.",
+ "creating": "Creating…",
+ "createdSuccess": "Pull request created and linked",
+ "createFailed": "Could not create this pull request",
"draft": "Draft",
"ready": "Ready",
"open": "Open",
diff --git a/apps/web/messages/fr/issue.json b/apps/web/messages/fr/issue.json
index ed195057..30ef4458 100644
--- a/apps/web/messages/fr/issue.json
+++ b/apps/web/messages/fr/issue.json
@@ -328,6 +328,44 @@
"title": "Développement",
"unlink": "Délier l'élément de développement",
"branch": "Branche",
+ "add": "Ajouter",
+ "empty": "Lier une pull request existante ou en créer une depuis une branche",
+ "linkExisting": "Lier une pull request",
+ "linkExistingDescription": "Choisissez une pull request ou une merge request dans un dépôt connecté.",
+ "createPullRequest": "Créer une pull request",
+ "createPullRequestDescription": "Ouvrez une pull request depuis une branche existante et liez-la à ce ticket.",
+ "noConnectedRepositories": "Connectez d'abord un dépôt GitHub ou GitLab dans les paramètres du projet.",
+ "loadingRepositories": "Chargement des dépôts…",
+ "chooseRepository": "Choisir un dépôt",
+ "openOnly": "Ouvertes",
+ "allPullRequests": "Toutes",
+ "searchPullRequests": "Rechercher par titre, branche ou numéro…",
+ "loadingPullRequests": "Chargement des pull requests…",
+ "noPullRequests": "Aucune pull request trouvée.",
+ "alreadyLinked": "Liée",
+ "loadMore": "Afficher plus",
+ "cancel": "Annuler",
+ "linking": "Liaison…",
+ "linkPullRequest": "Lier la pull request",
+ "linkedSuccess": "Pull request liée",
+ "linkFailed": "Impossible de lier cette pull request",
+ "repository": "Dépôt",
+ "sourceBranch": "Branche source",
+ "targetBranch": "Branche cible",
+ "chooseBranch": "Choisir une branche",
+ "loadingBranches": "Chargement des branches…",
+ "loadMoreBranches": "Afficher plus de branches",
+ "pullRequestTitle": "Titre",
+ "description": "Description",
+ "descriptionPlaceholder": "Ajoutez du contexte pour les reviewers…",
+ "mergeBehavior": "Lien avec le ticket",
+ "closeOnMerge": "Fermer après la fusion",
+ "referenceOnly": "Référence uniquement",
+ "createAsDraft": "Créer comme brouillon",
+ "branchesMustDiffer": "Les branches source et cible doivent être différentes.",
+ "creating": "Création…",
+ "createdSuccess": "Pull request créée et liée",
+ "createFailed": "Impossible de créer cette pull request",
"draft": "Brouillon",
"ready": "Prête",
"open": "Ouverte",
diff --git a/apps/web/messages/ru/issue.json b/apps/web/messages/ru/issue.json
index 5eeb69f4..80e80126 100644
--- a/apps/web/messages/ru/issue.json
+++ b/apps/web/messages/ru/issue.json
@@ -328,6 +328,44 @@
"title": "Разработка",
"unlink": "Удалить связь с разработкой",
"branch": "Ветка",
+ "add": "Добавить",
+ "empty": "Привязать существующий PR/MR или создать новый из ветки",
+ "linkExisting": "Привязать существующий",
+ "linkExistingDescription": "Выберите pull request или merge request из подключённого репозитория.",
+ "createPullRequest": "Создать PR/MR",
+ "createPullRequestDescription": "Создайте PR/MR из существующей ветки и привяжите его к задаче.",
+ "noConnectedRepositories": "Сначала подключите репозиторий GitHub или GitLab в настройках проекта.",
+ "loadingRepositories": "Загружаем репозитории…",
+ "chooseRepository": "Выберите репозиторий",
+ "openOnly": "Открытые",
+ "allPullRequests": "Все",
+ "searchPullRequests": "Поиск по названию, ветке или номеру…",
+ "loadingPullRequests": "Загружаем PR/MR…",
+ "noPullRequests": "PR/MR не найдены.",
+ "alreadyLinked": "Привязан",
+ "loadMore": "Показать ещё",
+ "cancel": "Отмена",
+ "linking": "Привязываем…",
+ "linkPullRequest": "Привязать PR/MR",
+ "linkedSuccess": "PR/MR привязан",
+ "linkFailed": "Не удалось привязать PR/MR",
+ "repository": "Репозиторий",
+ "sourceBranch": "Исходная ветка",
+ "targetBranch": "Целевая ветка",
+ "chooseBranch": "Выберите ветку",
+ "loadingBranches": "Загружаем ветки…",
+ "loadMoreBranches": "Показать ещё ветки",
+ "pullRequestTitle": "Название",
+ "description": "Описание",
+ "descriptionPlaceholder": "Добавьте контекст для ревью…",
+ "mergeBehavior": "Связь с задачей",
+ "closeOnMerge": "Закрыть после merge",
+ "referenceOnly": "Только упомянуть",
+ "createAsDraft": "Создать как draft",
+ "branchesMustDiffer": "Исходная и целевая ветки должны отличаться.",
+ "creating": "Создаём…",
+ "createdSuccess": "PR/MR создан и привязан",
+ "createFailed": "Не удалось создать PR/MR",
"draft": "Черновик",
"ready": "Готово к слиянию",
"open": "Открыт",
diff --git a/apps/web/messages/uk/issue.json b/apps/web/messages/uk/issue.json
index 0e42b9b7..b91eda09 100644
--- a/apps/web/messages/uk/issue.json
+++ b/apps/web/messages/uk/issue.json
@@ -328,6 +328,44 @@
"title": "Розробка",
"unlink": "Видалити зв’язок із розробкою",
"branch": "Гілка",
+ "add": "Додати",
+ "empty": "Прив’язати наявний PR/MR або створити новий із гілки",
+ "linkExisting": "Прив’язати наявний",
+ "linkExistingDescription": "Виберіть pull request або merge request із підключеного репозиторію.",
+ "createPullRequest": "Створити PR/MR",
+ "createPullRequestDescription": "Створіть PR/MR з наявної гілки та прив’яжіть його до задачі.",
+ "noConnectedRepositories": "Спочатку підключіть репозиторій GitHub або GitLab у налаштуваннях проєкту.",
+ "loadingRepositories": "Завантаження репозиторіїв…",
+ "chooseRepository": "Виберіть репозиторій",
+ "openOnly": "Відкриті",
+ "allPullRequests": "Усі",
+ "searchPullRequests": "Пошук за назвою, гілкою або номером…",
+ "loadingPullRequests": "Завантаження PR/MR…",
+ "noPullRequests": "PR/MR не знайдено.",
+ "alreadyLinked": "Прив’язано",
+ "loadMore": "Показати ще",
+ "cancel": "Скасувати",
+ "linking": "Прив’язуємо…",
+ "linkPullRequest": "Прив’язати PR/MR",
+ "linkedSuccess": "PR/MR прив’язано",
+ "linkFailed": "Не вдалося прив’язати PR/MR",
+ "repository": "Репозиторій",
+ "sourceBranch": "Вихідна гілка",
+ "targetBranch": "Цільова гілка",
+ "chooseBranch": "Виберіть гілку",
+ "loadingBranches": "Завантаження гілок…",
+ "loadMoreBranches": "Показати ще гілки",
+ "pullRequestTitle": "Назва",
+ "description": "Опис",
+ "descriptionPlaceholder": "Додайте контекст для рев’ю…",
+ "mergeBehavior": "Зв’язок із задачею",
+ "closeOnMerge": "Закрити після merge",
+ "referenceOnly": "Лише згадати",
+ "createAsDraft": "Створити як draft",
+ "branchesMustDiffer": "Вихідна та цільова гілки мають відрізнятися.",
+ "creating": "Створюємо…",
+ "createdSuccess": "PR/MR створено та прив’язано",
+ "createFailed": "Не вдалося створити PR/MR",
"draft": "Чернетка",
"ready": "Готово до злиття",
"open": "Відкрито",
diff --git a/apps/web/messages/zh-CN/issue.json b/apps/web/messages/zh-CN/issue.json
index b3bcba45..90ab529f 100644
--- a/apps/web/messages/zh-CN/issue.json
+++ b/apps/web/messages/zh-CN/issue.json
@@ -328,6 +328,44 @@
"title": "开发",
"unlink": "取消关联开发项",
"branch": "分支",
+ "add": "添加",
+ "empty": "关联现有拉取请求,或从分支创建一个",
+ "linkExisting": "关联现有请求",
+ "linkExistingDescription": "从已连接的仓库中选择拉取请求或合并请求。",
+ "createPullRequest": "创建拉取请求",
+ "createPullRequestDescription": "从现有分支创建拉取请求,并关联到此任务。",
+ "noConnectedRepositories": "请先在项目设置中连接 GitHub 或 GitLab 仓库。",
+ "loadingRepositories": "正在加载仓库…",
+ "chooseRepository": "选择仓库",
+ "openOnly": "开放",
+ "allPullRequests": "全部",
+ "searchPullRequests": "按标题、分支或编号搜索…",
+ "loadingPullRequests": "正在加载拉取请求…",
+ "noPullRequests": "未找到拉取请求。",
+ "alreadyLinked": "已关联",
+ "loadMore": "加载更多",
+ "cancel": "取消",
+ "linking": "正在关联…",
+ "linkPullRequest": "关联拉取请求",
+ "linkedSuccess": "拉取请求已关联",
+ "linkFailed": "无法关联此拉取请求",
+ "repository": "仓库",
+ "sourceBranch": "源分支",
+ "targetBranch": "目标分支",
+ "chooseBranch": "选择分支",
+ "loadingBranches": "正在加载分支…",
+ "loadMoreBranches": "加载更多分支",
+ "pullRequestTitle": "标题",
+ "description": "描述",
+ "descriptionPlaceholder": "为审阅者添加说明…",
+ "mergeBehavior": "任务关联",
+ "closeOnMerge": "合并时关闭",
+ "referenceOnly": "仅引用",
+ "createAsDraft": "创建为草稿",
+ "branchesMustDiffer": "源分支和目标分支必须不同。",
+ "creating": "正在创建…",
+ "createdSuccess": "拉取请求已创建并关联",
+ "createFailed": "无法创建此拉取请求",
"draft": "草稿",
"ready": "可合并",
"open": "打开",
diff --git a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
index de002e3a..b592f83c 100644
--- a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
@@ -75,6 +75,7 @@ export default function IssueDetailContent({
} = useIssueDetail(project, issueId, onIssueLoaded);
const permissions = usePermissions(project);
const canEdit = permissions.can('work_items', 'edit');
+ const canManageDevelopment = permissions.can('integrations', 'edit');
const canReadDocuments = permissions.can('documents', 'read');
const canLinkDocuments = canEdit && permissions.can('documents', 'edit');
const features = useProjectFeatures();
@@ -187,7 +188,14 @@ export default function IssueDetailContent({
{features.timeLogging && <IssueWorklogPanel project={project} issue={issue} />}
- <IssueDevelopmentPanel issueId={issue.id} links={issue.development ?? []} canEdit={canEdit} />
+ <IssueDevelopmentPanel
+ issueId={issue.id}
+ identifier={issue.identifier}
+ issueTitle={issue.title}
+ links={issue.development ?? []}
+ canEdit={canEdit}
+ canManage={canManageDevelopment}
+ />
{features.documents && (
<IssueDocumentsPanel
diff --git a/apps/web/src/features/issue/components/detail/IssueDevelopmentAddMenu.tsx b/apps/web/src/features/issue/components/detail/IssueDevelopmentAddMenu.tsx
new file mode 100644
index 00000000..9a4c6bc5
--- /dev/null
+++ b/apps/web/src/features/issue/components/detail/IssueDevelopmentAddMenu.tsx
@@ -0,0 +1,39 @@
+import { GitPullRequest, Link2, Plus } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+
+export default function IssueDevelopmentAddMenu({
+ onLink,
+ onCreate,
+}: {
+ onLink: () => void;
+ onCreate: () => void;
+}) {
+ const t = useTranslations('issue.development');
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm" className="h-7 gap-1 px-2 text-muted-foreground">
+ <Plus className="size-3.5" />
+ {t('add')}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-52">
+ <DropdownMenuItem onSelect={onLink}>
+ <Link2 />
+ {t('linkExisting')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onCreate}>
+ <GitPullRequest />
+ {t('createPullRequest')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/features/issue/components/detail/IssueDevelopmentCreateDialog.tsx b/apps/web/src/features/issue/components/detail/IssueDevelopmentCreateDialog.tsx
new file mode 100644
index 00000000..d68360a9
--- /dev/null
+++ b/apps/web/src/features/issue/components/detail/IssueDevelopmentCreateDialog.tsx
@@ -0,0 +1,250 @@
+import { useEffect, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Textarea } from '@/components/ui/textarea';
+import {
+ useCreateIssuePullRequest,
+ useDevelopmentBranchesQuery,
+ useIssueDevelopmentRepositoriesQuery,
+} from '@/services/issues.service';
+
+export default function IssueDevelopmentCreateDialog({
+ issueId,
+ identifier,
+ issueTitle,
+ open,
+ onOpenChange,
+}: {
+ issueId: number;
+ identifier: string;
+ issueTitle: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations('issue.development');
+ const repositoriesQuery = useIssueDevelopmentRepositoriesQuery(issueId, open);
+ const [repositoryId, setRepositoryId] = useState<number | null>(null);
+ const branchesQuery = useDevelopmentBranchesQuery(issueId, repositoryId, open);
+ const branches = useMemo(
+ () => [...new Set(branchesQuery.data?.pages.flatMap((page) => page.branches) ?? [])],
+ [branchesQuery.data],
+ );
+ const defaultBranch = branchesQuery.data?.pages[0]?.defaultBranch ?? null;
+ const [sourceBranch, setSourceBranch] = useState('');
+ const [targetBranch, setTargetBranch] = useState('');
+ const [title, setTitle] = useState('');
+ const [notes, setNotes] = useState('');
+ const [relation, setRelation] = useState<'closes' | 'references'>('closes');
+ const [draft, setDraft] = useState(true);
+ const create = useCreateIssuePullRequest(issueId);
+
+ useEffect(() => {
+ if (open && repositoryId === null && repositoriesQuery.data?.[0])
+ setRepositoryId(repositoriesQuery.data[0].id);
+ if (!open) {
+ setRepositoryId(null);
+ setSourceBranch('');
+ setTargetBranch('');
+ setTitle('');
+ setNotes('');
+ setRelation('closes');
+ setDraft(true);
+ }
+ }, [open, repositoryId, repositoriesQuery.data]);
+
+ useEffect(() => {
+ if (!open) return;
+ if (!title)
+ setTitle(
+ issueTitle.toUpperCase().startsWith(`${identifier.toUpperCase()}:`)
+ ? issueTitle
+ : `${identifier}: ${issueTitle}`,
+ );
+ if (!targetBranch && defaultBranch) setTargetBranch(defaultBranch);
+ }, [defaultBranch, identifier, issueTitle, open, targetBranch, title]);
+
+ async function submit() {
+ if (repositoryId === null) return;
+ const magicWord = relation === 'closes' ? 'Fixes' : 'Refs';
+ const description = [notes.trim(), `${magicWord} ${identifier}`].filter(Boolean).join('\n\n');
+ try {
+ await create.mutateAsync({
+ repositoryId,
+ sourceBranch,
+ targetBranch,
+ title: title.trim(),
+ description,
+ draft,
+ });
+ toast.success(t('createdSuccess'));
+ onOpenChange(false);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t('createFailed'));
+ }
+ }
+
+ const valid =
+ repositoryId !== null &&
+ sourceBranch.length > 0 &&
+ targetBranch.length > 0 &&
+ sourceBranch !== targetBranch &&
+ title.trim().length > 0;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{t('createPullRequest')}</DialogTitle>
+ <DialogDescription>{t('createPullRequestDescription')}</DialogDescription>
+ </DialogHeader>
+ {repositoriesQuery.isPending ? (
+ <div className="rounded-md border border-dashed px-4 py-8 text-center text-sm text-muted-foreground">
+ {t('loadingRepositories')}
+ </div>
+ ) : repositoriesQuery.data?.length === 0 ? (
+ <div className="rounded-md border border-dashed px-4 py-8 text-center text-sm text-muted-foreground">
+ {t('noConnectedRepositories')}
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <label className="block space-y-1.5 text-sm">
+ <span className="font-medium">{t('repository')}</span>
+ <Select
+ value={repositoryId === null ? undefined : String(repositoryId)}
+ onValueChange={(value) => {
+ setRepositoryId(Number(value));
+ setSourceBranch('');
+ setTargetBranch('');
+ }}
+ >
+ <SelectTrigger className="w-full rounded-md">
+ <SelectValue placeholder={t('chooseRepository')} />
+ </SelectTrigger>
+ <SelectContent>
+ {repositoriesQuery.data?.map((repository) => (
+ <SelectItem key={repository.id} value={String(repository.id)}>
+ {repository.fullName}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className="block space-y-1.5 text-sm">
+ <span className="font-medium">{t('sourceBranch')}</span>
+ <Select value={sourceBranch || undefined} onValueChange={setSourceBranch}>
+ <SelectTrigger className="w-full rounded-md">
+ <SelectValue placeholder={t('chooseBranch')} />
+ </SelectTrigger>
+ <SelectContent>
+ {branches
+ .filter((branch) => branch !== targetBranch)
+ .map((branch) => (
+ <SelectItem key={branch} value={branch}>
+ {branch}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <label className="block space-y-1.5 text-sm">
+ <span className="font-medium">{t('targetBranch')}</span>
+ <Select value={targetBranch || undefined} onValueChange={setTargetBranch}>
+ <SelectTrigger className="w-full rounded-md">
+ <SelectValue placeholder={t('chooseBranch')} />
+ </SelectTrigger>
+ <SelectContent>
+ {branches
+ .filter((branch) => branch !== sourceBranch)
+ .map((branch) => (
+ <SelectItem key={branch} value={branch}>
+ {branch}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ </div>
+ {branchesQuery.isPending && (
+ <p className="text-sm text-muted-foreground">{t('loadingBranches')}</p>
+ )}
+ {branchesQuery.hasNextPage && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="w-full"
+ disabled={branchesQuery.isFetchingNextPage}
+ onClick={() => void branchesQuery.fetchNextPage()}
+ >
+ {t('loadMoreBranches')}
+ </Button>
+ )}
+ <label className="block space-y-1.5 text-sm">
+ <span className="font-medium">{t('pullRequestTitle')}</span>
+ <Input value={title} onChange={(event) => setTitle(event.target.value)} />
+ </label>
+ <label className="block space-y-1.5 text-sm">
+ <span className="font-medium">{t('description')}</span>
+ <Textarea
+ value={notes}
+ onChange={(event) => setNotes(event.target.value)}
+ placeholder={t('descriptionPlaceholder')}
+ />
+ </label>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className="block space-y-1.5 text-sm">
+ <span className="font-medium">{t('mergeBehavior')}</span>
+ <Select
+ value={relation}
+ onValueChange={(value) => setRelation(value as typeof relation)}
+ >
+ <SelectTrigger className="w-full rounded-md">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="closes">{t('closeOnMerge')}</SelectItem>
+ <SelectItem value="references">{t('referenceOnly')}</SelectItem>
+ </SelectContent>
+ </Select>
+ </label>
+ <label className="flex items-center gap-2 self-end rounded-md border px-3 py-2 text-sm">
+ <Checkbox checked={draft} onCheckedChange={(value) => setDraft(value === true)} />
+ <span>{t('createAsDraft')}</span>
+ </label>
+ </div>
+ {sourceBranch && targetBranch && sourceBranch === targetBranch && (
+ <p className="text-sm text-destructive">{t('branchesMustDiffer')}</p>
+ )}
+ </div>
+ )}
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('cancel')}
+ </Button>
+ <Button type="button" disabled={!valid || create.isPending} onClick={() => void submit()}>
+ {create.isPending ? t('creating') : t('createPullRequest')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/issue/components/detail/IssueDevelopmentLinkDialog.tsx b/apps/web/src/features/issue/components/detail/IssueDevelopmentLinkDialog.tsx
new file mode 100644
index 00000000..e68c5704
--- /dev/null
+++ b/apps/web/src/features/issue/components/detail/IssueDevelopmentLinkDialog.tsx
@@ -0,0 +1,203 @@
+import { useEffect, useMemo, useState } from 'react';
+import { Check, GitPullRequest } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import {
+ useIssueDevelopmentRepositoriesQuery,
+ useLinkablePullRequestsQuery,
+ useLinkIssueDevelopment,
+} from '@/services/issues.service';
+
+export default function IssueDevelopmentLinkDialog({
+ issueId,
+ open,
+ onOpenChange,
+}: {
+ issueId: number;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations('issue.development');
+ const repositoriesQuery = useIssueDevelopmentRepositoriesQuery(issueId, open);
+ const [repositoryId, setRepositoryId] = useState<number | null>(null);
+ const [state, setState] = useState<'open' | 'all'>('open');
+ const [search, setSearch] = useState('');
+ const [selectedNumber, setSelectedNumber] = useState<number | null>(null);
+ const pullRequestsQuery = useLinkablePullRequestsQuery(issueId, repositoryId, state, open);
+ const link = useLinkIssueDevelopment(issueId);
+ const pullRequests = useMemo(
+ () => pullRequestsQuery.data?.pages.flatMap((page) => page.pullRequests) ?? [],
+ [pullRequestsQuery.data],
+ );
+ const needle = search.trim().toLowerCase();
+ const visiblePullRequests = pullRequests.filter(
+ (pullRequest) =>
+ !needle ||
+ pullRequest.title.toLowerCase().includes(needle) ||
+ pullRequest.sourceBranch?.toLowerCase().includes(needle) ||
+ String(pullRequest.number).includes(needle),
+ );
+
+ useEffect(() => {
+ if (open && repositoryId === null && repositoriesQuery.data?.[0])
+ setRepositoryId(repositoriesQuery.data[0].id);
+ if (!open) {
+ setRepositoryId(null);
+ setState('open');
+ setSearch('');
+ setSelectedNumber(null);
+ }
+ }, [open, repositoryId, repositoriesQuery.data]);
+
+ async function submit() {
+ if (repositoryId === null || selectedNumber === null) return;
+ try {
+ await link.mutateAsync({ repositoryId, number: selectedNumber });
+ toast.success(t('linkedSuccess'));
+ onOpenChange(false);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t('linkFailed'));
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{t('linkExisting')}</DialogTitle>
+ <DialogDescription>{t('linkExistingDescription')}</DialogDescription>
+ </DialogHeader>
+ {repositoriesQuery.isPending ? (
+ <div className="rounded-md border border-dashed px-4 py-8 text-center text-sm text-muted-foreground">
+ {t('loadingRepositories')}
+ </div>
+ ) : repositoriesQuery.data?.length === 0 ? (
+ <div className="rounded-md border border-dashed px-4 py-8 text-center text-sm text-muted-foreground">
+ {t('noConnectedRepositories')}
+ </div>
+ ) : (
+ <>
+ <div className="flex gap-2">
+ <Select
+ value={repositoryId === null ? undefined : String(repositoryId)}
+ onValueChange={(value) => {
+ setRepositoryId(Number(value));
+ setSelectedNumber(null);
+ }}
+ >
+ <SelectTrigger className="min-w-0 flex-1 rounded-md">
+ <SelectValue placeholder={t('chooseRepository')} />
+ </SelectTrigger>
+ <SelectContent>
+ {repositoriesQuery.data?.map((repository) => (
+ <SelectItem key={repository.id} value={String(repository.id)}>
+ {repository.fullName}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <div className="flex rounded-md border p-0.5">
+ {(['open', 'all'] as const).map((value) => (
+ <Button
+ key={value}
+ type="button"
+ size="sm"
+ variant={state === value ? 'secondary' : 'ghost'}
+ className="h-7 rounded-sm px-2.5"
+ onClick={() => {
+ setState(value);
+ setSelectedNumber(null);
+ }}
+ >
+ {t(value === 'open' ? 'openOnly' : 'allPullRequests')}
+ </Button>
+ ))}
+ </div>
+ </div>
+ <Input
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ placeholder={t('searchPullRequests')}
+ />
+ <div className="max-h-80 space-y-1 overflow-y-auto rounded-md border p-1.5">
+ {pullRequestsQuery.isPending && (
+ <p className="p-3 text-sm text-muted-foreground">{t('loadingPullRequests')}</p>
+ )}
+ {!pullRequestsQuery.isPending && visiblePullRequests.length === 0 && (
+ <p className="p-3 text-sm text-muted-foreground">{t('noPullRequests')}</p>
+ )}
+ {visiblePullRequests.map((pullRequest) => (
+ <button
+ key={pullRequest.number}
+ type="button"
+ disabled={pullRequest.linked}
+ className="flex w-full items-start gap-3 rounded-md px-3 py-2 text-start hover:bg-muted/60 disabled:opacity-60"
+ onClick={() => setSelectedNumber(pullRequest.number)}
+ >
+ <GitPullRequest className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium" dir="auto">
+ {pullRequest.title}
+ </span>
+ <span
+ className="block truncate font-mono text-[11px] text-muted-foreground"
+ dir="ltr"
+ >
+ #{pullRequest.number} · {pullRequest.sourceBranch ?? '?'} →{' '}
+ {pullRequest.targetBranch}
+ </span>
+ </span>
+ {pullRequest.linked ? (
+ <span className="text-xs text-muted-foreground">{t('alreadyLinked')}</span>
+ ) : selectedNumber === pullRequest.number ? (
+ <Check className="mt-0.5 size-4 text-primary" />
+ ) : null}
+ </button>
+ ))}
+ {pullRequestsQuery.hasNextPage && (
+ <Button
+ type="button"
+ variant="ghost"
+ className="w-full"
+ disabled={pullRequestsQuery.isFetchingNextPage}
+ onClick={() => void pullRequestsQuery.fetchNextPage()}
+ >
+ {t('loadMore')}
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('cancel')}
+ </Button>
+ <Button
+ type="button"
+ disabled={selectedNumber === null || link.isPending}
+ onClick={() => void submit()}
+ >
+ {link.isPending ? t('linking') : t('linkPullRequest')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/issue/components/detail/IssueDevelopmentPanel.tsx b/apps/web/src/features/issue/components/detail/IssueDevelopmentPanel.tsx
index 34690537..0bf14c9b 100644
--- a/apps/web/src/features/issue/components/detail/IssueDevelopmentPanel.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueDevelopmentPanel.tsx
@@ -1,34 +1,61 @@
+import { useState } from 'react';
import { type DevelopmentLink } from '@/lib/api';
import { usePersistedOpen } from '../../hooks/usePersistedOpen';
+import IssueDevelopmentAddMenu from './IssueDevelopmentAddMenu';
+import IssueDevelopmentCreateDialog from './IssueDevelopmentCreateDialog';
import IssueDevelopmentLinkCard from './IssueDevelopmentLinkCard';
+import IssueDevelopmentLinkDialog from './IssueDevelopmentLinkDialog';
import IssueSectionHeading from './IssueSectionHeading';
import { useTranslations } from 'next-intl';
export default function IssueDevelopmentPanel({
issueId,
+ identifier,
+ issueTitle,
links,
canEdit,
+ canManage,
}: {
issueId: number;
+ identifier: string;
+ issueTitle: string;
links: DevelopmentLink[];
canEdit: boolean;
+ canManage: boolean;
}) {
const t = useTranslations('issue.development');
const { open, toggle } = usePersistedOpen('issue-development-open');
- if (links.length === 0) return null;
+ const [linkOpen, setLinkOpen] = useState(false);
+ const [createOpen, setCreateOpen] = useState(false);
+ if (links.length === 0 && !canManage) return null;
return (
<div className={`mt-6 border-t pt-5 ${open ? '' : '-mb-2'}`}>
- <div className={`flex h-7 items-center ${open ? 'mb-3' : ''}`}>
+ <div className={`flex h-7 items-center justify-between gap-3 ${open ? 'mb-3' : ''}`}>
<IssueSectionHeading
label={t('title')}
tally={String(links.length)}
open={open}
onToggle={toggle}
/>
+ {canManage && (
+ <IssueDevelopmentAddMenu
+ onLink={() => setLinkOpen(true)}
+ onCreate={() => setCreateOpen(true)}
+ />
+ )}
</div>
{open && (
<div className="space-y-2">
+ {links.length === 0 && (
+ <button
+ type="button"
+ className="w-full rounded-md border border-dashed px-4 py-5 text-center text-sm text-muted-foreground hover:border-border hover:bg-muted/30 hover:text-foreground"
+ onClick={() => setLinkOpen(true)}
+ >
+ {t('empty')}
+ </button>
+ )}
{links.map((link) => (
<IssueDevelopmentLinkCard
key={link.id}
@@ -39,6 +66,14 @@ export default function IssueDevelopmentPanel({
))}
</div>
)}
+ <IssueDevelopmentLinkDialog issueId={issueId} open={linkOpen} onOpenChange={setLinkOpen} />
+ <IssueDevelopmentCreateDialog
+ issueId={issueId}
+ identifier={identifier}
+ issueTitle={issueTitle}
+ open={createOpen}
+ onOpenChange={setCreateOpen}
+ />
</div>
);
}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index d149671d..d02b570a 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -2230,6 +2230,46 @@ export interface DevelopmentLink {
updatedAt: string;
}
+export interface DevelopmentRepository {
+ id: number;
+ provider: 'github' | 'gitlab';
+ fullName: string;
+ webUrl: string;
+}
+
+export interface LinkablePullRequest {
+ number: number;
+ title: string;
+ url: string | null;
+ state: PullRequestState;
+ draft: boolean;
+ sourceBranch: string | null;
+ targetBranch: string;
+ headSha: string | null;
+ updatedAt: string;
+ linked: boolean;
+}
+
+export interface LinkablePullRequestPage {
+ pullRequests: LinkablePullRequest[];
+ nextPage: number | null;
+}
+
+export interface DevelopmentBranchPage {
+ branches: string[];
+ defaultBranch: string | null;
+ nextPage: number | null;
+}
+
+export interface CreateIssuePullRequestInput {
+ repositoryId: number;
+ sourceBranch: string;
+ targetBranch: string;
+ title: string;
+ description: string;
+ draft: boolean;
+}
+
// A relation between two issues (mirrors apps/api modules/issues/links.ts). 'blocks' and
// 'duplicates' are directional and read differently on each end, which direction
// selects: 'outward' is the side that blocks/duplicates, 'inward' the side that is
@@ -3030,6 +3070,32 @@ export const api = {
request<Issue>(`/issues/${id}`, { method: 'PATCH', body: JSON.stringify(patch) }),
removeIssueDevelopmentLink: (issueId: number, linkId: number) =>
request<void>(`/issues/${issueId}/development/${linkId}`, { method: 'DELETE' }),
+ listIssueDevelopmentRepositories: (issueId: number) =>
+ request<DevelopmentRepository[]>(`/issues/${issueId}/development/repositories`),
+ listLinkablePullRequests: (
+ issueId: number,
+ repositoryId: number,
+ input: { state: 'open' | 'all'; page: number },
+ ) =>
+ request<LinkablePullRequestPage>(
+ `/issues/${issueId}/development/repositories/${repositoryId}/pull-requests?${new URLSearchParams(
+ { state: input.state, page: String(input.page) },
+ )}`,
+ ),
+ listDevelopmentBranches: (issueId: number, repositoryId: number, page: number) =>
+ request<DevelopmentBranchPage>(
+ `/issues/${issueId}/development/repositories/${repositoryId}/branches?page=${page}`,
+ ),
+ linkIssueDevelopment: (issueId: number, input: { repositoryId: number; number: number }) =>
+ request<DevelopmentLink>(`/issues/${issueId}/development`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ }),
+ createIssuePullRequest: (issueId: number, input: CreateIssuePullRequestInput) =>
+ request<DevelopmentLink>(`/issues/${issueId}/development/pull-requests`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ }),
// An issue that has subtasks needs a disposition saying what happens to them;
// without one the server rejects the delete with a 409.
deleteIssue: (id: number, subtasks?: SubtaskDisposition) =>
diff --git a/apps/web/src/services/issues.service.ts b/apps/web/src/services/issues.service.ts
index 9eee87dd..579983fc 100644
--- a/apps/web/src/services/issues.service.ts
+++ b/apps/web/src/services/issues.service.ts
@@ -1,4 +1,10 @@
-import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import {
+ keepPreviousData,
+ useInfiniteQuery,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query';
import {
api,
type BulkIssuePatch,
@@ -41,6 +47,61 @@ export function useRemoveIssueDevelopmentLink(issueId: number) {
});
}
+export function useIssueDevelopmentRepositoriesQuery(issueId: number, enabled: boolean) {
+ return useQuery({
+ queryKey: qk.issueDevelopmentRepositories(issueId),
+ queryFn: () => api.listIssueDevelopmentRepositories(issueId),
+ enabled,
+ });
+}
+
+export function useLinkablePullRequestsQuery(
+ issueId: number,
+ repositoryId: number | null,
+ state: 'open' | 'all',
+ enabled: boolean,
+) {
+ return useInfiniteQuery({
+ queryKey: qk.issueDevelopmentPullRequests(issueId, repositoryId ?? -1, state),
+ queryFn: ({ pageParam }) =>
+ api.listLinkablePullRequests(issueId, repositoryId!, { state, page: pageParam }),
+ initialPageParam: 1,
+ getNextPageParam: (page) => page.nextPage ?? undefined,
+ enabled: enabled && repositoryId !== null,
+ });
+}
+
+export function useDevelopmentBranchesQuery(
+ issueId: number,
+ repositoryId: number | null,
+ enabled: boolean,
+) {
+ return useInfiniteQuery({
+ queryKey: qk.issueDevelopmentBranches(issueId, repositoryId ?? -1),
+ queryFn: ({ pageParam }) => api.listDevelopmentBranches(issueId, repositoryId!, pageParam),
+ initialPageParam: 1,
+ getNextPageParam: (page) => page.nextPage ?? undefined,
+ enabled: enabled && repositoryId !== null,
+ });
+}
+
+export function useLinkIssueDevelopment(issueId: number) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (input: { repositoryId: number; number: number }) =>
+ api.linkIssueDevelopment(issueId, input),
+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.issue(issueId) }),
+ });
+}
+
+export function useCreateIssuePullRequest(issueId: number) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (input: Parameters<typeof api.createIssuePullRequest>[1]) =>
+ api.createIssuePullRequest(issueId, input),
+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.issue(issueId) }),
+ });
+}
// The cycles an issue was planned into. Read only where the badge that shows them
// is, so a project without cycles never asks for it.
export function useIssueCyclesQuery(issueId: number) {
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index d63157f2..cc517729 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -109,6 +109,12 @@ export const qk = {
agentToolLinks: (projectKey: string, agentId: number) =>
['aiAgents', projectKey, agentId, 'tool-configs'] as const,
issue: (id: number) => ['issue', id] as const,
+ issueDevelopmentRepositories: (id: number) =>
+ ['issue', id, 'development', 'repositories'] as const,
+ issueDevelopmentPullRequests: (id: number, repositoryId: number, state: 'open' | 'all') =>
+ ['issue', id, 'development', 'repositories', repositoryId, 'pullRequests', state] as const,
+ issueDevelopmentBranches: (id: number, repositoryId: number) =>
+ ['issue', id, 'development', 'repositories', repositoryId, 'branches'] as const,
// Under the issue prefix, so every issue mutation refreshes the cycles with it.
issueCycles: (id: number) => ['issue', id, 'cycles'] as const,
anyIssue: ['issue'] as const,