๐คฏ 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
โจ feat(acceptance): add a keyset-paged list read and batch status/delete writes (#18896)
Arvin Xu903cffcf539b
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.tsnew file mode 100644index 00000000000..4bc3f1178af--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts@@ -0,0 +1,68 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { canManageAcceptance } from './acceptanceWriteScope';++const getMember = vi.hoisted(() => vi.fn());++vi.mock('@/database/models/workspaceMember', () => ({+ WorkspaceMemberModel: class {+ getMember = getMember;+ },+}));++const db = {} as never;+const row = (userId: string, workspaceId: string | null) =>+ ({ userId, workspaceId }) as { userId: string; workspaceId: string | null };++beforeEach(() => {+ getMember.mockReset();+});++describe('canManageAcceptance', () => {+ it('always lets the creator write, without a membership lookup', async () => {+ await expect(canManageAcceptance({ serverDB: db, userId: 'me' }, row('me', 'ws_a'))).resolves.toBe(+ true,+ );+ expect(getMember).not.toHaveBeenCalled();+ });++ it("lets an owner of the acceptance's OWN workspace write a teammate's delivery", async () => {+ getMember.mockResolvedValue({ role: 'owner' });++ await expect(+ canManageAcceptance({ serverDB: db, userId: 'me' }, row('teammate', 'ws_a')),+ ).resolves.toBe(true);+ // The row's workspace, never the caller's active one โ the caller is+ // routinely standing somewhere else, or nowhere.+ expect(getMember).toHaveBeenCalledWith('ws_a', 'me');+ });++ it('does not let an ordinary member write a teammate delivery', async () => {+ getMember.mockResolvedValue({ role: 'member' });++ await expect(+ canManageAcceptance({ serverDB: db, userId: 'me' }, row('teammate', 'ws_a')),+ ).resolves.toBe(false);+ });++ it('does not let a non-member write it', async () => {+ getMember.mockResolvedValue(undefined);++ await expect(+ canManageAcceptance({ serverDB: db, userId: 'me' }, row('teammate', 'ws_a')),+ ).resolves.toBe(false);+ });++ it('has no owner path for a personal acceptance โ only its creator writes it', async () => {+ await expect(+ canManageAcceptance({ serverDB: db, userId: 'me' }, row('teammate', null)),+ ).resolves.toBe(false);+ expect(getMember).not.toHaveBeenCalled();+ });++ it('refuses an anonymous caller', async () => {+ await expect(canManageAcceptance({ serverDB: db }, row('teammate', 'ws_a'))).resolves.toBe(false);+ expect(getMember).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.tsnew file mode 100644index 00000000000..cc3ce5b1805--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts@@ -0,0 +1,33 @@+import { WorkspaceMemberModel } from '@/database/models/workspaceMember';+import type { AcceptanceItem } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';++export interface AcceptanceScopeCtx {+ serverDB: LobeChatDatabase;+ userId?: string | null;+}++/**+ * May this caller write to this acceptance?+ *+ * The creator always may. Beyond that, an acceptance that belongs to a workspace+ * may also be managed by an OWNER of **that** workspace โ not of the caller's+ * currently-active one, which is frequently a different workspace or none at+ * all. Reading membership off the row's own workspace is what makes the rule+ * stable no matter where the caller happens to be standing, and it is the same+ * rule `getBundle` reports as `canReview`, so the page can never advertise an+ * action the mutation would refuse.+ */+export async function canManageAcceptance(+ ctx: AcceptanceScopeCtx,+ acceptance: Pick<AcceptanceItem, 'userId' | 'workspaceId'>,+): Promise<boolean> {+ if (ctx.userId && ctx.userId === acceptance.userId) return true;+ if (!ctx.userId || !acceptance.workspaceId) return false;++ const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(+ acceptance.workspaceId,+ ctx.userId,+ );+ return member?.role === 'owner';+}diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex 0521a988a11..86a45cdc386 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -22,6 +22,7 @@ import { VerifyRunModel } from '@/database/models/verifyRun';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import type { AcceptanceItem } from '@/database/schemas/verify';import { acceptances } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';import { isUuid } from '@/database/utils/uuid';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -39,6 +40,7 @@ import {} from '@/server/services/verify';import { after } from '@/server/utils/scheduleAfterResponse';+import { canManageAcceptance } from './_helpers/acceptanceWriteScope';import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';const subjectTypeSchema = z.enum(acceptanceSubjectTypes);@@ -63,17 +65,97 @@ const acceptanceProcedure = wsCompatProcedure.use(serverDatabase).use(async (opt// read-only); personal mode passes through unrestricted.const acceptanceWriteProcedure = acceptanceProcedure.use(requireWorkspaceRoleWhenScoped('member'));-const resolveAcceptance = async (- ctx: { acceptanceService: AcceptanceService },+/**+ * Resolve an acceptance for WRITING, with a service bound to the scope the row+ * actually lives in.+ *+ * Every model write is scoped by `buildWorkspaceWhere`, and `acceptances`+ * carries a `visibility` column โ so that predicate narrows PRIVATE rows to+ * `userId = <bound user>`, and workspace acceptances default to private. A+ * service bound to the caller therefore cannot resolve a teammate's row at all,+ * and the write dies as `NOT_FOUND` after authorization already said yes.+ *+ * So the service is bound to the row's OWNER โ the one binding that resolves it+ * โ while the acting user is carried separately, because decisions record+ * `decidedBy` and an audit trail that credits a teammate's verdict to the+ * author is worse than one nobody can sign.+ */+const resolveAcceptanceForWrite = async (+ ctx: { serverDB: LobeChatDatabase; userId: string },id: string,-): Promise<AcceptanceItem> => {- const acceptance = await ctx.acceptanceService.acceptanceModel.findById(id);-- if (!acceptance) {+): Promise<{ acceptance: AcceptanceItem; service: AcceptanceService }> => {+ const acceptance = isUuid(id)+ ? await ctx.serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, id) })+ : undefined;++ // An unauthorized caller gets the same answer as a missing row: the existence+ // of someone else's delivery is not ours to disclose.+ if (!acceptance || !(await canManageAcceptance(ctx, acceptance))) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });}- return acceptance;+ return {+ acceptance,+ service: new AcceptanceService(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ { actorUserId: ctx.userId },+ ),+ };+};++/** Max rows one multi-select sweep may touch โ the list itself is capped at 200. */+const ACCEPTANCE_BATCH_LIMIT = 200;++const acceptanceStatusOverrideSchema = z.enum(['delivered', 'accepted', 'closed', 'rejected']);++/**+ * Apply one user-facing lifecycle override to an already-resolved,+ * already-authorized aggregate. Shared by the single-row menu action and the+ * list's multi-select sweep, so both obey exactly the same transition rules.+ *+ * accept / reject go through the SERVICE, never a bare status write: the+ * service applies `requireDecidableAcceptance` (a premature `accepted` is+ * sticky in recomputeStatus and could never be corrected by a later verifier+ * result) and stamps the decision on the current round. Reopen is only+ * meaningful for an already-decided aggregate โ a still-running round must+ * not be forced back to a decision-pending state by hand.+ */+const applyAcceptanceStatus = async (+ service: AcceptanceService,+ acceptance: AcceptanceItem,+ status: z.infer<typeof acceptanceStatusOverrideSchema>,+) => {+ if (status === 'accepted') {+ await service.accept(acceptance.id);+ return;+ }++ if (status === 'closed') {+ await service.acceptanceModel.updateStatus(acceptance.id, 'closed');+ return;+ }++ if (status === 'rejected') {+ await service.reject(acceptance.id, 'Rejected from the acceptance list โ needs another round.');+ return;+ }++ // Reopen (โ delivered): only a decided aggregate can be re-opened; a live+ // round recomputes its own status and must not be clobbered.+ if (+ acceptance.status !== 'accepted' &&+ acceptance.status !== 'closed' &&+ acceptance.status !== 'rejected'+ ) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Only a decided acceptance can be reopened (status: ${acceptance.status})`,+ });+ }++ await service.acceptanceModel.updateStatus(acceptance.id, 'delivered');};export const acceptanceRouter = router({@@ -86,10 +168,9 @@ export const acceptanceRouter = router({accept: acceptanceWriteProcedure.input(z.object({ comment: z.string().max(2000).optional(), id: z.string() })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- return ctx.acceptanceService.accept(acceptance.id, input.comment);+ return service.accept(acceptance.id, input.comment);}),/**@@ -100,8 +181,7 @@ export const acceptanceRouter = router({attachRun: acceptanceWriteProcedure.input(z.object({ acceptanceId: z.string(), verifyRunId: z.string() })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.acceptanceId);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.acceptanceId);// The attach rewrites the RUN's acceptance_id/round_index too โ and a// workspace-visible run is not necessarily the caller's. Creator-scope it@@ -118,7 +198,7 @@ export const acceptanceRouter = router({assertWorkspaceRowManageable(ctx, run.userId, 'verify run');try {- return await ctx.acceptanceService.attachRun(run.id, acceptance.id);+ return await service.attachRun(run.id, acceptance.id);} catch (error) {throw new TRPCError({code: 'BAD_REQUEST',@@ -270,18 +350,25 @@ export const acceptanceRouter = router({}const isOwner = Boolean(ctx.userId) && ctx.userId === acceptance.userId;- let canRead = isOwner || acceptance.visibility === 'public';- if (!canRead && ctx.userId && acceptance.workspaceId) {- const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(- acceptance.workspaceId,- ctx.userId,- );- canRead = Boolean(member);- }+ // The viewer's membership in the acceptance's OWN workspace โ not their+ // currently-active one, which may be a different workspace entirely.+ const member =+ !isOwner && ctx.userId && acceptance.workspaceId+ ? await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(+ acceptance.workspaceId,+ ctx.userId,+ )+ : undefined;++ const canRead = isOwner || acceptance.visibility === 'public' || Boolean(member);if (!canRead) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });}+ // The one rule the write path enforces โ same helper, so the page can+ // never advertise an action the mutation would refuse.+ const canReview = await canManageAcceptance(ctx, acceptance);+// Sub-reads (rounds / results / evidence) are ownership-scoped models, so// read them AS the aggregate's owner โ same pattern as the evidence file// resolver. The visibility gate above is the actual access decision.@@ -408,8 +495,11 @@ export const acceptanceRouter = router({// Automated proposals are the reviewer's working state, not published// content โ a shared acceptance URL (the whole point of `public`// visibility) must not show visitors "an AI thinks this is broken".- // Owner-only, same rule as `origin`.- const predictions = isOwner+ // Scoped to whoever may REVIEW, not to the creator: the predict button is+ // gated the same way, and a reviewer who can spend the model budget but+ // never receives a `predictionStatus` polls until it times out, then+ // reports the work as still running after it finished.+ const predictions = canReview? await new VerifyReviewPredictionModel(ctx.serverDB,acceptance.userId,@@ -436,6 +526,7 @@ export const acceptanceRouter = router({return {acceptance,+ canReview,isOwner,checks: checks.map((check) => {// Projected from the result rows' user_decision(+detail) โ the@@ -507,6 +598,32 @@ export const acceptanceRouter = router({).query(async ({ ctx, input }) => ctx.acceptanceService.listWithSubjects(input)),+ /**+ * One keyset page of the same feed โ what the list panel scrolls.+ *+ * Speaks the same `filter` vocabulary as `list`, applied in the query, so a+ * page of "in progress" is a full page of in-progress rows. There is no+ * paged search on purpose: a title search must span the whole owned set,+ * which `list` already does โ the panel asks that one while a query is live.+ */+ listPage: acceptanceProcedure+ .input(+ z+ .object({+ cursor: z.string().optional(),+ filter: z.enum(['active', 'all', 'completed']).optional(),+ limit: z.number().int().min(1).max(100).optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) =>+ ctx.acceptanceService.listPageWithSubjects({+ cursor: input?.cursor,+ filter: input?.filter,+ limit: input?.limit,+ }),+ ),+/*** Fold one acceptance into another: the source's verification rounds (and* with them its checks, verdicts and evidence) re-chain onto the target, and@@ -519,13 +636,13 @@ export const acceptanceRouter = router({merge: acceptanceWriteProcedure.input(z.object({ sourceId: z.string(), targetId: z.string() })).mutation(async ({ ctx, input }) => {- const source = await resolveAcceptance(ctx, input.sourceId);- assertWorkspaceRowManageable(ctx, source.userId, 'acceptance');- const target = await resolveAcceptance(ctx, input.targetId);- assertWorkspaceRowManageable(ctx, target.userId, 'acceptance');+ // A merge rewrites BOTH aggregates, so both have to authorize; the source+ // owns the rows that move, so its scope is the one the write runs in.+ const { acceptance: source, service } = await resolveAcceptanceForWrite(ctx, input.sourceId);+ const { acceptance: target } = await resolveAcceptanceForWrite(ctx, input.targetId);try {- return await ctx.acceptanceService.merge(source.id, target.id);+ return await service.merge(source.id, target.id);} catch (error) {throw new TRPCError({code: 'BAD_REQUEST',@@ -572,14 +689,13 @@ export const acceptanceRouter = router({}),).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);// The feedback is addressed to the CURRENT round and lives on its run's// decision detail โ the same home as the round's terminal accept/reject// note, so staleness falls out of the round chain and a deleted round// takes its feedback along.- const { runs } = await ctx.acceptanceService.loadRounds(acceptance.id);+ const { runs } = await service.loadRounds(acceptance.id);const currentRun = runs.at(-1);if (!currentRun) {throw new TRPCError({@@ -661,11 +777,10 @@ export const acceptanceRouter = router({),).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);try {- const result = await ctx.acceptanceService.reviewChecks(acceptance.id, {+ const result = await service.reviewChecks(acceptance.id, {action: input.action,annotations: input.annotations,checkItemIds: input.checkItemIds,@@ -705,8 +820,9 @@ export const acceptanceRouter = router({}),).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ // Authorization only โ the prediction rows are read through their own+ // owner-scoped model just below.+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);const model = new VerifyReviewPredictionModel(ctx.serverDB,@@ -733,10 +849,9 @@ export const acceptanceRouter = router({predictReviews: acceptanceWriteProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- const { results, runs } = await ctx.acceptanceService.loadRounds(acceptance.id);+ const { results, runs } = await service.loadRounds(acceptance.id);const resultsByRun = new Map<string, typeof results>();for (const result of results) {const bucket = resultsByRun.get(result.verifyRunId!) ?? [];@@ -810,10 +925,9 @@ export const acceptanceRouter = router({setVisibility: acceptanceWriteProcedure.input(z.object({ id: z.string(), visibility: z.enum(acceptanceVisibilities) })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- const updated = await ctx.acceptanceService.acceptanceModel.update(acceptance.id, {+ const updated = await service.acceptanceModel.update(acceptance.id, {visibility: input.visibility,});// Cascade to every chained round: each round's report page is its own@@ -836,8 +950,7 @@ export const acceptanceRouter = router({markRepairing: acceptanceWriteProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);if (acceptance.status !== 'delivered' && acceptance.status !== 'errored') {throw new TRPCError({@@ -845,7 +958,7 @@ export const acceptanceRouter = router({message: `Only a settled acceptance can be sent back (status: ${acceptance.status})`,});}- return ctx.acceptanceService.acceptanceModel.updateStatus(acceptance.id, 'repairing');+ return service.acceptanceModel.updateStatus(acceptance.id, 'repairing');}),/**@@ -857,10 +970,9 @@ export const acceptanceRouter = router({reject: acceptanceWriteProcedure.input(z.object({ comment: z.string().min(1).max(2000), id: z.string() })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- return ctx.acceptanceService.reject(acceptance.id, input.comment);+ return service.reject(acceptance.id, input.comment);}),/**@@ -872,10 +984,9 @@ export const acceptanceRouter = router({rename: acceptanceWriteProcedure.input(z.object({ id: z.string(), title: z.string().trim().min(1).max(200) })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- return ctx.acceptanceService.acceptanceModel.update(acceptance.id, {+ return service.acceptanceModel.update(acceptance.id, {metadata: { ...acceptance.metadata, title: input.title },});}),@@ -892,8 +1003,7 @@ export const acceptanceRouter = router({setProject: acceptanceWriteProcedure.input(z.object({ id: z.string(), projectId: z.string().nullable() })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);if (input.projectId) {const project = await new ProjectModel(@@ -904,7 +1014,7 @@ export const acceptanceRouter = router({if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });}- await ctx.acceptanceService.acceptanceModel.update(acceptance.id, {+ await service.acceptanceModel.update(acceptance.id, {projectId: input.projectId,});return { success: true };@@ -913,50 +1023,14 @@ export const acceptanceRouter = router({/*** Manually move the acceptance's user-facing lifecycle state from the list โ* an owner override (mark accepted / closed / rejected, or reopen for another look).- *- * accept / reject go through the SERVICE, never a bare status write: the- * service applies `requireDecidableAcceptance` (a premature `accepted` is- * sticky in recomputeStatus and could never be corrected by a later verifier- * result) and stamps the decision on the current round. Reopen is only- * meaningful for an already-decided aggregate โ a still-running round must- * not be forced back to a decision-pending state by hand.*/updateStatus: acceptanceWriteProcedure- .input(- z.object({- id: z.string(),- status: z.enum(['delivered', 'accepted', 'closed', 'rejected']),- }),- )+ .input(z.object({ id: z.string(), status: acceptanceStatusOverrideSchema })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);try {- if (input.status === 'accepted') {- await ctx.acceptanceService.accept(acceptance.id);- } else if (input.status === 'closed') {- await ctx.acceptanceService.acceptanceModel.updateStatus(acceptance.id, 'closed');- } else if (input.status === 'rejected') {- await ctx.acceptanceService.reject(- acceptance.id,- 'Rejected from the acceptance list โ needs another round.',- );- } else {- // Reopen (โ delivered): only a decided aggregate can be re-opened; a- // live round recomputes its own status and must not be clobbered.- if (- acceptance.status !== 'accepted' &&- acceptance.status !== 'closed' &&- acceptance.status !== 'rejected'- ) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Only a decided acceptance can be reopened (status: ${acceptance.status})`,- });- }- await ctx.acceptanceService.acceptanceModel.updateStatus(acceptance.id, 'delivered');- }+ await applyAcceptanceStatus(service, acceptance, input.status);} catch (error) {if (error instanceof TRPCError) throw error;throw new TRPCError({@@ -967,6 +1041,42 @@ export const acceptanceRouter = router({return { success: true };}),+ /**+ * The multi-select twin of `updateStatus`: sweep a backlog of deliveries into+ * accepted / closed in one action.+ *+ * A row that cannot take the transition (mid-verification, so undecidable;+ * or someone else's row in a workspace) is COLLECTED, not thrown: one+ * ineligible row must not void the other forty the user just swept, and the+ * caller reports what actually landed. Sequential on purpose โ each accept+ * recomputes the aggregate and stamps its round, and a sweep is a background+ * chore, not a latency-critical path.+ */+ updateStatusBatch: acceptanceWriteProcedure+ .input(+ z.object({+ ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),+ status: acceptanceStatusOverrideSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const failedIds: string[] = [];+ let updated = 0;++ for (const id of new Set(input.ids)) {+ try {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);+ await applyAcceptanceStatus(service, acceptance, input.status);+ updated += 1;+ } catch (error) {+ console.error('[acceptance] batch status update failed for %s', id, error);+ failedIds.push(id);+ }+ }++ return { failedIds, updated };+ }),+/*** Delete the acceptance aggregate. Its chained verify runs detach* (acceptance_id โ null via the FK's `set null`) rather than cascade-delete,@@ -975,10 +1085,34 @@ export const acceptanceRouter = router({remove: acceptanceWriteProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {- const acceptance = await resolveAcceptance(ctx, input.id);- assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- await ctx.acceptanceService.acceptanceModel.delete(acceptance.id);+ await service.acceptanceModel.delete(acceptance.id);return { success: true };}),++ /**+ * The multi-select twin of `remove`. Like the batch status sweep, a row the+ * caller may not delete is collected rather than thrown, so the rest of the+ * selection still goes.+ */+ removeBatch: acceptanceWriteProcedure+ .input(z.object({ ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT) }))+ .mutation(async ({ ctx, input }) => {+ const failedIds: string[] = [];+ let deleted = 0;++ for (const id of new Set(input.ids)) {+ try {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);+ await service.acceptanceModel.delete(acceptance.id);+ deleted += 1;+ } catch (error) {+ console.error('[acceptance] batch delete failed for %s', id, error);+ failedIds.push(id);+ }+ }++ return { deleted, failedIds };+ }),});diff --git a/apps/server/src/services/verify/__tests__/acceptanceActor.test.ts b/apps/server/src/services/verify/__tests__/acceptanceActor.test.tsnew file mode 100644index 00000000000..bf0b462c51e--- /dev/null+++ b/apps/server/src/services/verify/__tests__/acceptanceActor.test.ts@@ -0,0 +1,28 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { AcceptanceService } from '../acceptanceService';++/**+ * An elevated write โ a workspace owner acting on a teammate's delivery โ is+ * scoped to the row's OWNER so the ownership predicate can resolve a private+ * row at all. The person credited must still be the one who decided.+ */+describe('AcceptanceService actor attribution', () => {+ const db = {} as never;++ it('credits the acting user, not the scope it had to bind to', () => {+ const service = new AcceptanceService(db, 'creator', 'ws_a', {+ actorUserId: 'workspace-owner',+ });++ expect(Reflect.get(service, 'userId')).toBe('creator');+ expect(Reflect.get(service, 'actorUserId')).toBe('workspace-owner');+ });++ it('credits the bound user when no separate actor is given', () => {+ const service = new AcceptanceService(db, 'creator', 'ws_a');++ expect(Reflect.get(service, 'actorUserId')).toBe('creator');+ });+});diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex fe23066ca7f..a7a124551f2 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -400,6 +400,16 @@ export interface AcceptanceSubjectSummary {type: AcceptanceSubjectType;}+/** The list filter as a status set โ one definition for the flat and paged reads. */+export type AcceptanceListFilter = 'active' | 'all' | 'completed';++const statusesForFilter = (filter: AcceptanceListFilter): AcceptanceStatus[] | undefined => {+ if (filter === 'active')+ return ['pending', 'planned', 'verifying', 'repairing', 'delivered', 'rejected', 'errored'];+ if (filter === 'completed') return ['accepted', 'closed'];+ return undefined;+};+export class AcceptanceService {private readonly db: LobeChatDatabase;private readonly userId: string;@@ -411,9 +421,27 @@ export class AcceptanceService {private readonly evidenceModel: VerifyEvidenceModel;private readonly reportModel: VerifyReportModel;- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ /**+ * Who is CREDITED for the writes this service performs.+ *+ * Normally the same person the service is scoped to. They diverge for an+ * elevated write โ a workspace owner acting on a teammate's delivery โ where+ * the scope has to be the row's owner for the ownership predicate to resolve+ * it at all, while `decidedBy` must still name the human who decided. An+ * audit trail that credits a teammate's verdict to the author is worse than+ * one nobody can sign.+ */+ private readonly actorUserId: string;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ options?: { actorUserId?: string },+ ) {this.db = db;this.userId = userId;+ this.actorUserId = options?.actorUserId ?? userId;this.workspaceId = workspaceId;this.acceptanceModel = new AcceptanceModel(db, userId, workspaceId);this.runModel = new VerifyRunModel(db, userId, workspaceId);@@ -832,7 +860,7 @@ export class AcceptanceService {const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;const detail: VerifyCheckDecisionDetail = {decidedAt: new Date().toISOString(),- decidedBy: this.userId,+ decidedBy: this.actorUserId,roundIndex: currentRoundIndex,...(input.comment ? { comment: input.comment } : {}),...(input.annotations?.length ? { annotations: input.annotations } : {}),@@ -925,7 +953,7 @@ export class AcceptanceService {const detail: VerifyRunDecisionDetail = {decidedAt: new Date().toISOString(),- decidedBy: this.userId,+ decidedBy: this.actorUserId,...(comment ? { comment } : {}),};await this.runModel.setDecision(current.id, decision, detail);@@ -1120,12 +1148,7 @@ export class AcceptanceService {} = {},) => {const { filter = 'all', limit = 50, q } = options;- const statuses: AcceptanceStatus[] | undefined =- filter === 'active'- ? ['pending', 'planned', 'verifying', 'repairing', 'delivered', 'rejected', 'errored']- : filter === 'completed'- ? ['accepted', 'closed']- : undefined;+ const statuses = statusesForFilter(filter);const normalizedQuery = q?.trim().toLocaleLowerCase();// A title search must span the complete owned set. Subject titles live in@@ -1162,6 +1185,44 @@ export class AcceptanceService {}));};+ /**+ * The paged twin of {@link listWithSubjects} โ one scroll page of the list+ * panel, newest first.+ *+ * Takes the same `filter` vocabulary, applied in the QUERY: a page of+ * "in progress" is thirty in-progress rows, not thirty rows of which some+ * happen to be in progress. Search deliberately has no paged form โ a title+ * search must span the whole owned set, which is what `listWithSubjects`+ * already does; the panel asks that one when a query is active.+ */+ listPageWithSubjects = async (options: {+ cursor?: string;+ filter?: AcceptanceListFilter;+ limit?: number;+ }) => {+ const { items, nextCursor } = await this.acceptanceModel.queryPage({+ cursor: options.cursor,+ limit: options.limit,+ statuses: statusesForFilter(options.filter ?? 'all'),+ });++ const subjects = await this.resolveSubjects(items);+ const [checkCounts, projects] = await Promise.all([+ this.latestCheckCounts(items.map((row) => row.id)),+ this.resolveProjects(items),+ ]);++ return {+ items: items.map((row) => ({+ ...row,+ checkCount: checkCounts.get(row.id) ?? null,+ project: projects.get(row.id) ?? null,+ subject: subjects.get(row.id)!,+ })),+ nextCursor,+ };+ };+/*** The authoring conversation behind the round chain, resolved to displayable* entities (agent avatar/title, topic title). Owner-only header data โ thediff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.tsindex 348c0dcb912..8ff81576162 100644--- a/packages/database/src/models/__tests__/acceptance.test.ts+++ b/packages/database/src/models/__tests__/acceptance.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import type { AcceptanceStatus } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -230,6 +231,146 @@ describe('AcceptanceModel', () => {expect((await model.findById(row.id))?.completedAt).toBeNull();});+ describe('queryPage', () => {+ /** Fixed, strictly-decreasing createdAt so the keyset order is deterministic. */+ const seed = async (+ rows: { minutesAgo: number; status: 'accepted' | 'closed' | 'delivered' | 'verifying' }[],+ ) => {+ const base = Date.UTC(2026, 7, 30, 12, 0, 0);+ await serverDB.insert(acceptances).values(+ rows.map((row, index) => ({+ createdAt: new Date(base - row.minutesAgo * 60_000),+ status: row.status,+ subjectId: `page-subject-${index}`,+ subjectType: 'standalone' as const,+ userId,+ })),+ );+ };++ const pageThrough = async (+ model: AcceptanceModel,+ limit: number,+ statuses?: AcceptanceStatus[],+ ) => {+ const seen: string[] = [];+ let cursor: string | undefined;+ // Bounded so a cursor that fails to advance fails the test instead of hanging.+ for (let page = 0; page < 10; page += 1) {+ const result = await model.queryPage({ cursor, limit, statuses });+ seen.push(...result.items.map((item) => item.subjectId));+ if (!result.nextCursor) return seen;+ cursor = result.nextCursor;+ }+ throw new Error('queryPage never reached the end of the feed');+ };++ it('walks the whole feed newest-first, with no row repeated or skipped', async () => {+ const model = new AcceptanceModel(serverDB, userId);+ await seed(+ [0, 1, 2, 3, 4].map((minutesAgo) => ({ minutesAgo, status: 'delivered' as const })),+ );++ const seen = await pageThrough(model, 2);++ expect(seen).toEqual([+ 'page-subject-0',+ 'page-subject-1',+ 'page-subject-2',+ 'page-subject-3',+ 'page-subject-4',+ ]);+ expect(new Set(seen).size).toBe(seen.length);+ });++ it('reports no next cursor on an exactly-full final page', async () => {+ // The classic off-by-one: `rows.length === limit` must not advertise a+ // further page, or the scroll spins on an empty fetch forever.+ const model = new AcceptanceModel(serverDB, userId);+ await seed([0, 1].map((minutesAgo) => ({ minutesAgo, status: 'delivered' as const })));++ expect(await model.queryPage({ limit: 2 })).toMatchObject({ nextCursor: null });+ });++ it('splits in-progress from completed in the QUERY, so a page is a full page', async () => {+ const model = new AcceptanceModel(serverDB, userId);+ await seed([+ { minutesAgo: 0, status: 'accepted' },+ { minutesAgo: 1, status: 'delivered' },+ { minutesAgo: 2, status: 'closed' },+ { minutesAgo: 3, status: 'verifying' },+ ]);++ const inProgress: AcceptanceStatus[] = ['delivered', 'verifying'];+ const completed: AcceptanceStatus[] = ['accepted', 'closed'];++ await expect(pageThrough(model, 10, inProgress)).resolves.toEqual([+ 'page-subject-1',+ 'page-subject-3',+ ]);+ await expect(pageThrough(model, 10, completed)).resolves.toEqual([+ 'page-subject-0',+ 'page-subject-2',+ ]);+ // A page of one still has to hand back the rest of its own split.+ await expect(pageThrough(model, 1, inProgress)).resolves.toEqual([+ 'page-subject-1',+ 'page-subject-3',+ ]);+ });++ it('never pages across owners', async () => {+ await seed([{ minutesAgo: 0, status: 'delivered' }]);++ await expect(+ new AcceptanceModel(serverDB, otherUserId).queryPage({ limit: 10 }),+ ).resolves.toMatchObject({ items: [], nextCursor: null });+ });++ it('treats a malformed cursor as the start of the feed', async () => {+ const model = new AcceptanceModel(serverDB, userId);+ await seed([{ minutesAgo: 0, status: 'delivered' }]);++ for (const cursor of [+ 'garbage',+ // Well-formed shape, unusable id: comparing it against a uuid column+ // makes Postgres raise 22P02, turning bad client input into a 500.+ '2026-08-30T12:00:00.000Z__not-a-uuid',+ 'not-a-date__00000000-0000-4000-8000-000000000000',+ ]) {+ const { items } = await model.queryPage({ cursor, limit: 10 });+ expect(items.map((item) => item.subjectId)).toEqual(['page-subject-0']);+ }+ });+ });++ it('resolves a private workspace row only for the scope it is bound to', async () => {+ // The write path binds a service to the acceptance's OWNER precisely because+ // of this: `acceptances` carries a `visibility` column, so the ownership+ // predicate narrows PRIVATE rows to the bound user โ and a workspace+ // acceptance is private by default. Binding to the acting workspace owner+ // instead makes every write miss the row and answer NOT_FOUND, after+ // authorization has already said yes.+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'scope-ws', primaryOwnerId: otherUserId, slug: 'scope-ws' })+ .returning();++ const creatorModel = new AcceptanceModel(serverDB, userId, workspace.id);+ const acceptance = await creatorModel.ensureForSubject('topic', topicId);+ expect(acceptance.visibility).toBe('private');++ // Bound to the acting owner: invisible, and a write silently changes nothing.+ const actorScoped = new AcceptanceModel(serverDB, otherUserId, workspace.id);+ expect(await actorScoped.findById(acceptance.id)).toBeUndefined();+ await actorScoped.updateStatus(acceptance.id, 'accepted');+ expect((await creatorModel.findById(acceptance.id))?.status).not.toBe('accepted');++ // Bound to the row's owner: found, and the write lands.+ await creatorModel.updateStatus(acceptance.id, 'accepted');+ expect((await creatorModel.findById(acceptance.id))?.status).toBe('accepted');+ });+it('findById reads a malformed uuid as not-found instead of aborting in Postgres', async () => {// Chat autolinkers glue trailing CJK punctuation onto shared links, so the// route param can arrive as `<uuid>๏ผๆฌ่ฝฎ` โ 22P02 (โ 500) before the guard.diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.tsindex 28476cee2de..bc78e28135c 100644--- a/packages/database/src/models/acceptance.ts+++ b/packages/database/src/models/acceptance.ts@@ -1,5 +1,5 @@import type { AcceptanceStatus, AcceptanceSubjectType } from '@lobechat/types';-import { and, desc, eq, inArray } from 'drizzle-orm';+import { and, desc, eq, inArray, lt, or, sql } from 'drizzle-orm';import type { AcceptanceItem, NewAcceptance } from '../schemas/verify';import { acceptances } from '../schemas/verify';@@ -10,6 +10,26 @@ import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';/** Statuses a user's decision produced โ sticky until explicitly re-opened. */const TERMINAL_ACCEPTANCE_STATUSES = new Set<AcceptanceStatus>(['accepted', 'closed', 'rejected']);+/**+ * Opaque list cursor = `${createdAt ISO}__${id}`. Both parts are metacharacter-+ * free (ISO timestamp + uuid), so a plain `__` delimiter round-trips safely.+ * Mirrors `VerifyRunModel.queryPage`, whose page the reports panel reads.+ */+const encodeCursor = (createdAt: Date, id: string): string => `${createdAt.toISOString()}__${id}`;++const decodeCursor = (cursor?: string): { createdAt: Date; id: string } | null => {+ if (!cursor) return null;+ const idx = cursor.lastIndexOf('__');+ if (idx <= 0) return null;+ const createdAt = new Date(cursor.slice(0, idx));+ const id = cursor.slice(idx + 2);+ // The id half is compared against a uuid column, so a malformed one would be+ // parsed by Postgres and raise 22P02 โ a client's bad cursor turning into a+ // 500. An unreadable cursor is simply the start of the feed.+ if (Number.isNaN(createdAt.getTime()) || !isUuid(id)) return null;+ return { createdAt, id };+};+/*** Owns the business-level acceptance aggregate (`acceptances`): one row per* subject (task / topic / document / standalone delivery) carrying the@@ -205,6 +225,56 @@ export class AcceptanceModel {});};+ /**+ * Keyset page of the same feed, newest first โ what the list panel scrolls.+ *+ * Takes the same `statuses` split as {@link query} so both entry points speak+ * one vocabulary: a page of "in progress" is thirty in-progress rows, not+ * thirty rows of which some happen to be in progress.+ */+ queryPage = async ({+ cursor,+ limit = 30,+ statuses,+ }: { cursor?: string; limit?: number; statuses?: AcceptanceStatus[] } = {}): Promise<{+ items: AcceptanceItem[];+ nextCursor: string | null;+ }> => {+ const conditions = [this.ownership()];+ if (statuses && statuses.length > 0) conditions.push(inArray(acceptances.status, statuses));++ // Millisecond-truncated createdAt โ the precision the cursor round-trips+ // at. Comparing the raw timestamptz (microseconds) against a cursor read+ // back as a JS Date would let a row satisfy its own bound and repeat.+ const createdAtMs = sql`date_trunc('milliseconds', ${acceptances.createdAt})`;++ const decoded = decodeCursor(cursor);+ if (decoded) {+ // (createdAt, id) < (cursor.createdAt, cursor.id) in descending order.+ conditions.push(+ or(+ lt(createdAtMs, decoded.createdAt),+ and(eq(createdAtMs, decoded.createdAt), lt(acceptances.id, decoded.id)),+ )!,+ );+ }++ const rows = await this.db.query.acceptances.findMany({+ limit: limit + 1,+ orderBy: [desc(createdAtMs), desc(acceptances.id)],+ where: and(...conditions),+ });++ const hasMore = rows.length > limit;+ const items = hasMore ? rows.slice(0, limit) : rows;+ const last = items.at(-1);++ return {+ items,+ nextCursor: hasMore && last ? encodeCursor(last.createdAt, last.id) : null,+ };+ };+update = async (id: string,value: Partial<