🤯 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): filter the list by participation, source and project (#20461)
Arvin Xu748dcdfb89cb
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.tsindex 87a7891e09b..b5b232e4966 100644--- a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts+++ b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts@@ -4,10 +4,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { canManageAcceptance, filterManageableAcceptances } from './acceptanceWriteScope';const getMember = vi.hoisted(() => vi.fn());+const getRolesInWorkspaces = vi.hoisted(() => vi.fn());vi.mock('@/database/models/workspaceMember', () => ({WorkspaceMemberModel: class {getMember = getMember;+ getRolesInWorkspaces = getRolesInWorkspaces;},}));@@ -17,6 +19,7 @@ const row = (userId: string, workspaceId: string | null) =>beforeEach(() => {getMember.mockReset();+ getRolesInWorkspaces.mockReset();});describe('canManageAcceptance', () => {@@ -71,8 +74,11 @@ describe('canManageAcceptance', () => {describe('filterManageableAcceptances', () => {it('applies the same rule as the single-row check', async () => {- getMember.mockImplementation(async (workspaceId: string) =>- workspaceId === 'ws_owned' ? { role: 'owner' } : { role: 'member' },+ getRolesInWorkspaces.mockResolvedValue(+ new Map([+ ['ws_owned', 'owner'],+ ['ws_member', 'member'],+ ]),);const rows = [@@ -87,8 +93,13 @@ describe('filterManageableAcceptances', () => {).resolves.toEqual([row('me', null), row('me', 'ws_member'), row('teammate', 'ws_owned')]);});- it('looks membership up once per distinct workspace, not once per row', async () => {- getMember.mockResolvedValue({ role: 'owner' });+ it('reads roles for every distinct foreign workspace in one query', async () => {+ getRolesInWorkspaces.mockResolvedValue(+ new Map([+ ['ws_a', 'owner'],+ ['ws_b', 'owner'],+ ]),+ );const rows = [row('teammate', 'ws_a'),@@ -102,13 +113,15 @@ describe('filterManageableAcceptances', () => {await expect(filterManageableAcceptances({ serverDB: db, userId: 'me' }, rows),).resolves.toHaveLength(5);- expect(getMember).toHaveBeenCalledTimes(2);+ expect(getRolesInWorkspaces).toHaveBeenCalledOnce();+ expect(getRolesInWorkspaces).toHaveBeenCalledWith(['ws_a', 'ws_b'], 'me');+ expect(getMember).not.toHaveBeenCalled();});it('returns nothing for an anonymous caller', async () => {await expect(filterManageableAcceptances({ serverDB: db }, [row('me', null)])).resolves.toEqual([],);- expect(getMember).not.toHaveBeenCalled();+ expect(getRolesInWorkspaces).not.toHaveBeenCalled();});});diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.tsindex bcb2a1ae9fe..7e7c9db7d2a 100644--- a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts+++ b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts@@ -33,9 +33,10 @@ export async function canManageAcceptance(}/**- * Batch twin of {@link canManageAcceptance} for sweep endpoints: same rule,- * but ONE membership lookup per distinct workspace instead of one per row —- * a 200-row sweep must not turn authorization into 200 serial queries.+ * Batch twin of {@link canManageAcceptance} for sweep and list endpoints: same+ * rule, but the caller's roles in every distinct foreign workspace come back in+ * ONE read — a 200-row sweep, or a participated page spanning many workspaces,+ * must not turn authorization into a chain of sequential queries.*/export async function filterManageableAcceptances<T extends Pick<AcceptanceItem, 'userId' | 'workspaceId'>,@@ -50,16 +51,13 @@ export async function filterManageableAcceptances<.map((row) => row.workspaceId as string),),];- const owned = new Set<string>();- for (const workspaceId of foreignWorkspaceIds) {- const member = await new WorkspaceMemberModel(ctx.serverDB, userId).getMember(- workspaceId,- userId,- );- if (member?.role === 'owner') owned.add(workspaceId);- }+ const roles = await new WorkspaceMemberModel(ctx.serverDB, userId).getRolesInWorkspaces(+ foreignWorkspaceIds,+ userId,+ );return rows.filter(- (row) => row.userId === userId || (row.workspaceId ? owned.has(row.workspaceId) : false),+ (row) =>+ row.userId === userId || (row.workspaceId ? roles.get(row.workspaceId) === 'owner' : false),);}diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex 840abfb2db3..ac1ad5959b6 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -213,6 +213,30 @@ const canReadAcceptance = async (return Boolean(member);};+/**+ * The list panel's narrowing, shared by the flat and paged reads. `projectId:+ * null` asks for acceptances filed under no project.+ */+const acceptanceListFiltersSchema = z.object({+ filter: z.enum(['active', 'all', 'completed']).optional(),+ projectId: z.string().nullable().optional(),+ scope: z.enum(['all', 'created', 'participated']).optional(),+ source: z.enum(['all', 'goal', 'standalone', 'task', 'topic']).optional(),+});++/**+ * Tag each list row with whether the caller may rename, refile, re-status or+ * delete it. "Participated" rows are often someone else's, so the panel must+ * know which menus to offer instead of letting the write fail as NOT_FOUND.+ */+const withManageFlag = async <T extends Pick<AcceptanceItem, 'id' | 'userId' | 'workspaceId'>>(+ ctx: { serverDB: LobeChatDatabase; userId: string },+ rows: T[],+): Promise<Array<T & { canManage: boolean }>> => {+ const manageable = new Set((await filterManageableAcceptances(ctx, rows)).map((row) => row.id));+ return rows.map((row) => ({ ...row, canManage: manageable.has(row.id) }));+};+/** Max rows one multi-select sweep may touch — the list itself is capped at 200. */const ACCEPTANCE_BATCH_LIMIT = 200;const PURGE_BATCH_CONCURRENCY = 4;@@ -935,44 +959,38 @@ export const acceptanceRouter = router({*/list: acceptanceProcedure.input(- z- .object({- filter: z.enum(['active', 'all', 'completed']).optional(),+ acceptanceListFiltersSchema+ .extend({limit: z.number().int().min(1).max(200).optional(),- projectId: z.string().optional(),q: z.string().max(200).optional(),}).optional(),)- .query(async ({ ctx, input }) => ctx.acceptanceService.listWithSubjects(input)),+ .query(async ({ ctx, input }) =>+ withManageFlag(ctx, await 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+ * 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({+ acceptanceListFiltersSchema+ .extend({cursor: z.string().optional(),- filter: z.enum(['active', 'all', 'completed']).optional(),limit: z.number().int().min(1).max(100).optional(),- projectId: z.string().optional(),}).optional(),)- .query(async ({ ctx, input }) =>- ctx.acceptanceService.listPageWithSubjects({- cursor: input?.cursor,- filter: input?.filter,- limit: input?.limit,- projectId: input?.projectId,- }),- ),+ .query(async ({ ctx, input }) => {+ const page = await ctx.acceptanceService.listPageWithSubjects({ ...input });+ return { ...page, items: await withManageFlag(ctx, page.items) };+ }),/*** Fold one acceptance into another: the source's verification rounds (anddiff --git a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.tsindex 706470cedcd..1c54cb10f3e 100644--- a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({resolveDocuments: vi.fn(),resolveTasks: vi.fn(),resolveTopics: vi.fn(),+ taskScopes: [] as Array<[string, string | undefined]>,}));vi.mock('@/database/models/document', () => ({@@ -16,6 +17,9 @@ vi.mock('@/database/models/document', () => ({}));vi.mock('@/database/models/task', () => ({TaskModel: class {+ constructor(_db: unknown, userId: string, workspaceId?: string) {+ mocks.taskScopes.push([userId, workspaceId]);+ }resolveMany = mocks.resolveTasks;},}));@@ -34,6 +38,7 @@ describe('AcceptanceService.listWithSubjects', () => {status: 'delivered',subjectId: 'recent',subjectType: 'task',+ userId: 'user-1',},{createdAt: new Date(0),@@ -41,6 +46,7 @@ describe('AcceptanceService.listWithSubjects', () => {status: 'delivered',subjectId: 'older',subjectType: 'topic',+ userId: 'user-1',},];const query = vi.fn().mockResolvedValue(rows);@@ -93,4 +99,102 @@ describe('AcceptanceService.listWithSubjects', () => {unbounded: false,});});++ it('passes the scope and source narrowings to the candidate query', async () => {+ const query = vi.fn().mockResolvedValue([]);+ const service = new AcceptanceService({} as any, 'user-1') as any;+ service.acceptanceModel = { query };++ await service.listWithSubjects({ projectId: null, scope: 'participated', source: 'goal' });++ expect(query).toHaveBeenCalledWith({+ limit: 50,+ projectId: null,+ scope: 'participated',+ source: 'goal',+ statuses: undefined,+ unbounded: false,+ });+ });++ it('resolves foreign rows in a fixed number of reads however many owners a page spans', async () => {+ mocks.resolveTasks.mockReset();+ mocks.resolveTasks.mockResolvedValue([{ id: 'mine', identifier: 'T-1', name: 'Task mine' }]);+ mocks.resolveTopics.mockResolvedValue([]);+ mocks.resolveDocuments.mockResolvedValue([]);+ mocks.taskScopes.length = 0;++ const foreignOwners = ['user-2', 'user-3', 'user-4', 'user-5'];+ const rows = [+ { id: 'a', subjectId: 'mine', subjectType: 'task', userId: 'user-1', workspaceId: null },+ ...foreignOwners.map((owner, index) => ({+ id: `f${index}`,+ subjectId: `theirs-${index}`,+ subjectType: index % 2 ? 'topic' : 'task',+ userId: owner,+ workspaceId: index === 0 ? 'ws-2' : null,+ })),+ ];+ const db = {+ query: {+ documents: { findMany: vi.fn().mockResolvedValue([]) },+ tasks: {+ findMany: vi.fn().mockResolvedValue([+ { id: 'theirs-0', identifier: 'X-1', name: 'Task theirs-0' },+ { id: 'theirs-2', identifier: 'X-3', name: null },+ ]),+ },+ topics: {+ findMany: vi.fn().mockResolvedValue([{ id: 'theirs-1', title: 'Topic theirs-1' }]),+ },+ },+ };+ const service = new AcceptanceService(db as any, 'user-1') as any;+ service.acceptanceModel = { query: vi.fn().mockResolvedValue(rows) };+ service.latestCheckCounts = vi.fn().mockResolvedValue(new Map());+ service.resolveProjects = vi.fn().mockResolvedValue(new Map());++ const result = await service.listWithSubjects({ scope: 'participated' });++ // One scoped read for the caller's own rows, one unscoped read per type+ // for everyone else's — never a read per owner.+ expect(mocks.taskScopes).toEqual([['user-1', undefined]]);+ expect(db.query.tasks.findMany).toHaveBeenCalledOnce();+ expect(db.query.topics.findMany).toHaveBeenCalledOnce();+ expect(db.query.documents.findMany).not.toHaveBeenCalled();+ expect(service.latestCheckCounts).toHaveBeenCalledOnce();+ expect(+ result.map(({ subject }: { subject: { title: string | null } }) => subject.title),+ ).toEqual(['Task mine', 'Task theirs-0', 'Topic theirs-1', 'X-3', null]);+ });++ it('reads check counts for rows of any owner in two batched queries', async () => {+ const db = {+ query: {+ verifyReports: {+ findMany: vi.fn().mockResolvedValue([+ { totalChecks: 5, verifyRunId: 'run-a2' },+ { totalChecks: 3, verifyRunId: 'run-b1' },+ ]),+ },+ verifyRuns: {+ findMany: vi.fn().mockResolvedValue([+ { acceptanceId: 'a', id: 'run-a1', roundIndex: 1 },+ { acceptanceId: 'a', id: 'run-a2', roundIndex: 2 },+ { acceptanceId: 'b', id: 'run-b1', roundIndex: 1 },+ ]),+ },+ },+ };+ const service = new AcceptanceService(db as any, 'user-1') as any;++ const counts = await service.latestCheckCounts(['a', 'b']);++ expect(db.query.verifyRuns.findMany).toHaveBeenCalledOnce();+ expect(db.query.verifyReports.findMany).toHaveBeenCalledOnce();+ expect([...counts]).toEqual([+ ['a', 5],+ ['b', 3],+ ]);+ });});diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex 2d0122314ba..325e96c1550 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -18,7 +18,12 @@ import type {} from '@lobechat/types';import debug from 'debug';-import { AcceptanceModel } from '@/database/models/acceptance';+import {+ type AcceptanceListProject,+ type AcceptanceListScope,+ type AcceptanceListSource,+ AcceptanceModel,+} from '@/database/models/acceptance';import { AgentModel } from '@/database/models/agent';import { DocumentModel } from '@/database/models/document';import { ProjectModel } from '@/database/models/project';@@ -36,6 +41,7 @@ import type {VerifyRunItem,} from '@/database/schemas/verify';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { ExpertiseRejectionWorkflow } from '@/server/workflows/expertiseRejection';import { type AcceptanceMergeSummary, mergeAcceptanceRounds } from './acceptanceMerge';@@ -451,6 +457,15 @@ export interface AcceptanceSubjectSummary {/** The list filter as a status set — one definition for the flat and paged reads. */export type AcceptanceListFilter = 'active' | 'all' | 'completed';+/** Every narrowing the list panel can apply, shared by the flat and paged reads. */+export interface AcceptanceListOptions {+ filter?: AcceptanceListFilter;+ /** A project id, or `null` for acceptances filed under no project. */+ projectId?: AcceptanceListProject;+ scope?: AcceptanceListScope;+ source?: AcceptanceListSource;+}+const statusesForFilter = (filter: AcceptanceListFilter): AcceptanceStatus[] | undefined => {if (filter === 'active')return ['pending', 'planned', 'verifying', 'repairing', 'delivered', 'rejected', 'errored'];@@ -1355,7 +1370,18 @@ export class AcceptanceService {if (!cur || round > cur.round) latest.set(run.acceptanceId, { id: run.id, round });}- const reports = await this.reportModel.findByRuns([...latest.values()].map((v) => v.id));+ // Unscoped on purpose, like the run read above: the run ids derive from+ // acceptance ids the caller's list query already authorized, and a+ // participated row's report belongs to its owner — an owner-scoped read+ // would need one query per owner.+ const runIds = [...latest.values()].map((v) => v.id);+ const reports =+ runIds.length > 0+ ? await this.db.query.verifyReports.findMany({+ columns: { totalChecks: true, verifyRunId: true },+ where: (report, { inArray }) => inArray(report.verifyRunId, runIds),+ })+ : [];const totalByRun = new Map(reports.map((report) => [report.verifyRunId, report.totalChecks]));for (const [acceptanceId, { id: runId }] of latest) {const total = totalByRun.get(runId);@@ -1371,15 +1397,12 @@ export class AcceptanceService {* carries the latest round's check count for the panel's at-a-glance line.*/listWithSubjects = async (- options: {- filter?: 'active' | 'all' | 'completed';+ options: AcceptanceListOptions & {limit?: number;- projectId?: string;q?: string;} = {},) => {const { filter = 'all', limit = 50, q } = options;- const statuses = statusesForFilter(filter);const normalizedQuery = q?.trim().toLocaleLowerCase();// A title search must span the complete owned set. Subject titles live in@@ -1387,76 +1410,157 @@ export class AcceptanceService {// applying the result cap instead of searching only the latest page.const candidates = await this.acceptanceModel.query({limit: normalizedQuery ? undefined : limit,- statuses,+ projectId: options.projectId,+ scope: options.scope,+ source: options.source,+ statuses: statusesForFilter(filter),unbounded: Boolean(normalizedQuery),- ...(options.projectId ? { projectId: options.projectId } : {}),});- const subjects = await this.resolveSubjects(candidates);- const withSubjects = candidates.map((row) => ({- row,- subject: subjects.get(row.id)!,- }));+ const subjects = await this.resolveSubjectsForList(candidates);const matched = normalizedQuery- ? withSubjects- .filter(({ row, subject }) =>- (subject.title || row.subjectId).toLocaleLowerCase().includes(normalizedQuery),+ ? candidates+ .filter((row) =>+ (subjects.get(row.id)?.title || row.subjectId)+ .toLocaleLowerCase()+ .includes(normalizedQuery),).slice(0, limit)- : withSubjects;- const rows = matched.map(({ row }) => row);- const [checkCounts, projects] = await Promise.all([- this.latestCheckCounts(rows.map((row) => row.id)),- this.resolveProjects(rows),- ]);+ : candidates;- return matched.map(({ row, subject }) => ({- ...row,- checkCount: checkCounts.get(row.id) ?? null,- project: projects.get(row.id) ?? null,- subject,- }));+ return this.decorateListRows(matched, subjects);};/*** 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+ * 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;- projectId?: string;- }) => {+ listPageWithSubjects = async (+ options: AcceptanceListOptions & {+ cursor?: string;+ limit?: number;+ },+ ) => {const { items, nextCursor } = await this.acceptanceModel.queryPage({cursor: options.cursor,limit: options.limit,+ projectId: options.projectId,+ scope: options.scope,+ source: options.source,statuses: statusesForFilter(options.filter ?? 'all'),- ...(options.projectId ? { projectId: options.projectId } : {}),});- 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)!,- })),+ items: await this.decorateListRows(items, await this.resolveSubjectsForList(items)),nextCursor,};};+ private isInOwnScope = (row: AcceptanceItem) =>+ row.workspaceId+ ? row.workspaceId === this.workspaceId+ : !this.workspaceId && row.userId === this.userId;++ /**+ * Subject headers for a mixed list. Rows in the caller's own scope go through+ * the scoped models as before. A participated row may belong to any number of+ * other owners, whose task/topic/document the caller's models cannot see —+ * those resolve in ONE unscoped read per subject type, so the cost stays+ * fixed however many owners a page spans. Safe because the list query has+ * already applied the read rule to these rows, and the bundle shows the same+ * title to anyone who can open them.+ */+ private resolveSubjectsForList = async (+ rows: AcceptanceItem[],+ ): Promise<Map<string, AcceptanceSubjectSummary>> => {+ const own = rows.filter(this.isInOwnScope);+ const foreign = rows.filter((row) => !this.isInOwnScope(row));+ const [ownSubjects, foreignSubjects] = await Promise.all([+ own.length > 0 ? this.resolveSubjects(own) : new Map<string, AcceptanceSubjectSummary>(),+ this.resolveForeignSubjects(foreign),+ ]);+ return new Map([...ownSubjects, ...foreignSubjects]);+ };++ private resolveForeignSubjects = async (+ rows: AcceptanceItem[],+ ): Promise<Map<string, AcceptanceSubjectSummary>> => {+ const result = new Map<string, AcceptanceSubjectSummary>();+ if (rows.length === 0) return result;++ const idsOf = (type: AcceptanceSubjectType) =>+ rows.filter((row) => row.subjectType === type).map((row) => row.subjectId);+ const titles = new Map<string, string | null>();+ try {+ const [taskIds, topicIds, documentIds] = [idsOf('task'), idsOf('topic'), idsOf('document')];+ const [taskRows, topicRows, documentRows] = await Promise.all([+ taskIds.length > 0+ ? this.db.query.tasks.findMany({+ columns: { id: true, identifier: true, name: true },+ where: (task, { and, inArray }) =>+ and(inArray(task.id, taskIds), notTrashed(task.isDeleted)),+ })+ : [],+ topicIds.length > 0+ ? this.db.query.topics.findMany({+ columns: { id: true, title: true },+ where: (topic, { and, inArray }) =>+ and(inArray(topic.id, topicIds), notTrashed(topic.isDeleted)),+ })+ : [],+ documentIds.length > 0+ ? this.db.query.documents.findMany({+ columns: { id: true, title: true },+ where: (document, { and, inArray }) =>+ and(inArray(document.id, documentIds), notTrashed(document.isDeleted)),+ })+ : [],+ ]);+ for (const task of taskRows) titles.set(`task:${task.id}`, task.name ?? task.identifier);+ for (const topic of topicRows) titles.set(`topic:${topic.id}`, topic.title ?? null);+ for (const document of documentRows)+ titles.set(`document:${document.id}`, document.title ?? null);+ } catch (error) {+ log('resolveForeignSubjects failed (non-fatal): %O', error);+ }++ for (const row of rows) {+ const override = row.metadata?.title;+ const overrideTitle =+ typeof override === 'string' && override.trim() ? override.trim() : null;+ result.set(row.id, {+ id: row.subjectId,+ title: overrideTitle ?? titles.get(`${row.subjectType}:${row.subjectId}`) ?? null,+ type: row.subjectType as AcceptanceSubjectType,+ });+ }+ return result;+ };++ private decorateListRows = async (+ rows: AcceptanceItem[],+ subjects: Map<string, AcceptanceSubjectSummary>,+ ) => {+ const [checkCounts, projects] = await Promise.all([+ this.latestCheckCounts(rows.map((row) => row.id)),+ // Projects stay in the caller's scope: another owner's project name is+ // theirs, and a row filed under it simply reads as unfiled here.+ this.resolveProjects(rows),+ ]);++ return rows.map((row) => ({+ ...row,+ checkCount: checkCounts.get(row.id) ?? null,+ project: projects.get(row.id) ?? null,+ subject: subjects.get(row.id)!,+ }));+ };+/*** The authoring conversation behind the round chain, resolved to displayable* entities (agent avatar/title, topic title). Owner-only header data — thediff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 87f0c5f7577..10f5dfe50c6 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -423,8 +423,23 @@"acceptance.workspace.filters.empty.active": "No acceptances in progress.","acceptance.workspace.filters.empty.all": "No acceptances yet.","acceptance.workspace.filters.empty.completed": "No completed acceptances.",+ "acceptance.workspace.filters.empty.filtered": "No acceptances match these filters.","acceptance.workspace.filters.noSearchResults": "No acceptances match “{{query}}”.",+ "acceptance.workspace.filters.project.all": "All projects",+ "acceptance.workspace.filters.project.none": "No project",+ "acceptance.workspace.filters.project.title": "Project",+ "acceptance.workspace.filters.scope.all": "All",+ "acceptance.workspace.filters.scope.created": "Created by me",+ "acceptance.workspace.filters.scope.participated": "Participated",+ "acceptance.workspace.filters.scope.title": "Scope","acceptance.workspace.filters.showAll": "Show all acceptances",+ "acceptance.workspace.filters.source.all": "All sources",+ "acceptance.workspace.filters.source.goal": "Goals",+ "acceptance.workspace.filters.source.standalone": "Standalone",+ "acceptance.workspace.filters.source.task": "Tasks",+ "acceptance.workspace.filters.source.title": "Source",+ "acceptance.workspace.filters.source.topic": "Topics",+ "acceptance.workspace.filters.status": "Status","acceptance.workspace.filters.title": "Filter acceptances","acceptance.workspace.groups.actions": "Project actions","acceptance.workspace.groups.byNone": "No grouping",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 9f07f24ec1d..98568c83220 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -423,8 +423,23 @@"acceptance.workspace.filters.empty.active": "暂无进行中的验收。","acceptance.workspace.filters.empty.all": "暂无验收。","acceptance.workspace.filters.empty.completed": "暂无已完成的验收。",+ "acceptance.workspace.filters.empty.filtered": "没有符合筛选条件的验收。","acceptance.workspace.filters.noSearchResults": "没有与「{{query}}」匹配的验收。",+ "acceptance.workspace.filters.project.all": "全部项目",+ "acceptance.workspace.filters.project.none": "未归档",+ "acceptance.workspace.filters.project.title": "项目",+ "acceptance.workspace.filters.scope.all": "全部",+ "acceptance.workspace.filters.scope.created": "我创建的",+ "acceptance.workspace.filters.scope.participated": "我参与的",+ "acceptance.workspace.filters.scope.title": "范围","acceptance.workspace.filters.showAll": "显示全部验收",+ "acceptance.workspace.filters.source.all": "全部来源",+ "acceptance.workspace.filters.source.goal": "目标",+ "acceptance.workspace.filters.source.standalone": "独立",+ "acceptance.workspace.filters.source.task": "任务",+ "acceptance.workspace.filters.source.title": "来源",+ "acceptance.workspace.filters.source.topic": "话题",+ "acceptance.workspace.filters.status": "状态","acceptance.workspace.filters.title": "筛选验收","acceptance.workspace.groups.actions": "项目操作","acceptance.workspace.groups.byNone": "不分组",diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.tsindex 69c78c4177a..baebefe4b98 100644--- a/packages/database/src/models/__tests__/acceptance.test.ts+++ b/packages/database/src/models/__tests__/acceptance.test.ts@@ -4,7 +4,18 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { acceptances, topics, users, verifyRuns, workspaces } from '../../schemas';+import {+ acceptanceComments,+ acceptances,+ goalNodes,+ goals,+ tasks,+ topics,+ users,+ verifyRuns,+ workspaceMembers,+ workspaces,+} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AcceptanceModel } from '../acceptance';import { ProjectModel } from '../project';@@ -258,6 +269,186 @@ describe('AcceptanceModel', () => {});});+ it('filters by project to only the unfiled acceptances when projectId is null', async () => {+ const alpha = await new ProjectModel(serverDB, userId).create({+ identifier: 'ALPHA',+ name: 'Alpha project',+ });+ const model = new AcceptanceModel(serverDB, userId);+ await model.create({ projectId: alpha.id, subjectId: 'filed', subjectType: 'standalone' });+ await model.create({ subjectId: 'unfiled', subjectType: 'standalone' });++ expect((await model.query({ projectId: null })).map((row) => row.subjectId)).toEqual([+ 'unfiled',+ ]);+ expect((await model.queryPage({ projectId: null })).items.map((row) => row.subjectId)).toEqual([+ 'unfiled',+ ]);+ });++ it('splits task acceptances into goal steps and plain tasks by source', async () => {+ await serverDB.insert(tasks).values([+ {+ createdByUserId: userId,+ id: 'goal-step-task',+ identifier: 'T-1',+ instruction: 'x',+ seq: 1,+ },+ { createdByUserId: userId, id: 'plain-task', identifier: 'T-2', instruction: 'x', seq: 2 },+ ]);+ const [goal] = await serverDB.insert(goals).values({ title: 'Ship it', userId }).returning();+ await serverDB+ .insert(goalNodes)+ .values({ goalId: goal.id, kind: 'task', taskId: 'goal-step-task', title: 'Step' });++ const model = new AcceptanceModel(serverDB, userId);+ await model.create({ subjectId: 'goal-step-task', subjectType: 'task' });+ await model.create({ subjectId: 'plain-task', subjectType: 'task' });+ await model.create({ subjectId: topicId, subjectType: 'topic' });+ await model.create({ subjectId: 'cli-run', subjectType: 'standalone' });+ await model.create({ subjectId: 'doc-1', subjectType: 'document' });++ const subjectsFor = async (source: 'goal' | 'standalone' | 'task' | 'topic') =>+ (await model.queryPage({ source })).items.map((row) => row.subjectId).sort();++ expect(await subjectsFor('goal')).toEqual(['goal-step-task']);+ expect(await subjectsFor('task')).toEqual(['plain-task']);+ expect(await subjectsFor('topic')).toEqual([topicId]);+ expect(await subjectsFor('standalone')).toEqual(['cli-run', 'doc-1']);+ expect(await model.query({ source: 'all' })).toHaveLength(5);+ });++ describe('scope', () => {+ const thirdUserId = 'acceptance-test-third';+ const workspaceId = 'acceptance-test-ws';++ beforeEach(async () => {+ await serverDB.insert(users).values({ id: thirdUserId });+ });++ afterEach(async () => {+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ });++ const comment = (acceptanceId: string, authorUserId: string, kind = 'comment') =>+ serverDB.insert(acceptanceComments).values({+ acceptanceId,+ authorUserId,+ clientId: `${acceptanceId}-${authorUserId}-${kind}`,+ content: 'looks good',+ kind: kind as 'comment',+ });++ it('lists every readable acceptance the caller commented on or approved, across owners', async () => {+ const mine = await new AcceptanceModel(serverDB, userId).create({+ subjectId: 'mine',+ subjectType: 'standalone',+ });+ const otherModel = new AcceptanceModel(serverDB, otherUserId);+ const sharedPublic = await otherModel.create({+ subjectId: 'shared-public',+ subjectType: 'standalone',+ visibility: 'public',+ });+ const approved = await otherModel.create({+ subjectId: 'approved',+ subjectType: 'standalone',+ visibility: 'public',+ });+ const reactedOnly = await otherModel.create({+ subjectId: 'reacted-only',+ subjectType: 'standalone',+ visibility: 'public',+ });+ const untouched = await otherModel.create({+ subjectId: 'untouched',+ subjectType: 'standalone',+ visibility: 'public',+ });+ const madePrivate = await otherModel.create({+ subjectId: 'made-private',+ subjectType: 'standalone',+ visibility: 'private',+ });++ await comment(mine.id, userId);+ await comment(sharedPublic.id, userId);+ await comment(approved.id, userId, 'approval');+ await comment(reactedOnly.id, userId, 'reaction');+ await comment(untouched.id, thirdUserId);+ await comment(madePrivate.id, userId);++ const model = new AcceptanceModel(serverDB, userId);+ const expected = ['approved', 'mine', 'shared-public'];+ expect(+ (await model.query({ scope: 'participated' })).map((row) => row.subjectId).sort(),+ ).toEqual(expected);+ expect(+ (await model.queryPage({ scope: 'participated' })).items.map((row) => row.subjectId).sort(),+ ).toEqual(expected);+ });++ it('keeps private acceptances of the caller own workspace readable through membership', async () => {+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: otherUserId, slug: workspaceId });+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId: otherUserId, workspaceId },+ { role: 'editor', userId, workspaceId },+ ]);+ const teammate = new AcceptanceModel(serverDB, otherUserId, workspaceId);+ const internal = await teammate.create({+ subjectId: 'internal',+ subjectType: 'standalone',+ visibility: 'private',+ });+ await comment(internal.id, userId);++ // Participation follows the person, so the personal scope still sees it.+ const personal = new AcceptanceModel(serverDB, userId);+ expect((await personal.query({ scope: 'participated' })).map((row) => row.id)).toEqual([+ internal.id,+ ]);++ // Leaving the workspace takes it away.+ await serverDB+ .update(workspaceMembers)+ .set({ deletedAt: new Date() })+ .where(eq(workspaceMembers.userId, userId));+ expect(await personal.query({ scope: 'participated' })).toEqual([]);+ });++ it('narrows the workspace list to the caller own acceptances with created', async () => {+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId, workspaceId },+ { role: 'editor', userId: otherUserId, workspaceId },+ ]);+ await new AcceptanceModel(serverDB, userId, workspaceId).create({+ subjectId: 'by-me',+ subjectType: 'standalone',+ visibility: 'public',+ });+ await new AcceptanceModel(serverDB, otherUserId, workspaceId).create({+ subjectId: 'by-teammate',+ subjectType: 'standalone',+ visibility: 'public',+ });++ const model = new AcceptanceModel(serverDB, userId, workspaceId);+ expect((await model.query({ scope: 'all' })).map((row) => row.subjectId).sort()).toEqual([+ 'by-me',+ 'by-teammate',+ ]);+ expect((await model.query({ scope: 'created' })).map((row) => row.subjectId)).toEqual([+ 'by-me',+ ]);+ });+ });+it('updateStatus stamps completedAt only on user-terminal statuses', async () => {const model = new AcceptanceModel(serverDB, userId);const row = await model.ensureForSubject('topic', topicId);diff --git a/packages/database/src/models/__tests__/workspaceMember.test.ts b/packages/database/src/models/__tests__/workspaceMember.test.tsindex cc0ed342174..634a9817c92 100644--- a/packages/database/src/models/__tests__/workspaceMember.test.ts+++ b/packages/database/src/models/__tests__/workspaceMember.test.ts@@ -121,6 +121,33 @@ describe('WorkspaceMemberModel', () => {});});+ describe('getRolesInWorkspaces', () => {+ it("returns the user's active role per workspace in one read", async () => {+ const model = new WorkspaceMemberModel(serverDB, inviterId);+ await model.addMember({ role: 'viewer', userId: memberId, workspaceId });+ await model.addMember({ role: 'admin', userId: memberId, workspaceId: otherWorkspaceId });+ await model.addMember({ userId: otherUserId, workspaceId });++ const roles = await model.getRolesInWorkspaces([workspaceId, otherWorkspaceId], memberId);++ expect(Object.fromEntries(roles)).toEqual({+ [otherWorkspaceId]: 'admin',+ [workspaceId]: 'viewer',+ });+ });++ it('omits workspaces the user left or never joined', async () => {+ const model = new WorkspaceMemberModel(serverDB, inviterId);+ await model.addMember({ userId: memberId, workspaceId });+ await model.removeMember(workspaceId, memberId);++ expect(await model.getRolesInWorkspaces([workspaceId, otherWorkspaceId], memberId)).toEqual(+ new Map(),+ );+ expect(await model.getRolesInWorkspaces([], memberId)).toEqual(new Map());+ });+ });+describe('listMembers', () => {it('lists only active members by default', async () => {const model = new WorkspaceMemberModel(serverDB, inviterId);diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.tsindex ee7714a39cc..73c8f504d1f 100644--- a/packages/database/src/models/acceptance.ts+++ b/packages/database/src/models/acceptance.ts@@ -4,14 +4,43 @@ import type {AcceptanceStatus,AcceptanceSubjectType,} from '@lobechat/types';-import { and, desc, eq, inArray, lt, or, sql } from 'drizzle-orm';+import type { SQL } from 'drizzle-orm';+import { and, desc, eq, exists, inArray, isNull, lt, not, or, sql } from 'drizzle-orm';+import { acceptanceComments } from '../schemas/acceptanceComment';+import { goalNodes } from '../schemas/goalGraph';import type { AcceptanceItem, NewAcceptance } from '../schemas/verify';import { acceptances } from '../schemas/verify';+import { workspaceMembers } from '../schemas/workspace';import type { LobeChatDatabase } from '../type';import { isUuid } from '../utils/uuid';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+/**+ * Whose acceptances the list shows.+ *+ * `all` / `created` stay inside the active scope (personal or workspace);+ * `participated` follows the caller across scopes — taking part in a review+ * is about the person, not the workspace they happen to have open.+ */+export type AcceptanceListScope = 'all' | 'created' | 'participated';++/**+ * Where an acceptance came from. `goal` is a task acceptance whose task is a+ * step of a goal graph; `standalone` also covers the rare document subject.+ */+export type AcceptanceListSource = 'all' | 'goal' | 'standalone' | 'task' | 'topic';++/** `null` = only acceptances filed under no project. */+export type AcceptanceListProject = string | null;++export interface AcceptanceListQuery {+ projectId?: AcceptanceListProject;+ scope?: AcceptanceListScope;+ source?: AcceptanceListSource;+ statuses?: AcceptanceStatus[];+}+/** Statuses a user's decision produced — sticky until explicitly re-opened. */const TERMINAL_ACCEPTANCE_STATUSES = new Set<AcceptanceStatus>(['accepted', 'closed', 'rejected']);@@ -57,6 +86,93 @@ export class AcceptanceModel {private ownership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, acceptances);+ /**+ * Acceptances the caller has spoken on — a remark or an approval, replies+ * included; a bare emoji reaction is not taking part. Rows the caller can no+ * longer read (made private, or they left its workspace) drop out: the link+ * would 404 and the title is no longer theirs to see. Mirrors the read rule+ * of `resolveAcceptanceCommentAccess`.+ */+ private participation = (): SQL =>+ and(+ exists(+ this.db+ .select({ one: sql`1` })+ .from(acceptanceComments)+ .where(+ and(+ eq(acceptanceComments.acceptanceId, acceptances.id),+ eq(acceptanceComments.authorUserId, this.userId),+ inArray(acceptanceComments.kind, ['comment', 'approval']),+ isNull(acceptanceComments.deletedAt),+ ),+ ),+ ),+ or(+ eq(acceptances.userId, this.userId),+ eq(acceptances.visibility, 'public'),+ exists(+ this.db+ .select({ one: sql`1` })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, acceptances.workspaceId),+ eq(workspaceMembers.userId, this.userId),+ isNull(workspaceMembers.deletedAt),+ ),+ ),+ ),+ ),+ )!;++ private sourceCondition = (source: AcceptanceListSource): SQL | undefined => {+ const goalStep = exists(+ this.db+ .select({ one: sql`1` })+ .from(goalNodes)+ .where(eq(goalNodes.taskId, acceptances.subjectId)),+ );+ switch (source) {+ case 'topic': {+ return eq(acceptances.subjectType, 'topic');+ }+ case 'task': {+ return and(eq(acceptances.subjectType, 'task'), not(goalStep));+ }+ case 'goal': {+ return and(eq(acceptances.subjectType, 'task'), goalStep);+ }+ case 'standalone': {+ return inArray(acceptances.subjectType, ['standalone', 'document']);+ }+ default: {+ return undefined;+ }+ }+ };++ /** The shared WHERE of {@link query} and {@link queryPage}. */+ private listConditions = ({+ projectId,+ scope = 'all',+ source = 'all',+ statuses,+ }: AcceptanceListQuery) => {+ const conditions: SQL[] = [];+ if (scope === 'participated') conditions.push(this.participation());+ else {+ conditions.push(this.ownership());+ if (scope === 'created') conditions.push(eq(acceptances.userId, this.userId));+ }+ if (projectId === null) conditions.push(isNull(acceptances.projectId));+ else if (projectId) conditions.push(eq(acceptances.projectId, projectId));+ if (statuses && statuses.length > 0) conditions.push(inArray(acceptances.status, statuses));+ const sourceCondition = this.sourceCondition(source);+ if (sourceCondition) conditions.push(sourceCondition);+ return conditions;+ };+/** Presentation-only write: never starts a round or rewrites evidence-bearing snapshots. */setCheckGroups = async (id: string, groups: AcceptanceCheckGroup[], expectedVersion: number) => {return this.db.transaction(async (tx) => {@@ -261,18 +377,14 @@ export class AcceptanceModel {/** Acceptances for the current user/workspace, newest first. */query = async (- options: {+ options: AcceptanceListQuery & {limit?: number;- projectId?: string;- statuses?: AcceptanceStatus[];unbounded?: boolean;} = {},) => {- const { projectId, statuses, unbounded } = options;+ const { unbounded, ...filters } = options;const limit = unbounded ? undefined : (options.limit ?? 50);- const conditions = [this.ownership()];- if (projectId) conditions.push(eq(acceptances.projectId, projectId));- if (statuses && statuses.length > 0) conditions.push(inArray(acceptances.status, statuses));+ const conditions = this.listConditions(filters);return this.db.query.acceptances.findMany({limit,@@ -291,20 +403,15 @@ export class AcceptanceModel {queryPage = async ({cursor,limit = 30,- projectId,- statuses,- }: {+ ...filters+ }: AcceptanceListQuery & {cursor?: string;limit?: number;- projectId?: string;- statuses?: AcceptanceStatus[];} = {}): Promise<{items: AcceptanceItem[];nextCursor: string | null;}> => {- const conditions = [this.ownership()];- if (projectId) conditions.push(eq(acceptances.projectId, projectId));- if (statuses && statuses.length > 0) conditions.push(inArray(acceptances.status, statuses));+ const conditions = this.listConditions(filters);// Millisecond-truncated createdAt — the precision the cursor round-trips// at. Comparing the raw timestamptz (microseconds) against a cursor readdiff --git a/packages/database/src/models/workspaceMember.ts b/packages/database/src/models/workspaceMember.tsindex 70408e8bc6a..679d51cfd5a 100644--- a/packages/database/src/models/workspaceMember.ts+++ b/packages/database/src/models/workspaceMember.ts@@ -62,6 +62,29 @@ export class WorkspaceMemberModel {});};+ /**+ * The caller's active roles across many workspaces in ONE read — for list+ * surfaces whose rows span workspaces, where a `getMember` per workspace+ * would turn a page into a chain of sequential queries.+ */+ getRolesInWorkspaces = async (+ workspaceIds: string[],+ userId: string,+ ): Promise<Map<string, string>> => {+ if (workspaceIds.length === 0) return new Map();+ const rows = await this.db+ .select({ role: workspaceMembers.role, workspaceId: workspaceMembers.workspaceId })+ .from(workspaceMembers)+ .where(+ and(+ inArray(workspaceMembers.workspaceId, workspaceIds),+ eq(workspaceMembers.userId, userId),+ isNull(workspaceMembers.deletedAt),+ ),+ );+ return new Map(rows.map((row) => [row.workspaceId, row.role]));+ };+/** Lock an active membership row. Call only from an enclosing transaction. */getMemberForUpdate = async (workspaceId: string, userId: string) => {const [member] = await this.dbdiff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 2b5a4898b06..9e75ea433bc 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -563,6 +563,21 @@ export default {'acceptance.workspace.filters.empty.all': 'No acceptances yet.','acceptance.workspace.filters.empty.active': 'No acceptances in progress.','acceptance.workspace.filters.empty.completed': 'No completed acceptances.',+ 'acceptance.workspace.filters.empty.filtered': 'No acceptances match these filters.',+ 'acceptance.workspace.filters.project.all': 'All projects',+ 'acceptance.workspace.filters.project.none': 'No project',+ 'acceptance.workspace.filters.project.title': 'Project',+ 'acceptance.workspace.filters.scope.all': 'All',+ 'acceptance.workspace.filters.scope.created': 'Created by me',+ 'acceptance.workspace.filters.scope.participated': 'Participated',+ 'acceptance.workspace.filters.scope.title': 'Scope',+ 'acceptance.workspace.filters.source.all': 'All sources',+ 'acceptance.workspace.filters.source.goal': 'Goals',+ 'acceptance.workspace.filters.source.standalone': 'Standalone',+ 'acceptance.workspace.filters.source.task': 'Tasks',+ 'acceptance.workspace.filters.source.title': 'Source',+ 'acceptance.workspace.filters.source.topic': 'Topics',+ 'acceptance.workspace.filters.status': 'Status','acceptance.workspace.filters.noSearchResults': 'No acceptances match “{{query}}”.','acceptance.workspace.filters.showAll': 'Show all acceptances','acceptance.workspace.filters.title': 'Filter acceptances',diff --git a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsxindex ac717b69e8f..e3a3b707b90 100644--- a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx+++ b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx@@ -18,10 +18,8 @@ import { createStaticStyles, cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';import {ArrowLeft,- Check,CircleDashed,FolderClosed,- Group,ListChecks,ListFilter,MoreHorizontal,@@ -34,6 +32,7 @@ import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate, useParams } from 'react-router';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { SkeletonList } from '@/features/NavPanel/components/SkeletonList';import { useLocalStorageState } from '@/hooks/useLocalStorageState';import { mutate as globalMutate } from '@/libs/swr';@@ -50,9 +49,16 @@ import AcceptanceBatchBar from './AcceptanceBatchBar';import { openAcceptanceDeleteConfirm } from './AcceptanceDeleteConfirm';import {acceptanceListEmptyVariant,+ type AcceptanceListFacets,type AcceptanceListFilter,+ acceptanceProjectScopeKey,+ DEFAULT_ACCEPTANCE_LIST_FACETS,DEFAULT_ACCEPTANCE_LIST_FILTER,+ effectiveAcceptanceListFacets,+ isAcceptanceListFacetsNarrowed,+ normalizeAcceptanceListFacets,normalizeAcceptanceListFilter,+ resetAcceptanceListFacets,} from './acceptanceListFilter';import AcceptanceRow from './AcceptanceRow';import {@@ -75,11 +81,13 @@ import {normalizeAcceptanceGroupMode,shouldRenderAcceptanceGroups,} from './groupAcceptanceList';+import { useAcceptanceListFilterMenu } from './useAcceptanceListFilterMenu';import type { ReportPanelExpand } from './useReportPanelExpand';const PANEL_MIN = 260;const PANEL_MAX = 420;const ACCEPTANCE_LIST_FILTER_STORAGE_KEY = 'lobehub-acceptance-list-filter';+const ACCEPTANCE_LIST_FACETS_STORAGE_KEY = 'lobehub-acceptance-list-facets';const ACCEPTANCE_GROUP_MODE_STORAGE_KEY = 'lobehub-acceptance-group-mode';/** Pull the next page before the sentinel is actually on screen. */const LOAD_MORE_ROOT_MARGIN = '240px';@@ -307,7 +315,24 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(ACCEPTANCE_GROUP_MODE_STORAGE_KEY,DEFAULT_ACCEPTANCE_GROUP_MODE,);+ const [storedFacets, setStoredFacets] = useLocalStorageState<AcceptanceListFacets>(+ ACCEPTANCE_LIST_FACETS_STORAGE_KEY,+ DEFAULT_ACCEPTANCE_LIST_FACETS,+ );const filter = normalizeAcceptanceListFilter(storedFilter);+ // A project choice is only meaningful in the workspace it was made in.+ const workspaceId = useActiveWorkspaceId();+ const facets = normalizeAcceptanceListFacets(+ storedFacets,+ acceptanceProjectScopeKey(workspaceId),+ );+ const facetsNarrowed = isAcceptanceListFacetsNarrowed(facets, projectId);+ const {+ projectId: listProjectId,+ scope,+ source,+ } = effectiveAcceptanceListFacets(facets, projectId);+ const listQuery = { projectId: listProjectId, scope, source };const groupMode = normalizeAcceptanceGroupMode(storedGroupMode);const debouncedQuery = useDebounce(query.trim(), { wait: 300 });const trimmedQuery = query.trim();@@ -318,8 +343,8 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(// WHOLE owned set — a paged search would only ever match what had scrolled// in, and would report an exhausted list while the match sat on page four.const search = useAcceptanceList(searching, {+ ...listQuery,filter,- projectId,q: debouncedQuery || undefined,});const {@@ -329,7 +354,7 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(items: pagedItems,loadMore,...pagedRest- } = useAcceptanceListInfinite(searching ? null : filter, projectId);+ } = useAcceptanceListInfinite(searching ? null : filter, listQuery);const items = searching ? (search.data ?? []) : pagedItems;const error = searching ? search.error : pagedRest.error;@@ -345,6 +370,7 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(});const emptyVariant = acceptanceListEmptyVariant({allListEmpty: allProbe.data ? allProbe.data.length === 0 : undefined,+ facetsNarrowed,filter,searching: Boolean(trimmedQuery),});@@ -379,8 +405,11 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(const [selected, setSelected] = useState<string[]>([]);const [anchorId, setAnchorId] = useState<string | null>(null);const [batchPending, setBatchPending] = useState(false);- const selectedVisible = visibleAcceptanceSelection(selected, items);- const selectAllState = acceptanceSelectAllState(items.length, selectedVisible.length);+ // Someone else's acceptance (a participated row) cannot be swept: the+ // batch writes would refuse it, so it never enters the selection at all.+ const selectableItems = items.filter((item) => item.canManage);+ const selectedVisible = visibleAcceptanceSelection(selected, selectableItems);+ const selectAllState = acceptanceSelectAllState(selectableItems.length, selectedVisible.length);const leaveSelecting = () => {setSelecting(false);@@ -586,9 +615,9 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(// to carry it on the row or the affiliation is simply not on screen.const showRowProject = groupMode !== 'project';- const orderedIds = (showGroups ? groups.flatMap((group) => group.items) : items).map(- (item) => item.id,- );+ const orderedIds = (showGroups ? groups.flatMap((group) => group.items) : items)+ .filter((item) => item.canManage)+ .map((item) => item.id);// Shift/⌘-click on a row while browsing enters selection on the spot: a// shift range starts from the open record, a ⌘ pick from nothing.@@ -609,48 +638,24 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(setAnchorId(id);};- const rowSelectionProps = (id: string) => ({- selectable: selecting,- selected: selecting && selectedVisible.includes(id),- onToggleSelect: (shift: boolean) => pickRow(id, shift),+ const rowSelectionProps = (item: { canManage: boolean; id: string }) => ({+ selectable: selecting && item.canManage,+ selected: selecting && selectedVisible.includes(item.id),+ onToggleSelect: item.canManage ? (shift: boolean) => pickRow(item.id, shift) : undefined,});// Grouping shares the filter's popover rather than taking a fourth icon in a// 260px header: both answer "what does this list show me", and one of them// is a preference the user sets once.- const filterItems: DropdownItem[] = [- ...(- [- ['active', t('acceptance.workspace.filters.active')],- ['all', t('acceptance.workspace.filters.all')],- ['completed', t('acceptance.workspace.filters.completed')],- ] as const- ).map(([key, label]) => ({- icon: <Icon icon={Check} style={{ opacity: filter === key ? 1 : 0 }} />,- key,- label,- onClick: () => setStoredFilter(key),- })),- { type: 'divider' as const },- {- children: (- [- ['project', t('acceptance.workspace.groups.byProject')],- ['status', t('acceptance.workspace.groups.byStatus')],- ['time', t('acceptance.workspace.groups.byTime')],- ['none', t('acceptance.workspace.groups.byNone')],- ] as const- ).map(([key, label]) => ({- icon: <Icon icon={Check} style={{ opacity: groupMode === key ? 1 : 0 }} />,- key,- label,- onClick: () => setStoredGroupMode(key),- })),- icon: <Icon icon={Group} />,- key: 'group-mode',- label: t('acceptance.workspace.groups.mode'),- },- ];+ const filterItems = useAcceptanceListFilterMenu({+ facets,+ filter,+ groupMode,+ hostProjectId: projectId,+ setFacets: setStoredFacets,+ setFilter: setStoredFilter,+ setGroupMode: setStoredGroupMode,+ });// One overflow menu for everything the header offers. Multi-select used to// sit outside as its own icon; a 260px header cannot carry a fourth control@@ -729,7 +734,7 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(</label><DropdownMenu items={filterItems} placement={'bottomRight'}><ActionIcon- active={filter !== 'all'}+ active={filter !== 'all' || facetsNarrowed}className={styles.filterButton}icon={ListFilter}size={'small'}@@ -750,9 +755,11 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(<div className={styles.selectionRow}><Checkboxchecked={selectAllState === 'all'}- disabled={items.length === 0}+ disabled={selectableItems.length === 0}indeterminate={selectAllState === 'partial'}- onChange={() => setSelected((previous) => nextAcceptanceSelectAll(previous, items))}+ onChange={() =>+ setSelected((previous) => nextAcceptanceSelectAll(previous, selectableItems))+ }>{t('acceptance.workspace.batch.selectAll')}</Checkbox>@@ -791,9 +798,11 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(<span className={styles.searchEmptyMsg}>{trimmedQuery? t('acceptance.workspace.filters.noSearchResults', { query: trimmedQuery })- : filter === 'all'- ? null- : t(EMPTY_FILTER_KEYS[filter])}+ : facetsNarrowed+ ? t('acceptance.workspace.filters.empty.filtered')+ : filter === 'all'+ ? null+ : t(EMPTY_FILTER_KEYS[filter])}</span><buttonclassName={styles.retryBtn}@@ -801,6 +810,7 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(onClick={() => {setQuery('');setStoredFilter('all');+ setStoredFacets(resetAcceptanceListFacets(facets, projectId));}}>{t('acceptance.workspace.filters.showAll')}@@ -861,7 +871,7 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(key={item.id}showProject={showRowProject}onChanged={mutate}- {...rowSelectionProps(item.id)}+ {...rowSelectionProps(item)}/>))}</div>@@ -881,7 +891,7 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(key={item.id}showProject={showRowProject}onChanged={mutate}- {...rowSelectionProps(item.id)}+ {...rowSelectionProps(item)}/>)))}diff --git a/src/features/Acceptance/Workspace/AcceptanceRow.tsx b/src/features/Acceptance/Workspace/AcceptanceRow.tsxindex 54b19267444..f02c259516a 100644--- a/src/features/Acceptance/Workspace/AcceptanceRow.tsx+++ b/src/features/Acceptance/Workspace/AcceptanceRow.tsx@@ -335,8 +335,10 @@ const AcceptanceRow = memo<{// Only where the grouping does not already say it, and only when the row// actually has one — stamping "ungrouped" on every other row would cost a// line of height to say nothing.+ // Someone else's acceptance (a participated row) offers no menu: every+ // entry in it is a write its owner alone may make.actions={- selectable ? undefined : (+ selectable || !item.canManage ? undefined : (<DropdownMenuiconSpaceMode={'group'}items={menuItems}@@ -381,8 +383,8 @@ const AcceptanceRow = memo<{: undefined}onClick={(e) => {- if (selectable || e.shiftKey || e.metaKey || e.ctrlKey) {- onToggleSelect?.(e.shiftKey);+ if (onToggleSelect && (selectable || e.shiftKey || e.metaKey || e.ctrlKey)) {+ onToggleSelect(e.shiftKey);return;}navigate(`/acceptance/${item.id}`);diff --git a/src/features/Acceptance/Workspace/acceptanceListFilter.test.ts b/src/features/Acceptance/Workspace/acceptanceListFilter.test.tsindex 1abb985edd3..c620497822e 100644--- a/src/features/Acceptance/Workspace/acceptanceListFilter.test.ts+++ b/src/features/Acceptance/Workspace/acceptanceListFilter.test.ts@@ -1,6 +1,14 @@import { describe, expect, it } from 'vitest';-import { acceptanceListEmptyVariant, normalizeAcceptanceListFilter } from './acceptanceListFilter';+import {+ acceptanceListEmptyVariant,+ acceptanceProjectScopeKey,+ effectiveAcceptanceListFacets,+ isAcceptanceListFacetsNarrowed,+ normalizeAcceptanceListFacets,+ normalizeAcceptanceListFilter,+ resetAcceptanceListFacets,+} from './acceptanceListFilter';describe('normalizeAcceptanceListFilter', () => {it('falls back to the active filter for malformed persisted values', () => {@@ -35,3 +43,90 @@ describe('acceptanceListEmptyVariant', () => {).toBe('firstRun');});});++describe('normalizeAcceptanceListFacets', () => {+ it('keeps valid persisted facets, including the unfiled project', () => {+ expect(+ normalizeAcceptanceListFacets({ projectId: null, scope: 'participated', source: 'goal' }),+ ).toEqual({ projectId: null, projectScope: 'personal', scope: 'participated', source: 'goal' });+ expect(normalizeAcceptanceListFacets({ projectId: 'proj-1' }).projectId).toBe('proj-1');+ });++ it('falls back per field for malformed values', () => {+ expect(normalizeAcceptanceListFacets(null)).toEqual({+ projectId: undefined,+ projectScope: 'personal',+ scope: 'all',+ source: 'all',+ });+ expect(+ normalizeAcceptanceListFacets({ projectId: 3, scope: 'mine', source: 'document' }),+ ).toEqual({ projectId: undefined, projectScope: 'personal', scope: 'all', source: 'all' });+ });++ it('drops a project choice made in another workspace but keeps scope and source', () => {+ const stored = {+ projectId: 'proj-a',+ projectScope: 'ws-a',+ scope: 'participated',+ source: 'goal',+ };++ expect(normalizeAcceptanceListFacets(stored, 'ws-a').projectId).toBe('proj-a');+ expect(normalizeAcceptanceListFacets(stored, 'ws-b')).toEqual({+ projectId: undefined,+ projectScope: 'ws-b',+ scope: 'participated',+ source: 'goal',+ });+ expect(normalizeAcceptanceListFacets(stored, acceptanceProjectScopeKey(null)).projectId).toBe(+ undefined,+ );+ });+});++describe('isAcceptanceListFacetsNarrowed', () => {+ it('treats any non-default facet as a narrowing', () => {+ expect(isAcceptanceListFacetsNarrowed({ scope: 'all', source: 'all' })).toBe(false);+ expect(isAcceptanceListFacetsNarrowed({ scope: 'participated', source: 'all' })).toBe(true);+ expect(isAcceptanceListFacetsNarrowed({ scope: 'all', source: 'topic' })).toBe(true);+ expect(isAcceptanceListFacetsNarrowed({ projectId: null, scope: 'all', source: 'all' })).toBe(+ true,+ );+ });++ it('keeps the filtered escape hatch for a facet-only narrowing', () => {+ expect(+ acceptanceListEmptyVariant({+ allListEmpty: false,+ facetsNarrowed: true,+ filter: 'all',+ searching: false,+ }),+ ).toBe('filtered');+ });+});++describe('hosted project lists', () => {+ const stored = { projectId: 'standalone-pick', scope: 'all', source: 'all' } as const;++ it('applies the host project instead of the persisted standalone pick', () => {+ expect(effectiveAcceptanceListFacets(stored, 'host-project').projectId).toBe('host-project');+ expect(effectiveAcceptanceListFacets(stored).projectId).toBe('standalone-pick');+ });++ it('does not count the hidden persisted project as an active narrowing', () => {+ expect(isAcceptanceListFacetsNarrowed(stored, 'host-project')).toBe(false);+ expect(isAcceptanceListFacetsNarrowed({ ...stored, source: 'goal' }, 'host-project')).toBe(+ true,+ );+ expect(isAcceptanceListFacetsNarrowed(stored)).toBe(true);+ });++ it('keeps the standalone project pick when "show all" resets a hosted list', () => {+ expect(resetAcceptanceListFacets({ ...stored, scope: 'participated' }, 'host-project')).toEqual(+ { projectId: 'standalone-pick', scope: 'all', source: 'all' },+ );+ expect(resetAcceptanceListFacets(stored)).toEqual({ scope: 'all', source: 'all' });+ });+});diff --git a/src/features/Acceptance/Workspace/acceptanceListFilter.ts b/src/features/Acceptance/Workspace/acceptanceListFilter.tsindex 155a4606b3c..6e5d9a74165 100644--- a/src/features/Acceptance/Workspace/acceptanceListFilter.ts+++ b/src/features/Acceptance/Workspace/acceptanceListFilter.ts@@ -1,3 +1,5 @@+import type { AcceptanceListScope, AcceptanceListSource } from '@/services/verify';+export type AcceptanceListFilter = 'active' | 'all' | 'completed';export const DEFAULT_ACCEPTANCE_LIST_FILTER: AcceptanceListFilter = 'active';@@ -5,6 +7,84 @@ export const DEFAULT_ACCEPTANCE_LIST_FILTER: AcceptanceListFilter = 'active';export const normalizeAcceptanceListFilter = (value: unknown): AcceptanceListFilter =>value === 'all' || value === 'completed' ? value : DEFAULT_ACCEPTANCE_LIST_FILTER;+export const ACCEPTANCE_LIST_SCOPES = ['all', 'created', 'participated'] as const;+export const ACCEPTANCE_LIST_SOURCES = ['all', 'topic', 'task', 'goal', 'standalone'] as const;++/**+ * The list narrowings beyond the status split. `projectId`: `undefined` = any+ * project, `null` = filed under none, a string = that project.+ */+export interface AcceptanceListFacets {+ projectId?: string | null;+ /**+ * The workspace (`personal` for none) the project choice was made in. Project+ * ids belong to one workspace, so a choice carried into another would send a+ * foreign id and read as an empty list.+ */+ projectScope?: string;+ scope: AcceptanceListScope;+ source: AcceptanceListSource;+}++/** The key a project choice is scoped to: the active workspace, or `personal`. */+export const acceptanceProjectScopeKey = (workspaceId?: string | null) => workspaceId ?? 'personal';++export const DEFAULT_ACCEPTANCE_LIST_FACETS: AcceptanceListFacets = { scope: 'all', source: 'all' };++/**+ * Persisted facets are untrusted — a stale or hand-edited value falls back per+ * field. A project choice made in another workspace is dropped.+ */+export const normalizeAcceptanceListFacets = (+ value: unknown,+ projectScope: string = acceptanceProjectScopeKey(),+): AcceptanceListFacets => {+ const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;+ const scope = ACCEPTANCE_LIST_SCOPES.find((item) => item === raw.scope) ?? 'all';+ const source = ACCEPTANCE_LIST_SOURCES.find((item) => item === raw.source) ?? 'all';+ const sameScope = (raw.projectScope ?? acceptanceProjectScopeKey()) === projectScope;+ const projectId = !sameScope+ ? undefined+ : raw.projectId === null+ ? null+ : typeof raw.projectId === 'string'+ ? raw.projectId+ : undefined;+ return { projectId, projectScope, scope, source };+};++/**+ * The facets a list actually applies. A project page hosts its own list: the+ * page's project replaces the persisted project facet, which belongs to the+ * standalone list and is not even offered in the hosted menu.+ */+export const effectiveAcceptanceListFacets = (+ facets: AcceptanceListFacets,+ hostProjectId?: string,+): AcceptanceListFacets => (hostProjectId ? { ...facets, projectId: hostProjectId } : facets);++/**+ * What "show all" resets the persisted facets to. On a hosted list it must not+ * wipe the standalone list's project choice — the user never saw it here.+ */+export const resetAcceptanceListFacets = (+ facets: AcceptanceListFacets,+ hostProjectId?: string,+): AcceptanceListFacets =>+ hostProjectId+ ? {+ ...DEFAULT_ACCEPTANCE_LIST_FACETS,+ projectId: facets.projectId,+ projectScope: facets.projectScope,+ }+ : DEFAULT_ACCEPTANCE_LIST_FACETS;++/** Whether the facets narrow the list beyond what its host already fixes. */+export const isAcceptanceListFacetsNarrowed = (+ { projectId, scope, source }: AcceptanceListFacets,+ hostProjectId?: string,+): boolean => scope !== 'all' || source !== 'all' || (!hostProjectId && projectId !== undefined);+/*** Which empty state a zero-result list should render.*@@ -20,11 +100,13 @@ export const normalizeAcceptanceListFilter = (value: unknown): AcceptanceListFil*/export const acceptanceListEmptyVariant = ({allListEmpty,+ facetsNarrowed = false,filter,searching,}: {allListEmpty?: boolean;+ facetsNarrowed?: boolean;filter: AcceptanceListFilter;searching: boolean;}): 'filtered' | 'firstRun' =>- (searching || filter !== 'all') && !allListEmpty ? 'filtered' : 'firstRun';+ (searching || filter !== 'all' || facetsNarrowed) && !allListEmpty ? 'filtered' : 'firstRun';diff --git a/src/features/Acceptance/Workspace/useAcceptanceListFilterMenu.tsx b/src/features/Acceptance/Workspace/useAcceptanceListFilterMenu.tsxnew file mode 100644index 00000000000..766074f0791--- /dev/null+++ b/src/features/Acceptance/Workspace/useAcceptanceListFilterMenu.tsx@@ -0,0 +1,195 @@+'use client';++import { Icon } from '@lobehub/ui';+import type { DropdownItem } from '@lobehub/ui/base-ui';+import { Check, FolderClosed, Group, Waypoints } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import {+ ACCEPTANCE_LIST_SCOPES,+ ACCEPTANCE_LIST_SOURCES,+ type AcceptanceListFacets,+ type AcceptanceListFilter,+} from './acceptanceListFilter';+import type { AcceptanceGroupMode } from './groupAcceptanceList';+import { useAcceptanceProjectOptions } from './useAcceptanceProjectMenuItem';++const SCOPE_LABEL_KEYS = {+ all: 'acceptance.workspace.filters.scope.all',+ created: 'acceptance.workspace.filters.scope.created',+ participated: 'acceptance.workspace.filters.scope.participated',+} as const;++const SOURCE_LABEL_KEYS = {+ all: 'acceptance.workspace.filters.source.all',+ goal: 'acceptance.workspace.filters.source.goal',+ standalone: 'acceptance.workspace.filters.source.standalone',+ task: 'acceptance.workspace.filters.source.task',+ topic: 'acceptance.workspace.filters.source.topic',+} as const;++const checkIcon = (checked: boolean) => <Icon icon={Check} style={{ opacity: checked ? 1 : 0 }} />;++interface AcceptanceListFilterMenuParams {+ facets: AcceptanceListFacets;+ filter: AcceptanceListFilter;+ groupMode: AcceptanceGroupMode;+ /** Set when the list is hosted inside a project page — the project is fixed. */+ hostProjectId?: string;+ setFacets: (facets: AcceptanceListFacets) => void;+ setFilter: (filter: AcceptanceListFilter) => void;+ setGroupMode: (mode: AcceptanceGroupMode) => void;+}++/**+ * The list header's one filter popover: who (scope) and lifecycle (status)+ * sit flat as the two most-used answers; source, project and grouping are+ * submenus labelled with their current value, so a narrowed list still says+ * what it is narrowed to without opening anything.+ */+export const useAcceptanceListFilterMenu = ({+ facets,+ filter,+ groupMode,+ hostProjectId,+ setFacets,+ setFilter,+ setGroupMode,+}: AcceptanceListFilterMenuParams): DropdownItem[] => {+ const { t } = useTranslation('verify');++ // Projects load the first time the submenu opens — or right away when a+ // persisted project filter needs its name for the label.+ const [projectsRequested, setProjectsRequested] = useState(false);+ const { data: projectData, error: projectError } = useAcceptanceProjectOptions(+ !hostProjectId && (projectsRequested || typeof facets.projectId === 'string'),+ );+ const projects = projectData?.data;++ const withValue = (title: string, value?: string) => (value ? `${title} · ${value}` : title);++ const scopeGroup: DropdownItem = {+ children: ACCEPTANCE_LIST_SCOPES.map((scope) => ({+ icon: checkIcon(facets.scope === scope),+ key: `scope-${scope}`,+ label: t(SCOPE_LABEL_KEYS[scope]),+ onClick: () => setFacets({ ...facets, scope }),+ })),+ key: 'scope',+ label: t('acceptance.workspace.filters.scope.title'),+ type: 'group',+ };++ const statusGroup: DropdownItem = {+ children: (+ [+ ['active', t('acceptance.workspace.filters.active')],+ ['all', t('acceptance.workspace.filters.all')],+ ['completed', t('acceptance.workspace.filters.completed')],+ ] as const+ ).map(([key, label]) => ({+ icon: checkIcon(filter === key),+ key,+ label,+ onClick: () => setFilter(key),+ })),+ key: 'status',+ label: t('acceptance.workspace.filters.status'),+ type: 'group',+ };++ const sourceItem: DropdownItem = {+ children: ACCEPTANCE_LIST_SOURCES.map((source) => ({+ icon: checkIcon(facets.source === source),+ key: `source-${source}`,+ label: t(SOURCE_LABEL_KEYS[source]),+ onClick: () => setFacets({ ...facets, source }),+ })),+ icon: <Icon icon={Waypoints} />,+ key: 'source',+ label: withValue(+ t('acceptance.workspace.filters.source.title'),+ facets.source === 'all' ? undefined : t(SOURCE_LABEL_KEYS[facets.source]),+ ),+ };++ const selectedProjectName =+ facets.projectId === null+ ? t('acceptance.workspace.filters.project.none')+ : facets.projectId+ ? projects?.find((project) => project.id === facets.projectId)?.name+ : undefined;++ const projectListItems: DropdownItem[] = projectError+ ? [{ disabled: true, key: 'project-error', label: t('acceptance.workspace.project.loadError') }]+ : !projects+ ? [+ {+ disabled: true,+ key: 'project-loading',+ label: t('acceptance.workspace.project.loading'),+ },+ ]+ : projects.map((project) => ({+ icon: checkIcon(facets.projectId === project.id),+ key: `project-${project.id}`,+ label: project.name,+ onClick: () => setFacets({ ...facets, projectId: project.id }),+ }));++ const projectItem: DropdownItem = {+ children: [+ {+ icon: checkIcon(facets.projectId === undefined),+ key: 'project-all',+ label: t('acceptance.workspace.filters.project.all'),+ onClick: () => setFacets({ ...facets, projectId: undefined }),+ },+ {+ icon: checkIcon(facets.projectId === null),+ key: 'project-none',+ label: t('acceptance.workspace.filters.project.none'),+ onClick: () => setFacets({ ...facets, projectId: null }),+ },+ { type: 'divider' },+ ...projectListItems,+ ],+ icon: <Icon icon={FolderClosed} />,+ key: 'project',+ label: withValue(t('acceptance.workspace.filters.project.title'), selectedProjectName),+ onOpenChange: (open: boolean) => {+ if (open) setProjectsRequested(true);+ },+ };++ const groupItem: DropdownItem = {+ children: (+ [+ ['project', t('acceptance.workspace.groups.byProject')],+ ['status', t('acceptance.workspace.groups.byStatus')],+ ['time', t('acceptance.workspace.groups.byTime')],+ ['none', t('acceptance.workspace.groups.byNone')],+ ] as const+ ).map(([key, label]) => ({+ icon: checkIcon(groupMode === key),+ key,+ label,+ onClick: () => setGroupMode(key),+ })),+ icon: <Icon icon={Group} />,+ key: 'group-mode',+ label: t('acceptance.workspace.groups.mode'),+ };++ return [+ scopeGroup,+ statusGroup,+ { type: 'divider' },+ sourceItem,+ // Inside a project page the project is the page itself.+ ...(hostProjectId ? [] : [projectItem]),+ { type: 'divider' },+ groupItem,+ ];+};diff --git a/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsx b/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsxindex 2b1d0d57d66..1f4de11a696 100644--- a/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsx+++ b/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsx@@ -54,6 +54,15 @@ interface AcceptanceProjectMenu {* The caller owns the write (and its toast); this hook only decides what the* menu offers.*/+/**+ * The caller's projects for acceptance menus, read only once `requested` — the+ * filing submenu and the list's project filter share one cache entry.+ */+export const useAcceptanceProjectOptions = (requested: boolean) =>+ useClientDataSWR(requested ? PROJECT_OPTIONS_KEY : null, () => projectService.listAll(), {+ revalidateOnFocus: false,+ });+export const useAcceptanceProjectMenu = ({currentProjectId,onSelect,@@ -62,11 +71,7 @@ export const useAcceptanceProjectMenu = ({const { t } = useTranslation('verify');const [requested, setRequested] = useState(false);- const { data, error } = useClientDataSWR(- requested ? PROJECT_OPTIONS_KEY : null,- () => projectService.listAll(),- { revalidateOnFocus: false },- );+ const { data, error } = useAcceptanceProjectOptions(requested);const state = buildAcceptanceProjectMenuState({currentProjectId,diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.tsindex b1d5154602a..0077134ad33 100644--- a/src/features/Acceptance/hooks.ts+++ b/src/features/Acceptance/hooks.ts@@ -9,6 +9,7 @@ import { documentService } from '@/services/document';import type {AcceptanceListFilter,AcceptanceListPage,+ AcceptanceListQuery,VerifyReportSummaryPage,} from '@/services/verify';import { verifyService } from '@/services/verify';@@ -96,17 +97,20 @@ export const useAcceptanceBySubject = (*/export const useAcceptanceList = (enabled: boolean,- options?: {- filter?: 'active' | 'all' | 'completed';+ options?: AcceptanceListQuery & {limit?: number;- projectId?: string;q?: string;revalidateOnMount?: boolean;},) =>useClientDataSWR(enabled- ? verifyKeys.acceptances(options?.limit, options?.q, options?.filter, options?.projectId)+ ? verifyKeys.acceptances(options?.limit, options?.q, {+ filter: options?.filter,+ projectId: options?.projectId,+ scope: options?.scope,+ source: options?.source,+ }): null,() =>verifyService.listAcceptances({@@ -114,6 +118,8 @@ export const useAcceptanceList = (limit: options?.limit,projectId: options?.projectId,q: options?.q,+ scope: options?.scope,+ source: options?.source,}),{...VERIFY_REPORT_SWR_CONFIG,@@ -140,9 +146,10 @@ export const useAcceptancePurgePreview = (acceptanceId: string | null) =>*/export const useAcceptanceListInfinite = (filter: AcceptanceListFilter | null,- projectId?: string,+ query: Omit<AcceptanceListQuery, 'filter'> = {},) => {const workspaceId = useActiveWorkspaceId();+ const { projectId, scope, source } = query;const getKey = useCallback((_index: number, previous: AcceptanceListPage | null) => {@@ -150,29 +157,32 @@ export const useAcceptanceListInfinite = (if (!filter) return null;return verifyKeys.acceptancePage(workspaceId ?? undefined,- filter,- projectId,+ { filter, projectId, scope, source },previous?.nextCursor ?? undefined,);},- [filter, projectId, workspaceId],+ [filter, projectId, scope, source, workspaceId],);const { data, error, isLoading, mutate, setSize, size } = useSWRInfinite(getKey,- ([, , , scopedProjectId, cursor]: readonly [string, string, string, string, string]) =>+ // Read the narrowing from the closure, not the key: the key spells the+ // unfiled project as a sentinel string, the server wants `null`.+ (key: readonly string[]) =>verifyService.listAcceptancePage({- cursor: cursor || undefined,+ cursor: key.at(-1) || undefined,filter: filter ?? undefined,limit: ACCEPTANCE_PAGE_SIZE,- projectId: scopedProjectId || undefined,+ projectId,+ scope,+ source,}),{ ...VERIFY_REPORT_SWR_CONFIG, revalidateFirstPage: false },);useEffect(() => {setSize(1);- }, [filter, projectId, workspaceId, setSize]);+ }, [filter, projectId, scope, source, workspaceId, setSize]);const loadMore = useCallback(() => {void setSize((s) => s + 1);diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 1087646ffd9..12432a29f59 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -69,13 +69,27 @@ describe('isAcceptanceListKey', () => {});it('keeps project-scoped acceptance feeds in separate cache entries', () => {- expect(verifyKeys.acceptances(undefined, undefined, 'all', 'project-1')).not.toEqual(- verifyKeys.acceptances(undefined, undefined, 'all', 'project-2'),+ expect(+ verifyKeys.acceptances(undefined, undefined, { filter: 'all', projectId: 'project-1' }),+ ).not.toEqual(+ verifyKeys.acceptances(undefined, undefined, { filter: 'all', projectId: 'project-2' }),);- expect(verifyKeys.acceptancePage('workspace-1', 'all', 'project-1')).not.toEqual(- verifyKeys.acceptancePage('workspace-1', 'all', 'project-2'),+ expect(+ verifyKeys.acceptancePage('workspace-1', { filter: 'all', projectId: 'project-1' }),+ ).not.toEqual(+ verifyKeys.acceptancePage('workspace-1', { filter: 'all', projectId: 'project-2' }),);});++ it('keeps the unfiled, scope and source narrowings in separate cache entries', () => {+ const base = { filter: 'all' };+ const page = (query: Parameters<typeof verifyKeys.acceptancePage>[1]) =>+ verifyKeys.acceptancePage('workspace-1', query);++ expect(page({ ...base, projectId: null })).not.toEqual(page(base));+ expect(page({ ...base, scope: 'participated' })).not.toEqual(page(base));+ expect(page({ ...base, source: 'goal' })).not.toEqual(page({ ...base, source: 'task' }));+ });});describe('workKeys', () => {diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex e89303aba30..731a4549b02 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1047,6 +1047,22 @@ export const expertiseKeys = {rules: def('expertise:rules', () => ['expertise:rules']),};+/** The Acceptance list narrowing as key parts — mirrors `AcceptanceListQuery`. */+interface AcceptanceListKeyQuery {+ filter?: string;+ projectId?: string | null;+ scope?: string;+ source?: string;+}++const acceptanceListKeyParts = ({ filter, projectId, scope, source }: AcceptanceListKeyQuery) => [+ filter ?? '',+ // `null` (no project) and `undefined` (any project) are different reads.+ projectId === null ? '~none' : (projectId ?? ''),+ scope ?? '',+ source ?? '',+];+export const verifyKeys = {acceptanceBundle: def('verify:acceptanceBundle', (acceptanceId: string) => ['verify:acceptanceBundle',@@ -1079,23 +1095,21 @@ export const verifyKeys = {]),acceptancePage: def('verify:acceptancePage',- (workspaceId: string | undefined, filter: string, projectId?: string, cursor?: string) => [+ (workspaceId: string | undefined, query: AcceptanceListKeyQuery, cursor?: string) => ['verify:acceptancePage',workspaceId ?? '',- filter,- projectId ?? '',+ ...acceptanceListKeyParts(query),cursor ?? '',],),/** Query inputs are part of the key so server-side list filtering never reuses stale rows. */acceptances: def('verify:acceptances',- (limit?: number, q?: string, filter?: string, projectId?: string) => [+ (limit?: number, q?: string, query: AcceptanceListKeyQuery = {}) => ['verify:acceptances',String(limit ?? ''),q ?? '',- filter ?? '',- projectId ?? '',+ ...acceptanceListKeyParts(query),],),criteria: def('verify:criteria', () => ['verify:criteria']),diff --git a/src/services/verify.ts b/src/services/verify.tsindex 9ab5871be28..01bc50dcf4e 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -45,6 +45,20 @@ export type AcceptancePurgePreview = Awaited</** The list's status split, shared by the flat and paged reads. */export type AcceptanceListFilter = 'active' | 'all' | 'completed';+/** Whose acceptances: the active scope, only mine, or any I commented on. */+export type AcceptanceListScope = 'all' | 'created' | 'participated';++/** Where the acceptance came from; `standalone` also covers documents. */+export type AcceptanceListSource = 'all' | 'goal' | 'standalone' | 'task' | 'topic';++/** Every list narrowing beyond search. `projectId: null` = filed under no project. */+export interface AcceptanceListQuery {+ filter?: AcceptanceListFilter;+ projectId?: string | null;+ scope?: AcceptanceListScope;+ source?: AcceptanceListSource;+}+/** The lifecycle states a reviewer may set by hand from the acceptance list. */export type AcceptanceStatusOverride = 'accepted' | 'closed' | 'delivered' | 'rejected';@@ -197,14 +211,14 @@ export class VerifyService {requirement: string,) => lambdaClient.acceptance.saveGoal.mutate({ requirement, subjectId, subjectType });- listAcceptances = (options?: {- filter?: 'active' | 'all' | 'completed';- /** Widen the recency window (server-capped) — the merge picker asks for more. */- limit?: number;- projectId?: string;- q?: string;- quiet?: boolean;- }): Promise<AcceptanceListItem[]> =>+ listAcceptances = (+ options?: AcceptanceListQuery & {+ /** Widen the recency window (server-capped) — the merge picker asks for more. */+ limit?: number;+ q?: string;+ quiet?: boolean;+ },+ ): Promise<AcceptanceListItem[]> =>lambdaClient.acceptance.list.query(options? {@@ -212,18 +226,20 @@ export class VerifyService {limit: options.limit,projectId: options.projectId,q: options.q,+ scope: options.scope,+ source: options.source,}: undefined,options?.quiet ? { context: { showNotification: false } } : undefined,);/** One keyset page of the acceptance feed — what the list panel scrolls. */- listAcceptancePage = (params: {- cursor?: string;- filter?: AcceptanceListFilter;- limit?: number;- projectId?: string;- }): Promise<AcceptanceListPage> => lambdaClient.acceptance.listPage.query(params);+ listAcceptancePage = (+ params: AcceptanceListQuery & {+ cursor?: string;+ limit?: number;+ },+ ): Promise<AcceptanceListPage> => lambdaClient.acceptance.listPage.query(params);/*** Acceptance status for a known set of subjects. `listAcceptances` is capped