Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(acceptance): scroll, group and sweep the acceptance list (#18897)

Arvin Xu80ed37a40995
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index fec498934b8..d6c2bf50671 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -687,6 +687,41 @@ with unrelated identifiers — a component name like `SkillRow` also matches a C
---
+**Same failure, fourth shape — the dep optimizer is wedged, and only Vite needs
+restarting.** The SPA sits on the HTML loading shell (`rootChildren: 0`, `innerText`
+empty) with a clean console and `vite connected` — no error anywhere. Crawling the
+module graph from the entry is what names it: every direct import returns 200 while
+`node_modules/.vite/deps/*` answers **504**, so `import()` of the entry fails with the
+generic `Failed to fetch dynamically imported module`, which reads like a broken route
+tree in the branch under test. Recovery is `rm -rf node_modules/.vite/deps` plus a real
+Vite process restart — and Vite is its OWN process here (`bash -c source /tmp/dev-env.sh
+&& bun run dev:spa`), independent of the `next dev` tree, so a shared worktree's Next
+server does not have to be touched. Reuse the same env file the running pair was
+started from rather than re-deriving it.
+
+### L-S17 — Diagnosing the feature when the dev DB lost its seeded user row
+
+**Wrong approach:** see the product's own list endpoint return `{ items: [] }` and its
+write endpoints fail, and start debugging the query, the scope filter, or the change
+under test.
+
+**Why it fails:** the dev server resolves `ctx.userId` for the seeded account without
+needing a `sessions` row, so a database that lost its `users` row still reads as
+authenticated: `setup-auth.sh status --surface web` reports green, every read returns
+an empty result, and every write dies inside Postgres on the `user_id` foreign key.
+The tRPC error surfaces as a giant `Failed query: insert into "acceptances" …` whose
+FK cause is only visible in the params tail, so it reads as a schema or payload
+problem rather than a missing row. The managed acceptance Postgres is shared and
+long-lived, so a `clean-db` from any worktree leaves every later run in this state.
+
+**Correct approach:** when reads are empty AND writes fail, check the row before the
+code — `select id from users` in the DB the server actually uses. Resolve that DB from
+the env file the running server was launched with, never from `test-env.sh` defaults;
+a dev server started by another session can point somewhere else entirely. Re-seed with
+`init-dev-env.sh seed-user`, then prove the fix with a real product write (an `ensure`
+round-trip), and re-run `setup-auth.sh web-seed` because the SPA's client-side auth
+gate still redirects to `/signin` after the row is recreated.
+
### L-S8 — Reading a first-boot renderer crash as a defect of the change under test
**Wrong approach:** treat the Electron dev instance's first renderer boot as
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 102a616baa6..79af3880837 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -256,6 +256,18 @@
"acceptance.workspace.actions.rename": "Rename",
"acceptance.workspace.actions.reopen": "Reopen for review",
"acceptance.workspace.actions.status": "Status",
+ "acceptance.workspace.batch.accept": "Accept",
+ "acceptance.workspace.batch.close": "Close",
+ "acceptance.workspace.batch.deleteConfirmDescription": "Delete the {{count}} selected acceptance(s)? Their verification rounds are kept — they detach into standalone reports.",
+ "acceptance.workspace.batch.deleteConfirmTitle": "Delete {{count}} acceptance(s)",
+ "acceptance.workspace.batch.deleteSuccess": "{{count}} acceptance(s) deleted",
+ "acceptance.workspace.batch.enter": "Select multiple",
+ "acceptance.workspace.batch.error": "The batch action failed. Try again.",
+ "acceptance.workspace.batch.exit": "Done",
+ "acceptance.workspace.batch.partial": "{{count}} updated, {{failed}} unchanged",
+ "acceptance.workspace.batch.selectAll": "Select all",
+ "acceptance.workspace.batch.selected": "{{count}} selected",
+ "acceptance.workspace.batch.statusSuccess": "{{count}} acceptance(s) updated",
"acceptance.workspace.checkCount": "{{count}} checks",
"acceptance.workspace.deleteConfirmDescription": "Delete the acceptance “{{title}}”? Its verification rounds are kept — they detach into standalone reports.",
"acceptance.workspace.deleteConfirmTitle": "Delete acceptance",
@@ -273,7 +285,22 @@
"acceptance.workspace.filters.showAll": "Show all acceptances",
"acceptance.workspace.filters.title": "Filter acceptances",
"acceptance.workspace.groups.actions": "Project actions",
+ "acceptance.workspace.groups.byNone": "No grouping",
+ "acceptance.workspace.groups.byProject": "By project",
+ "acceptance.workspace.groups.byStatus": "By status",
+ "acceptance.workspace.groups.byTime": "By time",
"acceptance.workspace.groups.createProject": "Create project",
+ "acceptance.workspace.groups.mode": "Group by",
+ "acceptance.workspace.groups.status.accepted": "Accepted",
+ "acceptance.workspace.groups.status.closed": "Closed",
+ "acceptance.workspace.groups.status.rejected": "Sent back",
+ "acceptance.workspace.groups.status.review": "Awaiting your review",
+ "acceptance.workspace.groups.status.running": "Verifying",
+ "acceptance.workspace.groups.time.earlier": "Earlier",
+ "acceptance.workspace.groups.time.month": "Last 30 days",
+ "acceptance.workspace.groups.time.today": "Today",
+ "acceptance.workspace.groups.time.week": "Last 7 days",
+ "acceptance.workspace.groups.time.yesterday": "Yesterday",
"acceptance.workspace.groups.ungrouped": "Ungrouped",
"acceptance.workspace.groups.viewProject": "View project",
"acceptance.workspace.listEmpty": "Ingest a verification report with the CLI and its acceptance will show up here.",
@@ -317,9 +344,11 @@
"acceptance.workspace.project.moveSuccess": "Moved to the project",
"acceptance.workspace.project.remove": "Remove from project",
"acceptance.workspace.project.removeSuccess": "Removed from the project",
- "acceptance.workspace.renameEmpty": "The title cannot be empty",
"acceptance.workspace.renameError": "Failed to rename",
+ "acceptance.workspace.renameModal.description": "Renames this entry only. The source topic, task or document keeps its own title.",
"acceptance.workspace.renameSuccess": "Renamed",
+ "acceptance.workspace.searchDeeper": "Search further back",
+ "acceptance.workspace.searchScope": "Searched the {{count}} loaded acceptance(s).",
"acceptance.workspace.statusError": "Failed to update status",
"acceptance.workspace.statusSuccess": "Status updated",
"acceptance.workspace.title": "Deliveries",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 78309ed65d8..acdb028635f 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -256,6 +256,18 @@
"acceptance.workspace.actions.rename": "重命名",
"acceptance.workspace.actions.reopen": "重新打开验收",
"acceptance.workspace.actions.status": "状态",
+ "acceptance.workspace.batch.accept": "标记验收",
+ "acceptance.workspace.batch.close": "标记关闭",
+ "acceptance.workspace.batch.deleteConfirmDescription": "将删除选中的 {{count}} 项验收?其验证轮次会保留,脱离为独立报告。",
+ "acceptance.workspace.batch.deleteConfirmTitle": "删除 {{count}} 项验收",
+ "acceptance.workspace.batch.deleteSuccess": "已删除 {{count}} 项验收",
+ "acceptance.workspace.batch.enter": "多选",
+ "acceptance.workspace.batch.error": "批量操作失败,请重试",
+ "acceptance.workspace.batch.exit": "完成",
+ "acceptance.workspace.batch.partial": "已更新 {{count}} 项,{{failed}} 项未变更",
+ "acceptance.workspace.batch.selectAll": "全选",
+ "acceptance.workspace.batch.selected": "已选 {{count}} 项",
+ "acceptance.workspace.batch.statusSuccess": "已更新 {{count}} 项验收",
"acceptance.workspace.checkCount": "{{count}} 项验收项",
"acceptance.workspace.deleteConfirmDescription": "确定删除验收「{{title}}」吗?各轮验证记录会保留,并拆分为独立的报告。",
"acceptance.workspace.deleteConfirmTitle": "删除验收",
@@ -273,7 +285,22 @@
"acceptance.workspace.filters.showAll": "显示全部验收",
"acceptance.workspace.filters.title": "筛选验收",
"acceptance.workspace.groups.actions": "项目操作",
+ "acceptance.workspace.groups.byNone": "不分组",
+ "acceptance.workspace.groups.byProject": "按项目",
+ "acceptance.workspace.groups.byStatus": "按状态",
+ "acceptance.workspace.groups.byTime": "按时间",
"acceptance.workspace.groups.createProject": "新建项目",
+ "acceptance.workspace.groups.mode": "分组方式",
+ "acceptance.workspace.groups.status.accepted": "已验收",
+ "acceptance.workspace.groups.status.closed": "已关闭",
+ "acceptance.workspace.groups.status.rejected": "已打回",
+ "acceptance.workspace.groups.status.review": "待你验收",
+ "acceptance.workspace.groups.status.running": "验证中",
+ "acceptance.workspace.groups.time.earlier": "更早",
+ "acceptance.workspace.groups.time.month": "最近 30 天",
+ "acceptance.workspace.groups.time.today": "今天",
+ "acceptance.workspace.groups.time.week": "最近 7 天",
+ "acceptance.workspace.groups.time.yesterday": "昨天",
"acceptance.workspace.groups.ungrouped": "未分组",
"acceptance.workspace.groups.viewProject": "查看项目",
"acceptance.workspace.listEmpty": "用 CLI ingest 一份验证报告后,对应的验收会出现在这里。",
@@ -317,9 +344,11 @@
"acceptance.workspace.project.moveSuccess": "已移动到该项目",
"acceptance.workspace.project.remove": "移出项目",
"acceptance.workspace.project.removeSuccess": "已移出项目",
- "acceptance.workspace.renameEmpty": "标题不能为空",
"acceptance.workspace.renameError": "重命名失败",
+ "acceptance.workspace.renameModal.description": "仅重命名这条记录,来源话题 / 任务 / 文档的标题不变。",
"acceptance.workspace.renameSuccess": "已重命名",
+ "acceptance.workspace.searchDeeper": "搜索更早的记录",
+ "acceptance.workspace.searchScope": "已在载入的 {{count}} 条中搜索。",
"acceptance.workspace.statusError": "状态更新失败",
"acceptance.workspace.statusSuccess": "状态已更新",
"acceptance.workspace.title": "交付",
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 5df3ecbf401..37fbfa01350 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -291,6 +291,19 @@ export default {
'acceptance.workspace.actions.rename': 'Rename',
'acceptance.workspace.actions.reopen': 'Reopen for review',
'acceptance.workspace.actions.status': 'Status',
+ 'acceptance.workspace.batch.accept': 'Accept',
+ 'acceptance.workspace.batch.close': 'Close',
+ 'acceptance.workspace.batch.deleteConfirmDescription':
+ 'Delete the {{count}} selected acceptance(s)? Their verification rounds are kept — they detach into standalone reports.',
+ 'acceptance.workspace.batch.deleteConfirmTitle': 'Delete {{count}} acceptance(s)',
+ 'acceptance.workspace.batch.deleteSuccess': '{{count}} acceptance(s) deleted',
+ 'acceptance.workspace.batch.enter': 'Select multiple',
+ 'acceptance.workspace.batch.error': 'The batch action failed. Try again.',
+ 'acceptance.workspace.batch.exit': 'Done',
+ 'acceptance.workspace.batch.partial': '{{count}} updated, {{failed}} unchanged',
+ 'acceptance.workspace.batch.selectAll': 'Select all',
+ 'acceptance.workspace.batch.selected': '{{count}} selected',
+ 'acceptance.workspace.batch.statusSuccess': '{{count}} acceptance(s) updated',
'acceptance.workspace.checkCount': '{{count}} checks',
'acceptance.workspace.deleteConfirmDescription':
'Delete the acceptance “{{title}}”? Its verification rounds are kept — they detach into standalone reports.',
@@ -313,6 +326,23 @@ export default {
'acceptance.workspace.groups.actions': 'Project actions',
'acceptance.workspace.groups.createProject': 'Create project',
'acceptance.workspace.groups.viewProject': 'View project',
+ 'acceptance.workspace.groups.byNone': 'No grouping',
+ 'acceptance.workspace.groups.byProject': 'By project',
+ 'acceptance.workspace.groups.byStatus': 'By status',
+ 'acceptance.workspace.groups.byTime': 'By time',
+ 'acceptance.workspace.groups.mode': 'Group by',
+ 'acceptance.workspace.groups.status.accepted': 'Accepted',
+ 'acceptance.workspace.groups.status.closed': 'Closed',
+ 'acceptance.workspace.groups.status.rejected': 'Sent back',
+ 'acceptance.workspace.groups.status.review': 'Awaiting your review',
+ 'acceptance.workspace.groups.status.running': 'Verifying',
+ 'acceptance.workspace.groups.time.earlier': 'Earlier',
+ 'acceptance.workspace.groups.time.month': 'Last 30 days',
+ 'acceptance.workspace.groups.time.today': 'Today',
+ 'acceptance.workspace.groups.time.week': 'Last 7 days',
+ 'acceptance.workspace.groups.time.yesterday': 'Yesterday',
+ 'acceptance.workspace.searchDeeper': 'Search further back',
+ 'acceptance.workspace.searchScope': 'Searched the {{count}} loaded acceptance(s).',
'acceptance.workspace.listEmpty':
'Ingest a verification report with the CLI and its acceptance will show up here.',
'acceptance.workspace.listEmptyTitle': 'No acceptances yet',
@@ -365,7 +395,8 @@ export default {
'acceptance.workspace.merge.confirm': 'Merge',
'acceptance.workspace.merge.success': '{{count}} checks merged',
'acceptance.workspace.merge.error': 'Failed to merge acceptance',
- 'acceptance.workspace.renameEmpty': 'The title cannot be empty',
+ 'acceptance.workspace.renameModal.description':
+ 'Renames this entry only. The source topic, task or document keeps its own title.',
'acceptance.workspace.renameError': 'Failed to rename',
'acceptance.workspace.renameSuccess': 'Renamed',
'acceptance.workspace.statusError': 'Failed to update status',
diff --git a/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx b/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx
index 86510943dbb..e5dc5f33faf 100644
--- a/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx
@@ -1,7 +1,7 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { ActionIcon, Select, Text } from '@lobehub/ui/base-ui';
+import { ActionIcon, Select, Text, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, useResponsive } from 'antd-style';
import { ChevronsDownUp, ChevronsUpDown } from 'lucide-react';
import type { ReactNode } from 'react';
@@ -28,6 +28,7 @@ import CheckList, {
} from './CheckList';
import { EMPTY_ID_SET, setAggregateEntry } from './expandState';
import { useAcceptanceBundle } from './useAcceptanceBundle';
+import { canReviewAcceptance } from './visibility';
const styles = createStaticStyles(({ css }) => ({
countBadge: css`
@@ -43,14 +44,12 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface AcceptanceCheckInventoryProps {
- canReview?: boolean;
children?: ReactNode;
onOpenTrace?: (verifierOperationId: string) => void | Promise<void>;
toolbar?: ReactNode;
}
const AcceptanceCheckInventory = ({
- canReview = false,
children,
onOpenTrace,
toolbar,
@@ -152,7 +151,29 @@ const AcceptanceCheckInventory = ({
if (!data) return null;
+ const canReview = canReviewAcceptance(data);
const checks = data.checks;
+
+ /**
+ * Every mutation the checklist fires goes through here.
+ *
+ * A rejected promise handed back to CheckList would escape as an unhandled
+ * rejection AND strand the row's own pending flag — the row that raised it
+ * spins forever, with the reason only in the console. Failing loudly and
+ * returning `false` lets the row settle and say what happened.
+ */
+ const runReviewMutation = async (action: () => Promise<unknown>) => {
+ try {
+ await action();
+ await mutate();
+ void globalMutate(isAcceptanceListKey);
+ return true;
+ } catch (cause) {
+ console.error('[acceptance:review]', cause);
+ toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));
+ return false;
+ }
+ };
const counts = {
accepted: checks.filter((check) => checkFilterState(check) === 'accepted').length,
ignored: checks.filter((check) => checkFilterState(check) === 'ignored').length,
@@ -247,34 +268,32 @@ const AcceptanceCheckInventory = ({
onDismissProposal={
canReview
? async (input) => {
- await verifyService.adjudicateProposal({
- adjudication: input.adjudication,
- id: data.acceptance.id,
- predictionId: input.predictionId,
- });
- await mutate();
- void globalMutate(isAcceptanceListKey);
+ await runReviewMutation(() =>
+ verifyService.adjudicateProposal({
+ adjudication: input.adjudication,
+ id: data.acceptance.id,
+ predictionId: input.predictionId,
+ }),
+ );
}
: undefined
}
onGroupFeedback={async (category, comment, fileIds) => {
if (!canReview) return false;
- await verifyService.addGroupFeedback({
- category,
- comment,
- fileIds: fileIds.length > 0 ? fileIds : undefined,
- id: data.acceptance.id,
- });
- await mutate();
- void globalMutate(isAcceptanceListKey);
- return true;
+ return runReviewMutation(() =>
+ verifyService.addGroupFeedback({
+ category,
+ comment,
+ fileIds: fileIds.length > 0 ? fileIds : undefined,
+ id: data.acceptance.id,
+ }),
+ );
}}
onReview={async (input) => {
if (!canReview) return false;
- await verifyService.reviewChecks({ id: data.acceptance.id, ...input });
- await mutate();
- void globalMutate(isAcceptanceListKey);
- return true;
+ return runReviewMutation(() =>
+ verifyService.reviewChecks({ id: data.acceptance.id, ...input }),
+ );
}}
onToggleGroup={(key) =>
setCollapsedGroups((previous) => {
diff --git a/src/features/Acceptance/Viewer/AcceptanceCheckOwnerToolbar.tsx b/src/features/Acceptance/Viewer/AcceptanceCheckOwnerToolbar.tsx
index b61227d8482..69dddbc382a 100644
--- a/src/features/Acceptance/Viewer/AcceptanceCheckOwnerToolbar.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceCheckOwnerToolbar.tsx
@@ -25,6 +25,13 @@ const AcceptanceCheckOwnerToolbar = () => {
const { acceptanceId } = useAcceptanceScope();
const { data, mutate } = useAcceptanceBundle(acceptanceId);
const [predicting, setPredicting] = useState(false);
+ /**
+ * Authoring the standing checklist and the goal writes through the SUBJECT
+ * (`ensureForSubject`), which is still resolved in the caller's own scope — it
+ * cannot reach a teammate's row, and the workspace-unique insert fallback then
+ * fails. Until that path is reviewer-aware these stay the creator's, so the page
+ * never offers an action that is guaranteed to answer `NOT_FOUND`.
+ */
if (!data?.isOwner) return null;
const standing = data.acceptance.config?.checklist ?? [];
diff --git a/src/features/Acceptance/Viewer/AcceptanceDecision.tsx b/src/features/Acceptance/Viewer/AcceptanceDecision.tsx
index f688368614d..e97efc6fd43 100644
--- a/src/features/Acceptance/Viewer/AcceptanceDecision.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceDecision.tsx
@@ -18,6 +18,7 @@ import DecisionBar from './DecisionBar';
import FeedbackDrawer, { type FeedbackListEntry } from './FeedbackDrawer';
import { openAcceptModal, openGroupFeedbackModal, openRejectModal } from './modals';
import { useAcceptanceBundle } from './useAcceptanceBundle';
+import { canReviewAcceptance } from './visibility';
import { formatAcceptanceCountsText, LIVE_ACCEPTANCE_STATUSES } from './verdict';
const AcceptanceDecision = () => {
@@ -27,7 +28,7 @@ const AcceptanceDecision = () => {
const { data, mutate } = useAcceptanceBundle(acceptanceId);
const [pending, setPending] = useState(false);
const [feedbackOpen, setFeedbackOpen] = useState(false);
- if (!data?.isOwner || data.acceptance.status === 'closed') return null;
+ if (!data || !canReviewAcceptance(data) || data.acceptance.status === 'closed') return null;
const { acceptance, checks, rounds } = data;
const currentRound = rounds.at(-1);
diff --git a/src/features/Acceptance/Viewer/AcceptanceFocusWorkspace.tsx b/src/features/Acceptance/Viewer/AcceptanceFocusWorkspace.tsx
index d8252325b12..901cd61a535 100644
--- a/src/features/Acceptance/Viewer/AcceptanceFocusWorkspace.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceFocusWorkspace.tsx
@@ -16,6 +16,7 @@ import { type CheckFilter, checkFilterState } from './CheckList';
import { copyCheckRepairPrompt } from './checkWork';
import { acceptanceCheckPath, acceptanceOverviewPath } from './routes';
import { useAcceptanceBundle } from './useAcceptanceBundle';
+import { canReviewAcceptance } from './visibility';
const CHECK_REVIEW_ORDER: Record<Exclude<CheckFilter, 'all'>, number> = {
pending: 0,
@@ -51,7 +52,7 @@ const AcceptanceFocusWorkspace = () => {
return (
<AcceptanceFocusReview
- canReview={data.isOwner}
+ canReview={canReviewAcceptance(data)}
checks={data.checks}
focusedCheck={focusedCheck}
orderedChecks={orderedChecks}
@@ -62,6 +63,8 @@ const AcceptanceFocusWorkspace = () => {
subjectTitle={data.subject.title ?? data.subject.id}
onBack={() => navigate(acceptanceOverviewPath(acceptanceId), { replace: true })}
onSelectCheck={(id) => navigate(acceptanceCheckPath(acceptanceId, id), { replace: true })}
+ // Checklist authoring writes through the subject — creator-only until that
+ // path is reviewer-aware. Reviewing the checks themselves is not.
onAddChecks={
data.isOwner
? () =>
@@ -73,7 +76,7 @@ const AcceptanceFocusWorkspace = () => {
: undefined
}
onCheckWork={
- data.isOwner && data.acceptance.status !== 'closed'
+ canReviewAcceptance(data) && data.acceptance.status !== 'closed'
? async () => {
await copyCheckRepairPrompt(data.acceptance.id, focusedCheck, copyToClipboard);
toast.success({ title: t('acceptance.checkWork.copied') });
@@ -100,11 +103,19 @@ const AcceptanceFocusWorkspace = () => {
}
: undefined
}
+ // A rejected write must settle the row, not escape as an unhandled
+ // rejection that leaves its button spinning with the reason in the console.
onReview={async (input) => {
- await verifyService.reviewChecks({ id: data.acceptance.id, ...input });
- await mutate();
- void globalMutate(isAcceptanceListKey);
- return true;
+ try {
+ await verifyService.reviewChecks({ id: data.acceptance.id, ...input });
+ await mutate();
+ void globalMutate(isAcceptanceListKey);
+ return true;
+ } catch (cause) {
+ console.error('[acceptance:review]', cause);
+ toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));
+ return false;
+ }
}}
/>
);
diff --git a/src/features/Acceptance/Viewer/AcceptanceGoalEdit.tsx b/src/features/Acceptance/Viewer/AcceptanceGoalEdit.tsx
index 01203d855b2..dfe7056d50c 100644
--- a/src/features/Acceptance/Viewer/AcceptanceGoalEdit.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceGoalEdit.tsx
@@ -15,6 +15,13 @@ const AcceptanceGoalEdit = () => {
const { t } = useTranslation('verify');
const { acceptanceId } = useAcceptanceScope();
const { data, mutate } = useAcceptanceBundle(acceptanceId);
+ /**
+ * Authoring the standing checklist and the goal writes through the SUBJECT
+ * (`ensureForSubject`), which is still resolved in the caller's own scope — it
+ * cannot reach a teammate's row, and the workspace-unique insert fallback then
+ * fails. Until that path is reviewer-aware these stay the creator's, so the page
+ * never offers an action that is guaranteed to answer `NOT_FOUND`.
+ */
if (!data?.isOwner) return null;
const handleEdit = async () => {
diff --git a/src/features/Acceptance/Viewer/AcceptanceStatusControl.tsx b/src/features/Acceptance/Viewer/AcceptanceStatusControl.tsx
index e3da14699ea..75a0001ca3a 100644
--- a/src/features/Acceptance/Viewer/AcceptanceStatusControl.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceStatusControl.tsx
@@ -14,12 +14,14 @@ import { useAcceptanceScope } from './AcceptanceScope';
import AcceptanceStatusPill from './AcceptanceStatusPill';
import { getAcceptanceStatusActions } from './statusActions';
import { useAcceptanceBundle } from './useAcceptanceBundle';
+import { canReviewAcceptance } from './visibility';
const AcceptanceStatusControl = () => {
const { t } = useTranslation('verify');
const { acceptanceId } = useAcceptanceScope();
const { data, mutate } = useAcceptanceBundle(acceptanceId);
- if (!data?.isOwner) return <AcceptanceStatusPill status={data?.acceptance.status ?? 'pending'} />;
+ if (!data || !canReviewAcceptance(data))
+ return <AcceptanceStatusPill status={data?.acceptance.status ?? 'pending'} />;
const changeStatus = async (status: 'accepted' | 'closed' | 'delivered') => {
try {
diff --git a/src/features/Acceptance/Viewer/index.tsx b/src/features/Acceptance/Viewer/index.tsx
index fc96d3adf86..93e5a34b999 100644
--- a/src/features/Acceptance/Viewer/index.tsx
+++ b/src/features/Acceptance/Viewer/index.tsx
@@ -78,7 +78,7 @@ const AcceptancePage = ({ acceptanceId: explicitAcceptanceId }: AcceptancePagePr
editSlot={<AcceptanceGoalEdit />}
reportSlot={<AcceptanceViewReportLink />}
/>
- <AcceptanceCheckInventory canReview toolbar={<AcceptanceCheckOwnerToolbar />} />
+ <AcceptanceCheckInventory toolbar={<AcceptanceCheckOwnerToolbar />} />
<AcceptanceDecision />
</>
)}
diff --git a/src/features/Acceptance/Viewer/visibility.test.ts b/src/features/Acceptance/Viewer/visibility.test.ts
index f25877f512d..c9a49899964 100644
--- a/src/features/Acceptance/Viewer/visibility.test.ts
+++ b/src/features/Acceptance/Viewer/visibility.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { canViewAcceptanceHistory, resolveAcceptanceHistoryNavigation } from './visibility';
+import {
+ canReviewAcceptance,
+ canViewAcceptanceHistory,
+ resolveAcceptanceHistoryNavigation,
+} from './visibility';
describe('canViewAcceptanceHistory', () => {
it('keeps run history available to the acceptance owner', () => {
@@ -18,3 +22,21 @@ describe('canViewAcceptanceHistory', () => {
expect(resolveAcceptanceHistoryNavigation(true, onRound)).toBe(onRound);
});
});
+
+describe('canReviewAcceptance', () => {
+ it('follows the server flag, not ownership', () => {
+ // A workspace owner opening a teammate's delivery is not the creator, but
+ // the write path lets them review — the UI must say the same thing.
+ expect(canReviewAcceptance({ canReview: true, isOwner: false })).toBe(true);
+ expect(canReviewAcceptance({ canReview: false, isOwner: true })).toBe(false);
+ });
+
+ it('withholds the actions from a shared viewer, whose writes cannot land', () => {
+ expect(canReviewAcceptance({ canReview: false })).toBe(false);
+ });
+
+ it('treats a not-yet-loaded bundle as read-only', () => {
+ expect(canReviewAcceptance(undefined)).toBe(false);
+ expect(canReviewAcceptance(null)).toBe(false);
+ });
+});
diff --git a/src/features/Acceptance/Viewer/visibility.ts b/src/features/Acceptance/Viewer/visibility.ts
index 364f912cb5a..fa99fbc4975 100644
--- a/src/features/Acceptance/Viewer/visibility.ts
+++ b/src/features/Acceptance/Viewer/visibility.ts
@@ -6,3 +6,19 @@ export const resolveAcceptanceHistoryNavigation = (
isOwner: boolean,
onRound: (round: number) => void,
) => (canViewAcceptanceHistory(isOwner) ? onRound : undefined);
+
+/**
+ * Whether the viewer may act on the checks (accept / reject / ignore, group
+ * feedback, proposal adjudication).
+ *
+ * The server decides this — it is the creator OR an owner of the acceptance's
+ * workspace, exactly what the write path enforces — so the client must not
+ * re-derive it from `isOwner`. Reading it off the bundle rather than taking it
+ * from the host is what keeps a shared link from rendering live controls whose
+ * every click answers "Acceptance not found"; deriving it from ownership alone
+ * is what locked a workspace owner out of a teammate's delivery.
+ */
+export const canReviewAcceptance = (
+ bundle?: { canReview?: boolean; isOwner?: boolean } | null,
+) =>
+ Boolean(bundle?.canReview);
diff --git a/src/features/Acceptance/Workspace/AcceptanceBatchBar.tsx b/src/features/Acceptance/Workspace/AcceptanceBatchBar.tsx
new file mode 100644
index 00000000000..2e5578a72f8
--- /dev/null
+++ b/src/features/Acceptance/Workspace/AcceptanceBatchBar.tsx
@@ -0,0 +1,81 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { ActionIcon, Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleCheck, Trash2, X } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ flex: none;
+
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+}));
+
+interface AcceptanceBatchBarProps {
+ /** Selected rows the accept sweep can actually move. */
+ acceptCount: number;
+ /** Selected rows the close sweep can actually move. */
+ closeCount: number;
+ onAccept: () => void;
+ onClose: () => void;
+ onDelete: () => void;
+ pending: boolean;
+}
+
+/**
+ * The multi-select action strip, docked under the acceptance list.
+ *
+ * Each status action is disabled when nothing in the selection can take it —
+ * an already-accepted delivery cannot be accepted again — so a live button is
+ * always a button that will change something. Delete stays an icon: it is the
+ * destructive one and must not read as a peer of the two routine sweeps.
+ */
+const AcceptanceBatchBar = memo<AcceptanceBatchBarProps>(
+ ({ acceptCount, closeCount, onAccept, onClose, onDelete, pending }) => {
+ const { t } = useTranslation('verify');
+
+ return (
+ <Flexbox horizontal align={'center'} className={styles.bar} gap={6}>
+ <Button
+ disabled={pending || acceptCount === 0}
+ icon={CircleCheck}
+ size={'small'}
+ type={'fill'}
+ onClick={onAccept}
+ >
+ {t('acceptance.workspace.batch.accept')}
+ </Button>
+ <Button
+ disabled={pending || closeCount === 0}
+ icon={X}
+ size={'small'}
+ type={'fill'}
+ onClick={onClose}
+ >
+ {t('acceptance.workspace.batch.close')}
+ </Button>
+ <Flexbox flex={1} />
+ <ActionIcon
+ danger
+ disabled={pending}
+ icon={Trash2}
+ size={'small'}
+ title={t('acceptance.workspace.actions.delete')}
+ onClick={onDelete}
+ />
+ </Flexbox>
+ );
+ },
+);
+
+AcceptanceBatchBar.displayName = 'AcceptanceBatchBar';
+
+export default AcceptanceBatchBar;
diff --git a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx
index e6044665199..a296cb849cd 100644
--- a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx
+++ b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx
@@ -12,7 +12,15 @@ import {
Icon,
} from '@lobehub/ui';
import type { DropdownItem } from '@lobehub/ui/base-ui';
-import { ActionIcon, DropdownMenu, Text } from '@lobehub/ui/base-ui';
+import {
+ ActionIcon,
+ Button,
+ Checkbox,
+ confirmModal,
+ DropdownMenu,
+ Text,
+ toast,
+} from '@lobehub/ui/base-ui';
import { useDebounce } from 'ahooks';
import { createStaticStyles, cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
@@ -20,23 +28,31 @@ import {
ArrowLeft,
Check,
FolderClosed,
+ Group,
+ ListChecks,
ListFilter,
PanelLeftClose,
Search,
TriangleAlert,
} from 'lucide-react';
import type { ReactNode } from 'react';
-import { memo, useState } from 'react';
+import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams } from 'react-router';
import { SkeletonList } from '@/features/NavPanel/components/SkeletonList';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
+import { mutate as globalMutate } from '@/libs/swr';
+import { verifyKeys } from '@/libs/swr/keys';
+import type { AcceptanceStatusOverride } from '@/services/verify';
+import { verifyService } from '@/services/verify';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import { useAcceptanceList } from '../hooks';
+import { useAcceptanceList, useAcceptanceListInfinite } from '../hooks';
import { acceptanceHomePath } from '../Viewer/routes';
+import type { AcceptanceStatusAction } from '../Viewer/statusActions';
+import AcceptanceBatchBar from './AcceptanceBatchBar';
import {
type AcceptanceListFilter,
DEFAULT_ACCEPTANCE_LIST_FILTER,
@@ -44,16 +60,32 @@ import {
} from './acceptanceListFilter';
import AcceptanceRow from './AcceptanceRow';
import {
+ acceptanceBatchTargets,
+ acceptanceSelectAllState,
+ chunkAcceptanceBatch,
+ nextAcceptanceSelectAll,
+ toggleAcceptanceSelection,
+ visibleAcceptanceSelection,
+} from './batchSelection';
+import {
+ type AcceptanceGroupMode,
+ DEFAULT_ACCEPTANCE_GROUP_MODE,
expandedAcceptanceGroupKeys,
groupAcceptanceList,
- hasProjectAcceptanceGroups,
nextCollapsedGroupKeys,
+ normalizeAcceptanceGroupMode,
+ shouldRenderAcceptanceGroups,
} from './groupAcceptanceList';
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_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';
+type BatchSuccessKey =
+ 'acceptance.workspace.batch.deleteSuccess' | 'acceptance.workspace.batch.statusSuccess';
const EMPTY_FILTER_KEYS = {
active: 'acceptance.workspace.filters.empty.active',
completed: 'acceptance.workspace.filters.empty.completed',
@@ -158,6 +190,16 @@ const styles = createStaticStyles(({ css }) => ({
filterButton: css`
flex: none;
`,
+ selectionRow: css`
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ margin-block: 2px 4px;
+ margin-inline: 4px;
+
+ font-size: 12px;
+ `,
searchEmpty: css`
display: flex;
flex-direction: column;
@@ -250,29 +292,268 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(
// Collapsed (not expanded) is the tracked set: a group that appears after
// mount — the project a delivery was just filed into — must come in open.
const [collapsedGroups, setCollapsedGroups] = useState<string[]>([]);
+ const [storedGroupMode, setStoredGroupMode] = useLocalStorageState<AcceptanceGroupMode>(
+ ACCEPTANCE_GROUP_MODE_STORAGE_KEY,
+ DEFAULT_ACCEPTANCE_GROUP_MODE,
+ );
const filter = normalizeAcceptanceListFilter(storedFilter);
+ const groupMode = normalizeAcceptanceGroupMode(storedGroupMode);
const debouncedQuery = useDebounce(query.trim(), { wait: 300 });
- const { data, error, isLoading, mutate } = useAcceptanceList(true, {
- filter,
- q: debouncedQuery || undefined,
- });
- const items = data ?? [];
- const groups = groupAcceptanceList(items);
- const showGroups = hasProjectAcceptanceGroups(groups);
const trimmedQuery = query.trim();
+ const searching = Boolean(debouncedQuery);
+
+ // Two feeds, one at a time. Browsing scrolls a keyset-paged feed; searching
+ // hands off to the flat read, which resolves every subject title across the
+ // 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, { filter, q: debouncedQuery || undefined });
+ const {
+ hasMore,
+ isLoadingInitial,
+ isLoadingMore,
+ items: pagedItems,
+ loadMore,
+ ...pagedRest
+ } = useAcceptanceListInfinite(searching ? null : filter);
+
+ const items = searching ? (search.data ?? []) : pagedItems;
+ const error = searching ? search.error : pagedRest.error;
+ const isLoading = searching ? search.isLoading : isLoadingInitial;
+ const mutate = searching ? search.mutate : pagedRest.mutate;
+
+ const groups = groupAcceptanceList(items, groupMode);
+ const showGroups = shouldRenderAcceptanceGroups(groupMode, groups);
+
+ // Auto-load the next page as the sentinel nears the viewport.
+ //
+ // The sentinel node is STATE, not a ref: on first paint the list is still a
+ // skeleton, so a ref would be null when the effect runs — and since none of
+ // `hasMore` / `isLoadingMore` / `loadMore` changes when the rows finally
+ // replace the skeleton, the effect would never re-run and the observer
+ // would never attach. Scrolling to the bottom then loads nothing, silently.
+ const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
+ const autoLoad = !searching && hasMore;
+ useEffect(() => {
+ // Re-created once each page settles, so a reader already parked at the
+ // bottom keeps pulling instead of stalling on a no-longer-firing observer.
+ if (!sentinel || !autoLoad || isLoadingMore) return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries[0]?.isIntersecting) loadMore();
+ },
+ { rootMargin: LOAD_MORE_ROOT_MARGIN },
+ );
+ observer.observe(sentinel);
+ return () => observer.disconnect();
+ }, [autoLoad, isLoadingMore, loadMore, sentinel]);
+
+ const [selecting, setSelecting] = useState(false);
+ const [selected, setSelected] = useState<string[]>([]);
+ const [batchPending, setBatchPending] = useState(false);
+ const selectedVisible = visibleAcceptanceSelection(selected, items);
+ const selectAllState = acceptanceSelectAllState(items.length, selectedVisible.length);
+
+ const leaveSelecting = () => {
+ setSelecting(false);
+ setSelected([]);
+ };
+
+ /**
+ * Re-read the list, refresh the bundles the sweep touched, and leave the
+ * rows that did NOT move selected — a partial sweep hands back exactly the
+ * remainder to retry instead of making the user re-pick it.
+ *
+ * `attemptedIds` is what the sweep actually acted on, which is only ever the
+ * VISIBLE selection. Picks the user made under another filter were never
+ * attempted, so they survive untouched — dropping them here would contradict
+ * the rule that clearing the filter brings earlier picks back.
+ */
+ const settleBatch = async (
+ attemptedIds: string[],
+ changedIds: string[],
+ failedIds: string[],
+ ) => {
+ await mutate();
+ await Promise.all(changedIds.map((id) => globalMutate(verifyKeys.acceptanceBundle(id))));
+
+ const attempted = new Set(attemptedIds);
+ let remaining: string[] = [];
+ setSelected((previous) => {
+ remaining = [...previous.filter((id) => !attempted.has(id)), ...failedIds];
+ return remaining;
+ });
+ // Only a sweep that leaves nothing selected at all is finished.
+ if (remaining.length === 0) setSelecting(false);
+ };
- 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),
- }));
+ // "Unchanged" covers both halves of a mixed sweep — rows the transition
+ // could not take, and rows the server refused — because to the reviewer
+ // they mean the same thing: that one did not move.
+ const reportBatch = (changed: number, attempted: number, successKey: BatchSuccessKey) => {
+ const unchanged = attempted - changed;
+ if (unchanged > 0) {
+ toast.warning({
+ title: t('acceptance.workspace.batch.partial', { count: changed, failed: unchanged }),
+ });
+ return;
+ }
+ toast.success(t(successKey, { count: changed }));
+ };
+
+ const sweepStatus = async (
+ action: AcceptanceStatusAction,
+ status: AcceptanceStatusOverride,
+ ) => {
+ // Only the rows the transition can actually move — an accepted delivery
+ // cannot be accepted twice, and a running one is not decidable at all.
+ const targets = acceptanceBatchTargets(items, selectedVisible, action);
+ if (targets.length === 0) return;
+
+ const attempted = selectedVisible.length;
+ setBatchPending(true);
+ try {
+ // The endpoint caps one request, so a long selection goes in chunks —
+ // otherwise select-all after enough scrolling is refused wholesale and
+ // nothing moves at all.
+ //
+ // `allSettled`, never `all`: a sibling chunk that rejects must not hide
+ // the chunks that already committed. Skipping the refresh there would
+ // leave the list showing rows the server has already moved.
+ const chunks = chunkAcceptanceBatch(targets);
+ const settled = await Promise.allSettled(
+ chunks.map((chunk) => verifyService.updateAcceptanceStatusBatch(chunk, status)),
+ );
+
+ let updated = 0;
+ const failedIds: string[] = [];
+ settled.forEach((part, index) => {
+ if (part.status === 'fulfilled') {
+ updated += part.value.updated;
+ failedIds.push(...part.value.failedIds);
+ return;
+ }
+ // A chunk that never reached the server: every id in it is unchanged.
+ console.error('[acceptance:batchStatus]', part.reason);
+ failedIds.push(...chunks[index]);
+ });
+
+ const failedSet = new Set(failedIds);
+ await settleBatch(
+ selectedVisible,
+ targets.filter((id) => !failedSet.has(id)),
+ selectedVisible.filter((id) => !targets.includes(id) || failedSet.has(id)),
+ );
+ reportBatch(updated, attempted, 'acceptance.workspace.batch.statusSuccess');
+ } catch (cause) {
+ console.error('[acceptance:batchStatus]', cause);
+ toast.error(t('acceptance.workspace.batch.error'));
+ } finally {
+ setBatchPending(false);
+ }
+ };
+
+ const deleteSelected = () => {
+ const targets = selectedVisible;
+ if (targets.length === 0) return;
+
+ confirmModal({
+ cancelText: t('actions.cancel'),
+ content: t('acceptance.workspace.batch.deleteConfirmDescription', {
+ count: targets.length,
+ }),
+ okButtonProps: { danger: true },
+ okText: t('actions.delete'),
+ title: t('acceptance.workspace.batch.deleteConfirmTitle', { count: targets.length }),
+ onOk: async () => {
+ setBatchPending(true);
+ try {
+ // `allSettled`, never `all`: a rejected chunk must not hide the ones
+ // that already deleted. Bailing out here would skip the refresh AND
+ // the navigate-away, leaving the route pointed at a row a sibling
+ // chunk had just removed.
+ const chunks = chunkAcceptanceBatch(targets);
+ const settled = await Promise.allSettled(
+ chunks.map((chunk) => verifyService.deleteAcceptanceBatch(chunk)),
+ );
+
+ let deleted = 0;
+ const failedIds: string[] = [];
+ settled.forEach((part, index) => {
+ if (part.status === 'fulfilled') {
+ deleted += part.value.deleted;
+ failedIds.push(...part.value.failedIds);
+ return;
+ }
+ console.error('[acceptance:batchDelete]', part.reason);
+ failedIds.push(...chunks[index]);
+ });
+
+ // The open acceptance just stopped existing — leave its dead route
+ // rather than letting the detail pane render a 404.
+ if (acceptanceId && targets.includes(acceptanceId) && !failedIds.includes(acceptanceId))
+ navigate(acceptanceHomePath(), { replace: true });
+ await settleBatch(targets, [], failedIds);
+ reportBatch(deleted, targets.length, 'acceptance.workspace.batch.deleteSuccess');
+ } catch (cause) {
+ console.error('[acceptance:batchDelete]', cause);
+ toast.error(t('acceptance.workspace.batch.error'));
+ } finally {
+ setBatchPending(false);
+ }
+ },
+ });
+ };
+
+ // Grouping by project already names it in the header; every other mode has
+ // to carry it on the row or the affiliation is simply not on screen.
+ const showRowProject = groupMode !== 'project';
+
+ const rowSelectionProps = (id: string) =>
+ selecting
+ ? {
+ selectable: true,
+ selected: selectedVisible.includes(id),
+ onToggleSelect: () =>
+ setSelected((previous) => toggleAcceptanceSelection(previous, id)),
+ }
+ : 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 [panelWidth, updateSystemStatus] = useGlobalStore((s) => [
systemStatusSelectors.verifyReportPanelWidth(s),
@@ -350,8 +631,37 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(
title={t('acceptance.workspace.filters.title')}
/>
</DropdownMenu>
+ <ActionIcon
+ active={selecting}
+ className={styles.filterButton}
+ icon={ListChecks}
+ size={'small'}
+ title={t('acceptance.workspace.batch.enter')}
+ onClick={() => (selecting ? leaveSelecting() : setSelecting(true))}
+ />
{!showGroups && renderProjectActions?.()}
</div>
+ {selecting && (
+ <div className={styles.selectionRow}>
+ <Checkbox
+ checked={selectAllState === 'all'}
+ disabled={items.length === 0}
+ indeterminate={selectAllState === 'partial'}
+ onChange={() =>
+ setSelected((previous) => nextAcceptanceSelectAll(previous, items))
+ }
+ >
+ {t('acceptance.workspace.batch.selectAll')}
+ </Checkbox>
+ <Flexbox flex={1} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.workspace.batch.selected', { count: selectedVisible.length })}
+ </Text>
+ <Button size={'small'} type={'text'} onClick={leaveSelecting}>
+ {t('acceptance.workspace.batch.exit')}
+ </Button>
+ </div>
+ )}
</div>
<Flexbox flex={1} style={{ minHeight: 0, overflowX: 'hidden', overflowY: 'auto' }}>
@@ -415,16 +725,23 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(
>
{groups.map((group) => (
<AccordionItem
- action={renderProjectActions?.(group.projectName ? group.key : undefined)}
itemKey={group.key}
key={group.key}
paddingBlock={4}
paddingInline={8}
+ action={
+ groupMode === 'project'
+ ? renderProjectActions?.(group.projectName ? group.key : undefined)
+ : undefined
+ }
title={
<span className={styles.groupTitle}>
- <Icon icon={FolderClosed} size={14} />
+ {/* The folder reads as "project"; a status or age
+ bucket is not a folder and must not wear one. */}
+ {groupMode === 'project' && <Icon icon={FolderClosed} size={14} />}
<span>
- {group.projectName ?? t('acceptance.workspace.groups.ungrouped')}
+ {group.name ??
+ t(group.labelKey as 'acceptance.workspace.groups.ungrouped')}
</span>
</span>
}
@@ -435,7 +752,9 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(
active={item.id === acceptanceId}
item={item}
key={item.id}
+ showProject={showRowProject}
onChanged={mutate}
+ {...rowSelectionProps(item.id)}
/>
))}
</div>
@@ -448,13 +767,33 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(
active={item.id === acceptanceId}
item={item}
key={item.id}
+ showProject={showRowProject}
onChanged={mutate}
+ {...rowSelectionProps(item.id)}
/>
))
)}
+ {!searching && (
+ <>
+ <div ref={setSentinel} style={{ height: 1 }} />
+ {isLoadingMore && (
+ <SkeletonList rows={2} style={{ paddingBlock: 4, paddingInline: 0 }} />
+ )}
+ </>
+ )}
</div>
)}
</Flexbox>
+ {selecting && (
+ <AcceptanceBatchBar
+ acceptCount={acceptanceBatchTargets(items, selectedVisible, 'accept').length}
+ closeCount={acceptanceBatchTargets(items, selectedVisible, 'close').length}
+ pending={batchPending || selectedVisible.length === 0}
+ onAccept={() => void sweepStatus('accept', 'accepted')}
+ onClose={() => void sweepStatus('close', 'closed')}
+ onDelete={deleteSelected}
+ />
+ )}
</DraggablePanelContainer>
</DraggablePanel>
);
diff --git a/src/features/Acceptance/Workspace/AcceptanceRow.tsx b/src/features/Acceptance/Workspace/AcceptanceRow.tsx
index d6853c3b2f4..e1a8a91045d 100644
--- a/src/features/Acceptance/Workspace/AcceptanceRow.tsx
+++ b/src/features/Acceptance/Workspace/AcceptanceRow.tsx
@@ -1,9 +1,9 @@
'use client';
import type { AcceptanceStatus } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
+import { Center, Flexbox, Icon } from '@lobehub/ui';
import type { DropdownItem } from '@lobehub/ui/base-ui';
-import { ActionIcon, confirmModal, DropdownMenu, toast } from '@lobehub/ui/base-ui';
+import { ActionIcon, Checkbox, confirmModal, DropdownMenu, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import dayjs from 'dayjs';
import {
@@ -21,10 +21,11 @@ import {
Trash2,
X,
} from 'lucide-react';
-import { memo, useRef, useState } from 'react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router';
+import { openRenameModal } from '@/components/RenameModal';
import NavItem from '@/features/NavPanel/components/NavItem';
import { mutate as globalMutate } from '@/libs/swr';
import { verifyKeys } from '@/libs/swr/keys';
@@ -36,9 +37,13 @@ import { openMergeAcceptanceModal } from './MergeAcceptanceModal';
import { useAcceptanceProjectMenuItem } from './useAcceptanceProjectMenuItem';
const styles = createStaticStyles(({ css }) => ({
- editRow: css`
- padding-block: 4px;
- padding-inline: 4px;
+ itemProject: css`
+ overflow: hidden;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
`,
itemTime: css`
flex: none;
@@ -46,25 +51,6 @@ const styles = createStaticStyles(({ css }) => ({
font-size: 12px;
color: ${cssVar.colorTextTertiary};
`,
- itemTitleInput: css`
- width: 100%;
- min-width: 0;
- height: 24px;
- padding-inline: 6px;
- border: 1px solid ${cssVar.colorBorder};
- border-radius: 4px;
-
- font-size: 13px;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorBgContainer};
- outline: none;
-
- &:focus {
- border-color: ${cssVar.colorPrimary};
- box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBg};
- }
- `,
spin: css`
animation: acceptance-spin 1.1s linear infinite;
@@ -118,60 +104,56 @@ const AcceptanceRow = memo<{
active: boolean;
item: AcceptanceListItem;
onChanged: () => Promise<unknown> | unknown;
-}>(({ active, item, onChanged }) => {
+ /**
+ * Show the row's project on a second line. Set by every grouping mode EXCEPT
+ * "by project", where the bucket header already names it and a second line
+ * would only repeat the header.
+ */
+ showProject?: boolean;
+ /** Multi-select is running: the row picks instead of navigating. */
+ selectable?: boolean;
+ selected?: boolean;
+ onToggleSelect?: () => void;
+}>(({ active, item, onChanged, onToggleSelect, selectable, selected, showProject }) => {
const { t } = useTranslation('verify');
const navigate = useNavigate();
- const [editing, setEditing] = useState(false);
const [mutating, setMutating] = useState(false);
- const isSavingRef = useRef(false);
const glyph = glyphOf(item.status as AcceptanceStatus);
const meta = glyphMeta[glyph];
const title = item.subject.title || item.subjectId;
- const [draftTitle, setDraftTitle] = useState(title);
const refresh = () =>
Promise.all([onChanged(), globalMutate(verifyKeys.acceptanceBundle(item.id))]);
- const startRename = () => {
- setDraftTitle(title);
- setEditing(true);
- };
-
- const cancelRename = () => {
- if (isSavingRef.current) return;
- setDraftTitle(title);
- setEditing(false);
- };
-
- const commitRename = async () => {
- if (isSavingRef.current) return;
- const next = draftTitle.trim();
- if (!next) {
- toast.error(t('acceptance.workspace.renameEmpty'));
- setDraftTitle(title);
- setEditing(false);
- return;
- }
- if (next === title) {
- setEditing(false);
- return;
- }
- isSavingRef.current = true;
- setMutating(true);
- try {
- await verifyService.renameAcceptance(item.id, next);
- await refresh();
- toast.success(t('acceptance.workspace.renameSuccess'));
- setEditing(false);
- } catch (error) {
- console.error('[acceptance:rename]', error);
- toast.error(t('acceptance.workspace.renameError'));
- } finally {
- isSavingRef.current = false;
- setMutating(false);
- }
- };
+ /**
+ * The shared rename dialog, same as a topic's. An in-place input inside a
+ * narrow panel gave a long delivery title a ~200px editing window with no
+ * room to see what was being edited; the modal is also where the note about
+ * what a rename does and does not touch can actually be read.
+ */
+ const startRename = () =>
+ openRenameModal({
+ defaultValue: title,
+ description: t('acceptance.workspace.renameModal.description'),
+ title: t('acceptance.workspace.actions.rename'),
+ onSave: async (next) => {
+ setMutating(true);
+ try {
+ await verifyService.renameAcceptance(item.id, next);
+ await refresh();
+ toast.success(t('acceptance.workspace.renameSuccess'));
+ } catch (error) {
+ console.error('[acceptance:rename]', error);
+ toast.error(t('acceptance.workspace.renameError'));
+ // Re-throw: the shared modal closes on a RESOLVED save, which would
+ // discard the title the user just typed and leave no way to retry.
+ throw error;
+ } finally {
+ setMutating(false);
+ }
+ },
+ });
const changeStatus = async (status: 'accepted' | 'closed' | 'delivered' | 'rejected') => {
setMutating(true);
@@ -291,7 +273,21 @@ const AcceptanceRow = memo<{
};
});
+ // Deciding the delivery is what this menu is FOR — status leads, then the
+ // filing actions, then the destructive one behind its own divider. Buried
+ // under rename/move/merge it read as an afterthought of housekeeping.
const menuItems: DropdownItem[] = [
+ ...(statusItems.length > 0
+ ? [
+ {
+ children: statusItems,
+ icon: <Icon icon={CircleDashed} />,
+ key: 'status',
+ label: t('acceptance.workspace.actions.status'),
+ },
+ { type: 'divider' as const },
+ ]
+ : []),
{
icon: <Icon icon={Pencil} />,
key: 'rename',
@@ -305,17 +301,7 @@ const AcceptanceRow = memo<{
label: t('acceptance.workspace.actions.merge'),
onClick: mergeIntoAcceptance,
},
- ...(statusItems.length > 0
- ? [
- {
- children: statusItems,
- icon: <Icon icon={CircleDashed} />,
- key: 'status',
- label: t('acceptance.workspace.actions.status'),
- },
- { type: 'divider' as const },
- ]
- : []),
+ { type: 'divider' as const },
{
danger: true,
icon: <Icon icon={Trash2} />,
@@ -325,65 +311,80 @@ const AcceptanceRow = memo<{
},
];
- if (editing) {
- return (
- <div className={styles.editRow}>
- <input
- autoFocus
- className={styles.itemTitleInput}
- value={draftTitle}
- onBlur={() => void commitRename()}
- onChange={(event) => setDraftTitle(event.target.value)}
- onFocus={(event) => event.currentTarget.select()}
- onKeyDown={(event) => {
- event.stopPropagation();
- if (event.key === 'Enter') {
- event.preventDefault();
- void commitRename();
- }
- if (event.key === 'Escape') {
- event.preventDefault();
- cancelRename();
- }
- }}
- />
- </div>
- );
- }
+ const statusGlyph = (
+ <Icon
+ className={SPINNING_GLYPHS.has(glyph) ? styles.spin : undefined}
+ icon={meta.icon}
+ size={16}
+ style={{ color: meta.color }}
+ />
+ );
+ // While selecting, the row PICKS instead of navigating:
+ // - `active` carries the ticked state — navigation is off, so no row can be
+ // "the open one" for the duration;
+ // - the checkbox takes the leading slot and the status glyph moves next to
+ // the timestamp, so a status sweep still sees what it is sweeping without
+ // the row growing a second line;
+ // - the row's own menu steps aside — the batch bar owns what happens to a
+ // selection, and one delete path per surface is enough.
return (
<NavItem
- active={active}
+ active={selectable ? selected : active}
+ icon={selectable ? undefined : statusGlyph}
key={item.id}
style={mutating ? { opacity: 0.62, pointerEvents: 'none' } : undefined}
title={title}
titleColor={cssVar.colorText}
+ // 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.
actions={
- <DropdownMenu
- iconSpaceMode={'group'}
- items={menuItems}
- placement={'bottomRight'}
- popupProps={{ style: { minWidth: 160 } }}
- >
- <ActionIcon
- icon={MoreHorizontal}
- size={'small'}
- title={t('acceptance.workspace.actions.more')}
- />
- </DropdownMenu>
+ selectable ? undefined : (
+ <DropdownMenu
+ iconSpaceMode={'group'}
+ items={menuItems}
+ placement={'bottomRight'}
+ popupProps={{ style: { minWidth: 160 } }}
+ >
+ <ActionIcon
+ icon={MoreHorizontal}
+ size={'small'}
+ title={t('acceptance.workspace.actions.more')}
+ />
+ </DropdownMenu>
+ )
+ }
+ description={
+ showProject && item.project ? (
+ <span className={styles.itemProject}>{item.project.name}</span>
+ ) : undefined
}
extra={
- <span className={styles.itemTime}>{relativeTime(item.updatedAt ?? item.createdAt)}</span>
+ <Flexbox horizontal align={'center'} gap={6}>
+ {selectable && statusGlyph}
+ <span className={styles.itemTime}>{relativeTime(item.updatedAt ?? item.createdAt)}</span>
+ </Flexbox>
}
- icon={
- <Icon
- className={SPINNING_GLYPHS.has(glyph) ? styles.spin : undefined}
- icon={meta.icon}
- size={16}
- style={{ color: meta.color }}
- />
+ slots={
+ selectable
+ ? {
+ iconPostfix: (
+ <Center
+ flex={'none'}
+ height={showProject && item.project ? 22 : undefined}
+ style={showProject && item.project ? { alignSelf: 'flex-start' } : undefined}
+ width={28}
+ >
+ {/* Read-only on purpose: the whole row is the hit target, so
+ the box reflects the state rather than owning it. */}
+ <Checkbox readOnly checked={selected} />
+ </Center>
+ ),
+ }
+ : undefined
}
- onClick={() => navigate(`/acceptance/${item.id}`)}
+ onClick={() => (selectable ? onToggleSelect?.() : navigate(`/acceptance/${item.id}`))}
/>
);
});
diff --git a/src/features/Acceptance/Workspace/batchSelection.test.ts b/src/features/Acceptance/Workspace/batchSelection.test.ts
new file mode 100644
index 00000000000..c515e8392c4
--- /dev/null
+++ b/src/features/Acceptance/Workspace/batchSelection.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from 'vitest';
+
+import type { AcceptanceListItem } from '@/services/verify';
+
+import {
+ ACCEPTANCE_BATCH_CHUNK,
+ acceptanceBatchTargets,
+ chunkAcceptanceBatch,
+ acceptanceSelectAllState,
+ nextAcceptanceSelectAll,
+ toggleAcceptanceSelection,
+ visibleAcceptanceSelection,
+} from './batchSelection';
+
+const item = (id: string, status: string) =>
+ ({ id, status, subject: { title: id }, subjectId: id }) as unknown as AcceptanceListItem;
+
+describe('toggleAcceptanceSelection', () => {
+ it('adds an unselected row and removes a selected one', () => {
+ expect(toggleAcceptanceSelection(['a'], 'b')).toEqual(['a', 'b']);
+ expect(toggleAcceptanceSelection(['a', 'b'], 'a')).toEqual(['b']);
+ });
+});
+
+describe('visibleAcceptanceSelection', () => {
+ it('drops picks the active filter no longer shows', () => {
+ // A sweep must act on exactly the ticked boxes on screen — never on a row
+ // that left the list when the filter changed.
+ expect(visibleAcceptanceSelection(['a', 'b'], [item('a', 'delivered')])).toEqual(['a']);
+ });
+});
+
+describe('acceptanceSelectAllState', () => {
+ it('reads none / partial / all from the visible counts', () => {
+ expect(acceptanceSelectAllState(3, 0)).toBe('none');
+ expect(acceptanceSelectAllState(3, 2)).toBe('partial');
+ expect(acceptanceSelectAllState(3, 3)).toBe('all');
+ expect(acceptanceSelectAllState(0, 0)).toBe('none');
+ });
+});
+
+describe('nextAcceptanceSelectAll', () => {
+ const visible = [item('a', 'delivered'), item('b', 'accepted')];
+
+ it('selects every visible row from a partial selection', () => {
+ expect(nextAcceptanceSelectAll(['a'], visible)).toEqual(['a', 'b']);
+ });
+
+ it('clears only the visible rows when everything visible is selected', () => {
+ // 'hidden' was picked under another filter; unticking the visible boxes
+ // must not silently discard it.
+ expect(nextAcceptanceSelectAll(['a', 'b', 'hidden'], visible)).toEqual(['hidden']);
+ });
+});
+
+describe('acceptanceBatchTargets', () => {
+ const items = [
+ item('delivered', 'delivered'),
+ item('accepted', 'accepted'),
+ item('verifying', 'verifying'),
+ item('closed', 'closed'),
+ ];
+ const selected = items.map((entry) => entry.id);
+
+ it('accepts only rows that can still be decided', () => {
+ expect(acceptanceBatchTargets(items, selected, 'accept')).toEqual(['delivered']);
+ });
+
+ it('closes everything except what is already closed', () => {
+ expect(acceptanceBatchTargets(items, selected, 'close')).toEqual([
+ 'delivered',
+ 'accepted',
+ 'verifying',
+ ]);
+ });
+
+ it('ignores rows outside the selection', () => {
+ expect(acceptanceBatchTargets(items, ['accepted'], 'close')).toEqual(['accepted']);
+ });
+});
+
+describe('chunkAcceptanceBatch', () => {
+ const ids = (count: number) => Array.from({ length: count }, (_, index) => `id-${index}`);
+
+ it('keeps a selection the server accepts in one request', () => {
+ expect(chunkAcceptanceBatch(ids(3))).toEqual([ids(3)]);
+ expect(chunkAcceptanceBatch(ids(ACCEPTANCE_BATCH_CHUNK))).toHaveLength(1);
+ });
+
+ it('splits a selection past the endpoint cap instead of letting it be refused', () => {
+ // Select-all after enough scrolling can exceed the cap; one oversized
+ // request fails before anything changes at all.
+ const chunks = chunkAcceptanceBatch(ids(ACCEPTANCE_BATCH_CHUNK + 1));
+
+ expect(chunks).toHaveLength(2);
+ expect(chunks[0]).toHaveLength(ACCEPTANCE_BATCH_CHUNK);
+ expect(chunks[1]).toEqual(['id-200']);
+ expect(chunks.flat()).toEqual(ids(ACCEPTANCE_BATCH_CHUNK + 1));
+ });
+
+ it('has nothing to send for an empty selection', () => {
+ expect(chunkAcceptanceBatch([])).toEqual([]);
+ });
+});
diff --git a/src/features/Acceptance/Workspace/batchSelection.ts b/src/features/Acceptance/Workspace/batchSelection.ts
new file mode 100644
index 00000000000..40589f1308e
--- /dev/null
+++ b/src/features/Acceptance/Workspace/batchSelection.ts
@@ -0,0 +1,94 @@
+import type { AcceptanceStatus } from '@lobechat/types';
+
+import type { AcceptanceListItem } from '@/services/verify';
+
+import { type AcceptanceStatusAction, getAcceptanceStatusActions } from '../Viewer/statusActions';
+
+export type AcceptanceSelectAllState = 'all' | 'none' | 'partial';
+
+export const toggleAcceptanceSelection = (selected: string[], id: string): string[] =>
+ selected.includes(id) ? selected.filter((entry) => entry !== id) : [...selected, id];
+
+/**
+ * The selection as the user can currently SEE it.
+ *
+ * Selection is remembered raw, but every read narrows it to the rows the active
+ * filter/search is showing: a sweep must never touch a row that scrolled out of
+ * the list behind a filter change, and the "3 selected" count must match the
+ * three ticked boxes on screen. Clearing the filter brings the earlier picks
+ * back, which is what a user who filtered mid-selection expects.
+ */
+export const visibleAcceptanceSelection = (
+ selected: string[],
+ visibleItems: AcceptanceListItem[],
+): string[] => {
+ const visible = new Set(visibleItems.map((item) => item.id));
+ return selected.filter((id) => visible.has(id));
+};
+
+export const acceptanceSelectAllState = (
+ visibleCount: number,
+ selectedCount: number,
+): AcceptanceSelectAllState => {
+ if (visibleCount === 0 || selectedCount === 0) return 'none';
+ return selectedCount >= visibleCount ? 'all' : 'partial';
+};
+
+/** Select-all toggles to "everything visible" unless everything already is. */
+export const nextAcceptanceSelectAll = (
+ selected: string[],
+ visibleItems: AcceptanceListItem[],
+): string[] => {
+ const visibleIds = visibleItems.map((item) => item.id);
+ const state = acceptanceSelectAllState(
+ visibleIds.length,
+ visibleAcceptanceSelection(selected, visibleItems).length,
+ );
+ if (state === 'all') return selected.filter((id) => !visibleIds.includes(id));
+
+ const merged = new Set(selected);
+ for (const id of visibleIds) merged.add(id);
+ return [...merged];
+};
+
+/**
+ * The subset of a selection a status action can actually move.
+ *
+ * A sweep mixes states — an already-accepted delivery cannot be accepted again,
+ * and a still-verifying one is not decidable at all. Filtering here (rather than
+ * letting the server reject row by row) is what lets the bar disable an action
+ * that would do nothing and report an honest count for one that does.
+ */
+export const acceptanceBatchTargets = (
+ items: AcceptanceListItem[],
+ selected: string[],
+ action: AcceptanceStatusAction,
+): string[] => {
+ const selectedSet = new Set(selected);
+ return items
+ .filter(
+ (item) =>
+ selectedSet.has(item.id) &&
+ getAcceptanceStatusActions(item.status as AcceptanceStatus).includes(action),
+ )
+ .map((item) => item.id);
+};
+
+/**
+ * The server caps one sweep at 200 ids, so a select-all after enough scrolling
+ * would be rejected wholesale — accept, close and delete all failing before
+ * anything changed. Split the work instead: a sweep is a background chore, and
+ * a partial result the caller can report beats a hard refusal.
+ */
+export const ACCEPTANCE_BATCH_CHUNK = 200;
+
+export const chunkAcceptanceBatch = (ids: string[], size = ACCEPTANCE_BATCH_CHUNK): string[][] => {
+ if (ids.length === 0) return [];
+ if (ids.length <= size) return [ids];
+
+ const chunks: string[][] = [];
+ for (let index = 0; index < ids.length; index += size) {
+ chunks.push(ids.slice(index, index + size));
+ }
+ return chunks;
+};
diff --git a/src/features/Acceptance/Workspace/groupAcceptanceList.test.ts b/src/features/Acceptance/Workspace/groupAcceptanceList.test.ts
index 4c9d5eac3c1..3854eaa803e 100644
--- a/src/features/Acceptance/Workspace/groupAcceptanceList.test.ts
+++ b/src/features/Acceptance/Workspace/groupAcceptanceList.test.ts
@@ -7,12 +7,17 @@ import {
groupAcceptanceList,
hasProjectAcceptanceGroups,
nextCollapsedGroupKeys,
+ normalizeAcceptanceGroupMode,
+ shouldRenderAcceptanceGroups,
} from './groupAcceptanceList';
const item = (id: string, project: { id: string; name: string } | null): AcceptanceListItem =>
({ id, project }) as AcceptanceListItem;
-describe('groupAcceptanceList', () => {
+const dated = (id: string, status: string, createdAt: string): AcceptanceListItem =>
+ ({ createdAt: new Date(createdAt), id, project: null, status }) as unknown as AcceptanceListItem;
+
+describe('groupAcceptanceList by project', () => {
it('groups acceptances by project and keeps missing projects under ungrouped', () => {
const groups = groupAcceptanceList([
item('ungrouped-1', null),
@@ -25,6 +30,8 @@ describe('groupAcceptanceList', () => {
expect(groups.map(({ key }) => key)).toEqual(['project-alpha', 'project-beta', 'ungrouped']);
expect(groups[1].items.map(({ id }) => id)).toEqual(['beta-1', 'beta-2']);
expect(groups[2].items.map(({ id }) => id)).toEqual(['ungrouped-1', 'ungrouped-2']);
+ expect(groups[0].name).toBe('Alpha');
+ expect(groups[2].labelKey).toBe('acceptance.workspace.groups.ungrouped');
});
it('does not require group chrome when every acceptance is ungrouped', () => {
@@ -37,7 +44,111 @@ describe('groupAcceptanceList', () => {
),
).toBe(true);
});
+});
+
+describe('groupAcceptanceList by status', () => {
+ const rows = [
+ dated('accepted', 'accepted', '2026-08-30T00:00:00Z'),
+ dated('verifying', 'verifying', '2026-08-30T00:00:00Z'),
+ dated('delivered', 'delivered', '2026-08-30T00:00:00Z'),
+ dated('rejected', 'rejected', '2026-08-30T00:00:00Z'),
+ dated('closed', 'closed', '2026-08-30T00:00:00Z'),
+ dated('repairing', 'repairing', '2026-08-30T00:00:00Z'),
+ ];
+
+ it('orders buckets by how the reviewer works down them, not by row order', () => {
+ expect(groupAcceptanceList(rows, 'status').map(({ key }) => key)).toEqual([
+ 'running',
+ 'review',
+ 'rejected',
+ 'accepted',
+ 'closed',
+ ]);
+ });
+
+ it('reads a repair round as still running, and a verdict as awaiting review', () => {
+ const byKey = new Map(groupAcceptanceList(rows, 'status').map((g) => [g.key, g]));
+ expect(byKey.get('running')!.items.map(({ id }) => id)).toEqual(['verifying', 'repairing']);
+ expect(byKey.get('review')!.items.map(({ id }) => id)).toEqual(['delivered']);
+ });
+
+ it('drops buckets nothing landed in', () => {
+ const groups = groupAcceptanceList([dated('a', 'accepted', '2026-08-30T00:00:00Z')], 'status');
+ expect(groups.map(({ key }) => key)).toEqual(['accepted']);
+ });
+});
+
+describe('groupAcceptanceList by time', () => {
+ // 2026-08-30 12:00 local — the reference "now" for every case below.
+ const now = new Date('2026-08-30T12:00:00').getTime();
+
+ it('cuts on rolling spans, so early-in-the-week does not fall off a calendar edge', () => {
+ const groups = groupAcceptanceList(
+ [
+ dated('today', 'delivered', '2026-08-30T01:00:00'),
+ dated('yesterday', 'delivered', '2026-08-29T23:00:00'),
+ dated('week', 'delivered', '2026-08-25T10:00:00'),
+ dated('month', 'delivered', '2026-08-10T10:00:00'),
+ dated('earlier', 'delivered', '2026-01-01T10:00:00'),
+ ],
+ 'time',
+ now,
+ );
+
+ expect(groups.map(({ key }) => key)).toEqual([
+ 'today',
+ 'yesterday',
+ 'week',
+ 'month',
+ 'earlier',
+ ]);
+ expect(groups.map(({ items }) => items.length)).toEqual([1, 1, 1, 1, 1]);
+ });
+
+ it('buckets on createdAt — the same key the feed pages on', () => {
+ // A row created a month ago but touched seconds ago must stay where the
+ // scroll will actually reach it, not jump into today and leave a gap.
+ const stale = {
+ createdAt: new Date('2026-07-20T10:00:00'),
+ id: 'stale',
+ project: null,
+ status: 'delivered',
+ updatedAt: new Date('2026-08-30T11:59:00'),
+ } as unknown as AcceptanceListItem;
+
+ expect(groupAcceptanceList([stale], 'time', now).map(({ key }) => key)).toEqual(['earlier']);
+ });
+});
+
+describe('shouldRenderAcceptanceGroups', () => {
+ const ungrouped = groupAcceptanceList([item('one', null)]);
+ const withProject = groupAcceptanceList([item('one', { id: 'p1', name: 'Alpha' })]);
+
+ it('skips a lone "ungrouped" header that would say nothing', () => {
+ expect(shouldRenderAcceptanceGroups('project', ungrouped)).toBe(false);
+ expect(shouldRenderAcceptanceGroups('project', withProject)).toBe(true);
+ });
+
+ it('always sections for an explicitly chosen mode', () => {
+ expect(shouldRenderAcceptanceGroups('none', [])).toBe(false);
+ expect(
+ shouldRenderAcceptanceGroups(
+ 'status',
+ groupAcceptanceList([dated('a', 'delivered', '2026-08-30T00:00:00Z')], 'status'),
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('normalizeAcceptanceGroupMode', () => {
+ it('falls back to project grouping for malformed persisted values', () => {
+ expect(normalizeAcceptanceGroupMode('unknown')).toBe('project');
+ expect(normalizeAcceptanceGroupMode(null)).toBe('project');
+ expect(normalizeAcceptanceGroupMode('time')).toBe('time');
+ });
+});
+describe('accordion expansion state', () => {
it('keeps a group that appears after mount expanded, and remembers manual collapses', () => {
const groups = groupAcceptanceList([
item('one', { id: 'p1', name: 'Alpha' }),
diff --git a/src/features/Acceptance/Workspace/groupAcceptanceList.ts b/src/features/Acceptance/Workspace/groupAcceptanceList.ts
index 1785b9a42bb..ca4c0b983ce 100644
--- a/src/features/Acceptance/Workspace/groupAcceptanceList.ts
+++ b/src/features/Acceptance/Workspace/groupAcceptanceList.ts
@@ -1,14 +1,96 @@
+import type { AcceptanceStatus } from '@lobechat/types';
+import dayjs from 'dayjs';
+
import type { AcceptanceListItem } from '@/services/verify';
+/** How the panel sections its rows. Persisted per user. */
+export type AcceptanceGroupMode = 'none' | 'project' | 'status' | 'time';
+
+export const DEFAULT_ACCEPTANCE_GROUP_MODE: AcceptanceGroupMode = 'project';
+
+export const normalizeAcceptanceGroupMode = (value: unknown): AcceptanceGroupMode =>
+ value === 'none' || value === 'status' || value === 'time'
+ ? value
+ : DEFAULT_ACCEPTANCE_GROUP_MODE;
+
export interface AcceptanceListGroup {
items: AcceptanceListItem[];
key: string;
+ /**
+ * Header text that comes from the data itself (a project's name). Fixed
+ * buckets carry a `labelKey` instead, so the panel never has to translate a
+ * user's project name or hardcode a bucket's wording.
+ */
+ name: string | null;
+ /** i18n key under `verify:acceptance.workspace.groups.*` for a fixed bucket. */
+ labelKey: string | null;
projectName: string | null;
}
const UNGROUPED_KEY = 'ungrouped';
-export const groupAcceptanceList = (items: AcceptanceListItem[]): AcceptanceListGroup[] => {
+/**
+ * Status buckets, in the order a reviewer works down them: what is still moving,
+ * what is waiting on them, what they sent back, then the settled tail.
+ */
+const STATUS_BUCKETS = ['running', 'review', 'rejected', 'accepted', 'closed'] as const;
+type StatusBucket = (typeof STATUS_BUCKETS)[number];
+
+const statusBucketOf = (status: AcceptanceStatus): StatusBucket => {
+ if (status === 'pending' || status === 'planned' || status === 'verifying') return 'running';
+ if (status === 'repairing') return 'running';
+ if (status === 'rejected') return 'rejected';
+ if (status === 'accepted') return 'accepted';
+ if (status === 'closed') return 'closed';
+ // delivered / failed / errored — a verdict is in and the reviewer owns it.
+ return 'review';
+};
+
+/**
+ * Age buckets. Cut on `createdAt`, which is also the feed's sort AND paging key:
+ * bucketing on last-activity instead would leave a "today" section that stays
+ * incomplete until the whole month has been scrolled in, because a row touched
+ * today can be paged in arbitrarily late.
+ *
+ * Spans are rolling ("last 7 days"), not calendar weeks — a Monday must not
+ * put everything from Sunday under "earlier".
+ */
+const TIME_BUCKETS = ['today', 'yesterday', 'week', 'month', 'earlier'] as const;
+type TimeBucket = (typeof TIME_BUCKETS)[number];
+
+const timeBucketOf = (createdAt: Date | string, now: number): TimeBucket => {
+ const created = dayjs(createdAt);
+ const startOfToday = dayjs(now).startOf('day');
+ if (!created.isBefore(startOfToday)) return 'today';
+ if (!created.isBefore(startOfToday.subtract(1, 'day'))) return 'yesterday';
+ if (!created.isBefore(startOfToday.subtract(7, 'day'))) return 'week';
+ if (!created.isBefore(startOfToday.subtract(30, 'day'))) return 'month';
+ return 'earlier';
+};
+
+const emptyGroup = (key: string, labelKey: string): AcceptanceListGroup => ({
+ items: [],
+ key,
+ labelKey,
+ name: null,
+ projectName: null,
+});
+
+/** Fixed buckets keep their declared order and drop the ones nothing landed in. */
+const collectFixedBuckets = <B extends string>(
+ order: readonly B[],
+ labelKeyOf: (bucket: B) => string,
+ items: AcceptanceListItem[],
+ bucketOf: (item: AcceptanceListItem) => B,
+): AcceptanceListGroup[] => {
+ const byBucket = new Map<B, AcceptanceListGroup>(
+ order.map((bucket) => [bucket, emptyGroup(bucket, labelKeyOf(bucket))]),
+ );
+ for (const item of items) byBucket.get(bucketOf(item))!.items.push(item);
+ return order.map((bucket) => byBucket.get(bucket)!).filter((group) => group.items.length > 0);
+};
+
+const groupByProject = (items: AcceptanceListItem[]): AcceptanceListGroup[] => {
const groups = new Map<string, AcceptanceListGroup>();
for (const item of items) {
@@ -22,6 +104,8 @@ export const groupAcceptanceList = (items: AcceptanceListItem[]): AcceptanceList
groups.set(key, {
items: [item],
key,
+ labelKey: item.project ? null : 'acceptance.workspace.groups.ungrouped',
+ name: item.project?.name ?? null,
projectName: item.project?.name ?? null,
});
}
@@ -33,14 +117,53 @@ export const groupAcceptanceList = (items: AcceptanceListItem[]): AcceptanceList
});
};
+export const groupAcceptanceList = (
+ items: AcceptanceListItem[],
+ mode: AcceptanceGroupMode = 'project',
+ now: number = Date.now(),
+): AcceptanceListGroup[] => {
+ if (mode === 'none') return [];
+ if (mode === 'project') return groupByProject(items);
+ if (mode === 'status')
+ return collectFixedBuckets(
+ STATUS_BUCKETS,
+ (bucket) => `acceptance.workspace.groups.status.${bucket}`,
+ items,
+ (item) => statusBucketOf(item.status as AcceptanceStatus),
+ );
+ return collectFixedBuckets(
+ TIME_BUCKETS,
+ (bucket) => `acceptance.workspace.groups.time.${bucket}`,
+ items,
+ (item) => timeBucketOf(item.createdAt, now),
+ );
+};
+
export const hasProjectAcceptanceGroups = (groups: AcceptanceListGroup[]) =>
groups.some(({ projectName }) => projectName !== null);
+/**
+ * Whether sectioning earns its chrome.
+ *
+ * `project` is the one mode that can degrade to a single bucket — a user with no
+ * projects would get one "Ungrouped" accordion wrapping the whole list, which is
+ * a header that says nothing. The explicit modes always section.
+ */
+export const shouldRenderAcceptanceGroups = (
+ mode: AcceptanceGroupMode,
+ groups: AcceptanceListGroup[],
+) => {
+ if (mode === 'none' || groups.length === 0) return false;
+ if (mode === 'project') return hasProjectAcceptanceGroups(groups);
+ return true;
+};
+
/**
* Which groups the accordion shows open. Expressed as "everything except what
* the user collapsed" on purpose: a group that appears AFTER mount — the one
- * the user just filed a delivery into — must be open, or the row they moved
- * silently disappears behind a collapsed header.
+ * the user just filed a delivery into, or the bucket the next scroll page opens
+ * — must be open, or the rows that landed in it silently disappear behind a
+ * collapsed header.
*/
export const expandedAcceptanceGroupKeys = (
groups: AcceptanceListGroup[],
diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.ts
index b8a8de41419..c54fccf85a7 100644
--- a/src/features/Acceptance/hooks.ts
+++ b/src/features/Acceptance/hooks.ts
@@ -6,10 +6,15 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import { useClientDataSWR } from '@/libs/swr';
import { verifyKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
-import type { VerifyReportSummaryPage } from '@/services/verify';
+import type {
+ AcceptanceListFilter,
+ AcceptanceListPage,
+ VerifyReportSummaryPage,
+} from '@/services/verify';
import { verifyService } from '@/services/verify';
const VERIFY_REPORT_PAGE_SIZE = 30;
+const ACCEPTANCE_PAGE_SIZE = 30;
const VERIFY_REPORT_SWR_CONFIG = {
revalidateIfStale: false,
revalidateOnFocus: false,
@@ -112,6 +117,73 @@ export const useAcceptanceList = (
},
);
+/**
+ * The panel's scroll feed: keyset pages, newest first, with the in-progress /
+ * completed split applied server-side (see `acceptance.listPage`).
+ *
+ * A `null` filter disables the feed entirely — that is how the panel hands off
+ * to the flat search read. Changing the filter starts a fresh key series, so the
+ * loaded depth collapses back to one page rather than cascading a refetch of as
+ * many pages as the previous view had open.
+ */
+export const useAcceptanceListInfinite = (filter: AcceptanceListFilter | null) => {
+ const workspaceId = useActiveWorkspaceId();
+
+ const getKey = useCallback(
+ (_index: number, previous: AcceptanceListPage | null) => {
+ if (previous && previous.nextCursor === null) return null;
+ if (!filter) return null;
+ return verifyKeys.acceptancePage(
+ workspaceId ?? undefined,
+ filter,
+ previous?.nextCursor ?? undefined,
+ );
+ },
+ [filter, workspaceId],
+ );
+
+ const { data, error, isLoading, mutate, setSize, size } = useSWRInfinite(
+ getKey,
+ ([, , , cursor]: readonly [string, string, string, string]) =>
+ verifyService.listAcceptancePage({
+ cursor: cursor || undefined,
+ filter: filter ?? undefined,
+ limit: ACCEPTANCE_PAGE_SIZE,
+ }),
+ { ...VERIFY_REPORT_SWR_CONFIG, revalidateFirstPage: false },
+ );
+
+ useEffect(() => {
+ setSize(1);
+ }, [filter, workspaceId, setSize]);
+
+ const loadMore = useCallback(() => {
+ void setSize((s) => s + 1);
+ }, [setSize]);
+
+ // SWR leaves a failed/pending page's slot `undefined`, so guard the holes.
+ const items = data?.flatMap((page) => page?.items ?? []) ?? [];
+ const lastLoadedPage = data?.findLast(Boolean);
+ const reachedEnd = lastLoadedPage ? lastLoadedPage.nextCursor === null : false;
+ const hasLoadedPages = data !== undefined;
+
+ const isLoadingInitial = !error && isLoading && !hasLoadedPages;
+ const isLoadingMore =
+ !error && hasLoadedPages && size > 0 && typeof data[size - 1] === 'undefined';
+
+ return {
+ error,
+ // Pause the sentinel while an error is showing so it cannot hot-loop the
+ // failed page; the panel offers a manual retry instead.
+ hasMore: !reachedEnd && !error,
+ isLoadingInitial,
+ isLoadingMore,
+ items,
+ loadMore,
+ mutate,
+ };
+};
+
/**
* Acceptance status for a known subject set — one read for a whole list.
*
diff --git a/src/features/Portal/AcceptanceCheck/Body.tsx b/src/features/Portal/AcceptanceCheck/Body.tsx
index f2d98bf6e8d..fee631b1b37 100644
--- a/src/features/Portal/AcceptanceCheck/Body.tsx
+++ b/src/features/Portal/AcceptanceCheck/Body.tsx
@@ -14,6 +14,7 @@ import {
FocusedCheckDetails,
useAcceptanceBundle,
} from '@/features/Acceptance';
+import { canReviewAcceptance } from '@/features/Acceptance/Viewer/visibility';
import { verifyService } from '@/services/verify';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -130,7 +131,7 @@ const Body = memo(() => {
</Flexbox>
)}
<FocusedCheckDetails
- canReview={data.isOwner}
+ canReview={canReviewAcceptance(data)}
check={check}
reviewPending={reviewPending}
onOpenTrace={openVerifierTrace}
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 3f1f377f7fc..069b8ff7a72 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -1030,6 +1030,19 @@ export const verifyKeys = {
[...subjectIds].sort().join(','),
],
),
+ /**
+ * One scroll page of the list panel. Keyed by workspace + the status split +
+ * the cursor, mirroring `reportSummaries` — the sibling paged feed.
+ */
+ acceptancePage: def(
+ 'verify:acceptancePage',
+ (workspaceId: string | undefined, filter: string, cursor?: string) => [
+ 'verify:acceptancePage',
+ workspaceId ?? '',
+ filter,
+ 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) => [
'verify:acceptances',
@@ -1066,9 +1079,14 @@ export const verifyKeys = {
tracing: def('verify:tracing', (tracingId: string) => ['verify:tracing', tracingId]),
};
-/** Match every parameterized Acceptance list key (filter / limit / search variants). */
+/**
+ * Match every cached Acceptance list read — the flat window's filter / limit /
+ * search variants AND every loaded page of the panel's scroll feed. A write has
+ * no idea how deep the panel has scrolled, so it invalidates the whole family.
+ */
export const isAcceptanceListKey = (key: unknown): boolean =>
- Array.isArray(key) && key[0] === verifyKeys.acceptances.root;
+ Array.isArray(key) &&
+ (key[0] === verifyKeys.acceptances.root || key[0] === verifyKeys.acceptancePage.root);
// ---- inbox / notifications ----------------------------------------------
export const inboxKeys = {
diff --git a/src/services/verify.ts b/src/services/verify.ts
index 8027f63b9e5..652932dc95f 100644
--- a/src/services/verify.ts
+++ b/src/services/verify.ts
@@ -32,6 +32,14 @@ export type AcceptanceListItem = Awaited<
ReturnType<typeof lambdaClient.acceptance.list.query>
>[number];
+export type AcceptanceListPage = Awaited<ReturnType<typeof lambdaClient.acceptance.listPage.query>>;
+
+/** The list's status split, shared by the flat and paged reads. */
+export type AcceptanceListFilter = 'active' | 'all' | 'completed';
+
+/** The lifecycle states a reviewer may set by hand from the acceptance list. */
+export type AcceptanceStatusOverride = 'accepted' | 'closed' | 'delivered' | 'rejected';
+
/** Editable fields of a single delivery-check criterion. */
export interface UpdateCriterionValue {
description?: string | null;
@@ -179,6 +187,13 @@ export class VerifyService {
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;
+ }): Promise<AcceptanceListPage> => lambdaClient.acceptance.listPage.query(params);
+
/**
* Acceptance status for a known set of subjects. `listAcceptances` is capped
* at the newest rows across every subject type, so a list surface deriving
@@ -276,9 +291,17 @@ export class VerifyService {
lambdaClient.acceptance.setProject.mutate({ id, projectId });
/** Owner override of the acceptance's decision state from the list. */
- updateAcceptanceStatus = (id: string, status: 'accepted' | 'closed' | 'delivered' | 'rejected') =>
+ updateAcceptanceStatus = (id: string, status: AcceptanceStatusOverride) =>
lambdaClient.acceptance.updateStatus.mutate({ id, status });
+ /**
+ * Sweep a multi-selection into one decision state. Reports what landed —
+ * rows that could not take the transition come back in `failedIds` instead
+ * of failing the whole sweep.
+ */
+ updateAcceptanceStatusBatch = (ids: string[], status: AcceptanceStatusOverride) =>
+ lambdaClient.acceptance.updateStatusBatch.mutate({ ids, status });
+
/**
* Fold one acceptance into another — the source's checks (and the rounds /
* evidence behind them) move onto the target, and the source entry is
@@ -290,6 +313,9 @@ export class VerifyService {
/** Delete the acceptance aggregate (its round reports detach, not delete). */
deleteAcceptance = (id: string) => lambdaClient.acceptance.remove.mutate({ id });
+ /** Batch twin of `deleteAcceptance` for the list's multi-selection. */
+ deleteAcceptanceBatch = (ids: string[]) => lambdaClient.acceptance.removeBatch.mutate({ ids });
+
// ---- per-run plan ----
getVerifyState = (operationId: string): Promise<VerifyStateResponse | null> =>
lambdaClient.verify.getVerifyState.query({