Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(acceptance): own linked pull requests on the acceptance, not the round (#20426)

Arvin Xudeed84709bd0
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.ts
index 61923e46fc5..840abfb2db3 100644
--- a/apps/server/src/routers/lambda/acceptance.ts
+++ b/apps/server/src/routers/lambda/acceptance.ts
@@ -20,6 +20,7 @@ import {
import { AcceptanceFlowModel } from '@/database/models/acceptanceFlow';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { ProjectModel } from '@/database/models/project';
+import { ScmChangeRequestModel } from '@/database/models/scm';
import { VerifyReviewPredictionModel } from '@/database/models/verifyReviewPrediction';
import { VerifyRunModel } from '@/database/models/verifyRun';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
@@ -31,6 +32,7 @@ import { isUuid } from '@/database/utils/uuid';
import { publicProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
+import { parseChangeRequestUrl } from '@/server/services/scm/changeRequestUrl';
import {
AcceptanceService,
buildAcceptanceCheckUnion,
@@ -45,6 +47,12 @@ import {
shouldSurfaceProposal,
VerifyReviewPredictorService,
} from '@/server/services/verify';
+import {
+ addPullRequestLink,
+ listAcceptancePullRequests,
+ removePullRequestLink,
+ updateAcceptancePullRequests,
+} from '@/server/services/verify/acceptancePullRequests';
import { after } from '@/server/utils/scheduleAfterResponse';
import {
@@ -425,6 +433,58 @@ export const acceptanceRouter = router({
}
}),
+ /**
+ * Record that a pull request delivers this acceptance. The link lives on the
+ * acceptance, not on a round: the pull request usually opens after the
+ * rounds that verified it, and stacked pull requests share one acceptance.
+ *
+ * Stored on the acceptance rather than on the shared `scm_change_requests`
+ * row: that row is keyed globally and owned by whichever tenant the
+ * provider routes the PR to, so a pasted URL must not claim it. A hand
+ * link is display-only and never drives merge β†’ accepted.
+ */
+ linkPullRequest: acceptanceWriteProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ title: z.string().trim().min(1).max(500).optional(),
+ url: z.string().max(2000),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);
+ const parsed = parseChangeRequestUrl(input.url);
+ if (!parsed) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Expected a GitHub pull request URL, e.g. https://github.com/owner/repo/pull/123',
+ });
+ }
+
+ await updateAcceptancePullRequests(ctx.serverDB, acceptance.id, (links) =>
+ addPullRequestLink(links, parsed, input.title),
+ );
+ return parsed;
+ }),
+
+ unlinkPullRequest: acceptanceWriteProcedure
+ .input(z.object({ id: z.string(), url: z.string().max(2000) }))
+ .mutation(async ({ ctx, input }) => {
+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);
+ const parsed = parseChangeRequestUrl(input.url);
+ const pullRequests = parsed
+ ? await updateAcceptancePullRequests(ctx.serverDB, acceptance.id, (links) =>
+ removePullRequestLink(links, parsed),
+ )
+ : null;
+ if (!pullRequests) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Linked pull request not found' });
+ }
+
+ return { success: true };
+ }),
+
/** Get (or lazily create) the aggregate for a subject β€” the ingest entry point. */
ensure: acceptanceWriteProcedure
.input(
@@ -599,22 +659,26 @@ export const acceptanceRouter = router({
acceptance.workspaceId ?? undefined,
);
- const [subject, { evidence, reports, results, runs }, authorRows] = await Promise.all([
- ownerService.resolveSubject(acceptance),
- ownerService.loadRounds(acceptance.id),
- // Who delivered this, the way a pull request names its author. A
- // shared link lands on someone else's record, and a record with no
- // name on it reads as nobody's.
- ctx.serverDB
- .select({
- avatar: users.avatar,
- fullName: users.fullName,
- id: users.id,
- username: users.username,
- })
- .from(users)
- .where(eq(users.id, acceptance.userId)),
- ]);
+ const [subject, { evidence, reports, results, runs }, authorRows, changeRequests] =
+ await Promise.all([
+ ownerService.resolveSubject(acceptance),
+ ownerService.loadRounds(acceptance.id),
+ // Who delivered this, the way a pull request names its author. A
+ // shared link lands on someone else's record, and a record with no
+ // name on it reads as nobody's.
+ ctx.serverDB
+ .select({
+ avatar: users.avatar,
+ fullName: users.fullName,
+ id: users.id,
+ username: users.username,
+ })
+ .from(users)
+ .where(eq(users.id, acceptance.userId)),
+ // Provider-verified PRs that deliver it. Owned by the acceptance, not
+ // by a round, so one opened after the last round still shows.
+ ScmChangeRequestModel.listByAcceptance(ctx.serverDB, acceptance.id),
+ ]);
const author = authorRows[0] ?? null;
const flowData = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).list(
@@ -793,6 +857,7 @@ export const acceptanceRouter = router({
return {
author,
+ pullRequests: listAcceptancePullRequests(changeRequests, acceptance.metadata?.pullRequests),
flows: flowData.map((flow) => ({
...flow,
versions: flow.versions.map((version) => ({
@@ -1290,9 +1355,7 @@ export const acceptanceRouter = router({
.mutation(async ({ ctx, input }) => {
const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);
- return service.acceptanceModel.update(acceptance.id, {
- metadata: { ...acceptance.metadata, title: input.title },
- });
+ return service.acceptanceModel.patchMetadata(acceptance.id, { title: input.title });
}),
/**
diff --git a/apps/server/src/services/scm/__tests__/changeRequestUrl.test.ts b/apps/server/src/services/scm/__tests__/changeRequestUrl.test.ts
new file mode 100644
index 00000000000..00c4749aa95
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/changeRequestUrl.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseChangeRequestUrl } from '../changeRequestUrl';
+
+describe('parseChangeRequestUrl', () => {
+ it('reads a GitHub pull request URL, including a tab under it', () => {
+ const expected = {
+ number: 20171,
+ provider: 'github',
+ repoFullName: 'lobehub/lobehub',
+ url: 'https://github.com/lobehub/lobehub/pull/20171',
+ };
+ expect(parseChangeRequestUrl('https://github.com/lobehub/lobehub/pull/20171')).toEqual(
+ expected,
+ );
+ expect(
+ parseChangeRequestUrl(' https://github.com/lobehub/lobehub/pull/20171/files?w=1#diff '),
+ ).toEqual(expected);
+ });
+
+ it('rejects anything that does not name a pull request', () => {
+ for (const value of [
+ 'not a url',
+ 'http://github.com/lobehub/lobehub/pull/1',
+ 'https://gitlab.com/lobehub/lobehub/pull/1',
+ 'https://github.com.evil.dev/lobehub/lobehub/pull/1',
+ 'https://github.com/lobehub/lobehub/issues/1',
+ 'https://github.com/lobehub/lobehub/pull/0',
+ 'https://github.com/lobehub/lobehub/pull/abc',
+ ])
+ expect(parseChangeRequestUrl(value)).toBeNull();
+ });
+});
diff --git a/apps/server/src/services/scm/changeRequestUrl.ts b/apps/server/src/services/scm/changeRequestUrl.ts
new file mode 100644
index 00000000000..9a2395916a5
--- /dev/null
+++ b/apps/server/src/services/scm/changeRequestUrl.ts
@@ -0,0 +1,40 @@
+import type { ScmProvider } from '@lobechat/types';
+
+export interface ParsedChangeRequestUrl {
+ number: number;
+ provider: ScmProvider;
+ repoFullName: string;
+ /** Canonical form, without any trailing tab path, query or fragment. */
+ url: string;
+}
+
+const GITHUB_PULL_PATH = /^\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)(?:\/.*)?$/;
+
+/**
+ * The change request a web URL names, or `null` when it names none. Only
+ * github.com pull requests today, matching `SCM_PROVIDERS`; a link to a
+ * PR's "Files changed" tab still names the PR.
+ */
+export const parseChangeRequestUrl = (value: string): ParsedChangeRequestUrl | null => {
+ let url: URL;
+ try {
+ url = new URL(value.trim());
+ } catch {
+ return null;
+ }
+ if (url.protocol !== 'https:' || url.hostname.toLowerCase() !== 'github.com') return null;
+
+ const match = GITHUB_PULL_PATH.exec(url.pathname);
+ if (!match) return null;
+ const [, owner, repo, rawNumber] = match;
+ const number = Number(rawNumber);
+ if (!Number.isSafeInteger(number) || number <= 0) return null;
+
+ const repoFullName = `${owner}/${repo}`;
+ return {
+ number,
+ provider: 'github',
+ repoFullName,
+ url: `https://github.com/${repoFullName}/pull/${number}`,
+ };
+};
diff --git a/apps/server/src/services/verify/__tests__/acceptancePullRequests.db.test.ts b/apps/server/src/services/verify/__tests__/acceptancePullRequests.db.test.ts
new file mode 100644
index 00000000000..9de2a334ab0
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptancePullRequests.db.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { acceptances, users } from '@/database/schemas';
+
+import { parseChangeRequestUrl } from '../../scm/changeRequestUrl';
+import { addPullRequestLink, updateAcceptancePullRequests } from '../acceptancePullRequests';
+
+const serverDB = await getTestDB();
+const userId = 'acceptance-pr-link-user';
+
+const parse = (url: string) => {
+ const parsed = parseChangeRequestUrl(url);
+ if (!parsed) throw new Error(`not a PR url: ${url}`);
+ return parsed;
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+describe('updateAcceptancePullRequests', () => {
+ it('keeps both stacked PRs linked concurrently and leaves other metadata alone', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({
+ metadata: { title: 'Durable waits' },
+ subjectId: 's',
+ subjectType: 'standalone',
+ userId,
+ })
+ .returning();
+
+ await Promise.all(
+ [20426, 20427].map((number) =>
+ updateAcceptancePullRequests(serverDB, acceptance.id, (links) =>
+ addPullRequestLink(
+ links,
+ parse(`https://github.com/lobehub/lobehub/pull/${number}`),
+ undefined,
+ ),
+ ),
+ ),
+ );
+
+ const stored = await serverDB.query.acceptances.findFirst({
+ where: eq(acceptances.id, acceptance.id),
+ });
+ expect(stored?.metadata?.title).toBe('Durable waits');
+ expect(stored?.metadata?.pullRequests?.map((link) => link.number).sort()).toEqual([
+ 20426, 20427,
+ ]);
+ });
+
+ it('writes nothing when the update declines', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 's2', subjectType: 'standalone', userId })
+ .returning();
+
+ expect(await updateAcceptancePullRequests(serverDB, acceptance.id, () => null)).toBeNull();
+ const stored = await serverDB.query.acceptances.findFirst({
+ where: eq(acceptances.id, acceptance.id),
+ });
+ expect(stored?.metadata?.pullRequests).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/acceptancePullRequests.test.ts b/apps/server/src/services/verify/__tests__/acceptancePullRequests.test.ts
new file mode 100644
index 00000000000..47050109ce8
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptancePullRequests.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ScmChangeRequestItem } from '@/database/schemas';
+
+import { parseChangeRequestUrl } from '../../scm/changeRequestUrl';
+import {
+ addPullRequestLink,
+ listAcceptancePullRequests,
+ removePullRequestLink,
+} from '../acceptancePullRequests';
+
+const parse = (url: string) => {
+ const parsed = parseChangeRequestUrl(url);
+ if (!parsed) throw new Error(`not a PR url: ${url}`);
+ return parsed;
+};
+
+const pr = parse('https://github.com/lobehub/lobehub/pull/20171');
+const now = new Date('2026-10-06T00:00:00Z');
+
+describe('acceptance pull request links', () => {
+ it('links a PR opened after the last round, once, whatever casing is pasted', () => {
+ const first = addPullRequestLink(undefined, pr, 'Durable waits', now);
+ const again = addPullRequestLink(
+ first,
+ parse('https://github.com/LobeHub/LobeHub/pull/20171/files'),
+ undefined,
+ new Date('2026-10-07T00:00:00Z'),
+ );
+
+ expect(again).toEqual([
+ {
+ linkedAt: now.toISOString(),
+ number: 20171,
+ provider: 'github',
+ repoFullName: 'LobeHub/LobeHub',
+ title: 'Durable waits',
+ url: 'https://github.com/LobeHub/LobeHub/pull/20171',
+ },
+ ]);
+ });
+
+ it('keeps stacked PRs side by side and unlinks one without touching the other', () => {
+ const stacked = parse('https://github.com/lobehub/lobehub/pull/20172');
+ const links = addPullRequestLink(
+ addPullRequestLink(undefined, pr, undefined, now),
+ stacked,
+ undefined,
+ now,
+ );
+
+ expect(removePullRequestLink(links, pr)).toEqual([links[1]]);
+ expect(
+ removePullRequestLink(links, parse('https://github.com/lobehub/lobehub/pull/2017')),
+ ).toBeNull();
+ });
+
+ it('lists verified provider rows first and drops hand links they already cover', () => {
+ const row = {
+ ciStatus: 'success',
+ isDraft: false,
+ mergedAt: null,
+ number: 20171,
+ provider: 'github',
+ repoFullName: 'lobehub/lobehub',
+ reviewDecision: 'approved',
+ state: 'open',
+ title: 'From provider',
+ topicId: 'private-topic',
+ url: pr.url,
+ } as unknown as ScmChangeRequestItem;
+ const links = addPullRequestLink(
+ addPullRequestLink(
+ undefined,
+ parse('https://github.com/LOBEHUB/lobehub/pull/20171'),
+ undefined,
+ now,
+ ),
+ parse('https://github.com/lobehub/lobehub/pull/20172'),
+ 'Stacked CLI',
+ now,
+ );
+
+ const listed = listAcceptancePullRequests([row], links);
+
+ expect(listed).toEqual([
+ expect.objectContaining({ number: 20171, source: 'provider', state: 'open' }),
+ expect.objectContaining({
+ number: 20172,
+ source: 'manual',
+ state: null,
+ title: 'Stacked CLI',
+ }),
+ ]);
+ expect(listed[0]).not.toHaveProperty('topicId');
+ });
+});
diff --git a/apps/server/src/services/verify/acceptancePullRequests.ts b/apps/server/src/services/verify/acceptancePullRequests.ts
new file mode 100644
index 00000000000..cd128888e17
--- /dev/null
+++ b/apps/server/src/services/verify/acceptancePullRequests.ts
@@ -0,0 +1,136 @@
+import type {
+ AcceptancePullRequestLink,
+ ScmChangeRequestState,
+ ScmCiStatus,
+ ScmReviewDecision,
+} from '@lobechat/types';
+import { eq, sql } from 'drizzle-orm';
+
+import type { ScmChangeRequestItem } from '@/database/schemas';
+import { acceptances } from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+
+import type { ParsedChangeRequestUrl } from '../scm/changeRequestUrl';
+
+/** GitHub names are case-insensitive, so the identity folds case. */
+const identity = (link: { number: number; provider: string; repoFullName: string }) =>
+ `${link.provider}:${link.repoFullName.toLowerCase()}#${link.number}`;
+
+/** Add or refresh a hand link; the same PR spelled differently is one link. */
+export const addPullRequestLink = (
+ links: AcceptancePullRequestLink[] | undefined,
+ parsed: ParsedChangeRequestUrl,
+ title: string | undefined,
+ now = new Date(),
+): AcceptancePullRequestLink[] => {
+ const key = identity(parsed);
+ const existing = links?.find((link) => identity(link) === key);
+ const next: AcceptancePullRequestLink = {
+ linkedAt: existing?.linkedAt ?? now.toISOString(),
+ number: parsed.number,
+ provider: parsed.provider,
+ repoFullName: parsed.repoFullName,
+ title: title ?? existing?.title,
+ url: parsed.url,
+ };
+ return [...(links ?? []).filter((link) => identity(link) !== key), next];
+};
+
+/** Drop a hand link; `null` when the acceptance had none for this PR. */
+export const removePullRequestLink = (
+ links: AcceptancePullRequestLink[] | undefined,
+ parsed: ParsedChangeRequestUrl,
+): AcceptancePullRequestLink[] | null => {
+ const key = identity(parsed);
+ if (!links?.some((link) => identity(link) === key)) return null;
+ return links.filter((link) => identity(link) !== key);
+};
+
+/**
+ * Read, change and write an acceptance's hand links under a row lock, touching
+ * only the `pullRequests` key. Stacked PRs are often linked by concurrent
+ * ingests, and a merge of a stale `metadata` snapshot would drop one of them
+ * (or a concurrent rename). Returns `null` when `update` declines.
+ */
+export const updateAcceptancePullRequests = async (
+ db: LobeChatDatabase,
+ acceptanceId: string,
+ update: (links: AcceptancePullRequestLink[] | undefined) => AcceptancePullRequestLink[] | null,
+): Promise<AcceptancePullRequestLink[] | null> =>
+ db.transaction(async (tx) => {
+ const [row] = await tx
+ .select({ metadata: acceptances.metadata })
+ .from(acceptances)
+ .where(eq(acceptances.id, acceptanceId))
+ .for('update');
+ if (!row) return null;
+
+ const next = update(row.metadata?.pullRequests);
+ if (!next) return null;
+ await tx
+ .update(acceptances)
+ .set({
+ metadata: sql`jsonb_set(COALESCE(${acceptances.metadata}, '{}'::jsonb), '{pullRequests}', ${JSON.stringify(next)}::jsonb)`,
+ updatedAt: new Date(),
+ })
+ .where(eq(acceptances.id, acceptanceId));
+ return next;
+ });
+
+export interface AcceptancePullRequest {
+ ciStatus: ScmCiStatus | null;
+ isDraft: boolean;
+ mergedAt: Date | null;
+ number: number;
+ provider: string;
+ repoFullName: string;
+ reviewDecision: ScmReviewDecision | null;
+ /** `provider`: a verified provider row; `manual`: a hand link nothing has vouched for. */
+ source: 'manual' | 'provider';
+ /** `null` for a hand link: no provider has reported its lifecycle to this acceptance. */
+ state: ScmChangeRequestState | null;
+ title: string | null;
+ url: string;
+}
+
+/**
+ * The pull requests that deliver an acceptance: provider-verified rows linked
+ * to it, then hand links no verified row already covers. Provider facts only β€”
+ * topic, task and installation links are the owner's plumbing, and a public
+ * acceptance is readable by anyone holding its URL.
+ */
+export const listAcceptancePullRequests = (
+ rows: ScmChangeRequestItem[],
+ links: AcceptancePullRequestLink[] | undefined,
+): AcceptancePullRequest[] => {
+ const verified = rows.map((row): AcceptancePullRequest => ({
+ ciStatus: row.ciStatus,
+ isDraft: row.isDraft,
+ mergedAt: row.mergedAt,
+ number: row.number,
+ provider: row.provider,
+ repoFullName: row.repoFullName,
+ reviewDecision: row.reviewDecision,
+ source: 'provider',
+ state: row.state,
+ title: row.title,
+ url: row.url,
+ }));
+ const covered = new Set(verified.map(identity));
+ const manual = (links ?? [])
+ .filter((link) => !covered.has(identity(link)))
+ .map((link): AcceptancePullRequest => ({
+ ciStatus: null,
+ isDraft: false,
+ mergedAt: null,
+ number: link.number,
+ provider: link.provider,
+ repoFullName: link.repoFullName,
+ reviewDecision: null,
+ source: 'manual',
+ state: null,
+ title: link.title ?? null,
+ url: link.url,
+ }));
+ return [...verified, ...manual];
+};
diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.ts
index 97b6e53783b..69c78c4177a 100644
--- a/packages/database/src/models/__tests__/acceptance.test.ts
+++ b/packages/database/src/models/__tests__/acceptance.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import type { AcceptanceStatus } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
@@ -275,6 +276,56 @@ describe('AcceptanceModel', () => {
expect((await model.findById(row.id))?.completedAt).toBeNull();
});
+ it('patches metadata keys without reverting keys another writer committed', async () => {
+ const model = new AcceptanceModel(serverDB, userId);
+ const acceptance = await model.create({
+ metadata: { title: 'Before' },
+ subjectId: topicId,
+ subjectType: 'topic',
+ });
+ const pullRequests = [
+ {
+ linkedAt: '2026-10-06T00:00:00.000Z',
+ number: 20426,
+ provider: 'github' as const,
+ repoFullName: 'lobehub/lobehub',
+ url: 'https://github.com/lobehub/lobehub/pull/20426',
+ },
+ ];
+
+ // A rename that read `acceptance` before a PR was linked.
+ await serverDB
+ .update(acceptances)
+ .set({ metadata: { ...acceptance.metadata, pullRequests } })
+ .where(eq(acceptances.id, acceptance.id));
+ const renamed = await model.patchMetadata(acceptance.id, { title: 'After' });
+
+ expect(renamed?.metadata).toEqual({ pullRequests, title: 'After' });
+ expect(
+ await new AcceptanceModel(serverDB, otherUserId).patchMetadata(acceptance.id, { title: 'x' }),
+ ).toBeUndefined();
+ });
+
+ it('fills a missing title on ensure without dropping keys written since its read', async () => {
+ const model = new AcceptanceModel(serverDB, userId);
+ const acceptance = await model.create({ subjectId: topicId, subjectType: 'topic' });
+ const findBySubject = model.findBySubject;
+ // Another writer links a PR between ensure's read and its write.
+ model.findBySubject = async (...args) => {
+ const existing = await findBySubject(...args);
+ await serverDB
+ .update(acceptances)
+ .set({ metadata: { pullRequests: [] } })
+ .where(eq(acceptances.id, acceptance.id));
+ return existing;
+ };
+
+ await model.ensureForSubject('topic', topicId, { metadata: { title: 'Delivery' } });
+
+ const stored = await model.findById(acceptance.id);
+ expect(stored?.metadata).toEqual({ pullRequests: [], title: 'Delivery' });
+ });
+
describe('queryPage', () => {
/** Fixed, strictly-decreasing createdAt so the keyset order is deterministic. */
const seed = async (
diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.ts
index 8e3736a78c7..ee7714a39cc 100644
--- a/packages/database/src/models/acceptance.ts
+++ b/packages/database/src/models/acceptance.ts
@@ -1,5 +1,6 @@
import type {
AcceptanceCheckGroup,
+ AcceptanceMetadata,
AcceptanceStatus,
AcceptanceSubjectType,
} from '@lobechat/types';
@@ -223,7 +224,12 @@ export class AcceptanceModel {
await this.db
.update(acceptances)
.set({
- metadata,
+ // Only the title key: `existing` was read without a lock.
+ ...(nextTitle
+ ? {
+ metadata: sql`COALESCE(${acceptances.metadata}, '{}'::jsonb) || ${JSON.stringify({ title: nextTitle })}::jsonb`,
+ }
+ : {}),
projectId: nextProjectId ?? existing.projectId,
requirement: nextRequirement ?? existing.requirement,
})
@@ -349,6 +355,27 @@ export class AcceptanceModel {
return row;
};
+ /**
+ * Set some metadata keys atomically, leaving every other key as stored.
+ * Metadata holds independent slots (title, check grouping, linked pull
+ * requests) written by different paths; spreading a previously read
+ * snapshot back would drop or revert whatever another writer committed in
+ * between.
+ */
+ patchMetadata = async (
+ id: string,
+ patch: Partial<AcceptanceMetadata>,
+ ): Promise<AcceptanceItem | undefined> => {
+ const [row] = await this.db
+ .update(acceptances)
+ .set({
+ metadata: sql`COALESCE(${acceptances.metadata}, '{}'::jsonb) || ${JSON.stringify(patch)}::jsonb`,
+ })
+ .where(and(eq(acceptances.id, id), this.ownership()))
+ .returning();
+ return row;
+ };
+
/** Internal policy write counterpart to `findPolicyBySubject`. */
updatePolicy = async (
id: string,
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index d1e6cfe26eb..12a3f168798 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -169,10 +169,29 @@ export interface AcceptanceMetadata {
[key: string]: unknown;
/** Current checklist organization; frozen plans, results and reviews keep their original IDs. */
checkGrouping?: { groups: AcceptanceCheckGroup[]; version: number };
+ /**
+ * Pull requests linked by hand (`lh acceptance link-pr`, or ingest finding
+ * one). Display-only claims: nothing is verified against the provider, so
+ * they never drive merge β†’ accepted. That stays with provider-verified
+ * `scm_change_requests` rows, which take precedence when both name a PR.
+ */
+ pullRequests?: AcceptancePullRequestLink[];
/** User-set display-title override for the acceptance (sidebar rename). */
title?: string;
}
+/** A hand-linked pull request on an acceptance. */
+export interface AcceptancePullRequestLink {
+ /** When it was linked (ISO 8601). */
+ linkedAt: string;
+ number: number;
+ provider: 'github';
+ /** `owner/name` as pasted; compare case-insensitively. */
+ repoFullName: string;
+ title?: string;
+ url: string;
+}
+
/**
* The user's per-check verdict on the acceptance union. `accept` and `ignore`
* are sticky β€” both settle the check across later rounds; `reject` binds to
diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx
index 9fe575a5527..4d1030cd00f 100644
--- a/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx
+++ b/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx
@@ -1,9 +1,8 @@
'use client';
-import { Flexbox, Icon } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Avatar, Text } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { GitPullRequest } from 'lucide-react';
+import { createStaticStyles, cssVar } from 'antd-style';
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,6 +10,7 @@ import { useAcceptanceScope } from '../AcceptanceScope';
import { acceptanceCodingScope } from '../History/codingScope';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
import AcceptanceStatusPill from './AcceptanceStatusPill';
+import PullRequestLinks from './PullRequestLinks';
const styles = createStaticStyles(({ css }) => ({
titleRow: css`
@@ -43,15 +43,6 @@ const styles = createStaticStyles(({ css }) => ({
font-size: 13px;
color: ${cssVar.colorTextSecondary};
`,
- scopeLink: css`
- cursor: pointer;
- color: ${cssVar.colorTextSecondary};
-
- &:hover {
- color: ${cssVar.colorText};
- text-decoration: underline;
- }
- `,
}));
interface AcceptanceIdentityProps {
@@ -86,10 +77,8 @@ const AcceptanceIdentity = ({ focusSlot, statusSlot, topicSlot }: AcceptanceIden
const { data } = useAcceptanceBundle(acceptanceId);
if (!data) return null;
- const { acceptance, author, origin, rounds, subject } = data;
+ const { acceptance, author, origin, pullRequests, rounds, subject } = data;
const authorName = author?.fullName || author?.username;
- const scope = acceptanceCodingScope(rounds);
- const pullRequest = scope?.pullRequest;
const originAgent = embedded ? null : origin?.agent;
const agentName = originAgent?.title ?? t('acceptance.origin.agentFallback');
@@ -132,25 +121,10 @@ const AcceptanceIdentity = ({ focusSlot, statusSlot, topicSlot }: AcceptanceIden
</Flexbox>
)}
{topicSlot}
- {pullRequest?.number ? (
- pullRequest.url ? (
- <a
- className={cx(styles.scopeLink)}
- href={pullRequest.url}
- rel={'noreferrer'}
- target={'_blank'}
- title={pullRequest.title ?? pullRequest.url}
- >
- <Flexbox horizontal align={'center'} gap={4}>
- <Icon icon={GitPullRequest} size={13} /> #{pullRequest.number}
- </Flexbox>
- </a>
- ) : (
- <Flexbox horizontal align={'center'} gap={4}>
- <Icon icon={GitPullRequest} size={13} /> #{pullRequest.number}
- </Flexbox>
- )
- ) : null}
+ <PullRequestLinks
+ fallback={acceptanceCodingScope(rounds)?.pullRequest}
+ pullRequests={pullRequests}
+ />
</Flexbox>
</Flexbox>
);
diff --git a/src/features/Acceptance/Viewer/Header/PullRequestLinks.tsx b/src/features/Acceptance/Viewer/Header/PullRequestLinks.tsx
new file mode 100644
index 00000000000..a6421456e11
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Header/PullRequestLinks.tsx
@@ -0,0 +1,104 @@
+'use client';
+
+import type { VerifyCodingPullRequest } from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import {
+ GitMerge,
+ GitPullRequest,
+ GitPullRequestClosed,
+ GitPullRequestDraft,
+ type LucideIcon,
+} from 'lucide-react';
+import { memo } from 'react';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+const styles = createStaticStyles(({ css }) => ({
+ link: css`
+ cursor: pointer;
+ color: ${cssVar.colorTextSecondary};
+
+ &:hover {
+ color: ${cssVar.colorText};
+ text-decoration: underline;
+ }
+ `,
+}));
+
+type PullRequest = AcceptanceBundle['pullRequests'][number];
+
+const stateIcon = (pullRequest: PullRequest): { color?: string; icon: LucideIcon } => {
+ if (pullRequest.state === 'merged') return { color: cssVar.purple, icon: GitMerge };
+ if (pullRequest.state === 'closed')
+ return { color: cssVar.colorError, icon: GitPullRequestClosed };
+ if (pullRequest.isDraft) return { icon: GitPullRequestDraft };
+ // A hand link nobody has reported a lifecycle for: no colour to claim.
+ if (!pullRequest.state) return { icon: GitPullRequest };
+ return { color: cssVar.colorSuccess, icon: GitPullRequest };
+};
+
+interface PullRequestLinksProps {
+ /** What a round recorded at ingest; only shown for acceptances with no linked pull request. */
+ fallback?: VerifyCodingPullRequest;
+ pullRequests: AcceptanceBundle['pullRequests'];
+}
+
+/**
+ * The pull requests that deliver this acceptance. Stacked pull requests share
+ * one acceptance, so this is a list; each carries its lifecycle in its icon,
+ * the way GitHub draws it, because "is it merged yet" is the question a
+ * reader brings to this row.
+ */
+const PullRequestLinks = memo<PullRequestLinksProps>(({ pullRequests, fallback }) => {
+ if (pullRequests.length > 0)
+ return (
+ <>
+ {pullRequests.map((pullRequest) => {
+ const { color, icon } = stateIcon(pullRequest);
+ return (
+ <a
+ className={styles.link}
+ href={pullRequest.url}
+ key={pullRequest.url}
+ rel={'noreferrer'}
+ target={'_blank'}
+ title={
+ pullRequest.title
+ ? `${pullRequest.repoFullName}#${pullRequest.number} ${pullRequest.title}`
+ : `${pullRequest.repoFullName}#${pullRequest.number}`
+ }
+ >
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon color={color} icon={icon} size={13} /> #{pullRequest.number}
+ </Flexbox>
+ </a>
+ );
+ })}
+ </>
+ );
+
+ if (!fallback?.number) return null;
+ const label = (
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon icon={GitPullRequest} size={13} /> #{fallback.number}
+ </Flexbox>
+ );
+ return fallback.url ? (
+ <a
+ className={styles.link}
+ href={fallback.url}
+ rel={'noreferrer'}
+ target={'_blank'}
+ title={fallback.title ?? fallback.url}
+ >
+ {label}
+ </a>
+ ) : (
+ label
+ );
+});
+
+PullRequestLinks.displayName = 'PullRequestLinks';
+
+export default PullRequestLinks;