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.

πŸ› fix(acceptance): let a hand-linked PR accept its acceptance on merge (#21607)

Arvin Xu9deed6c96b44
diff --git a/apps/server/src/routers/lambda/acceptance/deliveryLinks.ts b/apps/server/src/routers/lambda/acceptance/deliveryLinks.ts
index 1ee04ddf436..f0a37880834 100644
--- a/apps/server/src/routers/lambda/acceptance/deliveryLinks.ts
+++ b/apps/server/src/routers/lambda/acceptance/deliveryLinks.ts
@@ -5,11 +5,7 @@ import { VerifyRunModel } from '@/database/models/verifyRun';
import { router } from '@/libs/trpc/lambda';
import { notifyAcceptance } from '@/server/services/acceptanceReview/events';
import { parseChangeRequestUrl } from '@/server/services/scm/changeRequestUrl';
-import {
- addPullRequestLink,
- removePullRequestLink,
- updateAcceptancePullRequests,
-} from '@/server/services/verify/acceptancePullRequests';
+import { linkHandPullRequest, unlinkHandPullRequest } from '@/server/services/scm/handLink';
import { previewUrlSchema, recordPreviewUrl } from '../_helpers/acceptancePreviewUrl';
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
@@ -54,10 +50,11 @@ export const deliveryLinksRouter = router({
* 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.
+ * Stored on the acceptance, because the PR may not have reached us yet.
+ * When the provider row already exists in the acceptance's own tenant it
+ * is bound too, so the merge accepts this delivery (right away, if the PR
+ * is already merged). The row is keyed globally, so a row in another
+ * tenant is never claimed β€” a pasted URL stays display-only there.
*/
linkPullRequest: acceptanceWriteProcedure
.input(
@@ -78,9 +75,7 @@ export const deliveryLinksRouter = router({
});
}
- await updateAcceptancePullRequests(ctx.serverDB, acceptance.id, (links) =>
- addPullRequestLink(links, parsed, input.title),
- );
+ await linkHandPullRequest(ctx.serverDB, acceptance, parsed, input.title);
return parsed;
}),
unlinkPullRequest: acceptanceWriteProcedure
@@ -88,12 +83,10 @@ export const deliveryLinksRouter = router({
.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) {
+ const unlinked = parsed
+ ? await unlinkHandPullRequest(ctx.serverDB, acceptance, parsed)
+ : false;
+ if (!unlinked) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Linked pull request not found' });
}
diff --git a/apps/server/src/services/scm/ScmControlService.ts b/apps/server/src/services/scm/ScmControlService.ts
index ec3ff01586b..fba5fcb1e25 100644
--- a/apps/server/src/services/scm/ScmControlService.ts
+++ b/apps/server/src/services/scm/ScmControlService.ts
@@ -96,6 +96,27 @@ export class ScmControlService {
return outcome;
};
+ /**
+ * A change request just got its acceptance from a hand link, outside any
+ * provider event. Catch it up on what it missed: a PR already merged
+ * accepts now, an open one gets its tracking comment.
+ */
+ onAcceptanceLinked = async (row: ScmChangeRequestItem): Promise<ScmControlOutcome> => {
+ if (!(await this.ownerCanStillWrite(row))) {
+ return { detail: 'owner can no longer write to this workspace', outcome: 'skipped' };
+ }
+ if (row.state === 'merged') {
+ if (!(await this.isEnabled(row, 'acceptOnMerge'))) {
+ return { detail: 'acceptOnMerge is off', outcome: 'skipped' };
+ }
+ const outcome = await this.onMerged(row);
+ await this.refreshComment(row.id);
+ return outcome;
+ }
+ if (row.state === 'open') return this.syncComment(row);
+ return { detail: `${row.state} needs no action`, outcome: 'skipped' };
+ };
+
private route = async ({ event, kind, row }: ScmControlEvent): Promise<ScmControlOutcome> => {
switch (kind) {
case 'opened':
@@ -381,7 +402,21 @@ export class ScmControlService {
};
}
- const service = new AcceptanceService(this.db, row.userId, row.workspaceId ?? undefined);
+ // Bound to the acceptance's owner, not the row's: a hand link joins a PR
+ // to a teammate's delivery, and a private one is invisible to a service
+ // bound to the PR author. The author is still who the merge is credited to.
+ const [acceptance] = await this.db
+ .select({ userId: acceptances.userId, workspaceId: acceptances.workspaceId })
+ .from(acceptances)
+ .where(eq(acceptances.id, row.acceptanceId));
+ if (!acceptance) return { detail: 'acceptance no longer exists', outcome: 'skipped' };
+
+ const service = new AcceptanceService(
+ this.db,
+ acceptance.userId,
+ acceptance.workspaceId ?? undefined,
+ { actorUserId: row.userId },
+ );
const accepted = await service.acceptFromScmMerge(row.acceptanceId, {
mergedByExternalId: row.mergedByExternalId ?? undefined,
number: row.number,
diff --git a/apps/server/src/services/scm/__tests__/handLink.test.ts b/apps/server/src/services/scm/__tests__/handLink.test.ts
new file mode 100644
index 00000000000..77356def830
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/handLink.test.ts
@@ -0,0 +1,235 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ScmChangeRequestModel } from '@/database/models/scm';
+import { acceptances, users, verifyRuns, workspaceMembers, workspaces } from '@/database/schemas';
+
+import { parseChangeRequestUrl } from '../changeRequestUrl';
+import {
+ bindHandLinkedChangeRequest,
+ catchUpHandLinkedChangeRequest,
+ linkHandPullRequest,
+ unlinkHandPullRequest,
+} from '../handLink';
+
+const mocks = vi.hoisted(() => ({ postComment: vi.fn(), updateComment: vi.fn() }));
+
+vi.mock('../github/app', () => ({
+ fetchGitHubJobLogTail: vi.fn(),
+ fetchGitHubReviewFeedback: vi.fn(),
+ postGitHubPullRequestComment: mocks.postComment,
+ updateGitHubPullRequestComment: mocks.updateComment,
+}));
+vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => ({ set: vi.fn(async () => 'OK') }),
+}));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.test/' } }));
+vi.mock('@/server/workflows/expertiseRejection', () => ({
+ ExpertiseRejectionWorkflow: { trigger: vi.fn(async () => {}) },
+}));
+
+const serverDB = await getTestDB();
+const author = 'scm-hand-link-author';
+const bot = 'scm-hand-link-bot';
+const pr = parseChangeRequestUrl('https://github.com/lobehub/lobehub/pull/21560')!;
+
+let workspaceId: string;
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: author }, { id: bot }]);
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'ws', primaryOwnerId: bot, slug: 'scm-hand-link-ws' })
+ .returning();
+ workspaceId = workspace.id;
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId: bot, workspaceId },
+ { role: 'member', userId: author, workspaceId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
+ vi.clearAllMocks();
+});
+
+/** A private delivery the bot owns, with one round still waiting on a verdict. */
+const botAcceptance = async (subjectId = 's') => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({
+ status: 'delivered',
+ subjectId,
+ subjectType: 'standalone',
+ userId: bot,
+ visibility: 'private',
+ workspaceId,
+ })
+ .returning();
+ await serverDB
+ .insert(verifyRuns)
+ .values({ acceptanceId: acceptance.id, roundIndex: 1, userId: bot, workspaceId });
+ return acceptance;
+};
+
+/** The provider row for the PR, routed to its author as the webhook does. */
+const authorRow = (state: 'merged' | 'open', rowWorkspaceId: string | null = workspaceId) =>
+ ScmChangeRequestModel.upsert(serverDB, {
+ metadata: { routedBy: 'author' },
+ number: pr.number,
+ provider: 'github',
+ repoFullName: pr.repoFullName,
+ state,
+ url: pr.url,
+ userId: author,
+ workspaceId: rowWorkspaceId,
+ });
+
+const statusOf = async (id: string) =>
+ (await serverDB.select().from(acceptances).where(eq(acceptances.id, id)))[0].status;
+
+describe('hand-linked pull requests', () => {
+ it("accepts a teammate's delivery when its PR was merged before the link", async () => {
+ const acceptance = await botAcceptance();
+ const row = await authorRow('merged');
+
+ await linkHandPullRequest(serverDB, acceptance, pr);
+
+ expect(await statusOf(acceptance.id)).toBe('accepted');
+ const [run] = await serverDB
+ .select()
+ .from(verifyRuns)
+ .where(eq(verifyRuns.acceptanceId, acceptance.id));
+ expect(run.userDecision).toBe('accept');
+ expect(run.decisionDetail).toMatchObject({ decidedBy: author, source: 'scm_merge' });
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBe(
+ acceptance.id,
+ );
+ });
+
+ it('binds an open PR so its later merge accepts, and unlinking undoes it', async () => {
+ const acceptance = await botAcceptance();
+ const row = await authorRow('open');
+
+ await linkHandPullRequest(serverDB, acceptance, pr);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBe(
+ acceptance.id,
+ );
+ expect(await statusOf(acceptance.id)).toBe('delivered');
+
+ expect(await unlinkHandPullRequest(serverDB, acceptance, pr)).toBe(true);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBeNull();
+ });
+
+ it('matches the row whatever casing the pasted URL uses', async () => {
+ const acceptance = await botAcceptance();
+ const row = await authorRow('open');
+ const shouted = parseChangeRequestUrl('https://github.com/LobeHub/LobeHub/pull/21560')!;
+
+ await linkHandPullRequest(serverDB, acceptance, shouted);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBe(
+ acceptance.id,
+ );
+
+ expect(await unlinkHandPullRequest(serverDB, acceptance, shouted)).toBe(true);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBeNull();
+ });
+
+ it('does not accept on a catch-up an unlink overtook', async () => {
+ // A link binds and commits; before its catch-up runs, an unlink removes
+ // the link and the binding. The stale catch-up must not accept.
+ const acceptance = await botAcceptance();
+ const row = await authorRow('merged');
+ const rowId = await bindHandLinkedChangeRequest(serverDB, acceptance, pr);
+ expect(rowId).toBe(row.id);
+ await serverDB
+ .update(acceptances)
+ .set({ metadata: { pullRequests: [{ ...pr, linkedAt: new Date().toISOString() }] } })
+ .where(eq(acceptances.id, acceptance.id));
+ expect(await unlinkHandPullRequest(serverDB, acceptance, pr)).toBe(true);
+
+ await catchUpHandLinkedChangeRequest(serverDB, acceptance.id, row.id);
+
+ expect(await statusOf(acceptance.id)).toBe('delivered');
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBeNull();
+ });
+
+ it('never claims a row in another tenant or one that names another acceptance', async () => {
+ const acceptance = await botAcceptance();
+
+ // Routed to the author's personal scope: not the acceptance's workspace.
+ const personal = await authorRow('merged', null);
+ expect(await bindHandLinkedChangeRequest(serverDB, acceptance, pr)).toBeNull();
+ expect((await ScmChangeRequestModel.findById(serverDB, personal.id))?.acceptanceId).toBeNull();
+
+ // Back in the workspace, but already delivering a different acceptance.
+ const other = await botAcceptance('s-2');
+ await ScmChangeRequestModel.upsert(serverDB, {
+ links: { acceptanceId: other.id },
+ number: pr.number,
+ provider: 'github',
+ repoFullName: pr.repoFullName,
+ state: 'merged',
+ url: pr.url,
+ userId: author,
+ workspaceId,
+ });
+ expect(await bindHandLinkedChangeRequest(serverDB, acceptance, pr)).toBeNull();
+ expect(await statusOf(acceptance.id)).toBe('delivered');
+ });
+
+ it('lets only one of two acceptances claiming the same PR at once win', async () => {
+ const first = await botAcceptance();
+ const second = await botAcceptance('s-2');
+ const row = await authorRow('open');
+
+ const claims = await Promise.all([
+ bindHandLinkedChangeRequest(serverDB, first, pr),
+ bindHandLinkedChangeRequest(serverDB, second, pr),
+ ]);
+
+ const holder = (await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId;
+ expect(claims.filter(Boolean)).toHaveLength(1);
+ expect([first.id, second.id]).toContain(holder);
+ // Both read the row as free before either wrote; the loser must not overwrite.
+ expect(
+ await ScmChangeRequestModel.claimAcceptance(
+ serverDB,
+ row.id,
+ holder === first.id ? second.id : first.id,
+ ),
+ ).toBeNull();
+ });
+
+ it("links the delivery, never the subject's conversation, so unlinking leaves nothing", async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({
+ status: 'delivered',
+ subjectId: 'tpc_bot_conversation',
+ subjectType: 'topic',
+ userId: bot,
+ workspaceId,
+ })
+ .returning();
+ const row = await authorRow('open');
+
+ await linkHandPullRequest(serverDB, acceptance, pr);
+ const bound = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(bound?.acceptanceId).toBe(acceptance.id);
+ expect(bound?.topicId).toBeNull();
+
+ await unlinkHandPullRequest(serverDB, acceptance, pr);
+ const after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(after).toMatchObject({ acceptanceId: null, taskId: null, topicId: null });
+ });
+
+ it('does nothing for a PR the provider has not reported yet', async () => {
+ const acceptance = await botAcceptance();
+ expect(await bindHandLinkedChangeRequest(serverDB, acceptance, pr)).toBeNull();
+ });
+});
diff --git a/apps/server/src/services/scm/__tests__/links.test.ts b/apps/server/src/services/scm/__tests__/links.test.ts
index f62dec7ae7c..30d349adaad 100644
--- a/apps/server/src/services/scm/__tests__/links.test.ts
+++ b/apps/server/src/services/scm/__tests__/links.test.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
acceptances,
+ scmChangeRequests,
scmIdentities,
topics,
users,
@@ -345,6 +346,118 @@ describe('resolveChangeRequestLinks', () => {
expect(resolved.links.topicId).toBeUndefined();
});
+ it("finds a teammate's hand link in a workspace the author can write to", async () => {
+ // A bot verified the delivery and linked the PR; a person opened it.
+ const workspace = await workspaceWith('scm-links-hand-ws', otherUserId);
+ const handLink = {
+ linkedAt: new Date().toISOString(),
+ number: 19_719,
+ provider: 'github' as const,
+ repoFullName: 'LobeHub/LobeHub',
+ url: 'https://github.com/LobeHub/LobeHub/pull/19719',
+ };
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ title: 't', userId: otherUserId })
+ .returning();
+ await serverDB.insert(acceptances).values({
+ id: acceptanceId,
+ metadata: { pullRequests: [handLink] },
+ subjectId: topic.id,
+ subjectType: 'topic' as const,
+ userId: otherUserId,
+ workspaceId: workspace.id,
+ });
+ const scope = { kind: 'author', userId } as const;
+
+ // Not a member: the link stays out of reach.
+ expect(await resolve({ ...base, scope })).toEqual({});
+
+ await serverDB
+ .insert(workspaceMembers)
+ .values({ role: 'member', userId, workspaceId: workspace.id });
+ const resolved = await resolveChangeRequestLinks(serverDB, { ...base, scope });
+ // The acceptance only: a hand link does not hand over the subject's conversation.
+ // It is flagged as hand-sourced so the model revalidates it before writing.
+ expect(resolved).toEqual({
+ links: { acceptanceId, acceptanceSource: 'hand-link' },
+ workspaceId: workspace.id,
+ });
+
+ // Another PR number in the same repository is not linked.
+ expect(await resolve({ ...base, number: 19_720, scope })).toEqual({});
+ });
+
+ it('keeps the acceptance the row already carries over a later hand link', async () => {
+ // Two acceptances list the same PR: the first claimed the row, the second
+ // was refused by `link-pr` and kept its link. The newest link must not
+ // decide what a merge accepts.
+ const workspace = await workspaceWith('scm-links-claimed-ws', userId);
+ // One acceptance per subject, so the two links sit on different topics.
+ const [claimedTopic, laterTopic] = await serverDB
+ .insert(topics)
+ .values([
+ { title: 'claimed', userId },
+ { title: 'later', userId },
+ ])
+ .returning();
+ const laterId = '11111111-2222-4333-8444-555555555555';
+ const handLink = (at: string) => ({
+ linkedAt: at,
+ number: 19_719,
+ provider: 'github' as const,
+ repoFullName: 'lobehub/lobehub',
+ url: 'https://github.com/lobehub/lobehub/pull/19719',
+ });
+
+ await serverDB.insert(acceptances).values([
+ {
+ id: acceptanceId,
+ metadata: { pullRequests: [handLink('2026-10-01T00:00:00.000Z')] },
+ subjectId: claimedTopic.id,
+ subjectType: 'topic' as const,
+ updatedAt: new Date('2026-10-01T00:00:00.000Z'),
+ userId,
+ workspaceId: workspace.id,
+ },
+ {
+ id: laterId,
+ metadata: { pullRequests: [handLink('2026-10-20T00:00:00.000Z')] },
+ subjectId: laterTopic.id,
+ subjectType: 'topic' as const,
+ updatedAt: new Date('2026-10-20T00:00:00.000Z'),
+ userId,
+ workspaceId: workspace.id,
+ },
+ ]);
+ await serverDB.insert(scmChangeRequests).values({
+ acceptanceId,
+ number: 19_719,
+ provider: 'github',
+ repoFullName: 'lobehub/lobehub',
+ state: 'open',
+ url: base.url,
+ userId,
+ workspaceId: workspace.id,
+ });
+
+ const scope = { kind: 'author', userId } as const;
+ const resolved = await resolveChangeRequestLinks(serverDB, { ...base, scope });
+
+ // The row's own binding, echoed: the model lets the locked row decide.
+ expect(resolved).toEqual({
+ links: { acceptanceId, acceptanceSource: 'row-binding' },
+ workspaceId: workspace.id,
+ });
+
+ // With the binding gone the remaining link takes over again.
+ await serverDB.update(scmChangeRequests).set({ acceptanceId: null });
+ expect(await resolve({ ...base, scope })).toEqual({
+ acceptanceId: laterId,
+ acceptanceSource: 'hand-link',
+ });
+ });
+
it('returns nothing when no source matches', async () => {
expect(await resolve(base)).toEqual({});
});
diff --git a/apps/server/src/services/scm/handLink.ts b/apps/server/src/services/scm/handLink.ts
new file mode 100644
index 00000000000..e3299130c76
--- /dev/null
+++ b/apps/server/src/services/scm/handLink.ts
@@ -0,0 +1,128 @@
+import debug from 'debug';
+
+import { ScmChangeRequestModel } from '@/database/models/scm';
+import type { AcceptanceItem, ScmChangeRequestItem } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import {
+ addPullRequestLink,
+ removePullRequestLink,
+ updateAcceptancePullRequests,
+} from '@/server/services/verify/acceptancePullRequests';
+
+import type { ParsedChangeRequestUrl } from './changeRequestUrl';
+import { ScmControlService } from './ScmControlService';
+
+const log = debug('lobe-server:scm:hand-link');
+
+type LinkableAcceptance = Pick<AcceptanceItem, 'id' | 'userId' | 'workspaceId'>;
+
+/**
+ * A hand link may only claim a provider row that lives in the acceptance's
+ * own tenant: the same workspace, or the same person's personal scope. The
+ * row is keyed globally, so a pasted URL must not reach into someone else's.
+ */
+const sameTenant = (row: ScmChangeRequestItem, acceptance: LinkableAcceptance) =>
+ acceptance.workspaceId
+ ? row.workspaceId === acceptance.workspaceId
+ : !row.workspaceId && row.userId === acceptance.userId;
+
+/** The URL was pasted by a person, so its owner/repo casing may differ from GitHub's. */
+const findRow = (db: LobeChatDatabase, pr: ParsedChangeRequestUrl) =>
+ ScmChangeRequestModel.findByIdentityIgnoringCase(db, 'github', pr.repoFullName, pr.number);
+
+/**
+ * Give the provider row of a hand-linked PR its acceptance, so a merge
+ * accepts the delivery the same way a body link would. A row that already
+ * names an acceptance keeps it. Returns the bound row's id.
+ *
+ * Run it inside the transaction that writes the hand link (see
+ * {@link linkHandPullRequest}), so it is serialized with an unlink.
+ *
+ * A PR the provider has not reported yet has no row; its first event finds
+ * the hand link itself (see `resolveChangeRequestLinks`).
+ */
+export const bindHandLinkedChangeRequest = async (
+ db: LobeChatDatabase,
+ acceptance: LinkableAcceptance,
+ pr: ParsedChangeRequestUrl,
+): Promise<string | null> => {
+ const row = await findRow(db, pr);
+ if (!row || !sameTenant(row, acceptance)) return null;
+
+ // Conditional on the row still being free: another acceptance may be
+ // claiming the same PR right now, under a lock on its own row, not ours.
+ // The subject's conversation is deliberately not linked: a hand link says
+ // which delivery the PR closes, not whose conversation its CI failures and
+ // reviews should wake, and an unlink must leave nothing behind.
+ const bound = await ScmChangeRequestModel.claimAcceptance(db, row.id, acceptance.id);
+ return bound?.id ?? null;
+};
+
+/** Undo {@link bindHandLinkedChangeRequest} when the hand link is removed. */
+export const unbindHandLinkedChangeRequest = async (
+ db: LobeChatDatabase,
+ acceptance: LinkableAcceptance,
+ pr: ParsedChangeRequestUrl,
+): Promise<void> => {
+ const row = await findRow(db, pr);
+ if (row?.acceptanceId === acceptance.id) {
+ await ScmChangeRequestModel.detachAcceptance(db, row.id, acceptance.id);
+ }
+};
+
+/**
+ * Catch a freshly bound row up on what it missed: a PR already merged
+ * accepts now, an open one gets its tracking comment. Runs after the link
+ * commits β€” it may call the provider β€” so it re-reads the row and does
+ * nothing if an unlink got in between.
+ */
+export const catchUpHandLinkedChangeRequest = async (
+ db: LobeChatDatabase,
+ acceptanceId: string,
+ rowId: string,
+): Promise<void> => {
+ const row = await ScmChangeRequestModel.findById(db, rowId);
+ if (row?.acceptanceId !== acceptanceId) return;
+
+ // Must not fail the link the user asked for; the next provider event retries it.
+ try {
+ const outcome = await new ScmControlService(db).onAcceptanceLinked(row);
+ log('%s#%d bound to %s -> %o', row.repoFullName, row.number, acceptanceId, outcome);
+ } catch (error) {
+ log('catch-up for %s#%d failed: %O', row.repoFullName, row.number, error);
+ }
+};
+
+/** Record a hand link and bind its provider row in one serialized write, then catch up. */
+export const linkHandPullRequest = async (
+ db: LobeChatDatabase,
+ acceptance: LinkableAcceptance,
+ pr: ParsedChangeRequestUrl,
+ title?: string,
+): Promise<void> => {
+ let rowId: string | null = null;
+ await updateAcceptancePullRequests(
+ db,
+ acceptance.id,
+ (links) => addPullRequestLink(links, pr, title),
+ async (tx) => {
+ rowId = await bindHandLinkedChangeRequest(tx, acceptance, pr);
+ },
+ );
+ if (rowId) await catchUpHandLinkedChangeRequest(db, acceptance.id, rowId);
+};
+
+/** Remove a hand link and its provider binding together. `false` when it was not linked. */
+export const unlinkHandPullRequest = async (
+ db: LobeChatDatabase,
+ acceptance: LinkableAcceptance,
+ pr: ParsedChangeRequestUrl,
+): Promise<boolean> => {
+ const links = await updateAcceptancePullRequests(
+ db,
+ acceptance.id,
+ (current) => removePullRequestLink(current, pr),
+ (tx) => unbindHandLinkedChangeRequest(tx, acceptance, pr),
+ );
+ return links !== null;
+};
diff --git a/apps/server/src/services/scm/links.ts b/apps/server/src/services/scm/links.ts
index cbb5ae894c1..47e08ec0fc1 100644
--- a/apps/server/src/services/scm/links.ts
+++ b/apps/server/src/services/scm/links.ts
@@ -2,7 +2,13 @@ import type { ScmChangeRequestLinks } from '@lobechat/types';
import { and, desc, eq, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm';
import { ScmIdentityModel } from '@/database/models/scm';
-import { acceptances, verifyRuns, works, workspaceMembers } from '@/database/schemas';
+import {
+ acceptances,
+ scmChangeRequests,
+ verifyRuns,
+ works,
+ workspaceMembers,
+} from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { SCM_WRITE_ROLES } from './scope';
@@ -17,6 +23,10 @@ import { SCM_WRITE_ROLES } from './scope';
* (`works.resourceId = owner/repo#number`). Gives topic + agent.
* 3. The acceptance round that recorded this PR url in its coding context
* (`verify_runs.context.pullRequest.url`), written by `lh acceptance run ingest`.
+ * 4. The acceptance this PR was linked to by hand (`lh acceptance link-pr`,
+ * stored in `acceptances.metadata.pullRequests`). The acceptance already
+ * bound to the row wins over the newest link, so a link that lost the
+ * claim cannot decide what a later merge accepts.
*
* Every source is fenced, because a PR body can name any acceptance id and
* without a fence a merge on an attacker's repository would accept someone
@@ -165,6 +175,46 @@ const inScope = (
)!;
};
+/**
+ * Like {@link inScope}, but for records any writer in a workspace may own. An
+ * author reaches their personal records and every workspace record where
+ * they hold a write role, whoever created it; an installation reaches its
+ * own tenant, as before.
+ */
+const inTenantScope = (
+ db: LobeChatDatabase,
+ table: { userId: SQL.Aliased | any; workspaceId: any },
+ scope: ScmLinkScope,
+ pin: ScopePin,
+): SQL => {
+ if (scope.kind !== 'author') return inScope(db, table, scope, pin);
+
+ const pinned =
+ pin === undefined
+ ? undefined
+ : pin === null
+ ? isNull(table.workspaceId)
+ : eq(table.workspaceId, pin);
+ const memberOf = db
+ .select({ workspaceId: workspaceMembers.workspaceId })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.userId, scope.userId),
+ isNull(workspaceMembers.deletedAt),
+ inArray(workspaceMembers.role, [...SCM_WRITE_ROLES]),
+ ),
+ );
+
+ return and(
+ or(
+ and(eq(table.userId, scope.userId), isNull(table.workspaceId)),
+ inArray(table.workspaceId, memberOf),
+ ),
+ pinned,
+ )!;
+};
+
export const resolveChangeRequestLinks = async (
db: LobeChatDatabase,
params: ResolveLinksParams,
@@ -245,5 +295,75 @@ export const resolveChangeRequestLinks = async (
}
}
+ // 4. The acceptance this PR was linked to by hand. The link names the
+ // delivery from the acceptance side, so it is often written by someone
+ // other than the PR's author β€” a bot verifies, a person opens the PR. The
+ // fence is the tenant rather than the creator: a workspace acceptance the
+ // author can write to, or the author's own personal one. It contributes
+ // the acceptance only, not its subject's conversation: the link says which
+ // delivery the PR closes, not whose agent its failures should wake, and
+ // removing it must leave nothing behind on the row.
+ if (!links.acceptanceId) {
+ // A link can outlive its claim: a second `link-pr` is refused while the
+ // row already names another acceptance, but its metadata keeps the link,
+ // so it stays resolvable here. The binding on the row outranks it β€”
+ // otherwise whichever acceptance was touched last would decide what a
+ // merge accepts, and a delivery could change hands without an unlink.
+ const [bound] = await db
+ .select({ acceptanceId: scmChangeRequests.acceptanceId })
+ .from(scmChangeRequests)
+ .where(
+ and(
+ eq(scmChangeRequests.provider, 'github'),
+ sql`lower(${scmChangeRequests.repoFullName}) = ${params.repoFullName.toLowerCase()}`,
+ eq(scmChangeRequests.number, params.number),
+ isNotNull(scmChangeRequests.acceptanceId),
+ ),
+ )
+ .limit(1);
+
+ if (bound?.acceptanceId) {
+ const [boundRow] = await db
+ .select({ id: acceptances.id, workspaceId: acceptances.workspaceId })
+ .from(acceptances)
+ .where(
+ and(
+ eq(acceptances.id, bound.acceptanceId),
+ inTenantScope(db, acceptances, params.scope, pin),
+ ),
+ )
+ .limit(1);
+ if (boundRow) {
+ links.acceptanceId = boundRow.id;
+ // Read before the row lock the model writes under, so it is only an
+ // echo of what the row carried β€” the model lets the row decide.
+ links.acceptanceSource = 'row-binding';
+ pin ??= boundRow.workspaceId ?? null;
+ }
+ }
+ }
+
+ if (!links.acceptanceId) {
+ const linkedPullRequest = sql`EXISTS (
+ SELECT 1 FROM jsonb_array_elements(COALESCE(${acceptances.metadata} -> 'pullRequests', '[]'::jsonb)) AS pr
+ WHERE pr ->> 'provider' = 'github'
+ AND pr ->> 'number' = ${String(params.number)}
+ AND lower(pr ->> 'repoFullName') = ${params.repoFullName.toLowerCase()}
+ )`;
+ const [row] = await db
+ .select({ id: acceptances.id, workspaceId: acceptances.workspaceId })
+ .from(acceptances)
+ .where(and(linkedPullRequest, inTenantScope(db, acceptances, params.scope, pin)))
+ .orderBy(desc(acceptances.updatedAt))
+ .limit(1);
+ if (row) {
+ links.acceptanceId = row.id;
+ // This one is read under no lock of its own, so the model revalidates it
+ // against the hand link before writing it onto the row.
+ links.acceptanceSource = 'hand-link';
+ pin ??= row.workspaceId ?? null;
+ }
+ }
+
return { links, workspaceId: pin ?? null };
};
diff --git a/apps/server/src/services/verify/acceptancePullRequests.ts b/apps/server/src/services/verify/acceptancePullRequests.ts
index cd128888e17..1d2f47eef98 100644
--- a/apps/server/src/services/verify/acceptancePullRequests.ts
+++ b/apps/server/src/services/verify/acceptancePullRequests.ts
@@ -56,6 +56,12 @@ export const updateAcceptancePullRequests = async (
db: LobeChatDatabase,
acceptanceId: string,
update: (links: AcceptancePullRequestLink[] | undefined) => AcceptancePullRequestLink[] | null,
+ /**
+ * Writes that must move with the links, run in the same transaction under
+ * the same row lock β€” so an overlapping link and unlink of one PR cannot
+ * leave the links and those writes disagreeing.
+ */
+ alongside?: (tx: LobeChatDatabase) => Promise<void>,
): Promise<AcceptancePullRequestLink[] | null> =>
db.transaction(async (tx) => {
const [row] = await tx
@@ -74,6 +80,7 @@ export const updateAcceptancePullRequests = async (
updatedAt: new Date(),
})
.where(eq(acceptances.id, acceptanceId));
+ await alongside?.(tx as unknown as LobeChatDatabase);
return next;
});
diff --git a/packages/database/src/models/scm/__tests__/changeRequest.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
index 57297321123..cde0bde4b3b 100644
--- a/packages/database/src/models/scm/__tests__/changeRequest.test.ts
+++ b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
@@ -641,6 +641,53 @@ describe('ScmChangeRequestModel', () => {
await serverDB.delete(users).where(eq(users.id, otherUser));
});
+ it('claims a hand-linked acceptance only while the hand link is still there', async () => {
+ const [linked, unlinked] = await serverDB
+ .insert(acceptances)
+ .values([
+ {
+ metadata: {
+ pullRequests: [{ number: 7, provider: 'github', repoFullName: 'lobehub/lobehub' }],
+ },
+ subjectId: 'linked',
+ subjectType: 'standalone',
+ userId,
+ },
+ { subjectId: 'unlinked', subjectType: 'standalone', userId },
+ ])
+ .returning();
+
+ // The resolver read the link while it stood; nothing unlinked it here.
+ const bound = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { acceptanceId: linked.id, acceptanceSource: 'hand-link' },
+ });
+ expect(bound.acceptanceId).toBe(linked.id);
+
+ // This delivery read the link before the unlink committed. Applying the
+ // snapshot would put the removed binding back, and the merge after it
+ // would accept a delivery the pull request no longer leads to.
+ const raced = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { acceptanceId: unlinked.id, acceptanceSource: 'hand-link' },
+ number: 8,
+ url: 'https://github.com/lobehub/lobehub/pull/8',
+ });
+ expect(raced.acceptanceId).toBeNull();
+ });
+
+ it('never lets a row-binding echo revive a binding the row has lost', async () => {
+ // The resolver read the row before this transaction opened, so it echoed
+ // the acceptance the row carried then. The row here β€” as locked inside
+ // the write β€” no longer carries it: an unlink committed in between.
+ const echoed = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { acceptanceId: '11111111-2222-4333-8444-555555555555', acceptanceSource: 'row-binding' },
+ });
+
+ expect(echoed.acceptanceId).toBeNull();
+ });
+
it('replays the loser of a first-insert race under the lock instead of overwriting', async () => {
const otherUser = 'scm-model-user-race';
await serverDB.insert(users).values({ id: otherUser });
diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.ts
index b61ab257629..78ba626bc70 100644
--- a/packages/database/src/models/scm/changeRequest.ts
+++ b/packages/database/src/models/scm/changeRequest.ts
@@ -9,10 +9,10 @@ import type {
ScmReviewDecision,
ScmUpsertChangeRequestParams,
} from '@lobechat/types';
-import { and, desc, eq, inArray, isNull, lt, or, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNull, lt, or, type SQL,sql } from 'drizzle-orm';
import type { ScmChangeRequestItem } from '../../schemas';
-import { scmChangeRequests, scmInstallations } from '../../schemas';
+import { acceptances, scmChangeRequests, scmInstallations } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
const ownedByScope = (scope: { userId: string; workspaceId?: string | null }) =>
@@ -153,6 +153,32 @@ export class ScmChangeRequestModel {
return row ?? null;
};
+ /**
+ * {@link findByIdentity} for a name typed by a person, e.g. a pasted PR URL:
+ * GitHub names are case-insensitive, while the row keeps the provider's
+ * canonical casing.
+ */
+ static findByIdentityIgnoringCase = async (
+ db: LobeChatDatabase,
+ provider: ScmProvider,
+ repoFullName: string,
+ number: number,
+ ): Promise<ScmChangeRequestItem | null> => {
+ const [row] = await db
+ .select()
+ .from(scmChangeRequests)
+ .where(
+ and(
+ eq(scmChangeRequests.provider, provider),
+ eq(scmChangeRequests.number, number),
+ sql`lower(${scmChangeRequests.repoFullName}) = ${repoFullName.toLowerCase()}`,
+ ),
+ )
+ .limit(1);
+
+ return row ?? null;
+ };
+
static findById = async (
db: LobeChatDatabase,
id: string,
@@ -409,13 +435,47 @@ export class ScmChangeRequestModel {
const inherited = scopeMoved ? undefined : existing;
const pick = <T>(incoming: T | null | undefined, stored: T | null | undefined): T | null =>
(stale ? (stored ?? incoming) : (incoming ?? stored)) ?? null;
- const linkValues = {
+ const linkValues: {
+ acceptanceId: string | SQL | null;
+ installationId: string | null;
+ taskId: string | null;
+ topicId: string | null;
+ workId: string | null;
+ } = {
acceptanceId: pick(links.acceptanceId, inherited?.acceptanceId),
installationId: links.installationId ?? existing?.installationId ?? null,
taskId: pick(links.taskId, inherited?.taskId),
topicId: pick(links.topicId, inherited?.topicId),
workId: pick(links.workId, inherited?.workId),
};
+
+ // Both link sources below are resolved before this transaction opens, so
+ // an unlink may have committed in between. Writing the acceptance anyway
+ // would put back a binding the user removed, and a later merge would
+ // accept a delivery from a pull request that no longer leads to it.
+ const stored = inherited?.acceptanceId ?? null;
+ if (!stale && links.acceptanceSource && links.acceptanceId) {
+ if (links.acceptanceSource === 'row-binding' && stored !== links.acceptanceId) {
+ // The resolver only echoed the binding the row carried. The locked
+ // row is the authority, and an unlink may have cleared it since.
+ linkValues.acceptanceId = stored;
+ } else if (stored !== links.acceptanceId) {
+ const handLinkHolds = sql`EXISTS (
+ SELECT 1 FROM ${acceptances} AS hand_link
+ WHERE hand_link.id = ${links.acceptanceId}::uuid
+ AND EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(
+ COALESCE(hand_link.metadata -> 'pullRequests', '[]'::jsonb)
+ ) AS pr
+ WHERE pr ->> 'provider' = ${params.provider}
+ AND pr ->> 'number' = ${String(params.number)}
+ AND lower(pr ->> 'repoFullName') = ${params.repoFullName.toLowerCase()}
+ )
+ )`;
+ linkValues.acceptanceId = sql`CASE WHEN ${handLinkHolds} THEN ${links.acceptanceId}::uuid ELSE ${stored}::uuid END`;
+ }
+ }
const ownerValues = scopeMoved
? { userId: params.userId, workspaceId: params.workspaceId ?? null }
: {};
@@ -520,6 +580,46 @@ export class ScmChangeRequestModel {
return row;
};
+ /**
+ * Point the row at `acceptanceId` unless it already names another one,
+ * decided in the UPDATE itself so two acceptances claiming the same row at
+ * once cannot overwrite each other. Only the acceptance link moves, so
+ * {@link detachAcceptance} undoes it completely. Returns the row when this
+ * acceptance holds it.
+ */
+ static claimAcceptance = async (
+ db: LobeChatDatabase,
+ id: string,
+ acceptanceId: string,
+ ): Promise<ScmChangeRequestItem | null> => {
+ const [row] = await db
+ .update(scmChangeRequests)
+ .set({ acceptanceId, updatedAt: new Date() })
+ .where(
+ and(
+ eq(scmChangeRequests.id, id),
+ or(
+ isNull(scmChangeRequests.acceptanceId),
+ eq(scmChangeRequests.acceptanceId, acceptanceId),
+ ),
+ ),
+ )
+ .returning();
+ return row ?? null;
+ };
+
+ /** Clear the acceptance link, but only while it still points at `acceptanceId`. */
+ static detachAcceptance = async (
+ db: LobeChatDatabase,
+ id: string,
+ acceptanceId: string,
+ ): Promise<void> => {
+ await db
+ .update(scmChangeRequests)
+ .set({ acceptanceId: null, updatedAt: new Date() })
+ .where(and(eq(scmChangeRequests.id, id), eq(scmChangeRequests.acceptanceId, acceptanceId)));
+ };
+
/**
* Merge check results for a commit into the row and recompute the rollup.
* Results for a commit other than the row's current head are stale (the
diff --git a/packages/types/src/scm.ts b/packages/types/src/scm.ts
index 7519da1491b..8a873b1037e 100644
--- a/packages/types/src/scm.ts
+++ b/packages/types/src/scm.ts
@@ -230,6 +230,19 @@ export interface ScmChangeRequestSnapshot {
/** The LobeHub records a change request is tied to. Only ever filled in, never cleared. */
export interface ScmChangeRequestLinks {
acceptanceId?: string | null;
+ /**
+ * Where `acceptanceId` came from, when the answer decides whether the model
+ * may write it.
+ *
+ * - `hand-link` β€” the acceptance's own `metadata.pullRequests`. Resolved
+ * outside the change-request row lock, so the model re-checks the link
+ * before writing: an unlink that commits in between must not be undone by
+ * a delivery that read the link while it still stood.
+ * - `row-binding` β€” only echoed from the row the delivery matched. The row
+ * under its lock is the authority on that binding, and it may have lost it
+ * to an unlink since, so the model never lets the echo revive it.
+ */
+ acceptanceSource?: 'hand-link' | 'row-binding';
installationId?: string | null;
taskId?: string | null;
topicId?: string | null;