π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(database): backfill SCM change request links on PR work registration (#23310)
Bryand607f00d5bdd
diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.tsindex 36c7237d6ed..98d85adb654 100644--- a/packages/database/src/models/scm/changeRequest.ts+++ b/packages/database/src/models/scm/changeRequest.ts@@ -626,27 +626,84 @@ export class ScmChangeRequestModel {return row ?? null;});- /** Fill in links that are still null. Never overwrites a link already set. */+ /**+ * Fill in links that are still null. Never overwrites a link already set.+ *+ * The null check lives in the UPDATE itself (`COALESCE`), not in a read+ * first: a concurrent `pull_request` ingest filling a link between a+ * read-modify-write's two statements would otherwise be overwritten.+ * `guard` narrows the same statement further (e.g. a scope fence); a row+ * that fails it is untouched. Returns the row after the update, `null`+ * when it does not exist or the guard refused it.+ */static attachLinks = async (db: LobeChatDatabase,id: string,links: ScmChangeRequestLinks,+ guard?: SQL,): Promise<ScmChangeRequestItem | null> => {- const existing = await ScmChangeRequestModel.findById(db, id);- if (!existing) return null;-- const set: Partial<ScmChangeRequestLinks> = {};+ const set: Record<string, SQL> = {};for (const key of ['acceptanceId', 'installationId', 'taskId', 'topicId', 'workId'] as const) {- if (!existing[key] && links[key]) set[key] = links[key];+ if (links[key]) {+ set[key] = sql`coalesce(${scmChangeRequests[key]}, ${links[key]})`;+ }}- if (Object.keys(set).length === 0) return existing;+ if (Object.keys(set).length === 0) return ScmChangeRequestModel.findById(db, id);const [row] = await db.update(scmChangeRequests).set({ ...set, updatedAt: new Date() })- .where(eq(scmChangeRequests.id, id))+ .where(and(eq(scmChangeRequests.id, id), guard)).returning();- return row;+ return row ?? null;+ };++ /**+ * Backfill the row for a pull request a Work registration just tied to a+ * conversation β but only when the row lives in the Work's own scope.+ * Provider events re-resolve links on every `pull_request` delivery, so+ * this covers the gap between the last delivery and the next: a review or+ * a failing check in between would otherwise find no conversation to+ * wake. Fill-only like the event path; a link already set is never+ * replaced.+ */+ static attachPullRequestWork = async (+ db: LobeChatDatabase,+ params: {+ number: number;+ repoFullName: string;+ scope: { userId: string; workspaceId?: string | null };+ topicId?: string | null;+ workId: string;+ },+ ): Promise<void> => {+ const row = await ScmChangeRequestModel.findByIdentityIgnoringCase(+ db,+ 'github',+ params.repoFullName,+ params.number,+ );+ if (!row) return;++ // A row routed to another scope learns nothing: its `topicId` is looked+ // up under the row's owner when a wake fires, so a foreign conversation+ // would occupy a fill-only slot the right link can never take. The check+ // rides inside the UPDATE β a row re-routed between our read and write+ // is refused, not written.+ await ScmChangeRequestModel.attachLinks(+ db,+ row.id,+ {+ topicId: params.topicId,+ workId: params.workId,+ },+ and(+ eq(scmChangeRequests.userId, params.scope.userId),+ params.scope.workspaceId == null+ ? isNull(scmChangeRequests.workspaceId)+ : eq(scmChangeRequests.workspaceId, params.scope.workspaceId),+ ),+ );};/**diff --git a/packages/database/src/models/work/__tests__/scmChangeRequestBackfill.test.ts b/packages/database/src/models/work/__tests__/scmChangeRequestBackfill.test.tsnew file mode 100644index 00000000000..bfcd032a90b--- /dev/null+++ b/packages/database/src/models/work/__tests__/scmChangeRequestBackfill.test.ts@@ -0,0 +1,104 @@+// @vitest-environment node+import { agentShareWorkAccessScope, type ScmUpsertChangeRequestParams } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { scmChangeRequests, topics } from '../../../schemas';+import { ScmChangeRequestModel } from '../../scm';+import { WorkModel } from '..';+import {+ cleanupWorkTestData,+ seedWorkTestData,+ serverDB,+ topicId,+ userId,+ userId2,+} from './_fixtures';++beforeEach(seedWorkTestData);+afterEach(cleanupWorkTestData);++const pullRequestRow = (overrides: Partial<ScmUpsertChangeRequestParams> = {}) =>+ ScmChangeRequestModel.upsert(serverDB, {+ number: 7,+ provider: 'github',+ repoFullName: 'lobehub/lobehub',+ state: 'open',+ url: 'https://github.com/lobehub/lobehub/pull/7',+ userId,+ ...overrides,+ });++const registerPullRequest = (model: WorkModel, toolCallId = 'call-pr') =>+ model.registerExternal({+ changeType: 'created',+ identifier: 'lobehub/lobehub#7',+ patchFields: ['identifier'],+ resourceId: 'lobehub/lobehub#7',+ resourceType: 'github_pull_request',+ toolCallId,+ toolIdentifier: 'github',+ toolName: 'create_pull_request',+ topicId,+ });++const rowOf = async (id: string) => {+ const [row] = await serverDB.select().from(scmChangeRequests).where(eq(scmChangeRequests.id, id));+ return row;+};++describe('WorkModel Β· pull-request work backfills the provider row', () => {+ it('fills topicId and workId on a linkless row in the same scope', async () => {+ const row = await pullRequestRow();+ expect(row.topicId).toBeNull();+ expect(row.workId).toBeNull();++ const work = await registerPullRequest(new WorkModel(serverDB, userId));++ const after = await rowOf(row.id);+ expect(after?.topicId).toBe(topicId);+ expect(after?.workId).toBe(work?.id);+ });++ it('leaves a row owned by another scope untouched', async () => {+ const row = await pullRequestRow({ userId: userId2 });++ await registerPullRequest(new WorkModel(serverDB, userId));++ const after = await rowOf(row.id);+ expect(after?.topicId).toBeNull();+ expect(after?.workId).toBeNull();+ });++ it('never replaces a link the row already has', async () => {+ await serverDB.insert(topics).values({ id: 'existing-topic', userId });+ const row = await pullRequestRow({ links: { topicId: 'existing-topic' } });++ await registerPullRequest(new WorkModel(serverDB, userId));++ const after = await rowOf(row.id);+ expect(after?.topicId).toBe('existing-topic');+ // workId was still empty, so that one does fill.+ expect(after?.workId).not.toBeNull();+ });++ it('ignores share-visitor registrations', async () => {+ const row = await pullRequestRow();+ const visitor = new WorkModel(+ serverDB,+ userId,+ undefined,+ agentShareWorkAccessScope({+ shareId: 'share-1',+ topicId: 'visitor-topic',+ visitorUserId: userId,+ }),+ );++ await registerPullRequest(visitor);++ const after = await rowOf(row.id);+ expect(after?.topicId).toBeNull();+ expect(after?.workId).toBeNull();+ });+});diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex 228e36d8664..c223809f07d 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -16,8 +16,10 @@ import {type WorkSkillProvider,type WorkVisibility,} from '@lobechat/types';+import debug from 'debug';import type { LobeChatDatabase } from '../../type';+import { ScmChangeRequestModel } from '../scm';import {findCanvasIdByWorkId,findCanvasIdsByDeploymentIds,@@ -29,7 +31,7 @@ import {recordCanvasPublish,registerCanvasWork,} from './canvas';-import type { WorkContext } from './context';+import { resolveWorkAccessScope, type WorkContext } from './context';import { registerDocumentWork } from './document';import { registerExternalWork } from './external';import { findFileWorkVersionByToolCall, registerFileWork } from './file';@@ -64,6 +66,8 @@ const SKILL_TOOL_RESULT_NORMALIZERS = {(input: SkillToolResultWorkInput) => ExternalToolWorkOperation | null>;+const log = debug('lobe-database:work-model');+/*** Facade over the per-type Work modules. Holds the `WorkContext` (db + owner* scope) and delegates each public method to a free function in the matching@@ -97,8 +101,21 @@ export class WorkModel {registerDocument = (params: RegisterDocumentWorkParams): Promise<WorkItem | null> =>registerDocumentWork(this.ctx, params);- registerExternal = (params: RegisterExternalWorkParams): Promise<WorkItem | null> =>- registerExternalWork(this.ctx, params);+ registerExternal = async (params: RegisterExternalWorkParams): Promise<WorkItem | null> => {+ const work = await registerExternalWork(this.ctx, params);++ // A pull-request Work is also a link the provider row resolves from.+ // `pull_request` deliveries only re-resolve when the next one arrives, so+ // a Work registered after the last one leaves the row linkless β and a+ // review or a failing check in between finds no conversation to wake.+ if (work && params.resourceType === 'github_pull_request') {+ await this.backfillChangeRequest(work, params.topicId).catch((error) =>+ log('change-request backfill for %s failed: %O', work.resourceId, error),+ );+ }++ return work;+ };registerFile = (params: RegisterFileWorkParams): Promise<WorkItem> =>registerFileWork(this.ctx, params);@@ -182,6 +199,31 @@ export class WorkModel {return this.registerExternal({ ...operation.params, toolIdentifier });};+ /**+ * Hand a just-registered `github_pull_request` Work to the provider row,+ * when one exists in the Work's own scope. Share-visitor registrations stay+ * out: their Works are fenced off from the creator's surfaces and must not+ * steer the owner's automation.+ */+ private backfillChangeRequest = async (+ work: WorkItem,+ topicId?: string | null,+ ): Promise<void> => {+ if (resolveWorkAccessScope(this.ctx).type === 'agentShare' || !work.resourceId) return;++ const separator = work.resourceId.lastIndexOf('#');+ const number = Number(work.resourceId.slice(separator + 1));+ if (separator <= 0 || !Number.isInteger(number)) return;++ await ScmChangeRequestModel.attachPullRequestWork(this.ctx.db, {+ number,+ repoFullName: work.resourceId.slice(0, separator),+ scope: { userId: this.ctx.userId, workspaceId: this.ctx.workspaceId ?? null },+ topicId: work.originTopicId ?? topicId,+ workId: work.id,+ });+ };+deleteDocumentWork = (params: DeleteDocumentWorkParams): Promise<void> =>writes.deleteDocumentWork(this.ctx, params);