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): resolve handed-off comments when their repair delivery is accepted (#22127)

Inneicc3d7a85ad4b
diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.repair.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.repair.test.ts
index 30acbff87d6..206e9a915b5 100644
--- a/apps/server/src/routers/lambda/__tests__/acceptance.repair.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/acceptance.repair.test.ts
@@ -20,7 +20,9 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as AcceptanceModelModule from '@/database/models/acceptance';
+import type * as AcceptanceEventsModule from '@/server/services/acceptanceReview/events';
import { ProjectReviewService } from '@/server/services/projectReview';
+import { AcceptanceService } from '@/server/services/verify';
import * as agentGuard from '../_helpers/workspaceAgentGuard';
import { acceptanceRouter } from '../acceptance';
@@ -60,6 +62,17 @@ vi.mock('@/database/models/acceptance', async (importOriginal) => {
}
return { ...actual, AcceptanceModel };
});
+const notified = vi.hoisted(() => [] as [string, string][]);
+vi.mock('@/server/services/acceptanceReview/events', async (importOriginal) => {
+ const actual = await importOriginal<typeof AcceptanceEventsModule>();
+ return {
+ ...actual,
+ notifyAcceptance: (...args: Parameters<typeof actual.notifyAcceptance>) => {
+ notified.push([args[0], args[1]]);
+ return actual.notifyAcceptance(...args);
+ },
+ };
+});
vi.mock('@/server/services/aiAgent', () => ({
AiAgentService: vi.fn().mockImplementation(function () {
return { execAgent };
@@ -158,6 +171,151 @@ describe('acceptance repair handoff', () => {
expect(original?.resolvedAt).toBeNull();
});
+ const handOff = async () => {
+ await acceptanceRouter
+ .createCaller(createTestContext(userId))
+ .requestRepair({ id: acceptanceId });
+ const [task] = await serverDB.select().from(tasks).where(eq(tasks.projectId, projectId));
+ const delivery = await serverDB.query.acceptances.findFirst({
+ where: eq(acceptances.subjectId, task.id),
+ });
+ await serverDB
+ .update(acceptances)
+ .set({ status: 'delivered' })
+ .where(eq(acceptances.id, delivery!.id));
+ await serverDB.insert(verifyRuns).values({ acceptanceId: delivery!.id, roundIndex: 1, userId });
+ return delivery!.id;
+ };
+ const rootState = () =>
+ serverDB.query.acceptanceComments.findFirst({ where: eq(acceptanceComments.id, commentId) });
+
+ it('resolves the handed-off comments when a person accepts the delivery', async () => {
+ const deliveryId = await handOff();
+ expect((await rootState())?.resolvedAt).toBeNull();
+ await new AcceptanceService(serverDB, userId).accept(deliveryId);
+ const root = await rootState();
+ expect(root?.resolvedAt).not.toBeNull();
+ expect(root?.resolvedByUserId).toBe(userId);
+ expect(notified).toContainEqual([acceptanceId, 'comments']);
+ });
+
+ it('still resolves an earlier handoff after a later one replaces the source record', async () => {
+ const deliveryId = await handOff();
+ const source = await serverDB.query.acceptances.findFirst({
+ where: eq(acceptances.id, acceptanceId),
+ });
+ await serverDB
+ .update(acceptances)
+ .set({
+ metadata: {
+ ...source!.metadata,
+ repair: {
+ commentIds: [],
+ feedback: 'A later handoff',
+ id: randomUUID(),
+ requestedAt: new Date().toISOString(),
+ requestedBy: userId,
+ state: 'running',
+ },
+ },
+ })
+ .where(eq(acceptances.id, acceptanceId));
+
+ await new AcceptanceService(serverDB, userId).accept(deliveryId);
+
+ expect((await rootState())?.resolvedAt).not.toBeNull();
+ });
+
+ it('resolves the handed-off comments when a merge accepts the delivery', async () => {
+ const deliveryId = await handOff();
+ await new AcceptanceService(serverDB, userId).acceptFromScmMerge(deliveryId, {
+ number: 7,
+ provider: 'github',
+ repoFullName: 'lobehub/site',
+ url: 'https://github.com/lobehub/site/pull/7',
+ });
+ expect((await rootState())?.resolvedAt).not.toBeNull();
+ });
+
+ it('leaves comments of other acceptances alone even if a Task lists them', async () => {
+ const deliveryId = await handOff();
+ const [other] = await serverDB
+ .insert(acceptances)
+ .values({
+ projectId,
+ subjectId: randomUUID(),
+ subjectType: 'site',
+ status: 'delivered',
+ userId,
+ })
+ .returning();
+ const [foreign] = await serverDB
+ .insert(acceptanceComments)
+ .values({
+ acceptanceId: other.id,
+ authorUserId: userId,
+ clientId: randomUUID(),
+ content: 'Elsewhere',
+ })
+ .returning();
+ const [task] = await serverDB.select().from(tasks).where(eq(tasks.projectId, projectId));
+ const config = task.config as { acceptanceRepair: { commentIds: string[] } };
+ await serverDB
+ .update(tasks)
+ .set({
+ config: {
+ ...config,
+ acceptanceRepair: { ...config.acceptanceRepair, commentIds: [commentId, foreign.id] },
+ },
+ })
+ .where(eq(tasks.id, task.id));
+ await new AcceptanceService(serverDB, userId).accept(deliveryId);
+ const after = await serverDB.query.acceptanceComments.findFirst({
+ where: eq(acceptanceComments.id, foreign.id),
+ });
+ expect(after?.resolvedAt).toBeNull();
+ });
+
+ it('ignores a repair link a user writes into their own Task config', async () => {
+ await handOff();
+ const source = await serverDB.query.acceptances.findFirst({
+ where: eq(acceptances.id, acceptanceId),
+ });
+ const tasksOf = taskRouter.createCaller(createTestContext(outsiderId));
+ const { data: own } = await tasksOf.create({ instruction: 'Unrelated work', name: 'Mine' });
+ await tasksOf.updateConfig({
+ config: {
+ acceptanceRepair: {
+ acceptanceId,
+ commentIds: [commentId],
+ requestId: source!.metadata!.repair!.id,
+ },
+ },
+ id: own.id,
+ });
+ const [delivery] = await serverDB
+ .insert(acceptances)
+ .values({ status: 'delivered', subjectId: own.id, subjectType: 'task', userId: outsiderId })
+ .returning();
+ await serverDB
+ .insert(verifyRuns)
+ .values({ acceptanceId: delivery.id, roundIndex: 1, userId: outsiderId });
+
+ await new AcceptanceService(serverDB, outsiderId).accept(delivery.id);
+
+ expect((await rootState())?.resolvedAt).toBeNull();
+ });
+
+ it('does not resolve handed-off comments for someone who cannot resolve them by hand', async () => {
+ const deliveryId = await handOff();
+
+ await new AcceptanceService(serverDB, userId, undefined, { actorUserId: outsiderId }).accept(
+ deliveryId,
+ );
+
+ expect((await rootState())?.resolvedAt).toBeNull();
+ });
+
it('deduplicates concurrent requests and does not sweep in feedback posted during execution', async () => {
const caller = acceptanceRouter.createCaller(createTestContext(userId));
const results = await Promise.all([
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceFeedbackRepair.ts b/apps/server/src/routers/lambda/_helpers/acceptanceFeedbackRepair.ts
index 554d51dc755..de011968cdf 100644
--- a/apps/server/src/routers/lambda/_helpers/acceptanceFeedbackRepair.ts
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceFeedbackRepair.ts
@@ -71,6 +71,13 @@ export async function readAcceptanceRepair(
return repair;
}
+async function rootCommentIds(db: LobeChatDatabase, acceptanceId: string, ids: string[]) {
+ if (!ids.length) return [];
+ const rows = await new AcceptanceCommentModel(db).listByAcceptance(acceptanceId);
+ const parents = new Map(rows.map((row) => [row.id, row.parentCommentId]));
+ return [...new Set(ids.map((id) => parents.get(id) ?? id))];
+}
+
async function snapshotFeedback(
db: LobeChatDatabase,
service: AcceptanceService,
@@ -300,7 +307,11 @@ export async function dispatchAcceptanceFeedbackRepair(
acceptance.workspaceId ?? undefined,
).setVisibilityByAcceptance(delivery.id, 'private');
await deliveryService.acceptanceModel.patchMetadata(delivery.id, {
- repairSource: { acceptanceId: acceptance.id, requestId: request.id },
+ repairSource: {
+ acceptanceId: acceptance.id,
+ commentIds: await rootCommentIds(ctx.serverDB, acceptance.id, request.commentIds),
+ requestId: request.id,
+ },
});
await patch({ deliveryAcceptanceId: delivery.id });
const result = await createTaskExecutionRouter((operationId) =>
diff --git a/apps/server/src/services/verify/acceptanceService/index.ts b/apps/server/src/services/verify/acceptanceService/index.ts
index 2807f53a964..7022390936b 100644
--- a/apps/server/src/services/verify/acceptanceService/index.ts
+++ b/apps/server/src/services/verify/acceptanceService/index.ts
@@ -58,6 +58,7 @@ import {
completeTaskForDelivery,
completeTaskSubject,
reopenRejectedTaskSubject,
+ resolveRepairComments,
} from './taskLifecycle';
export type { AttachedRun } from './attachGuards';
@@ -484,8 +485,10 @@ export class AcceptanceService {
// the way, and those rejections are exactly the material.
this.distilSettledRound(acceptanceId, settled);
- if (acceptance.subjectType === 'task')
+ if (acceptance.subjectType === 'task') {
await completeTaskSubject(this.deps, acceptance.subjectId);
+ await resolveRepairComments(this.deps, acceptance);
+ }
return (await this.acceptanceModel.findById(acceptanceId))!;
};
@@ -524,8 +527,10 @@ export class AcceptanceService {
await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
notifyAcceptance(acceptanceId, 'session', this.actorUserId);
if (current) this.distilSettledRound(acceptanceId, current.id);
- if (acceptance.subjectType === 'task')
+ if (acceptance.subjectType === 'task') {
await completeTaskSubject(this.deps, acceptance.subjectId);
+ await resolveRepairComments(this.deps, acceptance);
+ }
log(
'acceptance %s accepted by merge of %s#%d (was %s)',
diff --git a/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts b/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
index 79d42827386..f0308db84ec 100644
--- a/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
+++ b/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
@@ -1,7 +1,13 @@
import debug from 'debug';
+import { eq } from 'drizzle-orm';
+import { AcceptanceCommentModel } from '@/database/models/acceptanceComment';
import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
+import { acceptances } from '@/database/schemas';
+import type { AcceptanceItem } from '@/database/schemas/verify';
+import { resolveReviewAccess } from '@/server/services/acceptanceReview/access';
+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';
import { TaskService } from '@/server/services/task';
import type { AcceptanceServiceDeps } from './deps';
@@ -51,6 +57,41 @@ const pendingCompletionOperation = (task: { context?: unknown }) =>
(task.context as { completion?: { requestedByOperationId?: string | null } } | null)?.completion
?.requestedByOperationId ?? undefined;
+export const resolveRepairComments = async (
+ deps: AcceptanceServiceDeps,
+ delivery: Pick<AcceptanceItem, 'id' | 'metadata'>,
+) => {
+ try {
+ // Written only by the feedback handoff, never by user input such as Task config.
+ const link = delivery.metadata?.repairSource;
+ if (!link) return;
+ const source = await deps.db.query.acceptances.findFirst({
+ where: eq(acceptances.id, link.acceptanceId),
+ });
+ if (!source) return;
+ const latest = source.metadata?.repair;
+ const handedOff = link.commentIds ?? (latest?.id === link.requestId ? latest.commentIds : []);
+
+ // Same rule as resolving a thread by hand: reviewers close any handed-off
+ // thread, everyone else only the threads they opened.
+ const access = await resolveReviewAccess(deps.db, deps.actorUserId, source.id);
+ if (!access) return;
+ const comments = new AcceptanceCommentModel(deps.db);
+ const rows = new Map((await comments.listByAcceptance(source.id)).map((row) => [row.id, row]));
+ const rootIds = new Set(handedOff.map((id) => rows.get(id)?.parentCommentId ?? id));
+ const ids = [...rootIds].filter((id) => {
+ const root = rows.get(id);
+ return root && (access.can.moderate || root.authorUserId === deps.actorUserId);
+ });
+
+ const resolved = await comments.resolveRoots(source.id, ids, deps.actorUserId);
+ if (resolved.length) notifyAcceptance(source.id, 'comments', deps.actorUserId);
+ log('acceptance %s resolved %d handed-off comments', delivery.id, resolved.length);
+ } catch (error) {
+ log('acceptance %s comment resolve failed: %O', delivery.id, error);
+ }
+};
+
/**
* The task whose status follows its acceptance's lifecycle: delivered →
* completed, rejected → reopened. Goal graph tasks are driven by their
diff --git a/packages/database/src/models/acceptanceComment.ts b/packages/database/src/models/acceptanceComment.ts
index 97a2e2da786..1128f5a51b3 100644
--- a/packages/database/src/models/acceptanceComment.ts
+++ b/packages/database/src/models/acceptanceComment.ts
@@ -475,6 +475,23 @@ export class AcceptanceCommentModel {
return row;
};
+ resolveRoots = async (acceptanceId: string, rootIds: string[], userId: string) => {
+ if (!rootIds.length) return [];
+ return this.db
+ .update(acceptanceComments)
+ .set({ resolvedAt: new Date(), resolvedByUserId: userId, updatedAt: new Date() })
+ .where(
+ and(
+ eq(acceptanceComments.acceptanceId, acceptanceId),
+ inArray(acceptanceComments.id, rootIds),
+ isNull(acceptanceComments.parentCommentId),
+ isNull(acceptanceComments.resolvedAt),
+ isNull(acceptanceComments.deletedAt),
+ ),
+ )
+ .returning();
+ };
+
/** Mark a thread root handled (or reopen it). Replies are not resolvable. */
setResolved = async (rootId: string, resolved: boolean, userId: string) => {
const [row] = await this.db
diff --git a/packages/types/src/acceptanceReview.test.ts b/packages/types/src/acceptanceReview.test.ts
new file mode 100644
index 00000000000..1cdaf1d13a9
--- /dev/null
+++ b/packages/types/src/acceptanceReview.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import { reviewAnchorSchema } from './acceptanceReview';
+
+const base = {
+ intent: 'change',
+ region: { height: 50, width: 80, x: 10, y: 20 },
+ scroll: { x: 0, y: 0 },
+ targets: [],
+ url: 'https://site.test/app#/settings',
+ v: 1,
+ viewport: { dpr: 2, height: 800, width: 1280 },
+};
+
+const ref = { box: { height: 0.5, width: 0.5, x: 0.1, y: 0.2 }, selector: '#card', text: 'Card' };
+
+describe('reviewAnchorSchema', () => {
+ it('keeps the route and region refs the SDK sends', () => {
+ const parsed = reviewAnchorSchema.parse({
+ ...base,
+ regionRefs: [ref, null],
+ route: '/app#/settings',
+ });
+ expect(parsed.route).toBe('/app#/settings');
+ expect(parsed.regionRefs).toEqual([ref, null]);
+ });
+
+ it('allows region ref selectors as long as target selectors', () => {
+ const long = { ...ref, selector: 's'.repeat(2000) };
+ expect(reviewAnchorSchema.safeParse({ ...base, regionRefs: [long] }).success).toBe(true);
+ });
+
+ it('still accepts anchors from older SDKs', () => {
+ const parsed = reviewAnchorSchema.parse(base);
+ expect(parsed.route).toBeUndefined();
+ expect(parsed.regionRefs).toBeUndefined();
+ });
+
+ it('rejects oversized routes and too many region refs', () => {
+ expect(reviewAnchorSchema.safeParse({ ...base, route: 'x'.repeat(501) }).success).toBe(false);
+ expect(
+ reviewAnchorSchema.safeParse({ ...base, regionRefs: Array.from({ length: 7 }, () => ref) })
+ .success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/types/src/acceptanceReview.ts b/packages/types/src/acceptanceReview.ts
index 35621ab0a23..8ea2e57a47f 100644
--- a/packages/types/src/acceptanceReview.ts
+++ b/packages/types/src/acceptanceReview.ts
@@ -21,6 +21,19 @@ export const reviewAnchorSchema = z.object({
.optional(),
intent: z.enum(['change', 'comment']),
region: rectSchema.optional(),
+ regionRefs: z
+ .array(
+ z
+ .object({
+ box: rectSchema,
+ selector: z.string().max(2000),
+ text: z.string().max(200).optional(),
+ })
+ .nullable(),
+ )
+ .max(6)
+ .optional(),
+ route: z.string().max(500).optional(),
scroll: z.object({ x: z.number().finite(), y: z.number().finite() }),
targets: z
.array(
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index e472d965d22..1ba9b60f0ca 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -186,7 +186,7 @@ export interface AcceptanceMetadata {
/** Latest explicit feedback handoff; kept apart from the standing Site review lifecycle. */
repair?: AcceptanceRepairRequest;
/** Task delivery's link back to the feedback handoff it addresses. */
- repairSource?: { acceptanceId: string; requestId: string };
+ repairSource?: { acceptanceId: string; commentIds?: string[]; requestId: string };
/** User-set display-title override for the acceptance (sidebar rename). */
title?: string;
}